diff --git a/src/components/md-table.tsx b/src/components/md-table.tsx index a4626bc..dc9083b 100644 --- a/src/components/md-table.tsx +++ b/src/components/md-table.tsx @@ -1,8 +1,8 @@ import { customElement, noShadowDOM } from 'solid-element'; import { createSignal, For, Show, createEffect, createMemo, createResource } from 'solid-js'; -import { parse } from 'csv-parse/browser/esm/sync'; import { marked } from '../markdown'; import { resolvePath } from '../utils'; +import { loadCSV } from './utils/csv-loader'; export interface TableProps { roll?: boolean; @@ -15,9 +15,6 @@ interface TableRow { [key: string]: string; } -// 全局缓存已加载的 CSV 内容 -const csvCache = new Map(); - customElement('md-table', { roll: false, remix: false }, (props, { element }) => { noShadowDOM(); const [rows, setRows] = createSignal([]); @@ -41,26 +38,6 @@ customElement('md-table', { roll: false, remix: false }, (props, { element }) => // 解析相对路径 const resolvedSrc = resolvePath(articlePath, src); - // 加载 CSV 文件的函数 - const loadCSV = async (path: string): Promise => { - // 先从缓存获取 - if (csvCache.has(path)) { - return csvCache.get(path)!; - } - const response = await fetch(path); - const content = await response.text(); - const records = parse(content, { - columns: true, - comment: '#', - trim: true, - skipEmptyLines: true - }); - const result = records as TableRow[]; - // 缓存结果 - csvCache.set(path, result); - return result; - }; - // 使用 createResource 加载 CSV,自动响应路径变化并避免重复加载 const [csvData] = createResource(() => resolvedSrc, loadCSV); diff --git a/src/components/utils/csv-loader.ts b/src/components/utils/csv-loader.ts index 7233952..b288d27 100644 --- a/src/components/utils/csv-loader.ts +++ b/src/components/utils/csv-loader.ts @@ -1,17 +1,17 @@ import { parse } from 'csv-parse/browser/esm/sync'; -import type { CardData } from '../types'; /** * 全局缓存已加载的 CSV 内容 */ -const csvCache = new Map(); +const csvCache = new Map[]>(); /** * 加载 CSV 文件 + * @template T 返回数据的类型,默认为 Record */ -export async function loadCSV(path: string): Promise { +export async function loadCSV>(path: string): Promise { if (csvCache.has(path)) { - return csvCache.get(path)!; + return csvCache.get(path)! as T[]; } const response = await fetch(path); @@ -23,7 +23,7 @@ export async function loadCSV(path: string): Promise { skipEmptyLines: true }); - const result = records as CardData[]; + const result = records as Record[]; csvCache.set(path, result); - return result; + return result as T[]; }