Simplify Custom JSX v2 authoring

This commit is contained in:
Thomas Camlong committed 2026-07-21 08:19:22 +02:00
1 parent 1faaf29c3b
commit 05dbad8069
177 files changed
+4775 -43426

No files matched your search

@@ -1,5 +1,6 @@
import { getCustomJsxBindingType } from "../core/component-registry";
import { customJsxRequestSchema } from "../core/request-schema";
import { z } from "zod/v4";
import { CUSTOM_JSX_LIMITS, validateCustomJsxTemplate } from "../jsx";
export type EditorDiagnosticCode =
@@ -103,7 +104,7 @@ export function analyzeJsxTemplate(
export function analyzeRequestManifest(value: string): EditorDiagnostic[] {
try {
const result = customJsxRequestSchema.array().safeParse(JSON.parse(value) as unknown);
const result = z.record(z.string(), customJsxRequestSchema).safeParse(JSON.parse(value) as unknown);
if (result.success) return [];
return result.error.issues.map((issue) => ({
code: "invalidRequestManifest",
@@ -116,11 +117,13 @@ export function analyzeRequestManifest(value: string): EditorDiagnostic[] {
}
}
export function parseRequestManifest(value: string): unknown[] {
export function parseRequestManifest(value: string): Record<string, unknown> {
try {
const parsed: unknown = JSON.parse(value);
return Array.isArray(parsed) ? parsed : [];
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: {};
} catch {
return [];
return {};
}
}
@@ -52,6 +52,8 @@ export interface CustomWidgetCodeEditorProps {
completions?: Completion[];
revealText?: string;
revealKey?: number;
insertText?: string;
insertKey?: number;
readOnly?: boolean;
reference?: CustomWidgetSchemaReferenceData;
height?: string;
@@ -51,6 +51,17 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
});
editorView.focus();
}, [editorCreated, editorInstanceId, props.revealKey, props.revealText]);
useEffect(() => {
const editorView = editorViews.get(editorInstanceId);
if (!editorView || !props.insertText) return;
const selection = editorView.state.selection.main;
editorView.dispatch({
changes: { from: selection.from, to: selection.to, insert: props.insertText },
selection: { anchor: selection.from + props.insertText.length },
scrollIntoView: true,
});
editorView.focus();
}, [editorCreated, editorInstanceId, props.insertKey, props.insertText]);
const handleCreateEditor = useCallback(
(view: EditorViewType) => {
editorViews.set(editorInstanceId, view);
@@ -1,6 +1,4 @@
import { snippetCompletion } from "@codemirror/autocomplete";
import type { Completion, CompletionSource } from "@codemirror/autocomplete";
import { jsxLanguage } from "@codemirror/lang-javascript";
import { hoverTooltip } from "@codemirror/view";
import {
@@ -41,72 +39,18 @@ const iconCompletions: Completion[] = customJsxTablerIconNames.map((name) => ({
detail: "Safe Tabler icon",
}));
export const customJsxSafeBlockCompletions: Completion[] = [
snippetCompletion("map((item) => {\n\tconst value = ${};\n\treturn ${};\n})", {
label: "map block",
detail: "Safe immutable collection callback",
type: "snippet",
}),
snippetCompletion("(() => {\n\tconst value = ${};\n\treturn ${};\n})()", {
label: "derived value IIFE",
detail: "Safe page-level derived value",
type: "snippet",
}),
];
const rootBindingCompletions: Completion[] = [...ROOT_BINDINGS].toSorted().map((label) => ({
label,
type: ["data", "status", "options", "inputs"].includes(label) ? "variable" : "function",
detail: "Safe Custom JSX binding",
}));
export function getCustomJsxLocalConstCompletions(source: string, cursor: number): Completion[] {
const wrapped = `<>${source}</>`;
const target = cursor + 2;
let activeNode = jsxLanguage.parser.parse(wrapped).resolveInner(target, -1);
while (activeNode.name !== "Block") {
const parent = activeNode.parent;
if (!parent) return [];
activeNode = parent;
}
const completions: Completion[] = [];
let arrow = activeNode.parent;
while (arrow && arrow.name !== "ArrowFunction") arrow = arrow.parent;
arrow
?.getChild("ParamList")
?.getChildren("VariableDefinition")
.forEach((definition) => {
completions.push({
label: wrapped.slice(definition.from, definition.to),
type: "variable",
detail: "Safe callback parameter",
});
});
for (let statement = activeNode.firstChild; statement; statement = statement.nextSibling) {
if (statement.name !== "VariableDeclaration" || statement.from >= target) continue;
if (statement.firstChild?.name !== "const") continue;
const definitions = statement.getChildren("VariableDefinition");
definitions.forEach((definition, index) => {
const nextDefinition = definitions[index + 1];
const declaratorFinished = nextDefinition ? nextDefinition.from <= target : statement.to < target;
if (!declaratorFinished) return;
completions.push({
label: wrapped.slice(definition.from, definition.to),
type: "variable",
detail: "Safe local const",
});
});
}
return completions;
}
export const createCustomJsxCompletionSource =
(additional: Completion[]): CompletionSource =>
(context) => {
const word = context.matchBefore(/[A-Za-z](?:[\w."'_-]|\[|\])*/u);
if (!word && !context.explicit) return null;
const source = context.state.doc.toString();
const localCompletions = getCustomJsxLocalConstCompletions(source, context.pos);
const componentName = activeOpeningComponent(source, context.pos);
const contextualCompletions = componentName
? [
@@ -116,13 +60,7 @@ export const createCustomJsxCompletionSource =
: componentCompletions;
return {
from: word?.from ?? context.pos,
options: [
...localCompletions,
...customJsxSafeBlockCompletions,
...rootBindingCompletions,
...contextualCompletions,
...additional,
],
options: [...rootBindingCompletions, ...contextualCompletions, ...additional],
};
};
@@ -11,22 +11,13 @@ const jsonObjectString = z.string().superRefine((value, ctx) => {
}
});
const jsonArrayString = z.string().superRefine((value, ctx) => {
try {
if (!Array.isArray(JSON.parse(value))) throw new Error();
} catch {
ctx.addIssue({ code: "custom", message: "Must be a JSON array" });
}
});
export const customWidgetFormSchema = z.object({
name: z.string().trim().min(1).max(128),
description: z.string().max(512),
iconUrl: z.union([z.literal(""), z.string().url()]),
sources: jsonArrayString,
requests: jsonArrayString,
optionsSchema: jsonObjectString,
defaultOptions: jsonObjectString,
sources: jsonObjectString,
requests: jsonObjectString,
options: jsonObjectString,
template: z.string().min(1).max(50_000),
secrets: z.array(
z.object({ sourceId: z.string(), kind: z.string(), value: z.string(), hasValue: z.boolean().optional() }),
@@ -54,8 +45,7 @@ export const DEFAULT_CUSTOM_WIDGET_FORM_VALUES: CustomWidgetFormValues = {
iconUrl: CUSTOM_WIDGET_STARTER.iconUrl ?? "",
sources: JSON.stringify(CUSTOM_WIDGET_STARTER.sources, null, 2),
requests: JSON.stringify(CUSTOM_WIDGET_STARTER.requests, null, 2),
optionsSchema: JSON.stringify(CUSTOM_WIDGET_STARTER.optionsSchema, null, 2),
defaultOptions: JSON.stringify(CUSTOM_WIDGET_STARTER.defaultOptions, null, 2),
options: JSON.stringify(CUSTOM_WIDGET_STARTER.options, null, 2),
template: CUSTOM_WIDGET_STARTER.template,
secrets: [],
};
@@ -5,7 +5,7 @@ export interface PreviewNamedRequest {
id: string;
kind: "query" | "action";
method: string;
pathTemplate: string;
path: string;
minimumBoardPermission?: string;
}
@@ -13,7 +13,7 @@ export interface PreviewJournalEntry {
id: string;
requestId: string;
method: string;
pathTemplate: string;
path: string;
simulated: boolean;
status: number | null;
durationMs: number;
@@ -82,7 +82,7 @@ export function PreviewRequestPanel({
{request.id}
</Text>
<Text size="xs" c="dimmed" ff="monospace" lineClamp={1}>
{request.pathTemplate}
{request.path}
</Text>
</div>
<Group gap={4} wrap="nowrap">
@@ -111,7 +111,7 @@ export function PreviewRequestPanel({
{entry.requestId}
</Text>
<Text size="xs" c="dimmed" ff="monospace" truncate>
{entry.pathTemplate}
{entry.path}
</Text>
</div>
<Group gap={4} wrap="nowrap">
@@ -11,20 +11,26 @@ export const redactPreviewUrl = (value: string): string => {
};
export const getPreviewNamedRequests = (definition: Record<string, unknown>): PreviewNamedRequest[] => {
if (!Array.isArray(definition.requests)) return [];
return definition.requests.filter(
(request): request is PreviewNamedRequest =>
request !== null &&
typeof request === "object" &&
"id" in request &&
typeof request.id === "string" &&
"kind" in request &&
(request.kind === "query" || request.kind === "action") &&
"method" in request &&
typeof request.method === "string" &&
"pathTemplate" in request &&
typeof request.pathTemplate === "string",
);
if (!definition.requests || typeof definition.requests !== "object" || Array.isArray(definition.requests)) return [];
return Object.entries(definition.requests as Record<string, unknown>).flatMap(([id, candidate]) => {
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return [];
const request = candidate as Record<string, unknown>;
if (
(request.kind !== "query" && request.kind !== "action") ||
typeof request.method !== "string" ||
typeof request.path !== "string"
)
return [];
return [
{
id,
kind: request.kind,
method: request.method,
path: request.path,
minimumBoardPermission: typeof request.permission === "string" ? request.permission : undefined,
},
];
});
};
export type CustomWidgetAccessibilityIssue = "imageAlt" | "actionIconLabel" | "inputLabel";
@@ -9,25 +9,55 @@ export function renameCustomWidgetRequest(
): HomarrCustomWidgetV2 {
const parsedId = customWidgetIdentifierSchema.safeParse(nextId);
if (!parsedId.success) throw new Error(parsedId.error.issues[0]?.message ?? "Invalid request ID");
if (!definition.requests.some((request) => request.id === currentId))
throw new Error(`Unknown request '${currentId}'`);
if (currentId !== nextId && definition.requests.some((request) => request.id === nextId)) {
if (!definition.requests[currentId]) throw new Error(`Unknown request '${currentId}'`);
if (currentId !== nextId && definition.requests[nextId]) {
throw new Error(`Request '${nextId}' already exists`);
}
const candidate = {
...definition,
requests: definition.requests.map((request) => ({
...request,
id: request.id === currentId ? nextId : request.id,
invalidates: request.invalidates?.map((id) => (id === currentId ? nextId : id)),
})),
optionsSchema: replaceDynamicOptionRequest(definition.optionsSchema, currentId, nextId),
requests: Object.fromEntries(
Object.entries(definition.requests).map(([id, request]) => [
id === currentId ? nextId : id,
{ ...request, invalidates: request.invalidates?.map((entry) => (entry === currentId ? nextId : entry)) },
]),
),
options: replaceDynamicOptionRequest(definition.options, currentId, nextId),
template: replaceTemplateRequestReferences(definition.template, currentId, nextId),
};
return customWidgetDefinitionSchema.parse(candidate);
}
export function renameCustomWidgetOption(
definition: HomarrCustomWidgetV2,
currentName: string,
nextName: string,
): HomarrCustomWidgetV2 {
const parsedName = customWidgetIdentifierSchema.safeParse(nextName);
if (!parsedName.success) throw new Error(parsedName.error.issues[0]?.message ?? "Invalid option name");
if (!definition.options[currentName]) throw new Error(`Unknown option '${currentName}'`);
if (currentName !== nextName && definition.options[nextName]) throw new Error(`Option '${nextName}' already exists`);
return customWidgetDefinitionSchema.parse({
...definition,
options: Object.fromEntries(
Object.entries(definition.options).map(([name, option]) => [name === currentName ? nextName : name, option]),
),
requests: Object.fromEntries(
Object.entries(definition.requests).map(([id, request]) => [
id,
{
...request,
path: request.path.replaceAll(`{option:${currentName}}`, `{option:${nextName}}`),
query: replaceOptionReferences(request.query, currentName, nextName),
body: replaceOptionReferences(request.body, currentName, nextName),
},
]),
),
template: replaceTemplateOptionReferences(definition.template, currentName, nextName),
});
}
function replaceDynamicOptionRequest<T>(value: T, currentId: string, nextId: string): T {
if (Array.isArray(value)) return value.map((entry) => replaceDynamicOptionRequest(entry, currentId, nextId)) as T;
if (value === null || typeof value !== "object") return value;
@@ -35,7 +65,7 @@ function replaceDynamicOptionRequest<T>(value: T, currentId: string, nextId: str
const replaced = Object.fromEntries(
Object.entries(record).map(([key, child]) => [key, replaceDynamicOptionRequest(child, currentId, nextId)]),
);
if (record.requestId === currentId && "valuePath" in record && "labelPath" in record) replaced.requestId = nextId;
if (record.request === currentId && "valuePath" in record && "labelPath" in record) replaced.request = nextId;
return replaced as T;
}
@@ -47,6 +77,25 @@ function replaceTemplateRequestReferences(template: string, currentId: string, n
.replace(new RegExp(`((?:data|status)\\.)${escaped}\\b`, "gu"), `$1${nextId}`);
}
function replaceOptionReferences<T>(value: T, currentName: string, nextName: string): T {
if (Array.isArray(value)) return value.map((entry) => replaceOptionReferences(entry, currentName, nextName)) as T;
if (value === null || typeof value !== "object") return value;
const entries = Object.entries(value as Record<string, unknown>);
if (entries.length === 1 && entries[0]?.[0] === "$option" && entries[0][1] === currentName) {
return { $option: nextName } as T;
}
return Object.fromEntries(
entries.map(([key, child]) => [key, replaceOptionReferences(child, currentName, nextName)]),
) as T;
}
function replaceTemplateOptionReferences(template: string, currentName: string, nextName: string) {
const escaped = escapeRegExp(currentName);
return template
.replace(new RegExp(`(options\\s*\\[\\s*["'])${escaped}(["']\\s*\\])`, "gu"), `$1${nextName}$2`)
.replace(new RegExp(`(options\\.)${escaped}\\b`, "gu"), `$1${nextName}`);
}
function escapeRegExp(value: string) {
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
}