okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221apps/host: the owner's UI and the Node App Host0b3299a01

main
2.5 KiB46 linesraw
1import { tr } from '../lib/i18n';
2import { useMemo, useState } from 'react';
3/** Handles quoted fields and embedded newlines without evaluating cell content. */
4export function parseCsv(text: string): string[][] {
5    const rows: string[][] = [];
6    let row: string[] = [], cell = '', quoted = false;
7    for (let i = 0; i < text.length; i++) {
8        const c = text[i];
9        if (c === '"') {
10            if (quoted && text[i + 1] === '"') {
11                cell += '"';
12                i++;
13            }
14            else
15                quoted = !quoted;
16        }
17        else if (!quoted && (c === ',' || c === '\n')) {
18            row.push(cell.replace(/\r$/, ''));
19            cell = '';
20            if (c === '\n') {
21                rows.push(row);
22                row = [];
23            }
24        }
25        else
26            cell += c;
27    }
28    if (cell || row.length) {
29        row.push(cell.replace(/\r$/, ''));
30        rows.push(row);
31    }
32    return rows;
33}
34export function TablePreview({ text }: {
35    text: string;
36}) {
37    const [query, setQuery] = useState(''), [sort, setSort] = useState<{
38        column: number;
39        desc: boolean;
40    } | null>(null);
41    const [headers, ...rows] = useMemo(() => parseCsv(text), [text]);
42    const filtered = rows.filter(r => r.join(' ').toLowerCase().includes(query.toLowerCase()));
43    if (sort)
44        filtered.sort((a, b) => (a[sort.column] ?? '').localeCompare(b[sort.column] ?? '', undefined, { numeric: true }) * (sort.desc ? -1 : 1));
45    return <div className="table-preview"><div className="section-toolbar"><span className="small muted">{tr(filtered.length)}{tr(" rows \u00B7 ")}{tr(headers?.length ?? 0)}{tr(" columns")}</span><input className="st-input" type="search" aria-label={tr("Filter table")} placeholder={tr("Filter rows…")} value={query} onChange={e => setQuery(e.target.value)}/></div><div className="st-tablewrap"><table className="st-table"><thead><tr>{tr(headers?.map((h, i) => <th key={i} aria-sort={sort?.column === i ? sort.desc ? 'descending' : 'ascending' : 'none'}><button className="table-sort" onClick={() => setSort({ column: i, desc: sort?.column === i ? !sort.desc : false })}>{h}{tr(sort?.column === i ? sort.desc ? ' ↓' : ' ↑' : '')}</button></th>))}</tr></thead><tbody>{tr(filtered.slice(0, 1000).map((r, i) => <tr key={i}>{tr(headers?.map((_, j) => <td key={j}>{r[j] ?? ''}</td>))}</tr>))}</tbody></table></div>{tr(filtered.length > 1000 ? <p className="xs muted">{tr("Showing the first 1,000 matching rows.")}</p> : null)}</div>;
46}