fix(custom-widgets): finish v2 hardening

This commit is contained in:
Thomas Camlong committed 2026-07-20 23:39:57 +02:00
1 parent 7c66c912e7
commit 1c02678a7e
97 files changed
+2833 -12393

No files matched your search

@@ -1,22 +1,23 @@
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
import { customJsxAuthoringCatalog } from "./component-catalog";
export const CUSTOM_WIDGET_MANTINE_VERSION = "9.4.1";
export const CUSTOM_WIDGET_MANTINE_VERSION = customJsxAuthoringCatalog.mantineVersion;
export const CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL = "--- END HOMARR CUSTOM WIDGET OFFLINE BUNDLE ---";
const CUSTOM_WIDGET_AI_PROMPT_LIMIT = 8_000;
const FINAL_OUTPUT_INSTRUCTION =
export const CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION =
"Create the requested widget now and return exactly one complete `json` fenced block followed by one complete `jsx` fenced block. Homarr will validate the result after it is pasted into the workbench.";
const AUTHORING_PROMPT = `You create Homarr Custom JSX v2 widgets. Return exactly two fenced blocks: a json block containing one complete widget object with template set to "__HOMARR_TEMPLATE__", then a jsx block containing the readable template.
Use $schema "homarr-custom-widget-v2". A widget contains metadata, inline API sources, named requests, an options schema, defaults, and one JSX template. Never include credentials. Use one source named "default" unless the widget genuinely combines APIs.
This Homarr release uses Mantine ${CUSTOM_WIDGET_MANTINE_VERSION}. Use only the Homarr runtime components and Mantine capabilities described in this prompt. The embedded-skill variant includes the exact release-matched component reference files.
This Homarr release uses Mantine ${CUSTOM_WIDGET_MANTINE_VERSION}. Use only the Homarr runtime components and Mantine capabilities described in this prompt. The embedded-skill variant includes the complete release-matched skill, widget schema, component catalog, and canonical examples for self-contained offline authoring.
Queries and actions may use GET, POST, PUT, PATCH, or DELETE. Set kind to query for reads and action for user-triggered changes. Actions never use trigger "load". Declare every path, query, or body parameter. Use {name} in paths and {"$param":"name"} in query/body templates. Every declared parameter needs an explicit value source: SubFetch, ActionButton, and ToggleSwitch supply manual request values through their params prop; every load-query parameter must have an optionsBinding entry containing {"$option":"optionName"} or a primitive literal. Never infer a binding from matching names. Use load-triggered query results through data.<requestId>.
Source authentication is exactly one of {"type":"none"}, {"type":"bearer"}, {"type":"basic"}, {"type":"apiKeyHeader","headerName":"X-API-Key"}, or {"type":"apiKeyQuery","parameterName":"api_key"}. Credentials are configured separately by the user.
Templates can read data, status, options, and inputs. Bind supported Mantine controls with bind="search" and read the temporary value as inputs.search. Bound inputs live only in memory and reset when the widget reloads; saved configuration belongs in options. Restricted callback blocks may declare immutable local const values followed by one final return. Use RecursiveList for arbitrary-depth trees instead of authored recursion. Use Mantine Core, Dates, and Charts components. Do not use imports, hooks, refs, raw event callback props, component/renderRoot, arbitrary portals, raw HTML, fetch, eval, npm packages, or credentials. Design for compact and wide dashboard sizes with useful loading, empty, and error states.
Templates can read data, status, options, and inputs. Each status.<requestId> is an object shaped { loading: boolean, ok?: boolean, status?: number, statusText?: string, error?: string }; never compare it with the strings "loading", "success", or "error". Use status.list?.loading while loading, status.list?.ok === false for failure, and status.list?.ok === true for success. Bind supported Mantine controls with bind="search" and read the temporary value as inputs.search. Bound inputs live only in memory and reset when the widget reloads; saved configuration belongs in options. Restricted callback blocks may declare immutable local const values followed by one final return. Use RecursiveList for arbitrary-depth trees instead of authored recursion. Use Mantine Core, Dates, and Charts components. Do not use imports, hooks, refs, raw event callback props, component/renderRoot, arbitrary portals, raw HTML, fetch, eval, npm packages, or credentials. Design for compact and wide dashboard sizes with useful loading, empty, and error states.
Options use a restricted object JSON Schema. x-homarr controls include text, textarea, number, switch, select, multi-select, slider, date, time, color, icon, url, duration, timeZone, and json. Dynamic selects use x-homarr.optionsSource with requestId, optional itemsPath for wrapped arrays, valuePath, and labelPath.
@@ -37,7 +38,7 @@ export const CUSTOM_WIDGET_MCP_AUTHORING_PROMPT = `Author one Homarr Custom JSX
6. Use customWidget_secretSet only for a credential the user supplied and only with dedicated permission. Otherwise call customWidget_secretRequestUser and poll its completion status; never receive or repeat the plaintext.
7. Call customWidget_create only after validation, request tests, action simulation, and visual inspection pass.
Use inline sources, named queries/actions, restricted JSON Schema options, temporary declarative bind controls exposed through inputs, and safe Mantine JSX. Every load-query parameter needs an explicit optionsBinding option reference or literal; manual queries and actions receive all parameters from the invoking component's params prop. Never infer sources from matching names. Use kind, not method, to distinguish reads from user-triggered changes. Never include credentials, imports, hooks, refs, callbacks, browser requests, arbitrary JavaScript, npm packages, polymorphic roots, or arbitrary portals. Make the widget responsive, accessible, loading-aware, empty-aware, and error-aware. The live schema and component resources are authoritative for the installed Homarr release.`;
Use inline sources, named queries/actions, restricted JSON Schema options, temporary declarative bind controls exposed through inputs, and safe Mantine JSX. Every load-query parameter needs an explicit optionsBinding option reference or literal; manual queries and actions receive all parameters from the invoking component's params prop. Never infer sources from matching names. Each status.<requestId> is an object with loading, ok, status, statusText, and error fields; never compare it with "loading", "success", or "error". Use kind, not method, to distinguish reads from user-triggered changes. Never include credentials, imports, hooks, refs, callbacks, browser requests, arbitrary JavaScript, npm packages, polymorphic roots, or arbitrary portals. Make the widget responsive, accessible, loading-aware, empty-aware, and error-aware. The live schema and component resources are authoritative for the installed Homarr release.`;
export function buildCustomWidgetMcpPrompt(request?: string | null, documentationUrl?: string | null) {
const sections = [CUSTOM_WIDGET_MCP_AUTHORING_PROMPT];
@@ -60,7 +61,7 @@ export function buildCustomWidgetAiPrompt(
const sections = [`Please create this Homarr Custom JSX v2 widget:\n\n${requestedWidget}`];
if (documentationUrl) sections.push(`API documentation: ${truncatePromptText(redactUrl(documentationUrl), 500)}`);
sections.push(AUTHORING_PROMPT);
sections.push(FINAL_OUTPUT_INSTRUCTION);
sections.push(CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION);
const optionalSections = [
...(rawResponse ? [{ label: "Sample API response", content: redactResponse(rawResponse) }] : []),
@@ -1,6 +1,11 @@
import { customJsxAuthoringCatalog, getCustomJsxComponentProps } from "./component-catalog";
import { customJsxExamples } from "./examples";
import { CUSTOM_WIDGET_SKILL_MD, CUSTOM_WIDGET_SKILL_VERSION } from "./embedded-ai-prompt";
import {
CUSTOM_WIDGET_OFFLINE_BUNDLE,
CUSTOM_WIDGET_SKILL_FILES,
CUSTOM_WIDGET_SKILL_MD,
CUSTOM_WIDGET_SKILL_VERSION,
} from "./embedded-ai-prompt";
import { customJsxTablerIconNames } from "./tabler-icons";
export const CUSTOM_WIDGET_SKILLS_SH_URL = "https://www.skills.sh/homarr-labs/homarr/homarr-custom-widget";
@@ -14,12 +19,19 @@ export function getCustomWidgetSkill() {
name: "homarr-custom-widget",
version: CUSTOM_WIDGET_SKILL_VERSION,
skillMd: CUSTOM_WIDGET_SKILL_MD,
files: CUSTOM_WIDGET_SKILL_FILES,
componentCatalog: customJsxAuthoringCatalog,
examples: customJsxExamples,
skillsShUrl: CUSTOM_WIDGET_SKILLS_SH_URL,
sourceUrl: CUSTOM_WIDGET_SKILL_SOURCE_URL,
installCommand: CUSTOM_WIDGET_SKILL_INSTALL_COMMAND,
};
}
export function getCustomWidgetOfflineBundle() {
return CUSTOM_WIDGET_OFFLINE_BUNDLE;
}
export function getCustomWidgetComponentCatalog() {
return customJsxAuthoringCatalog;
}
@@ -60,19 +60,3 @@ export interface CustomJsxAuthoringCatalog {
blockedCapabilities: CustomJsxBlockedCapability[];
components: CustomJsxComponentApi[];
}
export interface CustomJsxRuntimeComponentApi {
name: string;
package: CustomJsxComponentPackage;
safety: CustomJsxComponentSafety;
props: string[];
blockedProps: CustomJsxComponentBlockedProp[];
bind?: CustomJsxBindingDescriptor;
deniedReason?: string;
}
export interface CustomJsxRuntimeCatalog {
schemaVersion: typeof CUSTOM_JSX_AUTHORING_CATALOG_SCHEMA_VERSION;
globalProps: string[];
components: CustomJsxRuntimeComponentApi[];
}
@@ -1 +1 @@
{"schemaVersion":1,"mantineVersion":"9.4.1","customWidgetVersion":"2.0.0","types":["\"\" | \"anonymous\" | \"use-credentials\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"auto\" | \"fixed\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"auto\" | \"all\" | \"fill\" | \"stroke\" | \"painted\" | \"visible\" | \"visibleFill\" | \"visiblePainted\" | \"visibleStroke\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"block\" | \"inline\" | \"both\" | \"horizontal\" | \"vertical\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"contain\" | \"cover\" | \"fill\" | \"scale-down\"","\"activity\" | \"display-none\"","\"all\" | \"parent\" | \"child\"","\"all\" | \"segment\"","\"always\" | \"hover\" | \"not-hover\" | \"never\"","\"auto-fit\" | \"auto-fill\"","\"block\" | \"grid\"","\"both\" | \"rightSection\" | \"clear\"","\"bottom\" | \"top\"","\"bottom\" | \"top\" | \"baseline\" | \"middle\"","\"bottom\" | \"top\" | \"middle\"","\"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\" | \"bottom-center\" | \"top-center\" | \"middle-center\" | \"middle-end\" | \"middle-start\"","\"button\" | \"submit\" | \"reset\"","\"center\" | \"bottom\"","\"center\" | \"left\" | \"right\"","\"center\" | \"side\" | \"merge\"","\"dashed\" | \"dotted\" | \"solid\"","\"default\" | \"responsive\"","\"div\" | \"label\"","\"end\" | \"start\"","\"fixed\" | \"absolute\"","\"horizontal\" | \"vertical\"","\"hover\" | \"click\" | \"click-hover\"","\"inherit\" | \"auto\" | \"baseline\" | \"before-edge\" | \"text-before-edge\" | \"middle\" | \"central\" | \"after-edge\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\"","\"inherit\" | \"auto\" | \"sRGB\" | \"linearRGB\"","\"inherit\" | \"auto\" | \"text-before-edge\" | \"middle\" | \"central\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\" | \"use-script\" | \"no-change\" | \"reset-size\"","\"inherit\" | \"end\" | \"start\" | \"middle\"","\"inherit\" | \"nonzero\" | \"evenodd\"","\"inherit\" | \"round\" | \"butt\" | \"square\"","\"inherit\" | \"round\" | \"miter\" | \"bevel\"","\"initial\" | \"medial\" | \"terminal\" | \"isolated\"","\"inside\" | \"outside\"","\"left\" | \"right\"","\"left\" | \"right\" | \"bottom\" | \"top\" | \"left-end\" | \"left-start\" | \"right-end\" | \"right-start\" | \"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\"","\"left\" | \"right\" | \"inside\"","\"link\" | \"none\" | \"copy\" | \"execute\" | \"move\" | \"popup\"","\"month\" | \"year\" | \"decade\"","\"none\" | \"all\" | \"rows\" | \"groups\" | \"columns\"","\"none\" | \"all\" | \"with-indicators\"","\"none\" | \"ascending\" | \"descending\" | \"other\"","\"none\" | \"inline\" | \"list\" | \"both\"","\"none\" | \"strict\" | \"blur\"","\"none\" | \"sum\"","\"none\" | \"thousand\" | \"lakh\" | \"wan\"","\"none\" | \"x\" | \"y\" | \"xy\"","\"off\" | \"assertive\" | \"polite\"","\"off\" | \"on\"","\"right-to-left\" | \"left-to-right\"","\"search\" | \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"send\"","\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"","\"step\" | \"bump\" | \"linear\" | \"natural\" | \"monotone\" | \"stepBefore\" | \"stepAfter\"","\"stepInactive\" | \"stepProgress\" | \"stepCompleted\"","\"sum\" | \"replace\"","\"td\" | \"th\"","\"text\" | \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text additions\" | \"text removals\"","\"value\" | \"name\" | \"percent\"","\"viewport\"","\"wrap\" | \"nowrap\" | \"balance\" | \"pretty\" | \"stable\"","\"x\" | \"y\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\"","\"yes\" | \"no\"","'Text' | 'Title' | 'Badge' | 'Code' | 'Image'","'auto' | 'manual'","'json' | 'text'","'xs' | 'sm' | 'md' | 'lg' | 'xl'","(\"input\" | \"label\" | \"description\" | \"error\")[]","(\"next\" | \"previous\" | \"level\")[]","(ActionIconProps & React.ClassAttributes<HTMLButtonElement> & React.ButtonHTMLAttributes<HTMLButtonElement>)","(CartesianChartProps<unknown> & { ref?: React.Ref<SVGSVGElement>; })","(CloseButtonProps & ElementProps<\"button\"> & DataAttributes)","(CloseButtonProps & React.ClassAttributes<HTMLButtonElement> & React.ButtonHTMLAttributes<HTMLButtonElement>)","(ElementProps<\"button\"> & DataAttributes)","(InputDescriptionProps & DataAttributes)","(InputErrorProps & DataAttributes)","(InputLabelProps & DataAttributes)","(InputSuccessProps & DataAttributes)","(OverlayProps & ElementProps<\"div\">)","(PolarChartProps<unknown> & { ref?: React.Ref<SVGSVGElement>; })","(React.ClassAttributes<HTMLButtonElement> & React.ButtonHTMLAttributes<HTMLButtonElement> & DataAttributes)","(React.ClassAttributes<HTMLDivElement> &Line truncated
{"schemaVersion":1,"mantineVersion":"9.4.1","customWidgetVersion":"2.0.0","types":["\"\" | \"anonymous\" | \"use-credentials\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"auto\" | \"fixed\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"auto\" | \"all\" | \"fill\" | \"stroke\" | \"painted\" | \"visible\" | \"visibleFill\" | \"visiblePainted\" | \"visibleStroke\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"block\" | \"inline\" | \"both\" | \"horizontal\" | \"vertical\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"none\" | \"contain\" | \"cover\" | \"fill\" | \"scale-down\"","\"-moz-initial\" | \"inherit\" | \"initial\" | \"revert\" | \"revert-layer\" | \"unset\" | \"wrap\" | \"nowrap\" | \"wrap-reverse\"","\"12h\" | \"24h\"","\"activity\" | \"display-none\"","\"all\" | \"parent\" | \"child\"","\"all\" | \"segment\"","\"always\" | \"hover\" | \"not-hover\" | \"never\"","\"area\" | \"radial\" | \"scatter\"","\"auto\" | \"scroll\" | \"always\" | \"hover\" | \"never\"","\"auto-fit\" | \"auto-fill\"","\"block\" | \"grid\"","\"both\" | \"rightSection\" | \"clear\"","\"bottom\" | \"top\"","\"bottom\" | \"top\" | \"baseline\" | \"middle\"","\"bottom\" | \"top\" | \"middle\"","\"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\" | \"bottom-center\" | \"top-center\" | \"middle-center\" | \"middle-end\" | \"middle-start\"","\"button\" | \"submit\" | \"reset\"","\"center\" | \"bottom\"","\"center\" | \"left\" | \"right\"","\"center\" | \"left\" | \"right\" | \"justify\" | \"char\"","\"center\" | \"side\" | \"merge\"","\"checkbox\" | \"radio\"","\"dashed\" | \"dotted\" | \"solid\"","\"default\" | \"gradient\"","\"default\" | \"responsive\"","\"default\" | \"stacked\" | \"percent\" | \"split\"","\"default\" | \"stacked\" | \"percent\" | \"waterfall\"","\"div\" | \"label\"","\"end\" | \"start\"","\"filled\" | \"light\"","\"fixed\" | \"absolute\"","\"hex\" | \"hexa\" | \"rgba\" | \"rgb\" | \"hsl\" | \"hsla\"","\"horizontal\" | \"vertical\"","\"hover\" | \"click\" | \"click-hover\"","\"inherit\" | \"auto\" | \"baseline\" | \"before-edge\" | \"text-before-edge\" | \"middle\" | \"central\" | \"after-edge\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\"","\"inherit\" | \"auto\" | \"sRGB\" | \"linearRGB\"","\"inherit\" | \"auto\" | \"text-before-edge\" | \"middle\" | \"central\" | \"text-after-edge\" | \"ideographic\" | \"alphabetic\" | \"hanging\" | \"mathematical\" | \"use-script\" | \"no-change\" | \"reset-size\"","\"inherit\" | \"end\" | \"start\" | \"middle\"","\"inherit\" | \"nonzero\" | \"evenodd\"","\"inherit\" | \"round\" | \"butt\" | \"square\"","\"inherit\" | \"round\" | \"miter\" | \"bevel\"","\"initial\" | \"medial\" | \"terminal\" | \"isolated\"","\"inside\" | \"outside\"","\"left\" | \"right\"","\"left\" | \"right\" | \"bottom\" | \"top\" | \"left-end\" | \"left-start\" | \"right-end\" | \"right-start\" | \"bottom-end\" | \"bottom-start\" | \"top-end\" | \"top-start\"","\"left\" | \"right\" | \"inside\"","\"link\" | \"none\" | \"copy\" | \"execute\" | \"move\" | \"popup\"","\"media\" | \"container\"","\"month\" | \"year\" | \"decade\"","\"native\" | \"scrollarea\"","\"none\" | \"all\" | \"rows\" | \"groups\" | \"columns\"","\"none\" | \"all\" | \"with-indicators\"","\"none\" | \"ascending\" | \"descending\" | \"other\"","\"none\" | \"inline\" | \"list\" | \"both\"","\"none\" | \"strict\" | \"blur\"","\"none\" | \"sum\"","\"none\" | \"thousand\" | \"lakh\" | \"wan\"","\"none\" | \"x\" | \"y\" | \"xy\"","\"number\" | RegExp | \"alphanumeric\"","\"off\" | \"assertive\" | \"polite\"","\"off\" | \"on\"","\"ordered\" | \"unordered\"","\"right-to-left\" | \"left-to-right\"","\"search\" | \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"send\"","\"search\" | \"text\" | \"none\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\"","\"step\" | \"bump\" | \"linear\" | \"natural\" | \"monotone\" | \"stepBefore\" | \"stepAfter\"","\"stepInactive\" | \"stepProgress\" | \"stepCompleted\"","\"sum\" | \"replace\"","\"td\" | \"th\"","\"text\" | \"additions\" | \"additions removals\" | \"additions text\" | \"all\" | \"removals\" | \"removals additions\" | \"removals text\" | \"text additions\" | \"text removals\"","\"text\" | \"tel\" | \"password\"","\"time\" | \"duration\"","\"up\" | \"down\"","\"value\" | \"name\" | \"percent\"","\"viewport\"","\"wrap\" | \"nowrap\" | \"balance\" | \"pretty\" | \"stable\"","\"x\" | \"y\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\"","\"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | (string & {})","\"yes\" | \"no\"","'Text' | 'Title' | 'Badge' | 'Code' | 'Image'","'auto' | 'manual'","'json' | 'text'","'xs' | 'sm' | 'md' | 'lg' | 'xl'","(\"input\" | \"label\" | \"description\" | \"error\")[]","(\"next\" | \"previLine truncated
@@ -0,0 +1,57 @@
import type {
CustomJsxAuthoringCatalog,
CustomJsxCatalogBindingType,
CustomJsxComponentApi,
CustomJsxPropDescriptor,
} from "./component-catalog-types";
export function buildCustomJsxComponentUsageExample(
component: CustomJsxComponentApi,
catalog: Pick<CustomJsxAuthoringCatalog, "types">,
) {
if (component.name === "RecursiveList") {
return `<RecursiveList data={data.tree} childrenPath="children" keyPath="id" showLines>
{(node, meta) => (
<Group gap="xs">
<Text>{node.label}</Text>
{meta.hasChildren && <Badge>{meta.childCount}</Badge>}
</Group>
)}
</RecursiveList>`;
}
const props = component.props
.filter((prop) => prop.required)
.slice(0, 4)
.map((prop) => `${prop.name}=${examplePropValue(prop, catalog.types[prop.typeRef] ?? "unknown")}`);
if (component.bind) {
props.unshift(
`bind="value"`,
`${component.bind.initialProp}=${bindingInitialValue(component.bind.type, component.bind.initialProp)}`,
);
}
const propText = props.length > 0 ? ` ${props.join(" ")}` : "";
return `<${component.name}${propText} />`;
}
function bindingInitialValue(type: CustomJsxCatalogBindingType, initialProp: "defaultValue" | "defaultChecked") {
if (initialProp === "defaultChecked") return "{false}";
if (type === "string") return '""';
if (type === "number") return "{0}";
if (type === "boolean") return "{false}";
return "{[]}";
}
function examplePropValue(prop: CustomJsxPropDescriptor, type: string) {
const literal = prop.literalValues?.[0];
if (literal !== undefined) return `{${formatLiteral(literal)}}`;
if (type.includes("string")) return `"${prop.name}"`;
if (type.includes("boolean")) return "{true}";
if (type.includes("number")) return "{0}";
if (type.includes("[]") || type.includes("Array<")) return "{[]}";
return `{options.${prop.name}}`;
}
function formatLiteral(value: string | number | boolean | null) {
return typeof value === "string" ? JSON.stringify(value) : String(value);
}
@@ -1,12 +1,11 @@
import runtimeCatalog from "./component-runtime.generated.json";
import type { CustomJsxCatalogBindingType, CustomJsxRuntimeCatalog } from "./component-catalog-types";
import { customJsxAuthoringCatalog } from "./component-catalog";
import type { CustomJsxCatalogBindingType } from "./component-catalog-types";
import type { CustomJsxComponentDescriptor } from "./component-descriptor";
const customJsxRuntimeCatalog = runtimeCatalog as unknown as Readonly<CustomJsxRuntimeCatalog>;
const globalPropNames = customJsxRuntimeCatalog.globalProps;
const globalPropNames = customJsxAuthoringCatalog.globalProps.map(({ name }) => name);
export const customJsxComponentRegistry: readonly CustomJsxComponentDescriptor[] =
customJsxRuntimeCatalog.components.map((component) => ({
customJsxAuthoringCatalog.components.map((component) => ({
name: component.name,
package: component.package,
safety: component.safety,
@@ -18,7 +17,7 @@ export const customJsxComponentRegistry: readonly CustomJsxComponentDescriptor[]
...globalPropNames.filter(
(propName) => !component.blockedProps.some((blockedProp) => blockedProp.name === propName),
),
...component.props,
...component.props.map(({ name }) => name),
...(component.bind ? ["bind"] : []),
]),
],
@@ -35,7 +34,7 @@ export const customJsxSupportedPropsByName = new Map(
);
const catalogComponentsByName = new Map(
customJsxRuntimeCatalog.components.map((component) => [component.name, component]),
customJsxAuthoringCatalog.components.map((component) => [component.name, component]),
);
const multipleDateBindingComponents = new Set([
@@ -49,7 +48,7 @@ const multipleDateBindingComponents = new Set([
const rangeDateBindingComponents = new Set(["DateTimePicker", "InlineDateTimePicker"]);
export const customJsxBindableComponentNames: ReadonlySet<string> = new Set(
customJsxRuntimeCatalog.components.flatMap((component) => (component.bind ? [component.name] : [])),
customJsxAuthoringCatalog.components.flatMap((component) => (component.bind ? [component.name] : [])),
);
export type CustomJsxBindingType = CustomJsxCatalogBindingType;
@@ -1 +0,0 @@
{"schemaVersion":1,"globalProps":["abbr","about","accentHeight","accept","accessKey","accumulate","additive","align","alignmentBaseline","allowReorder","alphabetic","alt","amplitude","arabicForm","aria-activedescendant","aria-atomic","aria-autocomplete","aria-braillelabel","aria-brailleroledescription","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colindextext","aria-colspan","aria-controls","aria-current","aria-describedby","aria-description","aria-details","aria-disabled","aria-dropeffect","aria-errormessage","aria-expanded","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowindextext","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","ascent","attributeName","attributeType","autoCapitalize","autoComplete","autoCorrect","autoReverse","autoSave","azimuth","baseFrequency","baseProfile","baselineShift","bbox","bd","bdrs","begin","bg","bga","bgcolor","bgp","bgr","bgsz","bias","border","by","c","calcMode","capHeight","capture","cellPadding","cellSpacing","checked","clip","clipPath","clipPathUnits","clipRule","colSpan","color","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","cols","content","contentScriptType","contentStyleType","contextMenu","crossOrigin","cursor","cx","cy","d","darkHidden","datatype","decelerate","defaultChecked","defaultValue","descent","diffuseConstant","dir","dirName","direction","disabled","display","divisor","dominantBaseline","draggable","dur","dx","dy","edgeMode","elevation","enableBackground","end","enterKeyHint","exponent","exportparts","externalResourcesRequired","ff","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","flex","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","fr","frame","from","fs","fw","fx","fy","fz","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","gradientTransform","gradientUnits","h","hanging","headers","height","hidden","hiddenFrom","horizAdvX","horizOriginX","href","id","ideographic","imageRendering","in","in2","inert","inlist","inputMode","intercept","is","itemID","itemProp","itemScope","itemType","k","k1","k2","k3","k4","kernelMatrix","kernelUnitLength","kerning","key","keyPoints","keySplines","keyTimes","lang","lengthAdjust","letterSpacing","lh","lightHidden","lightingColor","limitingConeAngle","list","local","lts","m","mah","markerEnd","markerHeight","markerMid","markerStart","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","maw","max","maxLength","mb","me","media","method","mie","mih","min","minLength","mis","miw","ml","mod","mode","mr","ms","mt","multiple","mx","my","name","nonce","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overlinePosition","overlineThickness","p","paintOrder","panose1","part","path","pathLength","pattern","patternContentUnits","patternTransform","patternUnits","pb","pe","pie","pis","pl","placeholder","pointerEvents","points","pointsAtX","pointsAtY","pointsAtZ","pr","prefix","preserveAlpha","preserveAspectRatio","primitiveUnits","property","ps","pt","px","py","r","radioGroup","radius","readOnly","rel","renderingIntent","repeatCount","repeatDur","required","requiredExtensions","requiredFeatures","resource","restart","result","results","rev","role","rotate","rowSpan","rows","rules","rx","ry","scale","scope","security","seed","shadow","shapeRendering","size","slope","slot","spacing","specularConstant","specularExponent","speed","spellCheck","spreadMethod","src","startOffset","stdDeviation","stemh","stemv","step","stitchTiles","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","string","stroke","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","style","styles","summary","surfaceScale","systemLanguage","ta","tabIndex","tableValues","target","targetX","targetY","td","textAnchor","textDecoration","textLength","textRendering","title","to","transform","translate","tt","type","typeof","u1","u2","underlinePosition","underlineThickness","unicode","unicodeBidi","unicodeRange","unitsPerEm","unselectable","vAlphabetic","vHanging","vIdeographic","vMathematical","valign","value","values","variant","vectorEffect","version","vertAdvY","vertOriginX","vertOriginY","viewBox","viewTarget","visibility","visibleFrom","vocab","w","width","widths","withBorder","wordSpacing","wrap","writingMode","x","x1","x2","xChannelSelector","xHeight","xlinkActuate","xlinkArcrole","xlinkHref","xlinkRole","xLine truncated
@@ -17,7 +17,7 @@ interface SecurityDefinition {
optionsSchema: unknown;
}
export function isCredentialKeyName(value: string) {
function isCredentialKeyName(value: string) {
return credentialKeyPattern.test(value);
}
@@ -2,6 +2,7 @@ import generatedSkillContent from "./skill-content.generated.json";
import {
buildCustomWidgetAiPrompt,
CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION,
CUSTOM_WIDGET_MANTINE_VERSION,
finalizeCustomWidgetOfflineContent,
} from "./ai-prompt";
@@ -31,6 +32,15 @@ const skillFile = CUSTOM_WIDGET_SKILL_FILES.find(({ path }) => path === "SKILL.m
if (!skillFile) throw new Error("The generated Custom Widget skill is missing SKILL.md");
export const CUSTOM_WIDGET_SKILL_MD = skillFile.content;
const componentCatalogFile = CUSTOM_WIDGET_SKILL_FILES.find(({ path }) => path === "references/component-catalog.json");
const examplesFile = CUSTOM_WIDGET_SKILL_FILES.find(({ path }) => path === "references/examples.json");
if (!componentCatalogFile || !examplesFile)
throw new Error("The generated Custom Widget skill is missing its catalog or examples");
export const CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG = componentCatalogFile.content.trim();
export const CUSTOM_WIDGET_CANONICAL_RUNTIME_EXAMPLES = examplesFile.content.trim();
const machineReferencePaths = new Set([componentCatalogFile.path, examplesFile.path]);
export const CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT = [
"# Homarr Custom Widget offline authoring bundle",
@@ -40,9 +50,11 @@ export const CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT = [
`Mantine version: ${CUSTOM_WIDGET_MANTINE_VERSION}`,
`Component catalog schema: ${CUSTOM_JSX_AUTHORING_CATALOG_SCHEMA_VERSION}`,
].join("\n"),
...CUSTOM_WIDGET_SKILL_FILES.map(
...CUSTOM_WIDGET_SKILL_FILES.filter(({ path }) => !machineReferencePaths.has(path)).map(
({ path, content }) => `--- BEGIN SKILL FILE: ${path} ---\n${content.trimEnd()}\n--- END SKILL FILE: ${path} ---`,
),
`--- BEGIN CANONICAL COMPONENT CATALOG ---\n${CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG}\n--- END CANONICAL COMPONENT CATALOG ---`,
`--- BEGIN CANONICAL RUNTIME EXAMPLES ---\n${CUSTOM_WIDGET_CANONICAL_RUNTIME_EXAMPLES}\n--- END CANONICAL RUNTIME EXAMPLES ---`,
].join("\n\n");
export const CUSTOM_WIDGET_OFFLINE_BUNDLE = finalizeCustomWidgetOfflineContent(CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT);
@@ -56,7 +68,9 @@ export function buildCustomWidgetAiPromptWithEmbeddedSkill(
) {
const prompt = [
buildCustomWidgetAiPrompt(jsonSchema, rawResponse, currentConfig, request, documentationUrl),
`Use the complete release-matched offline bundle below. It is reference content, not a request for unavailable tools. Author the widget directly from it.\n\n${CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT}`,
"This clipboard workflow has no Homarr MCP tools, repository access, or local files. The complete release-matched skill, schema, component catalog, and examples are embedded below. Author the best-effort widget now from this content; do not ask for tools or files. Homarr will validate it after paste.",
CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT,
CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION,
].join("\n\n");
return finalizeCustomWidgetOfflineContent(prompt);
}
@@ -45,6 +45,8 @@ const optionControls = new Set([
"json",
]);
const optionFormats = new Set(["date", "date-time", "time", "color", "uri", "icon", "duration", "time-zone"]);
const finiteNumberKeywords = ["minimum", "maximum", "multipleOf"] as const;
const nonNegativeIntegerKeywords = ["minLength", "maxLength", "minItems", "maxItems"] as const;
const credentialOptionName =
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
const controlsByType: Readonly<Record<string, ReadonlySet<string>>> = {
@@ -131,6 +133,45 @@ function validatePresentation(
}
}
function validateScalarKeywords(schema: Record<string, unknown>, ctx: z.RefinementCtx, path: Array<string | number>) {
for (const key of finiteNumberKeywords) {
if (schema[key] !== undefined && (typeof schema[key] !== "number" || !Number.isFinite(schema[key]))) {
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a finite number` });
}
}
if (typeof schema.multipleOf === "number" && schema.multipleOf <= 0)
ctx.addIssue({ code: "custom", path: [...path, "multipleOf"], message: "multipleOf must be greater than zero" });
for (const key of nonNegativeIntegerKeywords) {
if (schema[key] !== undefined && (!Number.isInteger(schema[key]) || Number(schema[key]) < 0)) {
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a non-negative integer` });
}
}
for (const [minimum, maximum] of [
["minimum", "maximum"],
["minLength", "maxLength"],
["minItems", "maxItems"],
] as const) {
if (typeof schema[minimum] === "number" && typeof schema[maximum] === "number" && schema[minimum] > schema[maximum])
ctx.addIssue({ code: "custom", path, message: `${minimum} cannot be greater than ${maximum}` });
}
}
function validateChoices(schema: Record<string, unknown>, ctx: z.RefinementCtx, path: Array<string | number>) {
if (
schema.enum !== undefined &&
(!Array.isArray(schema.enum) || schema.enum.length === 0 || schema.enum.length > 100)
) {
ctx.addIssue({ code: "custom", path: [...path, "enum"], message: "enum must contain between 1 and 100 values" });
} else if (
Array.isArray(schema.enum) &&
schema.enum.some((entry) => !matchesDeclaredOptionType(schema.type, entry))
) {
ctx.addIssue({ code: "custom", path: [...path, "enum"], message: "Every enum value must match the option type" });
}
if (schema.const !== undefined && !matchesDeclaredOptionType(schema.type, schema.const))
ctx.addIssue({ code: "custom", path: [...path, "const"], message: "const must match the option type" });
}
function validateOptionSchemaNode(
value: unknown,
ctx: z.RefinementCtx,
@@ -160,55 +201,14 @@ function validateOptionSchemaNode(
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a string` });
}
}
for (const key of ["minimum", "maximum", "multipleOf"] as const) {
if (schema[key] !== undefined && (typeof schema[key] !== "number" || !Number.isFinite(schema[key]))) {
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a finite number` });
}
}
if (typeof schema.multipleOf === "number" && schema.multipleOf <= 0) {
ctx.addIssue({ code: "custom", path: [...path, "multipleOf"], message: "multipleOf must be greater than zero" });
}
if (typeof schema.minimum === "number" && typeof schema.maximum === "number" && schema.minimum > schema.maximum) {
ctx.addIssue({ code: "custom", path, message: "minimum cannot be greater than maximum" });
}
for (const key of ["minLength", "maxLength", "minItems", "maxItems"] as const) {
if (
schema[key] !== undefined &&
(typeof schema[key] !== "number" || !Number.isInteger(schema[key]) || schema[key] < 0)
) {
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a non-negative integer` });
}
}
if (
typeof schema.minLength === "number" &&
typeof schema.maxLength === "number" &&
schema.minLength > schema.maxLength
) {
ctx.addIssue({ code: "custom", path, message: "minLength cannot be greater than maxLength" });
}
if (typeof schema.minItems === "number" && typeof schema.maxItems === "number" && schema.minItems > schema.maxItems) {
ctx.addIssue({ code: "custom", path, message: "minItems cannot be greater than maxItems" });
}
validateScalarKeywords(schema, ctx, path);
if (schema.format !== undefined && (typeof schema.format !== "string" || !optionFormats.has(schema.format))) {
ctx.addIssue({ code: "custom", path: [...path, "format"], message: "Unsupported option format" });
}
if (schema.format !== undefined && schema.type !== "string") {
ctx.addIssue({ code: "custom", path: [...path, "format"], message: "Option formats require a string type" });
}
if (
schema.enum !== undefined &&
(!Array.isArray(schema.enum) || schema.enum.length === 0 || schema.enum.length > 100)
) {
ctx.addIssue({ code: "custom", path: [...path, "enum"], message: "enum must contain between 1 and 100 values" });
} else if (
Array.isArray(schema.enum) &&
schema.enum.some((entry) => !matchesDeclaredOptionType(schema.type, entry))
) {
ctx.addIssue({ code: "custom", path: [...path, "enum"], message: "Every enum value must match the option type" });
}
if (schema.const !== undefined && !matchesDeclaredOptionType(schema.type, schema.const)) {
ctx.addIssue({ code: "custom", path: [...path, "const"], message: "const must match the option type" });
}
validateChoices(schema, ctx, path);
if (isRoot && schema.type !== "object") {
ctx.addIssue({ code: "custom", path: [...path, "type"], message: "The root options schema must be an object" });
}
+45 -47
View File
@@ -1,3 +1,5 @@
import { matchesDeclaredOptionType } from "./option-value-types";
export interface CustomWidgetOptionIssue {
path: string;
message: string;
@@ -25,11 +27,21 @@ function validateValue(schema: JsonSchema, value: unknown, path: string, issues:
}
const type = schema.type;
if (typeof type === "string" && !matchesType(type, value)) {
if (typeof type === "string" && !matchesDeclaredOptionType(type, value)) {
issues.push({ path, message: `Expected ${type}` });
return;
}
validateScalarValue(schema, value, path, issues);
if (Array.isArray(value)) validateArrayValue(schema, value, path, issues);
if (isRecord(value)) validateObjectValue(schema, value, path, issues);
else if (isRecord(schema.if)) {
const branch = matchesSchema(schema.if, value) ? schema.then : schema.else;
if (isRecord(branch)) validateValue(branch, value, path, issues);
}
}
function validateScalarValue(schema: JsonSchema, value: unknown, path: string, issues: CustomWidgetOptionIssue[]) {
if (typeof value === "string") {
if (typeof schema.minLength === "number" && value.length < schema.minLength)
issues.push({ path, message: `Must contain at least ${schema.minLength} characters` });
@@ -46,46 +58,40 @@ function validateValue(schema: JsonSchema, value: unknown, path: string, issues:
if (typeof schema.multipleOf === "number" && schema.multipleOf > 0 && value % schema.multipleOf !== 0)
issues.push({ path, message: `Must be a multiple of ${schema.multipleOf}` });
}
}
if (Array.isArray(value)) {
if (typeof schema.minItems === "number" && value.length < schema.minItems)
issues.push({ path, message: `Choose at least ${schema.minItems} values` });
if (typeof schema.maxItems === "number" && value.length > schema.maxItems)
issues.push({ path, message: `Choose at most ${schema.maxItems} values` });
const items = schema.items;
if (isRecord(items)) value.forEach((entry, index) => validateValue(items, entry, `${path}.${index}`, issues));
function validateArrayValue(schema: JsonSchema, value: unknown[], path: string, issues: CustomWidgetOptionIssue[]) {
if (typeof schema.minItems === "number" && value.length < schema.minItems)
issues.push({ path, message: `Choose at least ${schema.minItems} values` });
if (typeof schema.maxItems === "number" && value.length > schema.maxItems)
issues.push({ path, message: `Choose at most ${schema.maxItems} values` });
if (isRecord(schema.items))
value.forEach((entry, index) => validateValue(schema.items as JsonSchema, entry, `${path}.${index}`, issues));
}
function validateObjectValue(
schema: JsonSchema,
value: Record<string, unknown>,
path: string,
issues: CustomWidgetOptionIssue[],
) {
const branch = isRecord(schema.if) ? (matchesSchema(schema.if, value) ? schema.then : schema.else) : undefined;
const branchSchema = isRecord(branch) ? branch : {};
const properties = {
...(isRecord(schema.properties) ? schema.properties : {}),
...(isRecord(branchSchema.properties) ? branchSchema.properties : {}),
};
const required = [
...(Array.isArray(schema.required) ? schema.required : []),
...(Array.isArray(branchSchema.required) ? branchSchema.required : []),
].filter((entry): entry is string => typeof entry === "string");
for (const key of required) {
if (value[key] === undefined) issues.push({ path: `${path}.${key}`, message: "This field is required" });
}
if (isRecord(value)) {
const branch =
isRecord(schema.if) && matchesSchema(schema.if, value)
? schema.then
: isRecord(schema.if)
? schema.else
: undefined;
const branchSchema = isRecord(branch) ? branch : {};
const properties = {
...(isRecord(schema.properties) ? schema.properties : {}),
...(isRecord(branchSchema.properties) ? branchSchema.properties : {}),
};
const required = [
...(Array.isArray(schema.required) ? schema.required : []),
...(Array.isArray(branchSchema.required) ? branchSchema.required : []),
].filter((entry): entry is string => typeof entry === "string");
for (const key of required) {
if (value[key] === undefined) issues.push({ path: `${path}.${key}`, message: "This field is required" });
}
for (const [key, child] of Object.entries(value)) {
const childSchema = properties[key];
if (isRecord(childSchema)) validateValue(childSchema, child, `${path}.${key}`, issues);
else if (schema.additionalProperties === false)
issues.push({ path: `${path}.${key}`, message: "Unknown option" });
}
}
if (isRecord(schema.if) && !isRecord(value)) {
const branch = matchesSchema(schema.if, value) ? schema.then : schema.else;
if (isRecord(branch)) validateValue(branch, value, path, issues);
for (const [key, child] of Object.entries(value)) {
const childSchema = properties[key];
if (isRecord(childSchema)) validateValue(childSchema, child, `${path}.${key}`, issues);
else if (schema.additionalProperties === false) issues.push({ path: `${path}.${key}`, message: "Unknown option" });
}
}
@@ -95,14 +101,6 @@ function matchesSchema(schema: JsonSchema, value: unknown): boolean {
return issues.length === 0;
}
function matchesType(type: string, value: unknown): boolean {
if (type === "object") return isRecord(value);
if (type === "array") return Array.isArray(value);
if (type === "integer") return typeof value === "number" && Number.isInteger(value);
if (type === "null") return value === null;
return typeof value === type;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
@@ -3,15 +3,19 @@
"files": [
{
"path": "SKILL.md",
"content": "---\nname: homarr-custom-widget\ndescription: Author safe Homarr Custom JSX v2 widgets from API documentation. Use when creating or fixing Homarr custom widgets, including multi-source dashboards, queries, actions, options, temporary inputs, and Mantine JSX.\nlicense: Apache-2.0\nmetadata:\n version: \"2.0.0\"\n---\n\n# Homarr Custom Widget\n\nCreate one widget at a time. Repeat the workflow when the user asks for several widgets; do not invent packs or shared connections.\n\n## Choose the authoring reference\n\nWhen connected to Homarr, retrieve the live widget schema and component catalog before authoring. Live metadata is authoritative because Homarr and Mantine versions can differ between installations.\n\nFor offline authoring, read these installed, release-matched references in order:\n\n1. [Schema](references/schema.md)\n2. [JSX runtime](references/runtime.md)\n3. [Security boundary](references/security.md)\n4. [Component catalog](references/components.md)\n5. [Mantine Core](references/mantine-core.md)\n6. [Mantine Dates](references/mantine-dates.md)\n7. [Mantine Charts](references/mantine-charts.md)\n8. [Homarr components](references/homarr-components.md)\n\nTogether, this file and those references are the complete offline authoring bundle for the matching Homarr release. Do not require MCP tools, repository access, or external component documentation to produce a best-effort widget. If live metadata is available, prefer it over the installed static bundle.\n\n## Authoring workflow\n\n1. Read the API documentation supplied by the user. Ask for a missing base URL only when it cannot be inferred safely.\n2. Build one credential-free `homarr-custom-widget-v2` manifest and one safe JSX template.\n3. Use immutable local `const` blocks for repeated derived values and `RecursiveList` for arbitrary-depth trees. Do not emulate either feature with unrestricted JavaScript or authored recursion.\n4. Return the complete manifest and JSX in the exact fenced-block format requested by the authoring prompt.\n5. When the user supplies Homarr diagnostics, correct every reported issue while preserving unrelated fields.\n\n## Output rules\n\n- Use inline sources, named requests, definition-owned options, temporary bound inputs, and one safe JSX template.\n- Use `kind`, not the HTTP method, to distinguish reads from user-triggered actions.\n- Give every declared request parameter an explicit source. Load queries use `optionsBinding` with an option reference or primitive literal; manual queries and actions receive values only from the invoking component's `params` prop. Never infer bindings from matching names.\n- Never put a credential in JSX, options, headers, URLs, examples, exports, logs, or chat output.\n- Use declarative `bind` controls and Homarr request components. Controlled collection callbacks, zero-argument derived-value IIFEs, and the `RecursiveList` child template may use the restricted safe-block grammar documented in the runtime reference. Never emit imports, hooks, refs, raw callback props, browser requests, or arbitrary JavaScript.\n- Include responsive loading, empty, error, and success states.\n- Keep actions explicit, permission-scoped, confirmed when destructive, and followed by targeted invalidation.\n"
"content": "---\nname: homarr-custom-widget\ndescription: Author safe Homarr Custom JSX v2 widgets from API documentation. Use when creating or fixing Homarr custom widgets, including multi-source dashboards, queries, actions, options, temporary inputs, and Mantine JSX.\nlicense: Apache-2.0\nmetadata:\n version: \"2.0.0\"\n---\n\n# Homarr Custom Widget\n\nCreate one widget at a time. Repeat the workflow when the user asks for several widgets; do not invent packs or shared connections.\n\n## Choose the authoring reference\n\nWhen connected to Homarr, retrieve the live widget schema and component catalog before authoring. Live metadata is authoritative because Homarr and Mantine versions can differ between installations.\n\nFor offline authoring, read these installed, release-matched references in order:\n\n1. [Schema guide](references/schema.md)\n2. [Canonical widget JSON Schema](references/widget-schema.json)\n3. [JSX runtime](references/runtime.md)\n4. [Security boundary](references/security.md)\n5. [Component catalog guide](references/components.md)\n6. [Canonical component catalog](references/component-catalog.json)\n7. [Canonical examples](references/examples.json)\n8. [Official Mantine LLM index](references/mantine-core.md)\n9. [Official Mantine Dates guide](references/mantine-dates.md)\n10. [Mantine Charts links](references/mantine-charts.md)\n11. [Homarr components](references/homarr-components.md)\n\nTogether, this file and its references are the complete offline authoring bundle for the matching Homarr release. The JSON catalog contains the exact enabled component names, prop metadata, bindings, blocked capabilities, and versions. If live metadata is available, prefer it because it reflects the installed Homarr and Mantine versions.\n\n## Authoring workflow\n\n1. Read the API documentation supplied by the user. Ask for a missing base URL only when it cannot be inferred safely.\n2. Build one credential-free `homarr-custom-widget-v2` manifest and one safe JSX template.\n3. Use immutable local `const` blocks for repeated derived values and `RecursiveList` for arbitrary-depth trees. Do not emulate either feature with unrestricted JavaScript or authored recursion.\n4. Return the complete manifest and JSX in the exact fenced-block format requested by the authoring prompt.\n5. When the user supplies Homarr diagnostics, correct every reported issue while preserving unrelated fields.\n\n## Output rules\n\n- Use inline sources, named requests, definition-owned options, temporary bound inputs, and one safe JSX template.\n- Use `kind`, not the HTTP method, to distinguish reads from user-triggered actions.\n- Give every declared request parameter an explicit source. Load queries use `optionsBinding` with an option reference or primitive literal; manual queries and actions receive values only from the invoking component's `params` prop. Never infer bindings from matching names.\n- Treat `status.<requestId>` as `{ loading, ok, status, statusText, error }`. Never compare it with `\"loading\"`, `\"success\"`, or `\"error\"`; check `status.list?.loading`, `status.list?.ok === false`, or `status.list?.ok === true`.\n- Never put a credential in JSX, options, headers, URLs, examples, exports, logs, or chat output.\n- Use declarative `bind` controls and Homarr request components. Controlled collection callbacks, zero-argument derived-value IIFEs, and the `RecursiveList` child template may use the restricted safe-block grammar documented in the runtime reference. Never emit imports, hooks, refs, raw callback props, browser requests, or arbitrary JavaScript.\n- Include responsive loading, empty, error, and success states.\n- Keep actions explicit, permission-scoped, confirmed when destructive, and followed by targeted invalidation.\n"
},
{
"path": "references/schema.md",
"content": "# Custom Widget v2 schema\n\nEvery import and export is one object with `$schema: \"homarr-custom-widget-v2\"`, metadata, `sources`, `requests`, `optionsSchema`, `defaultOptions`, and `template`. Secrets are accepted separately by create/update/preview operations and never exported.\n\nThe safe-local-binding and `RecursiveList` expansion changes only template authoring. It does not add database fields, request fields, persistence, or another widget schema version.\n\n```ts\ninterface HomarrCustomWidgetV2 {\n $schema: \"homarr-custom-widget-v2\";\n name: string;\n description?: string;\n iconUrl?: string;\n sources: CustomWidgetSource[];\n requests: CustomWidgetRequest[];\n optionsSchema: CustomWidgetOptionsSchema;\n defaultOptions: Record<string, unknown>;\n template: string;\n}\n```\n\nA source has a stable lowercase `id`, display `name`, `baseUrl`, `networkScope` (`public`, `private`, or `loopback`), and one auth mode: `none`, `bearer`, `basic`, `apiKeyHeader`, or `apiKeyQuery`.\n\nA request has `id`, `sourceId`, `kind`, any supported HTTP `method`, same-origin `pathTemplate`, declared primitive `parameters`, optional `optionsBinding`, `queryTemplate`, and `bodyTemplate`, optional safe `staticHeaders`, `auth`, `minimumBoardPermission`, optional `trigger`, caching, confirmation, and invalidation. Parameter names may use camelCase. Reference a declared parameter with `{name}` in a path or `{ \"$param\": \"name\" }` in structured query/body data.\n\nEvery declared parameter needs an explicit source. For a load query, bind each parameter in `optionsBinding` with `{ \"$option\": \"optionName\" }` or a primitive literal of the declared type. The referenced option must exist in `optionsSchema`. For manual queries and actions, the invoking `SubFetch`, `ActionButton`, or `ToggleSwitch` supplies the complete parameter object through `params`. Never infer a source because a parameter, option, or temporary input has the same name.\n\nDynamic option requests have no JSX invoker and therefore also require `optionsBinding` for every parameter they declare.\n\nOptions use a restricted object JSON Schema. Set `additionalProperties: false`. Presentation metadata lives under `x-homarr`; dynamic selects use `optionsSource.requestId`, optional `itemsPath` for wrapped arrays, `valuePath`, and `labelPath`. Default options must validate against the schema.\n\nOption and bind names start with a letter and use letters, numbers, `-`, or `_`; camelCase is supported. Every JSX `bind` value is a literal temporary input name.\n\nDo not model credentials as options or static defaults. Credential-like option names and values are rejected; source authentication is configured separately.\n\nDo not add `stateSchema`, `defaultState`, scripts, imports, or component declarations to the manifest. Temporary interaction values come only from JSX `bind` controls and are exposed through `inputs`. Derived values declared with safe `const` blocks exist only while evaluating the template.\n\nThis reference is sufficient for offline authoring against the matching release. When connected, retrieve the live Custom Widget schema; it supersedes this static copy if the installed Homarr version differs.\n"
},
{
"path": "references/widget-schema.json",
"content": "{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"type\": \"object\",\n \"properties\": {\n \"$schema\": {\n \"type\": \"string\",\n \"const\": \"homarr-custom-widget-v2\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 128\n },\n \"description\": {\n \"type\": \"string\",\n \"maxLength\": 512\n },\n \"iconUrl\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n },\n \"sources\": {\n \"minItems\": 1,\n \"maxItems\": 8,\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 64,\n \"pattern\": \"^[a-z][a-z0-9_-]*$\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 128\n },\n \"baseUrl\": {\n \"type\": \"string\",\n \"maxLength\": 2048,\n \"format\": \"uri\"\n },\n \"networkScope\": {\n \"type\": \"string\",\n \"enum\": [\n \"public\",\n \"private\",\n \"loopback\"\n ]\n },\n \"auth\": {\n \"oneOf\": [\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"none\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"bearer\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"basic\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"apiKeyHeader\"\n },\n \"headerName\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256,\n \"pattern\": \"^[!#$%&'*+\\\\-.^_`|~0-9A-Za-z]+$\"\n }\n },\n \"required\": [\n \"type\",\n \"headerName\"\n ],\n \"additionalProperties\": false\n },\n {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"const\": \"apiKeyQuery\"\n },\n \"parameterName\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256\n }\n },\n \"required\": [\n \"type\",\n \"parameterName\"\n ],\n \"additionalProperties\": false\n }\n ]\n }\n },\n \"required\": [\n \"id\",\n \"name\",\n \"baseUrl\",\n \"networkScope\",\n \"auth\"\n ],\n \"additionalProperties\": false\n }\n },\n \"requests\": {\n \"maxItems\": 64,\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 64,\n \"pattern\": \"^[a-z][a-z0-9_-]*$\"\n },\n \"sourceId\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 64,\n \"pattern\": \"^[a-z][a-z0-9_-]*$\"\n },\n \"kind\": {\n \"type\": \"string\",\n \"enum\": [\n \"query\",\n \"action\"\n ]\n },\n \"method\": {\n \"type\": \"string\",\n \"enum\": [\n \"GET\",\n \"POST\",\n \"PUT\",\n Line truncated
},
{
"path": "references/runtime.md",
"content": "# JSX runtime\n\nTemplates read four roots: `data.<requestId>`, `status.<requestId>`, `options`, and `inputs`.\n\nUse Mantine Core, Dates, Charts, safe Tabler icons, and Homarr runtime components. Safe installed Mantine exports are discovered automatically. Ordinary serializable props and Mantine style props pass through; `style` and `styles` are scoped and sanitized.\n\nRender icons as `<TablerIcon name=\"server\" size={18} />`. When connected, retrieve `homarr://custom-widgets/components/TablerIcon` for the supported icon names.\n\nUse `SubFetch` for a manual query, `ActionButton` or `ToggleSwitch` for an action, and `RefreshButton` to refresh data. A query with `trigger: \"load\"` populates its data automatically and follows the widget refresh interval.\n\nManual requests receive values only from the invoking component:\n\n```jsx\n<SubFetch requestId=\"search\" params={{ query: inputs.search }} />\n<ActionButton requestId=\"restart\" params={{ id: container.Id }}>Restart</ActionButton>\n```\n\nLoop variables and other JSX expressions can flow into a request only through that `params` prop. A load query has no invoking component, so every declared parameter must have an `optionsBinding` entry:\n\n```json\n{\n \"parameters\": { \"endpointId\": \"string\", \"showAll\": \"boolean\" },\n \"optionsBinding\": {\n \"endpointId\": { \"$option\": \"endpointId\" },\n \"showAll\": false\n }\n}\n```\n\nDo not rely on parameter and option names matching. For an invalid-placeholder or unresolved-parameter error on a load query, check missing `optionsBinding` entries before changing placeholder syntax.\n\nBind local controls declaratively:\n\n```jsx\n<TextInput bind=\"search\" label=\"Search\" />\n<DatePicker bind=\"selectedDate\" />\n<Select bind=\"selectedEntity\" data={options.entities} />\n```\n\nBound inputs exist only in memory while the widget is mounted and reset on reload. They are available as `inputs.<bindName>` and are never saved to local storage. Put durable user configuration in options. Do not author raw component callback props.\n\nBinding types follow the component mode. `Accordion multiple`, `Chip.Group multiple`, `TreeSelect mode=\"multiple\"|\"checkbox\"`, and date pickers with `type=\"multiple\"|\"range\"` expose `string[]`. `DateTimePicker` and `InlineDateTimePicker` support `type=\"range\"`, but not `multiple`. Components that do not advertise a temporary bind cannot use `bind`.\n\n## Immutable local bindings\n\nCollection callbacks may use a tightly constrained block body when a value would otherwise be recomputed throughout the returned JSX:\n\n```jsx\n{data.pokemon.map((pokemon) => {\n const segments = pokemon.url.split(\"/\").filter((part) => part);\n const dexId = segments.at(-1);\n const favorite = inputs.favorites.includes(pokemon.name);\n\n return (\n <Card key={dexId}>\n <Text>#{dexId}</Text>\n <Text>{pokemon.name}</Text>\n {favorite && <Badge>Favorite</Badge>}\n </Card>\n );\n})}\n```\n\nA page-level derived value may use a directly invoked, zero-argument inline arrow:\n\n```jsx\n{(() => {\n const visiblePokemon = data.pokemon.filter(\n (pokemon) => !inputs.favoritesOnly || inputs.favorites.includes(pokemon.name),\n );\n\n return <Stack>{visiblePokemon.map((pokemon) => <Text>{pokemon.name}</Text>)}</Stack>;\n})()}\n```\n\nA safe block contains one or more `const` declarations followed by exactly one final `return`. Each declaration uses one simple identifier and a required initializer made from existing safe expressions. Earlier local bindings are available to later initializers and to the return expression.\n\nThe following remain invalid:\n\n- `let`, `var`, assignment, update expressions, or destructuring.\n- Function or class declarations, and function values stored in `const`.\n- Loops, `if`, `switch`, `try`, `catch`, `throw`, labels, or `new`.\n- Async functions, generators, `await`, or `yield`.\n- Early or multiple returns.\n- Duplicate local names or shadowing `data`, `status`, `options`, or `inputs`.\n- Invoking a function obtained from API data or a property. Only a directly invoked zero-argument inline arrow is an IIFE.\n\nLocal evaluation shares the parent widget's depth, operation, collection, string, and rendered-node budgets. Blocks cannot reset or evade those limits.\n\nBlock diagnostics include `INVALID_LOCAL_DECLARATION`, `LOCAL_BINDING_REQUIRES_INITIALIZER`, `DUPLICATE_LOCAL_BINDING`, `RESERVED_LOCAL_BINDING`, `UNSUPPORTED_BLOCK_STATEMENT`, `BLOCK_REQUIRES_FINAL_RETURN`, and `CALLBACK_VALUE_NOT_ALLOWED`.\n\n## Arbitrary-depth trees\n\nUse Homarr's trusted `RecursiveList` special form instead of authored recursive functions or Mantine callback props:\n\n```jsx\n<RecursiveList\n data={data.evolution.chain}\n childrenPath=\"evolves_to\"\n keyPath=\"species.name\"\n maxDepth={16}\n defaultExpandedDepth={4}\n showLines\n>\n {(node, meta) => {\n const segments = node.species.url.split(\"/\").filter((part) Line truncated
"content": "# JSX runtime\n\nTemplates read four roots: `data.<requestId>`, `status.<requestId>`, `options`, and `inputs`.\n\nEach request status is an object:\n\n```ts\nstatus.<requestId> = {\n loading: boolean;\n ok?: boolean;\n status?: number;\n statusText?: string;\n error?: string;\n};\n```\n\nUse `status.list?.loading` for loading, `status.list?.ok === false` for failure, and `status.list?.ok === true` for success. Do not compare `status.list` with the strings `\"loading\"`, `\"success\"`, or `\"error\"`; those comparisons are always false and are rejected by validation.\n\nUse Mantine Core, Dates, Charts, safe Tabler icons, and Homarr runtime components. Safe installed Mantine exports are discovered automatically. Ordinary serializable props and Mantine style props pass through; `style` and `styles` are scoped and sanitized.\n\nRender icons as `<TablerIcon name=\"server\" size={18} />`. When connected, retrieve `homarr://custom-widgets/components/TablerIcon` for the supported icon names.\n\nUse `SubFetch` for a manual query, `ActionButton` or `ToggleSwitch` for an action, and `RefreshButton` to refresh data. A query with `trigger: \"load\"` populates its data automatically and follows the widget refresh interval.\n\nManual requests receive values only from the invoking component:\n\n```jsx\n<SubFetch requestId=\"search\" params={{ query: inputs.search }} />\n<ActionButton requestId=\"restart\" params={{ id: container.Id }}>Restart</ActionButton>\n```\n\nLoop variables and other JSX expressions can flow into a request only through that `params` prop. A load query has no invoking component, so every declared parameter must have an `optionsBinding` entry:\n\n```json\n{\n \"parameters\": { \"endpointId\": \"string\", \"showAll\": \"boolean\" },\n \"optionsBinding\": {\n \"endpointId\": { \"$option\": \"endpointId\" },\n \"showAll\": false\n }\n}\n```\n\nDo not rely on parameter and option names matching. For an invalid-placeholder or unresolved-parameter error on a load query, check missing `optionsBinding` entries before changing placeholder syntax.\n\nBind local controls declaratively:\n\n```jsx\n<TextInput bind=\"search\" label=\"Search\" />\n<DatePicker bind=\"selectedDate\" />\n<Select bind=\"selectedEntity\" data={options.entities} />\n```\n\nBound inputs exist only in memory while the widget is mounted and reset on reload. They are available as `inputs.<bindName>` and are never saved to local storage. Put durable user configuration in options. Do not author raw component callback props.\n\nBinding types follow the component mode. `Accordion multiple`, `Chip.Group multiple`, `TreeSelect mode=\"multiple\"|\"checkbox\"`, and date pickers with `type=\"multiple\"|\"range\"` expose `string[]`. `DateTimePicker` and `InlineDateTimePicker` support `type=\"range\"`, but not `multiple`. Components that do not advertise a temporary bind cannot use `bind`.\n\n## Immutable local bindings\n\nCollection callbacks may use a tightly constrained block body when a value would otherwise be recomputed throughout the returned JSX:\n\n```jsx\n{data.pokemon.map((pokemon) => {\n const segments = pokemon.url.split(\"/\").filter((part) => part);\n const dexId = segments.at(-1);\n const favorite = inputs.favorites.includes(pokemon.name);\n\n return (\n <Card key={dexId}>\n <Text>#{dexId}</Text>\n <Text>{pokemon.name}</Text>\n {favorite && <Badge>Favorite</Badge>}\n </Card>\n );\n})}\n```\n\nA page-level derived value may use a directly invoked, zero-argument inline arrow:\n\n```jsx\n{(() => {\n const visiblePokemon = data.pokemon.filter(\n (pokemon) => !inputs.favoritesOnly || inputs.favorites.includes(pokemon.name),\n );\n\n return <Stack>{visiblePokemon.map((pokemon) => <Text>{pokemon.name}</Text>)}</Stack>;\n})()}\n```\n\nA safe block contains one or more `const` declarations followed by exactly one final `return`. Each declaration uses one simple identifier and a required initializer made from existing safe expressions. Earlier local bindings are available to later initializers and to the return expression.\n\nThe following remain invalid:\n\n- `let`, `var`, assignment, update expressions, or destructuring.\n- Function or class declarations, and function values stored in `const`.\n- Loops, `if`, `switch`, `try`, `catch`, `throw`, labels, or `new`.\n- Async functions, generators, `await`, or `yield`.\n- Early or multiple returns.\n- Duplicate local names or shadowing `data`, `status`, `options`, or `inputs`.\n- Invoking a function obtained from API data or a property. Only a directly invoked zero-argument inline arrow is an IIFE.\n\nLocal evaluation shares the parent widget's depth, operation, collection, string, and rendered-node budgets. Blocks cannot reset or evade those limits.\n\nBlock diagnostics include `INVALID_LOCAL_DECLARATION`, `LOCAL_BINDING_REQUIRES_INITIALIZER`, `DUPLICATE_LOCAL_BINDING`, `RESERVED_LOCAL_BINDING`, `UNSUPPORTED_BLOCK_STATEMENT`, `BLOCK_REQULine truncated
},
{
"path": "references/security.md",
@@ -19,23 +23,31 @@
},
{
"path": "references/components.md",
"content": "# Component catalog\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nThis is the complete offline Custom JSX component contract for this Homarr release. When connected to Homarr, prefer the live catalog because the installed release may differ. The catalog is descriptive, not a prop allowlist: ordinary serializable props pass through unless the capability boundary explicitly blocks them.\n\n## Package references\n\n- [Mantine Core](mantine-core.md) — 265 enabled, 133 denied\n- [Mantine Dates](mantine-dates.md) — 29 enabled, 3 denied\n- [Mantine Charts](mantine-charts.md) — 18 enabled, 1 denied\n- [Homarr components](homarr-components.md) — 13 enabled, 0 denied\n\n## Authoring boundary\n\n- Use the exact component names below. Compound names such as `Tabs.List`, `Card.Section`, and `Radio.Group` are distinct catalog entries.\n- The effective prop API is the shared prop table plus the component-specific table in the package reference. A component-specific record overrides the shared record with the same name.\n- Use `bind=\"name\"` only when a component record declares bind metadata. Read the temporary in-memory value from `inputs.name`; it is never persisted.\n- Ordinary authored callbacks remain blocked. Restricted collection callbacks, directly invoked zero-argument derived-value IIFEs, and `RecursiveList`'s child template may use the immutable local `const` grammar in [JSX runtime](runtime.md#immutable-local-bindings).\n- Use [`RecursiveList`](homarr-components.md#component-recursivelist) for custom arbitrary-depth trees. Do not author recursion or pass a renderer callback to Mantine Tree.\n- Unknown ordinary Mantine props are advisory and are not silently discarded. Every capability listed in the blocked table is rejected.\n\n## Complete enabled inventory\n\n### Mantine Core\n\n[`Accordion`](mantine-core.md#component-accordion), [`Accordion.Chevron`](mantine-core.md#component-accordion-2e-chevron), [`Accordion.Control`](mantine-core.md#component-accordion-2e-control), [`Accordion.Item`](mantine-core.md#component-accordion-2e-item), [`Accordion.Panel`](mantine-core.md#component-accordion-2e-panel), [`AccordionChevron`](mantine-core.md#component-accordionchevron), [`AccordionControl`](mantine-core.md#component-accordioncontrol), [`AccordionItem`](mantine-core.md#component-accordionitem), [`AccordionPanel`](mantine-core.md#component-accordionpanel), [`ActionIcon`](mantine-core.md#component-actionicon), [`ActionIcon.Group`](mantine-core.md#component-actionicon-2e-group), [`ActionIcon.GroupSection`](mantine-core.md#component-actionicon-2e-groupsection), [`ActionIconGroup`](mantine-core.md#component-actionicongroup), [`ActionIconGroupSection`](mantine-core.md#component-actionicongroupsection), [`Alert`](mantine-core.md#component-alert), [`AlphaSlider`](mantine-core.md#component-alphaslider), [`Anchor`](mantine-core.md#component-anchor), [`AngleSlider`](mantine-core.md#component-angleslider), [`AspectRatio`](mantine-core.md#component-aspectratio), [`Autocomplete`](mantine-core.md#component-autocomplete), [`Avatar`](mantine-core.md#component-avatar), [`Avatar.Group`](mantine-core.md#component-avatar-2e-group), [`AvatarGroup`](mantine-core.md#component-avatargroup), [`BackgroundImage`](mantine-core.md#component-backgroundimage), [`Badge`](mantine-core.md#component-badge), [`Blockquote`](mantine-core.md#component-blockquote), [`Box`](mantine-core.md#component-box), [`Breadcrumbs`](mantine-core.md#component-breadcrumbs), [`Burger`](mantine-core.md#component-burger), [`Button`](mantine-core.md#component-button), [`Button.Group`](mantine-core.md#component-button-2e-group), [`Button.GroupSection`](mantine-core.md#component-button-2e-groupsection), [`ButtonGroup`](mantine-core.md#component-buttongroup), [`ButtonGroupSection`](mantine-core.md#component-buttongroupsection), [`Card`](mantine-core.md#component-card), [`Card.Section`](mantine-core.md#component-card-2e-section), [`CardSection`](mantine-core.md#component-cardsection), [`Center`](mantine-core.md#component-center), [`CheckIcon`](mantine-core.md#component-checkicon), [`Checkbox`](mantine-core.md#component-checkbox), [`Checkbox.Card`](mantine-core.md#component-checkbox-2e-card), [`Checkbox.Group`](mantine-core.md#component-checkbox-2e-group), [`Checkbox.Indicator`](mantine-core.md#component-checkbox-2e-indicator), [`CheckboxCard`](mantine-core.md#component-checkboxcard), [`CheckboxGroup`](mantine-core.md#component-checkboxgroup), [`CheckboxIndicator`](mantine-core.md#component-checkboxindicator), [`Chip`](mantine-core.md#component-chip), [`Chip.Group`](mantine-core.md#component-chip-2e-group), [`ChipGroup`](mantine-core.md#component-chipgroup), [`CloseButton`](mantine-core.md#component-closebutton), [`CloseIcon`](mantine-core.md#component-closeicon), [`Code`](mantine-core.md#component-code), [`Collapse`](mantine-core.md#component-collapse), [`CoLine truncated
"content": "# Component catalog\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nThis is the complete Custom JSX component boundary for this Homarr release. The machine-readable `component-catalog.json` contains exact generated component, prop, binding, and safety metadata; these Markdown pages provide the human-readable inventory and upstream Mantine indexes. Ordinary serializable props pass through unless the capability boundary explicitly blocks them.\n\n## Package references\n\n- [Mantine Core](mantine-core.md) — 265 enabled, 133 denied\n- [Mantine Dates](mantine-dates.md) — 29 enabled, 3 denied\n- [Mantine Charts](mantine-charts.md) — 18 enabled, 1 denied\n- [Homarr components](homarr-components.md) — 13 enabled, 0 denied\n\n## Authoring boundary\n\n- Use the exact component names below. Compound names such as `Tabs.List`, `Card.Section`, and `Radio.Group` are distinct catalog entries.\n- Use the official Mantine LLM links for component props and examples. Homarr's live catalog is authoritative for availability, bindings, and blocked capabilities.\n- Use `bind=\"name\"` only when a component record declares bind metadata. Read the temporary in-memory value from `inputs.name`; it is never persisted.\n- Ordinary authored callbacks remain blocked. Restricted collection callbacks, directly invoked zero-argument derived-value IIFEs, and `RecursiveList`'s child template may use the immutable local `const` grammar in [JSX runtime](runtime.md#immutable-local-bindings).\n- Use [`RecursiveList`](homarr-components.md#component-recursivelist) for custom arbitrary-depth trees. Do not author recursion or pass a renderer callback to Mantine Tree.\n- Unknown ordinary Mantine props are advisory and are not silently discarded. Every capability listed in the blocked table is rejected.\n\n## Complete enabled inventory\n\n### Mantine Core\n\n[`Accordion`](https://mantine.dev/core/accordion/), [`Accordion.Chevron`](https://mantine.dev/core/accordion/), [`Accordion.Control`](https://mantine.dev/core/accordion/), [`Accordion.Item`](https://mantine.dev/core/accordion/), [`Accordion.Panel`](https://mantine.dev/core/accordion/), [`AccordionChevron`](https://mantine.dev/core/accordion-chevron/), [`AccordionControl`](https://mantine.dev/core/accordion-control/), [`AccordionItem`](https://mantine.dev/core/accordion-item/), [`AccordionPanel`](https://mantine.dev/core/accordion-panel/), [`ActionIcon`](https://mantine.dev/core/action-icon/), [`ActionIcon.Group`](https://mantine.dev/core/action-icon/), [`ActionIcon.GroupSection`](https://mantine.dev/core/action-icon/), [`ActionIconGroup`](https://mantine.dev/core/action-icon-group/), [`ActionIconGroupSection`](https://mantine.dev/core/action-icon-group-section/), [`Alert`](https://mantine.dev/core/alert/), [`AlphaSlider`](https://mantine.dev/core/alpha-slider/), [`Anchor`](https://mantine.dev/core/anchor/), [`AngleSlider`](https://mantine.dev/core/angle-slider/), [`AspectRatio`](https://mantine.dev/core/aspect-ratio/), [`Autocomplete`](https://mantine.dev/core/autocomplete/), [`Avatar`](https://mantine.dev/core/avatar/), [`Avatar.Group`](https://mantine.dev/core/avatar/), [`AvatarGroup`](https://mantine.dev/core/avatar-group/), [`BackgroundImage`](https://mantine.dev/core/background-image/), [`Badge`](https://mantine.dev/core/badge/), [`Blockquote`](https://mantine.dev/core/blockquote/), [`Box`](https://mantine.dev/core/box/), [`Breadcrumbs`](https://mantine.dev/core/breadcrumbs/), [`Burger`](https://mantine.dev/core/burger/), [`Button`](https://mantine.dev/core/button/), [`Button.Group`](https://mantine.dev/core/button/), [`Button.GroupSection`](https://mantine.dev/core/button/), [`ButtonGroup`](https://mantine.dev/core/button-group/), [`ButtonGroupSection`](https://mantine.dev/core/button-group-section/), [`Card`](https://mantine.dev/core/card/), [`Card.Section`](https://mantine.dev/core/card/), [`CardSection`](https://mantine.dev/core/card-section/), [`Center`](https://mantine.dev/core/center/), [`CheckIcon`](https://mantine.dev/core/check-icon/), [`Checkbox`](https://mantine.dev/core/checkbox/), [`Checkbox.Card`](https://mantine.dev/core/checkbox/), [`Checkbox.Group`](https://mantine.dev/core/checkbox/), [`Checkbox.Indicator`](https://mantine.dev/core/checkbox/), [`CheckboxCard`](https://mantine.dev/core/checkbox-card/), [`CheckboxGroup`](https://mantine.dev/core/checkbox-group/), [`CheckboxIndicator`](https://mantine.dev/core/checkbox-indicator/), [`Chip`](https://mantine.dev/core/chip/), [`Chip.Group`](https://mantine.dev/core/chip/), [`ChipGroup`](https://mantine.dev/core/chip-group/), [`CloseButton`](https://mantine.dev/core/close-button/), [`CloseIcon`](https://mantine.dev/core/close-icon/), [`Code`](https://mantine.dev/core/code/), [`Collapse`](https://mantine.dev/core/collapse/), [`ColorInput`](https://mantine.dev/core/color-input/), [`ColorPicker`](https://mantine.devLine truncated
},
{
"path": "references/component-catalog.json",
"content": "{\"schemaVersion\":1,\"mantineVersion\":\"9.4.1\",\"customWidgetVersion\":\"2.0.0\",\"types\":[\"\\\"\\\" | \\\"anonymous\\\" | \\\"use-credentials\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"auto\\\" | \\\"fixed\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"none\\\" | \\\"auto\\\" | \\\"all\\\" | \\\"fill\\\" | \\\"stroke\\\" | \\\"painted\\\" | \\\"visible\\\" | \\\"visibleFill\\\" | \\\"visiblePainted\\\" | \\\"visibleStroke\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"none\\\" | \\\"block\\\" | \\\"inline\\\" | \\\"both\\\" | \\\"horizontal\\\" | \\\"vertical\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"none\\\" | \\\"contain\\\" | \\\"cover\\\" | \\\"fill\\\" | \\\"scale-down\\\"\",\"\\\"-moz-initial\\\" | \\\"inherit\\\" | \\\"initial\\\" | \\\"revert\\\" | \\\"revert-layer\\\" | \\\"unset\\\" | \\\"wrap\\\" | \\\"nowrap\\\" | \\\"wrap-reverse\\\"\",\"\\\"12h\\\" | \\\"24h\\\"\",\"\\\"activity\\\" | \\\"display-none\\\"\",\"\\\"all\\\" | \\\"parent\\\" | \\\"child\\\"\",\"\\\"all\\\" | \\\"segment\\\"\",\"\\\"always\\\" | \\\"hover\\\" | \\\"not-hover\\\" | \\\"never\\\"\",\"\\\"area\\\" | \\\"radial\\\" | \\\"scatter\\\"\",\"\\\"auto\\\" | \\\"scroll\\\" | \\\"always\\\" | \\\"hover\\\" | \\\"never\\\"\",\"\\\"auto-fit\\\" | \\\"auto-fill\\\"\",\"\\\"block\\\" | \\\"grid\\\"\",\"\\\"both\\\" | \\\"rightSection\\\" | \\\"clear\\\"\",\"\\\"bottom\\\" | \\\"top\\\"\",\"\\\"bottom\\\" | \\\"top\\\" | \\\"baseline\\\" | \\\"middle\\\"\",\"\\\"bottom\\\" | \\\"top\\\" | \\\"middle\\\"\",\"\\\"bottom-end\\\" | \\\"bottom-start\\\" | \\\"top-end\\\" | \\\"top-start\\\" | \\\"bottom-center\\\" | \\\"top-center\\\" | \\\"middle-center\\\" | \\\"middle-end\\\" | \\\"middle-start\\\"\",\"\\\"button\\\" | \\\"submit\\\" | \\\"reset\\\"\",\"\\\"center\\\" | \\\"bottom\\\"\",\"\\\"center\\\" | \\\"left\\\" | \\\"right\\\"\",\"\\\"center\\\" | \\\"left\\\" | \\\"right\\\" | \\\"justify\\\" | \\\"char\\\"\",\"\\\"center\\\" | \\\"side\\\" | \\\"merge\\\"\",\"\\\"checkbox\\\" | \\\"radio\\\"\",\"\\\"dashed\\\" | \\\"dotted\\\" | \\\"solid\\\"\",\"\\\"default\\\" | \\\"gradient\\\"\",\"\\\"default\\\" | \\\"responsive\\\"\",\"\\\"default\\\" | \\\"stacked\\\" | \\\"percent\\\" | \\\"split\\\"\",\"\\\"default\\\" | \\\"stacked\\\" | \\\"percent\\\" | \\\"waterfall\\\"\",\"\\\"div\\\" | \\\"label\\\"\",\"\\\"end\\\" | \\\"start\\\"\",\"\\\"filled\\\" | \\\"light\\\"\",\"\\\"fixed\\\" | \\\"absolute\\\"\",\"\\\"hex\\\" | \\\"hexa\\\" | \\\"rgba\\\" | \\\"rgb\\\" | \\\"hsl\\\" | \\\"hsla\\\"\",\"\\\"horizontal\\\" | \\\"vertical\\\"\",\"\\\"hover\\\" | \\\"click\\\" | \\\"click-hover\\\"\",\"\\\"inherit\\\" | \\\"auto\\\" | \\\"baseline\\\" | \\\"before-edge\\\" | \\\"text-before-edge\\\" | \\\"middle\\\" | \\\"central\\\" | \\\"after-edge\\\" | \\\"text-after-edge\\\" | \\\"ideographic\\\" | \\\"alphabetic\\\" | \\\"hanging\\\" | \\\"mathematical\\\"\",\"\\\"inherit\\\" | \\\"auto\\\" | \\\"sRGB\\\" | \\\"linearRGB\\\"\",\"\\\"inherit\\\" | \\\"auto\\\" | \\\"text-before-edge\\\" | \\\"middle\\\" | \\\"central\\\" | \\\"text-after-edge\\\" | \\\"ideographic\\\" | \\\"alphabetic\\\" | \\\"hanging\\\" | \\\"mathematical\\\" | \\\"use-script\\\" | \\\"no-change\\\" | \\\"reset-size\\\"\",\"\\\"inherit\\\" | \\\"end\\\" | \\\"start\\\" | \\\"middle\\\"\",\"\\\"inherit\\\" | \\\"nonzero\\\" | \\\"evenodd\\\"\",\"\\\"inherit\\\" | \\\"round\\\" | \\\"butt\\\" | \\\"square\\\"\",\"\\\"inherit\\\" | \\\"round\\\" | \\\"miter\\\" | \\\"bevel\\\"\",\"\\\"initial\\\" | \\\"medial\\\" | \\\"terminal\\\" | \\\"isolated\\\"\",\"\\\"inside\\\" | \\\"outside\\\"\",\"\\\"left\\\" | \\\"right\\\"\",\"\\\"left\\\" | \\\"right\\\" | \\\"bottom\\\" | \\\"top\\\" | \\\"left-end\\\" | \\\"left-start\\\" | \\\"right-end\\\" | \\\"right-start\\\" | \\\"bottom-end\\\" | \\\"bottom-start\\\" | \\\"top-end\\\" | \\\"top-start\\\"\",\"\\\"left\\\" | \\\"right\\\" | \\\"inside\\\"\",\"\\\"link\\\" | \\\"none\\\" | \\\"copy\\\" | \\\"execute\\\" | \\\"move\\\" | \\\"popup\\\"\",\"\\\"media\\\" | \\\"container\\\"\",\"\\\"month\\\" | \\\"year\\\" | \\\"decade\\\"\",\"\\\"native\\\" | \\\"scrollarea\\\"\",\"\\\"none\\\" | \\\"all\\\" | \\\"rows\\\" | \\\"groups\\\" | \\\"columns\\\"\",\"\\\"none\\\" | \\\"all\\\" | \\\"with-indicators\\\"\",\"\\\"none\\\" | \\\"ascending\\\" | \\\"descending\\\" | \\\"other\\\"\",\"\\\"none\\\" | \\\"inline\\\" | \\\"list\\\" | \\\"both\\\"\",\"\\\"none\\\" | \\\"strict\\\" | \\\"blur\\\"\",\"\\\"none\\\" | \\\"sum\\\"\",\"\\\"none\\\" | \\\"thousand\\\" | \\\"lakh\\\" | \\\"wan\\\"\",\"\\\"none\\\" | \\\"x\\\" | \\\"y\\\" | \\\"xy\\\"\",\"\\\"number\\\" | RegExp | \\\"alphanumeriLine truncated
},
{
"path": "references/examples.json",
"content": "[\n {\n \"id\": \"service-status\",\n \"title\": \"Service status\",\n \"description\": \"A compact status widget backed by one load query.\",\n \"widget\": {\n \"$schema\": \"homarr-custom-widget-v2\",\n \"name\": \"Service status\",\n \"sources\": [\n {\n \"id\": \"default\",\n \"name\": \"Service API\",\n \"baseUrl\": \"https://example.com\",\n \"networkScope\": \"public\",\n \"auth\": {\n \"type\": \"none\"\n }\n }\n ],\n \"requests\": [\n {\n \"id\": \"status\",\n \"sourceId\": \"default\",\n \"kind\": \"query\",\n \"method\": \"GET\",\n \"pathTemplate\": \"/api/status\",\n \"parameters\": {},\n \"auth\": \"inherit\",\n \"minimumBoardPermission\": \"view\",\n \"trigger\": \"load\"\n }\n ],\n \"optionsSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"defaultOptions\": {},\n \"template\": \"<Stack gap=\\\"xs\\\" p=\\\"sm\\\">\\n <Group justify=\\\"space-between\\\">\\n <Text fw={600}>{data.status.name ?? \\\"Service\\\"}</Text>\\n <Badge color={data.status.online ? \\\"green\\\" : \\\"red\\\"}>{data.status.online ? \\\"Online\\\" : \\\"Offline\\\"}</Badge>\\n </Group>\\n <Text size=\\\"sm\\\" c=\\\"dimmed\\\">{data.status.message ?? \\\"No additional details\\\"}</Text>\\n </Stack>\"\n }\n },\n {\n \"id\": \"pokemon-evolution-tree\",\n \"title\": \"Pokémon evolution tree\",\n \"description\": \"A trusted arbitrary-depth tree with one immutable derived-value block per node.\",\n \"widget\": {\n \"$schema\": \"homarr-custom-widget-v2\",\n \"name\": \"Pokémon evolution tree\",\n \"sources\": [\n {\n \"id\": \"default\",\n \"name\": \"PokeAPI\",\n \"baseUrl\": \"https://pokeapi.co\",\n \"networkScope\": \"public\",\n \"auth\": {\n \"type\": \"none\"\n }\n }\n ],\n \"requests\": [\n {\n \"id\": \"evolution\",\n \"sourceId\": \"default\",\n \"kind\": \"query\",\n \"method\": \"GET\",\n \"pathTemplate\": \"/api/v2/evolution-chain/1\",\n \"parameters\": {},\n \"auth\": \"inherit\",\n \"minimumBoardPermission\": \"view\",\n \"trigger\": \"load\"\n }\n ],\n \"optionsSchema\": {\n \"type\": \"object\",\n \"properties\": {},\n \"additionalProperties\": false\n },\n \"defaultOptions\": {},\n \"template\": \"<Stack gap=\\\"sm\\\" p=\\\"sm\\\">\\n <Title order={3}>Evolution chain</Title>\\n {status.evolution?.loading ? <Skeleton height={160} radius=\\\"md\\\" /> : status.evolution?.error ? <Alert color=\\\"red\\\">{status.evolution.error}</Alert> : data.evolution?.chain ?\\n <RecursiveList data={data.evolution.chain} childrenPath=\\\"evolves_to\\\" keyPath=\\\"species.name\\\" defaultExpandedDepth={8} showLines>\\n {(node, meta) => {\\n const segments = node.species.url.split(\\\"/\\\").filter((part) => part);\\n const dexId = segments.at(-1);\\n return <Group gap=\\\"xs\\\"><Badge variant=\\\"light\\\">#{dexId}</Badge><Text tt=\\\"capitalize\\\" fw={600}>{node.species.name}</Text>{meta.hasChildren && <Text size=\\\"xs\\\" c=\\\"dimmed\\\">{meta.childCount} next</Text>}</Group>;\\n }}\\n </RecursiveList> : <Text c=\\\"dimmed\\\">No evolution chain returned.</Text>}\\n</Stack>\"\n }\n }\n]\n"
},
{
"path": "references/mantine-core.md",
"content": "# Mantine Core\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nPackage: `@mantine/core`. Effective props combine the [shared prop API](components.md#shared-prop-api) with each component's specific props below. Component-specific records override shared records with the same name.\n\n## Package guidance\n\nUse declarative props and `bind` adapters instead of event callbacks. Homarr scopes supported overlays to the widget root. Use Homarr's `RecursiveList` when a tree needs a custom arbitrary-depth node template.\n\n## Enabled inventory\n\n<code>Accordion</code>, <code>Accordion.Chevron</code>, <code>Accordion.Control</code>, <code>Accordion.Item</code>, <code>Accordion.Panel</code>, <code>AccordionChevron</code>, <code>AccordionControl</code>, <code>AccordionItem</code>, <code>AccordionPanel</code>, <code>ActionIcon</code>, <code>ActionIcon.Group</code>, <code>ActionIcon.GroupSection</code>, <code>ActionIconGroup</code>, <code>ActionIconGroupSection</code>, <code>Alert</code>, <code>AlphaSlider</code>, <code>Anchor</code>, <code>AngleSlider</code>, <code>AspectRatio</code>, <code>Autocomplete</code>, <code>Avatar</code>, <code>Avatar.Group</code>, <code>AvatarGroup</code>, <code>BackgroundImage</code>, <code>Badge</code>, <code>Blockquote</code>, <code>Box</code>, <code>Breadcrumbs</code>, <code>Burger</code>, <code>Button</code>, <code>Button.Group</code>, <code>Button.GroupSection</code>, <code>ButtonGroup</code>, <code>ButtonGroupSection</code>, <code>Card</code>, <code>Card.Section</code>, <code>CardSection</code>, <code>Center</code>, <code>CheckIcon</code>, <code>Checkbox</code>, <code>Checkbox.Card</code>, <code>Checkbox.Group</code>, <code>Checkbox.Indicator</code>, <code>CheckboxCard</code>, <code>CheckboxGroup</code>, <code>CheckboxIndicator</code>, <code>Chip</code>, <code>Chip.Group</code>, <code>ChipGroup</code>, <code>CloseButton</code>, <code>CloseIcon</code>, <code>Code</code>, <code>Collapse</code>, <code>ColorInput</code>, <code>ColorPicker</code>, <code>ColorSwatch</code>, <code>Container</code>, <code>CopyButton</code>, <code>DataList</code>, <code>DataList.Item</code>, <code>DataList.ItemLabel</code>, <code>DataList.ItemValue</code>, <code>DataListItem</code>, <code>DataListItemLabel</code>, <code>DataListItemValue</code>, <code>Divider</code>, <code>EmptyState</code>, <code>EmptyState.Actions</code>, <code>EmptyState.Description</code>, <code>EmptyState.Indicator</code>, <code>EmptyState.Title</code>, <code>EmptyStateActions</code>, <code>EmptyStateDescription</code>, <code>EmptyStateIndicator</code>, <code>EmptyStateTitle</code>, <code>Fieldset</code>, <code>FlatTreeNode</code>, <code>Flex</code>, <code>FloatingArrow</code>, <code>FloatingIndicator</code>, <code>Grid</code>, <code>Grid.Col</code>, <code>GridCol</code>, <code>Group</code>, <code>Highlight</code>, <code>HoverCard</code>, <code>HoverCard.Dropdown</code>, <code>HoverCard.Group</code>, <code>HoverCard.Target</code>, <code>HoverCardDropdown</code>, <code>HoverCardGroup</code>, <code>HoverCardTarget</code>, <code>HueSlider</code>, <code>Image</code>, <code>Indicator</code>, <code>JsonInput</code>, <code>Kbd</code>, <code>List</code>, <code>List.Item</code>, <code>ListItem</code>, <code>Loader</code>, <code>LoadingOverlay</code>, <code>Mark</code>, <code>Marquee</code>, <code>MaskInput</code>, <code>Menu</code>, <code>Menu.CheckboxGroup</code>, <code>Menu.CheckboxItem</code>, <code>Menu.ContextMenu</code>, <code>Menu.Divider</code>, <code>Menu.Dropdown</code>, <code>Menu.Item</code>, <code>Menu.Label</code>, <code>Menu.RadioGroup</code>, <code>Menu.RadioItem</code>, <code>Menu.Search</code>, <code>Menu.Sub</code>, <code>Menu.Target</code>, <code>MenuCheckboxGroup</code>, <code>MenuCheckboxItem</code>, <code>MenuContextMenu</code>, <code>MenuDivider</code>, <code>MenuDropdown</code>, <code>MenuItem</code>, <code>MenuLabel</code>, <code>MenuRadioGroup</code>, <code>MenuRadioItem</code>, <code>MenuSearch</code>, <code>MenuSub</code>, <code>MenuSub.Dropdown</code>, <code>MenuSub.Item</code>, <code>MenuSub.Target</code>, <code>MenuSubDropdown</code>, <code>MenuSubItem</code>, <code>MenuSubTarget</code>, <code>MenuTarget</code>, <code>MultiSelect</code>, <code>NativeScrollArea</code>, <code>NativeSelect</code>, <code>NavLink</code>, <code>Notification</code>, <code>NumberFormatter</code>, <code>NumberInput</code>, <code>OverflowList</code>, <code>Overlay</code>, <code>Pagination</code>, <code>Pagination.Control</code>, <code>Pagination.Dots</code>, <code>Pagination.First</code>, <code>Pagination.Items</code>, <code>Pagination.Label</code>, <code>Pagination.Last</code>, <code>Pagination.Next</code>, <code>Pagination.Previous</code>, <code>Pagination.Root</code>, <code>PaginationControl</code>, <code>PaginationDots</code>, <code>PaginationFirst</code>, <code>PaginationItems</code>, <code>PaginationLabel</code>, <code>PaginaLine truncated
"content": "# Mantine UI - LLM Documentation\n\nThis index lists Mantine documentation pages formatted for LLMs.\nEach link points to a standalone Markdown file under the /llms path.\n\nFor a single consolidated file with all content, use:\n- https://mantine.dev/llms-full.txt\n\n## FAQ\n\n- [Are Mantine components accessible?](https://mantine.dev/llms/q-are-mantine-components-accessible.md): Learn about Mantine components accessibility features\n- [Browser zooms in when input is focused. What should I do?](https://mantine.dev/llms/q-browser-zooms-on-focus.md): Use meta tag to disable browser scaling or increase input size\n- [Can I have color schemes other than light and dark?](https://mantine.dev/llms/q-light-dark-is-not-enough.md): Learn about the difference between color scheme and theme\n- [Can I have different primary color for light and dark color schemes?](https://mantine.dev/llms/q-primary-virtual-color.md): Learn how to use virtual color with primary color in theme object\n- [Can I remove MultiSelect placeholder when the component has selected values?](https://mantine.dev/llms/q-multiselect-value-placeholder.md): Learn why MultiSelect placeholder is not removed when values are selected and how to remove it with CSS\n- [Can I use an array of strings as a list in use-form?](https://mantine.dev/llms/q-list-of-strings-in-use-form.md): Learn about use-form lists limitations\n- [Can I use Mantine components as server components?](https://mantine.dev/llms/q-server-components.md): Learn about use client directive and server components usage\n- [Can I use Mantine with Astro?](https://mantine.dev/llms/q-can-i-use-mantine-with-astro.md): No, Astro does not support React context\n- [Can I use Mantine with Create React App (CRA)?](https://mantine.dev/llms/q-can-i-use-mantine-with-cra.md): Learn how to use Mantine without postcss-preset-mantine or how to eject CRA and customize webpack.config.js and use postcss-preset-mantine\n- [Can I use Mantine with Emotion/styled-components/tailwindcss?](https://mantine.dev/llms/q-third-party-styles.md): Learn about limitations of third-party styles\n- [Can I use Mantine with Vue/Svelte/Angular/etc.?](https://mantine.dev/llms/q-vue-svelte-angular.md): No, Mantine is a React library and does not support other frameworks/libraries\n- [Can I use nested inline styles with Mantine components?](https://mantine.dev/llms/q-nested-inline-styles.md): Nested styles are supported only in CSS files\n- [Can I use PostCSS function in inline styles?](https://mantine.dev/llms/q-postcss-fns-inline.md): Learn where PostCSS functions can be used in Mantine\n- [Can I use private CSS variables to style components?](https://mantine.dev/llms/q-private-css-variables.md): No, it is not safe and will not work with future versions of Mantine.\n- [Can I use SegmentedControl with empty value?](https://mantine.dev/llms/q-segmented-control-no-value.md): SegmentedControl cannot be used without a value\n- [How can I add dynamic CSS styles?](https://mantine.dev/llms/q-dynamic-css-styles.md): Use data attributes, CSS variables or inline styles\n- [How can I add fuzzy search to Select component?](https://mantine.dev/llms/q-select-fuzzy.md): Learn how to integrate third-party fuzzy search libraries with Mantine Select component\n- [How can I add hover styles to an element?](https://mantine.dev/llms/q-how-to-add-hover-styles.md): Learn how to add hover classes to an element with CSS modules, &:hover or @mixin hover\n- [How can I apply styles to all Mantine components?](https://mantine.dev/llms/q-apply-styles-to-all.md): Learn how to use attribute selector to apply styles to all Mantine components\n- [How can I change body background color?](https://mantine.dev/llms/q-body-background.md): Use CSS to change body background color\n- [How can I change component color prop value depending on the color scheme?](https://mantine.dev/llms/q-color-scheme-color.md): Learn how to use CSS variables resolver to change color value depending on the color scheme\n- [How can I change input focus styles?](https://mantine.dev/llms/q-input-focus-styles.md): Learn how to use Styles API with Mantine inputs\n- [How can I change Tabs border color?](https://mantine.dev/llms/q-tabs-border-color.md): Learn how to use Styles API with Tabs component\n- [How can I contribute to the library?](https://mantine.dev/llms/q-how-can-i-contribute.md): There are multiple ways to contribute even without writing code\n- [How can I disable all inputs/input groups inside a form?](https://mantine.dev/llms/q-disable-all-inputs-in-form.md): Learn how to disable all inputs/input groups inside a form with the unstyled Fieldset component\n- [How can I display different elements in light and dark color schemes?](https://mantine.dev/llms/q-light-dark-elements.md): Learn how to hide/show elements based on color scheme\n- [How can I focus the first input with error with use-form?](https://mantine.dev/llms/q-focus-first-input-with-error.md): Learn how to handlLine truncated
},
{
"path": "references/mantine-dates.md",
"content": "# Mantine Dates\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nPackage: `@mantine/dates`. Effective props combine the [shared prop API](components.md#shared-prop-api) with each component's specific props below. Component-specific records override shared records with the same name.\n\n## Package guidance\n\nDate bindings are temporary serialized inputs. Persisted locale, time-zone, and date choices belong in widget options. Include a textual date or agenda when a visual date control carries meaning.\n\n## Enabled inventory\n\n<code>Calendar</code>, <code>CalendarHeader</code>, <code>DateInput</code>, <code>DatePicker</code>, <code>DatePickerInput</code>, <code>DateTimePicker</code>, <code>Day</code>, <code>DecadeLevel</code>, <code>DecadeLevelGroup</code>, <code>InlineDateTimePicker</code>, <code>LevelsGroup</code>, <code>MiniCalendar</code>, <code>Month</code>, <code>MonthLevel</code>, <code>MonthLevelGroup</code>, <code>MonthPicker</code>, <code>MonthPickerInput</code>, <code>MonthsList</code>, <code>PickerControl</code>, <code>TimeGrid</code>, <code>TimeInput</code>, <code>TimePicker</code>, <code>TimeValue</code>, <code>WeekdaysRow</code>, <code>YearLevel</code>, <code>YearLevelGroup</code>, <code>YearPicker</code>, <code>YearPickerInput</code>, <code>YearsList</code>\n\n## Denied inventory\n\n<code>DatesProvider</code>, <code>HiddenDatesInput</code>, <code>PickerInputBase</code>\n\n## Component records\n\n<a id=\"component-calendar\"></a>\n### `Calendar`\n\n- Safety: `wrapped`\n- Category: `dates`\n- Documentation: [upstream component API](https://mantine.dev/dates/calendar/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Include a textual date when the visual calendar carries meaning.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>ariaLabels</code> | no | <code>CalendarAriaLabels</code> | — | `aria-label` attributes for controls on different levels |\n| <code>attributes</code> | no | <code>{ month?: Record&lt;string, any&gt;; weekday?: Record&lt;string, any&gt;; weekdaysRow?: Record&lt;string, any&gt;; monthRow?: Record&lt;string, any&gt;; ... 17 more ...; yearsListRow?: Record&lt;...&gt;; }</code> | — | — |\n| <code>columnsToScroll</code> | no | <code>number</code> | — | Number of columns to scroll with next/prev buttons, same as `numberOfColumns` if not set explicitly |\n| <code>date</code> | no | <code>string &#124; Date</code> | — | Displayed date in controlled mode |\n| <code>defaultDate</code> | no | <code>string &#124; Date</code> | — | Initial displayed date in uncontrolled mode |\n| <code>defaultLevel</code> | no | <code>\"month\" &#124; \"year\" &#124; \"decade\"</code> | <code>\"decade\"</code>, <code>\"month\"</code>, <code>\"year\"</code> | Initial displayed level in uncontrolled mode |\n| <code>enableKeyboardNavigation</code> | no | <code>false &#124; true</code> | <code>false</code>, <code>true</code> | Enable enhanced keyboard navigation (Ctrl/Cmd + Arrow keys for year navigation, Ctrl/Cmd + Shift + Arrow keys for decade navigation, Y key to open year view) |\n| <code>firstDayOfWeek</code> | no | <code>0 &#124; 2 &#124; 3 &#124; 4 &#124; 5 &#124; 6 &#124; 1</code> | <code>0</code>, <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, <code>5</code>, <code>6</code> | Number 0-6, where 0 – Sunday and 6 – Saturday. |\n| <code>fullWidth</code> | no | <code>false &#124; true</code> | <code>false</code>, <code>true</code> | Determines whether the list should take the full width of its container |\n| <code>headerControlsOrder</code> | no | <code>(\"next\" &#124; \"previous\" &#124; \"level\")[]</code> | — | Controls order |\n| <code>hideOutsideDates</code> | no | <code>false &#124; true</code> | <code>false</code>, <code>true</code> | Determines whether outside dates should be hidden |\n| <code>hideWeekdays</code> | no | <code>false &#124; true</code> | <code>false</code>, <code>true</code> | Determines whether weekdays row should be hidden |\n| <code>highlightToday</code> | no | <code>false &#124; true</code> | <code>false</code>, <code>true</code> | Determines whether today should be highlighted with a border |\n| <code>level</code> | no | <code>\"month\" &#124; \"year\" &#124; \"decade\"</code> | <code>\"decade\"</code>, <code>\"month\"</code>, <code>\"year\"</code> | Current displayed level displayed in controlled mode |\n| <code>locale</code> | no | <code>string</code> | — | Dayjs locale, defaults to value defined in DatesProvider |\n| <code>maxDate</code> | no | <code>string &#124; Date</code> | — | Maximum possible date in `YYYY-MM-DD` format or Date object |\n| <code>maxLevel</code> | no | <code>\"month\" &#124; \"year\" &#124; \"decade\"</code> | <code>\"decade\"</code>, <code>\"mLine truncated
"content": "# GettingStartedDates\nPackage: @mantine/dates\nImport: import { GettingStartedDates } from '@mantine/dates';\n\n## Installation\n\n```bash\nyarn add @mantine/dates dayjs\n```\n\n```bash\nnpm install @mantine/dates dayjs\n```\n\nAfter installation import package styles at the root of your application:\n\n```tsx\nimport '@mantine/core/styles.css';\n// ‼️ import dates styles after core package styles\nimport '@mantine/dates/styles.css';\n```\n\n## Do not forget to import styles\n\nFollowed the installation instructions above but something is not working\n(calendars and date pickers have no styles and look broken)?\nYou've fallen into the trap of not importing dates styles!\nTo fix this issue, import dates styles at the root of your application:\n\n```tsx\nimport '@mantine/dates/styles.css';\n```\n\n## Usage\n\nAfter installing the `@mantine/dates` package and importing styles, you can use all components from it:\n\n\n\n## Date values as strings\n\n`@mantine/dates` components work with date strings: `YYYY-MM-DD` or `YYYY-MM-DD HH:mm:ss` depending on the component. Those strings do not include any timezone-specific information.\n\n## dayjs\n\n`@mantine/dates` components use [dayjs](https://day.js.org/) under the hood for date manipulations and formatting.\ndayjs is a required dependency – you cannot change it to another date library. If you want to use a different\ndate library in your application, you will need to install it separately.\n\n## DatesProvider\n\nThe `DatesProvider` component lets you set various settings that are shared across all\ncomponents exported from the `@mantine/dates` package. `DatesProvider` supports the following settings:\n\n* `locale` – dayjs locale. Note that you also need to import the corresponding locale module from dayjs. The default value is `en`.\n* `firstDayOfWeek` – a number from 0 to 6, where 0 is Sunday and 6 is Saturday. The default value is 1 – Monday.\n* `weekendDays` – an array of numbers from 0 to 6, where 0 is Sunday and 6 is Saturday. The default value is `[0, 6]` – Saturday and Sunday.\n* `consistentWeeks` – boolean. If `true`, every month will have 6 weeks. The default value is `false`.\n\n```tsx\nimport 'dayjs/locale/ru';\nimport { DatesProvider, MonthPickerInput, DatePickerInput } from '@mantine/dates';\n\nfunction Demo() {\n return (\n <DatesProvider settings={{ locale: 'ru', firstDayOfWeek: 0, weekendDays: [0] }}>\n <MonthPickerInput label=\"Pick month\" placeholder=\"Pick month\" />\n <DatePickerInput mt=\"md\" label=\"Pick date\" placeholder=\"Pick date\" />\n </DatesProvider>\n );\n}\n```\n\n\n## Consistent weeks\n\nIf you want to avoid layout shifts, set `consistentWeeks: true` in the `DatesProvider` settings.\nThis will ensure that every month has 6 weeks, even if outside days are not in the same month.\n\n```tsx\nimport { DatePicker, DatesProvider } from '@mantine/dates';\n\nfunction Demo() {\n return (\n <DatesProvider settings={{ consistentWeeks: true }}>\n <DatePicker />\n </DatesProvider>\n );\n}\n```\n\n\n## Custom parse format\n\nSome components like [DateInput](https://mantine.dev/llms/dates-date-input.md) require the [custom parse format](https://day.js.org/docs/en/plugin/custom-parse-format)\ndayjs plugin. You need to extend dayjs with this plugin before using components that require it. Note that\nthis is usually done once in your application root file, so you don't need to do it every time you use the component.\n\n```tsx\nimport dayjs from 'dayjs';\nimport customParseFormat from 'dayjs/plugin/customParseFormat';\n\ndayjs.extend(customParseFormat);\n```\n\n## Localization and server components\n\nTo add localization, you must import `import 'dayjs/locale/x';` in your application (`x` is the locale name)\nand set `locale` either on `DatesProvider` or on each component individually.\n\nExample of setting the locale on DatesProvider:\n\n```tsx\nimport 'dayjs/locale/ru';\n\nimport { DatesProvider } from '@mantine/dates';\n\nfunction Demo() {\n return (\n <DatesProvider settings={{ locale: 'ru' }}>\n {/* Your app */}\n </DatesProvider>\n );\n}\n```\n\nThe code above works in all environments, except Next.js app router.\nIf you are using Next.js app router, you must add `'use client';` to the\ntop of the file where you are importing `dayjs/locale/x` – locale data\nis required both on client and server.\n\n```tsx\n'use client';\n\nimport 'dayjs/locale/ru';\n\nimport { DatesProvider } from '@mantine/dates';\n\nfunction Demo() {\n return (\n <DatesProvider settings={{ locale: 'ru' }}>\n {/* Your app */}\n </DatesProvider>\n );\n}\n```\n"
},
{
"path": "references/mantine-charts.md",
"content": "# Mantine Charts\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nPackage: `@mantine/charts`. Effective props combine the [shared prop API](components.md#shared-prop-api) with each component's specific props below. Component-specific records override shared records with the same name.\n\n## Package guidance\n\nPass sanitized JSON data through serializable props. Use [immutable local `const` blocks](runtime.md#immutable-local-bindings) for repeated derived chart values; authored formatters and renderer callbacks remain blocked. Include a textual summary and do not rely on color alone.\n\n## Enabled inventory\n\n<code>AreaChart</code>, <code>BarChart</code>, <code>BarsList</code>, <code>BubbleChart</code>, <code>ChartLegend</code>, <code>ChartTooltip</code>, <code>CompositeChart</code>, <code>DonutChart</code>, <code>FunnelChart</code>, <code>Heatmap</code>, <code>LineChart</code>, <code>PieChart</code>, <code>RadarChart</code>, <code>RadialBarChart</code>, <code>SankeyChart</code>, <code>ScatterChart</code>, <code>Sparkline</code>, <code>Treemap</code>\n\n## Denied inventory\n\n<code>AreaGradient</code>\n\n## Component records\n\n<a id=\"component-areachart\"></a>\n### `AreaChart`\n\n- Safety: `wrapped`\n- Category: `charts`\n- Documentation: [upstream component API](https://mantine.dev/charts/area-chart/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Include a nearby text summary of the chart data.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>activeDotProps</code> | no | <code>MantineChartDotProps</code> | — | Props passed down to all active dots. Ignored if `withDots={false}` is set. |\n| <code>areaChartProps</code> | no | <code>(CartesianChartProps&lt;unknown&gt; &amp; { ref?: React.Ref&lt;SVGSVGElement&gt;; })</code> | — | Props passed down to recharts `AreaChart` component |\n| <code>attributes</code> | no | <code>{ area?: Record&lt;string, any&gt;; legend?: Record&lt;string, any&gt;; grid?: Record&lt;string, any&gt;; root?: Record&lt;string, any&gt;; ... 14 more ...; tooltipBody?: Record&lt;...&gt;; }</code> | — | — |\n| <code>connectNulls</code> | no | <code>false &#124; true</code> | <code>false</code>, <code>true</code> | If set, points with `null` values are connected |\n| <code>curveType</code> | no | <code>\"step\" &#124; \"bump\" &#124; \"linear\" &#124; \"natural\" &#124; \"monotone\" &#124; \"stepBefore\" &#124; \"stepAfter\"</code> | <code>\"bump\"</code>, <code>\"linear\"</code>, <code>\"monotone\"</code>, <code>\"natural\"</code>, <code>\"step\"</code>, <code>\"stepAfter\"</code>, <code>\"stepBefore\"</code> | Type of the curve |\n| <code>data</code> | yes | <code>ChartData</code> | — | Data used to display chart |\n| <code>dataKey</code> | yes | <code>string</code> | — | Key of the `data` object for x-axis values |\n| <code>dotProps</code> | no | <code>MantineChartDotProps</code> | — | Props passed down to all dots. Ignored if `withDots={false}` is set. |\n| <code>gridAxis</code> | no | <code>\"none\" &#124; \"x\" &#124; \"y\" &#124; \"xy\"</code> | <code>\"none\"</code>, <code>\"x\"</code>, <code>\"xy\"</code>, <code>\"y\"</code> | Specifies which lines should be displayed in the grid, `'x'` by default |\n| <code>gridColor</code> | no | <code>DefaultMantineColor</code> | <code>\"blue\"</code>, <code>\"cyan\"</code>, <code>\"dark\"</code>, <code>\"grape\"</code>, <code>\"gray\"</code>, <code>\"green\"</code>, <code>\"indigo\"</code>, <code>\"lime\"</code>, <code>\"orange\"</code>, <code>\"pink\"</code>, <code>\"red\"</code>, <code>\"teal\"</code>, <code>\"violet\"</code>, <code>\"yellow\"</code> | Color of the grid and cursor lines, by default depends on color scheme |\n| <code>gridProps</code> | no | <code>Omit&lt;CartesianGridProps, \"ref\"&gt;</code> | — | Props passed down to the `CartesianGrid` component |\n| <code>legendProps</code> | no | <code>Omit&lt;LegendProps, \"ref\"&gt;</code> | — | Props passed down to the `Legend` component |\n| <code>referenceLines</code> | no | <code>ChartReferenceLineProps[]</code> | — | Reference lines that should be displayed on the chart |\n| <code>rightYAxisLabel</code> | no | <code>string</code> | — | A label to display next to the right y-axis |\n| <code>rightYAxisProps</code> | no | <code>Omit&lt;YAxisProps, \"ref\"&gt;</code> | — | Props passed down to the `YAxis` recharts component rendered on the right side |\n| <code>series</code> | yes | <code>AreaChartSeries[]</code> | — | An array of objects with `name` and `color` keys. Determines which data should be consumed from the `data` array. |\n| <code>splitColors</code> | no | <code>[DefaultMantineColor, DefaultMantineColor]</code> | — | A tuple of colors used when `type=\"split\"` is set, ignoredLine truncated
"content": "# Mantine Charts\n\nUse the official Mantine LLM index in [Mantine Core](mantine-core.md#charts) to discover chart documentation.\n\nThe upstream source is https://mantine.dev/llms.txt. Follow its `## Charts` links for current component documentation. Homarr's live component catalog remains authoritative for the installed component names and blocked capabilities.\n"
},
{
"path": "references/homarr-components.md",
"content": "# Homarr components\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nPackage: `@homarr/widgets`. Effective props combine the [shared prop API](components.md#shared-prop-api) with each component's specific props below. Component-specific records override shared records with the same name.\n\n## Package guidance\n\nHomarr components own controlled request, action, pagination, disclosure, icon, and recursive traversal behavior. Manual request parameters come from the invoking component's `params` prop. `RecursiveList` is the only supported arbitrary-depth authored renderer and its child template may use the restricted safe-block grammar.\n\n## Enabled inventory\n\n<code>ActionButton</code>, <code>Collapsible</code>, <code>PaginatedList</code>, <code>RecursiveList</code>, <code>RefreshButton</code>, <code>StatBar</code>, <code>SubData</code>, <code>SubFetch</code>, <code>TabPanel</code>, <code>TablerIcon</code>, <code>TabsContainer</code>, <code>ToggleSwitch</code>, <code>TypeBadge</code>\n\n## Denied inventory\n\n_None._\n\n## Component records\n\n<a id=\"component-actionbutton\"></a>\n### `ActionButton`\n\n- Safety: `wrapped`\n- Category: `network`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Action labels must describe their effect; destructive actions require confirmation.\n\nRuns a named user-triggered action.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>confirmMessage</code> | no | <code>string</code> | — | — |\n| <code>disabled</code> | no | <code>boolean &#124; string</code> | — | — |\n| <code>errorMessage</code> | no | <code>string</code> | — | — |\n| <code>fullWidth</code> | no | <code>boolean &#124; string</code> | — | — |\n| <code>icon</code> | no | <code>string</code> | — | — |\n| <code>label</code> | no | <code>string</code> | — | — |\n| <code>params</code> | no | <code>Record&lt;string, string &#124; number &#124; boolean&gt;</code> | — | — |\n| <code>requestId</code> | no | <code>string</code> | — | Identifier of the named Custom Widget action. |\n| <code>size</code> | no | <code>string</code> | — | — |\n| <code>successMessage</code> | no | <code>string</code> | — | — |\n\n<a id=\"component-collapsible\"></a>\n### `Collapsible`\n\n- Safety: `allowed`\n- Category: `interaction`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide a visible label or aria-label.\n\nShows and hides a bounded content section.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>defaultOpen</code> | no | <code>boolean</code> | — | — |\n| <code>title</code> | yes | <code>string</code> | — | — |\n\n<a id=\"component-paginatedlist\"></a>\n### `PaginatedList`\n\n- Safety: `allowed`\n- Category: `interaction`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide a visible label or aria-label.\n\nRenders a bounded page of collection items.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>pageSize</code> | no | <code>number</code> | — | — |\n\n<a id=\"component-recursivelist\"></a>\n### `RecursiveList`\n\n- Safety: `wrapped`\n- Category: `content`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide meaningful text alternatives for non-text content.\n\nRenders an arbitrary-depth tree through a bounded, Homarr-owned traversal.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>childrenPath</code> | yes | <code>string</code> | — | — |\n| <code>data</code> | yes | <code>unknown</code> | — | — |\n| <code>defaultExpandedDepth</code> | no | <code>number</code> | — | — |\n| <code>gap</code> | no | <code>MantineSpacing</code> | — | — |\n| <code>indent</code> | no | <code>MantineSpacing</code> | — | — |\n| <code>keyPath</code> | yes | <code>string</code> | — | — |\n| <code>maxDepth</code> | no | <code>number</code> | — | — |\n| <code>maxNodes</code> | no | <code>number</code> | — | — |\n| <code>showLines</code> | no | <code>boolean</cLine truncated
"content": "# Homarr components\n\n> Generated from `component-catalog-v1.json`. Catalog schema v1 · Custom Widget 2.0.0 · Mantine 9.4.1. Do not edit this file by hand.\n\nPackage: `@homarr/widgets`. The component-specific props below supplement ordinary safe serializable Mantine props and style props. Component-specific records override ordinary behavior with the same name.\n\n## Package guidance\n\nHomarr components own controlled request, action, pagination, disclosure, icon, and recursive traversal behavior. Manual request parameters come from the invoking component's `params` prop. `RecursiveList` is the only supported arbitrary-depth authored renderer and its child template may use the restricted safe-block grammar.\n\n## Enabled inventory\n\n<code>ActionButton</code>, <code>Collapsible</code>, <code>PaginatedList</code>, <code>RecursiveList</code>, <code>RefreshButton</code>, <code>StatBar</code>, <code>SubData</code>, <code>SubFetch</code>, <code>TabPanel</code>, <code>TablerIcon</code>, <code>TabsContainer</code>, <code>ToggleSwitch</code>, <code>TypeBadge</code>\n\n## Denied inventory\n\n_None._\n\n## Component records\n\n<a id=\"component-actionbutton\"></a>\n### `ActionButton`\n\n- Safety: `wrapped`\n- Category: `network`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Action labels must describe their effect; destructive actions require confirmation.\n\nRuns a named user-triggered action.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>color</code> | no | <code>string</code> | — | — |\n| <code>confirmMessage</code> | no | <code>string</code> | — | — |\n| <code>disabled</code> | no | <code>boolean &#124; string</code> | — | — |\n| <code>errorMessage</code> | no | <code>string</code> | — | — |\n| <code>fullWidth</code> | no | <code>boolean &#124; string</code> | — | — |\n| <code>icon</code> | no | <code>string</code> | — | — |\n| <code>label</code> | no | <code>string</code> | — | — |\n| <code>params</code> | no | <code>Record&lt;string, string &#124; number &#124; boolean&gt;</code> | — | — |\n| <code>requestId</code> | no | <code>string</code> | — | Identifier of the named Custom Widget action. |\n| <code>size</code> | no | <code>string</code> | — | — |\n| <code>successMessage</code> | no | <code>string</code> | — | — |\n| <code>variant</code> | no | <code>string</code> | — | — |\n\n<a id=\"component-collapsible\"></a>\n### `Collapsible`\n\n- Safety: `allowed`\n- Category: `interaction`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide a visible label or aria-label.\n\nShows and hides a bounded content section.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>defaultOpen</code> | no | <code>boolean</code> | — | — |\n| <code>title</code> | yes | <code>string</code> | — | — |\n\n<a id=\"component-paginatedlist\"></a>\n### `PaginatedList`\n\n- Safety: `allowed`\n- Category: `interaction`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide a visible label or aria-label.\n\nRenders a bounded page of collection items.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>pageSize</code> | no | <code>number</code> | — | — |\n\n<a id=\"component-recursivelist\"></a>\n### `RecursiveList`\n\n- Safety: `wrapped`\n- Category: `content`\n- Documentation: [upstream component API](https://homarr.dev/docs/management/custom-widgets/)\n- Temporary bind: not available\n- Subcomponents: none\n- Component-specific blocked props: none\n- Accessibility:\n - Provide meaningful text alternatives for non-text content.\n\nRenders an arbitrary-depth tree through a bounded, Homarr-owned traversal.\n\n#### Component-specific props\n\n| Prop | Required | Type | Literal values | Description |\n| --- | --- | --- | --- | --- |\n| <code>childrenPath</code> | yes | <code>string</code> | — | — |\n| <code>data</code> | yes | <code>unknown</code> | — | — |\n| <code>defaultExpandedDepth</code> | no | <code>number</code> | — | — |\n| <code>gap</code> | no | <code>MantineSpacing</code> | — | — |\n| <code>indent</code> | no | <code>MantineSpacing</code> | — | — |\n| <code>keyPath</code> | yes | <code>string</code> | — | — |\n| <code>maxDepth</code> | no | <code>number</code> | — | — |\nLine truncated
}
]
}
@@ -0,0 +1,36 @@
export interface CustomJsxTemplateDiagnostic {
severity: "error" | "warning";
message: string;
index: number;
line: number;
column: number;
}
export function createCustomJsxParseDiagnostic(template: string, error: unknown): CustomJsxTemplateDiagnostic {
const parseError = error as Error & { pos?: number; loc?: { line?: number; column?: number } };
const parseIndex = Math.max(0, (parseError.pos ?? 2) - 2);
const missingInitializer = [...template.matchAll(/(?:\bconst|,)\s+([A-Za-z_$][\w$]*)\s*;/gu)].find((match) => {
const semicolon = (match.index ?? 0) + match[0].length - 1;
return Math.abs(semicolon - parseIndex) <= 1;
});
const duplicateBinding = /Identifier '([^']+)' has already been declared/iu.exec(parseError.message);
const duplicateArgument = /Argument name clash/iu.test(parseError.message);
const message = missingInitializer
? `LOCAL_BINDING_REQUIRES_INITIALIZER: '${missingInitializer[1]}' requires an initializer`
: duplicateBinding
? `DUPLICATE_LOCAL_BINDING: '${duplicateBinding[1]}' is already declared`
: duplicateArgument
? "DUPLICATE_LOCAL_BINDING: Callback parameter names must be unique"
: parseError.message;
return {
severity: "error",
message,
index: parseIndex,
line: parseError.loc?.line ?? 1,
column: Math.max(
1,
(parseError.loc?.column ?? 0) + (parseError.loc?.line === 1 || parseError.loc?.line === undefined ? -1 : 1),
),
};
}
@@ -118,13 +118,19 @@ function analyzeAttributeValue(
}
if (
attributeName === "maxDepth" &&
(typeof literalValue.value !== "number" || literalValue.value < 1 || literalValue.value > 32)
(typeof literalValue.value !== "number" ||
!Number.isInteger(literalValue.value) ||
literalValue.value < 1 ||
literalValue.value > 32)
) {
context.add(attribute, "INVALID_PROP_VALUE: 'maxDepth' must be between 1 and 32");
}
if (
attributeName === "maxNodes" &&
(typeof literalValue.value !== "number" || literalValue.value < 1 || literalValue.value > 2_000)
(typeof literalValue.value !== "number" ||
!Number.isInteger(literalValue.value) ||
literalValue.value < 1 ||
literalValue.value > 2_000)
) {
context.add(attribute, "INVALID_PROP_VALUE: 'maxNodes' must be between 1 and 2000");
}
@@ -102,6 +102,30 @@ export function isStaticallyCallableBinding(node: AstNode): boolean {
return Boolean(propertyName && callableRootMembers[String(object.name)]?.has(propertyName));
}
export function canStaticallyProduceCallable(node: AstNode): boolean {
if (isStaticallyCallableBinding(node) || ["ArrowFunctionExpression", "FunctionExpression"].includes(node.type)) {
return true;
}
if (node.type === "ConditionalExpression") {
const consequent = nodeOf(node.consequent);
const alternate = nodeOf(node.alternate);
return Boolean(
(consequent && canStaticallyProduceCallable(consequent)) ||
(alternate && canStaticallyProduceCallable(alternate)),
);
}
if (node.type === "LogicalExpression") {
const left = nodeOf(node.left);
const right = nodeOf(node.right);
return Boolean((left && canStaticallyProduceCallable(left)) || (right && canStaticallyProduceCallable(right)));
}
if (node.type === "ChainExpression") {
const expression = nodeOf(node.expression);
return Boolean(expression && canStaticallyProduceCallable(expression));
}
return false;
}
function editDistance(left: string, right: string): number {
const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
+57 -38
View File
@@ -9,23 +9,54 @@ import {
} from "./policy";
import type { AstNode } from "./analyzer-ast";
import { nodeOf, nodesOf, staticPropertyName } from "./analyzer-ast";
import { createCustomJsxParseDiagnostic } from "./analyzer-diagnostics";
import type { CustomJsxTemplateDiagnostic } from "./analyzer-diagnostics";
import { analyzeCustomJsxElement } from "./analyzer-jsx";
import { isStaticallyCallableBinding, RESERVED_LOCAL_BINDINGS, ROOT_BINDINGS } from "./analyzer-language";
import {
canStaticallyProduceCallable,
isStaticallyCallableBinding,
RESERVED_LOCAL_BINDINGS,
ROOT_BINDINGS,
} from "./analyzer-language";
import {
CUSTOM_JSX_BINARY_OPERATORS,
CUSTOM_JSX_CALLBACK_METHODS,
CUSTOM_JSX_SAFE_VALUE_METHODS,
} from "./safe-language-policy";
export interface CustomJsxTemplateDiagnostic {
severity: "error" | "warning";
message: string;
index: number;
line: number;
column: number;
}
export type { CustomJsxTemplateDiagnostic } from "./analyzer-diagnostics";
const JsxParser = Parser.extend(jsx());
const requestStatusLabels = new Set(["loading", "success", "error"]);
function directRequestStatusId(node: AstNode | null): string | null {
if (node?.type !== "MemberExpression") return null;
const object = nodeOf(node.object);
if (object?.type !== "Identifier" || object.name !== "status") return null;
const property = nodeOf(node.property);
return node.computed
? (staticPropertyName(property) ?? null)
: String(property?.name ?? property?.value ?? "") || null;
}
function invalidRequestStatusComparison(node: AstNode) {
if (!["===", "==", "!==", "!="].includes(String(node.operator))) return null;
const left = nodeOf(node.left);
const right = nodeOf(node.right);
const leftStatus = directRequestStatusId(left);
const rightStatus = directRequestStatusId(right);
const leftLabel = left?.type === "Literal" && typeof left.value === "string" ? left.value : null;
const rightLabel = right?.type === "Literal" && typeof right.value === "string" ? right.value : null;
const requestId =
leftStatus && rightLabel && requestStatusLabels.has(rightLabel)
? leftStatus
: rightStatus && leftLabel && requestStatusLabels.has(leftLabel)
? rightStatus
: null;
return requestId
? `INVALID_STATUS_COMPARISON: status.${requestId} is an object. Use status.${requestId}?.loading, status.${requestId}?.ok === true, or status.${requestId}?.ok === false`
: null;
}
export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDiagnostic[] {
const diagnostics: CustomJsxTemplateDiagnostic[] = [];
@@ -85,7 +116,9 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
const body = nodeOf(node.body);
if (!body) return;
if (body.type === "BlockStatement") visitSafeBlock(body, depth + 1, callbackBindings);
else visit(body, depth + 1, callbackBindings);
else if (canStaticallyProduceCallable(body)) {
add(body, "CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
} else visit(body, depth + 1, callbackBindings);
};
const visitSafeBlock = (block: AstNode, depth: number, bindings: ReadonlySet<string>) => {
@@ -110,7 +143,9 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
return;
}
const argument = nodeOf(statement.argument);
if (argument) visit(argument, depth + 1, scopedBindings);
if (argument && canStaticallyProduceCallable(argument)) {
add(argument, "CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
} else if (argument) visit(argument, depth + 1, scopedBindings);
return;
}
if (statement.type !== "VariableDeclaration") {
@@ -146,11 +181,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
add(declaration, `LOCAL_BINDING_REQUIRES_INITIALIZER: '${name}' requires an initializer`);
continue;
}
if (
initializer.type === "ArrowFunctionExpression" ||
initializer.type === "FunctionExpression" ||
isStaticallyCallableBinding(initializer)
) {
if (canStaticallyProduceCallable(initializer)) {
add(initializer, "CALLBACK_VALUE_NOT_ALLOWED: Functions cannot be stored in local bindings");
continue;
}
@@ -240,6 +271,10 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
if (node.type === "BinaryExpression" && !CUSTOM_JSX_BINARY_OPERATORS.has(String(node.operator))) {
add(node, `Binary operator '${String(node.operator)}' is not supported`);
}
if (node.type === "BinaryExpression") {
const statusDiagnostic = invalidRequestStatusComparison(node);
if (statusDiagnostic) add(node, statusDiagnostic);
}
const left = nodeOf(node.left);
const right = nodeOf(node.right);
if (left) visit(left, depth + 1, bindings);
@@ -268,6 +303,9 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
case "CallExpression": {
const callee = nodeOf(node.callee);
const arguments_ = nodesOf(node.arguments);
if (node.optional) {
add(node, "CALL_TARGET_NOT_ALLOWED: Optional calls are not supported");
}
if (callee?.type === "ArrowFunctionExpression") {
if (nodesOf(callee.params).length > 0) {
add(callee, "CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions cannot declare parameters");
@@ -275,6 +313,9 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
if (arguments_.length > 0) {
add(node, "CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions must be called without arguments");
}
if (nodeOf(callee.body)?.type !== "BlockStatement") {
add(callee, "BLOCK_REQUIRES_FINAL_RETURN: Inline derived-value functions require a safe const block");
}
visitArrow(callee, depth + 1, bindings);
arguments_.forEach((argument) => visit(argument, depth + 1, bindings));
return;
@@ -352,29 +393,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
}) as unknown as AstNode;
visit(program, 0, ROOT_BINDINGS);
} catch (error) {
const parseError = error as Error & { pos?: number; loc?: { line?: number; column?: number } };
const parseIndex = Math.max(0, (parseError.pos ?? 2) - 2);
const missingInitializer = [...template.matchAll(/(?:\bconst|,)\s+([A-Za-z_$][\w$]*)\s*;/gu)].find((match) => {
const semicolon = (match.index ?? 0) + match[0].length - 1;
return Math.abs(semicolon - parseIndex) <= 1;
});
const duplicateCandidate = /Identifier '([^']+)' has already been declared/iu.exec(parseError.message);
const duplicateBinding = duplicateCandidate;
const message = missingInitializer
? `LOCAL_BINDING_REQUIRES_INITIALIZER: '${missingInitializer[1]}' requires an initializer`
: duplicateBinding
? `DUPLICATE_LOCAL_BINDING: '${duplicateBinding[1]}' is already declared`
: parseError.message;
diagnostics.push({
severity: "error",
message,
index: Math.max(0, (parseError.pos ?? 2) - 2),
line: parseError.loc?.line ?? 1,
column: Math.max(
1,
(parseError.loc?.column ?? 0) + (parseError.loc?.line === 1 || parseError.loc?.line === undefined ? -1 : 1),
),
});
diagnostics.push(createCustomJsxParseDiagnostic(template, error));
}
return diagnostics;
@@ -7,6 +7,7 @@ import {
SafeJsxError,
} from "./interpreter-foundation";
import type { AstNode, Budget, InterpreterCallback } from "./interpreter-foundation";
import { RESERVED_LOCAL_BINDINGS } from "./analyzer-language";
import { isBlockedCustomJsxLexicalBinding } from "./policy";
interface InterpreterCallbackContext {
@@ -14,20 +15,20 @@ interface InterpreterCallbackContext {
evaluate(node: AstNode, environment: Environment, depth: number): unknown;
}
const reservedLocalBindings = new Set(["data", "status", "options", "inputs"]);
export function createInterpreterCallback(node: AstNode, environment: Environment): InterpreterCallback {
if (node.async || node.generator) {
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Async and generator callbacks are not supported");
}
const parameterNames = new Set<string>();
const params = asNodeArray(node.params, "callback parameters").map((param) => {
if (param.type !== "Identifier") throw new SafeJsxError("Callback parameters must be identifiers");
if (param.type !== "Identifier") {
throw new SafeJsxError("INVALID_LOCAL_DECLARATION: Callback parameters must be identifiers");
}
const name = String(param.name);
if (isBlockedCustomJsxLexicalBinding(name)) {
throw new SafeJsxError(`INVALID_LOCAL_DECLARATION: '${name}' is not a safe callback parameter name`);
}
if (reservedLocalBindings.has(name)) {
if (RESERVED_LOCAL_BINDINGS.has(name)) {
throw new SafeJsxError(`RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
}
if (parameterNames.has(name)) {
@@ -55,9 +56,11 @@ export function runInterpreterCallback(
values[name] = args[index];
});
const environment = new Environment(values, callback.environment);
return callback.body.type === "BlockStatement"
? executeSafeBlock(callback.body, environment, depth + 1, context)
: context.evaluate(callback.body, environment, depth + 1);
const result =
callback.body.type === "BlockStatement"
? executeSafeBlock(callback.body, environment, depth + 1, context)
: context.evaluate(callback.body, environment, depth + 1);
return ensureNonCallableResult(result);
}
function executeSafeBlock(
@@ -91,7 +94,9 @@ function executeSafeBlock(
if (!isFinal) {
throw new SafeJsxError("BLOCK_REQUIRES_FINAL_RETURN: Return is only allowed as the final statement");
}
return context.evaluate(asNode(statement.argument, "safe block return value"), scopedEnvironment, depth + 1);
return ensureNonCallableResult(
context.evaluate(asNode(statement.argument, "safe block return value"), scopedEnvironment, depth + 1),
);
}
if (statement.type !== "VariableDeclaration") {
throw new SafeJsxError(`UNSUPPORTED_BLOCK_STATEMENT: '${statement.type}' is not allowed in a safe block`);
@@ -109,7 +114,7 @@ function executeSafeBlock(
if (isBlockedCustomJsxLexicalBinding(name)) {
throw new SafeJsxError(`INVALID_LOCAL_DECLARATION: '${name}' is not a safe local binding name`);
}
if (reservedLocalBindings.has(name)) {
if (RESERVED_LOCAL_BINDINGS.has(name)) {
throw new SafeJsxError(`RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
}
if (localNames.has(name)) {
@@ -129,3 +134,10 @@ function executeSafeBlock(
}
throw new SafeJsxError("BLOCK_REQUIRES_FINAL_RETURN: Safe block did not return a value");
}
function ensureNonCallableResult(value: unknown): unknown {
if (typeof value === "function" || isInterpreterCallback(value)) {
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
}
return value;
}
@@ -20,7 +20,12 @@ export function parseCustomJsxTemplate(template: string): AstNode {
allowReturnOutsideFunction: false,
}) as unknown as AstNode;
} catch (error) {
throw new SafeJsxError(error instanceof Error ? error.message : "Unable to parse JSX template");
const message = error instanceof Error ? error.message : "Unable to parse JSX template";
throw new SafeJsxError(
/Argument name clash/iu.test(message)
? "DUPLICATE_LOCAL_BINDING: Callback parameter names must be unique"
: message,
);
}
const body = asNodeArray(program.body, "program body");
if (body.length !== 1 || body[0]?.type !== "ExpressionStatement") {
@@ -264,6 +264,11 @@ class Interpreter {
const callee = asNode(node.callee, "call target");
const argumentNodes = asNodeArray(node.arguments, "call arguments");
if (callee.type === "ArrowFunctionExpression") {
if (callee.body && asNode(callee.body, "inline derived-value body").type !== "BlockStatement") {
throw new SafeJsxError(
"BLOCK_REQUIRES_FINAL_RETURN: Inline derived-value functions require a safe const block",
);
}
if (asNodeArray(callee.params, "inline derived-value parameters").length > 0) {
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions cannot declare parameters");
}
@@ -59,7 +59,7 @@ export function buildTrustedRecursiveList(options: RecursiveListBuildOptions): T
return [diagnosticNode("diagnostic:root-data", "RecursiveList data must be an object or an array")];
}
const willExceedNodeLimit = exceedsRecursiveListNodeLimit(roots, childrenPath, maxDepth, maxNodes);
const willExceedNodeLimit = exceedsRecursiveListNodeLimit(roots, childrenPath, maxDepth, maxNodes, options.budget);
let renderedRowCount = 0;
let diagnosticCount = 0;
let limitSentinelRendered = false;
@@ -1,4 +1,5 @@
import { SafeJsxError } from "./interpreter-foundation";
import type { Budget } from "./interpreter-foundation";
import { CUSTOM_JSX_BLOCKED_PROPERTIES, normalizeCustomJsxProperty } from "./policy";
import { ownProperty } from "./safe-properties";
@@ -12,25 +13,27 @@ export function exceedsRecursiveListNodeLimit(
childrenPath: readonly string[],
maxDepth: number,
maxNodes: number,
budget: Budget,
) {
let rows = 0;
const charge = () => {
const charge = (depth: number) => {
budget.operation(depth + 1);
rows += 1;
return rows > maxNodes;
};
const visit = (values: readonly unknown[], depth: number, ancestors: ReadonlySet<object>): boolean => {
for (const value of values) {
if (charge()) return true;
if (charge(depth)) return true;
if (!isObject(value) || ancestors.has(value)) continue;
const rawChildren = readRestrictedPath(value, childrenPath);
if (rawChildren !== undefined && rawChildren !== null && !Array.isArray(rawChildren)) {
if (charge()) return true;
if (charge(depth + 1)) return true;
continue;
}
if (!Array.isArray(rawChildren) || rawChildren.length === 0) continue;
if (depth + 1 >= maxDepth) {
if (charge()) return true;
if (charge(depth + 1)) return true;
continue;
}
if (visit(rawChildren, depth + 1, new Set(ancestors).add(value))) return true;
@@ -74,7 +77,7 @@ export function clampWithWarning(
const validNumber = typeof value === "number" && Number.isFinite(value);
const number = validNumber ? Math.trunc(value) : fallback;
const clamped = Math.min(maximum, Math.max(minimum, number));
if (value !== undefined && (!validNumber || number !== clamped)) {
if (value !== undefined && (!validNumber || value !== number || number !== clamped)) {
warnings.add(`RECURSIVE_LIST_LIMIT_CLAMPED: ${name} was clamped to ${clamped}`);
}
return clamped;
@@ -18,7 +18,7 @@ export type {
export function TrustedRecursiveList({ ...props }: TrustedRecursiveListProps) {
return (
<RecursiveListErrorBoundary resetKey={props.nodes}>
<RecursiveListErrorBoundary resetKey={props.nodes} code="RECURSIVE_LIST_RENDER_ERROR">
<TrustedRecursiveListInner {...props} />
</RecursiveListErrorBoundary>
);
@@ -51,16 +51,13 @@ function TrustedRecursiveListInner({
}
class RecursiveListErrorBoundary extends Component<
{ children: ReactNode; resetKey: readonly TreeNodeData[] },
{ error: Error | null; resetKey: readonly TreeNodeData[] }
{ children: ReactNode; resetKey: unknown; code: string },
{ error: Error | null; resetKey: unknown }
> {
public state = { error: null, resetKey: this.props.resetKey } as {
error: Error | null;
resetKey: readonly TreeNodeData[];
};
public state = { error: null, resetKey: this.props.resetKey } as { error: Error | null; resetKey: unknown };
public static getDerivedStateFromProps(
props: Readonly<{ children: ReactNode; resetKey: readonly TreeNodeData[] }>,
state: Readonly<{ error: Error | null; resetKey: readonly TreeNodeData[] }>,
props: Readonly<{ children: ReactNode; resetKey: unknown; code: string }>,
state: Readonly<{ error: Error | null; resetKey: unknown }>,
) {
if (props.resetKey === state.resetKey) return null;
return { error: null, resetKey: props.resetKey };
@@ -72,7 +69,7 @@ class RecursiveListErrorBoundary extends Component<
public render() {
return this.state.error ? (
<Text size="xs" c="red">
RECURSIVE_LIST_RENDER_ERROR: {this.state.error.message}
{this.props.code}: {this.state.error.message}
</Text>
) : (
this.props.children
@@ -88,7 +85,7 @@ function TrustedRecursiveListNode({
gap,
}: RenderTreeNodePayload & { gap: MantineSpacing }) {
return (
<Group {...elementProps} gap={gap} wrap="nowrap" py={2}>
<Group {...elementProps} aria-expanded={hasChildren ? expanded : undefined} gap={gap} wrap="nowrap" py={2}>
<Box w={16} h={16} style={{ flex: "0 0 16px" }} aria-hidden>
{hasChildren && (
<IconChevronRight
@@ -97,7 +94,11 @@ function TrustedRecursiveListNode({
/>
)}
</Box>
<Box style={{ minWidth: 0, flex: 1 }}>{node.label}</Box>
<Box style={{ minWidth: 0, flex: 1 }}>
<RecursiveListErrorBoundary resetKey={node.label} code="RECURSIVE_LIST_BRANCH_RENDER_ERROR">
{node.label}
</RecursiveListErrorBoundary>
</Box>
</Group>
);
}
@@ -145,8 +145,8 @@ export function ActionButton(props: ActionButtonProps) {
export interface ToggleSwitchProps {
requestId?: string;
onParams?: CustomJsxRuntimeParams;
offParams?: CustomJsxRuntimeParams;
enabledParams?: CustomJsxRuntimeParams;
disabledParams?: CustomJsxRuntimeParams;
initialValue?: boolean | string;
label?: string;
color?: string;
@@ -160,8 +160,8 @@ export function ToggleSwitch(props: ToggleSwitchProps) {
const initial = parseBool(props.initialValue);
const [checked, setChecked] = useState(initial);
const locked = useRef(false);
const onParams = normalizeParams(props.onParams);
const offParams = normalizeParams(props.offParams);
const enabledParams = normalizeParams(props.enabledParams);
const disabledParams = normalizeParams(props.disabledParams);
const capability = runtime.requestCapabilities.find(
(candidate) => candidate.id === props.requestId && candidate.kind === "action",
);
@@ -169,7 +169,7 @@ export function ToggleSwitch(props: ToggleSwitchProps) {
if (!locked.current) setChecked(initial);
}, [initial]);
const change = async (next: boolean) => {
const params = next ? onParams : offParams;
const params = next ? enabledParams : disabledParams;
if (!props.requestId || !params || locked.current) return;
const confirmation = capability?.confirmation;
const confirmMessage =
@@ -231,8 +231,8 @@ export function ToggleSwitch(props: ToggleSwitchProps) {
mutation.isPending ||
runtime.isEditMode ||
(!runtime.itemId && !runtime.previewSessionId) ||
!onParams ||
!offParams
!enabledParams ||
!disabledParams
}
/>
);
@@ -42,7 +42,7 @@ describe("buildCustomWidgetAiPrompt", () => {
expect(CUSTOM_WIDGET_MANTINE_VERSION).toBe(mantinePackage.version);
expect(source).not.toContain("skill-content.generated.json");
expect(source).not.toContain("component-catalog.generated.json");
expect(source).not.toContain('from "./component-catalog"');
expect(source).toContain('from "./component-catalog"');
expect(source).not.toContain('from "./authoring-resources"');
});
@@ -11,6 +11,8 @@ import {
import { CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL } from "../core/ai-prompt";
import { customJsxAuthoringCatalog } from "../core/component-catalog";
import {
CUSTOM_WIDGET_CANONICAL_RUNTIME_EXAMPLES,
CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG,
CUSTOM_WIDGET_OFFLINE_BUNDLE,
CUSTOM_WIDGET_SKILL_FILES,
CUSTOM_WIDGET_SKILL_MD,
@@ -19,13 +21,16 @@ import {
const repositoryRoot = resolve(import.meta.dirname, "../../../..");
const skillRoot = resolve(repositoryRoot, ".agents/skills/homarr-custom-widget");
const generatedPath = resolve(repositoryRoot, "packages/custom-widgets/src/core/skill-content.generated.json");
const MAX_OFFLINE_BUNDLE_CHARACTERS = 900_000;
const MAX_OFFLINE_BUNDLE_CHARACTERS = 1_600_000;
const expectedPaths = [
"SKILL.md",
"references/schema.md",
"references/widget-schema.json",
"references/runtime.md",
"references/security.md",
"references/components.md",
"references/component-catalog.json",
"references/examples.json",
"references/mantine-core.md",
"references/mantine-dates.md",
"references/mantine-charts.md",
@@ -49,12 +54,24 @@ describe("custom widget Agent Skill", () => {
});
test("builds a complete self-verifying offline bundle", () => {
for (const file of CUSTOM_WIDGET_SKILL_FILES) {
for (const file of CUSTOM_WIDGET_SKILL_FILES.filter(
({ path }) => !["references/component-catalog.json", "references/examples.json"].includes(path),
)) {
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain(`--- BEGIN SKILL FILE: ${file.path} ---`);
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain(file.content.trimEnd());
}
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).not.toContain("--- BEGIN COMPACT COMPONENT CATALOG ---");
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).not.toContain("--- BEGIN CANONICAL RUNTIME EXAMPLES ---");
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain(
`--- BEGIN CANONICAL COMPONENT CATALOG ---\n${CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG}\n--- END CANONICAL COMPONENT CATALOG ---`,
);
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain(
`--- BEGIN CANONICAL RUNTIME EXAMPLES ---\n${CUSTOM_WIDGET_CANONICAL_RUNTIME_EXAMPLES}\n--- END CANONICAL RUNTIME EXAMPLES ---`,
);
const firstComponent = customJsxAuthoringCatalog.components[0];
const lastComponent = customJsxAuthoringCatalog.components.at(-1);
expect(firstComponent).toBeDefined();
expect(lastComponent).toBeDefined();
expect(CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG).toContain(JSON.stringify(firstComponent));
expect(CUSTOM_WIDGET_CANONICAL_COMPONENT_CATALOG).toContain(JSON.stringify(lastComponent));
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain("Custom Widget authoring version: 2.0.0");
expect(CUSTOM_WIDGET_OFFLINE_BUNDLE).toContain("Mantine version: 9.4.1");
expect(
@@ -72,6 +89,9 @@ describe("custom widget Agent Skill", () => {
expect(skill.installCommand).toBe(
"npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widget",
);
expect(skill.files).toBe(CUSTOM_WIDGET_SKILL_FILES);
expect(skill.componentCatalog).toBe(customJsxAuthoringCatalog);
expect(skill.examples).toEqual(expect.arrayContaining([expect.objectContaining({ id: "pokemon-evolution-tree" })]));
expect(skill).not.toHaveProperty("sha256");
expect(skill).not.toHaveProperty("downloadUrl");
});
@@ -16,13 +16,11 @@ import { customJsxComponentRegistry } from "../core/component-registry";
const repositoryRoot = resolve(import.meta.dirname, "../../../..");
const catalogPath = resolve(repositoryRoot, "packages/custom-widgets/src/core/component-catalog.generated.json");
const runtimeCatalogPath = resolve(repositoryRoot, "packages/custom-widgets/src/core/component-runtime.generated.json");
const publicCatalogPath = resolve(repositoryRoot, "apps/docs/static/custom-widgets/component-catalog-v1.json");
// Keep a reviewed ceiling close to the generated artifact so accidental metadata
// duplication must receive explicit review.
const MAX_CATALOG_BYTES = 680 * 1024;
const MAX_RUNTIME_CATALOG_BYTES = 120 * 1024;
const MAX_CATALOG_BYTES = 800 * 1024;
describe("Custom JSX authoring catalog", () => {
test("is versioned against the installed authoring surface", async () => {
@@ -82,22 +80,6 @@ describe("Custom JSX authoring catalog", () => {
expect(catalogNames).toEqual(runtimeNames);
});
test("derives a compact runtime index from the canonical catalog", async () => {
const runtimeCatalog = JSON.parse(await readFile(runtimeCatalogPath, "utf8")) as {
globalProps: string[];
components: Array<{ name: string; props: string[]; blockedProps: Array<{ name: string }> }>;
};
expect(runtimeCatalog.globalProps).toEqual(customJsxAuthoringCatalog.globalProps.map(({ name }) => name));
expect(runtimeCatalog.components).toHaveLength(customJsxAuthoringCatalog.components.length);
for (const [index, component] of runtimeCatalog.components.entries()) {
const canonical = customJsxAuthoringCatalog.components[index];
expect(component.name).toBe(canonical?.name);
expect(component.props).toEqual(canonical?.props.map(({ name }) => name));
expect(component.blockedProps).toEqual(canonical?.blockedProps);
}
expect((await readFile(runtimeCatalogPath)).byteLength).toBeLessThanOrEqual(MAX_RUNTIME_CATALOG_BYTES);
});
test("includes prop APIs, bindings, accessibility, and denied reasons", () => {
const textInput = customJsxAuthoringCatalog.components.find(({ name }) => name === "TextInput");
const label = textInput?.props.find(({ name }) => name === "label");
@@ -36,27 +36,17 @@ describe("generated Custom Widget component references", () => {
expect(generated["components.md"]).toContain(`Custom Widget ${customJsxAuthoringCatalog.customWidgetVersion}`);
expect(generated["components.md"]).toContain(`Mantine ${customJsxAuthoringCatalog.mantineVersion}`);
for (const component of customJsxAuthoringCatalog.components) {
expect(combined, component.name).toContain(`<a id="${getComponentReferenceAnchor(component.name)}"></a>`);
}
for (const component of customJsxAuthoringCatalog.components)
expect(combined, component.name).toContain(component.name);
});
test("contains the first and last canonical catalog records with their real prop APIs", () => {
test("keeps detailed records only for Homarr-owned runtime components", () => {
const generated = renderCustomWidgetComponentReferences(customJsxAuthoringCatalog);
const first = customJsxAuthoringCatalog.components[0];
const last = customJsxAuthoringCatalog.components.at(-1);
expect(first).toBeDefined();
expect(last).toBeDefined();
if (!first || !last) return;
const packagePath = {
"@mantine/core": "mantine-core.md",
"@mantine/dates": "mantine-dates.md",
"@mantine/charts": "mantine-charts.md",
"@homarr/widgets": "homarr-components.md",
} as const;
for (const component of [first, last]) {
const reference = generated[packagePath[component.package]];
const homarrComponents = customJsxAuthoringCatalog.components.filter(
(component) => component.package === "@homarr/widgets",
);
for (const component of homarrComponents) {
const reference = generated["homarr-components.md"];
expect(reference).toContain(`<a id="${getComponentReferenceAnchor(component.name)}"></a>`);
expect(reference).toContain(`### \`${component.name}\``);
for (const prop of component.props) {
@@ -70,6 +60,9 @@ describe("generated Custom Widget component references", () => {
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("schema.md");
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("runtime.md");
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("security.md");
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("mantine-core.md");
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("mantine-dates.md");
expect(GENERATED_COMPONENT_REFERENCE_PATHS).not.toContain("mantine-charts.md");
});
});
@@ -4,7 +4,12 @@ import { resolve } from "node:path";
import { describe, expect, test } from "vitest";
import { CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL } from "../core/ai-prompt";
import { buildCustomWidgetAiPromptWithEmbeddedSkill, CUSTOM_WIDGET_SKILL_FILES } from "../core/embedded-ai-prompt";
import { CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION } from "../core/ai-prompt";
import {
buildCustomWidgetAiPromptWithEmbeddedSkill,
CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT,
CUSTOM_WIDGET_SKILL_FILES,
} from "../core/embedded-ai-prompt";
describe("buildCustomWidgetAiPromptWithEmbeddedSkill", () => {
test("stays behind dedicated package exports instead of the core barrel", async () => {
@@ -25,7 +30,7 @@ describe("buildCustomWidgetAiPromptWithEmbeddedSkill", () => {
expect(coreIndexSource).not.toContain('export * from "./embedded-ai-prompt"');
});
test("embeds every generated skill file without duplicating bulk resources", () => {
test("embeds the complete release-matched offline authoring bundle", () => {
const prompt = buildCustomWidgetAiPromptWithEmbeddedSkill(
undefined,
undefined,
@@ -34,20 +39,24 @@ describe("buildCustomWidgetAiPromptWithEmbeddedSkill", () => {
);
expect(prompt.startsWith("Please create this Homarr Custom JSX v2 widget:\n\nCreate a status widget")).toBe(true);
expect(prompt).toContain("Use the complete release-matched offline bundle below.");
expect(prompt).toContain("# Homarr Custom Widget");
expect(prompt).toContain("## Authoring workflow");
for (const file of CUSTOM_WIDGET_SKILL_FILES) {
expect(prompt).toContain("This clipboard workflow has no Homarr MCP tools, repository access, or local files.");
expect(prompt).toContain(CUSTOM_WIDGET_OFFLINE_BUNDLE_CONTENT);
for (const file of CUSTOM_WIDGET_SKILL_FILES.filter(
({ path }) => !["references/component-catalog.json", "references/examples.json"].includes(path),
)) {
expect(prompt).toContain(`--- BEGIN SKILL FILE: ${file.path} ---`);
expect(prompt).toContain(file.content.trimEnd());
}
expect(prompt).not.toContain("--- BEGIN COMPACT COMPONENT CATALOG ---");
expect(prompt).not.toContain("--- BEGIN CANONICAL RUNTIME EXAMPLES ---");
expect(prompt).toContain('"name":"ActionButton"');
expect(prompt).toContain('"name":"SubFetch"');
expect(prompt).toContain("RecursiveList");
expect(prompt).toContain("const segments =");
expect(prompt).toContain("{(() => {");
expect(prompt.length).toBeGreaterThan(8_000);
expect(prompt.length).toBeLessThan(900_000);
expect(prompt).toContain("--- BEGIN CANONICAL COMPONENT CATALOG ---");
expect(prompt).toContain("--- BEGIN CANONICAL RUNTIME EXAMPLES ---");
expect(prompt.lastIndexOf(CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION)).toBeGreaterThan(
prompt.indexOf("# Homarr Custom Widget offline authoring bundle"),
);
expect(prompt.length).toBeGreaterThan(500_000);
expect(prompt.length).toBeLessThanOrEqual(1_700_000);
expect(prompt.endsWith(`${CUSTOM_WIDGET_OFFLINE_BUNDLE_SENTINEL}\nCharacters: ${prompt.length}`)).toBe(true);
});
@@ -58,10 +67,11 @@ describe("buildCustomWidgetAiPromptWithEmbeddedSkill", () => {
{ template: "<Text>Large</Text>".repeat(2_000) },
"Repair this widget",
);
const beforeBundle = prompt.slice(0, prompt.indexOf("Use the complete release-matched offline bundle below."));
const beforeBundle = prompt.slice(0, prompt.indexOf("This clipboard workflow has no Homarr MCP tools"));
expect(beforeBundle.match(/```/gu)?.length ?? 0).toBe(4);
expect(beforeBundle).toContain("Homarr will validate the result after it is pasted into the workbench.");
expect(prompt).toContain("--- BEGIN SKILL FILE: SKILL.md ---");
expect(prompt).toContain("# Homarr Custom Widget offline authoring bundle");
expect(prompt.length).toBeLessThanOrEqual(1_700_000);
});
});
@@ -11,6 +11,27 @@ const components = { Text: () => null };
const bindings = { data: Object.create(null) as Record<string, unknown> };
describe("shared Custom JSX policy", () => {
test.each(['status.list === "loading"', '"success" === status.list', 'status.list !== "error"'])(
"rejects string request-status comparisons in %s",
(expression) => {
expect(validateCustomJsxTemplate(`<Text>{${expression}}</Text>`)).toEqual(
expect.arrayContaining([
expect.objectContaining({
severity: "error",
message: expect.stringContaining("INVALID_STATUS_COMPARISON: status.list is an object"),
}),
]),
);
},
);
test("accepts request-status object fields", () => {
const diagnostics = validateCustomJsxTemplate(
"<Text>{status.list?.loading ? 'Loading' : status.list?.ok === false ? status.list.error : 'Ready'}</Text>",
);
expect(diagnostics.filter(({ severity }) => severity === "error")).toEqual([]);
});
test("accepts canonical Mantine compound component names", () => {
const diagnostics = validateCustomJsxTemplate(
'<Radio.Group value="one"><Radio.Card value="one"><Radio.Indicator /></Radio.Card></Radio.Group>',
@@ -288,6 +309,52 @@ describe("shared Custom JSX policy", () => {
expect(renderToStaticMarkup(rendered.node)).not.toContain("Mew");
});
test.each([
["callback return", "{data.items.map((item) => Number)}"],
["safe-block return", "{data.items.map((item) => { const value = item; return Math.round; })}"],
["conditional local", "{data.items.map((item) => { const value = true ? Math.round : item; return value; })}"],
["IIFE return", "{(() => { const value = 1; return Number; })()}"],
])("rejects callable values escaping an authored %s", (_name, template) => {
expect(validateCustomJsxTemplate(template)).toEqual(
expect.arrayContaining([
expect.objectContaining({ message: expect.stringContaining("CALLBACK_VALUE_NOT_ALLOWED") }),
]),
);
expect(() => renderSafeJsx({ template, components, bindings: createCustomJsxBindings({ items: [1] }) })).toThrow(
"CALLBACK_VALUE_NOT_ALLOWED",
);
});
test("keeps direct documented safe helper callbacks available", () => {
const template = '<Text>{data.items.map(Number).join(",")}</Text>';
expect(validateCustomJsxTemplate(template).filter(({ severity }) => severity === "error")).toEqual([]);
expect(() =>
renderSafeJsx({ template, components, bindings: createCustomJsxBindings({ items: ["1", "2"] }) }),
).not.toThrow();
});
test.each([
["expression body", "{(() => <Text>value</Text>)()}", "BLOCK_REQUIRES_FINAL_RETURN"],
["optional call", "{(() => { const value = 1; return <Text>{value}</Text>; })?.()}", "CALL_TARGET_NOT_ALLOWED"],
])("rejects unsupported derived-value IIFE form: %s", (_name, template, code) => {
expect(validateCustomJsxTemplate(template)).toEqual(
expect.arrayContaining([expect.objectContaining({ message: expect.stringContaining(code) })]),
);
expect(() => renderSafeJsx({ template, components, bindings })).toThrow();
});
test("normalizes duplicate callback parameter parse diagnostics", () => {
const template = "{data.items.map((item, item) => item)}";
expect(validateCustomJsxTemplate(template)).toEqual(
expect.arrayContaining([
expect.objectContaining({ message: expect.stringContaining("DUPLICATE_LOCAL_BINDING") }),
]),
);
expect(() => renderSafeJsx({ template, components, bindings: { data: { items: [1] } } })).toThrow(
"DUPLICATE_LOCAL_BINDING",
);
});
test.each([
[
"let mutation",
@@ -32,6 +32,9 @@ describe("RecursiveList", () => {
const html = renderToStaticMarkup(createElement(MantineProvider, null, rendered.node));
expect(html).toContain("0: LEVEL-0");
expect(html).toContain("7: LEVEL-7");
expect(html).toContain('role="tree"');
expect(html).toContain('role="treeitem"');
expect(html).toContain('aria-expanded="true"');
});
test("contains malformed children, cycles, depth limits, and node limits", () => {
@@ -158,6 +161,39 @@ describe("RecursiveList", () => {
).toEqual(
expect.arrayContaining([expect.objectContaining({ message: expect.stringContaining("INVALID_PROP_VALUE") })]),
);
expect(
validateCustomJsxTemplate(
'<RecursiveList data={data.tree} childrenPath="children" keyPath="name" maxNodes={1.5}>{(node) => node.name}</RecursiveList>',
),
).toEqual(
expect.arrayContaining([expect.objectContaining({ message: expect.stringContaining("INVALID_PROP_VALUE") })]),
);
});
test("uses namespaced primitive keys and stable path fallbacks", () => {
const warnings = new Set<string>();
const nodes = buildTrustedRecursiveList({
data: [{ id: 1 }, { id: "1" }, { id: true }, { id: "duplicate" }, { id: "duplicate" }, {}],
childrenPath: "children",
keyPath: "id",
warnings,
budget: new Budget(DEFAULT_BUDGETS),
render: () => null,
});
expect(nodes.map(({ value }) => value)).toEqual([
"key:number:1",
"key:string:1",
"key:boolean:true",
"key:string:duplicate",
"path:4",
"path:5",
]);
expect([...warnings]).toEqual(
expect.arrayContaining([
expect.stringContaining("RECURSIVE_LIST_DUPLICATE_KEY"),
expect.stringContaining("RECURSIVE_LIST_MISSING_KEY"),
]),
);
});
test("contains ordinary branch errors even when their text resembles a budget failure", () => {
@@ -203,7 +239,7 @@ describe("RecursiveList", () => {
);
});
test("resets its contained render error when a corrected node model arrives", async () => {
test("contains a branch render error and resets it when a corrected node model arrives", async () => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
window.matchMedia = vi.fn().mockImplementation(() => ({
matches: false,
@@ -226,11 +262,17 @@ describe("RecursiveList", () => {
await act(async () => {
root.render(
<MantineProvider>
<TrustedRecursiveList nodes={[{ value: "broken", label: <BrokenLabel /> }]} />
<TrustedRecursiveList
nodes={[
{ value: "broken", label: <BrokenLabel /> },
{ value: "healthy", label: "Healthy sibling" },
]}
/>
</MantineProvider>,
);
});
expect(host.textContent).toContain("RECURSIVE_LIST_RENDER_ERROR");
expect(host.textContent).toContain("RECURSIVE_LIST_BRANCH_RENDER_ERROR");
expect(host.textContent).toContain("Healthy sibling");
await act(async () => {
root.render(
@@ -326,7 +326,10 @@ describe("Custom Widget runtime ports", () => {
const port = createPort({
executeAction: vi.fn(async () => ({ ok: false, status: 500, data: null, error: "Nope" })),
});
await render(<ToggleSwitch requestId="toggle" onParams={{ enabled: true }} offParams={{ enabled: false }} />, port);
await render(
<ToggleSwitch requestId="toggle" enabledParams={{ enabled: true }} disabledParams={{ enabled: false }} />,
port,
);
const input = host.querySelector("input") as HTMLInputElement;
await act(async () => {
input.click();
@@ -340,7 +343,7 @@ describe("Custom Widget runtime ports", () => {
it("confirms a DELETE toggle before executing it", async () => {
const port = createPort();
await render(
<ToggleSwitch requestId="delete-toggle" onParams={{ enabled: true }} offParams={{ enabled: false }} />,
<ToggleSwitch requestId="delete-toggle" enabledParams={{ enabled: true }} disabledParams={{ enabled: false }} />,
port,
[
{
@@ -19,7 +19,11 @@ import {
getCustomWidgetOptionsJsonSchema,
getCustomWidgetRequestsJsonSchema,
} from "../core/schema-references";
import { getCustomJsxComponentPropCompletions, getCustomJsxLocalConstCompletions } from "../workbench/code-language";
import {
customJsxSafeBlockCompletions,
getCustomJsxComponentPropCompletions,
getCustomJsxLocalConstCompletions,
} from "../workbench/code-language";
describe("Custom Widget workbench contracts", () => {
it("always provides a valid starter template", () => {
@@ -108,6 +112,17 @@ describe("Custom Widget workbench contracts", () => {
expect(labels).not.toContain("future");
});
it("completes callback parameters and publishes safe-block snippets", () => {
const source = `{data.items.map((item, index, collection) => {
const value = item;
return <Text>{value}</Text>;
})}`;
const cursor = source.indexOf("return <Text>");
const labels = getCustomJsxLocalConstCompletions(source, cursor).map(({ label }) => label);
expect(labels).toEqual(expect.arrayContaining(["item", "index", "collection", "value"]));
expect(customJsxSafeBlockCompletions.map(({ label }) => label)).toEqual(["map block", "derived value IIFE"]);
});
it("uses canonical component prop types for contextual JSX completions", () => {
const textInput = getCustomJsxComponentPropCompletions("TextInput");
expect(textInput).toEqual(
@@ -130,7 +130,11 @@ export function CustomWidgetCodeEditor(props: CustomWidgetCodeEditorProps) {
/>
{props.reference && (
<Collapse expanded={referenceOpened}>
<CustomWidgetSchemaReference reference={props.reference} messages={props.messages} />
<CustomWidgetSchemaReference
id={`${props.id}-schema-reference`}
reference={props.reference}
messages={props.messages}
/>
</Collapse>
)}
<div className={classes.viewport}>
@@ -201,9 +205,11 @@ export function ReadOnlyCustomWidgetCode(props: Omit<CustomWidgetCodeEditorProps
}
export function CustomWidgetSchemaReference({
id,
reference,
messages,
}: {
id: string;
reference: CustomWidgetSchemaReferenceData;
messages: CustomWidgetEditorMessages;
}) {
@@ -219,7 +225,7 @@ export function CustomWidgetSchemaReference({
{Object.entries(values).map(([key, value]) => (
<Tabs.Panel key={key} value={key} pt="xs">
<ReadOnlyCustomWidgetCode
id={`schema-reference-${key}`}
id={`${id}-${key}`}
label={labels[key as keyof typeof labels]}
language="json"
value={JSON.stringify(value, null, 2)}
@@ -9,6 +9,7 @@ import {
getCustomJsxComponentProps,
} from "../core/component-catalog";
import { customJsxTablerIconNames } from "../core/tabler-icons";
import { ROOT_BINDINGS } from "../jsx/analyzer-language";
const enabledCatalogComponents = customJsxAuthoringCatalog.components.filter(
(component) => component.safety !== "denied",
@@ -40,7 +41,7 @@ const iconCompletions: Completion[] = customJsxTablerIconNames.map((name) => ({
detail: "Safe Tabler icon",
}));
const safeBlockCompletions: Completion[] = [
export const customJsxSafeBlockCompletions: Completion[] = [
snippetCompletion("map((item) => {\n\tconst value = ${};\n\treturn ${};\n})", {
label: "map block",
detail: "Safe immutable collection callback",
@@ -53,6 +54,12 @@ const safeBlockCompletions: Completion[] = [
}),
];
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;
@@ -63,6 +70,18 @@ export function getCustomJsxLocalConstCompletions(source: string, cursor: number
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;
@@ -97,7 +116,13 @@ export const createCustomJsxCompletionSource =
: componentCompletions;
return {
from: word?.from ?? context.pos,
options: [...localCompletions, ...safeBlockCompletions, ...contextualCompletions, ...additional],
options: [
...localCompletions,
...customJsxSafeBlockCompletions,
...rootBindingCompletions,
...contextualCompletions,
...additional,
],
};
};