Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(dashboard): draw widgets with a declarative card layout (#22016)

Arvin Xuab65979caaf4
diff --git a/apps/server/src/services/widget/__tests__/layoutSchema.test.ts b/apps/server/src/services/widget/__tests__/layoutSchema.test.ts
new file mode 100644
index 00000000000..b736860f078
--- /dev/null
+++ b/apps/server/src/services/widget/__tests__/layoutSchema.test.ts
@@ -0,0 +1,134 @@
+import { systemPrompt } from '@lobechat/builtin-tool-dashboard';
+import { describe, expect, it } from 'vitest';
+
+import { widgetLayoutSchema } from '../layoutSchema';
+import { widgetViewSchema } from '../versionSchema';
+
+const text = (value: unknown) => ({ type: 'text', value });
+
+describe('widgetLayoutSchema', () => {
+ it('accepts a nested layout with bindings, templates, conditions and a repeat', () => {
+ const result = widgetLayoutSchema.safeParse({
+ children: [
+ text({ bind: 'data.temp', digits: 0, format: 'number' }),
+ text({ template: 'H {data.hi}° · L {data.lo}°' }),
+ {
+ color: { bind: 'data.level', map: { 'high': 'error', '*': 'success' } },
+ name: 'thermometer',
+ type: 'icon',
+ visible: { bind: 'data.temp', gt: 30 },
+ },
+ {
+ items: 'data.hourly',
+ limit: 6,
+ template: text({ bind: 'item.t', format: 'time' }),
+ type: 'repeat',
+ },
+ { kind: 'area', key: 'temp', type: 'sparkline', values: 'data.hourly' },
+ { max: 100, type: 'ring', value: { bind: 'data.pct' }, children: [text('ok')] },
+ ],
+ type: 'stack',
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it.each([
+ ['an unknown node type', { type: 'script', value: 'alert(1)' }],
+ ['an unknown property', { type: 'text', value: 'x', style: { color: 'red' } }],
+ ['an unknown literal icon', { name: 'rocket-ship', type: 'icon' }],
+ ['an unknown literal color', { color: '#ff0000', type: 'progress', value: 1 }],
+ ['a non-https image', { src: 'http://example.com/a.png', type: 'image' }],
+ ['a path with brackets', text({ bind: 'data.hourly[0]' })],
+ ])('rejects %s', (_, layout) => {
+ expect(widgetLayoutSchema.safeParse(layout).success).toBe(false);
+ });
+
+ it('rejects a layout nested deeper than the limit', () => {
+ let layout: Record<string, unknown> = text('leaf');
+ for (let depth = 0; depth < 13; depth += 1) layout = { children: [layout], type: 'stack' };
+
+ const result = widgetLayoutSchema.safeParse(layout);
+
+ expect(result.success).toBe(false);
+ expect(JSON.stringify(result.error?.issues)).toContain('nested deeper');
+ });
+
+ it('rejects a repeat nested in another repeat', () => {
+ const repeat = (template: unknown) => ({ items: 'data.items', template, type: 'repeat' });
+
+ const result = widgetLayoutSchema.safeParse(repeat(repeat(repeat(repeat(text('x'))))));
+
+ expect(result.success).toBe(false);
+ expect(JSON.stringify(result.error?.issues)).toContain('cannot be nested');
+ });
+
+ it('rejects a layout whose repeats expand past the drawn-node limit', () => {
+ const row = { children: Array.from({ length: 60 }, () => text('x')), type: 'stack' };
+ const repeat = (limit?: number) => ({
+ items: 'data.items',
+ limit,
+ template: row,
+ type: 'repeat',
+ });
+
+ expect(widgetLayoutSchema.safeParse(repeat(10)).success).toBe(true);
+ const result = widgetLayoutSchema.safeParse(repeat());
+ expect(result.success).toBe(false);
+ expect(JSON.stringify(result.error?.issues)).toContain('once repeats');
+ });
+
+ it('counts each dot and bar a node draws, so a small tree cannot fan out into many elements', () => {
+ const dots = (total: unknown) => ({ total, type: 'dots', value: 1 });
+ const repeat = (template: unknown, limit = 48) => ({
+ items: 'data.items',
+ limit,
+ template,
+ type: 'repeat',
+ });
+
+ // a year of dots on its own fits
+ expect(widgetLayoutSchema.safeParse(dots(365)).success).toBe(true);
+ // 19 bound dot grids repeated 48 times would draw ~365k dots
+ const fanOut = repeat({
+ children: Array.from({ length: 19 }, () => dots({ bind: 'item' })),
+ type: 'stack',
+ });
+ const result = widgetLayoutSchema.safeParse(fanOut);
+ expect(result.success).toBe(false);
+ expect(JSON.stringify(result.error?.issues)).toContain('dots and bars');
+ // bar sparklines are weighed by their bars too
+ expect(
+ widgetLayoutSchema.safeParse(repeat({ kind: 'bar', type: 'sparkline', values: 'item.v' }, 12))
+ .success,
+ ).toBe(false);
+ });
+
+ it('rejects a layout with more nodes than the limit', () => {
+ const result = widgetLayoutSchema.safeParse({
+ children: Array.from({ length: 200 }, () => text('x')),
+ type: 'stack',
+ });
+
+ expect(result.success).toBe(false);
+ });
+});
+
+describe('widgetViewSchema surface', () => {
+ it('accepts a surface name or a binding, and rejects an unknown name', () => {
+ expect(widgetViewSchema.safeParse({ surface: 'rain' }).success).toBe(true);
+ expect(
+ widgetViewSchema.safeParse({ surface: { bind: 'data.cond', map: { rain: 'rain' } } }).success,
+ ).toBe(true);
+ expect(widgetViewSchema.safeParse({ surface: 'neon' }).success).toBe(false);
+ });
+});
+
+describe('dashboard tool prompt', () => {
+ it('teaches a weather view that passes validation', () => {
+ const example = systemPrompt.split('and the view is\n')[1]?.split('\n</card_layout>')[0];
+
+ expect(example).toBeTruthy();
+ expect(widgetViewSchema.safeParse(JSON.parse(example!)).success).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/widget/__tests__/metrics.test.ts b/apps/server/src/services/widget/__tests__/metrics.test.ts
new file mode 100644
index 00000000000..4c9d258a450
--- /dev/null
+++ b/apps/server/src/services/widget/__tests__/metrics.test.ts
@@ -0,0 +1,49 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { metricPoints, users } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { WidgetModel } from '@/database/models/widget';
+
+import { recordWidgetMetrics } from '../metrics';
+
+const userId = 'widget-metrics-user';
+let db: LobeChatDatabase;
+
+beforeEach(async () => {
+ db = await getTestDB();
+ await db.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+});
+
+describe('recordWidgetMetrics', () => {
+ it('trends a data output only through manifest.metric.valuePath', async () => {
+ const model = new WidgetModel(db, userId);
+ const widget = await model.create({ title: 'Weather' });
+ const version = await model.createVersion(widget.id, {
+ outputType: 'data',
+ runtime: 'node',
+ script: 'console.log("{}")',
+ sourceType: 'agent',
+ });
+ await model.publishVersion(widget.id, version!.id);
+ const run = await model.startRun(widget.id, { trigger: 'manual' });
+ const output = { data: { current: { temp: 18.4 } }, type: 'data' as const };
+ const record = (manifest?: { metric: { key: string; valuePath: string } }) =>
+ recordWidgetMetrics(db, widget, { manifest, observedAt: new Date(), output, runId: run!.id });
+
+ expect(await record()).toEqual({ pointsWritten: 0 });
+
+ const result = await record({ metric: { key: 'temp', valuePath: 'data.current.temp' } });
+ expect(result.pointsWritten).toBe(1);
+ const points = await db
+ .select()
+ .from(metricPoints)
+ .where(eq(metricPoints.metricId, result.primaryMetricId!));
+ expect(points.map((p) => p.value)).toEqual([18.4]);
+ });
+});
diff --git a/apps/server/src/services/widget/__tests__/outputContract.test.ts b/apps/server/src/services/widget/__tests__/outputContract.test.ts
index ad4cbf6f54b..f50b1b5c009 100644
--- a/apps/server/src/services/widget/__tests__/outputContract.test.ts
+++ b/apps/server/src/services/widget/__tests__/outputContract.test.ts
@@ -20,6 +20,13 @@ describe('parseWidgetOutput', () => {
type: 'table',
},
],
+ [
+ 'data',
+ {
+ data: { city: 'Hangzhou', hourly: [{ t: '2026-10-31T14:00', temp: 18 }], temp: 18.4 },
+ type: 'data',
+ },
+ ],
] as const)('accepts a valid %s output', (type, output) => {
const result = parseWidgetOutput(json(output), type);
@@ -70,6 +77,13 @@ describe('parseWidgetOutput', () => {
expect(!result.ok && result.message).toContain('value');
});
+ it('rejects a data output whose data is not an object', () => {
+ expect(parseWidgetOutput(json({ data: [1, 2], type: 'data' }))).toMatchObject({
+ code: 'INVALID_OUTPUT',
+ ok: false,
+ });
+ });
+
it('rejects unknown output types', () => {
expect(parseWidgetOutput(json({ type: 'pie', value: 1 }))).toMatchObject({
code: 'INVALID_OUTPUT',
diff --git a/apps/server/src/services/widget/layoutSchema.ts b/apps/server/src/services/widget/layoutSchema.ts
new file mode 100644
index 00000000000..2b815946f4f
--- /dev/null
+++ b/apps/server/src/services/widget/layoutSchema.ts
@@ -0,0 +1,257 @@
+import type { WidgetLayoutNode } from '@lobechat/types';
+import {
+ WIDGET_LAYOUT_COLORS,
+ WIDGET_LAYOUT_FORMATS,
+ WIDGET_LAYOUT_ICONS,
+ WIDGET_LAYOUT_LIMITS,
+ WIDGET_LAYOUT_SURFACES,
+} from '@lobechat/types';
+import { z } from 'zod';
+
+/**
+ * Validation of `WidgetView.layout` — the declarative card template. Values
+ * bound to data are checked by the renderer at display time; here only the
+ * tree's shape and size are fixed, so a stored layout always renders.
+ */
+
+const path = z
+ .string()
+ .min(1)
+ .max(200)
+ .regex(/^[\w$-]+(?:\.[\w$-]+)*$/, 'paths are dot-separated keys, e.g. data.hourly.0.temp');
+
+const literal = z.union([z.string().max(500), z.number().finite(), z.boolean(), z.null()]);
+
+const binding = z.strictObject({
+ bind: path,
+ digits: z.number().int().min(0).max(6).optional(),
+ fallback: literal.optional(),
+ format: z.enum(WIDGET_LAYOUT_FORMATS).optional(),
+ map: z.record(z.string().max(100), literal).optional(),
+ pattern: z.string().max(50).optional(),
+});
+
+const template = z.strictObject({ template: z.string().max(500) });
+
+const value = z.union([literal, binding, template]);
+
+const condition = z.strictObject({
+ bind: path,
+ eq: literal.optional(),
+ exists: z.boolean().optional(),
+ gt: z.number().optional(),
+ gte: z.number().optional(),
+ in: z.array(literal).max(50).optional(),
+ lt: z.number().optional(),
+ lte: z.number().optional(),
+ ne: literal.optional(),
+});
+
+const gap = z.number().min(0).max(48);
+const base = {
+ flex: z.number().min(0).max(12).optional(),
+ hideWhen: z.enum(['narrow', 'short']).optional(),
+ visible: condition.optional(),
+};
+const justify = z.enum(['start', 'center', 'end', 'between', 'around']);
+
+const node: z.ZodType<WidgetLayoutNode> = z.lazy(() =>
+ z.discriminatedUnion('type', [
+ z.strictObject({
+ ...base,
+ align: z.enum(['start', 'center', 'end', 'stretch', 'baseline']).optional(),
+ children: z.array(node).max(WIDGET_LAYOUT_LIMITS.nodes),
+ direction: z.enum(['row', 'column']).optional(),
+ gap: gap.optional(),
+ justify: justify.optional(),
+ padding: z.number().min(0).max(48).optional(),
+ type: z.literal('stack'),
+ wrap: z.boolean().optional(),
+ }),
+ z.strictObject({
+ ...base,
+ children: z.array(node).max(WIDGET_LAYOUT_LIMITS.nodes),
+ columns: z.number().int().min(1).max(12),
+ gap: gap.optional(),
+ type: z.literal('grid'),
+ }),
+ z.strictObject({
+ ...base,
+ align: z.enum(['start', 'center', 'end']).optional(),
+ lines: z.number().int().min(1).max(10).optional(),
+ size: z.enum(['xs', 'sm', 'md', 'lg', 'xl', '2xl', 'display']).optional(),
+ tone: z.enum(['default', 'secondary', 'tertiary', 'success', 'warning', 'error']).optional(),
+ type: z.literal('text'),
+ value,
+ weight: z.enum(['regular', 'medium', 'semibold', 'bold']).optional(),
+ }),
+ z.strictObject({
+ ...base,
+ color: value.optional(),
+ name: value,
+ size: z.number().min(8).max(160).optional(),
+ type: z.literal('icon'),
+ }),
+ z.strictObject({
+ ...base,
+ fit: z.enum(['cover', 'contain']).optional(),
+ height: z.number().min(8).max(800).optional(),
+ radius: z.number().min(0).max(400).optional(),
+ src: value,
+ type: z.literal('image'),
+ width: z.number().min(8).max(1600).optional(),
+ }),
+ z.strictObject({
+ ...base,
+ color: value.optional(),
+ max: value.optional(),
+ min: value.optional(),
+ type: z.literal('progress'),
+ value,
+ }),
+ z.strictObject({
+ ...base,
+ children: z.array(node).max(WIDGET_LAYOUT_LIMITS.nodes).optional(),
+ color: value.optional(),
+ max: value.optional(),
+ size: z.number().min(24).max(400).optional(),
+ type: z.literal('ring'),
+ value,
+ }),
+ z.strictObject({
+ ...base,
+ color: value.optional(),
+ columns: z.number().int().min(1).max(60).optional(),
+ total: value,
+ type: z.literal('dots'),
+ value,
+ }),
+ z.strictObject({
+ ...base,
+ color: value.optional(),
+ height: z.number().min(8).max(400).optional(),
+ key: z.string().max(100).optional(),
+ kind: z.enum(['line', 'area', 'bar']).optional(),
+ type: z.literal('sparkline'),
+ values: path,
+ }),
+ z.strictObject({ ...base, color: value.optional(), type: z.literal('badge'), value }),
+ z.strictObject({ ...base, type: z.literal('divider') }),
+ z.strictObject({ ...base, type: z.literal('spacer') }),
+ z.strictObject({
+ ...base,
+ direction: z.enum(['row', 'column']).optional(),
+ gap: gap.optional(),
+ items: path,
+ justify: justify.optional(),
+ limit: z.number().int().min(1).max(WIDGET_LAYOUT_LIMITS.repeat).optional(),
+ template: node,
+ type: z.literal('repeat'),
+ }),
+ ]),
+);
+
+const childrenOf = (n: WidgetLayoutNode): WidgetLayoutNode[] => {
+ if (n.type === 'stack' || n.type === 'grid') return n.children;
+ if (n.type === 'ring') return n.children ?? [];
+ if (n.type === 'repeat') return [n.template];
+ return [];
+};
+
+/** Literal colors and icon names are checked here; bound ones fall back at render time. */
+const literalIssues = (n: WidgetLayoutNode): string | undefined => {
+ if (
+ 'color' in n &&
+ typeof n.color === 'string' &&
+ !(WIDGET_LAYOUT_COLORS as readonly string[]).includes(n.color)
+ ) {
+ return `unknown color "${n.color}"; use one of ${WIDGET_LAYOUT_COLORS.join(', ')}`;
+ }
+ if (
+ n.type === 'icon' &&
+ typeof n.name === 'string' &&
+ !(WIDGET_LAYOUT_ICONS as readonly string[]).includes(n.name)
+ ) {
+ return `unknown icon "${n.name}"`;
+ }
+ if (n.type === 'image' && typeof n.src === 'string' && !n.src.startsWith('https://')) {
+ return 'image src must be an https URL';
+ }
+};
+
+/**
+ * Elements a node draws by itself: a `dots` node one per dot (its literal
+ * total, else the renderer's cap), a bar sparkline one per bar, the rest one.
+ */
+const elementCost = (n: WidgetLayoutNode): number => {
+ if (n.type === 'dots') {
+ const total = typeof n.total === 'number' ? Math.max(0, Math.ceil(n.total)) : Infinity;
+ return 1 + Math.min(total, WIDGET_LAYOUT_LIMITS.dots);
+ }
+ if (n.type === 'sparkline' && n.kind === 'bar') return 1 + WIDGET_LAYOUT_LIMITS.seriesPoints;
+ return 1;
+};
+
+/**
+ * Beyond its shape, a layout must stay small once drawn: a repeat multiplies
+ * its template by its item count, so templates are weighed by `limit` (the
+ * renderer's cap when unset), and a repeat may not sit inside another — nested
+ * caps would multiply into millions of nodes from a small tree.
+ */
+export const widgetLayoutSchema = node.superRefine((root, ctx) => {
+ let count = 0;
+ let expanded = 0;
+ const walk = (
+ n: WidgetLayoutNode,
+ depth: number,
+ at: (string | number)[],
+ weight = 1,
+ inRepeat = false,
+ ) => {
+ count += 1;
+ expanded += weight * elementCost(n);
+ if (n.type === 'repeat' && inRepeat) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'a repeat cannot be nested in another repeat',
+ path: at,
+ });
+ return;
+ }
+ if (depth > WIDGET_LAYOUT_LIMITS.depth) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `layout is nested deeper than ${WIDGET_LAYOUT_LIMITS.depth}`,
+ path: at,
+ });
+ return;
+ }
+ const issue = literalIssues(n);
+ if (issue) ctx.addIssue({ code: 'custom', message: issue, path: at });
+ const repeat = n.type === 'repeat';
+ childrenOf(n).forEach((child, index) =>
+ walk(
+ child,
+ depth + 1,
+ repeat ? [...at, 'template'] : [...at, 'children', index],
+ repeat ? weight * (n.limit ?? WIDGET_LAYOUT_LIMITS.repeat) : weight,
+ inRepeat || repeat,
+ ),
+ );
+ };
+ walk(root, 1, []);
+ if (expanded > WIDGET_LAYOUT_LIMITS.elements) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `layout draws up to ${expanded} elements once repeats, dots and bars expand; the limit is ${WIDGET_LAYOUT_LIMITS.elements} — lower repeat limits, dot totals or simplify the templates`,
+ });
+ }
+ if (count > WIDGET_LAYOUT_LIMITS.nodes) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `layout has ${count} nodes; the limit is ${WIDGET_LAYOUT_LIMITS.nodes}`,
+ });
+ }
+});
+
+export const widgetSurfaceSchema = z.union([z.enum(WIDGET_LAYOUT_SURFACES), binding]);
diff --git a/apps/server/src/services/widget/metrics.ts b/apps/server/src/services/widget/metrics.ts
index ac952ee5837..69d0d8d4622 100644
--- a/apps/server/src/services/widget/metrics.ts
+++ b/apps/server/src/services/widget/metrics.ts
@@ -60,6 +60,8 @@ const parseTime = (t: string): Date | undefined => {
*
* - `stat` — one point per run, the numeric `value` (or `manifest.metric.valuePath`)
* observed at the run's finish time. Non-numeric stats are skipped.
+ * - `data` — like `stat`, but only when `manifest.metric.valuePath` names the
+ * number to trend (e.g. `data.current.temp`).
* - `series` — one metric per series (`series:<name>`); only points with an
* ISO timestamp newer than the series' latest stored point are appended
* (serialized per series), so a script re-reporting a sliding window — even
@@ -112,9 +114,12 @@ export const recordWidgetMetrics = async (
sourceType: 'probe' as const,
};
- if (output.type === 'stat') {
+ if (output.type === 'stat' || output.type === 'data') {
+ const valuePath = manifest?.metric?.valuePath;
+ // A data output has no headline: it trends only the number valuePath names.
+ if (output.type === 'data' && !valuePath) return { pointsWritten: 0 };
const value = toNumber(
- manifest?.metric?.valuePath ? pickPath(output, manifest.metric.valuePath) : output.value,
+ valuePath ? pickPath(output, valuePath) : output.type === 'stat' ? output.value : undefined,
);
if (value === undefined) return { pointsWritten: 0 };
@@ -123,8 +128,8 @@ export const recordWidgetMetrics = async (
kind,
subjectId: widget.id,
subjectType: 'widget',
- title: output.label ?? widget.title,
- unit: manifest?.metric?.unit ?? output.unit,
+ title: (output.type === 'stat' ? output.label : undefined) ?? widget.title,
+ unit: manifest?.metric?.unit ?? (output.type === 'stat' ? output.unit : undefined),
});
if (!metric) return { pointsWritten: 0 };
diff --git a/apps/server/src/services/widget/outputContract.ts b/apps/server/src/services/widget/outputContract.ts
index 2fc7ce8e47c..430f49ed877 100644
--- a/apps/server/src/services/widget/outputContract.ts
+++ b/apps/server/src/services/widget/outputContract.ts
@@ -97,11 +97,19 @@ const tableSchema = z
}
});
+// Free-form: a layout binds to it by path. The byte limit above bounds its size.
+const dataSchema = z.object({
+ data: z.record(z.string(), z.unknown()),
+ meta: metaSchema,
+ type: z.literal('data'),
+});
+
const outputSchema = z.discriminatedUnion('type', [
statSchema,
listSchema,
seriesSchema,
tableSchema,
+ dataSchema,
]);
export type WidgetOutputErrorCode =
@@ -135,7 +143,7 @@ const extractJson = (stdout: string): unknown => {
/**
* Check a script's stdout against the widget output contract (stat / list /
- * series / table) and the version's declared output type.
+ * series / table / data) and the version's declared output type.
*
* `meta.complete === false` is accepted and reported as `partial`: the run
* finishes with status `partial` — its output is shown, but callers must not
diff --git a/apps/server/src/services/widget/versionSchema.ts b/apps/server/src/services/widget/versionSchema.ts
index e43a0d0aee1..35296b9de8d 100644
--- a/apps/server/src/services/widget/versionSchema.ts
+++ b/apps/server/src/services/widget/versionSchema.ts
@@ -1,6 +1,7 @@
import { WIDGET_OUTPUT_TYPES, WIDGET_RUNTIMES } from '@lobechat/types';
import { z } from 'zod';
+import { widgetLayoutSchema, widgetSurfaceSchema } from './layoutSchema';
import { WIDGET_SANDBOX_MAX_TIMEOUT_MS } from './sandbox/types';
/**
@@ -66,8 +67,10 @@ export const widgetManifestSchema = z.object({
export const widgetViewSchema = z.object({
chart: z.enum(['line', 'bar', 'area']).optional(),
columns: z.array(z.string()).optional(),
+ layout: widgetLayoutSchema.optional(),
limit: z.number().int().positive().max(500).optional(),
size: z.enum(['sm', 'md', 'lg']).optional(),
+ surface: widgetSurfaceSchema.optional(),
});
export const widgetVersionContentSchema = z.object({
diff --git a/packages/builtin-tool-dashboard/src/manifest.ts b/packages/builtin-tool-dashboard/src/manifest.ts
index 2ea2a16bc85..147d17d2c42 100644
--- a/packages/builtin-tool-dashboard/src/manifest.ts
+++ b/packages/builtin-tool-dashboard/src/manifest.ts
@@ -32,7 +32,7 @@ const runtimeSchema = {
const outputTypeSchema = {
description:
- 'Shape of the JSON the script prints: stat (one number), list (items), series (time series), table (columns + rows).',
+ 'Shape of the JSON the script prints: stat (one number), list (items), series (time series), table (columns + rows), data (free-form JSON drawn by view.layout — for rich cards such as weather).',
enum: [...WIDGET_OUTPUT_TYPES],
type: 'string',
};
@@ -124,7 +124,7 @@ const manifestSchema = {
const viewSchema = {
additionalProperties: false,
- description: 'Rendering hints for the card.',
+ description: 'How the card looks.',
properties: {
chart: { enum: ['line', 'bar', 'area'], type: 'string' },
columns: {
@@ -132,7 +132,17 @@ const viewSchema = {
items: { type: 'string' },
type: 'array',
},
+ layout: {
+ description:
+ 'Declarative card template (a tree of stack / grid / text / icon / image / progress / ring / dots / sparkline / badge / divider / spacer / repeat nodes) whose values bind to the output by path. Required for outputType data; replaces the default rendering for the other types. See <card_layout>.',
+ type: 'object',
+ },
limit: { description: 'Maximum list / table rows on the card.', type: 'number' },
+ surface: {
+ description:
+ 'Card background: a surface name (default, sky, cloudy, rain, storm, snow, night, sunset, forest, ocean, sand, rose, slate) or a binding {"bind":"data.x","map":{…}} that picks one from the data.',
+ type: ['string', 'object'],
+ },
},
type: 'object',
};
diff --git a/packages/builtin-tool-dashboard/src/systemRole.ts b/packages/builtin-tool-dashboard/src/systemRole.ts
index 272eb7c31b8..e51222fccc1 100644
--- a/packages/builtin-tool-dashboard/src/systemRole.ts
+++ b/packages/builtin-tool-dashboard/src/systemRole.ts
@@ -27,6 +27,7 @@ The script must print exactly ONE JSON document to stdout — nothing else (send
- list: {"type":"list","items":[{"title":"Fix login","url":"https://…","status":"open","time":"2026-01-02T03:04:05Z","value":3,"description":"…"}]}
- series: {"type":"series","unit":"ms","series":[{"name":"p95","points":[{"t":"2026-01-01","v":120},{"t":"2026-01-02","v":98}]}]}
- table: {"type":"table","columns":[{"key":"repo","title":"Repo"},{"key":"stars","type":"number"}],"rows":[{"repo":"lobehub","stars":100}]}
+- data: {"type":"data","data":{"city":"Hangzhou","temp":18,"cond":"rain","hourly":[{"t":"2026-01-02T14:00","temp":18}]}} — any JSON object; the card is drawn by view.layout (see <card_layout>)
Only "type" plus value / items / series / columns+rows are required. Column types: string | number | date | link. Timestamps are ISO-8601 strings.
Partial data: when one of several sources fails, still print the document with "meta":{"complete":false,"message":"GitHub API rate-limited"} — the card shows it as partial instead of failing. Exit non-zero only when there is nothing meaningful to show.
@@ -42,6 +43,31 @@ Partial data: when one of several sources fails, still print the document with "
- view hints: {"chart":"line"|"bar"|"area"} for series, {"columns":[…]} to pick table columns, {"limit":10} to cap list/table rows.
</script_rules>
+<card_layout>
+A single number is the right card for a single metric. When the data has more to say — weather, a countdown, a goal with progress, a leaderboard, several related numbers — use outputType "data" and design the card with view.layout. The script then reports clean data (raw numbers, ISO timestamps, short codes such as "rain"), and the layout decides presentation; to restyle, update only view and keep the script.
+
+Layout nodes (every node also accepts "flex" (grow factor), "visible" (condition) and "hideWhen":"narrow"|"short" to drop details on small cards):
+- stack {direction:"row"|"column", gap, align:"start"|"center"|"end"|"stretch"|"baseline", justify:"start"|"center"|"end"|"between"|"around", padding, wrap, children}
+- grid {columns, gap, children}
+- text {value, size:"xs"|"sm"|"md"|"lg"|"xl"|"2xl"|"display", weight:"regular"|"medium"|"semibold"|"bold", tone:"default"|"secondary"|"tertiary"|"success"|"warning"|"error", align, lines}
+- icon {name, size, color} — names: sun, moon, cloud, cloud-sun, cloud-moon, cloud-rain, cloud-drizzle, cloud-snow, cloud-lightning, cloud-fog, cloud-hail, snowflake, wind, droplet, droplets, thermometer, umbrella, sunrise, sunset, gauge, eye, navigation, arrow-up, arrow-down, trending-up, trending-down, check, x, alert-triangle, info, clock, calendar, map-pin, star, heart, flame, zap, activity, target, trophy, users, git-pull-request, git-commit, dollar-sign, server, database, globe, mail, message-circle, bell, timer
+- image {src (https), width, height, radius, fit}
+- progress {value, min, max, color} · ring {value, max, size, color, children} · dots {value, total, columns, color} (filled dots, e.g. days of the year)
+- sparkline {values:"data.hourly", key:"temp", kind:"line"|"area"|"bar", height, color}
+- badge {value, color} · divider · spacer
+- repeat {items:"data.hourly", limit, direction, gap, justify, template:<node>} — inside the template, "item" is the current element and "index" its position.
+
+Values: a literal; {"bind":"data.temp","format":"number","digits":0} (formats: number, compact, percent (0–1 ratio), date, time, datetime, weekday, relative; "pattern" takes a dayjs pattern); {"bind":"data.cond","map":{"rain":"cloud-rain","*":"cloud"}} (map raw values, "*" is the default); {"template":"H {data.hi}° · L {data.lo}°"} ("{item.t|time}" formats inside templates). Paths read data.* (the output's data; for stat/list/series/table, data is the whole output), item.*, index; array elements by number: data.hourly.0.temp.
+Conditions: {"bind":"data.alerts","exists":true}, {"bind":"data.temp","gt":30} (also eq, ne, gte, lt, lte, in).
+Colors: primary, success, warning, error, text, red, volcano, orange, gold, yellow, lime, green, cyan, blue, geekblue, purple, magenta — omitted means the text color.
+view.surface paints the whole card: default, sky, cloudy, rain, storm, snow, night, sunset, forest, ocean, sand, rose, slate — or a binding that picks one from the data, e.g. {"bind":"data.cond","map":{"clear":"sky","rain":"rain","*":"cloudy"}}. Colored surfaces use white text; secondary / tertiary tones dim it.
+
+Design: one hero element ("display" text or a ring), two or three supporting facts, details that fit the card; use "hideWhen" for what only a large card has room for. Default card is about 4×4 grid cells (≈ 300×300 px).
+
+Example — weather (outputType "data", network.allow ["api.open-meteo.com"], manifest.metric {"key":"temp","unit":"°C","valuePath":"data.temp"} to trend the temperature): the script prints {"type":"data","data":{"city":"Hangzhou","temp":18.9,"cond":"night","condText":"Clear","hi":25,"lo":15,"humidity":77,"wind":11.7,"rainChance":0,"hourly":[{"t":"2026-10-31T19:00","temp":19,"cond":"night"},…]}} and the view is
+{"surface":{"bind":"data.cond","map":{"clear":"sky","partly":"sky","night":"night","cloudy":"cloudy","fog":"cloudy","rain":"rain","snow":"snow","storm":"storm"}},"layout":{"type":"stack","gap":4,"children":[{"type":"stack","direction":"row","justify":"between","align":"start","children":[{"type":"stack","gap":2,"children":[{"type":"text","value":{"bind":"data.city"},"weight":"semibold"},{"type":"text","value":{"template":"{data.temp|number:0}°"},"size":"display","weight":"regular"}]},{"type":"icon","name":{"bind":"data.cond","map":{"clear":"sun","partly":"cloud-sun","night":"moon","cloudy":"cloud","fog":"cloud-fog","rain":"cloud-rain","snow":"cloud-snow","storm":"cloud-lightning","*":"cloud"}},"size":40}]},{"type":"text","value":{"template":"{data.condText} H {data.hi}° L {data.lo}°"},"size":"sm","tone":"secondary"},{"type":"stack","direction":"row","gap":14,"hideWhen":"narrow","children":[{"type":"stack","direction":"row","gap":4,"align":"center","children":[{"type":"icon","name":"droplets","size":14},{"type":"text","value":{"template":"{data.humidity}%"},"size":"sm"}]},{"type":"stack","direction":"row","gap":4,"align":"center","children":[{"type":"icon","name":"wind","size":14},{"type":"text","value":{"template":"{data.wind|number:0} km/h"},"size":"sm"}]},{"type":"stack","direction":"row","gap":4,"align":"center","children":[{"type":"icon","name":"umbrella","size":14},{"type":"text","value":{"template":"{data.rainChance}%"},"size":"sm"}]}]},{"type":"spacer"},{"type":"repeat","items":"data.hourly","limit":6,"direction":"row","justify":"between","hideWhen":"short","template":{"type":"stack","gap":6,"align":"center","children":[{"type":"text","value":"Now","size":"xs","tone":"secondary","visible":{"bind":"index","eq":0}},{"type":"text","value":{"bind":"item.t","format":"time"},"size":"xs","tone":"secondary","visible":{"bind":"index","ne":0}},{"type":"icon","name":{"bind":"item.cond","map":{"clear":"sun","partly":"cloud-sun","night":"moon","cloudy":"cloud","fog":"cloud-fog","rain":"cloud-rain","snow":"cloud-snow","storm":"cloud-lightning","*":"cloud"}},"size":18},{"type":"text","value":{"template":"{item.temp}°"},"size":"sm","weight":"medium"}]}}]}}
+</card_layout>
+
<metric_definition>
The description (口径) is shown on the card and must let the user trust the number: the data source, filters, time window, and unit — e.g. "Open issues labelled bug in lobehub/lobehub, excluding pull requests; counted at run time." Update it whenever the script's logic changes.
</metric_definition>
diff --git a/packages/database/src/models/__tests__/dashboard.test.ts b/packages/database/src/models/__tests__/dashboard.test.ts
index 12aaa690b96..17c9d08308a 100644
--- a/packages/database/src/models/__tests__/dashboard.test.ts
+++ b/packages/database/src/models/__tests__/dashboard.test.ts
@@ -348,6 +348,43 @@ describe('DashboardModel', () => {
expect((await model.listItems(dashboard.id)).map((r) => r.widget.id)).toEqual([w1.id]);
});
+ it("lists each item with its widget's published view", async () => {
+ const model = new DashboardModel(serverDB, userId);
+ const dashboard = await model.create({ title: 'Weather' });
+ const widgets = new WidgetModel(serverDB, userId);
+ const weather = await widgets.create({ title: 'Weather' });
+ const draftOnly = await widgets.create({ title: 'Draft only' });
+ await model.addItem(dashboard.id, weather.id);
+ await model.addItem(dashboard.id, draftOnly.id);
+
+ const view = {
+ layout: { type: 'text' as const, value: { bind: 'data.temp' } },
+ surface: 'rain',
+ };
+ const version = await widgets.createVersion(weather.id, {
+ outputType: 'data',
+ runtime: 'node',
+ script: 'console.log("{}")',
+ sourceType: 'agent',
+ view,
+ });
+ await widgets.publishVersion(weather.id, version!.id);
+ await widgets.createVersion(draftOnly.id, {
+ outputType: 'stat',
+ runtime: 'node',
+ script: '1',
+ sourceType: 'agent',
+ view: { chart: 'bar' },
+ });
+
+ const listed = await model.listItems(dashboard.id);
+
+ expect(listed.map((r) => [r.widget.title, r.view])).toEqual([
+ ['Weather', view],
+ ['Draft only', null],
+ ]);
+ });
+
it('refuses a new widget on a full board but still updates placed ones', async () => {
const model = new DashboardModel(serverDB, userId);
const dashboard = await model.create({ title: 'Full' });
diff --git a/packages/database/src/models/__tests__/widget.test.ts b/packages/database/src/models/__tests__/widget.test.ts
index dd8cfa34dfe..40bba15f0f7 100644
--- a/packages/database/src/models/__tests__/widget.test.ts
+++ b/packages/database/src/models/__tests__/widget.test.ts
@@ -301,6 +301,8 @@ describe('WidgetModel', () => {
expect((await model.findById(inProject.id))?.id).toBe(inProject.id);
expect((await model.findById(inAgent.id))?.id).toBe(inAgent.id);
expect((await model.listByProject('wgt-proj-bin')).map((w) => w.id)).toEqual([inProject.id]);
+ // each project widget carries its published version's view for the card
+ expect((await model.listByProject('wgt-proj-bin'))[0].publishedView).toEqual({ size: 'sm' });
expect(await model.listRuns(inProject.id)).toHaveLength(1);
expect((await member.findById(wsInProject.id))?.id).toBe(wsInProject.id);
expect((await member.list({ agentId: 'wgt-agent-bin-ws' })).map((w) => w.id)).toEqual([
diff --git a/packages/database/src/models/dashboard.ts b/packages/database/src/models/dashboard.ts
index 8426e680b84..c65f78972d0 100644
--- a/packages/database/src/models/dashboard.ts
+++ b/packages/database/src/models/dashboard.ts
@@ -4,7 +4,7 @@ import { and, asc, count, eq, inArray, max } from 'drizzle-orm';
import { agents } from '../schemas/agent';
import { dashboardItems, dashboards } from '../schemas/dashboard';
import { projects } from '../schemas/project';
-import { widgets } from '../schemas/widget';
+import { widgets, widgetVersions } from '../schemas/widget';
import type { LobeChatDatabase, Transaction } from '../type';
import {
assertScopeParents,
@@ -325,18 +325,20 @@ export class DashboardModel {
}
/**
- * Items of a readable board with their widgets, in display order. Widgets the
- * caller cannot read (trashed, private to a teammate, under a private
- * parent) drop out without losing their placement.
+ * Items of a readable board with their widgets and the published version's
+ * view (how the card draws the output; null before the first publish), in
+ * display order. Widgets the caller cannot read (trashed, private to a
+ * teammate, under a private parent) drop out without losing their placement.
*/
async listItems(dashboardId: string) {
const dashboard = await this.findById(dashboardId);
if (!dashboard) return [];
return this.db
- .select({ item: dashboardItems, widget: widgets })
+ .select({ item: dashboardItems, view: widgetVersions.view, widget: widgets })
.from(dashboardItems)
.innerJoin(widgets, eq(dashboardItems.widgetId, widgets.id))
+ .leftJoin(widgetVersions, eq(widgets.publishedVersionId, widgetVersions.id))
.where(and(eq(dashboardItems.dashboardId, dashboardId), this.readableWidget()))
.orderBy(asc(dashboardItems.sortOrder), asc(dashboardItems.createdAt));
}
diff --git a/packages/database/src/models/widget.ts b/packages/database/src/models/widget.ts
index 72aa48d9e46..2e47c146879 100644
--- a/packages/database/src/models/widget.ts
+++ b/packages/database/src/models/widget.ts
@@ -12,7 +12,20 @@ import type {
WidgetVisibility,
} from '@lobechat/types';
import { WIDGET_RUN_OUTPUT_STATUSES } from '@lobechat/types';
-import { and, asc, desc, eq, gte, inArray, isNotNull, lt, lte, max, sql } from 'drizzle-orm';
+import {
+ and,
+ asc,
+ desc,
+ eq,
+ getTableColumns,
+ gte,
+ inArray,
+ isNotNull,
+ lt,
+ lte,
+ max,
+ sql,
+} from 'drizzle-orm';
import { sha256Json } from '../repositories/ftsSearchDocument/fingerprint';
import { agents } from '../schemas/agent';
@@ -209,11 +222,16 @@ export class WidgetModel {
.orderBy(desc(widgets.updatedAt));
}
- /** Every widget of a project, including those an agent of the project also owns. */
+ /**
+ * Every widget of a project, including those an agent of the project also
+ * owns, each with its published version's view (how the card draws the
+ * output; null before the first publish).
+ */
async listByProject(projectId: string) {
return this.db
- .select()
+ .select({ ...getTableColumns(widgets), publishedView: widgetVersions.view })
.from(widgets)
+ .leftJoin(widgetVersions, eq(widgets.publishedVersionId, widgetVersions.id))
.where(and(this.readable(), buildProjectWhere(widgets, projectId)))
.orderBy(desc(widgets.updatedAt));
}
diff --git a/packages/types/src/widget/index.ts b/packages/types/src/widget/index.ts
index 4f96ffe603a..822807afddc 100644
--- a/packages/types/src/widget/index.ts
+++ b/packages/types/src/widget/index.ts
@@ -8,6 +8,10 @@
// scheduling, versioning and rendering. Widgets are a standalone entity so any
// host surface (a board, a goal, an agent page …) can mount the same widget.
+import type { WidgetLayoutNode, WidgetLayoutValue } from './layout';
+
+export * from './layout';
+
export const WIDGET_VISIBILITIES = ['private', 'public'] as const;
export type WidgetVisibility = (typeof WIDGET_VISIBILITIES)[number];
@@ -36,7 +40,7 @@ export interface WidgetLevelFilter {
export const WIDGET_RUNTIMES = ['node', 'python', 'bash'] as const;
export type WidgetRuntime = (typeof WIDGET_RUNTIMES)[number];
-export const WIDGET_OUTPUT_TYPES = ['stat', 'list', 'series', 'table'] as const;
+export const WIDGET_OUTPUT_TYPES = ['stat', 'list', 'series', 'table', 'data'] as const;
export type WidgetOutputType = (typeof WIDGET_OUTPUT_TYPES)[number];
export type WidgetTrend = 'up' | 'down' | 'flat';
@@ -116,9 +120,20 @@ export interface WidgetTableOutput {
type: 'table';
}
+/**
+ * Free-form data for a card drawn by `WidgetView.layout`, e.g. a forecast
+ * with the current reading, today's range and the next hours. The layout
+ * binds to it as `data.*`.
+ */
+export interface WidgetDataOutput {
+ data: Record<string, unknown>;
+ meta?: WidgetOutputMeta;
+ type: 'data';
+}
+
/** The JSON document a widget script prints to stdout. */
export type WidgetOutput =
- WidgetStatOutput | WidgetListOutput | WidgetSeriesOutput | WidgetTableOutput;
+ WidgetStatOutput | WidgetListOutput | WidgetSeriesOutput | WidgetTableOutput | WidgetDataOutput;
/** One secret or variable the script expects in its environment. */
export interface WidgetEnvRequirement {
@@ -208,9 +223,16 @@ export interface WidgetView {
chart?: 'line' | 'bar' | 'area';
/** Column keys to show, in order, for table output. */
columns?: string[];
+ /**
+ * Declarative card template. When set it replaces the built-in rendering of
+ * the output type; required to show a `data` output.
+ */
+ layout?: WidgetLayoutNode;
/** Maximum list / table rows before truncation. */
limit?: number;
size?: 'sm' | 'md' | 'lg';
+ /** Card background, a `WidgetLayoutSurface` — may be bound to the data. */
+ surface?: WidgetLayoutValue;
}
// ── Versions ────────────────────────────────────────────
diff --git a/packages/types/src/widget/layout.ts b/packages/types/src/widget/layout.ts
new file mode 100644
index 00000000000..59aa52306a2
--- /dev/null
+++ b/packages/types/src/widget/layout.ts
@@ -0,0 +1,324 @@
+// ============================================
+// Widget layout — a declarative card template
+// ============================================
+//
+// A widget script reports data; `WidgetView.layout` decides how that data
+// looks. The layout is a small JSON tree of fixed primitives whose values bind
+// to the output by path, so the agent (or a preset) can design a rich card
+// without shipping code to the browser, and the card follows the app theme.
+
+export type WidgetLayoutLiteral = string | number | boolean | null;
+
+/**
+ * How a bound value is printed:
+ *
+ * - `number` — locale grouping, `digits` fraction digits (default up to 2)
+ * - `compact` — 1.2K / 3.4M
+ * - `percent` — a 0–1 ratio as 42%
+ * - `date` / `time` / `datetime` / `weekday` — an ISO timestamp, or `pattern`
+ * (dayjs) for anything else
+ * - `relative` — "3 hours ago"
+ */
+export const WIDGET_LAYOUT_FORMATS = [
+ 'number',
+ 'compact',
+ 'percent',
+ 'date',
+ 'time',
+ 'datetime',
+ 'weekday',
+ 'relative',
+] as const;
+export type WidgetLayoutFormat = (typeof WIDGET_LAYOUT_FORMATS)[number];
+
+/**
+ * Read a value from the scope by path: `data.temp`, `data.hourly.0.temp`,
+ * `item.t` inside a `repeat`. `map` translates the raw value (e.g. a weather
+ * code to an icon name), `fallback` stands in when the path is missing.
+ */
+export interface WidgetLayoutBinding {
+ bind: string;
+ digits?: number;
+ fallback?: WidgetLayoutLiteral;
+ format?: WidgetLayoutFormat;
+ map?: Record<string, WidgetLayoutLiteral>;
+ /** dayjs pattern for date-like formats, e.g. 'HH:mm'. */
+ pattern?: string;
+}
+
+/** A string with `{path}` placeholders, e.g. "H {data.hi}° · L {data.lo}°". */
+export interface WidgetLayoutTemplate {
+ template: string;
+}
+
+export type WidgetLayoutValue = WidgetLayoutLiteral | WidgetLayoutBinding | WidgetLayoutTemplate;
+
+/** Show a node only when the bound value passes every given comparison. */
+export interface WidgetLayoutCondition {
+ bind: string;
+ eq?: WidgetLayoutLiteral;
+ exists?: boolean;
+ gt?: number;
+ gte?: number;
+ in?: WidgetLayoutLiteral[];
+ lt?: number;
+ lte?: number;
+ ne?: WidgetLayoutLiteral;
+}
+
+/** Palette colors, plus semantic ones that follow the theme. */
+export const WIDGET_LAYOUT_COLORS = [
+ 'primary',
+ 'success',
+ 'warning',
+ 'error',
+ 'text',
+ 'red',
+ 'volcano',
+ 'orange',
+ 'gold',
+ 'yellow',
+ 'lime',
+ 'green',
+ 'cyan',
+ 'blue',
+ 'geekblue',
+ 'purple',
+ 'magenta',
+] as const;
+export type WidgetLayoutColor = (typeof WIDGET_LAYOUT_COLORS)[number];
+
+/**
+ * Card backgrounds. `default` is the theme's card; the rest are fixed
+ * gradients with light text, picked to read in both light and dark mode.
+ */
+export const WIDGET_LAYOUT_SURFACES = [
+ 'default',
+ 'sky',
+ 'cloudy',
+ 'rain',
+ 'storm',
+ 'snow',
+ 'night',
+ 'sunset',
+ 'forest',
+ 'ocean',
+ 'sand',
+ 'rose',
+ 'slate',
+] as const;
+export type WidgetLayoutSurface = (typeof WIDGET_LAYOUT_SURFACES)[number];
+
+/** Icons a layout may name; kept to a fixed set so the bundle stays bounded. */
+export const WIDGET_LAYOUT_ICONS = [
+ // weather
+ 'sun',
+ 'moon',
+ 'cloud',
+ 'cloud-sun',
+ 'cloud-moon',
+ 'cloud-rain',
+ 'cloud-drizzle',
+ 'cloud-snow',
+ 'cloud-lightning',
+ 'cloud-fog',
+ 'cloud-hail',
+ 'snowflake',
+ 'wind',
+ 'droplet',
+ 'droplets',
+ 'thermometer',
+ 'umbrella',
+ 'sunrise',
+ 'sunset',
+ 'gauge',
+ 'eye',
+ 'navigation',
+ // general
+ 'arrow-up',
+ 'arrow-down',
+ 'trending-up',
+ 'trending-down',
+ 'check',
+ 'x',
+ 'alert-triangle',
+ 'info',
+ 'clock',
+ 'calendar',
+ 'map-pin',
+ 'star',
+ 'heart',
+ 'flame',
+ 'zap',
+ 'activity',
+ 'target',
+ 'trophy',
+ 'users',
+ 'git-pull-request',
+ 'git-commit',
+ 'dollar-sign',
+ 'server',
+ 'database',
+ 'globe',
+ 'mail',
+ 'message-circle',
+ 'bell',
+ 'timer',
+] as const;
+export type WidgetLayoutIconName = (typeof WIDGET_LAYOUT_ICONS)[number];
+
+export type WidgetLayoutTone =
+ 'default' | 'secondary' | 'tertiary' | 'success' | 'warning' | 'error';
+
+interface WidgetLayoutNodeBase {
+ /** Grow factor inside a stack, like CSS flex-grow. */
+ flex?: number;
+ /** Drop the node when the card is narrow (< 280px) or short (< 180px). */
+ hideWhen?: 'narrow' | 'short';
+ visible?: WidgetLayoutCondition;
+}
+
+export interface WidgetLayoutStackNode extends WidgetLayoutNodeBase {
+ align?: 'start' | 'center' | 'end' | 'stretch' | 'baseline';
+ children: WidgetLayoutNode[];
+ direction?: 'row' | 'column';
+ gap?: number;
+ justify?: 'start' | 'center' | 'end' | 'between' | 'around';
+ padding?: number;
+ type: 'stack';
+ wrap?: boolean;
+}
+
+export interface WidgetLayoutGridNode extends WidgetLayoutNodeBase {
+ children: WidgetLayoutNode[];
+ columns: number;
+ gap?: number;
+ type: 'grid';
+}
+
+export interface WidgetLayoutTextNode extends WidgetLayoutNodeBase {
+ align?: 'start' | 'center' | 'end';
+ /** Clamp to this many lines. */
+ lines?: number;
+ size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'display';
+ tone?: WidgetLayoutTone;
+ type: 'text';
+ value: WidgetLayoutValue;
+ weight?: 'regular' | 'medium' | 'semibold' | 'bold';
+}
+
+export interface WidgetLayoutIconNode extends WidgetLayoutNodeBase {
+ color?: WidgetLayoutValue;
+ /** One of `WIDGET_LAYOUT_ICONS`, usually mapped from data. */
+ name: WidgetLayoutValue;
+ size?: number;
+ type: 'icon';
+}
+
+export interface WidgetLayoutImageNode extends WidgetLayoutNodeBase {
+ fit?: 'cover' | 'contain';
+ height?: number;
+ radius?: number;
+ /** https URL only. */
+ src: WidgetLayoutValue;
+ type: 'image';
+ width?: number;
+}
+
+export interface WidgetLayoutProgressNode extends WidgetLayoutNodeBase {
+ color?: WidgetLayoutValue;
+ max?: WidgetLayoutValue;
+ min?: WidgetLayoutValue;
+ type: 'progress';
+ value: WidgetLayoutValue;
+}
+
+export interface WidgetLayoutRingNode extends WidgetLayoutNodeBase {
+ /** Content in the middle of the ring. */
+ children?: WidgetLayoutNode[];
+ color?: WidgetLayoutValue;
+ max?: WidgetLayoutValue;
+ size?: number;
+ type: 'ring';
+ value: WidgetLayoutValue;
+}
+
+export interface WidgetLayoutDotsNode extends WidgetLayoutNodeBase {
+ color?: WidgetLayoutValue;
+ columns?: number;
+ total: WidgetLayoutValue;
+ type: 'dots';
+ /** How many dots are filled. */
+ value: WidgetLayoutValue;
+}
+
+export interface WidgetLayoutSparklineNode extends WidgetLayoutNodeBase {
+ color?: WidgetLayoutValue;
+ height?: number;
+ /** Property to read from each item when `values` points at objects. */
+ key?: string;
+ kind?: 'line' | 'area' | 'bar';
+ type: 'sparkline';
+ /** Path to an array of numbers (or of objects, with `key`). */
+ values: string;
+}
+
+export interface WidgetLayoutBadgeNode extends WidgetLayoutNodeBase {
+ color?: WidgetLayoutValue;
+ type: 'badge';
+ value: WidgetLayoutValue;
+}
+
+export interface WidgetLayoutDividerNode extends WidgetLayoutNodeBase {
+ type: 'divider';
+}
+
+export interface WidgetLayoutSpacerNode extends WidgetLayoutNodeBase {
+ type: 'spacer';
+}
+
+/** Render `template` once per array item; inside it `item` and `index` are in scope. */
+export interface WidgetLayoutRepeatNode extends WidgetLayoutNodeBase {
+ direction?: 'row' | 'column';
+ gap?: number;
+ items: string;
+ justify?: 'start' | 'center' | 'end' | 'between' | 'around';
+ limit?: number;
+ template: WidgetLayoutNode;
+ type: 'repeat';
+}
+
+export type WidgetLayoutNode =
+ | WidgetLayoutStackNode
+ | WidgetLayoutGridNode
+ | WidgetLayoutTextNode
+ | WidgetLayoutIconNode
+ | WidgetLayoutImageNode
+ | WidgetLayoutProgressNode
+ | WidgetLayoutRingNode
+ | WidgetLayoutDotsNode
+ | WidgetLayoutSparklineNode
+ | WidgetLayoutBadgeNode
+ | WidgetLayoutDividerNode
+ | WidgetLayoutSpacerNode
+ | WidgetLayoutRepeatNode;
+
+export type WidgetLayoutNodeType = WidgetLayoutNode['type'];
+
+/** Bounds every stored layout stays within. */
+export const WIDGET_LAYOUT_LIMITS = {
+ depth: 12,
+ /** Most dots one `dots` node draws. */
+ dots: 400,
+ /**
+ * Elements one card may draw: every node once, a `dots` node per dot, a bar
+ * sparkline per bar, all multiplied by the enclosing repeat's limit.
+ */
+ elements: 2000,
+ nodes: 200,
+ repeat: 48,
+ /** Most points a sparkline draws; longer arrays are sampled down. */
+ seriesPoints: 240,
+ /** Most characters one text value prints, and one template slot contributes. */
+ textLength: 500,
+} as const;
diff --git a/src/features/Dashboard/Board/BoardWidgetCard.tsx b/src/features/Dashboard/Board/BoardWidgetCard.tsx
index 7a16e776caa..0bfca07209a 100644
--- a/src/features/Dashboard/Board/BoardWidgetCard.tsx
+++ b/src/features/Dashboard/Board/BoardWidgetCard.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { WidgetView } from '@lobechat/types';
import { memo } from 'react';
import type { DashboardWidgetItem } from '@/services/dashboard';
@@ -11,11 +12,13 @@ import WidgetRefreshButton from '../WidgetRefreshButton';
interface BoardWidgetCardProps {
onOpen: (widgetId: string) => void;
+ /** The published version's view; null before the first publish. */
+ view?: WidgetView | null;
widget: DashboardWidgetItem;
}
/** A widget card wired to the board: live trend, manual refresh and drill-down. */
-const BoardWidgetCard = memo<BoardWidgetCardProps>(({ widget, onOpen }) => {
+const BoardWidgetCard = memo<BoardWidgetCardProps>(({ view, widget, onOpen }) => {
const trend = useWidgetTrend(widget);
const running = useDashboardStore(dashboardSelectors.isWidgetRunning(widget.id));
@@ -24,6 +27,7 @@ const BoardWidgetCard = memo<BoardWidgetCardProps>(({ widget, onOpen }) => {
actions={<WidgetRefreshButton widget={widget} />}
runningLocally={running}
trend={trend}
+ view={view}
widget={widget}
onOpen={() => onOpen(widget.id)}
/>
diff --git a/src/features/Dashboard/Board/LayoutEditor.tsx b/src/features/Dashboard/Board/LayoutEditor.tsx
index ce58707462c..1a4ade13067 100644
--- a/src/features/Dashboard/Board/LayoutEditor.tsx
+++ b/src/features/Dashboard/Board/LayoutEditor.tsx
@@ -148,6 +148,7 @@ const EditableCell = memo<EditableCellProps>(({ entry, layout, onResize, editabl
>
<WidgetCard
className={gridStyles.editCard}
+ view={entry.view}
widget={entry.widget}
handle={
<span
diff --git a/src/features/Dashboard/Board/index.tsx b/src/features/Dashboard/Board/index.tsx
index e28cdc9467a..70d4e2ddb24 100644
--- a/src/features/Dashboard/Board/index.tsx
+++ b/src/features/Dashboard/Board/index.tsx
@@ -114,14 +114,14 @@ const DashboardBoard = memo<DashboardBoardProps>(({ dashboardId, empty }) => {
onRefreshAll={() => void handleRefreshAll()}
/>
<div className={gridStyles.grid} data-dashboard-grid={'view'}>
- {ordered.map(({ item, widget }) => (
+ {ordered.map(({ item, view, widget }) => (
<div
className={gridStyles.cell}
data-layout-cell={item.id}
key={item.id}
style={cellStyle(layouts[item.id])}
>
- <BoardWidgetCard widget={widget} onOpen={setOpenWidgetId} />
+ <BoardWidgetCard view={view} widget={widget} onOpen={setOpenWidgetId} />
</div>
))}
</div>
diff --git a/src/features/Dashboard/WidgetCard/index.tsx b/src/features/Dashboard/WidgetCard/index.tsx
index 0ef7efc4f66..ce6ebfb627b 100644
--- a/src/features/Dashboard/WidgetCard/index.tsx
+++ b/src/features/Dashboard/WidgetCard/index.tsx
@@ -24,6 +24,7 @@ import { getWidgetCardBody, getWidgetHealth, getWidgetUpdatedAt } from '../utils
import HealthDot from './HealthDot';
import StatusBadges from './StatusBadges';
import WidgetOutputView from './views';
+import { createLayoutScope, resolveSurface, WIDGET_SURFACE_STYLES } from './views/LayoutView';
const styles = createStaticStyles(({ css }) => ({
actions: css`
@@ -136,7 +137,14 @@ const WidgetCard = memo<WidgetCardProps>(
// Lists and tables are the only outputs taller than their card; the rest size to it.
const scrollable =
- bodyState === 'output' && (output?.type === 'list' || output?.type === 'table');
+ bodyState === 'output' &&
+ !view?.layout &&
+ (output?.type === 'list' || output?.type === 'table');
+ // A layout may paint the whole card; header and footer then follow its text color.
+ const surface =
+ view?.layout && output
+ ? WIDGET_SURFACE_STYLES[resolveSurface(view.surface, createLayoutScope(output))]
+ : undefined;
let body: ReactNode;
if (bodyState === 'output' && output) {
@@ -176,13 +184,21 @@ const WidgetCard = memo<WidgetCardProps>(
className={cx(styles.card, onOpen && styles.clickable, className)}
data-widget-id={widget.id}
data-widget-running={health.running}
+ data-widget-surface={surface ? 'custom' : undefined}
gap={10}
+ style={surface}
onClick={onOpen}
>
<Flexbox horizontal align={'center'} className={styles.header} gap={6}>
{handle}
{title ?? (
- <Text ellipsis className={styles.title} title={widget.title} weight={500}>
+ <Text
+ ellipsis
+ className={styles.title}
+ style={surface && { color: 'inherit' }}
+ title={widget.title}
+ weight={500}
+ >
{widget.title}
</Text>
)}
@@ -202,7 +218,13 @@ const WidgetCard = memo<WidgetCardProps>(
</Flexbox>
<div className={cx(styles.body, scrollable && styles.bodyScrollable)}>{body}</div>
{updatedAt && (
- <Flexbox horizontal align={'center'} className={styles.footer} gap={6}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.footer}
+ gap={6}
+ style={surface && { color: 'inherit', opacity: 0.72 }}
+ >
<HealthDot health={health} />
<Tooltip title={dayjs(updatedAt).format('YYYY-MM-DD HH:mm:ss')}>
<span data-widget-updated>
diff --git a/src/features/Dashboard/WidgetCard/views/DataView.tsx b/src/features/Dashboard/WidgetCard/views/DataView.tsx
new file mode 100644
index 00000000000..af27c1032d0
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/DataView.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import type { WidgetDataOutput } from '@lobechat/types';
+import { Flexbox, Text } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { formatLayoutValue } from './LayoutView/resolve';
+
+/**
+ * A `data` output whose version has no layout yet: its top-level scalar
+ * fields as label / value rows, so the card still shows what the script
+ * reported instead of nothing.
+ */
+const DataView = memo<{ output: WidgetDataOutput }>(({ output }) => {
+ const rows = Object.entries(output.data).filter(
+ ([, value]) => value === null || typeof value !== 'object',
+ );
+
+ return (
+ <Flexbox gap={4}>
+ {rows.map(([key, value]) => (
+ <Flexbox horizontal gap={12} justify={'space-between'} key={key}>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {key}
+ </Text>
+ <Text ellipsis fontSize={13} weight={500}>
+ {formatLayoutValue(value)}
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ );
+});
+
+DataView.displayName = 'DashboardDataView';
+
+export default DataView;
diff --git a/src/features/Dashboard/WidgetCard/views/LayoutView/LayoutNode.tsx b/src/features/Dashboard/WidgetCard/views/LayoutView/LayoutNode.tsx
new file mode 100644
index 00000000000..8e9327a5468
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/LayoutView/LayoutNode.tsx
@@ -0,0 +1,557 @@
+'use client';
+
+import type { WidgetLayoutIconName, WidgetLayoutNode } from '@lobechat/types';
+import { WIDGET_LAYOUT_LIMITS } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
+import type { StyleXStyles } from '@stylexjs/stylex';
+import * as stylex from '@stylexjs/stylex';
+import { type CSSProperties, Fragment, type ReactNode, useId } from 'react';
+
+import { sparklinePoints } from '../../../utils/series';
+import { WIDGET_LAYOUT_ICON_MAP } from './icons';
+import {
+ checkCondition,
+ getPath,
+ type LayoutScope,
+ resolveColor,
+ resolveNumber,
+ resolveNumbers,
+ resolveRaw,
+ resolveText,
+} from './resolve';
+
+const styles = stylex.create({
+ badge: {
+ alignItems: 'center',
+ borderRadius: 999,
+ display: 'inline-flex',
+ fontSize: 11,
+ fontWeight: 500,
+ lineHeight: '18px',
+ paddingInline: 7,
+ whiteSpace: 'nowrap',
+ },
+ box: {
+ display: 'flex',
+ minHeight: 0,
+ minWidth: 0,
+ },
+ clamp: {
+ WebkitBoxOrient: 'vertical',
+ display: '-webkit-box',
+ overflow: 'hidden',
+ },
+ divider: {
+ alignSelf: 'stretch',
+ backgroundColor: 'currentColor',
+ flexShrink: 0,
+ minHeight: 1,
+ minWidth: 1,
+ opacity: 0.15,
+ },
+ dot: {
+ aspectRatio: '1',
+ borderRadius: '50%',
+ width: '100%',
+ },
+ // A wrapper that is not a box at all, so the node inside keeps its own display.
+ hideNarrow: {
+ display: {
+ '@container (max-width: 279px)': 'none',
+ 'default': 'contents',
+ },
+ },
+ hideShort: {
+ display: {
+ '@container (max-height: 179px)': 'none',
+ 'default': 'contents',
+ },
+ },
+ image: {
+ display: 'block',
+ maxWidth: '100%',
+ },
+ nowrap: {
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ sizeDisplay: {
+ fontSize: 'clamp(32px, min(22cqi, 34cqh), 88px)',
+ fontVariantNumeric: 'tabular-nums',
+ letterSpacing: '-0.04em',
+ lineHeight: 1,
+ },
+ sizeLg: { fontSize: 16, lineHeight: 1.4 },
+ sizeMd: { fontSize: 14, lineHeight: 1.45 },
+ sizeSm: { fontSize: 12, lineHeight: 1.45 },
+ sizeXl: { fontSize: 20, letterSpacing: '-0.01em', lineHeight: 1.3 },
+ sizeXs: { fontSize: 11, lineHeight: 1.4 },
+ size2xl: {
+ fontSize: 28,
+ fontVariantNumeric: 'tabular-nums',
+ letterSpacing: '-0.02em',
+ lineHeight: 1.15,
+ },
+ spacer: {
+ flexGrow: 1,
+ },
+ text: {
+ margin: 0,
+ minWidth: 0,
+ },
+ toneSecondary: { opacity: 0.72 },
+ toneTertiary: { opacity: 0.5 },
+ track: {
+ backgroundColor: 'color-mix(in srgb, currentColor 16%, transparent)',
+ borderRadius: 999,
+ height: 6,
+ overflow: 'hidden',
+ width: '100%',
+ },
+ trackFill: {
+ borderRadius: 999,
+ height: '100%',
+ transformOrigin: 'left',
+ transitionDuration: '0.3s',
+ transitionProperty: 'transform',
+ width: '100%',
+ },
+});
+
+const SIZE_STYLES = {
+ '2xl': styles.size2xl,
+ 'display': styles.sizeDisplay,
+ 'lg': styles.sizeLg,
+ 'md': styles.sizeMd,
+ 'sm': styles.sizeSm,
+ 'xl': styles.sizeXl,
+ 'xs': styles.sizeXs,
+};
+
+const WEIGHTS = { bold: 700, medium: 500, regular: 400, semibold: 600 };
+
+const TONE_COLORS: Record<string, string | undefined> = {
+ error: resolveColor('error', {}),
+ success: resolveColor('success', {}),
+ warning: resolveColor('warning', {}),
+};
+
+const ALIGN = {
+ baseline: 'baseline',
+ center: 'center',
+ end: 'flex-end',
+ start: 'flex-start',
+ stretch: 'stretch',
+};
+
+const JUSTIFY = {
+ around: 'space-around',
+ between: 'space-between',
+ center: 'center',
+ end: 'flex-end',
+ start: 'flex-start',
+};
+
+const TEXT_ALIGN = { center: 'center', end: 'end', start: 'start' } as const;
+
+/** StyleX classes plus the node's own inline values on one element. */
+const props = (xstyle: StyleXStyles, style?: CSSProperties) => {
+ const result = stylex.props(xstyle);
+ return { className: result.className, style: { ...result.style, ...style } };
+};
+
+const clamp01 = (value: number) => Math.min(1, Math.max(0, value));
+
+type Direction = 'row' | 'column';
+
+interface LayoutNodeProps {
+ depth?: number;
+ node: WidgetLayoutNode;
+ /** Main axis of the parent: in a column nothing shrinks below its content. */
+ parentDirection?: Direction;
+ scope: LayoutScope;
+}
+
+/**
+ * One node of a widget layout. Unknown values never throw: a missing path
+ * renders empty, an unknown icon or color falls back, so a script that drops
+ * a field degrades the card instead of breaking it.
+ */
+const LayoutNode = (nodeProps: LayoutNodeProps): ReactNode => {
+ const { node, scope, depth = 0 } = nodeProps;
+ if (depth > WIDGET_LAYOUT_LIMITS.depth) return null;
+ if (!checkCondition(node.visible, scope)) return null;
+ if (!node.hideWhen) return <LayoutNodeBody {...nodeProps} />;
+
+ // The container query sits on a wrapper so the node keeps its own display.
+ return (
+ <div {...stylex.props(node.hideWhen === 'narrow' ? styles.hideNarrow : styles.hideShort)}>
+ <LayoutNodeBody {...nodeProps} />
+ </div>
+ );
+};
+
+const LayoutNodeBody = ({
+ node,
+ scope,
+ depth = 0,
+ parentDirection = 'column',
+}: LayoutNodeProps): ReactNode => {
+ const gradientId = useId();
+
+ // Stacked rows keep their height (overflow clips at the card edge instead of
+ // overlapping); items in a row may shrink so long text ellipsizes.
+ const flex: CSSProperties =
+ node.flex === undefined
+ ? { flexShrink: parentDirection === 'column' ? 0 : 1 }
+ : { flexBasis: 0, flexGrow: node.flex, flexShrink: 1 };
+ const direction: Direction = 'direction' in node && node.direction === 'row' ? 'row' : 'column';
+ const renderChildren = (children: WidgetLayoutNode[] = [], childScope = scope) =>
+ children.map((child, index) => (
+ <LayoutNode
+ depth={depth + 1}
+ key={index}
+ node={child}
+ parentDirection={direction}
+ scope={childScope}
+ />
+ ));
+
+ switch (node.type) {
+ case 'stack': {
+ return (
+ <div
+ data-layout-node={'stack'}
+ {...props(styles.box, {
+ ...flex,
+ alignItems: node.align ? ALIGN[node.align] : undefined,
+ flexDirection: node.direction === 'row' ? 'row' : 'column',
+ flexWrap: node.wrap ? 'wrap' : undefined,
+ gap: node.gap ?? 8,
+ justifyContent: node.justify ? JUSTIFY[node.justify] : undefined,
+ padding: node.padding,
+ })}
+ >
+ {renderChildren(node.children)}
+ </div>
+ );
+ }
+ case 'grid': {
+ return (
+ <div
+ data-layout-node={'grid'}
+ {...props(styles.box, {
+ ...flex,
+ display: 'grid',
+ gap: node.gap ?? 8,
+ gridTemplateColumns: `repeat(${node.columns}, minmax(0, 1fr))`,
+ })}
+ >
+ {renderChildren(node.children)}
+ </div>
+ );
+ }
+ case 'repeat': {
+ // Validation rejects nested repeats; never multiply caps for one that slipped through.
+ if ('item' in scope) return null;
+ const items = getPath(scope, node.items);
+ if (!Array.isArray(items)) return null;
+ const limit = Math.min(
+ node.limit ?? WIDGET_LAYOUT_LIMITS.repeat,
+ WIDGET_LAYOUT_LIMITS.repeat,
+ );
+ return (
+ <div
+ data-layout-node={'repeat'}
+ {...props(styles.box, {
+ ...flex,
+ flexDirection: node.direction === 'row' ? 'row' : 'column',
+ gap: node.gap ?? 8,
+ justifyContent: node.justify ? JUSTIFY[node.justify] : undefined,
+ })}
+ >
+ {items.slice(0, limit).map((item, index) => (
+ <Fragment key={index}>
+ <LayoutNode
+ depth={depth + 1}
+ node={node.template}
+ parentDirection={direction}
+ scope={{ ...scope, index, item }}
+ />
+ </Fragment>
+ ))}
+ </div>
+ );
+ }
+ case 'text': {
+ const text = resolveText(node.value, scope);
+ const toneColor = node.tone ? TONE_COLORS[node.tone] : undefined;
+ return (
+ <div
+ data-layout-node={'text'}
+ {...props(
+ [
+ styles.text,
+ SIZE_STYLES[node.size ?? 'md'],
+ node.lines === undefined ? styles.nowrap : styles.clamp,
+ node.tone === 'secondary' && styles.toneSecondary,
+ node.tone === 'tertiary' && styles.toneTertiary,
+ ],
+ {
+ ...flex,
+ WebkitLineClamp: node.lines,
+ color: toneColor,
+ fontWeight:
+ WEIGHTS[node.weight ?? (node.size === 'display' ? 'semibold' : 'regular')],
+ textAlign: node.align ? TEXT_ALIGN[node.align] : undefined,
+ },
+ )}
+ >
+ {text}
+ </div>
+ );
+ }
+ case 'icon': {
+ const icon = WIDGET_LAYOUT_ICON_MAP[resolveRaw(node.name, scope) as WidgetLayoutIconName];
+ if (!icon) return null;
+ return (
+ <span
+ data-layout-node={'icon'}
+ {...props(styles.box, {
+ ...flex,
+ color: node.color === undefined ? undefined : resolveColor(node.color, scope),
+ flexShrink: 0,
+ })}
+ >
+ <Icon icon={icon} size={node.size ?? 20} />
+ </span>
+ );
+ }
+ case 'image': {
+ const src = resolveText(node.src, scope);
+ if (!src.startsWith('https://')) return null;
+ return (
+ <img
+ alt={''}
+ data-layout-node={'image'}
+ loading={'lazy'}
+ referrerPolicy={'no-referrer'}
+ src={src}
+ {...props(styles.image, {
+ ...flex,
+ borderRadius: node.radius ?? 8,
+ height: node.height,
+ objectFit: node.fit ?? 'cover',
+ width: node.width,
+ })}
+ />
+ );
+ }
+ case 'progress': {
+ const min = resolveNumber(node.min, scope) ?? 0;
+ const max = resolveNumber(node.max, scope) ?? 100;
+ const value = resolveNumber(node.value, scope) ?? min;
+ const ratio = max === min ? 0 : clamp01((value - min) / (max - min));
+ return (
+ <div data-layout-node={'progress'} {...props(styles.track, flex)}>
+ <div
+ {...props(styles.trackFill, {
+ backgroundColor: resolveColor(node.color, scope),
+ transform: `scaleX(${ratio})`,
+ })}
+ />
+ </div>
+ );
+ }
+ case 'ring': {
+ const max = resolveNumber(node.max, scope) ?? 100;
+ const ratio = max > 0 ? clamp01((resolveNumber(node.value, scope) ?? 0) / max) : 0;
+ const size = node.size ?? 72;
+ const stroke = Math.max(4, size / 10);
+ const radius = (size - stroke) / 2;
+ const circumference = 2 * Math.PI * radius;
+ return (
+ <div
+ data-layout-node={'ring'}
+ {...props(styles.box, {
+ ...flex,
+ alignItems: 'center',
+ flexShrink: 0,
+ height: size,
+ justifyContent: 'center',
+ position: 'relative',
+ width: size,
+ })}
+ >
+ <svg
+ aria-hidden
+ height={size}
+ style={{ inset: 0, position: 'absolute', transform: 'rotate(-90deg)' }}
+ width={size}
+ >
+ <circle
+ cx={size / 2}
+ cy={size / 2}
+ fill={'none'}
+ r={radius}
+ stroke={'currentColor'}
+ strokeOpacity={0.16}
+ strokeWidth={stroke}
+ />
+ <circle
+ cx={size / 2}
+ cy={size / 2}
+ fill={'none'}
+ r={radius}
+ stroke={resolveColor(node.color, scope)}
+ strokeDasharray={`${circumference * ratio} ${circumference}`}
+ strokeLinecap={'round'}
+ strokeWidth={stroke}
+ />
+ </svg>
+ <div
+ {...props(styles.box, {
+ alignItems: 'center',
+ flexDirection: 'column',
+ position: 'relative',
+ })}
+ >
+ {renderChildren(node.children)}
+ </div>
+ </div>
+ );
+ }
+ case 'dots': {
+ const total = Math.min(
+ Math.max(0, Math.round(resolveNumber(node.total, scope) ?? 0)),
+ WIDGET_LAYOUT_LIMITS.dots,
+ );
+ const filled = Math.round(resolveNumber(node.value, scope) ?? 0);
+ const color = resolveColor(node.color, scope);
+ return (
+ <div
+ data-layout-node={'dots'}
+ {...props(styles.box, {
+ ...flex,
+ display: 'grid',
+ gap: 4,
+ gridTemplateColumns: `repeat(${node.columns ?? 10}, minmax(0, 1fr))`,
+ })}
+ >
+ {Array.from({ length: total }, (_, index) => (
+ <span
+ key={index}
+ {...props(styles.dot, {
+ backgroundColor:
+ index < filled ? color : 'color-mix(in srgb, currentColor 18%, transparent)',
+ })}
+ />
+ ))}
+ </div>
+ );
+ }
+ case 'sparkline': {
+ const values = resolveNumbers(node.values, scope, node.key);
+ if (values.length < 2) return null;
+ const color = resolveColor(node.color, scope);
+ const width = 100;
+ const height = 40;
+ const kind = node.kind ?? 'line';
+ let body: ReactNode;
+ if (kind === 'bar') {
+ const max = Math.max(...values.map(Math.abs), 1);
+ const slot = width / values.length;
+ body = values.map((value, index) => {
+ const barHeight = Math.max(1, (Math.abs(value) / max) * (height - 2));
+ return (
+ <rect
+ fill={color}
+ height={barHeight}
+ key={index}
+ rx={Math.min(1.5, slot / 4)}
+ width={slot * 0.62}
+ x={index * slot + slot * 0.19}
+ y={height - barHeight}
+ />
+ );
+ });
+ } else {
+ const points = sparklinePoints(values, width, height);
+ const line = points
+ .map(({ x, y }, index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`)
+ .join(' ');
+ body = (
+ <>
+ {kind === 'area' && (
+ <>
+ <defs>
+ <linearGradient id={gradientId} x1={0} x2={0} y1={0} y2={1}>
+ <stop offset={'0%'} stopColor={color} stopOpacity={0.35} />
+ <stop offset={'100%'} stopColor={color} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <path
+ d={`${line} L ${points.at(-1)!.x} ${height} L ${points[0].x} ${height} Z`}
+ fill={`url(#${gradientId})`}
+ />
+ </>
+ )}
+ <path
+ d={line}
+ fill={'none'}
+ stroke={color}
+ strokeLinecap={'round'}
+ strokeLinejoin={'round'}
+ strokeWidth={2}
+ vectorEffect={'non-scaling-stroke'}
+ />
+ </>
+ );
+ }
+ return (
+ <svg
+ aria-hidden
+ data-layout-node={'sparkline'}
+ preserveAspectRatio={'none'}
+ viewBox={`0 0 ${width} ${height}`}
+ {...props([], {
+ ...flex,
+ display: 'block',
+ height: node.height ?? 40,
+ overflow: 'visible',
+ width: '100%',
+ })}
+ >
+ {body}
+ </svg>
+ );
+ }
+ case 'badge': {
+ const color = resolveColor(node.color, scope);
+ return (
+ <span
+ data-layout-node={'badge'}
+ {...props(styles.badge, {
+ ...flex,
+ backgroundColor: `color-mix(in srgb, ${color} 18%, transparent)`,
+ color: node.color === undefined ? undefined : color,
+ })}
+ >
+ {resolveText(node.value, scope)}
+ </span>
+ );
+ }
+ case 'divider': {
+ return <div data-layout-node={'divider'} {...props(styles.divider, flex)} />;
+ }
+ case 'spacer': {
+ return <div data-layout-node={'spacer'} {...props(styles.spacer, flex)} />;
+ }
+ default: {
+ return null;
+ }
+ }
+};
+
+export default LayoutNode;
diff --git a/src/features/Dashboard/WidgetCard/views/LayoutView/icons.ts b/src/features/Dashboard/WidgetCard/views/LayoutView/icons.ts
new file mode 100644
index 00000000000..2e8966ec8ca
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/LayoutView/icons.ts
@@ -0,0 +1,109 @@
+import type { WidgetLayoutIconName } from '@lobechat/types';
+import type { LucideIcon } from 'lucide-react';
+import {
+ ActivityIcon,
+ ArrowDownIcon,
+ ArrowUpIcon,
+ BellIcon,
+ CalendarIcon,
+ CheckIcon,
+ ClockIcon,
+ CloudDrizzleIcon,
+ CloudFogIcon,
+ CloudHailIcon,
+ CloudIcon,
+ CloudLightningIcon,
+ CloudMoonIcon,
+ CloudRainIcon,
+ CloudSnowIcon,
+ CloudSunIcon,
+ DatabaseIcon,
+ DollarSignIcon,
+ DropletIcon,
+ DropletsIcon,
+ EyeIcon,
+ FlameIcon,
+ GaugeIcon,
+ GitCommitHorizontalIcon,
+ GitPullRequestIcon,
+ GlobeIcon,
+ HeartIcon,
+ InfoIcon,
+ MailIcon,
+ MapPinIcon,
+ MessageCircleIcon,
+ MoonIcon,
+ NavigationIcon,
+ ServerIcon,
+ SnowflakeIcon,
+ StarIcon,
+ SunIcon,
+ SunriseIcon,
+ SunsetIcon,
+ TargetIcon,
+ ThermometerIcon,
+ TimerIcon,
+ TrendingDownIcon,
+ TrendingUpIcon,
+ TriangleAlertIcon,
+ TrophyIcon,
+ UmbrellaIcon,
+ UsersIcon,
+ WindIcon,
+ XIcon,
+ ZapIcon,
+} from 'lucide-react';
+
+export const WIDGET_LAYOUT_ICON_MAP: Record<WidgetLayoutIconName, LucideIcon> = {
+ 'activity': ActivityIcon,
+ 'alert-triangle': TriangleAlertIcon,
+ 'arrow-down': ArrowDownIcon,
+ 'arrow-up': ArrowUpIcon,
+ 'bell': BellIcon,
+ 'calendar': CalendarIcon,
+ 'check': CheckIcon,
+ 'clock': ClockIcon,
+ 'cloud': CloudIcon,
+ 'cloud-drizzle': CloudDrizzleIcon,
+ 'cloud-fog': CloudFogIcon,
+ 'cloud-hail': CloudHailIcon,
+ 'cloud-lightning': CloudLightningIcon,
+ 'cloud-moon': CloudMoonIcon,
+ 'cloud-rain': CloudRainIcon,
+ 'cloud-snow': CloudSnowIcon,
+ 'cloud-sun': CloudSunIcon,
+ 'database': DatabaseIcon,
+ 'dollar-sign': DollarSignIcon,
+ 'droplet': DropletIcon,
+ 'droplets': DropletsIcon,
+ 'eye': EyeIcon,
+ 'flame': FlameIcon,
+ 'gauge': GaugeIcon,
+ 'git-commit': GitCommitHorizontalIcon,
+ 'git-pull-request': GitPullRequestIcon,
+ 'globe': GlobeIcon,
+ 'heart': HeartIcon,
+ 'info': InfoIcon,
+ 'mail': MailIcon,
+ 'map-pin': MapPinIcon,
+ 'message-circle': MessageCircleIcon,
+ 'moon': MoonIcon,
+ 'navigation': NavigationIcon,
+ 'server': ServerIcon,
+ 'snowflake': SnowflakeIcon,
+ 'star': StarIcon,
+ 'sun': SunIcon,
+ 'sunrise': SunriseIcon,
+ 'sunset': SunsetIcon,
+ 'target': TargetIcon,
+ 'thermometer': ThermometerIcon,
+ 'timer': TimerIcon,
+ 'trending-down': TrendingDownIcon,
+ 'trending-up': TrendingUpIcon,
+ 'trophy': TrophyIcon,
+ 'umbrella': UmbrellaIcon,
+ 'users': UsersIcon,
+ 'wind': WindIcon,
+ 'x': XIcon,
+ 'zap': ZapIcon,
+};
diff --git a/src/features/Dashboard/WidgetCard/views/LayoutView/index.tsx b/src/features/Dashboard/WidgetCard/views/LayoutView/index.tsx
new file mode 100644
index 00000000000..8494f78f156
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/LayoutView/index.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import type { WidgetLayoutNode, WidgetLayoutValue, WidgetOutput } from '@lobechat/types';
+import { cssVar } from '@lobehub/ui';
+import { memo } from 'react';
+
+import LayoutNode from './LayoutNode';
+import { createLayoutScope, resolveSurface } from './resolve';
+import { WIDGET_SURFACE_STYLES } from './surfaces';
+
+interface LayoutViewProps {
+ /**
+ * Draw the layout in its own card-sized frame with its surface, for hosts
+ * that show the output without a widget card around it (drill-down, run
+ * preview). A widget card paints the surface itself.
+ */
+ framed?: boolean;
+ layout: WidgetLayoutNode;
+ output: WidgetOutput;
+ surface?: WidgetLayoutValue;
+}
+
+/** A widget output drawn by its version's declarative layout. */
+const LayoutView = memo<LayoutViewProps>(({ layout, output, framed, surface }) => {
+ const scope = createLayoutScope(output);
+ const content = (
+ <div data-widget-layout style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
+ <LayoutNode node={{ flex: 1, ...layout } as WidgetLayoutNode} scope={scope} />
+ </div>
+ );
+ if (!framed) return content;
+
+ return (
+ <div
+ data-widget-layout-frame
+ style={{
+ border: `1px solid ${cssVar.colorBorderSecondary}`,
+ borderRadius: cssVar.borderRadiusLG,
+ containerType: 'size',
+ height: 300,
+ maxWidth: 420,
+ overflow: 'hidden',
+ padding: 16,
+ ...WIDGET_SURFACE_STYLES[resolveSurface(surface, scope)],
+ }}
+ >
+ {content}
+ </div>
+ );
+});
+
+LayoutView.displayName = 'DashboardWidgetLayoutView';
+
+export default LayoutView;
+
+export { createLayoutScope, resolveSurface } from './resolve';
+export { WIDGET_SURFACE_STYLES } from './surfaces';
diff --git a/src/features/Dashboard/WidgetCard/views/LayoutView/resolve.test.ts b/src/features/Dashboard/WidgetCard/views/LayoutView/resolve.test.ts
new file mode 100644
index 00000000000..7a52dee28aa
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/LayoutView/resolve.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ checkCondition,
+ createLayoutScope,
+ formatLayoutValue,
+ getPath,
+ LAYOUT_SERIES_MAX_POINTS,
+ resolveColor,
+ resolveNumbers,
+ resolveRaw,
+ resolveSurface,
+ resolveText,
+} from './resolve';
+
+const scope = createLayoutScope({
+ data: {
+ city: 'Hangzhou',
+ cond: 'rain',
+ hi: 21,
+ hourly: [
+ { t: '2026-10-31T14:00:00', temp: 18 },
+ { t: '2026-10-31T15:00:00', temp: 17.5 },
+ ],
+ temp: 18.44,
+ },
+ type: 'data',
+});
+
+describe('getPath', () => {
+ it('reads nested keys and array indexes, and stops at missing parents', () => {
+ expect(getPath(scope, 'data.hourly.1.temp')).toBe(17.5);
+ expect(getPath(scope, 'data.missing.temp')).toBeUndefined();
+ });
+});
+
+describe('createLayoutScope', () => {
+ it('exposes a built-in output as data, so a stat binds the same way', () => {
+ expect(getPath(createLayoutScope({ type: 'stat', value: 3 }), 'data.value')).toBe(3);
+ });
+});
+
+describe('resolveText', () => {
+ it('formats a bound number', () => {
+ expect(resolveText({ bind: 'data.temp', digits: 0, format: 'number' }, scope)).toBe('18');
+ });
+
+ it('fills a template, formatting slots that name a format', () => {
+ expect(resolveText({ template: '{data.city} {data.hourly.0.t|time}' }, scope)).toBe(
+ 'Hangzhou 14:00',
+ );
+ });
+
+ it('takes fraction digits after the format in a template slot', () => {
+ expect(resolveText({ template: '{data.temp|number:0}°' }, scope)).toBe('18°');
+ });
+
+ it('prints a mapped value as-is and uses the fallback for a missing path', () => {
+ expect(resolveText({ bind: 'data.cond', map: { rain: 'Rain' } }, scope)).toBe('Rain');
+ expect(resolveText({ bind: 'data.nope', fallback: '--' }, scope)).toBe('--');
+ });
+
+ it('clips long values and every template slot, so a repeated long string stays bounded', () => {
+ const long = createLayoutScope({ data: { a: 'x'.repeat(250_000) }, type: 'data' });
+
+ expect(resolveText({ bind: 'data.a' }, long)).toHaveLength(500);
+ expect(resolveText({ template: '{data.a}'.repeat(62) }, long)).toHaveLength(500);
+ });
+
+ it('never prints an object', () => {
+ expect(resolveText({ bind: 'data.hourly' }, scope)).toBe('');
+ });
+});
+
+describe('resolveRaw', () => {
+ it('uses the "*" entry when the map has no match', () => {
+ expect(resolveRaw({ bind: 'data.cond', map: { '*': 'cloud', 'sun': 'sun' } }, scope)).toBe(
+ 'cloud',
+ );
+ });
+});
+
+describe('formatLayoutValue', () => {
+ it('formats a ratio as a percent', () => {
+ expect(formatLayoutValue(0.42, 'percent')).toBe('42%');
+ });
+});
+
+describe('checkCondition', () => {
+ it.each([
+ [{ bind: 'data.temp', gt: 18 }, true],
+ [{ bind: 'data.temp', lt: 10 }, false],
+ [{ bind: 'data.cond', in: ['rain', 'snow'] }, true],
+ [{ bind: 'data.cond', ne: 'rain' }, false],
+ [{ bind: 'data.alerts', exists: true }, false],
+ [{ bind: 'data.alerts', exists: false }, true],
+ [{ bind: 'data.city', gt: 1 }, false],
+ ])('%j → %s', (condition, expected) => {
+ expect(checkCondition(condition, scope)).toBe(expected);
+ });
+});
+
+describe('resolveSurface / resolveColor', () => {
+ it('maps data to a known surface and falls back to default', () => {
+ expect(resolveSurface({ bind: 'data.cond', map: { rain: 'rain' } }, scope)).toBe('rain');
+ expect(resolveSurface('neon', scope)).toBe('default');
+ });
+
+ it('falls back to the text color for unknown colors', () => {
+ expect(resolveColor('#f00', scope)).toBe('currentColor');
+ expect(resolveColor(undefined, scope)).toBe('currentColor');
+ });
+});
+
+describe('resolveNumbers', () => {
+ it('reads one key of each item and skips non-numbers', () => {
+ expect(resolveNumbers('data.hourly', scope, 'temp')).toEqual([18, 17.5]);
+ expect(resolveNumbers('data.city', scope)).toEqual([]);
+ });
+
+ it('samples a huge array down to the point cap, keeping both ends', () => {
+ const big = createLayoutScope({
+ data: { values: Array.from({ length: 130_000 }, (_, index) => index) },
+ type: 'data',
+ });
+
+ const values = resolveNumbers('data.values', big);
+
+ expect(values).toHaveLength(LAYOUT_SERIES_MAX_POINTS);
+ expect(values[0]).toBe(0);
+ expect(values.at(-1)).toBe(129_999);
+ });
+});
diff --git a/src/features/Dashboard/WidgetCard/views/LayoutView/resolve.ts b/src/features/Dashboard/WidgetCard/views/LayoutView/resolve.ts
new file mode 100644
index 00000000000..a66a3e2f681
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/LayoutView/resolve.ts
@@ -0,0 +1,247 @@
+import type {
+ WidgetLayoutColor,
+ WidgetLayoutCondition,
+ WidgetLayoutFormat,
+ WidgetLayoutLiteral,
+ WidgetLayoutSurface,
+ WidgetLayoutValue,
+ WidgetOutput,
+} from '@lobechat/types';
+import {
+ WIDGET_LAYOUT_COLORS,
+ WIDGET_LAYOUT_LIMITS,
+ WIDGET_LAYOUT_SURFACES,
+} from '@lobechat/types';
+import { cssVar } from '@lobehub/ui';
+import dayjs from 'dayjs';
+
+/** What layout paths read from: `data.*`, `output.*`, and `item` / `index` inside a repeat. */
+export type LayoutScope = Record<string, unknown>;
+
+/**
+ * A `data` output exposes its payload as `data`; the built-in types expose the
+ * whole output there too, so `data.value` reads a stat the same way.
+ */
+export const createLayoutScope = (output: WidgetOutput): LayoutScope => ({
+ data: output.type === 'data' ? output.data : output,
+ output,
+});
+
+export const getPath = (scope: unknown, path: string): unknown => {
+ let current: unknown = scope;
+ for (const key of path.split('.')) {
+ if (current === null || current === undefined || typeof current !== 'object') return undefined;
+ current = (current as Record<string, unknown>)[key];
+ }
+ return current;
+};
+
+const isBinding = (
+ value: WidgetLayoutValue,
+): value is Extract<WidgetLayoutValue, { bind: string }> =>
+ typeof value === 'object' && value !== null && 'bind' in value;
+
+const isTemplate = (value: WidgetLayoutValue): value is { template: string } =>
+ typeof value === 'object' && value !== null && 'template' in value;
+
+const toNumber = (value: unknown): number | undefined => {
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
+ if (typeof value === 'string' && value.trim() !== '') {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : undefined;
+ }
+ return undefined;
+};
+
+const DATE_PATTERNS: Partial<Record<WidgetLayoutFormat, string>> = {
+ date: 'MMM D',
+ datetime: 'MMM D HH:mm',
+ time: 'HH:mm',
+ weekday: 'ddd',
+};
+
+/** Print one value the way `format` asks; unknown shapes fall back to plain text. */
+export const formatLayoutValue = (
+ raw: unknown,
+ format?: WidgetLayoutFormat,
+ options: { digits?: number; pattern?: string } = {},
+): string => {
+ if (raw === null || raw === undefined) return '';
+ const { digits, pattern } = options;
+
+ if (format && format in DATE_PATTERNS) {
+ const date = dayjs(raw as string | number);
+ return date.isValid() ? date.format(pattern ?? DATE_PATTERNS[format]) : String(raw);
+ }
+ if (format === 'relative') {
+ const date = dayjs(raw as string | number);
+ return date.isValid() ? date.fromNow() : String(raw);
+ }
+
+ const number = toNumber(raw);
+ if (number !== undefined && (format || typeof raw === 'number')) {
+ if (format === 'percent') {
+ return new Intl.NumberFormat(undefined, {
+ maximumFractionDigits: digits ?? 0,
+ style: 'percent',
+ }).format(number);
+ }
+ return new Intl.NumberFormat(undefined, {
+ maximumFractionDigits: digits ?? (format === 'compact' ? 1 : 2),
+ minimumFractionDigits: digits,
+ notation: format === 'compact' ? 'compact' : 'standard',
+ }).format(number);
+ }
+
+ if (typeof raw === 'object') return '';
+ return String(raw);
+};
+
+/** `{path}`, `{path|format}` or `{path|format:digits}`, e.g. `{data.temp|number:0}`. */
+const TEMPLATE_SLOT = /\{([\w$.-]+)(?:\|(\w+)(?::(\d))?)?\}/g;
+
+/**
+ * Resolve a layout value to what it stands for in this scope. Bindings keep
+ * the raw value (a number stays a number for progress / dots); use
+ * `resolveText` for anything printed.
+ */
+export const resolveRaw = (value: WidgetLayoutValue | undefined, scope: LayoutScope): unknown => {
+ if (value === undefined) return undefined;
+ if (isTemplate(value)) return resolveText(value, scope);
+ if (!isBinding(value)) return value;
+
+ const raw = getPath(scope, value.bind);
+ if (value.map && raw !== null && raw !== undefined) {
+ const mapped = value.map[String(raw)];
+ if (mapped !== undefined) return mapped;
+ if ('*' in value.map) return value.map['*'];
+ }
+ return raw ?? value.fallback;
+};
+
+const clip = (text: string) =>
+ text.length > WIDGET_LAYOUT_LIMITS.textLength
+ ? `${text.slice(0, WIDGET_LAYOUT_LIMITS.textLength - 1)}…`
+ : text;
+
+/**
+ * A layout value as printed text, at most `textLength` characters. Template
+ * slots are clipped before they are joined, so a template that repeats a long
+ * output string never builds a large string first.
+ */
+export const resolveText = (value: WidgetLayoutValue | undefined, scope: LayoutScope): string => {
+ if (value === undefined) return '';
+ if (isTemplate(value)) {
+ return clip(
+ value.template.replaceAll(
+ TEMPLATE_SLOT,
+ (_, path: string, format?: string, digits?: string) =>
+ clip(
+ formatLayoutValue(getPath(scope, path), format as WidgetLayoutFormat | undefined, {
+ digits: digits === undefined ? undefined : Number(digits),
+ }),
+ ),
+ ),
+ );
+ }
+ if (isBinding(value)) {
+ // A mapped value is the layout's own word ("Rain"), not a number to format.
+ const raw = resolveRaw(value, scope);
+ const mapped = value.map && raw !== getPath(scope, value.bind);
+ return clip(formatLayoutValue(raw, mapped ? undefined : value.format, value));
+ }
+ return clip(formatLayoutValue(value));
+};
+
+export const resolveNumber = (
+ value: WidgetLayoutValue | undefined,
+ scope: LayoutScope,
+): number | undefined => toNumber(resolveRaw(value, scope));
+
+const compare = (raw: unknown, expected: WidgetLayoutLiteral) =>
+ raw === expected || (raw !== null && raw !== undefined && String(raw) === String(expected));
+
+export const checkCondition = (
+ condition: WidgetLayoutCondition | undefined,
+ scope: LayoutScope,
+): boolean => {
+ if (!condition) return true;
+ const raw = getPath(scope, condition.bind);
+ const exists = raw !== null && raw !== undefined && raw !== '';
+ if (condition.exists !== undefined && condition.exists !== exists) return false;
+ if (condition.eq !== undefined && !compare(raw, condition.eq)) return false;
+ if (condition.ne !== undefined && compare(raw, condition.ne)) return false;
+ if (condition.in && !condition.in.some((entry) => compare(raw, entry))) return false;
+
+ const number = toNumber(raw);
+ const bounds = [
+ [condition.gt, (n: number, b: number) => n > b],
+ [condition.gte, (n: number, b: number) => n >= b],
+ [condition.lt, (n: number, b: number) => n < b],
+ [condition.lte, (n: number, b: number) => n <= b],
+ ] as const;
+ for (const [bound, test] of bounds) {
+ if (bound === undefined) continue;
+ if (number === undefined || !test(number, bound)) return false;
+ }
+ return true;
+};
+
+const SEMANTIC_COLORS: Record<string, string> = {
+ error: cssVar.colorError,
+ primary: cssVar.colorPrimary,
+ success: cssVar.colorSuccess,
+ text: 'currentColor',
+ warning: cssVar.colorWarning,
+};
+
+/** A layout color as CSS; unknown or missing colors follow the text color. */
+export const resolveColor = (value: WidgetLayoutValue | undefined, scope: LayoutScope): string => {
+ const name = resolveRaw(value, scope);
+ if (typeof name !== 'string' || !(WIDGET_LAYOUT_COLORS as readonly string[]).includes(name)) {
+ return 'currentColor';
+ }
+ return (
+ SEMANTIC_COLORS[name] ??
+ (cssVar as unknown as Record<string, string>)[name as WidgetLayoutColor] ??
+ 'currentColor'
+ );
+};
+
+export const resolveSurface = (
+ value: WidgetLayoutValue | undefined,
+ scope: LayoutScope,
+): WidgetLayoutSurface => {
+ const name = resolveRaw(value, scope);
+ return typeof name === 'string' && (WIDGET_LAYOUT_SURFACES as readonly string[]).includes(name)
+ ? (name as WidgetLayoutSurface)
+ : 'default';
+};
+
+/** Most points a sparkline draws; a card is a few hundred pixels wide at most. */
+export const LAYOUT_SERIES_MAX_POINTS = WIDGET_LAYOUT_LIMITS.seriesPoints;
+
+/**
+ * The array at `path`, as numbers — read from `key` when the items are
+ * objects. A longer array is sampled evenly down to `maxPoints` (first and
+ * last kept), so a large output never reaches the spread-based extrema or
+ * allocates one SVG element per entry.
+ */
+export const resolveNumbers = (
+ path: string,
+ scope: LayoutScope,
+ key?: string,
+ maxPoints = LAYOUT_SERIES_MAX_POINTS,
+): number[] => {
+ const list = getPath(scope, path);
+ if (!Array.isArray(list)) return [];
+ const count = Math.min(list.length, maxPoints);
+ const step = count > 1 ? (list.length - 1) / (count - 1) : 0;
+ const values: number[] = [];
+ for (let index = 0; index < count; index += 1) {
+ const entry = list[Math.round(index * step)];
+ const value = toNumber(key ? getPath(entry, key) : entry);
+ if (value !== undefined) values.push(value);
+ }
+ return values;
+};
diff --git a/src/features/Dashboard/WidgetCard/views/LayoutView/surfaces.ts b/src/features/Dashboard/WidgetCard/views/LayoutView/surfaces.ts
new file mode 100644
index 00000000000..42026a42ac5
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/LayoutView/surfaces.ts
@@ -0,0 +1,32 @@
+// lobe-design-ignore-file LOBE-RAW-COLOR: widget surfaces are fixed, theme-independent card colors under white text (like OS home-screen widgets); palette tokens cannot express them because the dark algorithm inverts palette steps (gray10 / geekblue9 turn light), which made "night" pale in dark mode.
+import type { WidgetLayoutSurface } from '@lobechat/types';
+import type { CSSProperties } from 'react';
+
+const gradient = (from: string, to: string): CSSProperties => ({
+ backgroundColor: to,
+ backgroundImage: `linear-gradient(165deg, ${from} 0%, ${to} 100%)`,
+ borderColor: 'transparent',
+ color: '#fff',
+});
+
+/**
+ * Card backgrounds a layout can pick. Each is a fixed mid-to-deep gradient
+ * under white text, so it reads the same in light and dark mode; `default`
+ * keeps the theme's card. Text inside follows `currentColor` and secondary
+ * tones dim it by opacity, so every primitive works on every surface.
+ */
+export const WIDGET_SURFACE_STYLES: Record<WidgetLayoutSurface, CSSProperties | undefined> = {
+ cloudy: gradient('#8A9BB0', '#56677D'),
+ default: undefined,
+ forest: gradient('#4E8A63', '#2B5A3E'),
+ night: gradient('#2E3D6B', '#10172F'),
+ ocean: gradient('#2BA4B5', '#1A6489'),
+ rain: gradient('#5E7593', '#33445B'),
+ rose: gradient('#EF8AA6', '#C24C76'),
+ sand: gradient('#E2B25C', '#B9772F'),
+ sky: gradient('#5AB4F8', '#2A72D6'),
+ slate: gradient('#3B4251', '#1D2129'),
+ snow: gradient('#9FBAD8', '#6888B0'),
+ storm: gradient('#4C5070', '#20213A'),
+ sunset: gradient('#F5A066', '#D2546A'),
+};
diff --git a/src/features/Dashboard/WidgetCard/views/index.tsx b/src/features/Dashboard/WidgetCard/views/index.tsx
index 1db999946ed..5321b622fff 100644
--- a/src/features/Dashboard/WidgetCard/views/index.tsx
+++ b/src/features/Dashboard/WidgetCard/views/index.tsx
@@ -5,6 +5,8 @@ import { memo } from 'react';
import type { DashboardTrendSeries } from '@/services/dashboard';
+import DataView from './DataView';
+import LayoutView from './LayoutView';
import ListView from './ListView';
import SeriesView from './SeriesView';
import StatView from './StatView';
@@ -18,13 +20,19 @@ export interface WidgetOutputViewProps {
view?: WidgetViewHints | null;
}
-/** Render one widget output by its contract type. */
+/** Render one widget output by its version's layout, else by its contract type. */
const WidgetOutputView = memo<WidgetOutputViewProps>(
({ output, trend, view, density = 'compact' }) => {
// Cards scroll and load rows as needed; only an explicit `view.limit` caps them.
const compact = density === 'compact';
const limit = compact ? view?.limit : undefined;
+ if (view?.layout) {
+ return (
+ <LayoutView framed={!compact} layout={view.layout} output={output} surface={view.surface} />
+ );
+ }
+
switch (output.type) {
case 'stat': {
return <StatView output={output} trend={trend} />;
@@ -47,6 +55,9 @@ const WidgetOutputView = memo<WidgetOutputViewProps>(
<TableView columns={view?.columns} incremental={compact} limit={limit} output={output} />
);
}
+ case 'data': {
+ return <DataView output={output} />;
+ }
default: {
return null;
}
diff --git a/src/features/Dashboard/WidgetDetail/index.tsx b/src/features/Dashboard/WidgetDetail/index.tsx
index e82fa7dae83..65845619aed 100644
--- a/src/features/Dashboard/WidgetDetail/index.tsx
+++ b/src/features/Dashboard/WidgetDetail/index.tsx
@@ -178,6 +178,10 @@ WidgetSummary.displayName = 'DashboardWidgetSummary';
const WidgetData = memo<{ widget: DashboardWidgetItem }>(({ widget }) => {
const { t } = useTranslation('dashboard');
const trend = useWidgetTrend(widget);
+ const useFetchWidgetVersions = useDashboardStore((s) => s.useFetchWidgetVersions);
+ useFetchWidgetVersions(widget.id);
+ const versions = useDashboardStore(dashboardSelectors.widgetVersions(widget.id));
+ const view = versions.find((version) => version.id === widget.publishedVersionId)?.view;
if (!widget.latestOutput) {
return (
@@ -190,7 +194,7 @@ const WidgetData = memo<{ widget: DashboardWidgetItem }>(({ widget }) => {
return (
// A stat fills its height with the trend, so give it room the drawer does not size.
<div style={widget.latestOutput.type === 'stat' ? { height: 200 } : { minHeight: 120 }}>
- <WidgetOutputView density={'full'} output={widget.latestOutput} trend={trend} />
+ <WidgetOutputView density={'full'} output={widget.latestOutput} trend={trend} view={view} />
</div>
);
});
diff --git a/src/features/Dashboard/WidgetGrid/index.tsx b/src/features/Dashboard/WidgetGrid/index.tsx
index aa483b19b55..70c4939f100 100644
--- a/src/features/Dashboard/WidgetGrid/index.tsx
+++ b/src/features/Dashboard/WidgetGrid/index.tsx
@@ -2,7 +2,7 @@
import { memo, useMemo, useState } from 'react';
-import type { DashboardWidgetItem } from '@/services/dashboard';
+import type { DashboardProjectWidgetItem } from '@/services/dashboard';
import BoardWidgetCard from '../Board/BoardWidgetCard';
import { cellStyle, gridStyles } from '../Board/style';
@@ -10,7 +10,7 @@ import { resolveLayouts } from '../utils/layout';
import WidgetDetailDrawer from '../WidgetDetail';
export interface DashboardWidgetGridProps {
- widgets: DashboardWidgetItem[];
+ widgets: DashboardProjectWidgetItem[];
}
/**
@@ -40,7 +40,7 @@ const DashboardWidgetGrid = memo<DashboardWidgetGridProps>(({ widgets }) => {
key={widget.id}
style={cellStyle(layouts[widget.id])}
>
- <BoardWidgetCard widget={widget} onOpen={setOpenWidgetId} />
+ <BoardWidgetCard view={widget.publishedView} widget={widget} onOpen={setOpenWidgetId} />
</div>
))}
</div>
diff --git a/src/features/Dashboard/utils/layout.ts b/src/features/Dashboard/utils/layout.ts
index d1352849b6f..197d6d51b6b 100644
--- a/src/features/Dashboard/utils/layout.ts
+++ b/src/features/Dashboard/utils/layout.ts
@@ -18,6 +18,8 @@ const DEFAULT_SIZE: Record<WidgetOutputType, { h: number; w: number }> = {
// Three rows (240px): header, label, value, description, the 28px trend line
// and the updated-at footer. Two rows squeezed the trend line to nothing.
stat: { h: 3, w: 3 },
+ // A layout card (weather, progress, …) reads best close to square.
+ data: { h: 4, w: 4 },
table: { h: 4, w: 12 },
};
diff --git a/src/services/dashboard.ts b/src/services/dashboard.ts
index 6db5cb55eaa..d962595b223 100644
--- a/src/services/dashboard.ts
+++ b/src/services/dashboard.ts
@@ -13,6 +13,8 @@ export type DashboardDetail = QueryData<DashboardRouter['detail']>;
/** One placed widget: the placement row plus the widget's hot read model. */
export type DashboardBoardItem = DashboardDetail['items'][number];
export type DashboardWidgetItem = DashboardBoardItem['widget'];
+/** A project widget, with its published version's view. */
+export type DashboardProjectWidgetItem = QueryData<WidgetRouter['listByProject']>[number];
export type DashboardWidgetDetail = QueryData<WidgetRouter['detail']>;
export type DashboardWidgetVersionItem = QueryData<WidgetRouter['listVersions']>[number];
export type DashboardWidgetRunItem = QueryData<WidgetRouter['listRuns']>[number];
diff --git a/src/store/dashboard/initialState.ts b/src/store/dashboard/initialState.ts
index db0444b8cc5..544a51d30d9 100644
--- a/src/store/dashboard/initialState.ts
+++ b/src/store/dashboard/initialState.ts
@@ -4,9 +4,9 @@ import { createReplicaState, type ReplicaState } from '@/libs/replica';
import type {
DashboardDetail,
DashboardListItem,
+ DashboardProjectWidgetItem,
DashboardTrendSeries,
DashboardWidgetDetail,
- DashboardWidgetItem,
DashboardWidgetRunDetail,
DashboardWidgetRunItem,
DashboardWidgetVersionItem,
@@ -30,9 +30,9 @@ export interface DashboardState {
/** Replica bookkeeping for `projectDashboardsMap`. */
projectDashboardsReplica: ReplicaState<DashboardListItem[]>;
/** Every widget of a project (with or without an agent), keyed by project id. */
- projectWidgetsMap: Record<string, DashboardWidgetItem[]>;
+ projectWidgetsMap: Record<string, DashboardProjectWidgetItem[]>;
/** Replica bookkeeping for `projectWidgetsMap`. */
- projectWidgetsReplica: ReplicaState<DashboardWidgetItem[]>;
+ projectWidgetsReplica: ReplicaState<DashboardProjectWidgetItem[]>;
/** Widgets with a board placement request in flight. */
widgetAddingIds: string[];
/** Widgets opened on their own (outside a board), keyed by widget id. */
diff --git a/src/store/dashboard/projection.ts b/src/store/dashboard/projection.ts
index 3f152113a4b..8263945332f 100644
--- a/src/store/dashboard/projection.ts
+++ b/src/store/dashboard/projection.ts
@@ -4,6 +4,7 @@ import { defineReplica } from '@/libs/replica';
import {
type DashboardDetail,
type DashboardListItem,
+ type DashboardProjectWidgetItem,
dashboardService,
type DashboardTrendSeries,
type DashboardWidgetDetail,
@@ -19,6 +20,7 @@ import { dashboardLevelKey } from './initialState';
export type {
DashboardDetail,
DashboardListItem,
+ DashboardProjectWidgetItem,
DashboardTrendSeries,
DashboardWidgetDetail,
DashboardWidgetItem,
@@ -61,7 +63,7 @@ export const projectDashboardListResource = defineReplica<string, DashboardListI
});
/** Every widget of a project (placed or not), one entry per project. */
-export const projectWidgetListResource = defineReplica<string, DashboardWidgetItem[]>({
+export const projectWidgetListResource = defineReplica<string, DashboardProjectWidgetItem[]>({
fetcher: (projectId) => dashboardService.listWidgetsByProject(projectId),
key: (projectId) => projectId,
name: 'projectWidgetList',
diff --git a/src/store/dashboard/store.ts b/src/store/dashboard/store.ts
index 700ebd31eb2..7e6cc7422a1 100644
--- a/src/store/dashboard/store.ts
+++ b/src/store/dashboard/store.ts
@@ -28,6 +28,7 @@ import {
dashboardDetailResource,
type DashboardListItem,
dashboardListResource,
+ type DashboardProjectWidgetItem,
type DashboardTrendSeries,
type DashboardWidgetDetail,
type DashboardWidgetItem,
@@ -153,7 +154,7 @@ export interface DashboardAction {
enabled?: boolean,
) => DashboardRequest<DashboardListItem[]>;
useFetchProjectDashboards: (projectId?: string) => DashboardRequest<DashboardListItem[]>;
- useFetchProjectWidgets: (projectId?: string) => DashboardRequest<DashboardWidgetItem[]>;
+ useFetchProjectWidgets: (projectId?: string) => DashboardRequest<DashboardProjectWidgetItem[]>;
useFetchWidgetDetail: (widgetId?: string) => DashboardRequest<DashboardWidgetDetail>;
useFetchWidgetRun: (
widgetId?: string,
@@ -192,11 +193,11 @@ export const useDashboardStore = createWithEqualityFn<DashboardStore>()(
});
const projectWidgets = createReplicaSlice(projectWidgetListResource, {
actionPrefix: 'dashboard/projectWidgets',
- entity: arrayEntity<DashboardWidgetItem>((widget) => widget.id),
+ entity: arrayEntity<DashboardProjectWidgetItem>((widget) => widget.id),
get,
set,
stateKey: 'projectWidgetsReplica',
- view: recordLens<DashboardStore, DashboardWidgetItem[]>('projectWidgetsMap'),
+ view: recordLens<DashboardStore, DashboardProjectWidgetItem[]>('projectWidgetsMap'),
});
const detail = createReplicaSlice(dashboardDetailResource, {
actionPrefix: 'dashboard/detail',