@writedocs/generator 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,135 @@
1
+ // Turns a ReadMe recipe (its `.md` export) into a writedocs page.
2
+ //
3
+ // A recipe is a walkthrough: the complete code in each language, then one
4
+ // `# Heading` per step, each naming the lines of the code it is about:
5
+ //
6
+ // ```python Python <- the code, one fence per language
7
+ // ...
8
+ // ```
9
+ // ```json Response Example <- optional: a fence whose title says "response"
10
+ // ...
11
+ // ```
12
+ //
13
+ // # Encode the credentials
14
+ //
15
+ // <!-- python@10-15 --> <- the step's lines, per language ("6-8,23-24")
16
+ // <!-- csharp@16-21 -->
17
+ //
18
+ // You can get your credentials ...
19
+ //
20
+ // On ReadMe the code sits beside the steps and the step's lines light up
21
+ // as you go. Here: the code goes in <RequestExample> (and responses in
22
+ // <ResponseExample>), which writedocs pins in the right-hand column, and
23
+ // the steps become <Steps>, each with its text and the lines it names, as
24
+ // a <CodeGroup> with one tab per language.
25
+
26
+ import { convertReadmeBody, splitBody, normalizeFenceInfo, jsxAttr } from './readme-mdx.js';
27
+
28
+ const RANGE_RE = /<!--\s*([\w#+.-]+)@([\d,\s-]+)\s*-->/g;
29
+
30
+ /** "6-8,23-24" -> [[6, 8], [23, 24]]. */
31
+ export function parseLineRanges(spec) {
32
+ return String(spec)
33
+ .split(',')
34
+ .map((part) => part.trim())
35
+ .filter(Boolean)
36
+ .map((part) => {
37
+ const [a, b] = part.split('-').map((n) => Number(n.trim()));
38
+ return [a, Number.isFinite(b) ? b : a];
39
+ })
40
+ .filter(([a, b]) => Number.isFinite(a) && a >= 1 && b >= a);
41
+ }
42
+
43
+ /** The lines `ranges` names (1-based, inclusive), ranges apart joined by
44
+ * an empty line, with their common indentation removed. */
45
+ export function sliceLines(lines, ranges) {
46
+ const parts = ranges.map(([a, b]) => lines.slice(a - 1, b)).filter((p) => p.length);
47
+ const all = parts.flat().filter((l) => l.trim());
48
+ const indent = all.length ? Math.min(...all.map((l) => /^\s*/.exec(l)[0].length)) : 0;
49
+ return parts.map((p) => p.map((l) => l.slice(indent)).join('\n')).join('\n\n');
50
+ }
51
+
52
+ /** Strips the export's frontmatter and its `# Title` line. */
53
+ function splitTitle(markdown) {
54
+ let md = String(markdown ?? '').replace(/\r\n?/g, '\n').replace(/^---\n[\s\S]*?\n---\n/, '');
55
+ const m = /^\s*#\s+(.+?)\s*\n/.exec(md);
56
+ let title = null;
57
+ if (m) {
58
+ title = m[1].trim();
59
+ md = md.slice(m[0].length);
60
+ }
61
+ return { title, body: md };
62
+ }
63
+
64
+ /**
65
+ * @param {string} markdown the recipe's .md export
66
+ * @param {object} ctx as for convertReadmeBody
67
+ * @returns {{ title: string | null, body: string }}
68
+ */
69
+ export function convertRecipe(markdown, ctx) {
70
+ const { title, body } = splitTitle(markdown);
71
+ const segments = splitBody(body);
72
+
73
+ // The leading code fences, before the first step heading.
74
+ const code = [];
75
+ let s = 0;
76
+ while (s < segments.length) {
77
+ const seg = segments[s];
78
+ if (seg.kind === 'code') code.push(seg);
79
+ else if (seg.kind !== 'text' || seg.lines.some((l) => /^#{1,6}\s/.test(l))) break;
80
+ else if (seg.lines.some((l) => l.trim())) break;
81
+ s++;
82
+ }
83
+ const rest = segments.slice(s);
84
+
85
+ const isResponse = (seg) => /response/i.test(seg.info);
86
+ const requests = code.filter((c) => !isResponse(c));
87
+ const responses = code.filter(isResponse);
88
+ const byLang = new Map(requests.map((c) => [c.info.split(/\s+/)[0].toLowerCase(), c]));
89
+ const fence = (c, text) => ['```' + normalizeFenceInfo(c.info, { inGroup: true }), text, '```'].join('\n');
90
+ const exampleBlock = (tag, blocks) => (blocks.length ? `<${tag}>\n${blocks.map((c) => fence(c, c.body.join('\n'))).join('\n\n')}\n</${tag}>` : '');
91
+
92
+ // The steps: split the rest of the page at its top-level headings.
93
+ const restText = rest
94
+ .map((seg) => (seg.kind === 'text' ? seg.lines.join('\n') : seg.kind === 'code' ? [seg.indent + seg.marks + seg.info, ...seg.body, seg.indent + seg.marks].join('\n') : `<HTMLBlock>{\`${seg.html}\`}</HTMLBlock>`))
95
+ .join('\n');
96
+ const steps = [];
97
+ const intro = [];
98
+ let current = null;
99
+ let inFence = false;
100
+ for (const line of restText.split('\n')) {
101
+ if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
102
+ const h = !inFence && /^#\s+(.+?)\s*#*\s*$/.exec(line);
103
+ if (h) {
104
+ current = { title: h[1], lines: [] };
105
+ steps.push(current);
106
+ } else (current ? current.lines : intro).push(line);
107
+ }
108
+
109
+ const parts = [];
110
+ const introText = convertReadmeBody(intro.join('\n'), ctx);
111
+ if (introText) parts.push(introText);
112
+ const req = exampleBlock('RequestExample', requests);
113
+ if (req) parts.push(req);
114
+ const res = exampleBlock('ResponseExample', responses);
115
+ if (res) parts.push(res);
116
+
117
+ if (steps.length) {
118
+ const rendered = steps.map((step) => {
119
+ const text = step.lines.join('\n');
120
+ const excerpts = [];
121
+ for (const m of text.matchAll(RANGE_RE)) {
122
+ const c = byLang.get(m[1].toLowerCase());
123
+ if (!c) continue;
124
+ const lines = sliceLines(c.body, parseLineRanges(m[2]));
125
+ if (lines.trim()) excerpts.push(fence(c, lines));
126
+ }
127
+ const description = convertReadmeBody(text.replace(RANGE_RE, ''), ctx);
128
+ const code = excerpts.length > 1 ? `<CodeGroup>\n${excerpts.join('\n')}\n</CodeGroup>` : excerpts[0] ?? '';
129
+ const inner = [description, code].filter(Boolean).join('\n\n');
130
+ return `<Step ${jsxAttr('title', step.title)}>\n\n${inner}\n\n</Step>`;
131
+ });
132
+ parts.push(`<Steps>\n\n${rendered.join('\n\n')}\n\n</Steps>`);
133
+ }
134
+ return { title, body: parts.join('\n\n') };
135
+ }
@@ -1491,12 +1491,71 @@ const components = {
1491
1491
  .wd-toc-col:has(.wd-example-host:not(:empty)) {
1492
1492
  width: 340px;
1493
1493
  }
1494
+ /* A flex column of the visible height, so a docked request/response
1495
+ example is held to it and scrolls its code inside its own frame
1496
+ (below) rather than the whole column scrolling - the tab strip and
1497
+ copy button stay in view. `height`, not only max-height: the examples
1498
+ share the column out of a definite height (flex-basis 0 below), which
1499
+ an auto-height column would collapse to nothing. It adds no page
1500
+ height - docking is desktop-only, where the sidebar column is already
1501
+ this tall (Sidebar.astro). The column's own overflow-y is left as the
1502
+ fallback for what can't shrink: a Panel's content, or several
1503
+ examples' tab strips that don't fit together. The [hidden] rule is
1504
+ needed because display: flex would otherwise beat the attribute
1505
+ undock() sets, leaving the empty host's padding above the table of
1506
+ contents. */
1494
1507
  .wd-example-host {
1495
1508
  position: sticky;
1496
1509
  top: var(--wd-topbar-offset, 5rem);
1497
- max-height: calc(100vh - var(--wd-topbar-offset, 5rem));
1510
+ height: calc(100vh - var(--wd-topbar-offset, 5rem));
1498
1511
  overflow-y: auto;
1499
1512
  padding: 1.5rem 0 1.5rem 0.5rem;
1513
+ display: flex;
1514
+ flex-direction: column;
1515
+ }
1516
+ .wd-example-host[hidden] {
1517
+ display: none;
1518
+ }
1519
+ /* Docked RequestExample/ResponseExample panels split the column evenly
1520
+ (flex 1 1 0), each capped at its own content's height (max-height:
1521
+ max-content) - so a short response keeps its full size and a long
1522
+ request takes the rest; two long ones get half each. Inside a panel,
1523
+ the shown block's <pre> is the part that gives way: the chain down
1524
+ to it (the .wd-codegroup, the shown .wd-code-block) is a flex column
1525
+ with min-height: 0, so the height limit reaches the <pre>, and the
1526
+ tab strip, dropdown, title bar and expand button keep their size. A
1527
+ Panel (.wd-panel) isn't in this chain: it keeps its content's height,
1528
+ and the column scrolls. A hidden tab's inline display: none still
1529
+ beats the display: flex here. */
1530
+ .wd-example-host > .wd-request-example,
1531
+ .wd-example-host > .wd-response-example {
1532
+ display: flex;
1533
+ flex-direction: column;
1534
+ flex: 1 1 0;
1535
+ max-height: max-content;
1536
+ min-height: 0;
1537
+ }
1538
+ .wd-example-host > .wd-example-panel > .wd-codegroup,
1539
+ .wd-example-host > .wd-example-panel > .wd-codegroup > .wd-code-block {
1540
+ display: flex;
1541
+ flex-direction: column;
1542
+ flex: 0 1 auto;
1543
+ min-height: 0;
1544
+ }
1545
+ .wd-example-host > .wd-panel,
1546
+ .wd-example-host > .wd-example-panel > .wd-codegroup > :not(.wd-code-block),
1547
+ .wd-example-host > .wd-example-panel > .wd-codegroup > .wd-code-block > :not(pre) {
1548
+ flex: none;
1549
+ }
1550
+ .wd-example-host > .wd-example-panel > .wd-codegroup > .wd-code-block > pre.astro-code {
1551
+ flex: 0 1 auto;
1552
+ min-height: 0;
1553
+ }
1554
+ /* In :where() so it stays weaker than an `expandable` block's collapsed
1555
+ overflow-y: hidden (components.css) - a collapsed block is clipped
1556
+ with its "Show more" button, as anywhere else. */
1557
+ :where(.wd-example-host > .wd-example-panel > .wd-codegroup > .wd-code-block > pre.astro-code) {
1558
+ overflow-y: auto;
1500
1559
  }
1501
1560
  /* Spacing between multiple docked panels (e.g. Request above
1502
1561
  Response) is this wrapper's own job only once docked - inline