Files

312 lines
10 KiB
TypeScript
Raw Permalink Normal View History

2026-10-12 21:41:35 -04:00
import { createContext, use, useCallback, useMemo, useRef, useState, type ComponentType, type ReactNode } from 'react';
2026-10-05 18:10:18 -04:00
import { basename, dirname, join, normalize } from 'pathe';
import { useLocation, useNavigate, useParams, useRouter } from '@tanstack/react-router';
2026-10-12 15:20:31 -04:00
import { httpErrorToHuman } from '@/api/http';
2026-10-05 18:10:18 -04:00
import { useSaveFileContent, useServerFileContent, writeFileContentsInput } from '@/api/server/files/queries';
2026-10-12 15:20:31 -04:00
import { useCurrentServer } from '@/api/server/queries';
import CodemirrorEditor from '@/components/elements/LazyCodemirrorEditor';
2026-10-05 18:10:18 -04:00
import { useDialogState } from '@/components/elements/dialog';
2026-10-12 15:20:31 -04:00
import { encodePathSegments, hashToPath } from '@/helpers';
2026-10-05 18:10:18 -04:00
import { clearNewFileDraft, readNewFileDraft, writeNewFileDraft } from '@/lib/fileDrafts';
2026-10-12 15:20:31 -04:00
import modes from '@/modes';
2026-10-05 18:10:18 -04:00
import { useDebouncedCallback } from '@/plugins/useDebouncedCallback';
import { useNavigationBlocker } from '@/plugins/useNavigationBlocker';
import { usePermissions } from '@/plugins/usePermissions';
2026-10-12 15:20:31 -04:00
import type { FileEditorCanvasProps, FileEditorModel, FileEditorPageModel } from '@/views/server/files';
import { fileBreadcrumbs } from './breadcrumbs';
import FileNameModal from './FileNameModal';
const FileEditorPageContext = createContext<FileEditorPageModel | null>(null);
const FileEditorSessionContext = createContext<FileEditorModel | null>(null);
const findModeByFilename = (filename: string) => {
const match = modes.find((mode) => mode.file?.test(filename));
const dot = filename.lastIndexOf('.');
const ext = dot > -1 ? filename.slice(dot + 1) : undefined;
return match ?? (ext ? modes.find((mode) => mode.ext?.includes(ext)) : undefined);
};
export const modeForFile = (filename: string) => findModeByFilename(filename)?.mime || 'text/plain';
export const editorLanguages: FileEditorModel['languages'] = modes.map(({ mime, name }) => ({ mime, name }));
/** The code editor of the open document; a remounted one starts from the live buffer. */
export function FileEditorCanvas({ className }: FileEditorCanvasProps) {
const model = use(FileEditorSessionContext);
if (!model) {
throw new Error('The file editor renders inside an open file editing session.');
}
const [initialContent] = useState(model.read);
return (
<CodemirrorEditor
className={className}
mode={model.language}
initialContent={initialContent}
onContentChanged={model.change}
onContentSaved={() => void model.save()}
/>
);
}
2026-10-12 21:41:35 -04:00
/** The editor canvas bound to a model that has no editing session around it, such as a fixture's. */
export function bindFileEditor(model: FileEditorModel): ComponentType<FileEditorCanvasProps> {
return function BoundFileEditor(props: FileEditorCanvasProps) {
return (
<FileEditorSessionContext.Provider value={model}>
<FileEditorCanvas {...props} />
</FileEditorSessionContext.Provider>
);
};
2026-10-12 15:20:31 -04:00
}
export function useFileEditorPage(): FileEditorPageModel {
const page = use(FileEditorPageContext);
if (!page) {
throw new Error('The file editor page renders inside its route.');
}
return page;
}
export function useFileEditorSession(): FileEditorModel {
const model = use(FileEditorSessionContext);
if (!model) {
throw new Error('The file editor renders inside an open file editing session.');
}
return model;
}
2019-10-19 14:51:10 -07:00
2026-10-05 18:10:18 -04:00
interface FileEditSessionProps {
id: string;
uuid: string;
file: string;
isNew: boolean;
content: string;
2026-10-12 15:20:31 -04:00
children?: ReactNode;
2026-10-05 18:10:18 -04:00
}
2019-10-26 13:16:27 -07:00
2026-10-05 18:10:18 -04:00
// A new file's draft stays in session storage, so leaving it needs no confirmation.
const keepDraft = () => true;
2026-10-12 15:20:31 -04:00
function FileEditSession({ id, uuid, file, isNew, content, children }: FileEditSessionProps) {
2026-10-05 18:10:18 -04:00
const navigate = useNavigate();
const saveFileContent = useSaveFileContent();
const fileNameDialog = useDialogState();
const [canUpdate, canCreate] = usePermissions(['file.update', 'file.create']);
const readOnly = !(isNew ? canCreate : canUpdate);
2026-10-05 18:10:18 -04:00
const buffer = useRef(content);
const saved = useRef(isNew ? '' : content);
const naming = useRef<((saved: boolean) => void) | null>(null);
const [dirty, setDirty] = useState(isNew && !readOnly && content !== '');
const [saving, setSaving] = useState(false);
const [language, setLanguage] = useState(() => modeForFile(file));
const saveDraft = useDebouncedCallback((value: string) => writeNewFileDraft(uuid, file, value), 300);
2026-10-05 18:10:18 -04:00
useNavigationBlocker(dirty, isNew ? { confirm: keepDraft } : undefined);
2019-10-12 15:29:45 -07:00
2026-10-05 18:10:18 -04:00
const change = useCallback(
(value: string) => {
buffer.current = value;
2026-10-08 16:53:20 -04:00
if (isNew) {
saveDraft(value);
}
2026-10-05 18:10:18 -04:00
setDirty(!readOnly && value !== saved.current);
},
[isNew, readOnly, saveDraft]
);
const write = useCallback(
async (target: string): Promise<boolean> => {
const value = buffer.current;
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
setSaving(true);
try {
await saveFileContent.mutateAsync(writeFileContentsInput(uuid, target, value));
} catch {
// Error toast is handled by the mutation.
return false;
} finally {
setSaving(false);
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
if (!isNew && target === file) {
saved.current = value;
setDirty(buffer.current !== value);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return true;
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
if (isNew) {
saveDraft.cancel();
clearNewFileDraft(uuid, file);
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
await navigate({
to: '/server/$id/files/$action',
params: { id, action: 'edit' },
hash: encodePathSegments(target),
ignoreBlocker: true,
});
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return true;
},
[saveFileContent, navigate, saveDraft, id, uuid, file, isNew]
);
const save = useCallback(async (): Promise<boolean> => {
2026-10-08 16:53:20 -04:00
if (readOnly || saving) {
return false;
}
if (!isNew) {
return write(file);
}
2026-10-05 18:10:18 -04:00
naming.current?.(false);
const named = new Promise<boolean>((resolve) => {
naming.current = resolve;
});
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
fileNameDialog.show();
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return named;
}, [readOnly, saving, isNew, write, file, fileNameDialog]);
const saveAs = useCallback(
async (name: string): Promise<boolean> => {
2026-10-08 16:53:20 -04:00
if (!canCreate || saving || !name) {
return false;
}
2026-10-05 18:10:18 -04:00
return write(normalize(name.startsWith('/') ? name : join(isNew ? file : dirname(file), name)));
},
[canCreate, saving, write, isNew, file]
);
2026-10-12 15:20:31 -04:00
const read = useCallback(() => buffer.current, []);
2026-10-05 18:10:18 -04:00
const model = useMemo<FileEditorModel>(
() => ({
path: file,
name: isNew ? '' : basename(file),
isNew,
content,
language,
2026-10-12 15:20:31 -04:00
languages: editorLanguages,
2026-10-05 18:10:18 -04:00
readOnly,
dirty,
saving,
2026-10-12 15:20:31 -04:00
Editor: FileEditorCanvas,
read,
2026-10-05 18:10:18 -04:00
change,
2026-10-12 15:20:31 -04:00
setLanguage,
2026-10-05 18:10:18 -04:00
save,
saveAs,
}),
2026-10-12 15:20:31 -04:00
[file, isNew, content, language, readOnly, dirty, saving, read, change, save, saveAs]
2026-10-05 18:10:18 -04:00
);
2026-10-05 18:10:18 -04:00
return (
<>
<FileNameModal
open={fileNameDialog.open}
2026-10-12 15:20:31 -04:00
directory={file}
2026-10-05 18:10:18 -04:00
onClose={() => {
fileNameDialog.hide();
naming.current?.(false);
naming.current = null;
}}
onFileNamed={(name) => {
fileNameDialog.hide();
const resolve = naming.current;
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
naming.current = null;
void write(name).then(resolve ?? undefined);
}}
/>
2026-10-12 15:20:31 -04:00
<FileEditorSessionContext.Provider value={model}>{children}</FileEditorSessionContext.Provider>
2026-10-05 18:10:18 -04:00
</>
);
}
2019-08-17 11:40:51 -07:00
2026-10-12 15:20:31 -04:00
/**
* The editor route's engine frame around its page view: it loads the document, holds the editing
* session with its unsaved-changes guard, and asks a new file's name, whatever the theme renders.
*/
export default function FileEditorFrame({ children }: { children?: ReactNode }) {
2026-10-05 18:10:18 -04:00
const { action } = useParams({ strict: false });
const isEditingFile = action === 'edit';
const router = useRouter();
const { hash } = useLocation();
const file = hashToPath(hash);
2019-10-26 13:16:27 -07:00
2026-10-05 18:10:18 -04:00
const server = useCurrentServer()!;
const id = server.attributes.identifier;
const uuid = server.attributes.uuid;
2019-12-21 16:38:40 -08:00
2026-10-05 18:10:18 -04:00
const hasFile = isEditingFile && file !== '/';
const { data, error, isFetching } = useServerFileContent(uuid, file, hasFile);
const key = `${uuid}:${action}:${file}`;
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
// Captured once per document; later cache writes must not replace the buffer.
const [opened, setOpened] = useState<{ key: string; content: string } | null>(null);
2026-10-08 16:53:20 -04:00
// Undefined while an existing file's content is still loading.
const loadContent = () => {
if (hasFile) {
return isFetching ? undefined : data;
}
if (isEditingFile) {
return '';
}
return readNewFileDraft(uuid, file);
};
2026-10-05 18:10:18 -04:00
if (opened?.key !== key) {
2026-10-08 16:53:20 -04:00
const loaded = loadContent();
if (loaded !== undefined) {
setOpened({ key, content: loaded });
}
2026-10-05 18:10:18 -04:00
}
2019-10-26 13:16:27 -07:00
2026-10-12 15:20:31 -04:00
const ready = opened?.key === key;
const failed = hasFile && !ready && error ? httpErrorToHuman(error) : null;
const name = isEditingFile ? basename(file) || null : null;
const page = useMemo<FileEditorPageModel>(
() => ({
breadcrumbs: fileBreadcrumbs(id, name ? dirname(file) : file, true),
file: name,
loading: !ready && !failed,
error: failed,
back: () => router.history.back(),
}),
[id, file, name, ready, failed, router]
);
2019-08-17 11:40:51 -07:00
return (
2026-10-12 15:20:31 -04:00
<FileEditorPageContext.Provider value={page}>
{ready ? (
2026-10-05 18:10:18 -04:00
<FileEditSession
key={key}
id={id}
uuid={uuid}
file={file}
isNew={!isEditingFile}
content={opened.content}
2026-10-12 15:20:31 -04:00
>
{children}
</FileEditSession>
2026-10-05 18:10:18 -04:00
) : (
2026-10-12 15:20:31 -04:00
children
2026-10-05 18:10:18 -04:00
)}
2026-10-12 15:20:31 -04:00
</FileEditorPageContext.Provider>
2019-08-17 11:40:51 -07:00
);
2026-10-05 18:10:18 -04:00
}