Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 39 additions & 9 deletions apps/admin/src/components/ui/EditableField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ export interface StringEditableFieldProps extends Omit<
input?: FieldInputConfig;
}

function multilineSaveShortcutLabel(): string {
if (!("navigator" in globalThis)) {
return "Ctrl+Enter";
}
return /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? "⌘↵" : "Ctrl+Enter";
}

function EditableFieldInner<T>({
value,
formatValue,
Expand All @@ -49,8 +56,11 @@ function EditableFieldInner<T>({
isUnchanged,
}: EditableFieldProps<T>): ReactElement {
const [editing, setEditing] = useState(false);
const [savedValue, setSavedValue] = useState<T | undefined>(undefined);
const [draft, setDraft] = useState(() => formatValue(value));
const [error, setError] = useState<string | null>(null);
const multilineSaveShortcut = multilineSaveShortcutLabel();
const displayValue = savedValue ?? value;

function valueIsEmpty(nextValue: T): boolean {
if (isEmpty) {
Expand All @@ -66,45 +76,52 @@ function EditableFieldInner<T>({
return formatValue(nextValue);
}

useEffect(() => {
setSavedValue(undefined);
}, [value]);

useEffect(() => {
if (!editing) {
setDraft(formatValue(value));
setDraft(formatValue(displayValue));
setError(null);
}
}, [value, editing, formatValue]);
}, [displayValue, editing, formatValue]);

function startEdit(): void {
setDraft(formatValue(value));
setDraft(formatValue(displayValue));
setError(null);
setEditing(true);
}

function cancelEdit(): void {
setDraft(formatValue(value));
setDraft(formatValue(displayValue));
setError(null);
setEditing(false);
}

async function handleSave(): Promise<void> {
const nextDraft = trimOnCommit ? draft.trim() : draft;
const changed = isUnchanged
? !isUnchanged(nextDraft, value)
: nextDraft !== formatValue(value);
? !isUnchanged(nextDraft, displayValue)
: nextDraft !== formatValue(displayValue);

if (!changed) {
setEditing(false);
setError(null);
return;
}

const parsed = parseDraft(nextDraft);

try {
await onSave(parseDraft(nextDraft));
await onSave(parsed);
setSavedValue(parsed);
setEditing(false);
setError(null);
} catch (err) {
setError(formatCaughtError(err));
if (revertOnError) {
setDraft(formatValue(value));
setDraft(formatValue(displayValue));
}
}
}
Expand Down Expand Up @@ -133,6 +150,11 @@ function EditableFieldInner<T>({
}

if (editing) {
const saveShortcut =
input.kind === "textarea" || input.kind === "json"
? multilineSaveShortcut
: "↵";

return (
<div className="min-w-0">
<FieldInput
Expand All @@ -147,6 +169,14 @@ function EditableFieldInner<T>({
onCancel={cancelEdit}
commitOnChange={input.kind === "select"}
/>
{input.kind !== "select" ? (
<div className="mt-1 flex gap-2 text-xs text-muted">
<span className="flex items-center gap-0.5">
{saveShortcut} save
</span>
<span className="flex items-center gap-0.5">Esc cancel</span>
</div>
) : null}
{error ? <p className="mt-1 text-xs text-danger">{error}</p> : null}
</div>
);
Expand All @@ -159,7 +189,7 @@ function EditableFieldInner<T>({
align === "start" ? "items-start" : "items-center",
)}
>
<div className="min-w-0 flex-1">{renderValue(value)}</div>
<div className="min-w-0 flex-1">{renderValue(displayValue)}</div>
<button
type="button"
aria-label={editLabel}
Expand Down
120 changes: 118 additions & 2 deletions apps/admin/src/components/ui/FieldInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ import {
useRef,
useState,
} from "react";
import { SuggestibleInput } from "@leda/lib/ui";
import Editor from "@monaco-editor/react";
import type * as Monaco from "monaco-editor";
import { SuggestibleInput, useTheme } from "@leda/lib/ui";

const SEARCH_DEBOUNCE_MS = 300;
const JSON_EDITOR_LIGHT_THEME = "leda-json-light";
const JSON_EDITOR_DARK_THEME = "leda-json-dark";

export interface FieldOption {
value: string;
Expand Down Expand Up @@ -97,12 +101,110 @@ function handleMultilineKeyDown(
onCancel();
return;
}
if (event.key === "Enter" && event.metaKey && onSave) {
if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && onSave) {
event.preventDefault();
onSave();
}
}

interface JsonEditorProps {
value: string;
onChange: (value: string) => void;
disabled: boolean;
autoFocus: boolean;
className: string;
onSave?: () => void;
onCancel?: () => void;
}

function JsonEditor({
value,
onChange,
disabled,
autoFocus,
className,
onSave,
onCancel,
}: JsonEditorProps): ReactElement {
const { effectiveTheme } = useTheme();
const onSaveRef = useRef(onSave);
const onCancelRef = useRef(onCancel);
const height = `${(value.split("\n").length + 1) * 20 + 8}px`;
const widestLineLength = Math.max(
1,
...value.split("\n").map((line) => line.length),
);
const minWidth = `calc(${widestLineLength}ch + 16px)`;

onSaveRef.current = onSave;
onCancelRef.current = onCancel;

return (
<div
className={classNames(className, "overflow-hidden p-0")}
style={{ height, minWidth }}
onClick={(event) => event.stopPropagation()}
>
<Editor
height="100%"
language="json"
theme={
effectiveTheme === "dark"
? JSON_EDITOR_DARK_THEME
: JSON_EDITOR_LIGHT_THEME
}
value={value}
onChange={(nextValue) => onChange(nextValue ?? "")}
beforeMount={(monaco: typeof Monaco) => {
monaco.editor.defineTheme(JSON_EDITOR_LIGHT_THEME, {
base: "vs",
inherit: true,
colors: { "editor.background": "#00000000" },
rules: [],
});
monaco.editor.defineTheme(JSON_EDITOR_DARK_THEME, {
base: "vs-dark",
inherit: true,
colors: { "editor.background": "#00000000" },
rules: [],
});
}}
onMount={(editor, monaco: typeof Monaco) => {
if (autoFocus) {
editor.focus();
}
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, () =>
onSaveRef.current?.(),
);
editor.addCommand(monaco.KeyCode.Escape, () => {
onCancelRef.current?.();
});
}}
options={{
readOnly: disabled,
minimap: { enabled: false },
fontSize: 13,
lineNumbers: "off",
folding: false,
glyphMargin: false,
overviewRulerLanes: 0,
renderLineHighlight: "none",
scrollBeyondLastLine: false,
wordWrap: "off",
automaticLayout: true,
tabSize: 2,
padding: { top: 4, bottom: 4 },
scrollbar: {
horizontal: "hidden",
vertical: "hidden",
handleMouseWheel: false,
},
}}
/>
</div>
);
}

interface AutocompleteInputProps {
loadOptions: (query: string) => Promise<FieldOption[]>;
value: string;
Expand Down Expand Up @@ -277,6 +379,20 @@ export function FieldInput({
);
}

if (input.kind === "json" && appearance === "inline") {
return (
<JsonEditor
value={value}
onChange={onChange}
disabled={disabled}
autoFocus={autoFocus}
className={resolvedClassName}
onSave={onSave}
onCancel={onCancel}
/>
);
}

if (input.kind === "textarea" || input.kind === "json") {
return (
<textarea
Expand Down
3 changes: 1 addition & 2 deletions apps/admin/src/pages/ReferenceDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,6 @@ export function ReferenceDetailsPage(): ReactElement {
if (response.error) {
throw new Error(formatApiError(response.error));
}
setRefreshKey((key) => key + 1);
} catch (err) {
setPatchError(formatCaughtError(err));
throw err;
Expand Down Expand Up @@ -359,7 +358,7 @@ export function ReferenceDetailsPage(): ReactElement {
const selectedKey = referenceTableKey(schema, table);

return (
<div className="min-w-0 w-full max-w-full overflow-x-hidden">
<div className="min-w-0 w-full max-w-full">
<div className="mb-4">
<h2 className="text-3xl font-bold">
{data.descriptor.description || selectedKey}
Expand Down
Loading
Loading