diff --git a/.changeset/35424-all-docs-page.md b/.changeset/35424-all-docs-page.md new file mode 100644 index 00000000000..60be18f71f8 --- /dev/null +++ b/.changeset/35424-all-docs-page.md @@ -0,0 +1,19 @@ +--- +'@objectstack/client': patch +'@object-ui/console': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): the 「All documentation」 page has the console's top bar, groups its books by app, and searches every article + +Clause-②: yes (widening) — @objectstack/client `meta.getItems` takes an optional `include` (`'content' | 'grants'`, sent as `?include=`) and exports its options type `MetaItemsListOptions`; @object-ui/i18n adds nine help.* keys (two of them plural, with their per-locale forms); nothing removed +Metadata-protocol: none + +- **The console's top bar on every portal page.** `/docs`, a book (`/docs/`) and an article (`/docs//
`) are drawn in Home's frame, whose bar reads 「 / Documentation」 (the crumb links to the portal's index) and carries the search, the inbox, the assistant and the avatar menu, so the reader can go back to any app. The portal's own 「Documentation / 」 strip is gone. +- **Books grouped by app.** The page lists each app's books under the app's name, as the launcher names it: a book goes under the first app whose navigation links to it (a module's navigation contributions included), else under its package's app; books no app carries are listed last under 「Other documentation」. No card shows a package id; a package's docs with no authored book are named by their app. A platform package's books (`com.objectstack.*`, such as Setup's) are listed only under an app in the member's list that carries them, never under 「Other documentation」, so they are not listed for a member whose app list has no such app. This is what the page lists, not who may read a doc: the server's audience gate decides that, as before. +- **The subtitle and the counts read the session language** (「9 篇」, not 「9 articles」). +- **「Search all documentation」.** A search field on the page searches every listed article's title, summary and body, and lists the matches with the words marked in context; each opens the article in its own book. The bodies are asked once, the first time the reader searches (`GET /meta/doc?include=content`, through the same audience gate as the list). The query stays in the URL (`?q=`). +- **A hand-typed article URL whose book does not hold the article** (`/docs/<book A>/<article of book B>`) now opens the article in its own book; with no book that holds it, the article draws no previous/next pager instead of showing both ends at once. Inside an app, an article whose book is in no package now keeps its 「← Back to <app>」 link. + +`@objectstack/client`: `client.meta.getItems(type, { include })` and the environment-scoped `meta.getItems` send `?include=`; leaving it out sends nothing, as before. `@object-ui/app-shell`: `AppHeader` takes a `docs` variant and `DefaultHomeLayout` a `variant` prop for it. diff --git a/packages/client/README.md b/packages/client/README.md index 8e26ff53638..c788a0b73d9 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -230,6 +230,7 @@ await client.connect(); // Discovery & Metadata await client.meta.getTypes(); // List metadata types await client.meta.getItems('object'); // List all objects +await client.meta.getItems('doc', { include: 'content' }); // List docs WITH their bodies (the list omits them by default) await client.meta.getItem('object', 'contact'); // Get specific object // Data Operations diff --git a/packages/client/src/client.test.ts b/packages/client/src/client.test.ts index e7e7f02b721..35150f22227 100644 --- a/packages/client/src/client.test.ts +++ b/packages/client/src/client.test.ts @@ -209,6 +209,28 @@ describe('ObjectStackClient', () => { ]); }); + it('sends `include` as `?include=`, on the unscoped and the environment surface (the doc list keeps its bodies)', async () => { + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ type: 'doc', items: [{ name: 'intro', content: '# Intro' }] }), + }); + const client = new ObjectStackClient({ baseUrl: 'http://localhost:3000', fetch: fetchMock }); + + await client.meta.getItems('doc', { include: 'content' }); + await client.meta.getItems('doc', { packageId: 'com.acme', include: 'content' }); + await client.environment('env_1').meta.getItems('doc', { include: 'content' }); + // Left out, nothing is sent: the list stays the slim default. + await client.meta.getItems('doc'); + + const urls = fetchMock.mock.calls.map((c) => String(c[0])); + expect(urls).toEqual([ + 'http://localhost:3000/api/v1/meta/doc?include=content', + 'http://localhost:3000/api/v1/meta/doc?package=com.acme&include=content', + 'http://localhost:3000/api/v1/environments/env_1/meta/doc?include=content', + 'http://localhost:3000/api/v1/meta/doc', + ]); + }); + it('should get metadata item by type and name', async () => { // The server's body is the spec-declared `GetMetaItemResponseSchema` // envelope — `{ type, name, item }`, with the metadata document under diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 7b49fb64fe0..ad4c82b97c1 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -235,6 +235,19 @@ export type { QualifiedAddressOptions } from './package-address'; */ export type ApiRouteType = keyof ApiRoutes; +/** + * The options of `meta.getItems` (`GET /meta/:type`). `packageId` scopes the + * list to one package (`?package=`); `names` narrows it to those items in one + * request (`?names=a,b,c`); `include` asks for what the list omits by default + * (`?include=`): `'content'` keeps each `doc`'s body (ADR-0046), `'grants'` + * adds each `position`'s grants. + */ +export interface MetaItemsListOptions { + packageId?: string; + names?: readonly string[]; + include?: 'content' | 'grants'; +} + /** * [#30205] `security.assignedWork.count`'s answer: per object and user field, * how many records hold the user, as the caller can read them. @@ -2083,12 +2096,16 @@ export class ObjectStackClient { * (sent as `?names=a,b,c`). A name that matches no item is simply absent * from the answer. An empty `names` array is sent as an empty filter, * which the server refuses with `400`; leave `names` out to list every item. + * `include` asks for what the list leaves out by default (`?include=`): + * `'content'` keeps each `doc`'s body (ADR-0046), `'grants'` adds each + * `position`'s grants. */ - getItems: async (type: string, options?: { packageId?: string; names?: readonly string[] }): Promise<GetMetaItemsResponse> => { + getItems: async (type: string, options?: MetaItemsListOptions): Promise<GetMetaItemsResponse> => { const route = this.getRoute('metadata'); const params = new URLSearchParams(); if (options?.packageId) params.set('package', options.packageId); if (options?.names !== undefined) params.set('names', options.names.join(',')); + if (options?.include) params.set('include', options.include); const qs = params.toString(); const url = `${this.baseUrl}${route}/${type}${qs ? `?${qs}` : ''}`; const res = await this.fetch(url); @@ -8696,11 +8713,12 @@ export class ScopedEnvironmentClient { const res = await this.parent._fetch(this.metaUrl('')); return this.parent._unwrap<GetMetaTypesResponse>(res); }, - /** The unscoped surface's `getItems`, `names` included (one `?names=a,b,c` request). */ - getItems: async (type: string, options?: { packageId?: string; names?: readonly string[] }): Promise<GetMetaItemsResponse> => { + /** The unscoped surface's `getItems`, `names` and `include` included (one `?names=a,b,c` request). */ + getItems: async (type: string, options?: MetaItemsListOptions): Promise<GetMetaItemsResponse> => { const params = new URLSearchParams(); if (options?.packageId) params.set('package', options.packageId); if (options?.names !== undefined) params.set('names', options.names.join(',')); + if (options?.include) params.set('include', options.include); const qs = params.toString(); const res = await this.parent._fetch(this.metaUrl(`/${type}${qs ? `?${qs}` : ''}`)); return this.parent._unwrap<GetMetaItemsResponse>(res); diff --git a/ui/apps/console/src/App.tsx b/ui/apps/console/src/App.tsx index 91e775e87cf..80fb26c3025 100644 --- a/ui/apps/console/src/App.tsx +++ b/ui/apps/console/src/App.tsx @@ -213,6 +213,20 @@ function HomeRoute() { ); } +/** + * The docs portal's frame (objectstack#35424): Home's layout with the docs bar, + * around the lazily loaded docs layout, so the bar is up while the portal's + * chunk loads. + */ +function DocsPortalRoute() { + const { user } = useAuth(); + return ( + <DefaultHomeLayout userId={user?.id} variant="docs"> + <Suspense fallback={<LoadingScreen />}><DocsLayout /></Suspense> + </DefaultHomeLayout> + ); +} + export function App() { /** * The console's ONE upload destination, mounted above `ConsoleShell` so it @@ -351,26 +365,6 @@ export function App() { * layer too late for a capability whose declared meaning is * "Enter the Studio metadata-design surfaces". */} {studioRoutes} - {/* Package documentation (ADR-0046): a platform-level portal - * lists every installed `doc` (grouped by package), and one - * viewer route renders any item; cross-references between docs - * resolve to that same viewer route. Both are app-independent. */} - {/* Docs portal (ADR-0046 §6). The layout fetches book + doc once - * and shares it with every child route via context. Children: - * index → book index - * :slug → a book landing, or a flat-doc permalink that - * redirects to its canonical /docs/<book>/<name> - * :slug/:name → in-book reader (doc identity stays single- - * coordinate; the book segment is derived nav). */} - <Route path="/docs" element={ - <ProtectedRoute> - <Suspense fallback={<LoadingScreen />}><DocsLayout /></Suspense> - </ProtectedRoute> - }> - <Route index element={<Suspense fallback={<LoadingScreen />}><DocsIndex /></Suspense>} /> - <Route path=":slug" element={<Suspense fallback={<LoadingScreen />}><DocsSlug /></Suspense>} /> - <Route path=":slug/:name" element={<Suspense fallback={<LoadingScreen />}><DocPage /></Suspense>} /> - </Route> {/* objectui#12700 — Home and every app share ONE * `/auth/me/permissions` source. A pathless layout route is their * common ancestor: its element (auth, the shell, the permissions @@ -419,6 +413,25 @@ export function App() { </RequireOrganization> }> <Route path="/home" element={<HomeRoute />} /> + {/* Package documentation (ADR-0046 §6): a platform-level portal + * lists every installed `doc` (grouped by the launcher's apps), + * and one viewer route renders any item; cross-references + * between docs resolve to that same viewer route. App-independent, + * so it is drawn in Home's frame with the docs bar (`docs` + * variant: 「PRODUCT / Documentation」), under this layout for + * the same `/auth/me/permissions` answer Home reads + * (objectstack#35424). The layout fetches book + doc once and + * shares it with every child route via context. Children: + * index → book index + * :slug → a book landing, or a flat-doc permalink that + * redirects to its canonical /docs/<book>/<name> + * :slug/:name → in-book reader (doc identity stays single- + * coordinate; the book segment is derived nav). */} + <Route path="/docs" element={<DocsPortalRoute />}> + <Route index element={<Suspense fallback={<LoadingScreen />}><DocsIndex /></Suspense>} /> + <Route path=":slug" element={<Suspense fallback={<LoadingScreen />}><DocsSlug /></Suspense>} /> + <Route path=":slug/:name" element={<Suspense fallback={<LoadingScreen />}><DocPage /></Suspense>} /> + </Route> <Route path="/apps/:appName/*" element={<AppContent />} /> {/* Internal authed form — same renderer as `/f/:slug`, different * submit path, and (objectui#4109) rendered INSIDE the console diff --git a/ui/apps/console/src/__tests__/App.docsPortalLazy.test.tsx b/ui/apps/console/src/__tests__/App.docsPortalLazy.test.tsx index 655566d76c1..70e528a4a1a 100644 --- a/ui/apps/console/src/__tests__/App.docsPortalLazy.test.tsx +++ b/ui/apps/console/src/__tests__/App.docsPortalLazy.test.tsx @@ -94,6 +94,8 @@ vi.mock('@object-ui/app-shell', async (importOriginal) => ({ // is pinned by `packages/app-shell/src/chrome/RedirectWithSplash.test.tsx`. RedirectWithSplash: stub('redirect-with-splash'), RequireAiSurface: passthrough, + // objectstack#35424: `/docs` sits under the organization gate with `/home` and `/apps`. + RequireOrganization: passthrough, SystemRedirect: () => null, DefaultHomeLayout: passthrough, DefaultHomePage: stub('home-page'), diff --git a/ui/apps/console/src/pages/BookPage.tsx b/ui/apps/console/src/pages/BookPage.tsx index b791f880760..1712008b5d7 100644 --- a/ui/apps/console/src/pages/BookPage.tsx +++ b/ui/apps/console/src/pages/BookPage.tsx @@ -23,9 +23,9 @@ import { resolveBookTree, bookSlug, firstDoc } from './book-nav'; * beneath the heading. Shared by `DocsSlug` (a segment the member's lists do not * answer) and `DocPage` (the reader). */ -export function DocRefusal({ name, message }: { name?: string; message?: string }) { +export function DocRefusal({ message }: { message?: string }) { return ( - <DocShell breadcrumb={name}> + <DocShell> <div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center"> <Lock className="h-10 w-10 text-muted-foreground" /> <h1 className="text-lg font-semibold">You do not have access to this documentation</h1> @@ -68,7 +68,7 @@ export default function BookPage() { // Unknown book, or a book with no readable docs yet. return ( - <DocShell breadcrumb={found ? (found.label ?? slug) : slug}> + <DocShell> <div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center"> {found ? ( <> diff --git a/ui/apps/console/src/pages/DocPage.tsx b/ui/apps/console/src/pages/DocPage.tsx index 9ce1ac08b3e..4295b7def5b 100644 --- a/ui/apps/console/src/pages/DocPage.tsx +++ b/ui/apps/console/src/pages/DocPage.tsx @@ -20,7 +20,7 @@ import { DocsNav, type DocsNavBook } from './DocsNav'; import { DocRefusal } from './BookPage'; import { useBookData } from './use-book-data'; import { useActiveHeading } from './useActiveHeading'; -import { articleNeighbours, type BookArticle } from './docs-reading'; +import { articleNeighbours, bookHoldsArticle, type BookArticle } from './docs-reading'; import { resolveBookTree, bookSlug, bookNamedBy, homeBook, labelUncategorized, pkgOfBook, type ResolvedBook } from './book-nav'; interface DocItem { @@ -282,11 +282,28 @@ export default function DocPage() { // context. Only a segment NO book answers by slug is consulted, so every // reader URL that finds its book today keeps its answer. const namedBook = useMemo(() => (slug && !resolvedBook ? bookNamedBy(slug, books) : null), [slug, resolvedBook, books]); + // objectstack#35424 — a reader URL whose book does not hold its doc (a + // hand-typed `/docs/BOOK_A/DOC_OF_BOOK_B`) reads in the doc's own book: it is + // redirected there once the doc has loaded, so the column, the path above + // the article and the pager all describe the book the article is in. With + // no book that holds it, the page draws no pager (see below). + const inBook = resolvedBook ? bookHoldsArticle(resolvedBook, name) : false; + const ownBook = useMemo(() => { + if (state !== 'ready' || doc?.name !== name || !name || !resolvedBook || inBook) return null; + const home = homeBook(name, books, allDocs, appName); + if (!home || bookSlug(home) === slug) return null; + const resolved = resolveBookTree(home, allDocs, undefined, authoredBooks); + return bookHoldsArticle(resolved, name) ? home : null; + }, [state, doc, name, resolvedBook, inBook, books, allDocs, authoredBooks, appName, slug]); if (namedBook && name) { return <Navigate to={{ pathname: `${base}/${bookSlug(namedBook)}/${name}`, hash }} replace />; } + if (ownBook && name) { + return <Navigate to={{ pathname: `${base}/${bookSlug(ownBook)}/${name}`, hash }} replace />; + } + if (state === 'loading') { return ( <div className="flex h-full items-center justify-center p-10 text-muted-foreground"> @@ -297,7 +314,7 @@ export default function DocPage() { if (state === 'missing') { return ( - <DocShell breadcrumb={name}> + <DocShell> <div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center"> <FileQuestion className="h-10 w-10 text-muted-foreground" /> <h1 className="text-lg font-semibold">Documentation not found</h1> @@ -311,12 +328,12 @@ export default function DocPage() { } if (state === 'refused') { - return <DocRefusal name={name} message={errorMessage} />; + return <DocRefusal message={errorMessage} />; } if (state === 'conflict') { return ( - <DocShell breadcrumb={name}> + <DocShell> <div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center"> <Layers className="h-10 w-10 text-muted-foreground" /> <h1 className="text-lg font-semibold"> @@ -357,7 +374,7 @@ export default function DocPage() { if (state === 'error') { return ( - <DocShell breadcrumb={name}> + <DocShell> <div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center"> <AlertCircle className="h-10 w-10 text-destructive" /> <h1 className="text-lg font-semibold">Failed to load documentation</h1> @@ -381,7 +398,7 @@ export default function DocPage() { const docsLabel = t('help.documentation', { defaultValue: 'Documentation' }); return ( - <DocShell breadcrumb={doc?.label ?? name} backLink={false}> + <DocShell backLink={!docsNav}> {/* objectstack#35424 — the docs column is the page's one navigation. * Inside an app it sits where the app menu would, full height beside * the article; on narrow screens it folds into a disclosure above it. */} @@ -441,7 +458,7 @@ export default function DocPage() { /> </MermaidEnlargeContext.Provider> </article> - {resolvedBook ? ( + {resolvedBook && inBook ? ( <ArticlePager previous={neighbours.previous} next={neighbours.next} diff --git a/ui/apps/console/src/pages/DocShell.tsx b/ui/apps/console/src/pages/DocShell.tsx index 4f4a6bee068..4b8dbcacb26 100644 --- a/ui/apps/console/src/pages/DocShell.tsx +++ b/ui/apps/console/src/pages/DocShell.tsx @@ -7,76 +7,40 @@ */ import type { ReactNode } from 'react'; -import { Link, useParams } from 'react-router-dom'; -import { BookOpen } from 'lucide-react'; -import { useObjectTranslation } from '@object-ui/i18n'; +import { useParams } from 'react-router-dom'; import { AppDocsBackLink } from './AppDocsBackLink'; import { useAppDocsBackTo } from './useAppDocsBackTo'; /** - * Lightweight chrome for the package-documentation routes (ADR-0046). + * The frame of the package-documentation pages (ADR-0046), inside the + * console's own top bar. It draws no bar of its own (objectstack#35424): * - * The doc viewer/portal are app-independent top-level routes, so they don't - * get the console's app sidebar. This adds a minimal sticky header — a - * "Documentation" home link (→ `/docs`) plus an optional breadcrumb — so a - * reader always knows where they are and has a way back, without pulling in - * the full app shell (which ADR-0046 deliberately keeps out of v1). - * - * Under an app (`/apps/:appName/docs/...`, ADR-0048) it draws no bar of its - * own (objectstack#35424): the app bar above already reads 「APP / - * Documentation」, and the reader names its book and article above the - * article. An app's docs routes draw no app menu either, so the bar's place - * holds 「← Back to APP」 (`AppDocsBackLink`) on every page but the reader, - * which carries it in its docs column and passes `backLink={false}`. The - * label reads the session language (`help.documentation`). + * - Under an app (`/apps/:appName/docs/...`, ADR-0048) the app bar above reads + * 「APP / Documentation」, and the reader names its book and article above + * the article. An app's docs routes draw no app menu either, so the bar's + * place holds 「← Back to APP」 (`AppDocsBackLink`) on every page but the + * reader, which carries it in its docs column and passes `backLink={false}`. + * - The portal (`/docs/...`) is drawn in Home's frame, whose bar reads + * 「PRODUCT / Documentation」 and links to the portal's index (`App.tsx`, + * the `docs` variant of `AppHeader`). */ export function DocShell({ - breadcrumb, backLink = true, children, }: { - breadcrumb?: string; - /** Inside an app: draw 「← Back to APP」 above the page. The reader turns it off (its column has it). */ + /** Inside an app: draw 「← Back to APP」 above the page. The reader turns it off when its column has it. */ backLink?: boolean; children: ReactNode; }) { const { appName } = useParams<{ appName?: string }>(); - const { t } = useObjectTranslation(); const backTo = useAppDocsBackTo(); - if (appName) { - return ( - <div className="min-h-full"> - {backLink && backTo ? ( - <div className="mx-auto flex max-w-3xl px-4 pt-4 sm:px-6" data-testid="docs-back-bar"> - <AppDocsBackLink backTo={backTo} /> - </div> - ) : null} - {children} - </div> - ); - } - const home = '/docs'; return ( <div className="min-h-full"> - <header className="sticky top-0 z-10 border-b border-border bg-background/80 backdrop-blur supports-[backdrop-filter]:bg-background/60"> - <div className="mx-auto flex max-w-3xl items-center gap-2 px-4 py-3 sm:px-6"> - <Link - to={home} - className="flex items-center gap-2 text-sm font-semibold hover:opacity-80" - > - <BookOpen className="h-4 w-4 text-muted-foreground" /> - <span>{t('help.documentation', { defaultValue: 'Documentation' })}</span> - </Link> - {breadcrumb ? ( - <> - <span className="text-muted-foreground/60" aria-hidden> - / - </span> - <span className="truncate text-sm text-muted-foreground">{breadcrumb}</span> - </> - ) : null} + {appName && backLink && backTo ? ( + <div className="mx-auto flex max-w-3xl px-4 pt-4 sm:px-6" data-testid="docs-back-bar"> + <AppDocsBackLink backTo={backTo} /> </div> - </header> + ) : null} {children} </div> ); diff --git a/ui/apps/console/src/pages/DocsIndex.tsx b/ui/apps/console/src/pages/DocsIndex.tsx index fef4e57ea97..3e81e12120e 100644 --- a/ui/apps/console/src/pages/DocsIndex.tsx +++ b/ui/apps/console/src/pages/DocsIndex.tsx @@ -6,29 +6,79 @@ * LICENSE file in the root directory of this source tree. */ -import { useMemo } from 'react'; -import { Link } from 'react-router-dom'; -import { AlertCircle, BookOpen, Loader2 } from 'lucide-react'; +import { useDeferredValue, useMemo } from 'react'; +import { Link, useSearchParams } from 'react-router-dom'; +import { AlertCircle, BookOpen, Loader2, Search } from 'lucide-react'; import { useObjectTranslation } from '@object-ui/i18n'; +import { filterActiveApps, useMetadata, useServedAppLabel } from '@object-ui/app-shell'; import { DocShell } from './DocShell'; import { useBookData } from './use-book-data'; -import { buildBookCards } from './book-nav'; +import { buildBookCards, type BookCard } from './book-nav'; +import { groupBooksByApp, searchDocs, type DocsIndexApp, type DocSearchHit } from './docs-index'; +import { useDocContents } from './useDocContents'; + +/** An app record as `/meta/app` serves it, the members the page reads. */ +type ServedApp = { name: string; label?: unknown; _packageId?: unknown; navigation?: unknown; areas?: unknown } & Record<string, unknown>; + +/** The page's search query, in the URL so a search can be shared and survives a reload. */ +const SEARCH_PARAM = 'q'; /** - * `/docs` — the platform-level documentation portal (ADR-0046 §6). + * `/docs` — "All documentation", the platform-level portal (ADR-0046 §6). * - * The portal is organised entirely by `book`: authored books plus an implicit - * per-package book for every package that has docs but no authored one (§6.4 — - * there is no "flat vs book" fork; a flat package is just its implicit book). - * Each card opens that book's grouped reader at `/docs/<slug>`; the single-doc - * reader lives at `/docs/<slug>/<name>`. + * The portal is organised by `book`: authored books plus an implicit + * per-package book for every package that has docs but no authored one (§6.4). + * objectstack#35424 — the books are grouped by the apps that carry them, named + * as the launcher names them (`groupBooksByApp`), with no package id on any + * card; a platform package's books are listed only under an app the caller's + * app list includes. 「Search all documentation」 searches every article's + * title, summary and body (`searchDocs`), over one lazily asked + * `GET /meta/doc?include=content`. Each card opens that book's grouped reader + * at `/docs/<slug>`; the single-doc reader lives at `/docs/<slug>/<name>`. */ export default function DocsIndex() { const { t } = useObjectTranslation(); const { books, docs, state, error } = useBookData(); + const { apps } = useMetadata(); + const { appLabel } = useServedAppLabel(); + const [params, setParams] = useSearchParams(); + const query = params.get(SEARCH_PARAM) ?? ''; + const deferredQuery = useDeferredValue(query); + const searching = deferredQuery.trim().length > 0; - // Cards carry the book's url slug so links match the `/docs/:slug` route. const cards = useMemo(() => buildBookCards(books, docs), [books, docs]); + const indexApps = useMemo<DocsIndexApp[]>( + () => + filterActiveApps(apps as ServedApp[] | undefined) + .filter((app) => typeof app.name === 'string' && app.name !== '') + .map((app) => ({ + name: app.name, + label: appLabel(app), + _packageId: typeof app._packageId === 'string' ? app._packageId : undefined, + navigation: app.navigation, + areas: app.areas, + })), + [apps, appLabel], + ); + const groups = useMemo(() => groupBooksByApp(books, cards, docs, indexApps), [books, cards, docs, indexApps]); + // Each listed book's name → its card's label, which a search hit names its book by. + const listedBooks = useMemo( + () => new Map(groups.flatMap((g) => g.cards.map((c) => [c.name, c.label] as const))), + [groups], + ); + + const contents = useDocContents(searching); + const hits = useMemo( + () => (searching && contents.state === 'ready' ? searchDocs(deferredQuery, contents.docs, books, docs, listedBooks) : []), + [searching, contents, deferredQuery, books, docs, listedBooks], + ); + + const setQuery = (next: string) => { + const nextParams = new URLSearchParams(params); + if (next) nextParams.set(SEARCH_PARAM, next); + else nextParams.delete(SEARCH_PARAM); + setParams(nextParams, { replace: true }); + }; if (state === 'loading') { return ( @@ -42,60 +92,150 @@ export default function DocsIndex() { return ( <div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center"> <AlertCircle className="h-10 w-10 text-destructive" /> - <h1 className="text-lg font-semibold">Failed to load documentation</h1> + <h1 className="text-lg font-semibold">{t('help.loadDocsFailed', { defaultValue: 'Failed to load documentation' })}</h1> <p className="text-sm text-muted-foreground">{error}</p> </div> ); } + const searchLabel = t('help.searchAllDocs', { defaultValue: 'Search all documentation' }); + return ( <DocShell> - <div className="mx-auto max-w-4xl p-4 sm:p-6"> - <header className="mb-6"> - <h1 className="text-2xl font-bold tracking-tight">{t('help.documentation', { defaultValue: 'Documentation' })}</h1> - <p className="mt-1 text-sm text-muted-foreground"> - Books and guides from your installed packages. - </p> + <div className="mx-auto max-w-6xl px-4 py-6 sm:px-8 sm:py-8"> + <header className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between"> + <div className="min-w-0"> + <h1 className="text-2xl font-bold tracking-tight">{t('help.documentation', { defaultValue: 'Documentation' })}</h1> + <p className="mt-1 text-sm text-muted-foreground"> + {t('help.docsIndexSubtitle', { defaultValue: 'Guides that come with your installed apps.' })} + </p> + </div> + <div role="search" className="relative w-full sm:w-80"> + <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden /> + <input + type="search" + value={query} + onChange={(e) => setQuery(e.target.value)} + placeholder={searchLabel} + aria-label={searchLabel} + data-testid="docs-search-all" + className="h-10 w-full rounded-md border border-input bg-background pl-9 pr-3 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring" + /> + </div> </header> - {cards.length === 0 ? ( + + {searching ? ( + <SearchResults state={contents.state} error={contents.error} hits={hits} /> + ) : groups.length === 0 ? ( <div className="flex flex-col items-center gap-3 py-16 text-center text-muted-foreground"> <BookOpen className="h-10 w-10" /> - <p className="text-sm"> - No documentation is installed. Packages ship docs as flat - <code className="mx-1 rounded bg-muted px-1 py-0.5">src/docs/*.md</code> - files, organised by a <code className="rounded bg-muted px-1 py-0.5">book</code> (ADR-0046). - </p> + <p className="text-sm">{t('help.noDocsInstalled', { defaultValue: 'No documentation is installed yet.' })}</p> </div> ) : ( - <ul className="grid items-stretch gap-3 sm:grid-cols-2"> - {cards.map((card) => ( - <li key={card.name} className="h-full"> - <Link - to={`/docs/${card.slug}`} - className="flex h-full items-start gap-3 rounded-md border border-border p-3 hover:bg-muted/50" - > - <BookOpen className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" /> - <div className="min-w-0"> - <div className="text-sm font-semibold">{card.label}</div> - {card.description ? ( - <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground"> - {card.description} - </div> - ) : card.subtitle ? ( - <div className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground/70"> - {card.subtitle} - </div> - ) : null} - <div className="mt-1 text-xs text-muted-foreground/80"> - {card.docCount} {card.docCount === 1 ? 'article' : 'articles'} - </div> - </div> - </Link> - </li> + <div className="flex flex-col gap-8"> + {groups.map((group) => ( + <section key={group.app ?? '_other'} aria-labelledby={`docs-group-${group.app ?? '_other'}`} data-testid="docs-group"> + <h2 id={`docs-group-${group.app ?? '_other'}`} className="mb-3 text-sm font-semibold text-foreground/90"> + {group.label ?? t('help.otherDocs', { defaultValue: 'Other documentation' })} + </h2> + <ul className="grid items-stretch gap-3 sm:grid-cols-2 lg:grid-cols-3"> + {group.cards.map((card) => ( + <li key={card.name} className="h-full"> + <BookCardLink card={card} /> + </li> + ))} + </ul> + </section> ))} - </ul> + </div> )} </div> </DocShell> ); } + +function BookCardLink({ card }: { card: BookCard }) { + const { t } = useObjectTranslation(); + return ( + <Link + to={`/docs/${card.slug}`} + className="flex h-full flex-col gap-1 rounded-lg border border-border p-4 hover:bg-muted/50" + > + <span className="text-sm font-semibold">{card.label}</span> + {card.description ? <span className="line-clamp-2 text-sm text-muted-foreground">{card.description}</span> : null} + <span className="mt-auto pt-1 text-xs text-muted-foreground/80"> + {t('help.articleCount', { + count: card.docCount, + defaultValue: card.docCount === 1 ? '{{count}} article' : '{{count}} articles', + })} + </span> + </Link> + ); +} + +function SearchResults({ + state, + error, + hits, +}: { + state: 'idle' | 'loading' | 'ready' | 'error'; + error?: string; + hits: DocSearchHit[]; +}) { + const { t } = useObjectTranslation(); + if (state === 'error') { + return ( + <p className="py-10 text-center text-sm text-destructive" role="alert"> + {t('help.docsSearchFailed', { defaultValue: 'Could not search the documentation: {{message}}', message: error ?? '' })} + </p> + ); + } + if (state !== 'ready') { + return ( + <p className="flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground" role="status"> + <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> + {t('help.searchingDocs', { defaultValue: 'Searching…' })} + </p> + ); + } + if (hits.length === 0) { + return ( + <p className="py-10 text-center text-sm text-muted-foreground" role="status"> + {t('help.noDocsMatch', { defaultValue: 'No articles match.' })} + </p> + ); + } + return ( + <section aria-live="polite"> + <p className="mb-3 text-sm text-muted-foreground" role="status"> + {t('help.searchResultCount', { + count: hits.length, + defaultValue: hits.length === 1 ? '{{count}} article found' : '{{count}} articles found', + })} + </p> + <ul className="flex flex-col divide-y rounded-lg border" data-testid="docs-search-results"> + {hits.map((hit) => ( + <li key={`${hit.bookSlug}/${hit.doc}`}> + <Link to={`/docs/${hit.bookSlug}/${hit.doc}`} className="flex flex-col gap-1 px-4 py-3 hover:bg-muted/50"> + <span className="text-sm font-medium text-primary">{hit.label}</span> + <span className="text-xs text-muted-foreground">{hit.bookLabel}</span> + {hit.snippet.length > 0 ? ( + <span className="line-clamp-2 text-sm text-muted-foreground"> + {hit.snippet.map((part, i) => + part.match ? ( + <mark key={i} className="rounded-sm bg-primary/15 px-0.5 text-foreground"> + {part.text} + </mark> + ) : ( + <span key={i}>{part.text}</span> + ), + )} + </span> + ) : null} + </Link> + </li> + ))} + </ul> + </section> + ); +} diff --git a/ui/apps/console/src/pages/DocsSlug.tsx b/ui/apps/console/src/pages/DocsSlug.tsx index 27fc3a24779..db9a20b3a1d 100644 --- a/ui/apps/console/src/pages/DocsSlug.tsx +++ b/ui/apps/console/src/pages/DocsSlug.tsx @@ -147,7 +147,7 @@ export default function DocsSlug() { // portal's own answer below standing. const refusal = answer !== null && answer.slug === slug ? answer.refusal : null; if (refusal !== null) { - return <DocRefusal name={slug} message={refusal} />; + return <DocRefusal message={refusal} />; } // The name-prefix fallback for a name no installed doc carries (unchanged). @@ -156,7 +156,7 @@ export default function DocsSlug() { } return ( - <DocShell breadcrumb={slug}> + <DocShell> <div className="mx-auto flex max-w-3xl flex-col items-center gap-3 p-10 text-center"> <FileQuestion className="h-10 w-10 text-muted-foreground" /> <h1 className="text-lg font-semibold">Documentation not found</h1> diff --git a/ui/apps/console/src/pages/docs-index.test.ts b/ui/apps/console/src/pages/docs-index.test.ts new file mode 100644 index 00000000000..0a3413e9c9f --- /dev/null +++ b/ui/apps/console/src/pages/docs-index.test.ts @@ -0,0 +1,155 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35424 — the "All documentation" page's grouping and full-text + * search, as pure readings. The page's integration (the real `DocsIndex` + * under the docs routes) is pinned in `docs-portal.test.tsx`. + */ + +import { describe, expect, it } from 'vitest'; +import { buildBookCards, buildPortalBooks, type Book, type ResolverDoc } from './book-nav'; +import { groupBooksByApp, markTerms, plainText, searchDocs, searchTerms, type DocsIndexApp } from './docs-index'; + +const DOCS: ResolverDoc[] = [ + { name: 'crm_start', label: 'Getting started', packageId: 'app.crm' }, + { name: 'crm_quotes', label: 'Quotes', packageId: 'app.crm.revenue' }, + { name: 'svc_cases', label: 'Cases', packageId: 'app.crm.service' }, + { name: 'setup_overview', label: 'Setup overview', packageId: 'com.objectstack.setup' }, + { name: 'loose_note', label: 'Loose note', packageId: 'acme.tools' }, +]; +const AUTHORED: Book[] = [ + { name: 'crm_manual', label: 'User Manual', packageId: 'app.crm', groups: [{ key: 'a', label: 'A', include: 'crm_start' }] }, + { name: 'crm_revenue_manual', label: 'Revenue Manual', packageId: 'app.crm.revenue', groups: [{ key: 'a', label: 'A', include: 'crm_quotes' }] }, + { name: 'crm_service_manual', label: 'Service Manual', packageId: 'app.crm.service', groups: [{ key: 'a', label: 'A', include: 'svc_*' }] }, +]; +const BOOKS = buildPortalBooks(AUTHORED, DOCS); +const CARDS = buildBookCards(BOOKS, DOCS); + +const SALES: DocsIndexApp = { + name: 'crm_enterprise', + label: 'Sales', + _packageId: 'app.crm', + // The revenue module contributes its manual into the Sales app's navigation. + navigation: [{ type: 'group', children: [{ type: 'doc', book: 'crm_revenue_manual' }] }], +}; +const SERVICE: DocsIndexApp = { name: 'crm_service', label: 'Service', _packageId: 'app.crm.service', navigation: [] }; +const SETUP: DocsIndexApp = { name: 'setup', label: 'System Settings', _packageId: 'com.objectstack.setup', navigation: [] }; + +const shape = (apps: DocsIndexApp[]) => + groupBooksByApp(BOOKS, CARDS, DOCS, apps).map((g) => [g.label, g.cards.map((c) => c.label)]); + +describe('groupBooksByApp (objectstack#35424)', () => { + it('a book goes under the app linking it, else its package\'s app, else the ungrouped group', () => { + expect(shape([SALES, SERVICE])).toEqual([ + ['Sales', ['Revenue Manual', 'User Manual']], + ['Service', ['Service Manual']], + [null, ['Tools']], + ]); + }); + + it('a link to one of the book\'s articles (a `doc` entry) counts as linking the book', () => { + const service = { ...SERVICE, _packageId: 'other.pkg', areas: [{ navigation: [{ type: 'doc', doc: 'svc_cases' }] }] }; + expect(shape([SALES, service])[1]).toEqual(['Service', ['Service Manual']]); + }); + + it('a platform package\'s book is listed only under its app; with no such app in the list it is not listed', () => { + expect(shape([SALES, SERVICE]).flatMap(([, cards]) => cards)).not.toContain('Setup'); + // Platform apps' groups come after the business apps'; the implicit book is named by its app. + expect(shape([SETUP, SALES, SERVICE])).toEqual([ + ['Sales', ['Revenue Manual', 'User Manual']], + ['Service', ['Service Manual']], + ['System Settings', ['System Settings']], + [null, ['Tools']], + ]); + }); + + it('a platform book an app in the list links is listed under that app, never under the ungrouped group', () => { + const linking = { ...SALES, navigation: [{ type: 'doc', book: 'com.objectstack.setup' }] }; + expect(shape([linking])).toEqual([ + ['Sales', ['User Manual', 'Setup']], + [null, ['Revenue Manual', 'Service Manual', 'Tools']], + ]); + // With its own app in the list too, it keeps that app's name under the app linking it. + expect(shape([linking, SETUP])[0]).toEqual(['Sales', ['User Manual', 'System Settings']]); + }); + + it('no card carries the package id line', () => { + const groups = groupBooksByApp(BOOKS, CARDS, DOCS, [SETUP, SALES]); + for (const g of groups) for (const c of g.cards) expect(c.subtitle).toBeUndefined(); + // CONTROL: the implicit book's card did carry it before the grouping. + expect(CARDS.find((c) => c.name === 'acme.tools')?.subtitle).toBe('acme.tools'); + }); +}); + +describe('the full-text search (objectstack#35424)', () => { + const listed = new Map(CARDS.map((c) => [c.name, c.label] as const)); + const SEARCHABLE = [ + { name: 'crm_start', label: 'Getting started', content: '# Welcome\n\nSign in, then open **Leads**.', packageId: 'app.crm' }, + { name: 'crm_quotes', label: 'Quotes', description: 'Leads become quotes', content: 'A quote expires after 30 days.', packageId: 'app.crm.revenue' }, + { + name: 'svc_cases', + label: 'Leads of a case', + content: '```mermaid\ngraph TD; leads-->x\n```\nCases route by SLA.', + packageId: 'app.crm.service', + }, + { name: 'setup_overview', label: 'Setup overview', content: 'Leads permission sets', packageId: 'com.objectstack.setup' }, + ]; + + it('needs every word, ranks title over summary over body, and links the article in its own book', () => { + const hits = searchDocs('leads', SEARCHABLE, BOOKS, DOCS, listed); + expect(hits.map((h) => h.doc)).toEqual(['svc_cases', 'crm_quotes', 'crm_start', 'setup_overview']); + expect(hits[0]).toMatchObject({ bookSlug: 'crm_service_manual', bookLabel: 'Service Manual' }); + expect(searchDocs('quote 30', SEARCHABLE, BOOKS, DOCS, listed).map((h) => h.doc)).toEqual(['crm_quotes']); + expect(searchDocs('quote nowhere', SEARCHABLE, BOOKS, DOCS, listed)).toEqual([]); + expect(searchDocs(' ', SEARCHABLE, BOOKS, DOCS, listed)).toEqual([]); + }); + + it('answers no article of a book the page does not list', () => { + const withoutSetup = new Map([...listed].filter(([b]) => b !== 'com.objectstack.setup')); + expect(searchDocs('permission', SEARCHABLE, BOOKS, DOCS, withoutSetup)).toEqual([]); + expect(searchDocs('permission', SEARCHABLE, BOOKS, DOCS, listed).map((h) => h.doc)).toEqual(['setup_overview']); + }); + + it('names a hit\'s book as the page\'s card does: an implicit book by its app, not its package', () => { + const groups = groupBooksByApp(BOOKS, CARDS, DOCS, [SETUP, SALES, SERVICE]); + const asListed = new Map(groups.flatMap((g) => g.cards.map((c) => [c.name, c.label] as const))); + const [hit] = searchDocs('permission', SEARCHABLE, BOOKS, DOCS, asListed); + expect(hit).toMatchObject({ doc: 'setup_overview', bookLabel: 'System Settings' }); + // CONTROL: the book's own label is its package's humanized id. + expect(BOOKS.find((b) => b.name === 'com.objectstack.setup')?.label).not.toBe('System Settings'); + }); + + it('answers every match, so the page\'s count is the true count', () => { + const many = Array.from({ length: 60 }, (_, i) => ({ name: `crm_note_${i}`, label: `Leads note ${i}`, packageId: 'app.crm' })); + const manyDocs: ResolverDoc[] = many.map((d) => ({ name: d.name, label: d.label, packageId: d.packageId })); + const books = buildPortalBooks([], manyDocs); + const asListed = new Map(buildBookCards(books, manyDocs).map((c) => [c.name, c.label] as const)); + expect(searchDocs('leads', many, books, manyDocs, asListed)).toHaveLength(60); + // CONTROL: an explicit limit still caps the answer. + expect(searchDocs('leads', many, books, manyDocs, asListed, 5)).toHaveLength(5); + }); + + it('searches the words a reader sees: no diagram source, no markup', () => { + expect(searchDocs('graph', SEARCHABLE, BOOKS, DOCS, listed)).toEqual([]); + expect(plainText('## Title\n\nSee [the guide](/docs/x) and `code` **bold** <b>tag</b>')).toBe('Title See the guide and code bold tag'); + }); + + it('marks each match in the snippet, case-insensitively, and matches CJK text without spaces', () => { + expect(markTerms('Open Leads, then leads', ['leads'])).toEqual([ + { text: 'Open ', match: false }, + { text: 'Leads', match: true }, + { text: ', then ', match: false }, + { text: 'leads', match: true }, + ]); + const zh = [{ name: 'crm_quotes', label: '报价单', content: '报价单生成后三十天过期。', packageId: 'app.crm.revenue' }]; + const [hit] = searchDocs('过期', zh, BOOKS, DOCS, listed); + expect(hit.snippet.filter((p) => p.match).map((p) => p.text)).toEqual(['过期']); + expect(searchTerms(' A b ')).toEqual(['a', 'b']); + }); +}); diff --git a/ui/apps/console/src/pages/docs-index.ts b/ui/apps/console/src/pages/docs-index.ts new file mode 100644 index 00000000000..4627e5dd892 --- /dev/null +++ b/ui/apps/console/src/pages/docs-index.ts @@ -0,0 +1,286 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { + bookSlug, + homeBook, + pkgOfBook, + resolveBookTree, + type Book, + type BookCard, + type ResolverDoc, +} from './book-nav'; +import { bookArticles } from './docs-reading'; + +/** + * The "All documentation" page's two readings (objectstack#35424): its books + * grouped by the apps that carry them, and the full-text search over every + * article. Pure, so the page and its tests read the same answer. + */ + +/** The members of an app record the grouping reads (`/meta/app`, as served to this caller). */ +export interface DocsIndexApp { + name: string; + /** The app's display name, as the launcher shows it. */ + label: string; + _packageId?: string; + navigation?: unknown; + areas?: unknown; +} + +/** One group of the page: an app and the books it carries, or the books no app carries. */ +export interface DocsIndexGroup { + /** The app's name; `null` for the books no app carries. */ + app: string | null; + /** The app's display name; `null` for the books no app carries (the page names that group). */ + label: string | null; + cards: BookCard[]; +} + +/** + * The platform reserves the `com.objectstack.*` package namespace for its + * code-delivered packages (the Setup app's docs, say); see + * `isPlatformBuiltinApp` in `@object-ui/app-shell`. + */ +const PLATFORM_PACKAGE_PREFIX = 'com.objectstack.'; + +function isPlatformPackage(packageId: string | undefined): boolean { + return typeof packageId === 'string' && packageId.startsWith(PLATFORM_PACKAGE_PREFIX); +} + +/** Every `type: 'doc'` navigation entry of an app, in its navigation and in every `areas[].navigation`, at every depth. */ +function docEntries(app: DocsIndexApp): Array<{ book?: string; doc?: string }> { + const out: Array<{ book?: string; doc?: string }> = []; + const walk = (items: unknown) => { + if (!Array.isArray(items)) return; + for (const item of items as Array<Record<string, unknown> | null>) { + if (!item || typeof item !== 'object') continue; + if (item.type === 'doc') { + out.push({ + book: typeof item.book === 'string' ? item.book : undefined, + doc: typeof item.doc === 'string' ? item.doc : undefined, + }); + } + walk(item.children); + } + }; + walk(app.navigation); + if (Array.isArray(app.areas)) { + for (const area of app.areas as Array<Record<string, unknown> | null>) walk(area?.navigation); + } + return out; +} + +/** + * Group the page's book cards by the apps that carry them, in the apps' order. + * + * A book belongs to the first app whose navigation links to it (a `doc` entry + * naming the book, or one of its articles; a module's navigation + * contributions are part of the app it contributes to, as served), else to the + * first app of the book's own package. A book no app carries goes to the + * ungrouped group at the end, except a platform package's book + * (`com.objectstack.*`): that one is listed only under an app in the caller's + * list that carries it (one linking it, else its own package's app), never + * under 「Other documentation」, so it is not listed for a caller whose app list + * has no such app (the Setup app is served to administrators only). This is a + * listing rule, not a read gate: + * the server's audience gate (ADR-0046 §6.7) is what decides who may read a + * doc. + * + * Platform apps' groups come after the others'. An implicit book (a package's + * docs with no authored book, ADR-0046 §6.4) is named by its app instead of + * its package id, and no card carries a package id. + */ +export function groupBooksByApp( + books: Book[], + cards: BookCard[], + docs: ResolverDoc[], + apps: DocsIndexApp[], +): DocsIndexGroup[] { + const linked = apps.map((app) => ({ app, entries: docEntries(app) })); + const byApp = new Map<string, BookCard[]>(); + const ungrouped: BookCard[] = []; + const bookByName = new Map(books.map((b) => [b.name, b])); + + for (const card of cards) { + const book = bookByName.get(card.name); + if (!book) continue; + const pkg = pkgOfBook(book); + let articles: Set<string> | null = null; + const holds = (doc: string) => { + articles ??= new Set(bookArticles(resolveBookTree(book, docs)).map((a) => a.doc)); + return articles.has(doc); + }; + const owner = + linked.find(({ entries }) => entries.some((e) => (e.book ? e.book === book.name : !!e.doc && holds(e.doc))))?.app ?? + apps.find((app) => app._packageId === pkg); + const { subtitle: _packageIdLine, ...rest } = card; + if (!owner) { + if (!isPlatformPackage(pkg)) ungrouped.push(rest); + continue; + } + // An implicit book is named by its own package's app, never by another app that links it. + const homeApp = apps.find((app) => app._packageId === pkg); + const named = book.implicit && homeApp ? { ...rest, label: homeApp.label } : rest; + const list = byApp.get(owner.name) ?? []; + list.push(named); + byApp.set(owner.name, list); + } + + const ordered = [ + ...apps.filter((a) => !isPlatformPackage(a._packageId)), + ...apps.filter((a) => isPlatformPackage(a._packageId)), + ]; + const groups: DocsIndexGroup[] = []; + for (const app of ordered) { + const list = byApp.get(app.name); + if (list && list.length > 0) groups.push({ app: app.name, label: app.label, cards: list }); + } + if (ungrouped.length > 0) groups.push({ app: null, label: null, cards: ungrouped }); + return groups; +} + +// ── Full-text search ───────────────────────────────────────────────────────── + +/** A doc as `GET /meta/doc?include=content` serves it (already in the session language). */ +export interface SearchableDoc { + name: string; + label?: string; + description?: string; + content?: string; + packageId?: string; +} + +/** A run of a snippet, marked when it is a match. */ +export interface SnippetPart { + text: string; + match: boolean; +} + +/** One search hit: the article, the book it reads in, and where the words were found. */ +export interface DocSearchHit { + doc: string; + label: string; + /** The reader URL segment of the article's book (`/docs/<bookSlug>/<doc>`). */ + bookSlug: string; + bookLabel: string; + /** The text around the first match in the body, or the summary when only the title or summary matched. */ + snippet: SnippetPart[]; +} + +/** Markdown reduced to the words a reader sees: no diagrams, markup, link targets or tags. */ +export function plainText(markdown: string): string { + return markdown + .replace(/```mermaid[\s\S]*?```/g, ' ') + .replace(/```[^\n]*\n?/g, ' ') + .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/<[^>]+>/g, ' ') + .replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/gm, '') + .replace(/[*_`~|]+/g, '') + .replace(/\s+/g, ' ') + .trim(); +} + +/** The query's words: split on white space, lower-cased; blank words dropped. */ +export function searchTerms(query: string): string[] { + return query + .toLocaleLowerCase() + .split(/\s+/) + .filter((w) => w.length > 0); +} + +function countOf(hay: string, term: string): number { + let n = 0; + for (let at = hay.indexOf(term); at >= 0; at = hay.indexOf(term, at + term.length)) n += 1; + return n; +} + +/** `text` cut to the words around `at`, its matches of `terms` marked. */ +function snippetAround(text: string, at: number, terms: string[], radius = 60): SnippetPart[] { + const start = Math.max(0, at - radius); + const end = Math.min(text.length, at + radius * 2); + const cut = `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`; + return markTerms(cut, terms); +} + +/** `text` split into runs, each match of any of `terms` (case-insensitive) its own marked run. */ +export function markTerms(text: string, terms: string[]): SnippetPart[] { + const lower = text.toLocaleLowerCase(); + const parts: SnippetPart[] = []; + let i = 0; + let plainFrom = 0; + while (i < text.length) { + const term = terms.find((t) => t && lower.startsWith(t, i)); + if (term) { + if (i > plainFrom) parts.push({ text: text.slice(plainFrom, i), match: false }); + parts.push({ text: text.slice(i, i + term.length), match: true }); + i += term.length; + plainFrom = i; + } else { + i += 1; + } + } + if (plainFrom < text.length) parts.push({ text: text.slice(plainFrom), match: false }); + return parts; +} + +/** + * The articles that contain every word of `query` in their title, summary or + * body, best first: a title match outranks a summary match, which outranks the + * body; then the more often the words occur, the higher. Only articles that + * read in one of `listedBooks` are answered, so the search never offers a doc + * the page itself does not list; each hit names its book as the page's card + * does (`listedBooks` maps a listed book's name to its card label, so an + * implicit book reads as its app, not its package). Every match is answered + * unless `limit` caps it, so a count read from the answer is the true count. + */ +export function searchDocs( + query: string, + searchable: SearchableDoc[], + books: Book[], + docs: ResolverDoc[], + listedBooks: ReadonlyMap<string, string>, + limit = Number.POSITIVE_INFINITY, +): DocSearchHit[] { + const terms = searchTerms(query); + if (terms.length === 0) return []; + const scored: Array<{ hit: DocSearchHit; score: number }> = []; + for (const item of searchable) { + const label = item.label ?? item.name; + const title = label.toLocaleLowerCase(); + const summary = (item.description ?? '').toLocaleLowerCase(); + const body = plainText(item.content ?? ''); + const bodyLower = body.toLocaleLowerCase(); + let score = 0; + let all = true; + for (const term of terms) { + const inTitle = title.includes(term); + const inSummary = summary.includes(term); + const inBody = countOf(bodyLower, term); + if (!inTitle && !inSummary && inBody === 0) { + all = false; + break; + } + score += (inTitle ? 100 : 0) + (inSummary ? 10 : 0) + Math.min(inBody, 20); + } + if (!all) continue; + const book = homeBook(item.name, books, docs, item.packageId); + if (!book || !listedBooks.has(book.name)) continue; + const first = Math.min(...terms.map((t) => bodyLower.indexOf(t)).filter((at) => at >= 0)); + const snippet = Number.isFinite(first) + ? snippetAround(body, first, terms) + : markTerms(item.description ?? '', terms); + scored.push({ + hit: { doc: item.name, label, bookSlug: bookSlug(book), bookLabel: listedBooks.get(book.name) ?? book.label ?? book.name, snippet }, + score, + }); + } + scored.sort((a, b) => b.score - a.score || a.hit.label.localeCompare(b.hit.label)); + return scored.slice(0, limit).map((s) => s.hit); +} diff --git a/ui/apps/console/src/pages/docs-portal.test.tsx b/ui/apps/console/src/pages/docs-portal.test.tsx index 66c2118412f..b1aa4ca0ad3 100644 --- a/ui/apps/console/src/pages/docs-portal.test.tsx +++ b/ui/apps/console/src/pages/docs-portal.test.tsx @@ -119,16 +119,35 @@ const { ADAPTER, WORLD, GATED_REASON } = vi.hoisted(() => { } return { item: { name, content: holders.length ? CONFLICT_CONTENT[holders[0]][name] : undefined } }; }; - const WORLD = { authored: false, conflict: false, exact: false, reads: [] as Array<string | undefined> }; + // objectstack#35424 — the "All documentation" page's world: the apps the + // caller's `/meta/app` lists, a platform package's doc switched on by + // `platform`, and every `?include=content` list read the page asks. + const PLATFORM_DOCS = [{ name: 'setup_overview', label: 'Setup overview', _packageId: 'com.objectstack.setup' }]; + const PLATFORM_CONTENT: Record<string, string> = { setup_overview: 'ADMIN BODY about permission sets' }; + const WORLD = { + authored: false, + conflict: false, + exact: false, + platform: false, + reads: [] as Array<string | undefined>, + apps: [] as Array<Record<string, unknown>>, + contentReads: 0, + }; const ADAPTER = { getClient: () => ({ meta: { - getItems: async (type: string) => - WORLD.conflict + getItems: async (type: string, options?: { include?: string }) => { + const list = WORLD.conflict ? (type === 'doc' ? CONFLICT_DOCS : []) // implicit books only : WORLD.authored - ? (type === 'doc' ? AUTHORED_DOCS : type === 'book' ? AUTHORED_BOOKS : []) - : (type === 'doc' ? DOCS : []), // no authored books + ? (type === 'doc' ? [...AUTHORED_DOCS, ...(WORLD.platform ? PLATFORM_DOCS : [])] : type === 'book' ? AUTHORED_BOOKS : []) + : (type === 'doc' ? DOCS : []); // no authored books + if (type !== 'doc' || options?.include !== 'content') return list; + // The list with every body, as `GET /meta/doc?include=content` serves it. + WORLD.contentReads += 1; + const bodies: Record<string, string> = { ...CONTENT, ...AUTHORED_CONTENT, ...PLATFORM_CONTENT }; + return list.map((d) => ({ ...d, content: bodies[d.name] })); + }, getItem: async (_type: string, name: string, options?: { packageId?: string }) => WORLD.conflict ? conflictRead(name, options?.packageId) @@ -142,6 +161,8 @@ const { ADAPTER, WORLD, GATED_REASON } = vi.hoisted(() => { vi.mock('@object-ui/app-shell', async (importOriginal) => ({ ...(await importOriginal<Record<string, unknown>>()), useAdapter: () => ADAPTER, + // The apps `/meta/app` serves this caller (objectstack#35424); none by default. + useMetadata: () => ({ apps: WORLD.apps }), })); // A `{#id}` marker in a doc body stands for a heading with that anchor id. Like @@ -176,7 +197,11 @@ vi.mock('@object-ui/plugin-markdown', async (importOriginal) => { vi.mock('@object-ui/i18n', async (importOriginal) => ({ ...(await importOriginal<Record<string, unknown>>()), - useObjectTranslation: () => ({ t: (_k: string, o?: { defaultValue?: string }) => o?.defaultValue ?? _k }), + // Interpolates `{{name}}` from the options, as i18next does. + useObjectTranslation: () => ({ + t: (_k: string, o?: { defaultValue?: string } & Record<string, unknown>) => + (o?.defaultValue ?? _k).replace(/\{\{(\w+)\}\}/g, (_m, name: string) => String(o?.[name] ?? '')), + }), })); // Imported AFTER the mocks so the pages pick up the mocked modules. @@ -360,8 +385,14 @@ describe('objectui#11197 — a book NAME reaches the book, and nothing that reso expect(await landsOn('/docs/handbook')).toEqual({ where: '/docs/handbook/alpha_welcome', content: 'ALPHA BODY' }); }); - it('…and as a reader segment it stays the slug\'s book: no redirect', async () => { - expect(await landsOn('/docs/handbook/beta_start')).toEqual({ where: '/docs/handbook/beta_start', content: 'BETA BODY' }); + it('…and as a reader segment it is the slug\'s book: a doc of that book stays, with no redirect', async () => { + expect(await landsOn('/docs/handbook/alpha_welcome')).toEqual({ where: '/docs/handbook/alpha_welcome', content: 'ALPHA BODY' }); + }); + + it('…while a doc the slug\'s book does not hold reads in its own book (objectstack#35424), never in the book NAMED like the slug', async () => { + // `beta_start` is in the book whose slug is `beta` (and whose name is + // `handbook`); `handbook` the slug is alpha's book, which does not hold it. + expect(await landsOn('/docs/handbook/beta_start')).toEqual({ where: '/docs/beta/beta_start', content: 'BETA BODY' }); }); it('a segment that is both an installed DOC\'s name and a BOOK\'s name stays the doc permalink', async () => { @@ -777,3 +808,150 @@ describe('objectstack#35424 — the in-app reader has one docs column and a path }); }); }); + +describe('objectstack#35424 — 「All documentation」 groups its books by app and searches every article', () => { + function Where() { + const loc = useLocation(); + return <div data-testid="where">{`${loc.pathname}${loc.search}`}</div>; + } + function Portal({ entry }: { entry: string }) { + return ( + <MemoryRouter initialEntries={[entry]}> + <Where /> + <Routes> + <Route path="/docs" element={<DocsLayout />}> + <Route index element={<DocsIndex />} /> + <Route path=":slug" element={<DocsSlug />} /> + <Route path=":slug/:name" element={<DocPage />} /> + </Route> + </Routes> + </MemoryRouter> + ); + } + const SETUP_APP = { name: 'setup', label: 'Setup', _packageId: 'com.objectstack.setup', navigation: [] }; + /** The cards of the group headed `label`, by their titles. */ + const groupCards = (label: string) => { + const heading = screen.getByRole('heading', { level: 2, name: label }); + const section = heading.closest('section')!; + return within(section).getAllByRole('link').map((l) => l.firstElementChild?.textContent); + }; + + beforeEach(() => { + WORLD.authored = true; + WORLD.contentReads = 0; + WORLD.apps = [ + { name: 'showcase_app', label: 'Showcase', _packageId: 'com.example.showcase', navigation: [] }, + // Beta's handbook is linked from Alpha's navigation, in a group. + { + name: 'alpha_app', + label: 'Alpha', + _packageId: 'com.example.alpha', + navigation: [{ id: 'help', type: 'group', children: [{ id: 'nav_beta', type: 'doc', book: 'handbook' }] }], + }, + ]; + }); + afterEach(() => { + WORLD.authored = false; + WORLD.platform = false; + WORLD.apps = []; + }); + + it('a book goes under the app whose navigation links it, else its package\'s app; the rest under 「Other documentation」', async () => { + render(<Portal entry="/docs" />); + await screen.findByRole('heading', { level: 2, name: 'Showcase' }); + expect(groupCards('Showcase')).toEqual(['Showcase Manual', 'Leads Book']); + expect(groupCards('Alpha')).toEqual(['Alpha Manual', 'Beta Handbook']); + expect(groupCards('Other documentation')).toEqual(['Acme Manual', 'Ops']); + // The groups follow the apps' order, the ungrouped last. + expect(screen.getAllByRole('heading', { level: 2 }).map((h) => h.textContent)).toEqual([ + 'Showcase', + 'Alpha', + 'Other documentation', + ]); + // The page names no package id, and counts in words. + expect(screen.queryByText(/com\.example/)).toBeNull(); + expect(screen.getAllByText('1 article').length).toBeGreaterThan(0); + }); + + it('a platform package\'s book is listed under its app, and not listed where the caller\'s app list has no such app', async () => { + WORLD.platform = true; + render(<Portal entry="/docs" />); + await screen.findByRole('heading', { level: 2, name: 'Showcase' }); + expect(screen.queryByText('Setup')).toBeNull(); + cleanup(); + + // An administrator's app list carries the Setup app: its docs are listed + // under it, named by the app, after the business apps. + WORLD.apps = [...WORLD.apps, SETUP_APP]; + render(<Portal entry="/docs" />); + await screen.findByRole('heading', { level: 2, name: 'Setup' }); + expect(groupCards('Setup')).toEqual(['Setup']); + expect(screen.getAllByRole('heading', { level: 2 }).map((h) => h.textContent)).toEqual([ + 'Showcase', + 'Alpha', + 'Setup', + 'Other documentation', + ]); + expect(screen.queryByText('com.objectstack.setup')).toBeNull(); + }); + + it('「Search all documentation」 finds an article by a word of its body, asks for the bodies once, and keeps the query in the URL', async () => { + render(<Portal entry="/docs" />); + await screen.findByRole('heading', { level: 2, name: 'Showcase' }); + expect(WORLD.contentReads).toBe(0); // nothing asked before a search + const search = screen.getByRole('searchbox', { name: 'Search all documentation' }); + fireEvent.change(search, { target: { value: 'alpha body' } }); + const results = await screen.findByTestId('docs-search-results'); + const hit = within(results).getByRole('link', { name: /Alpha Welcome/ }); + expect(hit).toHaveAttribute('href', '/docs/handbook/alpha_welcome'); + expect(within(hit).getByText('Alpha Manual')).toBeInTheDocument(); + // The words are marked in the snippet. + expect(within(hit).getAllByText(/alpha|body/i, { selector: 'mark' }).length).toBeGreaterThan(0); + expect(screen.getByTestId('where')).toHaveTextContent('/docs?q=alpha+body'); + // The groups give way to the results while searching. + expect(screen.queryByRole('heading', { level: 2 })).toBeNull(); + + fireEvent.change(search, { target: { value: 'zzz' } }); + expect(await screen.findByText('No articles match.')).toBeInTheDocument(); + fireEvent.change(search, { target: { value: '' } }); + await screen.findByRole('heading', { level: 2, name: 'Showcase' }); + fireEvent.change(search, { target: { value: 'lead' } }); + await screen.findByTestId('docs-search-results'); + expect(WORLD.contentReads).toBe(1); + }); + + it('the search offers no article the page does not list (a platform doc with no app in the caller\'s list)', async () => { + WORLD.platform = true; + render(<Portal entry="/docs?q=permission" />); + expect(await screen.findByText('No articles match.')).toBeInTheDocument(); + cleanup(); + WORLD.apps = [...WORLD.apps, SETUP_APP]; + render(<Portal entry="/docs?q=permission" />); + const results = await screen.findByTestId('docs-search-results'); + expect(within(results).getByRole('link', { name: /Setup overview/ })).toHaveAttribute( + 'href', + '/docs/com.objectstack.setup/setup_overview', + ); + }); + + it('the label is not the docs column\'s 「Search docs」', async () => { + render(<Portal entry="/docs" />); + await screen.findByRole('heading', { level: 2, name: 'Showcase' }); + expect(screen.queryByRole('searchbox', { name: 'Search docs' })).toBeNull(); + }); + + it('a hand-typed reader URL whose book does not hold the doc reads in the doc\'s own book', async () => { + render(<Portal entry="/docs/manual/alpha_welcome" />); + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/docs/handbook/alpha_welcome')); + expect(await screen.findByTestId('doc-content')).toHaveTextContent('ALPHA BODY'); + // The pager is the doc's own book's: one article, so both ends say so. + expect(screen.getByTestId('doc-pager-first')).toBeInTheDocument(); + expect(screen.getByTestId('doc-pager-last')).toBeInTheDocument(); + }); + + it('CONTROL: a reader URL whose book holds the doc stays where it is', async () => { + render(<Portal entry="/docs/manual/showcase_index" />); + expect(await screen.findByTestId('doc-content')).toHaveTextContent('INDEX BODY'); + expect(screen.getByTestId('where')).toHaveTextContent('/docs/manual/showcase_index'); + }); +}); diff --git a/ui/apps/console/src/pages/docs-reading.ts b/ui/apps/console/src/pages/docs-reading.ts index e5ea0d43fe0..57133a6c6d5 100644 --- a/ui/apps/console/src/pages/docs-reading.ts +++ b/ui/apps/console/src/pages/docs-reading.ts @@ -49,6 +49,11 @@ export function articleNeighbours( return { previous: articles[at - 1] ?? null, next: articles[at + 1] ?? null }; } +/** Is `doc` one of the book's articles? A reader URL may name a book that does not hold its doc. */ +export function bookHoldsArticle(book: ResolvedBook, doc: string | undefined): boolean { + return !!doc && bookArticles(book).some((a) => a.doc === doc); +} + /** Does `entry` match the docs column's filter (its title or summary, case-insensitive)? */ function entryMatches(entry: ResolvedEntry, needle: string): boolean { if (!entry.doc || entry.separator) return false; diff --git a/ui/apps/console/src/pages/useDocContents.ts b/ui/apps/console/src/pages/useDocContents.ts new file mode 100644 index 00000000000..de00b7b0766 --- /dev/null +++ b/ui/apps/console/src/pages/useDocContents.ts @@ -0,0 +1,85 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { useEffect, useRef, useState } from 'react'; +import { useAdapter } from '@object-ui/app-shell'; +import type { SearchableDoc } from './docs-index'; + +export interface DocContents { + state: 'idle' | 'loading' | 'ready' | 'error'; + docs: SearchableDoc[]; + error?: string; +} + +const IDLE: DocContents = { state: 'idle', docs: [] }; + +function unwrapList(result: unknown): unknown[] { + if (Array.isArray(result)) return result; + const r = result as { items?: unknown; value?: unknown } | null; + if (Array.isArray(r?.items)) return r.items; + if (Array.isArray(r?.value)) return r.value; + return []; +} + +function toSearchable(it: unknown): SearchableDoc | null { + const d = it as Record<string, unknown> | null; + if (!d || typeof d.name !== 'string' || !d.name) return null; + const text = (v: unknown) => (typeof v === 'string' ? v : undefined); + return { + name: d.name, + label: text(d.label), + description: text(d.description), + content: text(d.content), + packageId: text(d._packageId) ?? text(d.packageId), + }; +} + +/** + * Every doc WITH its body, for the "All documentation" page's full-text search + * (objectstack#35424): one `GET /meta/doc?include=content`, asked the first time + * `wanted` turns true (the reader types a query) and kept for the page's life. + * The server answers it through the same audience gate as the slim list + * (ADR-0046 §6.7) and collapses each doc to the session language. + */ +export function useDocContents(wanted: boolean): DocContents { + const adapter = useAdapter(); + const [data, setData] = useState<DocContents>(IDLE); + // Once wanted, wanted for good: clearing the query keeps the answer held. + const [sticky, setSticky] = useState(wanted); + if (wanted && !sticky) setSticky(true); + // Asked once per adapter: a later query reads the answer already held. + const askedFor = useRef<unknown>(null); + + useEffect(() => { + if (!sticky || !adapter || askedFor.current === adapter) return; + askedFor.current = adapter; + let cancelled = false; + setData({ state: 'loading', docs: [] }); + (async () => { + try { + const client = adapter.getClient() as { + meta: { getItems: (type: string, options?: { include?: 'content' }) => Promise<unknown> }; + }; + const raw = await client.meta.getItems('doc', { include: 'content' }); + if (cancelled) return; + const docs = unwrapList(raw).map(toSearchable).filter((d): d is SearchableDoc => d !== null); + setData({ state: 'ready', docs }); + } catch (err) { + if (cancelled) return; + setData({ state: 'error', docs: [], error: err instanceof Error ? err.message : String(err) }); + } + })(); + return () => { + cancelled = true; + // Unmounted or re-pointed before the answer: the next mount asks again. + askedFor.current = null; + }; + }, [sticky, adapter]); + + return data; +} diff --git a/ui/packages/app-shell/src/console/home/HomeLayout.tsx b/ui/packages/app-shell/src/console/home/HomeLayout.tsx index 2bc8532e2fb..eb58f7446c3 100644 --- a/ui/packages/app-shell/src/console/home/HomeLayout.tsx +++ b/ui/packages/app-shell/src/console/home/HomeLayout.tsx @@ -133,9 +133,15 @@ interface HomeLayoutProps { * reads the session user itself. */ userId?: string; + /** + * The bar's variant: `home` (the default), or `docs` for the documentation + * portal (`/docs/*`, objectstack#35424), which is the home bar with a + * 「/ Documentation」 crumb. + */ + variant?: 'home' | 'docs'; } -export function HomeLayout({ children }: HomeLayoutProps) { +export function HomeLayout({ children, variant = 'home' }: HomeLayoutProps) { const { setContext, currentAppName } = useNavigationContext(); const { user } = useAuth(); // The shared `current_user` normaliser, keyed on the session user (objectui#6515). @@ -162,7 +168,7 @@ export function HomeLayout({ children }: HomeLayoutProps) { const header = ( <header className={CONSOLE_TOP_BAR}> - <AppHeader variant="home" /> + <AppHeader variant={variant} /> </header> ); diff --git a/ui/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index 1754d4c1016..efdec501f46 100644 --- a/ui/packages/app-shell/src/layout/AppHeader.tsx +++ b/ui/packages/app-shell/src/layout/AppHeader.tsx @@ -413,7 +413,12 @@ function useGoHomeShortcut(enabled: boolean, homePath: string): void { // header doesn't ship phantom collaborators in production. const EMPTY_PRESENCE_USERS: PresenceUser[] = []; -export type AppHeaderVariant = 'app' | 'home' | 'orgs' | 'studio'; +/** + * `docs` is the documentation portal's bar (`/docs/*`, objectstack#35424): the + * home bar — the product mark and name, the search in the middle, the + * utilities — with a 「/ Documentation」 crumb after the product name. + */ +export type AppHeaderVariant = 'app' | 'home' | 'orgs' | 'studio' | 'docs'; export interface AppHeaderProps { variant?: AppHeaderVariant; @@ -860,7 +865,8 @@ export function AppHeader({ // search field and the utilities, so the field is the bar's middle, wider // than inside an app and named for what the palette finds. The `orgs` and // `studio` variants keep the search at the cluster's left edge. - const isHomeSearch = resolvedVariant === 'home' && hasCommandPalette; + // The docs portal's bar is the home bar with one crumb (objectstack#35424). + const isHomeSearch = (resolvedVariant === 'home' || resolvedVariant === 'docs') && hasCommandPalette; const centersSearch = (isApp && hasCommandPalette) || isHomeSearch; const searchLabel = isHomeSearch ? t('home.search', { defaultValue: 'Search apps, records, pages…' }) @@ -947,7 +953,7 @@ export function AppHeader({ /> )} - {resolvedVariant === 'home' && ( + {(resolvedVariant === 'home' || resolvedVariant === 'docs') && ( <span className="hidden sm:inline ml-2 text-sm font-semibold tracking-tight"> {getProductName()} </span> @@ -980,6 +986,19 @@ export function AppHeader({ </> )} + {resolvedVariant === 'docs' && ( + <> + <PathSep /> + <Link + to="/docs" + data-testid="app-bar-docs-crumb" + className="text-sm font-medium text-foreground/80 px-1.5 hover:text-foreground" + > + {t('help.documentation', { defaultValue: 'Documentation' })} + </Link> + </> + )} + {resolvedVariant === 'studio' && ( <> <PathSep /> diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.aboutBuild-12970.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.aboutBuild-12970.test.tsx index 20375cbd527..88c15ec1998 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.aboutBuild-12970.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.aboutBuild-12970.test.tsx @@ -178,6 +178,7 @@ const PATHS: Record<AppHeaderVariant, string> = { home: '/home', orgs: '/organizations', studio: '/studio', + docs: '/docs', }; function renderHeader(variant: AppHeaderVariant) { @@ -216,7 +217,7 @@ afterEach(() => { }); describe('AppHeader help menu: About names the console build (objectui#12970)', () => { - it.each<AppHeaderVariant>(['app', 'home', 'orgs', 'studio'])( + it.each<AppHeaderVariant>(['app', 'home', 'orgs', 'studio', 'docs'])( 'the `%s` bar\'s help menu carries About, read from the packs', (variant) => { renderHeader(variant); diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.centeredSearch-12472.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.centeredSearch-12472.test.tsx index 5599a820a18..76996b13b7f 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.centeredSearch-12472.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.centeredSearch-12472.test.tsx @@ -379,3 +379,25 @@ describe('the phone bar spends no room on group dividers (objectstack#34596)', ( expect(leftOf()).toContainElement(title); }); }); + +describe('the docs portal bar is the home bar with a 「/ Documentation」 crumb (objectstack#35424)', () => { + it('centers the search like Home and names the portal after the product name, linking to its index', () => { + mount({ pathname: '/docs', variant: 'docs' }); + + const trigger = screen.getByTestId(DESKTOP); + expect(rootOf().children).toHaveLength(3); + expect(rootOf().children[1]).toContainElement(trigger); + // Home's wider field, named for what the palette finds. + expect(classesOf(trigger)).toContain('w-80'); + + const crumb = screen.getByTestId('app-bar-docs-crumb'); + expect(leftOf()).toContainElement(crumb); + expect(crumb).toHaveAttribute('href', '/docs'); + expect(crumb).toHaveTextContent('Documentation'); + }); + + it('CONTROL: the home bar draws no docs crumb', () => { + mount({ pathname: '/home', variant: 'home' }); + expect(screen.queryByTestId('app-bar-docs-crumb')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.searchTriggerNeedsPalette-11912.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.searchTriggerNeedsPalette-11912.test.tsx index cb0f5a12e3a..380c1826264 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.searchTriggerNeedsPalette-11912.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.searchTriggerNeedsPalette-11912.test.tsx @@ -151,6 +151,7 @@ const FRAME: Record<AppHeaderVariant, string> = { orgs: '/organizations', studio: '/studio', app: '/apps/crm', + docs: '/docs', }; function header(variant: AppHeaderVariant) { @@ -166,11 +167,12 @@ afterEach(() => { }); describe('the header search trigger renders only where a command palette is mounted (objectui#11912)', () => { - // `home` is /home and /ai; `orgs` is /organizations and /organizations/SLUG. + // `home` is /home and /ai; `orgs` is /organizations and /organizations/SLUG; + // `docs` is /docs and its books and articles (objectstack#35424). // `studio` (the /studio front door, which mounts a palette since // objectui#11863) and `app` without a provider are not console frames, but // they pin that the gate is the palette's presence, not the variant name. - it.each<AppHeaderVariant>(['home', 'orgs', 'studio', 'app'])( + it.each<AppHeaderVariant>(['home', 'orgs', 'studio', 'app', 'docs'])( 'the `%s` variant with no CommandPaletteProvider draws neither trigger', (variant) => { render(<MemoryRouter initialEntries={[FRAME[variant]]}>{header(variant)}</MemoryRouter>); @@ -184,7 +186,7 @@ describe('the header search trigger renders only where a command palette is moun // `studio` is the /studio front door's own frame: `StudioLanding` mounts the // provider with the palette's `studio` scope (objectui#11863). - it.each<AppHeaderVariant>(['app', 'home', 'studio'])( + it.each<AppHeaderVariant>(['app', 'home', 'studio', 'docs'])( 'CONTROL — the `%s` variant under a CommandPaletteProvider draws both triggers, and each opens the palette', (variant) => { for (const testId of [DESKTOP, MOBILE]) { diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 78a974a167a..7ad62293f00 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3604,6 +3604,27 @@ const ar = { backToApp: 'العودة إلى {{app}}', searchDocs: 'البحث في المستندات', noDocsMatch: 'لا توجد مقالات مطابقة.', + docsIndexSubtitle: 'أدلة مرفقة بتطبيقاتك المثبتة.', + searchAllDocs: 'البحث في جميع المستندات', + articleCount: '{{count}} مقالة', + articleCount_zero: '{{count}} مقالة', + articleCount_one: '{{count}} مقالة', + articleCount_two: 'مقالتان ({{count}})', + articleCount_few: '{{count}} مقالات', + articleCount_many: '{{count}} مقالة', + articleCount_other: '{{count}} مقالة', + otherDocs: 'مستندات أخرى', + noDocsInstalled: 'لم يتم تثبيت أي مستندات بعد.', + loadDocsFailed: 'تعذر تحميل المستندات', + searchingDocs: 'جارٍ البحث…', + searchResultCount: 'تم العثور على {{count}} مقالة', + searchResultCount_zero: 'تم العثور على {{count}} مقالة', + searchResultCount_one: 'تم العثور على {{count}} مقالة', + searchResultCount_two: 'تم العثور على مقالتين ({{count}})', + searchResultCount_few: 'تم العثور على {{count}} مقالات', + searchResultCount_many: 'تم العثور على {{count}} مقالة', + searchResultCount_other: 'تم العثور على {{count}} مقالة', + docsSearchFailed: 'تعذر البحث في المستندات: {{message}}', docsNavigation: 'التنقل في المستندات', docsBreadcrumb: 'مسار المستندات', articlePager: 'المقالة السابقة والتالية', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index ea6f9d0089c..80c2d26e8e9 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3301,6 +3301,19 @@ const de = { backToApp: 'Zurück zu {{app}}', searchDocs: 'Dokumentation durchsuchen', noDocsMatch: 'Keine passenden Artikel.', + docsIndexSubtitle: 'Anleitungen, die mit Ihren installierten Apps geliefert werden.', + searchAllDocs: 'Gesamte Dokumentation durchsuchen', + articleCount: '{{count}} Artikel', + articleCount_one: '{{count}} Artikel', + articleCount_other: '{{count}} Artikel', + otherDocs: 'Weitere Dokumentation', + noDocsInstalled: 'Es ist noch keine Dokumentation installiert.', + loadDocsFailed: 'Dokumentation konnte nicht geladen werden', + searchingDocs: 'Suche läuft…', + searchResultCount: '{{count}} Artikel gefunden', + searchResultCount_one: '{{count}} Artikel gefunden', + searchResultCount_other: '{{count}} Artikel gefunden', + docsSearchFailed: 'Die Dokumentation konnte nicht durchsucht werden: {{message}}', docsNavigation: 'Dokumentationsnavigation', docsBreadcrumb: 'Dokumentationspfad', articlePager: 'Vorheriger und nächster Artikel', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 450dd722303..6a8dcd1249d 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3973,6 +3973,19 @@ const en = { backToApp: 'Back to {{app}}', searchDocs: 'Search docs', noDocsMatch: 'No articles match.', + docsIndexSubtitle: 'Guides that come with your installed apps.', + searchAllDocs: 'Search all documentation', + articleCount: '{{count}} articles', + articleCount_one: '{{count}} article', + articleCount_other: '{{count}} articles', + otherDocs: 'Other documentation', + noDocsInstalled: 'No documentation is installed yet.', + loadDocsFailed: 'Failed to load documentation', + searchingDocs: 'Searching…', + searchResultCount: '{{count}} articles found', + searchResultCount_one: '{{count}} article found', + searchResultCount_other: '{{count}} articles found', + docsSearchFailed: 'Could not search the documentation: {{message}}', docsNavigation: 'Documentation navigation', docsBreadcrumb: 'Documentation path', articlePager: 'Previous and next article', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 33002fdbd3c..488150d8699 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3378,6 +3378,21 @@ const es = { backToApp: 'Volver a {{app}}', searchDocs: 'Buscar en la documentación', noDocsMatch: 'Ningún artículo coincide.', + docsIndexSubtitle: 'Guías incluidas con tus aplicaciones instaladas.', + searchAllDocs: 'Buscar en toda la documentación', + articleCount: '{{count}} artículos', + articleCount_one: '{{count}} artículo', + articleCount_many: '{{count}} de artículos', + articleCount_other: '{{count}} artículos', + otherDocs: 'Otra documentación', + noDocsInstalled: 'Todavía no hay documentación instalada.', + loadDocsFailed: 'No se pudo cargar la documentación', + searchingDocs: 'Buscando…', + searchResultCount: '{{count}} artículos encontrados', + searchResultCount_one: '{{count}} artículo encontrado', + searchResultCount_many: '{{count}} de artículos encontrados', + searchResultCount_other: '{{count}} artículos encontrados', + docsSearchFailed: 'No se pudo buscar en la documentación: {{message}}', docsNavigation: 'Navegación de la documentación', docsBreadcrumb: 'Ruta de la documentación', articlePager: 'Artículo anterior y siguiente', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 309586fcc1d..995bb713f76 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3374,6 +3374,21 @@ const fr = { backToApp: 'Retour à {{app}}', searchDocs: 'Rechercher dans la documentation', noDocsMatch: 'Aucun article ne correspond.', + docsIndexSubtitle: 'Les guides fournis avec vos applications installées.', + searchAllDocs: 'Rechercher dans toute la documentation', + articleCount: '{{count}} articles', + articleCount_one: '{{count}} article', + articleCount_many: '{{count}} d\'articles', + articleCount_other: '{{count}} articles', + otherDocs: 'Autre documentation', + noDocsInstalled: 'Aucune documentation n\'est encore installée.', + loadDocsFailed: 'Impossible de charger la documentation', + searchingDocs: 'Recherche…', + searchResultCount: '{{count}} articles trouvés', + searchResultCount_one: '{{count}} article trouvé', + searchResultCount_many: '{{count}} d\'articles trouvés', + searchResultCount_other: '{{count}} articles trouvés', + docsSearchFailed: 'Impossible de rechercher dans la documentation : {{message}}', docsNavigation: 'Navigation de la documentation', docsBreadcrumb: 'Chemin de la documentation', articlePager: 'Article précédent et suivant', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 8a672779b4b..334a63ee460 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3303,6 +3303,19 @@ const ja = { backToApp: '{{app}}に戻る', searchDocs: 'ドキュメントを検索', noDocsMatch: '一致する記事はありません。', + docsIndexSubtitle: 'インストール済みアプリに付属するガイドです。', + searchAllDocs: 'すべてのドキュメントを検索', + articleCount: '{{count}} 件の記事', + articleCount_one: '{{count}} 件の記事', + articleCount_other: '{{count}} 件の記事', + otherDocs: 'その他のドキュメント', + noDocsInstalled: 'ドキュメントはまだインストールされていません。', + loadDocsFailed: 'ドキュメントを読み込めませんでした', + searchingDocs: '検索中…', + searchResultCount: '{{count}} 件の記事が見つかりました', + searchResultCount_one: '{{count}} 件の記事が見つかりました', + searchResultCount_other: '{{count}} 件の記事が見つかりました', + docsSearchFailed: 'ドキュメントを検索できませんでした: {{message}}', docsNavigation: 'ドキュメントのナビゲーション', docsBreadcrumb: 'ドキュメントの階層', articlePager: '前後の記事', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index ff0d10d666d..b465c7b5bb9 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3301,6 +3301,19 @@ const ko = { backToApp: '{{app}}(으)로 돌아가기', searchDocs: '문서 검색', noDocsMatch: '일치하는 문서가 없습니다.', + docsIndexSubtitle: '설치된 앱에 포함된 가이드입니다.', + searchAllDocs: '모든 문서 검색', + articleCount: '문서 {{count}}개', + articleCount_one: '문서 {{count}}개', + articleCount_other: '문서 {{count}}개', + otherDocs: '기타 문서', + noDocsInstalled: '아직 설치된 문서가 없습니다.', + loadDocsFailed: '문서를 불러오지 못했습니다', + searchingDocs: '검색 중…', + searchResultCount: '문서 {{count}}개 찾음', + searchResultCount_one: '문서 {{count}}개 찾음', + searchResultCount_other: '문서 {{count}}개 찾음', + docsSearchFailed: '문서를 검색할 수 없습니다: {{message}}', docsNavigation: '문서 탐색', docsBreadcrumb: '문서 경로', articlePager: '이전 및 다음 문서', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 2fe6f9851b0..0dc47abbe5a 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3373,6 +3373,21 @@ const pt = { backToApp: 'Voltar para {{app}}', searchDocs: 'Pesquisar na documentação', noDocsMatch: 'Nenhum artigo corresponde.', + docsIndexSubtitle: 'Guias que acompanham seus aplicativos instalados.', + searchAllDocs: 'Pesquisar em toda a documentação', + articleCount: '{{count}} artigos', + articleCount_one: '{{count}} artigo', + articleCount_many: '{{count}} de artigos', + articleCount_other: '{{count}} artigos', + otherDocs: 'Outra documentação', + noDocsInstalled: 'Ainda não há documentação instalada.', + loadDocsFailed: 'Não foi possível carregar a documentação', + searchingDocs: 'Pesquisando…', + searchResultCount: '{{count}} artigos encontrados', + searchResultCount_one: '{{count}} artigo encontrado', + searchResultCount_many: '{{count}} de artigos encontrados', + searchResultCount_other: '{{count}} artigos encontrados', + docsSearchFailed: 'Não foi possível pesquisar a documentação: {{message}}', docsNavigation: 'Navegação da documentação', docsBreadcrumb: 'Caminho da documentação', articlePager: 'Artigo anterior e próximo', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index c94bb0a2b89..25fa7767439 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3460,6 +3460,23 @@ const ru = { backToApp: 'Назад в {{app}}', searchDocs: 'Поиск по документации', noDocsMatch: 'Нет подходящих статей.', + docsIndexSubtitle: 'Руководства, поставляемые с установленными приложениями.', + searchAllDocs: 'Поиск по всей документации', + articleCount: '{{count}} статьи', + articleCount_one: '{{count}} статья', + articleCount_few: '{{count}} статьи', + articleCount_many: '{{count}} статей', + articleCount_other: '{{count}} статьи', + otherDocs: 'Прочая документация', + noDocsInstalled: 'Документация пока не установлена.', + loadDocsFailed: 'Не удалось загрузить документацию', + searchingDocs: 'Поиск…', + searchResultCount: 'Найдено {{count}} статьи', + searchResultCount_one: 'Найдена {{count}} статья', + searchResultCount_few: 'Найдено {{count}} статьи', + searchResultCount_many: 'Найдено {{count}} статей', + searchResultCount_other: 'Найдено {{count}} статьи', + docsSearchFailed: 'Не удалось выполнить поиск по документации: {{message}}', docsNavigation: 'Навигация по документации', docsBreadcrumb: 'Путь в документации', articlePager: 'Предыдущая и следующая статья', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index a0992ad3801..8c5f38c7773 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3382,6 +3382,19 @@ const zh = { backToApp: '返回{{app}}', searchDocs: '搜索文档', noDocsMatch: '没有匹配的篇目。', + docsIndexSubtitle: '已安装应用自带的使用手册。', + searchAllDocs: '搜索全部文档', + articleCount: '{{count}} 篇', + articleCount_one: '{{count}} 篇', + articleCount_other: '{{count}} 篇', + otherDocs: '其他文档', + noDocsInstalled: '还没有安装任何文档。', + loadDocsFailed: '文档加载失败', + searchingDocs: '正在搜索…', + searchResultCount: '找到 {{count}} 篇', + searchResultCount_one: '找到 {{count}} 篇', + searchResultCount_other: '找到 {{count}} 篇', + docsSearchFailed: '无法搜索文档:{{message}}', docsNavigation: '文档导航', docsBreadcrumb: '文档路径', articlePager: '上一篇和下一篇', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 794eac384d9..cc2f54d7eac 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3382,6 +3382,19 @@ const zhHant = { backToApp: '返回{{app}}', searchDocs: '搜尋文件', noDocsMatch: '沒有匹配的篇目。', + docsIndexSubtitle: '已安裝應用自帶的使用手冊。', + searchAllDocs: '搜尋全部文件', + articleCount: '{{count}} 篇', + articleCount_one: '{{count}} 篇', + articleCount_other: '{{count}} 篇', + otherDocs: '其他文件', + noDocsInstalled: '還沒有安裝任何文件。', + loadDocsFailed: '文件載入失敗', + searchingDocs: '正在搜尋…', + searchResultCount: '找到 {{count}} 篇', + searchResultCount_one: '找到 {{count}} 篇', + searchResultCount_other: '找到 {{count}} 篇', + docsSearchFailed: '無法搜尋文件:{{message}}', docsNavigation: '文件導航', docsBreadcrumb: '文件路徑', articlePager: '上一篇和下一篇',