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) =>
{p.selection.id}
, +})); +vi.mock('./metadata-admin/inspectors/DashboardDefaultInspector', () => ({ + DashboardDefaultInspector: (p: any) => ( +
+ +
+ ), +})); +vi.mock('./metadata-admin/previews/AddWidgetPicker', () => ({ + AddWidgetPicker: (p: any) => ( + + ), +})); + +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 (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 } }], +}; + +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(dashboard: Record = served, dataSource?: object) { + meta.value = { + apps: [], + objects: [], + dashboards: [dashboard], + 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' }; + 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 = []; +}); + +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('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(); + 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(); + // 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(); + 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..0da66322cf3 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,7 +40,17 @@ 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'; +import { useCustomizeDoorWalled } from './studio-design/StudioCustomizeControls.js'; /** * One refresh of this dashboard's data: the `onRefresh` handed to @@ -193,12 +205,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 +261,41 @@ 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 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); + }; + 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; @@ -254,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 ; @@ -364,9 +428,21 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { `hideHeaderText` already suppresses. */} } - actions={refreshState && ( + badge={editing ? : undefined} + actions={editing ? ( + + ) : (refreshState || editOffered) && ( +
+ {editOffered && } + {refreshState && ( + )} +
)} /> @@ -388,24 +466,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 } }); + 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 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' } }); + 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', + basedOn: '2.1.0', + }); + expect(d.ensureCustomization).toHaveBeenCalledWith('crm'); + }); + + 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(ensureDashboardSaveTarget(target, { ensureCustomization: refusing })).rejects.toThrow('forbidden'); + const readOnlyPair = vi.fn(async () => ({ packageId: 'crm.custom', writable: false })); + await expect(ensureDashboardSaveTarget(target, { ensureCustomization: readOnlyPair })).rejects.toThrow('not writable'); + }); + + it('a dashboard naming no package is saved where it lives', async () => { + 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', () => { + 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..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,6 +43,8 @@ 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 { 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 * `PageSchema`) joins the original three (#1541): a record page is edited in @@ -563,3 +565,142 @@ export async function saveAndPublishRuntimeMetadata( announceDraftLedgerWrite(); return 'published'; } + +/** + * 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 DashboardEditTarget = + | { kind: 'unbound' } + | { kind: 'package'; packageId: string } + | { kind: 'customization'; base: string; basedOn: string | null; pair: string | null } + | { kind: 'refused'; reason: string }; + +/** 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 }>; +} + +const DASHBOARD_TARGET_DOORS: DashboardSaveTargetDoors = { + listPackages: fetchListedPackageManifests, + ensureCustomization: ensureCustomizationPackage, +}; + +/** {@link DashboardEditTarget} for a dashboard `ownerPackageId` owns. Reads the package list only. */ +export async function resolveDashboardEditTarget( + ownerPackageId: string | null | undefined, + doors: Pick = 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 }; + 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 }; +} + +/** + * 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: the edit state + * is refused up front for that (`'no-version'`), as Studio's Customize is. + */ +export function dashboardSaveBody( + doc: Record, + target: Exclude | DashboardSaveTarget, +): 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: DashboardSaveTarget, + ctx: RuntimePersistCtx, +): Promise { + 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 }), + }; +} 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..26bf2effce1 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: Array[0]> = [ + { id: 'w_default' }, + { 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' } }, + ]; + + 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. diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 960bb5b64d4..620b5558057 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1951,6 +1951,26 @@ const ar = { allWidgetsForbiddenMessage: "ليست لديك صلاحية لعرض البيانات الخاصة بلوحة التحكم هذه.", details: "التفاصيل", openInList: "فتح في القائمة", + inPageEdit: { + edit: "تحرير", + editLabel: "تحرير لوحة القيادة هذه", + editing: "قيد التحرير", + hint: "تسري التغييرات المحفوظة على الجميع فورًا", + addCard: "إضافة بطاقة", + discard: "تجاهل", + save: "حفظ", + saving: "جارٍ الحفظ…", + saved: "تم حفظ لوحة القيادة", + saveFailed: "تعذّر حفظ لوحة القيادة", + loading: "جارٍ فتح لوحة القيادة للتحرير…", + loadFailed: "تعذّر فتح لوحة القيادة للتحرير", + pendingDraft: "لهذه اللوحة تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم حرّرها هنا.", + noPackage: "لا يمكن حفظ لوحة القيادة هذه هنا: لا يملك تطبيقها حزمة يمكن لهذا الحساب تخصيصها.", + walled: "في هذا النشر، يمكن لمشغّل المنصة وحده تخصيص لوحة قيادة تطبيق مثبّت.", + noVersion: "لا تذكر قائمة الحزم الإصدار المثبّت من هذا التطبيق، لذا لا يمكن تخصيص لوحة القيادة الخاصة به هنا.", + resizeCard: "تغيير حجم البطاقة", + panelTitle: "الخصائص", + }, filters: { label: "عوامل تصفية لوحة المعلومات", dateRange: "النطاق الزمني", @@ -1958,6 +1978,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..0d7a61db46a 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1719,6 +1719,26 @@ 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.", + 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", + }, filters: { label: "Dashboard-Filter", dateRange: "Zeitraum", @@ -1726,6 +1746,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..41db02c33f3 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2255,6 +2255,26 @@ 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.', + 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', + }, filters: { label: 'Dashboard filters', dateRange: 'Date range', @@ -2262,6 +2282,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..07b7367ebb5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1779,6 +1779,26 @@ 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.", + 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", + }, filters: { label: "Filtros del panel", dateRange: "Intervalo de fechas", @@ -1786,6 +1806,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..b6c172b4310 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1775,6 +1775,26 @@ 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.", + 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", + }, filters: { label: "Filtres du tableau de bord", dateRange: "Plage de dates", @@ -1782,6 +1802,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..7b7c65ab08a 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1719,6 +1719,26 @@ const ja = { allWidgetsForbiddenMessage: "このダッシュボードのデータを表示する権限がありません。", details: "詳細", openInList: "リストで開く", + inPageEdit: { + edit: "編集", + editLabel: "このダッシュボードを編集", + editing: "編集中", + hint: "保存した変更はすぐに全員に反映されます", + addCard: "カードを追加", + discard: "破棄", + save: "保存", + saving: "保存中…", + saved: "ダッシュボードを保存しました", + saveFailed: "ダッシュボードを保存できませんでした", + loading: "ダッシュボードを編集用に開いています…", + loadFailed: "ダッシュボードを編集用に開けませんでした", + pendingDraft: "このダッシュボードには Studio に未公開の変更があります。そちらで公開または破棄してから、ここで編集してください。", + noPackage: "このダッシュボードはここでは保存できません。このアカウントがカスタマイズできるパッケージがアプリにありません。", + walled: "このデプロイでは、インストール済みアプリのダッシュボードをカスタマイズできるのはプラットフォーム運営者だけです。", + noVersion: "パッケージ一覧にこのアプリのインストール済みバージョンが示されていないため、ここではダッシュボードをカスタマイズできません。", + resizeCard: "カードのサイズを変更", + panelTitle: "プロパティ", + }, filters: { label: "ダッシュボードのフィルター", dateRange: "期間", @@ -1726,6 +1746,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..04af09fd0ec 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1719,6 +1719,26 @@ const ko = { allWidgetsForbiddenMessage: "이 대시보드의 데이터를 볼 수 있는 권한이 없습니다.", details: "세부 정보", openInList: "목록에서 열기", + inPageEdit: { + edit: "편집", + editLabel: "이 대시보드 편집", + editing: "편집 중", + hint: "저장한 변경 사항은 모든 사용자에게 즉시 적용됩니다", + addCard: "카드 추가", + discard: "취소", + save: "저장", + saving: "저장 중…", + saved: "대시보드를 저장했습니다", + saveFailed: "대시보드를 저장할 수 없습니다", + loading: "편집할 대시보드를 여는 중…", + loadFailed: "편집할 대시보드를 열 수 없습니다", + pendingDraft: "이 대시보드에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 여기서 편집하세요.", + noPackage: "이 대시보드는 여기서 저장할 수 없습니다. 앱에 이 계정이 사용자 지정할 수 있는 패키지가 없습니다.", + walled: "이 배포에서는 플랫폼 운영자만 설치된 앱의 대시보드를 사용자 지정할 수 있습니다.", + noVersion: "패키지 목록에 이 앱의 설치된 버전이 나와 있지 않아 여기서는 대시보드를 사용자 지정할 수 없습니다.", + resizeCard: "카드 크기 조정", + panelTitle: "속성", + }, filters: { label: "대시보드 필터", dateRange: "기간", @@ -1726,6 +1746,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..9474c25e8c5 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1774,6 +1774,26 @@ 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.", + 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", + }, filters: { label: "Filtros do painel", dateRange: "Período", @@ -1781,6 +1801,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..061f1ea300f 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1839,6 +1839,26 @@ const ru = { allWidgetsForbiddenMessage: "У вас нет прав на просмотр данных этой панели.", details: "Подробности", openInList: "Открыть в списке", + inPageEdit: { + edit: "Изменить", + editLabel: "Изменить этот дашборд", + editing: "Редактирование", + hint: "Сохранённые изменения сразу видят все", + addCard: "Добавить карточку", + discard: "Отменить", + save: "Сохранить", + saving: "Сохранение…", + saved: "Дашборд сохранён", + saveFailed: "Не удалось сохранить дашборд", + loading: "Дашборд открывается для редактирования…", + loadFailed: "Не удалось открыть дашборд для редактирования", + pendingDraft: "В Studio есть неопубликованные изменения этого дашборда. Опубликуйте или отмените их там, затем редактируйте здесь.", + noPackage: "Этот дашборд нельзя сохранить здесь: у его приложения нет пакета, который эта учётная запись может настроить.", + walled: "В этом развертывании только оператор платформы может настраивать панель мониторинга установленного приложения.", + noVersion: "В списке пакетов не указана установленная версия этого приложения, поэтому его панель мониторинга нельзя настроить здесь.", + resizeCard: "Изменить размер карточки", + panelTitle: "Свойства", + }, filters: { label: "Фильтры дашборда", dateRange: "Период", @@ -1846,6 +1866,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..b1bf111650a 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1900,6 +1900,26 @@ const zh = { vsThisMonth: '较本月', vsThisQuarter: '较本季度', }, + inPageEdit: { + edit: '编辑', + editLabel: '编辑这个仪表盘', + editing: '编辑中', + hint: '保存后所有人立刻看到', + addCard: '添加卡片', + discard: '放弃', + save: '保存', + saving: '保存中…', + saved: '仪表盘已保存', + saveFailed: '仪表盘没有保存成功', + loading: '正在打开仪表盘以便编辑…', + loadFailed: '无法打开仪表盘进行编辑', + pendingDraft: '这个仪表盘在 Studio 里有未发布的改动。请先在那里发布或放弃,再在这里编辑。', + noPackage: '这个仪表盘不能在这里保存:它所在的应用没有这个账号能定制的软件包。', + walled: "在此部署中,只有平台运营方可以定制已安装应用的仪表盘。", + noVersion: "软件包列表没有给出此应用已安装的版本,因此无法在此定制它的仪表盘。", + resizeCard: '调整卡片大小', + panelTitle: '属性', + }, filters: { label: '仪表盘过滤器', dateRange: '日期范围', @@ -1907,6 +1927,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..b934594976f 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1900,6 +1900,26 @@ const zhHant = { vsThisMonth: '較本月', vsThisQuarter: '較本季度', }, + inPageEdit: { + edit: '編輯', + editLabel: '編輯這個儀表盤', + editing: '編輯中', + hint: '儲存後所有人立刻看到', + addCard: '新增卡片', + discard: '放棄', + save: '儲存', + saving: '儲存中…', + saved: '儀表盤已儲存', + saveFailed: '儀表盤沒有儲存成功', + loading: '正在開啟儀表盤以便編輯…', + loadFailed: '無法開啟儀表盤進行編輯', + pendingDraft: '這個儀表盤在 Studio 裡有未釋出的改動。請先在那裡釋出或放棄,再在這裡編輯。', + noPackage: '這個儀表盤不能在這裡儲存:它所在的應用沒有這個賬號能定製的軟體包。', + walled: "在此部署中,只有平台運營方可以定製已安裝應用的儀表盤。", + noVersion: "軟體包列表沒有給出此應用已安裝的版本,因此無法在此定製它的儀表盤。", + resizeCard: '調整卡片大小', + panelTitle: '屬性', + }, filters: { label: '儀表盤過濾器', dateRange: '日期範圍', @@ -1907,6 +1927,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..37489dfbf33 100644 --- a/ui/packages/plugin-dashboard/README.md +++ b/ui/packages/plugin-dashboard/README.md @@ -513,6 +513,37 @@ 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. 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. + ## 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 && ( + + )}
); } 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 && ) : ( {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 &&