fix(custom-widgets): finish v2 hardening
This commit is contained in:
97 files changed
+2833
-12393
No files matched your search
@@ -86,10 +86,12 @@ Use the interactive API reference to inspect the exact request body for each end
|
||||
|
||||
## Get Custom Widget authoring resources
|
||||
|
||||
Custom JSX v2 provides two HTTP discovery endpoints:
|
||||
Custom JSX v2 provides four HTTP discovery endpoints:
|
||||
|
||||
- `GET /api/custom-widgets/authoring-prompt` returns the current authoring prompt and live resource identifiers.
|
||||
- `GET /api/custom-widgets/skill` returns information about the Agent Skill.
|
||||
- `GET /api/custom-widgets/authoring-prompt` returns the current prompt plus MCP and HTTP resource identifiers.
|
||||
- `GET /api/custom-widgets/schema` returns the canonical widget JSON Schema.
|
||||
- `GET /api/custom-widgets/components` returns the release-matched static component catalog.
|
||||
- `GET /api/custom-widgets/skill` returns the complete Agent Skill files, catalog, examples, and skills.sh metadata.
|
||||
|
||||
Call `customWidget_secretRequestUser` to create a temporary credential entry URL. Do not construct or save this URL.
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widge
|
||||
|
||||
The portable skill gives authoring instructions that do not require a tool. The Homarr MCP prompt gives instructions for a connected workflow.
|
||||
|
||||
The offline copy prompt includes the complete portable skill and all eight release-matched references. Those references contain the generated component APIs and runtime examples, so Homarr does not append duplicate raw catalog data. A model can author directly from this bundle without MCP tools or repository access.
|
||||
The offline copy prompt includes the complete portable skill and all eleven release-matched references, including the canonical widget JSON Schema, minified component catalog, and canonical runtime examples. A model can author directly from this bundle without MCP tools or repository access.
|
||||
|
||||
The prompt starts with the user's widget request. It ends with:
|
||||
|
||||
@@ -39,23 +39,28 @@ Repository code cannot give this attribution.
|
||||
|
||||
- Prompt: `homarr-custom-widget-author`
|
||||
- Resources: `homarr://custom-widgets/schema`, `components`, `components/{name}`, `examples/{name}`, and `skill`
|
||||
- HTTP: `GET /api/custom-widgets/authoring-prompt` and `GET /api/custom-widgets/skill`
|
||||
- HTTP: `GET /api/custom-widgets/authoring-prompt`, `schema`, `components`, and `skill`
|
||||
|
||||
The authoring-prompt tool description contains one sentence. The prompt contains the workflow instructions and resource links.
|
||||
|
||||
`GET /api/custom-widgets/skill`, the MCP tool, and the MCP resource return the live `SKILL.md` with:
|
||||
`GET /api/custom-widgets/skill` and the MCP tool return the complete release-matched skill discovery payload:
|
||||
|
||||
```ts
|
||||
{
|
||||
name: "homarr-custom-widget";
|
||||
version: string;
|
||||
skillMd: string;
|
||||
files: Array<{ path: string; content: string }>;
|
||||
componentCatalog: CustomJsxAuthoringCatalog;
|
||||
examples: CustomJsxExample[];
|
||||
skillsShUrl: string;
|
||||
sourceUrl: string;
|
||||
installCommand: string;
|
||||
}
|
||||
```
|
||||
|
||||
The `homarr://custom-widgets/skill` MCP resource returns the same material as one plain-text offline bundle, ending with the truncation sentinel and exact character count.
|
||||
|
||||
These interfaces do not return an archive URL or archive hash.
|
||||
|
||||
## Create a Custom Widget with MCP
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
# Create a Custom Widget
|
||||
|
||||
import { CanonicalCustomWidgetExample } from "@site/src/components/custom-widget-code";
|
||||
import { CanonicalCustomWidgetExample, CustomWidgetCodeExample } from "@site/src/components/custom-widget-code";
|
||||
|
||||
export const explicitOptionsBindingExample = `{
|
||||
"pathTemplate": "/api/endpoints/{endpointId}/docker/containers/json",
|
||||
"parameters": { "endpointId": "string", "showAll": "boolean" },
|
||||
"queryTemplate": { "all": { "$param": "showAll" } },
|
||||
"optionsBinding": {
|
||||
"endpointId": { "$option": "endpointId" },
|
||||
"showAll": false
|
||||
}
|
||||
}`;
|
||||
|
||||
The desktop workbench shows the code and preview next to each other. On a mobile device, use the Configure and Preview tabs.
|
||||
|
||||
@@ -68,10 +78,12 @@ The standard prompt contains fewer than 8,000 characters. It includes the instal
|
||||
|
||||
It does not include a complete prop list, MCP workflow, server URL, or credentials. The prompt with the embedded skill is intentionally longer. It starts with your widget request, then includes:
|
||||
|
||||
- `SKILL.md` and all eight release-matched reference files
|
||||
- `SKILL.md` and all eleven release-matched reference files, including the canonical widget JSON Schema
|
||||
- The Custom Widget, Mantine, skill, and catalog-schema versions
|
||||
- The compact canonical component catalog
|
||||
- Canonical runtime examples
|
||||
|
||||
The generated reference files already contain the exact component and prop APIs. Homarr does not append a second raw catalog or a duplicate examples payload.
|
||||
The generated Markdown references remain readable offline. The compact JSON catalog gives tools the identical machine-readable component records used by Homarr.
|
||||
|
||||
The embedded prompt ends with this sentinel and an exact total character count:
|
||||
|
||||
@@ -101,7 +113,7 @@ Widget options use a restricted object JSON Schema. Homarr supports the followin
|
||||
- URL
|
||||
- Nested group
|
||||
- Conditional field
|
||||
- Advanced JSON
|
||||
- JSON value
|
||||
|
||||
Credentials are not widget options. Homarr rejects credential names and static credential values in widget options.
|
||||
|
||||
@@ -121,17 +133,12 @@ A parameter declaration does not give a value to the parameter. A matching widge
|
||||
|
||||
For a load query, bind each parameter in `optionsBinding`. Use an option reference or a type-compatible primitive literal:
|
||||
|
||||
```json
|
||||
{
|
||||
"pathTemplate": "/api/endpoints/{endpointId}/docker/containers/json",
|
||||
"parameters": { "endpointId": "string", "showAll": "boolean" },
|
||||
"queryTemplate": { "all": { "$param": "showAll" } },
|
||||
"optionsBinding": {
|
||||
"endpointId": { "$option": "endpointId" },
|
||||
"showAll": false
|
||||
}
|
||||
}
|
||||
```
|
||||
<CustomWidgetCodeExample
|
||||
id="explicit-options-binding"
|
||||
label="Explicit load-query option bindings"
|
||||
language="json"
|
||||
code={explicitOptionsBindingExample}
|
||||
/>
|
||||
|
||||
For a manual query or action, supply all parameters with the component `params` prop. Use `SubFetch`, `ActionButton`, or `ToggleSwitch`.
|
||||
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
# Use the Custom JSX runtime
|
||||
|
||||
import { CustomJsxComponentReference } from "@site/src/components/custom-jsx-component-reference";
|
||||
import { CustomWidgetCodeExample } from "@site/src/components/custom-widget-code";
|
||||
|
||||
Homarr interprets declarative JSX in the error boundary of the widget. A template cannot import a module or run arbitrary JavaScript.
|
||||
|
||||
## Use data roots
|
||||
|
||||
```jsx
|
||||
<Stack>
|
||||
export const dataRootsExample = `<Stack>
|
||||
<TextInput bind="search" label="Search TV shows" />
|
||||
<SubFetch requestId="search-series" params={{ query: inputs.search }} />
|
||||
{data["search-series"]?.map((series) => (
|
||||
@@ -18,14 +14,87 @@ Homarr interprets declarative JSX in the error boundary of the widget. A templat
|
||||
</ActionButton>
|
||||
</Group>
|
||||
))}
|
||||
</Stack>`;
|
||||
|
||||
export const localBindingExample = `{data.pokemon.map((pokemon) => {
|
||||
const segments = pokemon.url.split("/").filter((part) => part);
|
||||
const dexId = segments.at(-1);
|
||||
const isSelected = inputs.selectedPokemon === pokemon.name;
|
||||
|
||||
return (
|
||||
|
||||
<Card key={dexId} withBorder={isSelected}>
|
||||
<Text>#{dexId}</Text>
|
||||
<Text tt="capitalize">{pokemon.name}</Text>
|
||||
</Card>
|
||||
);
|
||||
})}`;
|
||||
|
||||
export const derivedValueExample = `{(() => {
|
||||
const visiblePokemon = data.pokemon.filter(
|
||||
(pokemon) => options.types.length === 0 || options.types.includes(pokemon.type),
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
<Stack>
|
||||
{visiblePokemon.map((pokemon) => (
|
||||
<Text>{pokemon.name}</Text>
|
||||
))}
|
||||
</Stack>
|
||||
```
|
||||
);
|
||||
})()}`;
|
||||
|
||||
export const recursiveListExample = `<RecursiveList
|
||||
data={data.evolution.chain}
|
||||
childrenPath="evolves_to"
|
||||
keyPath="species.name"
|
||||
defaultExpandedDepth={4}
|
||||
maxDepth={16}
|
||||
showLines
|
||||
>
|
||||
{(node, meta) => {
|
||||
const segments = node.species.url.split("/").filter((part) => part);
|
||||
const dexId = segments.at(-1);
|
||||
|
||||
return (
|
||||
<Group gap="xs">
|
||||
<Badge variant="light">#{dexId}</Badge>
|
||||
<Text tt="capitalize" fw={600}>
|
||||
{node.species.name}
|
||||
</Text>
|
||||
{meta.hasChildren && <Text c="dimmed">{meta.childCount} evolutions</Text>}
|
||||
</Group>
|
||||
);
|
||||
|
||||
}}
|
||||
|
||||
</RecursiveList>`;
|
||||
|
||||
export const temporaryInputsExample = `<TextInput bind="search" defaultValue="" />
|
||||
<DatePicker bind="selectedDate" />
|
||||
<Switch bind="enabled" defaultChecked={false} />
|
||||
<MultiSelect bind="selectedEntities" data={options.entities} />
|
||||
<SubFetch requestId="search" params={{ query: inputs.search }} />`;
|
||||
|
||||
Homarr interprets declarative JSX in the error boundary of the widget. A template cannot import a module or run arbitrary JavaScript.
|
||||
|
||||
## Use data roots
|
||||
|
||||
<CustomWidgetCodeExample
|
||||
id="custom-jsx-data-roots"
|
||||
label="Data roots and manual requests"
|
||||
language="jsx"
|
||||
code={dataRootsExample}
|
||||
/>
|
||||
|
||||
- `data.<requestId>` contains sanitized JSON or text results.
|
||||
- `status.<requestId>` contains the request status.
|
||||
- `status.<requestId>` contains `{ loading, ok, status, statusText, error }`.
|
||||
- `options` contains the validated board item configuration.
|
||||
- `inputs` contains temporary values from controls that use `bind`.
|
||||
|
||||
Check `status.list?.loading` while loading, `status.list?.ok === false` on failure, and `status.list?.ok === true` on success. Do not compare `status.list` with `"loading"`, `"success"`, or `"error"`; the status is an object, and validation rejects those comparisons.
|
||||
|
||||
Load queries get data automatically. They run at the widget refresh interval.
|
||||
|
||||
`SubFetch` runs a manual query. `ActionButton` and `ToggleSwitch` run actions.
|
||||
@@ -73,44 +142,23 @@ The explorer fetches only the plain, versioned static catalog. It does not impor
|
||||
|
||||
A collection callback can use a restricted block when the returned JSX needs the same derived value more than once:
|
||||
|
||||
```jsx
|
||||
{
|
||||
data.pokemon.map((pokemon) => {
|
||||
const segments = pokemon.url.split("/").filter((part) => part);
|
||||
const dexId = segments.at(-1);
|
||||
const isSelected = inputs.selectedPokemon === pokemon.name;
|
||||
|
||||
return (
|
||||
<Card key={dexId} withBorder={isSelected}>
|
||||
<Text>#{dexId}</Text>
|
||||
<Text tt="capitalize">{pokemon.name}</Text>
|
||||
</Card>
|
||||
);
|
||||
});
|
||||
}
|
||||
```
|
||||
<CustomWidgetCodeExample
|
||||
id="custom-jsx-local-bindings"
|
||||
label="Immutable local bindings"
|
||||
language="jsx"
|
||||
code={localBindingExample}
|
||||
/>
|
||||
|
||||
The block must contain one or more `const` declarations followed by exactly one final `return`. A declaration uses one simple identifier and a required initializer. An earlier local can be used by later declarations and the final JSX.
|
||||
|
||||
For one page-level derived value, directly invoke a zero-argument inline arrow:
|
||||
|
||||
```jsx
|
||||
{
|
||||
(() => {
|
||||
const visiblePokemon = data.pokemon.filter(
|
||||
(pokemon) => options.types.length === 0 || options.types.includes(pokemon.type),
|
||||
);
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
{visiblePokemon.map((pokemon) => (
|
||||
<Text>{pokemon.name}</Text>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
})();
|
||||
}
|
||||
```
|
||||
<CustomWidgetCodeExample
|
||||
id="custom-jsx-derived-iife"
|
||||
label="Page-level derived value"
|
||||
language="jsx"
|
||||
code={derivedValueExample}
|
||||
/>
|
||||
|
||||
This is not general JavaScript execution. The runtime rejects:
|
||||
|
||||
@@ -130,31 +178,13 @@ Relevant diagnostics include `INVALID_LOCAL_DECLARATION`, `LOCAL_BINDING_REQUIRE
|
||||
|
||||
Use the trusted `RecursiveList` special form for evolution chains, directory trees, nested comments, and other unknown-depth data. Do not write an authored recursive function or pass Mantine a render callback.
|
||||
|
||||
```jsx
|
||||
<RecursiveList
|
||||
data={data.evolution.chain}
|
||||
childrenPath="evolves_to"
|
||||
keyPath="species.name"
|
||||
defaultExpandedDepth={4}
|
||||
maxDepth={16}
|
||||
showLines
|
||||
>
|
||||
{(node, meta) => {
|
||||
const segments = node.species.url.split("/").filter((part) => part);
|
||||
const dexId = segments.at(-1);
|
||||
|
||||
return (
|
||||
<Group gap="xs">
|
||||
<Badge variant="light">#{dexId}</Badge>
|
||||
<Text tt="capitalize" fw={600}>
|
||||
{node.species.name}
|
||||
</Text>
|
||||
{meta.hasChildren && <Text c="dimmed">{meta.childCount} evolutions</Text>}
|
||||
</Group>
|
||||
);
|
||||
}}
|
||||
</RecursiveList>
|
||||
```
|
||||
<CustomWidgetCodeExample
|
||||
id="custom-jsx-recursive-list"
|
||||
label="Trusted recursive list"
|
||||
language="jsx"
|
||||
code={recursiveListExample}
|
||||
height="420px"
|
||||
/>
|
||||
|
||||
The child template receives the current `node` and this metadata:
|
||||
|
||||
@@ -180,13 +210,12 @@ Homarr detects cycles per ancestor chain. A malformed branch, render failure, or
|
||||
|
||||
Bind a control to a literal name. Read its value from `inputs`:
|
||||
|
||||
```jsx
|
||||
<TextInput bind="search" defaultValue="" />
|
||||
<DatePicker bind="selectedDate" />
|
||||
<Switch bind="enabled" defaultChecked={false} />
|
||||
<MultiSelect bind="selectedEntities" data={options.entities} />
|
||||
<SubFetch requestId="search" params={{ query: inputs.search }} />
|
||||
```
|
||||
<CustomWidgetCodeExample
|
||||
id="custom-jsx-temporary-inputs"
|
||||
label="Temporary inputs"
|
||||
language="jsx"
|
||||
code={temporaryInputsExample}
|
||||
/>
|
||||
|
||||
These values exist in React memory while the widget is mounted. Homarr does not save them in any storage location.
|
||||
|
||||
|
||||
@@ -193,6 +193,8 @@ Discovery resources:
|
||||
- `homarr://custom-widgets/examples/{name}`
|
||||
- `homarr://custom-widgets/skill`
|
||||
|
||||
An HTTP-only harness can use the matching `/api/custom-widgets/authoring-prompt`, `/schema`, `/components`, and `/skill` endpoints instead of MCP resource URIs.
|
||||
|
||||
The Custom Widget tools are:
|
||||
|
||||
- `customWidget_schema`
|
||||
|
||||
@@ -9,6 +9,10 @@ self-hosted Homarr instance.
|
||||
Workshop validates widget JSON in the browser before publishing. Homarr validates it again before installation. Widget
|
||||
exports must not contain credentials; users configure required credentials only after importing a widget.
|
||||
|
||||
Each submission stores the manifest's `$schema` value as separate compatibility metadata. Workshop marks the current
|
||||
Custom JSX schema and unsupported schemas in listings, while Homarr blocks installation if this metadata disagrees with
|
||||
the downloaded manifest. The manifest remains the source of truth and is always validated again locally.
|
||||
|
||||
Votes and reports are unique per user and submission. Listings expose vote totals without exposing voter identities.
|
||||
Reports include a category and explanation. Administrators can see the reporter, dismiss the report, or delete the
|
||||
reported submission.
|
||||
@@ -40,10 +44,12 @@ The central Workshop PocketBase service controls authentication. Register this c
|
||||
https://<workshop-host>/api/oauth2-redirect
|
||||
```
|
||||
|
||||
Self-hosted Homarr origins, including localhost and custom domains, do not need separate GitHub callbacks. The Workshop
|
||||
host completes authentication in a popup and returns the result to the calling Homarr page.
|
||||
Self-hosted Homarr origins, including localhost and custom domains, do not need separate GitHub callbacks. Homarr opens
|
||||
the popup synchronously, while PocketBase completes authentication through its realtime OAuth flow on the Workshop host.
|
||||
On successful sign-in, Homarr copies the GitHub display name or login and HTTPS avatar into that user's Workshop profile.
|
||||
The collection rules let users update their own profile fields but prevent them from setting `isAdmin`.
|
||||
|
||||
PocketBase permits all origins by default. If the deployment uses `--origins` or a restrictive reverse-proxy CORS policy,
|
||||
it must permit self-hosted Homarr origins. See [PocketBase routing and CORS](https://pocketbase.io/docs/go-routing/).
|
||||
|
||||
Homarr shows a visible error when the provider is misconfigured or the popup is blocked, cancelled, or times out.
|
||||
Homarr shows a visible error when the provider is misconfigured or the popup is blocked or cancelled.
|
||||
@@ -18,7 +18,6 @@
|
||||
"write-translations": "docusaurus write-translations",
|
||||
"write-heading-ids": "docusaurus write-heading-ids",
|
||||
"api-dump-contributors": "node ./scripts/dump-contributors.mjs",
|
||||
"check:custom-widgets-ste": "node ./scripts/check-custom-widgets-ste.mjs",
|
||||
"verify:search": "node ./scripts/verify-algolia-search.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,217 +0,0 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
import { britishSpellings, imperativeVerbs, nonSteTerms, technicalTerms } from "./custom-widgets-ste-terms.mjs";
|
||||
|
||||
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
|
||||
const docsDirectory = resolve(scriptDirectory, "../docs");
|
||||
|
||||
const files = [
|
||||
{ path: "management/custom-widgets/agent-authoring.mdx" },
|
||||
{ path: "management/custom-widgets/authoring.mdx" },
|
||||
{ path: "management/custom-widgets/custom-jsx.mdx" },
|
||||
{ path: "management/custom-widgets/index.mdx" },
|
||||
{ path: "management/custom-widgets/requests-and-security.mdx" },
|
||||
{ path: "management/custom-widgets/troubleshooting.mdx" },
|
||||
{ path: "management/workshop/index.mdx" },
|
||||
{ path: "widgets/custom-api/index.mdx" },
|
||||
{ path: "management/api/index.mdx", section: "Get Custom Widget authoring resources" },
|
||||
{ path: "management/mcp.mdx", section: "Create a Custom Widget with an AI agent", includeMatching: /Custom Widget/ },
|
||||
{ path: "advanced/environment-variables/index.mdx", includeMatching: /WORKSHOP_API_URL/ },
|
||||
{ path: "community/faq.mdx", section: "Can I add my own widgets? Do I need programming skills?" },
|
||||
{ path: "management/backup.mdx", includeMatching: /Custom Widget/ },
|
||||
];
|
||||
|
||||
const imperativeSet = new Set(imperativeVerbs);
|
||||
const issues = [];
|
||||
|
||||
const overview = await readFile(resolve(docsDirectory, "management/custom-widgets/index.mdx"), "utf8");
|
||||
if (!overview.includes("## Audience and prerequisites")) {
|
||||
addIssue("management/custom-widgets/index.mdx", 1, "Add the required audience and prerequisites section.");
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const absolutePath = resolve(docsDirectory, file.path);
|
||||
const source = await readFile(absolutePath, "utf8");
|
||||
const selectedLines = selectLines(source, file);
|
||||
const paragraphs = getProseParagraphs(selectedLines);
|
||||
|
||||
for (const paragraph of paragraphs) {
|
||||
const sentences = splitSentences(paragraph.text);
|
||||
if (sentences.length > 6) {
|
||||
addIssue(file.path, paragraph.line, `Paragraph has ${sentences.length} sentences. The limit is 6.`);
|
||||
}
|
||||
|
||||
for (const sentence of sentences) {
|
||||
const wordCount = countWords(sentence);
|
||||
const isProcedure = paragraph.isList || startsWithImperative(sentence);
|
||||
const limit = isProcedure ? 20 : 25;
|
||||
if (wordCount > limit) {
|
||||
const type = isProcedure ? "Procedural" : "Descriptive";
|
||||
addIssue(file.path, paragraph.line, `${type} sentence has ${wordCount} words. The limit is ${limit}.`);
|
||||
}
|
||||
}
|
||||
|
||||
checkTerms(file.path, paragraph.line, paragraph.text);
|
||||
}
|
||||
}
|
||||
|
||||
if (issues.length > 0) {
|
||||
console.error("Custom Widget STE check failed:\n");
|
||||
for (const issue of issues) console.error(`- ${issue}`);
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
console.log(`Custom Widget STE check passed. ${technicalTerms.length} technical terms are registered.`);
|
||||
}
|
||||
|
||||
function selectLines(source, file) {
|
||||
const lines = source.split("\n").map((text, index) => ({ text, line: index + 1 }));
|
||||
if (!file.section && !file.includeMatching) return lines;
|
||||
|
||||
const selected = [];
|
||||
if (file.section) {
|
||||
const start = lines.findIndex(({ text }) => text.trim().replace(/^#{2,6}\s+/, "") === file.section);
|
||||
if (start === -1) throw new Error(`Section '${file.section}' was not found in ${file.path}`);
|
||||
const headingLevel = lines[start].text.trim().match(/^#+/)?.[0].length ?? 2;
|
||||
|
||||
for (let index = start; index < lines.length; index += 1) {
|
||||
const nextHeadingLevel = lines[index].text.trim().match(/^#+(?=\s)/)?.[0].length;
|
||||
if (index > start && nextHeadingLevel && nextHeadingLevel <= headingLevel) break;
|
||||
selected.push(lines[index]);
|
||||
}
|
||||
}
|
||||
|
||||
if (file.includeMatching) {
|
||||
for (const line of lines) {
|
||||
if (file.includeMatching.test(line.text) && !selected.some((item) => item.line === line.line))
|
||||
selected.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
return selected.toSorted((left, right) => left.line - right.line);
|
||||
}
|
||||
|
||||
function getProseParagraphs(lines) {
|
||||
const paragraphs = [];
|
||||
let paragraph = null;
|
||||
let inFence = false;
|
||||
let inFrontmatter = false;
|
||||
let inTemplateExport = false;
|
||||
let inJsxTag = false;
|
||||
|
||||
const flush = () => {
|
||||
if (paragraph?.text.trim()) paragraphs.push({ ...paragraph, text: paragraph.text.trim() });
|
||||
paragraph = null;
|
||||
};
|
||||
|
||||
for (const { text: originalText, line } of lines) {
|
||||
const trimmed = originalText.trim();
|
||||
|
||||
if (line === 1 && trimmed === "---") {
|
||||
inFrontmatter = true;
|
||||
continue;
|
||||
}
|
||||
if (inFrontmatter && trimmed === "---") {
|
||||
inFrontmatter = false;
|
||||
continue;
|
||||
}
|
||||
if (trimmed.startsWith("```")) {
|
||||
flush();
|
||||
inFence = !inFence;
|
||||
continue;
|
||||
}
|
||||
if (inFence) continue;
|
||||
|
||||
if (/^export const .*?=\s*`/.test(trimmed)) inTemplateExport = true;
|
||||
if (inTemplateExport) {
|
||||
if (/`;\s*$/.test(trimmed)) inTemplateExport = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^(import|export)\s/.test(trimmed)) continue;
|
||||
if (trimmed.startsWith("<")) inJsxTag = true;
|
||||
if (inJsxTag) {
|
||||
if (trimmed.includes(">")) inJsxTag = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
let text = trimmed;
|
||||
if (inFrontmatter) {
|
||||
const match = text.match(/^(title|description|sidebar_label):\s*["']?(.*?)["']?$/);
|
||||
if (!match) continue;
|
||||
text = match[2];
|
||||
}
|
||||
|
||||
if (!text || /^\|?\s*:?-+:?/.test(text)) {
|
||||
flush();
|
||||
continue;
|
||||
}
|
||||
|
||||
const isList = /^\s*(?:[-*]|\d+\.)\s+/.test(text);
|
||||
text = cleanMarkdown(text);
|
||||
if (!text) {
|
||||
flush();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isList || text.startsWith("#") || text.startsWith("|")) flush();
|
||||
text = text
|
||||
.replace(/^#{1,6}\s+/, "")
|
||||
.replace(/^\s*(?:[-*]|\d+\.)\s+/, "")
|
||||
.replace(/^\|\s*/, "")
|
||||
.replace(/\s*\|\s*$/, "");
|
||||
|
||||
if (!paragraph) paragraph = { text, line, isList };
|
||||
else paragraph.text += ` ${text}`;
|
||||
|
||||
if (isList || trimmed.startsWith("#") || trimmed.startsWith("|")) flush();
|
||||
}
|
||||
|
||||
flush();
|
||||
return paragraphs;
|
||||
}
|
||||
|
||||
function cleanMarkdown(text) {
|
||||
return text
|
||||
.replace(/\[([^\]]+)]\([^\s)]+(?:\s+"[^"]*")?\)/g, "$1")
|
||||
.replace(/`[^`]*`/g, " ")
|
||||
.replace(/<[^>]+>/g, " ")
|
||||
.replace(/[*_~]/g, "")
|
||||
.replace(/https?:\/\/\S+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function splitSentences(text) {
|
||||
const normalized = text.replace(/\b(?:for example|such as)\b/gi, "example");
|
||||
const matches = normalized.match(/[^.!?]+[.!?]+|[^.!?]+$/g) ?? [];
|
||||
return matches.map((sentence) => sentence.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function countWords(sentence) {
|
||||
return sentence.match(/[A-Za-z0-9]+(?:[-'][A-Za-z0-9]+)*/g)?.length ?? 0;
|
||||
}
|
||||
|
||||
function startsWithImperative(sentence) {
|
||||
const firstWord = sentence.toLowerCase().match(/[a-z]+/)?.[0];
|
||||
return firstWord ? imperativeSet.has(firstWord) : false;
|
||||
}
|
||||
|
||||
function checkTerms(path, line, text) {
|
||||
const lowerText = text.toLowerCase();
|
||||
for (const spelling of britishSpellings) {
|
||||
if (new RegExp(`\\b${spelling}\\b`, "i").test(text)) {
|
||||
addIssue(path, line, `Use American English instead of '${spelling}'.`);
|
||||
}
|
||||
}
|
||||
for (const term of nonSteTerms) {
|
||||
if (new RegExp(`\\b${term}\\b`, "i").test(lowerText)) {
|
||||
addIssue(path, line, `Replace the non-STE term '${term}'.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addIssue(path, line, message) {
|
||||
issues.push(`${path}:${line} ${message}`);
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
export const technicalTerms = [
|
||||
"Homarr",
|
||||
"Custom Widget",
|
||||
"Custom JSX v2",
|
||||
"Workshop",
|
||||
"API source",
|
||||
"named request",
|
||||
"load query",
|
||||
"manual query",
|
||||
"action",
|
||||
"widget option",
|
||||
"temporary input",
|
||||
"CodeMirror",
|
||||
"Mantine",
|
||||
"PocketBase",
|
||||
"MCP",
|
||||
"JSON Schema",
|
||||
"API key",
|
||||
"network scope",
|
||||
"preview session",
|
||||
"error boundary",
|
||||
"HTTP",
|
||||
"JSON",
|
||||
"JSX",
|
||||
"React",
|
||||
"TypeScript",
|
||||
"Zod",
|
||||
"TLS",
|
||||
"DNS",
|
||||
"CORS",
|
||||
"OAuth",
|
||||
"SSRF",
|
||||
"tRPC",
|
||||
"GitHub",
|
||||
"Docker",
|
||||
"reverse proxy",
|
||||
"container networking",
|
||||
"API authentication",
|
||||
"bearer token",
|
||||
"basic authentication",
|
||||
"primitive literal",
|
||||
"prop metadata",
|
||||
"allowlist",
|
||||
"denylist",
|
||||
];
|
||||
|
||||
export const imperativeVerbs = [
|
||||
"add",
|
||||
"bind",
|
||||
"build",
|
||||
"call",
|
||||
"check",
|
||||
"configure",
|
||||
"correct",
|
||||
"create",
|
||||
"declare",
|
||||
"define",
|
||||
"delete",
|
||||
"disable",
|
||||
"download",
|
||||
"enable",
|
||||
"enter",
|
||||
"examine",
|
||||
"export",
|
||||
"get",
|
||||
"give",
|
||||
"import",
|
||||
"inspect",
|
||||
"install",
|
||||
"keep",
|
||||
"open",
|
||||
"paste",
|
||||
"read",
|
||||
"register",
|
||||
"remove",
|
||||
"repeat",
|
||||
"request",
|
||||
"run",
|
||||
"save",
|
||||
"select",
|
||||
"set",
|
||||
"start",
|
||||
"supply",
|
||||
"test",
|
||||
"use",
|
||||
"verify",
|
||||
"wait",
|
||||
"write",
|
||||
];
|
||||
|
||||
export const britishSpellings = [
|
||||
"authorise",
|
||||
"authorised",
|
||||
"behaviour",
|
||||
"cancelled",
|
||||
"centre",
|
||||
"colour",
|
||||
"customise",
|
||||
"customised",
|
||||
"initialise",
|
||||
"labelling",
|
||||
"licence",
|
||||
"organisation",
|
||||
"recognise",
|
||||
"serialise",
|
||||
"synchronise",
|
||||
"utilise",
|
||||
"visualise",
|
||||
];
|
||||
|
||||
export const nonSteTerms = [
|
||||
"easy",
|
||||
"easily",
|
||||
"genuinely",
|
||||
"leverage",
|
||||
"magic",
|
||||
"obviously",
|
||||
"seamless",
|
||||
"seamlessly",
|
||||
"simply",
|
||||
"straightforward",
|
||||
"utilize",
|
||||
"utilized",
|
||||
"wizard",
|
||||
];
|
||||
@@ -323,14 +323,6 @@
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
|
||||
.codeBlock {
|
||||
font-size: 0.75rem;
|
||||
margin: 0;
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.a11yList {
|
||||
font-size: 0.86rem;
|
||||
margin: 0 0 0.7rem;
|
||||
@@ -389,7 +381,7 @@
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.rawComponent .codeBlock {
|
||||
.rawComponent > div {
|
||||
margin-top: 0.6rem;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,48 +2,19 @@ import BrowserOnly from "@docusaurus/BrowserOnly";
|
||||
import useBaseUrl from "@docusaurus/useBaseUrl";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { buildCustomJsxComponentUsageExample } from "@homarr/custom-widgets/catalog-example";
|
||||
import type {
|
||||
CustomJsxAuthoringCatalog,
|
||||
CustomJsxComponentApi,
|
||||
CustomJsxPropDescriptor,
|
||||
} from "@homarr/custom-widgets/catalog";
|
||||
|
||||
import { CustomWidgetCodeExample } from "./custom-widget-code";
|
||||
import styles from "./custom-jsx-component-reference.module.css";
|
||||
|
||||
type ComponentSafety = "allowed" | "wrapped" | "denied";
|
||||
type ComponentPackage = "@mantine/core" | "@mantine/dates" | "@mantine/charts" | "@homarr/widgets";
|
||||
type ComponentBindingType = "string" | "number" | "boolean" | "string[]" | "number[]";
|
||||
|
||||
interface CatalogProp {
|
||||
name: string;
|
||||
typeRef: number;
|
||||
required: boolean;
|
||||
source: "global" | "component";
|
||||
literalValues?: Array<string | number | boolean | null>;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface CatalogComponent {
|
||||
name: string;
|
||||
package: ComponentPackage;
|
||||
category: string;
|
||||
safety: ComponentSafety;
|
||||
description?: string;
|
||||
documentationUrl: string;
|
||||
props: CatalogProp[];
|
||||
blockedProps: Array<{ name: string; reason: string }>;
|
||||
subcomponents: string[];
|
||||
bind?: {
|
||||
type: ComponentBindingType;
|
||||
initialProp: "defaultValue" | "defaultChecked";
|
||||
};
|
||||
accessibilityRequirements: string[];
|
||||
deniedReason?: string;
|
||||
}
|
||||
|
||||
interface ComponentCatalog {
|
||||
schemaVersion: number;
|
||||
mantineVersion: string;
|
||||
customWidgetVersion: string;
|
||||
types: string[];
|
||||
globalProps: CatalogProp[];
|
||||
blockedCapabilities: Array<{ kind: string; name: string; reason: string }>;
|
||||
components: CatalogComponent[];
|
||||
}
|
||||
type ComponentCatalog = CustomJsxAuthoringCatalog;
|
||||
type CatalogComponent = CustomJsxComponentApi;
|
||||
type CatalogProp = CustomJsxPropDescriptor;
|
||||
|
||||
const PAGE_SIZE = 40;
|
||||
|
||||
@@ -395,10 +366,13 @@ function ComponentDetails({ id, component, types }: { id: string; component: Cat
|
||||
<div className={styles.details} id={id}>
|
||||
<div className={styles.detailsGrid}>
|
||||
<section>
|
||||
<h5>Usage example</h5>
|
||||
<pre className={styles.codeBlock}>
|
||||
<code>{buildUsageExample(component, types)}</code>
|
||||
</pre>
|
||||
<CustomWidgetCodeExample
|
||||
id={`${componentAnchor(component.name)}-usage`}
|
||||
label="Usage example"
|
||||
language="jsx"
|
||||
code={buildCustomJsxComponentUsageExample(component, { types })}
|
||||
height="180px"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
@@ -457,9 +431,12 @@ function ComponentDetails({ id, component, types }: { id: string; component: Cat
|
||||
|
||||
<details className={styles.rawComponent}>
|
||||
<summary>Raw component JSON</summary>
|
||||
<pre className={styles.codeBlock}>
|
||||
<code>{JSON.stringify(component, null, 2)}</code>
|
||||
</pre>
|
||||
<CustomWidgetCodeExample
|
||||
id={`${componentAnchor(component.name)}-json`}
|
||||
label="Component JSON"
|
||||
code={JSON.stringify(component, null, 2)}
|
||||
height="320px"
|
||||
/>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
@@ -518,47 +495,3 @@ function humanize(value: string) {
|
||||
function formatLiteral(value: string | number | boolean | null) {
|
||||
return typeof value === "string" ? JSON.stringify(value) : String(value);
|
||||
}
|
||||
|
||||
function buildUsageExample(component: CatalogComponent, types: string[]) {
|
||||
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, 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: ComponentBindingType, 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: CatalogProp, 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}}`;
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
WorkshopUser,
|
||||
} from "@homarr/workshop";
|
||||
import { validateWorkshopWidget, WorkshopClient, workshopExportFilename } from "@homarr/workshop";
|
||||
import { CUSTOM_WIDGET_SCHEMA } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { CustomWidgetCodeExample } from "../custom-widget-code";
|
||||
import styles from "./workshop.module.css";
|
||||
@@ -31,6 +32,7 @@ export function WorkshopPage() {
|
||||
const [reportCategory, setReportCategory] = useState<WorkshopReport["category"]>("other");
|
||||
const [reportText, setReportText] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const draftValidation = useMemo(() => validateWorkshopWidget(draft.content), [draft.content]);
|
||||
const reportCounts = useMemo(() => {
|
||||
@@ -41,6 +43,7 @@ export function WorkshopPage() {
|
||||
const selectedReports = selected ? reports.filter((report) => report.submission === selected.id) : [];
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [nextReports, nextItems] = await Promise.all([
|
||||
user?.isAdmin ? client.listReports() : Promise.resolve([]),
|
||||
@@ -58,6 +61,8 @@ export function WorkshopPage() {
|
||||
setError("");
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Workshop is unavailable");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [client, search, sort, user?.isAdmin]);
|
||||
|
||||
@@ -252,7 +257,7 @@ export function WorkshopPage() {
|
||||
</select>
|
||||
</div>
|
||||
{error && <div className={styles.error}>{error}</div>}
|
||||
<div className={styles.grid}>
|
||||
<div className={styles.grid} aria-busy={loading}>
|
||||
{items.map((item) => {
|
||||
const reportCount = reportCounts.get(item.id) ?? 0;
|
||||
return (
|
||||
@@ -273,6 +278,9 @@ export function WorkshopPage() {
|
||||
▲ {item.upvotes} · ▼ {item.downvotes}
|
||||
</span>
|
||||
</div>
|
||||
<span className={item.widgetSchema === CUSTOM_WIDGET_SCHEMA ? styles.success : styles.error}>
|
||||
{item.widgetSchema === CUSTOM_WIDGET_SCHEMA ? "Current" : "Unsupported"} · {item.widgetSchema}
|
||||
</span>
|
||||
{user?.isAdmin && reportCount > 0 && (
|
||||
<span className={styles.reportCount}>
|
||||
{reportCount} {reportCount === 1 ? "report" : "reports"}
|
||||
@@ -288,7 +296,8 @@ export function WorkshopPage() {
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{items.length === 0 && <p className={styles.empty}>No widgets match this search.</p>}
|
||||
{loading && items.length === 0 && <p className={styles.empty}>Loading Workshop…</p>}
|
||||
{!loading && items.length === 0 && <p className={styles.empty}>No widgets match this search.</p>}
|
||||
|
||||
{selected && (
|
||||
<div
|
||||
@@ -308,6 +317,9 @@ export function WorkshopPage() {
|
||||
▲ {selected.upvotes} · ▼ {selected.downvotes}
|
||||
</span>
|
||||
</div>
|
||||
<span className={selected.widgetSchema === CUSTOM_WIDGET_SCHEMA ? styles.success : styles.error}>
|
||||
{selected.widgetSchema === CUSTOM_WIDGET_SCHEMA ? "Current" : "Unsupported"} · {selected.widgetSchema}
|
||||
</span>
|
||||
{user?.isAdmin && selectedReports.length > 0 && (
|
||||
<section className={styles.moderation} aria-labelledby="submission-reports-title">
|
||||
<h3 id="submission-reports-title">
|
||||
|
||||
@@ -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
|
||||
@@ -55,6 +55,7 @@
|
||||
"@mantine/colors-generator": "catalog:",
|
||||
"@mantine/core": "catalog:",
|
||||
"@mantine/dropzone": "catalog:",
|
||||
"@mantine/form": "catalog:",
|
||||
"@mantine/hooks": "catalog:",
|
||||
"@mantine/modals": "catalog:",
|
||||
"@mantine/tiptap": "catalog:",
|
||||
|
||||
@@ -95,7 +95,7 @@ describe("CopyAiPromptButton", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("copies the complete offline bundle and reports its exact character count", async () => {
|
||||
test("copies the complete embedded skill and reports its exact character count", async () => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
@@ -120,10 +120,26 @@ describe("CopyAiPromptButton", () => {
|
||||
|
||||
const prompt = writeText.mock.calls[0]?.[0] as string;
|
||||
expect(prompt.startsWith("Please create this Homarr Custom JSX v2 widget:\n\nCreate a Pokédex")).toBe(true);
|
||||
expect(prompt).toContain("# Homarr Custom Widget offline authoring bundle");
|
||||
expect(prompt).toContain("--- BEGIN SKILL FILE: SKILL.md ---");
|
||||
expect(prompt).toContain("--- BEGIN SKILL FILE: references/widget-schema.json ---");
|
||||
expect(prompt).toContain("--- BEGIN CANONICAL COMPONENT CATALOG ---");
|
||||
expect(prompt).toContain("--- BEGIN CANONICAL RUNTIME EXAMPLES ---");
|
||||
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);
|
||||
expect(showSuccessNotification).toHaveBeenCalledWith({
|
||||
title: "action.copyAiPrompt",
|
||||
message: `notification.aiPromptCopiedWithCount:${prompt.length}`,
|
||||
});
|
||||
});
|
||||
|
||||
test("places the AI authoring card before General information", async () => {
|
||||
const source = await readFile(
|
||||
resolve(process.cwd(), "apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-form.tsx"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(source.indexOf("<CustomWidgetAiCard")).toBeLessThan(source.indexOf('<EditorSection id="general"'));
|
||||
});
|
||||
});
|
||||
+20
-1
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { getCustomWidgetPreviewOptionIssues, loadPreviewQueries } from "./_custom-widget-form-utils";
|
||||
import { getChangedSecrets, getCustomWidgetPreviewOptionIssues, loadPreviewQueries } from "./_custom-widget-form-utils";
|
||||
|
||||
const previewQuery = vi.hoisted(() => vi.fn());
|
||||
|
||||
@@ -64,4 +64,23 @@ describe("Custom Widget workbench preview options", () => {
|
||||
{ path: "configuration.environmentId", message: "Expected number" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes only changed secrets for save and preview", () => {
|
||||
expect(
|
||||
getChangedSecrets({
|
||||
name: "Widget",
|
||||
description: "",
|
||||
iconUrl: "",
|
||||
sources: "[]",
|
||||
requests: "[]",
|
||||
optionsSchema: "{}",
|
||||
defaultOptions: "{}",
|
||||
template: "<Text />",
|
||||
secrets: [
|
||||
{ sourceId: "default", kind: "apiKey", value: "", hasValue: true },
|
||||
{ sourceId: "other", kind: "password", value: "replacement" },
|
||||
],
|
||||
}),
|
||||
).toEqual([{ sourceId: "other", kind: "password", value: "replacement" }]);
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,16 @@ export function buildDefinition(values: CustomWidgetFormValues) {
|
||||
});
|
||||
}
|
||||
|
||||
export function getChangedSecrets(values: CustomWidgetFormValues) {
|
||||
return values.secrets
|
||||
.filter((secret) => secret.value.trim())
|
||||
.map(({ sourceId, kind, value }) => ({
|
||||
sourceId,
|
||||
kind: kind as "apiKey" | "username" | "password",
|
||||
value,
|
||||
}));
|
||||
}
|
||||
|
||||
export function applyDefinition(form: CustomWidgetWorkbenchForm, widget: HomarrCustomWidgetV2) {
|
||||
form.setValues({
|
||||
...form.values,
|
||||
|
||||
@@ -165,6 +165,14 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
|
||||
</nav>
|
||||
<div className={classes.workbench} data-mobile-pane={mobilePane}>
|
||||
<Stack gap="lg" className={classes.configuration}>
|
||||
<CustomWidgetAiCard
|
||||
candidate={candidate.success ? candidate.data : null}
|
||||
request={request}
|
||||
onRequestChange={setRequest}
|
||||
documentationUrl={documentationUrl}
|
||||
onDocumentationUrlChange={setDocumentationUrl}
|
||||
onPaste={() => void pasteAiResponse()}
|
||||
/>
|
||||
<EditorSection id="general" title={w("generalInformation")} icon={IconSettings}>
|
||||
<TextInput label={t("field.name")} required {...form.getInputProps("name")} />
|
||||
<Textarea label={t("field.description")} autosize minRows={2} {...form.getInputProps("description")} />
|
||||
@@ -224,14 +232,6 @@ export function CustomWidgetForm({ mode, initialValues, definitionId }: CustomWi
|
||||
maxLength={50_000}
|
||||
/>
|
||||
</EditorSection>
|
||||
<CustomWidgetAiCard
|
||||
candidate={candidate.success ? candidate.data : null}
|
||||
request={request}
|
||||
onRequestChange={setRequest}
|
||||
documentationUrl={documentationUrl}
|
||||
onDocumentationUrlChange={setDocumentationUrl}
|
||||
onPaste={() => void pasteAiResponse()}
|
||||
/>
|
||||
<Paper p="md" className={classes.mobileSaveBar} shadow="sm">
|
||||
<SaveActions
|
||||
dirty={form.isDirty()}
|
||||
|
||||
+3
-14
@@ -18,6 +18,7 @@ import { useScopedI18n } from "@homarr/translation/client";
|
||||
import {
|
||||
applyDefinition,
|
||||
buildDefinition,
|
||||
getChangedSecrets,
|
||||
getCustomWidgetPreviewOptionIssues,
|
||||
isRecord,
|
||||
loadPreviewQueries,
|
||||
@@ -63,13 +64,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const changedSecrets = values.secrets
|
||||
.filter((secret) => secret.value.trim())
|
||||
.map(({ sourceId, kind, value }) => ({
|
||||
sourceId,
|
||||
kind: kind as "apiKey" | "username" | "password",
|
||||
value,
|
||||
}));
|
||||
const changedSecrets = getChangedSecrets(values);
|
||||
try {
|
||||
if (input.mode === "create") {
|
||||
const result = await createMutation.mutateAsync({ ...definition.data, secrets: changedSecrets });
|
||||
@@ -135,13 +130,7 @@ export function useCustomWidgetFormActions(input: FormActionsInput) {
|
||||
definition: input.candidate.data,
|
||||
definitionId: input.definitionId,
|
||||
options: input.optionsSnapshot,
|
||||
secrets: input.form.values.secrets
|
||||
.filter((secret) => secret.value.trim())
|
||||
.map(({ sourceId, kind, value }) => ({
|
||||
sourceId,
|
||||
kind: kind as "apiKey" | "username" | "password",
|
||||
value,
|
||||
})),
|
||||
secrets: getChangedSecrets(input.form.values),
|
||||
});
|
||||
const snapshot = await loadPreviewQueries(input.candidate.data, created.previewSession.id, input.optionsSnapshot);
|
||||
const failed = Object.values(snapshot.status).filter((status) => isRecord(status) && status.ok === false).length;
|
||||
|
||||
@@ -13,5 +13,6 @@ export function GET() {
|
||||
"homarr://custom-widgets/components",
|
||||
"homarr://custom-widgets/skill",
|
||||
],
|
||||
httpResources: ["/api/custom-widgets/schema", "/api/custom-widgets/components", "/api/custom-widgets/skill"],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
|
||||
|
||||
export const dynamic = "force-static";
|
||||
|
||||
export function GET() {
|
||||
return NextResponse.json(getCustomWidgetJsonSchema());
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import { buildCustomWidgetMcpPrompt } from "@homarr/custom-widgets/authoring-pro
|
||||
import {
|
||||
getCustomWidgetComponent,
|
||||
getCustomWidgetComponentCatalog,
|
||||
getCustomWidgetSkill,
|
||||
getCustomWidgetOfflineBundle,
|
||||
} from "@homarr/custom-widgets/authoring-resources";
|
||||
import { customJsxExamples, getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
|
||||
import { db } from "@homarr/db";
|
||||
@@ -252,8 +252,7 @@ const mcpHandler = createMcpHandler(
|
||||
if (uri === "homarr://custom-widgets/schema") text = JSON.stringify(getCustomWidgetJsonSchema());
|
||||
else if (uri === "homarr://custom-widgets/components") text = JSON.stringify(getCustomWidgetComponentCatalog());
|
||||
else if (uri === "homarr://custom-widgets/skill") {
|
||||
const skill = getCustomWidgetSkill();
|
||||
text = `${skill.skillMd}\n\nInstall from skills.sh: ${skill.skillsShUrl}\nSource: ${skill.sourceUrl}\nCommand: ${skill.installCommand}\n`;
|
||||
text = getCustomWidgetOfflineBundle();
|
||||
mimeType = "text/markdown";
|
||||
} else if (uri.startsWith("homarr://custom-widgets/components/")) {
|
||||
const name = decodeURIComponent(uri.slice("homarr://custom-widgets/components/".length));
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Code,
|
||||
Group,
|
||||
Image,
|
||||
Loader,
|
||||
Modal,
|
||||
Pagination,
|
||||
Select,
|
||||
@@ -33,6 +34,8 @@ import {
|
||||
} from "@tabler/icons-react";
|
||||
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { CUSTOM_WIDGET_SCHEMA } from "@homarr/custom-widgets/core";
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
import type { WorkshopReport, WorkshopSubmissionDetail, WorkshopUser } from "@homarr/workshop";
|
||||
import { validateWorkshopWidget, workshopExportFilename } from "@homarr/workshop";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
@@ -49,7 +52,7 @@ function downloadWorkshopSubmission(submission: WorkshopSubmissionDetail) {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
export function WorkshopBrowser({ onInstall }: { onInstall?(submission: WorkshopSubmissionDetail): Promise<void> }) {
|
||||
export function WorkshopBrowser({ onInstall }: { onInstall?(widget: HomarrCustomWidgetV2): Promise<void> }) {
|
||||
const t = useScopedI18n("workshop");
|
||||
const client = useMemo(createWorkshopClient, []);
|
||||
const queryClient = useQueryClient();
|
||||
@@ -85,6 +88,7 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
() => (detail.data ? validateWorkshopWidget(detail.data.content) : null),
|
||||
[detail.data],
|
||||
);
|
||||
const detailCompatible = detailValidation?.success === true && detail.data?.widgetSchema === CUSTOM_WIDGET_SCHEMA;
|
||||
const signIn = () => {
|
||||
setLoginPending(true);
|
||||
setLoginError(null);
|
||||
@@ -99,7 +103,7 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
.finally(() => setLoginPending(false));
|
||||
};
|
||||
const install = useMutation({
|
||||
mutationFn: async (submission: WorkshopSubmissionDetail) => onInstall?.(submission),
|
||||
mutationFn: async (widget: HomarrCustomWidgetV2) => onInstall?.(widget),
|
||||
onSuccess: () => setSelectedId(null),
|
||||
});
|
||||
const vote = useMutation({
|
||||
@@ -167,6 +171,7 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
<TextInput
|
||||
label={t("search")}
|
||||
leftSection={<IconSearch size={16} />}
|
||||
rightSection={list.isFetching ? <Loader size={16} /> : undefined}
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
setSearch(event.currentTarget.value);
|
||||
@@ -194,7 +199,7 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
<Skeleton h={280} />
|
||||
</SimpleGrid>
|
||||
) : list.isError ? (
|
||||
<Alert color="red">{t("unavailable")}</Alert>
|
||||
<Alert color="red">{list.error instanceof Error ? list.error.message : t("unavailable")}</Alert>
|
||||
) : list.data?.items.length ? (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }}>
|
||||
{list.data.items.map((item) => (
|
||||
@@ -223,6 +228,9 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
<IconThumbUp size={13} /> {item.upvotes} · <IconThumbDown size={13} /> {item.downvotes}
|
||||
</Text>
|
||||
</Group>
|
||||
<Badge color={item.widgetSchema === CUSTOM_WIDGET_SCHEMA ? "green" : "red"} variant="light">
|
||||
{item.widgetSchema}
|
||||
</Badge>
|
||||
<Text fw={700} lineClamp={1}>
|
||||
{item.title}
|
||||
</Text>
|
||||
@@ -254,7 +262,7 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
{detail.isPending ? (
|
||||
<Skeleton h={400} />
|
||||
) : detail.isError || !detail.data ? (
|
||||
<Alert color="red">{t("loadError")}</Alert>
|
||||
<Alert color="red">{detail.error instanceof Error ? detail.error.message : t("loadError")}</Alert>
|
||||
) : (
|
||||
<Stack>
|
||||
<Text>{detail.data.description}</Text>
|
||||
@@ -273,12 +281,17 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
))}
|
||||
</SimpleGrid>
|
||||
)}
|
||||
<CapabilitySummary content={detail.data.content} />
|
||||
{detailValidation?.success && <CapabilitySummary widget={detailValidation.data} />}
|
||||
{detailValidation && !detailValidation.success && (
|
||||
<Alert color="red" icon={<IconAlertTriangle size={18} />}>
|
||||
{t("installErrorDescription")} {detailValidation.error}
|
||||
</Alert>
|
||||
)}
|
||||
{detailValidation?.success && !detailCompatible && (
|
||||
<Alert color="red" icon={<IconAlertTriangle size={18} />}>
|
||||
{t("installErrorDescription")}
|
||||
</Alert>
|
||||
)}
|
||||
<Code block mah={360} style={{ overflow: "auto", whiteSpace: "pre" }}>
|
||||
{detail.data.content}
|
||||
</Code>
|
||||
@@ -294,7 +307,8 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
<Button
|
||||
variant="subtle"
|
||||
leftSection={<IconThumbUp size={16} />}
|
||||
disabled={!user}
|
||||
loading={vote.isPending && vote.variables?.value === 1}
|
||||
disabled={!user || vote.isPending}
|
||||
onClick={() => vote.mutate({ submission: detail.data.id, value: 1 })}
|
||||
>
|
||||
{detail.data.upvotes}
|
||||
@@ -302,7 +316,8 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
<Button
|
||||
variant="subtle"
|
||||
leftSection={<IconThumbDown size={16} />}
|
||||
disabled={!user}
|
||||
loading={vote.isPending && vote.variables?.value === -1}
|
||||
disabled={!user || vote.isPending}
|
||||
onClick={() => vote.mutate({ submission: detail.data.id, value: -1 })}
|
||||
>
|
||||
{detail.data.downvotes}
|
||||
@@ -320,8 +335,8 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
{onInstall && (
|
||||
<Button
|
||||
loading={install.isPending}
|
||||
disabled={!detailValidation?.success}
|
||||
onClick={() => install.mutate(detail.data)}
|
||||
disabled={!detailCompatible}
|
||||
onClick={() => detailValidation?.success && install.mutate(detailValidation.data)}
|
||||
>
|
||||
{t("install")}
|
||||
</Button>
|
||||
@@ -332,7 +347,7 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
{t("signInHint")}
|
||||
</Text>
|
||||
)}
|
||||
{vote.error && <Alert color="red">{t("voteError")}</Alert>}
|
||||
{vote.error && <Alert color="red">{vote.error.message || t("voteError")}</Alert>}
|
||||
{install.error && <Alert color="red">{install.error.message}</Alert>}
|
||||
</Stack>
|
||||
)}
|
||||
@@ -367,10 +382,8 @@ export function WorkshopBrowser({ onInstall }: { onInstall?(submission: Workshop
|
||||
);
|
||||
}
|
||||
|
||||
function CapabilitySummary({ content }: { content: string }) {
|
||||
function CapabilitySummary({ widget }: { widget: HomarrCustomWidgetV2 }) {
|
||||
const t = useScopedI18n("workshop");
|
||||
const parsed = validateWorkshopWidget(content);
|
||||
if (!parsed.success) return null;
|
||||
return (
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }}>
|
||||
<Card withBorder p="sm">
|
||||
@@ -378,7 +391,7 @@ function CapabilitySummary({ content }: { content: string }) {
|
||||
{t("sources")}
|
||||
</Text>
|
||||
<Stack gap={6}>
|
||||
{parsed.data.sources.map((source) => (
|
||||
{widget.sources.map((source) => (
|
||||
<Box key={source.id}>
|
||||
<Text size="sm" fw={500}>
|
||||
{source.name}
|
||||
@@ -402,13 +415,13 @@ function CapabilitySummary({ content }: { content: string }) {
|
||||
<Text fw={600} size="sm" mb="xs">
|
||||
{t("requests")}
|
||||
</Text>
|
||||
{parsed.data.requests.length === 0 ? (
|
||||
{widget.requests.length === 0 ? (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("noRequests")}
|
||||
</Text>
|
||||
) : (
|
||||
<Stack gap={6}>
|
||||
{parsed.data.requests.map((request) => (
|
||||
{widget.requests.map((request) => (
|
||||
<Group key={request.id} justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" ff="monospace" truncate>
|
||||
{request.id}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { WorkshopClient, WORKSHOP_API_URL } from "@homarr/workshop";
|
||||
|
||||
export function createWorkshopClient() {
|
||||
const runtimeUrl =
|
||||
typeof document === "undefined"
|
||||
? undefined
|
||||
: document.querySelector<HTMLMetaElement>('meta[name="homarr-workshop-api-url"]')?.content;
|
||||
let browserClient: WorkshopClient | undefined;
|
||||
|
||||
return new WorkshopClient(runtimeUrl || WORKSHOP_API_URL);
|
||||
export function createWorkshopClient() {
|
||||
if (typeof document === "undefined") return new WorkshopClient(WORKSHOP_API_URL);
|
||||
if (browserClient) return browserClient;
|
||||
|
||||
const runtimeUrl = document.querySelector<HTMLMetaElement>('meta[name="homarr-workshop-api-url"]')?.content;
|
||||
|
||||
browserClient = new WorkshopClient(runtimeUrl || WORKSHOP_API_URL);
|
||||
return browserClient;
|
||||
}
|
||||
@@ -5,9 +5,7 @@ import { Button, Modal } from "@mantine/core";
|
||||
import { useDisclosure } from "@mantine/hooks";
|
||||
import { IconBuildingStore } from "@tabler/icons-react";
|
||||
|
||||
import { customWidgetImportSchema } from "@homarr/custom-widgets/core";
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
|
||||
@@ -25,23 +23,9 @@ export function WorkshopInstallButton() {
|
||||
</Button>
|
||||
<Modal opened={opened} onClose={controls.close} title={t("installDialog")} size="90%">
|
||||
<WorkshopBrowser
|
||||
onInstall={async (submission) => {
|
||||
try {
|
||||
const parsed = customWidgetImportSchema.safeParse(JSON.parse(submission.content) as unknown);
|
||||
if (!parsed.success) throw new Error(t("installErrorDescription"));
|
||||
setPendingWidget(parsed.data);
|
||||
reviewControls.open();
|
||||
} catch (error) {
|
||||
showErrorNotification({
|
||||
title: t("installError"),
|
||||
message:
|
||||
error instanceof SyntaxError
|
||||
? t("installErrorDescription")
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: t("installErrorDescription"),
|
||||
});
|
||||
}
|
||||
onInstall={async (widget) => {
|
||||
setPendingWidget(widget);
|
||||
reviewControls.open();
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
@@ -4,38 +4,19 @@ import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useDisclosure } from "@mantine/hooks";
|
||||
|
||||
import { customWidgetImportSchema } from "@homarr/custom-widgets/core";
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import type { WorkshopSubmissionDetail } from "@homarr/workshop";
|
||||
|
||||
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
|
||||
import { WorkshopBrowser } from "./workshop-browser";
|
||||
|
||||
export function WorkshopInstaller() {
|
||||
const t = useScopedI18n("workshop");
|
||||
const router = useRouter();
|
||||
const [pendingWidget, setPendingWidget] = useState<HomarrCustomWidgetV2 | null>(null);
|
||||
const [reviewOpened, reviewControls] = useDisclosure(false);
|
||||
|
||||
const install = async (submission: WorkshopSubmissionDetail) => {
|
||||
try {
|
||||
const parsed = customWidgetImportSchema.safeParse(JSON.parse(submission.content) as unknown);
|
||||
if (!parsed.success) throw new Error(t("installErrorDescription"));
|
||||
setPendingWidget(parsed.data);
|
||||
reviewControls.open();
|
||||
} catch (error) {
|
||||
showErrorNotification({
|
||||
title: t("installError"),
|
||||
message:
|
||||
error instanceof SyntaxError
|
||||
? t("installErrorDescription")
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: t("installErrorDescription"),
|
||||
});
|
||||
}
|
||||
const install = async (widget: HomarrCustomWidgetV2) => {
|
||||
setPendingWidget(widget);
|
||||
reviewControls.open();
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -31,9 +31,8 @@ ENV PORT=8090
|
||||
RUN addgroup -S pocketbase && adduser -S -G pocketbase pocketbase
|
||||
COPY --from=website /app/apps/docs/build /pb_public
|
||||
COPY apps/workshop/entrypoint.sh /usr/local/bin/workshop-entrypoint
|
||||
COPY apps/workshop/pb_hooks /pb_hooks
|
||||
COPY apps/workshop/pb_migrations /pb_migrations
|
||||
RUN chmod +x /usr/local/bin/workshop-entrypoint && mkdir -p /pb_data && chown -R pocketbase:pocketbase /pb_data /pb_hooks /pb_migrations /pb_public
|
||||
RUN chmod +x /usr/local/bin/workshop-entrypoint && mkdir -p /pb_data && chown -R pocketbase:pocketbase /pb_data /pb_migrations /pb_public
|
||||
USER pocketbase
|
||||
EXPOSE 8090
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD wget -q --spider "http://127.0.0.1:${PORT}/api/health" || exit 1
|
||||
|
||||
+11
-4
@@ -3,7 +3,7 @@
|
||||
Workshop is a small PocketBase service that serves the public documentation site and stores one Custom JSX v2 widget per submission.
|
||||
|
||||
The runtime image extends `ghcr.io/muchobien/pocketbase:0.39`; Homarr adds only the built documentation, PocketBase
|
||||
collections, one small user-role guard, and its explicit serve arguments.
|
||||
collections, API rules, and its explicit serve arguments.
|
||||
|
||||
It intentionally has no approval queue, user bans, comments, email notifications, audit log, reusable widget connections,
|
||||
or remote control over installed widgets. Submissions publish immediately. Authenticated users can vote and report;
|
||||
@@ -20,8 +20,9 @@ container. With the image directly, set both values: `docker run -e PORT=3003 -p
|
||||
|
||||
Open `http://127.0.0.1:18090/_/`, create the first PocketBase superuser, and configure GitHub OAuth on the `users` collection.
|
||||
|
||||
The `users.isAdmin` field defaults to `false` and cannot be changed by regular users. Appoint administrators from the
|
||||
PocketBase dashboard with a superuser account.
|
||||
The `users.isAdmin` field defaults to `false`. Collection rules allow account creation only through OAuth without that
|
||||
field and reject regular-user updates to it. Appoint administrators from the PocketBase dashboard with a superuser
|
||||
account.
|
||||
|
||||
Users must sign in again after the role changes. Setting the value back to `false` removes Workshop administrator access.
|
||||
|
||||
@@ -39,8 +40,13 @@ Run the disposable service integration test from the repository root:
|
||||
pnpm test:workshop
|
||||
```
|
||||
|
||||
The test uses a separate Compose project and deletes its named volume on exit. It never writes fixture users or admin
|
||||
roles into the normal `homarr-workshop_pb_data` volume.
|
||||
|
||||
The Workshop does not maintain a second Custom Widget schema. Its frontend validates submissions with
|
||||
`customWidgetImportSchema` from `@homarr/custom-widgets`, and Homarr validates canonical content again before installation.
|
||||
The validated `$schema` is also stored as `widgetSchema` for listing compatibility badges; it must match the downloaded
|
||||
manifest before Homarr enables installation.
|
||||
PocketBase API rules enforce submission ownership, one vote/report per user and submission, and administrator-only
|
||||
moderation. Reports are dismissed by deleting them; PocketBase cascade deletion removes related votes and reports when a
|
||||
submission is deleted.
|
||||
@@ -53,7 +59,8 @@ Build the documentation and serve it from PocketBase using the same production i
|
||||
pnpm docker:docs
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:3003`. Set `DOCS_EXPOSE_PORT` to use another host port. The preview does not mount or persist PocketBase data.
|
||||
Open `http://127.0.0.1:3003`. Set `DOCS_EXPOSE_PORT` to use another host port. PocketBase data persists in the
|
||||
`homarr-workshop_pb_data` named volume.
|
||||
|
||||
Point a local Homarr checkout at it with:
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ services:
|
||||
- "127.0.0.1:${PB_EXPOSE_PORT:-8090}:${PB_EXPOSE_PORT:-8090}"
|
||||
volumes:
|
||||
- pb_data:/pb_data
|
||||
- ./pb_hooks:/pb_hooks:ro
|
||||
- ./pb_migrations:/pb_migrations:ro
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
|
||||
@@ -5,7 +5,6 @@ exec pocketbase serve \
|
||||
--http="0.0.0.0:${PORT:-8090}" \
|
||||
--origins="${PB_ALLOWED_ORIGINS:-*}" \
|
||||
--dir=/pb_data \
|
||||
--hooksDir=/pb_hooks \
|
||||
--migrationsDir=/pb_migrations \
|
||||
--publicDir=/pb_public \
|
||||
--indexFallback=true
|
||||
@@ -1,6 +0,0 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
onRecordCreate((e) => {
|
||||
e.record.set("isAdmin", false);
|
||||
e.next();
|
||||
}, "users");
|
||||
@@ -17,6 +17,7 @@ migrate(
|
||||
const adminRule = "@request.auth.isAdmin = true";
|
||||
users.listRule = adminRule;
|
||||
users.viewRule = `id = @request.auth.id || ${adminRule}`;
|
||||
users.createRule = '@request.context = "oauth2" && @request.body.isAdmin:isset = false';
|
||||
users.updateRule = "id = @request.auth.id && @request.body.isAdmin:isset = false";
|
||||
users.deleteRule = null;
|
||||
app.save(users);
|
||||
@@ -32,6 +33,7 @@ migrate(
|
||||
fields: [
|
||||
{ type: "text", name: "title", required: true, min: 3, max: 100 },
|
||||
{ type: "text", name: "description", max: 2000 },
|
||||
{ type: "text", name: "widgetSchema", required: true, min: 1, max: 100 },
|
||||
{ type: "text", name: "content", required: true, max: 1000000 },
|
||||
{
|
||||
type: "file",
|
||||
@@ -126,7 +128,7 @@ migrate(
|
||||
listRule: "",
|
||||
viewRule: "",
|
||||
viewQuery: `
|
||||
SELECT s.id, s.title, s.description, s.screenshots, s.author, u.displayName AS authorName,
|
||||
SELECT s.id, s.title, s.description, s.widgetSchema, s.screenshots, s.author, u.displayName AS authorName,
|
||||
s.created, s.updated,
|
||||
COALESCE(SUM(CASE WHEN v.value = 1 THEN 1 ELSE 0 END), 0) AS upvotes,
|
||||
COALESCE(SUM(CASE WHEN v.value = -1 THEN 1 ELSE 0 END), 0) AS downvotes,
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
WORKSHOP_TEST_DATA_DIR=$(mktemp -d)
|
||||
WORKSHOP_TEST_PORT=${WORKSHOP_TEST_PORT:-18090}
|
||||
WORKSHOP_TEST_PROJECT="homarr-workshop-test-$$"
|
||||
|
||||
cleanup() {
|
||||
WORKSHOP_DATA_DIR="$WORKSHOP_TEST_DATA_DIR" PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" \
|
||||
docker compose -f apps/workshop/docker-compose.yml down --remove-orphans >/dev/null 2>&1 || true
|
||||
rm -rf "$WORKSHOP_TEST_DATA_DIR"
|
||||
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
|
||||
-f apps/workshop/docker-compose.yml down --volumes --remove-orphans >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
WORKSHOP_DATA_DIR="$WORKSHOP_TEST_DATA_DIR" PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" \
|
||||
docker compose -f apps/workshop/docker-compose.yml up --build -d
|
||||
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
|
||||
-f apps/workshop/docker-compose.yml up --build -d
|
||||
|
||||
for attempt in $(seq 1 60); do
|
||||
if curl --fail --silent "http://127.0.0.1:$WORKSHOP_TEST_PORT/api/health" >/dev/null; then
|
||||
break
|
||||
fi
|
||||
if [ "$attempt" -eq 60 ]; then
|
||||
WORKSHOP_DATA_DIR="$WORKSHOP_TEST_DATA_DIR" PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" \
|
||||
docker compose -f apps/workshop/docker-compose.yml logs --no-color workshop
|
||||
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
|
||||
-f apps/workshop/docker-compose.yml logs --no-color workshop
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
docker exec homarr-workshop-workshop-1 pocketbase superuser create \
|
||||
docker compose -p "$WORKSHOP_TEST_PROJECT" -f apps/workshop/docker-compose.yml exec -T workshop \
|
||||
pocketbase superuser create \
|
||||
workshop-test@example.invalid 'WorkshopLocalTest123!' --dir=/pb_data
|
||||
|
||||
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_TEST_PORT" node apps/workshop/tests/workshop.integration.mjs
|
||||
@@ -37,6 +37,9 @@ for (const removed of ["comments", "workshop_admin_actions", "workshop_admins"])
|
||||
|
||||
// Production uses GitHub OAuth. Password auth is enabled only in this disposable database.
|
||||
const usersCollection = await request("/api/collections/users", { headers: rootHeaders });
|
||||
if (usersCollection.createRule !== '@request.context = "oauth2" && @request.body.isAdmin:isset = false') {
|
||||
throw new Error("User creation must be limited to OAuth without administrator fields");
|
||||
}
|
||||
await request("/api/collections/users", {
|
||||
method: "PATCH",
|
||||
headers: rootHeaders,
|
||||
@@ -67,8 +70,7 @@ const signIn = async (email, password) => {
|
||||
};
|
||||
|
||||
const authorPassword = "WorkshopAuthor123!";
|
||||
const author = await createUser("widget-author@example.invalid", "Widget Author", authorPassword, { isAdmin: true });
|
||||
if (author.isAdmin !== false) throw new Error("New users must not be able to start as Workshop administrators");
|
||||
const author = await createUser("widget-author@example.invalid", "Widget Author", authorPassword);
|
||||
const authorSession = await signIn(author.email, authorPassword);
|
||||
await expectStatus(
|
||||
`/api/collections/users/records/${author.id}`,
|
||||
@@ -104,11 +106,16 @@ const submission = await request("/api/collections/submissions/records", {
|
||||
body: JSON.stringify({
|
||||
title: "Workshop runtime probe",
|
||||
description: "PocketBase integration test",
|
||||
widgetSchema: widget.$schema,
|
||||
content: JSON.stringify(widget),
|
||||
author: author.id,
|
||||
}),
|
||||
});
|
||||
if (submission.author !== author.id || submission.title !== "Workshop runtime probe") {
|
||||
if (
|
||||
submission.author !== author.id ||
|
||||
submission.title !== "Workshop runtime probe" ||
|
||||
submission.widgetSchema !== widget.$schema
|
||||
) {
|
||||
throw new Error("Submission publication failed");
|
||||
}
|
||||
|
||||
@@ -117,7 +124,8 @@ const updatedSubmission = await request(`/api/collections/submissions/records/${
|
||||
headers: authorSession.headers,
|
||||
body: JSON.stringify({ title: "Updated runtime probe" }),
|
||||
});
|
||||
if (updatedSubmission.title !== "Updated runtime probe") throw new Error("Authors must be able to edit their submission");
|
||||
if (updatedSubmission.title !== "Updated runtime probe")
|
||||
throw new Error("Authors must be able to edit their submission");
|
||||
|
||||
await expectStatus(
|
||||
`/api/collections/submissions/records/${submission.id}`,
|
||||
@@ -161,7 +169,13 @@ await expectStatus(
|
||||
);
|
||||
|
||||
const listing = await request(`/api/collections/workshop_listings/records/${submission.id}`);
|
||||
if (listing.score !== 1 || listing.upvotes !== 1 || listing.downvotes !== 0 || listing.authorName !== "Widget Author") {
|
||||
if (
|
||||
listing.score !== 1 ||
|
||||
listing.upvotes !== 1 ||
|
||||
listing.downvotes !== 0 ||
|
||||
listing.authorName !== "Widget Author" ||
|
||||
listing.widgetSchema !== widget.$schema
|
||||
) {
|
||||
throw new Error("Workshop listing data is incorrect");
|
||||
}
|
||||
|
||||
@@ -222,6 +236,7 @@ const visitorSubmission = await request("/api/collections/submissions/records",
|
||||
body: JSON.stringify({
|
||||
title: "Administrator deletion probe",
|
||||
content: JSON.stringify(widget),
|
||||
widgetSchema: widget.$schema,
|
||||
author: visitor.id,
|
||||
}),
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user