diff --git a/.changeset/35424-docs-reader-one-column.md b/.changeset/35424-docs-reader-one-column.md new file mode 100644 index 00000000000..7c207565acc --- /dev/null +++ b/.changeset/35424-docs-reader-one-column.md @@ -0,0 +1,15 @@ +--- +'@object-ui/console': patch +'@object-ui/app-shell': patch +'@object-ui/plugin-markdown': patch +'@object-ui/i18n': patch +--- + +feat(console): an app's docs page has one navigation — the docs column — with the path to its book and the previous and next article + +Clause-②: yes (widening) — @object-ui/plugin-markdown exports MermaidEnlargeContext and MermaidEnlargeText; @object-ui/i18n adds 12 help.* keys; nothing removed +Metadata-protocol: none + +Inside an app, the documentation pages (`/apps//docs/…`) no longer draw the app menu beside the docs: the left column is the docs' own, with 「← Back to 」 at its top, a title filter, every book of the app's package (the current book open, the others folded, each with its article count; long titles wrap instead of truncating) and 「All documentation →」 at its foot. Every other docs page inside an app (the app's docs index, a book with no articles, a book or doc not found) carries the same 「← Back to 」 at its top. The app bar stays, and reads 「 / Documentation」; the separate 「Documentation / 」 bar under it is gone, and the path above the article names the book (Documentation › <book>). 「On this page」 marks the section being read as the page scrolls, and the article ends with its book's previous and next article. The article column is 720 px wide at 15 px, and a diagram carries an 「Enlarge」 control that opens it full size. + +`@object-ui/plugin-markdown` adds `MermaidEnlargeContext`: a host that provides its words gets the enlarge control on every rendered diagram; with no provider a diagram renders exactly as before. `@object-ui/app-shell` exports `matchAppBySegment` and `useServedAppLabel`, and `isAppDocsPath` beside `isRecordPagePath` from its `ConsoleLayout` module. New `help.*` keys in every shipped locale. No doc content, doc metadata, route or API changes. diff --git a/ui/apps/console/src/pages/AppDocsBackLink.tsx b/ui/apps/console/src/pages/AppDocsBackLink.tsx new file mode 100644 index 00000000000..a3937630e29 --- /dev/null +++ b/ui/apps/console/src/pages/AppDocsBackLink.tsx @@ -0,0 +1,32 @@ +/** + * 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 { Link } from 'react-router-dom'; +import { ArrowLeft } from 'lucide-react'; +import { useObjectTranslation } from '@object-ui/i18n'; +import type { AppDocsBackTo } from './useAppDocsBackTo'; + +/** + * 「← Back to APP」 (objectstack#35424). An app's docs routes draw no app + * menu, so every docs page inside an app carries this link: the reader in + * its docs column, every other page (the app's docs index, a book with no + * articles, a book or doc not found) at the top, through `DocShell`. + */ +export function AppDocsBackLink({ backTo }: { backTo: AppDocsBackTo }) { + const { t } = useObjectTranslation(); + return ( + <Link + to={backTo.to} + data-testid="docs-nav-back" + className="inline-flex items-center gap-1.5 self-start rounded px-2 py-1 text-sm font-medium text-primary hover:bg-muted/50" + > + <ArrowLeft className="h-4 w-4 shrink-0" aria-hidden /> + <span>{t('help.backToApp', { defaultValue: 'Back to {{app}}', app: backTo.label })}</span> + </Link> + ); +} diff --git a/ui/apps/console/src/pages/BookSidebar.tsx b/ui/apps/console/src/pages/BookSidebar.tsx index cac988421bc..57a94cc6ef0 100644 --- a/ui/apps/console/src/pages/BookSidebar.tsx +++ b/ui/apps/console/src/pages/BookSidebar.tsx @@ -16,6 +16,9 @@ import type { ResolvedBook } from './book-nav'; * alongside the single-doc reader so a reader can move within the book * without losing their place. * + * A long title wraps rather than truncating, so every entry is readable in + * full (objectstack#35424). + * * Routing is delegated: the parent supplies `docHref` so the same sidebar * works under the top-level `/docs/:name` route and the package-scoped * `/apps/:appName/docs/:name` route. @@ -24,22 +27,31 @@ export function BookSidebar({ book, activeDoc, docHref, + showLabel = true, + groupHeadings = 'always', }: { book: ResolvedBook; activeDoc?: string; docHref: (docName: string) => string; + /** Draw the book's label above its groups; off where a parent already names the book (the docs column). */ + showLabel?: boolean; + /** `multi`: a book of one group lists its entries under no heading, the book's name being the heading. */ + groupHeadings?: 'always' | 'multi'; }) { + const headings = groupHeadings === 'always' || book.groups.length > 1; return ( <nav aria-label={book.label ?? book.name} className="text-sm"> - {book.label ? ( + {showLabel && book.label ? ( <div className="mb-3 px-2 text-sm font-semibold text-foreground">{book.label}</div> ) : null} - <div className="space-y-5"> + <div className={headings ? 'space-y-5' : undefined}> {book.groups.map((group) => ( <div key={group.key}> - <div className="mb-1 px-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground"> - {group.label} - </div> + {headings ? ( + <div className="mb-1 px-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground"> + {group.label} + </div> + ) : null} <ul className="space-y-0.5"> {group.entries.map((entry, i) => { if (entry.separator) { @@ -54,7 +66,7 @@ export function BookSidebar({ rel="noreferrer" className="flex items-center gap-1.5 rounded px-2 py-1 text-muted-foreground hover:bg-muted/50 hover:text-foreground" > - <span className="truncate">{entry.label ?? entry.href}</span> + <span className="break-words">{entry.label ?? entry.href}</span> <ExternalLink className="h-3 w-3 shrink-0 opacity-60" /> </a> </li> @@ -67,9 +79,9 @@ export function BookSidebar({ <Link to={docHref(entry.doc)} aria-current={active ? 'page' : undefined} - className={`block truncate rounded px-2 py-1 transition ${ + className={`block break-words rounded px-2 py-1.5 leading-snug transition ${ active - ? 'bg-primary/10 font-medium text-foreground' + ? 'bg-primary/10 font-medium text-primary' : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground' }`} > diff --git a/ui/apps/console/src/pages/DocPage.docLinkBasename-12686.test.tsx b/ui/apps/console/src/pages/DocPage.docLinkBasename-12686.test.tsx index 5235a89a48b..06c6f5d52b9 100644 --- a/ui/apps/console/src/pages/DocPage.docLinkBasename-12686.test.tsx +++ b/ui/apps/console/src/pages/DocPage.docLinkBasename-12686.test.tsx @@ -193,6 +193,9 @@ describe("a doc-to-doc link in an app's doc stays in that app's docs route (obje it('CONTROL: outside an app the header home link is still the portal', async () => { renderDoc('/_console'); await screen.findByRole('link', { name: 'index' }); - expect(screen.getByRole('link', { name: 'Documentation' }).getAttribute('href')).toBe('/_console/docs'); + // The portal header's home link, and the path above the article + // (objectstack#35424): both name the portal. + const links = screen.getAllByRole('link', { name: 'Documentation' }); + expect(links.map((l) => l.getAttribute('href'))).toEqual(links.map(() => '/_console/docs')); }); }); diff --git a/ui/apps/console/src/pages/DocPage.tsx b/ui/apps/console/src/pages/DocPage.tsx index 477870c7f3c..9ce1ac08b3e 100644 --- a/ui/apps/console/src/pages/DocPage.tsx +++ b/ui/apps/console/src/pages/DocPage.tsx @@ -8,17 +8,20 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Link, Navigate, useHref, useLocation, useNavigate, useParams } from 'react-router-dom'; -import { AlertCircle, ChevronDown, FileQuestion, Layers, Loader2, Menu } from 'lucide-react'; +import { AlertCircle, ChevronDown, ChevronRight, FileQuestion, Layers, Loader2, Menu } from 'lucide-react'; import { useAdapter } from '@object-ui/app-shell'; -import { MarkdownRenderer, extractToc } from '@object-ui/plugin-markdown'; +import { MarkdownRenderer, MermaidEnlargeContext, extractToc } from '@object-ui/plugin-markdown'; import { useObjectTranslation } from '@object-ui/i18n'; import { rewriteDocLinks } from './doc-links'; import { conflictCandidates, readsByNameAfter } from './doc-address'; import { DocShell } from './DocShell'; -import { BookSidebar } from './BookSidebar'; +import { useAppDocsBackTo } from './useAppDocsBackTo'; +import { DocsNav, type DocsNavBook } from './DocsNav'; import { DocRefusal } from './BookPage'; import { useBookData } from './use-book-data'; -import { resolveBookTree, bookSlug, bookNamedBy, homeBook, labelUncategorized, type ResolvedBook } from './book-nav'; +import { useActiveHeading } from './useActiveHeading'; +import { articleNeighbours, type BookArticle } from './docs-reading'; +import { resolveBookTree, bookSlug, bookNamedBy, homeBook, labelUncategorized, pkgOfBook, type ResolvedBook } from './book-nav'; interface DocItem { name: string; @@ -244,6 +247,35 @@ export default function DocPage() { : null; }, [books, authoredBooks, allDocs, slug, uncategorizedLabel]); const docHref = useCallback((docName: string) => `${base}/${slug}/${docName}`, [base, slug]); + // objectstack#35424 — the docs column lists every book of the package the + // reader is in: the current book's package, else the route's app package. + const packageBooks = useMemo<DocsNavBook[]>(() => { + const current = books.find((b) => bookSlug(b) === slug); + const pkg = current ? pkgOfBook(current) : appName; + if (!pkg) return []; + return books + .filter((b) => pkgOfBook(b) === pkg) + .map((b) => ({ + slug: bookSlug(b), + book: labelUncategorized(resolveBookTree(b, allDocs, undefined, authoredBooks), uncategorizedLabel), + })); + }, [books, authoredBooks, allDocs, slug, appName, uncategorizedLabel]); + const neighbours = useMemo( + () => (resolvedBook ? articleNeighbours(resolvedBook, name) : { previous: null, next: null }), + [resolvedBook, name], + ); + const bookDocHref = useCallback((bookSegment: string, docName: string) => `${base}/${bookSegment}/${docName}`, [base]); + // The app the reader returns to (its docs column's back link). + const backTo = useAppDocsBackTo(); + const tocIds = useMemo(() => toc.map((item) => item.id), [toc]); + const activeHeading = useActiveHeading(state === 'ready' ? tocIds : []); + const enlargeText = useMemo( + () => ({ + enlarge: t('help.enlargeDiagram', { defaultValue: 'Enlarge' }), + title: t('help.diagram', { defaultValue: 'Diagram' }), + }), + [t], + ); // A `:slug` segment that is a book's NAME rather than its slug — what a // `{ type: 'doc', book, doc }` navigation entry links to (objectui#11197) — is // redirected to the canonical `bookSlug` URL, so the page reads in that book's @@ -335,62 +367,169 @@ export default function DocPage() { ); } + const docsNav = + packageBooks.length > 0 ? ( + <DocsNav + books={packageBooks} + currentSlug={slug} + activeDoc={name} + docHref={bookDocHref} + backTo={backTo} + allDocsHref="/docs" + /> + ) : null; + const docsLabel = t('help.documentation', { defaultValue: 'Documentation' }); + return ( - <DocShell breadcrumb={doc?.label ?? name}> - {/* Narrow screens: the persistent left sidebar is hidden, so the book - * nav collapses into a disclosure above the content instead of vanishing. */} - {resolvedBook ? ( - <details className="group mx-auto max-w-6xl px-4 pt-4 sm:px-6 lg:hidden"> - <summary className="flex cursor-pointer list-none items-center gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm font-medium [&::-webkit-details-marker]:hidden"> - <Menu className="h-4 w-4 text-muted-foreground" /> - <span className="truncate">{resolvedBook.label ?? 'Contents'}</span> - <ChevronDown className="ml-auto h-4 w-4 text-muted-foreground transition-transform group-open:rotate-180" /> - </summary> - <div className="mt-2 rounded-md border p-3"> - <BookSidebar book={resolvedBook} activeDoc={name} docHref={docHref} /> - </div> - </details> - ) : null} - <div className={`mx-auto flex gap-8 p-4 sm:p-6 ${resolvedBook ? 'max-w-6xl' : 'max-w-5xl'}`}> - {resolvedBook ? ( - <aside className="hidden w-56 shrink-0 lg:block"> - <nav className="sticky top-20 max-h-[calc(100vh-6rem)] overflow-auto pr-1"> - <BookSidebar book={resolvedBook} activeDoc={name} docHref={docHref} /> - </nav> - </aside> - ) : null} - <article - ref={articleRef} - className="min-w-0 max-w-3xl flex-1 [&_h1]:scroll-mt-24 [&_h2]:scroll-mt-24 [&_h3]:scroll-mt-24" - onClick={onContentClick} - > - <MarkdownRenderer - schema={{ type: 'markdown', content: rewriteDocLinks(doc?.content ?? '', docsHref) }} - /> - </article> - {toc.length >= 3 ? ( - <aside className="hidden xl:block w-56 shrink-0"> - <nav aria-label={tocLabel} className="sticky top-20 max-h-[calc(100vh-6rem)] overflow-auto"> - <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground"> - {tocLabel} - </div> - <ul className="border-l border-border text-sm"> - {toc.map((item) => ( - <li key={item.id} style={{ paddingLeft: (item.depth - 2) * 12 }}> - <a - href={`#${item.id}`} - onClick={(e) => onTocClick(e, item.id)} - className="-ml-px block border-l border-transparent py-0.5 pl-3 text-muted-foreground hover:border-primary hover:text-foreground" - > - {item.text} - </a> - </li> - ))} - </ul> + <DocShell breadcrumb={doc?.label ?? name} backLink={false}> + {/* 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. */} + <div className="flex min-h-full" data-testid="doc-reader"> + {docsNav ? ( + <aside className="hidden w-72 shrink-0 border-r lg:block"> + <nav + aria-label={t('help.docsNavigation', { defaultValue: 'Documentation navigation' })} + className={`sticky overflow-auto px-4 py-6 ${appName ? 'top-0 max-h-[calc(100svh-3rem)]' : 'top-12 max-h-[calc(100svh-3rem)]'}`} + > + {docsNav} </nav> </aside> ) : null} + <div className="min-w-0 flex-1"> + {docsNav ? ( + <details className="group mx-4 mt-4 sm:mx-6 lg:hidden"> + <summary className="flex cursor-pointer list-none items-center gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm font-medium [&::-webkit-details-marker]:hidden"> + <Menu className="h-4 w-4 text-muted-foreground" /> + <span className="truncate">{resolvedBook?.label ?? docsLabel}</span> + <ChevronDown className="ml-auto h-4 w-4 text-muted-foreground transition-transform group-open:rotate-180" /> + </summary> + <div className="mt-2 rounded-md border p-3">{docsNav}</div> + </details> + ) : null} + <div className="mx-auto flex max-w-[1080px] justify-center gap-10 px-4 py-6 sm:px-8 lg:py-8"> + <div className="min-w-0 max-w-[720px] flex-1"> + <nav + aria-label={t('help.docsBreadcrumb', { defaultValue: 'Documentation path' })} + className="mb-3 flex flex-wrap items-center gap-1 text-sm text-muted-foreground" + data-testid="doc-breadcrumb" + > + <Link to={base} className="hover:text-foreground"> + {docsLabel} + </Link> + {resolvedBook ? ( + <> + <ChevronRight className="h-3.5 w-3.5 shrink-0" aria-hidden /> + <Link to={`${base}/${slug}`} className="hover:text-foreground"> + {resolvedBook.label ?? resolvedBook.name} + </Link> + </> + ) : null} + </nav> + <article + ref={articleRef} + className="[&_h1]:scroll-mt-24 [&_h2]:scroll-mt-24 [&_h3]:scroll-mt-24" + onClick={onContentClick} + > + <MermaidEnlargeContext.Provider value={enlargeText}> + <MarkdownRenderer + schema={{ + type: 'markdown', + className: '!text-[15px]', + content: rewriteDocLinks(doc?.content ?? '', docsHref), + }} + /> + </MermaidEnlargeContext.Provider> + </article> + {resolvedBook ? ( + <ArticlePager + previous={neighbours.previous} + next={neighbours.next} + href={(article) => docHref(article.doc)} + /> + ) : null} + </div> + {toc.length >= 3 ? ( + <aside className="hidden w-56 shrink-0 xl:block"> + <nav aria-label={tocLabel} className="sticky top-6 max-h-[calc(100svh-6rem)] overflow-auto"> + <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground"> + {tocLabel} + </div> + <ul className="border-l border-border text-sm"> + {toc.map((item) => { + const current = item.id === activeHeading; + return ( + <li key={item.id} style={{ paddingLeft: (item.depth - 2) * 12 }}> + <a + href={`#${item.id}`} + onClick={(e) => onTocClick(e, item.id)} + aria-current={current ? 'location' : undefined} + className={`-ml-px block border-l-2 py-1 pl-3 ${ + current + ? 'border-primary font-medium text-primary' + : 'border-transparent text-muted-foreground hover:border-border hover:text-foreground' + }`} + > + {item.text} + </a> + </li> + ); + })} + </ul> + </nav> + </aside> + ) : null} + </div> + </div> </div> </DocShell> ); } + +/** + * The previous and next article of the book, at the article's end + * (objectstack#35424). At either end of the book the empty side says so + * instead of disappearing, so the two cards keep their places. + */ +function ArticlePager({ + previous, + next, + href, +}: { + previous: BookArticle | null; + next: BookArticle | null; + href: (article: BookArticle) => string; +}) { + const { t } = useObjectTranslation(); + const card = 'flex min-h-[4.5rem] flex-col justify-center gap-1 rounded-lg border px-4 py-3'; + return ( + <nav + aria-label={t('help.articlePager', { defaultValue: 'Previous and next article' })} + className="mt-12 grid gap-3 border-t pt-6 sm:grid-cols-2" + data-testid="doc-pager" + > + {previous ? ( + <Link to={href(previous)} rel="prev" className={`${card} hover:bg-muted/50`} data-testid="doc-pager-previous"> + <span className="text-xs text-muted-foreground">{t('help.previousArticle', { defaultValue: 'Previous' })}</span> + <span className="font-medium text-primary">← {previous.label}</span> + </Link> + ) : ( + <div className={`${card} text-muted-foreground`} data-testid="doc-pager-first"> + <span className="text-xs">{t('help.previousArticle', { defaultValue: 'Previous' })}</span> + <span className="text-sm">{t('help.firstInBook', { defaultValue: 'This is the first article in this book' })}</span> + </div> + )} + {next ? ( + <Link to={href(next)} rel="next" className={`${card} items-end text-right hover:bg-muted/50`} data-testid="doc-pager-next"> + <span className="text-xs text-muted-foreground">{t('help.nextArticle', { defaultValue: 'Next' })}</span> + <span className="font-medium text-primary">{next.label} →</span> + </Link> + ) : ( + <div className={`${card} items-end text-right text-muted-foreground`} data-testid="doc-pager-last"> + <span className="text-xs">{t('help.nextArticle', { defaultValue: 'Next' })}</span> + <span className="text-sm">{t('help.lastInBook', { defaultValue: 'This is the last article in this book' })}</span> + </div> + )} + </nav> + ); +} diff --git a/ui/apps/console/src/pages/DocShell.tsx b/ui/apps/console/src/pages/DocShell.tsx index 086d30f34d9..4f4a6bee068 100644 --- a/ui/apps/console/src/pages/DocShell.tsx +++ b/ui/apps/console/src/pages/DocShell.tsx @@ -10,6 +10,8 @@ import type { ReactNode } from 'react'; import { Link, useParams } from 'react-router-dom'; import { BookOpen } from 'lucide-react'; import { useObjectTranslation } from '@object-ui/i18n'; +import { AppDocsBackLink } from './AppDocsBackLink'; +import { useAppDocsBackTo } from './useAppDocsBackTo'; /** * Lightweight chrome for the package-documentation routes (ADR-0046). @@ -20,15 +22,40 @@ import { useObjectTranslation } from '@object-ui/i18n'; * 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) the home link is that - * app's docs index, so it keeps the reader inside the app shell, the same - * answer the sidebar and the body cross-references give. The label reads the - * session language (`help.documentation`). + * 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`). */ -export function DocShell({ breadcrumb, children }: { breadcrumb?: string; children: ReactNode }) { +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). */ + backLink?: boolean; + children: ReactNode; +}) { const { appName } = useParams<{ appName?: string }>(); const { t } = useObjectTranslation(); - const home = appName ? `/apps/${appName}/docs` : '/docs'; + 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"> diff --git a/ui/apps/console/src/pages/DocsNav.tsx b/ui/apps/console/src/pages/DocsNav.tsx new file mode 100644 index 00000000000..5173007f868 --- /dev/null +++ b/ui/apps/console/src/pages/DocsNav.tsx @@ -0,0 +1,130 @@ +/** + * 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 { useId, useState } from 'react'; +import { Link } from 'react-router-dom'; +import { ArrowRight, ChevronDown, ChevronRight, Search } from 'lucide-react'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { AppDocsBackLink } from './AppDocsBackLink'; +import type { AppDocsBackTo } from './useAppDocsBackTo'; +import { BookSidebar } from './BookSidebar'; +import { bookArticles, filterBookArticles } from './docs-reading'; +import type { ResolvedBook } from './book-nav'; + +/** One book of the column: its resolved spine and its URL segment. */ +export interface DocsNavBook { + slug: string; + book: ResolvedBook; +} + +/** + * The docs reader's one navigation column (objectstack#35424): a way back to + * the app the reader came from, a title filter, every book of the package + * (the current one open, the others folded, each with its article count), + * and a link to all documentation. Inside an app it takes the app menu's + * place; the shell draws no menu beside it. + */ +export function DocsNav({ + books, + currentSlug, + activeDoc, + docHref, + backTo, + allDocsHref, +}: { + books: readonly DocsNavBook[]; + currentSlug?: string; + activeDoc?: string; + docHref: (slug: string, doc: string) => string; + /** The app to return to; absent outside an app. */ + backTo?: AppDocsBackTo; + allDocsHref: string; +}) { + const { t } = useObjectTranslation(); + const [query, setQuery] = useState(''); + // A book the reader folded or unfolded; every other book follows the rule: + // the current book open, the rest folded. + const [toggled, setToggled] = useState<Record<string, boolean>>({}); + const searchId = useId(); + const searching = query.trim() !== ''; + const shown = books + .map((entry) => ({ ...entry, filtered: filterBookArticles(entry.book, query) })) + .filter((entry) => !searching || entry.filtered.groups.length > 0); + const searchLabel = t('help.searchDocs', { defaultValue: 'Search docs' }); + + return ( + <div className="flex flex-col gap-4 text-sm" data-testid="docs-nav"> + {backTo ? <AppDocsBackLink backTo={backTo} /> : null} + <div className="relative"> + <label htmlFor={searchId} className="sr-only"> + {searchLabel} + </label> + <Search className="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden /> + <input + id={searchId} + type="search" + value={query} + onChange={(e) => setQuery(e.target.value)} + placeholder={searchLabel} + data-testid="docs-nav-search" + className="h-9 w-full rounded-md border bg-background pl-8 pr-2 text-sm placeholder:text-muted-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring" + /> + </div> + {shown.length === 0 ? ( + <p className="px-2 text-muted-foreground" data-testid="docs-nav-no-match"> + {t('help.noDocsMatch', { defaultValue: 'No articles match.' })} + </p> + ) : ( + <ul className="flex flex-col gap-1"> + {shown.map(({ slug, book, filtered }) => { + const open = searching || (toggled[slug] ?? slug === currentSlug); + const label = book.label ?? book.name; + const count = bookArticles(book).length; + const Chevron = open ? ChevronDown : ChevronRight; + return ( + <li key={slug}> + <button + type="button" + aria-expanded={open} + disabled={searching} + onClick={() => setToggled((prev) => ({ ...prev, [slug]: !open }))} + className="flex w-full items-start gap-2 rounded px-2 py-1.5 text-left font-semibold text-foreground hover:bg-muted/50 disabled:cursor-default disabled:hover:bg-transparent" + > + <span className="min-w-0 flex-1 break-words">{label}</span> + <span className="mt-px shrink-0 text-xs font-normal tabular-nums text-muted-foreground">{count}</span> + <Chevron className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden /> + </button> + {open ? ( + <div className="mt-1 pb-2"> + <BookSidebar + book={filtered} + activeDoc={slug === currentSlug ? activeDoc : undefined} + docHref={(doc) => docHref(slug, doc)} + showLabel={false} + groupHeadings="multi" + /> + </div> + ) : null} + </li> + ); + })} + </ul> + )} + <div className="border-t pt-3"> + <Link + to={allDocsHref} + data-testid="docs-nav-all-docs" + className="inline-flex items-center gap-1.5 rounded px-2 py-1 font-medium text-primary hover:bg-muted/50" + > + <span>{t('help.allDocs', { defaultValue: 'All documentation' })}</span> + <ArrowRight className="h-4 w-4 shrink-0" aria-hidden /> + </Link> + </div> + </div> + ); +} diff --git a/ui/apps/console/src/pages/docs-portal.test.tsx b/ui/apps/console/src/pages/docs-portal.test.tsx index 2cb3f75bd9b..66c2118412f 100644 --- a/ui/apps/console/src/pages/docs-portal.test.tsx +++ b/ui/apps/console/src/pages/docs-portal.test.tsx @@ -184,6 +184,7 @@ import DocsLayout from './DocsLayout'; import DocsIndex from './DocsIndex'; import DocsSlug from './DocsSlug'; import DocPage from './DocPage'; +import AppDocsIndex from './AppDocsIndex'; // Mirrors the real route table: the layout fetches once and shares the data. function Harness({ entry }: { entry: string }) { @@ -656,3 +657,123 @@ describe('objectstack#34070 — a doc name two packages ship lists its candidate }); }); }); + +// ───────────────────────────────────────────────────────────────────────────── +// objectstack#35424 — the in-app reader: one docs column, a path above the +// article, and the previous / next article at its end +// ───────────────────────────────────────────────────────────────────────────── + +describe('objectstack#35424 — the in-app reader has one docs column and a path to its book', () => { + function Where() { + return <div data-testid="where">{useLocation().pathname}</div>; + } + function InApp({ entry }: { entry: string }) { + return ( + <MemoryRouter initialEntries={[entry]}> + <Where /> + <Routes> + <Route path="/apps/:appName/docs" element={<DocsLayout />}> + <Route index element={<AppDocsIndex />} /> + <Route path=":slug" element={<DocsSlug />} /> + <Route path=":slug/:name" element={<DocPage />} /> + </Route> + </Routes> + </MemoryRouter> + ); + } + /** The persistent column (the narrow-screen disclosure draws a second copy). */ + const column = () => screen.getAllByTestId('docs-nav')[0]; + + it('draws no bar of its own: the app bar names 「APP / Documentation」', async () => { + render(<InApp entry="/apps/crm/docs/crm/crm_intro" />); + await screen.findByTestId('doc-content'); + expect(document.querySelector('header')).toBeNull(); + }); + + it('the column leads back to the app and ends with all documentation', async () => { + render(<InApp entry="/apps/crm/docs/crm/crm_intro" />); + await screen.findByTestId('doc-content'); + expect(within(column()).getByTestId('docs-nav-back')).toHaveAttribute('href', '/apps/crm'); + // This harness's `t` returns the default text uninterpolated. + expect(within(column()).getByTestId('docs-nav-back')).toHaveTextContent('Back to'); + expect(within(column()).getByTestId('docs-nav-all-docs')).toHaveAttribute('href', '/docs'); + // The reader carries the link once, in its column: no second one above the page. + expect(screen.queryByTestId('docs-back-bar')).toBeNull(); + }); + + // The app menu is off on every docs route, so every docs page keeps a way back. + it('a book or doc that is not found still leads back to the app', async () => { + render(<InApp entry="/apps/crm/docs/nonesuch" />); + await screen.findByText(/not found/i); + const bar = screen.getByTestId('docs-back-bar'); + expect(within(bar).getByTestId('docs-nav-back')).toHaveAttribute('href', '/apps/crm'); + }); + + it('the path above the article names the book', async () => { + render(<InApp entry="/apps/crm/docs/crm/crm_intro" />); + await screen.findByTestId('doc-content'); + const path = screen.getByTestId('doc-breadcrumb'); + expect(within(path).getByRole('link', { name: 'Documentation' })).toHaveAttribute('href', '/apps/crm/docs'); + expect(within(path).getByRole('link', { name: 'Crm' })).toHaveAttribute('href', '/apps/crm/docs/crm'); + }); + + it('the first article says so on its previous side and links its next one', async () => { + render(<InApp entry="/apps/crm/docs/crm/crm_intro" />); + await screen.findByTestId('doc-content'); + expect(screen.getByTestId('doc-pager-first')).toHaveTextContent('This is the first article in this book'); + expect(screen.getByTestId('doc-pager-next')).toHaveAttribute('href', '/apps/crm/docs/crm/crm_guide_lead'); + expect(screen.getByTestId('doc-pager-next')).toHaveTextContent('Leads'); + }); + + it('the last article links its previous one and says it is the last', async () => { + render(<InApp entry="/apps/crm/docs/crm/crm_guide_lead" />); + await screen.findByTestId('doc-content'); + expect(screen.getByTestId('doc-pager-previous')).toHaveAttribute('href', '/apps/crm/docs/crm/crm_intro'); + expect(screen.getByTestId('doc-pager-last')).toHaveTextContent('This is the last article in this book'); + }); + + it('the search field narrows the column to matching titles, and says when none match', async () => { + render(<InApp entry="/apps/crm/docs/crm/crm_intro" />); + await screen.findByTestId('doc-content'); + const search = within(column()).getByTestId('docs-nav-search'); + fireEvent.change(search, { target: { value: 'lead' } }); + expect(within(column()).getByRole('link', { name: 'Leads' })).toBeInTheDocument(); + expect(within(column()).queryByRole('link', { name: 'CRM Intro' })).toBeNull(); + fireEvent.change(search, { target: { value: 'zzz' } }); + expect(within(column()).getByTestId('docs-nav-no-match')).toBeInTheDocument(); + }); + + describe('a package with several books', () => { + beforeEach(() => { + WORLD.authored = true; + }); + afterEach(() => { + WORLD.authored = false; + }); + + it('lists every book of the package, the current one open and the others folded', async () => { + render(<InApp entry="/apps/com.example.showcase/docs/manual/showcase_index" />); + await screen.findByTestId('doc-content'); + const current = within(column()).getByRole('button', { name: /Showcase Manual/ }); + const other = within(column()).getByRole('button', { name: /Leads Book/ }); + expect(current).toHaveAttribute('aria-expanded', 'true'); + expect(other).toHaveAttribute('aria-expanded', 'false'); + // No book of another package is listed. + expect(within(column()).queryByRole('button', { name: /Alpha Manual/ })).toBeNull(); + fireEvent.click(other); + expect(other).toHaveAttribute('aria-expanded', 'true'); + const lead = within(column()) + .getAllByRole('link', { name: 'Lead Guide' }) + .map((l) => l.getAttribute('href')); + expect(lead).toContain('/apps/com.example.showcase/docs/leads/showcase_lead_guide'); + }); + + it('the app\'s docs index (the path\'s 「Documentation」 link) leads back to the app', async () => { + render(<InApp entry="/apps/com.example.showcase/docs" />); + await screen.findByText('Leads Book'); + expect(screen.getByTestId('where')).toHaveTextContent('/apps/com.example.showcase/docs'); + const bar = screen.getByTestId('docs-back-bar'); + expect(within(bar).getByTestId('docs-nav-back')).toHaveAttribute('href', '/apps/com.example.showcase'); + }); + }); +}); diff --git a/ui/apps/console/src/pages/docs-reading.test.ts b/ui/apps/console/src/pages/docs-reading.test.ts new file mode 100644 index 00000000000..c57dd125aa6 --- /dev/null +++ b/ui/apps/console/src/pages/docs-reading.test.ts @@ -0,0 +1,109 @@ +/** + * 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 reader's reading order (previous / next article), + * the docs column's title filter, and which heading "On this page" marks. + */ + +import { describe, it, expect } from 'vitest'; +import { articleNeighbours, bookArticles, filterBookArticles } from './docs-reading'; +import { ACTIVE_HEADING_OFFSET, pickActiveHeading } from './useActiveHeading'; +import type { ResolvedBook } from './book-nav'; + +const BOOK: ResolvedBook = { + name: 'revenue', + label: 'Revenue', + groups: [ + { + key: 'quotes', + label: 'Quotes', + entries: [ + { doc: 'quotes', label: 'Quotes — generation and expiry', description: 'How a quote is priced' }, + { separator: true }, + { href: 'https://example.com', label: 'External' }, + { doc: 'products', label: 'Products and price books' }, + ], + }, + { + key: 'billing', + label: 'Billing', + entries: [ + { doc: 'billing', label: 'Billing hand-off' }, + // A doc placed twice keeps its first place. + { doc: 'quotes', label: 'Quotes — generation and expiry' }, + ], + }, + ], +}; + +describe('bookArticles / articleNeighbours', () => { + it('lists the docs in reading order, once each, without links or separators', () => { + expect(bookArticles(BOOK).map((a) => a.doc)).toEqual(['quotes', 'products', 'billing']); + }); + + it('answers the articles on either side, across groups', () => { + const { previous, next } = articleNeighbours(BOOK, 'products'); + expect(previous?.doc).toBe('quotes'); + expect(next?.doc).toBe('billing'); + }); + + it('answers null at the ends and for a doc the book does not hold', () => { + expect(articleNeighbours(BOOK, 'quotes').previous).toBeNull(); + expect(articleNeighbours(BOOK, 'billing').next).toBeNull(); + expect(articleNeighbours(BOOK, 'elsewhere')).toEqual({ previous: null, next: null }); + }); +}); + +describe('filterBookArticles', () => { + it('keeps the book unchanged for a blank query', () => { + expect(filterBookArticles(BOOK, ' ')).toBe(BOOK); + }); + + it('matches a title or a summary, case-insensitively, and drops empty groups', () => { + const byTitle = filterBookArticles(BOOK, 'PRICE BOOK'); + expect(byTitle.groups.map((g) => g.key)).toEqual(['quotes']); + expect(byTitle.groups[0].entries.map((e) => e.doc)).toEqual(['products']); + const bySummary = filterBookArticles(BOOK, 'priced'); + expect(bySummary.groups[0].entries.map((e) => e.doc)).toEqual(['quotes']); + }); + + it('never keeps a separator or an external link', () => { + const all = filterBookArticles(BOOK, 'e'); + expect(all.groups.flatMap((g) => g.entries).every((e) => !!e.doc && !e.separator)).toBe(true); + }); + + it('matches a non-Latin title', () => { + const zh: ResolvedBook = { name: 'b', groups: [{ key: 'g', label: 'G', entries: [{ doc: 'q', label: '报价单——生成与过期' }] }] }; + expect(filterBookArticles(zh, '报价').groups).toHaveLength(1); + }); +}); + +describe('pickActiveHeading', () => { + const tops = [ + { id: 'a', top: 40 }, + { id: 'b', top: 110 }, + { id: 'c', top: 600 }, + ]; + + it('is the last heading at or above the offset', () => { + expect(pickActiveHeading(tops, ACTIVE_HEADING_OFFSET, false)).toBe('b'); + }); + + it('is the first heading before any reaches the offset', () => { + expect(pickActiveHeading([{ id: 'a', top: 300 }, { id: 'b', top: 900 }], ACTIVE_HEADING_OFFSET, false)).toBe('a'); + }); + + it('is the last heading once the page is scrolled to its end', () => { + expect(pickActiveHeading(tops, ACTIVE_HEADING_OFFSET, true)).toBe('c'); + }); + + it('is null with no headings', () => { + expect(pickActiveHeading([], ACTIVE_HEADING_OFFSET, false)).toBeNull(); + }); +}); diff --git a/ui/apps/console/src/pages/docs-reading.ts b/ui/apps/console/src/pages/docs-reading.ts new file mode 100644 index 00000000000..e5ea0d43fe0 --- /dev/null +++ b/ui/apps/console/src/pages/docs-reading.ts @@ -0,0 +1,73 @@ +/** + * 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 type { ResolvedBook, ResolvedEntry, ResolvedGroup } from './book-nav'; + +/** + * Reading-order helpers for the docs reader (objectstack#35424): the previous + * and next article of a book, and the docs column's title filter. Pure, so the + * reader and its tests read the same answer. + */ + +/** One article of a book, in reading order. */ +export interface BookArticle { + doc: string; + label: string; +} + +/** + * The book's articles in reading order: every doc entry of every group, a doc + * placed twice counted once (its first place). External links and separators + * are not articles. + */ +export function bookArticles(book: ResolvedBook): BookArticle[] { + const seen = new Set<string>(); + const out: BookArticle[] = []; + for (const group of book.groups) { + for (const entry of group.entries) { + if (!entry.doc || entry.separator || seen.has(entry.doc)) continue; + seen.add(entry.doc); + out.push({ doc: entry.doc, label: entry.label ?? entry.doc }); + } + } + return out; +} + +/** The articles before and after `doc` in its book; `null` at either end, or when the book does not hold it. */ +export function articleNeighbours( + book: ResolvedBook, + doc: string | undefined, +): { previous: BookArticle | null; next: BookArticle | null } { + const articles = bookArticles(book); + const at = doc ? articles.findIndex((a) => a.doc === doc) : -1; + if (at < 0) return { previous: null, next: null }; + return { previous: articles[at - 1] ?? null, next: articles[at + 1] ?? null }; +} + +/** 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; + const hay = `${entry.label ?? entry.doc} ${entry.description ?? ''}`.toLocaleLowerCase(); + return hay.includes(needle); +} + +/** + * The book narrowed to the articles whose title or summary contains `query`: + * groups left empty are dropped, separators and external links go. A blank + * query answers the book unchanged. + */ +export function filterBookArticles(book: ResolvedBook, query: string): ResolvedBook { + const needle = query.trim().toLocaleLowerCase(); + if (!needle) return book; + const groups: ResolvedGroup[] = []; + for (const group of book.groups) { + const entries = group.entries.filter((e) => entryMatches(e, needle)); + if (entries.length > 0) groups.push({ ...group, entries }); + } + return { ...book, groups }; +} diff --git a/ui/apps/console/src/pages/useActiveHeading.ts b/ui/apps/console/src/pages/useActiveHeading.ts new file mode 100644 index 00000000000..c49754d80ba --- /dev/null +++ b/ui/apps/console/src/pages/useActiveHeading.ts @@ -0,0 +1,93 @@ +/** + * 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, useState } from 'react'; + +/** + * How far below the viewport's top a heading counts as "being read": the app + * bar (48 px) plus the headings' own scroll margin (`scroll-mt-24`, 96 px) + * leaves the heading a reader just jumped to at about 96 px; a little more + * keeps it current while its first lines are read. + */ +export const ACTIVE_HEADING_OFFSET = 120; + +/** + * Which of `ids` (in document order) the reader is in: the last heading whose + * top is at or above `offset`, the first one before any is, and the last one + * once the page is scrolled to its end (a short final section never reaches + * the top). Pure, for the hook and its test. + */ +export function pickActiveHeading( + tops: ReadonlyArray<{ id: string; top: number }>, + offset: number, + atEnd: boolean, +): string | null { + if (tops.length === 0) return null; + if (atEnd) return tops[tops.length - 1].id; + let active = tops[0].id; + for (const { id, top } of tops) { + if (top <= offset) active = id; + else break; + } + return active; +} + +/** Is the box that scrolled scrolled to its end? */ +function scrolledToEnd(el: Element): boolean { + return el.scrollHeight - el.scrollTop - el.clientHeight < 2; +} + +/** + * The id of the heading the reader is in, for the "On this page" column + * (objectstack#35424). The reader's page scrolls inside the app shell's + * content box, not the window, so scrolls are heard on the document in the + * capture phase, which every scrolling box reaches. Re-read once per frame. + */ +export function useActiveHeading(ids: readonly string[]): string | null { + const [active, setActive] = useState<string | null>(null); + const key = ids.join('\u0000'); + + useEffect(() => { + const list = key ? key.split('\u0000') : []; + if (list.length === 0) return; + let frame = 0; + // The box the last scroll came from: the page's scrolling element for a + // scroll of the document itself. + let lastTarget: Element | null = null; + const measure = () => { + frame = 0; + const tops: { id: string; top: number }[] = []; + for (const id of list) { + const el = document.getElementById(id); + if (el) tops.push({ id, top: el.getBoundingClientRect().top }); + } + setActive(pickActiveHeading(tops, ACTIVE_HEADING_OFFSET, lastTarget !== null && scrolledToEnd(lastTarget))); + }; + const schedule = (event?: Event) => { + if (event) { + const target = event.target === document ? document.scrollingElement : event.target; + // Only the box that scrolls the article counts: a side column that + // scrolls on its own says nothing about the reader's place. + const first = document.getElementById(list[0]); + if (target instanceof Element && first && target.contains(first)) lastTarget = target; + } + if (!frame) frame = requestAnimationFrame(measure); + }; + schedule(); + document.addEventListener('scroll', schedule, { capture: true, passive: true }); + window.addEventListener('resize', schedule); + return () => { + if (frame) cancelAnimationFrame(frame); + document.removeEventListener('scroll', schedule, { capture: true }); + window.removeEventListener('resize', schedule); + }; + }, [key]); + + // With no headings to watch nothing is current, whatever was measured last. + return key ? active : null; +} diff --git a/ui/apps/console/src/pages/useAppDocsBackTo.ts b/ui/apps/console/src/pages/useAppDocsBackTo.ts new file mode 100644 index 00000000000..5debd0761af --- /dev/null +++ b/ui/apps/console/src/pages/useAppDocsBackTo.ts @@ -0,0 +1,36 @@ +/** + * 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 { useMemo } from 'react'; +import { useParams } from 'react-router-dom'; +import { matchAppBySegment, useMetadata, useServedAppLabel } from '@object-ui/app-shell'; + +/** Where a docs page inside an app returns to, and the app's name for it. */ +export interface AppDocsBackTo { + to: string; + label: string; +} + +/** + * The app a docs page under `/apps/:appName/docs` returns to: the one the + * route's segment addresses, by the label the app bar shows. `undefined` + * outside an app (the portal). + */ +export function useAppDocsBackTo(): AppDocsBackTo | undefined { + const { appName } = useParams<{ appName?: string }>(); + const { apps } = useMetadata(); + const { appLabel } = useServedAppLabel(); + return useMemo(() => { + if (!appName) return undefined; + const app = matchAppBySegment( + apps as Array<{ name: string; _packageId?: string; label?: unknown } & Record<string, unknown>> | undefined, + appName, + ); + return { to: `/apps/${appName}`, label: app ? appLabel(app) : appName }; + }, [apps, appName, appLabel]); +} diff --git a/ui/packages/app-shell/src/index.ts b/ui/packages/app-shell/src/index.ts index d6816da4372..8e70689398c 100644 --- a/ui/packages/app-shell/src/index.ts +++ b/ui/packages/app-shell/src/index.ts @@ -94,6 +94,11 @@ export { // (objectui#4109 / PR #4279), which is the "two readers of one prose contract" // shape #3367 / #3842 record. `./utils/appRoute` is the contract. export { resolveHostAppSegment, appRouteSegment, filterActiveApps } from './utils/index.js'; +// objectstack#35424 — the docs reader names the app it returns to (「← Back to +// APP」) the way the app bar does: the app its route segment addresses, by its +// served label. +export { matchAppBySegment } from './utils/index.js'; +export { useServedAppLabel } from './hooks/useServedAppLabel.js'; // objectstack#32667 — which app OWNS a record of an object (the app a link to // the record, or to a page about it, opens under), as opposed to which app // hosts an app-independent page. `./utils/objectHostApp` is the contract. diff --git a/ui/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index 4f45e1dd8f0..1754d4c1016 100644 --- a/ui/packages/app-shell/src/layout/AppHeader.tsx +++ b/ui/packages/app-shell/src/layout/AppHeader.tsx @@ -782,6 +782,10 @@ export function AppHeader({ ?? reportLabel({ name: reportName, label: humanizeSlug(reportName) }), }); } + } else if (routeType === 'docs') { + // objectstack#35424 — 「APP / Documentation」: the docs page names its + // book and article itself, above the article. + extraSegments.push({ label: t('help.documentation', { defaultValue: 'Documentation' }) }); } else if (routeType === 'system') { extraSegments.push({ label: t('console.breadcrumb.system') }); if (pathParts[3]) { @@ -909,11 +913,12 @@ export function AppHeader({ <ChevronLeft className="h-5 w-5" aria-hidden /> </Link> ) - ) : isApp ? ( + ) : isApp && routeType !== 'docs' ? ( <LocalizedSidebarTrigger className="shrink-0 mr-1 max-md:size-11 max-md:mr-0" aria-label={t('common.toggleSidebar', { defaultValue: 'Toggle sidebar' })} /> ) : ( // objectui#12605 — the product mark sits at the same x on every - // surface. Off an app there is no sidebar to toggle, so the + // surface. Off an app, and on an app's docs pages (objectstack#35424, + // which draw no app menu), there is no sidebar to toggle, so the // trigger's slot (its 28 px box and its gap) is held empty: the // mark does not jump left when the viewer goes home. Below `sm` the // mark is not drawn inside an app, so there is nothing to hold. diff --git a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx index ceae7b13336..b21e2bf15fd 100644 --- a/ui/packages/app-shell/src/layout/ConsoleLayout.tsx +++ b/ui/packages/app-shell/src/layout/ConsoleLayout.tsx @@ -135,6 +135,15 @@ export function isRecordPagePath(pathname: string): boolean { return /^\/apps\/[^/]+\/[^/]+\/record\/[^/]+(?:\/page\/[^/]+)?\/?$/.test(pathname); } +/** + * Is `pathname` one of an app's documentation pages, `/apps/APP/docs` and + * everything under it (objectstack#35424)? A reader there has one navigation, + * the docs' own, so the app's menu is not drawn beside it. + */ +export function isAppDocsPath(pathname: string): boolean { + return /^\/apps\/[^/]+\/docs(?:\/|$)/.test(pathname); +} + /** Inner component that can access SidebarProvider context */ function ConsoleLayoutInner({ children }: { children: React.ReactNode }) { useResponsiveSidebar(); @@ -185,6 +194,9 @@ export function ConsoleLayout({ // the top left goes back. The route slot leaves the bar's height free at its // end. const phoneNavBar = phone && isPhoneTabRoute(location.pathname); + // objectstack#35424 — a docs page draws its own left column (the app's + // books and a way back to the app), so the app menu is not mounted there. + const docsPage = isAppDocsPath(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(); @@ -248,11 +260,13 @@ export function ConsoleLayout({ <PhoneAppHomeSlotProvider> <AppShell sidebar={ + docsPage ? undefined : ( <UnifiedSidebar activeAppName={activeAppName} onAppChange={onAppChange} railOverlay /> + ) } showHeader={!recordPageOwnsTopBar} navbar={ diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.systemBreadcrumbs-10969.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.systemBreadcrumbs-10969.test.tsx index 3cca6612ba7..7504add0a34 100644 --- a/ui/packages/app-shell/src/layout/__tests__/AppHeader.systemBreadcrumbs-10969.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.systemBreadcrumbs-10969.test.tsx @@ -199,3 +199,29 @@ describe('AppHeader — the console app\'s system/* breadcrumbs (objectui#10969) expect(screen.getAllByText('Some Host Page').length).toBeGreaterThan(0); }); }); + +describe('AppHeader — an app\'s docs pages read 「APP / Documentation」 (objectstack#35424)', () => { + it.each(['/apps/setup/docs', '/apps/setup/docs/manual', '/apps/setup/docs/manual/intro'])( + 'zh: %s reads 文档 after the app, in the session language', + (path) => { + renderAt(path, ZH); + expect(screen.getAllByText('文档').length).toBeGreaterThan(0); + expect(screen.queryAllByText('Documentation')).toHaveLength(0); + }, + ); + + it('en: a docs article reads Documentation', () => { + renderAt('/apps/setup/docs/manual/intro', EN); + expect(screen.getAllByText('Documentation').length).toBeGreaterThan(0); + }); + + it('a docs page draws no sidebar toggle (there is no app menu): its slot is held empty', () => { + renderAt('/apps/setup/docs/manual/intro', EN); + expect(screen.getByTestId('app-bar-trigger-slot')).toBeInTheDocument(); + }); + + it('control: a system page keeps the toggle, not the empty slot', () => { + renderAt('/apps/setup/system/settings', EN); + expect(screen.queryByTestId('app-bar-trigger-slot')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.phoneRecordOneBar-28483.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.phoneRecordOneBar-28483.test.tsx index 9f52191cb45..d80dd8201f9 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.phoneRecordOneBar-28483.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.phoneRecordOneBar-28483.test.tsx @@ -53,7 +53,7 @@ vi.mock('../ConsoleNotificationBanners', () => ({ ConsoleNotificationBanners: () vi.mock('../../preview/DraftPreviewBar', () => ({ DraftPreviewBar: () => null })); vi.mock('../../preview/UnpublishedAppBar', () => ({ UnpublishedAppBar: () => null })); -import { ConsoleLayout, isRecordPagePath } from '../ConsoleLayout'; +import { ConsoleLayout, isAppDocsPath, isRecordPagePath } from '../ConsoleLayout'; import { NavigationProvider } from '../../context/NavigationContext'; const APP = { name: 'crm', label: 'CRM', active: true, navigation: [] }; @@ -224,3 +224,33 @@ describe('the phone bottom bar is drawn on its three pages only (objectstack#358 } }); }); + +describe('an app\'s docs pages draw no app menu (objectstack#35424)', () => { + const appMenu = () => screen.queryByTestId('sidebar-stub'); + + it('at 1440 px a docs index, a book and an article draw no app menu, and keep the app bar', () => { + for (const path of ['/apps/crm/docs', '/apps/crm/docs/crm_manual', '/apps/crm/docs/crm_manual/crm_quotes']) { + mountAt(path, 1440); + expect(appMenu(), path).toBeNull(); + expect(screen.getByTestId('app-bar'), path).toBeInTheDocument(); + cleanup(); + } + }); + + it('control: every other app route keeps the app menu', () => { + for (const path of ['/apps/crm', '/apps/crm/crm_lead', '/apps/crm/dashboard/sales', '/apps/crm/docsearch']) { + mountAt(path, 1440); + expect(appMenu(), path).not.toBeNull(); + cleanup(); + } + }); + + it('isAppDocsPath names the docs tree under an app and nothing else', () => { + for (const path of ['/apps/crm/docs', '/apps/crm/docs/', '/apps/crm/docs/manual/intro']) { + expect(isAppDocsPath(path), path).toBe(true); + } + for (const path of ['/docs', '/docs/manual/intro', '/apps/crm', '/apps/crm/docsearch', '/apps/crm/crm_lead/docs']) { + expect(isAppDocsPath(path), path).toBe(false); + } + }); +}); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 70af4a16288..6447513ded7 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3594,6 +3594,18 @@ const ar = { docConflictCandidates: 'الحزم التي توفّر هذا المستند', documentation: 'الوثائق', uncategorized: 'غير مصنف', + backToApp: 'العودة إلى {{app}}', + searchDocs: 'البحث في المستندات', + noDocsMatch: 'لا توجد مقالات مطابقة.', + docsNavigation: 'التنقل في المستندات', + docsBreadcrumb: 'مسار المستندات', + articlePager: 'المقالة السابقة والتالية', + previousArticle: 'السابق', + nextArticle: 'التالي', + firstInBook: 'هذه أول مقالة في هذا الدليل', + lastInBook: 'هذه آخر مقالة في هذا الدليل', + enlargeDiagram: 'تكبير', + diagram: 'مخطط', about: 'حول', aboutTitle: 'حول وحدة التحكم هذه', aboutDescription: 'الإصدار الذي بُنيت منه وحدة التحكم هذه.', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7e99247e5ca..58d8c5c19c9 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3295,6 +3295,18 @@ const de = { docConflictCandidates: 'Pakete, die dieses Dokument bereitstellen', documentation: 'Dokumentation', uncategorized: 'Nicht kategorisiert', + backToApp: 'Zurück zu {{app}}', + searchDocs: 'Dokumentation durchsuchen', + noDocsMatch: 'Keine passenden Artikel.', + docsNavigation: 'Dokumentationsnavigation', + docsBreadcrumb: 'Dokumentationspfad', + articlePager: 'Vorheriger und nächster Artikel', + previousArticle: 'Zurück', + nextArticle: 'Weiter', + firstInBook: 'Dies ist der erste Artikel dieses Handbuchs', + lastInBook: 'Dies ist der letzte Artikel dieses Handbuchs', + enlargeDiagram: 'Vergrößern', + diagram: 'Diagramm', about: 'Über', aboutTitle: 'Über diese Konsole', aboutDescription: 'Der Build, aus dem diese Konsole kompiliert wurde.', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 13266e90f2a..2a362d076dd 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3964,6 +3964,18 @@ const en = { docConflictCandidates: 'Packages that provide this document', documentation: 'Documentation', uncategorized: 'Uncategorized', + backToApp: 'Back to {{app}}', + searchDocs: 'Search docs', + noDocsMatch: 'No articles match.', + docsNavigation: 'Documentation navigation', + docsBreadcrumb: 'Documentation path', + articlePager: 'Previous and next article', + previousArticle: 'Previous', + nextArticle: 'Next', + firstInBook: 'This is the first article in this book', + lastInBook: 'This is the last article in this book', + enlargeDiagram: 'Enlarge', + diagram: 'Diagram', about: 'About', aboutTitle: 'About this console', aboutDescription: 'The build this console was compiled from.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f06b1b1529d..570855dda14 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3371,6 +3371,18 @@ const es = { docConflictCandidates: 'Paquetes que proporcionan este documento', documentation: 'Documentación', uncategorized: 'Sin categoría', + backToApp: 'Volver a {{app}}', + searchDocs: 'Buscar en la documentación', + noDocsMatch: 'Ningún artículo coincide.', + docsNavigation: 'Navegación de la documentación', + docsBreadcrumb: 'Ruta de la documentación', + articlePager: 'Artículo anterior y siguiente', + previousArticle: 'Anterior', + nextArticle: 'Siguiente', + firstInBook: 'Este es el primer artículo de este manual', + lastInBook: 'Este es el último artículo de este manual', + enlargeDiagram: 'Ampliar', + diagram: 'Diagrama', about: 'Acerca de', aboutTitle: 'Acerca de esta consola', aboutDescription: 'La compilación a partir de la cual se generó esta consola.', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 749a7bfda0e..41a437ae450 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3367,6 +3367,18 @@ const fr = { docConflictCandidates: 'Packages qui fournissent ce document', documentation: 'Documentation', uncategorized: 'Non classé', + backToApp: 'Retour à {{app}}', + searchDocs: 'Rechercher dans la documentation', + noDocsMatch: 'Aucun article ne correspond.', + docsNavigation: 'Navigation de la documentation', + docsBreadcrumb: 'Chemin de la documentation', + articlePager: 'Article précédent et suivant', + previousArticle: 'Précédent', + nextArticle: 'Suivant', + firstInBook: 'C’est le premier article de ce manuel', + lastInBook: 'C’est le dernier article de ce manuel', + enlargeDiagram: 'Agrandir', + diagram: 'Diagramme', about: 'À propos', aboutTitle: 'À propos de cette console', aboutDescription: 'Le build à partir duquel cette console a été compilée.', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 9ff01af1738..5531e265c9c 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3297,6 +3297,18 @@ const ja = { docConflictCandidates: 'このドキュメントを提供するパッケージ', documentation: 'ドキュメント', uncategorized: '未分類', + backToApp: '{{app}}に戻る', + searchDocs: 'ドキュメントを検索', + noDocsMatch: '一致する記事はありません。', + docsNavigation: 'ドキュメントのナビゲーション', + docsBreadcrumb: 'ドキュメントの階層', + articlePager: '前後の記事', + previousArticle: '前の記事', + nextArticle: '次の記事', + firstInBook: 'このブックの最初の記事です', + lastInBook: 'このブックの最後の記事です', + enlargeDiagram: '拡大', + diagram: '図', about: 'バージョン情報', aboutTitle: 'このコンソールについて', aboutDescription: 'このコンソールのコンパイル元となったビルドです。', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 7136511d607..c637a5c4662 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3295,6 +3295,18 @@ const ko = { docConflictCandidates: '이 문서를 제공하는 패키지', documentation: '문서', uncategorized: '미분류', + backToApp: '{{app}}(으)로 돌아가기', + searchDocs: '문서 검색', + noDocsMatch: '일치하는 문서가 없습니다.', + docsNavigation: '문서 탐색', + docsBreadcrumb: '문서 경로', + articlePager: '이전 및 다음 문서', + previousArticle: '이전 문서', + nextArticle: '다음 문서', + firstInBook: '이 책의 첫 번째 문서입니다', + lastInBook: '이 책의 마지막 문서입니다', + enlargeDiagram: '확대', + diagram: '다이어그램', about: '정보', aboutTitle: '이 콘솔 정보', aboutDescription: '이 콘솔이 컴파일된 빌드입니다.', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0d1c9c34747..62c4bd24246 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3366,6 +3366,18 @@ const pt = { docConflictCandidates: 'Pacotes que fornecem este documento', documentation: 'Documentação', uncategorized: 'Sem categoria', + backToApp: 'Voltar para {{app}}', + searchDocs: 'Pesquisar na documentação', + noDocsMatch: 'Nenhum artigo corresponde.', + docsNavigation: 'Navegação da documentação', + docsBreadcrumb: 'Caminho da documentação', + articlePager: 'Artigo anterior e próximo', + previousArticle: 'Anterior', + nextArticle: 'Próximo', + firstInBook: 'Este é o primeiro artigo deste manual', + lastInBook: 'Este é o último artigo deste manual', + enlargeDiagram: 'Ampliar', + diagram: 'Diagrama', about: 'Sobre', aboutTitle: 'Sobre este console', aboutDescription: 'A build a partir da qual este console foi compilado.', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ef52983f948..788254bc4af 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3452,6 +3452,18 @@ const ru = { docConflictCandidates: 'Пакеты, в которых есть этот документ', documentation: 'Документация', uncategorized: 'Без категории', + backToApp: 'Назад в {{app}}', + searchDocs: 'Поиск по документации', + noDocsMatch: 'Нет подходящих статей.', + docsNavigation: 'Навигация по документации', + docsBreadcrumb: 'Путь в документации', + articlePager: 'Предыдущая и следующая статья', + previousArticle: 'Назад', + nextArticle: 'Далее', + firstInBook: 'Это первая статья руководства', + lastInBook: 'Это последняя статья руководства', + enlargeDiagram: 'Увеличить', + diagram: 'Схема', about: 'О программе', aboutTitle: 'Об этой консоли', aboutDescription: 'Сборка, из которой скомпилирована эта консоль.', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 7288c069e0d..43fcee66daa 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3376,6 +3376,18 @@ const zh = { docConflictCandidates: '提供此文档的包', documentation: '文档', uncategorized: '未分类', + backToApp: '返回{{app}}', + searchDocs: '搜索文档', + noDocsMatch: '没有匹配的篇目。', + docsNavigation: '文档导航', + docsBreadcrumb: '文档路径', + articlePager: '上一篇和下一篇', + previousArticle: '上一篇', + nextArticle: '下一篇', + firstInBook: '这是本手册第一篇', + lastInBook: '这是本手册最后一篇', + enlargeDiagram: '放大', + diagram: '图示', about: '关于', aboutTitle: '关于此控制台', aboutDescription: '此控制台编译所用的构建。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 33893d18585..6aba8b49100 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3376,6 +3376,18 @@ const zhHant = { docConflictCandidates: '提供此文件的包', documentation: '文件', uncategorized: '未分類', + backToApp: '返回{{app}}', + searchDocs: '搜尋文件', + noDocsMatch: '沒有匹配的篇目。', + docsNavigation: '文件導航', + docsBreadcrumb: '文件路徑', + articlePager: '上一篇和下一篇', + previousArticle: '上一篇', + nextArticle: '下一篇', + firstInBook: '這是本手冊第一篇', + lastInBook: '這是本手冊最後一篇', + enlargeDiagram: '放大', + diagram: '圖示', about: '關於', aboutTitle: '關於此控制台', aboutDescription: '此控制台編譯所用的構建。', diff --git a/ui/packages/plugin-markdown/src/Mermaid.enlarge-35424.test.tsx b/ui/packages/plugin-markdown/src/Mermaid.enlarge-35424.test.tsx new file mode 100644 index 00000000000..a57c9f64e07 --- /dev/null +++ b/ui/packages/plugin-markdown/src/Mermaid.enlarge-35424.test.tsx @@ -0,0 +1,63 @@ +/** + * 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 — a diagram opens full size where the host asks for it + * (`MermaidEnlargeContext`, provided by the docs reader), and draws no control + * anywhere else. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import * as React from 'react'; + +vi.mock('mermaid', () => ({ + default: { + initialize: () => undefined, + // Like mermaid: the render id prefixes the root id, the markers and the + // references to them. (jsdom drops an svg <style>'s text, so none here.) + render: async (id: string) => ({ + svg: `<svg id="${id}" data-testid="diagram-svg"><defs><marker id="${id}_arrow"></marker></defs><path marker-end="url(#${id}_arrow)"></path></svg>`, + }), + }, +})); + +import { Mermaid } from './Mermaid'; +import { MermaidEnlargeContext } from './MermaidEnlargeContext'; + +afterEach(cleanup); + +const TEXT = { enlarge: 'Enlarge', title: 'Diagram' }; + +describe('Mermaid — the enlarge control (objectstack#35424)', () => { + it('with the host\'s words, the drawn diagram carries an enlarge button that opens it full size', async () => { + render( + <MermaidEnlargeContext.Provider value={TEXT}> + <Mermaid chart="graph TD; A-->B;" /> + </MermaidEnlargeContext.Provider>, + ); + const button = await screen.findByRole('button', { name: 'Enlarge' }); + expect(screen.getAllByTestId('diagram-svg')).toHaveLength(1); + fireEvent.click(button); + const dialog = await screen.findByRole('dialog', { name: 'Diagram' }); + const enlarged = dialog.querySelector('[data-mermaid-enlarged] svg'); + expect(enlarged).not.toBeNull(); + // The dialog's copy has ids of its own: no id appears twice while it is open. + expect(enlarged?.id).toMatch(/^os-mermaid-\d+-enlarged$/); + expect(enlarged?.querySelector('marker')?.id).toBe(`${enlarged?.id}_arrow`); + expect(enlarged?.querySelector('path')?.getAttribute('marker-end')).toBe(`url(#${enlarged?.id}_arrow)`); + const ids = [...document.querySelectorAll('[id]')].map((el) => el.id).filter((v) => v.startsWith('os-mermaid-')); + expect(new Set(ids).size).toBe(ids.length); + }); + + it('without a provider the diagram draws no control, as before', async () => { + render(<Mermaid chart="graph TD; A-->B;" />); + await screen.findByTestId('diagram-svg'); + expect(screen.queryByRole('button')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-markdown/src/Mermaid.tsx b/ui/packages/plugin-markdown/src/Mermaid.tsx index f7f36c917af..4e69cdfab41 100644 --- a/ui/packages/plugin-markdown/src/Mermaid.tsx +++ b/ui/packages/plugin-markdown/src/Mermaid.tsx @@ -7,6 +7,8 @@ */ import * as React from "react" +import { Dialog, DialogContent, DialogTitle } from "@object-ui/components" +import { MermaidEnlargeContext } from "./MermaidEnlargeContext" /** * Mermaid diagram renderer for ```mermaid fenced code blocks (ADR-0046). @@ -98,7 +100,7 @@ export function Mermaid({ chart }: { chart: string }) { ) } - return ( + const diagram = ( <div data-mermaid role="img" @@ -107,4 +109,49 @@ export function Mermaid({ chart }: { chart: string }) { dangerouslySetInnerHTML={{ __html: svg }} /> ) + return <EnlargeableDiagram svg={svg}>{diagram}</EnlargeableDiagram> +} + +/** + * The dialog's copy of a rendered diagram, under its own ids. Mermaid prefixes + * the svg's root id, its scoped style selectors and its marker ids with the + * render id, so renaming that one prefix keeps the inline copy and the + * enlarged copy from sharing ids while the dialog is open. + */ +function enlargedSvg(svg: string): string { + const match = /\bid="(os-mermaid-\d+)"/.exec(svg) + return match ? svg.split(match[1]).join(`${match[1]}-enlarged`) : svg +} + +/** The diagram, plus an enlarge control and dialog when the host asks for one. */ +function EnlargeableDiagram({ svg, children }: { svg: string; children: React.ReactElement }) { + const text = React.useContext(MermaidEnlargeContext) + const [open, setOpen] = React.useState(false) + const dialogSvg = React.useMemo(() => enlargedSvg(svg), [svg]) + if (!text) return children + return ( + <div className="relative"> + {children} + <button + type="button" + data-mermaid-enlarge + onClick={() => setOpen(true)} + className="absolute right-2 top-2 rounded-md border bg-background/90 px-2.5 py-1 text-xs font-medium text-foreground shadow-sm hover:bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-ring" + > + {text.enlarge} + </button> + <Dialog open={open} onOpenChange={setOpen}> + <DialogContent className="max-w-[95vw] w-[95vw] max-h-[90vh] overflow-auto sm:max-w-[95vw]"> + <DialogTitle className="sr-only">{text.title}</DialogTitle> + <div + data-mermaid-enlarged + role="img" + className="flex justify-center [&_svg]:h-auto [&_svg]:w-full [&_svg]:max-w-none" + // the same trusted strict-mode SVG as the inline diagram, under its own ids + dangerouslySetInnerHTML={{ __html: dialogSvg }} + /> + </DialogContent> + </Dialog> + </div> + ) } diff --git a/ui/packages/plugin-markdown/src/MermaidEnlargeContext.ts b/ui/packages/plugin-markdown/src/MermaidEnlargeContext.ts new file mode 100644 index 00000000000..f33b97e4cbc --- /dev/null +++ b/ui/packages/plugin-markdown/src/MermaidEnlargeContext.ts @@ -0,0 +1,23 @@ +/** + * 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 * as React from "react" + +/** + * The words of a diagram's enlarge control, in the host's language. A host + * that wants every rendered diagram to open full size (the docs reader) + * provides them; with no provider a diagram draws no control, as before. + */ +export interface MermaidEnlargeText { + /** The control's text, e.g. "Enlarge". */ + enlarge: string + /** The enlarged view's accessible title, e.g. "Diagram". */ + title: string +} + +export const MermaidEnlargeContext = React.createContext<MermaidEnlargeText | null>(null) diff --git a/ui/packages/plugin-markdown/src/index.tsx b/ui/packages/plugin-markdown/src/index.tsx index 4ed33dc0f7f..0f3ba572d2f 100644 --- a/ui/packages/plugin-markdown/src/index.tsx +++ b/ui/packages/plugin-markdown/src/index.tsx @@ -14,6 +14,7 @@ import { Skeleton } from '@object-ui/components'; export type { MarkdownSchema } from './types'; export { extractToc, type TocItem } from './toc'; export { Mermaid } from './Mermaid'; +export { MermaidEnlargeContext, type MermaidEnlargeText } from './MermaidEnlargeContext'; // 🚀 Lazy load the implementation file // This ensures react-markdown is only loaded when the component is actually rendered