import { Component, createSignal, For, Show } from 'solid-js'; import { parse } from 'csv-parse/sync'; export interface TableProps { src: string; roll?: boolean; remix?: boolean; } interface TableRow { label: string; body: string; [key: string]: string; } export const Table: Component = (props) => { const [rows, setRows] = createSignal([]); const [activeTab, setActiveTab] = createSignal(0); // 解析 CSV 内容 const parseCSV = (content: string) => { const records = parse(content, { columns: true, skip_empty_lines: true, }); setRows(records as TableRow[]); }; // 加载 CSV 文件 const loadCSV = async () => { try { const response = await fetch(props.src); const content = await response.text(); parseCSV(content); } catch (error) { console.error('Failed to load CSV:', error); } }; // 初始化加载 loadCSV(); // 随机切换 tab const handleRoll = () => { const randomIndex = Math.floor(Math.random() * rows().length); setActiveTab(randomIndex); }; // 处理 body 内容中的 {{prop}} 语法 const processBody = (body: string, currentRow: TableRow): string => { if (!props.remix) { // 不启用 remix 时,只替换当前行的引用 return body.replace(/\{\{(\w+)\}\}/g, (_, key) => currentRow[key] || ''); } else { // 启用 remix 时,每次引用使用随机行的内容 return body.replace(/\{\{(\w+)\}\}/g, (_, key) => { const randomRow = rows()[Math.floor(Math.random() * rows().length)]; return randomRow?.[key] || ''; }); } }; return (
{(row, index) => ( )}
0}>
); };