From 87db6914304e97cdaca83489a442274609925f51 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 06:44:42 +0000 Subject: [PATCH 01/11] =?UTF-8?q?feat(list):=20phone=20list=20toolbar,=20b?= =?UTF-8?q?ottom-sheet=20sort/filter/view=20panels=20that=20apply=20on=20?= =?UTF-8?q?=E2=9C=93,=20long-press=20selection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Below `sm` the object list keeps its desktop content and changes its containers: the app bar's row becomes the page's own (‹, icon and name, ⋮ More with Select), one row of pills (view switcher, Sort N, Filter N, Search), and the sort, filter, view switcher and View settings panels open as bottom sheets. The sort and filter sheets stage a copy and hand it to the desktop's own writes on ✓; × drops it. SortBuilder gains a stacked layout and touch reorder. A long press on a card, or Select, starts a card selection shown in the page's selection bar. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- .changeset/35883-phone-list-toolbar-panels.md | 27 + .../app-shell/src/layout/AppHeader.tsx | 16 +- .../app-shell/src/layout/ConsoleLayout.tsx | 4 + .../app-shell/src/layout/PhonePageBar.tsx | 116 ++++ .../app-shell/src/views/ObjectView.tsx | 44 +- .../src/views/objectViewPageHeader.tsx | 47 +- .../src/views/objectViewSwitcherMenu.tsx | 44 +- .../src/views/objectViewTitleSwitcher.tsx | 101 +++- .../components/src/custom/sort-builder.tsx | 276 ++++++++-- ui/packages/i18n/src/locales/ar.ts | 17 + ui/packages/i18n/src/locales/de.ts | 17 + ui/packages/i18n/src/locales/en.ts | 17 + ui/packages/i18n/src/locales/es.ts | 17 + ui/packages/i18n/src/locales/fr.ts | 17 + ui/packages/i18n/src/locales/ja.ts | 17 + ui/packages/i18n/src/locales/ko.ts | 17 + ui/packages/i18n/src/locales/pt-BR.ts | 17 + ui/packages/i18n/src/locales/ru.ts | 17 + ui/packages/i18n/src/locales/zh-Hans.ts | 17 + ui/packages/i18n/src/locales/zh-Hant.ts | 17 + ui/packages/plugin-grid/src/ObjectGrid.tsx | 138 ++++- .../__tests__/cardSelection-35883.test.tsx | 151 ++++++ ui/packages/plugin-grid/src/index.tsx | 2 +- .../plugin-grid/src/listPageBarSlot.ts | 51 ++ ui/packages/plugin-list/src/ListView.tsx | 371 ++++++++----- .../ListView.phonePanels-35884.test.tsx | 223 ++++++++ .../ListView.phoneSortSearch-28911.test.tsx | 3 +- .../ListView.phoneWidth-29074.test.tsx | 11 +- .../src/conditions/ListConditionControls.tsx | 15 +- .../src/conditions/conditionTranslations.ts | 12 + ui/packages/plugin-list/src/index.tsx | 5 + .../plugin-list/src/phone/PhoneListPanels.tsx | 495 ++++++++++++++++++ 32 files changed, 2092 insertions(+), 247 deletions(-) create mode 100644 .changeset/35883-phone-list-toolbar-panels.md create mode 100644 ui/packages/app-shell/src/layout/PhonePageBar.tsx create mode 100644 ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx create mode 100644 ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx create mode 100644 ui/packages/plugin-list/src/phone/PhoneListPanels.tsx diff --git a/.changeset/35883-phone-list-toolbar-panels.md b/.changeset/35883-phone-list-toolbar-panels.md new file mode 100644 index 00000000000..551a9429c8e --- /dev/null +++ b/.changeset/35883-phone-list-toolbar-panels.md @@ -0,0 +1,27 @@ +--- +'@object-ui/components': patch +'@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」, 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, 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. +- 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. The selection shows in the page's selection bar. + +New exports and props: + +- `@object-ui/components`: `SortBuilder` takes `layout?: 'rows' | 'stacked'`, `onAddLevel` and `onChangeLevelField`; its handle reorders by touch in both layouts. +- `@object-ui/plugin-list`: `PhonePanelSheet`, `useListPhonePanels`, `PHONE_CHIP`, `PHONE_CHIP_ACTIVE` and the types `PhonePanelSheetProps`, `ListPhonePanels`; `FilterPanel` takes `advancedOffered`. +- `@object-ui/plugin-grid`: `requestListSelection` and `useListPageSelecting`. + +`@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/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index 4f45e1dd8f0..206688ab2cf 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'; @@ -458,6 +459,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 @@ -984,7 +990,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 @@ -1080,7 +1087,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 @@ -1262,7 +1270,7 @@ export function AppHeader({
{/* Group 3: Account (theme + lang moved into avatar dropdown) */} -
{/* User Profile + Organization switcher */} +
{/* User Profile + Organization switcher */} + {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 35b35b5071e..b1662518ca6 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 { useListViewFavorites, type ListViewFavorites } from '../layout/listViewFavorites.js'; @@ -51,7 +52,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']; @@ -152,6 +153,82 @@ 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 ( @@ -194,23 +271,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/custom/sort-builder.tsx b/ui/packages/components/src/custom/sort-builder.tsx index dcf0479ba11..c2541040174 100644 --- a/ui/packages/components/src/custom/sort-builder.tsx +++ b/ui/packages/components/src/custom/sort-builder.tsx @@ -7,13 +7,20 @@ */ import * as React from "react" -import { X, Plus, GripVertical } from "lucide-react" +import { X, Plus, GripVertical, MoreHorizontal, Check } from "lucide-react" import { createSafeTranslation } from "@object-ui/i18n" import type { SortItem as SpecSortItem } from "@objectstack/spec/shared" import { cn } from "../lib/utils" import { Button } from "../ui/button" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "../ui/dropdown-menu" const useSafeSortTranslation = createSafeTranslation( { @@ -27,6 +34,8 @@ const useSafeSortTranslation = createSafeTranslation( 'sortBuilder.addSort': 'Add sort', 'sortBuilder.removeSort': 'Remove sort', 'sortBuilder.reorder': 'Drag to reorder', + 'sortBuilder.levelOptions': 'Options for {{label}}', + 'sortBuilder.changeField': 'Change field', }, 'sortBuilder.sortBy', ) @@ -72,6 +81,25 @@ export interface SortBuilderProps { value?: SortItem[]; onChange?: (value: SortItem[]) => void; className?: string; + /** + * How a level is drawn (objectstack#35884). `rows` (the default): one line + * of selects per level. `stacked`: the phone panel's form, two lines per + * level (the field, then its direction) with the handle at the left and a + * 「⋯」 at the right that changes the field, the direction or removes the + * level; 「Add sort」 is a dashed button under the levels. The levels, their + * order, the one-row-per-field rule and every write are the same in both. + */ + layout?: 'rows' | 'stacked'; + /** + * The host draws the field choice for a new level (the phone panel's field + * list step). Absent ⇒ 「Add sort」 adds a level on the first field it may. + */ + onAddLevel?: () => void; + /** + * `stacked` only: the host draws the field choice for the level `id` + * (its 「⋯」 → 「Change field」). Absent ⇒ the menu does not offer it. + */ + onChangeLevelField?: (id: string) => void; } export function SortBuilder({ @@ -79,6 +107,9 @@ export function SortBuilder({ value = [], onChange, className, + layout = 'rows', + onAddLevel, + onChangeLevelField, }: SortBuilderProps) { const { t } = useSafeSortTranslation() // Normalize incoming items: ensure every row has an `id` (React key) and @@ -162,9 +193,191 @@ export function SortBuilder({ return moved.id; }; + // objectstack#35884 — a touch has no HTML5 drag: a finger on the handle + // moves its level by pointer events instead. The level under the finger is + // where it lands; lifting the finger moves it there. + const rowsRef = React.useRef(null); + const [touchDrag, setTouchDrag] = React.useState<{ from: number; over: number } | null>(null); + const indexAt = (clientY: number): number => { + const rows = Array.from(rowsRef.current?.querySelectorAll('[data-testid="sort-builder-row"]') ?? []); + for (let i = 0; i < rows.length; i += 1) { + const rect = rows[i].getBoundingClientRect(); + if (clientY < rect.top + rect.height / 2) return i; + } + return Math.max(0, rows.length - 1); + }; + const touchHandlers = (index: number) => ({ + onPointerDown: (event: React.PointerEvent) => { + if (event.pointerType === 'mouse' || items.length < 2) return; + event.preventDefault(); + event.currentTarget.setPointerCapture?.(event.pointerId); + setTouchDrag({ from: index, over: index }); + }, + onPointerMove: (event: React.PointerEvent) => { + if (!touchDrag) return; + const over = indexAt(event.clientY); + if (over !== touchDrag.over) setTouchDrag({ from: touchDrag.from, over }); + }, + onPointerUp: () => { + if (!touchDrag) return; + moveItem(touchDrag.from, touchDrag.over); + setTouchDrag(null); + }, + onPointerCancel: () => setTouchDrag(null), + }); + + const fieldLabel = (field: string) => fields.find((f) => f.value === field)?.label ?? field; + + // The handle, one control for both layouts: mouse drag (HTML5), touch drag + // (pointer events), and ArrowUp / ArrowDown when focused. + const renderHandle = (item: SortItem, index: number, className?: string) => ( + // A `span`, not a ` + + + {onChangeLevelField && ( + onChangeLevelField(item.id)} data-testid="sort-builder-row-change-field"> + {t('sortBuilder.changeField')} + + )} + {(['asc', 'desc'] as const).map((order) => ( + updateItem(item.id, { order })} + data-testid={`sort-builder-row-order-${order}`} + > + + ))} + + removeItem(item.id)} + data-testid="sort-builder-row-remove" + > + {t('sortBuilder.removeSort')} + + + +
+ ); + })} +
+ +
+ ); + } + return (
-
+
{items.map((item, index) => { const direction = directionLabels(item.field); return ( @@ -172,59 +385,14 @@ export function SortBuilder({ // the words, then the field beside Remove, then the direction.
{ - if (dragFrom.current === null) return; - event.preventDefault(); - event.stopPropagation(); - }} - onDrop={(event) => { - if (dragFrom.current === null) return; - event.preventDefault(); - event.stopPropagation(); - moveItem(dragFrom.current, index); - dragFrom.current = null; - }} + {...rowDropHandlers(index)} > - {/* A `span`, not a ` +
+ ) : ( + + )) : 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('SortBuilder, stacked layout (objectstack#35884)', () => { + const FIELDS = [ + { value: 'name', label: 'Name' }, + { value: 'amount', label: 'Amount' }, + ]; + + it('each level is two lines, the field over its direction', () => { + render(); + 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('Z → A'); + }); + + it('a finger on the handle moves a level: dropped over the first, the second leads', () => { + const onChange = vi.fn(); + render( + , + ); + 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(onChange).toHaveBeenCalledTimes(1); + expect(onChange.mock.calls[0][0].map((level: { field: string }) => level.field)).toEqual(['amount', 'name']); + }); +}); 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 a0bf4ab900b..d6a053ba2ae 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..1b5c5465217 100644 --- a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -16,6 +16,18 @@ 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': 'Sort, {{count}} levels', + 'listConditions.phone.filterCount': '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', 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..36591ab13fb --- /dev/null +++ b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx @@ -0,0 +1,495 @@ +/** + * 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`: `SortBuilder`'s `stacked` layout (the desktop's every-level + * sort panel, objectstack#35876) for the levels, `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, + DropdownMenuTrigger, + SortBuilder, + type FilterBuilderRowGroup, + type SortItem, +} from '@object-ui/components'; +import type { DataSource } from '@object-ui/types'; +import { ArrowUpDown, Check, ChevronLeft, 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; +} + +export function PhonePanelSheet({ open, onOpenChange, title, onApply, onBack, children, testId = 'phone-panel' }: PhonePanelSheetProps) { + const { t } = useListConditionTranslation(); + return ( + + +
+ {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 +// --------------------------------------------------------------------------- + +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 SortBuilderFields = React.ComponentProps['fields']; + +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 { + body = ( + setStep({ kind: 'add' })} + onChangeLevelField={(id) => setStep({ kind: 'field', id })} + /> + ); + } + + return ( + { + 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 ( + { + onApply(staged); + onOpenChange(false); + }} + onBack={step.kind === 'list' || !independent ? undefined : toList} + testId="phone-filter-panel" + > + {body} + + ); +} From 2a84bd7c994bf56674b1b50c7b5a29e1fb632568 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 07:48:54 +0000 Subject: [PATCH 02/11] fix(list): the phone view pill gives the name the room the pills leave; e2e pins follow the phone toolbar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The view switcher's phone pill draws the view's name and count with no type icon, and its slot loses the 55% cap, so 「All Customers」 stays whole at 375. The #33833 geometry pin now measures the phone pill row, and the #35548 source-order check reads the desktop trigger. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- ui/e2e/list-frame-geometry-35548.spec.ts | 4 +- ui/e2e/list-toolbar-view-name-phone.spec.ts | 230 +++++++----------- .../src/views/objectViewTitleSwitcher.tsx | 7 +- .../plugin-list/src/phone/PhoneListPanels.tsx | 2 +- 4 files changed, 89 insertions(+), 154 deletions(-) diff --git a/ui/e2e/list-frame-geometry-35548.spec.ts b/ui/e2e/list-frame-geometry-35548.spec.ts index da3e45ed67d..8faff683f64 100644 --- a/ui/e2e/list-frame-geometry-35548.spec.ts +++ b/ui/e2e/list-frame-geometry-35548.spec.ts @@ -105,7 +105,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/views/objectViewTitleSwitcher.tsx b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx index b1662518ca6..2bba6d0ad2b 100644 --- a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx +++ b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx @@ -191,11 +191,8 @@ export function ObjectViewTitleSwitcher({ onClick={() => setOpen(true)} className={cn(PHONE_CHIP, 'max-w-full justify-start text-foreground', open && 'bg-muted')} > - {ActiveIcon && ( - - )} + {/* The view's name and its count, as the card draws it: no type icon, so a + name keeps the room the three pills beside it leave. */} {activeLabel} {count !== null && ( diff --git a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx index 36591ab13fb..1ea8c135ccf 100644 --- a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx +++ b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx @@ -135,7 +135,7 @@ export function PhoneListToolbar({ data-testid="phone-list-toolbar" > {lead != null && ( -
+
{lead}
)} From 18a5ad346172170daab8fc2bad2f1e5db50250f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:08:19 +0000 Subject: [PATCH 03/11] fix(grid): a phone card is a keyboard control: role button, focus, Enter and Space The click census (objectui#13461) froze the card list as a clickable div without a keyboard path. The card now takes `role="button"`, `tabIndex={0}` and Enter / Space (its own key only), reports `aria-pressed` while selecting, and leaves the census backlog. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- .../clickableNonControlCensus-13461.test.ts | 2 -- ui/packages/plugin-grid/src/ObjectGrid.tsx | 15 +++++++++++++- .../__tests__/cardSelection-35883.test.tsx | 20 ++++++++++++++++--- 3 files changed, 31 insertions(+), 6 deletions(-) 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/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index f4f607ee9a4..90d8ab88a61 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -3991,7 +3991,12 @@ export const ObjectGrid: React.FC = ({ key={row.id || row._id || idx} data-testid="grid-mobile-card" data-selected={cardSelected || undefined} - aria-selected={cardSelecting ? cardSelected : undefined} + // A control (objectui#13461): a button cannot hold the card's cells, + // so the card takes the role, the focus and Enter / Space itself. + // While selecting it is a toggle (`aria-pressed`). + role="button" + tabIndex={0} + aria-pressed={cardSelecting ? cardSelected : undefined} // A row the host says opens nothing (`rowOpensRecord: false`) draws // no pointer and no hover wash on its card either (objectstack#33548). className={cn( @@ -4034,6 +4039,14 @@ export const ObjectGrid: React.FC = ({ 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 && ( { fireEvent.pointerUp(acme); fireEvent.click(acme); expect(onRowClick).not.toHaveBeenCalled(); - expect(acme).toHaveAttribute('aria-selected', 'true'); + expect(acme).toHaveAttribute('aria-pressed', 'true'); expect(onRowSelect).toHaveBeenLastCalledWith([expect.objectContaining({ id: 'a1' })]); const globex = await cardOf('Globex'); - expect(globex).toHaveAttribute('aria-selected', 'false'); + expect(globex).toHaveAttribute('aria-pressed', 'false'); expect(within(globex).getByTestId('grid-card-check')).toBeInTheDocument(); fireEvent.click(globex); expect(onRowSelect).toHaveBeenLastCalledWith([ @@ -134,10 +134,24 @@ describe('card list selection on a phone (objectstack#35883)', () => { 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-selected', 'false'); + expect(card).toHaveAttribute('aria-pressed', 'false'); } }); + 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'); From 962255750c78c6b34acdbe8ec42b02747aab76d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:12:36 +0000 Subject: [PATCH 04/11] fix(i18n): the phone Sort and Filter counts are i18next count families `listConditions.phone.sortCount` / `.filterCount` interpolate `{{count}}`, so each is a family with every CLDR slot its pack selects (objectui#11445) and a base key, in every pack and in the English fallbacks. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- ui/packages/i18n/src/locales/ar.ts | 14 +++++++++++++- ui/packages/i18n/src/locales/de.ts | 4 ++++ ui/packages/i18n/src/locales/en.ts | 4 ++++ ui/packages/i18n/src/locales/es.ts | 6 ++++++ ui/packages/i18n/src/locales/fr.ts | 6 ++++++ ui/packages/i18n/src/locales/ja.ts | 4 ++++ ui/packages/i18n/src/locales/ko.ts | 4 ++++ ui/packages/i18n/src/locales/pt-BR.ts | 6 ++++++ ui/packages/i18n/src/locales/ru.ts | 8 ++++++++ ui/packages/i18n/src/locales/zh-Hans.ts | 4 ++++ ui/packages/i18n/src/locales/zh-Hant.ts | 4 ++++ .../src/conditions/conditionTranslations.ts | 6 ++++-- 12 files changed, 67 insertions(+), 3 deletions(-) diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index d9112142c87..12627b7784c 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5533,8 +5533,20 @@ const ar = { listConditions: { phone: { toolbar: 'أدوات القائمة', - sortCount: 'الفرز، {{count}} مستويات', + 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: 'إغلاق', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 36dbfe42b46..1d68322c2fd 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4948,7 +4948,11 @@ const de = { 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', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index a35094dde3f..b4d4b1d601f 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5703,7 +5703,11 @@ const en = { 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', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f9328de8c54..0d95100b472 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -5095,7 +5095,13 @@ const es = { 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', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 5b259f8aedd..1b38aeba0d1 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -5091,7 +5091,13 @@ const fr = { 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', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 08b272c9da1..67ff88fd123 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4950,7 +4950,11 @@ const ja = { phone: { toolbar: 'リストツール', sortCount: '並べ替え({{count}} 段階)', + sortCount_one: '並べ替え({{count}} 段階)', + sortCount_other: '並べ替え({{count}} 段階)', filterCount: '絞り込み({{count}} 件)', + filterCount_one: '絞り込み({{count}} 件)', + filterCount_other: '絞り込み({{count}} 件)', back: '戻る', discard: '変更を破棄', close: '閉じる', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 62ab51b33af..6ee3b2e171c 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4947,7 +4947,11 @@ const ko = { phone: { toolbar: '목록 도구', sortCount: '정렬, {{count}}단계', + sortCount_one: '정렬, {{count}}단계', + sortCount_other: '정렬, {{count}}단계', filterCount: '필터, {{count}}개', + filterCount_one: '필터, {{count}}개', + filterCount_other: '필터, {{count}}개', back: '뒤로', discard: '변경 취소', close: '닫기', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 30e61658d00..34255ffb07d 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -5090,7 +5090,13 @@ const pt = { 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', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index b84dbfe6e15..a2b90d194d3 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -5251,7 +5251,15 @@ const ru = { 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: 'Закрыть', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index c0619882624..1ab8df10f7c 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5007,7 +5007,11 @@ const zh = { phone: { toolbar: '列表工具', sortCount: '排序,{{count}} 级', + sortCount_one: '排序,{{count}} 级', + sortCount_other: '排序,{{count}} 级', filterCount: '筛选,{{count}} 个', + filterCount_one: '筛选,{{count}} 个', + filterCount_other: '筛选,{{count}} 个', back: '返回', discard: '放弃改动', close: '关闭', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 508d993cc47..b5d2a7b9503 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5007,7 +5007,11 @@ const zhHant = { phone: { toolbar: '列表工具', sortCount: '排序,{{count}} 級', + sortCount_one: '排序,{{count}} 級', + sortCount_other: '排序,{{count}} 級', filterCount: '篩選,{{count}} 個', + filterCount_one: '篩選,{{count}} 個', + filterCount_other: '篩選,{{count}} 個', back: '返回', discard: '放棄改動', close: '關閉', diff --git a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts index 1b5c5465217..a4ba2acc7b0 100644 --- a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -17,8 +17,10 @@ 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': 'Sort, {{count}} levels', - 'listConditions.phone.filterCount': 'Filter, {{count}} in use', + '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', From ad6e39cc0e753296a8570463b02f14ada299434a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 10:01:29 +0000 Subject: [PATCH 05/11] test(app-shell): the phone FAB pin pays the lint package's first load at collection The page's draft bar reaches `import('@objectstack/lint')` inside a function, so the new test imports it at module top, as check:test-source-alias asks. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- .../src/views/ObjectView.phoneFabSelecting-35883.test.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ui/packages/app-shell/src/views/ObjectView.phoneFabSelecting-35883.test.tsx b/ui/packages/app-shell/src/views/ObjectView.phoneFabSelecting-35883.test.tsx index c31ccb64e9f..7672c1b265b 100644 --- a/ui/packages/app-shell/src/views/ObjectView.phoneFabSelecting-35883.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.phoneFabSelecting-35883.test.tsx @@ -22,6 +22,9 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, cleanup, screen, fireEvent } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; +// The page's draft bar reaches `import('@objectstack/lint')` inside a function; +// its first load is paid here, at collection, not in a clocked case. +import '@objectstack/lint'; /** Controllable principal verdict, keyed by action (`can()` is permissive by default). */ let principal: Record = {}; From 7bea6cb0ea90a090b8d279f763ac06f7066753f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 11:12:06 +0000 Subject: [PATCH 06/11] =?UTF-8?q?fix(list):=20phone=20=E3=80=8CSelect?= =?UTF-8?q?=E3=80=8D=20only=20where=20it=20opens=20a=20selection;=20sheets?= =?UTF-8?q?=20stand=20on=20the=20keyboard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ⋮ More offers 「Select」 only while the page's grid says a request would open a selection (cards whose rows take more than one tick), through a new usePublishListSelectable / useListPageSelectable pair in listPageScope. - PhonePanelSheet reads visualViewport while open: with the on-screen keyboard up its bottom is the keyboard's top and its height the visible area's less the top strip; vaul's own repositionInputs is off. - 「✓」 on an untouched sort or filter copy writes nothing. - The changeset drops FilterPanel.advancedOffered (not a package export). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- .changeset/35883-phone-list-toolbar-panels.md | 8 +- ...bjectView.phoneFabSelecting-35883.test.tsx | 63 ++++++++++++--- .../app-shell/src/views/ObjectView.tsx | 8 +- ui/packages/plugin-grid/src/ObjectGrid.tsx | 10 ++- .../__tests__/cardSelection-35883.test.tsx | 24 +++++- ui/packages/plugin-grid/src/index.tsx | 2 +- ui/packages/plugin-grid/src/listPageScope.ts | 37 +++++++++ .../ListView.phonePanels-35884.test.tsx | 79 +++++++++++++++++++ .../plugin-list/src/phone/PhoneListPanels.tsx | 49 +++++++++++- 9 files changed, 257 insertions(+), 23 deletions(-) diff --git a/.changeset/35883-phone-list-toolbar-panels.md b/.changeset/35883-phone-list-toolbar-panels.md index fa8f0893109..05453be4a84 100644 --- a/.changeset/35883-phone-list-toolbar-panels.md +++ b/.changeset/35883-phone-list-toolbar-panels.md @@ -13,15 +13,15 @@ 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」, the object's description, Import and the favorite. +- 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, 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. +- 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, 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 Space toggles it. New exports and props: - `@object-ui/components`: `SortBuilder` takes `layout?: 'rows' | 'stacked'`, `onAddLevel` and `onChangeLevelField`; its handle reorders by touch in both layouts. -- `@object-ui/plugin-list`: `PhonePanelSheet`, `useListPhonePanels`, `PHONE_CHIP`, `PHONE_CHIP_ACTIVE` and the types `PhonePanelSheetProps`, `ListPhonePanels`; `FilterPanel` takes `advancedOffered`. -- `@object-ui/plugin-grid`: `requestListSelection` and `useListPageSelecting`; `BulkActionBar` takes `open` (show 「0 selected ×」 with no actions while a host's selection is open and empty). +- `@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/packages/app-shell/src/views/ObjectView.phoneFabSelecting-35883.test.tsx b/ui/packages/app-shell/src/views/ObjectView.phoneFabSelecting-35883.test.tsx index 7672c1b265b..a9f30b08286 100644 --- a/ui/packages/app-shell/src/views/ObjectView.phoneFabSelecting-35883.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.phoneFabSelecting-35883.test.tsx @@ -17,6 +17,11 @@ * `listPageScope.ts`, the same module the page reads through the vitest * alias). What the real grid publishes is plugin-grid's pin * (`cardSelection-35883.test.tsx`). + * + * The same stand-in pins the phone's 「⋮ More」 → 「Select」: it is offered only + * while the list says a request would open a selection + * (`usePublishListSelectable`), so a kanban, a calendar or a list with no or + * single selection never shows an item that does nothing. */ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -49,6 +54,13 @@ vi.mock('@object-ui/permissions', async (importOriginal) => { }; }); +/** The page's phone verdict; the 「+」 case runs at the default (desktop) width. */ +let phoneViewport = false; +vi.mock('../hooks/usePhoneViewport.js', async (importOriginal) => ({ + ...(await importOriginal>()), + usePhoneViewport: () => phoneViewport, +})); + vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), @@ -93,6 +105,7 @@ vi.mock('./MetadataInspector', () => ({ vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null })); import { ObjectView } from './ObjectView'; +import { PhonePageBarProvider, PhonePageBarEnd } from '../layout/PhonePageBar'; import { ExpressionProvider } from '../providers/ExpressionProvider'; const OBJECT_NAME = 'showcase_project'; @@ -125,29 +138,35 @@ function makeDataSource() { async function renderList(objects: any[]) { render( - - - {}} />} - /> - - + + + + + {}} />} + /> + + + , ); return screen.findByTestId('card-scroller-stand-in'); } -import { usePublishListSelecting } from '../../../plugin-grid/src/listPageScope'; +import { usePublishListSelectable, usePublishListSelecting } from '../../../plugin-grid/src/listPageScope'; function CardListStandIn() { const [root, setRoot] = React.useState(null); const [selecting, setSelecting] = React.useState(false); + const [selectable, setSelectable] = React.useState(false); usePublishListSelecting(root, selecting); + usePublishListSelectable(root, selectable); return (
); } @@ -156,6 +175,7 @@ const fab = () => document.querySelector('[data-testid="mobile-fab-create"]'); beforeEach(() => { principal = {}; + phoneViewport = false; }); afterEach(() => cleanup()); @@ -172,3 +192,28 @@ describe('the phone 「+」 while cards are selected (objectstack#35883)', () => 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 332ac3a71b6..da4bc608705 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -25,7 +25,7 @@ import { ObjectView as PluginObjectView, ManageViewsDialog } from '@object-ui/pl // Do NOT add eager `import '@object-ui/plugin-*'` side-effect imports here. import { CheckSquare, Plus } from 'lucide-react'; import { DropdownMenuItem } from '@object-ui/components'; -import { requestListSelection, useListPageSelecting } from '@object-ui/plugin-grid'; +import { requestListSelection, useListPageSelectable, useListPageSelecting } from '@object-ui/plugin-grid'; import { getIcon } from '../utils/getIcon.js'; import { usePublishPhonePageBar } from '../layout/PhonePageBar.js'; import { useObjectListFavorite } from '../layout/SidebarItemMenu.js'; @@ -1244,6 +1244,10 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // 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 ? { icon: createElement(getIcon((objectDef as any)?.icon), { className: 'h-5 w-5' }), @@ -1256,7 +1260,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co importDisabled={importDisabled} listFavorite={listFavorite} triggerClassName="h-11 w-11 px-0 shadow-none" - leading={titleSwitcher ? ( + leading={listSelectable ? ( requestListSelection(pageColumnEl)} data-testid="object-view-select"> {t('console.objectView.select', { defaultValue: 'Select' })} diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index db3c12e2f87..0dff1255c95 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -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, useListSelectionRequest, usePublishListSelecting } 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'; @@ -1675,13 +1675,17 @@ export const ObjectGrid: React.FC = ({ // 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 (rowsSelectable && !singleSelection) setCardSelecting(true); - }, [selectionRequest, rowsSelectable, singleSelection]); + 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 }>({ diff --git a/ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx b/ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx index bca42f5a51e..4c815f760a3 100644 --- a/ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx @@ -16,6 +16,9 @@ * - The page's 「Select」 (`requestListSelection` on the page column) starts * the selection with nothing ticked. * + * - The page offers 「Select」 only where it would open a selection + * (`useListPageSelectable`): cards whose rows take more than one tick. + * * Pinned at 390 px, the card layout (see `phoneCardRow-28484.test.tsx`). */ import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; @@ -24,7 +27,7 @@ import '@testing-library/jest-dom'; import React from 'react'; import { ObjectGrid } from '../ObjectGrid'; -import { requestListSelection } from '../listPageScope'; +import { requestListSelection, useListPageSelectable } from '../listPageScope'; import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; import { registerAllFields } from '@object-ui/fields'; @@ -181,4 +184,23 @@ describe('card list selection on a phone (objectstack#35883)', () => { 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/index.tsx b/ui/packages/plugin-grid/src/index.tsx index 3f4450b4907..9c81199f3a2 100644 --- a/ui/packages/plugin-grid/src/index.tsx +++ b/ui/packages/plugin-grid/src/index.tsx @@ -40,7 +40,7 @@ export { BulkActionBar } from './components/SelectionBar'; // objectstack#35678 — the list page's scope, registered by the Console's page // bars, and the kept scroll position a list host loads back to. // objectstack#35883 — the phone's 「Select」 and whether a selection is open. -export { useListPageScope, requestListSelection, useListPageSelecting } from './listPageScope'; +export { useListPageScope, requestListSelection, useListPageSelecting, useListPageSelectable } from './listPageScope'; export { readListScrollState } from './objectGridInfiniteLoad'; export type { ListScrollState } from './objectGridInfiniteLoad'; // The bare-name fold, its development warning and the bar's own gate (the diff --git a/ui/packages/plugin-grid/src/listPageScope.ts b/ui/packages/plugin-grid/src/listPageScope.ts index 05570142320..c8f3ebc0fbe 100644 --- a/ui/packages/plugin-grid/src/listPageScope.ts +++ b/ui/packages/plugin-grid/src/listPageScope.ts @@ -137,3 +137,40 @@ export function useListPageSelecting(scope: HTMLElement | null): boolean { () => 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/__tests__/ListView.phonePanels-35884.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx index 1db1590e5a6..63bc0b3ce94 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx @@ -17,6 +17,10 @@ * `onFilterChange`); 「×」 drops the copy. * - An advanced filter (an 「or」 group) is not edited on a phone: the panel * says so. + * - 「✓」 on an untouched copy writes nothing. + * - With the on-screen keyboard up (the visual viewport shorter than the + * layout one), the sheet stands on the keyboard: its bottom is the + * keyboard's top and its height the visible area's, less the top strip. * * "Below `sm`" is `matchMedia('(max-width: 639.98px)')` answering a match, the * one query `useBelowSm` asks. Provider-less, so `t()` reads the English @@ -186,6 +190,81 @@ describe('phone filter panel (objectstack#35884)', () => { }); }); +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('SortBuilder, stacked layout (objectstack#35884)', () => { const FIELDS = [ { value: 'name', label: 'Name' }, diff --git a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx index 1ea8c135ccf..6e3d5e7e9fb 100644 --- a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx +++ b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx @@ -200,13 +200,53 @@ export interface PhonePanelSheetProps { 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. +
@@ -346,7 +386,8 @@ export function PhoneSortSheet({ open, onOpenChange, fields, shownFields, value, onOpenChange={onOpenChange} title={t('listConditions.chips.sort')} onApply={() => { - onApply(staged.filter((level) => level.field)); + // 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)} @@ -483,7 +524,9 @@ export function PhoneFilterSheet({ open, onOpenChange, fields, shownFields, valu onOpenChange={onOpenChange} title={t('listConditions.chips.filter')} onApply={() => { - onApply(staged); + // 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} From 92e74834f456ffefcdf0d92c35e11238012fe530 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 13:02:42 +0000 Subject: [PATCH 07/11] fix(list): a fresh press on a card never inherits the last long press's swallow flag Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- .changeset/35883-phone-list-toolbar-panels.md | 2 +- ui/packages/plugin-grid/src/ObjectGrid.tsx | 5 ++++- .../__tests__/cardSelection-35883.test.tsx | 20 +++++++++++++++++++ ui/packages/plugin-grid/src/listPageScope.ts | 2 ++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/.changeset/35883-phone-list-toolbar-panels.md b/.changeset/35883-phone-list-toolbar-panels.md index 05453be4a84..4e720ea5111 100644 --- a/.changeset/35883-phone-list-toolbar-panels.md +++ b/.changeset/35883-phone-list-toolbar-panels.md @@ -16,7 +16,7 @@ At phone width (below `sm`) the console's object list changes its containers, no - 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, 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 Space toggles it. +- 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: diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 0dff1255c95..6c33d97641c 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -4129,9 +4129,12 @@ export const ObjectGrid: React.FC = ({ cardSelected && 'border-primary bg-primary/5', )} onPointerDown={(event) => { - if (!cardsSelectable || cardSelecting) return; 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); diff --git a/ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx b/ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx index 4c815f760a3..d712d033a82 100644 --- a/ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/cardSelection-35883.test.tsx @@ -120,6 +120,26 @@ describe('card list selection on a phone (objectstack#35883)', () => { 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'); diff --git a/ui/packages/plugin-grid/src/listPageScope.ts b/ui/packages/plugin-grid/src/listPageScope.ts index c8f3ebc0fbe..90f4af7c31b 100644 --- a/ui/packages/plugin-grid/src/listPageScope.ts +++ b/ui/packages/plugin-grid/src/listPageScope.ts @@ -89,6 +89,8 @@ const selectRequests = new Map(); */ 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(); } From f6a0264d11d9da9b38d1d7f8c32c13f701df909b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 13:36:46 +0000 Subject: [PATCH 08/11] feat(app-shell): the phone list's top row draws the object's colour tile Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- ui/packages/app-shell/src/views/ObjectView.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index e50366f6b10..0c7a8e31a3d 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -12,7 +12,7 @@ import type { ColumnSummary } from '@objectstack/spec/ui'; import type { ListColumn } from '@object-ui/types'; import { columnsWithSummary, declaredColumnFields } from './columnSummaryWrite.js'; -import { createElement, useMemo, useState, useCallback, useEffect, useRef, lazy, Suspense, type ReactNode } from 'react'; +import { useMemo, useState, useCallback, useEffect, useRef, lazy, Suspense, type ReactNode } from 'react'; import { useParams, useSearchParams, useNavigate, useLocation, useHref, createSearchParams } from 'react-router-dom'; import { resolveAffordance, type FilterTokenScope, type SchemaLike } from '@object-ui/core'; import { useObjectListPreferences } from '../context/ListPreferencesProvider.js'; @@ -24,9 +24,8 @@ import { ObjectView as PluginObjectView, ManageViewsDialog } from '@object-ui/pl // uses ComponentRegistry.registerLazy so heavy plugins stay code-split). // Do NOT add eager `import '@object-ui/plugin-*'` side-effect imports here. import { CheckSquare, Plus } from 'lucide-react'; -import { DropdownMenuItem } from '@object-ui/components'; +import { DropdownMenuItem, ObjectIconTile } from '@object-ui/components'; import { requestListSelection, useListPageSelectable, useListPageSelecting } from '@object-ui/plugin-grid'; -import { getIcon } from '../utils/getIcon.js'; import { usePublishPhonePageBar } from '../layout/PhonePageBar.js'; import { useObjectListFavorite } from '../layout/SidebarItemMenu.js'; import { useMetaItemRefusal } from '../hooks/useMetaItemRefusal.js'; @@ -1251,7 +1250,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co const listSelectable = useListPageSelectable(pageColumnEl); const phoneDescription = objectDef.description ? objectDesc(objectDef) : undefined; usePublishPhonePageBar(phone ? { - icon: createElement(getIcon((objectDef as any)?.icon), { className: 'h-5 w-5' }), + // The object's colour tile, as the desktop page bar draws it (objectstack#35985). + icon: , title: listTitleOf(objectDef), end: ( Date: Sat, 21 Nov 2026 14:20:20 +0000 Subject: [PATCH 09/11] refactor(list): the phone sort level's face is drawn in plugin-list, keeping the eager components chunk under its ceiling SortBuilder takes renderLevel instead of a stacked layout: the builder keeps the levels, their order, the handle (mouse, touch, keys) and every write; the phone sheet draws each level's two lines and its menu, and its own Add sort. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- .changeset/35883-phone-list-toolbar-panels.md | 2 +- .../components/src/custom/sort-builder.tsx | 160 ++++-------------- .../ListView.phonePanels-35884.test.tsx | 14 +- .../src/conditions/conditionTranslations.ts | 5 + .../plugin-list/src/phone/PhoneListPanels.tsx | 84 ++++++++- 5 files changed, 128 insertions(+), 137 deletions(-) diff --git a/.changeset/35883-phone-list-toolbar-panels.md b/.changeset/35883-phone-list-toolbar-panels.md index 4e720ea5111..0ef47fb93ae 100644 --- a/.changeset/35883-phone-list-toolbar-panels.md +++ b/.changeset/35883-phone-list-toolbar-panels.md @@ -20,7 +20,7 @@ At phone width (below `sm`) the console's object list changes its containers, no New exports and props: -- `@object-ui/components`: `SortBuilder` takes `layout?: 'rows' | 'stacked'`, `onAddLevel` and `onChangeLevelField`; its handle reorders by touch in both layouts. +- `@object-ui/components`: `SortBuilder` takes `renderLevel` (the host draws each level's face around the builder's own handle, order and writes, and 「Add sort」 itself), with the type `SortBuilderLevel`; its handle reorders by touch. - `@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). diff --git a/ui/packages/components/src/custom/sort-builder.tsx b/ui/packages/components/src/custom/sort-builder.tsx index c2541040174..1d3184e0a1c 100644 --- a/ui/packages/components/src/custom/sort-builder.tsx +++ b/ui/packages/components/src/custom/sort-builder.tsx @@ -7,20 +7,13 @@ */ import * as React from "react" -import { X, Plus, GripVertical, MoreHorizontal, Check } from "lucide-react" +import { X, Plus, GripVertical } from "lucide-react" import { createSafeTranslation } from "@object-ui/i18n" import type { SortItem as SpecSortItem } from "@objectstack/spec/shared" import { cn } from "../lib/utils" import { Button } from "../ui/button" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, - DropdownMenuTrigger, -} from "../ui/dropdown-menu" const useSafeSortTranslation = createSafeTranslation( { @@ -34,8 +27,6 @@ const useSafeSortTranslation = createSafeTranslation( 'sortBuilder.addSort': 'Add sort', 'sortBuilder.removeSort': 'Remove sort', 'sortBuilder.reorder': 'Drag to reorder', - 'sortBuilder.levelOptions': 'Options for {{label}}', - 'sortBuilder.changeField': 'Change field', }, 'sortBuilder.sortBy', ) @@ -82,24 +73,22 @@ export interface SortBuilderProps { onChange?: (value: SortItem[]) => void; className?: string; /** - * How a level is drawn (objectstack#35884). `rows` (the default): one line - * of selects per level. `stacked`: the phone panel's form, two lines per - * level (the field, then its direction) with the handle at the left and a - * 「⋯」 at the right that changes the field, the direction or removes the - * level; 「Add sort」 is a dashed button under the levels. The levels, their - * order, the one-row-per-field rule and every write are the same in both. + * The host draws each level's face itself (objectstack#35884: the phone + * sheet's two-line level) and 「Add sort」 (none is drawn). The levels, their + * order, the handle (mouse, touch, keys) and every write stay the builder's. */ - layout?: 'rows' | 'stacked'; - /** - * The host draws the field choice for a new level (the phone panel's field - * list step). Absent ⇒ 「Add sort」 adds a level on the first field it may. - */ - onAddLevel?: () => void; - /** - * `stacked` only: the host draws the field choice for the level `id` - * (its 「⋯」 → 「Change field」). Absent ⇒ the menu does not offer it. - */ - onChangeLevelField?: (id: string) => void; + renderLevel?: (level: SortBuilderLevel) => React.ReactNode; +} + +/** One level, as {@link SortBuilderProps.renderLevel} receives it. */ +export interface SortBuilderLevel { + item: SortItem; + /** The builder's reorder handle for this level. */ + handle: React.ReactNode; + /** The words for this field's two directions. */ + direction: { asc: string; desc: string }; + setOrder: (order: 'asc' | 'desc') => void; + remove: () => void; } export function SortBuilder({ @@ -107,9 +96,7 @@ export function SortBuilder({ value = [], onChange, className, - layout = 'rows', - onAddLevel, - onChangeLevelField, + renderLevel, }: SortBuilderProps) { const { t } = useSafeSortTranslation() // Normalize incoming items: ensure every row has an `id` (React key) and @@ -199,7 +186,8 @@ export function SortBuilder({ const rowsRef = React.useRef(null); const [touchDrag, setTouchDrag] = React.useState<{ from: number; over: number } | null>(null); const indexAt = (clientY: number): number => { - const rows = Array.from(rowsRef.current?.querySelectorAll('[data-testid="sort-builder-row"]') ?? []); + // The levels are the list's own children, one per level. + const rows = Array.from(rowsRef.current?.children ?? []); for (let i = 0; i < rows.length; i += 1) { const rect = rows[i].getBoundingClientRect(); if (clientY < rect.top + rect.height / 2) return i; @@ -226,9 +214,7 @@ export function SortBuilder({ onPointerCancel: () => setTouchDrag(null), }); - const fieldLabel = (field: string) => fields.find((f) => f.value === field)?.label ?? field; - - // The handle, one control for both layouts: mouse drag (HTML5), touch drag + // The handle, one control for every level face: mouse drag (HTML5), touch drag // (pointer events), and ArrowUp / ArrowDown when focused. const renderHandle = (item: SortItem, index: number, className?: string) => ( // A `span`, not a ` - - - {onChangeLevelField && ( - onChangeLevelField(item.id)} data-testid="sort-builder-row-change-field"> - {t('sortBuilder.changeField')} - - )} - {(['asc', 'desc'] as const).map((order) => ( - updateItem(item.id, { order })} - data-testid={`sort-builder-row-order-${order}`} - > - - ))} - - removeItem(item.id)} - data-testid="sort-builder-row-remove" - > - {t('sortBuilder.removeSort')} - - - -
- ); - })} -
- -
- ); - } - return (
-
+
{items.map((item, index) => { const direction = directionLabels(item.field); + const over = touchDrag && touchDrag.over === index && touchDrag.from !== index; + if (renderLevel) return ( +
+ {renderLevel({ + item, + handle: renderHandle(item, index, "h-11 w-8"), + direction, + setOrder: (order) => updateItem(item.id, { order }), + remove: () => removeItem(item.id), + })} +
+ ); return ( // Below `sm` a level takes three lines so no select cuts its label: // the words, then the field beside Remove, then the direction. @@ -387,7 +301,7 @@ export function SortBuilder({ key={item.id} className={cn( "flex items-center gap-2 max-sm:grid max-sm:grid-cols-[auto_minmax(0,1fr)_auto]", - touchDrag && touchDrag.over === index && touchDrag.from !== index && "rounded bg-accent", + over && "rounded bg-accent", )} data-testid="sort-builder-row" {...rowDropHandlers(index)} @@ -444,16 +358,16 @@ export function SortBuilder({ ); })}
- + }
); } diff --git a/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx index 63bc0b3ce94..b60ab02af44 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx @@ -265,24 +265,28 @@ describe('phone panels and the on-screen keyboard (objectstack#35884)', () => { }); }); -describe('SortBuilder, stacked layout (objectstack#35884)', () => { +describe('the phone sort level, drawn in SortBuilder (objectstack#35884)', () => { const FIELDS = [ { value: 'name', label: 'Name' }, { value: 'amount', label: 'Amount' }, ]; - it('each level is two lines, the field over its direction', () => { - render(); + 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('Z → A'); + 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', () => { const onChange = vi.fn(); render(
{level.handle}
} fields={FIELDS} value={[{ id: 'a', field: 'name', order: 'asc' }, { id: 'b', field: 'amount', order: 'desc' }]} onChange={onChange} diff --git a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts index a4ba2acc7b0..fce00b15f22 100644 --- a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -92,6 +92,11 @@ 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.removeSort': 'Remove sort', + 'sortBuilder.levelOptions': 'Options for {{label}}', + 'sortBuilder.changeField': 'Change field', }; export const useListConditionTranslation = createSafeTranslation( diff --git a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx index 6e3d5e7e9fb..09cabcb830f 100644 --- a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx +++ b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx @@ -42,8 +42,10 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, + DropdownMenuSeparator, DropdownMenuTrigger, SortBuilder, + type SortBuilderLevel, type FilterBuilderRowGroup, type SortItem, } from '@object-ui/components'; @@ -315,6 +317,55 @@ function useStaged(open: boolean, value: T, firstStep: S): [T, React.Dispa // Sort // --------------------------------------------------------------------------- +/** + * A level of the phone sort sheet, drawn inside `SortBuilder` (`renderLevel`): + * the builder's handle, the field over its direction, and a 「⋯」 that changes + * the field, the direction or removes the level. The writes are the builder's. + */ +function PhoneSortLevel({ level, label, onChangeField }: { level: SortBuilderLevel; label: string; onChangeField: () => void }) { + const { t } = useListConditionTranslation(); + const { item, direction } = level; + return ( +
+ {level.handle} +
+
{label}
+
+ {direction[item.order]} +
+
+ + + + + + + {t('sortBuilder.changeField')} + + {(['asc', 'desc'] as const).map((order) => ( + level.setOrder(order)} data-testid={`sort-builder-row-order-${order}`}> + + ))} + + + {t('sortBuilder.removeSort')} + + + +
+ ); +} + export interface PhoneSortSheetProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -368,15 +419,32 @@ export function PhoneSortSheet({ open, onOpenChange, fields, shownFields, value,
); } else { + const held = new Set(staged.map((level) => level.field)); body = ( - setStep({ kind: 'add' })} - onChangeLevelField={(id) => setStep({ kind: 'field', id })} - /> +
+ ( + field.value === level.item.field)?.label ?? level.item.field} + onChangeField={() => setStep({ kind: 'field', id: level.item.id })} + /> + )} + /> + +
); } From 74cf9d88a4e7b5714c861f9f2b2904006889a480 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:01:05 +0000 Subject: [PATCH 10/11] refactor(list): the phone sort levels live in plugin-list; SortBuilder stays as on main The eager ui-components chunk sits at its ceiling on main, so the phone's two-line level face, its touch handle and its menu are drawn by PhoneSortLevels in plugin-list over the same SortItem list. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXQEtN6Kp1wRKH6Fde --- .changeset/35883-phone-list-toolbar-panels.md | 4 +- .../components/src/custom/sort-builder.tsx | 190 +++++------------ .../ListView.phonePanels-35884.test.tsx | 32 ++- .../src/conditions/conditionTranslations.ts | 5 + .../plugin-list/src/phone/PhoneListPanels.tsx | 194 ++++++++++++------ 5 files changed, 210 insertions(+), 215 deletions(-) diff --git a/.changeset/35883-phone-list-toolbar-panels.md b/.changeset/35883-phone-list-toolbar-panels.md index 0ef47fb93ae..e0a29470538 100644 --- a/.changeset/35883-phone-list-toolbar-panels.md +++ b/.changeset/35883-phone-list-toolbar-panels.md @@ -1,5 +1,4 @@ --- -'@object-ui/components': patch '@object-ui/plugin-list': patch '@object-ui/plugin-grid': patch '@object-ui/app-shell': patch @@ -15,12 +14,11 @@ At phone width (below `sm`) the console's object list changes its containers, no - 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, 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. +- 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/components`: `SortBuilder` takes `renderLevel` (the host draws each level's face around the builder's own handle, order and writes, and 「Add sort」 itself), with the type `SortBuilderLevel`; its handle reorders by touch. - `@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). diff --git a/ui/packages/components/src/custom/sort-builder.tsx b/ui/packages/components/src/custom/sort-builder.tsx index 1d3184e0a1c..dcf0479ba11 100644 --- a/ui/packages/components/src/custom/sort-builder.tsx +++ b/ui/packages/components/src/custom/sort-builder.tsx @@ -72,23 +72,6 @@ export interface SortBuilderProps { value?: SortItem[]; onChange?: (value: SortItem[]) => void; className?: string; - /** - * The host draws each level's face itself (objectstack#35884: the phone - * sheet's two-line level) and 「Add sort」 (none is drawn). The levels, their - * order, the handle (mouse, touch, keys) and every write stay the builder's. - */ - renderLevel?: (level: SortBuilderLevel) => React.ReactNode; -} - -/** One level, as {@link SortBuilderProps.renderLevel} receives it. */ -export interface SortBuilderLevel { - item: SortItem; - /** The builder's reorder handle for this level. */ - handle: React.ReactNode; - /** The words for this field's two directions. */ - direction: { asc: string; desc: string }; - setOrder: (order: 'asc' | 'desc') => void; - remove: () => void; } export function SortBuilder({ @@ -96,7 +79,6 @@ export function SortBuilder({ value = [], onChange, className, - renderLevel, }: SortBuilderProps) { const { t } = useSafeSortTranslation() // Normalize incoming items: ensure every row has an `id` (React key) and @@ -180,133 +162,69 @@ export function SortBuilder({ return moved.id; }; - // objectstack#35884 — a touch has no HTML5 drag: a finger on the handle - // moves its level by pointer events instead. The level under the finger is - // where it lands; lifting the finger moves it there. - const rowsRef = React.useRef(null); - const [touchDrag, setTouchDrag] = React.useState<{ from: number; over: number } | null>(null); - const indexAt = (clientY: number): number => { - // The levels are the list's own children, one per level. - const rows = Array.from(rowsRef.current?.children ?? []); - for (let i = 0; i < rows.length; i += 1) { - const rect = rows[i].getBoundingClientRect(); - if (clientY < rect.top + rect.height / 2) return i; - } - return Math.max(0, rows.length - 1); - }; - const touchHandlers = (index: number) => ({ - onPointerDown: (event: React.PointerEvent) => { - if (event.pointerType === 'mouse' || items.length < 2) return; - event.preventDefault(); - event.currentTarget.setPointerCapture?.(event.pointerId); - setTouchDrag({ from: index, over: index }); - }, - onPointerMove: (event: React.PointerEvent) => { - if (!touchDrag) return; - const over = indexAt(event.clientY); - if (over !== touchDrag.over) setTouchDrag({ from: touchDrag.from, over }); - }, - onPointerUp: () => { - if (!touchDrag) return; - moveItem(touchDrag.from, touchDrag.over); - setTouchDrag(null); - }, - onPointerCancel: () => setTouchDrag(null), - }); - - // The handle, one control for every level face: mouse drag (HTML5), touch drag - // (pointer events), and ArrowUp / ArrowDown when focused. - const renderHandle = (item: SortItem, index: number, className?: string) => ( - // A `span`, not a `
- {!renderLevel && } +
); } diff --git a/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx index b60ab02af44..a7585f06815 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.phonePanels-35884.test.tsx @@ -32,7 +32,6 @@ import '@testing-library/jest-dom'; import React from 'react'; import { ComponentRegistry } from '@object-ui/core'; import { SchemaRendererProvider } from '@object-ui/react'; -import { SortBuilder } from '@object-ui/components'; import type { ListViewSchema } from '@object-ui/types'; import { ListView } from '../ListView'; @@ -265,11 +264,7 @@ describe('phone panels and the on-screen keyboard (objectstack#35884)', () => { }); }); -describe('the phone sort level, drawn in SortBuilder (objectstack#35884)', () => { - const FIELDS = [ - { value: 'name', label: 'Name' }, - { value: 'amount', label: 'Amount' }, - ]; +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(); @@ -282,16 +277,14 @@ describe('the phone sort level, drawn in SortBuilder (objectstack#35884)', () => 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', () => { - const onChange = vi.fn(); - render( -
{level.handle}
} - fields={FIELDS} - value={[{ id: 'a', field: 'name', order: 'asc' }, { id: 'b', field: 'amount', order: 'desc' }]} - onChange={onChange} - />, - ); + 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: () => ({}) }); @@ -300,7 +293,10 @@ describe('the phone sort level, drawn in SortBuilder (objectstack#35884)', () => 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(onChange).toHaveBeenCalledTimes(1); - expect(onChange.mock.calls[0][0].map((level: { field: string }) => level.field)).toEqual(['amount', 'name']); + 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']); }); }); diff --git a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts index fce00b15f22..35d7b9daef6 100644 --- a/ui/packages/plugin-list/src/conditions/conditionTranslations.ts +++ b/ui/packages/plugin-list/src/conditions/conditionTranslations.ts @@ -94,6 +94,11 @@ export const LIST_CONDITION_DEFAULT_TRANSLATIONS: Record = { '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', diff --git a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx index 09cabcb830f..2f7180049e4 100644 --- a/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx +++ b/ui/packages/plugin-list/src/phone/PhoneListPanels.tsx @@ -16,10 +16,10 @@ * 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`: `SortBuilder`'s `stacked` layout (the desktop's every-level - * sort panel, objectstack#35876) for the levels, `SortPanel` (the desktop's - * field list with the direction on top) to add one and `FieldList` to change - * a level's field. + * - `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 视图设置. @@ -44,13 +44,11 @@ import { DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, - SortBuilder, - type SortBuilderLevel, type FilterBuilderRowGroup, type SortItem, } from '@object-ui/components'; import type { DataSource } from '@object-ui/types'; -import { ArrowUpDown, Check, ChevronLeft, Info, ListFilter, MoreHorizontal, Plus, X } from 'lucide-react'; +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'; @@ -317,51 +315,139 @@ function useStaged(open: boolean, value: T, firstStep: S): [T, React.Dispa // Sort // --------------------------------------------------------------------------- +const DATE_SORT_TYPES = new Set(['date', 'datetime']); + /** - * A level of the phone sort sheet, drawn inside `SortBuilder` (`renderLevel`): - * the builder's handle, the field over its direction, and a 「⋯」 that changes - * the field, the direction or removes the level. The writes are the builder's. + * 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 PhoneSortLevel({ level, label, onChangeField }: { level: SortBuilderLevel; label: string; onChangeField: () => void }) { +function PhoneSortLevels({ fields, value, onChange, onChangeField }: { + fields: ReadonlyArray; + value: SortItem[]; + onChange: (next: SortItem[]) => void; + onChangeField: (id: string) => void; +}) { const { t } = useListConditionTranslation(); - const { item, direction } = level; + const listRef = React.useRef(null); + const [drag, setDrag] = React.useState<{ from: number; over: number } | null>(null); + 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); + }; + // 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 ( -
- {level.handle} -
-
{label}
-
- {direction[item.order]} -
-
- - - - - - - {t('sortBuilder.changeField')} - - {(['asc', 'desc'] as const).map((order) => ( - level.setOrder(order)} data-testid={`sort-builder-row-order-${order}`}> - - ))} - - - {t('sortBuilder.removeSort')} - - - + 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(); + move(index, to); + }} + 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')} + + + +
+ ); + })}
); } @@ -379,8 +465,6 @@ export interface PhoneSortSheetProps { note?: React.ReactNode; } -type SortBuilderFields = React.ComponentProps['fields']; - type SortStep = { kind: 'levels' } | { kind: 'add' } | { kind: 'field'; id: string }; export function PhoneSortSheet({ open, onOpenChange, fields, shownFields, value, onApply, note }: PhoneSortSheetProps) { @@ -422,17 +506,11 @@ export function PhoneSortSheet({ open, onOpenChange, fields, shownFields, value, const held = new Set(staged.map((level) => level.field)); body = (
- ( - field.value === level.item.field)?.label ?? level.item.field} - onChangeField={() => setStep({ kind: 'field', id: level.item.id })} - /> - )} + onChangeField={(id) => setStep({ kind: 'field', id })} />