Skip to content

Commit 847e424

Browse files
feat(console): the list title switches views from a dropdown, a pinned view opens by default, and a starred view joins the sidebar favorites (#27943)
domain:ui#2 · os-bill · session_01Utp6CY2n1JmZZKrHgtp9jC <!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgP6XkfpjCfyzzG2KwQPUZfy)_ Fixes #27594 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:对象列表的标题变成视图切换下拉「视图名 ▾ · 条数」(搜索框常在,分「📌 固定 · 最近 · 全部」三段,全部里作者视图在前、用户保存的视图在后,底部「+ 新建视图」和管理员的「管理视图」);平铺视图页签行退役;📌 让某视图成为本人打开该对象时的默认视图(按对象按人存);☆ 把视图放进侧栏「收藏」组,可拖动排序,菜单里已有的视图 ☆ 置灰并提示「已在菜单中」。 - 为什么改:每种元数据的视图数量不定,页签行五个就溢出,在 464px 的分屏列表里更挤(epic #26676 的卡)。 - 风险与回滚:只动 ui(app-shell 私有包 + i18n 十个语言包各加 7 个键 + 文档一节);不改元数据、协议、spec;收藏视图存进现有收藏库(type `view`),固定视图存本浏览器的 workspacePreference;回滚即 revert 本 PR。 - 先看:`views/objectViewTitleSwitcher.tsx`(下拉组件与组装它的 hook)、`ObjectView.tsx`(📌 默认视图的解析顺序:地址 > 固定 > 作者默认 > 第一个)、`layout/listViewFavorites.ts` 与 `layout/UnifiedSidebar.tsx`(☆ 与收藏组拖序)。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/app-shell/src/views/ObjectView.titleViewSwitcher-27594.test.tsx packages/app-shell/src/views/objectViewTitleSwitcher.test.tsx`,预期两个文件全绿。 - 需要你做的:无;epic 座位在控制台预览里验收(卡 Acceptance 3)。下方「Open question」有一处前提偏差(对象路由没有面包屑)请座位定夺。 ## What changes Measured first, on `main` at `ddab8b99`: the object list page drew its views as a flat tab row in the list's toolbar (`ViewTabBar`, handed to `ListView` as `toolbarLeading`, objectui#12440), the page header's `h1` read the object's plural, and a reader could not pin or star a view. - **The title is the view switcher.** `ObjectViewTitleSwitcher` (new, `views/objectViewTitleSwitcher.tsx`) is the page header's title: the open view's label, ▾, and `· <count>` once the list reports its total (`ListView.onTotalChange`, kept per view id). It opens a popover with a search box (always), then **📌 Pinned**, **Recent** (at most three, the pinned one excluded) and **All** (the authored views in their order, then the views saved at runtime), each row with its view-type icon and, on hover or focus, ☆ and 📌. Its foot is **+ New view** (the existing create-view flow) and, for an admin, **Manage views** (the existing dialog). A search lists the matching views flat, in All's order. The split pane's list (#27545) is the same page, so it has the same switcher; nothing is special-cased. - **The flat tab row retires.** `objectViewTabBar.tsx` is deleted; the list gets no `toolbarLeading`, and a chart view no longer draws its own tab row above the chart. The filter / sort / display controls keep their own row. - **📌 Pinned = the reader's default.** `LIST_PINNED_VIEW_PREFERENCE` (`list.view.pinned`, scope `object:NAME`) in #27052's `workspacePreference` module. A bare list address opens the pinned view, else the authored default (`isDefault`), else the first; a view in the address still wins. A pin naming a view the list no longer offers is no pin. Unpinning stores `null`. - **☆ Starred views in the sidebar's Favorites (收藏).** A star is a favorite of type `view` (id `view:OBJECT:VIEW`, href `/apps/APP/OBJECT/view/VIEW`, the object's icon) in the existing favorites store. The sidebar draws a view favorite only in the app its address names, beside the object's icon, and the section's own rows (views, records, objects, dashboards) can now be dragged into order, or moved with Space and the arrow keys, through `reorderFavorites` (`SortableFavoriteRows`, the same gesture as the pinned entries of objectui#12059). A view an app navigation entry already opens (an `object` entry with that `viewName`, as the member is shown it) shows its ☆ disabled with 「已在菜单中」 / "Already in the menu". - **The view description is shown once.** The tab row used to carry it as the active tab's tooltip. A list face now draws it through `ListView`'s own info control at the start of its toolbar row (its behaviour for a host with no leading node); a chart face, which has no toolbar row, carries it as the switcher's tooltip. - i18n: `view.switcher.{label,pinned,recent,all,pin,unpin,inMenu}` in all ten packs. Docs: `content/docs/ui/views.mdx` gains "Switching views". ### Deviations from the card, each agreed with the seat before the code - **File surface.** The card names `ui/packages/plugin-list/src/**` for the tab row → switcher. The console's tab row is drawn by app-shell (`objectViewTabBar.tsx`, `objectViewPageHeader.tsx`, `objectViewViewCrud.tsx`), so the switcher lives in app-shell (`objectViewTitleSwitcher.tsx`, new) and plugin-list is untouched. The card's `components/UnifiedSidebar.tsx` is `layout/UnifiedSidebar.tsx`. - **Where a star is stored (seat ruling B).** Target 4 says the 收藏 entry is a "reader preference, same module, scope `app:NAME`". It is stored in the existing favorites store instead (`FavoritesProvider`, the `ui.favorites` user-preference row, type `view`), filtered by the app its address names. Reason: the sidebar's 收藏 section already draws that store (objectui#12427), so a second store would split one section into two lists with two orders, and the favorites row follows the reader across devices where `workspacePreference` is this browser's. - **Recent** is read from the recent-items list the console already keeps for list-view visits (`RecentViewItem`, objectui#12604). - **Manage views** at the dropdown's foot (admins only) is an addition the card did not name: the tab row's ▾ menu was the only way into that dialog, and it retires with the row. ## Tests New: - `views/objectViewTitleSwitcher.test.tsx` (13): label and count; authored-then-saved order in All; search box always there; Pinned → Recent (≤3, without the pinned) → All; a pinned view the list no longer offers draws no Pinned; case-insensitive search narrows flat; choosing switches and closes; 📌 pin / unpin; ☆ toggles, and a menu view's ☆ is disabled with its reason; no ☆ off an app route; the foot and its CONTROL. - `views/ObjectView.titleViewSwitcher-27594.test.tsx` (real `ObjectView`): the title in the `h1` with the view label and count; no tab bar, tab row or toolbar slot; the dropdown's order; search and its empty state; pin stores `{"view":"v3","v":1}` at `os:pref:list.view.pinned@object:crm_lead` and a bare route opens it on remount; unpin returns to the default; a view in the address beats the pin; the split pane (`?recordId=` with the split preference) shows the same switcher. - `views/ObjectView.starredView-27594.test.tsx`: ☆ writes the `view` favorite (id, label, href, icon); an authored `viewName` entry's ☆ is disabled with "Already in the menu". - `layout/__tests__/UnifiedSidebar.starredViews-27594.test.tsx`: a starred view of this app is drawn with its icon and address, one of another app is not; a keyboard reorder saves the new order. Updated (they read the retired tab row, a tab's text, or the plural `h1`): `ObjectView.chartViewTabs-13114`, `viewRefusal-12112`, `labelLessViewTab-12774`, `servedViewLabel-11295`, `userListState-12418`, `viewWriteRefusal-11583`, `ufViewSwitch-11992`, `createViewRefusal-11578`, `createKanbanView-11581`, `createChartView-11576`, `recordOpenPreference-26677`, `refreshInPlace-10035`, `externalRefreshSum-10572`, `relayRungCensus-7559`, `listTitlePlural-11696`, `managedByBadgeAuthoring-12194`, `setupListBadge-13385`, `listActionsReadGate-12109`, `objectBoundActions-7234`, and console `recordOpenFromEveryView-27057`. `ObjectView.viewTabsInToolbar-12440.test.tsx` is replaced by `ObjectView.titleViewSwitcher-27594.test.tsx` (the toolbar slot it pinned is gone). ## Acceptance notes - **Open question (premise drift).** The card says the object name "stays in the breadcrumb and the sidebar highlight". An object route draws no crumb (objectui#12461: the page header named the object, so a crumb said it twice), so with the title naming the view the object is named by the sidebar's active entry and the header's object icon. A label-less view is still called by the plural (objectui#12774), and so are the tests of #11696 and the badge tests, which now open such a view. Restoring an object crumb on list routes is a one-line call for the seat; this PR does not make it. - Screenshots are on `examples/app-crm` (HotCRM is not in this workspace), a deviation from Acceptance 2, and are kept in the project's files for the seat rather than on an evidence branch; see Verification. Two layout faults they showed were fixed before this PR opened: the trigger's negative margin cut a four-character label by one, and its outer focus ring was clipped by the title's truncation. - The count is the list's reported total, so it is drawn for a view whose list reports one (the paged grid); a board or calendar that does not report a total shows the label and ▾ alone. - The admin-shared `isPinned` flag of a saved view (the old tab row's pin) is not drawn in the dropdown; 📌 is the reader's own pin. - The phone keeps its app-bar view switcher (`MobileViewSwitcherContext`); the page header with the title switcher is `sm` and up, as before. - Seen while taking the split-pane screenshot, not changed here: in the split arm the list draws its own record-count bar and `ObjectView` draws `record-count-footer` under it, so 「5 条记录」 shows twice (`ObjectView.tsx`, the split pane's footer; untouched by this diff). - `packages/spec/**` is untouched. One spec description still names the tab strip: `view.list.tabs`' removal note says "the tab strip above an object's records is the saved-view switcher (ViewTabBar)". It is prose in the generated reference; noted for the spec lane, not changed here. ## Verification <details><summary>Local runs (head 16c2570, after merging origin/main 04740b7 once)</summary> All under `scripts/pm/os-verify-lock.sh`: - `pnpm --dir ui exec vitest run` over the 238 test files that name `ObjectView`, the retired tab bar or toolbar slot, `FavoritesProvider`/`useFavorites`, `workspacePreference`, `objectViewListRenderer`, `objectViewPageHeader`, `StarredApps` or `list-view-switcher` (app-shell views, layout, context, utils, console home and `AppContent` tests, console `recordOpenFromEveryView-27057`), plus `packages/i18n/` → Test Files 330 passed (330), Tests 3335 passed, 13 skipped; `VITEST_EXIT=0`. - `pnpm --filter @object-ui/app-shell run type-check` (both tsc programs) → `TYPECHECK_EXIT=0`. - `eslint` on every changed app-shell file → 0 errors (warnings carried over from the deleted `objectViewTabBar.tsx`). - `pnpm --dir ui run check:i18n-drift` → 0 en values changed, 7 keys added; `check:i18n-keys` and `check:i18n-dead-keys` → exit 0; `pnpm check:new-line-citations` (ui) → 0 new citations, exit 0. - Not run locally, declared to CI: the whole Test UI shards, the console type-check (no export of `@object-ui/app-shell` changed; one console test file changed), and the rest of the lint farm. </details> <details><summary>Ablations (each through scripts/ablation-replace.mjs, each restored to HEAD with an empty diff)</summary> - `ObjectView.tsx`: the pin dropped from the open-view resolution (`resolvedViewId || defaultViewId`) → `titleViewSwitcher-27594` 1 of 7 red (the pin is kept and the bare address opens it). - `objectViewTitleSwitcher.tsx`: authored-first order dropped → `objectViewTitleSwitcher.test` 1 of 13 red. - `UnifiedSidebar.tsx`: view favorites not filtered by app → `UnifiedSidebar.starredViews-27594` 2 of 2 red. - `listViewFavorites.ts`: `inMenu` always false → `starredView-27594` 1 of 2 red. - `UnifiedSidebar.tsx`: the sidebar's drop not saved (`onReorder={() => {}}`) → `UnifiedSidebar.starredViews-27594` 1 of 2 red. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at `16c257005a` derived 66 families (the same list as at `8aec374c05`); each run and recorded as `command :: exit code` before any pipe; all 66 exit 0, including `node scripts/check-sdui-manifest.mjs` and `pnpm --dir ui exec vitest run scripts/` (run alone, nothing else running). `pnpm --filter @objectstack/spec run check:skill-examples` exited 3 (NOT MEASURED: stale `@objectstack/client-react` declarations) on the first pass at `8aec374c05`; after `pnpm --filter @objectstack/client-react build` it exited 0, and 0 again at `16c257005a`. `--ran` reconciliation: 66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN. </details> <details><summary>Screenshots (examples/app-crm, zh-CN, 1440 × 900)</summary> Backend `examples/app-crm` with `objectstack dev --seed-admin --fresh` on its own port, Console from `ui/apps/console` (Vite, src) pointed at it, driven by Playwright; both stopped afterwards. Eight PNGs in the project's files for the seat (`ui-seat2/card-27594/shots/`): - `00-list-title.png`: 「全部线索 ▾ · 5」 as the title; no tab row; the filter / sort / display controls on their own row. - `01-dropdown-open.png`: the dropdown open, a row hovered with ☆ and 📌, 「新建视图」 and 「管理视图」 at the foot. - `02-bare-address-opens-pinned.png`: after 📌 on 「线索看板」, the bare list address opens the board. - `03-dropdown-pinned-recent-all.png`: 「固定 · 最近 · 全部」. - `04-dropdown-search.png`: searching 「看板」. - `05-sidebar-starred-view.png`: 「收藏」 at the top of the sidebar with the starred 「线索看板」 beside the object's icon. - `06-split-pane.png`, `07-split-pane-dropdown.png`: a record open in the split pane; the list beside it keeps the same switcher, and it opens there. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CanDVECEsojSwtvSs7)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4bb5eea commit 847e424

51 files changed

Lines changed: 2206 additions & 560 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
feat(console): the list title switches views from a dropdown, a pinned view opens by default, and a starred view joins the sidebar's Favorites (#27594)
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
- The flat row of view tabs above an object's list is gone. The list title now reads 「<view label> ▾ · <count>」 and opens a dropdown: a search box, then 📌 Pinned, Recent (the reader's last three views of this object) and All (the views the app ships first, then the ones saved at runtime), each row with its view-type icon. New view and, for an admin, Manage views sit at its foot. The split pane beside an open record keeps the same title switcher.
12+
- 📌 on a row makes that view the one this reader's list of this object opens on a bare address; it is kept per object in the workspace preferences of this browser (`list.view.pinned`, scope `object:NAME`). Unpinning goes back to the shipped default view. A view named in the address still wins.
13+
- ☆ on a row stars the view: it appears in the sidebar's Favorites section of the app it was starred in, a click opens it, and the section's starred rows can be dragged (or moved with Space and the arrow keys) into an order that is kept. A view the app's own menu already opens shows its ☆ disabled, 「Already in the menu」. Starred views are favorites of type `view` in the existing favorites store, so they follow the reader across devices like every other favorite.
14+
- Nothing to do: no metadata, protocol or configuration changes. New translation keys sit under `view.switcher` in every language pack.

‎content/docs/ui/views.mdx‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,21 @@ gantt: {
357357
}
358358
```
359359

360+
### Switching views
361+
362+
In the Console the list's title is the view switcher: it reads the open view's `label` and a
363+
▾, and on a grid the number of records the view holds. It opens a dropdown with a search box
364+
and three sections: **Pinned**, **Recent** (the user's last views of this object) and
365+
**All**, where the views you author come first and the views users save at runtime follow.
366+
The split pane beside an open record keeps the same switcher.
367+
368+
- **📌 Pin** makes a view the one this user's list of the object opens when the address names
369+
no view. The pin is kept per object, in that browser; unpinning goes back to the object's
370+
default view. A view named in the address always wins.
371+
- **☆ Star** puts a view in the sidebar's **Favorites** section of the app, where the user can
372+
drag it into place. A view your app's navigation already opens (an `object` entry with that
373+
`viewName`) is in the menu already, so its star is disabled.
374+
360375
## Form View
361376

362377
A Form View defines how a single record is displayed for viewing or editing. It lives in the same `defineView` container as the object's list views:
@@ -491,7 +506,7 @@ A header sort, a column drag or resize, a filter change, a density change, Hide
491506
and a Manage Views drag are saved for that user (`sys_user_preference`, key
492507
`ui.list.<object>`), never to the view metadata, so they work even where the tenant's
493508
metadata is read-only. What you author (`sort`, filters, columns, `rowHeight`,
494-
`hiddenFields`, tab order) is the default for every user with no state of their own.
509+
`hiddenFields`, the views' order) is the default for every user with no state of their own.
495510

496511
- A link carrying list state (`uf_*` parameters) wins over the stored state.
497512
- A user's hidden fields only subtract from the columns the view shows, never add one.

‎ui/apps/console/src/__tests__/recordOpenFromEveryView-27057.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ async function mountView(viewKey: string, navigation?: Record<string, unknown>)
228228
</ExpressionProvider>
229229
</I18nProvider>,
230230
);
231-
await screen.findByTestId('view-tab-bar', undefined, { timeout: 5000 });
231+
await screen.findByTestId('list-view-switcher', undefined, { timeout: 5000 });
232232
}
233233

234234
/** The record page is open, embedded, on record `id` — and the quick-look is not. */

‎ui/packages/app-shell/src/console/home/StarredApps.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ const TYPE_TONES: Record<string, string> = {
2424
record: 'bg-amber-500/10 text-amber-600 dark:text-amber-400 ring-amber-500/20',
2525
};
2626

27-
// Per-type icon for four of the six `FavoriteItem['type']` kinds (object /
27+
// Per-type icon for four of the seven `FavoriteItem['type']` kinds (object /
2828
// record / dashboard / page) so those cards are visually distinguishable at
29-
// a glance; `report` has no dedicated glyph and falls back to the same
30-
// Database icon as any unrecognized name. `nav` is the sixth kind — it never
29+
// a glance; `report` and `view` have no dedicated glyph and fall back to the
30+
// same Database icon as any unrecognized name. `nav` is the seventh kind — it never
3131
// reaches this lookup because it is filtered out below (nav items are
3232
// excluded from Starred; see FavoritesProvider's `FavoriteItem['type']` doc,
3333
// objectui#6335).

‎ui/packages/app-shell/src/context/FavoritesProvider.tsx‎

Lines changed: 59 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,22 @@ export interface FavoriteItem {
4747
/**
4848
* Item kind.
4949
*
50-
* - `object` / `dashboard` / `page` / `report` / `record` — content favorites
51-
* surfaced on Home (Starred Apps) and the sidebar Favorites section.
50+
* - `object` / `dashboard` / `page` / `report` / `record` / `view` — content
51+
* favorites surfaced on Home (Starred Apps) and the sidebar Favorites
52+
* section. A `view` is one list view of an object (objectstack#27594), id
53+
* `view:OBJECT:VIEW`; the sidebar draws it only in the app its `href` names.
5254
* - `nav` — a sidebar navigation entry promoted to the "Pinned" position via
5355
* the in-tree pin toggle (see `useNavPins`). Excluded from Home/Starred and
5456
* from the generic sidebar Favorites list so it doesn't render twice.
5557
*/
56-
type: 'object' | 'dashboard' | 'page' | 'report' | 'record' | 'nav';
58+
type: 'object' | 'dashboard' | 'page' | 'report' | 'record' | 'view' | 'nav';
5759
/** ISO timestamp of when the item was favorited */
5860
favoritedAt: string;
61+
/**
62+
* The icon the sidebar draws for the item, a Lucide name. Set for a `view`
63+
* favorite: the icon of the object the view lists (objectstack#27594).
64+
*/
65+
icon?: string;
5966
/**
6067
* When true, the item is pinned to the top of the sidebar (Pinned section).
6168
* `nav`-type items are always pinned by construction; other types may also
@@ -110,6 +117,15 @@ interface FavoritesContextValue {
110117
* favorite keep their places. An id with no nav favorite is ignored.
111118
*/
112119
reorderNavPins: (navIds: string[]) => void;
120+
/**
121+
* Put the named content favorites (not `nav` pins) in this order
122+
* (objectstack#27594): the sidebar's Favorites rows after the pinned
123+
* entries, as the user dragged them. Like {@link reorderNavPins}, the named
124+
* favorites take the positions they already hold, so a favorite that is not
125+
* named (one the sidebar of another app draws, say) keeps its place. An id
126+
* with no content favorite is ignored.
127+
*/
128+
reorderFavorites: (ids: string[]) => void;
113129
}
114130

115131
// ---------------------------------------------------------------------------
@@ -184,11 +200,33 @@ function withNavPinOrder(items: FavoriteItem[], navIds: string[]): FavoriteItem[
184200
for (const f of items) {
185201
if (f.type === 'nav' && f.navId && !byNavId.has(f.navId)) byNavId.set(f.navId, f);
186202
}
203+
return withNamedOrder(items, navIds, byNavId);
204+
}
205+
206+
/**
207+
* `items` with the content favorites (every type but `nav`) named by `ids` put
208+
* in that order, in the positions they already hold; `items` itself when
209+
* nothing moves (objectstack#27594).
210+
*/
211+
export function withFavoriteOrder(items: FavoriteItem[], ids: string[]): FavoriteItem[] {
212+
const byId = new Map<string, FavoriteItem>();
213+
for (const f of items) {
214+
if (f.type !== 'nav' && !byId.has(f.id)) byId.set(f.id, f);
215+
}
216+
return withNamedOrder(items, ids, byId);
217+
}
218+
219+
/** `items` with the entries `byKey` finds for `keys` put in that order, in the positions they hold. */
220+
function withNamedOrder(
221+
items: FavoriteItem[],
222+
keys: string[],
223+
byKey: Map<string, FavoriteItem>,
224+
): FavoriteItem[] {
187225
const wanted: FavoriteItem[] = [];
188226
const seen = new Set<string>();
189-
for (const id of navIds) {
190-
const f = byNavId.get(id);
191-
if (f && !seen.has(id)) { wanted.push(f); seen.add(id); }
227+
for (const key of keys) {
228+
const f = byKey.get(key);
229+
if (f && !seen.has(key)) { wanted.push(f); seen.add(key); }
192230
}
193231
const moving = new Set(wanted);
194232
let k = 0;
@@ -505,6 +543,18 @@ export function FavoritesProvider({ children }: FavoritesProviderProps) {
505543
[commit],
506544
);
507545

546+
const reorderFavorites = useCallback(
547+
(ids: string[]) => {
548+
setFavorites(prev => {
549+
const updated = withFavoriteOrder(prev, ids);
550+
if (updated === prev) return prev;
551+
commit(updated);
552+
return updated;
553+
});
554+
},
555+
[commit],
556+
);
557+
508558
const value = useMemo<FavoritesContextValue>(() => {
509559
const pinnedNavIds = new Set<string>();
510560
for (const f of favorites) {
@@ -522,8 +572,9 @@ export function FavoritesProvider({ children }: FavoritesProviderProps) {
522572
isPinned: (id: string) => favorites.some(f => f.id === id && !!f.pinned),
523573
pinnedNavIds,
524574
reorderNavPins,
575+
reorderFavorites,
525576
};
526-
}, [favorites, addFavorite, removeFavorite, toggleFavorite, clearFavorites, refreshLabel, setPinned, reorderNavPins]);
577+
}, [favorites, addFavorite, removeFavorite, toggleFavorite, clearFavorites, refreshLabel, setPinned, reorderNavPins, reorderFavorites]);
527578

528579
return (
529580
<FavoritesContext.Provider value={value}>
@@ -559,6 +610,7 @@ export function useFavorites(): FavoritesContextValue {
559610
isPinned: () => false,
560611
pinnedNavIds: new Set<string>(),
561612
reorderNavPins: () => {},
613+
reorderFavorites: () => {},
562614
};
563615
}
564616
return ctx;

‎ui/packages/app-shell/src/layout/MobileViewSwitcherContext.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
*
88
* On mobile (<sm), the AppHeader replaces its static page label with a
99
* `<viewName> ▾` dropdown trigger when a switcher has been registered.
10-
* Desktop continues to use the inline `ViewTabBar` and ignores this
11-
* context entirely.
10+
* Desktop switches from the page title's view switcher (objectstack#27594)
11+
* and ignores this context entirely.
1212
*
1313
* Design notes:
1414
* - The provider stores a single nullable value (last registered wins).
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The sidebar Favorites section's own rows — the favorites that are not
5+
* navigation entries (a starred list view, record, object, dashboard, page) —
6+
* as a list the user orders by dragging (objectstack#27594). It is the same
7+
* gesture the pinned entries above it take (`NavigationRenderer`'s pinned
8+
* list, objectui#12059): a row is dragged by its own link, with no grip at
9+
* rest; from the keyboard, Space picks the focused row up, the arrow keys move
10+
* it, Space drops it and Escape cancels. The other rows hold still and an
11+
* insertion line shows where the row lands. A drop reports the ids of the rows
12+
* drawn here, in their new order. The rows are `SidebarMenuItem`s for the
13+
* menu list the section already draws them in (`extraFavorites`).
14+
*
15+
* @module
16+
*/
17+
18+
import * as React from 'react';
19+
import {
20+
DndContext,
21+
KeyboardSensor,
22+
PointerSensor,
23+
closestCenter,
24+
useDndContext,
25+
useSensor,
26+
useSensors,
27+
type DragCancelEvent,
28+
type DragEndEvent,
29+
type DraggableSyntheticListeners,
30+
type KeyboardSensorOptions,
31+
} from '@dnd-kit/core';
32+
import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, type SortingStrategy } from '@dnd-kit/sortable';
33+
import { CSS } from '@dnd-kit/utilities';
34+
import { SidebarMenuItem, cn } from '@object-ui/components';
35+
36+
/** Pixels a pointer moves before a press becomes a drag, so a click still follows the link. */
37+
const DRAG_ACTIVATION_DISTANCE = 5;
38+
39+
/** Space starts and ends a keyboard drag; Enter stays the link's. */
40+
const KEYBOARD_SENSOR: KeyboardSensorOptions = {
41+
coordinateGetter: sortableKeyboardCoordinates,
42+
keyboardCodes: { start: ['Space'], cancel: ['Escape'], end: ['Space'] },
43+
};
44+
45+
/** The other rows hold still while one is dragged; the insertion line shows where it lands. */
46+
const holdRowsStill: SortingStrategy = () => null;
47+
48+
const startedByKeyboard = (event: { activatorEvent: Event | null }) => event.activatorEvent?.type === 'keydown';
49+
50+
/**
51+
* Swallows the click that ends a pointer drag: the button is released over the
52+
* row's own link, and the browser would follow it with a full page load.
53+
*/
54+
function swallowClickAfterPointerDrag(): void {
55+
const swallow = (event: MouseEvent) => event.preventDefault();
56+
window.addEventListener('click', swallow, { capture: true });
57+
window.setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 50);
58+
}
59+
60+
/** What a row hands the element that starts its drag: its own link. */
61+
export interface FavoriteRowDragProps {
62+
ref: (element: HTMLElement | null) => void;
63+
'aria-describedby': string;
64+
onKeyUp: (event: React.KeyboardEvent) => void;
65+
[listener: string]: unknown;
66+
}
67+
68+
export interface SortableFavoriteRowsProps<T extends { id: string }> {
69+
items: readonly T[];
70+
/** Called on a drop with the ids of the rows, in their new order. */
71+
onReorder: (ids: string[]) => void;
72+
/** The row's content inside its `SidebarMenuItem`; spread `drag` on the row's link. */
73+
renderRow: (item: T, drag: FavoriteRowDragProps) => React.ReactNode;
74+
}
75+
76+
export function SortableFavoriteRows<T extends { id: string }>({ items, onReorder, renderRow }: SortableFavoriteRowsProps<T>) {
77+
const sensors = useSensors(
78+
useSensor(PointerSensor, { activationConstraint: { distance: DRAG_ACTIVATION_DISTANCE } }),
79+
useSensor(KeyboardSensor, KEYBOARD_SENSOR),
80+
);
81+
const ids = items.map((item) => item.id);
82+
83+
const handleDragEnd = (event: DragEndEvent) => {
84+
if (!startedByKeyboard(event)) swallowClickAfterPointerDrag();
85+
const { active, over } = event;
86+
if (!over || active.id === over.id) return;
87+
const from = ids.indexOf(String(active.id));
88+
const to = ids.indexOf(String(over.id));
89+
if (from === -1 || to === -1) return;
90+
onReorder(arrayMove(ids, from, to));
91+
};
92+
const handleDragCancel = (event: DragCancelEvent) => {
93+
if (!startedByKeyboard(event)) swallowClickAfterPointerDrag();
94+
};
95+
96+
return (
97+
<DndContext
98+
id="sidebar-favorites"
99+
sensors={sensors}
100+
collisionDetection={closestCenter}
101+
onDragEnd={handleDragEnd}
102+
onDragCancel={handleDragCancel}
103+
>
104+
<SortableContext items={ids} strategy={holdRowsStill}>
105+
{items.map((item) => (
106+
<SortableFavoriteRow key={item.id} id={item.id}>
107+
{(drag) => renderRow(item, drag)}
108+
</SortableFavoriteRow>
109+
))}
110+
</SortableContext>
111+
</DndContext>
112+
);
113+
}
114+
115+
function SortableFavoriteRow({ id, children }: { id: string; children: (drag: FavoriteRowDragProps) => React.ReactNode }) {
116+
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging, isOver, activeIndex, index } =
117+
useSortable({ id });
118+
const { activatorEvent } = useDndContext();
119+
// A keyboard drag leaves the row in place, dimmed, so it never covers the
120+
// row it is over: the insertion line alone shows where it lands.
121+
const heldInPlace = isDragging && activatorEvent?.type === 'keydown';
122+
const style: React.CSSProperties = {
123+
transform: heldInPlace ? undefined : CSS.Transform.toString(transform),
124+
transition,
125+
opacity: isDragging ? 0.5 : undefined,
126+
zIndex: isDragging ? 10 : undefined,
127+
};
128+
const dropIndicator = isOver && !isDragging && activeIndex !== -1 ? (activeIndex < index ? 'after' : 'before') : null;
129+
const drag: FavoriteRowDragProps = {
130+
ref: setActivatorNodeRef,
131+
...(listeners as DraggableSyntheticListeners & Record<string, unknown>),
132+
'aria-describedby': attributes['aria-describedby'],
133+
onKeyUp: (event: React.KeyboardEvent) => {
134+
if (event.code === 'Space') event.preventDefault();
135+
},
136+
};
137+
return (
138+
<SidebarMenuItem ref={setNodeRef} style={style} className="relative" data-favorite-id={id}>
139+
{dropIndicator && (
140+
<span
141+
aria-hidden="true"
142+
data-drop-indicator={dropIndicator}
143+
className={cn(
144+
'pointer-events-none absolute inset-x-2 h-0.5 rounded-full bg-primary',
145+
dropIndicator === 'before' ? '-top-px' : '-bottom-px',
146+
)}
147+
/>
148+
)}
149+
{children(drag)}
150+
</SidebarMenuItem>
151+
);
152+
}

0 commit comments

Comments
 (0)