diff --git a/.changeset/36372-dashboard-in-page-edit.md b/.changeset/36372-dashboard-in-page-edit.md
new file mode 100644
index 00000000000..d29ad0796c2
--- /dev/null
+++ b/.changeset/36372-dashboard-in-page-edit.md
@@ -0,0 +1,18 @@
+---
+'@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`), 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`, 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 (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 ce67666a511..3afdc083c72 100644
--- a/content/docs/frontend/plugins/plugin-dashboard.mdx
+++ b/content/docs/frontend/plugins/plugin-dashboard.mdx
@@ -143,6 +143,37 @@ 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. 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.
+
+## 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/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) => ({
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..0c23fda3e3e
--- /dev/null
+++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts
@@ -0,0 +1,153 @@
+/**
+ * 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';
+// 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,
+ withAddedWidget,
+ withResizedWidget,
+} from './DashboardInPageEditor';
+
+/**
+ * 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 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' }] };
+
+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: doors(true) })).resolves.toEqual({
+ kind: 'ready',
+ target: { kind: 'package', packageId: 'crm' },
+ doc: stored,
+ });
+ expect(client.getDraft).toHaveBeenCalledWith('dashboard', 'exec', { packageId: 'crm' });
+ });
+
+ 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 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: 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: 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: 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..0a27b679ebb
--- /dev/null
+++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx
@@ -0,0 +1,475 @@
+/**
+ * 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 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. 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
+ * 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,
+ ensureDashboardSaveTarget,
+ resolveDashboardEditTarget,
+ saveDashboardInPlace,
+ unwrapDraftBody,
+ type DashboardEditTarget,
+ 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';
+
+/** 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: WritableDashboardEditTarget; doc: Record }
+ | { kind: 'refused'; reason: DashboardEditRefusal; 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;
+}
+
+/** 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 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,
+ options: DashboardEditOpenOptions = {},
+): Promise {
+ const target = await resolveDashboardEditTarget(ownerPackageId, options.doors);
+ if (target.kind === 'refused') return { kind: 'refused', reason: 'no-package', detail: target.reason };
+ 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 (at && unwrapDraftBody(await client.getDraft('dashboard', name, at))) {
+ return { kind: 'refused', reason: 'pending-draft' };
+ }
+ 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) };
+ }
+}
+
+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 (
+
+ );
+}
+
+/** 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 (
+
+
+
+
+
+ );
+}
+
+/**
+ * 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 (
+
+ );
+}
+
+/** 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,
+ 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: WritableDashboardEditTarget;
+ 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, walled });
+ 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, walled]);
+
+ 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 {
+ // 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,
+ });
+ if (outcome === 'published') {
+ setSession(null);
+ setSelection(null);
+ }
+ return outcome;
+ } finally {
+ setSaving(false);
+ }
+ }, [session, name, client, dataSource, doors]);
+
+ 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..9fbd6cec533
--- /dev/null
+++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx
@@ -0,0 +1,325 @@
+/**
+ * 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, 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.
+ *
+ * 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';
+// 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' }, 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[] }));
+
+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.ensured.push(base);
+ return packages.ensure!(base);
+ },
+}));
+vi.mock('./studio-design/StudioCustomizeControls', async (importOriginal) => ({
+ ...(await importOriginal>()),
+ useCustomizeDoorWalled: () => gate.walled,
+}));
+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) =>