diff --git a/README.md b/README.md index 3322c33..2272d4c 100644 --- a/README.md +++ b/README.md @@ -324,7 +324,10 @@ Markdown lives next to what it describes: | `requests///README.md` | an operation, above its parameter tables | | `requests//docs/.md` | the same, flat: one `docs/` folder per service | -A heading made of one code span (`` ## `name` ``) attaches the text under it to that field. +Write whatever markdown you like. The Docs tab also shows the parameters, the request body and each response status +from the spec, below your page; to put one where it belongs in your text, add a comment on a line of its own: +``, `path`, `query`, `headers`, `body`, `responses`, `auth`, `description` or `examples`. +What each field means comes from the spec. ### Try it on any page diff --git a/apps/docs/demo/requests/petstore/GetPetById/README.md b/apps/docs/demo/requests/petstore/GetPetById/README.md index dc8365d..14af51e 100644 --- a/apps/docs/demo/requests/petstore/GetPetById/README.md +++ b/apps/docs/demo/requests/petstore/GetPetById/README.md @@ -1,7 +1,7 @@ Looks a pet up by its id. Use this to check that a pet you added is really there. -## `petId` +The demo's seed pets are 1 to 3, and ones you add start at 1001. -The pet's number, as `Add a pet` returned it. The demo's seed pets are 1 to 3, and ones you add start at 1001. + diff --git a/apps/docs/public/llms.txt b/apps/docs/public/llms.txt index b2c63dd..e3da6ba 100644 --- a/apps/docs/public/llms.txt +++ b/apps/docs/public/llms.txt @@ -236,7 +236,7 @@ do not prove it: a request that needs Node builds cleanly and passes in node, an ## Notes beside the code (optional) -Markdown next to what it describes is shown in the UI: `requests///README.md` for an operation, `.req.md` beside a request, `.seq.md` beside a flow. A heading made of one code span (`` ## `petId` ``) attaches its text to that field. +Markdown next to what it describes is shown in the UI: `requests///README.md` for an operation, `.req.md` beside a request, `.seq.md` beside a flow. The Docs tab shows the spec's parameters, request body and responses below the page; `` (also `path`, `query`, `headers`, `body`, `responses`) on a line of its own puts one where you want it. Field descriptions come from the spec, not from the page. ## Docs diff --git a/apps/docs/src/content/docs/reference/documentation-pages.mdx b/apps/docs/src/content/docs/reference/documentation-pages.mdx new file mode 100644 index 0000000..6cfb0f8 --- /dev/null +++ b/apps/docs/src/content/docs/reference/documentation-pages.mdx @@ -0,0 +1,59 @@ +--- +title: Documentation pages +description: Write your own markdown for an operation, a request or a flow, and say where the generated tables go. +--- + +import Snippet from '../../../components/Snippet.astro' + +The Docs tab of an operation shows what the spec says: the description, the parameters, the request body and each +response. A markdown page beside your code adds what the spec does not say. Write whatever you like in it. + +## Where a page lives + +| File | Documents | +| --- | --- | +| `requests///README.md` | an operation | +| `requests//docs/.md` | the same, flat: one `docs/` folder per service | +| `requests/.req.md` | the request in `.req.ts` | +| `sequences/.seq.md` | the flow in `.seq.ts` | + +A markdown file anywhere else can name what it documents in its front matter, such as `operation: petstore/GetPetById`. +If two pages claim one operation, the first by path is used and the other is reported. + +By default the page follows the spec's own description. Put `replace: true` in the front matter to have it stand in +for that description instead. + +## Placing the generated tables + +Without any markers the page comes first and the tables follow it. To put a table inside your text, write a comment +on a line of its own: + + + +| Comment | What appears there | +| --- | --- | +| `` | The spec's description of the operation. | +| `` | How to authorize, and which profiles in this project work. | +| `` | The path, query and header parameters together. | +| ``, `query`, `headers` | One of those on its own. | +| `` | The request body. | +| `` | Each response status, with what comes back. | +| `` | The named examples, each opening the Try tab. | + +A block you do not place still appears, after your page, in that order. Placing it moves it; it never shows twice. +A comment inside a sentence, or one that names no block, is left alone and shows nothing. + +## What the tables hold + +Field descriptions come from the spec, so fix them there. The tables list an object's fields and mark the ones that +are required. A field that holds an object, or a list of them, has a [+]: click its row to open it and its plain fields appear +indented one step below it. An object among them is a group of its own at the left, named by its whole path, such as +`address.county`, with its fields below it when you open that in turn. Nothing is ever indented further than one +step. A field that can be one of several shapes names them. A response is a tab for each status, with the spec's text for it and +the type of its body. + +## Moving from field notes + +Earlier versions turned a heading made of one code span, such as `` ## `petId` ``, into a note on that field. That no +longer happens: the heading is shown as ordinary text. Move the sentence into the spec's description for the field, +or into your own text, and put the table where it should sit with a comment. diff --git a/apps/docs/src/pages/document.astro b/apps/docs/src/pages/document.astro index b6d6311..7efdcff 100644 --- a/apps/docs/src/pages/document.astro +++ b/apps/docs/src/pages/document.astro @@ -49,7 +49,7 @@ import Page from '../layouts/Page.astro'
  • A request: <name>.req.md beside <name>.req.ts.
  • A flow: <name>.seq.md beside <name>.seq.ts.
  • Anywhere else: a markdown file whose front matter names what it documents, like operation: petstore/GetPetById.
  • -
  • A field: a heading made of one code span, like ## `petId`, attaches its text to that field.
  • +
  • Where the tables go: a comment on a line of its own, like <!-- specbook: params -->, puts the parameters, body or responses there. Without one they follow your text.
  • diff --git a/apps/example/requests/petstore/AddPet/README.md b/apps/example/requests/petstore/AddPet/README.md index a2d477f..98cfe30 100644 --- a/apps/example/requests/petstore/AddPet/README.md +++ b/apps/example/requests/petstore/AddPet/README.md @@ -8,10 +8,9 @@ store assigns an `id` when you leave it out. Press **Play** to try it against the mock. The request gives every pet a generated name (`petName`), so each play sends a new one. -## `name` +## What to send -Shown in the shop's catalogue, so keep it under 40 characters. Names are not unique. +The name is shown in the shop's catalogue, so keep it under 40 characters. Names are not unique. Give at +least one photo URL: the demo store does not fetch them, so any `https://` address works. -## `photoUrls` - -At least one URL. The demo store does not fetch them, so any `https://` address works. + diff --git a/packages/cli/agent-guide.md b/packages/cli/agent-guide.md index 782e1d3..d6c0c81 100644 --- a/packages/cli/agent-guide.md +++ b/packages/cli/agent-guide.md @@ -236,4 +236,4 @@ do not prove it: a request that needs Node builds cleanly and passes in node, an ## Notes beside the code (optional) -Markdown next to what it describes is shown in the UI: `requests///README.md` for an operation, `.req.md` beside a request, `.seq.md` beside a flow. A heading made of one code span (`` ## `petId` ``) attaches its text to that field. +Markdown next to what it describes is shown in the UI: `requests///README.md` for an operation, `.req.md` beside a request, `.seq.md` beside a flow. The Docs tab shows the spec's parameters, request body and responses below the page; `` (also `path`, `query`, `headers`, `body`, `responses`) on a line of its own puts one where you want it. Field descriptions come from the spec, not from the page. diff --git a/packages/codegen/src/browser.ts b/packages/codegen/src/browser.ts index c1e07f4..011f8ea 100644 --- a/packages/codegen/src/browser.ts +++ b/packages/codegen/src/browser.ts @@ -15,6 +15,7 @@ export type { ManifestOperation, ManifestSecurityScheme, OperationMeta, + ResponseDoc, } from './build' export { generateFromDoc, logoOf } from './build' diff --git a/packages/codegen/src/build.ts b/packages/codegen/src/build.ts index ac9cd7c..a848675 100644 --- a/packages/codegen/src/build.ts +++ b/packages/codegen/src/build.ts @@ -73,6 +73,13 @@ interface ExampleDoc { body?: unknown } +/** What `docs/.json` says about one response, for the Docs tab. */ +export interface ResponseDoc { + description?: string + /** the media type the body is written in, as the spec names it */ + contentType?: string +} + export interface ManifestOperation { id: string method: string @@ -174,6 +181,7 @@ function findJsonLike(content: Record | undefined) { schema: content[mime].schema as Schema | undefined, encoding: enc, media: content[mime], + mime, } } const json = Object.keys(content).find((m) => /json/.test(m)) @@ -182,6 +190,7 @@ function findJsonLike(content: Record | undefined) { schema: content[json].schema as Schema | undefined, encoding: 'json', media: content[json], + mime: json, } const binary = Object.keys(content).find((m) => BINARY_MIME.test(m)) if (binary) @@ -189,6 +198,7 @@ function findJsonLike(content: Record | undefined) { schema: content[binary].schema as Schema | undefined, encoding: 'binary', media: content[binary], + mime: binary, mediaType: binary, } // A wildcard stands for whatever the server sends, and a framework that is not told what it produces @@ -201,6 +211,7 @@ function findJsonLike(content: Record | undefined) { schema, encoding: file ? 'binary' : 'json', media: content[any], + mime: any, ...(file ? { mediaType: any } : {}), } } @@ -544,6 +555,18 @@ function generateAll( let defaultSchema: Schema | undefined const responseSchemas: Record = {} const mockVariants: NonNullable = {} + const responseDocs: Record = {} + let defaultDoc: ResponseDoc | undefined + const docOf = (res: any, found: { mime?: string } | undefined): ResponseDoc | undefined => { + const description = + typeof res?.description === 'string' && res.description.trim() + ? res.description.trim() + : undefined + const contentType = found?.mime ?? Object.keys(res?.content ?? {})[0] + return description || contentType + ? { ...(description ? { description } : {}), ...(contentType ? { contentType } : {}) } + : undefined + } let defaultVariants: ManifestOperation['mockVariants'] extends infer M ? M extends Record ? V | undefined @@ -551,7 +574,9 @@ function generateAll( : never for (const [code, rawRes] of Object.entries(op.responses ?? {})) { if (code === 'default') { - const found = findJsonLike(resolveAny(rawRes)?.content) + const defaultRes = resolveAny(rawRes) + const found = findJsonLike(defaultRes?.content) + defaultDoc = docOf(defaultRes, found) if (found?.schema) { hasDefault = true if (ts) defaultType = tsType(found.schema, ' ', 'T.') @@ -569,6 +594,8 @@ function generateAll( const res = resolveAny(rawRes) const found = findJsonLike(res?.content) statuses.push(Number(code)) + const responseDoc = docOf(res, found) + if (responseDoc) responseDocs[code] = responseDoc if (found?.schema) responseSchemas[code] = toJsonSchema(found.schema, `${defsId}#/$defs/`) if (ts) responseTypes.push( @@ -587,6 +614,7 @@ function generateAll( for (const st of DEFAULT_ERROR_STATUSES) { if (statuses.includes(st)) continue statuses.push(st) + if (defaultDoc) responseDocs[String(st)] = defaultDoc if (defaultSchema) responseSchemas[String(st)] = defaultSchema if (defaultVariants) mockVariants[String(st)] = defaultVariants if (defaultType) responseTypes.push(`${st}: ${defaultType}`) @@ -746,6 +774,7 @@ ${jsdoc({ description: [...new Set([op.summary, op.description].filter(Boolean)) content: `${JSON.stringify({ ...(op.description && op.description !== summary ? { description: op.description } : {}), examples: docs.map((d) => ({ name: d.name, title: d.title, source: d.source })), + ...(Object.keys(responseDocs).length ? { responses: responseDocs } : {}), })}\n`, }) operations.push({ diff --git a/packages/codegen/test/generate.test.ts b/packages/codegen/test/generate.test.ts index 951fb08..e2416fc 100644 --- a/packages/codegen/test/generate.test.ts +++ b/packages/codegen/test/generate.test.ts @@ -1328,3 +1328,69 @@ describe('round 2: what the spec still says', () => { expect(synthesize(string, none, 0, [], 'master_branch')).toBe('main') }) }) + +describe('what each response is, for the docs page', () => { + const docs = (files: { path: string; content: string }[], id: string) => + JSON.parse(files.find((f) => f.path === `docs/${id}.json`)?.content ?? 'null') + + it('keeps the description and media type of every status', async () => { + const { files } = await generate({ spec: fx('bookstore.json'), service: 'books' }) + expect(docs(files, 'ListShelf').responses).toEqual({ + '200': { description: 'The shelf', contentType: 'application/json' }, + '409': { description: 'Not available', contentType: 'application/json' }, + }) + }) + + it('keeps the description of a status that has no body', async () => { + const { files } = await generate({ spec: fx('petstore3.json'), service: 'petstore' }) + const responses = docs(files, 'GetPetById').responses + expect(responses['400']).toEqual({ description: 'Invalid ID supplied' }) + expect(responses['200'].contentType).toBe('application/json') + }) + + it('gives a default response to every status it stands for, and names non-JSON media types', async () => { + const dir = await mkdtemp(join(tmpdir(), 'specbook-docs-')) + dirs.push(dir) + const spec = join(dir, 'spec.json') + await writeFile( + spec, + JSON.stringify({ + openapi: '3.0.3', + info: { title: 't', version: '1' }, + paths: { + '/a': { + get: { + operationId: 'GetA', + responses: { + '200': { + description: 'Fine', + content: { 'text/csv': { schema: { type: 'string' } } }, + }, + default: { + description: 'Something went wrong', + content: { + 'application/json': { + schema: { type: 'object', properties: { message: { type: 'string' } } }, + }, + }, + }, + }, + }, + }, + }, + }), + ) + const { files } = await generate({ spec, service: 'a' }) + const responses = docs(files, 'GetA').responses + expect(responses['200']).toEqual({ description: 'Fine', contentType: 'text/csv' }) + for (const code of [400, 401, 402, 403, 404, 409, 422, 429, 500]) + expect(responses[String(code)]).toEqual({ + description: 'Something went wrong', + contentType: 'application/json', + }) + const schemas = JSON.parse( + files.find((f) => f.path === 'schemas/GetA.responses.schema.json')?.content ?? '{}', + ) + expect(schemas['200']).toBeUndefined() + }) +}) diff --git a/packages/ui/src/fielddoc.ts b/packages/ui/src/fielddoc.ts index 26b3c7c..516bbf4 100644 --- a/packages/ui/src/fielddoc.ts +++ b/packages/ui/src/fielddoc.ts @@ -1,4 +1,3 @@ -import { type FieldSection, noteKey } from './panel/fieldnotes-split' import { type Defs, describe, @@ -19,8 +18,6 @@ export interface FieldDoc { required: boolean enum?: string[] description?: string - /** the project's own note for this field (HTML), shown after the spec's description */ - note?: string /** what the enclosing object says about itself, shown when the field has no description */ parent?: string deprecated?: boolean @@ -80,14 +77,3 @@ export function fieldDoc( export function keyPath(key: string): KeyPath { return (key.match(/[^[\]]+/g) ?? [key]).map((s) => (/^\d+$/.test(s) ? Number(s) : s)) } - -/** Adds the project's note for `path` in `section` (see `README.md` field sections), when there is one. */ -export function withNote( - doc: FieldDoc | undefined, - notes: Map | undefined, - section: FieldSection, - path: string, -): FieldDoc | undefined { - const note = doc && notes?.get(noteKey(section, path)) - return doc && note ? { ...doc, note } : doc -} diff --git a/packages/ui/src/markdown.ts b/packages/ui/src/markdown.ts index fe93259..9b61134 100644 --- a/packages/ui/src/markdown.ts +++ b/packages/ui/src/markdown.ts @@ -21,6 +21,38 @@ function inline(text: string): string { return s.replace(/\uE000(\d+)\uE000/g, (_m, i: string) => codes[Number(i)] ?? '') } +/** + * The HTML some specs write their descriptions in (Stripe's are `

    …

    `) as the markdown this file reads: the tags + * that mean something become their markdown, and any other known tag is dropped, so none is shown as text. Text that + * only looks like a tag (``) and fenced code are left alone. + */ +export function fromHtml(src: string): string { + return src + .split(/(```[\s\S]*?```)/) + .map((part, i) => + i % 2 + ? part + : part + .replace(/<\/p>\s*]*>/gi, '\n\n') + .replace(//gi, '\n') + .replace(/]*>([\s\S]*?)<\/code>/gi, '`$1`') + .replace(/<(strong|b)(\s[^>]*)?>([\s\S]*?)<\/\1>/gi, '**$3**') + .replace(/<(em|i)(\s[^>]*)?>([\s\S]*?)<\/\1>/gi, '*$3*') + .replace( + /]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi, + (_m, href: string, text: string) => `[${text}](${href})`, + ) + .replace(/]*>/gi, '\n- ') + .replace( + /<\/?(p|ul|ol|li|div|span|h[1-6]|table|thead|tbody|tr|td|th)(\s[^>]*)?>/gi, + '\n', + ) + .replace(/\n{3,}/g, '\n\n'), + ) + .join('') + .trim() +} + /** * A small, safe markdown subset for descriptions: paragraphs, headings, bullet and numbered lists, fenced * code, and inline code, bold, italics and links. Everything is HTML-escaped first, and only http(s) and @@ -28,7 +60,7 @@ function inline(text: string): string { */ export function markdownToHtml(src: string | undefined): string { if (!src) return '' - const lines = src.replace(/\r\n?/g, '\n').split('\n') + const lines = fromHtml(src).replace(/\r\n?/g, '\n').split('\n') const out: string[] = [] let para: string[] = [] let list: { tag: 'ul' | 'ol'; items: string[] } | undefined @@ -100,7 +132,7 @@ export function markdownToHtml(src: string | undefined): string { /** Markdown reduced to readable plain text: links keep their label, markers and fences disappear. */ export function plainText(src: string | undefined): string { if (!src) return '' - return src + return fromHtml(src) .replace(/```[\s\S]*?```/g, ' ') .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') .replace(/^#{1,6}\s+/gm, '') @@ -113,7 +145,7 @@ export function plainText(src: string | undefined): string { export function firstParagraph(src: string | undefined): string { if (!src) return '' - return (src.trim().split(/\n\s*\n/)[0] ?? '').replace(/\s*\n\s*/g, ' ').trim() + return (fromHtml(src).split(/\n\s*\n/)[0] ?? '').replace(/\s*\n\s*/g, ' ').trim() } /** Inline markup only (code, bold, italics, links) in already-safe HTML, for a single line or cell. */ diff --git a/packages/ui/src/panel/Body.tsx b/packages/ui/src/panel/Body.tsx index 41099db..2e45174 100644 --- a/packages/ui/src/panel/Body.tsx +++ b/packages/ui/src/panel/Body.tsx @@ -1,7 +1,7 @@ import { type Encoding, fromFormRows, toFormRows } from '@specbook/core' import { useEffect, useMemo, useRef, useState } from 'preact/hooks' -import { type FieldDoc as Doc, fieldDoc, keyPath, withNote } from '../fielddoc' -import { type Defs, type JsonSchema, linePaths, pathString } from '../schema' +import { type FieldDoc as Doc, fieldDoc, keyPath } from '../fielddoc' +import { type Defs, type JsonSchema, linePaths } from '../schema' import { BodyEditor } from './BodyEditor' import { jsonCompletions } from './completions' import { type Draft, type FieldRow, gridMode } from './draft' @@ -18,8 +18,6 @@ interface Props { defs?: Defs /** dotted body paths that are uploads */ files?: string[] - /** the project's own notes for body fields, by `data.` */ - notes?: Map /** shown, not edited */ readOnly?: boolean } @@ -79,16 +77,7 @@ function GraphqlBody({ const language = (e: Encoding) => (e === 'graphql' ? 'graphql' : e === 'text' ? 'text' : 'json') -export function Body({ - encoding, - draft, - onChange, - schema, - defs, - files = [], - notes, - readOnly, -}: Props) { +export function Body({ encoding, draft, onChange, schema, defs, files = [], readOnly }: Props) { const [line, setLine] = useState(0) const paths = useMemo(() => linePaths(draft.body), [draft.body]) const documented = encoding === 'json' || encoding === 'form' @@ -102,10 +91,8 @@ export function Body({ }, [draft.body]) const doc: Doc | undefined = useMemo(() => { const p = paths[line] - return p && documented - ? withNote(fieldDoc(schema, defs, p, ['data'], typed), notes, 'data', pathString(p)) - : undefined - }, [paths, line, schema, defs, documented, notes, typed]) + return p && documented ? fieldDoc(schema, defs, p, ['data'], typed) : undefined + }, [paths, line, schema, defs, documented, typed]) const complete = useMemo( () => documented && schema @@ -168,7 +155,7 @@ export function Body({ readOnly={readOnly} onChange={set} documented={[...new Set(fileKeys)].map((name) => ({ name, file: true }))} - docFor={(k) => withNote(fieldDoc(schema, defs, keyPath(k), ['data']), notes, 'data', k)} + docFor={(k) => fieldDoc(schema, defs, keyPath(k), ['data'])} /> ) diff --git a/packages/ui/src/panel/FieldDoc.tsx b/packages/ui/src/panel/FieldDoc.tsx index 456b84c..62cf6e6 100644 --- a/packages/ui/src/panel/FieldDoc.tsx +++ b/packages/ui/src/panel/FieldDoc.tsx @@ -22,13 +22,12 @@ export function FieldDoc({ doc, hint }: { doc?: Doc; hint?: string }) { class="field-doc-text" dangerouslySetInnerHTML={{ __html: markdownToHtml(doc.description) }} /> - ) : doc.note ? null : ( + ) : (

    The spec has no description for this field. {doc.parent && <> It is part of: {doc.parent}}

    )} - {doc.note &&
    } {doc.enum && (

    {doc.enum.slice(0, 12).map((v) => ( diff --git a/packages/ui/src/panel/FieldTable.tsx b/packages/ui/src/panel/FieldTable.tsx index 8ab922b..90d5fda 100644 --- a/packages/ui/src/panel/FieldTable.tsx +++ b/packages/ui/src/panel/FieldTable.tsx @@ -1,19 +1,26 @@ +import { useState } from 'preact/hooks' import { inlineSummary } from '../markdown' import { type Defs, describe, type JsonSchema, kindOf, + type Prop, propsOf, typeInfo, unionFor, unwrap, } from '../schema' -import { type FieldSection, noteKey } from './fieldnotes-split' -interface Row { +export interface Row { + /** what the row is called: a field's name, or for an object under an open field its whole path (`address.county`) */ name: string - depth: number + /** what an open field is looked up by */ + key: string + /** the path of the field from the top of the table, which is what the fields of an object below it are named under */ + path: string + /** 0 for the fields of the table and for an object under an open field, 1 for the other fields under it: never further */ + depth: 0 | 1 type: string /** the whole text of a type shortened to fit */ typeTitle?: string @@ -22,73 +29,244 @@ interface Row { enum?: string[] /** a heading for one variant of a union, with the fields of that variant under it */ variant?: boolean + /** the field has fields of its own to show, or variants */ + schema?: JsonSchema +} + +/** The most rows one open field shows. */ +const MAX_EXPANDED = 150 + +type Union = NonNullable> + +const objectBranches = (union: Union, defs: Defs) => + union.branches.filter((b) => kindOf(unwrap(b.schema, defs)) === 'object') + +const tagText = (union: { tagProp?: string }, tag?: string) => + union.tagProp && tag !== undefined ? `${union.tagProp} = "${tag}"` : '' + +/** The union a property is, or that the items of a property that is a list are. */ +function unionOfProp(schema: JsonSchema, defs: Defs) { + const u = unwrap(schema, defs) + const isList = kindOf(u) === 'array' + return { u, isList, union: unionFor(isList ? u.items : schema, defs) } +} + +function heading(union: Union, b: { name?: string; tag?: string }, key: string): Row { + const name = b.name ?? 'variant' + return { + name, + key: `${key}/${name}`, + path: '', + depth: 1, + type: tagText(union, b.tag), + required: false, + variant: true, + } +} + +/** Whether a field has anything to open: fields of an object (or of the objects of a list), or variants. */ +function openable(schema: JsonSchema, defs: Defs): boolean { + const { u, isList, union } = unionOfProp(schema, defs) + if (union) return objectBranches(union, defs).length > 0 + const inner = isList ? unwrap(u.items, defs) : u + return kindOf(inner) === 'object' && propsOf(inner, defs).length > 0 +} + +function propRow( + p: Prop, + defs: Defs, + at: { name: string; key: string; path: string; depth: 0 | 1 }, +): Row { + const u = unwrap(p.schema, defs) + const info = typeInfo(p.schema, defs) + return { + ...at, + type: info.text, + typeTitle: info.title, + required: p.required, + description: describe(u), + enum: Array.isArray(u.enum) && u.enum.length <= 10 ? u.enum.map(String) : undefined, + schema: openable(p.schema, defs) ? p.schema : undefined, + } +} + +/** + * The fields of an object as they sit under an open field: the plain ones indented one step, then each object + * among them at the left under its whole path, to be opened in its turn. (An object's fields are never pushed + * further in, so a table is as narrow at the bottom as at the top.) + */ +function fieldsUnder(obj: JsonSchema, defs: Defs, scope: string, path: string): Row[] { + const props = propsOf(obj, defs) + const plain = props.filter((p) => !openable(p.schema, defs)) + const nested = props.filter((p) => openable(p.schema, defs)) + const at = (p: Prop, depth: 0 | 1) => { + const whole = path ? `${path}.${p.name}` : p.name + return { name: depth === 0 ? whole : p.name, key: `${scope}>${p.name}`, path: whole, depth } + } + return [ + ...plain.map((p) => propRow(p, defs, at(p, 1))), + ...nested.map((p) => propRow(p, defs, at(p, 0))), + ] +} + +/** What an open field holds: a heading and the fields of each variant of a union, else the fields of an object. */ +export function expansion(row: Row, defs: Defs): Row[] { + if (!row.schema) return [] + const { u, isList, union } = unionOfProp(row.schema, defs) + if (union) { + return objectBranches(union, defs).flatMap((b) => [ + heading(union, b, row.key), + ...fieldsUnder(unwrap(b.schema, defs), defs, `${row.key}/${b.name ?? 'variant'}`, row.path), + ]) + } + const inner = isList ? unwrap(u.items, defs) : u + return kindOf(inner) === 'object' ? fieldsUnder(inner, defs, row.key, row.path) : [] } -const MAX_ROWS = 60 +/** The variants of a union field, named, for when the field is closed: what it can be, without what is in it. */ +function variantsOf(row: Row, defs: Defs): Row[] { + if (!row.schema) return [] + const { union } = unionOfProp(row.schema, defs) + return union ? objectBranches(union, defs).map((b) => heading(union, b, row.key)) : [] +} /** - * The rows of a field table. `depth` is how far a row is indented; `level` how deep the schema has gone, which - * is what is limited: a variant's heading is a row, not a level, so a union costs no depth of its own. + * The fields of an object, or of the objects of a list, or the variants of a union with the fields of each, all + * at the left: what is in a field is shown when the field is opened (see `expansion`). */ -export function flatten( +export function topRows(schema: JsonSchema | undefined, defs: Defs): Row[] { + if (!schema) return [] + const { u, isList, union } = unionOfProp(schema, defs) + const top = (obj: JsonSchema, scope: string) => + propsOf(obj, defs).map((p) => + propRow(p, defs, { name: p.name, key: `${scope}${p.name}`, path: p.name, depth: 0 }), + ) + if (union) { + return objectBranches(union, defs).flatMap((b) => [ + { ...heading(union, b, ''), depth: 0 as const }, + ...top(unwrap(b.schema, defs), `${b.name ?? 'variant'}/`), + ]) + } + return top(isList ? unwrap(u.items, defs) : u, '') +} + +/** A name that may break after a dot or an underscore, where a person would, and nowhere else. */ +function Breakable({ name }: { name: string }) { + return ( + <> + {(name.match(/[^._]*[._]?/g) ?? []).filter(Boolean).map((part, i) => ( + <> + {i > 0 && } + {part} + + ))} + + ) +} + +function RowView({ r, open, onToggle }: { r: Row; open?: boolean; onToggle?: () => void }) { + return ( + { + if ((e.target as HTMLElement).closest('a')) return + if (window.getSelection()?.toString()) return + onToggle() + } + : undefined + } + > + + {r.variant ? ( + {r.name} + ) : ( + + {onToggle ? ( + + ) : ( + + )} + + + + {r.required && ( + + * + + )} + + )} + + + {r.type && ( + + {r.type} + + )} + + + + {r.enum && ( + + {' '} + {r.enum.map((v) => ( + {v} + ))} + + )} + + + ) +} + +/** A row to draw, or a count of what is left out. */ +export type Shown = { row: Row } | { more: number; key: string } + +/** What the table shows with the fields in `opened` open: what is under them, or for a closed union field, its variants. */ +export function visibleRows( schema: JsonSchema | undefined, defs: Defs, - depth = 0, - prefix = '', - level = depth, -): Row[] { - if (!schema || level > 2) return [] - const rows: Row[] = [] - for (const p of propsOf(schema, defs)) { - const u = unwrap(p.schema, defs) - const name = prefix ? `${prefix}.${p.name}` : p.name - const info = typeInfo(p.schema, defs) - rows.push({ - name, - depth, - type: info.text, - typeTitle: info.title, - required: p.required, - description: describe(u), - enum: Array.isArray(u.enum) && u.enum.length <= 10 ? u.enum.map(String) : undefined, - }) - const isList = kindOf(u) === 'array' - const union = unionFor(isList ? u.items : p.schema, defs) - if (union) { - // each variant under a heading that says what it is called and what its tag is - for (const b of union.branches) { - if (kindOf(unwrap(b.schema, defs)) !== 'object') continue - rows.push({ - name: `${name}.${b.name ?? 'variant'}`, - depth: depth + 1, - type: union.tagProp && b.tag !== undefined ? `${union.tagProp} = "${b.tag}"` : '', - required: false, - variant: true, - }) - rows.push(...flatten(b.schema, defs, depth + 2, name, level + 1)) - } - continue - } - const nested = isList ? unwrap(u.items, defs) : u - if (kindOf(nested) === 'object') rows.push(...flatten(nested, defs, depth + 1, name, level + 1)) + opened: ReadonlySet, +): Shown[] { + const walk = (row: Row): Shown[] => { + const out: Shown[] = [{ row }] + if (!row.schema) return out + const more = opened.has(row.key) ? expansion(row, defs) : variantsOf(row, defs) + for (const m of more.slice(0, MAX_EXPANDED)) out.push(...walk(m)) + if (more.length > MAX_EXPANDED) + out.push({ more: more.length - MAX_EXPANDED, key: `${row.key}>more` }) + return out } - return rows + return topRows(schema, defs).flatMap(walk) } -export function FieldTable({ - schema, - defs, - section = 'data', - notes, -}: { - schema?: JsonSchema - defs: Defs - /** where these fields sit in the request, for looking up the project's notes */ - section?: FieldSection - notes?: Map -}) { - const rows = flatten(schema, defs) - if (rows.length === 0) return null +export function FieldTable({ schema, defs }: { schema?: JsonSchema; defs: Defs }) { + const [opened, setOpened] = useState>(new Set()) + const shown = visibleRows(schema, defs, opened) + if (shown.length === 0) return null + const toggle = (key: string) => + setOpened((s) => { + const next = new Set(s) + if (!next.delete(key)) next.add(key) + return next + }) return ( @@ -99,57 +277,21 @@ export function FieldTable({ - {rows.slice(0, MAX_ROWS).map((r) => ( - - - - - - ))} - {rows.length > MAX_ROWS && ( - - - + {shown.map((s) => + 'more' in s ? ( + + + + ) : ( + toggle(s.row.key) : undefined} + /> + ), )}
    - {r.variant ? ( - {r.name.split('.').pop()} - ) : ( - {r.name.split('.').pop()} - )} - {r.required && ( - - * - - )} - - {r.type && ( - - {r.type} - - )} - - - {notes?.get(noteKey(section, r.name)) && ( -
    - )} - {r.enum && ( - - {' '} - {r.enum.map((v) => ( - {v} - ))} - - )} -
    - +{rows.length - MAX_ROWS} more fields in the spec -
    + +{s.more} more fields in the spec +
    diff --git a/packages/ui/src/panel/OperationDocs.tsx b/packages/ui/src/panel/OperationDocs.tsx index 518b27e..15ac192 100644 --- a/packages/ui/src/panel/OperationDocs.tsx +++ b/packages/ui/src/panel/OperationDocs.tsx @@ -6,11 +6,12 @@ import type { Variant } from '../engine' import { markdownToHtml } from '../markdown' import { engine, registry } from '../runtime' import type { Defs, JsonSchema } from '../schema' -import { unwrap } from '../schema' +import { typeInfo, unwrap } from '../schema' import { statusClass, statusName } from '../status' import { version } from '../store' import { FieldTable } from './FieldTable' -import { useOperationNotes } from './fieldnotes' +import type { BlockName, Segment } from './includes' +import { useOperationPage } from './page' export interface DocOp { id: string @@ -26,9 +27,16 @@ export interface DocOp { security?: Record[] } +interface ResponseDoc { + description?: string + contentType?: string +} + interface LongDocs { description?: string examples: { name: string; title: string; source: string }[] + /** what each status is, by code */ + responses?: Record } const SECTIONS = [ @@ -41,6 +49,8 @@ const SECTIONS = [ interface Loaded { long?: LongDocs req?: JsonSchema + /** the schema of each status's body, by code */ + resp?: Record defs?: Defs /** a saved request's own markdown (`.req.md` beside its `.req.ts`), by file */ saved: Record @@ -53,11 +63,17 @@ function loadAll(key: string, service: string, files: string[]): Promise return Promise.all([ soft(registry.operationDocs[key]?.().then((m: { default: LongDocs }) => m.default)), soft(registry.schemas[key]?.().then((m: { default: JsonSchema }) => m.default)), + soft( + registry.responseSchemas[key]?.().then( + (m: { default: Record }) => m.default, + ), + ), soft(registry.definitions[service]?.().then((m: { default: Defs }) => m.default)), Promise.all(files.map((f) => soft(registry.docs.find((d) => d.requestFile === f)?.load()))), - ]).then(([long, req, defs, notes]) => ({ + ]).then(([long, req, resp, defs, notes]) => ({ long, req, + resp, defs, saved: Object.fromEntries(files.flatMap((f, i) => (notes[i] ? [[f, notes[i] as string]] : []))), })) @@ -76,6 +92,85 @@ function SavedRequestNote({ variant, html }: { variant: Variant; html?: string } ) } +/** What a body is, in a line: its type, and the media type it is written in when the spec says. */ +function BodyType({ + schema, + defs, + contentType, +}: { + schema?: JsonSchema + defs?: Defs + contentType?: string +}) { + const info = schema ? typeInfo(schema, defs) : undefined + return ( +

    + {info ? ( + <> + + {info.text} + {' '} + + ) : ( + !contentType && No body described + )} + {contentType && {contentType}} +

    + ) +} + +function ResponseSection({ + statuses, + mockVariants, + docs, + schemas, + defs, +}: { + statuses: number[] + mockVariants?: DocOp['mockVariants'] + docs?: Record + schemas?: Record + defs?: Defs +}) { + const [status, setStatus] = useState( + () => statuses.find((s) => s >= 200 && s < 300) ?? (statuses[0] as number), + ) + const doc = docs?.[String(status)] + const schema = schemas?.[String(status)] + const variants = mockVariants?.[String(status)] + return ( +
    +

    Responses

    +
    + {statuses.map((s) => ( + + ))} +
    +
    + {doc?.description && ( +
    + )} + + {variants && variants.length > 1 && ( +

    Variants: {variants.map((v) => v.title ?? v.name).join(' · ')}

    + )} + {schema && } +
    +
    + ) +} + export function OperationDocs({ service, op, @@ -123,14 +218,122 @@ export function OperationDocs({ const schemes = registry.manifests[service]?.securitySchemes const alternatives = describeSecurity(op.security, schemes) - const page = useOperationNotes(key) + const page = useOperationPage(key) // the header is there at once; everything below it appears together once it has all arrived const ready = !!loaded && page.loaded - const { long, req, defs } = loaded ?? { saved: {} } + const { long, req, resp, defs } = loaded ?? { saved: {} } const root = req ? unwrap(req, defs) : undefined const section = (name: string) => root?.properties?.[name] as JsonSchema | undefined const body = section('data') + const description = long?.description && ( +
    + ) + const auth = + alternatives.length > 0 || (schemes && !op.secured) ? ( +
    +

    Authorization

    + {alternatives.length === 0 ? ( +

    No credentials needed.

    + ) : ( + <> +

    {alternatives.length > 1 ? 'Send one of:' : 'Send:'}

    +
      + {alternatives.map((parts) => ( +
    • + {parts.map((p, i) => ( + <> + {i > 0 && ' and '} + {p.scheme} {p.how} + {p.scopes.length > 0 && ( + <> + {' '} + with scopes {p.scopes.join(', ')} + + )} + + ))} +
    • + ))} +
    + {works && works.length > 0 &&

    In this project: {works.join(', ')}.

    } + + )} +
    + ) : null + const saved = variants.map((v) => ( + + )) + const params = (k: 'path' | 'query' | 'headers') => { + const schema = section(k) + return schema ? ( +
    +

    {SECTIONS.find(([n]) => n === k)?.[1]} parameters

    + +
    + ) : null + } + const requestBody = body && ( +
    +

    Request body

    + + +
    + ) + const responses = op.statuses.length > 0 && ( + + ) + const examples = (long?.examples.length ?? 0) > 1 && ( +
    +

    Examples

    +
      + {long?.examples.map((e) => ( +
    • + +
    • + ))} +
    +
    + ) + const blocks: Record = { + description, + auth, + path: params('path'), + query: params('query'), + headers: params('headers'), + params: [params('path'), params('query'), params('headers')], + body: requestBody, + responses, + examples, + } + + // the blocks the page puts where it wants them; the rest follow it in the usual order + const placed = new Set() + for (const seg of page.segments) if ('block' in seg) placed.add(seg.block) + if (placed.has('params')) for (const k of ['path', 'query', 'headers'] as const) placed.add(k) + const show = (name: BlockName) => (placed.has(name) ? null : blocks[name]) + + const segment = (seg: Segment) => + 'block' in seg ? ( + (blocks[seg.block] as preact.ComponentChild) + ) : ( +
    + ) + return (
    @@ -144,103 +347,16 @@ export function OperationDocs({ {ready && ( <> {/* the spec's own text first; the project's page follows it, or stands in for it with `replace: true` */} - {!(page.found && page.replace) && long?.description && ( -
    - )} - {page.intro && ( -
    - )} - - {(alternatives.length > 0 || (schemes && !op.secured)) && ( -
    -

    Authorization

    - {alternatives.length === 0 ? ( -

    No credentials needed.

    - ) : ( - <> -

    {alternatives.length > 1 ? 'Send one of:' : 'Send:'}

    -
      - {alternatives.map((parts) => ( -
    • - {parts.map((p, i) => ( - <> - {i > 0 && ' and '} - {p.scheme} {p.how} - {p.scopes.length > 0 && ( - <> - {' '} - with scopes {p.scopes.join(', ')} - - )} - - ))} -
    • - ))} -
    - {works && works.length > 0 && ( -

    In this project: {works.join(', ')}.

    - )} - - )} -
    - )} - - {variants.map((v) => ( - - ))} - - {SECTIONS.map(([k, title]) => - section(k) ? ( -
    -

    {title} parameters

    - -
    - ) : null, - )} - - {body && ( -
    -

    Request body

    - -
    - )} - - {op.statuses.length > 0 && ( -
    -

    Responses

    -
      - {op.statuses.map((s) => ( -
    • - {s} {statusName(s)} - {op.mockVariants?.[String(s)]?.map((v) => ( - · {v.title ?? v.name} - ))} -
    • - ))} -
    -
    - )} - - {(long?.examples.length ?? 0) > 1 && ( -
    -

    Examples

    -
      - {long?.examples.map((e) => ( -
    • - -
    • - ))} -
    -
    - )} + {!(page.found && page.replace) && show('description')} + {page.segments.map(segment)} + {show('auth')} + {saved} + {show('path')} + {show('query')} + {show('headers')} + {show('body')} + {show('responses')} + {show('examples')} )}
    diff --git a/packages/ui/src/panel/RequestPanel.tsx b/packages/ui/src/panel/RequestPanel.tsx index f53ed16..3860fd0 100644 --- a/packages/ui/src/panel/RequestPanel.tsx +++ b/packages/ui/src/panel/RequestPanel.tsx @@ -9,7 +9,7 @@ import { useEffect, useMemo, useRef, useState } from 'preact/hooks' import type { Security } from '../auth-options' import { EnvBadge } from '../components/EnvBadge' import type { Variant } from '../engine' -import { fieldDoc, withNote } from '../fielddoc' +import { fieldDoc } from '../fielddoc' import { engine, isStatic, registry, saveFile } from '../runtime' import { type Defs, type JsonSchema, propsOf, unwrap } from '../schema' import { @@ -35,7 +35,6 @@ import { announcement, describeRun } from './announce' import { Body } from './Body' import { DraftCodeSample } from './CodeSample' import { type Draft, draftFrom, forStorage, previewUrl, requestParts } from './draft' -import { useOperationNotes } from './fieldnotes' import { PaperPlane, StopSquare } from './icons' import { type Documented, ParamGrid } from './ParamGrid' import { RequestView } from './RequestView' @@ -128,7 +127,6 @@ export function RequestPanel({ service, op, variants, initial, autoRun }: Props) : undefined const requestNote = useRequestNote(saved?.file) - const opNotes = useOperationNotes(key) const [meta, setMeta] = useState<{ encoding: Encoding; files: string[] }>() const [base, setBase] = useState() const [draft, setDraft] = useState() @@ -247,12 +245,12 @@ export function RequestPanel({ service, op, variants, initial, autoRun }: Props) if (!sec) continue out[s] = propsOf(sec, defs).map((p) => ({ name: p.name, - doc: withNote(fieldDoc(reqSchema, defs, [p.name], [s]), opNotes.notes, s, p.name), + doc: fieldDoc(reqSchema, defs, [p.name], [s]), repeat: unwrap(p.schema, defs).type === 'array', })) } return out - }, [reqSchema, defs, opNotes.notes]) + }, [reqSchema, defs]) const placeholders = useMemo(() => { if (!draft) return [] @@ -689,7 +687,6 @@ export function RequestPanel({ service, op, variants, initial, autoRun }: Props) schema={reqSchema} defs={defs} files={meta?.files} - notes={opNotes.notes} readOnly={!!saved} /> )} @@ -727,10 +724,7 @@ export function RequestPanel({ service, op, variants, initial, autoRun }: Props) security={security} sent={ step?.request ? ( - + ) : undefined } /> diff --git a/packages/ui/src/panel/RequestView.tsx b/packages/ui/src/panel/RequestView.tsx index d7681d6..c066e30 100644 --- a/packages/ui/src/panel/RequestView.tsx +++ b/packages/ui/src/panel/RequestView.tsx @@ -1,7 +1,7 @@ import type { RenderedRequest } from '@specbook/core' import { useMemo, useState } from 'preact/hooks' -import { fieldDoc, withNote } from '../fielddoc' -import { type Defs, type JsonSchema, linePaths, pathString } from '../schema' +import { fieldDoc } from '../fielddoc' +import { type Defs, type JsonSchema, linePaths } from '../schema' import { BodyEditor } from './BodyEditor' import { FieldDoc } from './FieldDoc' import { show } from './short' @@ -21,7 +21,6 @@ export function queryString(query: Record) { export interface RequestDocs { schema?: JsonSchema defs?: Defs - notes?: Map } /** The body as sent, with the documentation of the field the cursor is on below it. */ @@ -32,14 +31,7 @@ function SentBody({ body, docs }: { body: unknown; docs?: RequestDocs }) { const paths = useMemo(() => (documented ? linePaths(text) : []), [documented, text]) const doc = useMemo(() => { const p = paths[line] - return p && docs - ? withNote( - fieldDoc(docs.schema, docs.defs, p, ['data'], body), - docs.notes, - 'data', - pathString(p), - ) - : undefined + return p && docs ? fieldDoc(docs.schema, docs.defs, p, ['data'], body) : undefined }, [paths, line, docs, body]) return ( <> diff --git a/packages/ui/src/panel/fieldnotes-split.ts b/packages/ui/src/panel/fieldnotes-split.ts deleted file mode 100644 index 95d1be4..0000000 --- a/packages/ui/src/panel/fieldnotes-split.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** Section a field belongs to in a request schema (`{ path, query, headers, data }`). */ -export type FieldSection = 'path' | 'query' | 'headers' | 'data' - -const SECTIONS = new Set(['path', 'query', 'headers', 'data']) - -export interface FieldNotes { - /** the page without the field sections */ - intro: string - /** `section.path` -> HTML, e.g. `data.address.city` */ - notes: Map -} - -/** `items[0].price` and `items.price` are the same field. */ -const segments = (s: string) => (s.match(/[^.[\]]+/g) ?? []).filter((p) => !/^\d+$/.test(p)) - -/** The key notes are stored and looked up by. */ -export function noteKey(section: FieldSection, path: string): string { - return [section, ...segments(path)].join('.') -} - -/** A heading's text becomes a key when it names a field: `name`, `data.name`, `query.status`. */ -function headingKey(text: string): string | undefined { - const parts = segments(text.trim()) - if (parts.length === 0) return undefined - const first = parts[0] as string - if (parts.length >= 2 && SECTIONS.has(first)) return parts.join('.') - return ['data', ...parts].join('.') -} - -const plain = (h: string) => - h - .replace(/<[^>]+>/g, '') - .replace(/&/g, '&') - .replace(/</g, '<') - .replace(/>/g, '>') - -/** - * A heading made of one inline code span (`## \`data.name\``) attaches the text under it, up to the next - * heading of that kind, to that field. Everything else stays in the intro. - */ -export function splitFieldNotes(html: string): FieldNotes { - const notes = new Map() - if (!html) return { intro: html, notes } - const intro: string[] = [] - for (const chunk of html.split(/(?=])/)) { - const m = /^]*>\s*([^<]+)<\/code>\s*<\/h\1>/.exec(chunk) - const key = m ? headingKey(plain(m[2] as string)) : undefined - if (m && key) { - const prev = notes.get(key) - const body = chunk.slice(m[0].length) - notes.set(key, prev ? prev + body : body) - } else intro.push(chunk) - } - return { intro: intro.join(''), notes } -} diff --git a/packages/ui/src/panel/includes.ts b/packages/ui/src/panel/includes.ts new file mode 100644 index 0000000..b25b1d2 --- /dev/null +++ b/packages/ui/src/panel/includes.ts @@ -0,0 +1,40 @@ +/** What an author's page can place with `` on a line of its own. */ +export const BLOCKS = [ + 'description', + 'auth', + 'path', + 'query', + 'headers', + 'params', + 'body', + 'responses', + 'examples', +] as const + +export type BlockName = (typeof BLOCKS)[number] + +export type Segment = { html: string } | { block: BlockName } + +const isBlock = (name: string): name is BlockName => (BLOCKS as readonly string[]).includes(name) + +// markdown turns a comment on a line of its own into a block of its own; one inside a sentence stays in its paragraph +const INCLUDE = /(^|\n)/g + +/** + * The page's HTML cut at the places the author put a generated block. A comment that names no block, or that + * sits inside a paragraph, stays where it is (a comment shows nothing). + */ +export function splitIncludes(html: string): Segment[] { + const out: Segment[] = [] + let last = 0 + for (const m of html.matchAll(INCLUDE)) { + const name = m[2] as string + if (!isBlock(name)) continue + const start = (m.index as number) + (m[1] as string).length + if (start > last) out.push({ html: html.slice(last, start) }) + out.push({ block: name }) + last = start + m[0].length - (m[1] as string).length + } + if (last < html.length) out.push({ html: html.slice(last) }) + return out.filter((s) => !('html' in s) || s.html.trim() !== '') +} diff --git a/packages/ui/src/panel/fieldnotes.ts b/packages/ui/src/panel/page.ts similarity index 64% rename from packages/ui/src/panel/fieldnotes.ts rename to packages/ui/src/panel/page.ts index b30c6e1..d6e06f6 100644 --- a/packages/ui/src/panel/fieldnotes.ts +++ b/packages/ui/src/panel/page.ts @@ -1,10 +1,10 @@ import { useEffect, useMemo, useState } from 'preact/hooks' import { registry } from '../runtime' -import { type FieldNotes, splitFieldNotes } from './fieldnotes-split' +import { type Segment, splitIncludes } from './includes' -export { type FieldNotes, type FieldSection, noteKey, splitFieldNotes } from './fieldnotes-split' - -export interface OperationNotes extends FieldNotes { +export interface OperationPage { + /** the page, cut where it places the blocks the viewer generates */ + segments: Segment[] /** the page replaces the spec's description instead of following it */ replace: boolean /** an operation page exists */ @@ -13,10 +13,10 @@ export interface OperationNotes extends FieldNotes { loaded: boolean } -const NONE = { intro: '', notes: new Map(), replace: false, found: false } +const NONE = { segments: [], replace: false, found: false } -/** The markdown that sits with an operation (`...//README.md` or `requests//docs/.md`), split into intro and field notes. */ -export function useOperationNotes(key: string): OperationNotes { +/** The markdown that sits with an operation (`...//README.md` or `requests//docs/.md`). */ +export function useOperationPage(key: string): OperationPage { const [html, setHtml] = useState() const [loaded, setLoaded] = useState(false) const page = registry.docs.find((d) => d.operation === key) @@ -35,6 +35,6 @@ export function useOperationNotes(key: string): OperationNotes { }, [key, page]) return useMemo(() => { if (!page || html === undefined) return { ...NONE, loaded } - return { ...splitFieldNotes(html), replace: !!page.replace, found: true, loaded } + return { segments: splitIncludes(html), replace: !!page.replace, found: true, loaded } }, [html, page, loaded]) } diff --git a/packages/ui/src/styles/panel.css b/packages/ui/src/styles/panel.css index 059b7c3..99cb704 100644 --- a/packages/ui/src/styles/panel.css +++ b/packages/ui/src/styles/panel.css @@ -97,15 +97,76 @@ font-weight: 600; color: var(--sb-text); } - .statuses, .examples, .steps { margin: 0; padding-left: var(--sb-space-4); } - .statuses { - list-style: none; + /* a response is a tab per status; on a phone they wrap onto more lines instead of scrolling */ + .status-tabs { + display: flex; + flex-wrap: wrap; + gap: var(--sb-space-1); + margin-bottom: var(--sb-space-3); + border-bottom: 1px solid var(--sb-border); + } + .status-tabs .rq-tab { + padding: 6px 8px; + } + .body-type { + margin: 0 0 var(--sb-space-2); + font-size: 12.5px; + } + /* the [+] box that opens a field to what is in it */ + /* the box and the name stay on one line, and a name too long for the column breaks inside itself */ + table.fields .field-name { + display: flex; + align-items: baseline; + } + /* a name is the first thing read in a row: larger than the text beside it, and broken only at a dot or underscore (the column is kept wide enough that most never are) */ + table.fields .field-name code { + min-width: 0; + font-size: 14px; + font-weight: 500; + overflow-wrap: break-word; + } + table.fields th:first-child { + width: 30%; + min-width: 12rem; + } + /* [+] opens a field and [−] closes it; the empty box of a plain field keeps the names in line */ + table.fields .expand { + flex: none; + display: inline-block; + box-sizing: border-box; + width: 18px; + height: 18px; + margin: 0 8px 0 0; padding: 0; + border: 1px solid var(--sb-border); + border-radius: 4px; + background: var(--sb-surface); + color: var(--sb-text-muted); + font: 600 13px / 16px var(--sb-font-mono); + text-align: center; + cursor: pointer; + } + /* a row that opens is all one target: the pointer says so, and the row lights up under it */ + table.fields tr.openable, + table.fields tr.openable * { + cursor: pointer; + } + table.fields tr.openable:hover td { + background: var(--sb-surface-raised); + } + table.fields button.expand:hover { + color: var(--sb-text); + border-color: var(--sb-text-muted); + } + table.fields .expand.gap { + border-color: transparent; + background: none; + cursor: default; } .req { color: var(--sb-danger); @@ -1481,18 +1542,6 @@ .doc-project { margin-top: var(--sb-space-3); } - .field-note { - margin-top: var(--sb-space-2); - padding-left: 8px; - border-left: 2px solid var(--sb-accent); - font-size: 12.5px; - } - .field-note > :first-child { - margin-top: 0; - } - .field-note > :last-child { - margin-bottom: 0; - } .step-note-row td { padding-top: 0; border-top: 0; @@ -2210,7 +2259,6 @@ padding-left: var(--indent, 8px); } table.fields td:last-child .doc-inline:not(:empty), - table.fields td:last-child .field-note, table.fields td:last-child .field-doc-enum { display: block; margin-top: 3px; diff --git a/packages/ui/src/viewer/bundles.ts b/packages/ui/src/viewer/bundles.ts index 41d4b77..4eaf324 100644 --- a/packages/ui/src/viewer/bundles.ts +++ b/packages/ui/src/viewer/bundles.ts @@ -41,9 +41,17 @@ export function sortFiles(files: GeneratedFile[]): Parts { else if (parts[0] === 'schemas' && parts[1]?.endsWith('.responses.schema.json')) at(parts[1].replace(/\.responses\.schema\.json$/, '')).responses = trim(f.content) else if (parts[0] === 'docs' && parts[1]?.endsWith('.json')) { - // nothing worth a file or a request: no text, and no examples beyond the generated pair - const d = JSON.parse(f.content) as { description?: string; examples?: unknown[] } - if (d.description || (d.examples?.length ?? 0) > 2) + // nothing worth a file or a request: no text, no response notes, and no examples beyond the generated pair + const d = JSON.parse(f.content) as { + description?: string + examples?: unknown[] + responses?: Record + } + if ( + d.description || + (d.examples?.length ?? 0) > 2 || + Object.keys(d.responses ?? {}).length > 0 + ) at(parts[1].replace(/\.json$/, '')).docs = trim(f.content) } else if (parts[0] === 'examples' && parts.length === 3) { const [, id, file] = parts as [string, string, string] diff --git a/packages/ui/src/virtual.d.ts b/packages/ui/src/virtual.d.ts index a4de93f..184d080 100644 --- a/packages/ui/src/virtual.d.ts +++ b/packages/ui/src/virtual.d.ts @@ -72,11 +72,15 @@ declare module 'virtual:specbook/registry' { export const brandingAssets: Partial Promise>> /** Non-secret variables from `.specbook/environments/.env`, by environment. */ export const environmentVars: Record> - /** Long description and example titles per `service/OperationId`, loaded when its page opens. */ + /** Long description, example titles and what each response is, per `service/OperationId`, loaded when its page opens. */ export const operationDocs: Record< string, () => Promise<{ - default: { description?: string; examples: { name: string; title: string; source: string }[] } + default: { + description?: string + examples: { name: string; title: string; source: string }[] + responses?: Record + } }> > export const operations: Record Promise>> diff --git a/packages/ui/test/browser/app.test.tsx b/packages/ui/test/browser/app.test.tsx index e89dbe0..7d5d86c 100644 --- a/packages/ui/test/browser/app.test.tsx +++ b/packages/ui/test/browser/app.test.tsx @@ -248,14 +248,16 @@ describe('docs and play panel', () => { expect($('.saved-note-doc')?.textContent).toContain('quickest way to find a') }) - it('adds the project page and field notes to the spec tables on the Docs tab', async () => { + it('shows the project page on the Docs tab, with the request body where the page places it', async () => { await mount() go({ kind: 'op', key: 'petstore/AddPet', tab: 'docs' }) await waitFor(() => expect($('.doc-project')?.textContent).toContain('registers it in the store'), ) - // and a field note sits in the field's row - await waitFor(() => expect($('.field-note')?.textContent).toContain('under 40 characters')) + // the page says where the body goes: the table follows its text, and no field has a note of its own + await waitFor(() => expect($('.doc-project')?.textContent).toContain('under 40 characters')) + await waitFor(() => expect($('.doc-project + section table.fields')).toBeTruthy()) + expect($('.field-note')).toBeNull() }) it('is usable at phone width: a settings menu and a full-width panel without sideways scrolling', async () => { diff --git a/packages/ui/test/bundles.test.ts b/packages/ui/test/bundles.test.ts new file mode 100644 index 0000000..0e27dee --- /dev/null +++ b/packages/ui/test/bundles.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { bundleJson, sortFiles } from '../src/viewer/bundles' + +const docs = (id: string, body: unknown) => ({ + path: `docs/${id}.json`, + content: JSON.stringify(body), +}) + +describe('which docs files the viewer keeps', () => { + const kept = (body: unknown) => + JSON.parse(bundleJson(sortFiles([docs('Op', body)]).ops.get('Op'))).docs + + it('keeps one that only says what the responses are', () => { + const responses = { '404': { description: 'No such pet' } } + expect(kept({ examples: [], responses })).toEqual({ examples: [], responses }) + }) + + it('drops one with no text, no response notes and no examples beyond the generated pair', () => { + expect(kept({ examples: [{ name: 'a' }, { name: 'b' }] })).toBeUndefined() + }) + + it('keeps one with a description', () => { + expect(kept({ description: 'Looks a pet up.', examples: [] })).toBeDefined() + }) +}) diff --git a/packages/ui/test/embed-static/embed-static.test.ts b/packages/ui/test/embed-static/embed-static.test.ts index e4b9398..9d62472 100644 --- a/packages/ui/test/embed-static/embed-static.test.ts +++ b/packages/ui/test/embed-static/embed-static.test.ts @@ -48,7 +48,7 @@ const HOST = ` /** * What opening one request may cost beyond the page, gzipped, counting every file the click brings in until the page - * is quiet again: about 102 KB for a small project and 142 KB for the example's four services (the choice of how to authenticate added about 4 KB to each). About 23 KB of that is + * is quiet again: about 103 KB for a small project and 143 KB for the example's four services (the choice of how to authenticate added about 4 KB to each, and the response tables on the Docs tab about 1 KB). About 23 KB of that is * the index of loaders for all 1,874 of the example's operations, which arrives just after the panel appears. A count * that stops when the panel appears misses it some of the time, which is why this waits. Before the lists of services * were fetched one at a time it was about 40 KB more for the whole API (GitHub's list alone is 29 KB). diff --git a/packages/ui/test/markdown.test.ts b/packages/ui/test/markdown.test.ts index 12f3ac9..3533a9f 100644 --- a/packages/ui/test/markdown.test.ts +++ b/packages/ui/test/markdown.test.ts @@ -7,6 +7,27 @@ import { plainText, } from '../src/markdown' +describe('a description written in HTML', () => { + it('is read as the markdown it means, with no tag shown as text', () => { + expect( + markdownToHtml( + '

    Creates a Link.

    See docs.

    ', + ), + ).toBe( + '

    Creates a Link.

    See docs.

    ', + ) + expect(plainText('

    One two

    ')).toBe('One two') + expect(inlineSummary('

    First.

    Second.

    ')).toBe('First.') + }) + + it('leaves text that only looks like a tag, and fenced code, alone', () => { + expect(markdownToHtml('Send as the id.')).toBe('

    Send <name> as the id.

    ') + expect(markdownToHtml('```\n

    x

    \n```')).toBe( + '
    <p>x</p>
    ', + ) + }) +}) + describe('markdownToHtml', () => { it('renders paragraphs, emphasis, code and links', () => { const html = markdownToHtml( diff --git a/packages/ui/test/panel.test.ts b/packages/ui/test/panel.test.ts index a04bca3..5dabd43 100644 --- a/packages/ui/test/panel.test.ts +++ b/packages/ui/test/panel.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest' -import { fieldDoc, keyPath, withNote } from '../src/fielddoc' +import { fieldDoc, keyPath } from '../src/fielddoc' import { draftFrom, previewUrl, requestParts } from '../src/panel/draft' -import { noteKey, splitFieldNotes } from '../src/panel/fieldnotes-split' import { joinGraphql, splitGraphql } from '../src/panel/graphql' +import { splitIncludes } from '../src/panel/includes' import { parsePasted } from '../src/panel/ParamGrid' import { splitStepNotes } from '../src/panel/stepnotes-split' @@ -173,31 +173,33 @@ describe('splitStepNotes', () => { }) }) -describe('field notes', () => { - const html = - '

    Intro.

    Notes

    kept

    name

    short names

    ' + - '

    query.status

    pending is sandbox only

    ' + - '

    data.items[0].price

    in cents

    ' - - it('attaches text under a code heading to the field, and keeps the rest as intro', () => { - const { intro, notes } = splitFieldNotes(html) - expect(intro).toBe('

    Intro.

    Notes

    kept

    ') - expect(notes.get('data.name')).toBe('

    short names

    ') - expect(notes.get('query.status')).toBe('

    pending is sandbox only

    ') - // array indexes are ignored: `items[0].price` is `items.price` - expect(notes.get('data.items.price')).toBe('

    in cents

    ') - }) - - it('looks fields up the same way the editor names them', () => { - expect(noteKey('data', 'items[2].price')).toBe('data.items.price') - expect(noteKey('query', 'status')).toBe('query.status') - }) - - it('adds a note to a field doc only when one exists', () => { - const notes = new Map([['data.name', '

    n

    ']]) - const doc = fieldDoc(request, defs, ['name'], ['data']) - expect(withNote(doc, notes, 'data', 'name')?.note).toBe('

    n

    ') - expect(withNote(doc, notes, 'data', 'status')?.note).toBeUndefined() - expect(withNote(undefined, notes, 'data', 'name')).toBeUndefined() +describe('includes in an author page', () => { + it('cuts the page where a block is placed, on a line of its own', () => { + const html = + '

    Intro.

    \n

    Notes

    after

    \n\n' + expect(splitIncludes(html)).toEqual([ + { html: '

    Intro.

    \n' }, + { block: 'body' }, + { html: '

    Notes

    after

    \n' }, + { block: 'responses' }, + ]) + }) + + it('leaves a comment that is inside a sentence, or names no block, in the text', () => { + const html = + '

    See here.

    \n\n' + expect(splitIncludes(html)).toEqual([{ html }]) + }) + + it('is the whole page when nothing is placed', () => { + expect(splitIncludes('

    a

    ')).toEqual([{ html: '

    a

    ' }]) + expect(splitIncludes('')).toEqual([]) + }) + + it('takes params as one block that stands for path, query and headers', () => { + expect(splitIncludes('

    a

    \n')).toEqual([ + { html: '

    a

    \n' }, + { block: 'params' }, + ]) }) }) diff --git a/packages/ui/test/polymorphism.test.ts b/packages/ui/test/polymorphism.test.ts index d71a518..c478f20 100644 --- a/packages/ui/test/polymorphism.test.ts +++ b/packages/ui/test/polymorphism.test.ts @@ -3,7 +3,7 @@ import { generate } from '@specbook/codegen' import { beforeAll, describe, expect, it } from 'vitest' import { fieldDoc } from '../src/fielddoc' import { jsonCompletions } from '../src/panel/completions' -import { flatten } from '../src/panel/FieldTable' +import { expansion, topRows, visibleRows } from '../src/panel/FieldTable' import { jsonCursor } from '../src/panel/jsonCursor' import { typeInfo, validate } from '../src/schema' @@ -186,31 +186,68 @@ describe('how a union is shown', () => { }) }) - it('lists each variant’s fields under a heading that names it and its tag', () => { - const rows = flatten(shelf, defs).map((r) => - `${' '.repeat(r.depth)}${r.variant ? '— ' : ''}${r.name.split('.').pop()} ${r.type}`.trimEnd(), - ) - expect(rows).toEqual([ + const lines = (rows: { name: string; depth: number; variant?: boolean; type: string }[]) => + rows.map((r) => `${' '.repeat(r.depth)}${r.variant ? '— ' : ''}${r.name} ${r.type}`.trimEnd()) + + it('lists the fields of an object closed, with a union field naming its variants', () => { + expect( + lines(visibleRows(shelf, defs, new Set()).flatMap((s) => ('row' in s ? [s.row] : []))), + ).toEqual([ 'name string', 'items (Book | Album | Zine)[]', ' — Book kind = "book"', - ' kind string', - ' title string', - ' pages integer', - ' related Album[]', - ' kind string', - ' title string', - ' tracks integer', ' — Album kind = "album"', - ' kind string', - ' title string', - ' tracks integer', ' — Zine kind = "Zine"', - ' kind string', - ' title string', - ' issue integer', ]) }) + + it('opens a union field to the fields of each variant, an object among them at the left under its path', () => { + const items = topRows(shelf, defs).find((r) => r.name === 'items') as never + expect(lines(expansion(items, defs))).toEqual([ + ' — Book kind = "book"', + ' kind string', + ' title string', + ' pages integer', + 'items.related Album[]', + ' — Album kind = "album"', + ' kind string', + ' title string', + ' tracks integer', + ' — Zine kind = "Zine"', + ' kind string', + ' title string', + ' issue integer', + ]) + }) + + it('opens an object under an open field in its turn, its fields one step in', () => { + const items = topRows(shelf, defs).find((r) => r.name === 'items') as never + const rows = visibleRows(shelf, defs, new Set(['items', 'items/Book>related'])) + .flatMap((s) => ('row' in s ? [s.row] : [])) + .map((r) => `${' '.repeat(r.depth)}${r.name}`) + const at = rows.indexOf('items.related') + expect(rows.slice(at, at + 4)).toEqual(['items.related', ' kind', ' title', ' tracks']) + expect(items).toBeDefined() + }) + + it('lists a response that is a union as its variants, each with its fields', () => { + expect(lines(topRows(conflict, defs)).slice(0, 4)).toEqual([ + '— OutOfStock error = "OUT_OF_STOCK"', + 'error string', + 'message string', + 'sku string', + ]) + expect( + topRows(conflict, defs) + .filter((r) => r.variant) + .map((r) => r.name), + ).toEqual(['OutOfStock', 'Discontinued']) + }) + + it('lists the fields of the items of a list that is the whole response', () => { + const list = { type: 'array', items: { $ref: 'specbook://books/defs#/$defs/Album' } } + expect(lines(topRows(list, defs))).toEqual(['kind string', 'title string', 'tracks integer']) + }) }) describe('the field a cursor is on, in a list of variants', () => { diff --git a/packages/ui/test/viewer/viewer.test.ts b/packages/ui/test/viewer/viewer.test.ts index f30ef60..6ab45cf 100644 --- a/packages/ui/test/viewer/viewer.test.ts +++ b/packages/ui/test/viewer/viewer.test.ts @@ -278,6 +278,13 @@ describe('the hosted viewer opens a spec at run time', () => { await page.getByRole('tab', { name: 'Docs' }).click() await page.waitForSelector('.doc table.fields') expect(await page.locator('.doc').innerText()).toContain('status') + // the 200 answer is a list of pets: the status tab says so and the table lists a pet's fields + const pane = page.locator('.doc [role=tabpanel]') + expect( + await page.locator('.doc .statuses [role=tab][aria-selected=true]').innerText(), + ).toContain('200') + expect(await pane.locator('.body-type').innerText()).toContain('Pet[]') + expect(await pane.locator('table.fields').innerText()).toContain('photoUrls') expect(errors).toEqual([]) await page.close() }) @@ -459,7 +466,11 @@ describe('the hosted viewer opens a spec at run time', () => { await page.getByRole('tab', { name: 'Docs' }).click() await page.waitForSelector('.doc table.fields tr.variant', { timeout: 10_000 }) expect( - await page.locator('.doc table.fields tr.variant .variant-name').allInnerTexts(), + await page + .locator('.doc table.fields') + .first() + .locator('tr.variant .variant-name') + .allInnerTexts(), ).toEqual(['Book', 'Album', 'Zine']) expect(await page.locator('.doc table.fields').first().innerText()).toContain( '(Book | Album | Zine)[]', @@ -467,6 +478,59 @@ describe('the hosted viewer opens a spec at run time', () => { await page.close() }) + it('documents each status of an operation: what it says, what comes back, and what is in it', async () => { + const { page } = await open(spec('bookstore.json')) + await ready(page) + await goOp(page, 'bookstore/ListShelf') + await page.getByRole('tab', { name: 'Docs' }).click() + await page.waitForSelector('.doc .statuses [role=tab]', { timeout: 10_000 }) + const tabs = await page.locator('.doc .statuses [role=tab]').allInnerTexts() + expect(tabs.map((t) => t.replace(/\s+/g, ' '))).toEqual(['200 OK', '409 Conflict']) + // the answer is a shelf whose items are of three kinds, closed until a person opens them + const pane = page.locator('.doc [role=tabpanel]') + expect(await pane.locator('.body-type').innerText()).toContain('Shelf') + expect(await pane.innerText()).toContain('The shelf') + expect(await pane.locator('tr.variant .variant-name').allInnerTexts()).toEqual([ + 'Book', + 'Album', + 'Zine', + ]) + // the chevron sits on the name's line, not above it + const chevron = await pane.locator('table.fields button.expand').first().boundingBox() + const name = await pane.locator('table.fields .field-name code').nth(1).boundingBox() + expect( + Math.abs( + (chevron?.y ?? 0) + (chevron?.height ?? 0) / 2 - ((name?.y ?? 0) + (name?.height ?? 0) / 2), + ), + ).toBeLessThan(10) + const before = await pane.locator('table.fields tr').count() + await pane.getByRole('button', { name: 'Show what is in items', exact: true }).click() + expect(await pane.locator('table.fields tr').count()).toBeGreaterThan(before) + // an object among them is a group of its own, named by its whole path, opened in its turn + expect(await pane.locator('table.fields').innerText()).toContain('items.related') + // the pointer says the row opens, and a click anywhere on it does, not only on the box + const opens = pane.locator('table.fields tr', { hasText: 'items.related' }) + expect( + await opens + .locator('td') + .nth(2) + .evaluate((e) => getComputedStyle(e).cursor), + ).toBe('pointer') + await pane.locator('table.fields tr', { hasText: 'items.related' }).locator('td').nth(2).click() + expect(await pane.locator('table.fields').innerText()).toContain('tracks') + // the other status is a different answer: two kinds of error, each with its own fields + await page.getByRole('tab', { name: /409/ }).click() + expect(await pane.locator('.body-type').innerText()).toContain('OutOfStock | Discontinued') + expect(await pane.innerText()).toContain('Not available') + expect(await pane.locator('tr.variant .variant-name').allInnerTexts()).toEqual([ + 'OutOfStock', + 'Discontinued', + ]) + expect(await pane.locator('table.fields').innerText()).toContain('sku') + expect(await page.locator('.prism-code-editor').count()).toBe(0) + await page.close() + }) + it('lays a field table out for a phone: stacked, nothing scrolling sideways, a variant’s tag on one line', async () => { const page = await browser.newPage({ viewport: { width: 390, height: 844 } }) await page.goto(`${siteUrl}/v1/?${spec('bookstore.json')}`) @@ -474,6 +538,9 @@ describe('the hosted viewer opens a spec at run time', () => { await goOp(page, 'bookstore/AddItems') await page.getByRole('tab', { name: 'Docs' }).click() await page.waitForSelector('.doc table.fields tr.variant', { timeout: 10_000 }) + // open the list of variants: the fields under it are as far in as any field ever goes + await page.getByRole('button', { name: 'Show what is in items', exact: true }).first().click() + await page.waitForSelector('.doc table.fields tr:has-text("title")') const fit = await page.evaluate(() => [...document.querySelectorAll('table.fields')].map((t) => t.scrollWidth <= t.clientWidth + 1), ) diff --git a/packages/vite/src/index.ts b/packages/vite/src/index.ts index d33aa85..96755ca 100644 --- a/packages/vite/src/index.ts +++ b/packages/vite/src/index.ts @@ -544,9 +544,18 @@ export const loadConfig = ${cfg ? imp(cfg) : '() => Promise.resolve({ default: { if (p.schema) out.schema = await read(p.schema) if (p.responses) out.responses = await read(p.responses) if (p.docs) { - const docs = (await read(p.docs)) as { description?: string; examples?: unknown[] } - // nothing worth a file or a request: no text, and no examples beyond the generated pair - if (docs.description || (docs.examples?.length ?? 0) > 2) out.docs = docs + const docs = (await read(p.docs)) as { + description?: string + examples?: unknown[] + responses?: Record + } + // nothing worth a file or a request: no text, no response notes, and no examples beyond the generated pair + if ( + docs.description || + (docs.examples?.length ?? 0) > 2 || + Object.keys(docs.responses ?? {}).length > 0 + ) + out.docs = docs } const names = Object.keys(p.examples) if (names.length) {