/** Text / Data tab of each open CSV editor, and a counter of each CSV file's text changes. */ import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view"; import { create } from "zustand"; import { registerEditorContribution } from "@/editor/api"; import { isCsvPath } from "./csv"; export type CsvMode = "text" | "data"; export const useCsvModes = create>(() => ({})); export const useCsvSourceHidden = (tabId: string) => useCsvModes((s) => s[tabId] === "data"); /** The last caret a navigation placed in each CSV file's text (Find in Files, Go to Line…). */ export const useCsvReveals = create>(() => ({})); let revealSeq = 0; /** Bumped when a CSV file's text changes. */ export const useCsvVersions = create>(() => ({})); const bump = (path: string) => useCsvVersions.setState((s) => ({ [path]: (s[path] ?? 0) + 1 })); const TEXT_DELAY = 300; export function registerCsvLiveSource(): () => void { return registerEditorContribution({ id: "database.csvLive", extensions: (ctx) => !ctx.virtual && isCsvPath(ctx.path) ? [ ViewPlugin.fromClass( class { private timer: ReturnType | undefined; constructor(_view: EditorView) { bump(ctx.path); } update(u: ViewUpdate) { if (u.transactions.some((tr) => tr.isUserEvent("select.reveal"))) useCsvReveals.setState({ [ctx.path]: { offset: u.state.selection.main.head, seq: ++revealSeq } }); if (!u.docChanged) return; clearTimeout(this.timer); this.timer = setTimeout(() => bump(ctx.path), TEXT_DELAY); } destroy() { clearTimeout(this.timer); } }, ), ] : [], }); }