From 4b888dc9cfe7b54d6ae25df01e44330427ff00ea Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 06:18:08 +0000 Subject: [PATCH 1/5] wip(list): a list's changes are a draft with Discard and Save (#35955) Claude-Session: https://claude.ai/code/session_01L6bhgUr9HRqChVQu82hqdz Co-authored-by: Claude --- .../app-shell/src/views/ListDraftActions.tsx | 170 ++++++++++++++ .../src/views/ListPersonalizedMarker.tsx | 153 ------------- .../app-shell/src/views/ObjectView.tsx | 101 +++++++-- .../app-shell/src/views/listDraftStore.ts | 208 ++++++++++++++++++ .../src/views/objectViewListRenderer.tsx | 86 +++++--- .../src/views/objectViewListUrlState.ts | 133 ++++++----- .../app-shell/src/views/personalViews.ts | 15 +- .../app-shell/src/views/userFilterUrlState.ts | 8 + ui/packages/i18n/src/locales/ar.ts | 16 +- ui/packages/i18n/src/locales/de.ts | 16 +- ui/packages/i18n/src/locales/en.ts | 16 +- ui/packages/i18n/src/locales/es.ts | 16 +- ui/packages/i18n/src/locales/fr.ts | 16 +- ui/packages/i18n/src/locales/ja.ts | 16 +- ui/packages/i18n/src/locales/ko.ts | 16 +- ui/packages/i18n/src/locales/pt-BR.ts | 16 +- ui/packages/i18n/src/locales/ru.ts | 16 +- ui/packages/i18n/src/locales/zh-Hans.ts | 16 +- ui/packages/i18n/src/locales/zh-Hant.ts | 16 +- 19 files changed, 745 insertions(+), 305 deletions(-) create mode 100644 ui/packages/app-shell/src/views/ListDraftActions.tsx delete mode 100644 ui/packages/app-shell/src/views/ListPersonalizedMarker.tsx create mode 100644 ui/packages/app-shell/src/views/listDraftStore.ts diff --git a/ui/packages/app-shell/src/views/ListDraftActions.tsx b/ui/packages/app-shell/src/views/ListDraftActions.tsx new file mode 100644 index 00000000000..97e0e45de54 --- /dev/null +++ b/ui/packages/app-shell/src/views/ListDraftActions.tsx @@ -0,0 +1,170 @@ +/** + * objectstack#35955 — Discard and Save on a Console list, drawn while the list + * holds a DRAFT: a change the reader made on the list (`./listDraftStore.ts`) + * that applies at once and is not saved anywhere. It replaces the + * 「Personalized · Reset」 marker (objectstack#28950) at the end of the + * condition row (objectstack#35878); with no draft the slot is empty. + * + * - **Discard** puts the list back as its view declares it (the host's + * `onDiscard`). + * - **Save** opens its choices: 「Save to this view」 (`onSaveToView`, offered + * only where the host may write the open view) and 「Save as my view」 + * (`onSaveAsMyView`, which asks a name first). The menu names what is + * unsaved, so a reader sees what a save keeps. + * + * As the list narrows (the phone list draws this same control in its chip + * row, objectstack#35883), the two faces fold into ONE Save whose menu also + * holds Discard: one control, one save path, at every width. + * + * Nothing here is configurable: no metadata key or option reaches it. + */ + +import { + Button, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, + cn, +} from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import type { ListViewProps } from '@object-ui/plugin-list'; +import { ChevronDown, CopyPlus, RotateCcw, Save } from 'lucide-react'; + +/** One part of a list that can differ from its view (`ListView`'s vocabulary). */ +export type ListPersonalizationPart = Parameters>[0][number]; + +/** The order the menu names the unsaved parts in: the toolbar's, then the Display panel's. */ +const LIST_DRAFT_PART_ORDER: readonly ListPersonalizationPart[] = [ + 'filters', + 'sort', + 'grouping', + 'columns', + 'hiddenFields', + 'layout', + 'rowColor', + 'inlineEdit', +]; + +export function ListDraftActions({ + parts, + onDiscard, + onSaveToView, + onSaveAsMyView, + className, +}: { + /** The list's unsaved parts; nothing is drawn while there is none. */ + parts: ReadonlyArray; + onDiscard: () => void; + /** Save the list into the open view; absent where the reader may not write it. */ + onSaveToView?: () => void; + /** Save the list as one of the reader's own views; absent where they may not create one. */ + onSaveAsMyView?: () => void; + className?: string; +}) { + const { t } = useObjectTranslation(); + if (parts.length === 0) return null; + const ordered = LIST_DRAFT_PART_ORDER.filter((part) => parts.includes(part)); + // Each label a literal key, so the i18n call-site and dead-key gates read it. + const partLabels: Record = { + filters: t('console.objectView.personalizedParts.filters'), + search: t('console.objectView.personalizedParts.search'), + sort: t('console.objectView.personalizedParts.sort'), + grouping: t('console.objectView.personalizedParts.grouping'), + columns: t('console.objectView.personalizedParts.columns'), + hiddenFields: t('console.objectView.personalizedParts.hiddenFields'), + density: t('console.objectView.personalizedParts.density'), + layout: t('console.objectView.personalizedParts.layout'), + rowColor: t('console.objectView.personalizedParts.rowColor'), + inlineEdit: t('console.objectView.personalizedParts.inlineEdit'), + }; + const discardLabel = t('console.objectView.draft.discard'); + const discardTitle = t('console.objectView.draft.discardTitle'); + const saveLabel = t('console.objectView.draft.save'); + const offersSave = !!onSaveToView || !!onSaveAsMyView; + + const saveItems = ( + <> + + {t('console.objectView.draft.heading')} + {': '} + {ordered.map((part) => partLabels[part]).join(t('console.objectView.draft.partSeparator'))} + + + {onSaveToView ? ( + onSaveToView()} data-testid="list-draft-save-to-view"> + + ) : null} + {onSaveAsMyView ? ( + onSaveAsMyView()} data-testid="list-draft-save-as"> + + ) : null} + + ); + + return ( + + {/* The wide face: Discard beside Save ▾. */} + + {offersSave ? ( + + + + + + {saveItems} + + + ) : null} + {/* The narrow face: one Save, whose menu also holds Discard. */} + + + + + + {offersSave ? saveItems : null} + {offersSave ? : null} + onDiscard()} data-testid="list-draft-compact-discard"> + + + + + ); +} diff --git a/ui/packages/app-shell/src/views/ListPersonalizedMarker.tsx b/ui/packages/app-shell/src/views/ListPersonalizedMarker.tsx deleted file mode 100644 index d6d59e339ab..00000000000 --- a/ui/packages/app-shell/src/views/ListPersonalizedMarker.tsx +++ /dev/null @@ -1,153 +0,0 @@ -/** - * objectstack#28950 — the 「Personalized」 marker of a Console list: drawn beside - * the list title while the reader's list differs from the view, and the ONE way - * back to the view. Opening it names what differs and offers a single reset, - * whose sentence says everything it puts back and what it leaves alone. - * - * The parts come from the list itself (`ListView`'s `onPersonalizationChange`) - * plus the host's stored column layout; the reset is the host's - * (`useObjectViewListUrlState`'s `handleResetView`). Nothing here is - * configurable: no metadata key or option reaches it. - * - * On one of the reader's own views (objectstack#30073) it also offers 保存 - * (`onSave`): the list on screen becomes the view's stored body. Edits not - * saved stay the reader's temporary list state, never written to the view. - * - * objectstack#35878 — it ends the condition row under the view bar: - * 「Personalized」 (the trigger, naming what differs) and 「Reset」 beside it, - * one click back to the view. As the list narrows the words 「Personalized」 - * go first, then 「Reset」 folds to its icon. - */ - -import { useState } from 'react'; -import { Button, Popover, PopoverContent, PopoverTrigger, cn } from '@object-ui/components'; -import { useObjectTranslation } from '@object-ui/i18n'; -import type { ListViewProps } from '@object-ui/plugin-list'; -import { RotateCcw, Save } from 'lucide-react'; - -/** One part of a list that can differ from its view (`ListView`'s vocabulary). */ -export type ListPersonalizationPart = Parameters>[0][number]; - -/** The order the marker names the parts in: the toolbar's, then the Display panel's. */ -const LIST_PERSONALIZATION_PART_ORDER: readonly ListPersonalizationPart[] = [ - 'filters', - 'search', - 'sort', - 'grouping', - 'columns', - 'hiddenFields', - 'density', - 'layout', - 'rowColor', - 'inlineEdit', -]; - -export function ListPersonalizedMarker({ - parts, - onReset, - onSave, - className, -}: { - parts: ReadonlyArray; - onReset: () => void; - /** Save the list on screen into the open view; offered only for a view the reader owns and may update. */ - onSave?: () => void; - className?: string; -}) { - const { t } = useObjectTranslation(); - const [open, setOpen] = useState(false); - if (parts.length === 0) return null; - const ordered = LIST_PERSONALIZATION_PART_ORDER.filter((part) => parts.includes(part)); - // Each label a literal key, so the i18n call-site and dead-key gates read it. - const partLabels: Record = { - filters: t('console.objectView.personalizedParts.filters'), - search: t('console.objectView.personalizedParts.search'), - sort: t('console.objectView.personalizedParts.sort'), - grouping: t('console.objectView.personalizedParts.grouping'), - columns: t('console.objectView.personalizedParts.columns'), - hiddenFields: t('console.objectView.personalizedParts.hiddenFields'), - density: t('console.objectView.personalizedParts.density'), - layout: t('console.objectView.personalizedParts.layout'), - rowColor: t('console.objectView.personalizedParts.rowColor'), - inlineEdit: t('console.objectView.personalizedParts.inlineEdit'), - }; - const label = t('console.objectView.personalized'); - // The short 「Reset」 of the condition row (the popover keeps its longer one). - const resetLabel = t('listConditions.chips.reset'); - return ( - - - - - - -

{t('console.objectView.personalizedHeading')}

-
    - {ordered.map((part) => ( -
  • - {partLabels[part]} -
  • - ))} -
- {onSave ? ( - - ) : null} -

{t('console.objectView.resetViewTitle')}

- -
-
- -
- ); -} diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 18e53fbec4e..f8a1fb735f5 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -96,10 +96,12 @@ import { } from './objectViewPageHeader.js'; import { ObjectViewRecordOverlay } from './objectViewRecordOverlay.js'; import { useObjectViewListRenderer } from './objectViewListRenderer.js'; -import { ListPersonalizedMarker } from './ListPersonalizedMarker.js'; +import { ListDraftActions } from './ListDraftActions.js'; +import { listDraftPreference, listDraftScope, useListDraft } from './listDraftStore.js'; import { useObjectViewViewCrud } from './objectViewViewCrud.js'; import { PERSONAL_VIEW_OBJECT, + buildInPlaceViewConfig, buildPersonalViewConfig, personalViewEntry, personalViewPanelFilters, @@ -724,6 +726,13 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co localizedToolbarActions, isEnvironmentList, }); + // objectstack#35955 — the open list's DRAFT: what the reader changed and + // has not saved (`./listDraftStore.ts`). It outlives this page while a + // record is open as a page, and goes when another view or object opens. + const listDraft = useListDraft(listDraftScope(user?.id, objectName ?? '', activeView?.id ? String(activeView.id) : '')); + /** The list on screen in the reader-state shape the view builders read (draft + kept widths and row height). */ + const draftPreferenceOf = (id: string | undefined) => + id ? listDraftPreference(listDraft.draft, listPrefs.preference.perView?.[id]) : undefined; // objectstack#25992 slice 8: the list's toolbar state in the URL (seed, write-back, // "Reset view") moved to `./objectViewListUrlState.ts`. const { @@ -732,7 +741,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co ownListParamsRef, writeListUrlState, handleListPersonalizationChange, - listPersonalizedParts, + listDraftParts, handleResetView, clearSourceListState, readPanelFilters, @@ -743,6 +752,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co activeView, viewResolving: awaitingPersonalViews, listPrefs, + listDraft: listDraft.draft, perms, user, searchParams, @@ -767,7 +777,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // The panel's group is the one the list shows (an emptied panel // included), not the address's copy of it. url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, - preference: listPrefs.preference.perView?.[activeView.id], + preference: draftPreferenceOf(activeView.id), panelFilters: viewPanelFilters, }); if (!built.ok) { @@ -776,7 +786,11 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co } try { await personalViews.update(activeView.id, built.config); + // objectstack#35955 — the draft is the view now: Discard and Save + // go, and the list opens again on the saved view (its sort and + // filter chips stay, the view carries them). handleResetView(); + toast.success(t('console.objectView.draft.saved')); } catch (err) { console.error('[ObjectView] Failed to save a personal view:', err); toast.error(t('form.saveError'), { @@ -785,11 +799,17 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co }); } }; - const personalizedMarker = !isEnvironmentList && listPersonalizedParts.length > 0 ? ( - { void handleSaveToPersonalView(); } : undefined} + // objectstack#35955 — Discard and Save while the list holds a draft, at + // the end of the condition row (the phone draws the same slot). 「Save to + // this view」 writes one of the reader's own views here; a shared view's + // save is not offered on the list yet. 「Save as my view」 asks a name. + const canSaveAsMyView = personalViewsReady && personalGrant('create') && !!activeView; + const draftActions = !isEnvironmentList && listDraftParts.length > 0 ? ( + { void handleSaveToPersonalView(); } : undefined} + onSaveAsMyView={canSaveAsMyView ? () => setPersonalViewDialog({ mode: 'saveAs' }) : undefined} /> ) : null; @@ -878,7 +898,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // `PersonalViewNameDialog`. A reader who cannot read the list's own object // is offered no create: there is no list to keep. const listReadable = !perms.isLoaded || perms.can(objectDef.name, 'read'); - const [personalViewDialog, setPersonalViewDialog] = useState<{ mode: 'rename'; viewId: string } | null>(null); + const [personalViewDialog, setPersonalViewDialog] = useState<{ mode: 'rename'; viewId: string } | { mode: 'saveAs' } | null>(null); const openPersonalView = (id: string) => { if (viewId) navigate(`../${id}`, { relative: 'path' }); else navigate(`view/${id}`); @@ -926,6 +946,44 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co const renamingPersonalView = personalViewDialog?.mode === 'rename' ? personalViews.views.find((v) => v.id === personalViewDialog.viewId) : undefined; + /** + * objectstack#35955 — 「Save as my view」: the list on screen (the open + * view's body with the draft laid over it, `buildInPlaceViewConfig` as + * the switcher's create card builds it) becomes one of the reader's own + * views under the name they gave, and opens. The view it came from loses + * the draft and opens as its own next time. + */ + const handleSaveAsMyView = async (label: string): Promise => { + if (!activeView) return false; + const built = buildInPlaceViewConfig( + objectDef.name, + activeView, + { type: String((activeView as any).type ?? 'grid') }, + { + url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, + preference: draftPreferenceOf(activeView.id), + panelFilters: viewPanelFilters, + }, + ); + if (!built.ok) { + toast.error(t('form.saveError'), { description: t(FILTER_FOLD_REFUSAL_KEYS[built.reason]) }); + return false; + } + try { + const id = await personalViews.save(label, built.config); + clearSourceListState(String(activeView.id)); + toast.success(t('console.objectView.draft.saved')); + openPersonalView(id); + return true; + } catch (err) { + console.error('[ObjectView] Failed to save a personal view:', err); + toast.error(t('form.saveError'), { + description: err instanceof Error ? err.message : String(err), + classNames: { description: 'whitespace-pre-line' }, + }); + return false; + } + }; // Current user — also used below for `{current_user_id}` filter-token // substitution. The schema-action handlers (toast/navigate/api/flow/server) @@ -1044,7 +1102,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co activeView, readListState: () => ({ url: { ...parseListStateParams(searchParams, acceptListField), filters: readPanelFilters() }, - preference: activeView ? listPrefs.preference.perView?.[activeView.id] : undefined, + preference: draftPreferenceOf(activeView?.id), panelFilters: viewPanelFilters, }), savePersonal: personalViews.save, @@ -1053,7 +1111,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co clearSourceListState, canCreatePersonal: personalViewsReady && personalGrant('create') && listReadable && !!activeView && !viewAccess.refusal, canCreateShared: isAdmin, - hasUnsavedConditions: listPersonalizedParts.some((part) => part === 'filters' || part === 'sort'), + hasUnsavedConditions: listDraftParts.some((part) => part === 'filters' || part === 'sort'), }, onRenamePersonalView: personalViewsReady && personalGrant('update') ? (id: string) => setPersonalViewDialog({ mode: 'rename', viewId: id }) @@ -1086,6 +1144,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co managedUserMarker, savedViews, listPrefs, + listDraft, derivedColumnViewIds, baseView, activeView, @@ -1121,7 +1180,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co ? : tools) : null, - conditionRowEnd: personalizedMarker, + conditionRowEnd: draftActions, handleListPersonalizationChange, urlFilters, initialUfSelections, @@ -1137,8 +1196,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co : activeView && isAdmin && !activeViewPackageRefusesSaves && savedViews.some((sv: any) => viewRowId(sv) === activeView.id) ? async (label: string) => { await handleRenameView(String(activeView.id), label); return true; } : undefined, - save: !isEnvironmentList && canUpdatePersonalView && listPersonalizedParts.length > 0 ? () => { void handleSaveToPersonalView(); } : undefined, - reset: !isEnvironmentList && listPersonalizedParts.length > 0 ? handleResetView : undefined, + save: !isEnvironmentList && canUpdatePersonalView && listDraftParts.length > 0 ? () => { void handleSaveToPersonalView(); } : undefined, + reset: !isEnvironmentList && listDraftParts.length > 0 ? handleResetView : undefined, // objectstack#35702 — the footer's calculation, saved on the open // view (ruling 7045525672): a personal view at once; a shared one, // by a reader who may edit it, as a draft through the view panel's @@ -1461,11 +1520,17 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co { if (!open) setPersonalViewDialog(null); }} - title={t('view.rename', { defaultValue: 'Rename' })} - initialName={renamingPersonalView?.label ?? ''} - onSubmit={(name) => (personalViewDialog + title={personalViewDialog?.mode === 'saveAs' + ? t('console.objectView.draft.saveAsMyView') + : t('view.rename', { defaultValue: 'Rename' })} + initialName={personalViewDialog?.mode === 'saveAs' + ? t('console.objectView.draft.copyName', { name: activeView?.label ?? '' }) + : renamingPersonalView?.label ?? ''} + onSubmit={(name) => (personalViewDialog?.mode === 'rename' ? handleRenamePersonalView(personalViewDialog.viewId, name) - : Promise.resolve(false))} + : personalViewDialog?.mode === 'saveAs' + ? handleSaveAsMyView(name) + : Promise.resolve(false))} t={t} /> diff --git a/ui/packages/app-shell/src/views/listDraftStore.ts b/ui/packages/app-shell/src/views/listDraftStore.ts new file mode 100644 index 00000000000..3961706a18f --- /dev/null +++ b/ui/packages/app-shell/src/views/listDraftStore.ts @@ -0,0 +1,208 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35955 — the list's DRAFT: what a reader changed on a Console list + * and has not saved. It applies at once and is kept nowhere durable — not in + * the reader's preferences, not in the view. The reader keeps it with Save + * (into the open view, or as a view of their own) or drops it with Discard. + * + * What a draft holds: the sort, the Filter panel's group, the grouping, the + * search term, the columns shown (hidden ones, added ones), the column order + * and the Display panel's layout and row colour. What it never holds: the + * column widths and the row height, which are remembered for the reader + * (`ListPreferencesProvider`), and the view tab order. + * + * ## How long it lives + * + * ONE draft at a time, for one reader, object and view (its `scope`), in this + * tab's memory: + * + * - opening a record (as a page or in the side panel) and coming back keeps + * it: the record page draws no list of this store, so nothing replaces it; + * - opening another view or another object replaces it (`claimListDraft` with + * another scope), with no prompt; + * - a reload loses it, the module's memory with it. The address's `uf_*` + * copy of the toolbar state is dropped on a reload too + * (`isDocumentReload`, read by the list's seed), so the list opens as its + * view declares it. + * + * Not React state: the list page unmounts while a record is open as a page, + * and the draft must outlive it. Readers subscribe through + * {@link useListDraft}. + * + * @module + */ + +import { useCallback, useSyncExternalStore } from 'react'; +import type { GroupingConfig } from '@objectstack/spec/ui'; +import type { + ListFilterGroupPreference, + ListSortPreference, + ListViewPreference, +} from '../context/ListPreferencesProvider.js'; + +/** A list's unsaved changes. An absent part is the view's own. */ +export interface ListDraft { + sort?: ListSortPreference[]; + filters?: ListFilterGroupPreference; + grouping?: GroupingConfig; + search?: string; + /** The grid's column order, as the reader dragged it. */ + columnOrder?: string[]; + /** The columns the reader hid: the whole list the Hide Fields popover emits. */ + hiddenFields?: string[]; + /** The object's fields the reader added as columns. */ + addedFields?: string[]; + /** The visualization the reader switched to (`ListView`'s layout control). */ + viewType?: string; + /** The row colour the reader picked, or `null` for "none" over a view that colours its rows. */ + rowColor?: { field: string; colors?: Record } | null; +} + +/** A patch: a part set to `undefined` is dropped back to the view's own. */ +export type ListDraftPatch = { [K in keyof ListDraft]?: ListDraft[K] | undefined }; + +interface Slot { + scope: string; + draft: ListDraft; +} + +const EMPTY_DRAFT: ListDraft = Object.freeze({}) as ListDraft; +let slot: Slot = { scope: '', draft: EMPTY_DRAFT }; +const listeners = new Set<() => void>(); + +function emit(): void { + for (const listener of listeners) listener(); +} + +/** The scope of one list's draft: the reader, the object and the view. */ +export function listDraftScope(userId: string | null | undefined, objectName: string, viewId: string): string { + return JSON.stringify([userId ?? '', objectName, viewId]); +} + +/** The draft held for `scope`, else the empty draft. */ +export function readListDraft(scope: string): ListDraft { + return slot.scope === scope ? slot.draft : EMPTY_DRAFT; +} + +/** + * The list for `scope` is the one on screen now: a draft held for any other + * list is dropped (another view or object was opened). Called once per list + * identity, where the list takes its seed. Does not notify: the caller is + * rendering, and a list that changed scope reads its own (empty) draft. + */ +export function claimListDraft(scope: string): void { + if (slot.scope !== scope) slot = { scope, draft: EMPTY_DRAFT }; +} + +function isEmptyPart(value: unknown): boolean { + return value === undefined; +} + +/** Lay `patch` over the draft of `scope`, claiming the scope when it is not held. */ +export function patchListDraft(scope: string, patch: ListDraftPatch): void { + const base = slot.scope === scope ? slot.draft : EMPTY_DRAFT; + const next: Record = { ...base }; + let changed = slot.scope !== scope; + for (const [key, value] of Object.entries(patch)) { + const before = (base as Record)[key]; + if (isEmptyPart(value)) { + if (key in next) { + delete next[key]; + changed = true; + } + continue; + } + if (JSON.stringify(before) !== JSON.stringify(value)) { + next[key] = value; + changed = true; + } + } + if (!changed) return; + slot = { scope, draft: next as ListDraft }; + emit(); +} + +/** Drop the draft of `scope` (Discard, or once it was saved). */ +export function discardListDraft(scope: string): void { + if (slot.scope !== scope || slot.draft === EMPTY_DRAFT) return; + slot = { scope, draft: EMPTY_DRAFT }; + emit(); +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +/** The draft of one list, and its writers. */ +export function useListDraft(scope: string): { + draft: ListDraft; + patch: (patch: ListDraftPatch) => void; + discard: () => void; +} { + const draft = useSyncExternalStore( + subscribe, + () => readListDraft(scope), + () => readListDraft(scope), + ); + const patch = useCallback((p: ListDraftPatch) => patchListDraft(scope, p), [scope]); + const discard = useCallback(() => discardListDraft(scope), [scope]); + return { draft, patch, discard }; +} + +/** + * Was this document opened by a reload? Read once per document: only the + * first list this page seeds is the one the reload asked for again; every + * later one was navigated to inside the app. + */ +let reloadConsumed = false; +export function takeDocumentReload(): boolean { + if (reloadConsumed) return false; + reloadConsumed = true; + try { + const entry = typeof performance !== 'undefined' && typeof performance.getEntriesByType === 'function' + ? (performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined) + : undefined; + return entry?.type === 'reload'; + } catch { + return false; + } +} + +/** + * The list's state in the reader-state shape the list relay and the view + * builders read (`ListViewPreference`): the draft's columns, their order and + * its sort and filters, with the two parts kept for the reader — the column + * widths and the row height — from what they stored. Nothing else they + * stored is read: a sort, filter, column order or hidden column stored + * before objectstack#35955 no longer applies. + */ +export function listDraftPreference( + draft: ListDraft, + stored: ListViewPreference | undefined, +): ListViewPreference | undefined { + const widths = stored?.columnState?.widths; + const out: ListViewPreference = {}; + if (draft.sort) out.sort = draft.sort; + if (draft.filters) out.filters = draft.filters; + if (draft.hiddenFields) out.hiddenFields = draft.hiddenFields; + if (draft.addedFields?.length) out.addedFields = draft.addedFields; + if (draft.columnOrder || widths) { + out.columnState = { + ...(draft.columnOrder ? { order: draft.columnOrder } : {}), + ...(widths ? { widths } : {}), + }; + } + if (stored?.rowHeight) out.rowHeight = stored.rowHeight; + return Object.keys(out).length > 0 ? out : undefined; +} + +/** Test seam: forget the held draft and the reload read. */ +export function resetListDraftStoreForTests(): void { + slot = { scope: '', draft: EMPTY_DRAFT }; + reloadConsumed = false; + emit(); +} diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index c75a5710d3f..c8000e5806f 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -11,7 +11,7 @@ import type { ColumnSummary } from '@objectstack/spec/ui'; import { useCallback, useLayoutEffect, useRef, useState, useSyncExternalStore, lazy, Suspense, type ReactNode } from 'react'; import { DENSITY_MODE_TO_ROW_HEIGHT, columnIdentity, normalizeListViewSchema, servedPackageId, type FilterTokenScope } from '@object-ui/core'; -import { buildListFilterKey, writeListFilterState } from './listFilterStorage.js'; +import { listDraftPreference, type useListDraft } from './listDraftStore.js'; import type { useObjectListPreferences, ListViewPreference, ListViewPreferencePatch } from '../context/ListPreferencesProvider.js'; const ObjectChart = lazy(() => import('@object-ui/plugin-charts').then((m) => ({ default: m.ObjectChart })), @@ -87,6 +87,7 @@ export function useObjectViewListRenderer({ managedUserMarker, savedViews, listPrefs, + listDraft, derivedColumnViewIds, baseView, activeView, @@ -125,6 +126,8 @@ export function useObjectViewListRenderer({ managedUserMarker: ReturnType['managedUserMarker']; savedViews: Parameters[0]['savedViews']; listPrefs: ReturnType; + /** objectstack#35955 — the open list's unsaved changes, and their writer. */ + listDraft: ReturnType; derivedColumnViewIds: Set; baseView: ReturnType[number]; activeView: ReturnType[number]; @@ -322,21 +325,27 @@ export function useObjectViewListRenderer({ const identityKey = listIdentityKey ?? `${objectName}-${activeView.id}`; const viewDef = activeView; - // Per-user, per-view search-term cache. Restored into ListView at mount - // so leaving via a nav link and coming back keeps what the user was - // searching — URL params alone don't survive that (the nav link has no - // query string). Keyed on the signed-in user so two accounts on one - // browser never share it. The Filter panel's conditions are the user's - // list state since objectui#12418 (`listPrefs`), not this cache. - const listFilterKey = buildListFilterKey(user?.id, objectName, activeView.id); - // objectui#12418 — this user's own state for this view: its sort and - // filters arrive through the seed below, its column layout here. - const viewPref: ListViewPreference | undefined = listPrefs.preference.perView?.[viewDef.id]; + // objectstack#35955 — the list's DRAFT (`./listDraftStore.ts`): its + // sort, filters, grouping and search arrive through the seed below, + // its columns and their order here. The column widths and the row + // height are the reader's own (`listPrefs`), never a draft: they are + // laid in from what the reader stored, and nothing else stored is. + const viewPref: ListViewPreference | undefined = listDraftPreference( + listDraft.draft, + listPrefs.preference.perView?.[viewDef.id], + ); const persistListSort = (sort: Array<{ field: string; order?: string }>) => { - listPrefs.patchView(viewDef.id, { sort }); + listDraft.patch({ sort: sort as ListViewPreference['sort'] }); }; + // One report carries the order and the widths: the order is a draft, + // the widths are kept for the reader (a drag that changed only a width + // hands back the order the draft already holds). const persistListColumnState = (state: { order?: string[]; widths?: Record }) => { - listPrefs.patchView(viewDef.id, { columnState: state }); + listDraft.patch({ columnOrder: state.order && state.order.length > 0 ? state.order : undefined }); + const storedWidths = listPrefs.preference.perView?.[viewDef.id]?.columnState?.widths; + if (JSON.stringify(state.widths ?? {}) !== JSON.stringify(storedWidths ?? {})) { + listPrefs.patchView(viewDef.id, { columnState: state.widths ? { widths: state.widths } : null }); + } }; // objectui#11860 — what the list opens with: the URL's state, else this // cache (see `listSeedRef`). Same identity as the list's `key`. @@ -492,11 +501,11 @@ export function useObjectViewListRenderer({ const calendarOptions = calendarViewOptions(viewDef); /** - * objectui#12474 — the Hide Fields popover's choice is the USER's: it - * is stored on their own list state (`listPrefs`, beside the sort and - * the column layout), never written into the shared view, so one - * user's click no longer hides a column for everyone and a walled - * tenant member is not refused. It is a SUBTRACTION from the columns + * objectui#12474 — the Hide Fields popover's choice is the READER's, + * never written into the shared view by the click, so one user's click + * hides no column for everyone and a walled tenant member is not + * refused. Since objectstack#35955 it is a DRAFT (`listDraft`), kept + * only once the reader saves it into a view. It is a SUBTRACTION from the columns * the view declares: the popover offers only those (and, objectui#11984, * only the ones the caller may read), and the list draws `columns` * minus this list, so it can never add a column. @@ -522,7 +531,7 @@ export function useObjectViewListRenderer({ */ const persistHiddenFields = (hidden: string[]) => { if (!activeViewDeclaresColumns && !activeViewIsSaved) return; - listPrefs.patchView(viewDef.id, { hiddenFields: hidden }); + listDraft.patch({ hiddenFields: hidden }); }; /** @@ -543,7 +552,7 @@ export function useObjectViewListRenderer({ addedFieldsStored ? viewPref?.addedFields : undefined, ); const persistAddedFields = (added: string[]) => { - listPrefs.patchView(viewDef.id, { addedFields: added }); + listDraft.patch({ addedFields: added.length > 0 ? added : undefined }); }; /** @@ -578,9 +587,14 @@ export function useObjectViewListRenderer({ * `persistListSort` / `persistHiddenFields` and stays stored. */ const restoreViewDefaults = (parts: ReadonlyArray<'sort' | 'hiddenFields' | 'rowHeight'>) => { - const patch: ListViewPreferencePatch = {}; - for (const part of parts) patch[part] = null; - listPrefs.patchView(viewDef.id, patch); + // objectstack#35955 — the sort and the hidden fields leave the + // draft; the row height is the reader's stored choice. + if (parts.includes('sort')) listDraft.patch({ sort: undefined }); + if (parts.includes('hiddenFields')) listDraft.patch({ hiddenFields: undefined }); + if (parts.includes('rowHeight')) { + const patch: ListViewPreferencePatch = { rowHeight: null }; + listPrefs.patchView(viewDef.id, patch); + } if (parts.includes('sort')) writeListUrlState({ sort: null }); }; @@ -1120,21 +1134,25 @@ export function useObjectViewListRenderer({ }} // objectui#11860 — the URL only: nothing else stores the // toolbar grouping, and the view's own stays as authored. - onGroupingChange={(grouping) => writeListUrlState({ grouping: grouping ?? null })} + onGroupingChange={(grouping) => { + // objectstack#35955 — a draft, and the URL, so the list is a link. + listDraft.patch({ grouping: grouping ?? undefined }); + writeListUrlState({ grouping: grouping ?? null }); + }} onFilterChange={(filter: any) => { - // The USER's state (objectui#12418), never the view's - // stored body (objectui#4155) — the user's list state keeps - // the BUILDER's group verbatim, read back into - // `initialFilters`, which needs `conditions` (and the row - // ids) to rehydrate the toolbar. It follows the user to - // another browser, and the panel's own "Clear all" clears - // it: it writes an empty group through this same handler. - listPrefs.patchView(viewDef.id, { filters: filter }); + // A DRAFT (objectstack#35955), never the view's stored body + // (objectui#4155) — the draft keeps the BUILDER's group + // verbatim, read back into `initialFilters`, which needs + // `conditions` (and the row ids) to rehydrate the toolbar. + // The panel's own "Clear all" writes an empty group through + // this same handler. + listDraft.patch({ filters: filter }); // objectui#11860 — and the URL, so the list is a link. writeListUrlState({ filters: filter }); }} onSearchChange={(search: string) => { - writeListFilterState(listFilterKey, { search }); + // objectstack#35955 — the search lives as long as the draft. + listDraft.patch({ search: search || undefined }); writeListUrlState({ search }); }} onHiddenFieldsChange={persistHiddenFields} @@ -1183,7 +1201,7 @@ export function useObjectViewListRenderer({ dataSource={ds} /> ); - }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, openInPanel, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, summaryPickKey, previewDrafts, previewDataSource, unpublishedObjects]); + }, [hasViewBarTrailing, trailStore, rowEndStore, activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, listDraft.draft, listDraft.patch, managedUsers, managedUserMarker, openInPanel, rowOpensRecord, handleListRowsChange, handleListTotalChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, summaryPickKey, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/app-shell/src/views/objectViewListUrlState.ts b/ui/packages/app-shell/src/views/objectViewListUrlState.ts index cbb3e1e7667..299cc8aa0c8 100644 --- a/ui/packages/app-shell/src/views/objectViewListUrlState.ts +++ b/ui/packages/app-shell/src/views/objectViewListUrlState.ts @@ -21,17 +21,25 @@ import { applyListStateParams, parseListPageParam, userFilterParamsKey, + acceptGroupingConfig, type ListStatePatch, type ListUrlFieldGate, type ListUrlState, type ListSortRule, } from './userFilterUrlState.js'; -import { buildListFilterKey, readListFilterState, clearListFilterState } from './listFilterStorage.js'; import type { useObjectListPreferences, ListFilterGroupPreference, ListSortPreference, } from '../context/ListPreferencesProvider.js'; +import { + claimListDraft, + discardListDraft, + listDraftScope, + readListDraft, + takeDocumentReload, + type ListDraft, +} from './listDraftStore.js'; import { parseUrlEqualityFilterTriples } from './drillUrlFilters.js'; import { selectFilterParams } from './objectViewHelpers.js'; import type { buildViewTabs } from './objectViewTabs.js'; @@ -120,12 +128,20 @@ function linkFilterConditionCount(searchParams: URLSearchParams): number { return Array.isArray(parsed.conditions) ? parsed.conditions.length : 0; } +/** + * objectstack#35955 — parts the list reports that are no unsaved change to + * the view: the row height is remembered for the reader, and a search term + * alone is not something a view stores. + */ +const NOT_DRAFT_PARTS: ReadonlySet = new Set(['density', 'search']); + export function useObjectViewListUrlState({ objectName, objectDef, activeView, viewResolving, listPrefs, + listDraft, perms, user, searchParams, @@ -141,6 +157,8 @@ export function useObjectViewListUrlState({ */ viewResolving: boolean; listPrefs: ReturnType; + /** objectstack#35955 — the open list's unsaved changes (`./listDraftStore.ts`). */ + listDraft: ListDraft; perms: ReturnType; user: ReturnType['user']; searchParams: URLSearchParams; @@ -161,12 +179,19 @@ export function useObjectViewListUrlState({ * the per-browser cache is not consulted, so a shared link opens the * same list for everyone who may read it. A piece the URL lacks is * absent, not filled from storage. - * 2. Otherwise the user's own state (objectui#12418, `listPrefs`): the - * Filter panel's conditions and the sort they left this view with, and - * the search term from the per-user cache (`listFilterStorage`); the - * view's own sort when they stored none, and its own grouping. The - * seed waits until that state has been read (`listPrefs.ready`), so a - * second browser opens on it rather than on an empty cache. + * 2. Otherwise the list's DRAFT (objectstack#35955, `./listDraftStore.ts`): + * the Filter panel's conditions, the search term, the sort and the + * grouping the reader changed and has not saved, kept while they open + * a record and come back; the view's own for every part the draft + * lacks. Nothing the reader stored earlier is read: their stored sort + * and filters (objectui#12418) no longer apply. The seed still waits + * for the stored state to be read (`listPrefs.ready`): the column + * widths and the row height are kept there. + * + * A RELOAD is neither (objectstack#35955): the first list a reloaded page + * seeds opens as its view declares it, and the write-back strips the + * `uf_*` params a reload carried. A link opened in a new tab is not a + * reload, and still opens the list it names. * * Neither seed is taken, and nothing is written, while the view the * address names is still being resolved (`viewResolving`, objectstack#30034): @@ -237,6 +262,11 @@ export function useObjectViewListUrlState({ // `uf_*` params, whoever wrote them, and its write-back strips them all. const resetPendingRef = useRef(false); if (listIdentityKey && listPrefs.ready && !viewResolving && listSeedRef.current?.key !== listIdentityKey) { + // objectstack#35955 — this list is the one on screen: a draft held + // for another view or object goes. + const draftScope = listDraftScope(user?.id, objectName ?? '', String(activeView.id)); + claimListDraft(draftScope); + const seedDraft = readListDraft(draftScope); // A field the object does not declare (a stale link, or a stored state // older than the field's deletion) or one this user cannot read is // dropped. Field-level permissions gate only once loaded — the same @@ -245,7 +275,7 @@ export function useObjectViewListUrlState({ !!objectDef.fields?.[field] && (!perms.isLoaded || perms.checkField(objectDef.name, field, 'read')); const carried = userFilterParamsKey(searchParams); - const reset = resetPendingRef.current; + const reset = resetPendingRef.current || takeDocumentReload(); resetPendingRef.current = false; if (carried && carried !== ownListParamsRef.current && !reset) { const state = parseListStateParams(searchParams, acceptField); @@ -260,15 +290,14 @@ export function useObjectViewListUrlState({ refusedLinkFilter, }; } else { - const stored = readListFilterState(buildListFilterKey(user?.id, objectName, activeView.id)); - const viewPref = listPrefs.preference.perView?.[activeView.id]; listSeedRef.current = { key: listIdentityKey, source: 'storage', state: { - filters: acceptStoredFilters(viewPref?.filters, acceptField) as ListUrlState['filters'], - search: stored?.search || undefined, - sort: acceptStoredSort(viewPref?.sort, acceptField), + filters: acceptStoredFilters(seedDraft.filters, acceptField) as ListUrlState['filters'], + search: seedDraft.search || undefined, + sort: acceptStoredSort(seedDraft.sort, acceptField), + grouping: acceptGroupingConfig(seedDraft.grouping, acceptField), }, reset, }; @@ -326,12 +355,15 @@ export function useObjectViewListUrlState({ ); /** - * objectstack#28950 — what of the reader's list differs from the view, as - * the list reports it (`ListView`'s `onPersonalizationChange`), held with - * the list identity it came from so a report never outlives its list. The - * column layout is the one part only this page knows: a stored column - * state is the reader's own, and so are the fields they added as columns - * (objectstack#30077), which the list draws as columns of the view. + * objectstack#35955 — what of the reader's list is an unsaved change (its + * DRAFT parts: Discard and Save are drawn while there is one), as the list + * reports it (`ListView`'s `onPersonalizationChange`, objectstack#28950), + * held with the list identity it came from so a report never outlives its + * list. Two parts the list reports are not a change to the view: the row + * height (`density`), which is remembered for the reader, and the search + * term alone, which a view does not store. The column order and the added + * fields (objectstack#30077) are the one part only this page knows: they + * are the draft's. */ const [reportedPersonalization, setReportedPersonalization] = useState<{ key: string; @@ -344,48 +376,44 @@ export function useObjectViewListUrlState({ }, [], ); - const listPersonalizedParts: ListPersonalizationPart[] = [ - ...(reportedPersonalization && reportedPersonalization.key === listIdentityKey + const listDraftParts: ListPersonalizationPart[] = ( + reportedPersonalization && reportedPersonalization.key === listIdentityKey ? reportedPersonalization.parts - : []), - ]; - const storedViewPreference = activeView?.id ? listPrefs.preference.perView?.[activeView.id] : undefined; - if ((storedViewPreference?.columnState || storedViewPreference?.addedFields?.length) - && !listPersonalizedParts.includes('columns')) { - listPersonalizedParts.push('columns'); + : [] + ).filter((part) => !NOT_DRAFT_PARTS.has(part)); + if ((listDraft.columnOrder || listDraft.addedFields?.length) && !listDraftParts.includes('columns')) { + listDraftParts.push('columns'); } /** - * objectstack#28950 — "Reset to view", the marker's one way back: the - * reader's whole list for the active view returns to the view's own. Their - * stored entry goes (sort, filters, column layout, density, hidden fields, - * objectui#12418; added fields, objectstack#30077), the cached search term with it, and the list opens - * again from that cleared state (the identity moves, so it remounts and - * re-seeds; a reset is the one case that WANTS the list's own state thrown - * away). The new seed ignores the `uf_*` params and its write-back strips - * them, chips included, so neither a reload nor Back brings the old list - * back. The remount puts the grouping, layout, row color, row numbers, - * inline edit and the "In a queue" toggle back to the view's. + * objectstack#35955 — Discard (objectstack#28950's "Reset to view" before + * it): the list returns to the view's own. Its draft goes (sort, filters, + * grouping, search, columns shown and their order, layout, row colour), + * and the list opens again from the view (the identity moves, so it + * remounts and re-seeds; a discard is the one case that WANTS the list's + * own state thrown away). The new seed ignores the `uf_*` params and its + * write-back strips them, chips included, so neither a reload nor Back + * brings the old list back. The remount puts row numbers, inline edit and + * the "In a queue" toggle back to the view's too. * - * Not this view's list state, so untouched: the record-open preference, - * the tab order (pinned views), favorites and a `filter[...]` scope a - * "View all" link opened the list with. + * Not a change to the view, so untouched: the column widths and the row + * height (remembered for the reader), the record-open preference, the tab + * order (pinned views), favorites and a `filter[...]` scope a "View all" + * link opened the list with. */ const handleResetView = useCallback(() => { if (!activeView?.id) return; - listPrefs.resetView(activeView.id); - clearListFilterState(buildListFilterKey(user?.id, objectName, activeView.id)); + discardListDraft(listDraftScope(user?.id, objectName ?? '', String(activeView.id))); resetPendingRef.current = true; setListResetGeneration(g => g + 1); - }, [activeView?.id, listPrefs.resetView, user?.id, objectName]); + }, [activeView?.id, user?.id, objectName]); /** * objectstack#30073 — the list the reader just saved as a view of its own - * leaves the view it came from: that view's stored list state (sort, - * filters, column layout, density, hidden fields, every part the saved - * body carries) and its cached search term go, and the address the page - * is leaving loses its `uf_*` params, so neither Back nor the next open - * of that view brings the conditions back, nor marks it personalized. - * The caller navigates to the saved view next. + * leaves the view it came from: that view's draft (objectstack#35955) + * goes, and the address the page is leaving loses its `uf_*` params, so + * neither Back nor the next open of that view brings the conditions back, + * nor draws Discard and Save on it. The caller navigates to the saved view + * next. */ /** * objectstack#30073 — the Filter panel's group on screen: the list's last @@ -402,10 +430,9 @@ export function useObjectViewListUrlState({ return seed && seed.key === listIdentityKeyRef.current ? seed.state.filters : undefined; }, []); const clearSourceListState = useCallback((viewId: string) => { - listPrefs.resetView(viewId); - clearListFilterState(buildListFilterKey(user?.id, objectName, viewId)); + discardListDraft(listDraftScope(user?.id, objectName ?? '', viewId)); setSearchParams(prev => withoutListStateParams(prev), { replace: true }); - }, [listPrefs.resetView, user?.id, objectName, setSearchParams]); + }, [user?.id, objectName, setSearchParams]); /** * objectstack#30850 — the page the list shows, read from the address on * every render: `ListView` takes it as a controlled `page`, and its every @@ -424,7 +451,7 @@ export function useObjectViewListUrlState({ ownListParamsRef, writeListUrlState, handleListPersonalizationChange, - listPersonalizedParts, + listDraftParts, handleResetView, }; } diff --git a/ui/packages/app-shell/src/views/personalViews.ts b/ui/packages/app-shell/src/views/personalViews.ts index 7481aa77dcc..31f28e5901a 100644 --- a/ui/packages/app-shell/src/views/personalViews.ts +++ b/ui/packages/app-shell/src/views/personalViews.ts @@ -192,9 +192,9 @@ function columnName(column: unknown): string | undefined { * the panel alone is the filter: the reader may have edited or removed one. * - **sort** and **grouping**: the ones the address carries; absent there, * the view's own. - * - **columns**: the view's, in the reader's dragged order, without the - * columns they hid (so `hiddenFields` and `fieldOrder` are applied, not - * carried). **rowHeight**: the reader's density, else the view's. + * - **columns**: the view's and the ones the reader added, in the reader's + * dragged order, without the columns they hid (so `hiddenFields` and + * `fieldOrder` are applied, not carried). **rowHeight**: the reader's density, else the view's. * * The body is narrowed to the keys spec's closed `ListViewSchema` declares and * bound to this object (`config.data.object`) by `buildViewConfigSaveBody`, @@ -222,6 +222,15 @@ export function buildPersonalViewConfig( const hidden = new Set(pref?.hiddenFields ?? (Array.isArray(view.hiddenFields) ? view.hiddenFields : [])); const order = pref?.columnState?.order ?? (Array.isArray(view.fieldOrder) ? view.fieldOrder : undefined); let columns: unknown[] | undefined = Array.isArray(view.columns) ? [...view.columns] : undefined; + // objectstack#35955 — the fields the reader added as columns (objectstack#30077) + // are columns of the saved view, after the view's own, in the same spelling. + if (columns && pref?.addedFields?.length) { + const names = new Set(columns.map(columnName).filter((n): n is string => !!n)); + const asObjects = columns.some((c) => typeof c !== 'string'); + for (const field of pref.addedFields) { + if (!names.has(field)) columns.push(asObjects ? { field } : field); + } + } if (columns) { if (order && order.length > 0) { const rank = new Map(order.map((name: string, i: number) => [name, i])); diff --git a/ui/packages/app-shell/src/views/userFilterUrlState.ts b/ui/packages/app-shell/src/views/userFilterUrlState.ts index 453d41daef3..a2e29dc7006 100644 --- a/ui/packages/app-shell/src/views/userFilterUrlState.ts +++ b/ui/packages/app-shell/src/views/userFilterUrlState.ts @@ -250,6 +250,14 @@ function parseGroupingParam(raw: string | null, acceptField: ListUrlFieldGate): return config.success ? config.data : undefined; } +/** + * objectstack#35955 — a grouping held outside the address (the list's draft) + * through the same level-by-level checks the `uf__group` param gets. + */ +export function acceptGroupingConfig(value: unknown, acceptField: ListUrlFieldGate): GroupingConfig | undefined { + return value ? parseGroupingParam(JSON.stringify(value), acceptField) : undefined; +} + /** * Read the list state a URL carries. Each piece is `undefined` when the URL * does not carry it, or when nothing in it survives the checks above. diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 70af4a16288..89b48a8afec 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2916,11 +2916,19 @@ const ar = { viewNameInvalid: "استخدم أحرفًا إنجليزية صغيرة وأرقامًا وشرطات سفلية؛ وابدأ بحرف أو شرطة سفلية.", systemViewReadonly: "عرض النظام معرَّف في الكود — للقراءة فقط.", cannotEditMetaView: "هذا عرض مدمج معرَّف في الكود — لا يمكن تعديله.", - resetView: "الرجوع إلى إعدادات العرض", - resetViewTitle: "يعيد عوامل التصفية والبحث والترتيب والتجميع وترتيب الأعمدة والحقول المخفية والكثافة والتخطيط ولون الصف وأرقام الصفوف والتحرير المضمّن الخاصة بهذا العرض. تبقى طرق العرض المثبتة والمفضلة وطريقة فتح السجلات كما هي. تتغير قائمتك فقط.", + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: "تجاهل", + discardTitle: "يعيد القائمة كما يحددها العرض: عوامل التصفية والفرز والتجميع والأعمدة والتخطيط. يبقى عرض الأعمدة وارتفاع الصفوف كما هما.", + save: "حفظ", + heading: "تغييرات غير محفوظة", + partSeparator: "، ", + saveToView: "حفظ في هذا العرض", + saveAsMyView: "حفظ كعرض خاص بي", + copyName: "نسخة من {{name}}", + saved: "تم الحفظ", + }, linkFilterRefused: 'لم يُطبَّق عامل التصفية في هذا الرابط، لأنه يذكر حقلًا لا يمكنك التصفية حسبه هنا، لذا تعرض القائمة طريقة العرض دونه.', - personalized: "مخصّصة", - personalizedHeading: "تختلف قائمتك عن هذا العرض في", personalizedParts: { filters: "عوامل التصفية", search: "البحث", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7e99247e5ca..f672cf961c0 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2636,11 +2636,19 @@ const de = { viewNameInvalid: "Verwenden Sie Kleinbuchstaben, Ziffern und Unterstriche; beginnen Sie mit einem Buchstaben oder Unterstrich.", systemViewReadonly: "Systemansicht — im Code definiert, schreibgeschützt.", cannotEditMetaView: "Diese Ansicht ist integriert und im Code definiert – sie kann nicht geändert werden.", - resetView: "Auf Ansicht zurücksetzen", - resetViewTitle: "Stellt die eigenen Filter, Suche, Sortierung, Gruppierung, Spaltenanordnung, ausgeblendeten Felder, Dichte, Layout, Zeilenfarbe, Zeilennummern und Inline-Bearbeitung dieser Ansicht wieder her. Angeheftete Ansichten, Favoriten und die Art, wie Datensätze geöffnet werden, bleiben unverändert. Nur Ihre Liste ändert sich.", + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: "Verwerfen", + discardTitle: "Setzt die Liste auf den Stand der Ansicht zurück: Filter, Sortierung, Gruppierung, Spalten und Layout. Spaltenbreiten und Zeilenhöhe bleiben.", + save: "Speichern", + heading: "Ungespeicherte Änderungen", + partSeparator: ", ", + saveToView: "In dieser Ansicht speichern", + saveAsMyView: "Als meine Ansicht speichern", + copyName: "{{name}} (Kopie)", + saved: "Gespeichert", + }, linkFilterRefused: 'Der Filter dieses Links wurde nicht angewendet. Er nennt ein Feld, nach dem Sie hier nicht filtern können, daher zeigt die Liste die Ansicht ohne ihn.', - personalized: "Personalisiert", - personalizedHeading: "Ihre Liste weicht von dieser Ansicht ab bei", personalizedParts: { filters: "Filter", search: "Suche", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 13266e90f2a..b64939b4205 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3228,11 +3228,19 @@ const en = { // (rename / pin / set-as-default / configure), so the copy has to cover // any change to a built-in view rather than name one operation. cannotEditMetaView: 'This view is built in and defined in code — it cannot be changed.', - resetView: 'Reset to view', - resetViewTitle: 'Puts back this view’s own filters, search, sort, grouping, column layout, hidden fields, density, layout, row color, row numbers and inline editing. Pinned views, favorites and how records open stay as they are. Only your list changes.', + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: 'Discard', + discardTitle: 'Puts the list back as its view declares it: filters, sort, grouping, columns and layout. Column widths and row height stay.', + save: 'Save', + heading: 'Unsaved changes', + partSeparator: ', ', + saveToView: 'Save to this view', + saveAsMyView: 'Save as my view', + copyName: '{{name}} copy', + saved: 'Saved', + }, linkFilterRefused: 'This link’s filter was not applied. It names a field you can’t filter on here, so the list shows the view without it.', - personalized: 'Personalized', - personalizedHeading: 'Your list differs from this view in', personalizedParts: { filters: 'Filters', search: 'Search', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f06b1b1529d..2f932c2beb8 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2708,11 +2708,19 @@ const es = { viewNameInvalid: "Use minúsculas, números y guiones bajos; empiece por una letra o un guion bajo.", systemViewReadonly: "Vista del sistema definida en el código: solo lectura.", cannotEditMetaView: "Esta vista está integrada y definida en el código: no se puede modificar.", - resetView: "Restablecer a la vista", - resetViewTitle: "Restaura los filtros, la búsqueda, la ordenación, la agrupación, la disposición de columnas, los campos ocultos, la densidad, el diseño, el color de fila, los números de fila y la edición en línea propios de esta vista. Las vistas fijadas, los favoritos y la forma de abrir los registros no cambian. Solo cambia su lista.", + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: "Descartar", + discardTitle: "Devuelve la lista a como la define su vista: filtros, orden, agrupación, columnas y diseño. El ancho de las columnas y el alto de las filas se mantienen.", + save: "Guardar", + heading: "Cambios sin guardar", + partSeparator: ", ", + saveToView: "Guardar en esta vista", + saveAsMyView: "Guardar como mi vista", + copyName: "{{name}} (copia)", + saved: "Guardado", + }, linkFilterRefused: 'No se aplicó el filtro de este enlace. Incluye un campo por el que no puede filtrar aquí, así que la lista muestra la vista sin él.', - personalized: "Personalizada", - personalizedHeading: "Su lista difiere de esta vista en", personalizedParts: { filters: "Filtros", search: "Búsqueda", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 749a7bfda0e..487d83386c1 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2704,11 +2704,19 @@ const fr = { viewNameInvalid: "Utilisez des minuscules, des chiffres et des tirets bas ; commencez par une lettre ou un tiret bas.", systemViewReadonly: "Vue système définie dans le code — en lecture seule.", cannotEditMetaView: "Cette vue est intégrée et définie dans le code — elle ne peut pas être modifiée.", - resetView: "Revenir à la vue", - resetViewTitle: "Rétablit les filtres, la recherche, le tri, le regroupement, la disposition des colonnes, les champs masqués, la densité, la disposition, la couleur de ligne, les numéros de ligne et l’édition en ligne propres à cette vue. Les vues épinglées, les favoris et le mode d’ouverture des enregistrements ne changent pas. Seule votre liste change.", + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: "Abandonner", + discardTitle: "Remet la liste telle que la vue la définit : filtres, tri, regroupement, colonnes et disposition. La largeur des colonnes et la hauteur des lignes restent.", + save: "Enregistrer", + heading: "Modifications non enregistrées", + partSeparator: ", ", + saveToView: "Enregistrer dans cette vue", + saveAsMyView: "Enregistrer comme ma vue", + copyName: "{{name}} (copie)", + saved: "Enregistré", + }, linkFilterRefused: 'Le filtre de ce lien n’a pas été appliqué. Il cite un champ sur lequel vous ne pouvez pas filtrer ici, la liste affiche donc la vue sans ce filtre.', - personalized: "Personnalisée", - personalizedHeading: "Votre liste diffère de cette vue par", personalizedParts: { filters: "Filtres", search: "Recherche", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 9ff01af1738..74ca146ad31 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2638,11 +2638,19 @@ const ja = { viewNameInvalid: "英小文字、数字、アンダースコアを使用し、先頭は文字かアンダースコアにしてください。", systemViewReadonly: "システムビューはコードで定義されており、読み取り専用です。", cannotEditMetaView: "このビューはコードで定義された組み込みビューのため、変更できません。", - resetView: "ビューの設定に戻す", - resetViewTitle: "このビュー本来のフィルター、検索、並べ替え、グループ、列の配置、非表示フィールド、密度、レイアウト、行の色、行番号、インライン編集に戻します。ピン留めしたビュー、お気に入り、レコードの開き方は変わりません。変わるのはあなたのリストだけです。", + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: "破棄", + discardTitle: "一覧をビュー本来の状態に戻します:フィルター、並べ替え、グループ化、列、レイアウト。列幅と行の高さはそのままです。", + save: "保存", + heading: "未保存の変更", + partSeparator: "、", + saveToView: "このビューに保存", + saveAsMyView: "マイビューとして保存", + copyName: "{{name}} のコピー", + saved: "保存しました", + }, linkFilterRefused: 'このリンクのフィルターは適用されませんでした。ここでは絞り込めないフィールドが含まれているため、ビュー本来の内容を表示しています。', - personalized: "個人設定あり", - personalizedHeading: "このビューと異なる項目", personalizedParts: { filters: "フィルター", search: "検索", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 7136511d607..ef8b2f89099 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2636,11 +2636,19 @@ const ko = { viewNameInvalid: "소문자, 숫자, 밑줄을 사용하고 문자 또는 밑줄로 시작하세요.", systemViewReadonly: "시스템 보기는 코드에 정의되어 있어 읽기 전용입니다.", cannotEditMetaView: "이 보기는 코드에 정의된 기본 제공 보기이므로 변경할 수 없습니다.", - resetView: "보기 설정으로 되돌리기", - resetViewTitle: "이 보기 자체의 필터, 검색, 정렬, 그룹, 열 배치, 숨긴 필드, 밀도, 레이아웃, 행 색상, 행 번호, 인라인 편집으로 되돌립니다. 고정한 보기, 즐겨찾기, 레코드 열기 방식은 그대로 유지됩니다. 본인의 목록만 변경됩니다.", + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: "변경 취소", + discardTitle: "목록을 보기에 정의된 상태로 되돌립니다: 필터, 정렬, 그룹, 열, 레이아웃. 열 너비와 행 높이는 그대로입니다.", + save: "저장", + heading: "저장되지 않은 변경", + partSeparator: ", ", + saveToView: "이 보기에 저장", + saveAsMyView: "내 보기로 저장", + copyName: "{{name}} 사본", + saved: "저장했습니다", + }, linkFilterRefused: '이 링크의 필터가 적용되지 않았습니다. 여기서 필터링할 수 없는 필드가 포함되어 있어 뷰를 그대로 표시합니다.', - personalized: "개인 설정됨", - personalizedHeading: "이 보기와 다른 항목", personalizedParts: { filters: "필터", search: "검색", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0d1c9c34747..09006df66a6 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2703,11 +2703,19 @@ const pt = { viewNameInvalid: "Use letras minúsculas, números e sublinhados; comece com uma letra ou sublinhado.", systemViewReadonly: "Exibição do sistema definida no código — somente leitura.", cannotEditMetaView: "Esta exibição é integrada e definida no código — não é possível alterá-la.", - resetView: "Voltar à exibição", - resetViewTitle: "Restaura os filtros, a pesquisa, a ordenação, o agrupamento, a disposição das colunas, os campos ocultos, a densidade, o layout, a cor da linha, os números de linha e a edição em linha próprios desta exibição. Exibições fixadas, favoritos e a forma de abrir registros não mudam. Apenas a sua lista muda.", + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: "Descartar", + discardTitle: "Devolve a lista ao que a exibição define: filtros, ordenação, agrupamento, colunas e layout. A largura das colunas e a altura das linhas continuam.", + save: "Salvar", + heading: "Alterações não salvas", + partSeparator: ", ", + saveToView: "Salvar nesta exibição", + saveAsMyView: "Salvar como minha exibição", + copyName: "{{name}} (cópia)", + saved: "Salvo", + }, linkFilterRefused: 'O filtro deste link não foi aplicado. Ele cita um campo pelo qual você não pode filtrar aqui, então a lista mostra a visualização sem ele.', - personalized: "Personalizada", - personalizedHeading: "Sua lista difere desta exibição em", personalizedParts: { filters: "Filtros", search: "Pesquisa", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ef52983f948..3d2754ad97a 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2782,11 +2782,19 @@ const ru = { viewNameInvalid: "Используйте строчные латинские буквы, цифры и подчёркивания; начните с буквы или подчёркивания.", systemViewReadonly: "Системное представление определено в коде — только для чтения.", cannotEditMetaView: "Это встроенное представление, определённое в коде, — изменить его нельзя.", - resetView: "Вернуть настройки представления", - resetViewTitle: "Возвращает собственные фильтры, поиск, сортировку, группировку, расположение столбцов, скрытые поля, плотность, макет, цвет строк, номера строк и встроенное редактирование этого представления. Закреплённые представления, избранное и способ открытия записей не меняются. Меняется только ваш список.", + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: "Отменить", + discardTitle: "Возвращает список к виду, заданному представлением: фильтры, сортировка, группировка, столбцы и макет. Ширина столбцов и высота строк сохраняются.", + save: "Сохранить", + heading: "Несохранённые изменения", + partSeparator: ", ", + saveToView: "Сохранить в это представление", + saveAsMyView: "Сохранить как моё представление", + copyName: "{{name}} (копия)", + saved: "Сохранено", + }, linkFilterRefused: 'Фильтр из этой ссылки не применён: в нём есть поле, по которому здесь нельзя фильтровать, поэтому список показан по представлению без него.', - personalized: "Настроено", - personalizedHeading: "Ваш список отличается от представления", personalizedParts: { filters: "Фильтры", search: "Поиск", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 7288c069e0d..514bf3ef5e9 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2723,11 +2723,19 @@ const zh = { }, systemViewReadonly: '系统视图由代码定义,只读。', cannotEditMetaView: '该视图为内置视图,由代码定义,无法修改。', - resetView: '恢复为视图设置', - resetViewTitle: '恢复此视图自身的筛选、搜索、排序、分组、列布局、隐藏字段、密度、布局、行颜色、行号和行内编辑。固定的视图、收藏和记录的打开方式保持不变。只影响你自己的列表。', + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: '放弃', + discardTitle: '把列表恢复成视图本来的样子:筛选、排序、分组、列和布局。列宽和行高不变。', + save: '保存', + heading: '未保存的改动', + partSeparator: '、', + saveToView: '保存到这个视图', + saveAsMyView: '另存为我的视图', + copyName: '{{name}} 副本', + saved: '已保存', + }, linkFilterRefused: '此链接的筛选条件未应用:其中包含你在此处无法筛选的字段,因此列表按视图本身显示。', - personalized: '已个性化', - personalizedHeading: '你的列表与此视图不同之处', personalizedParts: { filters: '筛选', search: '搜索', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 33893d18585..da4e52e981c 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2723,11 +2723,19 @@ const zhHant = { }, systemViewReadonly: '系統檢視由程式碼定義,只讀。', cannotEditMetaView: '該檢視為內建檢視,由程式碼定義,無法修改。', - resetView: '恢復為檢視設定', - resetViewTitle: '恢復此檢視自身的篩選、搜尋、排序、分組、列布局、隱藏欄位、密度、佈局、行顏色、行號和行內編輯。固定的檢視、收藏和記錄的開啟方式保持不變。只影響你自己的列表。', + // objectstack#35955 — a list's unsaved changes: Discard and Save. + draft: { + discard: '放棄', + discardTitle: '把列表恢復成檢視本來的樣子:篩選、排序、分組、列和佈局。列寬和行高不變。', + save: '儲存', + heading: '未儲存的改動', + partSeparator: '、', + saveToView: '儲存到這個檢視', + saveAsMyView: '另存為我的檢視', + copyName: '{{name}} 副本', + saved: '已儲存', + }, linkFilterRefused: '此連結的篩選條件未應用:其中包含你在此處無法篩選的欄位,因此列表按檢視本身顯示。', - personalized: '已個性化', - personalizedHeading: '你的列表與此檢視不同之處', personalizedParts: { filters: '篩選', search: '搜尋', From a1ceb46a5cd4d557a374713778e2f32a068883b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 07:56:51 +0000 Subject: [PATCH 2/5] feat(console): a change on a list is a draft, with Discard and Save Finishes the draft layer: the tests follow it, the docs and the platform checklist item say it, the retired marker's locale keys stay in every pack, and a changeset carries the upgrade note. Column widths, row height and the views' order stay stored for the reader. Claude-Session: https://claude.ai/code/session_01L6bhgUr9HRqChVQu82hqdz Co-authored-by: Claude --- .changeset/35955-list-changes-are-drafts.md | 21 + content/docs/ui/views.mdx | 37 +- .../areas/records-forms.json | 26 +- .../consoleListStateWall-12418.test.tsx | 35 +- ...ew.emptyColumnsNoProjection-10694.test.tsx | 61 +- .../ObjectView.listPageInUrl-30850.test.tsx | 3 + ...ObjectView.listPersonalized-28950.test.tsx | 102 ++-- .../ObjectView.listUrlState-11860.test.tsx | 36 +- .../views/ObjectView.overlayPatchOnly.test.ts | 4 +- .../ObjectView.personalViews-29635.test.tsx | 83 ++- .../ObjectView.ufViewSwitch-11992.test.tsx | 10 +- .../ObjectView.userListState-12418.test.tsx | 531 +++++++++--------- .../app-shell/src/views/listDraftStore.ts | 21 +- .../src/views/objectViewListUrlState.ts | 2 +- .../views/view-filter-fold.ratchet.test.ts | 8 +- ui/packages/i18n/src/locales/ar.ts | 6 + ui/packages/i18n/src/locales/de.ts | 6 + ui/packages/i18n/src/locales/en.ts | 6 + ui/packages/i18n/src/locales/es.ts | 6 + ui/packages/i18n/src/locales/fr.ts | 6 + ui/packages/i18n/src/locales/ja.ts | 6 + ui/packages/i18n/src/locales/ko.ts | 6 + ui/packages/i18n/src/locales/pt-BR.ts | 6 + ui/packages/i18n/src/locales/ru.ts | 6 + ui/packages/i18n/src/locales/zh-Hans.ts | 6 + ui/packages/i18n/src/locales/zh-Hant.ts | 6 + 26 files changed, 612 insertions(+), 434 deletions(-) create mode 100644 .changeset/35955-list-changes-are-drafts.md diff --git a/.changeset/35955-list-changes-are-drafts.md b/.changeset/35955-list-changes-are-drafts.md new file mode 100644 index 00000000000..dfa14b2bba1 --- /dev/null +++ b/.changeset/35955-list-changes-are-drafts.md @@ -0,0 +1,21 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): a change on a list is a draft, with Discard and Save + +Clause-②: yes (widening) — new `console.objectView.draft.*` keys in every `@object-ui/i18n` locale pack (`discard`, `discardTitle`, `save`, `heading`, `partSeparator`, `saveToView`, `saveAsMyView`, `copyName`, `saved`); nothing removed or renamed +Metadata-protocol: none + +On a Console object list, a header sort, a filter change, grouping, the search, Hide Fields, an added field and a column drag apply at once and are now a draft: they are kept nowhere. They used to be saved at once into the reader's own list preference (`sys_user_preference`, key `ui.list.`) and followed them to every device. + +- While the list holds a draft, **Discard** and **Save** sit at the end of the condition row, where the 「Personalized · Reset to view」 marker was. On a narrow list or a phone they fold into one **Save** whose menu also holds Discard. +- **Save** names what is unsaved and offers **Save to this view** (on a view of the reader's own) and **Save as my view**, which asks a name first (the view's name with "copy"), saves the draft as a new view of the reader's own and opens it. Either says "Saved", and the buttons go while the conditions stay. +- **Discard** puts the list back as its view declares it and removes the list's `uf_*` parameters from the address bar. +- The draft survives opening a record (as a page or in the side panel) and coming back. Opening another view or object, or reloading the page, drops it. +- Column widths, the row height and the views' order are not a draft. They are still remembered for the reader in the same `ui.list.` row. + +Upgrade note: a sort, filter, search, column order, hidden column or added column that an earlier Console stored in a reader's `ui.list.` row no longer applies; the list opens as its view declares it. Nothing stored is rewritten or deleted by this change. A reader who wants such a list kept saves it as a view of their own. + +Saving into a shared view is not offered yet. No metadata key, value or default changes. diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index 082edc0fb45..51158c65a6b 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -619,24 +619,29 @@ reader's right-column and panel choices on it, are described in ### A user's list state never writes the view -A header sort, a column drag or resize, a filter change, a density change, Hide Fields -and a Manage Views drag are saved for that user (`sys_user_preference`, key -`ui.list.`), never to the view metadata, so they work even where the tenant's -metadata is read-only. What you author (`sort`, filters, columns, `rowHeight`, -`hiddenFields`, the views' order) is the default for every user with no state of their own. - -- A link carrying list state (`uf_*` parameters) wins over the stored state. +A header sort, a filter change, grouping, the search, Hide Fields, an added field and a +column drag apply at once and are a **draft**: they are kept nowhere and never write the +view metadata, so they work even where the tenant's metadata is read-only. While the list +holds a draft, **Discard** and **Save** sit at the end of the condition row (one **Save** +whose menu also holds Discard on a narrow list or a phone). + +- **Save** names what is unsaved and keeps the sort, filters, columns and hidden fields: + **Save to this view** on a view of the user's own, or **Save as my view**, which asks a + name first (the view's name with "copy") and then opens the new view. Either says + "Saved", and the buttons go while the conditions stay. +- **Discard** puts the list back as its view declares it, the Display panel's layout and row + color included, and removes the list's `uf_*` parameters from the address bar. +- The draft survives opening a record and coming back. Opening another view or object, + or reloading the page, drops it, so a reload opens the view as it is declared. +- Column widths, the row height (density) and the views' order are not a draft: they are + remembered for the user (`sys_user_preference`, key `ui.list.`). A sort, filter, + column order or hidden column an earlier Console stored there no longer applies. +- A link carrying list state (`uf_*` parameters) opened in a new tab applies it as a draft. - When a session ends, the sign-in page's return link keeps the list's path but never its - `uf_*` state, so whoever signs in next opens their own stored state or the view's default. + `uf_*` state, so whoever signs in next opens the view's default. - A user's hidden fields only subtract from the columns the view shows, never add one. -- While a user's list differs from the view, a **Personalized** marker sits beside the list - title (an icon alone on a phone). Opening it names what differs: filters, search, sort, - grouping, column layout, hidden fields, density, and the Display panel's layout, row - color and inline editing. Its **Reset to view** is the one way back: it - drops the active view's stored state and cached search, and removes the list's `uf_*` - parameters from the address bar, so the list is the view's own again after a reload too. - Pinned views, favorites, how records open and a "View all" link's `filter[...]` scope are - not list state and stay. Nothing about the marker is configurable. +- Pinned views, favorites, how records open and a "View all" link's `filter[...]` scope are + not part of a draft and stay. Nothing about Discard and Save is configurable. ### A view the user may not open diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 9bba7b25ae3..c6a44c78f31 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -2925,7 +2925,7 @@ "title": "User-built FilterBuilder/SortBuilder toolbar merges with the view filter, restores across nav, and reproduces rows from the URL", "since": "v16", "status": "active", - "revision": 12, + "revision": 13, "priority": "P1", "surface": "browser", "personas": [ @@ -2946,8 +2946,8 @@ "sign in as admin; open showcase_task and switch to the in_progress saved view (stored filter status=in_progress); screenshot", "open Filter in the condition row under the view bar (since objectstack#35878 the bar has no Filter or Sort button: the row is always there, with a dashed 「Filter」 button while no filter of the reader's own is set and a 「+」 after the filter chips once one is, both data-testid condition-add-filter; Sort is the row's first control, the dashed 「Sort」 button or, once sorted, the one sort chip 「Sorted by X +N」, data-testid condition-sort, ui/packages/plugin-list/src/conditions/ListConditionControls.tsx). Since objectstack#35549 / #35550 each opens the shared field list (the fields the view shows first, a search box, a type icon per row): Filter → a field → its values applies at once, with no Apply, and each condition shows as a chip in the condition row under the view bar; Sort → the direction on top → a field adds a level, the sort chip before the filter chips counting it as 「+N」. The full builders are one click further, behind the field list's footer: 「Advanced filter」 opens the FilterBuilder (no 「Where」 label any more) and 「All sort levels」 the SortBuilder. Add 2 conditions that leave at least TWO rows, so the sort clause has an order to read — on the stock seed priority = high AND estimate_hours > 4 leaves ONE row on in_progress, a single-datapoint for acceptance[1] (QA run #24616): check the count first and pick a pair that keeps ≥ 2; open the SortBuilder and add a sort (due_date desc); type a term into the list's quick search that keeps rows (acceptance[2] reads it back; QA run #29890 used 'pipeline'); capture the data request", "assert the request's `filter` param is the MERGE of the view's stored rule AND the two toolbar conditions (buildEffectiveFilter/mergeFilterNodes), and `sort` carries the toolbar sort (e.g. sort=-due_date) — the console spells its list params without a `$`; the returned rows satisfy view-filter AND toolbar conditions", - "navigate away via an in-app nav link to another object (the link carries no query string, so the URL state is dropped), then navigate back to showcase_task in_progress through the Tasks nav entry and the view switcher (it lands on /view/showcase_task.in_progress). ⛔ Not the sidebar's 'In-Progress Tasks' Data Slices link: it opens /showcase_task/data?filter[status]=in_progress, a different surface from the saved view; screenshot; confirm the toolbar filter + sort restored", - "read where the toolbar filter and sort are kept: the signed-in user's own sys_user_preference row keyed ui.list.showcase_task (GET /api/v1/data/sys_user_preference filtered to that key; its value's perView. carries the filters and the sort — objectui ListPreferencesProvider.tsx, objectui#12418), and its localStorage write-through cache list-state::showcase_task. Confirm both are the signed-in user's: the row's user_id, and the cache key's user segment. (Only the search term stays under the older list-filters::showcase_task: key)", + "navigate away via an in-app nav link to another object (the link carries no query string, so the URL state is dropped), then navigate back to showcase_task in_progress through the Tasks nav entry and the view switcher (it lands on /view/showcase_task.in_progress). ⛔ Not the sidebar's 'In-Progress Tasks' Data Slices link: it opens /showcase_task/data?filter[status]=in_progress, a different surface from the saved view; screenshot; confirm the list opens as the view declares it: no toolbar filter chip, the view's own sort, an empty search, and no 「Discard」/「Save」 at the condition row's end (objectstack#35955: opening another object drops the draft). Then build the two conditions, the sort and the search again, open a record from the list and come back with the browser's Back: confirm the conditions, the sort and the search are all still there, with 「Discard」 and 「Save」 at the condition row's end", + "read where the toolbar filter and sort are kept: nowhere durable. Since objectstack#35955 they are the list's DRAFT, held in this tab's memory (ui/packages/app-shell/src/views/listDraftStore.ts): the signed-in user's sys_user_preference row keyed ui.list.showcase_task (GET /api/v1/data/sys_user_preference filtered to that key) gains no filters, sort or search from the change — it holds only what is remembered for the reader (perView..columnState.widths, rowHeight, viewOrder) — and localStorage gains no list-filters::showcase_task: key. Reload the page: the list opens as the view declares it", "sign out through the account menu (the avatar menu's Log out, user.logout in ui/packages/app-shell/src/layout/AppHeader.tsx; never by clearing storage). That Log out itself removes the signed-out user's list-state:* and list-filters:* keys from localStorage (purgeSignedOutUserClientState, ui/packages/auth/src/ActiveOrganizationStorage.ts, run by AuthProvider's sign-out), so the first account's keys are gone by the time the second signs in; the clause holds by that wipe AND by the user-keyed row. Sign in as the SECOND account; open the same object+view; confirm the first account's cached toolbar filter does NOT appear", "userFilters/URL: where UserFilters are hosted (an interface page or the userFilters surface — NOT a bare object list, ADR-0053), apply a quick-filter; copy the URL; open it in a fresh tab; confirm the uf_ params (comma-joined, URI-encoded) reproduce the same rows and uf__tab carries the active preset (ADR-0047)", "negative sweep: confirm tabs-element userFilters (preset chips, uf__tab) do NOT leak onto the bare object list view — dropdown chips the object view itself declares are allowed there (ADR-0047 amendment) and their uf_ params are not a leak" @@ -2966,16 +2966,16 @@ "evidence": "the request URL + row order" }, { - "clause": "the toolbar filter + search survive a FULL in-app navigation away and back — restored from the user's own list preference (sys_user_preference ui.list., cached in localStorage list-state::; URL params alone are lost on an in-app nav link that carries no query string, which is what the preference bridges)", + "clause": "the toolbar filter, sort and search are a DRAFT (objectstack#35955): they survive opening a record and coming back, and are dropped when another object (or view) is opened or the page reloads, so the list then opens as its view declares it; while a draft is held 「Discard」 and 「Save」 sit at the end of the condition row", "oracle": "dom", - "verify": "after a screenshot confirms the list rendered, the condition row under the view bar shows the two conditions as filter chips and the sort as a sort chip (objectstack#35549 / #35550; the same rows also show in the FilterBuilder and SortBuilder behind the field list's footers), and the quick search box shows the term (kept under list-filters::showcase_task:, steps[4]); the request re-issued on return carries the same merged `filter` param (the console spells it without a `$`; objectui app-shell/src/context/ListPreferencesProvider.tsx)", - "evidence": "before/after screenshots + the re-issued request" + "verify": "after a screenshot confirms the list rendered: on return through an in-app nav link from another object the condition row shows no filter chip, the sort chip is the view's own and the quick search box is empty, and the re-issued request carries only the view's filter; after a record opened from the list and Back, the condition row shows the two conditions as filter chips and the sort as a sort chip (objectstack#35549 / #35550), the quick search box shows the term, and the re-issued request carries the same merged `filter` param (the console spells it without a `$`; ui/packages/app-shell/src/views/listDraftStore.ts, objectViewListUrlState.ts)", + "evidence": "screenshots after each return (other object; record and Back) + the two re-issued requests" }, { - "clause": "the list state is USER-SCOPED — it is the user's own sys_user_preference row (user_id = the signed-in user), and its localStorage cache key embeds the user id (list-state::), so a second account on the same browser never reads the first account's filters (a filter value can be sensitive)", + "clause": "the list state is never shared across accounts — the draft is never written to the user's sys_user_preference row or to browser storage, so a second account on the same browser never reads the first account's filters (a filter value can be sensitive)", "oracle": "dom", - "verify": "read account A's ui.list.showcase_task preference row and its list-state cache key, then sign A out through the account menu's Log out and sign in as account B on the same browser and confirm B's view opens with no A-authored toolbar filter (B reads its own row, or none)", - "evidence": "the two accounts' storage keys + B's clean toolbar" + "verify": "with account A's toolbar filter on screen, read A's ui.list.showcase_task preference row (no filters or sort in it) and localStorage (no list-filters:* key for the view), then sign A out through the account menu's Log out and sign in as account B on the same browser and confirm B's view opens with no A-authored toolbar filter", + "evidence": "A's preference row + localStorage keys + B's clean toolbar" }, { "clause": "uf_* URL params make a filtered list shareable and reproducible: uf_ params (comma-joined, each URI-encoded) reproduce the same rows on a fresh load and uf__tab carries the active preset (ADR-0047)", @@ -3001,7 +3001,7 @@ }, "source": [ "objectui: packages/plugin-list/src/ListView.tsx (buildEffectiveFilter, convertFilterGroupToAST, mergeFilterNodes; $filter + $orderby assembly)", - "objectui: packages/app-shell/src/context/ListPreferencesProvider.tsx (objectui#12418 — the per-user ui.list. sys_user_preference row, cached in localStorage list-state::); packages/app-shell/src/views/listFilterStorage.ts now keeps only the search term", + "objectui: packages/app-shell/src/views/listDraftStore.ts (objectstack#35955 — the list's draft: filters, sort, grouping, search and columns, held in the tab's memory for one reader, object and view); packages/app-shell/src/context/ListPreferencesProvider.tsx (the per-user ui.list. sys_user_preference row, which since objectstack#35955 a list change writes only column widths, row height and the view order to)", "objectui: packages/app-shell/src/views/userFilterUrlState.ts (uf_* params, ADR-0047)", "ADR-0053 (userFilters belong to interface pages, suppressed on object list views); examples/app-showcase/src/ui/views/task.view.ts", "cross-ref: records-forms.list-view-capabilities (saved-view-filter / userFilters negative)" @@ -3078,6 +3078,12 @@ "date": "2026-11-20", "change": "steps[1] re-pointed to the two-row list toolbar (objectstack#35878): the view bar has no Filter or Sort button; Filter is the condition row's dashed 「Filter」 button or its 「+」 (condition-add-filter) and Sort its dashed 「Sort」 button or its one sort chip (condition-sort).", "ref": "#35878" + }, + { + "revision": 13, + "date": "2026-11-21", + "change": "steps[3], steps[4], acceptance[2] (clause, verify, evidence), acceptance[3] (clause, verify, evidence) and source[1] re-pointed to the list draft (objectstack#35955): a toolbar filter, sort and search are a draft held in the tab's memory, kept on opening a record and coming back and dropped on opening another object or view or on a reload; they are no longer stored in the user's ui.list. row. The in-app-navigation restore of revision 3 is replaced by the record round trip, and the user-scope clause now reads that nothing is stored at all. Not loosened: a second account must still see none of the first account's filters", + "ref": "#35955" } ] }, diff --git a/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx b/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx index 1937c17599a..5dd8890dd09 100644 --- a/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx @@ -23,11 +23,13 @@ * * ## The pins * - * 1. A header sort and a drag-reorder put NO metadata write on the wire, - * raise no error, and land as ONE preference write of the object's row. - * 2. objectui#12474 — the density toggle and a Hide Fields change each put - * NO metadata write on the wire, raise no error, and land as ONE - * preference write each, of the same row. + * 1. A header sort and a drag-reorder put NO metadata write on the wire + * and raise no error. The drag lands as ONE preference write of the + * object's row; the sort is the list's draft (objectstack#35955) and + * writes nothing. + * 2. objectui#12474 — the density toggle and a Hide Fields change put NO + * metadata write on the wire and raise no error. The density lands as + * ONE preference write of the same row; the hide is the draft's. * 3. CONTROL — the wall is live: a metadata write made in this same tree * (the real adapter's own view write, `createView`) is answered 403. * Since objectui#12474 no list toolbar control makes one, so the control @@ -121,6 +123,7 @@ import { toast } from 'sonner'; import { ConsoleShell, ConnectedShell } from '../ConsoleShell'; import { useAdapter } from '../../providers/AdapterProvider'; import { ObjectView } from '../../views/ObjectView'; +import { resetListDraftStoreForTests } from '../../views/listDraftStore'; import { createPreferenceFramework, preferenceRowId, type PreferenceFramework } from './preferenceFramework'; const FIELDS = { @@ -172,6 +175,7 @@ function boot() { const wait = (ms: number) => act(() => new Promise((resolve) => setTimeout(resolve, ms))); beforeEach(() => { + resetListDraftStoreForTests(); listProps = null; pageAdapter = null; localStorage.clear(); @@ -189,7 +193,7 @@ afterEach(() => { }); describe('a user\'s list state under a walled posture (objectui#12418)', () => { - it('a header sort and a drag-reorder write no metadata, raise no error, and land as one preference write', async () => { + it('a header sort and a drag-reorder write no metadata and raise no error; the drag lands as one preference write, the sort as the draft', async () => { boot(); await waitFor(() => expect(typeof listProps?.onSortChange).toBe('function'), { timeout: 5000 }); await screen.findByTestId('stub-reorder'); @@ -213,13 +217,11 @@ describe('a user\'s list state under a walled posture (objectui#12418)', () => { // An update of the row the boot read found: no second read, no insert. expect(write.id).toBe(preferenceRowId('u1', 'ui.list.account')); expect(fake.wire.gets.length).toBe(readsBefore); - expect(write.value).toEqual({ - viewOrder: [MINE_ID, ALL_ID], - perView: { [ALL_ID]: { sort: [{ field: 'name', order: 'desc' }] } }, - }); + // objectstack#35955 — the sort is the list's draft: it is stored nowhere. + expect(write.value).toEqual({ viewOrder: [MINE_ID, ALL_ID] }); }); - it('a density toggle and a Hide Fields change write no metadata, raise no error, and land as one preference write each (objectui#12474)', async () => { + it('a density toggle and a Hide Fields change write no metadata and raise no error; the density lands as one preference write, the hide as the draft (objectui#12474)', async () => { boot(); await waitFor(() => expect(typeof listProps?.schema?.onDensityChange).toBe('function'), { timeout: 5000 }); await wait(100); @@ -245,16 +247,11 @@ describe('a user\'s list state under a walled posture (objectui#12418)', () => { act(() => { listProps.onHiddenFieldsChange(['name']); }); - await waitFor(() => expect(fake.wire.writes).toHaveLength(2), { timeout: 3000 }); - await wait(400); + // Past the preference debounce (500 ms) and a round trip: nothing more is written. + await wait(900); expect(fake.wire.metaWrites).toEqual([]); expect(toast.error).not.toHaveBeenCalled(); - expect(fake.wire.writes).toHaveLength(2); - expect(fake.wire.writes[1].id).toBe(preferenceRowId('u1', 'ui.list.account')); - expect(fake.wire.writes[1].value).toEqual({ - viewOrder: [ALL_ID, MINE_ID], - perView: { [ALL_ID]: { rowHeight: 'medium', hiddenFields: ['name'] } }, - }); + expect(fake.wire.writes).toHaveLength(1); expect(listProps.schema.hiddenFields).toEqual(['name']); // No second read: each write updates the row the boot read found. expect(fake.wire.gets.length).toBe(readsBefore); diff --git a/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx b/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx index 3f77fac3073..8c8c59cfd7e 100644 --- a/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.emptyColumnsNoProjection-10694.test.tsx @@ -180,6 +180,7 @@ import '@objectstack/lint'; import { ObjectView } from './ObjectView'; import { ExpressionProvider } from '../providers/ExpressionProvider'; import { localListStateKey } from '../context/ListPreferencesProvider'; +import { listDraftScope, patchListDraft, readListDraft, resetListDraftStoreForTests } from './listDraftStore'; const OBJECT_NAME = 'duly_task'; @@ -316,13 +317,16 @@ const viewWrites = (dataSource: any): unknown[][] => [ ]; /** - * objectui#12474 — the hidden fields this user stored for `viewId`, read off - * their list state. This harness mounts no preference provider, so the state - * is this browser's cache (the provider-less fallback). + * objectui#12474 — the hidden fields this user chose for `viewId`. Since + * objectstack#35955 the choice is the list's DRAFT (`./listDraftStore.ts`): + * kept while the reader opens a record and comes back (a remount here), never + * stored. The second half reads that nothing reaches the reader's stored + * state either. */ function storedHiddenFields(viewId: string): unknown { const raw = localStorage.getItem(localListStateKey('u1', OBJECT_NAME)); - return raw ? JSON.parse(raw)?.perView?.[viewId]?.hiddenFields : undefined; + expect(raw ? JSON.parse(raw)?.perView?.[viewId]?.hiddenFields : undefined).toBeUndefined(); + return readListDraft(listDraftScope('u1', OBJECT_NAME, viewId)).hiddenFields; } /** Longer than the old view write's 300ms debounce, with room to spare. */ @@ -381,6 +385,7 @@ async function expectSessionOnlyToggle(dataSource: any): Promise { beforeEach(() => { storedViews = {}; localStorage.clear(); + resetListDraftStoreForTests(); unreadable.clear(); vi.stubGlobal( 'fetch', @@ -442,7 +447,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the expect(storedHiddenFields(PROBE_ID)).toBeUndefined(); }); - it('CONTROL: on a system view that declares `columns`, the toggle is stored as the user\'s own, and the view is not written (objectui#12474)', async () => { + it('CONTROL: on a system view that declares `columns`, the toggle is the reader\'s draft, and the view is not written (objectui#12474, objectstack#35955)', async () => { const dataSource = makeDataSource(viewWriteSpies()); const listViews = { [PROBE_ID]: { @@ -458,12 +463,13 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the expect(viewWrites(dataSource)).toEqual([]); cleanup(); - // Reload: the user's choice is applied over the view's own `columns`. + // Back to the list (objectstack#35955: the draft outlives a record open): + // the choice is applied over the view's own `columns`. await mountRoute(listViews, PROBE_ID, makeDataSource()); await waitFor(() => expect(drawn).toEqual(['name', 'stage'])); }); - it('THE FIX (objectui#12505): on a saved view with no `columns`, the hide is this user\'s own and survives a reload; the row is not written', async () => { + it('THE FIX (objectui#12505): on a saved view with no `columns`, the hide is this reader\'s draft and survives coming back to the list; the row is not written', async () => { // objectui#12474 made the hide session-only here (it used to persist only // through a whole-view write that declared the drawn defaults as `columns` // for every user). It is now stored on the user's own list state and @@ -480,7 +486,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the expect(viewWrites(first)).toEqual([]); cleanup(); - // Reload: the stored list is applied over the drawn defaults. + // Back to the list: the draft is applied over the drawn defaults. await mountRoute(SAVED_BESIDE, SAVED_ID, savedViewSource()); await waitFor(() => expect(drawn).toEqual(defaults.filter((f) => f !== 'region')), { timeout: 5000 }); }); @@ -494,10 +500,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the const defaults = drawn!; cleanup(); - localStorage.setItem( - localListStateKey('u1', OBJECT_NAME), - JSON.stringify({ perView: { [SAVED_ID]: { hiddenFields: ['amount'] } } }), - ); + patchListDraft(listDraftScope('u1', OBJECT_NAME, SAVED_ID), { hiddenFields: ['amount'] }); await mountRoute(SAVED_BESIDE, SAVED_ID, savedViewSource({ hiddenFields: ['stage'] })); await waitFor(() => expect(drawn).toEqual(defaults.filter((f) => f !== 'amount')), { timeout: 5000 }); }); @@ -510,10 +513,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the expect(defaults).not.toContain('id'); cleanup(); - localStorage.setItem( - localListStateKey('u1', OBJECT_NAME), - JSON.stringify({ perView: { [SAVED_ID]: { hiddenFields: ['ghost', 'id', 'region'] } } }), - ); + patchListDraft(listDraftScope('u1', OBJECT_NAME, SAVED_ID), { hiddenFields: ['ghost', 'id', 'region'] }); await mountRoute(SAVED_BESIDE, SAVED_ID, savedViewSource()); await waitFor(() => expect(drawn).toEqual(defaults.filter((f) => f !== 'region')), { timeout: 5000 }); }); @@ -535,10 +535,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the it('CONTROL (objectui#12505): a stored list on a SYSTEM view with no `columns` is still not applied (ruling 5839344270, B)', async () => { const defaults = await drawView({ columns: [] }); - localStorage.setItem( - localListStateKey('u1', OBJECT_NAME), - JSON.stringify({ perView: { [PROBE_ID]: { hiddenFields: ['region'] } } }), - ); + patchListDraft(listDraftScope('u1', OBJECT_NAME, PROBE_ID), { hiddenFields: ['region'] }); expect(await drawView({ columns: [] })).toEqual(defaults); }); @@ -556,10 +553,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the await waitFor(() => expect(drawn).toEqual(['name', 'owner'])); cleanup(); - localStorage.setItem( - localListStateKey('u1', OBJECT_NAME), - JSON.stringify({ perView: { [PROBE_ID]: { hiddenFields: ['region'] } } }), - ); + patchListDraft(listDraftScope('u1', OBJECT_NAME, PROBE_ID), { hiddenFields: ['region'] }); await mountRoute(listViews, PROBE_ID, makeDataSource()); // `stage` is back (it is in `columns`); `region` is in no `columns`, so // naming it hides nothing and adds nothing. @@ -569,10 +563,7 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the // On a view that declares no projection the stored list is not applied. const unprojected = { [PROBE_ID]: { name: PROBE_ID, label: 'Probe', type: 'grid', columns: [] } }; const defaults = await drawView({ columns: [] }); - localStorage.setItem( - localListStateKey('u1', OBJECT_NAME), - JSON.stringify({ perView: { [PROBE_ID]: { hiddenFields: ['stage'] } } }), - ); + patchListDraft(listDraftScope('u1', OBJECT_NAME, PROBE_ID), { hiddenFields: ['stage'] }); await mountRoute(unprojected, PROBE_ID, makeDataSource()); await waitFor(() => expect(drawn).toEqual(defaults)); }); @@ -642,4 +633,18 @@ describe('an unprojected view applies neither hiddenFields nor fieldOrder on the // [name, stage, owner] projected; `stage` hidden; `owner` sorted first. await waitFor(() => expect(drawn).toEqual(['owner', 'name'])); }); + it('objectstack#35955: hidden fields an earlier console stored for the reader no longer apply', async () => { + const listViews = { + [PROBE_ID]: { + name: PROBE_ID, label: 'Probe', type: 'grid', + columns: ['name', 'stage', 'owner'], userActions: { hideFields: true }, + }, + }; + localStorage.setItem( + localListStateKey('u1', OBJECT_NAME), + JSON.stringify({ perView: { [PROBE_ID]: { hiddenFields: ['stage'] } } }), + ); + await mountRoute(listViews, PROBE_ID, makeDataSource()); + await waitFor(() => expect(drawn).toEqual(['name', 'stage', 'owner'])); + }); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.listPageInUrl-30850.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listPageInUrl-30850.test.tsx index 432168acad0..1d75d7bb358 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listPageInUrl-30850.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listPageInUrl-30850.test.tsx @@ -86,6 +86,7 @@ import '@object-ui/plugin-grid'; import '@objectstack/lint'; import { ExpressionProvider } from '../providers/ExpressionProvider'; import { LIST_PAGE_PARAM, LIST_SEARCH_PARAM } from './userFilterUrlState'; +import { resetListDraftStoreForTests } from './listDraftStore'; const OBJ = 'paged_task_30850'; const VIEW_ID = 'all'; @@ -219,6 +220,8 @@ afterEach(() => { vi.restoreAllMocks(); setWidth(DESKTOP_WIDTH); window.localStorage.clear(); + // objectstack#35955 — the list's draft lives in the module: one test's search is not the next one's. + resetListDraftStoreForTests(); window.history.replaceState(null, '', '/'); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.listPersonalized-28950.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listPersonalized-28950.test.tsx index ae23b8a5b30..c7192e39f05 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listPersonalized-28950.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listPersonalized-28950.test.tsx @@ -1,6 +1,6 @@ /** - * objectstack#28950 — the 「Personalized」 marker beside the list title and its - * one reset, at the host seam: the real object page, the real + * objectstack#35955 — Discard and Save on a list that holds a draft (the + * 「Personalized」 marker of objectstack#28950 before it), at the host seam: the real object page, the real * `ListPreferencesProvider` and the real router, with `ListView` captured (its * own half, what of the list differs from the view, is pinned in plugin-list's * `ListView.personalization-28950.test.tsx`). @@ -11,15 +11,16 @@ * Filter panel, search, sort, grouping and every chip) and keeps every * other param: a `filter[...]` scope a "View all" link opened the list * with, the open record. - * 2. The marker is drawn only while the list reports a part (or a column - * layout is stored), names the parts, and is the header's one reset: the - * ⋯ menu carries none. - * 3. After a reload (the list seeded from the URL), the reset opens the list + * 2. Discard and Save are drawn only while the list reports a draft part + * (or holds a column order or an added column): the row height and a + * search alone draw nothing. Save's menu names the parts; the compact + * face holds Discard in it; the ⋯ menu carries no reset. + * 3. After a reload (the list seeded from the URL), Discard opens the list * as the view declares it: the address bar has no `uf_*` param left, a * reload would not bring the old list back, and the chips start empty. - * This is the case the header's old "Reset view" re-seeded from the URL. - * 4. In session, the reset also drops the cached search term, which the old - * "Reset view" wrote back into the address bar. + * 4. In session, the search term is the draft's, kept in no storage, and + * Discard drops it. + * 5. Column widths are the reader's: never a draft, and Discard keeps them. */ import * as React from 'react'; @@ -27,7 +28,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; // `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at // collection, never inside a case's clocked window (`check:test-source-alias`). import '@objectstack/lint'; -import { render, cleanup, act, screen, fireEvent, waitFor } from '@testing-library/react'; +import { render, cleanup, act, screen, fireEvent, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; @@ -112,6 +113,7 @@ vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ })); import { ObjectView, type ConsoleObjectViewProps } from './ObjectView'; +import { listDraftScope, readListDraft, resetListDraftStoreForTests } from './listDraftStore'; import { ExpressionProvider } from '../providers/ExpressionProvider'; import { UserStateAdaptersProvider, useAttachListStateFamily } from '../context/UserStateAdapters'; import { ListPreferencesProvider } from '../context/ListPreferencesProvider'; @@ -233,6 +235,7 @@ beforeEach(() => { listProps = null; currentSearch = ''; localStorage.clear(); + resetListDraftStoreForTests(); client = new MetadataClient({ baseUrl: 'http://localhost', fetch: vi.fn(async () => json({ data: [] }, 200)) as unknown as typeof fetch }); vi.stubGlobal('fetch', vi.fn(async () => json({ data: [] }, 200))); vi.spyOn(console, 'error').mockImplementation(() => {}); @@ -261,31 +264,40 @@ describe('withoutListStateParams (objectstack#28950)', () => { }); }); -describe('the 「Personalized」 marker and its one reset (objectstack#28950)', () => { - it('is drawn only while the list reports a part, names the parts, and the header ⋯ carries no reset', async () => { +/** Open a Radix menu the way a pointer does (jsdom sends no click-open). */ +function openMenu(trigger: HTMLElement) { + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' }); +} + +describe('Discard and Save, while the list holds a draft (objectstack#35955; the marker of objectstack#28950 before it)', () => { + it('is drawn only while the list reports a draft part, names the parts in the Save menu, and the header ⋯ carries no reset', async () => { mount(makeFamily({})); await listReady(); - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); + expect(screen.queryByTestId('list-draft')).toBeNull(); + + // The row height is the reader's, and a search alone is not a change to the view. + act(() => listProps.onPersonalizationChange(['search', 'density'])); + await wait(50); + expect(screen.queryByTestId('list-draft')).toBeNull(); act(() => listProps.onPersonalizationChange(['sort', 'search', 'rowColor'])); - const marker = await screen.findByTestId('list-personalized-marker'); - // Named by its label, which the icon-only phone face keeps as `aria-label`. - expect(marker.getAttribute('aria-label')).toBe('console.objectView.personalized'); - fireEvent.click(marker); - const parts = await screen.findByTestId('list-personalized-parts'); - expect([...parts.querySelectorAll('li')].map((li) => li.getAttribute('data-part'))).toEqual(['search', 'sort', 'rowColor']); - expect([...parts.querySelectorAll('li')].map((li) => li.textContent)).toEqual([ - 'console.objectView.personalizedParts.search', - 'console.objectView.personalizedParts.sort', - 'console.objectView.personalizedParts.rowColor', - ]); + expect(await screen.findByTestId('list-draft-discard')).toBeTruthy(); + // The compact face (a phone, a narrow list) holds Discard in Save's menu. + openMenu(screen.getByTestId('list-draft-compact')); + const menu = await screen.findByTestId('list-draft-compact-menu'); + expect(within(menu).getByTestId('list-draft-parts').textContent).toBe( + 'console.objectView.draft.heading: console.objectView.personalizedParts.sort' + + 'console.objectView.draft.partSeparator' + + 'console.objectView.personalizedParts.rowColor', + ); + expect(within(menu).getByTestId('list-draft-compact-discard')).toBeTruthy(); expect(screen.queryByTestId('object-view-reset-view-button')).toBeNull(); act(() => listProps.onPersonalizationChange([])); - await waitFor(() => expect(screen.queryByTestId('list-personalized-marker')).toBeNull()); + await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); }); - it('after a reload, the reset opens the list as the view declares it and leaves no `uf_*` param behind', async () => { + it('after a reload, Discard opens the list as the view declares it and leaves no `uf_*` param behind', async () => { const family = makeFamily({}); mount(family, personalizedQuery()); await listReady(); @@ -297,9 +309,8 @@ describe('the 「Personalized」 marker and its one reset (objectstack#28950)', const before = listProps; act(() => listProps.onPersonalizationChange(['filters', 'search', 'sort', 'grouping'])); - fireEvent.click(await screen.findByTestId('list-personalized-marker')); await act(async () => { - fireEvent.click(await screen.findByTestId('list-personalized-reset')); + fireEvent.click(await screen.findByTestId('list-draft-discard')); }); await wait(400); @@ -312,46 +323,51 @@ describe('the 「Personalized」 marker and its one reset (objectstack#28950)', expect(ufParams()).toEqual([]); // The drill scope is not the reader's list state: it stays. expect(new URLSearchParams(currentSearch).get('filter[owner]')).toBe('u1'); - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); + expect(screen.queryByTestId('list-draft')).toBeNull(); }); - it('in session, the reset drops the cached search term, which would otherwise seed the list again', async () => { + it('in session, the search is the draft\'s: kept nowhere durable, and Discard drops it', async () => { mount(makeFamily({})); await listReady(); const cacheKey = buildListFilterKey(session.userId, OBJECT_NAME, SYSTEM_ID); act(() => listProps.onSearchChange('Alan')); await wait(400); - expect(JSON.parse(localStorage.getItem(cacheKey!) ?? '{}').search).toBe('Alan'); + expect(localStorage.getItem(cacheKey!)).toBeNull(); + expect(readListDraft(listDraftScope(session.userId, OBJECT_NAME, SYSTEM_ID)).search).toBe('Alan'); expect(new URLSearchParams(currentSearch).get('uf__search')).toBe('Alan'); - act(() => listProps.onPersonalizationChange(['search'])); - fireEvent.click(await screen.findByTestId('list-personalized-marker')); + act(() => listProps.onPersonalizationChange(['search', 'sort'])); await act(async () => { - fireEvent.click(await screen.findByTestId('list-personalized-reset')); + fireEvent.click(await screen.findByTestId('list-draft-discard')); }); await wait(400); - expect(localStorage.getItem(cacheKey!)).toBeNull(); + expect(readListDraft(listDraftScope(session.userId, OBJECT_NAME, SYSTEM_ID))).toEqual({}); expect(listProps.initialSearchTerm).toBeUndefined(); expect(ufParams()).toEqual([]); }); - it('CONTROL: a stored column layout alone draws the marker, and the reset drops it with the rest of the entry', async () => { + it('column widths are the reader\'s, never a draft: a stored width draws nothing, and Discard keeps it', async () => { const family = makeFamily({ [`ui.list.${OBJECT_NAME}`]: { perView: { [SYSTEM_ID]: { columnState: { widths: { name: 280 } } } } } }); mount(family); await listReady(); + expect(screen.queryByTestId('list-draft')).toBeNull(); + expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); - fireEvent.click(await screen.findByTestId('list-personalized-marker')); - const parts = await screen.findByTestId('list-personalized-parts'); - expect([...parts.querySelectorAll('li')].map((li) => li.getAttribute('data-part'))).toEqual(['columns']); + // A drag of the column order is a draft; the width rides on the same report. + act(() => listProps.schema.onColumnStateChange({ order: ['amount', 'name'], widths: { name: 280 } })); + expect(await screen.findByTestId('list-draft-discard')).toBeTruthy(); await act(async () => { - fireEvent.click(screen.getByTestId('list-personalized-reset')); + fireEvent.click(screen.getByTestId('list-draft-discard')); }); await wait(700); - expect(family.save).toHaveBeenCalledWith(`ui.list.${OBJECT_NAME}`, {}); - expect(listProps.schema.columnState).toEqual({}); - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); + expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); + expect(screen.queryByTestId('list-draft')).toBeNull(); + // Nothing of the order reached the reader's stored row. + for (const [, value] of family.save.mock.calls) { + expect(JSON.stringify(value)).not.toContain('order'); + } }); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx index 37dff773b83..9ad6b526a31 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx @@ -101,6 +101,7 @@ import { ExpressionProvider } from '../providers/ExpressionProvider'; import { buildListFilterKey } from './listFilterStorage'; import { LIST_FILTER_PARAM, LIST_GROUP_PARAM, LIST_SEARCH_PARAM, LIST_SORT_PARAM, withoutListStateParams } from './userFilterUrlState'; import { localListStateKey } from '../context/ListPreferencesProvider'; +import { listDraftScope, patchListDraft, resetListDraftStoreForTests, type ListDraftPatch } from './listDraftStore'; import { acceptStoredFilters, acceptStoredSort } from './objectViewListUrlState'; import { toast } from 'sonner'; @@ -233,13 +234,19 @@ function link(path: string, state: { filter?: unknown; search?: string; sort?: u const URGENT = { logic: 'and', conditions: [{ field: 'priority', operator: 'equals', value: 'urgent' }] }; +/** + * The list's draft for one view (objectstack#35955, `./listDraftStore.ts`): + * what the reader changed and left there when they opened a record — the + * state a bare URL opens on. (It used to be the per-browser cache.) + */ function storeListState(viewId: string, state: { filters?: unknown; search?: string }) { - localStorage.setItem(buildListFilterKey('u1', OBJ, viewId)!, JSON.stringify(state)); + patchListDraft(listDraftScope('u1', OBJ, viewId), state as ListDraftPatch); } beforeEach(() => { cleanup(); localStorage.clear(); + resetListDraftStoreForTests(); listQueries = []; groupQueries = []; rows = []; @@ -273,7 +280,7 @@ describe('a list is a link (objectui#11860)', () => { expect(screen.getByTestId('search-active-keyword').textContent).toBe('acme'); }); - it('a link wins over the per-user cache WHOLE — nothing of the cache is merged in', async () => { + it('a link wins over the list\'s draft WHOLE — nothing of the draft is merged in', async () => { storeListState('all', { filters: { id: 'root', logic: 'and', conditions: [{ id: 'r', field: 'status', operator: 'equals', value: 'open' }] }, search: 'mine', @@ -286,7 +293,7 @@ describe('a list is a link (objectui#11860)', () => { expect(q.$search).toBeUndefined(); }); - it('a bare URL restores the per-user cache, and the address bar then shows it — replaced, not pushed', async () => { + it('a bare URL restores the list\'s draft (a record opened and closed), and the address bar then shows it — replaced, not pushed', async () => { storeListState('all', { filters: { id: 'root', logic: 'and', conditions: [{ id: 'r', field: 'status', operator: 'equals', value: 'open' }] }, search: 'mine', @@ -429,11 +436,28 @@ describe('a malformed or stale param is dropped — the list opens and nothing t }); }); -/** This user's stored state for one view (objectui#12418's per-browser cache, the shape the server row has). */ +/** The list's draft for one view (objectstack#35955; it was objectui#12418's stored state, the same shape). */ function storeViewPreference(viewId: string, pref: { sort?: unknown; filters?: unknown }) { - localStorage.setItem(localListStateKey('u1', OBJ), JSON.stringify({ perView: { [viewId]: pref } })); + patchListDraft(listDraftScope('u1', OBJ, viewId), pref as ListDraftPatch); } +describe('objectstack#35955 — state an earlier console stored for the reader no longer opens the list', () => { + it('a stored sort and filter, in the server row\'s cache or the older per-browser key, are not applied', async () => { + localStorage.setItem(localListStateKey('u1', OBJ), JSON.stringify({ + perView: { all: { sort: [{ field: 'due_date', order: 'desc' }], filters: { id: 'root', logic: 'and', conditions: [{ id: 'p', field: 'priority', operator: 'equals', value: 'urgent' }] } } }, + })); + localStorage.setItem(buildListFilterKey('u1', OBJ, 'all')!, JSON.stringify({ search: 'mine' })); + const host = await mountHost([`${VIEW}/all`]); + const q = lastQuery(); + expect(filterOf(q)).not.toContain('urgent'); + expect(q.$search).toBeUndefined(); + expect(q.$orderby).not.toEqual([{ field: 'due_date', order: 'desc' }]); + const params = new URLSearchParams(host.search()); + expect(params.has(LIST_FILTER_PARAM)).toBe(false); + expect(params.has(LIST_SEARCH_PARAM)).toBe(false); + }); +}); + describe('a link\'s filter is judged whole (objectstack#31869)', () => { it('CONTROL: a link whose every condition passes applies them all, with no notice', async () => { perms.isLoaded = true; @@ -821,7 +845,7 @@ describe('the link a sign-in hands over opens the next user\'s list on their own expect(host.search()).not.toContain('urgent'); }); - it('the next user\'s own stored state applies there, and nothing of A\'s is merged in', async () => { + it('the next user\'s own draft applies there, and nothing of A\'s is merged in', async () => { storeListState('sorted', { filters: { id: 'root', logic: 'and', conditions: [{ id: 'r', field: 'status', operator: 'equals', value: 'open' }] }, search: 'mine', diff --git a/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts b/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts index bf24a0c0eb4..b101cfa3980 100644 --- a/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts +++ b/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts @@ -347,9 +347,9 @@ describe('objectui#12504 census — the toolbar-to-view write family is retired' expect(objectViewCode).toMatch(/await persistRuntimeMetadata\('view', vid, buildViewConfigSaveBody\(objectName, draft\)/); }); - it('CONTROL: the doors objectui#12474 moved still write the user\'s own list state', () => { + it('CONTROL: the doors objectui#12474 moved write the reader\'s state, never the view (density kept, hidden fields a draft since objectstack#35955)', () => { expect(objectViewCode).toMatch(/onDensityChange:\s*\(mode\)\s*=>\s*\{\s*listPrefs\.patchView\(/); - expect(objectViewCode).toMatch(/const persistHiddenFields = \(hidden: string\[\]\) => \{[\s\S]{0,120}?listPrefs\.patchView\(viewDef\.id, \{ hiddenFields: hidden \}\)/); + expect(objectViewCode).toMatch(/const persistHiddenFields = \(hidden: string\[\]\) => \{[\s\S]{0,120}?listDraft\.patch\(\{ hiddenFields: hidden \}\)/); }); it('`DataSource` declares no `updateViewConfig` (@object-ui/types)', () => { diff --git a/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx b/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx index da24e991b33..27f1d69418e 100644 --- a/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx @@ -105,6 +105,7 @@ vi.mock('./MetadataInspector', () => ({ vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); import { ObjectView } from './ObjectView'; +import { listDraftScope, patchListDraft, readListDraft, resetListDraftStoreForTests, type ListDraftPatch } from './listDraftStore'; import { ExpressionProvider } from '../providers/ExpressionProvider'; import { UserStateAdaptersProvider, useAttachListStateFamily } from '../context/UserStateAdapters'; import { ListPreferencesProvider, listPreferenceKey, localListStateKey } from '../context/ListPreferencesProvider'; @@ -247,6 +248,7 @@ beforeEach(() => { grants.isLoaded = false; grants.denied.clear(); localStorage.clear(); + resetListDraftStoreForTests(); fetchCalls.length = 0; vi.mocked(toast.error).mockClear(); Object.defineProperty(window, 'innerWidth', { value: 1440, configurable: true, writable: true }); @@ -603,8 +605,17 @@ describe('objectstack#30034 — a personal view opened by its address never carr describe('objectstack#30073 — a personal view\'s conditions are Filter panel rows, saved back by 保存', () => { const ROME = { id: 'root', logic: 'and' as const, conditions: [{ id: 'r1', field: 'city', operator: 'equals', value: 'Rome' }] }; const romeLink = (path: string) => `${path}?${applyListStateParams(new URLSearchParams(), { filters: ROME as never }).toString()}`; - const storeListState = (state: unknown) => localStorage.setItem(localListStateKey('u1', 'crm_lead'), JSON.stringify(state)); - const storedListState = () => JSON.parse(localStorage.getItem(localListStateKey('u1', 'crm_lead')) ?? '{}'); + // objectstack#35955 — the list's draft (what the reader changed and left + // when they opened a record), the state a bare address opens on. + const storeListState = (state: { perView: Record }) => { + for (const [viewId, draft] of Object.entries(state.perView)) patchListDraft(listDraftScope('u1', 'crm_lead', viewId), draft); + }; + const draftOf = (viewId: string) => readListDraft(listDraftScope('u1', 'crm_lead', viewId)); + /** Open Save's menu and pick 「Save to this view」. */ + const saveToThisView = async () => { + fireEvent.pointerDown(await screen.findByTestId('list-draft-save'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await screen.findByTestId('list-draft-save-to-view')); + }; const filterTrigger = () => screen.getByTestId('condition-add-filter'); const lastLeadRead = (dataSource: ReturnType['dataSource']) => JSON.stringify(leadReads(dataSource).at(-1)); @@ -622,18 +633,17 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r // The panel row is the condition: it is not laid under the list as well. await waitFor(() => expect(lastLeadRead(dataSource)).toContain('Paris')); expect(lastLeadRead(dataSource).match(/Paris/g)).toHaveLength(1); - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); + expect(screen.queryByTestId('list-draft')).toBeNull(); expect(dataSource.update).not.toHaveBeenCalled(); }); - it('an edited panel is personalized and offers 保存, which writes the panel into that view in the stored shape', async () => { + it('an edited panel is a draft and Save offers 「Save to this view」, which writes the panel into that view in the stored shape', async () => { const { dataSource } = mountLeads(romeLink('/apps/crm/crm_lead/view/pv_mine')); await listToolbar(); - const marker = await screen.findByTestId('list-personalized-marker'); + await screen.findByTestId('list-draft-discard'); // Nothing is written back while the edit is only on screen. expect(dataSource.update).not.toHaveBeenCalled(); - fireEvent.click(marker); - fireEvent.click(await screen.findByTestId('list-personalized-save')); + await saveToThisView(); await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); const [resource, id, patch] = dataSource.update.mock.calls[0]; @@ -641,16 +651,18 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r expect(ListViewSchema.safeParse(patch.config).success).toBe(true); expect(patch.config.data).toEqual({ provider: 'object', object: 'crm_lead' }); expect(patch.config.filter).toEqual([{ field: 'city', operator: 'equals', value: 'Rome' }]); - // The list opens again on the saved view: its rows are the view's own. - await waitFor(() => expect(screen.queryByTestId('list-personalized-marker')).toBeNull()); + // The list opens again on the saved view: its rows are the view's own, + // Discard and Save go, and one notice says it was saved. + await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); await waitFor(() => expect(lastLeadRead(dataSource)).toContain('Rome')); expect(lastLeadRead(dataSource)).not.toContain('Paris'); + expect(toast.success).toHaveBeenCalledWith('Saved'); }); it('Options offers the same 保存 beside 恢复默认 (objectstack#35551): it writes the panel into that view', async () => { const { dataSource } = mountLeads(romeLink('/apps/crm/crm_lead/view/pv_mine')); await listToolbar(); - await screen.findByTestId('list-personalized-marker'); + await screen.findByTestId('list-draft-discard'); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); const reset = await screen.findByTestId('display-reset-button'); expect(reset).toBeEnabled(); @@ -660,7 +672,7 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r const [resource, id, patch] = dataSource.update.mock.calls[0]; expect([resource, id, Object.keys(patch)]).toEqual(['sys_personal_view', 'pv_mine', ['config']]); expect(patch.config.filter).toEqual([{ field: 'city', operator: 'equals', value: 'Rome' }]); - await waitFor(() => expect(screen.queryByTestId('list-personalized-marker')).toBeNull()); + await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); // Nothing differs from the view now: no 保存, and 恢复默认 is dimmed. fireEvent.click(screen.getByTestId('toolbar-display-trigger')); await waitFor(() => expect(screen.getByTestId('display-reset-button')).toBeDisabled()); @@ -670,10 +682,10 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r it('Options\' 恢复默认 is the marker\'s reset: the view opens as its own again', async () => { const { dataSource } = mountLeads(romeLink('/apps/crm/crm_lead/view/pv_mine')); await listToolbar(); - await screen.findByTestId('list-personalized-marker'); + await screen.findByTestId('list-draft-discard'); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); fireEvent.click(await screen.findByTestId('display-reset-button')); - await waitFor(() => expect(screen.queryByTestId('list-personalized-marker')).toBeNull()); + await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); await waitFor(() => expect(lastLeadRead(dataSource)).toContain('Paris')); expect(dataSource.update).not.toHaveBeenCalled(); }); @@ -683,20 +695,20 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r grants.denied.add('sys_personal_view:update'); mountLeads(romeLink('/apps/crm/crm_lead/view/pv_mine')); await listToolbar(); - await screen.findByTestId('list-personalized-marker'); + await screen.findByTestId('list-draft-discard'); fireEvent.click(screen.getByTestId('toolbar-display-trigger')); expect(await screen.findByTestId('display-reset-button')).toBeEnabled(); expect(screen.queryByTestId('display-save-button')).toBeNull(); }); - it('a reader without update on their views is not offered 保存', async () => { + it('a reader without update on their views is not offered 「Save to this view」, only 「Save as my view」', async () => { grants.isLoaded = true; grants.denied.add('sys_personal_view:update'); mountLeads(romeLink('/apps/crm/crm_lead/view/pv_mine')); await listToolbar(); - fireEvent.click(await screen.findByTestId('list-personalized-marker')); - await screen.findByTestId('list-personalized-reset'); - expect(screen.queryByTestId('list-personalized-save')).toBeNull(); + fireEvent.pointerDown(await screen.findByTestId('list-draft-save'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + expect(await screen.findByTestId('list-draft-save-as')).toBeInTheDocument(); + expect(screen.queryByTestId('list-draft-save-to-view')).toBeNull(); }); it('a panel the fold cannot write keeps the refusal: nothing is written to the view', async () => { @@ -709,8 +721,7 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r }); const { dataSource } = mountLeads('/apps/crm/crm_lead/view/pv_mine'); await listToolbar(); - fireEvent.click(await screen.findByTestId('list-personalized-marker')); - fireEvent.click(await screen.findByTestId('list-personalized-save')); + await saveToThisView(); await waitFor(() => expect(toast.error).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ description: expect.stringContaining('nested condition groups') }), @@ -734,7 +745,7 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r storeListState({ perView: { v1: { filters: ROME } } }); const first = mountLeads(romeLink('/apps/crm/crm_lead/view/v1')); await listToolbar(); - await screen.findByTestId('list-personalized-marker'); + await screen.findByTestId('list-draft-discard'); const card = await saveAsMyView(openSwitcher(), 'Rome leads'); fireEvent.click(within(card).getByTestId('create-view-card-submit')); @@ -743,9 +754,9 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r expect(first.dataSource.create.mock.calls[0][1].config.filter).toEqual([{ field: 'city', operator: 'equals', value: 'Rome' }]); await waitFor(() => expect(switcher()).toHaveTextContent('Rome leads')); // The new view holds the conditions as its own rows: nothing reads personalized. - await waitFor(() => expect(screen.queryByTestId('list-personalized-marker')).toBeNull()); - // The source's stored list state is gone. - expect(storedListState().perView?.v1).toBeUndefined(); + await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); + // The source's draft is gone. + expect(draftOf('v1')).toEqual({}); first.unmount(); const again = mountLeads('/apps/crm/crm_lead/view/v1'); @@ -754,6 +765,28 @@ describe('objectstack#30073 — a personal view\'s conditions are Filter panel r await waitFor(() => expect(leadReads(again.dataSource).length).toBeGreaterThan(0)); expect(lastLeadRead(again.dataSource)).not.toContain('Rome'); expect(filterTrigger()).toHaveAttribute('data-empty', 'true'); - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); + expect(screen.queryByTestId('list-draft')).toBeNull(); + }); + + it('objectstack#35955 — 「Save as my view」 in Save\'s menu asks a name first (« copy»), saves the draft, opens the new view and says so', async () => { + const first = mountLeads(romeLink('/apps/crm/crm_lead/view/v1')); + await listToolbar(); + fireEvent.pointerDown(await screen.findByTestId('list-draft-save'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await screen.findByTestId('list-draft-save-as')); + const input = await screen.findByDisplayValue('View 1 copy'); + // Nothing is written before the name is given. + expect(first.dataSource.create).not.toHaveBeenCalled(); + fireEvent.change(input, { target: { value: 'Rome leads' } }); + fireEvent.click(screen.getByTestId('personal-view-name-submit')); + + await waitFor(() => expect(first.dataSource.create).toHaveBeenCalledTimes(1)); + const [resource, row] = first.dataSource.create.mock.calls[0]; + expect(resource).toBe('sys_personal_view'); + expect(row.label).toBe('Rome leads'); + expect(row.config.filter).toEqual([{ field: 'city', operator: 'equals', value: 'Rome' }]); + await waitFor(() => expect(switcher()).toHaveTextContent('Rome leads')); + expect(toast.success).toHaveBeenCalledWith('Saved'); + await waitFor(() => expect(screen.queryByTestId('list-draft')).toBeNull()); + expect(draftOf('v1')).toEqual({}); }); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx b/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx index 5f8eabee27e..2e8ee2b90df 100644 --- a/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx @@ -92,6 +92,7 @@ vi.mock('./MetadataInspector', () => ({ vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); import { ObjectView } from './ObjectView'; +import { resetListDraftStoreForTests } from './listDraftStore'; import { ExpressionProvider } from '../providers/ExpressionProvider'; import { buildListFilterKey } from './listFilterStorage'; import { LIST_FILTER_PARAM } from './userFilterUrlState'; @@ -213,6 +214,7 @@ async function mountHost(entry: string): Promise { beforeEach(() => { cleanup(); localStorage.clear(); + resetListDraftStoreForTests(); listQueries = []; window.history.replaceState(null, '', '/'); vi.stubGlobal( @@ -270,17 +272,19 @@ describe('a view switch reads the next view\'s own URL for its quick filters (ob expect(chipCount()).toBe(1); }); - it('the view switched to still opens on its per-user cache — objectui#11915\'s precedence is untouched', async () => { + it('the view switched to opens as its view declares it: no other list\'s draft and no older per-browser filter ride along (objectstack#35955)', async () => { + // A Filter panel group an earlier console kept for this browser: since + // objectstack#35955 a list opens on its draft only, never on stored state. localStorage.setItem( buildListFilterKey('u1', OBJ, 'qb')!, JSON.stringify({ filters: { id: 'root', logic: 'and', conditions: [{ id: 'r', field: 'status', operator: 'equals', value: 'open' }] } }), ); const host = await mountHost(`${VIEW}/qa?uf_priority=urgent`); await host.clickTab('qb'); - expect(filterOf(lastQuery())).toContain('"status","=","open"'); + expect(filterOf(lastQuery())).not.toContain('status'); expect(filterOf(lastQuery())).not.toContain('priority'); const params = new URLSearchParams(host.search()); - expect(params.has(LIST_FILTER_PARAM)).toBe(true); + expect(params.has(LIST_FILTER_PARAM)).toBe(false); expect(params.has('uf_priority')).toBe(false); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx b/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx index 51f16e366be..f6636a599e6 100644 --- a/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.userListState-12418.test.tsx @@ -1,16 +1,17 @@ /** - * objectui#12418 — on the object page, a list's sort, column layout, Filter - * panel conditions and tab order are the signed-in user's own state, and the - * shared view is written only by the view editor. + * objectui#12418 — on the object page, a toolbar change on a list is never the + * shared view's: the view is written only by the view editor. objectstack#35955 + * — what the reader changes on the list is a DRAFT (`./listDraftStore.ts`): it + * applies at once, is stored nowhere, and is kept with Save or dropped with + * Discard. What stays stored for the reader is what never becomes a draft: the + * column widths, the row height and the tab order. * - * ## The defect this pins + * ## The defect objectui#12418 pinned * * A header sort went through `persistViewPatch` (the toolbar's view write, * retired in objectui#12504) into the view (`/meta/view`), a column drag the - * same way, and a Manage Views drag PATCHed a `sortOrder` - * onto every saved view's row: one user's click changed the list for every - * user. The Filter panel and the tab order lived in this browser only, so they - * were gone on another device. + * same way, and a Manage Views drag PATCHed a `sortOrder` onto every saved + * view's row: one user's click changed the list for every user. * * ## What runs * @@ -18,50 +19,41 @@ * debounce included) and a list-state family that records its `load` and * `save` the way `@object-ui/data-objectstack`'s does (`sys_user_preference`, * one `ui.list.` row per object). The view writes are the adapter's - * `updateView` spy and, for the view editor's save, a - * real `MetadataClient` whose `PUT /meta/view/…` is counted. `ListView` is - * captured (a toolbar change is the page's own callback) and Manage Views is - * reduced to its reorder and its config entry. + * `updateView` spy and, for the view editor's save, a real `MetadataClient` + * whose `PUT /meta/view/…` is counted. `ListView` is captured (a toolbar change + * is the page's own callback) and Manage Views is reduced to its reorder and + * its config entry. * * ## The pins * - * 1. A header sort and a column resize write no view and land as ONE save - * of the object's row. - * 2. A Manage Views drag writes no view and lands as ONE save. - * 3. The view editor's save still writes `/meta/view`. - * 4. Cross-device: a fresh browser opens on the user's stored order, sort - * and filters once the family has loaded; another user sees the view's - * authored defaults. The list waits for that load. - * 5. "Reset to view", the one reset of the 「Personalized」 marker beside - * the title (objectstack#28950; it replaced the header ⋯ "Reset view"), - * drops that state and the list opens on the view's own sort again. The - * marker is drawn while the list reports a part that differs, or while - * a column layout is stored. - * 6. objectui#12474 — the density toggle and a Hide Fields change are the - * user's too: each writes no view and lands as ONE save; a fresh browser - * opens on them, another user sees the view's own, and "Reset to view" - * drops them. - * 6b. objectui#12505 — on a SAVED view that declares no `columns`, a Hide - * Fields change is stored the same way and applied over the drawn - * defaults; another user sees the defaults; "Reset to view" drops it. - * 6c. objectui#12949 — the list is handed the view's own density and - * hidden fields in `viewDefaults`, beside the user's in `schema`, so - * its Display reset compares against the view; on an unprojected saved - * view the view hides nothing. - * 6d. objectstack#28948 — the list's "Reset to view default" (Display and - * sort) is told apart from a choice: the reset parts are CLEARED from - * the stored entry, so the user follows later changes to the view; a - * deliberate `sort: []` / `hiddenFields: []` is still stored. - * 6e. objectstack#30077 — a field the reader adds with the Hide Fields - * popover is theirs: it writes no view and lands as ONE save - * (`addedFields`), the list is handed it appended to the view's - * columns, a fresh browser opens with it, another user does not see it, - * and "Reset to view" drops it. - * 7. CONTROL — no provider (a host without the console shell): the state is - * this browser's, as the tab order and filters were before; a sort still - * writes no view; the older `viewOrder:` key is still honoured. + * 1. A header sort writes no view and nothing stored: it is the draft's. A + * column resize lands as ONE save of the object's row, widths only. A + * Manage Views drag lands as ONE save. The view editor's save still + * writes `/meta/view`. + * 2. A fresh browser opens on the reader's stored tab order and column + * widths once the family has loaded; a sort or filter an earlier console + * stored there no longer applies. Another user sees the view's own. + * Discard puts the list back as its view declares it and keeps the + * widths; it writes nothing. + * 3. objectui#12474 — the density stays the reader's stored choice; a Hide + * Fields change is the draft's. objectui#12505 — on a saved view that + * declares no `columns` the draft's hide applies over the drawn defaults. + * 4. objectui#12949 — the list is handed the view's own density and hidden + * fields in `viewDefaults`, beside the reader's in `schema`. + * 5. objectstack#28948 — the list's "Reset to view default" drops the reset + * parts (from the draft, or the stored row height), so the reader follows + * later changes to the view; a deliberate `sort: []` / `hiddenFields: []` + * is a draft part too. + * 6. objectstack#30077 — a field the reader adds is a draft part: the list is + * handed it appended to the view's columns, and Discard drops it. + * 7. CONTROL — no provider (a host without the console shell): a sort is the + * draft's there too; the older `viewOrder:` key still orders the + * tabs, and the Filter panel's older per-browser group no longer applies. + * 8. objectstack#32627 — a width change writes the reader's row only when it + * changes it. */ + import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, cleanup, act, screen, fireEvent, waitFor } from '@testing-library/react'; @@ -128,7 +120,7 @@ vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ listProps = props; // objectstack#35548 — the view switcher leads the list's view bar: draw the slot. const lead = props.toolbarLeading; - // objectstack#35878 — the condition row's end (the 「Personalized」 marker) draws too. + // objectstack#35878 — the condition row's end (Discard and Save, objectstack#35955) draws too. return ( <> {typeof lead === 'function' ? lead({ recordCount: null, layout: 'grid' }) : lead ?? null} @@ -200,6 +192,7 @@ import { ObjectView, type ConsoleObjectViewProps } from './ObjectView'; import { ExpressionProvider } from '../providers/ExpressionProvider'; import { UserStateAdaptersProvider, useAttachListStateFamily } from '../context/UserStateAdapters'; import { ListPreferencesProvider, localListStateKey } from '../context/ListPreferencesProvider'; +import { listDraftScope, patchListDraft, readListDraft, resetListDraftStoreForTests } from './listDraftStore'; const FIELDS = { id: { type: 'text', label: 'Id' }, @@ -308,17 +301,17 @@ async function listReady() { await wait(50); } -/** - * objectstack#28950 — the marker's one reset. The captured list reports what - * of it differs from the view first (`parts`), as the real list does; with - * none, the marker must already be drawn (a stored column layout). - */ -async function resetToView(parts: string[] = []) { - if (parts.length) act(() => listProps.onPersonalizationChange(parts)); - fireEvent.click(await screen.findByTestId('list-personalized-marker')); - const reset = await screen.findByTestId('list-personalized-reset'); + +/** objectstack#35955 — the draft the page holds for `viewId`, for the signed-in user. */ +function draftOf(viewId: string = SYSTEM_ID) { + return readListDraft(listDraftScope(session.userId, OBJECT_NAME, viewId)); +} + +/** objectstack#35955 — Discard, drawn at the condition row's end while the list holds a draft. */ +async function discard() { + const button = await screen.findByTestId('list-draft-discard'); await act(async () => { - fireEvent.click(reset); + fireEvent.click(button); }); } @@ -345,6 +338,7 @@ beforeEach(() => { listProps = null; manageViewsOrder = []; localStorage.clear(); + resetListDraftStoreForTests(); client = new MetadataClient({ baseUrl: 'http://localhost', fetch: wire() as unknown as typeof fetch }); vi.stubGlobal('fetch', vi.fn(async () => json({ data: [] }, 200))); vi.spyOn(console, 'error').mockImplementation(() => {}); @@ -358,8 +352,8 @@ afterEach(() => { vi.clearAllMocks(); }); -describe('a toolbar change is the user\'s, not the view\'s (objectui#12418)', () => { - it('a header sort and a column resize write no view and land as one save of the object\'s row', async () => { +describe('a toolbar change writes no view (objectui#12418); what it changes is a draft (objectstack#35955)', () => { + it('a header sort writes nothing stored; a column resize lands as one save of the object\'s row, widths only', async () => { const ds = makeDataSource(); const { family } = makeFamily({}); mountWithFamily(ds, family); @@ -375,24 +369,46 @@ describe('a toolbar change is the user\'s, not the view\'s (objectui#12418)', () expect(toast.error).not.toHaveBeenCalled(); expect(family.save).toHaveBeenCalledTimes(1); expect(family.save).toHaveBeenCalledWith(LIST_KEY, { - perView: { [SYSTEM_ID]: { sort: [{ field: 'amount', order: 'desc' }], columnState: { widths: { name: 320 } } } }, + perView: { [SYSTEM_ID]: { columnState: { widths: { name: 320 } } } }, }); - // The page hands the grid the user's layout back. + // The sort is the draft's (the list holds it on screen itself). + expect(draftOf().sort).toEqual([{ field: 'amount', order: 'desc' }]); + // The page hands the grid the reader's widths back. expect(listProps.schema.columnState).toEqual({ widths: { name: 320 } }); }); - it('the schema-level sort relay is the same user write', async () => { + it('a column drag is the draft\'s order; the widths reported with it are the only stored part', async () => { const ds = makeDataSource(); const { family } = makeFamily({}); mountWithFamily(ds, family); await listReady(); - act(() => listProps.schema.onSortChange([{ field: 'amount', order: 'asc' }])); + act(() => listProps.onColumnStateChange({ order: ['amount', 'name'], widths: { name: 300 } })); await wait(700); expect(viewWrites(ds)).toBe(0); expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save.mock.calls[0][1]).toEqual({ perView: { [SYSTEM_ID]: { sort: [{ field: 'amount', order: 'asc' }] } } }); + expect(family.save).toHaveBeenCalledWith(LIST_KEY, { + perView: { [SYSTEM_ID]: { columnState: { widths: { name: 300 } } } }, + }); + expect(draftOf().columnOrder).toEqual(['amount', 'name']); + expect(listProps.schema.columnState).toEqual({ order: ['amount', 'name'], widths: { name: 300 } }); + // A drag lights Discard and Save on its own: the list reports no part for it. + expect(screen.getByTestId('list-draft')).toBeTruthy(); + }); + + it('the schema-level sort relay is the same draft write', async () => { + const ds = makeDataSource(); + const { family } = makeFamily({}); + mountWithFamily(ds, family); + await listReady(); + + act(() => listProps.schema.onSortChange([{ field: 'amount', order: 'asc' }])); + await wait(700); + + expect(viewWrites(ds)).toBe(0); + expect(family.save).not.toHaveBeenCalled(); + expect(draftOf().sort).toEqual([{ field: 'amount', order: 'asc' }]); }); it('a Manage Views drag writes no view and lands as one save', async () => { @@ -435,7 +451,8 @@ describe('a toolbar change is the user\'s, not the view\'s (objectui#12418)', () }); }); -describe('the user\'s state follows them, and only them (objectui#12418)', () => { +describe('what the reader keeps follows them; the draft does not (objectui#12418, objectstack#35955)', () => { + /** A row an earlier console stored: its sort and filters are no longer read. */ const STORED = { [LIST_KEY]: { viewOrder: [SAVED_ID, SYSTEM_ID], @@ -449,12 +466,12 @@ describe('the user\'s state follows them, and only them (objectui#12418)', () => }, }; - it('a fresh browser opens on the stored order, sort, filters and column layout once the family has loaded', async () => { + it('a fresh browser opens on the stored tab order and column widths once the family has loaded; the stored sort and filters no longer apply', async () => { const ds = makeDataSource(); const { family, release } = makeFamily(structuredClone(STORED), { held: true }); mountWithFamily(ds, family); - // The list waits for the user's state: nothing to open on yet. + // The list waits for the reader's state: nothing to open on yet. await screen.findByTestId('object-view-list-preferences-pending'); expect(listProps).toBeNull(); @@ -463,11 +480,11 @@ describe('the user\'s state follows them, and only them (objectui#12418)', () => expect(family.load).toHaveBeenCalledTimes(1); expect(manageViewsOrder).toEqual([SAVED_ID, SYSTEM_ID]); - expect(listProps.schema.sort).toEqual([{ field: 'amount', order: 'desc' }]); - expect(listProps.initialFilters).toEqual(STORED[LIST_KEY].perView[SYSTEM_ID].filters); expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); - // Written through to this browser's cache. - expect(JSON.parse(localStorage.getItem(localListStateKey('u1', OBJECT_NAME)) ?? '{}')).toEqual(STORED[LIST_KEY]); + expect(listProps.schema.sort).toEqual(AUTHORED_SORT); + expect(listProps.initialFilters).toBeUndefined(); + // Widths are not a draft: nothing to discard or save. + expect(screen.queryByTestId('list-draft')).toBeNull(); }); it('another user, with no state of their own, sees the view\'s authored defaults', async () => { @@ -482,53 +499,49 @@ describe('the user\'s state follows them, and only them (objectui#12418)', () => expect(listProps.initialFilters).toBeUndefined(); // No layout of anyone's: the grid is handed none, so its own cache cannot stand in. expect(listProps.schema.columnState).toEqual({}); - // Nothing of theirs differs: no marker, and no reset anywhere. - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); + expect(screen.queryByTestId('list-draft')).toBeNull(); expect(await overflowTestIds()).not.toContain('object-view-reset-view-button'); }); - it('"Reset to view" drops the user\'s state for the view and the list opens on the view\'s own sort again', async () => { + it('Discard puts the list back as its view declares it, keeps the widths and writes nothing', async () => { const ds = makeDataSource(); const { family } = makeFamily(structuredClone(STORED)); mountWithFamily(ds, family); await listReady(); - expect(listProps.schema.sort).toEqual([{ field: 'amount', order: 'desc' }]); - expect(typeof listProps.onPersonalizationChange).toBe('function'); + const filters = { id: 'root', logic: 'and', conditions: [{ id: 'c2', field: 'name', operator: 'contains', value: 'Beta' }] }; + act(() => { + listProps.onSortChange([{ field: 'amount', order: 'asc' }]); + listProps.onFilterChange(filters); + listProps.onPersonalizationChange(['sort', 'filters']); + }); + await wait(50); + expect(draftOf().sort).toEqual([{ field: 'amount', order: 'asc' }]); const before = listProps; - // The stored column layout alone draws the marker; the list adds the rest. - expect(screen.getByTestId('list-personalized-marker')).toBeTruthy(); - act(() => listProps.onPersonalizationChange(['sort', 'filters'])); - fireEvent.click(screen.getByTestId('list-personalized-marker')); - const parts = await screen.findByTestId('list-personalized-parts'); - expect([...parts.querySelectorAll('li')].map((li) => li.getAttribute('data-part'))).toEqual(['filters', 'sort', 'columns']); - const reset = screen.getByTestId('list-personalized-reset'); // This harness mounts no I18nProvider, so `t` answers with the key: the pin - // is WHICH key labels the reset and which says what it covers. - expect(reset.textContent?.trim()).toBe('console.objectView.resetView'); - expect(screen.getByTestId('list-personalized-popover').textContent).toContain('console.objectView.resetViewTitle'); - await act(async () => { - fireEvent.click(reset); - }); + // is WHICH key labels Discard and which says what it covers. + const button = screen.getByTestId('list-draft-discard'); + expect(button.textContent?.trim()).toBe('console.objectView.draft.discard'); + expect(button.getAttribute('title')).toBe('console.objectView.draft.discardTitle'); + await discard(); await wait(700); expect(viewWrites(ds)).toBe(0); - // The view's entry is gone; the tab order is not the view's to reset. - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { viewOrder: [SAVED_ID, SYSTEM_ID] }); + expect(family.save).not.toHaveBeenCalled(); + expect(draftOf()).toEqual({}); + // The list is mounted again on the view's own. expect(listProps).not.toBe(before); expect(listProps.schema.sort).toEqual(AUTHORED_SORT); expect(listProps.initialFilters).toBeUndefined(); - expect(listProps.schema.columnState).toEqual({}); - // The remounted list has reported nothing yet, and nothing is stored: no marker. - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); - // The header ⋯ has no reset of its own any more (objectstack#28950). + expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); + expect(screen.queryByTestId('list-draft')).toBeNull(); + // The header ⋯ has no reset of its own (objectstack#28950). expect(await overflowTestIds()).not.toContain('object-view-reset-view-button'); }); - it('with no favorites entry (no app segment), the ⋯ offers no reset: the way back is the marker beside the title', async () => { + it('with no favorites entry (no app segment), the ⋯ offers no reset: the way back is Discard', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); + const { family } = makeFamily({}); mountWithFamily(ds, family, SYSTEM_ID, { app: false }); await listReady(); @@ -541,29 +554,38 @@ describe('the user\'s state follows them, and only them (objectui#12418)', () => expect(entries.some((text) => /favorites|reset/i.test(text))).toBe(false); fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); } - await resetToView(['sort']); - await wait(700); - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); + act(() => { + listProps.onSortChange([{ field: 'amount', order: 'asc' }]); + listProps.onPersonalizationChange(['sort']); + }); + await discard(); + await wait(50); + expect(screen.queryByTestId('list-draft')).toBeNull(); + expect(listProps.schema.sort).toEqual(AUTHORED_SORT); }); - it('"Clear all" in the Filter panel clears the user\'s filters for the view', async () => { + it('"Clear all" in the Filter panel drops the draft\'s filters and keeps its sort', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); + const { family } = makeFamily({}); mountWithFamily(ds, family); await listReady(); + act(() => { + listProps.onSortChange([{ field: 'amount', order: 'asc' }]); + listProps.onFilterChange({ id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'Acme' }] }); + }); + expect(draftOf().filters).toBeDefined(); act(() => listProps.onFilterChange({ id: 'root', logic: 'and', conditions: [] })); await wait(700); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledTimes(1); - const saved = family.save.mock.calls[0][1] as any; - expect(saved.perView[SYSTEM_ID]).not.toHaveProperty('filters'); - expect(saved.perView[SYSTEM_ID].sort).toEqual([{ field: 'amount', order: 'desc' }]); + expect(family.save).not.toHaveBeenCalled(); + expect(draftOf()).not.toHaveProperty('filters'); + expect(draftOf().sort).toEqual([{ field: 'amount', order: 'asc' }]); }); }); -describe('the density and the hidden fields are the user\'s too (objectui#12474)', () => { +describe('the density stays the reader\'s; the hidden fields are the draft\'s (objectui#12474, objectstack#35955)', () => { it('a density toggle writes no view and lands as one save of the object\'s row', async () => { const ds = makeDataSource(); const { family } = makeFamily({}); @@ -579,23 +601,24 @@ describe('the density and the hidden fields are the user\'s too (objectui#12474) expect(family.save).toHaveBeenCalledTimes(1); expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } }); expect(listProps.schema.rowHeight).toBe('compact'); + expect(draftOf()).toEqual({}); }); - it('a Hide Fields change writes no view and lands as one save of the object\'s row', async () => { + it('a Hide Fields change writes no view and nothing stored: the list is handed the draft\'s', async () => { const ds = makeDataSource(); const { family } = makeFamily({}); mountWithFamily(ds, family); await listReady(); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); - // The whole list the popover emits: the user showed `amount` and hid `name`. + // The whole list the popover emits: the reader showed `amount` and hid `name`. act(() => listProps.onHiddenFieldsChange(['name'])); await wait(700); expect(viewWrites(ds)).toBe(0); expect(toast.error).not.toHaveBeenCalled(); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SYSTEM_ID]: { hiddenFields: ['name'] } } }); + expect(family.save).not.toHaveBeenCalled(); + expect(draftOf().hiddenFields).toEqual(['name']); expect(listProps.schema.hiddenFields).toEqual(['name']); }); @@ -603,7 +626,7 @@ describe('the density and the hidden fields are the user\'s too (objectui#12474) [LIST_KEY]: { perView: { [SYSTEM_ID]: { rowHeight: 'compact', hiddenFields: [] } } }, }; - it('a fresh browser opens on the stored density and hidden fields once the family has loaded', async () => { + it('a fresh browser opens on the stored density; hidden fields an earlier console stored no longer apply', async () => { const ds = makeDataSource(); const { family, release } = makeFamily(structuredClone(STORED), { held: true }); mountWithFamily(ds, family); @@ -612,8 +635,7 @@ describe('the density and the hidden fields are the user\'s too (objectui#12474) await listReady(); expect(listProps.schema.rowHeight).toBe('compact'); - // An empty list is the user's choice ("show every column"), not the view's. - expect(listProps.schema.hiddenFields).toEqual([]); + expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); }); it('another user, with no state of their own, sees the view\'s authored density and hidden fields', async () => { @@ -627,34 +649,46 @@ describe('the density and the hidden fields are the user\'s too (objectui#12474) expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); }); - it('"Reset to view" drops the stored density and hidden fields, and the list opens on the view\'s own', async () => { + it('Discard drops the hidden fields and keeps the stored density', async () => { const ds = makeDataSource(); const { family } = makeFamily(structuredClone(STORED)); mountWithFamily(ds, family); await listReady(); - expect(listProps.schema.rowHeight).toBe('compact'); + act(() => { + listProps.onHiddenFieldsChange(['name']); + listProps.onPersonalizationChange(['density', 'hiddenFields']); + }); + expect(listProps.schema.hiddenFields).toEqual(['name']); - await resetToView(['density', 'hiddenFields']); + await discard(); await wait(700); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, {}); - expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); + expect(family.save).not.toHaveBeenCalled(); + expect(listProps.schema.rowHeight).toBe('compact'); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); }); + + it('a density the list reports alone draws no Discard: it is not a draft part', async () => { + const ds = makeDataSource(); + const { family } = makeFamily(structuredClone(STORED)); + mountWithFamily(ds, family); + await listReady(); + act(() => listProps.onPersonalizationChange(['density'])); + await wait(50); + expect(screen.queryByTestId('list-draft')).toBeNull(); + }); }); -describe('on a saved view that declares no `columns`, the hidden fields are the user\'s own too (objectui#12505)', () => { +describe('on a saved view that declares no `columns`, the draft\'s hidden fields apply over the drawn defaults (objectui#12505)', () => { /** * The saved row with no `columns`: the page draws the object's defaults into * it, and declares no projection. Its own authored `hiddenFields` is never - * applied there (objectui#10694); the user's list is. + * applied there (objectui#10694); the draft's list is. */ const UNPROJECTED_SAVED_ROW = { name: SAVED_ID, object: OBJECT_NAME, label: 'Pipeline', type: 'grid', hiddenFields: ['name'] }; - const STORED = { [LIST_KEY]: { perView: { [SAVED_ID]: { hiddenFields: ['amount'] } } } }; - it('a Hide Fields change writes no view and lands as one save of the object\'s row', async () => { + it('a Hide Fields change writes no view and nothing stored, and applies at once', async () => { const ds = makeDataSource(UNPROJECTED_SAVED_ROW); const { family } = makeFamily({}); mountWithFamily(ds, family, SAVED_ID); @@ -667,52 +701,41 @@ describe('on a saved view that declares no `columns`, the hidden fields are the await wait(700); expect(viewWrites(ds)).toBe(0); - expect(toast.error).not.toHaveBeenCalled(); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SAVED_ID]: { hiddenFields: ['amount'] } } }); - expect(listProps.schema.hiddenFields).toEqual(['amount']); - }); - - it('a fresh browser opens on the stored list once the family has loaded', async () => { - const ds = makeDataSource(UNPROJECTED_SAVED_ROW); - const { family, release } = makeFamily(structuredClone(STORED), { held: true }); - mountWithFamily(ds, family, SAVED_ID); - await screen.findByTestId('object-view-list-preferences-pending'); - await act(async () => release()); - await listReady(); - + expect(family.save).not.toHaveBeenCalled(); + expect(draftOf(SAVED_ID).hiddenFields).toEqual(['amount']); expect(listProps.schema.hiddenFields).toEqual(['amount']); }); - it('another user, with no state of their own, sees the default columns', async () => { - session.userId = 'u2'; + it('a list an earlier console stored for the view no longer applies', async () => { const ds = makeDataSource(UNPROJECTED_SAVED_ROW); - const { family } = makeFamily({}); + const { family } = makeFamily({ [LIST_KEY]: { perView: { [SAVED_ID]: { hiddenFields: ['amount'] } } } }); mountWithFamily(ds, family, SAVED_ID); await listReady(); expect(listProps.schema.columns).toEqual(expect.arrayContaining(['name', 'amount'])); - // Not the view's authored `['name']`: it declares nothing on an unprojected view. + // Not the view's authored `['name']` either: it declares nothing on an unprojected view. expect(listProps.schema.hiddenFields).toBeUndefined(); }); - it('"Reset to view" drops the stored list, and the list opens on the default columns', async () => { + it('Discard drops the draft\'s list, and the list opens on the default columns', async () => { const ds = makeDataSource(UNPROJECTED_SAVED_ROW); - const { family } = makeFamily(structuredClone(STORED)); + const { family } = makeFamily({}); mountWithFamily(ds, family, SAVED_ID); await listReady(); - expect(listProps.schema.hiddenFields).toEqual(['amount']); + act(() => { + listProps.onHiddenFieldsChange(['amount']); + listProps.onPersonalizationChange(['hiddenFields']); + }); - await resetToView(['hiddenFields']); + await discard(); await wait(700); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, {}); + expect(family.save).not.toHaveBeenCalled(); expect(listProps.schema.hiddenFields).toBeUndefined(); }); - it('CONTROL: on the saved view that declares `columns`, the hide is stored and applied as before', async () => { + it('CONTROL: on the saved view that declares `columns`, the hide applies the same way', async () => { const ds = makeDataSource(); const { family } = makeFamily({}); mountWithFamily(ds, family, SAVED_ID); @@ -723,31 +746,29 @@ describe('on a saved view that declares no `columns`, the hidden fields are the await wait(700); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SAVED_ID]: { hiddenFields: ['name'] } } }); + expect(family.save).not.toHaveBeenCalled(); expect(listProps.schema.hiddenFields).toEqual(['name']); }); }); -describe('the list is handed the view\'s own density and hidden fields beside the user\'s (objectui#12949)', () => { - /** A stored choice that differs from the view's on both settings. */ - const STORED = { - [LIST_KEY]: { perView: { [SYSTEM_ID]: { rowHeight: 'compact', hiddenFields: ['name'] } } }, - }; +describe('the list is handed the view\'s own density and hidden fields beside the reader\'s (objectui#12949)', () => { + const STORED = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } } }; - it('after a reload, `schema` carries the user\'s choice and `viewDefaults` the view\'s own', async () => { + it('`schema` carries the reader\'s density and the draft\'s hidden fields, `viewDefaults` the view\'s own', async () => { const ds = makeDataSource(); const { family, release } = makeFamily(structuredClone(STORED), { held: true }); mountWithFamily(ds, family); await screen.findByTestId('object-view-list-preferences-pending'); await act(async () => release()); await listReady(); + act(() => listProps.onHiddenFieldsChange(['name'])); expect(listProps.schema.rowHeight).toBe('compact'); expect(listProps.schema.hiddenFields).toEqual(['name']); expect(listProps.viewDefaults).toEqual({ hiddenFields: AUTHORED_HIDDEN, rowHeight: AUTHORED_ROW_HEIGHT, sort: AUTHORED_SORT }); }); - it('a choice equal to the view\'s own, made through the controls\' doors, lands as the user\'s choice', async () => { + it('a choice equal to the view\'s own, made through the controls\' doors, is still the reader\'s choice', async () => { const ds = makeDataSource(); const { family } = makeFamily(structuredClone(STORED)); mountWithFamily(ds, family); @@ -761,9 +782,8 @@ describe('the list is handed the view\'s own density and hidden fields beside th expect(viewWrites(ds)).toBe(0); expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { - perView: { [SYSTEM_ID]: { rowHeight: AUTHORED_ROW_HEIGHT, hiddenFields: AUTHORED_HIDDEN } }, - }); + expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SYSTEM_ID]: { rowHeight: AUTHORED_ROW_HEIGHT } } }); + expect(draftOf().hiddenFields).toEqual(AUTHORED_HIDDEN); expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); expect(listProps.viewDefaults).toEqual({ hiddenFields: AUTHORED_HIDDEN, rowHeight: AUTHORED_ROW_HEIGHT, sort: AUTHORED_SORT }); @@ -786,63 +806,64 @@ describe('the list is handed the view\'s own density and hidden fields beside th it('on a saved view that declares no `columns`, the view hides nothing: its authored key stays unapplied (objectui#12505)', async () => { const UNPROJECTED_SAVED_ROW = { name: SAVED_ID, object: OBJECT_NAME, label: 'Pipeline', type: 'grid', hiddenFields: ['name'] }; const ds = makeDataSource(UNPROJECTED_SAVED_ROW); - const { family } = makeFamily({ [LIST_KEY]: { perView: { [SAVED_ID]: { hiddenFields: ['amount'] } } } }); + const { family } = makeFamily({}); mountWithFamily(ds, family, SAVED_ID); await listReady(); + act(() => listProps.onHiddenFieldsChange(['amount'])); expect(listProps.schema.hiddenFields).toEqual(['amount']); expect(listProps.viewDefaults.hiddenFields).toBeUndefined(); }); }); -describe('the list\'s "Reset to view default" clears the user\'s stored part instead of copying the view into it (objectstack#28948)', () => { - /** A stored choice that differs from the view's on the sort, the density and the hidden fields. */ - const STORED = { - [LIST_KEY]: { - perView: { - [SYSTEM_ID]: { sort: [{ field: 'amount', order: 'desc' }], rowHeight: 'compact', hiddenFields: ['name'] }, - }, - }, - }; +describe('the list\'s "Reset to view default" drops the reset parts instead of copying the view into them (objectstack#28948)', () => { + const STORED = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { rowHeight: 'compact' } } } }; const VIEW = OBJECT.listViews[SYSTEM_ID] as Record; - it('the list is wired to tell a reset from a choice, and is handed the view\'s own sort', async () => { + /** + * Mount on `rows` with a draft sort and hidden fields that differ from the + * view's: the draft is held before the list mounts, as when the reader comes + * back from a record. + */ + async function mountChanged(rows: Record = structuredClone(STORED)) { + patchListDraft(listDraftScope(session.userId, OBJECT_NAME, SYSTEM_ID), { + sort: [{ field: 'amount', order: 'desc' }], + hiddenFields: ['name'], + }); const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); + const { family } = makeFamily(rows); + const mounted = mountWithFamily(ds, family); await listReady(); + return { ds, family, ...mounted }; + } + + it('the list is wired to tell a reset from a choice, and is handed the view\'s own sort', async () => { + await mountChanged(); expect(typeof listProps.onRestoreViewDefaults).toBe('function'); - // `schema.sort` is the user's; the reset's baseline is the view's own. + // `schema.sort` is the draft's; the reset's baseline is the view's own. expect(listProps.schema.sort).toEqual([{ field: 'amount', order: 'desc' }]); expect(listProps.viewDefaults.sort).toEqual(AUTHORED_SORT); }); - it('a Display reset of density and hidden fields leaves neither in the stored entry', async () => { - const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); - mountWithFamily(ds, family); - await listReady(); + it('a Display reset of density and hidden fields drops the draft\'s hidden fields and the stored row height', async () => { + const { ds, family } = await mountChanged(); act(() => listProps.onRestoreViewDefaults(['hiddenFields', 'rowHeight'])); await wait(700); expect(viewWrites(ds)).toBe(0); expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { - perView: { [SYSTEM_ID]: { sort: [{ field: 'amount', order: 'desc' }] } }, - }); + expect(family.save).toHaveBeenCalledWith(LIST_KEY, {}); + expect(draftOf()).toEqual({ sort: [{ field: 'amount', order: 'desc' }] }); // The list is handed the view's own again. expect(listProps.schema.rowHeight).toBe(AUTHORED_ROW_HEIGHT); expect(listProps.schema.hiddenFields).toEqual(AUTHORED_HIDDEN); }); - it('after the reset the user follows the view: a changed `rowHeight` and `hiddenFields` reach them on the next open', async () => { + it('after the reset the reader follows the view: a changed `rowHeight` and `hiddenFields` reach them on the next open', async () => { const rows = structuredClone(STORED) as Record; - const ds = makeDataSource(); - const { family } = makeFamily(rows); - const { unmount } = mountWithFamily(ds, family); - await listReady(); + const { unmount } = await mountChanged(rows); act(() => listProps.onRestoreViewDefaults(['hiddenFields', 'rowHeight'])); await wait(700); unmount(); @@ -863,41 +884,18 @@ describe('the list\'s "Reset to view default" clears the user\'s stored part ins } }); - it('a sort reset leaves no sort stored; with nothing else stored the entry goes', async () => { - const ds = makeDataSource(); - const { family } = makeFamily({ [LIST_KEY]: { perView: { [SYSTEM_ID]: { sort: [{ field: 'amount', order: 'desc' }] } } } }); - mountWithFamily(ds, family); - await listReady(); + it('a sort reset drops the draft\'s sort and writes nothing', async () => { + const { ds, family } = await mountChanged({}); act(() => listProps.onRestoreViewDefaults(['sort'])); await wait(700); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, {}); - }); - - it('after a sort reset a changed view sort reaches the user on the next open', async () => { - const rows: Record = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { sort: [{ field: 'amount', order: 'desc' }] } } } }; - const { unmount } = mountWithFamily(makeDataSource(), makeFamily(rows).family); - await listReady(); - act(() => listProps.onRestoreViewDefaults(['sort'])); - await wait(700); - unmount(); - - const before = VIEW.sort; - VIEW.sort = [{ field: 'amount', order: 'asc' }]; - try { - listProps = null; - mountWithFamily(makeDataSource(), makeFamily(rows).family); - await listReady(); - expect(listProps.schema.sort).toEqual([{ field: 'amount', order: 'asc' }]); - } finally { - VIEW.sort = before; - } + expect(family.save).not.toHaveBeenCalled(); + expect(draftOf()).toEqual({ hiddenFields: ['name'] }); }); - it('CONTROL: a deliberate "no sort" and "show every column" are still stored, and survive a reload', async () => { + it('CONTROL: a deliberate "no sort" and "show every column" are draft parts, and survive the list being mounted again', async () => { const rows: Record = {}; const { unmount } = mountWithFamily(makeDataSource(), makeFamily(rows).family); await listReady(); @@ -906,9 +904,11 @@ describe('the list\'s "Reset to view default" clears the user\'s stored part ins listProps.onHiddenFieldsChange([]); }); await wait(700); - expect(rows[LIST_KEY]).toEqual({ perView: { [SYSTEM_ID]: { sort: [], hiddenFields: [] } } }); + expect(rows).toEqual({}); + expect(draftOf()).toEqual({ sort: [], hiddenFields: [] }); unmount(); + // Opening a record as a page and coming back mounts the list again. listProps = null; mountWithFamily(makeDataSource(), makeFamily(rows).family); await listReady(); @@ -917,10 +917,8 @@ describe('the list\'s "Reset to view default" clears the user\'s stored part ins }); }); -describe('a field the reader adds to their list is theirs, stored with their personalization (objectstack#30077)', () => { - const STORED = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { addedFields: ['owner'] } } } }; - - it('adding a field writes no view, lands as one save, and the list is handed it as a column', async () => { +describe('a field the reader adds to their list is a draft part (objectstack#30077, objectstack#35955)', () => { + it('adding a field writes no view and nothing stored, and the list is handed it as a column', async () => { const ds = makeDataSource(); const { family } = makeFamily({}); mountWithFamily(ds, family); @@ -934,28 +932,15 @@ describe('a field the reader adds to their list is theirs, stored with their per expect(viewWrites(ds)).toBe(0); expect(toast.error).not.toHaveBeenCalled(); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SYSTEM_ID]: { addedFields: ['owner'] } } }); - expect(listProps.schema.columns).toEqual(['name', 'amount', 'owner']); - expect(listProps.addedFields).toEqual(['owner']); - }); - - it('a fresh browser opens with the added column once the family has loaded', async () => { - const ds = makeDataSource(); - const { family, release } = makeFamily(structuredClone(STORED), { held: true }); - mountWithFamily(ds, family); - await screen.findByTestId('object-view-list-preferences-pending'); - await act(async () => release()); - await listReady(); - + expect(family.save).not.toHaveBeenCalled(); + expect(draftOf().addedFields).toEqual(['owner']); expect(listProps.schema.columns).toEqual(['name', 'amount', 'owner']); expect(listProps.addedFields).toEqual(['owner']); }); - it('another user, with no state of their own, sees the view\'s columns alone', async () => { - session.userId = 'u2'; + it('a field an earlier console stored as added no longer applies', async () => { const ds = makeDataSource(); - const { family } = makeFamily({}); + const { family } = makeFamily({ [LIST_KEY]: { perView: { [SYSTEM_ID]: { addedFields: ['owner'] } } } }); mountWithFamily(ds, family); await listReady(); @@ -963,41 +948,38 @@ describe('a field the reader adds to their list is theirs, stored with their per expect(listProps.addedFields).toEqual([]); }); - it('"Reset to view" drops the added field: the stored added fields alone draw the marker, and the list opens on the view\'s columns', async () => { + it('Discard drops the added field: the addition alone draws Discard and Save, and the list opens on the view\'s columns', async () => { const ds = makeDataSource(); - const { family } = makeFamily(structuredClone(STORED)); + const { family } = makeFamily({}); mountWithFamily(ds, family); await listReady(); + act(() => listProps.onAddedFieldsChange(['owner'])); expect(listProps.schema.columns).toEqual(['name', 'amount', 'owner']); - // Nothing reported by the list: the stored addition is a part of its own. - fireEvent.click(await screen.findByTestId('list-personalized-marker')); - const parts = await screen.findByTestId('list-personalized-parts'); - expect([...parts.querySelectorAll('li')].map((li) => li.getAttribute('data-part'))).toEqual(['columns']); - await act(async () => { - fireEvent.click(screen.getByTestId('list-personalized-reset')); - }); + // Nothing reported by the list: the addition is a part of its own. + expect(screen.getByTestId('list-draft')).toBeTruthy(); + await discard(); await wait(700); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledTimes(1); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, {}); + expect(family.save).not.toHaveBeenCalled(); expect(listProps.schema.columns).toEqual(['name', 'amount']); expect(listProps.addedFields).toEqual([]); - expect(screen.queryByTestId('list-personalized-marker')).toBeNull(); + expect(screen.queryByTestId('list-draft')).toBeNull(); }); - it('a stored name the view declares itself is the view\'s column, not an addition: no duplicate, nothing handed as added', async () => { + it('a name the view declares itself is the view\'s column, not an addition: no duplicate, nothing handed as added', async () => { const ds = makeDataSource(); - const { family } = makeFamily({ [LIST_KEY]: { perView: { [SYSTEM_ID]: { addedFields: ['amount', 'owner'] } } } }); + const { family } = makeFamily({}); mountWithFamily(ds, family); await listReady(); + act(() => listProps.onAddedFieldsChange(['amount', 'owner'])); expect(listProps.schema.columns).toEqual(['name', 'amount', 'owner']); expect(listProps.addedFields).toEqual(['owner']); }); - it('on a saved view that declares `columns` the addition is stored and applied the same way', async () => { + it('on a saved view that declares `columns` the addition applies the same way', async () => { const ds = makeDataSource(); const { family } = makeFamily({}); mountWithFamily(ds, family, SAVED_ID); @@ -1008,17 +990,17 @@ describe('a field the reader adds to their list is theirs, stored with their per await wait(700); expect(viewWrites(ds)).toBe(0); - expect(family.save).toHaveBeenCalledWith(LIST_KEY, { perView: { [SAVED_ID]: { addedFields: ['amount'] } } }); + expect(family.save).not.toHaveBeenCalled(); expect(listProps.schema.columns).toEqual(['name', 'amount']); }); }); -describe('CONTROL — no provider: this browser\'s state, as before (objectui#12418)', () => { +describe('CONTROL — no provider: a sort is the draft\'s here too (objectui#12418, objectstack#35955)', () => { function mountBare(ds: ConsoleObjectViewProps['dataSource'], viewId = SYSTEM_ID) { return render(page(ds, viewId)); } - it('a sort writes no view, persists in this browser, and the next mount opens on it', async () => { + it('a sort writes no view and nothing in this browser\'s storage, and the list mounted again opens on it', async () => { const ds = makeDataSource(); mountBare(ds); await listReady(); @@ -1026,9 +1008,7 @@ describe('CONTROL — no provider: this browser\'s state, as before (objectui#12 await wait(400); expect(viewWrites(ds)).toBe(0); - expect(JSON.parse(localStorage.getItem(localListStateKey('u1', OBJECT_NAME)) ?? '{}')).toEqual({ - perView: { [SYSTEM_ID]: { sort: [{ field: 'amount', order: 'desc' }] } }, - }); + expect(localStorage.getItem(localListStateKey('u1', OBJECT_NAME))).toBeNull(); cleanup(); listProps = null; @@ -1037,7 +1017,7 @@ describe('CONTROL — no provider: this browser\'s state, as before (objectui#12 expect(listProps.schema.sort).toEqual([{ field: 'amount', order: 'desc' }]); }); - it('the older per-browser keys still open the list: `viewOrder:` and the Filter panel\'s group', async () => { + it('the older `viewOrder:` key still orders the tabs; the Filter panel\'s older per-browser group no longer applies', async () => { localStorage.setItem(`viewOrder:${OBJECT_NAME}`, JSON.stringify([SAVED_ID, SYSTEM_ID])); const filters = { id: 'root', logic: 'and', conditions: [{ id: 'c1', field: 'name', operator: 'contains', value: 'Acme' }] }; localStorage.setItem(`list-filters:u1:${OBJECT_NAME}:${SYSTEM_ID}`, JSON.stringify({ filters, search: 'acme' })); @@ -1046,8 +1026,8 @@ describe('CONTROL — no provider: this browser\'s state, as before (objectui#12 await listReady(); expect(manageViewsOrder).toEqual([SAVED_ID, SYSTEM_ID]); - expect(listProps.initialFilters).toEqual(filters); - expect(listProps.initialSearchTerm).toBe('acme'); + expect(listProps.initialFilters).toBeUndefined(); + expect(listProps.initialSearchTerm ?? '').toBe(''); }); it('a drag writes no view and keeps the order in this browser', async () => { @@ -1067,11 +1047,10 @@ describe('CONTROL — no provider: this browser\'s state, as before (objectui#12 }); }); -describe('a list change writes the user\'s row only when it changes a preference (objectstack#32627)', () => { - const STORED_SORT = [{ field: 'amount', order: 'desc' }]; - const STORED = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { sort: STORED_SORT, columnState: { widths: { name: 280 } } } } } }; +describe('a width change writes the reader\'s row only when it changes it (objectstack#32627)', () => { + const STORED = { [LIST_KEY]: { perView: { [SYSTEM_ID]: { columnState: { widths: { name: 280 } } } } } }; - it('re-stating the stored sort and column layout, and clearing filters nobody set, sends no write', async () => { + it('re-stating the stored widths, a sort, and clearing filters nobody set, sends no write', async () => { const ds = makeDataSource(); const { family } = makeFamily(structuredClone(STORED)); mountWithFamily(ds, family); @@ -1087,34 +1066,34 @@ describe('a list change writes the user\'s row only when it changes a preference expect(family.save).not.toHaveBeenCalled(); }); - it('a change undone before the write leaves sends no write', async () => { + it('a width change undone before the write leaves sends no write', async () => { const ds = makeDataSource(); const { family } = makeFamily(structuredClone(STORED)); mountWithFamily(ds, family); await listReady(); - act(() => listProps.onSortChange([{ field: 'amount', order: 'asc' }])); - act(() => listProps.onSortChange([{ field: 'amount', order: 'desc' }])); + act(() => listProps.onColumnStateChange({ widths: { name: 400 } })); + act(() => listProps.onColumnStateChange({ widths: { name: 280 } })); await wait(700); expect(family.save).not.toHaveBeenCalled(); - expect(listProps.schema.sort).toEqual(STORED_SORT); + expect(listProps.schema.columnState).toEqual({ widths: { name: 280 } }); }); - it('CONTROL: a sort that differs from the stored one is one write, and undoing it after it landed is another', async () => { + it('CONTROL: a width that differs from the stored one is one write, and undoing it after it landed is another', async () => { const ds = makeDataSource(); const { family } = makeFamily(structuredClone(STORED)); mountWithFamily(ds, family); await listReady(); - act(() => listProps.onSortChange([{ field: 'amount', order: 'asc' }])); + act(() => listProps.onColumnStateChange({ widths: { name: 400 } })); await wait(700); expect(family.save).toHaveBeenCalledTimes(1); - expect((family.save.mock.calls[0][1] as any).perView[SYSTEM_ID].sort).toEqual([{ field: 'amount', order: 'asc' }]); + expect((family.save.mock.calls[0][1] as any).perView[SYSTEM_ID].columnState).toEqual({ widths: { name: 400 } }); - act(() => listProps.onSortChange([{ field: 'amount', order: 'desc' }])); + act(() => listProps.onColumnStateChange({ widths: { name: 280 } })); await wait(700); expect(family.save).toHaveBeenCalledTimes(2); - expect((family.save.mock.calls[1][1] as any).perView[SYSTEM_ID].sort).toEqual(STORED_SORT); + expect((family.save.mock.calls[1][1] as any).perView[SYSTEM_ID].columnState).toEqual({ widths: { name: 280 } }); }); }); diff --git a/ui/packages/app-shell/src/views/listDraftStore.ts b/ui/packages/app-shell/src/views/listDraftStore.ts index 3961706a18f..e62151e459d 100644 --- a/ui/packages/app-shell/src/views/listDraftStore.ts +++ b/ui/packages/app-shell/src/views/listDraftStore.ts @@ -99,12 +99,31 @@ function isEmptyPart(value: unknown): boolean { return value === undefined; } +/** + * A part as the draft keeps it: a sort is its fields and directions (a grid + * reports row ids beside them), and a filter group with no condition is no + * filter (the Filter panel's "Clear all" reports an empty group). + */ +function normalizePart(key: string, value: unknown): unknown { + if (key === 'sort' && Array.isArray(value)) { + return value + .filter((item): item is { field: string; order?: string } => !!item && typeof item.field === 'string' && !!item.field) + .map((item) => ({ field: item.field, order: item.order === 'desc' ? 'desc' : 'asc' })); + } + if (key === 'filters') { + const conditions = (value as { conditions?: unknown } | null | undefined)?.conditions; + return Array.isArray(conditions) && conditions.length > 0 ? value : undefined; + } + return value; +} + /** Lay `patch` over the draft of `scope`, claiming the scope when it is not held. */ export function patchListDraft(scope: string, patch: ListDraftPatch): void { const base = slot.scope === scope ? slot.draft : EMPTY_DRAFT; const next: Record = { ...base }; let changed = slot.scope !== scope; - for (const [key, value] of Object.entries(patch)) { + for (const [key, raw] of Object.entries(patch)) { + const value = normalizePart(key, raw); const before = (base as Record)[key]; if (isEmptyPart(value)) { if (key in next) { diff --git a/ui/packages/app-shell/src/views/objectViewListUrlState.ts b/ui/packages/app-shell/src/views/objectViewListUrlState.ts index 299cc8aa0c8..28875c4d736 100644 --- a/ui/packages/app-shell/src/views/objectViewListUrlState.ts +++ b/ui/packages/app-shell/src/views/objectViewListUrlState.ts @@ -44,7 +44,7 @@ import { parseUrlEqualityFilterTriples } from './drillUrlFilters.js'; import { selectFilterParams } from './objectViewHelpers.js'; import type { buildViewTabs } from './objectViewTabs.js'; import type { ConsoleObjectViewProps } from './ObjectView.js'; -import type { ListPersonalizationPart } from './ListPersonalizedMarker.js'; +import type { ListPersonalizationPart } from './ListDraftActions.js'; const isRecord = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); diff --git a/ui/packages/app-shell/src/views/view-filter-fold.ratchet.test.ts b/ui/packages/app-shell/src/views/view-filter-fold.ratchet.test.ts index 27061f0fae0..acb73843805 100644 --- a/ui/packages/app-shell/src/views/view-filter-fold.ratchet.test.ts +++ b/ui/packages/app-shell/src/views/view-filter-fold.ratchet.test.ts @@ -126,10 +126,10 @@ describe('objectui#4155 ratchet — the filter panel persists nothing', () => { }); it('the surviving handler still keeps SESSION state — the panel is not amnesiac', () => { - // Since objectui#12418 the conditions are the user's own list state - // (`listPrefs`, a `sys_user_preference` row), not this browser's - // localStorage alone: still never the view's stored body. - expect(objectViewSrc).toMatch(/onFilterChange=\{[^}]*listPrefs\.patchView\(viewDef\.id, \{ filters/s); + // Since objectstack#35955 the conditions are the list's DRAFT + // (`listDraft`, `./listDraftStore.ts`), kept until the reader saves or + // discards them: still never the view's stored body. + expect(objectViewSrc).toMatch(/onFilterChange=\{[^}]*listDraft\.patch\(\{ filters/s); }); it('the EXPLICIT save path is untouched — this is the control', () => { diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 89b48a8afec..1445e9d1fb8 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2916,6 +2916,12 @@ const ar = { viewNameInvalid: "استخدم أحرفًا إنجليزية صغيرة وأرقامًا وشرطات سفلية؛ وابدأ بحرف أو شرطة سفلية.", systemViewReadonly: "عرض النظام معرَّف في الكود — للقراءة فقط.", cannotEditMetaView: "هذا عرض مدمج معرَّف في الكود — لا يمكن تعديله.", + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: "الرجوع إلى إعدادات العرض", + resetViewTitle: "يعيد عوامل التصفية والبحث والترتيب والتجميع وترتيب الأعمدة والحقول المخفية والكثافة والتخطيط ولون الصف وأرقام الصفوف والتحرير المضمّن الخاصة بهذا العرض. تبقى طرق العرض المثبتة والمفضلة وطريقة فتح السجلات كما هي. تتغير قائمتك فقط.", + personalized: "مخصّصة", + personalizedHeading: "تختلف قائمتك عن هذا العرض في", // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: "تجاهل", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index f672cf961c0..953faa24e29 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2636,6 +2636,12 @@ const de = { viewNameInvalid: "Verwenden Sie Kleinbuchstaben, Ziffern und Unterstriche; beginnen Sie mit einem Buchstaben oder Unterstrich.", systemViewReadonly: "Systemansicht — im Code definiert, schreibgeschützt.", cannotEditMetaView: "Diese Ansicht ist integriert und im Code definiert – sie kann nicht geändert werden.", + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: "Auf Ansicht zurücksetzen", + resetViewTitle: "Stellt die eigenen Filter, Suche, Sortierung, Gruppierung, Spaltenanordnung, ausgeblendeten Felder, Dichte, Layout, Zeilenfarbe, Zeilennummern und Inline-Bearbeitung dieser Ansicht wieder her. Angeheftete Ansichten, Favoriten und die Art, wie Datensätze geöffnet werden, bleiben unverändert. Nur Ihre Liste ändert sich.", + personalized: "Personalisiert", + personalizedHeading: "Ihre Liste weicht von dieser Ansicht ab bei", // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: "Verwerfen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index b64939b4205..ed4a3b289f5 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3228,6 +3228,12 @@ const en = { // (rename / pin / set-as-default / configure), so the copy has to cover // any change to a built-in view rather than name one operation. cannotEditMetaView: 'This view is built in and defined in code — it cannot be changed.', + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: 'Reset to view', + resetViewTitle: 'Puts back this view’s own filters, search, sort, grouping, column layout, hidden fields, density, layout, row color, row numbers and inline editing. Pinned views, favorites and how records open stay as they are. Only your list changes.', + personalized: 'Personalized', + personalizedHeading: 'Your list differs from this view in', // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: 'Discard', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 2f932c2beb8..63ec19f91af 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2708,6 +2708,12 @@ const es = { viewNameInvalid: "Use minúsculas, números y guiones bajos; empiece por una letra o un guion bajo.", systemViewReadonly: "Vista del sistema definida en el código: solo lectura.", cannotEditMetaView: "Esta vista está integrada y definida en el código: no se puede modificar.", + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: "Restablecer a la vista", + resetViewTitle: "Restaura los filtros, la búsqueda, la ordenación, la agrupación, la disposición de columnas, los campos ocultos, la densidad, el diseño, el color de fila, los números de fila y la edición en línea propios de esta vista. Las vistas fijadas, los favoritos y la forma de abrir los registros no cambian. Solo cambia su lista.", + personalized: "Personalizada", + personalizedHeading: "Su lista difiere de esta vista en", // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: "Descartar", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 487d83386c1..257b6355a23 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2704,6 +2704,12 @@ const fr = { viewNameInvalid: "Utilisez des minuscules, des chiffres et des tirets bas ; commencez par une lettre ou un tiret bas.", systemViewReadonly: "Vue système définie dans le code — en lecture seule.", cannotEditMetaView: "Cette vue est intégrée et définie dans le code — elle ne peut pas être modifiée.", + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: "Revenir à la vue", + resetViewTitle: "Rétablit les filtres, la recherche, le tri, le regroupement, la disposition des colonnes, les champs masqués, la densité, la disposition, la couleur de ligne, les numéros de ligne et l’édition en ligne propres à cette vue. Les vues épinglées, les favoris et le mode d’ouverture des enregistrements ne changent pas. Seule votre liste change.", + personalized: "Personnalisée", + personalizedHeading: "Votre liste diffère de cette vue par", // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: "Abandonner", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 74ca146ad31..05fda05a97c 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2638,6 +2638,12 @@ const ja = { viewNameInvalid: "英小文字、数字、アンダースコアを使用し、先頭は文字かアンダースコアにしてください。", systemViewReadonly: "システムビューはコードで定義されており、読み取り専用です。", cannotEditMetaView: "このビューはコードで定義された組み込みビューのため、変更できません。", + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: "ビューの設定に戻す", + resetViewTitle: "このビュー本来のフィルター、検索、並べ替え、グループ、列の配置、非表示フィールド、密度、レイアウト、行の色、行番号、インライン編集に戻します。ピン留めしたビュー、お気に入り、レコードの開き方は変わりません。変わるのはあなたのリストだけです。", + personalized: "個人設定あり", + personalizedHeading: "このビューと異なる項目", // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: "破棄", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index ef8b2f89099..6ca5c8bdb10 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2636,6 +2636,12 @@ const ko = { viewNameInvalid: "소문자, 숫자, 밑줄을 사용하고 문자 또는 밑줄로 시작하세요.", systemViewReadonly: "시스템 보기는 코드에 정의되어 있어 읽기 전용입니다.", cannotEditMetaView: "이 보기는 코드에 정의된 기본 제공 보기이므로 변경할 수 없습니다.", + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: "보기 설정으로 되돌리기", + resetViewTitle: "이 보기 자체의 필터, 검색, 정렬, 그룹, 열 배치, 숨긴 필드, 밀도, 레이아웃, 행 색상, 행 번호, 인라인 편집으로 되돌립니다. 고정한 보기, 즐겨찾기, 레코드 열기 방식은 그대로 유지됩니다. 본인의 목록만 변경됩니다.", + personalized: "개인 설정됨", + personalizedHeading: "이 보기와 다른 항목", // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: "변경 취소", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 09006df66a6..262910f4bc2 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2703,6 +2703,12 @@ const pt = { viewNameInvalid: "Use letras minúsculas, números e sublinhados; comece com uma letra ou sublinhado.", systemViewReadonly: "Exibição do sistema definida no código — somente leitura.", cannotEditMetaView: "Esta exibição é integrada e definida no código — não é possível alterá-la.", + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: "Voltar à exibição", + resetViewTitle: "Restaura os filtros, a pesquisa, a ordenação, o agrupamento, a disposição das colunas, os campos ocultos, a densidade, o layout, a cor da linha, os números de linha e a edição em linha próprios desta exibição. Exibições fixadas, favoritos e a forma de abrir registros não mudam. Apenas a sua lista muda.", + personalized: "Personalizada", + personalizedHeading: "Sua lista difere desta exibição em", // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: "Descartar", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 3d2754ad97a..ceda7864357 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2782,6 +2782,12 @@ const ru = { viewNameInvalid: "Используйте строчные латинские буквы, цифры и подчёркивания; начните с буквы или подчёркивания.", systemViewReadonly: "Системное представление определено в коде — только для чтения.", cannotEditMetaView: "Это встроенное представление, определённое в коде, — изменить его нельзя.", + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: "Вернуть настройки представления", + resetViewTitle: "Возвращает собственные фильтры, поиск, сортировку, группировку, расположение столбцов, скрытые поля, плотность, макет, цвет строк, номера строк и встроенное редактирование этого представления. Закреплённые представления, избранное и способ открытия записей не меняются. Меняется только ваш список.", + personalized: "Настроено", + personalizedHeading: "Ваш список отличается от представления", // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: "Отменить", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 514bf3ef5e9..cce546771c0 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2723,6 +2723,12 @@ const zh = { }, systemViewReadonly: '系统视图由代码定义,只读。', cannotEditMetaView: '该视图为内置视图,由代码定义,无法修改。', + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: '恢复为视图设置', + resetViewTitle: '恢复此视图自身的筛选、搜索、排序、分组、列布局、隐藏字段、密度、布局、行颜色、行号和行内编辑。固定的视图、收藏和记录的打开方式保持不变。只影响你自己的列表。', + personalized: '已个性化', + personalizedHeading: '你的列表与此视图不同之处', // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: '放弃', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index da4e52e981c..65f94e055db 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2723,6 +2723,12 @@ const zhHant = { }, systemViewReadonly: '系統檢視由程式碼定義,只讀。', cannotEditMetaView: '該檢視為內建檢視,由程式碼定義,無法修改。', + // The 「Personalized · Reset to view」 marker's words (objectstack#28950), no longer drawn + // since objectstack#35955: kept in every pack, so no published key goes away. + resetView: '恢復為檢視設定', + resetViewTitle: '恢復此檢視自身的篩選、搜尋、排序、分組、列布局、隱藏欄位、密度、佈局、行顏色、行號和行內編輯。固定的檢視、收藏和記錄的開啟方式保持不變。只影響你自己的列表。', + personalized: '已個性化', + personalizedHeading: '你的列表與此檢視不同之處', // objectstack#35955 — a list's unsaved changes: Discard and Save. draft: { discard: '放棄', From 1afc23b8fc42524a491af518f41dbcb9aa30fc3a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:05:38 +0000 Subject: [PATCH 3/5] test(console): three list pins pay the lint load at collection Claude-Session: https://claude.ai/code/session_01L6bhgUr9HRqChVQu82hqdz Co-authored-by: Claude --- .../src/console/__tests__/consoleListStateWall-12418.test.tsx | 2 ++ .../app-shell/src/views/ObjectView.overlayPatchOnly.test.ts | 2 ++ .../app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx | 2 ++ 3 files changed, 6 insertions(+) diff --git a/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx b/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx index 5dd8890dd09..9b000e241bc 100644 --- a/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/consoleListStateWall-12418.test.tsx @@ -122,6 +122,8 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => ({ import { toast } from 'sonner'; import { ConsoleShell, ConnectedShell } from '../ConsoleShell'; import { useAdapter } from '../../providers/AdapterProvider'; +// Paid at collection, not in a case's clock: the source reaches `@objectstack/lint` on demand. +import '@objectstack/lint'; import { ObjectView } from '../../views/ObjectView'; import { resetListDraftStoreForTests } from '../../views/listDraftStore'; import { createPreferenceFramework, preferenceRowId, type PreferenceFramework } from './preferenceFramework'; diff --git a/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts b/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts index b101cfa3980..650f672b86a 100644 --- a/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts +++ b/ui/packages/app-shell/src/views/ObjectView.overlayPatchOnly.test.ts @@ -49,6 +49,8 @@ import { fileURLToPath } from 'node:url'; import type { DataSource } from '@object-ui/types'; import * as dataObjectstack from '@object-ui/data-objectstack'; import { ObjectStackAdapter } from '@object-ui/data-objectstack'; +// Paid at collection, not in a case's clock: the source reaches `@objectstack/lint` on demand. +import '@objectstack/lint'; import { buildViewTabs, loadViewOverrides, sanitizeViewOverride } from './ObjectView'; import { answerObjectViewRead } from './__tests__/objectViewRoute'; // @ts-expect-error — plain-JS shared helper, intentionally untyped (`allowJs: false`) diff --git a/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx b/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx index 2e8ee2b90df..c0bbecd8966 100644 --- a/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.ufViewSwitch-11992.test.tsx @@ -91,6 +91,8 @@ vi.mock('./MetadataInspector', () => ({ })); vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); +// Paid at collection, not in a case's clock: the source reaches `@objectstack/lint` on demand. +import '@objectstack/lint'; import { ObjectView } from './ObjectView'; import { resetListDraftStoreForTests } from './listDraftStore'; import { ExpressionProvider } from '../providers/ExpressionProvider'; From cb6774f68f8321093c5f3fd92b63db58ac47b266 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:19:32 +0000 Subject: [PATCH 4/5] test(console): drop an unused import from the personal views pin Claude-Session: https://claude.ai/code/session_01L6bhgUr9HRqChVQu82hqdz Co-authored-by: Claude --- .../app-shell/src/views/ObjectView.personalViews-29635.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx b/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx index 27f1d69418e..adb040185ad 100644 --- a/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.personalViews-29635.test.tsx @@ -108,7 +108,7 @@ import { ObjectView } from './ObjectView'; import { listDraftScope, patchListDraft, readListDraft, resetListDraftStoreForTests, type ListDraftPatch } from './listDraftStore'; import { ExpressionProvider } from '../providers/ExpressionProvider'; import { UserStateAdaptersProvider, useAttachListStateFamily } from '../context/UserStateAdapters'; -import { ListPreferencesProvider, listPreferenceKey, localListStateKey } from '../context/ListPreferencesProvider'; +import { ListPreferencesProvider, listPreferenceKey } from '../context/ListPreferencesProvider'; import { applyListStateParams } from './userFilterUrlState'; import { toast } from 'sonner'; From fe3589d65a101f3e61382861dea8f995c2217a87 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:52:20 +0000 Subject: [PATCH 5/5] fix(console): a reload drops a list's address state only when the reload was of that list Review round 1 of the list draft. The reload check now compares the reloaded address with the list's own, so a reload of another page (the AI chat page) followed by an in-app list link keeps the link's state. The narrow face draws Discard alone where no save is offered. Save as my view and the switcher's create card share one test. Stale comments, the plugin-list README and the grid personalization checklist item follow the draft; the changeset's upgrade note is exact. Claude-Session: https://claude.ai/code/session_01L6bhgUr9HRqChVQu82hqdz Co-authored-by: Claude --- .changeset/35955-list-changes-are-drafts.md | 8 ++- content/docs/ui/views.mdx | 5 +- .../areas/records-forms.json | 16 +++-- .../ListDraftActions.noSave-35955.test.tsx | 37 +++++++++++ .../app-shell/src/views/ListDraftActions.tsx | 65 ++++++++++++------- .../ObjectView.listUrlState-11860.test.tsx | 42 ++++++++++++ .../app-shell/src/views/ObjectView.tsx | 19 +++--- .../app-shell/src/views/listDraftStore.ts | 48 ++++++++++---- .../src/views/objectViewListRenderer.tsx | 15 +++-- .../src/views/objectViewListUrlState.ts | 11 ++-- ui/packages/plugin-list/README.md | 6 +- 11 files changed, 203 insertions(+), 69 deletions(-) create mode 100644 ui/packages/app-shell/src/views/ListDraftActions.noSave-35955.test.tsx diff --git a/.changeset/35955-list-changes-are-drafts.md b/.changeset/35955-list-changes-are-drafts.md index dfa14b2bba1..7d912a2bd1f 100644 --- a/.changeset/35955-list-changes-are-drafts.md +++ b/.changeset/35955-list-changes-are-drafts.md @@ -1,6 +1,7 @@ --- '@object-ui/app-shell': patch '@object-ui/i18n': patch +'@object-ui/plugin-list': patch --- feat(console): a change on a list is a draft, with Discard and Save @@ -13,9 +14,10 @@ On a Console object list, a header sort, a filter change, grouping, the search, - While the list holds a draft, **Discard** and **Save** sit at the end of the condition row, where the 「Personalized · Reset to view」 marker was. On a narrow list or a phone they fold into one **Save** whose menu also holds Discard. - **Save** names what is unsaved and offers **Save to this view** (on a view of the reader's own) and **Save as my view**, which asks a name first (the view's name with "copy"), saves the draft as a new view of the reader's own and opens it. Either says "Saved", and the buttons go while the conditions stay. - **Discard** puts the list back as its view declares it and removes the list's `uf_*` parameters from the address bar. -- The draft survives opening a record (as a page or in the side panel) and coming back. Opening another view or object, or reloading the page, drops it. +- Where the reader may not save (no personal view can be created or updated), both faces are Discard alone. +- The draft survives opening a record (as a page or in the side panel) and coming back. Opening another view or object, or reloading the list's page, drops it. A reload of another page does not drop the state an in-app link to a list carries. - Column widths, the row height and the views' order are not a draft. They are still remembered for the reader in the same `ui.list.` row. -Upgrade note: a sort, filter, search, column order, hidden column or added column that an earlier Console stored in a reader's `ui.list.` row no longer applies; the list opens as its view declares it. Nothing stored is rewritten or deleted by this change. A reader who wants such a list kept saves it as a view of their own. +Upgrade note: a sort, filter, search, column order, hidden column or added column that an earlier Console stored in a reader's `ui.list.` row no longer applies; the list opens as its view declares it. Nothing stored is deleted by this change; a later column-width change rewrites that row's column state with the widths alone. A reader who wants such a list kept saves it as a view of their own. -Saving into a shared view is not offered yet. No metadata key, value or default changes. +Saving into a shared view, and saving the Display panel's layout and row colour, are not offered yet. `@object-ui/plugin-list` changes only its README, which now describes added fields as part of the draft. No metadata key, value or default changes. diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index 51158c65a6b..e94a8160c38 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -632,11 +632,12 @@ whose menu also holds Discard on a narrow list or a phone). - **Discard** puts the list back as its view declares it, the Display panel's layout and row color included, and removes the list's `uf_*` parameters from the address bar. - The draft survives opening a record and coming back. Opening another view or object, - or reloading the page, drops it, so a reload opens the view as it is declared. + or reloading the list's page, drops it, so that reload opens the view as it is declared. - Column widths, the row height (density) and the views' order are not a draft: they are remembered for the user (`sys_user_preference`, key `ui.list.`). A sort, filter, column order or hidden column an earlier Console stored there no longer applies. -- A link carrying list state (`uf_*` parameters) opened in a new tab applies it as a draft. +- A link carrying list state (`uf_*` parameters) applies it as a draft, whether it opens in a + new tab or in-app (an AI answer's list link, after a reload of the chat page too). - When a session ends, the sign-in page's return link keeps the list's path but never its `uf_*` state, so whoever signs in next opens the view's default. - A user's hidden fields only subtract from the columns the view shows, never add one. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index c6a44c78f31..b8c8aa36721 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -3582,7 +3582,7 @@ "title": "Grid personalization persists across reload: column resize/reorder/pin, row-height, group-by (with API-true totals), row-color", "since": "v16", "status": "active", - "revision": 8, + "revision": 9, "priority": "P2", "surface": "browser", "personas": [ @@ -3608,17 +3608,17 @@ "steps": [ "open showcase_task grid; screenshot", "resize a column (reorder two columns only on a grid that sets reorderableColumns; there is no runtime pin control — acceptance[0]), and set a row height on the Row height level of the list's options menu (the toolbar's options trigger, then 行高 / Row height: three choices, 紧凑 / 标准 / 宽松 — Compact / Standard / Spacious, ui/packages/plugin-list/src/components/ViewSettingsPopover.tsx; a gallery's Row height level picks its card size the same way) — three modes, stored as rowHeight compact / medium / tall (the spec's five row heights compact/short/medium/tall/extra_tall narrow onto these three: objectui core normalize-list-view.ts DENSITY_MODE_TO_ROW_HEIGHT / ROW_HEIGHT_TO_DENSITY_MODE)", - "reload; confirm the columnState (widths, and the order where reorder is enabled) and row-height restored — they now persist in the signed-in user's own list preference, sys_user_preference ui.list.showcase_task (perView..columnState / rowHeight, objectui#12418), with localStorage grid-columns-showcase_task[-] as the component's cache; the old per-view override through dataSource.updateViewConfig is retired (objectui#12504). Also reload in a FRESH browser context as the same user: the layout follows the user", + "reload; confirm the column widths and row-height restored — they persist in the signed-in user's own list preference, sys_user_preference ui.list.showcase_task (perView..columnState.widths / rowHeight, objectui#12418). A column ORDER is not: since objectstack#35955 it is the list's unsaved draft, so a reload reopens on the view's own order unless it was saved into a view, with localStorage grid-columns-showcase_task[-] as the component's cache; the old per-view override through dataSource.updateViewConfig is retired (objectui#12504). Also reload in a FRESH browser context as the same user: the layout follows the user", "group-by status ('Add group field' pre-selects the first field, Title, and groups at once, so switch it to Status). A runtime grouping lives in the list's URL (uf__group, ui/packages/app-shell/src/views/objectViewListUrlState.ts), not in sys_user_preference: reloading that URL keeps it, a reload of the bare list URL reopens on the view's own grouping by design, and steps[6] reads it that way (QA run #33861). Confirm per-group headers appear and each group shows its record count — summarizeField (estimate_hours) is declared on the KANBAN config of task.view.ts, not on the grid, so grid groups carry counts; clear grouping and confirm the headers are removed cleanly", "cross-check each group's count against a direct per-group server count (GET /api/v1/data/showcase_task filtered to that status, read its total)", "read the row-color rule the stock Grid view declares — rowColor on priority with the colors map low slate / medium blue / high amber / urgent red (examples/app-showcase/src/ui/views/task.view.ts); there is no runtime row-color authoring control — and confirm rows paint by it (useRowColor, the -100 tint of each name)", - "reload once more; confirm every personalization survives; capture a screenshot per variant" + "reload once more; confirm every personalization this item stores survives (column widths, row height); capture a screenshot per variant" ], "acceptance": [ { - "clause": "PER-VARIANT: column RESIZE persists across a reload — the widths restore from the column-state store (localStorage grid-columns-[-], or a persisted view override). Column REORDER and PIN are not stock list-view personalizations, and the clause does not assert them there. ObjectGrid enables drag-reorder only from `reorderableColumns` (default false), which is an object-grid component prop (packages/spec/src/ui/component.zod.ts#ObjectGridPropsSchema), not a ListView key. Pinning is AUTHOR-declared per column (`pinned`, packages/spec/src/ui/view.zod.ts#ListColumnSchema), with no runtime pin control, and the persisted column state carries widths and order, never pins. So: reorder persists across a reload only on a grid that enables it (score it there, or record n/a on the stock showcase_task list view); a column the view declares `pinned` renders pinned after the reload (n/a when the view declares none, as the stock task views do)", + "clause": "PER-VARIANT: column RESIZE persists across a reload — the widths restore from the column-state store (localStorage grid-columns-[-], or a persisted view override). Column REORDER and PIN are not stock list-view personalizations, and the clause does not assert them there. ObjectGrid enables drag-reorder only from `reorderableColumns` (default false), which is an object-grid component prop (packages/spec/src/ui/component.zod.ts#ObjectGridPropsSchema), not a ListView key. Pinning is AUTHOR-declared per column (`pinned`, packages/spec/src/ui/view.zod.ts#ListColumnSchema), with no runtime pin control, and the persisted column state carries widths and order, never pins. So: a column order is the list's unsaved draft since objectstack#35955 and does NOT persist across a reload (it is kept only by Save into a view); on a grid that enables reorder, score that the reload reopens on the view's order, or record n/a on the stock showcase_task list view; a column the view declares `pinned` renders pinned after the reload (n/a when the view declares none, as the stock task views do)", "oracle": "dom", - "verify": "after a screenshot confirms render, the reloaded grid shows the same widths (ObjectGrid columnState priority: props override > localStorage > empty; saveColumnState persists widths and order only). The reorder and pin variants are judged as the clause scopes them", + "verify": "after a screenshot confirms render, the reloaded grid shows the same widths (ObjectGrid columnState priority: props override > localStorage > empty; saveColumnState persists widths and order, and the console hands the grid the reader's widths alone (objectViewListRenderer.tsx persistListColumnState), so the props override carries no order after a reload). The reorder and pin variants are judged as the clause scopes them", "evidence": "before/after-reload screenshots + the storage value" }, { @@ -3709,6 +3709,12 @@ "date": "2026-11-19", "change": "steps[1] and acceptance[1].clause re-pointed to the options menu's Row height level: three named choices (紧凑 / 标准 / 宽松, Compact / Standard / Spacious) replace the cycling density button, on a grid and on a gallery (its card size). Stored values unchanged (rowHeight compact / medium / tall). No clause's meaning changed.", "ref": "#35551" + }, + { + "revision": 9, + "date": "2026-11-21", + "change": "steps[2], steps[6] and acceptance[0] (clause, verify) re-pointed to the list draft (objectstack#35955): a column order is the list's unsaved draft, kept only by Save into a view, so it no longer comes back after a reload; the widths and the row height still persist in the user's ui.list. row. Not loosened: widths and row height must still survive a reload and follow the user to a fresh browser", + "ref": "#35955" } ] }, diff --git a/ui/packages/app-shell/src/views/ListDraftActions.noSave-35955.test.tsx b/ui/packages/app-shell/src/views/ListDraftActions.noSave-35955.test.tsx new file mode 100644 index 00000000000..bff4f4e9d08 --- /dev/null +++ b/ui/packages/app-shell/src/views/ListDraftActions.noSave-35955.test.tsx @@ -0,0 +1,37 @@ +/** + * objectstack#35955 — Discard and Save where no save is offered (personal + * views not ready, or no grant to create one on a shared view): both faces + * are Discard alone. The narrow face never draws a Save that holds nothing + * to save. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, cleanup, fireEvent, screen } from '@testing-library/react'; +import { ListDraftActions } from './ListDraftActions'; + +afterEach(() => cleanup()); + +describe('Discard and Save with no save offered (objectstack#35955)', () => { + it('draws Discard on both faces and no Save at all', () => { + const onDiscard = vi.fn(); + render(); + + expect(screen.queryByTestId('list-draft-save')).toBeNull(); + expect(screen.queryByTestId('list-draft-compact')).toBeNull(); + expect(screen.getByTestId('list-draft-discard')).toBeTruthy(); + const compact = screen.getByTestId('list-draft-compact-discard'); + // A plain button, not a menu item: it discards on a click. + expect(compact.tagName).toBe('BUTTON'); + fireEvent.click(compact); + expect(onDiscard).toHaveBeenCalledTimes(1); + }); + + it('CONTROL: with a save offered, the narrow face is one Save whose menu holds Discard', () => { + render( {}} onSaveAsMyView={() => {}} />); + + expect(screen.getByTestId('list-draft-compact')).toBeTruthy(); + // Discard lives inside that menu, not beside it. + expect(screen.queryByTestId('list-draft-compact-discard')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/ListDraftActions.tsx b/ui/packages/app-shell/src/views/ListDraftActions.tsx index 97e0e45de54..19ed7239239 100644 --- a/ui/packages/app-shell/src/views/ListDraftActions.tsx +++ b/ui/packages/app-shell/src/views/ListDraftActions.tsx @@ -14,7 +14,8 @@ * * As the list narrows (the phone list draws this same control in its chip * row, objectstack#35883), the two faces fold into ONE Save whose menu also - * holds Discard: one control, one save path, at every width. + * holds Discard: one control, one save path, at every width. Where no save + * is offered, both faces are Discard alone. * * Nothing here is configurable: no metadata key or option reaches it. */ @@ -142,29 +143,45 @@ export function ListDraftActions({ ) : null} - {/* The narrow face: one Save, whose menu also holds Discard. */} - - - - - - {offersSave ? saveItems : null} - {offersSave ? : null} - onDiscard()} data-testid="list-draft-compact-discard"> - - - + {/* The narrow face: one Save, whose menu also holds Discard. With no + save offered, a Save would hold nothing to save: Discard alone. */} + {offersSave ? ( + + + + + + {saveItems} + + onDiscard()} data-testid="list-draft-compact-discard"> + + + + ) : ( + + )} ); } diff --git a/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx index 9ad6b526a31..62631fd7f18 100644 --- a/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.listUrlState-11860.test.tsx @@ -356,6 +356,48 @@ describe('a list is a link (objectui#11860)', () => { }); }); +describe('objectstack#35955 — a reload drops a list\'s address state only when the reload was of that list', () => { + /** The document's navigation entry, as `performance` reports it. */ + function stubNavigation(type: string, name: string) { + vi.spyOn(performance, 'getEntriesByType').mockImplementation(((kind: string) => + kind === 'navigation' ? [{ type, name } as unknown as PerformanceEntry] : []) as typeof performance.getEntriesByType); + } + afterEach(() => { + window.history.replaceState(null, '', '/'); + }); + + it('a reload of the list itself opens the view\'s own state and strips the `uf_*` params', async () => { + const address = link(`${VIEW}/all`, { filter: URGENT, search: 'acme' }); + window.history.replaceState(null, '', address); + stubNavigation('reload', new URL(address, window.location.origin).href); + const host = await mountHost([address]); + const q = lastQuery(); + expect(filterOf(q)).not.toContain('urgent'); + expect(q.$search).toBeUndefined(); + expect(new URLSearchParams(host.search()).has(LIST_FILTER_PARAM)).toBe(false); + }); + + it('a reload of ANOTHER page, then an in-app link to a list with a filter: the link\'s filter applies', async () => { + // The reader reloaded the AI chat page; the answer's list link then navigates in-app. + window.history.replaceState(null, '', '/apps/crm/ai-chat'); + stubNavigation('reload', new URL('/apps/crm/ai-chat', window.location.origin).href); + const address = link(`${VIEW}/all`, { filter: URGENT }); + const host = await mountHost(['/elsewhere']); + window.history.replaceState(null, '', address); + await host.go(address); + expect(filterOf(lastQuery())).toContain('"priority","=","urgent"'); + expect(new URLSearchParams(host.search()).has(LIST_FILTER_PARAM)).toBe(true); + }); + + it('CONTROL: a first load (not a reload) of a list link applies its filter', async () => { + const address = link(`${VIEW}/all`, { filter: URGENT }); + window.history.replaceState(null, '', address); + stubNavigation('navigate', new URL(address, window.location.origin).href); + await mountHost([address]); + expect(filterOf(lastQuery())).toContain('"priority","=","urgent"'); + }); +}); + describe('a malformed or stale param is dropped — the list opens and nothing throws (objectui#11860)', () => { it('a filter that is not JSON and a sort that is not the spec shape', async () => { const host = await mountHost([ diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index f8a1fb735f5..4d82e5044cd 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -758,9 +758,9 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co searchParams, setSearchParams, }); - // objectstack#28950 — the 「Personalized」 marker beside the list title (the - // page header's badge slot, and the phone title): drawn only while the - // reader's list differs from the view, and the one way back to it. + // objectstack#35955 — Discard and Save at the condition row's end (the + // 「Personalized」 marker of objectstack#28950 before them): drawn only while + // the reader's list holds a draft, and the one way back to the view. // objectstack#30073 — 保存: the list on screen written back into the open // personal view, through the body Save as my view builds (so the stored // shape is the same), then the reader's list state for it is cleared and @@ -803,13 +803,17 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // the end of the condition row (the phone draws the same slot). 「Save to // this view」 writes one of the reader's own views here; a shared view's // save is not offered on the list yet. 「Save as my view」 asks a name. - const canSaveAsMyView = personalViewsReady && personalGrant('create') && !!activeView; + // objectstack#29635 — the one test for creating one of the reader's own + // views, shared by Save as my view here and the view switcher's create + // card: a reader who cannot read the list's own object has no list to keep. + const listReadable = !perms.isLoaded || perms.can(objectDef.name, 'read'); + const canCreatePersonalView = personalViewsReady && personalGrant('create') && listReadable && !!activeView && !viewAccess.refusal; const draftActions = !isEnvironmentList && listDraftParts.length > 0 ? ( { void handleSaveToPersonalView(); } : undefined} - onSaveAsMyView={canSaveAsMyView ? () => setPersonalViewDialog({ mode: 'saveAs' }) : undefined} + onSaveAsMyView={canCreatePersonalView ? () => setPersonalViewDialog({ mode: 'saveAs' }) : undefined} /> ) : null; @@ -896,8 +900,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // the view switcher's in-place create card (objectstack#35553, which // folded Save as my view into it); a rename's name is asked in // `PersonalViewNameDialog`. A reader who cannot read the list's own object - // is offered no create: there is no list to keep. - const listReadable = !perms.isLoaded || perms.can(objectDef.name, 'read'); + // is offered no create: there is no list to keep (`listReadable`, above). const [personalViewDialog, setPersonalViewDialog] = useState<{ mode: 'rename'; viewId: string } | { mode: 'saveAs' } | null>(null); const openPersonalView = (id: string) => { if (viewId) navigate(`../${id}`, { relative: 'path' }); @@ -1109,7 +1112,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co openPersonal: openPersonalView, createShared: handleViewCreate, clearSourceListState, - canCreatePersonal: personalViewsReady && personalGrant('create') && listReadable && !!activeView && !viewAccess.refusal, + canCreatePersonal: canCreatePersonalView, canCreateShared: isAdmin, hasUnsavedConditions: listDraftParts.some((part) => part === 'filters' || part === 'sort'), }, diff --git a/ui/packages/app-shell/src/views/listDraftStore.ts b/ui/packages/app-shell/src/views/listDraftStore.ts index e62151e459d..a9439cf1e2d 100644 --- a/ui/packages/app-shell/src/views/listDraftStore.ts +++ b/ui/packages/app-shell/src/views/listDraftStore.ts @@ -8,7 +8,7 @@ * * What a draft holds: the sort, the Filter panel's group, the grouping, the * search term, the columns shown (hidden ones, added ones), the column order - * and the Display panel's layout and row colour. What it never holds: the + * and (from PR 2) the Display panel's layout and row colour. What it never holds: the * column widths and the row height, which are remembered for the reader * (`ListPreferencesProvider`), and the view tab order. * @@ -21,10 +21,11 @@ * it: the record page draws no list of this store, so nothing replaces it; * - opening another view or another object replaces it (`claimListDraft` with * another scope), with no prompt; - * - a reload loses it, the module's memory with it. The address's `uf_*` - * copy of the toolbar state is dropped on a reload too - * (`isDocumentReload`, read by the list's seed), so the list opens as its - * view declares it. + * - a reload loses it, the module's memory with it. When the reloaded page + * is the list itself, the address's `uf_*` copy of the toolbar state is + * dropped too (`takeDocumentReload`, read by the list's seed), so the list + * opens as its view declares it. A reload of another page does not touch a + * list an in-app link opens later. * * Not React state: the list page unmounts while a record is open as a page, * and the draft must outlive it. Readers subscribe through @@ -53,9 +54,16 @@ export interface ListDraft { hiddenFields?: string[]; /** The object's fields the reader added as columns. */ addedFields?: string[]; - /** The visualization the reader switched to (`ListView`'s layout control). */ + /** + * The visualization the reader switched to (`ListView`'s layout control). + * Nothing writes it yet: the list hands its layout out from PR 2 of + * objectstack#35955, and Save keeps it from then. + */ viewType?: string; - /** The row colour the reader picked, or `null` for "none" over a view that colours its rows. */ + /** + * The row colour the reader picked, or `null` for "none" over a view that + * colours its rows. Written from PR 2 of objectstack#35955, as `viewType`. + */ rowColor?: { field: string; colors?: Record } | null; } @@ -173,19 +181,35 @@ export function useListDraft(scope: string): { } /** - * Was this document opened by a reload? Read once per document: only the - * first list this page seeds is the one the reload asked for again; every - * later one was navigated to inside the app. + * Was THIS list's address the one a reload opened? Read once per document: + * only the first list this page seeds can be the one the reload asked for + * again, and only when the reloaded address is the address that list opens + * on (path and query; the hash is ignored). A reload of another page (the AI + * chat page, say) followed by an in-app link to a list with `uf_*` state is + * NOT a reload of that list: the link's state applies. */ let reloadConsumed = false; -export function takeDocumentReload(): boolean { +export function takeDocumentReload(currentHref?: string): boolean { if (reloadConsumed) return false; reloadConsumed = true; try { const entry = typeof performance !== 'undefined' && typeof performance.getEntriesByType === 'function' ? (performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined) : undefined; - return entry?.type === 'reload'; + if (entry?.type !== 'reload') return false; + const here = currentHref ?? (typeof window !== 'undefined' ? window.location.href : ''); + return sameAddress(entry.name, here); + } catch { + return false; + } +} + +/** Two absolute addresses name the same page: origin, path and query alike. */ +function sameAddress(a: string, b: string): boolean { + try { + const x = new URL(a); + const y = new URL(b); + return x.origin === y.origin && x.pathname === y.pathname && x.search === y.search; } catch { return false; } diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index c8000e5806f..dd0fa7f6e13 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -161,7 +161,7 @@ export function useObjectViewListRenderer({ * of the page, read through a store like the lead. */ viewBarTrailing: ((tools: ReactNode) => ReactNode) | null; - /** objectstack#35878 — the condition row's right end: the 「Personalized · Reset」 marker, or `null`. */ + /** objectstack#35878 — the condition row's right end: Discard and Save while the list holds a draft (objectstack#35955), or `null`. */ conditionRowEnd: ReactNode; /** objectstack#28950 — what of the list differs from the view, keyed by the list identity. */ handleListPersonalizationChange: ReturnType['handleListPersonalizationChange']; @@ -172,7 +172,7 @@ export function useObjectViewListRenderer({ * objectstack#30073 — the active view's own conditions when the Filter * panel holds them as rows (a personal view, `personalViewPanelFilters`): * the panel opens on them, they are not applied under the list a second - * time, and the list judges its 「Personalized」 filters against them. + * time, and the list judges its draft filters against them. */ viewPanelFilters?: FilterBuilderRowGroup; /** @@ -536,9 +536,10 @@ export function useObjectViewListRenderer({ /** * objectstack#30077 (ruling 6631126993, option A) — the object's fields - * this user ADDED to their list as columns with the same popover, stored - * beside their hidden fields (`addedFields`) and dropped with the rest of - * the entry by "Reset to view". The `columns` rung below appends them to + * this user ADDED to their list as columns with the same popover, held + * in the list's draft beside their hidden fields (`addedFields`, + * objectstack#35955): Save keeps them in a view, Discard drops them with + * the rest of the draft. The `columns` rung below appends them to * the view's columns, so the list fetches, expands and draws them as it * does a declared column; `ListView` offers only fields the caller may * read. Offered where a Hide Fields choice is stored, never on the @@ -1083,8 +1084,8 @@ export function useObjectViewListRenderer({ // objectstack#28948 — those resets clear the user's state. onRestoreViewDefaults={restoreViewDefaults} // objectstack#28950 — what of the list differs from the view, - // for the 「Personalized」 marker, which then owns the one reset - // (the Display control draws none of its own). + // for Discard and Save (objectstack#35955), which then own the + // one reset (the Display control draws none of its own). onPersonalizationChange={(parts) => handleListPersonalizationChange(identityKey, parts)} // objectstack#35551 — the view's rename, 保存 and full reset in the options menu. onRenameView={offersRename ? (label: string) => listViewActionsRef.current?.rename?.(label) ?? false : undefined} diff --git a/ui/packages/app-shell/src/views/objectViewListUrlState.ts b/ui/packages/app-shell/src/views/objectViewListUrlState.ts index 28875c4d736..4708e60e451 100644 --- a/ui/packages/app-shell/src/views/objectViewListUrlState.ts +++ b/ui/packages/app-shell/src/views/objectViewListUrlState.ts @@ -257,9 +257,10 @@ export function useObjectViewListUrlState({ } | undefined>(undefined); const { t } = useObjectTranslation(); const ownListParamsRef = useRef(undefined); - // objectstack#28950 — set by "Reset to view" and taken by the next seed: - // that list opens from the (just cleared) stored state, never from the - // `uf_*` params, whoever wrote them, and its write-back strips them all. + // objectstack#28950 — set by Discard ("Reset to view" before + // objectstack#35955) and taken by the next seed: that list opens from the + // (just dropped) draft, never from the `uf_*` params, whoever wrote them, + // and its write-back strips them all. const resetPendingRef = useRef(false); if (listIdentityKey && listPrefs.ready && !viewResolving && listSeedRef.current?.key !== listIdentityKey) { // objectstack#35955 — this list is the one on screen: a draft held @@ -439,7 +440,7 @@ export function useObjectViewListUrlState({ * move comes back through `writeListUrlState({ page })`, replacing the * entry. So Back from a record opened as a full page, a reload and a copied * link land on the page the reader left; the list's own reset to page 1 - * deletes the param, and "Reset to view" strips it with the rest. + * deletes the param, and Discard strips it with the rest. */ const listPage = parseListPageParam(searchParams); return { @@ -526,7 +527,7 @@ export function useObjectViewUrlFilters({ */ const ufSelectionsRef = useRef<{ key: string; selections: Record | undefined } | undefined>(undefined); if (listIdentityKey && ufSelectionsRef.current?.key !== listIdentityKey) { - // objectstack#28950 — the list "Reset to view" opened starts with no + // objectstack#28950 — the list Discard opened starts with no // chip selected: its seed strips their params from the address bar. const reset = listSeedRef?.current?.key === listIdentityKey && !!listSeedRef.current.reset; ufSelectionsRef.current = { key: listIdentityKey, selections: reset ? undefined : parseUserFilterParams(searchParams) }; diff --git a/ui/packages/plugin-list/README.md b/ui/packages/plugin-list/README.md index 28a84eafafd..2a07217973d 100644 --- a/ui/packages/plugin-list/README.md +++ b/ui/packages/plugin-list/README.md @@ -294,13 +294,13 @@ A host that lets a reader add fields to their own list wires panel's section) then lists, after the view's columns, every other field of the object the reader may read and the definition does not mark `hidden`, unticked. Ticking one calls `onAddedFieldsChange` with the whole new list of added names; -the host stores it as the reader's own and appends those fields to +the host keeps it as the reader's own and appends those fields to `schema.columns`, naming them in `addedFields`, so unticking an added column takes it off the list instead of hiding it. These are React props for the host app, not schema keys: list metadata cannot set them. Without `onAddedFieldsChange` the popover lists the view's columns alone. The console -wires both on the object list page, where the added fields are kept with the -reader's other list preferences and cleared by "Reset to view". +wires both on the object list page, where the added fields are part of the +list's unsaved draft: Save keeps them in a view, Discard drops them. ```tsx import { ListView } from '@object-ui/plugin-list';