Files
skillshare/ui/src/hooks/useEditableFile.ts
T
Willie 4b1e8d4e58 refactor(ui): extract useEditableFile for config page editors
ConfigPage repeated the same load, dirty-tracking, save and reset state
for config.yaml, .skillignore and .agentignore. One hook now holds it,
with tests, and each editor passes only its own save call.

The discard check for the extensions tab no longer reads the .agentignore
dirty flag, which the old three-way ternary returned for any other tab.
2026-09-30 02:24:12 +08:00

56 lines
1.7 KiB
TypeScript

import { useEffect, useState } from 'react';
import { useToast } from '../components/Toast';
interface EditableFileOptions {
// Writes the edited text. Return the text actually written when it differs
// from the edit (config.yaml is normalized on save) so the editor shows it.
save: (value: string) => Promise<string | void>;
// Keep the editor as it is when the fetched text is empty.
skipEmpty?: boolean;
}
// useEditableFile holds the editor state for one server file: it loads the
// fetched text, tracks whether the edit differs from it, saves, and resets.
export function useEditableFile(data: { raw?: string } | undefined, { save, skipEmpty = false }: EditableFileOptions) {
const { toast } = useToast();
const [value, setValue] = useState('');
const [dirty, setDirty] = useState(false);
const [saving, setSaving] = useState(false);
const original = data?.raw ?? '';
useEffect(() => {
if (data && (!skipEmpty || data.raw)) {
setValue(data.raw ?? '');
setDirty(false);
}
}, [data, skipEmpty]);
// Returns whether the new text differs from the fetched file.
const change = (next: string) => {
setValue(next);
const changed = next !== original;
setDirty(changed);
return changed;
};
const handleSave = async () => {
setSaving(true);
try {
const written = await save(value);
if (written !== undefined) setValue(written);
setDirty(false);
} catch (e: unknown) {
toast((e as Error).message, 'error');
} finally {
setSaving(false);
}
};
const reset = () => {
setValue(original);
setDirty(false);
};
return { value, dirty, saving, change, save: handleSave, reset };
}