diff --git a/.changeset/35883-phone-list-toolbar-panels.md b/.changeset/35883-phone-list-toolbar-panels.md new file mode 100644 index 00000000000..e0a29470538 --- /dev/null +++ b/.changeset/35883-phone-list-toolbar-panels.md @@ -0,0 +1,25 @@ +--- +'@object-ui/plugin-list': patch +'@object-ui/plugin-grid': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(list): a phone's object list gets its own top row, one row of pills, and bottom-sheet sort, filter and view panels that apply on 「✓」 + +Clause-②: yes (widening) +Metadata-protocol: none + +At phone width (below `sm`) the console's object list changes its containers, not its content: + +- The app bar's row becomes the page's own: 「‹」, the object's icon and name, and 「⋮ More」 at the right. The app pill, the page title, the search, the bell and the avatar are not drawn while the list is on screen (the phone has them in the bottom bar and on the app's home). 「⋮ More」 offers 「Select」 (only on a card list whose rows take more than one tick), the object's description, Import and the favorite. +- Below it, one row of pills: the view switcher, Sort and Filter with a count of what is in force, and Search, which expands into a field in place. There is no condition row on a phone. +- Sort, Filter, the view switcher and View settings open as bottom sheets. The sort and filter sheets edit a copy: 「✓」 applies it through the same write the desktop chips use, 「×」 drops it. The sort sheet lists each level on two lines (field over direction) with a handle a finger can drag (or ArrowUp / ArrowDown moves), a ⋯ menu per level (change field, direction, remove) and 「Add sort」. The filter sheet lists the conditions, each with a ⋯ menu (edit, remove), and shows a sentence and 「Add filter」 when there are none. A view whose filter is an 「or」 group says it uses an advanced filter and is changed on a computer. View settings keeps its desktop content and applies as before. 「✓」 on an untouched copy writes nothing. While the on-screen keyboard is up, a sheet stands on it (it reads `visualViewport`), so its 「✓」 and the focused field stay in view. +- A long press on a card starts selecting with that card ticked, as 「Select」 in 「⋮ More」 does with none; a tap then ticks or unticks a card, and unticking the last ends it. The selection shows in the list's floating selection bar, which after 「Select」 reads 「0 selected ×」 until a card is ticked. The 「+」 create button is not drawn while selecting. A card is also a keyboard control: Enter opens it, and while selecting Enter or Space toggles it. + +New exports and props: + +- `@object-ui/plugin-list`: `PhonePanelSheet`, `useListPhonePanels`, `PHONE_CHIP`, `PHONE_CHIP_ACTIVE` and the types `PhonePanelSheetProps`, `ListPhonePanels`. +- `@object-ui/plugin-grid`: `requestListSelection`, `useListPageSelecting` and `useListPageSelectable` (would 「Select」 open a selection in this page's list); `BulkActionBar` takes `open` (show 「0 selected ×」 with no actions while a host's selection is open and empty). + +`@object-ui/app-shell` changes no public export: the page's top row is an internal store (`PhonePageBarProvider`, mounted by `ConsoleLayout`). diff --git a/ui/e2e/list-frame-geometry-35548.spec.ts b/ui/e2e/list-frame-geometry-35548.spec.ts index e74aa6716fc..bf3a67d33f6 100644 --- a/ui/e2e/list-frame-geometry-35548.spec.ts +++ b/ui/e2e/list-frame-geometry-35548.spec.ts @@ -108,7 +108,9 @@ const SWITCHER_TRIGGER = carrying( ); /** The trigger's children in source order, read off their test ids. */ const SWITCHER_PARTS = ['type-icon', 'label', 'count', 'caret'] as const; -const switcherBody = SRC.switcher.slice(SRC.switcher.indexOf('data-testid="list-view-switcher"'), SRC.switcher.indexOf('')); +// The desktop trigger, inside its popover's trigger: the phone toolbar's pill +// (objectstack#35883) comes first in the file and draws no type icon. +const switcherBody = SRC.switcher.slice(SRC.switcher.indexOf('')); // ── grid ──────────────────────────────────────────────────────────────────── const DENSITY = (() => { diff --git a/ui/e2e/list-toolbar-view-name-phone.spec.ts b/ui/e2e/list-toolbar-view-name-phone.spec.ts index 0cf778b3e0e..fbddb9067ee 100644 --- a/ui/e2e/list-toolbar-view-name-phone.spec.ts +++ b/ui/e2e/list-toolbar-view-name-phone.spec.ts @@ -6,13 +6,13 @@ import path from 'node:path'; import { uiRoot } from '../scripts/ui-root.mjs'; /** - * GEOMETRY pin for objectstack#33833: on a phone the list's toolbar row keeps - * the view name readable. Below `sm` the Console hands the list its view - * switcher as `toolbarLeading`, and the row that draws it also carries the - * user-filter chips, the 「In a queue」 toggle and the tool cluster, whose - * icons are 44 px touch targets there. On one line those left the name about - * a character and a half (「全部客户」 drawn as 「全.」 at 375 px). The row now - * wraps below `sm` (`listToolbarRow.ts` in plugin-list says how). + * GEOMETRY pin for objectstack#33833, re-pointed at the phone toolbar of + * objectstack#35883: on a phone the list's view name stays readable. Below + * `sm` the list draws ONE row of pills (`PhoneListToolbar`, plugin-list's + * `phone/PhoneListPanels.tsx`): the view switcher's pill (the view's name, + * its count, the caret), then Sort, Filter and Search, each a 44 px pill. + * The name takes what the three pills leave and ends in an ellipsis only + * when it is wider than that. * * ⚠️ A Playwright spec, not a vitest test: jsdom and happy-dom have no layout * engine, so a width read there is 0 and a class-shape assertion would pass @@ -20,29 +20,23 @@ import { uiRoot } from '../scripts/ui-root.mjs'; * * ## What is real here and what is a fixture * - * REAL, read out of the sources at run time: the row's classes (the constants - * in `packages/plugin-list/src/listToolbarRow.ts`, by name), the 「In a queue」 - * toggle's and the View settings trigger's class strings and the phone - * touch-target classes from plugin-list, the switcher's own classes from app-shell's - * `objectViewTitleSwitcher.tsx` (the trigger now draws the view type's icon - * and the record count beside the name, objectstack#35548), and the phone - * title's wrapper from - * `ObjectView.tsx`, compiled with the installed `tailwindcss`. Change a class - * in any of them and what this file measures changes with it. + * REAL, read out of the sources at run time: the row's and its view slot's + * classes and `PHONE_CHIP` (plugin-list `phone/PhoneListPanels.tsx`), the + * phone search pill's own classes (`ListView.tsx`), the switcher pill's + * classes (app-shell `objectViewTitleSwitcher.tsx`) and the phone title's + * wrapper (`ObjectView.tsx`), compiled with the installed `tailwindcss`. + * Change a class in any of them and what this file measures changes with it. * * FIXTURE: the element tree is transcribed from those sources, icons are empty - * boxes of their declared size, the `Button` base is reduced to its layout - * tokens (`inline-flex items-center justify-center whitespace-nowrap`), and - * fonts are Chromium's. The assertions are clipping, overflow and lines, not - * pixels. + * boxes of their declared size, and fonts are Chromium's. The assertions are + * clipping, overflow and lines, not pixels. */ const ROOT = uiRoot(); const read = (rel: string) => readFileSync(path.join(ROOT, rel), 'utf8'); -const ROW_FILE = 'packages/plugin-list/src/listToolbarRow.ts'; +const PANELS_FILE = 'packages/plugin-list/src/phone/PhoneListPanels.tsx'; const LIST_FILE = 'packages/plugin-list/src/ListView.tsx'; -const TOUCH_FILE = 'packages/plugin-list/src/components/ViewSettingsPopover.tsx'; const SWITCHER_FILE = 'packages/app-shell/src/views/objectViewTitleSwitcher.tsx'; const OBJECT_VIEW_FILE = 'packages/app-shell/src/views/ObjectView.tsx'; @@ -55,7 +49,8 @@ function constant(source: string, file: string, name: string): string { /** * The first quoted class string of the JSX tag that carries `anchor` - * (`className="…"`, or the first literal of `className={cn('…'`), read from + * (`className="…"`, or the first literal of `className={cn('…'` or + * `className={cn(CONSTANT, '…'`), read from * the tag's opening `<` up to the next element's. `mustContain` holds tokens * that string has to carry, so a walk onto the wrong element throws instead of * measuring it. @@ -68,7 +63,7 @@ function tagClass(source: string, file: string, anchor: string, mustContain: str next.lastIndex = at; const end = next.exec(source)?.index ?? source.length; const tag = source.slice(open, end); - const hit = /className=(?:"([^"]+)"|\{cn\(\s*(?:\/\/[^\n]*\n\s*)*['"]([^'"]+)['"])/.exec(tag); + const hit = /className=(?:"([^"]+)"|\{cn\(\s*(?:\/\/[^\n]*\n\s*)*(?:[A-Z_]+,\s*)?['"]([^'"]+)['"])/.exec(tag); if (!hit) throw new Error(`${file}: no class string in the tag carrying ${anchor}`); const cls = hit[1] ?? hit[2]; for (const token of mustContain) { @@ -79,98 +74,47 @@ function tagClass(source: string, file: string, anchor: string, mustContain: str return cls; } -const rowSrc = read(ROW_FILE); +const panelsSrc = read(PANELS_FILE); const listSrc = read(LIST_FILE); -const ROW_NAMES = [ - 'TOOLBAR_ROW', - 'TOOLBAR_ROW_LEADING_PHONE', - 'TOOLBAR_LEFT_GROUP_LEADING', - 'TOOLBAR_LEADING', - 'TOOLBAR_USER_FILTERS', - 'TOOLBAR_USER_FILTERS_LEADING_PHONE', - 'TOOLBAR_CLUSTER', - 'TOOLBAR_CLUSTER_LEADING_PHONE', -] as const; -const ROW = Object.fromEntries(ROW_NAMES.map((n) => [n, constant(rowSrc, ROW_FILE, n)])) as Record< - (typeof ROW_NAMES)[number], - string ->; - const switcherSrc = read(SWITCHER_FILE); const objectViewSrc = read(OBJECT_VIEW_FILE); -const SWITCHER = { - phoneTitle: tagClass(objectViewSrc, OBJECT_VIEW_FILE, 'data-testid="list-phone-title"', ['min-w-0', 'max-sm:font-semibold']), - trigger: tagClass(switcherSrc, SWITCHER_FILE, 'data-testid="list-view-switcher"', ['min-w-0', 'max-sm:min-h-11']), -}; -// The switcher's outer span is the first element of its return. -const SWITCHER_OUTER = (() => { - const hit = /return \(\s*\s* (phone ? `${base} ${add}` : base); - return { - row: plus(ROW.TOOLBAR_ROW, ROW.TOOLBAR_ROW_LEADING_PHONE), - left: phone ? ROW.TOOLBAR_LEFT_GROUP_LEADING : ROW.TOOLBAR_LEFT_GROUP_LEADING.replace(/\s*max-sm:\S+/g, ''), - leading: phone ? ROW.TOOLBAR_LEADING : ROW.TOOLBAR_LEADING.replace(/\s*max-sm:\S+/g, ''), - filters: plus(ROW.TOOLBAR_USER_FILTERS, ROW.TOOLBAR_USER_FILTERS_LEADING_PHONE), - cluster: plus(ROW.TOOLBAR_CLUSTER, ROW.TOOLBAR_CLUSTER_LEADING_PHONE), - }; +if (!/className=\{cn\(\s*PHONE_CHIP,\s*'sm:hidden'/.test(listSrc)) { + throw new Error(`${LIST_FILE}: the phone search pill no longer draws from PHONE_CHIP`); } +const ICON = 'h-4 w-4'; +const CARET = 'h-3.5 w-3.5 shrink-0'; -function fixture(label: string, { chips = 0, phone = true } = {}): string { - const c = rowClasses(phone); - const icon = ``; +function fixture(label: string): string { + const pill = (id: string, cls: string) => ``; return ` -
-
-
- - - -
- ${chips > 0 ? `
${Array.from({ length: chips }, () => ``).join('')}
` : ''} - +
+
+ + +
-
${Array.from({ length: 4 }, () => ``).join('')}
+ ${pill('sort', PHONE_CHIP)} + ${pill('filter', PHONE_CHIP)} + ${pill('search', BAR.search)}
`; } -const CANDIDATES = [ - ...Object.values(ROW), - ...Object.values(SWITCHER), - SWITCHER_OUTER, - QUEUE, - ICON_BUTTON, - ICON, - TYPE_ICON, - COUNT, - CARET, - CHIP, - 'truncate flex min-w-0 items-center gap-1', -] +const CANDIDATES = [...Object.values(BAR), PHONE_CHIP, ICON, CARET, 'flex min-w-0'] .join(' ') .split(/\s+/) .filter(Boolean); @@ -187,7 +131,7 @@ test.beforeAll(async () => { }); css = compiler.build(CANDIDATES); if (!css.includes('@media')) { - throw new Error('Tailwind produced no media queries, so the max-sm variants under test would be inert.'); + throw new Error('Tailwind produced no media queries, so the sm variants under test would be inert.'); } }); @@ -197,16 +141,17 @@ type Reading = { labelScrollWidth: number; labelClipped: boolean; row: Box; + rowScrolls: boolean; leading: Box; - queue: Box; - cluster: Box; - chips: Box | null; + pills: Box[]; overflowX: number; }; async function measure(page: Page, html: string, width: number): Promise { await page.setViewportSize({ width, height: 812 }); - await page.setContent(`${html}`, { waitUntil: 'load' }); + // The meta makes a mobile project lay the page out at the viewport's width, + // not 980 px, so the `sm:` variants answer the width under test. + await page.setContent(`${html}`, { waitUntil: 'load' }); await page.evaluate(() => document.fonts?.ready); return page.evaluate(() => { const box = (id: string) => { @@ -222,10 +167,12 @@ async function measure(page: Page, html: string, width: number): Promise Math.ceil(w), row: box('row')!, + rowScrolls: (() => { + const row = document.getElementById('row')!; + return row.scrollWidth > row.clientWidth; + })(), leading: box('leading')!, - queue: box('queue')!, - cluster: box('cluster')!, - chips: box('chips'), + pills: ['sort', 'filter', 'search'].map((id) => box(id)!), overflowX: document.documentElement.scrollWidth - document.documentElement.clientWidth, }; }); @@ -233,51 +180,40 @@ async function measure(page: Page, html: string, width: number): Promise inner.left >= outer.left - 0.5 && inner.right <= outer.right + 0.5; -test.describe('list toolbar keeps the view name readable on a phone (objectstack#33833)', () => { - test('ListView draws its toolbar row from these constants', () => { - for (const name of ROW_NAMES) { - expect(listSrc.includes(name), `${LIST_FILE} no longer reads ${name}, so this file would measure nothing it draws`).toBe(true); - } - }); +const NAMES = ['全部客户', 'All Customers']; - for (const width of [320, 375, 390]) { - for (const label of ['全部客户', 'All Customers']) { - test(`${width}px: 「${label}」 is drawn whole, and nothing scrolls the page`, async ({ page }) => { +test.describe('the phone toolbar keeps the view name readable (objectstack#33833, #35883)', () => { + for (const width of [375, 390]) { + for (const label of NAMES) { + test(`${width}px: 「${label}」 is drawn whole on one row with Sort, Filter and Search`, async ({ page }) => { const r = await measure(page, fixture(label), width); expect(r.labelClipped, `label ${r.labelWidth.toFixed(2)}px of ${r.labelScrollWidth}px`).toBe(false); expect(r.overflowX, 'the toolbar pushed the page sideways').toBe(0); - for (const [name, b] of [['queue', r.queue], ['cluster', r.cluster]] as const) { - expect(within(b, r.row), `${name} leaves the row`).toBe(true); + expect(r.rowScrolls, 'the row scrolls sideways').toBe(false); + for (const pill of r.pills) { + expect(within(pill, r.row), 'a pill leaves the row').toBe(true); + expect(pill.top < r.leading.bottom && pill.bottom > r.leading.top, 'a pill left the name\'s line').toBe(true); + expect(Math.round(pill.bottom - pill.top), 'a 44 px touch target').toBe(44); } - // The tools keep the row's right edge (its `px-2` padding) on whichever line they land. - expect(r.row.right - r.cluster.right, 'the tool cluster left the right edge').toBeLessThanOrEqual(8.5); }); } } - test('375px with five filter chips, wider than the row: the name is whole, the chips scroll inside the row', async ({ page }) => { - const r = await measure(page, fixture('全部客户', { chips: 5 }), 375); - expect(r.labelClipped, `label ${r.labelWidth.toFixed(2)}px of ${r.labelScrollWidth}px`).toBe(false); - expect(r.overflowX).toBe(0); - expect(within(r.chips!, r.row), 'chips leave the row').toBe(true); + test('320px: 「全部客户」 is whole; a wider name gives way with an ellipsis, and the pills stay on screen', async ({ page }) => { + const short = await measure(page, fixture('全部客户'), 320); + expect(short.labelClipped).toBe(false); + expect(short.rowScrolls).toBe(false); + const wide = await measure(page, fixture('All Customers In The Northwest Sales Region Pipeline'), 320); + expect(wide.labelClipped, 'a name wider than the room is truncated').toBe(true); + expect(wide.overflowX).toBe(0); + expect(wide.rowScrolls, 'the name, not the row, gives way').toBe(false); + for (const pill of wide.pills) expect(within(pill, wide.row), 'a pill leaves the row').toBe(true); }); - test('375px with a name longer than the row: it keeps most of the row and ends in an ellipsis', async ({ page }) => { - const r = await measure(page, fixture('All Customers In The Northwest Sales Region Pipeline'), 375); - expect(r.labelClipped, 'a name wider than the row is truncated').toBe(true); - expect(r.labelWidth, `label ${r.labelWidth.toFixed(2)}px in a ${r.row.width}px row`).toBeGreaterThan(r.row.width * 0.6); - expect(r.overflowX).toBe(0); - }); - - // CONTROL: from `sm` up the phone additions are inert, so the row lays out - // exactly as it does without them, on one line. - test('1280px: the row is one line and identical with or without the phone classes', async ({ page }) => { - const withPhone = await measure(page, fixture('全部客户', { chips: 2 }), 1280); - const without = await measure(page, fixture('全部客户', { chips: 2, phone: false }), 1280); - expect(withPhone).toEqual(without); - expect(withPhone.labelClipped).toBe(false); - for (const [name, b] of [['queue', withPhone.queue], ['cluster', withPhone.cluster]] as const) { - expect(b.top < withPhone.leading.bottom && b.bottom > withPhone.leading.top, `${name} is on the name's line`).toBe(true); - } + // CONTROL: from `sm` up the phone search pill is not drawn (`sm:hidden`); + // the row itself is the phone's only (the list draws it below `sm` alone). + test('640px: the search pill is not drawn', async ({ page }) => { + const r = await measure(page, fixture('全部客户'), 640); + expect(r.pills[2].width).toBe(0); }); }); diff --git a/ui/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index efdec501f46..221161117d6 100644 --- a/ui/packages/app-shell/src/layout/AppHeader.tsx +++ b/ui/packages/app-shell/src/layout/AppHeader.tsx @@ -72,6 +72,7 @@ import { } from 'lucide-react'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; import { isPhoneTabRoute } from './PhoneAppNavBar.js'; +import { PhonePageBarEnd, PhonePageBarTitle, useHasPhonePageBar } from './PhonePageBar.js'; import { useState, useEffect, useLayoutEffect, useCallback, useRef, type RefObject } from 'react'; import { useOffline } from '@object-ui/react'; @@ -463,6 +464,11 @@ export function AppHeader({ // leftmost control is 「‹」 back to the app's home. const phone = usePhoneViewport(); const phoneTab = isApp && phone && isPhoneTabRoute(location.pathname); + // objectstack#35883 — a page with its own phone top row (the object list: + // its icon and name, then its 「⋮ More」) takes the bar's middle and right: + // no app pill, search, bell, assistant or avatar there. + const hasPhonePageBar = useHasPhonePageBar(); + const phonePageBar = isApp && phone && !phoneTab && hasPhonePageBar; const phoneAppHome = `/apps/${params.appName ?? activeAppName ?? ''}`; const { isOnline } = useOffline(); // Idempotent, direct open of the ⌘K command palette (ADR-0054 C1). Replaces a @@ -1008,7 +1014,8 @@ export function AppHeader({ )} - {isApp && ( + {phonePageBar && } + {isApp && !phonePageBar && ( <> {/* App pill — the app's glyph and name, and its switcher, after the product mark's `/` rule. At every width: below `sm` it is @@ -1104,7 +1111,8 @@ export function AppHeader({ {/* Group 1: Search */} {/* Only where a palette is mounted (objectui#11912) — see `hasCommandPalette`. */} - {hasCommandPalette && !phoneTab && ( + {phonePageBar && } + {hasCommandPalette && !phoneTab && !phonePageBar && (
+
{/* Edit app — the app → builder reverse bridge (ADR-0080), at the left edge of this utility cluster (objectui#12201 item 6). Admins jump from the running app to its owning package's design @@ -1286,7 +1294,7 @@ export function AppHeader({
{/* Group 3: Account (theme + lang moved into avatar dropdown) */} -
{/* User Profile + Organization switcher */} +
{/* User Profile + Organization switcher */}
+ ); +} + +const fab = () => document.querySelector('[data-testid="mobile-fab-create"]'); + +beforeEach(() => { + principal = {}; + phoneViewport = false; +}); + +afterEach(() => cleanup()); + +describe('the phone 「+」 while cards are selected (objectstack#35883)', () => { + it('is drawn, is not drawn while a selection is open, and is drawn again after it ends', async () => { + await renderList(objectsWith(undefined)); + expect(fab(), 'CONTROL: drawn with no selection').toBeTruthy(); + + fireEvent.click(screen.getByTestId('toggle-selecting')); + expect(fab(), 'not drawn while selecting').toBeNull(); + + fireEvent.click(screen.getByTestId('toggle-selecting')); + expect(fab(), 'back once the selection ends').toBeTruthy(); + }); +}); + +describe('the phone 「⋮ More」 → 「Select」 (objectstack#35883)', () => { + const openMore = async () => { + const trigger = (await screen.findByTestId('phone-page-bar-end')).querySelector('button'); + expect(trigger, 'the ⋮ More trigger').toBeTruthy(); + fireEvent.keyDown(trigger!, { key: 'Enter' }); + await screen.findByRole('menu'); + }; + const selectItem = () => document.querySelector('[data-testid="object-view-select"]'); + + it('is not offered while the list says no selection would open', async () => { + phoneViewport = true; + await renderList(objectsWith(undefined)); + await openMore(); + expect(selectItem(), 'no 「Select」 on a list that would not open one').toBeNull(); + }); + + it('is offered once the list says a selection would open', async () => { + phoneViewport = true; + await renderList(objectsWith(undefined)); + fireEvent.click(screen.getByTestId('toggle-selectable')); + await openMore(); + expect(selectItem(), 'CONTROL: 「Select」 on a list that would open one').toBeTruthy(); + }); +}); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 9f809b4453c..75c59569f78 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -23,7 +23,10 @@ import { ObjectView as PluginObjectView, ManageViewsDialog } from '@object-ui/pl // Plugin registration is handled by the host app (e.g. apps/console/src/main.tsx // uses ComponentRegistry.registerLazy so heavy plugins stay code-split). // Do NOT add eager `import '@object-ui/plugin-*'` side-effect imports here. -import { Plus } from 'lucide-react'; +import { CheckSquare, Plus } from 'lucide-react'; +import { DropdownMenuItem, ObjectIconTile } from '@object-ui/components'; +import { requestListSelection, useListPageSelectable, useListPageSelecting } from '@object-ui/plugin-grid'; +import { usePublishPhonePageBar } from '../layout/PhonePageBar.js'; import { useObjectListFavorite } from '../layout/SidebarItemMenu.js'; import { useMetaItemRefusal } from '../hooks/useMetaItemRefusal.js'; import { useTenancyPosture } from '../hooks/useTenancyPosture.js'; @@ -91,6 +94,7 @@ import { OBJECT_VIEW_PAGE_COLUMN_ATTR, ObjectViewBarObjectName, ObjectViewBarTrailing, + ObjectViewMoreMenu, ObjectViewPageHeader, type ObjectViewPageBarProps, } from './objectViewPageHeader.js'; @@ -1194,7 +1198,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // 「Object / View ▾」: the page draws no page bar of its own above the // list. The 「Personalized · Reset」 marker ends the condition row. phoneTitle: titleSwitcher ? ( - + {titleSwitcher} @@ -1321,6 +1325,39 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co }; pageBarPropsRef.current = pageBarProps; + // objectstack#35883 — on a phone the page's top row is its own: 「‹」 (the + // app bar's), the object's icon and name, then ⋮ More with 「Select」 first. + // The app bar draws it in place of its pill, search, bell and avatar. + const [pageColumnEl, setPageColumnEl] = useState(null); + const listSelecting = useListPageSelecting(pageColumnEl); + // 「Select」 is offered only where the list would open a selection: cards + // whose rows take more than one tick (not a kanban, a calendar, or a list + // with no or single selection). + const listSelectable = useListPageSelectable(pageColumnEl); + const phoneDescription = objectDef.description ? objectDesc(objectDef) : undefined; + usePublishPhonePageBar(phone ? { + // The object's colour tile, as the desktop page bar draws it (objectstack#35985). + icon: , + title: listTitleOf(objectDef), + end: ( + requestListSelection(pageColumnEl)} data-testid="object-view-select"> + + {t('console.objectView.select', { defaultValue: 'Select' })} + + ) : undefined} + t={t} + /> + ), + } : null); + // The list itself: one element whether or not a record is open // (objectstack#27545), so a `?recordId=` change — a row click, a step — // hands React the same element and re-renders none of the list. Memoised @@ -1356,7 +1393,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // over (objectstack#27545); it keeps its full width (objectstack#28915). const pageColumn = ( -
+
{/* 1. Header with breadcrumb + description. The managed-by badge sits inline with the title so the lifecycle bucket (system / config / append-only / @@ -1406,7 +1443,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co objectui#13134 — the list it floats over leaves room at its end while it is drawn (`listFabClearance`), and only then: the same `showCreate` decides both. */} - {showCreate && ( + {/* objectstack#35883 — not while cards are being selected. */} + {showCreate && !listSelecting && ( + {leading} + {leading && rest && } {description && ( <> - )} - - ); } diff --git a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx index 8f228130770..c7d6d9e6353 100644 --- a/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx +++ b/ui/packages/app-shell/src/views/objectViewSwitcherMenu.tsx @@ -62,6 +62,14 @@ export interface ObjectViewSwitcherMenuProps { create?: SwitcherCreateOptions; /** 「Add view」 for a host with no card to offer: the dropdown closes and this runs (the Create View dialog). */ onAddView?: () => void; + /** + * objectstack#35884 — the phone's view panel: the views take the sheet's + * height, the search box comes last and does not take focus (no keyboard + * rises over the views), and `footerEnd` follows 「Add view」. + */ + phone?: boolean; + /** A last footer row (the phone's 「View settings」, objectstack#35883). */ + footerEnd?: ReactNode; t: TFn; } @@ -83,7 +91,7 @@ function GroupLabel({ children, icon }: { children: ReactNode; icon?: ReactNode ); } -const FOOTER_ITEM = 'flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-[13px] hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring max-sm:min-h-11'; +export const FOOTER_ITEM = 'flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-[13px] hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring max-sm:min-h-11'; export function ObjectViewSwitcherMenu({ views, @@ -100,6 +108,8 @@ export function ObjectViewSwitcherMenu({ onDeletePersonalView, create, onAddView, + phone = false, + footerEnd, t, }: ObjectViewSwitcherMenuProps) { const [mode, setMode] = useState<'list' | 'create'>('list'); @@ -241,20 +251,24 @@ export function ObjectViewSwitcherMenu({ ); }; + const searchBox = ( +
+ setQuery(e.target.value)} + placeholder={t('view.searchViews', { defaultValue: 'Search views' })} + aria-label={t('view.searchViews', { defaultValue: 'Search views' })} + data-testid="list-view-switcher-search" + className="h-8 text-[13px] max-sm:h-11" + /> +
+ ); + return (
-
- setQuery(e.target.value)} - placeholder={t('view.searchViews', { defaultValue: 'Search views' })} - aria-label={t('view.searchViews', { defaultValue: 'Search views' })} - data-testid="list-view-switcher-search" - className="h-8 text-[13px] max-sm:h-11" - /> -
-
+ {!phone && searchBox} +
{needle ? ( matches.length > 0 ? matches.map((v) => row(v, 'match')) @@ -294,7 +308,7 @@ export function ObjectViewSwitcherMenu({ )}
- {(create || onAddView || onManageViews) && ( + {(create || onAddView || onManageViews || footerEnd) && (
{(create || onAddView) && (
)} + {phone && searchBox}
); } diff --git a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx index 45cda91ba8e..3f53d1935d5 100644 --- a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx +++ b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx @@ -35,13 +35,14 @@ * a view dropdown of its own. */ -import { createContext, createElement, useContext, useMemo, useState, type ComponentType, type Dispatch, type SetStateAction } from 'react'; +import { createContext, createElement, useContext, useMemo, useState, type ComponentType, type Dispatch, type ReactNode, type SetStateAction } from 'react'; import { cn, Popover, PopoverContent, PopoverTrigger } from '@object-ui/components'; import type { ViewTabItem } from '@object-ui/plugin-view'; import { resolveViewId } from '@object-ui/core'; import { useDisplayLocale, pickLocalized } from '@object-ui/i18n'; import type { useObjectLabel, useObjectTranslation } from '@object-ui/i18n'; -import { ChevronDown } from 'lucide-react'; +import { ChevronDown, Settings2 } from 'lucide-react'; +import { PhonePanelSheet, useListPhonePanels, PHONE_CHIP } from '@object-ui/plugin-list'; import { viewRowId } from '../utils/viewIdentity.js'; import { useRecentItems } from '../hooks/useRecentItems.js'; import { usePackagesRefusingSaves } from '../hooks/useStudioDesignGate.js'; @@ -53,7 +54,7 @@ import { VIEW_TYPE_ICONS } from './objectViewHelpers.js'; import { viewTabLabel } from './viewTabLabel.js'; import type { buildViewTabs } from './objectViewTabs.js'; import type { ConsoleObjectViewProps } from './ObjectView.js'; -import { ObjectViewSwitcherMenu, type SwitcherCreateOptions } from './objectViewSwitcherMenu.js'; +import { FOOTER_ITEM, ObjectViewSwitcherMenu, type SwitcherCreateOptions } from './objectViewSwitcherMenu.js'; import { useCreateViewInPlace } from './objectViewViewCrud.js'; type TFn = ReturnType['t']; @@ -154,6 +155,79 @@ export function ObjectViewTitleSwitcher({ if (viewId !== activeViewId) onViewChange(viewId); }; + const menu = (phone: boolean, footerEnd?: ReactNode) => ( + setOpen(false)} + pinnedViewId={pinnedViewId} + onPinnedViewChange={onPinnedViewChange} + recentViewIds={recentViewIds} + favorites={favorites} + viewTypeIcons={viewTypeIcons} + onManageViews={onManageViews} + onRenamePersonalView={onRenamePersonalView} + onDeletePersonalView={onDeletePersonalView} + create={create} + onAddView={onAddView} + phone={phone} + footerEnd={footerEnd} + t={t} + /> + ); + + // objectstack#35883 / #35884 — in the list's phone toolbar the switcher is + // its first pill (the view's name, its count, the caret) and opens the + // same menu in the list's bottom sheet; a view chosen there opens at once + // and the sheet closes, so it has no 「✓」. 视图设置 is its last row. + const phonePanels = useListPhonePanels(); + if (phonePanels) { + const openSettings = phonePanels.openViewSettings; + return ( + <> + + + {menu(true, openSettings ? ( + + ) : undefined)} + + + ); + } + return ( @@ -196,23 +270,7 @@ export function ObjectViewTitleSwitcher({ data-testid="list-view-switcher-menu" aria-label={t('view.switcher.label', { defaultValue: 'Views' })} > - setOpen(false)} - pinnedViewId={pinnedViewId} - onPinnedViewChange={onPinnedViewChange} - recentViewIds={recentViewIds} - favorites={favorites} - viewTypeIcons={viewTypeIcons} - onManageViews={onManageViews} - onRenamePersonalView={onRenamePersonalView} - onDeletePersonalView={onDeletePersonalView} - create={create} - onAddView={onAddView} - t={t} - /> + {menu(false)} diff --git a/ui/packages/components/src/__tests__/clickableNonControlCensus-13461.test.ts b/ui/packages/components/src/__tests__/clickableNonControlCensus-13461.test.ts index e756c43f15f..dab8b22a978 100644 --- a/ui/packages/components/src/__tests__/clickableNonControlCensus-13461.test.ts +++ b/ui/packages/components/src/__tests__/clickableNonControlCensus-13461.test.ts @@ -271,8 +271,6 @@ const BACKLOG: Array<[file: string, key: string]> = [ ['packages/plugin-gantt/src/GanttView.tsx', 'div · setSelectedTaskId'], ['packages/plugin-gantt/src/GanttView.tsx', 'div · setSelectedTaskId'], ['packages/plugin-gantt/src/GanttView.tsx', 'div · setSelectedTaskId'], - // The mobile card list. - ['packages/plugin-grid/src/ObjectGrid.tsx', 'div · handleClick'], ['packages/plugin-grid/src/VirtualGrid.tsx', 'div · getSelection,trim,toString,intersectsNode,getRangeAt,onRowClick'], ['packages/plugin-view/src/ManageViewsDialog.tsx', 'div · onRowClick'], ]; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 56b6567f5cb..3ca9b8ea9a2 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3013,6 +3013,7 @@ const ar = { endDateField: "حقل تاريخ الانتهاء", import: "استيراد", importTitle: "استيراد من CSV", + select: 'تحديد', importedToast: "تم استيراد {{count}} صف(صفوف).", importedToast_zero: "تم استيراد {{count}} صف.", importedToast_one: "تم استيراد {{count}} صف.", @@ -5606,6 +5607,32 @@ const ar = { }, }, listConditions: { + phone: { + toolbar: 'أدوات القائمة', + sortCount: 'الفرز، {{count}} مستوى', + sortCount_zero: 'الفرز، {{count}} مستوى', + sortCount_one: 'الفرز، {{count}} مستوى', + sortCount_two: 'الفرز، {{count}} مستويان', + sortCount_few: 'الفرز، {{count}} مستويات', + sortCount_many: 'الفرز، {{count}} مستوى', + sortCount_other: 'الفرز، {{count}} مستوى', + filterCount: 'التصفية، {{count}} قيد الاستخدام', + filterCount_zero: 'التصفية، {{count}} قيد الاستخدام', + filterCount_one: 'التصفية، {{count}} قيد الاستخدام', + filterCount_two: 'التصفية، {{count}} قيد الاستخدام', + filterCount_few: 'التصفية، {{count}} قيد الاستخدام', + filterCount_many: 'التصفية، {{count}} قيد الاستخدام', + filterCount_other: 'التصفية، {{count}} قيد الاستخدام', + back: 'رجوع', + discard: 'تجاهل التغييرات', + close: 'إغلاق', + apply: 'تطبيق', + advancedNotice: 'يستخدم هذا العرض عامل تصفية متقدمًا. غيّره من جهاز كمبيوتر.', + filterEmpty: 'لا توجد عوامل تصفية بعد. أضف واحدًا لعرض السجلات المطابقة فقط.', + itemOptions: 'خيارات {{label}}', + edit: 'تعديل', + remove: 'إزالة', + }, fieldList: { search: 'البحث في الحقول', shown: 'في طريقة العرض هذه', @@ -5688,6 +5715,8 @@ const ar = { addSort: "إضافة ترتيب", removeSort: "إزالة الترتيب", reorder: 'اسحب لإعادة الترتيب', + levelOptions: 'خيارات {{label}}', + changeField: 'تغيير الحقل', }, collaboration: { // objectui#11445 — `commentCount` and `reactionCount` below are count diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index c347cc22840..1706c1361e5 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2722,6 +2722,7 @@ const de = { endDateField: "Enddatumsfeld", import: "Importieren", importTitle: "Aus CSV importieren", + select: 'Auswählen', importedToast: "{{count}} Zeile(n) importiert.", importedToast_one: "{{count}} Zeile importiert.", importedToast_other: "{{count}} Zeilen importiert.", @@ -5008,6 +5009,24 @@ const de = { }, }, listConditions: { + phone: { + toolbar: 'Listenwerkzeuge', + sortCount: 'Sortierung, {{count}} Ebenen', + sortCount_one: 'Sortierung, {{count}} Ebene', + sortCount_other: 'Sortierung, {{count}} Ebenen', + filterCount: 'Filter, {{count}} aktiv', + filterCount_one: 'Filter, {{count}} aktiv', + filterCount_other: 'Filter, {{count}} aktiv', + back: 'Zurück', + discard: 'Änderungen verwerfen', + close: 'Schließen', + apply: 'Anwenden', + advancedNotice: 'Diese Ansicht verwendet einen erweiterten Filter. Ändern Sie ihn am Computer.', + filterEmpty: 'Noch kein Filter. Fügen Sie einen hinzu, um nur passende Datensätze zu zeigen.', + itemOptions: 'Optionen für {{label}}', + edit: 'Bearbeiten', + remove: 'Entfernen', + }, fieldList: { search: 'Felder suchen', shown: 'In dieser Ansicht', @@ -5090,6 +5109,8 @@ const de = { addSort: "Sortierung hinzufügen", removeSort: "Sortierung entfernen", reorder: 'Zum Neuordnen ziehen', + levelOptions: 'Optionen für {{label}}', + changeField: 'Feld ändern', }, collaboration: { commentCount: "{{count}} Kommentare", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 20e3f55ac33..d01aff226c2 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3293,6 +3293,7 @@ const en = { new: 'New', import: 'Import', importTitle: 'Import from CSV', + select: 'Select', importedToast: 'Imported {{count}} row(s).', importedToast_one: 'Imported {{count}} row.', importedToast_other: 'Imported {{count}} rows.', @@ -5768,6 +5769,24 @@ const en = { }, }, listConditions: { + phone: { + toolbar: 'List tools', + sortCount: 'Sort, {{count}} levels', + sortCount_one: 'Sort, {{count}} level', + sortCount_other: 'Sort, {{count}} levels', + filterCount: 'Filter, {{count}} in use', + filterCount_one: 'Filter, {{count}} in use', + filterCount_other: 'Filter, {{count}} in use', + back: 'Back', + discard: 'Discard changes', + close: 'Close', + apply: 'Apply', + advancedNotice: 'This view uses an advanced filter. Change it on a computer.', + filterEmpty: 'No filter yet. Add one to show only the records that match.', + itemOptions: 'Options for {{label}}', + edit: 'Edit', + remove: 'Remove', + }, fieldList: { search: 'Search fields', shown: 'In this view', @@ -5850,6 +5869,8 @@ const en = { addSort: 'Add sort', removeSort: 'Remove sort', reorder: 'Drag to reorder', + levelOptions: 'Options for {{label}}', + changeField: 'Change field', }, // `@object-ui/collaboration` — the comment thread's copy (objectstack#5506, // objectui#3424). The package used to carry every one of these as an English diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 5a9c2d0003c..0194db912c4 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2796,6 +2796,7 @@ const es = { endDateField: "Campo de fecha de fin", import: "Importar", importTitle: "Importar desde CSV", + select: 'Seleccionar', importedToast: "{{count}} fila(s) importada(s).", importedToast_one: "{{count}} fila importada.", importedToast_many: "{{count}} de filas importadas.", @@ -5158,6 +5159,26 @@ const es = { }, }, listConditions: { + phone: { + toolbar: 'Herramientas de la lista', + sortCount: 'Orden, {{count}} niveles', + sortCount_one: 'Orden, {{count}} nivel', + sortCount_many: 'Orden, {{count}} niveles', + sortCount_other: 'Orden, {{count}} niveles', + filterCount: 'Filtro, {{count}} activos', + filterCount_one: 'Filtro, {{count}} activo', + filterCount_many: 'Filtro, {{count}} activos', + filterCount_other: 'Filtro, {{count}} activos', + back: 'Atrás', + discard: 'Descartar cambios', + close: 'Cerrar', + apply: 'Aplicar', + advancedNotice: 'Esta vista usa un filtro avanzado. Cámbialo en un ordenador.', + filterEmpty: 'Aún no hay filtros. Añade uno para mostrar solo los registros que coinciden.', + itemOptions: 'Opciones de {{label}}', + edit: 'Editar', + remove: 'Quitar', + }, fieldList: { search: 'Buscar campos', shown: 'En esta vista', @@ -5240,6 +5261,8 @@ const es = { addSort: "Agregar orden", removeSort: "Quitar orden", reorder: 'Arrastra para reordenar', + levelOptions: 'Opciones de {{label}}', + changeField: 'Cambiar campo', }, collaboration: { commentCount: "{{count}} comentarios", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index efaebb7ac85..f995f4c4090 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2792,6 +2792,7 @@ const fr = { endDateField: "Champ de date de fin", import: "Importer", importTitle: "Importer depuis CSV", + select: 'Sélectionner', importedToast: "{{count}} ligne(s) importée(s).", importedToast_one: "{{count}} ligne importée.", importedToast_many: "{{count}} de lignes importées.", @@ -5154,6 +5155,26 @@ const fr = { }, }, listConditions: { + phone: { + toolbar: 'Outils de la liste', + sortCount: 'Tri, {{count}} niveaux', + sortCount_one: 'Tri, {{count}} niveau', + sortCount_many: 'Tri, {{count}} niveaux', + sortCount_other: 'Tri, {{count}} niveaux', + filterCount: 'Filtre, {{count}} actifs', + filterCount_one: 'Filtre, {{count}} actif', + filterCount_many: 'Filtre, {{count}} actifs', + filterCount_other: 'Filtre, {{count}} actifs', + back: 'Retour', + discard: 'Annuler les modifications', + close: 'Fermer', + apply: 'Appliquer', + advancedNotice: 'Cette vue utilise un filtre avancé. Modifiez-le sur un ordinateur.', + filterEmpty: 'Aucun filtre pour l’instant. Ajoutez-en un pour n’afficher que les enregistrements correspondants.', + itemOptions: 'Options pour {{label}}', + edit: 'Modifier', + remove: 'Supprimer', + }, fieldList: { search: 'Rechercher des champs', shown: 'Dans cette vue', @@ -5236,6 +5257,8 @@ const fr = { addSort: "Ajouter un tri", removeSort: "Supprimer le tri", reorder: 'Faire glisser pour réorganiser', + levelOptions: 'Options pour {{label}}', + changeField: 'Changer de champ', }, collaboration: { commentCount: "{{count}} commentaires", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 38dcdc76b67..7171667d36b 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2724,6 +2724,7 @@ const ja = { endDateField: "終了日フィールド", import: "インポート", importTitle: "CSVからインポート", + select: '選択', importedToast: "{{count}} 行をインポートしました。", importedToast_one: "{{count}} 行をインポートしました。", importedToast_other: "{{count}} 行をインポートしました。", @@ -5010,6 +5011,24 @@ const ja = { }, }, listConditions: { + phone: { + toolbar: 'リストツール', + sortCount: '並べ替え({{count}} 段階)', + sortCount_one: '並べ替え({{count}} 段階)', + sortCount_other: '並べ替え({{count}} 段階)', + filterCount: '絞り込み({{count}} 件)', + filterCount_one: '絞り込み({{count}} 件)', + filterCount_other: '絞り込み({{count}} 件)', + back: '戻る', + discard: '変更を破棄', + close: '閉じる', + apply: '適用', + advancedNotice: 'このビューは高度な絞り込みを使っています。パソコンで変更してください。', + filterEmpty: 'まだ絞り込みはありません。追加すると条件に合うレコードだけを表示します。', + itemOptions: '{{label}} のオプション', + edit: '編集', + remove: '削除', + }, fieldList: { search: 'フィールドを検索', shown: 'ビューに表示', @@ -5092,6 +5111,8 @@ const ja = { addSort: "並べ替えを追加", removeSort: "並べ替えを削除", reorder: 'ドラッグして並べ替え', + levelOptions: '{{label}} のオプション', + changeField: 'フィールドを変更', }, collaboration: { commentCount: "コメント {{count}} 件", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index b0102e0d9fd..8de437747cf 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2722,6 +2722,7 @@ const ko = { endDateField: "종료 날짜 필드", import: "가져오기", importTitle: "CSV에서 가져오기", + select: '선택', importedToast: "{{count}}개 행 가져옴.", importedToast_one: "{{count}}개 행 가져옴.", importedToast_other: "{{count}}개 행 가져옴.", @@ -5007,6 +5008,24 @@ const ko = { }, }, listConditions: { + phone: { + toolbar: '목록 도구', + sortCount: '정렬, {{count}}단계', + sortCount_one: '정렬, {{count}}단계', + sortCount_other: '정렬, {{count}}단계', + filterCount: '필터, {{count}}개', + filterCount_one: '필터, {{count}}개', + filterCount_other: '필터, {{count}}개', + back: '뒤로', + discard: '변경 취소', + close: '닫기', + apply: '적용', + advancedNotice: '이 보기는 고급 필터를 사용합니다. 컴퓨터에서 변경하세요.', + filterEmpty: '아직 필터가 없습니다. 추가하면 조건에 맞는 레코드만 표시됩니다.', + itemOptions: '{{label}} 옵션', + edit: '수정', + remove: '삭제', + }, fieldList: { search: '필드 검색', shown: '이 보기에 표시', @@ -5089,6 +5108,8 @@ const ko = { addSort: "정렬 추가", removeSort: "정렬 삭제", reorder: '드래그하여 순서 변경', + levelOptions: '{{label}} 옵션', + changeField: '필드 변경', }, collaboration: { commentCount: "댓글 {{count}}개", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 652138d24cf..17fb8e5b7e9 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2791,6 +2791,7 @@ const pt = { endDateField: "Campo de data de término", import: "Importar", importTitle: "Importar do CSV", + select: 'Selecionar', importedToast: "{{count}} linha(s) importada(s).", importedToast_one: "{{count}} linha importada.", importedToast_many: "{{count}} de linhas importadas.", @@ -5153,6 +5154,26 @@ const pt = { }, }, listConditions: { + phone: { + toolbar: 'Ferramentas da lista', + sortCount: 'Ordenação, {{count}} níveis', + sortCount_one: 'Ordenação, {{count}} nível', + sortCount_many: 'Ordenação, {{count}} níveis', + sortCount_other: 'Ordenação, {{count}} níveis', + filterCount: 'Filtro, {{count}} ativos', + filterCount_one: 'Filtro, {{count}} ativo', + filterCount_many: 'Filtro, {{count}} ativos', + filterCount_other: 'Filtro, {{count}} ativos', + back: 'Voltar', + discard: 'Descartar alterações', + close: 'Fechar', + apply: 'Aplicar', + advancedNotice: 'Esta visualização usa um filtro avançado. Altere-o em um computador.', + filterEmpty: 'Nenhum filtro ainda. Adicione um para mostrar só os registros que correspondem.', + itemOptions: 'Opções de {{label}}', + edit: 'Editar', + remove: 'Remover', + }, fieldList: { search: 'Pesquisar campos', shown: 'Nesta visualização', @@ -5235,6 +5256,8 @@ const pt = { addSort: "Adicionar ordenação", removeSort: "Remover ordenação", reorder: 'Arraste para reordenar', + levelOptions: 'Opções de {{label}}', + changeField: 'Alterar campo', }, collaboration: { commentCount: "{{count}} comentários", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 39a945a76a0..667057c9850 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2875,6 +2875,7 @@ const ru = { endDateField: "Поле даты окончания", import: "Импорт", importTitle: "Импорт из CSV", + select: 'Выбрать', importedToast: "{{count}} строк импортировано.", importedToast_one: "Импортирована {{count}} строка.", importedToast_few: "Импортировано {{count}} строки.", @@ -5317,6 +5318,28 @@ const ru = { }, }, listConditions: { + phone: { + toolbar: 'Инструменты списка', + sortCount: 'Сортировка, уровней: {{count}}', + sortCount_one: 'Сортировка, уровней: {{count}}', + sortCount_few: 'Сортировка, уровней: {{count}}', + sortCount_many: 'Сортировка, уровней: {{count}}', + sortCount_other: 'Сортировка, уровней: {{count}}', + filterCount: 'Фильтр, активно: {{count}}', + filterCount_one: 'Фильтр, активно: {{count}}', + filterCount_few: 'Фильтр, активно: {{count}}', + filterCount_many: 'Фильтр, активно: {{count}}', + filterCount_other: 'Фильтр, активно: {{count}}', + back: 'Назад', + discard: 'Отменить изменения', + close: 'Закрыть', + apply: 'Применить', + advancedNotice: 'В этом представлении используется расширенный фильтр. Измените его на компьютере.', + filterEmpty: 'Фильтров пока нет. Добавьте фильтр, чтобы показать только подходящие записи.', + itemOptions: 'Параметры: {{label}}', + edit: 'Изменить', + remove: 'Удалить', + }, fieldList: { search: 'Поиск полей', shown: 'В этом представлении', @@ -5399,6 +5422,8 @@ const ru = { addSort: "Добавить сортировку", removeSort: "Удалить сортировку", reorder: 'Перетащите, чтобы изменить порядок', + levelOptions: 'Параметры: {{label}}', + changeField: 'Изменить поле', }, collaboration: { commentCount: "Комментариев: {{count}}", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index a35f4da21ce..b413fe7c8cb 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2789,6 +2789,7 @@ const zh = { new: '新建', import: '导入', importTitle: '从 CSV 文件导入', + select: '选择', importedToast: '成功导入 {{count}} 行。', importedToast_one: '成功导入 {{count}} 行。', importedToast_other: '成功导入 {{count}} 行。', @@ -5067,6 +5068,24 @@ const zh = { }, }, listConditions: { + phone: { + toolbar: '列表工具', + sortCount: '排序,{{count}} 级', + sortCount_one: '排序,{{count}} 级', + sortCount_other: '排序,{{count}} 级', + filterCount: '筛选,{{count}} 个', + filterCount_one: '筛选,{{count}} 个', + filterCount_other: '筛选,{{count}} 个', + back: '返回', + discard: '放弃改动', + close: '关闭', + apply: '应用', + advancedNotice: '这个视图用了高级筛选,请在电脑上修改。', + filterEmpty: '还没有筛选。添加一个,只显示符合条件的记录。', + itemOptions: '{{label}} 的选项', + edit: '修改', + remove: '删除', + }, fieldList: { search: '搜索字段', shown: '视图中显示', @@ -5149,6 +5168,8 @@ const zh = { addSort: '添加排序', removeSort: '删除排序', reorder: '拖动以调整先后', + levelOptions: '{{label}} 的选项', + changeField: '改字段', }, collaboration: { commentCount: '{{count}} 条评论', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index b2cb363edd2..254b4e5bd02 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2789,6 +2789,7 @@ const zhHant = { new: '新建', import: '匯入', importTitle: '從 CSV 檔案匯入', + select: '選擇', importedToast: '成功匯入 {{count}} 行。', importedToast_one: '成功匯入 {{count}} 行。', importedToast_other: '成功匯入 {{count}} 行。', @@ -5067,6 +5068,24 @@ const zhHant = { }, }, listConditions: { + phone: { + toolbar: '列表工具', + sortCount: '排序,{{count}} 級', + sortCount_one: '排序,{{count}} 級', + sortCount_other: '排序,{{count}} 級', + filterCount: '篩選,{{count}} 個', + filterCount_one: '篩選,{{count}} 個', + filterCount_other: '篩選,{{count}} 個', + back: '返回', + discard: '放棄改動', + close: '關閉', + apply: '應用', + advancedNotice: '這個檢視用了高階篩選,請在電腦上修改。', + filterEmpty: '還沒有篩選。新增一個,只顯示符合條件的記錄。', + itemOptions: '{{label}} 的選項', + edit: '修改', + remove: '刪除', + }, fieldList: { search: '搜尋欄位', shown: '檢視中顯示', @@ -5149,6 +5168,8 @@ const zhHant = { addSort: '新增排序', removeSort: '刪除排序', reorder: '拖動以調整先後', + levelOptions: '{{label}} 的選項', + changeField: '改欄位', }, collaboration: { commentCount: '{{count}} 條評論', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 660a7f57543..92d2eef13ca 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -81,7 +81,7 @@ import { useDetailTranslation, type ConcurrentUpdateConflict, } from '@object-ui/plugin-detail'; -import { ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, Download, Rows2, Rows3, Rows4, AlignJustify, Loader2 } from 'lucide-react'; +import { ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, Download, Rows2, Rows3, Rows4, AlignJustify, Loader2, Check } from 'lucide-react'; import { useRowColor } from './useRowColor'; import { GroupRow } from './GroupRow'; import { resolveRowCrudAffordances, resolveRowRecordCrudAffordance } from './rowCrudAffordances'; @@ -126,7 +126,7 @@ import { resolveObjectGridPersistedColumns } from './objectGridPersistedColumns' import { resolveObjectGridActionsColumn } from './objectGridActionsColumn'; import { useInlineRowActionFold } from './objectGridInlineActionFold'; import { BULK_SELECT_ALL_MATCHING_CAP } from './bulkSelectAllMatchingCap'; -import { useIsListPageGrid } from './listPageScope'; +import { useIsListPageGrid, useListSelectionRequest, usePublishListSelectable, usePublishListSelecting } from './listPageScope'; import { useInfiniteRowLoad } from './objectGridInfiniteLoad'; export type { RetiredListColumnKey, ObjectGridColumnHolds, ObjectGridColumnDraft, ObjectGridColumn } from './objectGridColumns'; export type { ObjectGridColumnState, ObjectGridFooterSummary, ObjectGridExternalPaginationProps, ObjectGridRowGroup } from './objectGridProps'; @@ -925,6 +925,10 @@ export const ObjectGrid: React.FC = ({ const [exportError, setExportError] = useState(null); const [rowHeightMode, setRowHeightMode] = useState(resolveRowHeightMode(schema.rowHeight)); const [selectedRows, setSelectedRows] = useState([]); + // objectstack#35883 — a phone's cards select by a long press (or the page's + // 「⋮ More」 → 「Select」): while this is on, a tap on a card adds or removes + // it instead of opening the record, and each card shows a tick. + const [cardSelecting, setCardSelecting] = useState(false); const [selectAllMatching, setSelectAllMatching] = useState(false); // Bumped to tell the underlying table to drop its internal checkbox selection. // The table owns that state, so clearing our `selectedRows` alone would leave @@ -1696,6 +1700,29 @@ export const ObjectGrid: React.FC = ({ return () => { updateActionContext({ selectionAvailable: undefined }); }; }, [rowsSelectable, updateActionContext]); + // objectstack#35883 — the page's 「Select」 (`requestListSelection`) opens a + // card selection with nothing ticked yet. Only a request made after this + // grid mounted counts. + // The page draws 「Select」 only where it would open one: on cards whose rows + // take more than one tick. + const cardsSelectRequestable = useCardView && rowsSelectable && !singleSelection; + usePublishListSelectable(gridRoot, cardsSelectRequestable); + const selectionRequest = useListSelectionRequest(gridRoot); + const seenSelectionRequest = React.useRef(selectionRequest); + useEffect(() => { + if (selectionRequest === seenSelectionRequest.current) return; + seenSelectionRequest.current = selectionRequest; + if (cardsSelectRequestable) setCardSelecting(true); + }, [selectionRequest, cardsSelectRequestable]); + // A long press on a card: held 500 ms without moving starts the selection + // with that card ticked; the click that follows the press is swallowed. + const longPress = React.useRef<{ timer: ReturnType | null; x: number; y: number; fired: boolean }>({ + timer: null, x: 0, y: 0, fired: false, + }); + useEffect(() => () => { + if (longPress.current.timer) clearTimeout(longPress.current.timer); + }, []); + // --- Row color support --- const getRowClassName = useRowColor(schema.rowColor); @@ -1786,6 +1813,10 @@ export const ObjectGrid: React.FC = ({ onResidentSummaryRowChange?.(residentRowDrawn); }, [onResidentSummaryRowChange, residentRowDrawn]); + // objectstack#35883 — tell the page whether a selection is open (it hides + // its floating create button, which would sit on the selection bar). + usePublishListSelecting(gridRoot, selectedRows.length > 0 || cardSelecting); + // objectstack#35554 — a host that loads its rows window by window // (`onLoadMore`) is asked for the next window as the table's scroll box // nears its end, and the box's position is kept across a return to the list @@ -2423,6 +2454,26 @@ export const ObjectGrid: React.FC = ({ setSelectedRows([]); setSelectAllMatching(false); setSelectionResetKey(k => k + 1); + setCardSelecting(false); + }; + + // objectstack#35883 — the cards' selection. A row is the same row object + // the table selects, keyed by its id; the selection is the grid's one + // `selectedRows`, so the page bar's selection face and its actions read it + // as they read the table's. + const cardRowKey = (row: any) => row?.id ?? row?._id; + const toggleCardRow = (row: any) => { + const key = cardRowKey(row); + const held = selectedRows.some((r) => cardRowKey(r) === key); + const next = held ? selectedRows.filter((r) => cardRowKey(r) !== key) : [...selectedRows, row]; + setSelectedRows(next); + onRowSelect?.(next); + // Unticking the last card ends the selection. + if (next.length === 0) setCardSelecting(false); + }; + const startCardSelection = (row?: any) => { + setCardSelecting(true); + if (row && !selectedRows.some((r) => cardRowKey(r) === cardRowKey(row))) toggleCardRow(row); }; /** @@ -3343,7 +3394,9 @@ export const ObjectGrid: React.FC = ({ // On the list page, where rows draw no actions of their own (#35554), one // selected record offers that record's actions; elsewhere the row keeps its // own menu and the bar offers the bulk actions at any count. - const selecting = selectedRows.length > 0; + // objectstack#35883 — a card selection opened by 「Select」 shows the bar + // before its first card is ticked, so its 「×」 ends it. + const selecting = selectedRows.length > 0 || cardSelecting; const selectionBar = selecting ? ( = ({ totalMatching={canOfferSelectAllMatching ? resolvedTotalMatching : undefined} allMatchingSelected={selectAllMatching} onSelectAllMatching={canOfferSelectAllMatching ? () => setSelectAllMatching(true) : undefined} + open={cardSelecting} /> ) : null; // The room a face that is not the table keeps at its scroller's end while @@ -4062,7 +4116,18 @@ export const ObjectGrid: React.FC = ({ return col.cell ? col.cell(value, row) : String(coerceToSafeValue(value) ?? ''); }; + const selectedKeys = new Set(selectedRows.map(cardRowKey)); + const cardsSelectable = rowsSelectable && !singleSelection; + const cancelLongPress = () => { + const press = longPress.current; + if (press.timer) { + clearTimeout(press.timer); + press.timer = null; + } + }; + return (row: any, idx: number) => { + const cardSelected = cardSelecting && selectedKeys.has(cardRowKey(row)); const subtitle = subtitleColumns.filter( (col) => !isMaskedCardColumn(col.accessorKey) && !isEmptyCardValue(row[col.accessorKey]), ); @@ -4081,14 +4146,79 @@ export const ObjectGrid: React.FC = ({
navigation.handleClick(row)} + onPointerDown={(event) => { + const press = longPress.current; + // A fresh press never inherits the last one's flag: a long press + // the browser ended with no click (a finger that slid off, Android + // after its context menu) would otherwise swallow this tap. + press.fired = false; + if (!cardsSelectable || cardSelecting) return; + press.x = event.clientX; + press.y = event.clientY; + if (press.timer) clearTimeout(press.timer); + press.timer = setTimeout(() => { + press.timer = null; + press.fired = true; + startCardSelection(row); + }, 500); + }} + onPointerMove={(event) => { + const press = longPress.current; + if (press.timer && Math.hypot(event.clientX - press.x, event.clientY - press.y) > 10) { + clearTimeout(press.timer); + press.timer = null; + } + }} + onPointerUp={cancelLongPress} + onPointerCancel={cancelLongPress} + onPointerLeave={cancelLongPress} + // A phone's long press also asks for the browser's own menu. + onContextMenu={(event) => { + if (cardsSelectable) event.preventDefault(); + }} + onClick={() => { + if (longPress.current.fired) { + longPress.current.fired = false; + return; + } + if (cardSelecting) toggleCardRow(row); + else navigation.handleClick(row); + }} + onKeyDown={(event) => { + // Only the card's own key: a link or button inside keeps its own. + if (event.target !== event.currentTarget) return; + if (event.key !== 'Enter' && event.key !== ' ') return; + event.preventDefault(); + if (cardSelecting) toggleCardRow(row); + else navigation.handleClick(row); + }} > + {cardSelecting && ( + + )}
{titleKey !== undefined && (
@@ -4195,6 +4325,9 @@ export const ObjectGrid: React.FC = ({ return ( <>
{ + registerAllFields(); + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as unknown as Element['scrollIntoView']; + } +}); + +const ORIGINAL_INNER_WIDTH = window.innerWidth; + +afterEach(() => { + cleanup(); + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: ORIGINAL_INNER_WIDTH }); +}); + +const ROWS = [ + { id: 'a1', name: 'Acme' }, + { id: 'a2', name: 'Globex' }, +]; + +function renderCards(selection: unknown = { type: 'multiple' }) { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 390 }); + const onRowClick = vi.fn(); + const onRowSelect = vi.fn(); + const dataSource = { + find: vi.fn(async () => ({ data: ROWS, total: ROWS.length, hasMore: false, pageSize: 50 })), + getObjectSchema: async (name: string) => ({ + name, + nameField: 'name', + fields: { id: { type: 'text' }, name: { type: 'text', label: 'Name' } }, + }), + } as never; + render( + + +
+ +
+
+
, + ); + return { onRowClick, onRowSelect }; +} + +const cardOf = async (title: string) => { + await waitFor(() => expect(screen.getAllByTestId('grid-mobile-card').length).toBe(2)); + return screen.getAllByTestId('grid-mobile-card').find((c) => c.textContent?.includes(title))!; +}; + +const hold = (ms: number) => act(() => new Promise((resolve) => setTimeout(resolve, ms))); + +describe('card list selection on a phone (objectstack#35883)', () => { + it('a long press ticks the card and opens nothing; a tap then ticks another, unticking the last ends it', async () => { + const { onRowClick, onRowSelect } = renderCards(); + const acme = await cardOf('Acme'); + fireEvent.pointerDown(acme, { clientX: 10, clientY: 10 }); + await hold(600); + fireEvent.pointerUp(acme); + fireEvent.click(acme); + expect(onRowClick).not.toHaveBeenCalled(); + expect(acme).toHaveAttribute('aria-pressed', 'true'); + expect(onRowSelect).toHaveBeenLastCalledWith([expect.objectContaining({ id: 'a1' })]); + + const globex = await cardOf('Globex'); + expect(globex).toHaveAttribute('aria-pressed', 'false'); + expect(within(globex).getByTestId('grid-card-check')).toBeInTheDocument(); + fireEvent.click(globex); + expect(onRowSelect).toHaveBeenLastCalledWith([ + expect.objectContaining({ id: 'a1' }), + expect.objectContaining({ id: 'a2' }), + ]); + + fireEvent.click(globex); + fireEvent.click(await cardOf('Acme')); + expect(onRowSelect).toHaveBeenLastCalledWith([]); + expect(screen.queryAllByTestId('grid-card-check')).toHaveLength(0); + expect(onRowClick).not.toHaveBeenCalled(); + }); + + it('a long press the browser ends with no click does not swallow the next tap', async () => { + const { onRowSelect } = renderCards(); + const acme = await cardOf('Acme'); + fireEvent.pointerDown(acme, { clientX: 10, clientY: 10 }); + await hold(600); + fireEvent.pointerUp(acme); + // No click follows the press (Android after its context menu, a finger that slid off). + expect(acme).toHaveAttribute('aria-pressed', 'true'); + + const globex = await cardOf('Globex'); + fireEvent.pointerDown(globex, { clientX: 10, clientY: 60 }); + fireEvent.pointerUp(globex); + fireEvent.click(globex); + expect(globex, 'one tap ticks it').toHaveAttribute('aria-pressed', 'true'); + expect(onRowSelect).toHaveBeenLastCalledWith([ + expect.objectContaining({ id: 'a1' }), + expect.objectContaining({ id: 'a2' }), + ]); + }); + + it('a press that moves (a scroll) starts nothing; a plain tap opens the record', async () => { + const { onRowClick } = renderCards(); + const acme = await cardOf('Acme'); + fireEvent.pointerDown(acme, { clientX: 10, clientY: 10 }); + fireEvent.pointerMove(acme, { clientX: 10, clientY: 40 }); + await hold(600); + expect(screen.queryAllByTestId('grid-card-check')).toHaveLength(0); + fireEvent.click(acme); + expect(onRowClick).toHaveBeenCalledTimes(1); + }); + + it('the page\'s 「Select」 starts a selection with nothing ticked', async () => { + renderCards(); + await cardOf('Acme'); + act(() => requestListSelection(screen.getByTestId('page-column'))); + await waitFor(() => expect(screen.getAllByTestId('grid-card-check')).toHaveLength(2)); + for (const card of screen.getAllByTestId('grid-mobile-card')) { + expect(card).toHaveAttribute('aria-pressed', 'false'); + } + // The selection bar (objectstack#35678) shows 「0 selected」 and its 「×」, + // with no action to run on nothing; 「×」 ends the selection. + const bar = screen.getByTestId('bulk-actions-bar'); + expect(within(bar).getByTestId('bulk-selection-count')).toHaveTextContent('0'); + expect(within(bar).queryAllByRole('button').map((b) => b.getAttribute('data-testid'))).toEqual(['bulk-selection-clear']); + fireEvent.click(within(bar).getByTestId('bulk-selection-clear')); + expect(screen.queryAllByTestId('grid-card-check')).toHaveLength(0); + expect(screen.queryByTestId('bulk-actions-bar')).toBeNull(); + }); + + it('a long press shows the selection bar at the bottom of the cards with 「1 selected」', async () => { + renderCards(); + const acme = await cardOf('Acme'); + fireEvent.pointerDown(acme, { clientX: 10, clientY: 10 }); + await hold(600); + fireEvent.pointerUp(acme); + const anchor = screen.getByTestId('floating-selection-bar'); + expect(within(anchor).getByTestId('bulk-selection-count')).toHaveTextContent('1'); + expect(screen.getByTestId('object-grid-card-scroller').nextElementSibling).toBe(anchor); + }); + + it('a keyboard reaches the card: Enter opens it, and while selecting Space toggles it', async () => { + const { onRowClick, onRowSelect } = renderCards(); + const acme = await cardOf('Acme'); + expect(acme).toHaveAttribute('role', 'button'); + expect(acme).toHaveAttribute('tabIndex', '0'); + fireEvent.keyDown(acme, { key: 'Enter' }); + expect(onRowClick).toHaveBeenCalledTimes(1); + act(() => requestListSelection(screen.getByTestId('page-column'))); + await waitFor(() => expect(screen.getAllByTestId('grid-card-check')).toHaveLength(2)); + fireEvent.keyDown(await cardOf('Acme'), { key: ' ' }); + expect(onRowSelect).toHaveBeenLastCalledWith([expect.objectContaining({ id: 'a1' })]); + expect(onRowClick).toHaveBeenCalledTimes(1); + }); + + it('a list without selection: no long press, no 「Select」', async () => { + const { onRowClick } = renderCards({ type: 'none' }); + const acme = await cardOf('Acme'); + fireEvent.pointerDown(acme, { clientX: 10, clientY: 10 }); + await hold(600); + act(() => requestListSelection(screen.getByTestId('page-column'))); + expect(screen.queryAllByTestId('grid-card-check')).toHaveLength(0); + fireEvent.click(acme); + expect(onRowClick).toHaveBeenCalledTimes(1); + }); + + it('the page offers 「Select」 only on cards whose rows take more than one tick', async () => { + for (const [selection, offered] of [ + [{ type: 'multiple' }, true], + [{ type: 'single' }, false], + [{ type: 'none' }, false], + ] as const) { + renderCards(selection); + await cardOf('Acme'); + const scope = screen.getByTestId('page-column'); + const { getByTestId } = render(); + expect(getByTestId('selectable-probe').dataset.selectable, `selection ${selection.type}`).toBe(String(offered)); + cleanup(); + } + }); +}); + +function SelectableProbe({ scope }: { scope: HTMLElement }) { + return ; +} diff --git a/ui/packages/plugin-grid/src/components/SelectionBar.tsx b/ui/packages/plugin-grid/src/components/SelectionBar.tsx index e7c869340f3..d40188cd117 100644 --- a/ui/packages/plugin-grid/src/components/SelectionBar.tsx +++ b/ui/packages/plugin-grid/src/components/SelectionBar.tsx @@ -376,6 +376,12 @@ export interface BulkActionBarProps { allMatchingSelected?: boolean; /** Invoked when the user clicks "Select all N". */ onSelectAllMatching?: () => void; + /** + * objectstack#35883 — the host's selection is open with nothing ticked yet + * (a phone card list after 「Select」): the bar shows 「0 selected」 and its + * 「×」, so the user can end it. Without it the bar draws nothing at 0. + */ + open?: boolean; } /** @@ -405,6 +411,7 @@ export const BulkActionBar: React.FC = ({ totalMatching, allMatchingSelected, onSelectAllMatching, + open = false, }) => { const { t } = useObjectTranslation(); const barRef = React.useRef(null); @@ -414,7 +421,7 @@ export const BulkActionBar: React.FC = ({ const fit = useFittedCount(barRef, chosen, `${single ? 'one' : 'many'}:${count}`); React.useEffect(() => { - if (!onClearSelection || count === 0) return undefined; + if (!onClearSelection || (count === 0 && !open)) return undefined; const onKeyDown = (event: KeyboardEvent) => { if (event.key !== 'Escape' || event.defaultPrevented) return; if (isEditableTarget(event.target) || anotherLayerIsOpen(barRef.current)) return; @@ -422,9 +429,9 @@ export const BulkActionBar: React.FC = ({ }; document.addEventListener('keydown', onKeyDown); return () => document.removeEventListener('keydown', onKeyDown); - }, [onClearSelection, count]); + }, [onClearSelection, count, open]); - if (count === 0) return null; + if (count === 0 && !open) return null; const overCap = exceedsBulkSelectAllMatchingCap(totalMatching); const offerAll = @@ -495,7 +502,8 @@ export const BulkActionBar: React.FC = ({ : t('grid.selectAllTotal', { total: totalMatching, defaultValue: 'Select all {{total}}' })} )} - {single ? ( + {/* Nothing ticked yet (`open`): no action has rows to act on. */} + {count === 0 ? null : single ? ( ) : ( false, ); } + +// --------------------------------------------------------------------------- +// objectstack#35883 — the phone's 「Select」: the page asks its list to start a +// selection, and reads whether one is open (to hide its floating create +// button, which would sit on the selection bar). +// --------------------------------------------------------------------------- + +/** How many times each page column has asked its list to start selecting. */ +const selectRequests = new Map(); + +/** + * The page's side: ask the list inside `scope` (the page column) to start + * selecting with nothing ticked, as a long press on a card does with that + * card. The phone's 「⋮ More」 → 「Select」 calls it. + */ +export function requestListSelection(scope: HTMLElement | null): void { + if (!scope) return; + // A page column that has left the document asks nothing any more. + for (const held of selectRequests.keys()) if (!held.isConnected) selectRequests.delete(held); + selectRequests.set(scope, (selectRequests.get(scope) ?? 0) + 1); + emit(); +} + +/** + * The grid's side: a number that grows each time the page column holding + * `root` asks for a selection (`requestListSelection`); `0` before any. + */ +export function useListSelectionRequest(root: HTMLElement | null): number { + return React.useSyncExternalStore( + subscribe, + () => { + if (!root) return 0; + for (const [scope, count] of selectRequests) if (scope.contains(root)) return count; + return 0; + }, + () => 0, + ); +} + +/** The grid roots whose selection is open now. */ +const selectingRoots = new Set(); + +/** The grid's side: publish whether the grid rooted at `root` is selecting. */ +export function usePublishListSelecting(root: HTMLElement | null, selecting: boolean): void { + React.useLayoutEffect(() => { + if (!root || !selecting) return undefined; + selectingRoots.add(root); + emit(); + return () => { + selectingRoots.delete(root); + emit(); + }; + }, [root, selecting]); +} + +/** The page's side: is a selection open in a list inside `scope`? */ +export function useListPageSelecting(scope: HTMLElement | null): boolean { + return React.useSyncExternalStore( + subscribe, + () => { + if (!scope) return false; + for (const root of selectingRoots) if (scope.contains(root)) return true; + return false; + }, + () => false, + ); +} + +/** The grid roots where a 「Select」 request would open a selection now. */ +const selectableRoots = new Set(); + +/** + * The grid's side: publish whether a 「Select」 request (`requestListSelection`) + * would open a selection in the grid rooted at `root`: its cards are on screen + * and its rows take more than one tick. + */ +export function usePublishListSelectable(root: HTMLElement | null, selectable: boolean): void { + React.useLayoutEffect(() => { + if (!root || !selectable) return undefined; + selectableRoots.add(root); + emit(); + return () => { + selectableRoots.delete(root); + emit(); + }; + }, [root, selectable]); +} + +/** + * The page's side: would 「Select」 open a selection in a list inside `scope`? + * `false` for a kanban, a calendar, a list whose rows cannot be selected or + * take a single tick, and while no grid is mounted. + */ +export function useListPageSelectable(scope: HTMLElement | null): boolean { + return React.useSyncExternalStore( + subscribe, + () => { + if (!scope) return false; + for (const root of selectableRoots) if (scope.contains(root)) return true; + return false; + }, + () => false, + ); +} diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 7ecfd1938a6..f52fdafde30 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -17,10 +17,22 @@ import { ListEmptyState, hasDeclaredFilter, filterNamesCurrentUser } from './Lis import { ListViewCompactHeader, ListViewCompactRows, ListViewCappedRows, CAPPED_LIST_DEFAULT_LIMIT } from './ListViewCompact'; import { ViewSettingsPopover, + ViewSettingsContent, groupFieldOptions, type ViewSettingsField, PHONE_TOUCH_TARGET, + useBelowSm, } from './components/ViewSettingsPopover'; +import { + ListPhonePanelsContext, + PhoneFilterSheet, + PhoneListToolbar, + PhonePanelSheet, + PhoneSortSheet, + PHONE_CHIP, + PHONE_CHIP_ACTIVE, + type ListPhonePanels, +} from './phone/PhoneListPanels'; import { UserFilters, type UserFiltersHandle } from './UserFilters'; import { ConditionChipRow, SortPanel } from './conditions/ListConditionControls'; import { @@ -2434,6 +2446,11 @@ export const ListView = React.forwardRef(({ const [showSearchPopover, setShowSearchPopover] = React.useState(false); // Below `sm` the list search is an icon that expands into a field in place. const [phoneSearchOpen, setPhoneSearchOpen] = React.useState(false); + // objectstack#35883 / #35884 — below `sm` the list draws the phone's one + // toolbar row and opens its sort, filter and view-settings panels as + // bottom sheets (`./phone/PhoneListPanels.tsx`); which one is open. + const belowSm = useBelowSm(); + const [phonePanel, setPhonePanel] = React.useState<'sort' | 'filter' | 'settings' | null>(null); // Sort State const [currentSort, setCurrentSort] = React.useState(() => @@ -6982,6 +6999,143 @@ export const ListView = React.forwardRef(({
); + // Search, phone form: the icon expands into a field in place, with the + // bar's touch size. Enter or Escape folds it back to the icon, which then + // carries the active keyword as the desktop trigger does; the clear button + // empties the term and folds it. Below `sm` it is a chip of the phone + // toolbar (objectstack#35883), which draws the list's one search. + const phoneSearch = toolbarFlags.showSearch ? (phoneSearchOpen ? ( +
+
+ ) : ( + + )) : null; + + // 视图设置's props, once: the desktop draws them as the popover beside the + // view's name, the phone as the content of its bottom sheet + // (objectstack#35883: a row of the view panel opens it there). + const viewSettingsElement = ( + { + const type = (objectDef?.fields as Record | undefined)?.[name]?.type; + return typeof type === 'string' ? type : undefined; + }} + layout={viewSwitcherOffered ? (closeMenu) => ( + { + // Choosing a layout completes the choice: Display closes + // (objectui#12621). + closeMenu(); + handleViewChange(view); + }} + /> + ) : undefined} + showGroup={toolbarFlags.showGroup} + groupingConfig={chosenGroupingConfig} + setGroupingConfig={changeGrouping} + showColor={toolbarFlags.showColor} + rowColorConfig={offeredRowColorConfig} + setRowColorConfig={setRowColorConfig} + showDensity={toolbarFlags.showDensity} + density={currentView === 'gallery' + ? { + mode: galleryCardSize === 'small' ? 'compact' : galleryCardSize === 'medium' ? 'comfortable' : 'spacious', + cycle: cycleGalleryDensity, + setMode: setGalleryDensityMode, + } + : density as any} + showHideFields={toolbarFlags.showHideFields} + hiddenFields={offeredHiddenFields} + updateHiddenFields={updateListedFields} + addableFields={addableFields} + onAddField={addListedField} + changedCount={displayChangedCount} + // objectstack#35551 — the view's name and its rename head the + // menu; the field order is the grid's column order, the state + // the header's column drag writes. + viewName={typeof schema.label === 'string' && schema.label && (onRenameView || onPersonalizationChange) + ? { label: schema.label, onRename: onRenameView } + : undefined} + fieldOrder={currentView === 'grid' ? (schema.columnState as { order?: string[]; widths?: Record } | undefined)?.order : undefined} + onFieldOrderChange={currentView === 'grid' && onColumnStateChange + ? (order) => onColumnStateChange({ ...(schema.columnState as { order?: string[]; widths?: Record } | undefined), order }) + : undefined} + // objectstack#28950 — a host that marks a personalized list owns + // the one reset. It hands it over while there is something to + // restore, and the menu draws it as 恢复默认, dimmed between + // times (objectstack#35551); the list offers none of its own. + onReset={onResetView ?? (onPersonalizationChange ? () => {} : resetDisplayToViewDefault)} + resetDisabled={onResetView ? false : onPersonalizationChange ? true : undefined} + onSave={onSaveView} + exportFormats={resolvedExportOptions && exportPermitted && exportableFormats.length > 0 ? exportableFormats : undefined} + onExport={(format) => handleExport(format as 'csv' | 'xlsx' | 'json' | 'pdf')} + exportBusy={exportBusy} + exportError={exportError} + /> + ); + const phonePanels: ListPhonePanels | null = React.useMemo( + () => ({ openViewSettings: displayOffered ? () => setPhonePanel('settings') : undefined }), + [displayOffered], + ); + return (
(({ read as one segmented control rather than a loose bag of icons. Not in the compact posture (objectui#12703), nor in the capped one (objectstack#26613). */} - {listChromeShown && ( + {/* objectstack#35883 — below `sm`, one row of pills: the view, Sort, + Filter and Search, and the host's end (its Save) at the right. The + counts on Sort and Filter say what is in force, so there is no + condition row. Authored quick filters keep a line of their own. */} + {listChromeShown && belowSm && ( + + setPhonePanel('sort')} + onOpenFilter={() => setPhonePanel('filter')} + trailing={toolbarTrailing ? toolbarTrailing(phoneSearch) : phoneSearch} + end={conditionRowEnd} + /> + {((filterElements && userFilterBarShown) || (queueFilterOffered && !datasetChartOnScreen)) && ( +
+ {filterElements && userFilterBarShown && ( +
+ +
+ )} + {queueFilterOffered && !datasetChartOnScreen && ( + + )} +
+ )} + {toolbarFlags.showSort && ( + setPhonePanel(open ? 'sort' : null)} + fields={sortFields} + shownFields={shownFieldNames} + value={currentSort} + onApply={applySort} + note={sortPanelNote} + /> + )} + {toolbarFlags.showFilters && ( + setPhonePanel(open ? 'filter' : null)} + fields={filterFields} + shownFields={shownFieldNames} + value={currentFilters} + onApply={applyPanelFilters} + dataSource={dataSource} + /> + )} + {displayOffered && ( + setPhonePanel(open ? 'settings' : null)} + title={t('list.viewSettings')} + testId="phone-view-settings-panel" + > + setPhonePanel(null)} /> + + )} +
+ )} + + {listChromeShown && !belowSm && (
{/* With a host's leading node the left group grows (`flex-1`) so that node's `flex-1` wrapper has the width the tool cluster leaves — @@ -7050,69 +7288,7 @@ export const ListView = React.forwardRef(({ columns, then Group, Row height and the rest. Every control writes through the same door as its wide-form button; the panel adds no storage of its own. */} - {displayOffered && ( - { - const type = (objectDef?.fields as Record | undefined)?.[name]?.type; - return typeof type === 'string' ? type : undefined; - }} - layout={viewSwitcherOffered ? (closeMenu) => ( - { - // Choosing a layout completes the choice: Display closes - // (objectui#12621). - closeMenu(); - handleViewChange(view); - }} - /> - ) : undefined} - showGroup={toolbarFlags.showGroup} - groupingConfig={chosenGroupingConfig} - setGroupingConfig={changeGrouping} - showColor={toolbarFlags.showColor} - rowColorConfig={offeredRowColorConfig} - setRowColorConfig={setRowColorConfig} - showDensity={toolbarFlags.showDensity} - density={currentView === 'gallery' - ? { - mode: galleryCardSize === 'small' ? 'compact' : galleryCardSize === 'medium' ? 'comfortable' : 'spacious', - cycle: cycleGalleryDensity, - setMode: setGalleryDensityMode, - } - : density as any} - showHideFields={toolbarFlags.showHideFields} - hiddenFields={offeredHiddenFields} - updateHiddenFields={updateListedFields} - addableFields={addableFields} - onAddField={addListedField} - changedCount={displayChangedCount} - // objectstack#35551 — the view's name and its rename head the - // menu; the field order is the grid's column order, the state - // the header's column drag writes. - viewName={typeof schema.label === 'string' && schema.label && (onRenameView || onPersonalizationChange) - ? { label: schema.label, onRename: onRenameView } - : undefined} - fieldOrder={currentView === 'grid' ? (schema.columnState as { order?: string[]; widths?: Record } | undefined)?.order : undefined} - onFieldOrderChange={currentView === 'grid' && onColumnStateChange - ? (order) => onColumnStateChange({ ...(schema.columnState as { order?: string[]; widths?: Record } | undefined), order }) - : undefined} - // objectstack#28950 — a host that marks a personalized list owns - // the one reset. It hands it over while there is something to - // restore, and the menu draws it as 恢复默认, dimmed between - // times (objectstack#35551); the list offers none of its own. - onReset={onResetView ?? (onPersonalizationChange ? () => {} : resetDisplayToViewDefault)} - resetDisabled={onResetView ? false : onPersonalizationChange ? true : undefined} - onSave={onSaveView} - exportFormats={resolvedExportOptions && exportPermitted && exportableFormats.length > 0 ? exportableFormats : undefined} - onExport={(format) => handleExport(format as 'csv' | 'xlsx' | 'json' | 'pdf')} - exportBusy={exportBusy} - exportError={exportError} - /> - )} + {displayOffered && viewSettingsElement} {/* User Filters — filter elements (dropdown chips / preset tabs / toggles). Mutually exclusive with view tabs above, so at most one filter element group ever renders here. On mobile we keep @@ -7642,70 +7818,7 @@ export const ListView = React.forwardRef(({ )} - {/* Search, phone form: the icon expands into a field in place, with - the bar's touch size. Enter or Escape folds it back to the icon, - which then carries the active keyword as the desktop trigger - does; the clear button empties the term and folds it. */} - {toolbarFlags.showSearch && (phoneSearchOpen ? ( -
-
- ) : ( - - ))} + {phoneSearch} ); return toolbarTrailing ? toolbarTrailing(searchTools) : searchTools; @@ -7719,7 +7832,7 @@ export const ListView = React.forwardRef(({ (objectstack#35878): with nothing set it holds the dashed 「Sort」 and 「Filter」 buttons, so the first condition does not push the table down a row. One line; what does not fit scrolls sideways. */} - {listChromeShown && ( + {listChromeShown && !belowSm && (
; + +function stubPhone() { + vi.stubGlobal('matchMedia', vi.fn().mockImplementation((q: string) => ({ + matches: q === '(max-width: 639.98px)', + media: q, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + }))); +} + +function mount(schema: Partial = {}, props: Record = {}) { + const dataSource = { + find: vi.fn().mockResolvedValue({ data: RECORDS, total: 1 }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn().mockResolvedValue({ + name: 'account', + fields: { name: { type: 'text', label: 'Name' }, stage: { type: 'text', label: 'Stage' } }, + }), + }; + render( + + + , + ); + return dataSource; +} + +beforeEach(() => { + stubPhone(); + previousGrid = ComponentRegistry.get('object-grid'); + ComponentRegistry.register('object-grid', () =>
); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + if (previousGrid) ComponentRegistry.register('object-grid', previousGrid as any); +}); + +/** Open the sort panel and add a level on `field` through its field list. */ +async function addSortLevel(field: string) { + fireEvent.click(screen.getByTestId('phone-sort-chip')); + await screen.findByTestId('phone-sort-panel'); + fireEvent.click(screen.getByTestId('sort-builder-add')); + fireEvent.click(await screen.findByTestId(`phone-sort-add-fields-item-${field}`)); + // Back on the levels, with the new one listed. + await waitFor(() => expect(screen.getAllByTestId('sort-builder-row')).toHaveLength(1)); +} + +describe('phone list toolbar (objectstack#35883)', () => { + it('one row of pills, no condition row and no View settings button on the bar', async () => { + mount(); + await screen.findByTestId('grid-stub'); + const bar = screen.getByTestId('phone-list-toolbar'); + expect(within(bar).getByTestId('phone-sort-chip')).toHaveAttribute('data-count', '0'); + expect(within(bar).getByTestId('phone-filter-chip')).toHaveAttribute('data-count', '0'); + expect(within(bar).getByTestId('phone-search-trigger')).toBeInTheDocument(); + expect(screen.queryByTestId('list-condition-row')).toBeNull(); + expect(screen.queryByTestId('toolbar-display-trigger')).toBeNull(); + }); + + it('`userActions.sort: false` draws no Sort pill', async () => { + mount({ userActions: { sort: false } } as Partial); + await screen.findByTestId('grid-stub'); + expect(screen.queryByTestId('phone-sort-chip')).toBeNull(); + }); +}); + +describe('phone sort panel: 「✓」 applies, 「×」 discards (objectstack#35884)', () => { + it('a level added in the panel changes nothing until 「✓」, then sorts through onSortChange', async () => { + const onSortChange = vi.fn(); + mount({}, { onSortChange }); + await screen.findByTestId('grid-stub'); + + await addSortLevel('name'); + expect(onSortChange).not.toHaveBeenCalled(); + expect(screen.getByTestId('phone-sort-chip')).toHaveAttribute('data-count', '0'); + + fireEvent.click(screen.getByTestId('phone-sort-panel-apply')); + await waitFor(() => expect(onSortChange).toHaveBeenCalledTimes(1)); + expect(onSortChange.mock.calls[0][0]).toEqual([expect.objectContaining({ field: 'name', order: 'asc' })]); + await waitFor(() => expect(screen.getByTestId('phone-sort-chip')).toHaveAttribute('data-count', '1')); + expect(screen.getByTestId('phone-sort-chip-count')).toHaveTextContent('1'); + }); + + it('「×」 drops the panel\'s change: no write, the count stays', async () => { + const onSortChange = vi.fn(); + mount({}, { onSortChange }); + await screen.findByTestId('grid-stub'); + + await addSortLevel('name'); + fireEvent.click(screen.getByTestId('phone-sort-panel-close')); + // Closed (the sheet may stay mounted for its slide-out). + await waitFor(() => { + const panel = screen.queryByTestId('phone-sort-panel'); + expect(panel === null || panel.getAttribute('data-state') === 'closed').toBe(true); + }); + expect(onSortChange).not.toHaveBeenCalled(); + expect(screen.getByTestId('phone-sort-chip')).toHaveAttribute('data-count', '0'); + + // Opened again, the panel starts from the list's sort, not the dropped copy. + fireEvent.click(screen.getByTestId('phone-sort-chip')); + await waitFor(() => expect(screen.getByTestId('phone-sort-panel')).toHaveAttribute('data-state', 'open')); + expect(screen.queryAllByTestId('sort-builder-row')).toHaveLength(0); + }); +}); + +describe('phone filter panel (objectstack#35884)', () => { + it('with no filter: a sentence and one 「Add filter」 button', async () => { + mount(); + await screen.findByTestId('grid-stub'); + fireEvent.click(screen.getByTestId('phone-filter-chip')); + const empty = await screen.findByTestId('phone-filter-empty'); + expect(within(empty).getByTestId('phone-filter-add')).toHaveTextContent('Add filter'); + // The phone panel offers no advanced filter step. + fireEvent.click(within(empty).getByTestId('phone-filter-add')); + await screen.findByTestId('phone-filter-step-fields'); + expect(screen.queryByTestId('phone-filter-step-open-advanced')).toBeNull(); + }); + + it('an 「or」 group is not edited on a phone: the panel says so', async () => { + mount({}, { + initialFilters: { + id: 'root', + logic: 'or', + conditions: [ + { id: 'a', field: 'name', operator: 'contains', value: 'Ac' }, + { id: 'b', field: 'stage', operator: 'contains', value: 'wo' }, + ], + }, + }); + await screen.findByTestId('grid-stub'); + fireEvent.click(screen.getByTestId('phone-filter-chip')); + expect(await screen.findByTestId('phone-filter-advanced-notice')).toHaveTextContent( + 'This view uses an advanced filter. Change it on a computer.', + ); + }); +}); + +describe('phone panels: an untouched 「✓」 writes nothing (objectstack#35884)', () => { + it('sort: 「✓」 with no change does not call onSortChange', async () => { + const onSortChange = vi.fn(); + mount({}, { onSortChange }); + await screen.findByTestId('grid-stub'); + fireEvent.click(screen.getByTestId('phone-sort-chip')); + await screen.findByTestId('phone-sort-panel'); + fireEvent.click(screen.getByTestId('phone-sort-panel-apply')); + await waitFor(() => { + const panel = screen.queryByTestId('phone-sort-panel'); + expect(panel === null || panel.getAttribute('data-state') === 'closed').toBe(true); + }); + expect(onSortChange).not.toHaveBeenCalled(); + }); + + it('filter: 「✓」 on the advanced-filter notice does not call onFilterChange', async () => { + const onFilterChange = vi.fn(); + mount({}, { + onFilterChange, + initialFilters: { + id: 'root', + logic: 'or', + conditions: [ + { id: 'a', field: 'name', operator: 'contains', value: 'Ac' }, + { id: 'b', field: 'stage', operator: 'contains', value: 'wo' }, + ], + }, + }); + await screen.findByTestId('grid-stub'); + onFilterChange.mockClear(); + fireEvent.click(screen.getByTestId('phone-filter-chip')); + await screen.findByTestId('phone-filter-advanced-notice'); + fireEvent.click(screen.getByTestId('phone-filter-panel-apply')); + await waitFor(() => { + const panel = screen.queryByTestId('phone-filter-panel'); + expect(panel === null || panel.getAttribute('data-state') === 'closed').toBe(true); + }); + expect(onFilterChange).not.toHaveBeenCalled(); + }); +}); + +describe('phone panels and the on-screen keyboard (objectstack#35884)', () => { + /** A `visualViewport` whose height the test moves, as a keyboard would. */ + function stubVisualViewport(height: number) { + const viewport = Object.assign(new EventTarget(), { height, offsetTop: 0, width: 390, offsetLeft: 0, pageTop: 0, pageLeft: 0, scale: 1 }); + vi.stubGlobal('visualViewport', viewport); + return viewport; + } + + it('stands on the keyboard while it is up, and fills the screen again once it goes', async () => { + const full = window.innerHeight; + const viewport = stubVisualViewport(full); + mount(); + await screen.findByTestId('grid-stub'); + fireEvent.click(screen.getByTestId('phone-filter-chip')); + const panel = await screen.findByTestId('phone-filter-panel'); + expect(panel, 'CONTROL: no keyboard, no inset').not.toHaveAttribute('data-keyboard-inset'); + + // The keyboard comes up: 300 px of the layout viewport are covered. + viewport.height = full - 300; + viewport.dispatchEvent(new Event('resize')); + await waitFor(() => expect(panel).toHaveAttribute('data-keyboard-inset', '300')); + expect(panel.style.bottom).toBe('300px'); + expect(panel.style.height).toBe(`${full - 300 - 40}px`); + expect(panel.style.maxHeight).toBe(`${full - 300 - 40}px`); + + // It goes down: the sheet's own height again. + viewport.height = full; + viewport.dispatchEvent(new Event('resize')); + await waitFor(() => expect(panel).not.toHaveAttribute('data-keyboard-inset')); + expect(panel.style.bottom).toBe(''); + expect(panel.style.height).toBe(''); + }); +}); + +describe('the phone sort levels (objectstack#35884)', () => { + + it('each level is two lines, the field over its direction, with the builder\'s handle', async () => { + mount(); + await screen.findByTestId('grid-stub'); + await addSortLevel('name'); + const row = screen.getByTestId('sort-builder-row'); + expect(within(row).getByTestId('sort-builder-row-field')).toHaveTextContent('Name'); + expect(within(row).getByTestId('sort-builder-row-direction')).toHaveTextContent('A → Z'); + expect(within(row).getByTestId('sort-builder-handle')).toBeInTheDocument(); + expect(within(row).getByTestId('sort-builder-row-menu')).toHaveAccessibleName('Options for Name'); + }); + + it('a finger on the handle moves a level: dropped over the first, the second leads, and 「✓」 writes that order', async () => { + const onSortChange = vi.fn(); + mount({}, { onSortChange }); + await screen.findByTestId('grid-stub'); + await addSortLevel('name'); + fireEvent.click(screen.getByTestId('sort-builder-add')); + fireEvent.click(await screen.findByTestId('phone-sort-add-fields-item-stage')); + await waitFor(() => expect(screen.getAllByTestId('sort-builder-row')).toHaveLength(2)); + const rows = screen.getAllByTestId('sort-builder-row'); + rows.forEach((row, i) => { + row.getBoundingClientRect = () => ({ top: i * 56, height: 56, bottom: i * 56 + 56, left: 0, right: 300, width: 300, x: 0, y: i * 56, toJSON: () => ({}) }); + }); + const handle = within(rows[1]).getByTestId('sort-builder-handle'); + fireEvent.pointerDown(handle, { pointerType: 'touch', pointerId: 1, clientY: 84 }); + fireEvent.pointerMove(handle, { pointerType: 'touch', pointerId: 1, clientY: 10 }); + fireEvent.pointerUp(handle, { pointerType: 'touch', pointerId: 1, clientY: 10 }); + expect(screen.getAllByTestId('sort-builder-row-field').map((el) => el.textContent)).toEqual(['Stage', 'Name']); + expect(onSortChange, 'staged: nothing written yet').not.toHaveBeenCalled(); + fireEvent.click(screen.getByTestId('phone-sort-panel-apply')); + await waitFor(() => expect(onSortChange).toHaveBeenCalledTimes(1)); + expect(onSortChange.mock.calls[0][0].map((level: { field: string }) => level.field)).toEqual(['stage', 'name']); + }); + + it('ArrowDown on a handle moves its level and the handle keeps focus, so ArrowUp from it moves it back', async () => { + mount(); + await screen.findByTestId('grid-stub'); + await addSortLevel('name'); + fireEvent.click(screen.getByTestId('sort-builder-add')); + fireEvent.click(await screen.findByTestId('phone-sort-add-fields-item-stage')); + await waitFor(() => expect(screen.getAllByTestId('sort-builder-row')).toHaveLength(2)); + const fields = () => screen.getAllByTestId('sort-builder-row-field').map((el) => el.textContent); + const handleOf = (i: number) => within(screen.getAllByTestId('sort-builder-row')[i]).getByTestId('sort-builder-handle'); + + // A browser drops focus from a node React moves; jsdom keeps it, so the + // test drops it by hand, as the browser would, right after the move. + const pressOn = (handle: HTMLElement, key: string) => { + fireEvent.keyDown(handle, { key }); + handle.blur(); + }; + handleOf(0).focus(); + pressOn(handleOf(0), 'ArrowDown'); + expect(fields()).toEqual(['Stage', 'Name']); + await waitFor(() => expect(handleOf(1)).toHaveFocus()); + + pressOn(document.activeElement as HTMLElement, 'ArrowUp'); + expect(fields()).toEqual(['Name', 'Stage']); + await waitFor(() => expect(handleOf(0)).toHaveFocus()); + }); +}); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.phoneSortSearch-28911.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.phoneSortSearch-28911.test.tsx index b2806643640..b11dd89981a 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.phoneSortSearch-28911.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.phoneSortSearch-28911.test.tsx @@ -144,7 +144,8 @@ describe('phone list: the search icon expands in place (objectstack#28911)', () const trigger = screen.getByTestId('phone-search-trigger'); expect(trigger).toBeVisible(); expect(trigger).toHaveAccessibleName('Search'); - expect(sizeTokens(trigger)).toEqual(sizeTokens(screen.getByTestId('toolbar-display-trigger'))); + // objectstack#35883 — a pill of the phone toolbar, 44 px like its other pills. + expect(sizeTokens(trigger)).toEqual(expect.arrayContaining(['h-11', 'min-w-11'])); fireEvent.click(trigger); const input = screen.getByTestId('phone-search-input'); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx index b631aad62c0..be1859e29b8 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.phoneWidth-29074.test.tsx @@ -75,13 +75,14 @@ afterEach(() => { }); describe('list bar touch targets below sm (objectstack#29074)', () => { - it('Filter, Sort, Display and the phone search trigger are 44 px below sm and keep h-7 from sm up', async () => { + it('Filter, Sort and Display are 44 px below sm and keep h-7 from sm up; the phone search pill is 44 px', async () => { mount(); await screen.findByTestId('grid-stub'); - for (const id of ['toolbar-display-trigger', 'phone-search-trigger']) { - const el = screen.getByTestId(id); - expect(tokens(el), id).toEqual(expect.arrayContaining(['h-7', 'min-w-7', ...PHONE_TOUCH_TARGET.split(' ')])); - } + const display = screen.getByTestId('toolbar-display-trigger'); + expect(tokens(display)).toEqual(expect.arrayContaining(['h-7', 'min-w-7', ...PHONE_TOUCH_TARGET.split(' ')])); + // objectstack#35883 — the phone search is a pill of the phone toolbar, + // 44 px at its one width (it is not drawn from `sm` up). + expect(tokens(screen.getByTestId('phone-search-trigger'))).toEqual(expect.arrayContaining(['h-11', 'min-w-11', 'sm:hidden'])); // Filter and Sort are the condition row's since objectstack#35878: 24 px // from `sm` up, the same 44 px below it. for (const id of ['condition-add-filter', 'condition-sort']) { diff --git a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx index 8671c58b118..0a1c6764f0b 100644 --- a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx +++ b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx @@ -147,7 +147,7 @@ function viewChipText( // --------------------------------------------------------------------------- /** One condition as the name read sees it: a field and the value it compares. */ -interface NamedCondition { +export interface NamedCondition { field?: string; operator?: string; value?: unknown; @@ -171,7 +171,7 @@ function lookupIds(value: unknown): string[] { * arrays the host rebuilds every render (`ui/AGENTS.md` #10). A read that * fails, or a record nothing names, answers `undefined`: the chip keeps the id. */ -function useLookupValueNames( +export function useLookupValueNames( dataSource: Pick | null | undefined, fields: ReadonlyArray, conditions: ReadonlyArray, @@ -268,6 +268,12 @@ export interface FilterPanelProps { renderAdvanced: () => React.ReactNode; /** Open on this row's values instead of the field list. */ conditionId?: string; + /** + * The field list's footer opens the advanced panel (the default). `false` + * (the phone's panel, objectstack#35884, which does not edit advanced + * filters): no footer. + */ + advancedOffered?: boolean; testId?: string; } @@ -280,6 +286,7 @@ export function FilterPanel({ onChange, renderAdvanced, conditionId, + advancedOffered = true, testId = 'filter-panel', }: FilterPanelProps) { const { t } = useListConditionTranslation(); @@ -339,7 +346,7 @@ export function FilterPanel({ shownFields={shownFields} onPick={pickField} testId={`${testId}-fields`} - footer={ + footer={advancedOffered ? ( - } + ) : undefined} /> ); } diff --git a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts index 708b657360a..35d7b9daef6 100644 --- a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -16,6 +16,20 @@ import { createSafeTranslation } from '@object-ui/i18n'; */ export const LIST_CONDITION_DEFAULT_TRANSLATIONS: Record = { 'listConditions.fieldList.search': 'Search fields', + 'listConditions.phone.toolbar': 'List tools', + 'listConditions.phone.sortCount_one': 'Sort, {{count}} level', + 'listConditions.phone.sortCount_other': 'Sort, {{count}} levels', + 'listConditions.phone.filterCount_one': 'Filter, {{count}} in use', + 'listConditions.phone.filterCount_other': 'Filter, {{count}} in use', + 'listConditions.phone.back': 'Back', + 'listConditions.phone.discard': 'Discard changes', + 'listConditions.phone.close': 'Close', + 'listConditions.phone.apply': 'Apply', + 'listConditions.phone.advancedNotice': 'This view uses an advanced filter. Change it on a computer.', + 'listConditions.phone.filterEmpty': 'No filter yet. Add one to show only the records that match.', + 'listConditions.phone.itemOptions': 'Options for {{label}}', + 'listConditions.phone.edit': 'Edit', + 'listConditions.phone.remove': 'Remove', 'listConditions.fieldList.shown': 'In this view', 'listConditions.fieldList.hidden': 'Hidden fields', 'listConditions.fieldList.empty': 'No field matches', @@ -78,6 +92,16 @@ export const LIST_CONDITION_DEFAULT_TRANSLATIONS: Record = { 'dashboard.filters.range.this_week': 'This week', 'dashboard.filters.range.this_month': 'This month', 'dashboard.filters.range.last_30_days': 'Last 30 days', + // The phone sort sheet's level (objectstack#35884), in SortBuilder's words. + 'sortBuilder.addSort': 'Add sort', + 'sortBuilder.ascending': 'A → Z', + 'sortBuilder.descending': 'Z → A', + 'sortBuilder.oldestFirst': 'Oldest → Newest', + 'sortBuilder.newestFirst': 'Newest → Oldest', + 'sortBuilder.reorder': 'Drag to reorder', + 'sortBuilder.removeSort': 'Remove sort', + 'sortBuilder.levelOptions': 'Options for {{label}}', + 'sortBuilder.changeField': 'Change field', }; export const useListConditionTranslation = createSafeTranslation( diff --git a/ui/packages/plugin-list/src/index.tsx b/ui/packages/plugin-list/src/index.tsx index b48b44935f2..13c84be3a74 100644 --- a/ui/packages/plugin-list/src/index.tsx +++ b/ui/packages/plugin-list/src/index.tsx @@ -20,6 +20,11 @@ export { ListView, ListViewBlock, ViewSwitcher, ObjectGallery }; export { TabBar } from './components/TabBar'; export type { TabBarProps, ViewTab } from './components/TabBar'; export { UserFilters } from './UserFilters'; +// objectstack#35883 / #35884 — the phone toolbar's panel container and the +// context its view switcher reads, for the console's switcher to draw its +// phone face with the list's own sheet. +export { PhonePanelSheet, useListPhonePanels, PHONE_CHIP, PHONE_CHIP_ACTIVE } from './phone/PhoneListPanels'; +export type { PhonePanelSheetProps, ListPhonePanels } from './phone/PhoneListPanels'; export type { UserFiltersProps, UserFiltersHandle } from './UserFilters'; export { normalizeFilterCondition, normalizeFilters } from './ListView'; // The provider-less fallback table, exported so objectui#4401's mirror gate can diff --git a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx new file mode 100644 index 00000000000..28abfd80bf0 --- /dev/null +++ b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx @@ -0,0 +1,692 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The phone's list toolbar and its panels (objectstack#35883, objectstack#35884). + * + * The phone is the same console at a narrow width, not a second app: every + * panel here draws the desktop's own content in a different container. + * + * - `PhonePanelSheet`: the container. A sheet that rises from the bottom and + * covers nearly the whole screen; a round 「×」 at the top left, the title in + * the middle, a round 「✓」 at the top right. A swipe down, the overlay or + * Escape close it as 「×」 does. + * - `PhoneSortSheet`: the list's sort levels on two lines each + * (`PhoneSortLevels`, the same `SortItem`s the desktop `SortBuilder` edits), + * `SortPanel` (the desktop's field list with the direction on top) to add + * one and `FieldList` to change a level's field. + * - `PhoneFilterSheet`: one item per filter, then `FilterPanel` (the desktop's + * field list → values steps) to add or change one. + * - `PhoneViewSettingsSheet`: `ViewSettingsContent`, the desktop's 视图设置. + * + * The one behaviour the phone adds is 「✓ to apply」 on sort and filter: the + * sheet edits a copy of the list's sort or filter (the staging layer) and hands + * it to the list's own write (`onApply`, the same `applySort` / + * `applyPanelFilters` the desktop chips call) only on 「✓」. 「×」 drops the copy. + * Nothing here stores anything. + */ + +import * as React from 'react'; +import { + cn, + Button, + Drawer, + DrawerContent, + DrawerDescription, + DrawerTitle, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, + type FilterBuilderRowGroup, + type SortItem, +} from '@object-ui/components'; +import type { DataSource } from '@object-ui/types'; +import { ArrowUpDown, Check, ChevronLeft, GripVertical, Info, ListFilter, MoreHorizontal, Plus, X } from 'lucide-react'; +import { FieldList } from '../conditions/FieldList'; +import { isQuickRowApplied } from '../conditions/FilterValuePanel'; +import { FilterPanel, SortPanel, describeConditionValue, useLookupValueNames } from '../conditions/ListConditionControls'; +import { chipsAreIndependent, removeCondition, type ConditionField } from '../conditions/conditionModel'; +import { useListConditionTranslation } from '../conditions/conditionTranslations'; + +// --------------------------------------------------------------------------- +// The toolbar's chips +// --------------------------------------------------------------------------- + +/** A chip of the phone toolbar: a pill, 44 px tall (the phone's touch size, WCAG 2.5.5), 13 px text. */ +export const PHONE_CHIP = + 'inline-flex h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 rounded-full border bg-background px-3 text-[13px] font-medium leading-none transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; + +/** A chip whose condition is in force: highlighted, as the desktop's sort chip is. */ +export const PHONE_CHIP_ACTIVE = 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15'; + +/** + * What the list hands a view switcher drawn in its phone toolbar (the host's + * `toolbarLeading`). Present ⇒ the switcher is in the phone toolbar: it draws + * as a pill and opens its views in a `PhonePanelSheet`. `openViewSettings` + * opens 视图设置, which on a phone is a row of the view panel rather than a + * toolbar button (objectstack#35883); absent where the list offers no + * settings. The context is `null` outside a phone toolbar. + */ +export interface ListPhonePanels { + openViewSettings?: () => void; +} + +export const ListPhonePanelsContext = React.createContext(null); + +/** The phone panels the list on screen offers to its view switcher; `null` off a phone toolbar. */ +export function useListPhonePanels(): ListPhonePanels | null { + return React.useContext(ListPhonePanelsContext); +} + +function CountBadge({ count, testId }: { count: number; testId: string }) { + return ( + + {count} + + ); +} + +export interface PhoneListToolbarProps { + /** The host's view switcher (the list's `toolbarLeading`), first in the row. */ + lead?: React.ReactNode; + /** The sort levels in force; `null` ⇒ no Sort chip (`userActions.sort: false`). */ + sortCount: number | null; + /** The reader's filters in force; `null` ⇒ no Filter chip. */ + filterCount: number | null; + onOpenSort: () => void; + onOpenFilter: () => void; + /** The list's search, already drawn by its host's right end (`toolbarTrailing`). */ + trailing?: React.ReactNode; + /** The host's end of the row: the condition row's end on desktop (its Save, objectstack#35955). */ + end?: React.ReactNode; +} + +/** + * objectstack#35883 — the phone's one toolbar row: the view (its name and + * count), Sort, Filter and Search, all pills; the host's end (Save, once there + * is something to save) at the right. No condition row: the counts on the + * chips say what is in force. One line; what does not fit scrolls inside it. + */ +export function PhoneListToolbar({ + lead, + sortCount, + filterCount, + onOpenSort, + onOpenFilter, + trailing, + end, +}: PhoneListToolbarProps) { + const { t } = useListConditionTranslation(); + return ( +
+ {lead != null && ( +
+ {lead} +
+ )} + {sortCount !== null && ( + + )} + {filterCount !== null && ( + + )} + {trailing} + {end ? ( +
{end}
+ ) : null} +
+ ); +} + +// --------------------------------------------------------------------------- +// The sheet +// --------------------------------------------------------------------------- + +/** The field list and value steps take the sheet's width and height, not a popover's. */ +const STEP_FILL = '[&>*]:w-full [&>*]:max-w-none [&_[role=listbox]]:max-h-none'; + +const ROUND_BUTTON = + 'inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-muted text-foreground transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; + +export interface PhonePanelSheetProps { + open: boolean; + /** `false` from 「×」, a swipe down, the overlay or Escape: the host drops its copy. */ + onOpenChange: (open: boolean) => void; + title: string; + /** 「✓」: absent ⇒ the sheet draws none (a panel that applies each choice at once). */ + onApply?: () => void; + /** A step inside the panel: the left button goes back to the panel's first step instead of closing. */ + onBack?: () => void; + children: React.ReactNode; + testId?: string; +} + +/** The strip of the page left in view above an open sheet, in px (`2.5rem`). */ +const SHEET_TOP_GAP = 40; + +/** + * The on-screen keyboard while `active`: how far the visible area's bottom + * (`visualViewport`) sits above the layout viewport's, and the visible + * height. `null` with no keyboard up (or no `visualViewport`). + * + * `100dvh` does not shrink for the keyboard (iOS Safari, and Chrome on + * Android's default `resizes-visual`): only the visual viewport does. So the + * sheet reads it and stands on the keyboard, its 「✓」 and the focused field + * in view. + */ +function useKeyboardInset(active: boolean): { bottom: number; visibleHeight: number } | null { + const [inset, setInset] = React.useState<{ bottom: number; visibleHeight: number } | null>(null); + React.useEffect(() => { + const viewport = typeof window === 'undefined' ? null : window.visualViewport; + if (!active || !viewport) return undefined; + const read = () => { + const bottom = Math.max(0, Math.round(window.innerHeight - viewport.height - viewport.offsetTop)); + // Below this the gap is the browser's own chrome moving, not a keyboard. + setInset(bottom < 80 ? null : { bottom, visibleHeight: Math.round(viewport.height) }); + }; + read(); + viewport.addEventListener('resize', read); + viewport.addEventListener('scroll', read); + return () => { + viewport.removeEventListener('resize', read); + viewport.removeEventListener('scroll', read); + }; + }, [active]); + return active ? inset : null; +} + +export function PhonePanelSheet({ open, onOpenChange, title, onApply, onBack, children, testId = 'phone-panel' }: PhonePanelSheetProps) { + const { t } = useListConditionTranslation(); + const keyboard = useKeyboardInset(open); + const keyboardHeight = keyboard ? `${Math.max(0, keyboard.visibleHeight - SHEET_TOP_GAP)}px` : undefined; + return ( + // The sheet follows the keyboard itself (`useKeyboardInset`), so vaul's + // own input repositioning, which would also write its height, is off. + + +
+ {onBack ? ( + + ) : ( + + )} + + {title} + + {onApply ? ( + + ) : ( +
+ {title} +
+ {children} +
+
+
+ ); +} + +/** + * The staging layer: a copy of `value` taken each time the sheet opens, and the + * panel's first step again. Reset while rendering (React's "adjust state when a + * prop changes" pattern), so the first frame of an opening sheet already shows + * the list's current value. + */ +function useStaged(open: boolean, value: T, firstStep: S): [T, React.Dispatch>, S, React.Dispatch>] { + const [staged, setStaged] = React.useState(value); + const [step, setStep] = React.useState(firstStep); + const [wasOpen, setWasOpen] = React.useState(open); + if (open !== wasOpen) { + setWasOpen(open); + if (open) { + setStaged(value); + setStep(firstStep); + } + } + return [staged, setStaged, step, setStep]; +} + +// --------------------------------------------------------------------------- +// Sort +// --------------------------------------------------------------------------- + +const DATE_SORT_TYPES = new Set(['date', 'datetime']); + +/** + * The phone sort sheet's levels (objectstack#35884): each level on two lines, + * the field over its direction, with a handle a finger drags (pointer events: + * HTML5 drag does not fire on touch) or ArrowUp / ArrowDown moves, and a 「⋯」 + * that changes the field, the direction or removes the level. The levels are + * the list's own `SortItem`s, the ones the desktop `SortBuilder` edits; this + * is their phone face, drawn here rather than in `@object-ui/components` so + * that package's eager chunk carries no phone-only bytes. + */ +function PhoneSortLevels({ fields, value, onChange, onChangeField }: { + fields: ReadonlyArray; + value: SortItem[]; + onChange: (next: SortItem[]) => void; + onChangeField: (id: string) => void; +}) { + const { t } = useListConditionTranslation(); + const listRef = React.useRef(null); + const [drag, setDrag] = React.useState<{ from: number; over: number } | null>(null); + const handles = React.useRef(new Map()); + const move = (from: number, to: number) => { + if (from === to || to < 0 || to >= value.length) return; + const next = value.slice(); + next.splice(to, 0, ...next.splice(from, 1)); + onChange(next); + return value[from].id; + }; + // The level under the finger: the first whose middle is below it. + const indexAt = (clientY: number) => { + const rows = Array.from(listRef.current?.children ?? []); + const i = rows.findIndex((row) => { + const rect = row.getBoundingClientRect(); + return clientY < rect.top + rect.height / 2; + }); + return i < 0 ? rows.length - 1 : i; + }; + return ( +
+ {value.map((item, index) => { + const field = fields.find((f) => f.value === item.field); + const label = field?.label ?? item.field; + const direction = DATE_SORT_TYPES.has(field?.type ?? '') + ? { asc: t('sortBuilder.oldestFirst'), desc: t('sortBuilder.newestFirst') } + : { asc: t('sortBuilder.ascending'), desc: t('sortBuilder.descending') }; + return ( +
+ { + if (node) handles.current.set(item.id, node); + else handles.current.delete(item.id); + }} + role="button" + tabIndex={value.length > 1 ? 0 : -1} + aria-disabled={value.length < 2 || undefined} + aria-label={t('sortBuilder.reorder')} + // A bottom sheet that closes on a downward swipe leaves this drag alone. + data-vaul-no-drag="" + className="inline-flex h-11 w-8 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring aria-disabled:opacity-40" + // The sheet's own swipe never sees this drag either. + onPointerDown={(event) => { + event.stopPropagation(); + if (value.length < 2) return; + event.preventDefault(); + event.currentTarget.setPointerCapture?.(event.pointerId); + setDrag({ from: index, over: index }); + }} + onPointerMove={(event) => { + event.stopPropagation(); + if (!drag) return; + const over = indexAt(event.clientY); + if (over !== drag.over) setDrag({ from: drag.from, over }); + }} + onPointerUp={(event) => { + event.stopPropagation(); + if (!drag) return; + move(drag.from, drag.over); + setDrag(null); + }} + onPointerCancel={() => setDrag(null)} + onKeyDown={(event) => { + const to = event.key === 'ArrowUp' ? index - 1 : event.key === 'ArrowDown' ? index + 1 : null; + if (to === null) return; + event.preventDefault(); + const moved = move(index, to); + // The handle keeps focus at the level's new place. + if (moved) requestAnimationFrame(() => handles.current.get(moved)?.focus()); + }} + data-testid="sort-builder-handle" + > + +
+
{label}
+
+ {direction[item.order]} +
+
+ + + + + + onChangeField(item.id)} data-testid="sort-builder-row-change-field"> + {t('sortBuilder.changeField')} + + {(['asc', 'desc'] as const).map((order) => ( + onChange(value.map((level) => (level.id === item.id ? { ...level, order } : level)))} + data-testid={`sort-builder-row-order-${order}`} + > + + ))} + + onChange(value.filter((level) => level.id !== item.id))} + data-testid="sort-builder-row-remove" + > + {t('sortBuilder.removeSort')} + + + +
+ ); + })} +
+ ); +} + +export interface PhoneSortSheetProps { + open: boolean; + onOpenChange: (open: boolean) => void; + fields: ReadonlyArray; + shownFields?: ReadonlyArray; + /** The sort in force. */ + value: ReadonlyArray; + /** 「✓」: the list's own sort write (`applySort`). */ + onApply: (next: SortItem[]) => void; + /** The host's note under the field list (fields it cannot sort by). */ + note?: React.ReactNode; +} + +type SortStep = { kind: 'levels' } | { kind: 'add' } | { kind: 'field'; id: string }; + +export function PhoneSortSheet({ open, onOpenChange, fields, shownFields, value, onApply, note }: PhoneSortSheetProps) { + const { t } = useListConditionTranslation(); + const levels: SortStep = { kind: 'levels' }; + const [staged, setStaged, step, setStep] = useStaged(open, value as SortItem[], levels); + + let body: React.ReactNode; + if (step.kind === 'add') { + body = ( +
+ setStep(levels)} + footer={note} + testId="phone-sort-add" + /> +
+ ); + } else if (step.kind === 'field') { + const held = new Set(staged.filter((level) => level.id !== step.id).map((level) => level.field)); + body = ( +
+ !field.disabled && !held.has(field.value))} + shownFields={shownFields} + onPick={(item) => { + setStaged((current) => current.map((level) => (level.id === step.id ? { ...level, field: item.value } : level))); + setStep(levels); + }} + testId="phone-sort-field" + /> +
+ ); + } else { + const held = new Set(staged.map((level) => level.field)); + body = ( +
+ setStep({ kind: 'field', id })} + /> + +
+ ); + } + + return ( + { + // An untouched copy is still the list's own value: nothing to write. + if (staged !== value) onApply(staged.filter((level) => level.field)); + onOpenChange(false); + }} + onBack={step.kind === 'levels' ? undefined : () => setStep(levels)} + testId="phone-sort-panel" + > + {body} + + ); +} + +// --------------------------------------------------------------------------- +// Filter +// --------------------------------------------------------------------------- + +export interface PhoneFilterSheetProps { + open: boolean; + onOpenChange: (open: boolean) => void; + fields: ReadonlyArray; + shownFields?: ReadonlyArray; + /** The reader's filter in force (the panel's group, unfinished rows included). */ + value: FilterBuilderRowGroup; + /** 「✓」: the list's own filter write (`applyPanelFilters`). */ + onApply: (next: FilterBuilderRowGroup) => void; + dataSource?: Pick | null; +} + +type FilterStep = { kind: 'list' } | { kind: 'add' } | { kind: 'edit'; id: string }; + +export function PhoneFilterSheet({ open, onOpenChange, fields, shownFields, value, onApply, dataSource }: PhoneFilterSheetProps) { + const { t } = useListConditionTranslation(); + const [staged, setStaged, step, setStep] = useStaged(open, value, { kind: 'list' }); + const applied = (staged.conditions ?? []).filter(isQuickRowApplied); + const nameOf = useLookupValueNames(dataSource, fields, applied); + const independent = chipsAreIndependent(staged); + const toList = () => setStep({ kind: 'list' }); + + let body: React.ReactNode; + if (!independent) { + // An advanced filter (groups, 「or」) is not edited on a phone: it says so + // and keeps filtering. + body = ( +
+
+ ); + } else if (step.kind !== 'list') { + body = ( +
+ null} + advancedOffered={false} + conditionId={step.kind === 'edit' ? step.id : undefined} + testId="phone-filter-step" + /> +
+ ); + } else if (applied.length === 0) { + body = ( +
+

{t('listConditions.phone.filterEmpty')}

+ +
+ ); + } else { + body = ( +
+
+ {applied.map((row) => { + const field = fields.find((f) => f.value === row.field); + const label = field?.label ?? row.field; + return ( +
+ + + + + + + setStep({ kind: 'edit', id: row.id })} data-testid="phone-filter-item-edit"> + {t('listConditions.phone.edit')} + + setStaged((current) => removeCondition(current, row.id))} + data-testid="phone-filter-item-remove" + > + {t('listConditions.phone.remove')} + + + +
+ ); + })} +
+ +
+ ); + } + + return ( + { + // An untouched copy (and the advanced-filter notice, which edits + // nothing) is still the list's own value: nothing to write. + if (staged !== value) onApply(staged); + onOpenChange(false); + }} + onBack={step.kind === 'list' || !independent ? undefined : toList} + testId="phone-filter-panel" + > + {body} + + ); +}