diff --git a/DESIGN.md b/DESIGN.md index 1cb2aab6e5..279606e453 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -300,6 +300,11 @@ Content sits on the Cool Shell in a grid of panels: Feed White, 8px, hairline-bo - **Status:** the console is the one place with status colors, `success` (lane-1's green) and `warning` (lane-5's ochre) beside Rm Red. They only ever mark state (healthy, watch, failing; event levels; better or worse than the period before) and always come with an icon, a sign or a word. They are not lanes and never mark a person. - **Charts:** drawn in SVG at their real size, one y-axis, hairline gridlines, mono 11px ticks. History is a 2px ink line; a forecast continues it as a dashed Muted Ink line over a 15% Muted Ink wash for its range, after a dashed Rail Gray "today" rule. Columns are at most 24px wide with a 2px surface gap between stacked segments. Hovering shows the inverted tooltip; every chart carries a screen-reader table. +### API Docs +The API docs use the Operations Console's shell (`ConsoleLayout`), for everyone, guests included: the wordmark with a bordered mono `api` chip, a sidebar grouping the guides under `guide`, the theme switch and "Back to /dev/null" (without an avatar for a guest). The header names the section and says in one line what it holds; on the right a mono `v1`. + +- **Guides:** read like the site's other long pages, never a card per section: one Feed White sheet on the Cool Shell, 1160px wide, 8px and hairline-bordered, whose sections follow one another with a hairline between them, each under a Section heading that links to itself. Prose at 15px, named values in a hairline list with mono keys like the settings, and code in the same code blocks as commits, highlighted on the server, its language above it. + ### Error Pages 403, 404, 429, 500 (outside debug), and 503 render one standalone `error` page, with no app shell, for guests and signed-in users alike. A broken rail: the wordmark sits on a node in the viewer's lane (Rail Gray for guests) whose segment fades out before reaching a hollow, dangling node. Beside it, a mono git-style line (`fatal: path '/x' does not exist in 'HEAD'`), a Headline sentence saying what happened, one muted sentence saying what to do, and a single primary button ("Back to your log", "Go to the home page", or "Try again" during maintenance). A 419 is not a page: it redirects back with an error toast. diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 1756750c87..411c8dab2b 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -579,7 +579,9 @@ The read-only JSON API at `/api/v1` requires no authentication or token, except Subscribe in a feed reader to `/@{handle}/feed.atom` for a profile's latest **50 approved top-level commits**, including image enclosures. Feeds are public and can be cached for five minutes. -Sources: [API routes](routes/api.php), [API controllers](app/Http/Controllers/Api), [feed generation](app/Actions/CreateUserFeed.php), [rate limits](app/Providers/AppServiceProvider.php). +The **API docs** at `/docs/api`, linked as **API** from the aside and the user menu, are readable by everyone. Their Introduction says what the API is for, its base URL and format, with a first request anyone can send. + +Sources: [API routes](routes/api.php), [API controllers](app/Http/Controllers/Api), [feed generation](app/Actions/CreateUserFeed.php), [rate limits](app/Providers/AppServiceProvider.php), [docs page](app/Http/Controllers/ApiDocsController.php), [guides](resources/js/pages/api-docs/guides). ### Signed API and devices diff --git a/app/Enums/ApiDocsSection.php b/app/Enums/ApiDocsSection.php new file mode 100644 index 0000000000..a9d45b5655 --- /dev/null +++ b/app/Enums/ApiDocsSection.php @@ -0,0 +1,37 @@ +name; + } + + public function description(): string + { + return match ($this) { + self::Introduction => 'What the API is for, and where it lives', + }; + } + + /** + * @return array{slug: string, title: string, description: string} + */ + public function toArray(): array + { + return [ + 'slug' => $this->value, + 'title' => $this->title(), + 'description' => $this->description(), + ]; + } +} diff --git a/app/Http/Controllers/ApiDocsController.php b/app/Http/Controllers/ApiDocsController.php new file mode 100644 index 0000000000..58a5f8a841 --- /dev/null +++ b/app/Http/Controllers/ApiDocsController.php @@ -0,0 +1,30 @@ + array_map(fn (ApiDocsSection $section): array => $section->toArray(), ApiDocsSection::cases()), + 'current' => $section->value, + 'snippets' => $snippets->for($section), + ])->withViewData(['preview' => $metadata->page( + $section->title().' - API docs - /dev/null', + $section->description().'. The JSON API the /dev/null apps use, open to anything you build.', + route('api-docs.show', $section), + )]); + } +} diff --git a/app/Services/ApiGuideSnippets.php b/app/Services/ApiGuideSnippets.php new file mode 100644 index 0000000000..b59ec1d1a1 --- /dev/null +++ b/app/Services/ApiGuideSnippets.php @@ -0,0 +1,39 @@ + + */ + public function for(ApiDocsSection $section): array + { + $snippets = match ($section) { + ApiDocsSection::Introduction => [ + 'firstRequest' => ['bash', 'curl '.self::BaseUrl."/users/nunomaduro \\\n -H 'Accept: application/json'"], + ], + }; + + return array_map(fn (array $snippet): array => [ + 'language' => $snippet[0], + 'html' => $this->highlighter->parse($snippet[1], $snippet[0]), + ], $snippets); + } +} diff --git a/resources/js/components/api-docs/guide.tsx b/resources/js/components/api-docs/guide.tsx new file mode 100644 index 0000000000..39983231bd --- /dev/null +++ b/resources/js/components/api-docs/guide.tsx @@ -0,0 +1,119 @@ +import type { ReactNode } from 'react'; +import { CodeBlock } from '@/components/code-block'; +import { cn } from '@/lib/utils'; +import type { ApiDocsSnippet } from '@/types'; + +/** + * How wide the docs' content is, so moving between their pages never changes the page's width. + */ +export const DOCS_WIDTH = 'max-w-[1160px]'; + +/** + * A guide of the API docs, read like the site's other long pages: one Feed White sheet on the console's shell, its + * sections one after the other with a hairline between them, never a card each. + */ +export function Guide({ children }: { children: ReactNode }) { + return ( +
+ {children} +
+ ); +} + +function anchor(title: string): string { + return title + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, ''); +} + +/** + * A section of a guide, its title a link to itself, so a reader can point someone at it. + */ +export function GuideSection({ + title, + children, +}: { + title: string; + children: ReactNode; +}) { + const id = anchor(title); + + return ( +
+
+

+ + {title} + +

+
+ {children} +
+ ); +} + +/** + * A guide's code, in the code block the rest of the site uses, highlighted by the server. + */ +export function Snippet({ snippet }: { snippet: ApiDocsSnippet | undefined }) { + if (snippet === undefined) { + return null; + } + + return ( + + ); +} + +export function Code({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +/** + * Named values in a hairline list, keys in mono, as the settings list what they show. + */ +export function FieldList({ + fields, +}: { + fields: { name: string; children: ReactNode }[]; +}) { + return ( +
+ {fields.map((field) => ( +
+
+ {field.name} +
+
{field.children}
+
+ ))} +
+ ); +} diff --git a/resources/js/components/app-aside.tsx b/resources/js/components/app-aside.tsx index ac5f1184d5..48ffac7e0a 100644 --- a/resources/js/components/app-aside.tsx +++ b/resources/js/components/app-aside.tsx @@ -1,6 +1,7 @@ import { Link, usePage } from '@inertiajs/react'; import { Search } from 'lucide-react'; import AboutController from '@/actions/App/Http/Controllers/AboutController'; +import ApiDocsController from '@/actions/App/Http/Controllers/ApiDocsController'; import AppController from '@/actions/App/Http/Controllers/AppController'; import ChangelogController from '@/actions/App/Http/Controllers/ChangelogController'; import PartnerController from '@/actions/App/Http/Controllers/PartnerController'; @@ -114,6 +115,13 @@ export function AppAside({ > Apps + + API + + + + + API + + ({ + key: section.slug, + title: section.title, + description: section.description, + href: ApiDocsController.show(section.slug), + icon: BookOpen, + })); +} + +/** + * The API docs as a console beside the log, its guides in the sidebar. + */ +export default function ApiDocsLayout({ children }: PropsWithChildren) { + const { props } = usePage(); + + const groups: ConsoleNavGroup[] = [ + { + label: 'Guide', + items: navItems(props.sections), + }, + ]; + + return ( + + v1 + + } + > + {children} + + ); +} diff --git a/resources/js/layouts/console/layout.tsx b/resources/js/layouts/console/layout.tsx new file mode 100644 index 0000000000..1e829b9ca0 --- /dev/null +++ b/resources/js/layouts/console/layout.tsx @@ -0,0 +1,284 @@ +import { Link } from '@inertiajs/react'; +import type { InertiaLinkProps } from '@inertiajs/react'; +import type { LucideIcon } from 'lucide-react'; +import { ArrowUpRight } from 'lucide-react'; +import { useEffect, useRef } from 'react'; +import type { ReactNode } from 'react'; +import AppLogoIcon from '@/components/app-logo-icon'; +import AppWordmark from '@/components/app-wordmark'; +import AppearanceToggleTab from '@/components/appearance-tabs'; +import { UserAvatar } from '@/components/user-avatar'; +import { cn } from '@/lib/utils'; +import type { User } from '@/types'; + +export type ConsoleNavItem = { + key: string; + title: string; + description: string; + href: NonNullable; + icon: LucideIcon; + external?: boolean; +}; + +export type ConsoleNavGroup = { + label: string; + items: ConsoleNavItem[]; +}; + +const itemClassName = + 'flex h-9 shrink-0 items-center gap-2.5 rounded-lg px-2.5 text-sm font-medium whitespace-nowrap text-muted-foreground transition-colors hover:bg-accent hover:text-foreground'; + +function NavItem({ + item, + isActive, + prefetch, +}: { + item: ConsoleNavItem; + isActive: boolean; + prefetch: boolean; +}) { + if (item.external) { + return ( + + + {item.title} + + + ); + } + + return ( + + + {item.title} + + ); +} + +function Brand({ + chip, + label, + href, + prefetch, +}: { + chip: string; + label: string; + href: NonNullable; + prefetch: boolean; +}) { + return ( + + + + + {chip} + + + ); +} + +/** + * The shell of a standalone console beside the log, such as Operations: a sidebar of grouped pages, a header naming + * the current one, and a way back to /dev/null. Its pages prefetch on hover only when the console asks for it. + */ +export default function ConsoleLayout({ + chip, + label, + navLabel, + brandHref, + prefetch = false, + groups, + current, + backHref, + user, + headerActions, + children, +}: { + chip: string; + label: string; + navLabel: string; + brandHref: NonNullable; + prefetch?: boolean; + groups: ConsoleNavGroup[]; + current: string; + backHref: string; + user: User | null; + headerActions?: ReactNode; + children: ReactNode; +}) { + const items = groups.flatMap((group) => group.items); + const page = items.find((item) => item.key === current && !item.external); + const mobileNav = useRef(null); + + useEffect(() => { + mobileNav.current + ?.querySelector('[aria-current="page"]') + ?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + }, [current]); + + return ( +
+ + +
+
+
+
+ +
+
+

+ {page?.title ?? navLabel} +

+

+ {page?.description} +

+
+ +
+ {headerActions} + + {user ? ( + + ) : ( + + )} + +
+
+ + +
+ +
+
+

+ {page?.title ?? navLabel} +

+

+ {page?.description} +

+
+ {children} +
+
+
+ ); +} diff --git a/resources/js/layouts/operations/layout.tsx b/resources/js/layouts/operations/layout.tsx index e8c7c913e3..22548ec0ec 100644 --- a/resources/js/layouts/operations/layout.tsx +++ b/resources/js/layouts/operations/layout.tsx @@ -1,9 +1,6 @@ -import { Link, router, usePage, usePoll } from '@inertiajs/react'; -import type { InertiaLinkProps } from '@inertiajs/react'; -import type { LucideIcon } from 'lucide-react'; +import { router, usePage, usePoll } from '@inertiajs/react'; import { Activity, - ArrowUpRight, ChartNoAxesCombined, Flag, Gauge, @@ -18,7 +15,7 @@ import { ShieldCheck, TrendingUp, } from 'lucide-react'; -import { useEffect, useRef, useState } from 'react'; +import { useState } from 'react'; import type { PropsWithChildren } from 'react'; import EmailController from '@/actions/App/Http/Controllers/EmailController'; import FeatureController from '@/actions/App/Http/Controllers/FeatureController'; @@ -31,13 +28,11 @@ import ProductMetricsController from '@/actions/App/Http/Controllers/ProductMetr import SiteActivityController from '@/actions/App/Http/Controllers/SiteActivityController'; import SystemHealthController from '@/actions/App/Http/Controllers/SystemHealthController'; import TrafficController from '@/actions/App/Http/Controllers/TrafficController'; -import AppLogoIcon from '@/components/app-logo-icon'; -import AppWordmark from '@/components/app-wordmark'; -import AppearanceToggleTab from '@/components/appearance-tabs'; import { ChatDock } from '@/components/chat/chat-dock'; import { Button } from '@/components/ui/button'; -import { UserAvatar } from '@/components/user-avatar'; import { useRemoteAlerts, useRemoteUpdates } from '@/hooks/use-chat'; +import ConsoleLayout from '@/layouts/console/layout'; +import type { ConsoleNavGroup } from '@/layouts/console/layout'; import { backgroundPollOptions } from '@/lib/background-poll'; import { cn } from '@/lib/utils'; import { home } from '@/routes'; @@ -104,35 +99,27 @@ const POLL_PROPS = Object.fromEntries( ]), ) as Record; -type NavEntry = { - page: OperationsPage; - title: string; - description: string; - href: NonNullable; - icon: LucideIcon; -}; - -function navGroups(): { label: string; items: NavEntry[] }[] { +function navGroups(): ConsoleNavGroup[] { return [ { label: 'Monitor', items: [ { - page: 'operations/show', + key: 'operations/show', title: 'Overview', description: 'What needs attention, and what is fine', href: OperationsController.show(), icon: LayoutDashboard, }, { - page: 'operations/health', + key: 'operations/health', title: 'Health', description: 'Services, queues, failed jobs and backlogs', href: SystemHealthController.show(), icon: HeartPulse, }, { - page: 'operations/events', + key: 'operations/events', title: 'Events', description: 'Everything that happened, newest first', href: OperationsEventController.index(), @@ -144,28 +131,28 @@ function navGroups(): { label: string; items: NavEntry[] }[] { label: 'Product', items: [ { - page: 'operations/forecasts', + key: 'operations/forecasts', title: 'Forecasts', description: 'Where the trends are heading next', href: ForecastController.show(), icon: TrendingUp, }, { - page: 'operations/metrics', + key: 'operations/metrics', title: 'Growth', description: 'Acquisition, activation and retention', href: ProductMetricsController.show(), icon: ChartNoAxesCombined, }, { - page: 'operations/activity', + key: 'operations/activity', title: 'Activity', description: 'Commits, replies and signups over time', href: SiteActivityController.show(), icon: Activity, }, { - page: 'operations/traffic', + key: 'operations/traffic', title: 'Traffic', description: 'Visitors and where they come from', href: TrafficController.show(), @@ -177,14 +164,14 @@ function navGroups(): { label: string; items: NavEntry[] }[] { label: 'Control', items: [ { - page: 'operations/features', + key: 'operations/features', title: 'Features', description: 'Choose who can use each feature', href: FeatureController.index(), icon: Flag, }, { - page: 'operations/emails', + key: 'operations/emails', title: 'Emails', description: 'Write to everyone, or the people you pick', href: EmailController.create(), @@ -192,6 +179,19 @@ function navGroups(): { label: string; items: NavEntry[] }[] { }, ], }, + { + label: 'Elsewhere', + items: [ + { + key: 'moderation', + title: 'Moderation', + description: 'Commits waiting for review', + href: ModerationController.show().url, + icon: ShieldCheck, + external: true, + }, + ], + }, ]; } @@ -201,41 +201,6 @@ function Poll({ only }: { only: string[] }) { return null; } -function NavItem({ item, isActive }: { item: NavEntry; isActive: boolean }) { - return ( - - - {item.title} - - ); -} - -function Brand() { - return ( - - - - - ops - - - ); -} - export default function OperationsLayout({ children }: PropsWithChildren) { const { component, props } = usePage(); const page = component as OperationsPage; @@ -243,26 +208,16 @@ export default function OperationsLayout({ children }: PropsWithChildren) { const [isLive, setIsLive] = useState(true); const only = PAGE_PROPS[page] ?? []; const polls = !ON_DEMAND.includes(page); - const groups = navGroups(); - const items = groups.flatMap((group) => group.items); - const current = items.find((item) => item.page === page); const user = props.auth.user; const hasRemotes = user !== null && props.auth.remotes !== null; const backHref = props.auth.log === null ? home().url : LogController.show(props.auth.log).url; - const mobileNav = useRef(null); useRemoteAlerts(hasRemotes ? user.id : null); useRemoteUpdates(hasRemotes ? user.id : null); - useEffect(() => { - mobileNav.current - ?.querySelector('[aria-current="page"]') - ?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); - }, [page]); - const refresh = () => { if (isRefreshing) { return; @@ -285,226 +240,84 @@ export default function OperationsLayout({ children }: PropsWithChildren) { }; return ( -
+ <> {polls && isLive && ( )} - - -
-
-
-
- -
-
-

- {current?.title ?? 'Operations'} -

-

- {current?.description} -

-
- -
- {polls ? ( - - ) : ( - - - on demand - - )} + + {polls ? ( - {user && ( - - - - )} -
-
- - -
- -
-
-

- {current?.title ?? 'Operations'} -

-

- {current?.description} -

-
- {children} -
-
+ + + + } + > + {children} + {hasRemotes && } -
+ ); } diff --git a/resources/js/pages/api-docs/guides/introduction.tsx b/resources/js/pages/api-docs/guides/introduction.tsx new file mode 100644 index 0000000000..a490ab7372 --- /dev/null +++ b/resources/js/pages/api-docs/guides/introduction.tsx @@ -0,0 +1,66 @@ +import { + Code, + FieldList, + Guide, + GuideSection, + Snippet, +} from '@/components/api-docs/guide'; +import type { ApiDocsSnippet } from '@/types'; + +const API_URL = 'https://dev-null.sh/api/v1'; + +export function Introduction({ + snippets, +}: { + snippets: Record; +}) { + return ( + + +

+ The JSON API the /dev/null apps use, open to anything you + build: a bot, a bridge, a widget on your own site. +

+

+ Reading public profiles and commits needs nothing. Acting + for someone needs their approval and a signature on every + request: there are no passwords and no API tokens. +

+ {API_URL} }, + { + name: 'format', + children: + 'JSON, or multipart when a request carries images or a voice note', + }, + { + name: 'accept', + children: ( + <> + Accept: application/json on + every request, so every error comes back as + JSON + + ), + }, + ]} + /> +
+ + +

A profile, as anyone can read it:

+ +
+ + +

+ A signed request sees what the web shows the person who + signed it, and goes through the same validation, moderation + and limits: a commit may come back pending, and a blocked + profile stays out of reach. +

+
+
+ ); +} diff --git a/resources/js/pages/api-docs/show.tsx b/resources/js/pages/api-docs/show.tsx new file mode 100644 index 0000000000..05981c44c6 --- /dev/null +++ b/resources/js/pages/api-docs/show.tsx @@ -0,0 +1,19 @@ +import { Head, usePage } from '@inertiajs/react'; +import ApiDocsLayout from '@/layouts/api-docs/layout'; +import { Introduction } from '@/pages/api-docs/guides/introduction'; +import type { ApiDocsProps } from '@/types'; + +export default function Show() { + const { sections, current, snippets } = usePage().props; + const section = sections.find((candidate) => candidate.slug === current); + + return ( + <> + + + {current === 'introduction' && } + + ); +} + +Show.layout = ApiDocsLayout; diff --git a/resources/js/types/api-docs.ts b/resources/js/types/api-docs.ts new file mode 100644 index 0000000000..9e1191b80c --- /dev/null +++ b/resources/js/types/api-docs.ts @@ -0,0 +1,16 @@ +export type ApiDocsSection = { + slug: string; + title: string; + description: string; +}; + +export type ApiDocsSnippet = { + language: string; + html: string; +}; + +export type ApiDocsProps = { + sections: ApiDocsSection[]; + current: string; + snippets: Record; +}; diff --git a/resources/js/types/index.ts b/resources/js/types/index.ts index f7facc21a5..e585011f25 100644 --- a/resources/js/types/index.ts +++ b/resources/js/types/index.ts @@ -1,4 +1,5 @@ export type * from './achievement'; +export type * from './api-docs'; export type * from './activity'; export type * from './auth'; export type * from './commit'; diff --git a/routes/web.php b/routes/web.php index c10b9580d9..618ff52962 100644 --- a/routes/web.php +++ b/routes/web.php @@ -2,9 +2,11 @@ declare(strict_types=1); +use App\Enums\ApiDocsSection; use App\Enums\Log; use App\Enums\ProfileType; use App\Http\Controllers\AboutController; +use App\Http\Controllers\ApiDocsController; use App\Http\Controllers\AppController; use App\Http\Controllers\BanController; use App\Http\Controllers\BannedController; @@ -251,6 +253,10 @@ // What was merged into production, readable by everyone... Route::get('changelog', [ChangelogController::class, 'index'])->name('changelog.index'); +// The API docs, readable by everyone... +Route::redirect('docs/api', '/docs/api/'.ApiDocsSection::Introduction->value)->name('api-docs.index'); +Route::get('docs/api/{section}', [ApiDocsController::class, 'show'])->name('api-docs.show'); + // Public pages, readable by guests and crawlers... Route::middleware([RememberIntendedUrl::class, RedirectToHandleCase::class])->group(function (): void { // A handle no user has may be an organization's, an unclaimed developer's, or one to look up on GitHub. Bindings diff --git a/tests/Feature/Controllers/ApiDocsControllerTest.php b/tests/Feature/Controllers/ApiDocsControllerTest.php new file mode 100644 index 0000000000..40c758b853 --- /dev/null +++ b/tests/Feature/Controllers/ApiDocsControllerTest.php @@ -0,0 +1,55 @@ +get('/docs/api')->assertRedirect(route('api-docs.show', ApiDocsSection::Introduction)); +}); + +it('renders every section of the API docs for guests', function (ApiDocsSection $section): void { + $this->get(route('api-docs.show', $section)) + ->assertOk() + ->assertInertia(fn ($page) => $page->component('api-docs/show') + ->where('current', $section->value)); +})->with(ApiDocsSection::cases()); + +it('renders the API docs for signed in users', function (): void { + $this->actingAs(User::factory()->create()) + ->get(route('api-docs.show', ApiDocsSection::Introduction)) + ->assertOk() + ->assertInertia(fn ($page) => $page->component('api-docs/show')); +}); + +it('lists the guides in reading order', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::Introduction)) + ->assertInertia(fn ($page) => $page + ->has('sections', 1) + ->where('sections.0', [ + 'slug' => 'introduction', + 'title' => 'Introduction', + 'description' => 'What the API is for, and where it lives', + ])); +}); + +it('gives a guide its code blocks', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::Introduction)) + ->assertInertia(fn ($page) => $page + ->has('snippets', 1) + ->has('snippets.firstRequest', fn ($snippet) => $snippet->where('language', 'bash')->has('html'))); +}); + +it('answers a section the docs do not have with the not found page', function (): void { + $this->get('/docs/api/webhooks') + ->assertNotFound() + ->assertHeader('Content-Type', 'text/html; charset=UTF-8'); +}); + +it('describes each section to search engines and link previews', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::Introduction)) + ->assertOk() + ->assertSee('Introduction - API docs - /dev/null', false) + ->assertSee('', false); +}); diff --git a/tests/Unit/ApiDocsGuides.test.tsx b/tests/Unit/ApiDocsGuides.test.tsx new file mode 100644 index 0000000000..919f305d0b --- /dev/null +++ b/tests/Unit/ApiDocsGuides.test.tsx @@ -0,0 +1,60 @@ +/// + +import assert from 'node:assert/strict'; +import { renderToString } from 'react-dom/server'; +import { test } from 'vite-plus/test'; +import { + DOCS_WIDTH, + Guide, + GuideSection, +} from '../../resources/js/components/api-docs/guide'; +import { Introduction } from '../../resources/js/pages/api-docs/guides/introduction'; + +test('lays a guide out as sections of one article, never as cards', () => { + const html = renderToString( + + +

body

+
+
, + ); + + assert.match(html, /^]*bg-card[^>]*>/); + assert.match( + html, + new RegExp(`^]*${DOCS_WIDTH.replace(/[[\]]/g, '\\$&')}`), + ); + assert.match(html, /^]*divide-y/); + assert.match(html, /
]*>/, ''), /bg-card/); + assert.match( + html, + /]*>]*>Signing a request<\/a>/, + ); +}); + +test("shows a guide's code in the docs' code blocks, as highlighted by the server", () => { + const html = renderToString( + curl https://dev-null.sh/api/v1/users/nunomaduro', + }, + }} + />, + ); + + assert.match(html, /
curl<\/span> https:\/\/dev-null\.sh/, + ); +}); + +test('asks for JSON on every request, so every error comes back as JSON', () => { + const html = renderToString(); + + assert.match(html, />accept<.*Accept: application\/json/s); +}); diff --git a/tests/Unit/ConsoleLayout.test.tsx b/tests/Unit/ConsoleLayout.test.tsx new file mode 100644 index 0000000000..3d84c65e3a --- /dev/null +++ b/tests/Unit/ConsoleLayout.test.tsx @@ -0,0 +1,207 @@ +/// + +import assert from 'node:assert/strict'; +import { createInertiaApp } from '@inertiajs/react'; +import type { InertiaLinkProps } from '@inertiajs/react'; +import { BookOpen, ShieldCheck, Users } from 'lucide-react'; +import { createElement } from 'react'; +import type { ComponentProps } from 'react'; +import { renderToString } from 'react-dom/server'; +import { beforeEach, test, vi } from 'vite-plus/test'; +import ConsoleLayout from '../../resources/js/layouts/console/layout'; +import type { User } from '../../resources/js/types'; + +const links = vi.hoisted(() => [] as InertiaLinkProps[]); + +// Inertia renders nothing of `prefetch` on the server, so the links' props are read as they are given. +vi.mock('@inertiajs/react', async (importOriginal) => { + const inertia = await importOriginal(); + + return { + ...inertia, + Link: (props: InertiaLinkProps) => { + links.push(props); + + return createElement(inertia.Link, props); + }, + }; +}); + +beforeEach(() => { + links.length = 0; +}); + +function prefetchOf(href: string): InertiaLinkProps['prefetch'][] { + return links + .filter((link) => link.href === href) + .map((link) => link.prefetch); +} + +const groups: ComponentProps['groups'] = [ + { + label: 'Pages', + items: [ + { + key: 'overview', + title: 'Overview', + description: 'What the console is for', + href: '/console/overview', + icon: BookOpen, + }, + ], + }, + { + label: 'Lists', + items: [ + { + key: 'people', + title: 'People', + description: 'Who uses it, and how much', + href: '/console/people', + icon: Users, + }, + ], + }, + { + label: 'Elsewhere', + items: [ + { + key: 'moderation', + title: 'Moderation', + description: 'The review queue', + href: '/moderation', + icon: ShieldCheck, + external: true, + }, + ], + }, +]; + +async function render( + props: Partial> = {}, +): Promise { + const result = await createInertiaApp({ + page: { + component: 'console', + props: { errors: {} }, + url: '/console/people', + version: null, + clearHistory: false, + encryptHistory: false, + rescuedProps: [], + rememberedState: {}, + flash: {}, + }, + resolve: () => () => ( + +

content

+
+ ), + render: renderToString, + setup: ({ App, props: appProps }) => , + }); + + return result.body; +} + +test('brands the console with its chip', async () => { + const html = await render(); + + assert.match(html, />ops<\/span>/); + assert.match(html, /aria-label="\/dev\/null console"/); +}); + +test('names the navigation after the console, apart from the brand link', async () => { + const html = await render(); + + assert.equal(html.match(/