From ed2f04eafa5a52686744fe5ce3538143cdc06e12 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 08:57:31 +0000
Subject: [PATCH 1/7] feat(core): name the dashboard filters a widget is not
bound to
dashboardFiltersNotApplied asks the binding buildWidgetScopedFilter asks, so a
card's not-applied mark and the card's query read one resolver.
Co-authored-by: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jUeSU9HhKxjcVsyprx
---
ui/packages/core/src/index.ts | 1 +
.../utils/__tests__/dashboard-filters.test.ts | 38 +++++++++++++++++++
.../core/src/utils/dashboard-filters.ts | 15 ++++++++
3 files changed, 54 insertions(+)
diff --git a/ui/packages/core/src/index.ts b/ui/packages/core/src/index.ts
index 57a35d0499f..15e0b079b0a 100644
--- a/ui/packages/core/src/index.ts
+++ b/ui/packages/core/src/index.ts
@@ -246,6 +246,7 @@ export {
buildFilterCondition,
buildWidgetScopedFilter,
boundMemberFilterNames,
+ dashboardFiltersNotApplied,
type DashboardFilterJsonColumnOperators,
} from './utils/dashboard-filters.js';
export * from './utils/merge-filters.js';
diff --git a/ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts b/ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts
index 86b233ac302..c4ac1633ea6 100644
--- a/ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts
+++ b/ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts
@@ -12,6 +12,7 @@ import {
dashboardFilterVariableDefs,
buildFilterCondition,
buildWidgetScopedFilter,
+ dashboardFiltersNotApplied,
resetDashboardFilterWarnings,
DATE_RANGE_FILTER_NAME,
DATE_RANGE_PRESETS,
@@ -855,3 +856,40 @@ describe('a `{current_iso_week}` default seeds the filter with the resolved week
}
});
});
+
+// objectstack#36372 — the card mark that names a filter not applied to a card
+// reads `dashboardFiltersNotApplied`. A listed filter adds no condition to the
+// card's query for any value; an unlisted one adds one. The mark and the data
+// read the same binding.
+describe('dashboardFiltersNotApplied agrees with buildWidgetScopedFilter', () => {
+ const ownerDef: DashboardFilterDef = { name: 'owner', field: 'owner', type: 'text' };
+ const stageDef: DashboardFilterDef = { name: 'stage', field: 'stage', type: 'text', targetWidgets: ['w_listed'] };
+ const defs = [ownerDef, stageDef];
+ const widgets = [
+ { id: 'w_default' },
+ { id: 'w_opt_out', filterBindings: { owner: false as const } },
+ { id: 'w_rebound', filterBindings: { owner: 'account_owner' } },
+ { id: 'w_listed' },
+ { id: 'w_explicit_over_list', filterBindings: { stage: 'pipeline_stage' } },
+ ];
+
+ it('names exactly the filters that add no condition to the widget query', () => {
+ for (const widget of widgets) {
+ const notApplied = new Set(dashboardFiltersNotApplied(widget, defs).map((d) => d.name));
+ for (const def of defs) {
+ const scoped = buildWidgetScopedFilter(widget, [def], { [def.name]: 'x' });
+ expect({ widget: widget.id, filter: def.name, applied: scoped !== undefined }).toEqual({
+ widget: widget.id,
+ filter: def.name,
+ applied: !notApplied.has(def.name),
+ });
+ }
+ }
+ });
+
+ it('lists an opted-out filter and a filter whose allow-list leaves the widget out', () => {
+ expect(dashboardFiltersNotApplied({ id: 'w_opt_out', filterBindings: { owner: false } }, defs).map((d) => d.name))
+ .toEqual(['owner', 'stage']);
+ expect(dashboardFiltersNotApplied({ id: 'w_listed' }, defs)).toEqual([]);
+ });
+});
diff --git a/ui/packages/core/src/utils/dashboard-filters.ts b/ui/packages/core/src/utils/dashboard-filters.ts
index e7919638f3d..9ae5027baf9 100644
--- a/ui/packages/core/src/utils/dashboard-filters.ts
+++ b/ui/packages/core/src/utils/dashboard-filters.ts
@@ -752,6 +752,21 @@ export function boundMemberFilterNames(
return names;
}
+/**
+ * The dashboard filters that never reach this widget's query: each `def` the
+ * widget is not bound to, in `defs` order. It asks the binding
+ * {@link buildWidgetScopedFilter} asks (`resolveBoundField`), so a card's
+ * "this filter does not apply here" mark and the query the card sends cannot
+ * disagree: a filter listed here contributes no condition for any value, and
+ * one left out contributes one for every value it lowers.
+ */
+export function dashboardFiltersNotApplied(
+ widget: Pick,
+ defs: DashboardFilterDef[],
+): DashboardFilterDef[] {
+ return defs.filter((def) => resolveBoundField(widget, def) === undefined);
+}
+
/**
* Resolve which of the widget's fields a filter binds to.
* Returns `undefined` when the widget is not bound to this filter.
From ae0a9d546fc60236fe040a0eca4a05837fdeb5e1 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 09:24:23 +0000
Subject: [PATCH 2/7] feat(console): edit a dashboard on its own page, and mark
the page filters a card does not follow
An admin who may design the dashboard's package gets Edit in the page
header. The edit state opens the stored document with the cards in design
mode (drag, corner resize by grid tracks, click to select), Studio's own
dashboard panels at the right, Add card, Add filter, Discard and Save.
Save stages the draft and publishes that one item through the confirmed-
save door, into the owning package or the app's customization package, and
refuses over a pending Studio draft.
Every card names the page filters that do not reach it, read through the
same binding its query is built from.
Co-authored-by: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jUeSU9HhKxjcVsyprx
---
.changeset/36372-dashboard-in-page-edit.md | 19 +
.../frontend/plugins/plugin-dashboard.mdx | 29 ++
.../src/views/DashboardInPageEditor.test.ts | 100 ++++
.../src/views/DashboardInPageEditor.tsx | 435 ++++++++++++++++++
.../DashboardView.inPageEdit-36372.test.tsx | 261 +++++++++++
.../app-shell/src/views/DashboardView.tsx | 120 ++++-
.../runtime-metadata-persistence.test.ts | 98 ++++
.../src/views/runtime-metadata-persistence.ts | 123 ++++-
.../utils/__tests__/dashboard-filters.test.ts | 4 +-
ui/packages/i18n/src/locales/ar.ts | 20 +
ui/packages/i18n/src/locales/de.ts | 20 +
ui/packages/i18n/src/locales/en.ts | 20 +
ui/packages/i18n/src/locales/es.ts | 20 +
ui/packages/i18n/src/locales/fr.ts | 20 +
ui/packages/i18n/src/locales/ja.ts | 20 +
ui/packages/i18n/src/locales/ko.ts | 20 +
ui/packages/i18n/src/locales/pt-BR.ts | 20 +
ui/packages/i18n/src/locales/ru.ts | 20 +
ui/packages/i18n/src/locales/zh-Hans.ts | 20 +
ui/packages/i18n/src/locales/zh-Hant.ts | 20 +
ui/packages/plugin-dashboard/README.md | 29 ++
.../src/DashboardFilterBar.tsx | 40 +-
.../src/DashboardRenderer.tsx | 41 +-
.../DashboardRenderer.designMode.test.tsx | 53 +++
.../DashboardRenderer.filters.test.tsx | 74 +++
.../src/designAffordances.test.ts | 43 ++
.../src/designAffordances.tsx | 192 ++++++++
27 files changed, 1855 insertions(+), 26 deletions(-)
create mode 100644 .changeset/36372-dashboard-in-page-edit.md
create mode 100644 ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
create mode 100644 ui/packages/app-shell/src/views/DashboardInPageEditor.tsx
create mode 100644 ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
create mode 100644 ui/packages/plugin-dashboard/src/designAffordances.test.ts
create mode 100644 ui/packages/plugin-dashboard/src/designAffordances.tsx
diff --git a/.changeset/36372-dashboard-in-page-edit.md b/.changeset/36372-dashboard-in-page-edit.md
new file mode 100644
index 00000000000..48806be2689
--- /dev/null
+++ b/.changeset/36372-dashboard-in-page-edit.md
@@ -0,0 +1,19 @@
+---
+'@object-ui/core': patch
+'@object-ui/i18n': patch
+'@object-ui/plugin-dashboard': patch
+'@object-ui/app-shell': patch
+---
+
+feat(console): a dashboard is edited on its own page by the people who may design its package, and every card marks the page filters it does not follow
+
+Clause-②: yes (widening) — one new exported function (`dashboardFiltersNotApplied` in `@object-ui/core`), two new optional `DashboardRenderer` props (`onWidgetResize`, `onAddFilter`), an optional `{ packageId }` on `saveAndPublishRuntimeMetadata`, and new `@object-ui/i18n` keys (`dashboard.inPageEdit.*`, `dashboard.filters.notApplied`, `dashboard.filters.addFilter`); nothing is removed or renamed
+Metadata-protocol: none
+
+A dashboard page draws an **Edit** button for a workspace admin who may author metadata, on a package Studio lists (the gate of the app's Studio entries). Edit opens the dashboard as stored (never the translated copy the page shows) in an edit state: the header says **Editing**, with **Add card**, **Discard** and **Save**; every card draws a dashed outline and can be dragged to move it, resized from its corner by whole grid tracks (or with the arrow keys on the corner handle) and clicked to select it. The panel at the right is Studio's own dashboard panels, as they stand: a selected card's (its data, its "follow page filters" switches, Remove) and otherwise the dashboard's (label, cards, filters, layout). The filter bar's **Add filter** opens the panel's Filters section. Add card appends a card at the end and selects it.
+
+Save writes where Studio's Customize would and publishes that one item in the same act, so everyone sees the change at once without the app's package being published: into the owning package when it is writable, else into the app's customization package (` .custom`, asked of the ensure door, declaring `overrides: { package, basedOn }`), so an installed app's dashboard is edited too. A dashboard with a draft already pending there (a Studio edit not yet published) is not opened for editing, and a save over one writes nothing: that draft is never published on its saver's behalf. Discard drops every change.
+
+Every card, in every mode, carries a small mark naming the page filters that do not reach it ("Not filtered by Region"), asked of the same binding its query is built from (`dashboardFiltersNotApplied` over `resolveBoundField`): a filter the card opts out of, or one whose `targetWidgets` leaves it out. A card every filter reaches carries none.
+
+`saveAndPublishRuntimeMetadata` takes an optional `{ packageId }`, named on its draft write, its publish and its discard; omitted, it writes exactly as before.
diff --git a/content/docs/frontend/plugins/plugin-dashboard.mdx b/content/docs/frontend/plugins/plugin-dashboard.mdx
index ce67666a511..20489ce35df 100644
--- a/content/docs/frontend/plugins/plugin-dashboard.mdx
+++ b/content/docs/frontend/plugins/plugin-dashboard.mdx
@@ -143,6 +143,35 @@ request draws it, and a widget re-reads on its own when a write invalidates the
object it reads. A query asked alone, and every query of an adapter without
`queryDatasetBatch`, takes `queryDataset` unchanged.
+## Filters a widget does not follow
+
+Every widget, in every mode, carries a small mark naming the dashboard
+filters that do not reach it, for example "Not filtered by Region": a filter
+it opts out of (`filterBindings[name]: false`) or one whose `targetWidgets`
+leaves it out. A widget every filter reaches carries none. The list is
+`dashboardFiltersNotApplied(widget, defs)` from `@object-ui/core`, which asks
+`resolveBoundField`, the binding the widget's query is built from, so the
+mark and the data cannot disagree.
+
+## Design mode: resizing and "Add filter"
+
+In `designMode` two more affordances are drawn when the host hands their
+handler:
+
+- `onWidgetResize(widgetId, { w, h })`: a corner handle on each widget
+ resizes it by whole grid tracks (it snaps as the pointer crosses half a
+ track; the arrow keys on the handle grow or shrink it by one). Width stays
+ within the grid's columns. The host writes the span into the widget's
+ `layout`. Not drawn below the phone breakpoint.
+- `onAddFilter()`: an "Add filter" button at the end of the filter bar, which
+ is drawn for it even before any filter is declared.
+
+The console's dashboard page uses both in its in-page edit state: an admin
+who may design the dashboard's package opens it with **Edit**, changes it with
+Studio's own dashboard panels at the right, and **Save** publishes that one
+dashboard (into the package, or into the app's customization package for an
+installed app), so everyone sees it at once.
+
## TypeScript Support
```ts
diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
new file mode 100644
index 00000000000..6e8b8abbfd3
--- /dev/null
+++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
@@ -0,0 +1,100 @@
+/**
+ * ObjectUI
+ * Copyright (c) 2024-present ObjectStack Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+import {
+ filtersSectionLabel,
+ openDashboardForEdit,
+ withAddedWidget,
+ withResizedWidget,
+} from './DashboardInPageEditor';
+import type { DashboardSaveTargetDoors } from './runtime-metadata-persistence';
+
+/**
+ * objectstack#36372 — opening a dashboard for in-page editing, and the two
+ * buffer edits the page makes itself (add a card, resize a card). The rest of
+ * the buffer's edits are Studio's panels' own `onPatch`.
+ */
+
+const doors = (writable: boolean): DashboardSaveTargetDoors => ({
+ listPackages: async () => new Map([['crm', { writable, manifest: { id: 'crm', version: '3.0.0' } } as any]]),
+ ensureCustomization: async (base) => ({ packageId: `${base}.custom`, writable: true }),
+});
+
+const stored = { name: 'exec', label: 'Exec', widgets: [{ id: 'a', type: 'bar' }] };
+
+describe('openDashboardForEdit', () => {
+ it('opens the layered effective document of the owning package', async () => {
+ const client = {
+ getDraft: vi.fn(async () => null),
+ layered: vi.fn(async () => ({ code: { name: 'exec' }, effective: stored })),
+ };
+ await expect(openDashboardForEdit('exec', 'crm', client, doors(true))).resolves.toEqual({
+ kind: 'ready',
+ target: { kind: 'package', packageId: 'crm' },
+ doc: stored,
+ });
+ expect(client.getDraft).toHaveBeenCalledWith('dashboard', 'exec', { packageId: 'crm' });
+ });
+
+ it('into a customization pair that does not hold it yet, opens its base\'s document', async () => {
+ const client = {
+ getDraft: vi.fn(async () => null),
+ layered: vi.fn(async (_t: string, _n: string, o?: { packageId?: string }) =>
+ o?.packageId === 'crm' ? { code: stored, effective: stored } : { code: null, effective: null },
+ ),
+ };
+ const opened = await openDashboardForEdit('exec', 'crm', client, doors(false));
+ expect(opened).toMatchObject({ kind: 'ready', target: { kind: 'customization', packageId: 'crm.custom', base: 'crm' }, doc: stored });
+ expect(client.getDraft).toHaveBeenCalledWith('dashboard', 'exec', { packageId: 'crm.custom' });
+ });
+
+ it('is refused over a pending draft, without reading the document', async () => {
+ const client = {
+ getDraft: vi.fn(async () => ({ item: { name: 'exec' } })),
+ layered: vi.fn(),
+ };
+ await expect(openDashboardForEdit('exec', 'crm', client, doors(true))).resolves.toEqual({ kind: 'refused', reason: 'pending-draft' });
+ expect(client.layered).not.toHaveBeenCalled();
+ });
+
+ it('is refused when there is no package to save into, and when the read fails', async () => {
+ const client = { getDraft: vi.fn(async () => null), layered: vi.fn(async () => ({ code: null, effective: null })) };
+ await expect(openDashboardForEdit('exec', 'gone', client, doors(true))).resolves.toMatchObject({ kind: 'refused', reason: 'no-package' });
+ await expect(openDashboardForEdit('exec', 'crm', client, doors(true))).resolves.toMatchObject({ kind: 'refused', reason: 'load-failed' });
+ const failing = { getDraft: vi.fn(async () => { throw new Error('500'); }), layered: vi.fn() };
+ await expect(openDashboardForEdit('exec', 'crm', failing, doors(true))).resolves.toEqual({
+ kind: 'refused',
+ reason: 'load-failed',
+ detail: '500',
+ });
+ });
+});
+
+describe('the page\'s own buffer edits', () => {
+ it('adds a card at the end with a fresh id', () => {
+ const added = withAddedWidget({ ...stored, widgets: [{ id: 'widget_1', type: 'bar' }] }, 'pie');
+ expect(added.id).toBe('widget_2');
+ const widgets = added.doc.widgets as Array<{ id: string; type: string }>;
+ expect(widgets.map((w) => w.id)).toEqual(['widget_1', 'widget_2']);
+ expect(widgets[1].type).toBe('pie');
+ });
+
+ it('resizes a card, keeping the coordinates the span does not name', () => {
+ const doc = { widgets: [{ id: 'a', type: 'bar', layout: { x: 6, y: 2, w: 3, h: 4 } }, { id: 'b', type: 'bar' }] };
+ expect((withResizedWidget(doc, 'a', { w: 4, h: 2 }).widgets as any[])[0].layout).toEqual({ x: 6, y: 2, w: 4, h: 2 });
+ // A card with no layout gets the grid's auto placement for its index.
+ expect((withResizedWidget(doc, 'b', { w: 2, h: 1 }).widgets as any[])[1].layout).toEqual({ x: 3, y: 0, w: 2, h: 1 });
+ // An unknown id changes nothing.
+ expect(withResizedWidget(doc, 'zz', { w: 2, h: 1 })).toBe(doc);
+ });
+
+ it('finds the panel section that edits the page filters', () => {
+ expect(filtersSectionLabel('en-US')).toBe('Filters');
+ });
+});
diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx
new file mode 100644
index 00000000000..709cc51e502
--- /dev/null
+++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx
@@ -0,0 +1,435 @@
+/**
+ * objectstack#36372 — editing a dashboard on its own page, for the people who
+ * may design its package.
+ *
+ * The page's Edit button opens an edit state over the dashboard as it is
+ * stored (never the served, translated copy): the cards draw dashed and can be
+ * dragged, corner-resized and clicked; the panel at the right is Studio's own
+ * dashboard panels, as they stand (`DashboardWidgetInspector` for a selected
+ * card, `DashboardDefaultInspector` for the page and its filters). Save writes
+ * where Studio's would, and publishes that one item in the same act, so the
+ * change applies to everyone at once without the app's package being
+ * published; Discard drops every change.
+ *
+ * Where a save lands is {@link resolveDashboardSaveTarget}'s answer: the
+ * owning package when it is writable, else the app's customization package
+ * ` .custom` (ADR-0146), so an installed app is edited too. Over a draft
+ * already pending there (a Studio edit not yet published) the edit state is
+ * not entered: that draft is its saver's, and is never published on their
+ * behalf.
+ *
+ * Out of scope here: undo, a business user's own copy, a new dashboard, chart
+ * drawing and drill-down.
+ */
+
+import * as React from 'react';
+import { Badge, Button } from '@object-ui/components';
+import { Pencil } from 'lucide-react';
+import { completeWidgetLayout, defaultWidgetPlacement, type DashboardWidgetSchema } from '@object-ui/types';
+import { useSafeTranslate } from '@object-ui/i18n';
+import {
+ dashboardSaveBody,
+ resolveDashboardSaveTarget,
+ saveDashboardInPlace,
+ unwrapDraftBody,
+ type DashboardSaveTarget,
+ type DashboardSaveTargetDoors,
+ type SaveAndPublishOutcome,
+} from './runtime-metadata-persistence.js';
+import { useStudioEntryGate } from '../hooks/useStudioDesignGate.js';
+import { DashboardWidgetInspector } from './metadata-admin/inspectors/DashboardWidgetInspector.js';
+import { DashboardDefaultInspector } from './metadata-admin/inspectors/DashboardDefaultInspector.js';
+import { AddWidgetPicker } from './metadata-admin/previews/AddWidgetPicker.js';
+import { WIDGET_TYPE_META } from './metadata-admin/previews/widget-types.js';
+import { appendArray, uniqueId } from './metadata-admin/inspectors/_shared.js';
+import { getDashboardForm } from './metadata-admin/dashboard-schema.js';
+import { useMetadataLocale, type SupportedLocale } from './metadata-admin/i18n.js';
+import type { MetadataSelection } from './metadata-admin/preview-registry.js';
+
+/** A save target the editor can write to. */
+export type WritableDashboardSaveTarget = Exclude;
+
+/** What opening a dashboard for editing found. */
+export type DashboardEditOpening =
+ | { kind: 'ready'; target: WritableDashboardSaveTarget; doc: Record }
+ | { kind: 'refused'; reason: 'no-package' | 'pending-draft' | 'load-failed'; detail?: string };
+
+/** The metadata client calls {@link openDashboardForEdit} makes. */
+export interface DashboardEditReader {
+ getDraft(type: string, name: string, options?: { packageId?: string }): Promise;
+ layered(
+ type: string,
+ name: string,
+ options?: { packageId?: string },
+ ): Promise<{ code: unknown; effective: unknown }>;
+}
+
+function authoredDoc(layers: { code: unknown; effective: unknown } | null): Record | null {
+ const doc = layers ? (layers.effective ?? layers.code) : null;
+ return doc && typeof doc === 'object' && !Array.isArray(doc) ? (doc as Record) : null;
+}
+
+/**
+ * Open `name` for editing: where a save would land, and the document as
+ * authored there (its layered read's `effective`, the buffer Studio edits; a
+ * customization package that does not hold the item yet starts from its
+ * base's). Refused when there is no package to save into, when a draft is
+ * already pending there, or when the item cannot be read.
+ */
+export async function openDashboardForEdit(
+ name: string,
+ ownerPackageId: string | null | undefined,
+ client: DashboardEditReader,
+ doors?: DashboardSaveTargetDoors,
+): Promise {
+ const target = await resolveDashboardSaveTarget(ownerPackageId, doors);
+ if (target.kind === 'refused') return { kind: 'refused', reason: 'no-package', detail: target.reason };
+ const at = target.kind === 'unbound' ? {} : { packageId: target.packageId };
+ try {
+ if (unwrapDraftBody(await client.getDraft('dashboard', name, at))) {
+ return { kind: 'refused', reason: 'pending-draft' };
+ }
+ let doc = authoredDoc(await client.layered('dashboard', name, at));
+ if (!doc && target.kind === 'customization') {
+ doc = authoredDoc(await client.layered('dashboard', name, { packageId: target.base }));
+ }
+ if (!doc) return { kind: 'refused', reason: 'load-failed' };
+ return { kind: 'ready', target, doc };
+ } catch (err) {
+ return { kind: 'refused', reason: 'load-failed', detail: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+type Widget = DashboardWidgetSchema & { id?: string };
+
+function widgetsOf(doc: Record): Widget[] {
+ return Array.isArray(doc.widgets) ? (doc.widgets as Widget[]) : [];
+}
+
+/**
+ * `doc` with a new card of `type` appended, the way Studio's Add widget makes
+ * one (a unique `widget_N` id, the type's defaults), and the id it got.
+ */
+export function withAddedWidget(
+ doc: Record,
+ type: string,
+): { doc: Record; id: string; label: string } {
+ const widgets = widgetsOf(doc);
+ const id = uniqueId('widget', widgets.map((w) => w?.id).filter(Boolean) as string[]);
+ const meta = WIDGET_TYPE_META[type];
+ const label = meta ? `New ${meta.label.toLowerCase()}` : 'New widget';
+ const widget = { id, type, title: label, ...(meta?.defaults ?? {}) } as unknown as Widget;
+ return { doc: { ...doc, widgets: appendArray(widgets, widget) }, id, label };
+}
+
+/**
+ * `doc` with card `widgetId` spanning `span` grid tracks: its `layout` keeps
+ * every coordinate the span does not name (`completeWidgetLayout`).
+ */
+export function withResizedWidget(
+ doc: Record,
+ widgetId: string,
+ span: { w: number; h: number },
+): Record {
+ const widgets = widgetsOf(doc);
+ const index = widgets.findIndex((w) => w?.id === widgetId);
+ if (index < 0) return doc;
+ const widget = widgets[index] as Widget & { layout?: Record };
+ const layout = completeWidgetLayout(widget.layout, span, defaultWidgetPlacement(index));
+ const next = widgets.slice();
+ next[index] = { ...widget, layout } as Widget;
+ return { ...doc, widgets: next };
+}
+
+/** The label of the panel section that edits the page filters (`globalFilters`). */
+export function filtersSectionLabel(locale: SupportedLocale): string | null {
+ const form = getDashboardForm(locale);
+ const section = form?.sections?.find((s) =>
+ (s.fields ?? []).some((f) => (typeof f === 'string' ? f : f.field) === 'globalFilters'),
+ );
+ return typeof section?.label === 'string' ? section.label : null;
+}
+
+/**
+ * Whether this principal is offered the Edit button for a dashboard
+ * `ownerPackageId` owns: the gate of the app → Studio entries
+ * (`useStudioEntryGate`: a workspace admin who may author metadata, on a
+ * package Studio lists, writable or not; never a kernel package). A
+ * read-only package's dashboard is edited through its customization package.
+ */
+export function useDashboardEditOffered(ownerPackageId: string | null | undefined): boolean {
+ const path = ownerPackageId ? `/studio/${encodeURIComponent(ownerPackageId)}` : null;
+ return useStudioEntryGate(path) !== null;
+}
+
+/** The page header's Edit button. */
+export function DashboardEditButton({ onClick, busy }: { onClick: () => void; busy?: boolean }) {
+ const tt = useSafeTranslate();
+ return (
+
+
+ {busy ? tt('dashboard.inPageEdit.loading', 'Opening the dashboard for editing…') : tt('dashboard.inPageEdit.edit', 'Edit')}
+
+ );
+}
+
+/** The page header's badge while editing. */
+export function DashboardEditingBadge() {
+ const tt = useSafeTranslate();
+ return (
+
+ {tt('dashboard.inPageEdit.editing', 'Editing')}
+
+ );
+}
+
+/** The page header's actions while editing: Add card, Discard, Save. */
+export function DashboardEditActions({
+ onAddCard,
+ onDiscard,
+ onSave,
+ saving,
+ dirty,
+}: {
+ onAddCard: (type: string) => void;
+ onDiscard: () => void;
+ onSave: () => void;
+ saving: boolean;
+ dirty: boolean;
+}) {
+ const tt = useSafeTranslate();
+ return (
+
+
+
+ {tt('dashboard.inPageEdit.discard', 'Discard')}
+
+
+ {saving ? tt('dashboard.inPageEdit.saving', 'Saving…') : tt('dashboard.inPageEdit.save', 'Save')}
+
+
+ );
+}
+
+/**
+ * The right panel while editing: Studio's card panel for the selected card,
+ * its dashboard panel (label, cards, filters, layout) otherwise. `revealFilters`
+ * opens and scrolls to the filters section, the "Add filter" path.
+ */
+export function DashboardEditPanel({
+ name,
+ draft,
+ selection,
+ onPatch,
+ onSelectionChange,
+ revealFilters,
+ onFiltersRevealed,
+}: {
+ name: string;
+ draft: Record;
+ selection: MetadataSelection | null;
+ onPatch: (patch: Record) => void;
+ onSelectionChange: (next: MetadataSelection | null) => void;
+ revealFilters: boolean;
+ onFiltersRevealed: () => void;
+}) {
+ const locale = useMetadataLocale();
+ const tt = useSafeTranslate();
+ const ref = React.useRef(null);
+
+ React.useEffect(() => {
+ if (!revealFilters || selection) return;
+ const label = filtersSectionLabel(locale);
+ const trigger = label
+ ? Array.from(ref.current?.querySelectorAll('button[data-state]') ?? []).find(
+ (b) => b.querySelector('span > span')?.textContent === label,
+ )
+ : undefined;
+ if (trigger) {
+ if (trigger.getAttribute('data-state') === 'closed') trigger.click();
+ trigger.scrollIntoView?.({ block: 'start' });
+ }
+ onFiltersRevealed();
+ }, [revealFilters, selection, locale, onFiltersRevealed]);
+
+ return (
+
+ {selection?.kind === 'widget' ? (
+ onSelectionChange(null)}
+ onSelectionChange={onSelectionChange}
+ readOnly={false}
+ locale={locale}
+ />
+ ) : (
+
+ )}
+
+ );
+}
+
+/** The client {@link useDashboardInPageEdit} reads and writes through. */
+export type DashboardEditClient = DashboardEditReader & {
+ save: (...args: any[]) => Promise;
+ publish: (...args: any[]) => Promise;
+ reset: (...args: any[]) => Promise;
+};
+
+/** The edit state of one dashboard page. */
+export interface DashboardInPageEdit {
+ /** The document being edited, `null` outside the edit state. */
+ draft: Record | null;
+ opening: boolean;
+ saving: boolean;
+ dirty: boolean;
+ selection: MetadataSelection | null;
+ revealFilters: boolean;
+ /** Enter the edit state; resolves the refusal when it is not entered. */
+ open: () => Promise | null>;
+ discard: () => void;
+ /** Save and publish; resolves what the save did, or throws its refusal. */
+ save: () => Promise;
+ patch: (patch: Record) => void;
+ select: (next: MetadataSelection | null) => void;
+ addCard: (type: string) => void;
+ resize: (widgetId: string, span: { w: number; h: number }) => void;
+ reorder: (widgets: unknown) => void;
+ requestFilters: () => void;
+ filtersRevealed: () => void;
+}
+
+/** The edit state's buffer, selection and save. */
+export function useDashboardInPageEdit({
+ name,
+ ownerPackageId,
+ client,
+ dataSource,
+ doors,
+}: {
+ name: string;
+ ownerPackageId: string | null | undefined;
+ client: DashboardEditClient;
+ dataSource?: object | null;
+ doors?: DashboardSaveTargetDoors;
+}): DashboardInPageEdit {
+ const [session, setSession] = React.useState<{
+ target: WritableDashboardSaveTarget;
+ draft: Record;
+ dirty: boolean;
+ } | null>(null);
+ const [opening, setOpening] = React.useState(false);
+ const [saving, setSaving] = React.useState(false);
+ const [selection, setSelection] = React.useState(null);
+ const [revealFilters, setRevealFilters] = React.useState(false);
+
+ // Another dashboard on the same route drops the edit state.
+ React.useEffect(() => {
+ setSession(null);
+ setSelection(null);
+ }, [name]);
+
+ const update = React.useCallback((fn: (doc: Record) => Record) => {
+ setSession((s) => (s ? { ...s, draft: fn(s.draft), dirty: true } : s));
+ }, []);
+
+ const open = React.useCallback(async () => {
+ setOpening(true);
+ try {
+ const opened = await openDashboardForEdit(name, ownerPackageId, client, doors);
+ if (opened.kind === 'refused') return opened;
+ setSession({ target: opened.target, draft: opened.doc, dirty: false });
+ setSelection(null);
+ return null;
+ } finally {
+ setOpening(false);
+ }
+ }, [name, ownerPackageId, client, doors]);
+
+ const discard = React.useCallback(() => {
+ setSession(null);
+ setSelection(null);
+ setRevealFilters(false);
+ }, []);
+
+ const save = React.useCallback(async (): Promise => {
+ if (!session) return 'published';
+ const body = dashboardSaveBody(session.draft, session.target);
+ if (!body) return 'invalid-body';
+ setSaving(true);
+ try {
+ const outcome = await saveDashboardInPlace(name, body, session.target, {
+ metadataClient: client,
+ dataSource: (dataSource ?? null) as any,
+ });
+ if (outcome === 'published') {
+ setSession(null);
+ setSelection(null);
+ }
+ return outcome;
+ } finally {
+ setSaving(false);
+ }
+ }, [session, name, client, dataSource]);
+
+ const addCard = React.useCallback(
+ (type: string) => {
+ if (!session) return;
+ const added = withAddedWidget(session.draft, type);
+ setSession({ ...session, draft: added.doc, dirty: true });
+ setSelection({ kind: 'widget', id: added.id, label: added.label });
+ },
+ [session],
+ );
+
+ return {
+ draft: session?.draft ?? null,
+ opening,
+ saving,
+ dirty: session?.dirty ?? false,
+ selection,
+ revealFilters,
+ open,
+ discard,
+ save,
+ patch: React.useCallback((p: Record) => update((doc) => ({ ...doc, ...p })), [update]),
+ select: setSelection,
+ addCard,
+ resize: React.useCallback(
+ (widgetId: string, span: { w: number; h: number }) => update((doc) => withResizedWidget(doc, widgetId, span)),
+ [update],
+ ),
+ reorder: React.useCallback((widgets: unknown) => update((doc) => ({ ...doc, widgets })), [update]),
+ requestFilters: React.useCallback(() => {
+ setSelection(null);
+ setRevealFilters(true);
+ }, []),
+ filtersRevealed: React.useCallback(() => setRevealFilters(false), []),
+ };
+}
diff --git a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
new file mode 100644
index 00000000000..178d36a9efb
--- /dev/null
+++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
@@ -0,0 +1,261 @@
+/**
+ * ObjectUI
+ * Copyright (c) 2024-present ObjectStack Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/**
+ * objectstack#36372 — a dashboard is edited on its own page by the people who
+ * may design its package.
+ *
+ * Through the real `DashboardView`, the real `DashboardRenderer` and the real
+ * save seam (`saveDashboardInPlace` over a recording metadata client), this
+ * file pins:
+ * - the Edit button is drawn only when the app → Studio gate lets the
+ * principal in;
+ * - Edit opens the stored document (the layered read's `effective`, never
+ * the served copy), with the Editing badge, the panel and the cards in
+ * design mode; Save is off until something changes;
+ * - a corner resize, then Save, stages the body in the owning package under
+ * the first-write pin and publishes that one item, and the page leaves
+ * the edit state;
+ * - an installed (read-only) package saves into its customization pair,
+ * declaring the override of its base;
+ * - a draft already pending there refuses the edit state and writes nothing;
+ * - Discard drops every change and writes nothing.
+ *
+ * Studio's two dashboard panels and the add-card picker are stubbed to the
+ * props this view hands them: their own behaviour is pinned beside them.
+ */
+
+import * as React from 'react';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, act, cleanup, fireEvent, waitFor } from '@testing-library/react';
+import { MetadataCtx } from '@object-ui/react';
+
+const meta = vi.hoisted(() => ({ value: null as unknown }));
+const gate = vi.hoisted(() => ({ entry: null as null | { path: string; posture: 'edit' | 'view' } }));
+const client = vi.hoisted(() => ({ value: null as any }));
+const packages = vi.hoisted(() => ({
+ listed: new Map(),
+ ensure: null as null | ((base: string) => Promise<{ packageId: string; writable: boolean }>),
+}));
+const toasts = vi.hoisted(() => ({ success: [] as unknown[], error: [] as unknown[] }));
+
+vi.mock('../providers/MetadataProvider', () => ({ useMetadata: () => meta.value }));
+vi.mock('react-router-dom', () => ({
+ useParams: () => ({ dashboardName: 'ops_board' }),
+ useNavigate: () => vi.fn(),
+ useLocation: () => ({ pathname: '/apps/crm/dashboard/ops_board', search: '' }),
+}));
+vi.mock('./useOpenRecordList', () => ({
+ useRecordListDrillNavigation: () => ({ openRecordList: vi.fn(), canOpenRecordList: () => true }),
+}));
+vi.mock('./MetadataInspector', () => ({
+ MetadataPanel: () => null,
+ useMetadataInspector: () => ({ showDebug: false }),
+}));
+vi.mock('../providers/AdapterProvider', () => ({ useAdapter: () => ({}) }));
+vi.mock('../providers/ExpressionProvider', () => ({ useExpressionContext: () => ({ app: undefined }) }));
+vi.mock('../hooks/useStudioDesignGate', () => ({ useStudioEntryGate: () => gate.entry }));
+vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => client.value }));
+vi.mock('./studio-design/packages-io', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ fetchListedPackageManifests: async () => packages.listed,
+ ensureCustomizationPackage: (base: string) => packages.ensure!(base),
+}));
+vi.mock('sonner', () => ({
+ toast: {
+ success: (...a: unknown[]) => toasts.success.push(a),
+ error: (...a: unknown[]) => toasts.error.push(a),
+ info: vi.fn(),
+ },
+}));
+vi.mock('./metadata-admin/inspectors/DashboardWidgetInspector', () => ({
+ DashboardWidgetInspector: (p: any) => {p.selection.id}
,
+}));
+vi.mock('./metadata-admin/inspectors/DashboardDefaultInspector', () => ({
+ DashboardDefaultInspector: (p: any) => (
+
+ p.onPatch({ label: 'Renamed (36372)' })}>stub-rename
+
+ ),
+}));
+vi.mock('./metadata-admin/previews/AddWidgetPicker', () => ({
+ AddWidgetPicker: (p: any) => (
+ p.onAdd('bar')}>{p.label}
+ ),
+}));
+
+import { DashboardView } from './DashboardView';
+
+/** The served dashboard: translated for the session, with its read's decorations. */
+const served = {
+ name: 'ops_board',
+ label: 'Operations (served)',
+ _packageId: 'crm',
+ widgets: [{ id: 'widget_total', type: 'kpi', title: 'Total (served)', options: { value: 42 } }],
+};
+
+/** The same dashboard as stored: what the edit state opens. */
+const stored = {
+ name: 'ops_board',
+ label: 'Operations (stored)',
+ widgets: [{ id: 'widget_total', type: 'kpi', title: 'Total (stored)', options: { value: 42 } }],
+ _packageId: 'crm',
+};
+
+function makeClient(over: Partial> = {}) {
+ return {
+ getDraft: vi.fn(async () => null),
+ layered: vi.fn(async () => ({ code: null, overlay: null, effective: stored })),
+ save: vi.fn(async () => undefined),
+ publish: vi.fn(async () => undefined),
+ reset: vi.fn(async () => undefined),
+ ...over,
+ };
+}
+
+function mount() {
+ meta.value = {
+ apps: [],
+ objects: [],
+ dashboards: [served],
+ reports: [],
+ pages: [],
+ loading: false,
+ error: null,
+ refresh: async () => {},
+ invalidate: () => {},
+ ensureType: async () => [],
+ getItem: vi.fn(async () => null),
+ getItemsByType: () => [],
+ getTypeStatus: () => 'ready',
+ };
+ return render(
+ }>
+
+ ,
+ );
+}
+
+async function openEdit() {
+ fireEvent.click(await screen.findByTestId('dashboard-edit'));
+ await screen.findByTestId('dashboard-editing-badge');
+}
+
+beforeEach(() => {
+ gate.entry = { path: '/studio/crm', posture: 'edit' };
+ client.value = makeClient();
+ packages.listed = new Map([['crm', { id: 'crm', writable: true, manifest: { id: 'crm', version: '1.4.0' } }]]);
+ packages.ensure = async (base) => ({ packageId: `${base}.custom`, writable: true });
+ toasts.success = [];
+ toasts.error = [];
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('DashboardView in-page edit (objectstack#36372)', () => {
+ it('draws no Edit button for a principal the Studio gate keeps out', async () => {
+ gate.entry = null;
+ mount();
+ await screen.findAllByText('Total (served)');
+ expect(screen.queryByTestId('dashboard-edit')).not.toBeInTheDocument();
+ });
+
+ it('Edit opens the stored document in design mode, with the badge and the panel; Save waits for a change', async () => {
+ mount();
+ await openEdit();
+ expect(client.value.layered).toHaveBeenCalledWith('dashboard', 'ops_board', { packageId: 'crm' });
+ // The stored title, not the served one.
+ expect((await screen.findAllByText('Total (stored)')).length).toBeGreaterThan(0);
+ expect(screen.queryAllByText('Total (served)')).toHaveLength(0);
+ expect(screen.getByTestId('dashboard-preview-widget-widget_total')).toBeInTheDocument();
+ expect(screen.getByTestId('stub-default-inspector')).toBeInTheDocument();
+ expect(screen.getByTestId('dashboard-edit-save')).toBeDisabled();
+
+ // A click on a card selects it, and the panel swaps to the card's.
+ fireEvent.click(screen.getByTestId('dashboard-preview-widget-widget_total'));
+ expect(screen.getByTestId('stub-widget-inspector')).toHaveTextContent('widget_total');
+ });
+
+ it('a corner resize then Save stages and publishes the one item in its package, and leaves the edit state', async () => {
+ mount();
+ await openEdit();
+ fireEvent.keyDown(screen.getByTestId('dashboard-widget-resize-handle'), { key: 'ArrowRight' });
+ const save = screen.getByTestId('dashboard-edit-save');
+ expect(save).not.toBeDisabled();
+ await act(async () => {
+ fireEvent.click(save);
+ });
+
+ expect(client.value.save).toHaveBeenCalledTimes(1);
+ const [type, name, body, options] = client.value.save.mock.calls[0];
+ expect([type, name, options]).toEqual(['dashboard', 'ops_board', { mode: 'draft', ifNoneMatch: '*', packageId: 'crm' }]);
+ expect(body).not.toHaveProperty('_packageId');
+ expect(body.label).toBe('Operations (stored)');
+ expect(body.widgets[0].layout).toMatchObject({ w: 2, h: 1 });
+ expect(client.value.publish).toHaveBeenCalledWith('dashboard', 'ops_board', { packageId: 'crm' });
+ await waitFor(() => expect(screen.queryByTestId('dashboard-editing-badge')).not.toBeInTheDocument());
+ expect(toasts.success).toHaveLength(1);
+ });
+
+ it('Add card appends a card and selects it', async () => {
+ mount();
+ await openEdit();
+ fireEvent.click(screen.getByTestId('stub-add-card'));
+ expect(screen.getByTestId('stub-widget-inspector')).toHaveTextContent('widget_1');
+ expect(screen.getByTestId('dashboard-preview-widget-widget_1')).toBeInTheDocument();
+ });
+
+ it('an installed package saves into its customization pair, declaring the override of its base', async () => {
+ packages.listed = new Map([['crm', { id: 'crm', writable: false, manifest: { id: 'crm', version: '1.4.0' } }]]);
+ gate.entry = { path: '/studio/crm', posture: 'view' };
+ client.value = makeClient({
+ // The pair does not hold the dashboard yet: the base's is opened.
+ layered: vi.fn(async (_t: string, _n: string, o: { packageId?: string }) =>
+ o.packageId === 'crm' ? { code: stored, overlay: null, effective: stored } : { code: null, overlay: null, effective: null },
+ ),
+ });
+ mount();
+ await openEdit();
+ fireEvent.click(screen.getByText('stub-rename'));
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('dashboard-edit-save'));
+ });
+
+ const [, , body, options] = client.value.save.mock.calls[0];
+ expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*', packageId: 'crm.custom' });
+ expect(body).toMatchObject({ label: 'Renamed (36372)', overrides: { package: 'crm', basedOn: '1.4.0' } });
+ expect(client.value.publish).toHaveBeenCalledWith('dashboard', 'ops_board', { packageId: 'crm.custom' });
+ });
+
+ it('a draft already pending in the package refuses the edit state and writes nothing', async () => {
+ client.value = makeClient({ getDraft: vi.fn(async () => ({ item: { name: 'ops_board', label: 'Studio draft' } })) });
+ mount();
+ const edit = await screen.findByTestId('dashboard-edit');
+ await act(async () => {
+ fireEvent.click(edit);
+ });
+ await waitFor(() => expect(toasts.error).toHaveLength(1));
+ expect(screen.queryByTestId('dashboard-editing-badge')).not.toBeInTheDocument();
+ expect(toasts.error).toHaveLength(1);
+ expect(String((toasts.error[0] as unknown[])[0])).toContain('unpublished changes in Studio');
+ expect(client.value.save).not.toHaveBeenCalled();
+ });
+
+ it('Discard drops every change and writes nothing', async () => {
+ mount();
+ await openEdit();
+ fireEvent.click(screen.getByText('stub-rename'));
+ fireEvent.click(screen.getByTestId('dashboard-edit-discard'));
+ expect(screen.queryByTestId('dashboard-editing-badge')).not.toBeInTheDocument();
+ expect((await screen.findAllByText('Total (served)')).length).toBeGreaterThan(0);
+ expect(client.value.save).not.toHaveBeenCalled();
+ expect(client.value.publish).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx
index 7b9e294577e..95a9124bc69 100644
--- a/ui/packages/app-shell/src/views/DashboardView.tsx
+++ b/ui/packages/app-shell/src/views/DashboardView.tsx
@@ -2,14 +2,16 @@
* Dashboard View Component
* Renders a dashboard based on the dashboardName parameter.
*
- * This is a pure VIEWER. Authoring a dashboard (adding/removing widgets,
- * editing config) lives in Studio's Interfaces pillar — reached via the top
- * bar's "Design in Studio" icon, which deep-links to this dashboard's design
- * surface. The former in-page inline edit button + config panel were retired
- * so there is a single, consistent authoring surface.
+ * A viewer, with one edit state for the people who may design the
+ * dashboard's package (objectstack#36372): the header's Edit button opens it
+ * in place, over the stored document, with Studio's own dashboard panels at
+ * the right (`DashboardInPageEditor.tsx`). Its Save writes where Studio's
+ * would and publishes that one item, so everyone sees the change at once.
+ * Deeper authoring (a new dashboard, chart drawing) stays in Studio's
+ * Interfaces pillar, reached through the top bar's "Design in Studio" icon.
*/
-import { useState, useEffect, useMemo, type ComponentProps } from 'react';
+import { useState, useEffect, useMemo, useRef, type ComponentProps } from 'react';
import { useParams } from 'react-router-dom';
import { DashboardRenderer } from '@object-ui/plugin-dashboard';
import { DrillNavigationProvider, notifyDataChanged } from '@object-ui/react';
@@ -38,6 +40,15 @@ import { useBundledItem } from '../providers/bundledReads.js';
import { readDashboardWidgetObjects } from '../console/appObjectScope.js';
import { useObjectTranslation, useSafeTranslate } from '@object-ui/i18n';
import { DeploymentNotice } from '../console/deployment-notice/DeploymentNotice.js';
+import { useMetadataClient } from './metadata-admin/useMetadata.js';
+import {
+ DashboardEditActions,
+ DashboardEditButton,
+ DashboardEditingBadge,
+ DashboardEditPanel,
+ useDashboardEditOffered,
+ useDashboardInPageEdit,
+} from './DashboardInPageEditor.js';
import { useInSetupApp } from '../console/setupApp.js';
/**
@@ -193,12 +204,20 @@ export function DashboardView({ dataSource }: { dataSource?: any }) {
// prefer-local, as before. While the bundle is on the wire the dashboard is
// not yet known.
const bundledDashboard = useBundledItem('dashboard', dashboardName, (activeApp as any)?._packageId);
- const dashboard =
+ const readDashboard =
bundledDashboard.state === 'hit'
? bundledDashboard.value
: bundledDashboard.state === 'miss'
? preferLocal(metadata.dashboards as any[], dashboardName, (activeApp as any)?._packageId)
: undefined;
+ // objectstack#36372 — a save re-reads the bundle, which is on the wire for a
+ // moment: the dashboard shown keeps standing meanwhile, so a save does not
+ // flash the skeleton. Only for the same name: another dashboard waits.
+ const lastShown = useRef<{ name: string | undefined; value: any } | null>(null);
+ if (readDashboard) lastShown.current = { name: dashboardName, value: readDashboard };
+ const dashboard =
+ readDashboard ??
+ (bundledDashboard.state === 'pending' && lastShown.current?.name === dashboardName ? lastShown.current?.value : undefined);
// ---- A miss: refused, or not there? (objectui#12112) ---------------------
// The server lists only the dashboards this caller may open
@@ -241,6 +260,37 @@ export function DashboardView({ dataSource }: { dataSource?: any }) {
if (registered.size === 0) return null;
return (name) => !registered.has(name);
}, [absentObjectNames, listedObjects]);
+ // ---- In-page edit (objectstack#36372) ------------------------------------
+ // The package the dashboard is served from, else the app's.
+ const ownerPackageId: string | null =
+ (dashboard as any)?._packageId ?? (activeApp as any)?._packageId ?? null;
+ const editOffered = useDashboardEditOffered(ownerPackageId);
+ const metadataClient = useMetadataClient();
+ const edit = useDashboardInPageEdit({
+ name: dashboardName ?? '',
+ ownerPackageId,
+ client: metadataClient as any,
+ dataSource: adapter as any,
+ });
+ const editing = edit.draft !== null;
+ const startEdit = async () => {
+ const refused = await edit.open();
+ if (!refused) return;
+ if (refused.reason === 'pending-draft') toast.error(tt('dashboard.inPageEdit.pendingDraft', 'This dashboard has unpublished changes in Studio. Publish or discard them there, then edit it here.'));
+ else if (refused.reason === 'no-package') toast.error(tt('dashboard.inPageEdit.noPackage', "This dashboard cannot be saved here: its app has no package this account can customize."), refused.detail ? { description: refused.detail } : undefined);
+ else toast.error(tt('dashboard.inPageEdit.loadFailed', 'The dashboard could not be opened for editing'), refused.detail ? { description: refused.detail } : undefined);
+ };
+ const saveEdit = async () => {
+ try {
+ const outcome = await edit.save();
+ if (outcome === 'published') toast.success(tt('dashboard.inPageEdit.saved', 'Dashboard saved'));
+ else if (outcome === 'pending-draft') toast.error(tt('dashboard.inPageEdit.pendingDraft', 'This dashboard has unpublished changes in Studio. Publish or discard them there, then edit it here.'));
+ else toast.error(tt('dashboard.inPageEdit.saveFailed', 'The dashboard could not be saved'));
+ } catch (err: any) {
+ toast.error(tt('dashboard.inPageEdit.saveFailed', 'The dashboard could not be saved'), { description: err?.message || String(err) });
+ }
+ };
+
const previewSchema = useMemo(() => {
if (!dashboard || !unregistered) return dashboard;
const widgets = (dashboard as any).widgets;
@@ -364,9 +414,21 @@ export function DashboardView({ dataSource }: { dataSource?: any }) {
`hideHeaderText` already suppresses. */}
}
- actions={refreshState && (
+ badge={editing ? : undefined}
+ actions={editing ? (
+
+ ) : (refreshState || editOffered) && (
+
+ {editOffered && }
+ {refreshState && (
{refreshState.refreshing ? tt('dashboard.refreshing', 'Refreshing…') : tt('dashboard.refreshAll', 'Refresh All')}
+ )}
+
)}
/>
@@ -388,24 +452,54 @@ export function DashboardView({ dataSource }: { dataSource?: any }) {
{/* ── Main area ────────────────────────────────────────────── */}
-
+
{/* `localized`: this document is the `/meta` read's, already
translated for this language, so the renderer draws its
- title, description and sub-caption as served (objectui#11295). */}
+ title, description and sub-caption as served (objectui#11295).
+ The edit state draws the stored document instead, every card
+ of it, so it resolves its own labels and prunes nothing. */}
edit.select(id ? { kind: 'widget', id } : null),
+ onWidgetsReorder: edit.reorder,
+ onWidgetResize: edit.resize,
+ onAddFilter: edit.requestFilters,
+ }
+ : {})}
/>
+ {editing && (
+
}
+ selection={edit.selection}
+ onPatch={edit.patch}
+ onSelectionChange={edit.select}
+ revealFilters={edit.revealFilters}
+ onFiltersRevealed={edit.filtersRevealed}
+ />
+ )}
+
{
+ const listed = (entries: Record) =>
+ new Map(
+ Object.entries(entries).map(([id, e]) => [id, { writable: e.writable, manifest: { id, version: e.version } } as any]),
+ );
+ const doors = (
+ entries: Record,
+ ensure: DashboardSaveTargetDoors['ensureCustomization'] = vi.fn(async (base: string) => ({ packageId: `${base}.custom`, writable: true })),
+ ): DashboardSaveTargetDoors => ({ listPackages: vi.fn(async () => listed(entries)), ensureCustomization: ensure });
+
+ it('a dashboard of a writable package saves into that package, asking no pair', async () => {
+ const d = doors({ crm: { writable: true } });
+ await expect(resolveDashboardSaveTarget('crm', d)).resolves.toEqual({ kind: 'package', packageId: 'crm' });
+ expect(d.ensureCustomization).not.toHaveBeenCalled();
+ });
+
+ it('a dashboard of a read-only (installed) package saves into its customization pair, based on the listed version', async () => {
+ const d = doors({ crm: { writable: false, version: '2.1.0' } });
+ await expect(resolveDashboardSaveTarget('crm', d)).resolves.toEqual({
+ kind: 'customization',
+ packageId: 'crm.custom',
+ base: 'crm',
+ basedOn: '2.1.0',
+ });
+ expect(d.ensureCustomization).toHaveBeenCalledWith('crm');
+ });
+
+ it('is refused when the owner is not listed, the ensure door refuses, or the pair is not writable', async () => {
+ await expect(resolveDashboardSaveTarget('crm', doors({}))).resolves.toMatchObject({ kind: 'refused' });
+ const refusing = vi.fn(async () => {
+ throw new Error('forbidden');
+ });
+ await expect(resolveDashboardSaveTarget('crm', doors({ crm: { writable: false } }, refusing))).resolves.toEqual({
+ kind: 'refused',
+ reason: 'forbidden',
+ });
+ const readOnlyPair = vi.fn(async () => ({ packageId: 'crm.custom', writable: false }));
+ await expect(resolveDashboardSaveTarget('crm', doors({ crm: { writable: false } }, readOnlyPair))).resolves.toMatchObject({
+ kind: 'refused',
+ });
+ });
+
+ it('a dashboard naming no package is saved where it lives', async () => {
+ await expect(resolveDashboardSaveTarget(null, doors({}))).resolves.toEqual({ kind: 'unbound' });
+ });
+
+ it('the body drops the read\'s `_` keys, and into a pair declares the override of its base', () => {
+ const doc = { name: 'exec', label: 'Exec', widgets: [], _packageId: 'crm', _diagnostics: [] };
+ expect(dashboardSaveBody(doc, { kind: 'package', packageId: 'crm' })).toEqual({ name: 'exec', label: 'Exec', widgets: [] });
+ expect(dashboardSaveBody(doc, { kind: 'customization', packageId: 'crm.custom', base: 'crm', basedOn: '2.1.0' })).toEqual({
+ name: 'exec',
+ label: 'Exec',
+ widgets: [],
+ overrides: { package: 'crm', basedOn: '2.1.0' },
+ });
+ // No version to declare the override at, and none declared: nothing is guessed.
+ expect(dashboardSaveBody(doc, { kind: 'customization', packageId: 'crm.custom', base: 'crm', basedOn: null })).toBeNull();
+ });
+
+ it('stages and publishes the one item in the target package', async () => {
+ const metadataClient = makeMetadataClient();
+ const body = { name: 'exec', widgets: [] };
+ await expect(
+ saveDashboardInPlace('exec', body, { kind: 'customization', packageId: 'crm.custom', base: 'crm', basedOn: '2.1.0' }, { metadataClient }),
+ ).resolves.toBe('published');
+ expect(metadataClient.save).toHaveBeenCalledWith('dashboard', 'exec', body, { mode: 'draft', ifNoneMatch: '*', packageId: 'crm.custom' });
+ expect(metadataClient.publish).toHaveBeenCalledWith('dashboard', 'exec', { packageId: 'crm.custom' });
+ });
+
+ it('over a pending Studio draft nothing is published', async () => {
+ const metadataClient = makeMetadataClient();
+ metadataClient.save.mockRejectedValue(Object.assign(new Error('pending'), { status: 409, code: 'METADATA_CONFLICT' }));
+ await expect(
+ saveDashboardInPlace('exec', {}, { kind: 'package', packageId: 'crm' }, { metadataClient }),
+ ).resolves.toBe('pending-draft');
+ expect(metadataClient.publish).not.toHaveBeenCalled();
+ });
+
+ it('a refused publish discards its own draft in the same package', async () => {
+ const metadataClient = makeMetadataClient();
+ const refused = Object.assign(new Error('refused'), { status: 400 });
+ metadataClient.publish.mockRejectedValue(refused);
+ await expect(saveDashboardInPlace('exec', {}, { kind: 'package', packageId: 'crm' }, { metadataClient })).rejects.toBe(refused);
+ expect(metadataClient.reset).toHaveBeenCalledWith('dashboard', 'exec', { state: 'draft', packageId: 'crm' });
+ });
+});
diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
index b61a26a2c44..ed5032719f1 100644
--- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
+++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
@@ -42,7 +42,13 @@ import { stripReadDecorations } from '@objectstack/spec/kernel';
import { emitMetadataRefresh } from '../assistant/assistantBus.js';
import { slugify } from './metadata-admin/createDerive.js';
import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js';
-import { ensureCustomizationPackage, fetchListedPackageManifests } from './studio-design/packages-io.js';
+import {
+ ensureCustomizationPackage,
+ fetchListedPackageManifests,
+ listedPackageVersion,
+ type ListedPackageManifest,
+} from './studio-design/packages-io.js';
+import { overrideDraftBody } from './studio-design/StudioCustomizeControls.js';
/** The runtime-editable artifact types ADR-0034 unifies. `page` (a record
* `PageSchema`) joins the original three (#1541): a record page is edited in
@@ -536,9 +542,16 @@ export async function saveAndPublishRuntimeMetadata(
name: string,
body: any,
ctx: RuntimePersistCtx,
+ /**
+ * objectstack#36372 — the package the draft is written into and published
+ * from (`?package=` on all three writes). Omitted, every write names no
+ * package and addresses the name's one holding package, as before.
+ */
+ options: { packageId?: string } = {},
): Promise {
+ const bound = options.packageId ? { packageId: options.packageId } : {};
try {
- await ctx.metadataClient.save(type, name, body, { mode: 'draft', ifNoneMatch: '*' });
+ await ctx.metadataClient.save(type, name, body, { mode: 'draft', ifNoneMatch: '*', ...bound });
} catch (err) {
if (isDraftVersionConflict(err)) {
return 'pending-draft';
@@ -546,10 +559,12 @@ export async function saveAndPublishRuntimeMetadata(
throw err;
}
try {
- await ctx.metadataClient.publish(type, name);
+ await (options.packageId
+ ? ctx.metadataClient.publish(type, name, bound)
+ : ctx.metadataClient.publish(type, name));
} catch (err) {
try {
- await ctx.metadataClient.reset(type, name, { state: 'draft' });
+ await ctx.metadataClient.reset(type, name, { state: 'draft', ...bound });
} catch (discardErr) {
// The draft this call wrote stays pending: the view settings' draft
// bar shows it, and its Discard removes it.
@@ -563,3 +578,103 @@ export async function saveAndPublishRuntimeMetadata(
announceDraftLedgerWrite();
return 'published';
}
+
+/**
+ * objectstack#36372 — where a dashboard edited on its own page is saved: the
+ * package that owns it when that package is writable, else the app's
+ * customization package ` .custom` (ADR-0146 D2/D3), asked of the ensure
+ * door, the layer Studio's Customize writes. `refused` when neither can be
+ * had (the owner is not listed, the ensure door refuses, or the pair it
+ * answers is not writable): the editor then offers no save.
+ *
+ * `unbound` is a dashboard that names no package: it is saved where it lives,
+ * naming none.
+ */
+export type DashboardSaveTarget =
+ | { kind: 'unbound' }
+ | { kind: 'package'; packageId: string }
+ | { kind: 'customization'; packageId: string; base: string; basedOn: string | null }
+ | { kind: 'refused'; reason: string };
+
+/** The two package doors {@link resolveDashboardSaveTarget} asks. */
+export interface DashboardSaveTargetDoors {
+ listPackages: () => Promise>>;
+ ensureCustomization: (basePackageId: string) => Promise<{ packageId: string; writable: boolean }>;
+}
+
+const DASHBOARD_TARGET_DOORS: DashboardSaveTargetDoors = {
+ listPackages: fetchListedPackageManifests,
+ ensureCustomization: ensureCustomizationPackage,
+};
+
+/** {@link DashboardSaveTarget} for a dashboard `ownerPackageId` owns. */
+export async function resolveDashboardSaveTarget(
+ ownerPackageId: string | null | undefined,
+ doors: DashboardSaveTargetDoors = DASHBOARD_TARGET_DOORS,
+): Promise {
+ if (!ownerPackageId) return { kind: 'unbound' };
+ let listed: ReadonlyMap>;
+ try {
+ listed = await doors.listPackages();
+ } catch (err) {
+ return { kind: 'refused', reason: err instanceof Error ? err.message : String(err) };
+ }
+ const owner = listed.get(ownerPackageId);
+ if (!owner) return { kind: 'refused', reason: `The package '${ownerPackageId}' is not listed.` };
+ if (owner.writable) return { kind: 'package', packageId: ownerPackageId };
+ try {
+ const pair = await doors.ensureCustomization(ownerPackageId);
+ if (!pair.writable) return { kind: 'refused', reason: `The customization package '${pair.packageId}' is not writable.` };
+ return {
+ kind: 'customization',
+ packageId: pair.packageId,
+ base: ownerPackageId,
+ basedOn: listedPackageVersion(listed as ReadonlyMap, ownerPackageId),
+ };
+ } catch (err) {
+ return { kind: 'refused', reason: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/**
+ * The body an in-page dashboard save writes: `doc` without its top-level `_`
+ * keys (the read's decorations belong to the served item), and, into a
+ * customization package, declaring the override of its base
+ * (`overrideDraftBody`, the body Studio's Customize writes). `null` when an
+ * override is owed and there is no version to declare it at.
+ */
+export function dashboardSaveBody(
+ doc: Record,
+ target: Exclude,
+): Record | null {
+ if (target.kind === 'customization') return overrideDraftBody(doc, target.base, target.basedOn);
+ const body: Record = {};
+ for (const [key, value] of Object.entries(doc)) {
+ if (!key.startsWith('_')) body[key] = value;
+ }
+ return body;
+}
+
+/**
+ * objectstack#36372 — save a dashboard edited on its page so everyone sees it
+ * at once: staged as its draft in `target`'s package and published from it in
+ * the same act ({@link saveAndPublishRuntimeMetadata}, the confirmed-save door
+ * of ruling record 7058616478). One item's publish: no package-wide
+ * publish-drafts. Over a draft already pending there nothing is written
+ * (`'pending-draft'`), so a Studio draft is never published on its saver's
+ * behalf.
+ */
+export async function saveDashboardInPlace(
+ name: string,
+ body: Record,
+ target: Exclude,
+ ctx: RuntimePersistCtx,
+): Promise {
+ return saveAndPublishRuntimeMetadata(
+ 'dashboard',
+ name,
+ body,
+ ctx,
+ target.kind === 'unbound' ? {} : { packageId: target.packageId },
+ );
+}
diff --git a/ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts b/ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts
index c4ac1633ea6..26bf2effce1 100644
--- a/ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts
+++ b/ui/packages/core/src/utils/__tests__/dashboard-filters.test.ts
@@ -865,9 +865,9 @@ describe('dashboardFiltersNotApplied agrees with buildWidgetScopedFilter', () =>
const ownerDef: DashboardFilterDef = { name: 'owner', field: 'owner', type: 'text' };
const stageDef: DashboardFilterDef = { name: 'stage', field: 'stage', type: 'text', targetWidgets: ['w_listed'] };
const defs = [ownerDef, stageDef];
- const widgets = [
+ const widgets: Array[0]> = [
{ id: 'w_default' },
- { id: 'w_opt_out', filterBindings: { owner: false as const } },
+ { id: 'w_opt_out', filterBindings: { owner: false } },
{ id: 'w_rebound', filterBindings: { owner: 'account_owner' } },
{ id: 'w_listed' },
{ id: 'w_explicit_over_list', filterBindings: { stage: 'pipeline_stage' } },
diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts
index 960bb5b64d4..f707ea6d9c5 100644
--- a/ui/packages/i18n/src/locales/ar.ts
+++ b/ui/packages/i18n/src/locales/ar.ts
@@ -1951,6 +1951,24 @@ const ar = {
allWidgetsForbiddenMessage: "ليست لديك صلاحية لعرض البيانات الخاصة بلوحة التحكم هذه.",
details: "التفاصيل",
openInList: "فتح في القائمة",
+ inPageEdit: {
+ edit: "تحرير",
+ editLabel: "تحرير لوحة القيادة هذه",
+ editing: "قيد التحرير",
+ hint: "تسري التغييرات المحفوظة على الجميع فورًا",
+ addCard: "إضافة بطاقة",
+ discard: "تجاهل",
+ save: "حفظ",
+ saving: "جارٍ الحفظ…",
+ saved: "تم حفظ لوحة القيادة",
+ saveFailed: "تعذّر حفظ لوحة القيادة",
+ loading: "جارٍ فتح لوحة القيادة للتحرير…",
+ loadFailed: "تعذّر فتح لوحة القيادة للتحرير",
+ pendingDraft: "لهذه اللوحة تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم حرّرها هنا.",
+ noPackage: "لا يمكن حفظ لوحة القيادة هذه هنا: لا يملك تطبيقها حزمة يمكن لهذا الحساب تخصيصها.",
+ resizeCard: "تغيير حجم البطاقة",
+ panelTitle: "الخصائص",
+ },
filters: {
label: "عوامل تصفية لوحة المعلومات",
dateRange: "النطاق الزمني",
@@ -1958,6 +1976,8 @@ const ar = {
custom: "مخصص…",
all: "الكل",
reset: "إعادة تعيين",
+ notApplied: "غير مُصفّى حسب {{filters}}",
+ addFilter: "إضافة عامل تصفية",
range: {
today: "اليوم",
yesterday: "أمس",
diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts
index 705e38b763d..e0baf1945fe 100644
--- a/ui/packages/i18n/src/locales/de.ts
+++ b/ui/packages/i18n/src/locales/de.ts
@@ -1719,6 +1719,24 @@ const de = {
allWidgetsForbiddenMessage: "Sie haben keine Berechtigung, die Daten dieses Dashboards anzuzeigen.",
details: "Details",
openInList: "In Liste öffnen",
+ inPageEdit: {
+ edit: "Bearbeiten",
+ editLabel: "Dieses Dashboard bearbeiten",
+ editing: "Wird bearbeitet",
+ hint: "Gespeicherte Änderungen gelten sofort für alle",
+ addCard: "Karte hinzufügen",
+ discard: "Verwerfen",
+ save: "Speichern",
+ saving: "Wird gespeichert…",
+ saved: "Dashboard gespeichert",
+ saveFailed: "Das Dashboard konnte nicht gespeichert werden",
+ loading: "Dashboard wird zum Bearbeiten geöffnet…",
+ loadFailed: "Das Dashboard konnte nicht zum Bearbeiten geöffnet werden",
+ pendingDraft: "Dieses Dashboard hat unveröffentlichte Änderungen in Studio. Veröffentlichen oder verwerfen Sie sie dort und bearbeiten Sie es dann hier.",
+ noPackage: "Dieses Dashboard kann hier nicht gespeichert werden: Seine App hat kein Paket, das dieses Konto anpassen kann.",
+ resizeCard: "Kartengröße ändern",
+ panelTitle: "Eigenschaften",
+ },
filters: {
label: "Dashboard-Filter",
dateRange: "Zeitraum",
@@ -1726,6 +1744,8 @@ const de = {
custom: "Benutzerdefiniert…",
all: "Alle",
reset: "Zurücksetzen",
+ notApplied: "Nicht gefiltert nach {{filters}}",
+ addFilter: "Filter hinzufügen",
range: {
today: "Heute",
yesterday: "Gestern",
diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts
index 8a43689a990..a8c7da5de2c 100644
--- a/ui/packages/i18n/src/locales/en.ts
+++ b/ui/packages/i18n/src/locales/en.ts
@@ -2255,6 +2255,24 @@ const en = {
vsThisMonth: 'vs this month',
vsThisQuarter: 'vs this quarter',
},
+ inPageEdit: {
+ edit: 'Edit',
+ editLabel: 'Edit this dashboard',
+ editing: 'Editing',
+ hint: 'Saved changes apply to everyone at once',
+ addCard: 'Add card',
+ discard: 'Discard',
+ save: 'Save',
+ saving: 'Saving…',
+ saved: 'Dashboard saved',
+ saveFailed: 'The dashboard could not be saved',
+ loading: 'Opening the dashboard for editing…',
+ loadFailed: 'The dashboard could not be opened for editing',
+ pendingDraft: 'This dashboard has unpublished changes in Studio. Publish or discard them there, then edit it here.',
+ noPackage: 'This dashboard cannot be saved here: its app has no package this account can customize.',
+ resizeCard: 'Resize card',
+ panelTitle: 'Properties',
+ },
filters: {
label: 'Dashboard filters',
dateRange: 'Date range',
@@ -2262,6 +2280,8 @@ const en = {
custom: 'Custom…',
all: 'All',
reset: 'Reset',
+ notApplied: 'Not filtered by {{filters}}',
+ addFilter: 'Add filter',
range: {
today: 'Today',
yesterday: 'Yesterday',
diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts
index f24e9816f31..7d5170f10b7 100644
--- a/ui/packages/i18n/src/locales/es.ts
+++ b/ui/packages/i18n/src/locales/es.ts
@@ -1779,6 +1779,24 @@ const es = {
allWidgetsForbiddenMessage: "No tienes permiso para ver los datos de este panel.",
details: "Detalles",
openInList: "Abrir en la lista",
+ inPageEdit: {
+ edit: "Editar",
+ editLabel: "Editar este panel de control",
+ editing: "Editando",
+ hint: "Los cambios guardados se aplican a todos al instante",
+ addCard: "Añadir tarjeta",
+ discard: "Descartar",
+ save: "Guardar",
+ saving: "Guardando…",
+ saved: "Panel de control guardado",
+ saveFailed: "No se pudo guardar el panel de control",
+ loading: "Abriendo el panel de control para editarlo…",
+ loadFailed: "No se pudo abrir el panel de control para editarlo",
+ pendingDraft: "Este panel de control tiene cambios sin publicar en Studio. Publícalos o descártalos allí y luego edítalo aquí.",
+ noPackage: "Este panel de control no se puede guardar aquí: su aplicación no tiene un paquete que esta cuenta pueda personalizar.",
+ resizeCard: "Cambiar el tamaño de la tarjeta",
+ panelTitle: "Propiedades",
+ },
filters: {
label: "Filtros del panel",
dateRange: "Intervalo de fechas",
@@ -1786,6 +1804,8 @@ const es = {
custom: "Personalizado…",
all: "Todo",
reset: "Restablecer",
+ notApplied: "Sin filtrar por {{filters}}",
+ addFilter: "Añadir filtro",
range: {
today: "Hoy",
yesterday: "Ayer",
diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts
index 868c80eb488..faa3ce18b1a 100644
--- a/ui/packages/i18n/src/locales/fr.ts
+++ b/ui/packages/i18n/src/locales/fr.ts
@@ -1775,6 +1775,24 @@ const fr = {
allWidgetsForbiddenMessage: "Vous n’avez pas l’autorisation de voir les données de ce tableau de bord.",
details: "Détails",
openInList: "Ouvrir dans la liste",
+ inPageEdit: {
+ edit: "Modifier",
+ editLabel: "Modifier ce tableau de bord",
+ editing: "Modification en cours",
+ hint: "Les modifications enregistrées s’appliquent immédiatement à tous",
+ addCard: "Ajouter une carte",
+ discard: "Abandonner",
+ save: "Enregistrer",
+ saving: "Enregistrement…",
+ saved: "Tableau de bord enregistré",
+ saveFailed: "Le tableau de bord n’a pas pu être enregistré",
+ loading: "Ouverture du tableau de bord pour modification…",
+ loadFailed: "Le tableau de bord n’a pas pu être ouvert pour modification",
+ pendingDraft: "Ce tableau de bord a des modifications non publiées dans Studio. Publiez-les ou abandonnez-les là-bas, puis modifiez-le ici.",
+ noPackage: "Ce tableau de bord ne peut pas être enregistré ici : son application n’a aucun paquet que ce compte peut personnaliser.",
+ resizeCard: "Redimensionner la carte",
+ panelTitle: "Propriétés",
+ },
filters: {
label: "Filtres du tableau de bord",
dateRange: "Plage de dates",
@@ -1782,6 +1800,8 @@ const fr = {
custom: "Personnalisé…",
all: "Tout",
reset: "Réinitialiser",
+ notApplied: "Non filtré par {{filters}}",
+ addFilter: "Ajouter un filtre",
range: {
today: "Aujourd'hui",
yesterday: "Hier",
diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts
index f5fefa091a6..51084bc5a32 100644
--- a/ui/packages/i18n/src/locales/ja.ts
+++ b/ui/packages/i18n/src/locales/ja.ts
@@ -1719,6 +1719,24 @@ const ja = {
allWidgetsForbiddenMessage: "このダッシュボードのデータを表示する権限がありません。",
details: "詳細",
openInList: "リストで開く",
+ inPageEdit: {
+ edit: "編集",
+ editLabel: "このダッシュボードを編集",
+ editing: "編集中",
+ hint: "保存した変更はすぐに全員に反映されます",
+ addCard: "カードを追加",
+ discard: "破棄",
+ save: "保存",
+ saving: "保存中…",
+ saved: "ダッシュボードを保存しました",
+ saveFailed: "ダッシュボードを保存できませんでした",
+ loading: "ダッシュボードを編集用に開いています…",
+ loadFailed: "ダッシュボードを編集用に開けませんでした",
+ pendingDraft: "このダッシュボードには Studio に未公開の変更があります。そちらで公開または破棄してから、ここで編集してください。",
+ noPackage: "このダッシュボードはここでは保存できません。このアカウントがカスタマイズできるパッケージがアプリにありません。",
+ resizeCard: "カードのサイズを変更",
+ panelTitle: "プロパティ",
+ },
filters: {
label: "ダッシュボードのフィルター",
dateRange: "期間",
@@ -1726,6 +1744,8 @@ const ja = {
custom: "カスタム…",
all: "すべて",
reset: "リセット",
+ notApplied: "{{filters}} の絞り込み対象外",
+ addFilter: "フィルターを追加",
range: {
today: "今日",
yesterday: "昨日",
diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts
index 5d3500174de..4943d1a373f 100644
--- a/ui/packages/i18n/src/locales/ko.ts
+++ b/ui/packages/i18n/src/locales/ko.ts
@@ -1719,6 +1719,24 @@ const ko = {
allWidgetsForbiddenMessage: "이 대시보드의 데이터를 볼 수 있는 권한이 없습니다.",
details: "세부 정보",
openInList: "목록에서 열기",
+ inPageEdit: {
+ edit: "편집",
+ editLabel: "이 대시보드 편집",
+ editing: "편집 중",
+ hint: "저장한 변경 사항은 모든 사용자에게 즉시 적용됩니다",
+ addCard: "카드 추가",
+ discard: "취소",
+ save: "저장",
+ saving: "저장 중…",
+ saved: "대시보드를 저장했습니다",
+ saveFailed: "대시보드를 저장할 수 없습니다",
+ loading: "편집할 대시보드를 여는 중…",
+ loadFailed: "편집할 대시보드를 열 수 없습니다",
+ pendingDraft: "이 대시보드에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 여기서 편집하세요.",
+ noPackage: "이 대시보드는 여기서 저장할 수 없습니다. 앱에 이 계정이 사용자 지정할 수 있는 패키지가 없습니다.",
+ resizeCard: "카드 크기 조정",
+ panelTitle: "속성",
+ },
filters: {
label: "대시보드 필터",
dateRange: "기간",
@@ -1726,6 +1744,8 @@ const ko = {
custom: "사용자 지정…",
all: "전체",
reset: "초기화",
+ notApplied: "{{filters}} 필터 미적용",
+ addFilter: "필터 추가",
range: {
today: "오늘",
yesterday: "어제",
diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts
index 53dc0b099f4..65ea1060f35 100644
--- a/ui/packages/i18n/src/locales/pt-BR.ts
+++ b/ui/packages/i18n/src/locales/pt-BR.ts
@@ -1774,6 +1774,24 @@ const pt = {
allWidgetsForbiddenMessage: "Você não tem permissão para ver os dados deste painel.",
details: "Detalhes",
openInList: "Abrir na lista",
+ inPageEdit: {
+ edit: "Editar",
+ editLabel: "Editar este painel",
+ editing: "Editando",
+ hint: "As alterações salvas valem para todos na hora",
+ addCard: "Adicionar cartão",
+ discard: "Descartar",
+ save: "Salvar",
+ saving: "Salvando…",
+ saved: "Painel salvo",
+ saveFailed: "Não foi possível salvar o painel",
+ loading: "Abrindo o painel para edição…",
+ loadFailed: "Não foi possível abrir o painel para edição",
+ pendingDraft: "Este painel tem alterações não publicadas no Studio. Publique ou descarte-as lá e depois edite-o aqui.",
+ noPackage: "Este painel não pode ser salvo aqui: o aplicativo dele não tem um pacote que esta conta possa personalizar.",
+ resizeCard: "Redimensionar cartão",
+ panelTitle: "Propriedades",
+ },
filters: {
label: "Filtros do painel",
dateRange: "Período",
@@ -1781,6 +1799,8 @@ const pt = {
custom: "Personalizado…",
all: "Tudo",
reset: "Redefinir",
+ notApplied: "Não filtrado por {{filters}}",
+ addFilter: "Adicionar filtro",
range: {
today: "Hoje",
yesterday: "Ontem",
diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts
index 8f782fc7386..56c38ff90c7 100644
--- a/ui/packages/i18n/src/locales/ru.ts
+++ b/ui/packages/i18n/src/locales/ru.ts
@@ -1839,6 +1839,24 @@ const ru = {
allWidgetsForbiddenMessage: "У вас нет прав на просмотр данных этой панели.",
details: "Подробности",
openInList: "Открыть в списке",
+ inPageEdit: {
+ edit: "Изменить",
+ editLabel: "Изменить этот дашборд",
+ editing: "Редактирование",
+ hint: "Сохранённые изменения сразу видят все",
+ addCard: "Добавить карточку",
+ discard: "Отменить",
+ save: "Сохранить",
+ saving: "Сохранение…",
+ saved: "Дашборд сохранён",
+ saveFailed: "Не удалось сохранить дашборд",
+ loading: "Дашборд открывается для редактирования…",
+ loadFailed: "Не удалось открыть дашборд для редактирования",
+ pendingDraft: "В Studio есть неопубликованные изменения этого дашборда. Опубликуйте или отмените их там, затем редактируйте здесь.",
+ noPackage: "Этот дашборд нельзя сохранить здесь: у его приложения нет пакета, который эта учётная запись может настроить.",
+ resizeCard: "Изменить размер карточки",
+ panelTitle: "Свойства",
+ },
filters: {
label: "Фильтры дашборда",
dateRange: "Период",
@@ -1846,6 +1864,8 @@ const ru = {
custom: "Произвольный…",
all: "Все",
reset: "Сбросить",
+ notApplied: "Не фильтруется по: {{filters}}",
+ addFilter: "Добавить фильтр",
range: {
today: "Сегодня",
yesterday: "Вчера",
diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts
index 677386b0bbd..3a2363477b4 100644
--- a/ui/packages/i18n/src/locales/zh-Hans.ts
+++ b/ui/packages/i18n/src/locales/zh-Hans.ts
@@ -1900,6 +1900,24 @@ const zh = {
vsThisMonth: '较本月',
vsThisQuarter: '较本季度',
},
+ inPageEdit: {
+ edit: '编辑',
+ editLabel: '编辑这个仪表盘',
+ editing: '编辑中',
+ hint: '保存后所有人立刻看到',
+ addCard: '添加卡片',
+ discard: '放弃',
+ save: '保存',
+ saving: '保存中…',
+ saved: '仪表盘已保存',
+ saveFailed: '仪表盘没有保存成功',
+ loading: '正在打开仪表盘以便编辑…',
+ loadFailed: '无法打开仪表盘进行编辑',
+ pendingDraft: '这个仪表盘在 Studio 里有未发布的改动。请先在那里发布或放弃,再在这里编辑。',
+ noPackage: '这个仪表盘不能在这里保存:它所在的应用没有这个账号能定制的软件包。',
+ resizeCard: '调整卡片大小',
+ panelTitle: '属性',
+ },
filters: {
label: '仪表盘过滤器',
dateRange: '日期范围',
@@ -1907,6 +1925,8 @@ const zh = {
custom: '自定义…',
all: '全部',
reset: '重置',
+ notApplied: '不跟随「{{filters}}」筛选',
+ addFilter: '添加筛选',
range: {
today: '今天',
yesterday: '昨天',
diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts
index 9e423c7f593..84516f779cd 100644
--- a/ui/packages/i18n/src/locales/zh-Hant.ts
+++ b/ui/packages/i18n/src/locales/zh-Hant.ts
@@ -1900,6 +1900,24 @@ const zhHant = {
vsThisMonth: '較本月',
vsThisQuarter: '較本季度',
},
+ inPageEdit: {
+ edit: '編輯',
+ editLabel: '編輯這個儀表盤',
+ editing: '編輯中',
+ hint: '儲存後所有人立刻看到',
+ addCard: '新增卡片',
+ discard: '放棄',
+ save: '儲存',
+ saving: '儲存中…',
+ saved: '儀表盤已儲存',
+ saveFailed: '儀表盤沒有儲存成功',
+ loading: '正在開啟儀表盤以便編輯…',
+ loadFailed: '無法開啟儀表盤進行編輯',
+ pendingDraft: '這個儀表盤在 Studio 裡有未釋出的改動。請先在那裡釋出或放棄,再在這裡編輯。',
+ noPackage: '這個儀表盤不能在這裡儲存:它所在的應用沒有這個賬號能定製的軟體包。',
+ resizeCard: '調整卡片大小',
+ panelTitle: '屬性',
+ },
filters: {
label: '儀表盤過濾器',
dateRange: '日期範圍',
@@ -1907,6 +1925,8 @@ const zhHant = {
custom: '自定義…',
all: '全部',
reset: '重置',
+ notApplied: '不跟隨「{{filters}}」篩選',
+ addFilter: '新增篩選',
range: {
today: '今天',
yesterday: '昨天',
diff --git a/ui/packages/plugin-dashboard/README.md b/ui/packages/plugin-dashboard/README.md
index 2967d256b45..a3f8590518d 100644
--- a/ui/packages/plugin-dashboard/README.md
+++ b/ui/packages/plugin-dashboard/README.md
@@ -513,6 +513,35 @@ Notes:
warning instead of emitting a query that matches nothing. Explicit
`filterBindings` strings are always honoured as written.
+## Filters a widget does not follow
+
+Every widget, in every mode, carries a small mark naming the dashboard
+filters that do not reach it, for example "Not filtered by Region": a filter
+it opts out of (`filterBindings[name]: false`) or one whose `targetWidgets`
+leaves it out. A widget every filter reaches carries none. The list is
+`dashboardFiltersNotApplied(widget, defs)` from `@object-ui/core`, which asks
+`resolveBoundField`, the binding the widget's query is built from, so the
+mark and the data cannot disagree.
+
+## Design mode: resizing and "Add filter"
+
+In `designMode` two more affordances are drawn when the host hands their
+handler:
+
+- `onWidgetResize(widgetId, { w, h })`: a corner handle on each widget
+ resizes it by whole grid tracks (it snaps as the pointer crosses half a
+ track; the arrow keys on the handle grow or shrink it by one). Width stays
+ within the grid's columns. The host writes the span into the widget's
+ `layout`. Not drawn below the phone breakpoint.
+- `onAddFilter()`: an "Add filter" button at the end of the filter bar, which
+ is drawn for it even before any filter is declared.
+
+The console's dashboard page uses both in its in-page edit state: an admin
+who may design the dashboard's package opens it with **Edit**, changes it with
+Studio's own dashboard panels at the right, and **Save** publishes that one
+dashboard (into the package, or into the app's customization package for an
+installed app), so everyone sees it at once.
+
## Widget accent colour (`colorVariant`)
A KPI widget can declare a semantic accent. The vocabulary is
diff --git a/ui/packages/plugin-dashboard/src/DashboardFilterBar.tsx b/ui/packages/plugin-dashboard/src/DashboardFilterBar.tsx
index d4df6a6c338..813140de25a 100644
--- a/ui/packages/plugin-dashboard/src/DashboardFilterBar.tsx
+++ b/ui/packages/plugin-dashboard/src/DashboardFilterBar.tsx
@@ -32,7 +32,7 @@ import {
SelectValue,
useIsMobile,
} from '@object-ui/components';
-import { CalendarIcon, RotateCcw } from 'lucide-react';
+import { CalendarIcon, Plus, RotateCcw } from 'lucide-react';
import { useSafeTranslate, useObjectTranslation, useSafeFieldLabel, pickLocalized } from '@object-ui/i18n';
import { useDataInvalidation } from '@object-ui/react';
import { DatasetQueryCoalescerContext } from './datasetQueryBatch';
@@ -91,10 +91,22 @@ import {
* unchanged.
*/
function useFilterLabel(def: DashboardFilterDef): string {
+ return useDashboardFilterLabeler()(def);
+}
+
+/**
+ * The rule {@link useFilterLabel} applies, as a function of the filter, for a
+ * caller that labels several filters in one render (a card's not-applied
+ * mark names every filter that does not reach it, objectstack#36372). One
+ * rule: the bar and the mark name a filter alike.
+ */
+export function useDashboardFilterLabeler(): (def: DashboardFilterDef) => string {
const { language } = useObjectTranslation();
const { fieldLabel } = useSafeFieldLabel();
- const authored = pickLocalized(def.label, language);
- return def.object ? fieldLabel(def.object, def.field, authored) : authored;
+ return (def) => {
+ const authored = pickLocalized(def.label, language);
+ return def.object ? fieldLabel(def.object, def.field, authored) : authored;
+ };
}
/** Sentinel for the Select's clear item (Radix Select forbids empty values). */
@@ -116,6 +128,12 @@ export interface DashboardFilterBarProps {
onReset?: () => void;
dataSource?: any;
className?: string;
+ /**
+ * objectstack#36372 — the in-page editor's "Add filter": drawn at the end
+ * of the bar, and the bar is drawn for it even when the dashboard declares
+ * no filter yet. Absent, the bar is what it was.
+ */
+ onAddFilter?: () => void;
}
/** Format an ISO date (or macro token) for the trigger label. */
@@ -583,9 +601,9 @@ function TextFilter({ def, value, onChange }: { def: DashboardFilterDef; value:
);
}
-export function DashboardFilterBar({ defs, values, onChange, onReset, dataSource, className }: DashboardFilterBarProps) {
+export function DashboardFilterBar({ defs, values, onChange, onReset, dataSource, className, onAddFilter }: DashboardFilterBarProps) {
const tt = useSafeTranslate();
- if (defs.length === 0) return null;
+ if (defs.length === 0 && !onAddFilter) return null;
// The variables provider initializes undefined defaults to '' / {} by
// type — normalize those to "empty" so a pristine bar shows no Reset.
@@ -622,6 +640,18 @@ export function DashboardFilterBar({ defs, values, onChange, onReset, dataSource
{tt('dashboard.filters.reset', 'Reset')}
)}
+ {onAddFilter && (
+
+
+ {tt('dashboard.filters.addFilter', 'Add filter')}
+
+ )}
);
}
diff --git a/ui/packages/plugin-dashboard/src/DashboardRenderer.tsx b/ui/packages/plugin-dashboard/src/DashboardRenderer.tsx
index f55f05727ef..1c9a1545058 100644
--- a/ui/packages/plugin-dashboard/src/DashboardRenderer.tsx
+++ b/ui/packages/plugin-dashboard/src/DashboardRenderer.tsx
@@ -16,6 +16,7 @@ import {
dashboardFilterVariableDefs,
buildWidgetScopedFilter,
boundMemberFilterNames,
+ dashboardFiltersNotApplied,
mergeFilters,
toDomProps,
chartCategoryKey,
@@ -49,6 +50,7 @@ import { DatasetWidget } from './DatasetWidget';
import type { DashboardChartRenderSchema } from './chartRenderHandoff';
import { useDashboardAutoRefresh, type DashboardAutoRefresh } from './useDashboardAutoRefresh';
import { DashboardFilterBar } from './DashboardFilterBar';
+import { WidgetFilterMark, WidgetResizeHandle } from './designAffordances';
import { DatasetQueryCoalescerContext, useDatasetQueryCoalescer } from './datasetQueryBatch';
import { filterFieldSource, jsonColumnOperatorsFor, useFilterFieldFacts, warnFilterLoweredWithoutFacts, type FilterFieldSource } from './filterFieldFacts';
@@ -282,6 +284,18 @@ export interface DashboardRendererProps
* while the component arm was assignable to the widget arm).
*/
onWidgetsReorder?: (widgets: DashboardComponentSchema['widgets']) => void;
+ /**
+ * objectstack#36372 — a widget's corner handle was dragged (or arrowed) to
+ * a new span, in whole grid tracks. Drawn in design mode only, on a widget
+ * with an `id`, and only when this is set; the host writes the span into
+ * the widget's `layout`.
+ */
+ onWidgetResize?: (widgetId: string, span: { w: number; h: number }) => void;
+ /**
+ * objectstack#36372 — design mode's "Add filter", drawn at the end of the
+ * filter bar (and the bar drawn for it when no filter is declared yet).
+ */
+ onAddFilter?: () => void;
/** Optional handler for actionType="modal" header actions. Receives a schema and ActionContext. */
modalHandler?: ModalHandler;
/** Optional named handlers for actionType="script" header actions, keyed by action name (actionUrl). */
@@ -344,7 +358,7 @@ export interface DashboardRendererProps
}
const DashboardRendererInner = forwardRef
(
- ({ schema, className, dataSource: dataSourceProp, onRefresh, recordCount, userActions, designMode, selectedWidgetId, onWidgetClick, onWidgetsReorder, modalHandler, scriptHandlers, hideHeaderText, onRefreshStateChange, localized, ...props }: DashboardRendererProps & { [key: string]: any }, ref) => {
+ ({ schema, className, dataSource: dataSourceProp, onRefresh, recordCount, userActions, designMode, selectedWidgetId, onWidgetClick, onWidgetsReorder, onWidgetResize, onAddFilter, modalHandler, scriptHandlers, hideHeaderText, onRefreshStateChange, localized, ...props }: DashboardRendererProps & { [key: string]: any }, ref) => {
// The package this dashboard is served from: its widgets' datasets were
// authored against it, so each dataset query names it as the reader's
// package (`callerPackage`, ADR-0150 D3).
@@ -1149,6 +1163,21 @@ const DashboardRendererInner = forwardRef 0 ? dashboardFiltersNotApplied(widgetArm, filterDefs) : [];
+ const filterMark = filtersNotApplied.length > 0
+ ?
+ : null;
+ const resizeHandle = designMode && onWidgetResize && widget.id && !isMobile ? (
+ onWidgetResize(widget.id as string, span)}
+ />
+ ) : null;
const designModeProps = designMode ? {
'data-testid': `dashboard-preview-widget-${widget.id}`,
@@ -1187,7 +1216,9 @@ const DashboardRendererInner = forwardRef
+ {filterMark && {filterMark}
}
{designMode &&
}
+ {resizeHandle}
) : (
{resolvedDescription}
)}
+ {filterMark && {filterMark}
}
)}
@@ -1228,9 +1260,13 @@ const DashboardRendererInner = forwardRef
: }
+ {/* A dataset metric tile draws no card header: its mark
+ sits under the tile instead (objectstack#36372). */}
+ {filterMark && (datasetMetric || !resolvedTitle) && {filterMark}
}
{designMode &&
}
+ {resizeHandle}
);
@@ -1409,7 +1445,7 @@ const DashboardRendererInner = forwardRef
);
- const filterBar = filterDefs.length > 0 && (
+ const filterBar = (filterDefs.length > 0 || (designMode && onAddFilter)) && (
);
diff --git a/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.designMode.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.designMode.test.tsx
index aefc97a2020..6af8e16b135 100644
--- a/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.designMode.test.tsx
+++ b/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.designMode.test.tsx
@@ -399,3 +399,56 @@ describe('DashboardRenderer design mode', () => {
});
});
});
+
+/**
+ * objectstack#36372 — the in-page edit state's two renderer affordances: the
+ * corner handle that resizes a card by whole grid tracks, and the filter
+ * bar's "Add filter". Both are design mode's only, and only when the host
+ * hands their handler.
+ */
+describe('DashboardRenderer design mode — resize and add filter (objectstack#36372)', () => {
+ it('draws a corner handle on every card when the host takes resizes', () => {
+ render(
+ ,
+ );
+ expect(screen.getAllByTestId('dashboard-widget-resize-handle')).toHaveLength(3);
+ });
+
+ it('draws no handle without a resize handler, nor outside design mode', () => {
+ const { unmount } = render( );
+ expect(screen.queryByTestId('dashboard-widget-resize-handle')).not.toBeInTheDocument();
+ unmount();
+ render( );
+ expect(screen.queryByTestId('dashboard-widget-resize-handle')).not.toBeInTheDocument();
+ });
+
+ it('the handle grows and shrinks the card by one track from the keyboard, within the columns, without selecting it', () => {
+ const onWidgetResize = vi.fn();
+ const onWidgetClick = vi.fn();
+ const schema: DashboardComponentSchema = {
+ ...DASHBOARD_WITH_WIDGETS,
+ widgets: [{ id: 'w1', title: 'Revenue', type: 'bar', layout: { x: 0, y: 0, w: 1, h: 2 } } as any],
+ };
+ render( );
+ const handle = screen.getByTestId('dashboard-widget-resize-handle');
+ fireEvent.keyDown(handle, { key: 'ArrowRight' });
+ expect(onWidgetResize).toHaveBeenLastCalledWith('w1', { w: 2, h: 2 });
+ fireEvent.keyDown(handle, { key: 'ArrowUp' });
+ expect(onWidgetResize).toHaveBeenLastCalledWith('w1', { w: 1, h: 1 });
+ fireEvent.click(handle);
+ expect(onWidgetClick).not.toHaveBeenCalled();
+ });
+
+ it('draws the filter bar with "Add filter" in design mode, even before any filter exists', () => {
+ const onAddFilter = vi.fn();
+ render( );
+ fireEvent.click(screen.getByTestId('dashboard-filter-add'));
+ expect(onAddFilter).toHaveBeenCalledTimes(1);
+ });
+
+ it('draws no "Add filter" outside design mode', () => {
+ render( );
+ expect(screen.queryByTestId('dashboard-filter-add')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('dashboard-filter-bar')).not.toBeInTheDocument();
+ });
+});
diff --git a/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.filters.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.filters.test.tsx
index 7e448c71ec5..1304a23cfeb 100644
--- a/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.filters.test.tsx
+++ b/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.filters.test.tsx
@@ -197,3 +197,77 @@ describe('DashboardRenderer dashboard-level filters', () => {
});
});
});
+
+/**
+ * objectstack#36372 — the always-visible mark naming the dashboard filters a
+ * widget is not filtered by. It is asked of the binding the widget's query is
+ * built from (`dashboardFiltersNotApplied` over `resolveBoundField`), so each
+ * case reads the query beside the mark: a marked filter is absent from the
+ * widget's `runtimeFilter`, an unmarked one is in it.
+ */
+describe('DashboardRenderer — the not-filtered mark agrees with the query (objectstack#36372)', () => {
+ const region = {
+ name: 'region',
+ field: 'region',
+ label: 'Region',
+ type: 'select' as const,
+ options: [{ value: 'EMEA', label: 'EMEA' }],
+ defaultValue: 'EMEA',
+ };
+
+ it('marks the opted-out widget, and only it, with the filter it does not follow', async () => {
+ const queryDataset = makeQueryDataset();
+ const schema: DashboardComponentSchema = {
+ type: 'dashboard',
+ globalFilters: [region],
+ widgets: [
+ { id: 'w1', type: 'bar', dataset: 'invoices', values: ['count'] },
+ { id: 'w2', type: 'pie', dataset: 'accounts', values: ['count'], filterBindings: { region: false } },
+ { id: 'w3', type: 'line', dataset: 'orders', values: ['count'], filterBindings: { region: 'ship_region' } },
+ ],
+ };
+ render( );
+
+ await waitFor(() => {
+ expect(lastRuntimeFilter(queryDataset, 'invoices')).toEqual({ region: 'EMEA' });
+ expect(lastRuntimeFilter(queryDataset, 'orders')).toEqual({ ship_region: 'EMEA' });
+ });
+ expect(lastRuntimeFilter(queryDataset, 'accounts')).toBeUndefined();
+
+ const mark = screen.getByTestId('dashboard-widget-filter-mark-w2');
+ expect(mark).toHaveAttribute('data-filters', 'region');
+ expect(mark).toHaveTextContent('Region');
+ expect(screen.queryByTestId('dashboard-widget-filter-mark-w1')).not.toBeInTheDocument();
+ // A rebound filter still reaches the widget, on another field: no mark.
+ expect(screen.queryByTestId('dashboard-widget-filter-mark-w3')).not.toBeInTheDocument();
+ });
+
+ it('marks a widget a filter\'s targetWidgets leaves out', async () => {
+ const queryDataset = makeQueryDataset();
+ const schema: DashboardComponentSchema = {
+ type: 'dashboard',
+ globalFilters: [{ ...region, targetWidgets: ['w1'] } as any],
+ widgets: [
+ { id: 'w1', type: 'bar', dataset: 'invoices', values: ['count'] },
+ { id: 'w2', type: 'pie', dataset: 'accounts', values: ['count'] },
+ ],
+ };
+ render( );
+
+ await waitFor(() => expect(lastRuntimeFilter(queryDataset, 'invoices')).toEqual({ region: 'EMEA' }));
+ expect(lastRuntimeFilter(queryDataset, 'accounts')).toBeUndefined();
+ expect(screen.getByTestId('dashboard-widget-filter-mark-w2')).toHaveAttribute('data-filters', 'region');
+ expect(screen.queryByTestId('dashboard-widget-filter-mark-w1')).not.toBeInTheDocument();
+ });
+
+ it('draws no mark on a dashboard that declares no filters', async () => {
+ const queryDataset = makeQueryDataset();
+ const schema: DashboardComponentSchema = {
+ type: 'dashboard',
+ widgets: [{ id: 'w1', type: 'bar', dataset: 'invoices', values: ['count'], filterBindings: { region: false } }],
+ };
+ render( );
+ await waitFor(() => expect(queryDataset).toHaveBeenCalled());
+ expect(screen.queryByTestId('dashboard-widget-filter-mark-w1')).not.toBeInTheDocument();
+ });
+});
diff --git a/ui/packages/plugin-dashboard/src/designAffordances.test.ts b/ui/packages/plugin-dashboard/src/designAffordances.test.ts
new file mode 100644
index 00000000000..01f079c4244
--- /dev/null
+++ b/ui/packages/plugin-dashboard/src/designAffordances.test.ts
@@ -0,0 +1,43 @@
+/**
+ * ObjectUI
+ * Copyright (c) 2024-present ObjectStack Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { resizedSpan } from './designAffordances';
+
+/**
+ * objectstack#36372 — a corner drag snaps to whole grid tracks: each axis
+ * moves by the drag over one track's pitch (the card's size plus the gap,
+ * over its span), rounded.
+ */
+describe('resizedSpan', () => {
+ // A 2×1 card, 200×80 px, in a grid with a 16 px gap: one column is 108 px
+ // of pitch, one row 96 px.
+ const start = { w: 2, h: 1 };
+ const box = { width: 200, height: 80 };
+
+ it('keeps the span under half a track', () => {
+ expect(resizedSpan(start, box, 16, { dx: 50, dy: 40 }, 4)).toEqual({ w: 2, h: 1 });
+ });
+
+ it('adds a track once the pointer crosses half of one', () => {
+ expect(resizedSpan(start, box, 16, { dx: 60, dy: 50 }, 4)).toEqual({ w: 3, h: 2 });
+ });
+
+ it('shrinks by a dragged-back track, never under one', () => {
+ expect(resizedSpan(start, box, 16, { dx: -110, dy: 0 }, 4)).toEqual({ w: 1, h: 1 });
+ expect(resizedSpan(start, box, 16, { dx: -900, dy: -900 }, 4)).toEqual({ w: 1, h: 1 });
+ });
+
+ it('never grows past the grid\'s columns', () => {
+ expect(resizedSpan(start, box, 16, { dx: 900, dy: 0 }, 4)).toEqual({ w: 4, h: 1 });
+ });
+
+ it('moves nothing for a box it could not measure', () => {
+ expect(resizedSpan(start, { width: 0, height: 0 }, 0, { dx: 300, dy: 300 }, 4)).toEqual(start);
+ });
+});
diff --git a/ui/packages/plugin-dashboard/src/designAffordances.tsx b/ui/packages/plugin-dashboard/src/designAffordances.tsx
new file mode 100644
index 00000000000..1cee1a4a7cd
--- /dev/null
+++ b/ui/packages/plugin-dashboard/src/designAffordances.tsx
@@ -0,0 +1,192 @@
+/**
+ * ObjectUI
+ * Copyright (c) 2024-present ObjectStack Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/**
+ * Two pieces `DashboardRenderer` draws on a widget (objectstack#36372):
+ *
+ * - {@link WidgetFilterMark}: the always-visible mark naming the dashboard
+ * filters that do not reach a widget. It is handed the list
+ * `dashboardFiltersNotApplied` answers, which asks the binding the
+ * widget's query is built from, so the mark and the data agree.
+ * - {@link WidgetResizeHandle}: the design-mode corner handle that resizes a
+ * widget by whole grid tracks.
+ */
+
+import * as React from 'react';
+import { cn } from '@object-ui/components';
+import { useObjectTranslation } from '@object-ui/i18n';
+import type { DashboardFilterDef } from '@object-ui/core';
+import { useDashboardFilterLabeler } from './DashboardFilterBar';
+
+/** `items` as one list in `language` ("Region and Owner"), else comma-joined. */
+function listOf(items: string[], language: string | undefined): string {
+ // `Intl.ListFormat` is ES2021: typed here, since the package's `lib` is ES2020.
+ const ListFormat = (Intl as unknown as {
+ ListFormat?: new (locale?: string, options?: { style: string; type: string }) => { format(list: string[]): string };
+ }).ListFormat;
+ if (!ListFormat) return items.join(', ');
+ try {
+ return new ListFormat(language || undefined, { style: 'long', type: 'conjunction' }).format(items);
+ } catch {
+ return items.join(', ');
+ }
+}
+
+/**
+ * The filters that do not reach a widget, named in one short line. Draws
+ * nothing for an empty list: a widget every filter reaches carries no mark.
+ */
+export function WidgetFilterMark({
+ defs,
+ widgetId,
+ className,
+}: {
+ defs: readonly DashboardFilterDef[];
+ widgetId?: string;
+ className?: string;
+}) {
+ const { t, language } = useObjectTranslation();
+ const labelOf = useDashboardFilterLabeler();
+ if (defs.length === 0) return null;
+ const names = listOf(defs.map((def) => labelOf(def) || def.name), language);
+ const text = t('dashboard.filters.notApplied', { filters: names, defaultValue: 'Not filtered by {{filters}}' });
+ return (
+ def.name).join(',')}
+ title={text}
+ >
+ {text}
+
+ );
+}
+
+/** A widget's span in grid tracks. */
+export interface WidgetSpan {
+ w: number;
+ h: number;
+}
+
+/**
+ * The span a pointer drag of `(dx, dy)` pixels from `start` asks for, in
+ * whole tracks: each axis moves by the drag over one track's pitch (the span's
+ * own size plus the grid gap, divided by its track count), rounded, so the
+ * widget snaps to the grid as the pointer crosses half a track. Width stays
+ * within `1..maxColumns`, height at least `1`.
+ */
+export function resizedSpan(
+ start: WidgetSpan,
+ box: { width: number; height: number },
+ gapPx: number,
+ drag: { dx: number; dy: number },
+ maxColumns: number,
+): WidgetSpan {
+ const pitchW = (box.width + gapPx) / Math.max(1, start.w);
+ const pitchH = (box.height + gapPx) / Math.max(1, start.h);
+ const w = start.w + (pitchW > 0 ? Math.round(drag.dx / pitchW) : 0);
+ const h = start.h + (pitchH > 0 ? Math.round(drag.dy / pitchH) : 0);
+ return {
+ w: Math.min(Math.max(1, w), Math.max(1, maxColumns)),
+ h: Math.max(1, h),
+ };
+}
+
+/**
+ * The bottom-right corner handle of a widget in design mode. A drag reports
+ * each new whole-track span through `onResize` as the pointer crosses a track;
+ * the host writes it into the widget's `layout`. The pointer is captured so
+ * the drag survives leaving the handle, and the pointer-down stops there: the
+ * widget's reorder drag and its click-to-select do not start under it.
+ */
+export function WidgetResizeHandle({
+ span,
+ maxColumns,
+ gapPx,
+ label,
+ onResize,
+}: {
+ span: WidgetSpan;
+ maxColumns: number;
+ gapPx: number;
+ label: string;
+ onResize: (next: WidgetSpan) => void;
+}) {
+ const drag = React.useRef<{
+ x: number;
+ y: number;
+ start: WidgetSpan;
+ box: { width: number; height: number };
+ last: WidgetSpan;
+ } | null>(null);
+
+ const onPointerDown = (e: React.PointerEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+ const card = e.currentTarget.parentElement;
+ const rect = card?.getBoundingClientRect();
+ drag.current = {
+ x: e.clientX,
+ y: e.clientY,
+ start: span,
+ box: { width: rect?.width ?? 0, height: rect?.height ?? 0 },
+ last: span,
+ };
+ e.currentTarget.setPointerCapture?.(e.pointerId);
+ };
+ const onPointerMove = (e: React.PointerEvent) => {
+ const d = drag.current;
+ if (!d) return;
+ const next = resizedSpan(d.start, d.box, gapPx, { dx: e.clientX - d.x, dy: e.clientY - d.y }, maxColumns);
+ if (next.w === d.last.w && next.h === d.last.h) return;
+ d.last = next;
+ onResize(next);
+ };
+ const end = (e: React.PointerEvent) => {
+ if (!drag.current) return;
+ drag.current = null;
+ e.currentTarget.releasePointerCapture?.(e.pointerId);
+ };
+ // The keyboard path: arrows grow or shrink the span by one track.
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ const step: Record> = {
+ ArrowRight: { w: span.w + 1 },
+ ArrowLeft: { w: span.w - 1 },
+ ArrowDown: { h: span.h + 1 },
+ ArrowUp: { h: span.h - 1 },
+ };
+ const patch = step[e.key];
+ if (!patch) return;
+ e.preventDefault();
+ e.stopPropagation();
+ const next = {
+ w: Math.min(Math.max(1, patch.w ?? span.w), Math.max(1, maxColumns)),
+ h: Math.max(1, patch.h ?? span.h),
+ };
+ if (next.w !== span.w || next.h !== span.h) onResize(next);
+ };
+
+ return (
+ e.stopPropagation()}
+ onKeyDown={onKeyDown}
+ />
+ );
+}
From 77c230392fd5594e423b99bc701fde4125a220f1 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 09:54:37 +0000
Subject: [PATCH 3/7] test(console): pay the panels' lazy imports during
collection in the in-page edit tests
Co-authored-by: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jUeSU9HhKxjcVsyprx
---
ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts | 4 ++++
.../src/views/DashboardView.inPageEdit-36372.test.tsx | 3 +++
2 files changed, 7 insertions(+)
diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
index 6e8b8abbfd3..4a54b910ea7 100644
--- a/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
+++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
@@ -7,6 +7,10 @@
*/
import { describe, it, expect, vi } from 'vitest';
+// Paid during collection, not inside a case's clock: Studio's dashboard panels
+// reach both through dynamic imports (check:test-source-alias).
+import '@objectstack/lint';
+import '@objectstack/formula';
import {
filtersSectionLabel,
openDashboardForEdit,
diff --git a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
index 178d36a9efb..133b9d69bb3 100644
--- a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
+++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
@@ -34,6 +34,9 @@ import * as React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, act, cleanup, fireEvent, waitFor } from '@testing-library/react';
import { MetadataCtx } from '@object-ui/react';
+// Paid during collection, not inside a case's clock: Studio's card panel
+// reaches `@objectstack/lint` through a dynamic import (check:test-source-alias).
+import '@objectstack/lint';
const meta = vi.hoisted(() => ({ value: null as unknown }));
const gate = vi.hoisted(() => ({ entry: null as null | { path: string; posture: 'edit' | 'view' } }));
From 071fdb48a634dc2ab0159bcb866015e658042118 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 09:57:29 +0000
Subject: [PATCH 4/7] refactor(console): keep the persistence module's package
import line as main has it
Co-authored-by: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jUeSU9HhKxjcVsyprx
---
.../app-shell/src/views/runtime-metadata-persistence.ts | 8 ++------
1 file changed, 2 insertions(+), 6 deletions(-)
diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
index ed5032719f1..95a4a98518d 100644
--- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
+++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
@@ -42,12 +42,8 @@ import { stripReadDecorations } from '@objectstack/spec/kernel';
import { emitMetadataRefresh } from '../assistant/assistantBus.js';
import { slugify } from './metadata-admin/createDerive.js';
import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js';
-import {
- ensureCustomizationPackage,
- fetchListedPackageManifests,
- listedPackageVersion,
- type ListedPackageManifest,
-} from './studio-design/packages-io.js';
+import { ensureCustomizationPackage, fetchListedPackageManifests } from './studio-design/packages-io.js';
+import { listedPackageVersion, type ListedPackageManifest } from './studio-design/packages-io.js';
import { overrideDraftBody } from './studio-design/StudioCustomizeControls.js';
/** The runtime-editable artifact types ADR-0034 unifies. `page` (a record
From b06377778975fee24fae8ae63126333b74b19c9b Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 09:58:02 +0000
Subject: [PATCH 5/7] refactor(console): a package-bound dashboard save leaves
the confirmed-save door unchanged
Co-authored-by: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jUeSU9HhKxjcVsyprx
---
.changeset/36372-dashboard-in-page-edit.md | 3 +-
.../src/views/runtime-metadata-persistence.ts | 44 +++++++++++--------
2 files changed, 26 insertions(+), 21 deletions(-)
diff --git a/.changeset/36372-dashboard-in-page-edit.md b/.changeset/36372-dashboard-in-page-edit.md
index 48806be2689..2a0c0936bc7 100644
--- a/.changeset/36372-dashboard-in-page-edit.md
+++ b/.changeset/36372-dashboard-in-page-edit.md
@@ -7,7 +7,7 @@
feat(console): a dashboard is edited on its own page by the people who may design its package, and every card marks the page filters it does not follow
-Clause-②: yes (widening) — one new exported function (`dashboardFiltersNotApplied` in `@object-ui/core`), two new optional `DashboardRenderer` props (`onWidgetResize`, `onAddFilter`), an optional `{ packageId }` on `saveAndPublishRuntimeMetadata`, and new `@object-ui/i18n` keys (`dashboard.inPageEdit.*`, `dashboard.filters.notApplied`, `dashboard.filters.addFilter`); nothing is removed or renamed
+Clause-②: yes (widening) — one new exported function (`dashboardFiltersNotApplied` in `@object-ui/core`), two new optional `DashboardRenderer` props (`onWidgetResize`, `onAddFilter`), and new `@object-ui/i18n` keys (`dashboard.inPageEdit.*`, `dashboard.filters.notApplied`, `dashboard.filters.addFilter`); nothing is removed or renamed
Metadata-protocol: none
A dashboard page draws an **Edit** button for a workspace admin who may author metadata, on a package Studio lists (the gate of the app's Studio entries). Edit opens the dashboard as stored (never the translated copy the page shows) in an edit state: the header says **Editing**, with **Add card**, **Discard** and **Save**; every card draws a dashed outline and can be dragged to move it, resized from its corner by whole grid tracks (or with the arrow keys on the corner handle) and clicked to select it. The panel at the right is Studio's own dashboard panels, as they stand: a selected card's (its data, its "follow page filters" switches, Remove) and otherwise the dashboard's (label, cards, filters, layout). The filter bar's **Add filter** opens the panel's Filters section. Add card appends a card at the end and selects it.
@@ -16,4 +16,3 @@ Save writes where Studio's Customize would and publishes that one item in the sa
Every card, in every mode, carries a small mark naming the page filters that do not reach it ("Not filtered by Region"), asked of the same binding its query is built from (`dashboardFiltersNotApplied` over `resolveBoundField`): a filter the card opts out of, or one whose `targetWidgets` leaves it out. A card every filter reaches carries none.
-`saveAndPublishRuntimeMetadata` takes an optional `{ packageId }`, named on its draft write, its publish and its discard; omitted, it writes exactly as before.
diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
index 95a4a98518d..5a2d30c22ce 100644
--- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
+++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
@@ -538,16 +538,9 @@ export async function saveAndPublishRuntimeMetadata(
name: string,
body: any,
ctx: RuntimePersistCtx,
- /**
- * objectstack#36372 — the package the draft is written into and published
- * from (`?package=` on all three writes). Omitted, every write names no
- * package and addresses the name's one holding package, as before.
- */
- options: { packageId?: string } = {},
): Promise {
- const bound = options.packageId ? { packageId: options.packageId } : {};
try {
- await ctx.metadataClient.save(type, name, body, { mode: 'draft', ifNoneMatch: '*', ...bound });
+ await ctx.metadataClient.save(type, name, body, { mode: 'draft', ifNoneMatch: '*' });
} catch (err) {
if (isDraftVersionConflict(err)) {
return 'pending-draft';
@@ -555,12 +548,10 @@ export async function saveAndPublishRuntimeMetadata(
throw err;
}
try {
- await (options.packageId
- ? ctx.metadataClient.publish(type, name, bound)
- : ctx.metadataClient.publish(type, name));
+ await ctx.metadataClient.publish(type, name);
} catch (err) {
try {
- await ctx.metadataClient.reset(type, name, { state: 'draft', ...bound });
+ await ctx.metadataClient.reset(type, name, { state: 'draft' });
} catch (discardErr) {
// The draft this call wrote stays pending: the view settings' draft
// bar shows it, and its Discard removes it.
@@ -666,11 +657,26 @@ export async function saveDashboardInPlace(
target: Exclude,
ctx: RuntimePersistCtx,
): Promise {
- return saveAndPublishRuntimeMetadata(
- 'dashboard',
- name,
- body,
- ctx,
- target.kind === 'unbound' ? {} : { packageId: target.packageId },
- );
+ if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('dashboard', name, body, ctx);
+ return saveAndPublishRuntimeMetadata('dashboard', name, body, {
+ ...ctx,
+ metadataClient: boundToPackage(ctx.metadataClient, target.packageId),
+ });
+}
+
+/**
+ * `client` with `packageId` named on every write {@link saveAndPublishRuntimeMetadata}
+ * makes (`save`, `publish`, `reset`: `?package=` on the draft, the publish and
+ * the discard of a refused publish), so the one door serves a package-bound save
+ * unchanged. Only those three: they are all the door calls.
+ */
+function boundToPackage(client: any, packageId: string): any {
+ return {
+ save: (type: string, name: string, body: unknown, options: Record = {}) =>
+ client.save(type, name, body, { ...options, packageId }),
+ publish: (type: string, name: string, options: Record = {}) =>
+ client.publish(type, name, { ...options, packageId }),
+ reset: (type: string, name: string, options: Record = {}) =>
+ client.reset(type, name, { ...options, packageId }),
+ };
}
From 3e7995a73b6f2176048981406fb832391a61c2e1 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 10:18:30 +0000
Subject: [PATCH 6/7] test(console): the dashboard route test's Studio gate
mock answers the Edit button's read too
Co-authored-by: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jUeSU9HhKxjcVsyprx
---
.../__tests__/AppContent.dashboardRouteReads-28784.test.tsx | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.dashboardRouteReads-28784.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.dashboardRouteReads-28784.test.tsx
index 6205f92bce1..7d35e3ed345 100644
--- a/ui/packages/app-shell/src/console/__tests__/AppContent.dashboardRouteReads-28784.test.tsx
+++ b/ui/packages/app-shell/src/console/__tests__/AppContent.dashboardRouteReads-28784.test.tsx
@@ -51,7 +51,8 @@ vi.mock('../../layout/ConsoleLayout', () => ({
ConsoleLayout: ({ children }: { children?: React.ReactNode }) => {children}
,
}));
vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null }));
-vi.mock('../../hooks/useStudioDesignGate', () => ({ useStudioDesignGate: () => null }));
+// `useStudioEntryGate`: the dashboard page's Edit button reads it (objectstack#36372).
+vi.mock('../../hooks/useStudioDesignGate', () => ({ useStudioDesignGate: () => null, useStudioEntryGate: () => null }));
vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null }));
vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null }));
vi.mock('@object-ui/i18n', async (importOriginal) => ({
From f0750e0ddb2a638b2cf0c3c57e16d549ac10b355 Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 22 Nov 2026 11:34:40 +0000
Subject: [PATCH 7/7] fix(console): opening a dashboard's in-page edit writes
nothing, and refuses where Studio's Customize would
Edit on an installed app's dashboard asked the ensure door at open, which
creates the app's customization package on first use, so Edit then Discard
left a new package behind. Opening now only reads: the pair is looked up in
the package list (listedCustomizationPairOf), and the ensure door is asked at
Save, the edit's first write. The edit state is also refused up front where
Studio's Customize is: the ensure door walled for this caller, and a base
listing no version to declare the override at (unless the item already
declares one).
Two things a live run showed: the not-filtered mark named the built-in date
filter by its reserved name ("dateRange") instead of "Date range", and the
edit state drew the stored document without the served _packageId, so its
cards' dataset queries no longer named the dashboard's package as their
reader. Both fixed and pinned.
Co-authored-by: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jUeSU9HhKxjcVsyprx
---
.changeset/36372-dashboard-in-page-edit.md | 4 +-
.../frontend/plugins/plugin-dashboard.mdx | 4 +-
.../src/views/DashboardInPageEditor.test.ts | 73 +++++++++++++---
.../src/views/DashboardInPageEditor.tsx | 86 ++++++++++++++-----
.../DashboardView.inPageEdit-36372.test.tsx | 77 +++++++++++++++--
.../app-shell/src/views/DashboardView.tsx | 16 +++-
.../runtime-metadata-persistence.test.ts | 44 ++++++----
.../src/views/runtime-metadata-persistence.ts | 82 +++++++++++-------
ui/packages/i18n/src/locales/ar.ts | 2 +
ui/packages/i18n/src/locales/de.ts | 2 +
ui/packages/i18n/src/locales/en.ts | 2 +
ui/packages/i18n/src/locales/es.ts | 2 +
ui/packages/i18n/src/locales/fr.ts | 2 +
ui/packages/i18n/src/locales/ja.ts | 2 +
ui/packages/i18n/src/locales/ko.ts | 2 +
ui/packages/i18n/src/locales/pt-BR.ts | 2 +
ui/packages/i18n/src/locales/ru.ts | 2 +
ui/packages/i18n/src/locales/zh-Hans.ts | 2 +
ui/packages/i18n/src/locales/zh-Hant.ts | 2 +
ui/packages/plugin-dashboard/README.md | 4 +-
.../DashboardRenderer.filters.test.tsx | 20 +++++
.../src/designAffordances.tsx | 12 ++-
22 files changed, 349 insertions(+), 95 deletions(-)
diff --git a/.changeset/36372-dashboard-in-page-edit.md b/.changeset/36372-dashboard-in-page-edit.md
index 2a0c0936bc7..d29ad0796c2 100644
--- a/.changeset/36372-dashboard-in-page-edit.md
+++ b/.changeset/36372-dashboard-in-page-edit.md
@@ -12,7 +12,7 @@ Metadata-protocol: none
A dashboard page draws an **Edit** button for a workspace admin who may author metadata, on a package Studio lists (the gate of the app's Studio entries). Edit opens the dashboard as stored (never the translated copy the page shows) in an edit state: the header says **Editing**, with **Add card**, **Discard** and **Save**; every card draws a dashed outline and can be dragged to move it, resized from its corner by whole grid tracks (or with the arrow keys on the corner handle) and clicked to select it. The panel at the right is Studio's own dashboard panels, as they stand: a selected card's (its data, its "follow page filters" switches, Remove) and otherwise the dashboard's (label, cards, filters, layout). The filter bar's **Add filter** opens the panel's Filters section. Add card appends a card at the end and selects it.
-Save writes where Studio's Customize would and publishes that one item in the same act, so everyone sees the change at once without the app's package being published: into the owning package when it is writable, else into the app's customization package (` .custom`, asked of the ensure door, declaring `overrides: { package, basedOn }`), so an installed app's dashboard is edited too. A dashboard with a draft already pending there (a Studio edit not yet published) is not opened for editing, and a save over one writes nothing: that draft is never published on its saver's behalf. Discard drops every change.
+Save writes where Studio's Customize would and publishes that one item in the same act, so everyone sees the change at once without the app's package being published: into the owning package when it is writable, else into the app's customization package (` .custom`, declaring `overrides: { package, basedOn }`), so an installed app's dashboard is edited too. Opening the edit state writes nothing: the pair is asked of the ensure door, which creates it on first use, at Save only. As with Studio's Customize, an installed app's dashboard is not opened where that door is walled for the caller or the package list gives no installed version to declare the override at. A dashboard with a draft already pending there (a Studio edit not yet published) is not opened for editing, and a save over one writes nothing: that draft is never published on its saver's behalf. Discard drops every change and writes nothing.
-Every card, in every mode, carries a small mark naming the page filters that do not reach it ("Not filtered by Region"), asked of the same binding its query is built from (`dashboardFiltersNotApplied` over `resolveBoundField`): a filter the card opts out of, or one whose `targetWidgets` leaves it out. A card every filter reaches carries none.
+Every card, in every mode, carries a small mark naming the page filters that do not reach it ("Not filtered by Region"), asked of the same binding its query is built from (`dashboardFiltersNotApplied` over `resolveBoundField`): a filter the card opts out of, or one whose `targetWidgets` leaves it out (an explicit string binding wins over `targetWidgets`). A card every filter reaches carries none.
diff --git a/content/docs/frontend/plugins/plugin-dashboard.mdx b/content/docs/frontend/plugins/plugin-dashboard.mdx
index 20489ce35df..3afdc083c72 100644
--- a/content/docs/frontend/plugins/plugin-dashboard.mdx
+++ b/content/docs/frontend/plugins/plugin-dashboard.mdx
@@ -148,7 +148,9 @@ object it reads. A query asked alone, and every query of an adapter without
Every widget, in every mode, carries a small mark naming the dashboard
filters that do not reach it, for example "Not filtered by Region": a filter
it opts out of (`filterBindings[name]: false`) or one whose `targetWidgets`
-leaves it out. A widget every filter reaches carries none. The list is
+leaves it out. An explicit string binding (`filterBindings[name]: 'field'`)
+wins over `targetWidgets`, so a widget that names its field is reached even
+when the list leaves it out. A widget every filter reaches carries none. The list is
`dashboardFiltersNotApplied(widget, defs)` from `@object-ui/core`, which asks
`resolveBoundField`, the binding the widget's query is built from, so the
mark and the data cannot disagree.
diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
index 4a54b910ea7..0c23fda3e3e 100644
--- a/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
+++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
@@ -17,7 +17,6 @@ import {
withAddedWidget,
withResizedWidget,
} from './DashboardInPageEditor';
-import type { DashboardSaveTargetDoors } from './runtime-metadata-persistence';
/**
* objectstack#36372 — opening a dashboard for in-page editing, and the two
@@ -25,10 +24,12 @@ import type { DashboardSaveTargetDoors } from './runtime-metadata-persistence';
* the buffer's edits are Studio's panels' own `onPatch`.
*/
-const doors = (writable: boolean): DashboardSaveTargetDoors => ({
- listPackages: async () => new Map([['crm', { writable, manifest: { id: 'crm', version: '3.0.0' } } as any]]),
- ensureCustomization: async (base) => ({ packageId: `${base}.custom`, writable: true }),
+const listed = (entries: Record) => ({
+ listPackages: vi.fn(async () =>
+ new Map(Object.entries(entries).map(([id, e]) => [id, { writable: e.writable, manifest: { id, version: e.version } } as any])),
+ ),
});
+const doors = (writable: boolean) => listed({ crm: { writable, version: '3.0.0' } });
const stored = { name: 'exec', label: 'Exec', widgets: [{ id: 'a', type: 'bar' }] };
@@ -38,7 +39,7 @@ describe('openDashboardForEdit', () => {
getDraft: vi.fn(async () => null),
layered: vi.fn(async () => ({ code: { name: 'exec' }, effective: stored })),
};
- await expect(openDashboardForEdit('exec', 'crm', client, doors(true))).resolves.toEqual({
+ await expect(openDashboardForEdit('exec', 'crm', client, { doors: doors(true) })).resolves.toEqual({
kind: 'ready',
target: { kind: 'package', packageId: 'crm' },
doc: stored,
@@ -46,33 +47,81 @@ describe('openDashboardForEdit', () => {
expect(client.getDraft).toHaveBeenCalledWith('dashboard', 'exec', { packageId: 'crm' });
});
- it('into a customization pair that does not hold it yet, opens its base\'s document', async () => {
+ it('an installed app with no pair yet opens its base\'s document, reading no pair and creating none', async () => {
+ const client = {
+ getDraft: vi.fn(async () => null),
+ layered: vi.fn(async () => ({ code: stored, effective: stored })),
+ };
+ // The doors carry no ensure door at all: opening could not create the pair if it tried.
+ const opened = await openDashboardForEdit('exec', 'crm', client, { doors: doors(false) });
+ expect(opened).toEqual({ kind: 'ready', target: { kind: 'customization', base: 'crm', basedOn: '3.0.0', pair: null }, doc: stored });
+ expect(client.getDraft).not.toHaveBeenCalled();
+ expect(client.layered).toHaveBeenCalledTimes(1);
+ expect(client.layered).toHaveBeenCalledWith('dashboard', 'exec', { packageId: 'crm' });
+ });
+
+ it('into a listed pair that does not hold it yet, opens its base\'s document', async () => {
const client = {
getDraft: vi.fn(async () => null),
layered: vi.fn(async (_t: string, _n: string, o?: { packageId?: string }) =>
o?.packageId === 'crm' ? { code: stored, effective: stored } : { code: null, effective: null },
),
};
- const opened = await openDashboardForEdit('exec', 'crm', client, doors(false));
- expect(opened).toMatchObject({ kind: 'ready', target: { kind: 'customization', packageId: 'crm.custom', base: 'crm' }, doc: stored });
+ const pairListed = listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } });
+ const opened = await openDashboardForEdit('exec', 'crm', client, { doors: pairListed });
+ expect(opened).toMatchObject({ kind: 'ready', target: { kind: 'customization', base: 'crm', pair: 'crm.custom' }, doc: stored });
expect(client.getDraft).toHaveBeenCalledWith('dashboard', 'exec', { packageId: 'crm.custom' });
});
+ it('is refused for an installed app where Studio\'s Customize is: the ensure door walled, or no version to declare', async () => {
+ const client = { getDraft: vi.fn(async () => null), layered: vi.fn(async () => ({ code: stored, effective: stored })) };
+ await expect(openDashboardForEdit('exec', 'crm', client, { doors: doors(false), walled: true })).resolves.toEqual({
+ kind: 'refused',
+ reason: 'walled',
+ });
+ expect(client.layered).not.toHaveBeenCalled();
+ // A writable package is not customized, so the wall does not apply to it.
+ await expect(openDashboardForEdit('exec', 'crm', client, { doors: doors(true), walled: true })).resolves.toMatchObject({ kind: 'ready' });
+ await expect(
+ openDashboardForEdit('exec', 'crm', client, { doors: listed({ crm: { writable: false } }) }),
+ ).resolves.toMatchObject({ kind: 'refused', reason: 'no-version' });
+ // An item the pair already declares an override of keeps that declaration: no listed version is owed.
+ const customized = { ...stored, overrides: { package: 'crm', basedOn: '2.0.0' } };
+ const inPair = {
+ getDraft: vi.fn(async () => null),
+ layered: vi.fn(async () => ({ code: null, effective: customized })),
+ };
+ await expect(
+ openDashboardForEdit('exec', 'crm', inPair, {
+ doors: listed({ crm: { writable: false }, 'crm.custom': { writable: true } }),
+ }),
+ ).resolves.toMatchObject({ kind: 'ready', doc: customized });
+ });
+
it('is refused over a pending draft, without reading the document', async () => {
const client = {
getDraft: vi.fn(async () => ({ item: { name: 'exec' } })),
layered: vi.fn(),
};
- await expect(openDashboardForEdit('exec', 'crm', client, doors(true))).resolves.toEqual({ kind: 'refused', reason: 'pending-draft' });
+ await expect(openDashboardForEdit('exec', 'crm', client, { doors: doors(true) })).resolves.toEqual({
+ kind: 'refused',
+ reason: 'pending-draft',
+ });
expect(client.layered).not.toHaveBeenCalled();
});
it('is refused when there is no package to save into, and when the read fails', async () => {
const client = { getDraft: vi.fn(async () => null), layered: vi.fn(async () => ({ code: null, effective: null })) };
- await expect(openDashboardForEdit('exec', 'gone', client, doors(true))).resolves.toMatchObject({ kind: 'refused', reason: 'no-package' });
- await expect(openDashboardForEdit('exec', 'crm', client, doors(true))).resolves.toMatchObject({ kind: 'refused', reason: 'load-failed' });
+ await expect(openDashboardForEdit('exec', 'gone', client, { doors: doors(true) })).resolves.toMatchObject({
+ kind: 'refused',
+ reason: 'no-package',
+ });
+ await expect(openDashboardForEdit('exec', 'crm', client, { doors: doors(true) })).resolves.toMatchObject({
+ kind: 'refused',
+ reason: 'load-failed',
+ });
const failing = { getDraft: vi.fn(async () => { throw new Error('500'); }), layered: vi.fn() };
- await expect(openDashboardForEdit('exec', 'crm', failing, doors(true))).resolves.toEqual({
+ await expect(openDashboardForEdit('exec', 'crm', failing, { doors: doors(true) })).resolves.toEqual({
kind: 'refused',
reason: 'load-failed',
detail: '500',
diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx
index 709cc51e502..0a27b679ebb 100644
--- a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx
+++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx
@@ -11,11 +11,15 @@
* change applies to everyone at once without the app's package being
* published; Discard drops every change.
*
- * Where a save lands is {@link resolveDashboardSaveTarget}'s answer: the
+ * Where a save lands is {@link resolveDashboardEditTarget}'s answer: the
* owning package when it is writable, else the app's customization package
- * ` .custom` (ADR-0146), so an installed app is edited too. Over a draft
- * already pending there (a Studio edit not yet published) the edit state is
- * not entered: that draft is its saver's, and is never published on their
+ * ` .custom` (ADR-0146), so an installed app is edited too. Opening
+ * writes nothing: the pair is read from the package list, and asked of the
+ * ensure door (which creates it on first use) only at Save. The edit state is
+ * not entered where Studio's Customize is refused up front (the ensure door
+ * walled for this caller, or the base listing no version to declare the
+ * override at), nor over a draft already pending there (a Studio edit not yet
+ * published): that draft is its saver's, and is never published on their
* behalf.
*
* Out of scope here: undo, a business user's own copy, a new dashboard, chart
@@ -29,10 +33,11 @@ import { completeWidgetLayout, defaultWidgetPlacement, type DashboardWidgetSchem
import { useSafeTranslate } from '@object-ui/i18n';
import {
dashboardSaveBody,
- resolveDashboardSaveTarget,
+ ensureDashboardSaveTarget,
+ resolveDashboardEditTarget,
saveDashboardInPlace,
unwrapDraftBody,
- type DashboardSaveTarget,
+ type DashboardEditTarget,
type DashboardSaveTargetDoors,
type SaveAndPublishOutcome,
} from './runtime-metadata-persistence.js';
@@ -46,13 +51,16 @@ import { getDashboardForm } from './metadata-admin/dashboard-schema.js';
import { useMetadataLocale, type SupportedLocale } from './metadata-admin/i18n.js';
import type { MetadataSelection } from './metadata-admin/preview-registry.js';
-/** A save target the editor can write to. */
-export type WritableDashboardSaveTarget = Exclude;
+/** Where the editor would save, as read at open (nothing is written to open). */
+export type WritableDashboardEditTarget = Exclude;
+
+/** Why the edit state is not entered. */
+export type DashboardEditRefusal = 'no-package' | 'walled' | 'no-version' | 'pending-draft' | 'load-failed';
/** What opening a dashboard for editing found. */
export type DashboardEditOpening =
- | { kind: 'ready'; target: WritableDashboardSaveTarget; doc: Record }
- | { kind: 'refused'; reason: 'no-package' | 'pending-draft' | 'load-failed'; detail?: string };
+ | { kind: 'ready'; target: WritableDashboardEditTarget; doc: Record }
+ | { kind: 'refused'; reason: DashboardEditRefusal; detail?: string };
/** The metadata client calls {@link openDashboardForEdit} makes. */
export interface DashboardEditReader {
@@ -69,31 +77,58 @@ function authoredDoc(layers: { code: unknown; effective: unknown } | null): Reco
return doc && typeof doc === 'object' && !Array.isArray(doc) ? (doc as Record) : null;
}
+/** What {@link openDashboardForEdit} is told besides the item. */
+export interface DashboardEditOpenOptions {
+ doors?: Pick;
+ /**
+ * The ensure door refuses this caller on this deployment
+ * (`useCustomizeDoorWalled`): an installed app's dashboard is then not
+ * opened, as Studio's Customize is disabled for it.
+ */
+ walled?: boolean;
+}
+
/**
* Open `name` for editing: where a save would land, and the document as
* authored there (its layered read's `effective`, the buffer Studio edits; a
- * customization package that does not hold the item yet starts from its
- * base's). Refused when there is no package to save into, when a draft is
- * already pending there, or when the item cannot be read.
+ * customization package that does not list the pair or hold the item yet
+ * starts from its base's). Reads only: the customization pair is never
+ * created here. Refused when there is no package to save into, where Studio's
+ * Customize would be (the ensure door walled for this caller; no listed base
+ * version to declare the override at), when a draft is already pending
+ * there, or when the item cannot be read.
*/
export async function openDashboardForEdit(
name: string,
ownerPackageId: string | null | undefined,
client: DashboardEditReader,
- doors?: DashboardSaveTargetDoors,
+ options: DashboardEditOpenOptions = {},
): Promise {
- const target = await resolveDashboardSaveTarget(ownerPackageId, doors);
+ const target = await resolveDashboardEditTarget(ownerPackageId, options.doors);
if (target.kind === 'refused') return { kind: 'refused', reason: 'no-package', detail: target.reason };
- const at = target.kind === 'unbound' ? {} : { packageId: target.packageId };
+ if (target.kind === 'customization' && options.walled) return { kind: 'refused', reason: 'walled' };
+ // A pair not listed yet holds nothing: no draft to find, the base's document opens.
+ const at =
+ target.kind === 'unbound'
+ ? {}
+ : target.kind === 'package'
+ ? { packageId: target.packageId }
+ : target.pair
+ ? { packageId: target.pair }
+ : null;
try {
- if (unwrapDraftBody(await client.getDraft('dashboard', name, at))) {
+ if (at && unwrapDraftBody(await client.getDraft('dashboard', name, at))) {
return { kind: 'refused', reason: 'pending-draft' };
}
- let doc = authoredDoc(await client.layered('dashboard', name, at));
+ let doc = at ? authoredDoc(await client.layered('dashboard', name, at)) : null;
if (!doc && target.kind === 'customization') {
doc = authoredDoc(await client.layered('dashboard', name, { packageId: target.base }));
}
if (!doc) return { kind: 'refused', reason: 'load-failed' };
+ // Studio's `noVersion`: no override declared yet, and no version to declare it at.
+ if (target.kind === 'customization' && dashboardSaveBody(doc, target) === null) {
+ return { kind: 'refused', reason: 'no-version', detail: target.base };
+ }
return { kind: 'ready', target, doc };
} catch (err) {
return { kind: 'refused', reason: 'load-failed', detail: err instanceof Error ? err.message : String(err) };
@@ -332,15 +367,18 @@ export function useDashboardInPageEdit({
client,
dataSource,
doors,
+ walled = false,
}: {
name: string;
ownerPackageId: string | null | undefined;
client: DashboardEditClient;
dataSource?: object | null;
doors?: DashboardSaveTargetDoors;
+ /** `useCustomizeDoorWalled()` for this session: see {@link DashboardEditOpenOptions.walled}. */
+ walled?: boolean;
}): DashboardInPageEdit {
const [session, setSession] = React.useState<{
- target: WritableDashboardSaveTarget;
+ target: WritableDashboardEditTarget;
draft: Record;
dirty: boolean;
} | null>(null);
@@ -362,7 +400,7 @@ export function useDashboardInPageEdit({
const open = React.useCallback(async () => {
setOpening(true);
try {
- const opened = await openDashboardForEdit(name, ownerPackageId, client, doors);
+ const opened = await openDashboardForEdit(name, ownerPackageId, client, { doors, walled });
if (opened.kind === 'refused') return opened;
setSession({ target: opened.target, draft: opened.doc, dirty: false });
setSelection(null);
@@ -370,7 +408,7 @@ export function useDashboardInPageEdit({
} finally {
setOpening(false);
}
- }, [name, ownerPackageId, client, doors]);
+ }, [name, ownerPackageId, client, doors, walled]);
const discard = React.useCallback(() => {
setSession(null);
@@ -384,7 +422,9 @@ export function useDashboardInPageEdit({
if (!body) return 'invalid-body';
setSaving(true);
try {
- const outcome = await saveDashboardInPlace(name, body, session.target, {
+ // The first write of the edit: an installed app's pair is asked for (and made) here.
+ const target = await ensureDashboardSaveTarget(session.target, doors);
+ const outcome = await saveDashboardInPlace(name, body, target, {
metadataClient: client,
dataSource: (dataSource ?? null) as any,
});
@@ -396,7 +436,7 @@ export function useDashboardInPageEdit({
} finally {
setSaving(false);
}
- }, [session, name, client, dataSource]);
+ }, [session, name, client, dataSource, doors]);
const addCard = React.useCallback(
(type: string) => {
diff --git a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
index 133b9d69bb3..9fbd6cec533 100644
--- a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
+++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
@@ -22,7 +22,11 @@
* the first-write pin and publishes that one item, and the page leaves
* the edit state;
* - an installed (read-only) package saves into its customization pair,
- * declaring the override of its base;
+ * declaring the override of its base, and the pair is asked of the
+ * ensure door (which creates it) at Save only: Edit then Discard there
+ * creates no pair and writes nothing;
+ * - where Studio's Customize is walled for the caller, an installed app's
+ * dashboard is not opened;
* - a draft already pending there refuses the edit state and writes nothing;
* - Discard drops every change and writes nothing.
*
@@ -39,11 +43,12 @@ import { MetadataCtx } from '@object-ui/react';
import '@objectstack/lint';
const meta = vi.hoisted(() => ({ value: null as unknown }));
-const gate = vi.hoisted(() => ({ entry: null as null | { path: string; posture: 'edit' | 'view' } }));
+const gate = vi.hoisted(() => ({ entry: null as null | { path: string; posture: 'edit' | 'view' }, walled: false }));
const client = vi.hoisted(() => ({ value: null as any }));
const packages = vi.hoisted(() => ({
listed: new Map(),
ensure: null as null | ((base: string) => Promise<{ packageId: string; writable: boolean }>),
+ ensured: [] as string[],
}));
const toasts = vi.hoisted(() => ({ success: [] as unknown[], error: [] as unknown[] }));
@@ -67,7 +72,14 @@ vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => client
vi.mock('./studio-design/packages-io', async (importOriginal) => ({
...(await importOriginal>()),
fetchListedPackageManifests: async () => packages.listed,
- ensureCustomizationPackage: (base: string) => packages.ensure!(base),
+ ensureCustomizationPackage: (base: string) => {
+ packages.ensured.push(base);
+ return packages.ensure!(base);
+ },
+}));
+vi.mock('./studio-design/StudioCustomizeControls', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ useCustomizeDoorWalled: () => gate.walled,
}));
vi.mock('sonner', () => ({
toast: {
@@ -102,12 +114,11 @@ const served = {
widgets: [{ id: 'widget_total', type: 'kpi', title: 'Total (served)', options: { value: 42 } }],
};
-/** The same dashboard as stored: what the edit state opens. */
+/** The same dashboard as stored: what the edit state opens (the layered read carries no `_packageId`). */
const stored = {
name: 'ops_board',
label: 'Operations (stored)',
widgets: [{ id: 'widget_total', type: 'kpi', title: 'Total (stored)', options: { value: 42 } }],
- _packageId: 'crm',
};
function makeClient(over: Partial> = {}) {
@@ -121,11 +132,11 @@ function makeClient(over: Partial> = {}) {
};
}
-function mount() {
+function mount(dashboard: Record = served, dataSource?: object) {
meta.value = {
apps: [],
objects: [],
- dashboards: [served],
+ dashboards: [dashboard],
reports: [],
pages: [],
loading: false,
@@ -139,7 +150,7 @@ function mount() {
};
return render(
}>
-
+
,
);
}
@@ -151,9 +162,11 @@ async function openEdit() {
beforeEach(() => {
gate.entry = { path: '/studio/crm', posture: 'edit' };
+ gate.walled = false;
client.value = makeClient();
packages.listed = new Map([['crm', { id: 'crm', writable: true, manifest: { id: 'crm', version: '1.4.0' } }]]);
packages.ensure = async (base) => ({ packageId: `${base}.custom`, writable: true });
+ packages.ensured = [];
toasts.success = [];
toasts.error = [];
});
@@ -207,6 +220,21 @@ describe('DashboardView in-page edit (objectstack#36372)', () => {
expect(toasts.success).toHaveLength(1);
});
+ it('in the edit state, a dataset card still queries as the dashboard\'s package', async () => {
+ const queryDataset = vi.fn(async () => ({ rows: [], fields: [] }));
+ const dsWidget = { id: 'widget_ds', type: 'bar', title: 'By stage', dataset: 'ops_metrics', values: ['n'] };
+ client.value = makeClient({
+ layered: vi.fn(async () => ({ code: null, overlay: null, effective: { ...stored, widgets: [dsWidget] } })),
+ });
+ mount({ ...served, widgets: [dsWidget] }, { queryDataset });
+ await waitFor(() => expect(queryDataset).toHaveBeenCalled());
+ expect(queryDataset.mock.calls.every((c: unknown[]) => (c[2] as { callerPackage?: string })?.callerPackage === 'crm')).toBe(true);
+ queryDataset.mockClear();
+ await openEdit();
+ await waitFor(() => expect(queryDataset).toHaveBeenCalled());
+ expect(queryDataset.mock.calls.every((c: unknown[]) => (c[2] as { callerPackage?: string })?.callerPackage === 'crm')).toBe(true);
+ });
+
it('Add card appends a card and selects it', async () => {
mount();
await openEdit();
@@ -226,17 +254,50 @@ describe('DashboardView in-page edit (objectstack#36372)', () => {
});
mount();
await openEdit();
+ // Opening wrote nothing: the pair is asked for at Save.
+ expect(packages.ensured).toEqual([]);
fireEvent.click(screen.getByText('stub-rename'));
await act(async () => {
fireEvent.click(screen.getByTestId('dashboard-edit-save'));
});
+ expect(packages.ensured).toEqual(['crm']);
const [, , body, options] = client.value.save.mock.calls[0];
expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*', packageId: 'crm.custom' });
expect(body).toMatchObject({ label: 'Renamed (36372)', overrides: { package: 'crm', basedOn: '1.4.0' } });
expect(client.value.publish).toHaveBeenCalledWith('dashboard', 'ops_board', { packageId: 'crm.custom' });
});
+ it('Edit then Discard on an installed app creates no customization package and writes nothing', async () => {
+ packages.listed = new Map([['crm', { id: 'crm', writable: false, manifest: { id: 'crm', version: '1.4.0' } }]]);
+ gate.entry = { path: '/studio/crm', posture: 'view' };
+ mount();
+ await openEdit();
+ fireEvent.click(screen.getByText('stub-rename'));
+ fireEvent.click(screen.getByTestId('dashboard-edit-discard'));
+ expect(screen.queryByTestId('dashboard-editing-badge')).not.toBeInTheDocument();
+ expect(packages.ensured).toEqual([]);
+ expect(client.value.save).not.toHaveBeenCalled();
+ expect(client.value.publish).not.toHaveBeenCalled();
+ expect(client.value.reset).not.toHaveBeenCalled();
+ });
+
+ it('where the customization door is walled for this caller, an installed app\'s dashboard is not opened', async () => {
+ packages.listed = new Map([['crm', { id: 'crm', writable: false, manifest: { id: 'crm', version: '1.4.0' } }]]);
+ gate.entry = { path: '/studio/crm', posture: 'view' };
+ gate.walled = true;
+ mount();
+ const edit = await screen.findByTestId('dashboard-edit');
+ await act(async () => {
+ fireEvent.click(edit);
+ });
+ await waitFor(() => expect(toasts.error).toHaveLength(1));
+ expect(String((toasts.error[0] as unknown[])[0])).toContain('only the platform operator');
+ expect(screen.queryByTestId('dashboard-editing-badge')).not.toBeInTheDocument();
+ expect(packages.ensured).toEqual([]);
+ expect(client.value.layered).not.toHaveBeenCalled();
+ });
+
it('a draft already pending in the package refuses the edit state and writes nothing', async () => {
client.value = makeClient({ getDraft: vi.fn(async () => ({ item: { name: 'ops_board', label: 'Studio draft' } })) });
mount();
diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx
index 95a9124bc69..0da66322cf3 100644
--- a/ui/packages/app-shell/src/views/DashboardView.tsx
+++ b/ui/packages/app-shell/src/views/DashboardView.tsx
@@ -50,6 +50,7 @@ import {
useDashboardInPageEdit,
} from './DashboardInPageEditor.js';
import { useInSetupApp } from '../console/setupApp.js';
+import { useCustomizeDoorWalled } from './studio-design/StudioCustomizeControls.js';
/**
* One refresh of this dashboard's data: the `onRefresh` handed to
@@ -266,17 +267,21 @@ export function DashboardView({ dataSource }: { dataSource?: any }) {
(dashboard as any)?._packageId ?? (activeApp as any)?._packageId ?? null;
const editOffered = useDashboardEditOffered(ownerPackageId);
const metadataClient = useMetadataClient();
+ const customizeWalled = useCustomizeDoorWalled();
const edit = useDashboardInPageEdit({
name: dashboardName ?? '',
ownerPackageId,
client: metadataClient as any,
dataSource: adapter as any,
+ walled: customizeWalled,
});
const editing = edit.draft !== null;
const startEdit = async () => {
const refused = await edit.open();
if (!refused) return;
if (refused.reason === 'pending-draft') toast.error(tt('dashboard.inPageEdit.pendingDraft', 'This dashboard has unpublished changes in Studio. Publish or discard them there, then edit it here.'));
+ else if (refused.reason === 'walled') toast.error(tt('dashboard.inPageEdit.walled', "On this deployment, only the platform operator can customize an installed app's dashboard."));
+ else if (refused.reason === 'no-version') toast.error(tt('dashboard.inPageEdit.noVersion', 'The package list does not say which version of this app is installed, so its dashboard cannot be customized here.'));
else if (refused.reason === 'no-package') toast.error(tt('dashboard.inPageEdit.noPackage', "This dashboard cannot be saved here: its app has no package this account can customize."), refused.detail ? { description: refused.detail } : undefined);
else toast.error(tt('dashboard.inPageEdit.loadFailed', 'The dashboard could not be opened for editing'), refused.detail ? { description: refused.detail } : undefined);
};
@@ -304,6 +309,15 @@ export function DashboardView({ dataSource }: { dataSource?: any }) {
return { ...dashboard, widgets: filtered };
}, [dashboard, unregistered]);
+ // The edit buffer is the stored document, which carries none of the read's
+ // decorations: it is drawn with the served `_packageId` beside it, so its
+ // cards' dataset queries keep naming the dashboard's package as their reader
+ // (`callerPackage`, ADR-0150 D3), as in view mode. A save drops `_` keys.
+ const editSchema = useMemo(
+ () => (edit.draft ? { ...edit.draft, _packageId: (dashboard as { _packageId?: unknown } | undefined)?._packageId } : null),
+ [edit.draft, dashboard],
+ );
+
// ---- Loading / not-found guards -----------------------------------------
if (isLoading) {
return ;
@@ -466,7 +480,7 @@ export function DashboardView({ dataSource }: { dataSource?: any }) {
The edit state draws the stored document instead, every card
of it, so it resolves its own labels and prunes nothing. */}
{
const listed = (entries: Record) =>
@@ -399,13 +401,19 @@ describe('dashboard in-page save (objectstack#36372)', () => {
it('a dashboard of a writable package saves into that package, asking no pair', async () => {
const d = doors({ crm: { writable: true } });
- await expect(resolveDashboardSaveTarget('crm', d)).resolves.toEqual({ kind: 'package', packageId: 'crm' });
+ const target = await resolveDashboardEditTarget('crm', d);
+ expect(target).toEqual({ kind: 'package', packageId: 'crm' });
+ await expect(ensureDashboardSaveTarget(target as any, d)).resolves.toEqual({ kind: 'package', packageId: 'crm' });
expect(d.ensureCustomization).not.toHaveBeenCalled();
});
- it('a dashboard of a read-only (installed) package saves into its customization pair, based on the listed version', async () => {
+ it('a read-only (installed) package is read for its pair without creating one; the ensure door is asked at save', async () => {
const d = doors({ crm: { writable: false, version: '2.1.0' } });
- await expect(resolveDashboardSaveTarget('crm', d)).resolves.toEqual({
+ const target = await resolveDashboardEditTarget('crm', d);
+ // No pair listed yet: none is named, and none is made by reading.
+ expect(target).toEqual({ kind: 'customization', base: 'crm', basedOn: '2.1.0', pair: null });
+ expect(d.ensureCustomization).not.toHaveBeenCalled();
+ await expect(ensureDashboardSaveTarget(target as any, d)).resolves.toEqual({
kind: 'customization',
packageId: 'crm.custom',
base: 'crm',
@@ -414,23 +422,25 @@ describe('dashboard in-page save (objectstack#36372)', () => {
expect(d.ensureCustomization).toHaveBeenCalledWith('crm');
});
- it('is refused when the owner is not listed, the ensure door refuses, or the pair is not writable', async () => {
- await expect(resolveDashboardSaveTarget('crm', doors({}))).resolves.toMatchObject({ kind: 'refused' });
+ it('a pair the package list already lists is named for reading', async () => {
+ const d = doors({ crm: { writable: false, version: '2.1.0' }, 'crm.custom': { writable: true, version: '0.0.0' } });
+ await expect(resolveDashboardEditTarget('crm', d)).resolves.toMatchObject({ kind: 'customization', pair: 'crm.custom' });
+ expect(d.ensureCustomization).not.toHaveBeenCalled();
+ });
+
+ it('is refused when the owner is not listed; at save, when the ensure door refuses or the pair is not writable', async () => {
+ await expect(resolveDashboardEditTarget('crm', doors({}))).resolves.toMatchObject({ kind: 'refused' });
+ const target = { kind: 'customization' as const, base: 'crm', basedOn: '2.1.0', pair: null };
const refusing = vi.fn(async () => {
throw new Error('forbidden');
});
- await expect(resolveDashboardSaveTarget('crm', doors({ crm: { writable: false } }, refusing))).resolves.toEqual({
- kind: 'refused',
- reason: 'forbidden',
- });
+ await expect(ensureDashboardSaveTarget(target, { ensureCustomization: refusing })).rejects.toThrow('forbidden');
const readOnlyPair = vi.fn(async () => ({ packageId: 'crm.custom', writable: false }));
- await expect(resolveDashboardSaveTarget('crm', doors({ crm: { writable: false } }, readOnlyPair))).resolves.toMatchObject({
- kind: 'refused',
- });
+ await expect(ensureDashboardSaveTarget(target, { ensureCustomization: readOnlyPair })).rejects.toThrow('not writable');
});
it('a dashboard naming no package is saved where it lives', async () => {
- await expect(resolveDashboardSaveTarget(null, doors({}))).resolves.toEqual({ kind: 'unbound' });
+ await expect(resolveDashboardEditTarget(null, doors({}))).resolves.toEqual({ kind: 'unbound' });
});
it('the body drops the read\'s `_` keys, and into a pair declares the override of its base', () => {
diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
index 5a2d30c22ce..e48fc37401e 100644
--- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
+++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts
@@ -43,7 +43,7 @@ import { emitMetadataRefresh } from '../assistant/assistantBus.js';
import { slugify } from './metadata-admin/createDerive.js';
import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js';
import { ensureCustomizationPackage, fetchListedPackageManifests } from './studio-design/packages-io.js';
-import { listedPackageVersion, type ListedPackageManifest } from './studio-design/packages-io.js';
+import { listedCustomizationPairOf, listedPackageVersion, type ListedPackageManifest } from './studio-design/packages-io.js';
import { overrideDraftBody } from './studio-design/StudioCustomizeControls.js';
/** The runtime-editable artifact types ADR-0034 unifies. `page` (a record
@@ -567,23 +567,34 @@ export async function saveAndPublishRuntimeMetadata(
}
/**
- * objectstack#36372 — where a dashboard edited on its own page is saved: the
- * package that owns it when that package is writable, else the app's
- * customization package ` .custom` (ADR-0146 D2/D3), asked of the ensure
- * door, the layer Studio's Customize writes. `refused` when neither can be
- * had (the owner is not listed, the ensure door refuses, or the pair it
- * answers is not writable): the editor then offers no save.
+ * objectstack#36372 — where a dashboard edited on its own page would be
+ * saved, as read when the edit state opens: the package that owns it when
+ * that package is writable, else the app's customization package
+ * ` .custom` (ADR-0146 D2/D3), the layer Studio's Customize writes.
+ * `refused` when the owner is not listed (or the list cannot be read).
+ *
+ * Read only: opening writes nothing. A customization target names the pair
+ * only when the package list already lists it (`listedCustomizationPairOf`,
+ * the read Studio makes of a pair); the pair is asked of the ensure door,
+ * which creates it on first use, at Save and never before
+ * ({@link ensureDashboardSaveTarget}).
*
* `unbound` is a dashboard that names no package: it is saved where it lives,
* naming none.
*/
-export type DashboardSaveTarget =
+export type DashboardEditTarget =
| { kind: 'unbound' }
| { kind: 'package'; packageId: string }
- | { kind: 'customization'; packageId: string; base: string; basedOn: string | null }
+ | { kind: 'customization'; base: string; basedOn: string | null; pair: string | null }
| { kind: 'refused'; reason: string };
-/** The two package doors {@link resolveDashboardSaveTarget} asks. */
+/** Where a save lands, once the ensure door has answered for a customization. */
+export type DashboardSaveTarget =
+ | { kind: 'unbound' }
+ | { kind: 'package'; packageId: string }
+ | { kind: 'customization'; packageId: string; base: string; basedOn: string | null };
+
+/** The two package doors the in-page editor asks: the list to read, the ensure door to write. */
export interface DashboardSaveTargetDoors {
listPackages: () => Promise>>;
ensureCustomization: (basePackageId: string) => Promise<{ packageId: string; writable: boolean }>;
@@ -594,11 +605,11 @@ const DASHBOARD_TARGET_DOORS: DashboardSaveTargetDoors = {
ensureCustomization: ensureCustomizationPackage,
};
-/** {@link DashboardSaveTarget} for a dashboard `ownerPackageId` owns. */
-export async function resolveDashboardSaveTarget(
+/** {@link DashboardEditTarget} for a dashboard `ownerPackageId` owns. Reads the package list only. */
+export async function resolveDashboardEditTarget(
ownerPackageId: string | null | undefined,
- doors: DashboardSaveTargetDoors = DASHBOARD_TARGET_DOORS,
-): Promise {
+ doors: Pick = DASHBOARD_TARGET_DOORS,
+): Promise {
if (!ownerPackageId) return { kind: 'unbound' };
let listed: ReadonlyMap>;
try {
@@ -609,18 +620,30 @@ export async function resolveDashboardSaveTarget(
const owner = listed.get(ownerPackageId);
if (!owner) return { kind: 'refused', reason: `The package '${ownerPackageId}' is not listed.` };
if (owner.writable) return { kind: 'package', packageId: ownerPackageId };
- try {
- const pair = await doors.ensureCustomization(ownerPackageId);
- if (!pair.writable) return { kind: 'refused', reason: `The customization package '${pair.packageId}' is not writable.` };
- return {
- kind: 'customization',
- packageId: pair.packageId,
- base: ownerPackageId,
- basedOn: listedPackageVersion(listed as ReadonlyMap, ownerPackageId),
- };
- } catch (err) {
- return { kind: 'refused', reason: err instanceof Error ? err.message : String(err) };
- }
+ const manifests = listed as ReadonlyMap;
+ return {
+ kind: 'customization',
+ base: ownerPackageId,
+ basedOn: listedPackageVersion(manifests, ownerPackageId),
+ pair: listedCustomizationPairOf(manifests, ownerPackageId),
+ };
+}
+
+/**
+ * The {@link DashboardSaveTarget} a save writes to. A customization asks the
+ * ensure door for the pair here, at Save, the first write of the edit (the
+ * door creates the pair on first use, as Studio's first saved customization
+ * does). Throws the door's refusal, or when the pair it answers is not
+ * writable: nothing has been written then.
+ */
+export async function ensureDashboardSaveTarget(
+ target: Exclude,
+ doors: Pick = DASHBOARD_TARGET_DOORS,
+): Promise {
+ if (target.kind !== 'customization') return target;
+ const pair = await doors.ensureCustomization(target.base);
+ if (!pair.writable) throw new Error(`The customization package '${pair.packageId}' is not writable.`);
+ return { kind: 'customization', packageId: pair.packageId, base: target.base, basedOn: target.basedOn };
}
/**
@@ -628,11 +651,12 @@ export async function resolveDashboardSaveTarget(
* keys (the read's decorations belong to the served item), and, into a
* customization package, declaring the override of its base
* (`overrideDraftBody`, the body Studio's Customize writes). `null` when an
- * override is owed and there is no version to declare it at.
+ * override is owed and there is no version to declare it at: the edit state
+ * is refused up front for that (`'no-version'`), as Studio's Customize is.
*/
export function dashboardSaveBody(
doc: Record,
- target: Exclude,
+ target: Exclude | DashboardSaveTarget,
): Record | null {
if (target.kind === 'customization') return overrideDraftBody(doc, target.base, target.basedOn);
const body: Record = {};
@@ -654,7 +678,7 @@ export function dashboardSaveBody(
export async function saveDashboardInPlace(
name: string,
body: Record,
- target: Exclude,
+ target: DashboardSaveTarget,
ctx: RuntimePersistCtx,
): Promise {
if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('dashboard', name, body, ctx);
diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts
index f707ea6d9c5..620b5558057 100644
--- a/ui/packages/i18n/src/locales/ar.ts
+++ b/ui/packages/i18n/src/locales/ar.ts
@@ -1966,6 +1966,8 @@ const ar = {
loadFailed: "تعذّر فتح لوحة القيادة للتحرير",
pendingDraft: "لهذه اللوحة تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم حرّرها هنا.",
noPackage: "لا يمكن حفظ لوحة القيادة هذه هنا: لا يملك تطبيقها حزمة يمكن لهذا الحساب تخصيصها.",
+ walled: "في هذا النشر، يمكن لمشغّل المنصة وحده تخصيص لوحة قيادة تطبيق مثبّت.",
+ noVersion: "لا تذكر قائمة الحزم الإصدار المثبّت من هذا التطبيق، لذا لا يمكن تخصيص لوحة القيادة الخاصة به هنا.",
resizeCard: "تغيير حجم البطاقة",
panelTitle: "الخصائص",
},
diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts
index e0baf1945fe..0d7a61db46a 100644
--- a/ui/packages/i18n/src/locales/de.ts
+++ b/ui/packages/i18n/src/locales/de.ts
@@ -1734,6 +1734,8 @@ const de = {
loadFailed: "Das Dashboard konnte nicht zum Bearbeiten geöffnet werden",
pendingDraft: "Dieses Dashboard hat unveröffentlichte Änderungen in Studio. Veröffentlichen oder verwerfen Sie sie dort und bearbeiten Sie es dann hier.",
noPackage: "Dieses Dashboard kann hier nicht gespeichert werden: Seine App hat kein Paket, das dieses Konto anpassen kann.",
+ walled: "In dieser Bereitstellung kann nur der Plattformbetreiber das Dashboard einer installierten App anpassen.",
+ noVersion: "Die Paketliste gibt nicht an, welche Version dieser App installiert ist, daher kann ihr Dashboard hier nicht angepasst werden.",
resizeCard: "Kartengröße ändern",
panelTitle: "Eigenschaften",
},
diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts
index a8c7da5de2c..41db02c33f3 100644
--- a/ui/packages/i18n/src/locales/en.ts
+++ b/ui/packages/i18n/src/locales/en.ts
@@ -2270,6 +2270,8 @@ const en = {
loadFailed: 'The dashboard could not be opened for editing',
pendingDraft: 'This dashboard has unpublished changes in Studio. Publish or discard them there, then edit it here.',
noPackage: 'This dashboard cannot be saved here: its app has no package this account can customize.',
+ walled: "On this deployment, only the platform operator can customize an installed app's dashboard.",
+ noVersion: 'The package list does not say which version of this app is installed, so its dashboard cannot be customized here.',
resizeCard: 'Resize card',
panelTitle: 'Properties',
},
diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts
index 7d5170f10b7..07b7367ebb5 100644
--- a/ui/packages/i18n/src/locales/es.ts
+++ b/ui/packages/i18n/src/locales/es.ts
@@ -1794,6 +1794,8 @@ const es = {
loadFailed: "No se pudo abrir el panel de control para editarlo",
pendingDraft: "Este panel de control tiene cambios sin publicar en Studio. Publícalos o descártalos allí y luego edítalo aquí.",
noPackage: "Este panel de control no se puede guardar aquí: su aplicación no tiene un paquete que esta cuenta pueda personalizar.",
+ walled: "En esta implementación, solo el operador de la plataforma puede personalizar el panel de control de una aplicación instalada.",
+ noVersion: "La lista de paquetes no indica qué versión de esta aplicación está instalada, así que su panel de control no se puede personalizar aquí.",
resizeCard: "Cambiar el tamaño de la tarjeta",
panelTitle: "Propiedades",
},
diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts
index faa3ce18b1a..b6c172b4310 100644
--- a/ui/packages/i18n/src/locales/fr.ts
+++ b/ui/packages/i18n/src/locales/fr.ts
@@ -1790,6 +1790,8 @@ const fr = {
loadFailed: "Le tableau de bord n’a pas pu être ouvert pour modification",
pendingDraft: "Ce tableau de bord a des modifications non publiées dans Studio. Publiez-les ou abandonnez-les là-bas, puis modifiez-le ici.",
noPackage: "Ce tableau de bord ne peut pas être enregistré ici : son application n’a aucun paquet que ce compte peut personnaliser.",
+ walled: "Sur ce déploiement, seul l’opérateur de la plateforme peut personnaliser le tableau de bord d’une application installée.",
+ noVersion: "La liste des paquets n’indique pas quelle version de cette application est installée : son tableau de bord ne peut donc pas être personnalisé ici.",
resizeCard: "Redimensionner la carte",
panelTitle: "Propriétés",
},
diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts
index 51084bc5a32..7b7c65ab08a 100644
--- a/ui/packages/i18n/src/locales/ja.ts
+++ b/ui/packages/i18n/src/locales/ja.ts
@@ -1734,6 +1734,8 @@ const ja = {
loadFailed: "ダッシュボードを編集用に開けませんでした",
pendingDraft: "このダッシュボードには Studio に未公開の変更があります。そちらで公開または破棄してから、ここで編集してください。",
noPackage: "このダッシュボードはここでは保存できません。このアカウントがカスタマイズできるパッケージがアプリにありません。",
+ walled: "このデプロイでは、インストール済みアプリのダッシュボードをカスタマイズできるのはプラットフォーム運営者だけです。",
+ noVersion: "パッケージ一覧にこのアプリのインストール済みバージョンが示されていないため、ここではダッシュボードをカスタマイズできません。",
resizeCard: "カードのサイズを変更",
panelTitle: "プロパティ",
},
diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts
index 4943d1a373f..04af09fd0ec 100644
--- a/ui/packages/i18n/src/locales/ko.ts
+++ b/ui/packages/i18n/src/locales/ko.ts
@@ -1734,6 +1734,8 @@ const ko = {
loadFailed: "편집할 대시보드를 열 수 없습니다",
pendingDraft: "이 대시보드에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 여기서 편집하세요.",
noPackage: "이 대시보드는 여기서 저장할 수 없습니다. 앱에 이 계정이 사용자 지정할 수 있는 패키지가 없습니다.",
+ walled: "이 배포에서는 플랫폼 운영자만 설치된 앱의 대시보드를 사용자 지정할 수 있습니다.",
+ noVersion: "패키지 목록에 이 앱의 설치된 버전이 나와 있지 않아 여기서는 대시보드를 사용자 지정할 수 없습니다.",
resizeCard: "카드 크기 조정",
panelTitle: "속성",
},
diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts
index 65ea1060f35..9474c25e8c5 100644
--- a/ui/packages/i18n/src/locales/pt-BR.ts
+++ b/ui/packages/i18n/src/locales/pt-BR.ts
@@ -1789,6 +1789,8 @@ const pt = {
loadFailed: "Não foi possível abrir o painel para edição",
pendingDraft: "Este painel tem alterações não publicadas no Studio. Publique ou descarte-as lá e depois edite-o aqui.",
noPackage: "Este painel não pode ser salvo aqui: o aplicativo dele não tem um pacote que esta conta possa personalizar.",
+ walled: "Nesta implantação, somente o operador da plataforma pode personalizar o painel de um aplicativo instalado.",
+ noVersion: "A lista de pacotes não informa qual versão deste aplicativo está instalada, então o painel dele não pode ser personalizado aqui.",
resizeCard: "Redimensionar cartão",
panelTitle: "Propriedades",
},
diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts
index 56c38ff90c7..061f1ea300f 100644
--- a/ui/packages/i18n/src/locales/ru.ts
+++ b/ui/packages/i18n/src/locales/ru.ts
@@ -1854,6 +1854,8 @@ const ru = {
loadFailed: "Не удалось открыть дашборд для редактирования",
pendingDraft: "В Studio есть неопубликованные изменения этого дашборда. Опубликуйте или отмените их там, затем редактируйте здесь.",
noPackage: "Этот дашборд нельзя сохранить здесь: у его приложения нет пакета, который эта учётная запись может настроить.",
+ walled: "В этом развертывании только оператор платформы может настраивать панель мониторинга установленного приложения.",
+ noVersion: "В списке пакетов не указана установленная версия этого приложения, поэтому его панель мониторинга нельзя настроить здесь.",
resizeCard: "Изменить размер карточки",
panelTitle: "Свойства",
},
diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts
index 3a2363477b4..b1bf111650a 100644
--- a/ui/packages/i18n/src/locales/zh-Hans.ts
+++ b/ui/packages/i18n/src/locales/zh-Hans.ts
@@ -1915,6 +1915,8 @@ const zh = {
loadFailed: '无法打开仪表盘进行编辑',
pendingDraft: '这个仪表盘在 Studio 里有未发布的改动。请先在那里发布或放弃,再在这里编辑。',
noPackage: '这个仪表盘不能在这里保存:它所在的应用没有这个账号能定制的软件包。',
+ walled: "在此部署中,只有平台运营方可以定制已安装应用的仪表盘。",
+ noVersion: "软件包列表没有给出此应用已安装的版本,因此无法在此定制它的仪表盘。",
resizeCard: '调整卡片大小',
panelTitle: '属性',
},
diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts
index 84516f779cd..b934594976f 100644
--- a/ui/packages/i18n/src/locales/zh-Hant.ts
+++ b/ui/packages/i18n/src/locales/zh-Hant.ts
@@ -1915,6 +1915,8 @@ const zhHant = {
loadFailed: '無法開啟儀表盤進行編輯',
pendingDraft: '這個儀表盤在 Studio 裡有未釋出的改動。請先在那裡釋出或放棄,再在這裡編輯。',
noPackage: '這個儀表盤不能在這裡儲存:它所在的應用沒有這個賬號能定製的軟體包。',
+ walled: "在此部署中,只有平台運營方可以定製已安裝應用的儀表盤。",
+ noVersion: "軟體包列表沒有給出此應用已安裝的版本,因此無法在此定製它的儀表盤。",
resizeCard: '調整卡片大小',
panelTitle: '屬性',
},
diff --git a/ui/packages/plugin-dashboard/README.md b/ui/packages/plugin-dashboard/README.md
index a3f8590518d..37489dfbf33 100644
--- a/ui/packages/plugin-dashboard/README.md
+++ b/ui/packages/plugin-dashboard/README.md
@@ -518,7 +518,9 @@ Notes:
Every widget, in every mode, carries a small mark naming the dashboard
filters that do not reach it, for example "Not filtered by Region": a filter
it opts out of (`filterBindings[name]: false`) or one whose `targetWidgets`
-leaves it out. A widget every filter reaches carries none. The list is
+leaves it out. An explicit string binding (`filterBindings[name]: 'field'`)
+wins over `targetWidgets`, so a widget that names its field is reached even
+when the list leaves it out. A widget every filter reaches carries none. The list is
`dashboardFiltersNotApplied(widget, defs)` from `@object-ui/core`, which asks
`resolveBoundField`, the binding the widget's query is built from, so the
mark and the data cannot disagree.
diff --git a/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.filters.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.filters.test.tsx
index 1304a23cfeb..e326730c957 100644
--- a/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.filters.test.tsx
+++ b/ui/packages/plugin-dashboard/src/__tests__/DashboardRenderer.filters.test.tsx
@@ -260,6 +260,26 @@ describe('DashboardRenderer — the not-filtered mark agrees with the query (obj
expect(screen.queryByTestId('dashboard-widget-filter-mark-w1')).not.toBeInTheDocument();
});
+ it('names the built-in date filter "Date range", never its reserved name', async () => {
+ const queryDataset = makeQueryDataset();
+ const schema: DashboardComponentSchema = {
+ type: 'dashboard',
+ dateRange: { field: 'created_at', defaultRange: 'last_90_days' },
+ widgets: [
+ { id: 'w1', type: 'bar', dataset: 'invoices', values: ['count'] },
+ { id: 'w2', type: 'pie', dataset: 'accounts', values: ['count'], filterBindings: { dateRange: false } },
+ ],
+ } as DashboardComponentSchema;
+ render( );
+
+ await waitFor(() => expect(lastRuntimeFilter(queryDataset, 'invoices')).toHaveProperty('created_at'));
+ expect(lastRuntimeFilter(queryDataset, 'accounts')).toBeUndefined();
+ const mark = screen.getByTestId('dashboard-widget-filter-mark-w2');
+ expect(mark).toHaveAttribute('data-filters', 'dateRange');
+ expect(mark).toHaveTextContent('Not filtered by Date range');
+ expect(screen.queryByTestId('dashboard-widget-filter-mark-w1')).not.toBeInTheDocument();
+ });
+
it('draws no mark on a dashboard that declares no filters', async () => {
const queryDataset = makeQueryDataset();
const schema: DashboardComponentSchema = {
diff --git a/ui/packages/plugin-dashboard/src/designAffordances.tsx b/ui/packages/plugin-dashboard/src/designAffordances.tsx
index 1cee1a4a7cd..93381cfd813 100644
--- a/ui/packages/plugin-dashboard/src/designAffordances.tsx
+++ b/ui/packages/plugin-dashboard/src/designAffordances.tsx
@@ -53,7 +53,17 @@ export function WidgetFilterMark({
const { t, language } = useObjectTranslation();
const labelOf = useDashboardFilterLabeler();
if (defs.length === 0) return null;
- const names = listOf(defs.map((def) => labelOf(def) || def.name), language);
+ // The bar's fallbacks: an unlabelled built-in date filter reads the
+ // translated "Date range" (never its reserved name `dateRange`), any other
+ // filter its `name`.
+ const names = listOf(
+ defs.map(
+ (def) =>
+ labelOf(def) ||
+ (def.type === 'dateRange' ? t('dashboard.filters.dateRange', { defaultValue: 'Date range' }) : def.name),
+ ),
+ language,
+ );
const text = t('dashboard.filters.notApplied', { filters: names, defaultValue: 'Not filtered by {{filters}}' });
return (