From 03d9324aafefcfe7536fce676e91d5107ba433b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:15:26 +0000 Subject: [PATCH 1/3] feat(app-shell): phone lands in an app whose home is its whole menu; bottom bar fixed to Home, Notifications, Approvals and search On a phone (below 768 px): - `/` opens the app the person used last (a per-person `ui.app.last` preference on the shared read), else the declared default, else the single app, else the app list. - `/apps/SEGMENT` is the app's home: the sidebar's own menu drawn into the page through a portal, scroll restored on return. - The app pill opens a bottom sheet listing the apps with search; `/home` is the same list as a page. - The bottom bar is three fixed cells (Home, Notifications, Approvals) and a search button, shown only on those three pages; pinned menu entries, More and the stars are removed. Desktop and tablet widths are unchanged. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgU7ah5dc72qr3aWHFu --- .changeset/35881-phone-app-home-fixed-bar.md | 17 + .../RootLandingRedirect.route.test.tsx | 52 ++- .../components/RootLandingRedirect.test.ts | 45 ++- .../src/components/RootLandingRedirect.tsx | 51 ++- .../live/phone-nav-drawer-back-29131.spec.ts | 36 +- .../app-shell/src/console/AppContent.tsx | 18 +- .../app-shell/src/console/ConsoleShell.tsx | 12 + .../AppContent.phoneAppHome-35881.test.tsx | 195 ++++++++++ .../consoleUserPreferenceBudget.test.tsx | 37 +- .../app-shell/src/console/home/HomePage.tsx | 22 ++ .../HomePage.phoneTapTargets-29147.test.tsx | 20 +- .../app-shell/src/context/LastAppProvider.tsx | 157 ++++++++ .../src/context/UserStateAdapters.tsx | 6 +- ui/packages/app-shell/src/index.ts | 4 + .../app-shell/src/layout/AppHeader.tsx | 39 +- .../app-shell/src/layout/AppSwitcher.tsx | 70 +++- .../app-shell/src/layout/ConsoleLayout.tsx | 51 +-- .../app-shell/src/layout/PhoneAppHome.tsx | 98 +++++ .../app-shell/src/layout/PhoneAppList.tsx | 130 +++++++ .../app-shell/src/layout/PhoneAppNavBar.tsx | 314 ++++++---------- .../app-shell/src/layout/UnifiedSidebar.tsx | 205 ++++------- .../AppHeader.sidebarTrigger-12429.test.tsx | 57 ++- .../AppSwitcher.phoneSheet-35881.test.tsx | 126 +++++++ ...oleLayout.phoneRecordOneBar-28483.test.tsx | 77 ++-- .../PhoneAppNavBar.fixedTabs-35882.test.tsx | 156 ++++++++ ...UnifiedSidebar.phoneAppHome-35881.test.tsx | 234 ++++++++++++ .../UnifiedSidebar.phoneNavBar-34594.test.tsx | 346 ------------------ ui/packages/i18n/src/locales/ar.ts | 15 +- ui/packages/i18n/src/locales/de.ts | 15 +- ui/packages/i18n/src/locales/en.ts | 15 +- ui/packages/i18n/src/locales/es.ts | 15 +- ui/packages/i18n/src/locales/fr.ts | 15 +- ui/packages/i18n/src/locales/ja.ts | 15 +- ui/packages/i18n/src/locales/ko.ts | 15 +- ui/packages/i18n/src/locales/pt-BR.ts | 15 +- ui/packages/i18n/src/locales/ru.ts | 15 +- ui/packages/i18n/src/locales/zh-Hans.ts | 15 +- ui/packages/i18n/src/locales/zh-Hant.ts | 15 +- 38 files changed, 1913 insertions(+), 827 deletions(-) create mode 100644 .changeset/35881-phone-app-home-fixed-bar.md create mode 100644 ui/packages/app-shell/src/console/__tests__/AppContent.phoneAppHome-35881.test.tsx create mode 100644 ui/packages/app-shell/src/context/LastAppProvider.tsx create mode 100644 ui/packages/app-shell/src/layout/PhoneAppHome.tsx create mode 100644 ui/packages/app-shell/src/layout/PhoneAppList.tsx create mode 100644 ui/packages/app-shell/src/layout/__tests__/AppSwitcher.phoneSheet-35881.test.tsx create mode 100644 ui/packages/app-shell/src/layout/__tests__/PhoneAppNavBar.fixedTabs-35882.test.tsx create mode 100644 ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.phoneAppHome-35881.test.tsx delete mode 100644 ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.phoneNavBar-34594.test.tsx diff --git a/.changeset/35881-phone-app-home-fixed-bar.md b/.changeset/35881-phone-app-home-fixed-bar.md new file mode 100644 index 00000000000..14e428c0219 --- /dev/null +++ b/.changeset/35881-phone-app-home-fixed-bar.md @@ -0,0 +1,17 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): on a phone, sign-in lands in an app whose home is its whole menu, and the bottom bar is fixed to Home, Notifications, Approvals and search + +Clause-②: no +Metadata-protocol: none + +Phone width only (below 768 px). Desktop and tablet widths do not change. + +- **Where sign-in lands.** A phone opens the app the person used last. The app the product marks as default is used only when there is no record yet, for example on a first sign-in. With one app it opens that app; with several and neither, it opens the app list. The last app is kept per person with their other console preferences (the `ui.app.last` key), so it follows them across devices. It is read in the same request as those preferences, not in a new one. A desktop still lands on the declared default first, as before. +- **The app's home is its whole menu.** On a phone, `/apps/SEGMENT` shows the app's menu with its groups, order and icons, one row per entry. It no longer redirects to the first entry. This is the sidebar's own menu drawn in a second place, so it cannot list an entry the sidebar hides. 「‹」 on a page one level down goes back to it, and the page comes back scrolled as it was left. An app that shows the member no entry still says so. +- **App switcher.** The app pill at the top left opens a bottom sheet: 「Current app」 with a check, then 「Other apps」 with Setup last, and a search box at the bottom. On a phone, `/home` is that same list as a page. +- **Bottom bar.** The bar has three fixed cells, Home, Notifications and Approvals, and a round search button. They do not change with the app and cannot be configured. Home opens the app's home. Notifications and Approvals open the pages the bell opens, with the bell's two counts as badges. Search opens the command palette. The bar shows only on those three pages; a list, a record, a form or any deeper page has the screen to itself. The bar no longer holds menu entries, a 「More」 cell or pinned entries (objectstack#34594). Pins already stored are ignored, and the drawer's menu search and pin hint are gone. The drawer still opens with a swipe in from the left edge. diff --git a/ui/apps/console/src/components/RootLandingRedirect.route.test.tsx b/ui/apps/console/src/components/RootLandingRedirect.route.test.tsx index b295d426668..f428a0a7bb5 100644 --- a/ui/apps/console/src/components/RootLandingRedirect.route.test.tsx +++ b/ui/apps/console/src/components/RootLandingRedirect.route.test.tsx @@ -64,7 +64,7 @@ */ import { describe, expect, it, vi, beforeEach } from 'vitest'; -import { render, screen } from '@testing-library/react'; +import { act, render, screen } from '@testing-library/react'; import { MemoryRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom'; import type { ReactNode } from 'react'; @@ -82,6 +82,11 @@ const metadata = vi.hoisted(() => ({ }, })); +/** objectstack#35881 — the width and the person's last app, varied by the phone cases. */ +const phone = vi.hoisted(() => ({ + value: { isPhone: false, lastApp: null as string | null, settled: true }, +})); + /** The auth verdict each case varies. */ const auth = vi.hoisted(() => ({ value: { isAuthenticated: false, isLoading: false, user: null as any }, @@ -107,6 +112,8 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ ), + usePhoneViewport: () => phone.value.isPhone, + useLastApp: () => ({ lastApp: phone.value.lastApp, settled: phone.value.settled, rememberApp: () => {} }), SETUP_APP_PACKAGE_ID: 'com.objectstack.setup', SETUP_APP_NAME: 'setup', useMetadata: () => ({ @@ -187,6 +194,7 @@ const OTHER_APP = { name: 'showcase_app' }; beforeEach(() => { metadata.value = { apps: [], loading: false, status: 'ready', refresh: vi.fn(async () => {}) }; auth.value = { isAuthenticated: false, isLoading: false, user: null }; + phone.value = { isPhone: false, lastApp: null, settled: true }; }); // ── (b) The control QA used to isolate the defect ──────────────────────── @@ -390,3 +398,45 @@ describe('the landing carries the query and hash `/` arrived with', () => { expect(screen.getByTestId('location-hash').textContent).toBe(''); }); }); + +// ── objectstack#35881, ruling 7045309332 (「上次用的优先」) ──────────────────── +describe('a phone lands in the app the person used last (objectstack#35881)', () => { + beforeEach(() => { + auth.value.isAuthenticated = true; + metadata.value.apps = [OTHER_APP, DEFAULT_APP]; + }); + + it('the last-used app wins over the declared default', () => { + phone.value = { isPhone: true, lastApp: 'showcase_app', settled: true }; + renderAt('/'); + expect(location()).toBe('/apps/showcase_app'); + }); + + it('with no record yet it takes the declared default', () => { + phone.value = { isPhone: true, lastApp: null, settled: true }; + renderAt('/'); + expect(location()).toBe('/apps/crm_app'); + }); + + it('waits while the record is still being read, then resolves without it after the wait', () => { + vi.useFakeTimers(); + try { + phone.value = { isPhone: true, lastApp: null, settled: false }; + renderAt('/'); + expect(location()).toBe('/'); + expect(screen.getByTestId('loading-fallback')).toBeInTheDocument(); + act(() => { + vi.advanceTimersByTime(2000); + }); + expect(location()).toBe('/apps/crm_app'); + } finally { + vi.useRealTimers(); + } + }); + + it('CONTROL — a desktop ignores the last app and keeps the declared default', () => { + phone.value = { isPhone: false, lastApp: 'showcase_app', settled: true }; + renderAt('/'); + expect(location()).toBe('/apps/crm_app'); + }); +}); diff --git a/ui/apps/console/src/components/RootLandingRedirect.test.ts b/ui/apps/console/src/components/RootLandingRedirect.test.ts index 6fdcbbf63f6..c1060144ad5 100644 --- a/ui/apps/console/src/components/RootLandingRedirect.test.ts +++ b/ui/apps/console/src/components/RootLandingRedirect.test.ts @@ -1,7 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect } from 'vitest'; -import { resolveLandingPath, isAppListConclusive } from './RootLandingRedirect'; +import { resolveLandingPath, resolvePhoneLandingPath, isAppListConclusive } from './RootLandingRedirect'; describe('resolveLandingPath', () => { it('routes to the App marked isDefault (isDefault now ROUTES, not just badges)', () => { @@ -185,3 +185,46 @@ describe('isAppListConclusive — is this list an answer, or an unknown?', () => expect(isAppListConclusive(undefined)).toBe(true); }); }); + +// objectstack#35881, ruling 7045309332 (「上次用的优先」): on a phone the app the +// person used last wins; the declared default applies only when there is no +// record yet. One function, one test per order. +describe('resolvePhoneLandingPath — the last app first, then the desktop order', () => { + const APPS = [ + { name: 'crm', _packageId: 'com.acme.crm' }, + { name: 'cloud_control', isDefault: true }, + { name: 'service' }, + ]; + + it('the last-used app beats the declared default', () => { + expect(resolvePhoneLandingPath(APPS, 'service')).toBe('/apps/service'); + }); + + it('the last-used app lands at its address segment (its package id when it has one)', () => { + expect(resolvePhoneLandingPath(APPS, 'crm')).toBe('/apps/com.acme.crm'); + }); + + it('no record yet: the declared default', () => { + expect(resolvePhoneLandingPath(APPS, null)).toBe('/apps/cloud_control'); + expect(resolvePhoneLandingPath(APPS, undefined)).toBe('/apps/cloud_control'); + }); + + it('no record and no default: the single visible app, else /home', () => { + expect(resolvePhoneLandingPath([{ name: 'only' }], null)).toBe('/apps/only'); + expect(resolvePhoneLandingPath([{ name: 'a' }, { name: 'b' }], null)).toBe('/home'); + }); + + it('a last app that is gone, hidden or switched off is ignored', () => { + expect(resolvePhoneLandingPath(APPS, 'removed')).toBe('/apps/cloud_control'); + expect( + resolvePhoneLandingPath([...APPS, { name: 'secret', hidden: true }], 'secret'), + ).toBe('/apps/cloud_control'); + expect( + resolvePhoneLandingPath([...APPS, { name: 'off', active: false }], 'off'), + ).toBe('/apps/cloud_control'); + }); + + it('CONTROL — the desktop resolver does not read the last app', () => { + expect(resolveLandingPath(APPS)).toBe('/apps/cloud_control'); + }); +}); diff --git a/ui/apps/console/src/components/RootLandingRedirect.tsx b/ui/apps/console/src/components/RootLandingRedirect.tsx index c128700964f..93b6d2d970f 100644 --- a/ui/apps/console/src/components/RootLandingRedirect.tsx +++ b/ui/apps/console/src/components/RootLandingRedirect.tsx @@ -33,7 +33,7 @@ * declaration is the source of truth.) */ -import { useEffect, useRef } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { useLocation } from 'react-router-dom'; import { useMetadata, @@ -41,6 +41,8 @@ import { RedirectWithSplash, SETUP_APP_PACKAGE_ID, SETUP_APP_NAME, + useLastApp, + usePhoneViewport, } from '@object-ui/app-shell'; import type { MetadataTypeStatus } from '@object-ui/app-shell'; @@ -136,6 +138,39 @@ export function resolveLandingPath(apps: readonly LandingApp[] | null | undefine return '/home'; } +/** + * The path `/` redirects to on a phone (objectstack#35881): the app this + * person last had open, when it is still an active, visible app; otherwise + * the three rules of {@link resolveLandingPath} (the declared default, the one + * app, the app list at `/home`). + * + * The order is the maintainer's ruling (record 7045309332 on #35881, Sales + * 2026-11-20 16:50Z, 「上次用的优先」): the last app beats a declared default, + * which decides only a first sign-in with no last app yet. From 768 px up `/` + * resolves as before, through {@link resolveLandingPath} alone. + */ +export function resolvePhoneLandingPath( + apps: readonly LandingApp[] | null | undefined, + lastApp: string | null | undefined, +): string { + const list = apps ?? []; + const last = lastApp + ? list.find( + (a): a is LandingApp & { name: string } => + a?.name === lastApp && a.active !== false && a.hidden !== true, + ) + : undefined; + if (last) return `/apps/${landingSegment(list, last)}`; + return resolveLandingPath(apps); +} + +/** + * How long a phone's `/` waits for the person's last app to be read before it + * resolves without it (objectstack#35881). The row rides the console's one + * preference read, which is normally in by the time the app list is. + */ +const LAST_APP_WAIT_MS = 2000; + /** * Is the app list this resolver was handed an ANSWER, or an unknown standing * in for one? (objectui#4233) @@ -183,6 +218,15 @@ const APP_LIST_RETRY_DELAY_MS = 1500; export function RootLandingRedirect() { const { apps, loading, getTypeStatus, refresh } = useMetadata(); const location = useLocation(); + // objectstack#35881 — a phone lands in the person's last app. + const phone = usePhoneViewport(); + const { lastApp, settled: lastAppSettled } = useLastApp(); + const [lastAppWaitOver, setLastAppWaitOver] = useState(false); + useEffect(() => { + if (!phone || lastAppSettled) return; + const id = setTimeout(() => setLastAppWaitOver(true), LAST_APP_WAIT_MS); + return () => clearTimeout(id); + }, [phone, lastAppSettled]); // "Not yet" (`loading`) and "asked and failed" (`status === 'error'`) are // both "no answer" — they differ only in whether waiting will help. @@ -207,6 +251,7 @@ export function RootLandingRedirect() { }, [unresolved, refresh]); if (loading || unresolved) return ; + if (phone && !lastAppSettled && !lastAppWaitOver) return ; // `RedirectWithSplash`, not a bare `` (objectui#6378). This is the // widest measured instance of the boot blank: the line above holds the splash // while the app list loads, and handing off to a null-rendering redirect left @@ -217,6 +262,8 @@ export function RootLandingRedirect() { // overlays (`?palette=1`, `?recordId=`) live in the query, and the landing is // a bare `/apps/` or `/home`, so there is nothing to merge with. The // app root it lands on carries them on to the app's own landing in turn. - const landing = resolveLandingPath(apps as LandingApp[] | undefined); + const landing = phone + ? resolvePhoneLandingPath(apps as LandingApp[] | undefined, lastApp) + : resolveLandingPath(apps as LandingApp[] | undefined); return ; } diff --git a/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts b/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts index 871b5ced219..2423a18bc78 100644 --- a/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts +++ b/ui/e2e/live/phone-nav-drawer-back-29131.spec.ts @@ -12,11 +12,13 @@ import { test, expect, type Page } from '@playwright/test'; * browser's own, the close is an outside tap, and the reload is a real one, * which keeps `history.state`. * - * On a phone inside an app the drawer opens from the bottom menu bar's 「More」 - * cell (objectstack#34594): the app bar's left slot holds the Back-to-home - * link there, not the sidebar trigger, which only the desktop control below - * still taps. Both open the same drawer through `setOpenMobile(true)`, so the - * history hook sees the same `openMobile` whichever control opened it. + * On a phone inside an app the drawer opens by a swipe in from the left edge: + * the bottom bar's 「More」 cell is gone (objectstack#35882, the app's menu is + * the app's home page, objectstack#35881), and the app bar's left slot holds + * 「‹」 back to that home, not the sidebar trigger, which only the desktop + * control below still taps. Both open the same drawer through + * `setOpenMobile(true)`, so the history hook sees the same `openMobile` + * whichever opened it. * * In `test:e2e:live:nightly`, not the required `:ci` allowlist. */ @@ -25,7 +27,8 @@ const APP = 'com.example.showcase'; const LIST = `/apps/${APP}/showcase_task`; const DRAWER = '[data-sidebar="sidebar"][data-mobile="true"]'; const TRIGGER = 'button[data-sidebar="trigger"]'; -const MORE = '[data-testid="phone-app-nav-more"]'; +/** On a phone list the app bar's 「‹」, there once the page is drawn. */ +const PHONE_BACK = '[data-testid="app-bar-phone-home"]'; const FLAG = '__navDrawerOpen'; async function openList(page: Page, opener: string) { @@ -36,8 +39,17 @@ async function openList(page: Page, opener: string) { await expect(page.locator(opener).first()).toBeVisible(); } +/** A swipe in from the left edge, the phone's drawer gesture (`UnifiedSidebar`). */ +async function swipeFromEdge(page: Page) { + await page.evaluate(() => { + const touch = (x: number) => new Touch({ identifier: 1, target: document.body, clientX: x, clientY: 420 }); + document.dispatchEvent(new TouchEvent('touchstart', { touches: [touch(10)], changedTouches: [touch(10)] })); + document.dispatchEvent(new TouchEvent('touchend', { touches: [], changedTouches: [touch(120)] })); + }); +} + async function openDrawer(page: Page) { - await page.locator(MORE).first().tap(); + await swipeFromEdge(page); await expect(page.locator(DRAWER)).toBeVisible(); await expect.poll(() => drawerFlag(page)).toBe(true); } @@ -58,7 +70,7 @@ for (const width of [375, 390]) { test.use({ viewport: { width, height: 844 }, isMobile: true, hasTouch: true }); test('Back with the drawer open closes it and stays on the list', async ({ page }) => { - await openList(page, MORE); + await openList(page, PHONE_BACK); const url = page.url(); await openDrawer(page); @@ -70,7 +82,7 @@ for (const width of [375, 390]) { }); test('an outside tap closes the drawer and pops its entry: Back goes to the previous page', async ({ page }) => { - await openList(page, MORE); + await openList(page, PHONE_BACK); const before = await historyLength(page); await openDrawer(page); @@ -87,7 +99,7 @@ for (const width of [375, 390]) { }); test('choosing a nav entry replaces the drawer entry: Back returns to the list', async ({ page }) => { - await openList(page, MORE); + await openList(page, PHONE_BACK); const listUrl = page.url(); await openDrawer(page); @@ -112,12 +124,12 @@ for (const width of [375, 390]) { }); test('a reload with the drawer open leaves it closed, with no flagged entry left', async ({ page }) => { - await openList(page, MORE); + await openList(page, PHONE_BACK); await openDrawer(page); const length = await historyLength(page); await page.reload(); - await expect(page.locator(MORE).first()).toBeVisible(); + await expect(page.locator(PHONE_BACK).first()).toBeVisible(); await expect.poll(() => drawerFlag(page)).toBe(false); await expect(page.locator(DRAWER)).toBeHidden(); diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index 3105075f6b9..9e115400ed1 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -36,7 +36,8 @@ import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPrese import { useLauncherApps } from '../hooks/useLauncherApps.js'; import { resolveRecordFormTarget, resolveRecordFormModalLayout, resolveFormViewChrome, selectRecordFormView, resolveNavigateCreateUrl, resolveNavigateEditUrl, resolvePostCreateTarget, recordFormCreateValues, readRecordFormCreateValues, RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js'; import { deriveRecordSurface, deriveRecordFlowSurface } from '@object-ui/plugin-view/core'; -import { isPhoneViewportNow } from '../hooks/usePhoneViewport.js'; +import { isPhoneViewportNow, usePhoneViewport } from '../hooks/usePhoneViewport.js'; +import { PhoneAppHome } from '../layout/PhoneAppHome.js'; import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js'; import { RECORD_DRAWER_PARAM, RECORD_FORM_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_LINK_PARAM } from '../urlParams.js'; import { appAddressSegment, appRouteSegment, canonicalAppPathname, matchAppBySegment } from '../utils/appRoute.js'; @@ -1968,6 +1969,11 @@ function AppRootLanding({ }) { const gates = useNavMemberGates(); const location = useLocation(); + // objectstack#35881 — on a phone the app's root is the app's home: its whole + // menu, drawn by the sidebar into this page (`PhoneAppHome`), rather than a + // redirect to its first entry. Read synchronously, so the first frame does + // not start a redirect a phone would then undo. + const phone = usePhoneViewport(); // objectstack#25338 — an app that names objects, none of which this member // may read, has nothing for them: its dashboards and pages would answer a // grid of "You don't have access" tiles. Say so once, before any landing is @@ -2003,6 +2009,15 @@ function AppRootLanding({ gates.evaluateVisibility, ctx, ); + // objectstack#35881 — a phone never redirects to an entry: the menu is the + // page. An app that shows this member no entry, now or once its pending + // reads answer, still says so. + if (phone) { + if (appServesNoNavigation(shownApp) && appServesNoNavigation(undecidedApp)) { + return ; + } + return ; + } if ( undecidedLanding !== landing || (!landing && appServesNoNavigation(shownApp) !== appServesNoNavigation(undecidedApp)) @@ -2027,6 +2042,7 @@ function AppRootLanding({ if (appServesNoNavigation(shownApp)) { return ; } + // objectstack-ai/objectstack#29771 — a navigation with no in-app landing: // every entry the member is shown, in `navigation` and in every area, is a // `url` or `action` link (a working or `doc` entry anywhere would have diff --git a/ui/packages/app-shell/src/console/ConsoleShell.tsx b/ui/packages/app-shell/src/console/ConsoleShell.tsx index 69732c58463..abe7433388a 100644 --- a/ui/packages/app-shell/src/console/ConsoleShell.tsx +++ b/ui/packages/app-shell/src/console/ConsoleShell.tsx @@ -38,6 +38,7 @@ import { NavigationProvider } from '../context/NavigationContext.js'; import { FavoritesProvider } from '../context/FavoritesProvider.js'; import { RecentItemsProvider, useDropDeletedRecordsFromRecents } from '../context/RecentItemsProvider.js'; import { FlowPaletteRecentsProvider } from '../context/FlowPaletteRecentsProvider.js'; +import { LastAppProvider, LAST_APP_PREFERENCE_KEY } from '../context/LastAppProvider.js'; import { UserStateAdaptersProvider, useAttachListStateFamily, @@ -200,6 +201,7 @@ function ConsoleShellProviders({ children }: { children: ReactNode }) { + {/* objectui#4467 — the impersonation indicator. Above the @@ -234,6 +236,7 @@ function ConsoleShellProviders({ children }: { children: ReactNode }) { + @@ -387,6 +390,7 @@ function UserStateBridge() { attach('favorites', null); attach('recent', null); attach('flowPaletteRecents', null); + attach('lastApp', null); attachListState(null); attachRecordState(null); return; @@ -406,6 +410,12 @@ function UserStateBridge() { userId: user.id, key: 'ui.flow.palette.recents', }); + // objectstack#35881 — the person's last app, where a phone lands. + const lastApp = createObjectStackUserStateAdapter({ + dataSource, + userId: user.id, + key: LAST_APP_PREFERENCE_KEY, + }); // objectui#12418 — every object's list state, `ui.list.`: a key // family, loaded by prefix in the same one read as the three slots above. const listState = createObjectStackUserPreferenceFamily({ @@ -416,6 +426,7 @@ function UserStateBridge() { attach('favorites', favorites); attach('recent', recent); attach('flowPaletteRecents', flowPaletteRecents); + attach('lastApp', lastApp); // objectstack#25883 — every object's record-page state, `ui.record.` // ("show empty fields"): a second key family in the same one read. const recordState = createObjectStackUserPreferenceFamily({ @@ -429,6 +440,7 @@ function UserStateBridge() { attach('favorites', null); attach('recent', null); attach('flowPaletteRecents', null); + attach('lastApp', null); attachListState(null); attachRecordState(null); }; diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.phoneAppHome-35881.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.phoneAppHome-35881.test.tsx new file mode 100644 index 00000000000..32bcaa967c2 --- /dev/null +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.phoneAppHome-35881.test.tsx @@ -0,0 +1,195 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35881 — on a phone the app's root is the app's home: its whole + * menu, not a redirect to its landing entry. The URL stays `/apps/SEGMENT`, so + * 「‹」 from any page one level down comes back to it. An app that shows the + * member no entry still says so. From 768 px up the root still opens the app's + * landing entry, as before (`AppContent.declaredLanding-28450`). + * + * The harness is `AppContent.declaredLanding-28450.test.tsx`'s, with the + * phone-width hook stubbed. + */ +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +// The page reaches a dynamic `@objectstack/lint` import; its first load is paid +// here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; + +// AGENTS.md §测试纪律 — the lazy page modules are stubbed so no unbounded +// `import()` races a bounded `findBy` window. +vi.mock('../../views/metadata-admin', () => ({ + MetadataDirectoryPage: () =>
, + MetadataResourceListPage: () =>
, + MetadataResourceEditPage: () =>
, + MetadataResourceHistoryPage: () =>
, + MetadataDiagnosticsPage: () =>
, +})); + +vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({ + ...(await importOriginal()), + CreateAppPage: () =>
, + EditAppPage: () =>
, + DashboardDesignPage: () =>
, +})); + +vi.mock('../../layout/ConsoleLayout', () => ({ + ConsoleLayout: ({ activeAppName, children }: { activeAppName?: string; children?: React.ReactNode }) => ( +
+ {children} +
+ ), +})); +vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null })); +vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null })); +vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null })); +vi.mock('../../views/ObjectView', () => ({ + ObjectView: () =>
, +})); +vi.mock('../../views/DashboardView', () => ({ + DashboardView: () =>
, +})); + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (key: string, options?: Record) => + String(options?.defaultValue ?? key).replace(/\{\{(\w+)\}\}/g, (_m, name: string) => String(options?.[name] ?? '')), + }), + useObjectLabel: () => ({ + objectLabel: ({ label }: { label?: string }) => label, + objectPluralLabel: ({ label }: { label?: string }) => label, + appLabel: ({ name, label }: { name: string; label?: string }) => label ?? name, + }), +})); + +/** The viewer under test: a `member` by default; positions name the audience. */ +let viewerRole = 'member'; +let viewerPositions: string[] = []; +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ + user: { id: 'u_1', name: 'Service Agent', email: 'agent@example.com', role: viewerRole, positions: viewerPositions }, + getAuthConfig: async () => ({ features: {} }), + activeOrganization: { id: 'org_1', name: 'Org' }, + }), + useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }), +})); + +const dataSourceStub = { + onConnectionStateChange: () => () => {}, + getConnectionState: () => 'connected', +}; +vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => dataSourceStub, +})); + +/** The app list as the server hands it to this session. */ +let metadataApps: unknown[] = []; +vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => ({ + apps: metadataApps, + objects: [], + loading: false, + ensureType: undefined, + error: null, + refresh: vi.fn(async () => {}), + }), +})); + +const actionRunnerStub = { registerHandler: vi.fn(), getContext: () => ({}) }; +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useActionRunner: () => ({ execute: vi.fn(), runner: actionRunnerStub }), + useGlobalUndo: () => {}, + useMutationInvalidationBridge: () => {}, +})); + +const viewport = vi.hoisted(() => ({ phone: true })); +vi.mock('../../hooks/usePhoneViewport', () => ({ usePhoneViewport: () => viewport.phone })); + +import { AppContent } from '../AppContent'; + +function LocationProbe() { + const location = useLocation(); + return
{location.pathname}
; +} + +/** The member's `/me/permissions` answer: every object readable unless denied. */ +function permissionsDenying(...unreadable: string[]): MePermissionsAuthenticatedResponse { + return { + authenticated: true, + userId: 'u_1', + tenantId: null, + positions: [], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: [], + objects: { + '*': { allowRead: true }, + ...Object.fromEntries(unreadable.map((name) => [name, { allowRead: false }])), + }, + fields: {}, + } as MePermissionsAuthenticatedResponse; +} + +function renderConsoleAt(initialUrl: string, permissions: Partial>) { + return render( + } {...permissions}> + + + + } /> + + + , + ); +} + +const pathname = () => screen.getByTestId('pathname').textContent; + +const crmApp = { + name: 'crm', + label: 'CRM', + navigation: [ + { id: 'nav_home', type: 'dashboard', dashboardName: 'executive_dashboard', label: 'Home' }, + { id: 'nav_leads', type: 'object', objectName: 'crm_lead', label: 'Leads' }, + ], +}; + +describe('a phone\'s app root is the app home, not a redirect (objectstack#35881)', () => { + beforeEach(() => { + viewerRole = 'member'; + viewerPositions = []; + metadataApps = [crmApp]; + viewport.phone = true; + }); + + it('375 px: the root draws the app home and stays at /apps/crm', async () => { + renderConsoleAt('/apps/crm', { initialPermissions: permissionsDenying() }); + expect(await screen.findByTestId('phone-app-home')).toBeInTheDocument(); + expect(pathname()).toBe('/apps/crm'); + expect(screen.queryByTestId('dashboard-view')).toBeNull(); + }); + + it('375 px: an app that shows the member no entry still says so', async () => { + metadataApps = [{ name: 'crm', label: 'CRM', navigation: [] }]; + renderConsoleAt('/apps/crm', { initialPermissions: permissionsDenying() }); + expect(await screen.findByTestId('app-no-access-empty-state')).toBeInTheDocument(); + expect(screen.queryByTestId('phone-app-home')).toBeNull(); + }); + + it('CONTROL — 1024 px: the root still opens the landing entry', async () => { + viewport.phone = false; + renderConsoleAt('/apps/crm', { initialPermissions: permissionsDenying() }); + expect(await screen.findByTestId('dashboard-view')).toBeInTheDocument(); + expect(pathname()).toBe('/apps/crm/dashboard/executive_dashboard'); + expect(screen.queryByTestId('phone-app-home')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/console/__tests__/consoleUserPreferenceBudget.test.tsx b/ui/packages/app-shell/src/console/__tests__/consoleUserPreferenceBudget.test.tsx index 1480626e993..fddd86d6bfb 100644 --- a/ui/packages/app-shell/src/console/__tests__/consoleUserPreferenceBudget.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/consoleUserPreferenceBudget.test.tsx @@ -26,6 +26,9 @@ * in the same read. The budget stays ONE read, asking for the three keys and * both prefixes. * + * objectstack#35881 adds a fourth key, the person's last app (`ui.app.last`): + * the budget stays ONE read, now asking for four keys and both prefixes. + * * ## The tree * * The real `ConsoleShell` providers and the real `ConnectedShell`: its @@ -91,6 +94,7 @@ import { ConsoleShell, ConnectedShell } from '../ConsoleShell'; import { useFavorites } from '../../context/FavoritesProvider'; import { useRecentItems } from '../../context/RecentItemsProvider'; import { useFlowPaletteRecents } from '../../context/FlowPaletteRecentsProvider'; +import { useLastApp } from '../../context/LastAppProvider'; import { useObjectListPreferences, type ObjectListPreference } from '../../context/ListPreferencesProvider'; import { useRecordPagePreferences } from '@object-ui/react'; import { createPreferenceFramework, preferenceRowId as rowId, type PreferenceFramework } from './preferenceFramework'; @@ -98,7 +102,9 @@ import { createPreferenceFramework, preferenceRowId as rowId, type PreferenceFra const FAVORITES_KEY = 'ui.favorites'; const RECENT_KEY = 'ui.recent'; const FLOW_KEY = 'ui.flow.palette.recents'; -const BRIDGE_KEYS = [FAVORITES_KEY, RECENT_KEY, FLOW_KEY]; +/** objectstack#35881 — the person's last app, a fourth key in the same read. */ +const LAST_APP_KEY = 'ui.app.last'; +const BRIDGE_KEYS = [FAVORITES_KEY, RECENT_KEY, FLOW_KEY, LAST_APP_KEY]; /** objectui#12418 — the list-state family, and one object's row of it. */ const LIST_PREFIX = 'ui.list.'; const LIST_KEY = 'ui.list.account'; @@ -113,6 +119,7 @@ const STORE: Record> = { [FAVORITES_KEY]: [{ id: 'object:contact', label: 'Contact', href: '/contact', type: 'object' }], [RECENT_KEY]: [{ id: 'object:lead', type: 'object', name: 'lead', href: '/lead', visitedAt: '2026-10-01T00:00:00.000Z' }], [FLOW_KEY]: ['flow_step_alpha'], + [LAST_APP_KEY]: ['sales'], [LIST_KEY]: { viewOrder: ['account.mine', 'account.all'] }, [RECORD_KEY]: { showEmptyFields: true }, }, @@ -120,6 +127,7 @@ const STORE: Record> = { [FAVORITES_KEY]: [{ id: 'object:invoice', label: 'Invoice', href: '/invoice', type: 'object' }], [RECENT_KEY]: [{ id: 'object:quote', type: 'object', name: 'quote', href: '/quote', visitedAt: '2026-10-02T00:00:00.000Z' }], [FLOW_KEY]: ['flow_step_omega'], + [LAST_APP_KEY]: ['service'], [LIST_KEY]: { viewOrder: ['account.all', 'account.closed'] }, [RECORD_KEY]: { showEmptyFields: false }, }, @@ -135,6 +143,8 @@ interface Seen { favorites: string[]; recent: string[]; flow: string[]; + /** The person's last app (objectstack#35881). */ + lastApp: string | null; /** The `account` list state's tab order (objectui#12418). */ listOrder: string[]; /** The `account` record page's "show empty fields" choice (objectstack#25883). */ @@ -146,13 +156,14 @@ interface Seen { * — the same shape `MetadataProvider.requestBudget.test.tsx` uses. Not props, * because writing through a prop is what the react-compiler rule refuses. */ -const EMPTY_SEEN: Seen = { favorites: [], recent: [], flow: [], listOrder: [], recordShowEmpty: undefined }; +const EMPTY_SEEN: Seen = { favorites: [], recent: [], flow: [], lastApp: null, listOrder: [], recordShowEmpty: undefined }; const latest: { current: Seen } = { current: EMPTY_SEEN }; const actions: { current: { addFavorite?: ReturnType['addFavorite']; addRecentItem?: ReturnType['addRecentItem']; recordRecent?: ReturnType['recordRecent']; + rememberApp?: ReturnType['rememberApp']; patchListView?: ReturnType['patchView']; updateRecordPage?: NonNullable>['update']; }; @@ -162,6 +173,7 @@ function Consumers() { const { favorites, addFavorite } = useFavorites(); const { recentItems, addRecentItem } = useRecentItems(); const { recents, recordRecent } = useFlowPaletteRecents(); + const { lastApp, rememberApp } = useLastApp(); const list = useObjectListPreferences('account'); const listPreference: ObjectListPreference = list.preference; const listOrderKey = JSON.stringify(listPreference.viewOrder ?? []); @@ -174,11 +186,12 @@ function Consumers() { favorites: favorites.map((f) => f.id), recent: recentItems.map((r) => r.id), flow: [...recents], + lastApp, listOrder: JSON.parse(listOrderKey), recordShowEmpty, }; - actions.current = { addFavorite, addRecentItem, recordRecent, patchListView, updateRecordPage }; - }, [favorites, recentItems, recents, listOrderKey, recordShowEmpty, addFavorite, addRecentItem, recordRecent, patchListView, updateRecordPage]); + actions.current = { addFavorite, addRecentItem, recordRecent, rememberApp, patchListView, updateRecordPage }; + }, [favorites, recentItems, recents, lastApp, listOrderKey, recordShowEmpty, addFavorite, addRecentItem, recordRecent, rememberApp, patchListView, updateRecordPage]); return
content
; } @@ -204,11 +217,11 @@ async function settle(ms = 150) { } const U1_SEEN: Seen = { - favorites: ['object:contact'], recent: ['object:lead'], flow: ['flow_step_alpha'], + favorites: ['object:contact'], recent: ['object:lead'], flow: ['flow_step_alpha'], lastApp: 'sales', listOrder: ['account.mine', 'account.all'], recordShowEmpty: true, }; const U2_SEEN: Seen = { - favorites: ['object:invoice'], recent: ['object:quote'], flow: ['flow_step_omega'], + favorites: ['object:invoice'], recent: ['object:quote'], flow: ['flow_step_omega'], lastApp: 'service', listOrder: ['account.all', 'account.closed'], recordShowEmpty: false, }; @@ -226,7 +239,7 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { vi.unstubAllGlobals(); }); - it('one boot puts one sys_user_preference read on the wire, asking for the three keys and both family prefixes', async () => { + it('one boot puts one sys_user_preference read on the wire, asking for the four keys and both family prefixes', async () => { boot(); await waitFor(() => expect(wire().gets.length).toBeGreaterThan(0)); await settle(); @@ -257,15 +270,16 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { actions.current.addFavorite?.({ id: 'object:account', label: 'Account', href: '/account', type: 'object' }); actions.current.addRecentItem?.({ id: 'object:deal', type: 'object', name: 'deal', href: '/deal' }); actions.current.recordRecent?.('flow_step_beta'); + actions.current.rememberApp?.('service'); actions.current.patchListView?.('account.all', { sort: [{ field: 'name', order: 'desc' }] }); actions.current.updateRecordPage?.('account', { showEmptyFields: false }); }); // Each provider debounces its write (500 ms; the record page writes on the - // click); all five land, once each. - await waitFor(() => expect(wire().writes).toHaveLength(5), { timeout: 3000 }); + // click); all six land, once each. + await waitFor(() => expect(wire().writes).toHaveLength(6), { timeout: 3000 }); await settle(); - expect(wire().writes).toHaveLength(5); + expect(wire().writes).toHaveLength(6); const byId = new Map(wire().writes.map((w) => [w.id, w])); // An update of the row its own load found — no insert, no other row. @@ -276,6 +290,7 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { ); expect((byId.get(rowId('u1', RECENT_KEY))?.value as { id: string }[])[0].id).toBe('object:deal'); expect(byId.get(rowId('u1', FLOW_KEY))?.value).toEqual(['flow_step_beta', 'flow_step_alpha']); + expect(byId.get(rowId('u1', LAST_APP_KEY))?.value).toEqual(['service']); // The object's row carries what it held and the new sort. expect(byId.get(rowId('u1', LIST_KEY))?.value).toEqual({ viewOrder: ['account.mine', 'account.all'], @@ -300,7 +315,7 @@ describe('console sys_user_preference request budget (objectui#12187)', () => { const afterSwitch = wire().gets.slice(before); const forU2 = afterSwitch.filter((g) => g.user === 'u2'); - // One read for the new user, asking for all three keys and both prefixes. + // One read for the new user, asking for all four keys and both prefixes. expect(forU2).toHaveLength(1); expect([...forU2[0].keys].sort()).toEqual([...BRIDGE_KEYS].sort()); expect([...forU2[0].prefixes].sort()).toEqual(BOTH_PREFIXES); diff --git a/ui/packages/app-shell/src/console/home/HomePage.tsx b/ui/packages/app-shell/src/console/home/HomePage.tsx index a78bb362514..5ca20464e50 100644 --- a/ui/packages/app-shell/src/console/home/HomePage.tsx +++ b/ui/packages/app-shell/src/console/home/HomePage.tsx @@ -40,6 +40,8 @@ import { useAgents, isAskAgent, agentHasCapability } from '@object-ui/plugin-cha // unknown→fail-open) lives with the hook. import { useCanAuthorMetadata, useCanReadPendingDrafts } from '../../hooks/useCanAuthorMetadata.js'; import { HomeAppsStrip } from './HomeAppsStrip.js'; +import { PhoneAppList } from '../../layout/PhoneAppList.js'; +import { appAddressSegment } from '../../utils/appRoute.js'; import { appSegmentOf, lastOpenedByApp } from './appLastOpened.js'; import { recentItemObject, recentItemTypeLabel } from './recentItemTypeLabel.js'; import { RecoveryPasswordReminder } from './RecoveryPasswordReminder.js'; @@ -676,6 +678,26 @@ export function HomePage({ checklist }: HomePageProps = {}) { ); } + // objectstack#35881 — on a phone, Home is the list of apps and nothing else: + // where a first sign-in with several apps lands, to pick one. It is the + // list the app pill's sheet shows inside an app, drawn as the whole page. + // The greeting, the templates, My work (the bottom bar's Notifications and + // Approvals carry it inside an app), the assistant card, Continue and the + // activity column are a desktop's (objectstack#34596's checklist with them). + if (phone && launcher.apps.length > 0) { + return ( +
+

+ {t('layout.appSwitcher.chooseApp', { defaultValue: 'Choose an app' })} +

+ navigate(`/apps/${appAddressSegment(apps, app) ?? app.name}`)} + /> +
+ ); + } + if (activeApps.length === 0) { return (
diff --git a/ui/packages/app-shell/src/console/home/__tests__/HomePage.phoneTapTargets-29147.test.tsx b/ui/packages/app-shell/src/console/home/__tests__/HomePage.phoneTapTargets-29147.test.tsx index bed235a0bc3..bb9d7dc6c1b 100644 --- a/ui/packages/app-shell/src/console/home/__tests__/HomePage.phoneTapTargets-29147.test.tsx +++ b/ui/packages/app-shell/src/console/home/__tests__/HomePage.phoneTapTargets-29147.test.tsx @@ -256,7 +256,7 @@ describe('"Recently accessed" and the activity feed (objectstack#29147)', () => }); }); -describe('the host checklist slot: above the page on a desktop, after the apps on a phone (objectstack#34596)', () => { +describe('the host checklist slot: above the page on a desktop; a phone with apps shows the app list alone (objectstack#34596, objectstack#35881)', () => { const realWidth = window.innerWidth; function atWidth(width: number) { Object.defineProperty(window, 'innerWidth', { value: width, configurable: true, writable: true }); @@ -286,15 +286,17 @@ describe('the host checklist slot: above the page on a desktop, after the apps o expect(follows(screen.getByTestId('home-apps-count'), marker)).toBe(true); }); - it('375 px: drawn once, after the apps and before "My work"; never above them', () => { + // objectstack#35881 — a phone's Home is the app list alone: the checklist + // goes with the rest of the page it used to sit in (objectstack#34596). + it('375 px with apps: the page is the app list, and no placement is asked for', () => { atWidth(375); const { placements, checklist } = slot(); render(); - const marker = screen.getByTestId('checklist-slot-afterApps'); - expect(screen.queryByTestId('checklist-slot-top')).toBeNull(); - expect(new Set(placements)).toEqual(new Set(['afterApps'])); - expect(follows(marker, screen.getByTestId('app-tile-app_0'))).toBe(true); - expect(follows(screen.getByTestId('home-my-work-open-inbox'), marker)).toBe(true); + expect(screen.getByTestId('home-phone-app-list')).toBeInTheDocument(); + expect(screen.getByTestId('phone-app-row-app_0')).toBeInTheDocument(); + expect(placements).toEqual([]); + expect(screen.queryByTestId('home-work-summary')).toBeNull(); + expect(screen.queryByTestId('home-my-work-open-inbox')).toBeNull(); }); it('375 px with no app yet: there are no apps to keep, so it is drawn above the empty state', () => { @@ -306,8 +308,8 @@ describe('the host checklist slot: above the page on a desktop, after the apps o expect(new Set(placements)).toEqual(new Set(['top'])); }); - it('CONTROL: with no slot given the page draws as it did', () => { - atWidth(375); + it('CONTROL: with no slot given a desktop page draws as it did', () => { + atWidth(1024); render(); expect(screen.queryByTestId('checklist-slot-top')).toBeNull(); expect(screen.queryByTestId('checklist-slot-afterApps')).toBeNull(); diff --git a/ui/packages/app-shell/src/context/LastAppProvider.tsx b/ui/packages/app-shell/src/context/LastAppProvider.tsx new file mode 100644 index 00000000000..37b0cc0884b --- /dev/null +++ b/ui/packages/app-shell/src/context/LastAppProvider.tsx @@ -0,0 +1,157 @@ +/** + * LastAppProvider + * + * The app this person last had open (objectstack#35881): where a phone lands + * after sign-in when the product declares no landing of its own and the + * person is served more than one app. Stored per person, so it follows them to + * another device: one `sys_user_preference` row, `ui.app.last`, holding the + * app's `name`, through the same adapter channel and the same one shared read + * the favorites and the recent items use (objectui#12187). The browser keeps a + * copy, scoped to the user, for the first frame and for a session with no + * adapter. + * + * Written whenever an app is open, at any width: it is the person's last app, + * not their last phone app. Read only by the phone's landing (`HomePage`). + * + * @module + */ + +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from 'react'; +import { useAuth } from '@object-ui/auth'; +import { + createDebouncedFlush, + scopedKey, + useStorageSync, + useUserStateAdapter, +} from './UserStateAdapters.js'; + +/** The preference row's key, and the browser copy's base key. */ +export const LAST_APP_PREFERENCE_KEY = 'ui.app.last'; + +interface LastAppValue { + /** The last app's `name`, or `null` when none is known. */ + lastApp: string | null; + /** + * Whether `lastApp` is an answer: the person's row has been read, or the + * browser already held a copy. Before that, a landing waits rather than + * showing the app list to someone who has a last app on the server. + */ + settled: boolean; + /** Record `name` as the app now open. */ + rememberApp: (name: string) => void; +} + +function sanitize(value: unknown): string | null { + const first = Array.isArray(value) ? value[0] : value; + return typeof first === 'string' && first ? first : null; +} + +function loadLocal(userId: string | null): string | null { + try { + const raw = localStorage.getItem(scopedKey(LAST_APP_PREFERENCE_KEY, userId)); + return raw ? sanitize(JSON.parse(raw)) : null; + } catch { + return null; + } +} + +function saveLocal(name: string, userId: string | null) { + try { + localStorage.setItem(scopedKey(LAST_APP_PREFERENCE_KEY, userId), JSON.stringify([name])); + } catch { + // storage full / privacy mode: the server row still carries it + } +} + +const LastAppContext = createContext(null); + +export function LastAppProvider({ children }: { children: ReactNode }) { + const { user } = useAuth(); + const userId = user?.id ?? null; + // A list-shaped adapter, like every slot: the list holds the one name. + const adapter = useUserStateAdapter('lastApp'); + + const [local, setLocal] = useState<{ userId: string | null; name: string | null }>(() => ({ + userId, + name: loadLocal(userId), + })); + const [remote, setRemote] = useState<{ adapter: unknown; name: string | null } | null>(null); + // A pick made in this session beats any read that lands after it. + const picked = useRef(null); + + if (local.userId !== userId) { + // Adjusted while rendering, on the signed-in user changing. + setLocal({ userId, name: loadLocal(userId) }); + picked.current = null; + } + + useStorageSync(scopedKey(LAST_APP_PREFERENCE_KEY, userId), (value) => { + setLocal({ userId, name: sanitize(value) }); + }); + + const flusher = useMemo( + () => + createDebouncedFlush(async (items) => { + if (adapter) await adapter.save(items); + }, 500), + [adapter], + ); + useEffect(() => () => void flusher.flush(), [flusher]); + + useEffect(() => { + if (!adapter) return; + let cancelled = false; + void adapter + .load() + .catch(() => []) + .then((items) => { + if (cancelled) return; + const name = sanitize(items); + setRemote({ adapter, name }); + if (name && !picked.current) saveLocal(name, userId); + }); + return () => { + cancelled = true; + }; + }, [adapter, userId]); + + const rememberApp = useCallback( + (name: string) => { + if (!name) return; + picked.current = name; + setLocal((prev) => (prev.name === name && prev.userId === userId ? prev : { userId, name })); + if (loadLocal(userId) === name && remote?.name === name) return; + saveLocal(name, userId); + if (adapter) flusher.schedule([name]); + }, + [userId, adapter, flusher, remote?.name], + ); + + const remoteName = remote && remote.adapter === adapter ? remote.name : null; + const remoteRead = !!remote && remote.adapter === adapter; + const lastApp = picked.current ?? remoteName ?? local.name; + const settled = remoteRead || local.name !== null || picked.current !== null; + + const value = useMemo( + () => ({ lastApp, settled, rememberApp }), + [lastApp, settled, rememberApp], + ); + return {children}; +} + +/** Outside a provider (unit tests, previews): nothing known, nothing kept. */ +const NO_LAST_APP: LastAppValue = { lastApp: null, settled: true, rememberApp: () => {} }; + +/** The person's last app, and the write that records the app now open. */ +export function useLastApp(): LastAppValue { + return useContext(LastAppContext) ?? NO_LAST_APP; +} diff --git a/ui/packages/app-shell/src/context/UserStateAdapters.tsx b/ui/packages/app-shell/src/context/UserStateAdapters.tsx index 88b46512cbb..5c307b8852d 100644 --- a/ui/packages/app-shell/src/context/UserStateAdapters.tsx +++ b/ui/packages/app-shell/src/context/UserStateAdapters.tsx @@ -36,12 +36,14 @@ import type { UserDataAdapter, UserPreferenceFamily } from '@object-ui/data-obje // on that declaration (objectui#6349, batch 9). export type { UserDataAdapter }; -export type UserStateKind = 'favorites' | 'recent' | 'flowPaletteRecents'; +export type UserStateKind = 'favorites' | 'recent' | 'flowPaletteRecents' | 'lastApp'; interface UserStateAdaptersValue { favorites: UserDataAdapter | null; recent: UserDataAdapter | null; flowPaletteRecents: UserDataAdapter | null; + /** objectstack#35881 — the person's last app (`ui.app.last`, `LastAppProvider`). */ + lastApp: UserDataAdapter | null; /** * objectui#12418 — the per-object list state (`ui.list.`), a key * FAMILY rather than one list: one row per object, loaded together by prefix @@ -71,6 +73,7 @@ const ReadCtx = createContext({ favorites: null, recent: null, flowPaletteRecents: null, + lastApp: null, listState: null, recordState: null, }); @@ -85,6 +88,7 @@ export function UserStateAdaptersProvider({ children }: { children: ReactNode }) favorites: null, recent: null, flowPaletteRecents: null, + lastApp: null, listState: null, recordState: null, }); diff --git a/ui/packages/app-shell/src/index.ts b/ui/packages/app-shell/src/index.ts index 9cce5710344..d6816da4372 100644 --- a/ui/packages/app-shell/src/index.ts +++ b/ui/packages/app-shell/src/index.ts @@ -283,6 +283,10 @@ export { useAttachUserStateAdapters, } from './context/index.js'; export type { UserDataAdapter, UserStateKind } from './context/index.js'; +// objectstack#35881 — the person's last app and the phone breakpoint: the +// console's `/` landing reads both on a phone. +export { useLastApp } from './context/LastAppProvider.js'; +export { usePhoneViewport } from './hooks/usePhoneViewport.js'; // Default page implementations (consumers can partial-override slots) export { AppContent as DefaultAppContent } from './console/AppContent.js'; diff --git a/ui/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index 4dc30ffe652..4f45e1dd8f0 100644 --- a/ui/packages/app-shell/src/layout/AppHeader.tsx +++ b/ui/packages/app-shell/src/layout/AppHeader.tsx @@ -71,6 +71,7 @@ import { ChevronLeft, } from 'lucide-react'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; +import { isPhoneTabRoute } from './PhoneAppNavBar.js'; import { useState, useEffect, useLayoutEffect, useCallback, useRef, type RefObject } from 'react'; import { useOffline } from '@object-ui/react'; @@ -449,10 +450,15 @@ export function AppHeader({ // landing, so the chrome cannot offer a second, contradicting "home". const homePath = useHomePath(); useGoHomeShortcut(isApp, homePath); - // objectstack#34594 — on a phone inside an app the menu is the bottom bar - // (its 「More」 opens the drawer), so the bar's leftmost control goes back - // to the environment's home instead of opening the drawer. + // objectstack#35881 — on a phone inside an app the menu is the app's home + // page. On that page and the two inbox pages the bottom bar opens + // (`isPhoneTabRoute`), the bar's left is the app pill with the app's name, + // which switches apps, and the bottom bar carries the search and the inbox, + // so the top bar does not repeat them. On every page below them the bar's + // leftmost control is 「‹」 back to the app's home. const phone = usePhoneViewport(); + const phoneTab = isApp && phone && isPhoneTabRoute(location.pathname); + const phoneAppHome = `/apps/${params.appName ?? activeAppName ?? ''}`; const { isOnline } = useOffline(); // Idempotent, direct open of the ⌘K command palette (ADR-0054 C1). Replaces a // synthetic `⌘K` KeyboardEvent re-dispatch that did nothing under automation. @@ -888,19 +894,21 @@ export function AppHeader({ collapse/expand toggle for the sidebar and its icon rail from 768 px up. It is the bar's leftmost control inside an app, so it never moves when the sidebar collapses; the sidebar itself carries - no trigger. On a phone that slot goes back to the environment's - home, and the drawer opens from the bottom menu bar's 「More」 - (objectstack#34594). */} + no trigger. On a phone that slot goes back to the app's home, the + app's menu (objectstack#35881), and on the app's home and the two + inbox pages it is not drawn: the app pill comes first there. */} {isApp && phone ? ( + phoneTab ? null : ( + ) ) : isApp ? ( ) : ( @@ -996,6 +1004,7 @@ export function AppHeader({ onAppChange={(segment) => confirmUnsavedLeave(() => onAppChange(segment))} designInStudioPath={studioEntry?.path ?? null} studioPosture={studioEntry?.posture} + showNameOnPhone={phoneTab} /> ) : appName ? ( @@ -1021,9 +1030,11 @@ export function AppHeader({ (objectstack#27058), so the bar draws no view dropdown. No margin of its own: the pill's padding already parts the two, and the width goes to the label (objectstack#34596). */} - - {lastSegmentLabel} - + {!phoneTab && ( + + {lastSegmentLabel} + + )} )} @@ -1069,7 +1080,7 @@ export function AppHeader({ {/* Group 1: Search */} {/* Only where a palette is mounted (objectui#11912) — see `hasCommandPalette`. */} - {hasCommandPalette && ( + {hasCommandPalette && !phoneTab && (
+ )} {/* AI Assistant — only when the runtime serves AI (hidden on Community Edition so it can't dead-end on an agent-less chat). diff --git a/ui/packages/app-shell/src/layout/AppSwitcher.tsx b/ui/packages/app-shell/src/layout/AppSwitcher.tsx index 83885738444..37b070cfd27 100644 --- a/ui/packages/app-shell/src/layout/AppSwitcher.tsx +++ b/ui/packages/app-shell/src/layout/AppSwitcher.tsx @@ -26,6 +26,9 @@ import * as React from 'react'; import { Link } from 'react-router-dom'; import { + Sheet, + SheetContent, + SheetTitle, DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, @@ -33,7 +36,7 @@ import { DropdownMenuLabel, DropdownMenuSeparator, } from '@object-ui/components'; -import { ChevronDown, Check, Eye, Home, LayoutGrid, Pencil, Settings } from 'lucide-react'; +import { ChevronDown, ChevronsUpDown, Check, Eye, Home, LayoutGrid, Pencil, Settings } from 'lucide-react'; import { useMetadata } from '../providers/MetadataProvider.js'; import { matchAppBySegment, appRouteSegment } from '../utils/index.js'; import { appAddressSegment } from '../utils/appRoute.js'; @@ -45,6 +48,8 @@ import { SETUP_APP_NAME, SETUP_APP_PACKAGE_ID } from '../console/ConsoleShell.js import { GO_HOME_SHORTCUT, shortcutKeycaps } from '../chrome/advertisedShortcuts.js'; import { isSingleAppSwitcherHidden } from '../runtime-config.js'; import { AppMark } from './AppMark.js'; +import { PhoneAppList } from './PhoneAppList.js'; +import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; /** * The Setup app in an app list: by its package id first, then by its name — @@ -73,10 +78,26 @@ export interface AppSwitcherProps { * posture, passed in for the same reason as the path. */ studioPosture?: 'edit' | 'view'; + /** + * On a phone, draw the app's name beside its glyph (objectstack#35881): the + * app's home and the two inbox pages, where the pill is the bar's title. + * Elsewhere on a phone the pill is the glyph alone, as before. + */ + showNameOnPhone?: boolean; } -export function AppSwitcher({ activeAppName, onAppChange, designInStudioPath, studioPosture = 'edit' }: AppSwitcherProps) { +export function AppSwitcher({ + activeAppName, + onAppChange, + designInStudioPath, + studioPosture = 'edit', + showNameOnPhone = false, +}: AppSwitcherProps) { const { apps: metadataApps } = useMetadata(); + // objectstack#35881 — on a phone the pill opens the app list as a bottom + // sheet rather than a dropdown. Read before any return (rules of hooks). + const phone = usePhoneViewport(); + const [sheetOpen, setSheetOpen] = React.useState(false); const { t } = useObjectTranslation(); const { appLabel } = useServedAppLabel(); // objectui#7256 — 「All apps」 goes to the DECLARED home, like every other @@ -131,6 +152,51 @@ export function AppSwitcher({ activeAppName, onAppChange, designInStudioPath, st // to switch between. Read off the viewer's own list: a viewer whose list // carries no Setup app (the server withholds it without `setup.access`) is // offered no row. + if (phone) { + const switchLabel = t('layout.appSwitcher.switchApplication', { defaultValue: 'Switch Application' }); + return ( + + + +
+ {switchLabel} +
+ { + setSheetOpen(false); + if (app.name !== activeApp.name) onAppChange(appAddressSegment(apps, app) ?? app.name); + }} + /> +
+
+ ); + } + const setupApp = findSetupApp(activeApps); const switchApps = setupApp ? activeApps.filter((app) => app !== setupApp) : activeApps; const setupPath = setupApp ? `/apps/${appRouteSegment(setupApp) ?? setupApp.name}` : null; diff --git a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx index 3daa18a68cc..ceae7b13336 100644 --- a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx +++ b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx @@ -23,6 +23,11 @@ import { DraftPreviewBar } from '../preview/DraftPreviewBar.js'; import { UnpublishedAppBar } from '../preview/UnpublishedAppBar.js'; import { ConsoleNotificationBanners } from './ConsoleNotificationBanners.js'; import { UnifiedSidebar } from './UnifiedSidebar.js'; +import { PhoneAppNavBar, isPhoneTabRoute } from './PhoneAppNavBar.js'; +import { PhoneAppHomeSlotProvider } from './PhoneAppHome.js'; +import { useLastApp } from '../context/LastAppProvider.js'; +import { useMetadata } from '../providers/MetadataProvider.js'; +import { appAddressSegment } from '../utils/appRoute.js'; import { AppHeader } from './AppHeader.js'; import { useResponsiveSidebar } from '../hooks/useResponsiveSidebar.js'; import { usePhoneNavDrawerHistory } from './usePhoneNavDrawerHistory.js'; @@ -130,19 +135,6 @@ export function isRecordPagePath(pathname: string): boolean { return /^\/apps\/[^/]+\/[^/]+\/record\/[^/]+(?:\/page\/[^/]+)?\/?$/.test(pathname); } -/** - * Does `pathname` keep the phone's bottom menu bar off (objectstack#34594)? A - * record page (its bottom edge is the record's action bar) and a record form, - * create (`/apps/APP/OBJECT/new`) or edit (`.../record/ID/edit`), whose bottom - * edge is its submit buttons. Every other app route draws the bar. - */ -export function hidesPhoneNavBar(pathname: string): boolean { - return ( - isRecordPagePath(pathname) || - /^\/apps\/[^/]+\/[^/]+\/(?:new|record\/[^/]+\/edit)\/?$/.test(pathname) - ); -} - /** Inner component that can access SidebarProvider context */ function ConsoleLayoutInner({ children }: { children: React.ReactNode }) { useResponsiveSidebar(); @@ -187,10 +179,20 @@ export function ConsoleLayout({ // page draws its phone face at, so the two never disagree for a frame. const phone = usePhoneViewport(); const recordPageOwnsTopBar = phone && isRecordPagePath(location.pathname); - // objectstack#34594 — on a phone the app's menu is a bar along the bottom - // edge, except where that edge belongs to a record's actions or a form's - // submit buttons. The route slot leaves the bar's height free at its end. - const phoneNavBar = phone && !hidesPhoneNavBar(location.pathname); + // objectstack#35882 — on a phone the bottom bar (Home, Notifications, + // Approvals, search) is drawn on the three pages it opens and on no page + // below them: a list, a record or a form has the page to itself, and 「‹」 at + // the top left goes back. The route slot leaves the bar's height free at its + // end. + const phoneNavBar = phone && isPhoneTabRoute(location.pathname); + // objectstack#35881 — the app this person last had open, where a phone + // lands after sign-in. Recorded at every width: it is the person's last app. + const { rememberApp } = useLastApp(); + useEffect(() => { + if (activeAppName) rememberApp(activeAppName); + }, [activeAppName, rememberApp]); + const { apps: metadataApps } = useMetadata(); + const appBasePath = `/apps/${appAddressSegment(metadataApps, activeApp) ?? activeAppName}`; // objectstack#30043 — the page in view, handed to the dock as its // `context.surface` (cloud#1610's shape): the object of a list, the object // and record id of a record page, the dashboard, report or page. Read off the @@ -241,13 +243,15 @@ export function ConsoleLayout({ {/* objectui#13130 — first in the DOM, so it is the first Tab stop. */} + {/* objectstack#35881 — the phone app home's slot, shared by the sidebar + (which draws the menu into it) and the route (which holds it). */} + } showHeader={!recordPageOwnsTopBar} @@ -270,14 +274,15 @@ export function ConsoleLayout({ // the table's, the record-count footer below the fold. The phone keeps // block layout. // - // objectstack#34594 — while the phone menu bar is drawn, the inset keeps - // the bar's height (h-12 plus the safe area) free at its bottom: a page + // objectstack#34594 — while the phone bottom bar is drawn, the inset keeps + // the bar's height (h-12, its 4 px padding each side, plus the safe + // area; objectstack#35882) free at its bottom: a page // that bounds itself to the inset ends above the bar (the inset's // content box is that much shorter), and a taller page scrolls its last // row out from under the bar (a scroll container's end padding scrolls). className={cn( '!p-0 overflow-y-auto overflow-x-hidden bg-muted/5 lg:flex lg:flex-col', - phoneNavBar && '!pb-[calc(3rem+env(safe-area-inset-bottom))]', + phoneNavBar && '!pb-[calc(3.5rem+env(safe-area-inset-bottom))]', )} rightRail={chatDock.rail} branding={ @@ -331,9 +336,13 @@ export function ConsoleLayout({
+ {/* objectstack#35882 — the phone's bottom bar, after the page in reading order. */} + {phoneNavBar && } + {/* Under `md` the drawer is a bottom sheet (no room for a rail on a phone). */} {chatDock.sheet} + ); diff --git a/ui/packages/app-shell/src/layout/PhoneAppHome.tsx b/ui/packages/app-shell/src/layout/PhoneAppHome.tsx new file mode 100644 index 00000000000..240da391899 --- /dev/null +++ b/ui/packages/app-shell/src/layout/PhoneAppHome.tsx @@ -0,0 +1,98 @@ +/** + * PhoneAppHome + * + * A phone's app home (objectstack#35881): the app's root, `/apps/SEGMENT`, + * shows the app's whole menu, its groups and its order, one row per entry with + * its icon. A tap opens the entry's page (an object's list, a dashboard, a + * report, a page), and 「‹」 there comes back here, where the page is scrolled + * as it was left. From 768 px up the app root still opens the app's landing + * entry, as before. + * + * The menu is the sidebar's own: `UnifiedSidebar` draws its navigation tree + * (the same `NavigationRenderer`, pruned by the same member gates, with the + * same area switcher, labels and icons) into the slot this page holds, through + * a portal. So the page cannot list an entry the sidebar hides, or order + * them differently: there is one menu, shown in a second place. + * + * @module + */ + +import * as React from 'react'; +import { useLayoutEffect, useRef } from 'react'; + +interface SlotContextValue { + slot: HTMLElement | null; + setSlot: (el: HTMLElement | null) => void; +} + +const PhoneAppHomeSlotContext = React.createContext(null); + +/** Holds the page's slot element for the sidebar to draw into. `ConsoleLayout` mounts it. */ +export function PhoneAppHomeSlotProvider({ children }: { children: React.ReactNode }) { + const [slot, setSlot] = React.useState(null); + const value = React.useMemo(() => ({ slot, setSlot }), [slot]); + return {children}; +} + +/** The element the phone app home holds open for the menu, or `null` when none is mounted. */ +export function usePhoneAppHomeSlot(): HTMLElement | null { + return React.useContext(PhoneAppHomeSlotContext)?.slot ?? null; +} + +/** Where each app's home was scrolled to when it was left, by app address. */ +const scrollByApp = new Map(); + +/** The nearest ancestor that scrolls vertically (the console's inset), else the document's scroller. */ +function scrollParentOf(el: HTMLElement): HTMLElement { + for (let node = el.parentElement; node; node = node.parentElement) { + const { overflowY } = window.getComputedStyle(node); + if (overflowY === 'auto' || overflowY === 'scroll') return node; + } + return (document.scrollingElement as HTMLElement | null) ?? document.documentElement; +} + +export interface PhoneAppHomeProps { + /** The app's address, `/apps/SEGMENT`: the key its scroll position is kept under. */ + basePath: string; +} + +export function PhoneAppHome({ basePath }: PhoneAppHomeProps) { + const setSlot = React.useContext(PhoneAppHomeSlotContext)?.setSlot; + const rootRef = useRef(null); + + // Come back where the page was left: the menu renders into the slot in the + // same commit, so the restore waits a frame for the rows (a long menu draws + // its rest right after the first frame) and asks again once more after it. + useLayoutEffect(() => { + const root = rootRef.current; + if (!root) return; + const saved = scrollByApp.get(basePath); + const target = scrollParentOf(root); + const frames: number[] = []; + if (saved) { + const restore = () => { + target.scrollTop = saved; + }; + frames.push(requestAnimationFrame(() => { + restore(); + frames.push(requestAnimationFrame(restore)); + })); + } + let last = saved ?? 0; + const onScroll = () => { + last = target.scrollTop; + }; + target.addEventListener('scroll', onScroll, { passive: true }); + return () => { + frames.forEach((id) => cancelAnimationFrame(id)); + target.removeEventListener('scroll', onScroll); + scrollByApp.set(basePath, last); + }; + }, [basePath]); + + return ( +
+
+
+ ); +} diff --git a/ui/packages/app-shell/src/layout/PhoneAppList.tsx b/ui/packages/app-shell/src/layout/PhoneAppList.tsx new file mode 100644 index 00000000000..1451ec2ef1a --- /dev/null +++ b/ui/packages/app-shell/src/layout/PhoneAppList.tsx @@ -0,0 +1,130 @@ +/** + * PhoneAppList + * + * The phone's list of apps (objectstack#35881): 「Current app」 with a check, + * then 「Other apps」, and a search box at the bottom that narrows both. One + * list, two containers: the bottom sheet the app pill opens inside an app + * (`AppSwitcher` on a phone), and the whole page a phone shows at `/home`, the + * list a first sign-in with several apps lands on. + * + * The apps are the launcher's (`useLauncherApps`: active, not hidden, and not + * withheld by `/me/apps`), the same set the desktop switcher and the Home + * tiles offer. Setup is in the list like any other app, last. + * + * @module + */ + +import * as React from 'react'; +import { Check, Search } from 'lucide-react'; +import { cn } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { useMetadata } from '../providers/MetadataProvider.js'; +import { useLauncherApps } from '../hooks/useLauncherApps.js'; +import { useServedAppLabel } from '../hooks/useServedAppLabel.js'; +import { matchAppBySegment } from '../utils/index.js'; +import { SETUP_APP_NAME, SETUP_APP_PACKAGE_ID } from '../console/ConsoleShell.js'; +import { AppMark } from './AppMark.js'; + +export interface PhoneAppListProps { + /** The app open now (its route segment or name), checked under 「Current app」. */ + activeAppName?: string; + /** Called with the picked app. */ + onPick: (app: any) => void; + /** `sheet` inside the switcher, `page` for `/home`. */ + variant: 'sheet' | 'page'; +} + +const ROW_CLASS = + 'flex min-h-12 w-full items-center gap-3 rounded-xl border bg-card px-3 text-left text-[15px] font-medium transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring'; + +function isSetupApp(app: any): boolean { + return app?._packageId === SETUP_APP_PACKAGE_ID || app?.name === SETUP_APP_NAME; +} + +export function PhoneAppList({ activeAppName, onPick, variant }: PhoneAppListProps) { + const { t } = useObjectTranslation(); + const { apps: metadataApps } = useMetadata(); + const { apps: launcherApps } = useLauncherApps(metadataApps || []); + const { appLabel } = useServedAppLabel(); + const [query, setQuery] = React.useState(''); + + const current = activeAppName ? matchAppBySegment(launcherApps, activeAppName) : undefined; + const ordered = [ + ...launcherApps.filter((app: any) => !isSetupApp(app)), + ...launcherApps.filter((app: any) => isSetupApp(app)), + ]; + const needle = query.trim().toLocaleLowerCase(); + const matches = (app: any) => !needle || String(appLabel(app) ?? '').toLocaleLowerCase().includes(needle); + const showCurrent = !!current && matches(current); + const others = ordered.filter((app: any) => app !== current && matches(app)); + + const row = (app: any, isCurrent: boolean) => ( +
  • + +
  • + ); + + const searchLabel = t('layout.appSwitcher.searchApps', { defaultValue: 'Search apps…' }); + + return ( +
    +
    + {showCurrent && ( +
    +

    + {t('layout.appSwitcher.currentApp', { defaultValue: 'Current app' })} +

    +
      {row(current, true)}
    +
    + )} + {others.length > 0 && ( +
    +

    + {current + ? t('layout.appSwitcher.otherApps', { defaultValue: 'Other apps' }) + : t('layout.appSwitcher.yourApps', { defaultValue: 'Your apps' })} +

    +
      {others.map((app: any) => row(app, false))}
    +
    + )} + {!showCurrent && others.length === 0 && ( +

    + {t('layout.appSwitcher.noAppsMatch', { defaultValue: 'No apps match' })} +

    + )} +
    +
    + +
    +
    + ); +} diff --git a/ui/packages/app-shell/src/layout/PhoneAppNavBar.tsx b/ui/packages/app-shell/src/layout/PhoneAppNavBar.tsx index d772853b7f0..107b2987702 100644 --- a/ui/packages/app-shell/src/layout/PhoneAppNavBar.tsx +++ b/ui/packages/app-shell/src/layout/PhoneAppNavBar.tsx @@ -1,241 +1,153 @@ /** * PhoneAppNavBar * - * The phone's bottom menu bar inside an app (objectstack#34594). Below 768 px - * the app's menu lived only in the sidebar drawer, behind an unlabeled icon at - * the top left, and many users never found it. The bar keeps the menu on - * screen: up to four of the app's entries, then 「More」, which opens the full - * menu (the drawer) where every entry carries a star. + * The phone's bottom bar inside an app (objectstack#35882). Three fixed cells, + * Home, Notifications and Approvals, and a round search button beside them. + * They do not change with the app and the user does not configure them: the + * app's menu is the app's home page (objectstack#35881), so the bar no longer + * holds menu entries, a 「More」 cell or the stars that pinned entries to it + * (objectstack#34594, superseded; pins already stored are simply not read). * - * Which four: the entries the user pinned (the star, `useNavPins`, the same - * per-user store the desktop sidebar's Favorites section reads), in the - * user's pinned order, then the app's own entries in menu order to fill the - * rest. Pins are stored by navigation id and are not scoped per app, so only - * the pins this app's menu holds are read here. No metadata key is involved. + * - Home opens the current app's home, its whole menu (`/apps/SEGMENT`). + * - Notifications opens the full-page inbox the bell's 「View all」 opens + * (`sys_inbox_message?view=mine`), and Approvals the approvals inbox + * (`system/approvals`), both hosted under the app the bell hosts them under + * (`resolveHostAppSegment`), so the two doors cannot lead to two pages. + * - Search opens the console's command palette, as the top bar's search does. * - * What it draws is what the drawer draws: the tree it is handed is the - * sidebar's own (already pruned of entries the member may not read), walked by - * `drawnNavigationEntries`, the sidebar's guard statement and order rule. - * A cell opens what its drawer row opens (`resolveHref`), and lights when - * that row lights (`resolveActiveNavItem`). When the row that lights is drawn - * in the full menu but holds no cell, 「More」 lights in its place - * (objectstack#35020): one cell at most is lit, and it is the way back to the - * page in view. + * The badges are the bell's two addends (`useInboxBell`, the one wiring of the + * shared feeds): unread notification topics on Notifications, pending + * approvals on Approvals. Each sits inside its cell, on the glyph's corner, so + * the bar's edge cannot cut it (objectstack#34596). * - * The console layout decides where the bar is mounted: on a phone, inside an - * app, never on a record page or a record form, whose bottom edge belongs to - * the record's own action bar and submit buttons. + * The console layout mounts the bar on the three pages it opens and nowhere + * else (`isPhoneTabRoute`): a list, a record, a form or any other page one + * level down has the page to itself, and 「‹」 at the top left goes back. * * @module */ +import { useMemo } from 'react'; import { Link, useLocation } from 'react-router-dom'; -import { MoreHorizontal, Star } from 'lucide-react'; -import { SidebarMenuAction, cn } from '@object-ui/components'; -import { - drawnNavigationEntries, - resolveActiveNavItem, - resolveHref, - resolveIcon, - resolveNavItemIcon, - resolveNavItemLabel, - type NavigationVisibilityOptions, - type NavTargetIconResolver, - type NavTargetLabelResolver, - type NavTemplateContext, -} from '@object-ui/layout'; -import type { NavigationItem } from '@object-ui/types'; +import { Bell, CheckSquare, Home, Search } from 'lucide-react'; +import { cn } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { useInboxBell } from '../hooks/useInboxBell.js'; +import { useMetadata } from '../providers/MetadataProvider.js'; +import { useCommandPalette } from '../context/CommandPaletteProvider.js'; +import { groupNotifications } from './inboxGrouping.js'; +import { resolveHostAppSegment } from '../utils/appRoute.js'; -/** How many of the app's entries the bar holds; 「More」 is the cell after them. */ -export const PHONE_NAV_BAR_ENTRY_CELLS = 4; +/** Which of the three cells a path opens, or `null` for any other page. */ +export type PhoneTab = 'home' | 'notifications' | 'approvals'; /** - * The bar's entries: the app's pinned entries in the user's pinned order, - * then the app's drawn entries in menu order, to at most `cells` entries. A - * pinned id this app's menu does not draw (another app's pin, or an entry the - * member cannot see) takes no cell. + * The cell `pathname` is the page of: the app's root (its home), the inbox + * list, or the approvals inbox. `null` for every other route, where the bar is + * not drawn. */ -export function phoneNavBarEntries( - items: readonly NavigationItem[], - pinnedIds: readonly string[], - guards: NavigationVisibilityOptions, - hasAddress: (item: NavigationItem) => boolean, - cells: number = PHONE_NAV_BAR_ENTRY_CELLS, -): NavigationItem[] { - // The drawer's rows in its reading order (the walk every tab bar shares), - // less `action` entries (an action runs something; a cell opens a page) and - // entries whose target resolves to no address. - const entries: NavigationItem[] = drawnNavigationEntries(items, guards).filter( - (entry) => entry.type !== 'action' && hasAddress(entry), - ); - const byId = new Map(entries.map((entry) => [entry.id, entry])); - const chosen: NavigationItem[] = []; - const taken = new Set(); - for (const id of pinnedIds) { - const entry = byId.get(id); - if (!entry || taken.has(id)) continue; - chosen.push(entry); - taken.add(id); - if (chosen.length === cells) return chosen; - } - for (const entry of entries) { - if (taken.has(entry.id)) continue; - chosen.push(entry); - taken.add(entry.id); - if (chosen.length === cells) break; - } - return chosen; +export function phoneTabOf(pathname: string): PhoneTab | null { + const parts = pathname.split('/').filter(Boolean); + if (parts[0] !== 'apps' || !parts[1]) return null; + if (parts.length === 2) return 'home'; + if (parts.length === 3 && parts[2] === 'sys_inbox_message') return 'notifications'; + if (parts.length === 4 && parts[2] === 'system' && parts[3] === 'approvals') return 'approvals'; + return null; +} + +/** Is `pathname` one of the three pages the phone's bottom bar opens? */ +export function isPhoneTabRoute(pathname: string): boolean { + return phoneTabOf(pathname) !== null; } export interface PhoneAppNavBarProps { - /** The app's navigation tree, as the sidebar holds it (pruned, every visible area). */ - items: NavigationItem[]; - /** The pinned navigation ids, in the user's order (`useNavPins().pinnedIds`). */ - pinnedIds: readonly string[]; - /** The app's address, `/apps/SEGMENT`. */ + /** The app's address, `/apps/SEGMENT`: where Home goes. */ basePath: string; - /** The sidebar's guard inputs. */ - guards: NavigationVisibilityOptions; - templateContext?: NavTemplateContext; - resolveTargetLabel?: NavTargetLabelResolver; - resolveTargetIcon?: NavTargetIconResolver; - locale?: string; - t: (key: string, options?: Record) => string; - /** Whether the full menu is open, so 「More」 reads as the current cell. */ - menuOpen: boolean; - /** Opens the full menu (the drawer). */ - onOpenMenu: () => void; + /** The app's `name` (what `ConsoleLayout` publishes), for the inboxes' host. */ + activeAppName: string; } /** One cell's box: a 44 px-tall target, icon over label. */ const CELL_CLASS = 'relative flex min-w-0 flex-1 flex-col items-center justify-center gap-0.5 px-1 text-[11px] leading-tight transition-colors outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring'; -export function PhoneAppNavBar({ - items, - pinnedIds, - basePath, - guards, - templateContext, - resolveTargetLabel, - resolveTargetIcon, - locale, - t, - menuOpen, - onOpenMenu, -}: PhoneAppNavBarProps) { +const BADGE_CLASS = + 'absolute top-0.5 left-1/2 ml-1.5 h-4 min-w-[16px] rounded-full bg-red-500 px-1 text-center text-[10px] leading-4 text-white'; + +export function PhoneAppNavBar({ basePath, activeAppName }: PhoneAppNavBarProps) { const location = useLocation(); - const hasAddress = (item: NavigationItem) => { - const { href } = resolveHref(item, basePath, templateContext); - return !!href && href !== '#'; - }; - const entries = phoneNavBarEntries(items, pinnedIds, guards, hasAddress); - // The row the drawer lights, elected over the whole tree as the drawer - // elects it, so at most one cell lights and it is that row. - const currentId = - resolveActiveNavItem(items, location.pathname, location.search, basePath, templateContext)?.id ?? null; - const activeId = menuOpen ? null : currentId; - // A row the full menu draws but no cell holds lights 「More」, the cell that - // opens it. A page no drawn row addresses lights nothing: 「More」 lit says - // the menu behind it has the page's row selected. While the menu is open, - // 「More」 is lit for the open menu and the bar marks no page. - const currentBehindMore = - currentId !== null && - !entries.some((entry) => entry.id === currentId) && - drawnNavigationEntries(items, guards).some((entry) => entry.id === currentId); - const moreMarksPage = !menuOpen && currentBehindMore; - const moreLabel = t('common.more', { defaultValue: 'More' }); + const { t } = useObjectTranslation(); + const { apps } = useMetadata(); + const { openCommandPalette } = useCommandPalette(); + const { notifications, pendingApprovalsCount } = useInboxBell(); + // The bell's own count: unread TOPICS, not raw rows (#2765). + const unreadTopics = useMemo( + () => groupNotifications(notifications).reduce((sum, g) => sum + (g.unreadCount > 0 ? 1 : 0), 0), + [notifications], + ); + const host = resolveHostAppSegment(apps, activeAppName); + const current = phoneTabOf(location.pathname); + + const cells: Array<{ tab: PhoneTab; to: string; label: string; Icon: typeof Home; badge: number }> = [ + { tab: 'home', to: basePath, label: t('console.nav.phoneHome', { defaultValue: 'Home' }), Icon: Home, badge: 0 }, + { + tab: 'notifications', + // `?view=mine`: the user-scoped view, the bell's 「View all」 target. + to: `/apps/${host}/sys_inbox_message?view=mine`, + label: t('console.nav.phoneNotifications', { defaultValue: 'Notifications' }), + Icon: Bell, + badge: unreadTopics, + }, + { + tab: 'approvals', + to: `/apps/${host}/system/approvals`, + label: t('console.nav.phoneApprovals', { defaultValue: 'Approvals' }), + Icon: CheckSquare, + badge: pendingApprovalsCount, + }, + ]; + const searchLabel = t('console.nav.phoneSearch', { defaultValue: 'Search' }); return ( ); } - -export interface PhoneMenuStarProps { - /** The text the row shows. */ - label: string; - /** The entry is pinned (it is offered to the bottom bar). */ - pinned: boolean; - onToggle: () => void; - t: (key: string, options?: Record) => string; -} - -/** - * The star a full-menu row carries on a phone (objectstack#34594): one tap - * pins the entry, through the same pin store the desktop sidebar's ⋯ menu - * writes, so it joins the bottom bar; another tap unpins it. Drawn at rest, - * not on hover (a phone has none), centred on the 44 px row. - */ -export function PhoneMenuStar({ label, pinned, onToggle, t }: PhoneMenuStarProps) { - const name = pinned - ? t('console.nav.unpinItem', { defaultValue: 'Unpin {{name}}', name: label }) - : t('console.nav.pinItem', { defaultValue: 'Pin {{name}}', name: label }); - return ( - - - - ); -} diff --git a/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx b/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx index d795f05ffe5..67829b8674f 100644 --- a/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx +++ b/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx @@ -14,6 +14,7 @@ */ import * as React from 'react'; +import { createPortal } from 'react-dom'; import { Link, useLocation } from 'react-router-dom'; import { getIcon } from '../utils/getIcon.js'; import { @@ -28,7 +29,6 @@ import { SidebarMenuItem, SidebarMenuButton, SidebarMenuAction, - SidebarInput, cn, useSidebar, } from '@object-ui/components'; @@ -81,7 +81,7 @@ import { SortableFavoriteRows, type FavoriteRowDragProps } from './SortableFavor import { favoriteAppSegment } from './listViewFavorites.js'; import { electSidebarArea, type SidebarAreaRoute } from './sidebarAreaElection.js'; import type { FavoriteItem } from '../hooks/useFavorites.js'; -import { PhoneAppNavBar, PhoneMenuStar } from './PhoneAppNavBar.js'; +import { usePhoneAppHomeSlot } from './PhoneAppHome.js'; /** * The class the Recent group's label carries so that, once the sidebar @@ -158,13 +158,6 @@ interface UnifiedSidebarProps { * every width, collapsed to the primitive's icon rail. */ railOverlay?: boolean; - /** - * On a phone, draw the app's bottom menu bar (objectstack#34594) and give the - * drawer, which its 「More」 cell opens, a search box and a star per entry. - * The console layout decides it: a phone, inside an app, not on a record - * page or a record form. Ignored outside an app and from 768 px up. - */ - phoneNavBar?: boolean; } function isMetadataDirectoryItem(item: NavigationItem): boolean { @@ -182,8 +175,8 @@ function isOverviewGroup(item: NavigationItem): boolean { return id === 'overview' || label === 'overview'; } -export function UnifiedSidebar({ activeAppName, railOverlay = false, phoneNavBar = false }: UnifiedSidebarProps) { - const { isMobile, openMobile, setOpenMobile } = useSidebar(); +export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSidebarProps) { + const { isMobile, setOpenMobile } = useSidebar(); const location = useLocation(); const { t, language } = useObjectTranslation(); const { appLabel } = useServedAppLabel(); @@ -514,34 +507,11 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false, phoneNavBar // Recent section collapsed by default const [recentExpanded, setRecentExpanded] = React.useState(false); - // objectstack#34594 — the phone's bottom menu bar and the full menu its - // 「More」 cell opens. The bar reads every visible area of the app (the drawer - // shows one area at a time; a pin from another area keeps its cell), and the - // same pruned trees the drawer draws. Studio's menu is the rewritten one the - // drawer shows. - const phoneMenu = isMobile && phoneNavBar && context === 'app' && !!activeApp; - const phoneBarItems: NavigationItem[] = isStudioApp - ? studioNavigationItems - : visibleAreas.length > 0 - ? visibleAreas.flatMap((area) => area.navigation ?? []) - : readableAppNavigation ?? []; - // The full menu's search: ephemeral, cleared whenever the drawer closes. - const [menuQuery, setMenuQuery] = React.useState(''); - const [menuQueryOpen, setMenuQueryOpen] = React.useState(openMobile); - if (menuQueryOpen !== openMobile) { - // Adjusted while rendering, on the drawer's open state changing (React's - // "adjusting state when a prop changes"), not in an effect. - setMenuQueryOpen(openMobile); - if (!openMobile) setMenuQuery(''); - } - const renderPhoneMenuStar = (item: NavigationItem, row: NavItemActionContext) => ( - togglePin(item.id, !item.pinned, item, row.basePath)} - t={t} - /> - ); + // objectstack#35881 — on a phone the app's root is the app's home, its whole + // menu: this sidebar draws its own navigation tree into the slot that page + // holds (`PhoneAppHome`), so the page lists what the sidebar lists, in its + // order, under the same gates. + const phoneHomeSlot = usePhoneAppHomeSlot(); // One ⋯ menu on every entry, in place of the pin action (objectui#12427): // its first entry adds the entry to Favorites or removes it, through the @@ -618,66 +588,11 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false, phoneNavBar /> ); - return ( -
    - - {/* Mobile-only drawer header — the app's glyph and name (objectui#12201 - item 3). On a phone the top bar hides the app pill, so this is the - one place that says which app the user is in. It replaces the old - Home row, and keeps that row's job: the trailing 「All apps」 - button is the way back out of the app, since a phone has no - path-separator, no back arrow and no top-bar pill to open. Render - it inside the sheet header so it survives the SidebarHeader vs - SidebarContent split. */} - {isMobile && context === 'app' && activeApp && ( - -
    - - - {appLabel(activeApp)} - - setOpenMobile(false)} data-testid="mobile-sidebar-home" aria-label={t('layout.appSwitcher.allApps', { defaultValue: 'All apps' })} title={t('layout.appSwitcher.allApps', { defaultValue: 'All apps' })} className="inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-muted-foreground transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring"> - - -
    - {/* objectstack#34594 — the full menu the bottom bar's 「More」 - opens: searchable, and each entry's star offers it to the bar. */} - {phoneMenu && ( -
    - setMenuQuery(event.target.value)} - placeholder={t('console.nav.searchMenu', { defaultValue: 'Search menu' })} - aria-label={t('console.nav.searchMenu', { defaultValue: 'Search menu' })} - data-testid="phone-menu-search" - className="h-10 text-[15px]" - /> -

    - {t('console.nav.phoneBarHint', { - defaultValue: 'Star an entry to put it in the bottom bar. The bar shows the first four.', - })} -

    -
    - )} -
    - )} - - {/* The sidebar's one navigation landmark, so assistive tech can jump - to it. The `Sidebar` primitive draws a plain `div` (and a dialog on - a phone) and is Shadcn-synced, so the landmark rides inside its - content slot, where it reaches the drawer as well. */} -