6715fbd971
- EditorModal loads once per path (a parent re-render no longer reloads the file over the user's typing), refuses Save after a failed load, opens a truncated (>256 KB) file read-only, and asks before overwriting a file that changed on disk or could not be re-read. - Settings/Hooks editors unset only keys from the snapshot taken at Edit, warn when the file changed underneath, keep a renamed key's value, and refuse a new key named like a redacted one (env) or a read-only hook event, which used to replace the secret/hooks. - Project scope shows its resolved folder and is disabled inside the plugin cache. Account-profile, pricing-row and pet deletes confirm; two-click actions disarm after 3 s; unsaved drafts ask before closing. - Search indexes every Claude Code / Codex sub-tab, opens it via ?tab= and scrolls to + highlights the row; the active config tab is in the URL. - General splits into General / Data / About; Pricing moves to a Cost group with one shared load; config tabs group as Content / Extensions / Config with arrow-key roving; Promise.allSettled per tab. - Data: browser-preferences export/import (allowlisted keys), per-section reset, housekeeping dry-run first, clear-all behind a typed phrase. Server: purge days must be a whole number >= 1 (INVALID_PURGE_DAYS) and dry_run returns exactly what the real run would delete. - Alerts can be edited; webhooks/alerts/remote-source failures toast; copies go through copyText; modals get dialog roles and useDialog. - Sagi: Ctrl/Cmd+B only when shown and not typing, default spot clear of row controls, arrow keys move it, reduced motion honoured; the dead /run launch link goes to the workspace.
383 lines
15 KiB
TypeScript
383 lines
15 KiB
TypeScript
/**
|
|
* @file EditorModal.tsx
|
|
* @description Create/edit modal for text-file config artifacts (skills,
|
|
* agents, commands, output styles, memory). Tool-agnostic: it takes a
|
|
* `fetchContent` callback instead of reaching for any particular tool's API,
|
|
* so the same modal serves both the Claude Code and Codex config pages. It
|
|
* loads a file ONCE per path (never over the user's typing), refuses to save
|
|
* over a failed or truncated read, asks before discarding edits or overwriting
|
|
* a file changed on disk, and is a real dialog (focus trap, Escape).
|
|
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
|
*/
|
|
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { Pencil, X, Save, AlertCircle } from "lucide-react";
|
|
import type { CcArtifactType } from "../../lib/api";
|
|
import { confirmDialog, confirmDiscard } from "../../lib/confirm";
|
|
import { useDialog } from "../../hooks/useDialog";
|
|
import { useUnsavedGuard } from "../../hooks/useUnsavedGuard";
|
|
|
|
/** What a fetcher may answer: the text, or the API's `{text, truncated}`. */
|
|
type Fetched = string | { text: string; truncated?: boolean };
|
|
const textOf = (r: Fetched) => (typeof r === "string" ? r : r.text);
|
|
|
|
/** Same rule the server applies to an artifact name. */
|
|
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
|
|
/** Claude Code's own scope union, kept as the default so existing callers
|
|
* (CcConfig.tsx) don't need to name it. Codex has no `auto-memory` scope —
|
|
* its caller instantiates `TScope` as just `"user" | "project"` instead of
|
|
* casting its own narrower type into this one. */
|
|
type DefaultScope = "user" | "project" | "auto-memory";
|
|
|
|
export type EditorState<
|
|
TType extends string = CcArtifactType,
|
|
TScope extends string = DefaultScope,
|
|
> =
|
|
| {
|
|
mode: "create";
|
|
type: TType;
|
|
defaultScope: "user" | "project";
|
|
template: string;
|
|
project?: string; // set for type === "auto-memory"
|
|
}
|
|
| {
|
|
mode: "edit";
|
|
type: TType;
|
|
scope: TScope;
|
|
name: string;
|
|
filePath: string;
|
|
project?: string; // set for type === "auto-memory"
|
|
}
|
|
| null;
|
|
|
|
/** Types that are a single fixed file per scope (e.g. Claude's CLAUDE.md, Codex's
|
|
* AGENTS.md / config.toml) - no `name` field, and no artifact name is ever sent. */
|
|
const DEFAULT_NAMELESS_TYPES = ["memory"];
|
|
|
|
interface EditorModalProps<
|
|
TType extends string = CcArtifactType,
|
|
TScope extends string = DefaultScope,
|
|
> {
|
|
state: NonNullable<EditorState<TType, TScope>>;
|
|
fetchContent: (filePath: string) => Promise<Fetched>;
|
|
onClose: () => void;
|
|
onSave: (args: {
|
|
type: TType;
|
|
targetScope: TScope;
|
|
name: string | undefined;
|
|
content: string;
|
|
project?: string;
|
|
}) => Promise<void>;
|
|
/** Which `state.type` values are nameless singleton files. Defaults to
|
|
* Claude Code's own `["memory"]` so existing callers are unaffected. */
|
|
namelessTypes?: readonly string[];
|
|
/** Refuse the Project target (its folder is the plugin cache, wiped on update). */
|
|
projectDisabled?: boolean;
|
|
}
|
|
|
|
export function EditorModal<
|
|
TType extends string = CcArtifactType,
|
|
TScope extends string = DefaultScope,
|
|
>({
|
|
state,
|
|
fetchContent,
|
|
onClose,
|
|
onSave,
|
|
namelessTypes = DEFAULT_NAMELESS_TYPES,
|
|
projectDisabled = false,
|
|
}: EditorModalProps<TType, TScope>) {
|
|
const { t } = useTranslation("ccConfig");
|
|
const isCreate = state.mode === "create";
|
|
const isNameless = namelessTypes.includes(state.type);
|
|
const isAutoMemory = state.type === "auto-memory";
|
|
const [content, setContent] = useState<string>(isCreate ? state.template : "");
|
|
const [name, setName] = useState<string>("");
|
|
const [targetScope, setTargetScope] = useState<"user" | "project">(
|
|
isCreate
|
|
? state.defaultScope
|
|
: state.scope === "auto-memory"
|
|
? "user"
|
|
: (state.scope as "user" | "project")
|
|
);
|
|
const [loading, setLoading] = useState(!isCreate);
|
|
const [saving, setSaving] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
// "ok" once an edit's text is in; a failed or truncated load never saves —
|
|
// Save over a failed load wrote an EMPTY file, over a truncated one a cut file.
|
|
const [loadState, setLoadState] = useState<"ok" | "failed" | "truncated">(
|
|
isCreate ? "ok" : "failed"
|
|
);
|
|
// The text as opened; `dirty` and the changed-on-disk check compare to it.
|
|
const original = useRef<string>(isCreate ? state.template : "");
|
|
const panelRef = useRef<HTMLDivElement>(null);
|
|
const titleId = "cc-editor-title";
|
|
const dirty = !loading && content !== original.current;
|
|
useUnsavedGuard(dirty);
|
|
|
|
// Read through a ref: callers pass an inline fetcher, and a dependency on it
|
|
// reloaded the file on every parent render — overwriting the user's typing.
|
|
const fetchRef = useRef(fetchContent);
|
|
fetchRef.current = fetchContent;
|
|
const editPath = state.mode === "edit" ? state.filePath : null;
|
|
|
|
// `t` through a ref too: a language switch must not re-run the load below.
|
|
const tRef = useRef(t);
|
|
tRef.current = t;
|
|
|
|
// For edit mode, fetch the file once per path.
|
|
useEffect(() => {
|
|
if (editPath === null) return;
|
|
let live = true;
|
|
setLoading(true);
|
|
fetchRef
|
|
.current(editPath)
|
|
.then((r) => {
|
|
if (!live) return;
|
|
const text = textOf(r);
|
|
original.current = text;
|
|
setContent(text);
|
|
const cut = typeof r !== "string" && !!r.truncated;
|
|
setLoadState(cut ? "truncated" : "ok");
|
|
if (cut) setError(tRef.current("edit.truncatedReadOnly"));
|
|
setLoading(false);
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!live) return;
|
|
const msg = err instanceof Error ? err.message : "unknown";
|
|
setLoadState("failed");
|
|
setError(tRef.current("edit.loadError", { message: msg }));
|
|
setLoading(false);
|
|
});
|
|
return () => {
|
|
live = false;
|
|
};
|
|
}, [editPath]);
|
|
|
|
const requestClose = useCallback(async () => {
|
|
if (dirty && !(await confirmDiscard())) return;
|
|
onClose();
|
|
}, [dirty, onClose]);
|
|
|
|
// Escape closes — but not while typing in the textarea, where it only leaves
|
|
// the field (an editor's Escape must never cost a draft).
|
|
useDialog(true, panelRef, () => {
|
|
const el = document.activeElement;
|
|
if (el instanceof HTMLTextAreaElement) {
|
|
el.blur();
|
|
return;
|
|
}
|
|
void requestClose();
|
|
});
|
|
|
|
const handleSave = useCallback(async () => {
|
|
setSaving(true);
|
|
setError(null);
|
|
try {
|
|
if (!isNameless && state.mode === "create") {
|
|
if (!name.trim()) {
|
|
setError(t("edit.nameRequired"));
|
|
return;
|
|
}
|
|
if (!isAutoMemory && !NAME_RE.test(name)) {
|
|
setError(t("edit.nameInvalid"));
|
|
return;
|
|
}
|
|
}
|
|
// The file changed on disk since it was opened (a running session, a
|
|
// terminal): say so instead of silently overwriting that change.
|
|
if (state.mode === "edit") {
|
|
const fresh = await fetchRef
|
|
.current(state.filePath)
|
|
.then(textOf)
|
|
.catch(() => null);
|
|
// Could not re-read it: say so rather than saving blind.
|
|
const ask =
|
|
fresh === null
|
|
? {
|
|
title: t("edit.unverifiedTitle"),
|
|
message: t("edit.unverifiedBody"),
|
|
confirmLabel: t("edit.saveAnyway"),
|
|
}
|
|
: fresh !== original.current
|
|
? {
|
|
title: t("edit.changedOnDiskTitle"),
|
|
message: t("edit.changedOnDiskBody"),
|
|
confirmLabel: t("edit.overwrite"),
|
|
}
|
|
: null;
|
|
if (ask && !(await confirmDialog(ask))) return;
|
|
}
|
|
// For auto-memory creates, append a .md extension when the user omits it.
|
|
const createName = isAutoMemory && !/\.md$/i.test(name) ? `${name}.md` : name;
|
|
const effectiveName =
|
|
state.mode === "edit" ? state.name : isNameless ? undefined : createName;
|
|
await onSave({
|
|
type: state.type,
|
|
// Widening back to TScope: this component is the one place that
|
|
// legitimately knows about all three scope shapes across both
|
|
// callers; a Codex caller's TScope ("user" | "project") never
|
|
// actually receives "auto-memory" since isAutoMemory can only be
|
|
// true when TType includes "auto-memory" (Claude-only).
|
|
targetScope: (isAutoMemory ? "auto-memory" : targetScope) as TScope,
|
|
name: effectiveName,
|
|
content,
|
|
project: state.project,
|
|
});
|
|
original.current = content;
|
|
} catch (err: unknown) {
|
|
const msg = err instanceof Error ? err.message : "unknown";
|
|
setError(t("edit.writeError", { message: msg }));
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}, [state, targetScope, name, content, isAutoMemory, isNameless, onSave, t]);
|
|
|
|
const titleText = isCreate
|
|
? isAutoMemory
|
|
? t("memory.newFileTitle", { project: state.project ?? "" })
|
|
: t("edit.newTitle", { type: state.type })
|
|
: t("edit.editTitle", { name: state.mode === "edit" ? state.name : "" });
|
|
|
|
return (
|
|
<div
|
|
className="fixed inset-0 bg-surface-0/70 z-50 flex items-center justify-center p-4"
|
|
onClick={() => void requestClose()}
|
|
>
|
|
<div
|
|
ref={panelRef}
|
|
role="dialog"
|
|
aria-modal="true"
|
|
aria-labelledby={titleId}
|
|
className="relative w-full max-w-4xl max-h-[90vh] rounded-xl border border-border bg-surface-1 flex flex-col"
|
|
onClick={(e) => e.stopPropagation()}
|
|
>
|
|
<div className="flex items-center gap-2 border-b border-border px-4 py-2.5">
|
|
<Pencil className="w-4 h-4 text-fg-muted" />
|
|
<span id={titleId} className="text-sm font-medium text-fg-primary flex-1 truncate">
|
|
{titleText}
|
|
</span>
|
|
<button
|
|
type="button"
|
|
onClick={() => void requestClose()}
|
|
className="text-fg-secondary hover:text-fg-primary p-1 rounded-md hover:bg-surface-3"
|
|
aria-label={t("common.close")}
|
|
>
|
|
<X className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
|
|
<div className="overflow-auto p-4 space-y-3">
|
|
{isCreate && !isNameless && (
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
|
<div>
|
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-fg-muted mb-1">
|
|
{t("edit.nameLabel")}
|
|
</label>
|
|
<input
|
|
value={name}
|
|
onChange={(e) => setName(e.target.value)}
|
|
placeholder={
|
|
isAutoMemory ? t("memory.namePlaceholder") : t("edit.namePlaceholder")
|
|
}
|
|
pattern={isAutoMemory ? undefined : "[A-Za-z0-9][A-Za-z0-9._-]{0,63}"}
|
|
className="w-full bg-surface-2 border border-border rounded-md px-3 py-1.5 text-sm font-mono text-fg-primary placeholder:text-fg-muted focus:outline-none focus:border-accent/50"
|
|
/>
|
|
<p className="mt-1 text-[10px] text-fg-muted">
|
|
{isAutoMemory ? t("memory.nameHelp") : t("edit.nameHelp")}
|
|
</p>
|
|
</div>
|
|
{isAutoMemory ? (
|
|
<div>
|
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-fg-muted mb-1">
|
|
{t("memory.projectLabel")}
|
|
</label>
|
|
<div className="rounded-md border border-border bg-surface-2 px-3 py-1.5 font-mono text-[11px] text-fg-secondary truncate">
|
|
{state.project}
|
|
</div>
|
|
<p className="mt-1 text-[10px] text-fg-muted">{t("memory.projectHelp")}</p>
|
|
</div>
|
|
) : (
|
|
<div>
|
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-fg-muted mb-1">
|
|
{t("edit.scopePicker")}
|
|
</label>
|
|
<div className="inline-flex rounded-md border border-border bg-surface-2 p-0.5">
|
|
{(["user", "project"] as const).map((s) => (
|
|
<button
|
|
key={s}
|
|
type="button"
|
|
aria-pressed={targetScope === s}
|
|
disabled={s === "project" && projectDisabled}
|
|
title={
|
|
s === "project" && projectDisabled ? t("scope.projectInCache") : undefined
|
|
}
|
|
onClick={() => setTargetScope(s)}
|
|
className={`px-3 py-1 text-[11px] font-medium rounded disabled:opacity-40 disabled:cursor-not-allowed ${
|
|
targetScope === s
|
|
? "bg-accent/20 text-accent border border-accent/30"
|
|
: "text-fg-secondary hover:text-fg-primary"
|
|
}`}
|
|
>
|
|
{t(`scope.${s}`)}
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
<div>
|
|
<label className="block text-[11px] font-semibold uppercase tracking-wider text-fg-muted mb-1">
|
|
{t("edit.contentLabel")}
|
|
</label>
|
|
{loading ? (
|
|
<div className="h-72 rounded-md border border-border bg-surface-2 animate-pulse" />
|
|
) : (
|
|
<textarea
|
|
value={content}
|
|
onChange={(e) => setContent(e.target.value)}
|
|
readOnly={loadState !== "ok"}
|
|
aria-label={t("edit.contentLabel")}
|
|
spellCheck={false}
|
|
className="w-full h-72 bg-surface-2 border border-border rounded-md px-3 py-2 text-[11px] font-mono text-fg-primary placeholder:text-fg-muted focus:outline-none focus:border-accent/50 resize-y"
|
|
/>
|
|
)}
|
|
</div>
|
|
|
|
{error && (
|
|
<div
|
|
role="alert"
|
|
className="rounded-md border border-status-danger/40 bg-status-danger/10 px-3 py-2 text-xs text-status-danger inline-flex items-center gap-2"
|
|
>
|
|
<AlertCircle className="w-3.5 h-3.5" />
|
|
{error}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="border-t border-border px-4 py-3 flex items-center justify-end gap-2">
|
|
<button
|
|
type="button"
|
|
onClick={() => void requestClose()}
|
|
className="text-[12px] font-medium px-3 py-1.5 rounded-md border border-border bg-surface-2 hover:bg-surface-3 text-fg-secondary"
|
|
>
|
|
{t("edit.cancel")}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleSave}
|
|
disabled={saving || loading || loadState !== "ok"}
|
|
className="text-[12px] font-medium px-3 py-1.5 rounded-md border border-accent/40 bg-accent/15 hover:bg-accent/25 text-accent inline-flex items-center gap-1.5 disabled:opacity-60"
|
|
>
|
|
<Save className="w-3.5 h-3.5" />
|
|
{saving ? t("edit.saving") : t("edit.save")}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|