sendproof-core 0.1.0.alpha.1

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.
Files changed (229) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +55 -0
  4. data/lib/sendproof/assets.rb +70 -0
  5. data/lib/sendproof/attribution.rb +98 -0
  6. data/lib/sendproof/capture.rb +66 -0
  7. data/lib/sendproof/clock.rb +54 -0
  8. data/lib/sendproof/configuration.rb +241 -0
  9. data/lib/sendproof/data_store.rb +34 -0
  10. data/lib/sendproof/dynamodb/store.rb +183 -0
  11. data/lib/sendproof/dynamodb.rb +17 -0
  12. data/lib/sendproof/elasticsearch/store.rb +24 -0
  13. data/lib/sendproof/elasticsearch.rb +17 -0
  14. data/lib/sendproof/firestore/interceptor.rb +38 -0
  15. data/lib/sendproof/firestore/store.rb +150 -0
  16. data/lib/sendproof/firestore.rb +99 -0
  17. data/lib/sendproof/handler.rb +23 -0
  18. data/lib/sendproof/identity.rb +37 -0
  19. data/lib/sendproof/limits.rb +113 -0
  20. data/lib/sendproof/middleware.rb +68 -0
  21. data/lib/sendproof/mongo/engine.rb +692 -0
  22. data/lib/sendproof/mongo/guarded.rb +100 -0
  23. data/lib/sendproof/mongo/plain.rb +45 -0
  24. data/lib/sendproof/mongo/store.rb +54 -0
  25. data/lib/sendproof/mongo/subscriber.rb +21 -0
  26. data/lib/sendproof/mongo.rb +41 -0
  27. data/lib/sendproof/mongoid/store.rb +58 -0
  28. data/lib/sendproof/mongoid.rb +65 -0
  29. data/lib/sendproof/observed_request.rb +108 -0
  30. data/lib/sendproof/opensearch/store.rb +21 -0
  31. data/lib/sendproof/opensearch.rb +17 -0
  32. data/lib/sendproof/operation_matcher.rb +28 -0
  33. data/lib/sendproof/pool_hooks.rb +80 -0
  34. data/lib/sendproof/preview_request.rb +44 -0
  35. data/lib/sendproof/preview_transport.rb +331 -0
  36. data/lib/sendproof/protocol.rb +81 -0
  37. data/lib/sendproof/provider.rb +83 -0
  38. data/lib/sendproof/recorder.rb +298 -0
  39. data/lib/sendproof/redaction.rb +98 -0
  40. data/lib/sendproof/redis/commands.rb +76 -0
  41. data/lib/sendproof/redis/store.rb +205 -0
  42. data/lib/sendproof/redis.rb +18 -0
  43. data/lib/sendproof/search/middleware.rb +39 -0
  44. data/lib/sendproof/search/store.rb +213 -0
  45. data/lib/sendproof/search.rb +82 -0
  46. data/lib/sendproof/stores/classify.rb +346 -0
  47. data/lib/sendproof/stores/guard.rb +127 -0
  48. data/lib/sendproof/stores/tables.rb +1328 -0
  49. data/lib/sendproof/stores.rb +12 -0
  50. data/lib/sendproof/trace_store.rb +110 -0
  51. data/lib/sendproof/transaction_control.rb +187 -0
  52. data/lib/sendproof/ui/action-bar.js +91 -0
  53. data/lib/sendproof/ui/api.js +239 -0
  54. data/lib/sendproof/ui/app.css +848 -0
  55. data/lib/sendproof/ui/app.js +742 -0
  56. data/lib/sendproof/ui/autofill.js +137 -0
  57. data/lib/sendproof/ui/code-copy.js +71 -0
  58. data/lib/sendproof/ui/code-picker.js +149 -0
  59. data/lib/sendproof/ui/commands.js +197 -0
  60. data/lib/sendproof/ui/components.js +77 -0
  61. data/lib/sendproof/ui/context-bar.js +82 -0
  62. data/lib/sendproof/ui/copy.js +92 -0
  63. data/lib/sendproof/ui/coverage-popover.js +35 -0
  64. data/lib/sendproof/ui/crumb-fit.js +80 -0
  65. data/lib/sendproof/ui/deprecation.js +164 -0
  66. data/lib/sendproof/ui/display-settings.js +175 -0
  67. data/lib/sendproof/ui/doc-diff.js +209 -0
  68. data/lib/sendproof/ui/docs-view.js +347 -0
  69. data/lib/sendproof/ui/favicon.png +0 -0
  70. data/lib/sendproof/ui/favicon.svg +1 -0
  71. data/lib/sendproof/ui/field-help.js +52 -0
  72. data/lib/sendproof/ui/field-modules.js +23 -0
  73. data/lib/sendproof/ui/fields/controls.js +179 -0
  74. data/lib/sendproof/ui/fields/dom.js +36 -0
  75. data/lib/sendproof/ui/fields/infer.js +71 -0
  76. data/lib/sendproof/ui/fields/lookup-source.js +63 -0
  77. data/lib/sendproof/ui/fields/lookup.js +285 -0
  78. data/lib/sendproof/ui/fields/render.js +496 -0
  79. data/lib/sendproof/ui/fields/select.js +175 -0
  80. data/lib/sendproof/ui/fields/validate.js +363 -0
  81. data/lib/sendproof/ui/fields/validation-formats.js +164 -0
  82. data/lib/sendproof/ui/fields/validation-references.js +68 -0
  83. data/lib/sendproof/ui/fields/validation-values.js +137 -0
  84. data/lib/sendproof/ui/generate-menu.js +44 -0
  85. data/lib/sendproof/ui/generate.js +184 -0
  86. data/lib/sendproof/ui/header-editor.js +777 -0
  87. data/lib/sendproof/ui/headers.js +188 -0
  88. data/lib/sendproof/ui/highlight.js +257 -0
  89. data/lib/sendproof/ui/history-popover.js +24 -0
  90. data/lib/sendproof/ui/i18n.js +253 -0
  91. data/lib/sendproof/ui/icons.js +87 -0
  92. data/lib/sendproof/ui/index.html +70 -0
  93. data/lib/sendproof/ui/issues.js +187 -0
  94. data/lib/sendproof/ui/json-view.js +166 -0
  95. data/lib/sendproof/ui/lang-icons.js +62 -0
  96. data/lib/sendproof/ui/layout.js +262 -0
  97. data/lib/sendproof/ui/listbox.js +334 -0
  98. data/lib/sendproof/ui/locales/ar-capture.js +366 -0
  99. data/lib/sendproof/ui/locales/ar-stores.js +116 -0
  100. data/lib/sendproof/ui/locales/ar.js +561 -0
  101. data/lib/sendproof/ui/locales/cs-capture.js +442 -0
  102. data/lib/sendproof/ui/locales/cs-stores.js +116 -0
  103. data/lib/sendproof/ui/locales/cs.js +689 -0
  104. data/lib/sendproof/ui/locales/da-capture.js +347 -0
  105. data/lib/sendproof/ui/locales/da-stores.js +116 -0
  106. data/lib/sendproof/ui/locales/da.js +522 -0
  107. data/lib/sendproof/ui/locales/de-capture.js +347 -0
  108. data/lib/sendproof/ui/locales/de-stores.js +116 -0
  109. data/lib/sendproof/ui/locales/de.js +519 -0
  110. data/lib/sendproof/ui/locales/el-capture.js +347 -0
  111. data/lib/sendproof/ui/locales/el-stores.js +116 -0
  112. data/lib/sendproof/ui/locales/el.js +520 -0
  113. data/lib/sendproof/ui/locales/en-capture.js +349 -0
  114. data/lib/sendproof/ui/locales/en-stores.js +95 -0
  115. data/lib/sendproof/ui/locales/en.js +522 -0
  116. data/lib/sendproof/ui/locales/es-capture.js +353 -0
  117. data/lib/sendproof/ui/locales/es-stores.js +116 -0
  118. data/lib/sendproof/ui/locales/es.js +525 -0
  119. data/lib/sendproof/ui/locales/fa-capture.js +348 -0
  120. data/lib/sendproof/ui/locales/fa-stores.js +116 -0
  121. data/lib/sendproof/ui/locales/fa.js +521 -0
  122. data/lib/sendproof/ui/locales/fi-capture.js +347 -0
  123. data/lib/sendproof/ui/locales/fi-stores.js +116 -0
  124. data/lib/sendproof/ui/locales/fi.js +523 -0
  125. data/lib/sendproof/ui/locales/fr-capture.js +353 -0
  126. data/lib/sendproof/ui/locales/fr-stores.js +116 -0
  127. data/lib/sendproof/ui/locales/fr.js +525 -0
  128. data/lib/sendproof/ui/locales/he-capture.js +358 -0
  129. data/lib/sendproof/ui/locales/he-stores.js +116 -0
  130. data/lib/sendproof/ui/locales/he.js +529 -0
  131. data/lib/sendproof/ui/locales/hi-capture.js +348 -0
  132. data/lib/sendproof/ui/locales/hi-stores.js +116 -0
  133. data/lib/sendproof/ui/locales/hi.js +523 -0
  134. data/lib/sendproof/ui/locales/id-capture.js +347 -0
  135. data/lib/sendproof/ui/locales/id-stores.js +116 -0
  136. data/lib/sendproof/ui/locales/id.js +521 -0
  137. data/lib/sendproof/ui/locales/it-capture.js +361 -0
  138. data/lib/sendproof/ui/locales/it-stores.js +116 -0
  139. data/lib/sendproof/ui/locales/it.js +523 -0
  140. data/lib/sendproof/ui/locales/ja-capture.js +346 -0
  141. data/lib/sendproof/ui/locales/ja-stores.js +116 -0
  142. data/lib/sendproof/ui/locales/ja.js +521 -0
  143. data/lib/sendproof/ui/locales/ko-capture.js +346 -0
  144. data/lib/sendproof/ui/locales/ko-stores.js +116 -0
  145. data/lib/sendproof/ui/locales/ko.js +522 -0
  146. data/lib/sendproof/ui/locales/nb-capture.js +349 -0
  147. data/lib/sendproof/ui/locales/nb-stores.js +116 -0
  148. data/lib/sendproof/ui/locales/nb.js +521 -0
  149. data/lib/sendproof/ui/locales/nl-capture.js +355 -0
  150. data/lib/sendproof/ui/locales/nl-stores.js +116 -0
  151. data/lib/sendproof/ui/locales/nl.js +520 -0
  152. data/lib/sendproof/ui/locales/pl-capture.js +432 -0
  153. data/lib/sendproof/ui/locales/pl-stores.js +116 -0
  154. data/lib/sendproof/ui/locales/pl.js +528 -0
  155. data/lib/sendproof/ui/locales/pt-BR-capture.js +350 -0
  156. data/lib/sendproof/ui/locales/pt-BR-stores.js +116 -0
  157. data/lib/sendproof/ui/locales/pt-BR.js +523 -0
  158. data/lib/sendproof/ui/locales/pt-PT-capture.js +350 -0
  159. data/lib/sendproof/ui/locales/pt-PT-stores.js +116 -0
  160. data/lib/sendproof/ui/locales/pt-PT.js +523 -0
  161. data/lib/sendproof/ui/locales/ru-capture.js +437 -0
  162. data/lib/sendproof/ui/locales/ru-stores.js +116 -0
  163. data/lib/sendproof/ui/locales/ru.js +624 -0
  164. data/lib/sendproof/ui/locales/sv-capture.js +349 -0
  165. data/lib/sendproof/ui/locales/sv-stores.js +116 -0
  166. data/lib/sendproof/ui/locales/sv.js +518 -0
  167. data/lib/sendproof/ui/locales/th-capture.js +347 -0
  168. data/lib/sendproof/ui/locales/th-stores.js +116 -0
  169. data/lib/sendproof/ui/locales/th.js +521 -0
  170. data/lib/sendproof/ui/locales/tr-capture.js +348 -0
  171. data/lib/sendproof/ui/locales/tr-stores.js +116 -0
  172. data/lib/sendproof/ui/locales/tr.js +521 -0
  173. data/lib/sendproof/ui/locales/uk-capture.js +442 -0
  174. data/lib/sendproof/ui/locales/uk-stores.js +116 -0
  175. data/lib/sendproof/ui/locales/uk.js +630 -0
  176. data/lib/sendproof/ui/locales/vi-capture.js +346 -0
  177. data/lib/sendproof/ui/locales/vi-stores.js +116 -0
  178. data/lib/sendproof/ui/locales/vi.js +523 -0
  179. data/lib/sendproof/ui/locales/zh-Hans-capture.js +347 -0
  180. data/lib/sendproof/ui/locales/zh-Hans-stores.js +116 -0
  181. data/lib/sendproof/ui/locales/zh-Hans.js +523 -0
  182. data/lib/sendproof/ui/locales/zh-Hant-capture.js +346 -0
  183. data/lib/sendproof/ui/locales/zh-Hant-stores.js +116 -0
  184. data/lib/sendproof/ui/locales/zh-Hant.js +522 -0
  185. data/lib/sendproof/ui/manifest.json +866 -0
  186. data/lib/sendproof/ui/markdown.js +39 -0
  187. data/lib/sendproof/ui/model-view.js +182 -0
  188. data/lib/sendproof/ui/navigation.js +233 -0
  189. data/lib/sendproof/ui/operation-header.js +76 -0
  190. data/lib/sendproof/ui/operations.js +7 -0
  191. data/lib/sendproof/ui/overview-view.js +63 -0
  192. data/lib/sendproof/ui/personas.js +59 -0
  193. data/lib/sendproof/ui/popover.js +71 -0
  194. data/lib/sendproof/ui/preview-false.js +108 -0
  195. data/lib/sendproof/ui/request-editor.js +496 -0
  196. data/lib/sendproof/ui/response-metadata.js +354 -0
  197. data/lib/sendproof/ui/response-viewer.js +618 -0
  198. data/lib/sendproof/ui/result-blocked.js +155 -0
  199. data/lib/sendproof/ui/result-capture.js +25 -0
  200. data/lib/sendproof/ui/result-database.js +185 -0
  201. data/lib/sendproof/ui/result-effects.js +176 -0
  202. data/lib/sendproof/ui/result-headers.js +106 -0
  203. data/lib/sendproof/ui/result-logs.js +408 -0
  204. data/lib/sendproof/ui/result-states.js +213 -0
  205. data/lib/sendproof/ui/results.js +371 -0
  206. data/lib/sendproof/ui/router.js +118 -0
  207. data/lib/sendproof/ui/schema-model.js +336 -0
  208. data/lib/sendproof/ui/schema-tree.js +344 -0
  209. data/lib/sendproof/ui/schema.js +397 -0
  210. data/lib/sendproof/ui/security.js +31 -0
  211. data/lib/sendproof/ui/seeded-menu.js +69 -0
  212. data/lib/sendproof/ui/settings.js +93 -0
  213. data/lib/sendproof/ui/shortcuts-sheet.js +73 -0
  214. data/lib/sendproof/ui/shortcuts.js +190 -0
  215. data/lib/sendproof/ui/sidebar.js +289 -0
  216. data/lib/sendproof/ui/signin.js +259 -0
  217. data/lib/sendproof/ui/snippets.js +530 -0
  218. data/lib/sendproof/ui/store-marks.js +47 -0
  219. data/lib/sendproof/ui/stores.js +131 -0
  220. data/lib/sendproof/ui/styles.css +971 -0
  221. data/lib/sendproof/ui/toggletip.js +53 -0
  222. data/lib/sendproof/ui/uuid.js +10 -0
  223. data/lib/sendproof/ui/view.js +122 -0
  224. data/lib/sendproof/ui/views.css +653 -0
  225. data/lib/sendproof/version.rb +9 -0
  226. data/lib/sendproof/workbench.rb +102 -0
  227. data/lib/sendproof-core.rb +3 -0
  228. data/lib/sendproof.rb +121 -0
  229. metadata +292 -0
@@ -0,0 +1,137 @@
1
+ import { esc, icon } from './components.js';
2
+ import { formatTime, t } from './i18n.js';
3
+ import { randomValid } from './generate.js';
4
+ import { resolveSchema, sampleValue } from './schema.js';
5
+ import { inferLookup } from './fields/infer.js';
6
+ import { fromLastResponse, getLookupOptions } from './fields/lookup-source.js';
7
+ import { newUuid } from './uuid.js';
8
+ import { matchesShortcut, shortcutAttrs, shortcutHint } from './shortcuts.js';
9
+
10
+ function type(schema) {
11
+ return (Array.isArray(schema.type) ? schema.type.find(item => item !== 'null') : schema.type) ||
12
+ (schema.properties ? 'object' : schema.items ? 'array' : undefined);
13
+ }
14
+
15
+ /** Fill a draft from documented examples, in-scope lookup records, and schema samples. */
16
+ export async function fillDraft(raw, draft, example, context, { all = false, regenerate = false } = {}, path = [], refs = new Set()) {
17
+ if (raw?.$ref && refs.has(raw.$ref)) return draft;
18
+ const schema = context.resolve(raw);
19
+ if (schema.readOnly) return draft;
20
+ const nextRefs = raw?.$ref ? new Set([...refs, raw.$ref]) : refs;
21
+ if (schema.properties && (draft == null || typeof draft === 'object' && !Array.isArray(draft))) {
22
+ const fields = Object.entries(schema.properties).filter(([key, child]) =>
23
+ !context.resolve(child).readOnly && (regenerate || all || schema.required?.includes(key)));
24
+ const values = await Promise.all(fields.map(async ([key, child]) => [
25
+ key,
26
+ await fillDraft(child, draft?.[key], example?.[key], context, { all, regenerate }, [...path, key], nextRefs),
27
+ ]));
28
+ return Object.fromEntries([...Object.entries(draft ?? {}), ...values.filter(([, value]) => value !== undefined)]);
29
+ }
30
+ if (type(schema) === 'array' && Array.isArray(draft) && regenerate) {
31
+ return Promise.all(draft.map((child, index) =>
32
+ fillDraft(schema.items, child, undefined, context, { regenerate }, [...path, index], nextRefs)));
33
+ }
34
+ const lookup = inferLookup(context, schema, String(path.at(-1) || ''));
35
+ if (regenerate) {
36
+ if (lookup || schema.format !== 'uuid' || draft == null) return draft;
37
+ return newUuid();
38
+ }
39
+ if (draft !== undefined && draft !== null && draft !== '') return draft;
40
+ let value;
41
+ let source;
42
+ if (lookup) {
43
+ try {
44
+ const last = fromLastResponse(context.lastResponse, lookup);
45
+ const records = await getLookupOptions(context, lookup);
46
+ value = records.find(option => Object.is(option.value, example))?.value ?? last?.value ?? records[0]?.value;
47
+ source = context.actor ? t('gen.realRecordAs', { name: context.actor }) : t('gen.realRecord');
48
+ } catch {
49
+ // A failed lookup leaves its ID editable instead of inventing a record.
50
+ }
51
+ } else if (example !== undefined) {
52
+ value = example;
53
+ source = t('gen.fromExample');
54
+ } else {
55
+ // Random within the schema's constraints, so repeated previews don't all look the same.
56
+ const generated = randomValid(schema, draft);
57
+ value = generated ? generated.value : sampleValue(raw, context.document);
58
+ source = generated?.source ?? t('gen.fromSchema');
59
+ }
60
+ if (value !== undefined) context.filled.set(JSON.stringify(path), source);
61
+ return value;
62
+ }
63
+
64
+ export function autofillContext(document, basePath, operationPath, lastResponse, lookupCache, filled, actor) {
65
+ return { document, basePath, operationPath, lastResponse, lookupCache, filled, actor, resolve: schema => resolveSchema(schema, document), kind: type };
66
+ }
67
+
68
+ const items = [
69
+ ['required', 'wand', 'shortcut.autofill-required', 'fill.requiredSub'],
70
+ ['all', 'list', 'shortcut.autofill-all', 'fill.allSub'],
71
+ ['reuse', 'history', 'shortcut.autofill-reuse', ''],
72
+ ['ids', 'refresh', 'fill.ids', 'fill.idsSub'],
73
+ ['clear', 'trash', 'shortcut.autofill-clear', ''],
74
+ ];
75
+
76
+ /** Open a keyboard-operable menu without adding anything to the form's flow. */
77
+ export function showAutofillMenu(anchor, { history, onSelect, canRegenerate, lookupActor, optionalCount = 0 }) {
78
+ const request = anchor.closest('.request');
79
+ if (!request) return;
80
+ const previous = request.querySelector('.autofill-pop');
81
+ if (previous) { previous.closeMenu(true); return; }
82
+ function markup([id, glyph, text, hint]) {
83
+ if ((id === 'reuse' && !history) || (id === 'ids' && !canRegenerate)) return '';
84
+ const secondary = id === 'reuse' ? `${history.op.title} · ${formatTime(history.when)}` : hint ? t(hint, { n: optionalCount }) : '';
85
+ return `<button type="button" class="opt-row" role="menuitem" data-fill="${id}" ${shortcutAttrs('autofill-' + id)}>${icon(glyph, true)}<span class="stack">
86
+ <span class="main"${id === 'clear' ? ' style="font-weight:400"' : ''}>${esc(t(text))}</span>${secondary ? `<span class="sub">${esc(secondary)}</span>` : ''}
87
+ </span><span class="end">${shortcutHint('autofill-' + id)}</span></button>`;
88
+ }
89
+ request.insertAdjacentHTML('beforeend', `<div class="pop autofill-pop" id="autofill-menu" role="menu" aria-label="${esc(t('req.autofill'))}">
90
+ <div class="pop-group">${items.slice(0, -1).map(markup).join('')}</div>
91
+ <div class="pop-group">${markup(items.at(-1))}</div>
92
+ ${lookupActor ? `<div class="pop-foot">${icon('db', true)}<span>${esc(t('fill.realIds', { name: lookupActor }))}</span></div>` : ''}
93
+ </div>`);
94
+ const menu = request.querySelector('.autofill-pop');
95
+ const bounds = request.getBoundingClientRect();
96
+ const trigger = anchor.getBoundingClientRect();
97
+ const rtl = document.documentElement.dir === 'rtl';
98
+ menu.style.top = `${trigger.bottom - bounds.top + 4}px`;
99
+ menu.style.insetInlineEnd = `${rtl ? trigger.left - bounds.left : bounds.right - trigger.right}px`;
100
+ anchor.setAttribute('aria-expanded', 'true');
101
+ const controllers = new AbortController();
102
+ const signal = controllers.signal;
103
+ const close = (restore = false) => {
104
+ controllers.abort();
105
+ menu.remove();
106
+ anchor.setAttribute('aria-expanded', 'false');
107
+ if (restore) anchor.focus();
108
+ };
109
+ menu.closeMenu = close;
110
+ const buttons = [...menu.querySelectorAll('button')];
111
+ const focus = index => {
112
+ buttons.forEach((button, i) => button.classList.toggle('is-active', index === i));
113
+ buttons[index]?.focus();
114
+ };
115
+ focus(0);
116
+ menu.addEventListener('keydown', event => {
117
+ const key = ['down', 'up', 'home', 'end', 'escape'].find(id => matchesShortcut(id, event));
118
+ if (!key) return;
119
+ event.preventDefault();
120
+ event.stopPropagation();
121
+ if (key === 'escape') return close(true);
122
+ const index = buttons.indexOf(document.activeElement);
123
+ const next = key === 'home' ? 0 : key === 'end' ? buttons.length - 1 :
124
+ (index + (key === 'down' ? 1 : -1) + buttons.length) % buttons.length;
125
+ focus(next);
126
+ }, { signal });
127
+ menu.addEventListener('click', event => {
128
+ const choice = event.target.closest('[data-fill]')?.dataset.fill;
129
+ if (!choice) return;
130
+ close(true);
131
+ onSelect(choice);
132
+ }, { signal });
133
+ document.addEventListener('pointerdown', event => {
134
+ if (!menu.contains(event.target) && !anchor.contains(event.target)) close();
135
+ }, { signal });
136
+ request.querySelector('.pane-scroll').addEventListener('scroll', () => close(), { once: true, signal });
137
+ }
@@ -0,0 +1,71 @@
1
+ // Copying from a code viewer puts only the code on the clipboard.
2
+ //
3
+ // A code view is a grid of lines: a line number, a fold button, the source and hover actions. The
4
+ // browser's own copy walks that grid and picks up the numbers and button labels, and the source
5
+ // text itself has lost its indentation because the viewer indents with padding (--d, in 2-space
6
+ // steps). So one `copy` listener on the document rebuilds the text: for each selected line, the
7
+ // selected part of its source, with the indentation put back wherever the selection starts at the
8
+ // beginning of a line, and lines joined by newlines. A collapsed node's "N keys" badge copies as an
9
+ // ellipsis. Selections outside a code view, or across several of them, keep the native copy
10
+ // (the gutter is user-select: none, so those carry no numbers either).
11
+
12
+ /** Spaces per nesting level in the viewer (matches JSON.stringify(value, null, 2)). */
13
+ export const INDENT = ' ';
14
+
15
+ /**
16
+ * Joins selected lines into clipboard text.
17
+ * @param {{ text: string, depth: number, whole: boolean }[]} parts `whole` is true when the line is
18
+ * selected from its first character, so its indentation belongs in the copy.
19
+ */
20
+ export function joinCodeLines(parts) {
21
+ return parts.map(({ text, depth, whole }) => (whole ? INDENT.repeat(depth) : '') + text).join('\n');
22
+ }
23
+
24
+ /** The text of a range of one source element, with collapsed badges written as an ellipsis. */
25
+ function textOf(range) {
26
+ const fragment = range.cloneContents();
27
+ for (const badge of fragment.querySelectorAll('.folded')) badge.replaceWith('…');
28
+ return fragment.textContent;
29
+ }
30
+
31
+ /**
32
+ * The code in the current selection, or null when it should be left to the browser. Line numbers,
33
+ * fold buttons and line actions are not in `.src`, so they can never be included.
34
+ */
35
+ export function selectedCode(selection = globalThis.getSelection?.()) {
36
+ if (!selection || selection.isCollapsed || !selection.rangeCount) return null;
37
+ const range = selection.getRangeAt(0);
38
+ const anchor = range.commonAncestorContainer;
39
+ const view = (anchor.nodeType === 1 ? anchor : anchor.parentElement)?.closest('.code-view');
40
+ if (!view) return null;
41
+ const parts = [];
42
+ for (const line of view.querySelectorAll('.ln')) {
43
+ const source = line.querySelector('.src');
44
+ if (!source || !range.intersectsNode(source)) continue;
45
+ const part = document.createRange();
46
+ part.selectNodeContents(source);
47
+ // Clip the line's range to the selection; the line is "whole" when the selection starts before it.
48
+ const clippedStart = range.compareBoundaryPoints(Range.START_TO_START, part) > 0;
49
+ if (clippedStart) part.setStart(range.startContainer, range.startOffset);
50
+ if (range.compareBoundaryPoints(Range.END_TO_END, part) < 0) part.setEnd(range.endContainer, range.endOffset);
51
+ // A selection that starts exactly at the first character of the source still counts as whole.
52
+ let atStart = false;
53
+ if (clippedStart) {
54
+ const before = document.createRange();
55
+ before.selectNodeContents(source);
56
+ before.setEnd(range.startContainer, range.startOffset);
57
+ atStart = before.toString() === '';
58
+ }
59
+ parts.push({ text: textOf(part), depth: Number.parseInt(source.style.getPropertyValue('--d'), 10) || 0, whole: !clippedStart || atStart });
60
+ }
61
+ return parts.length ? joinCodeLines(parts) : null;
62
+ }
63
+
64
+ if (typeof document !== 'undefined') {
65
+ document.addEventListener('copy', event => {
66
+ const text = selectedCode();
67
+ if (text === null || !event.clipboardData) return;
68
+ event.clipboardData.setData('text/plain', text);
69
+ event.preventDefault();
70
+ });
71
+ }
@@ -0,0 +1,149 @@
1
+ // The language picker shared by the Docs "Request sample" card and the Try it Code panel.
2
+ //
3
+ // A fixed-width trigger button shows `[mark] Language` with the client library in muted text and a
4
+ // chevron; it opens a listbox with one row per language (mark, name, library right-aligned in
5
+ // muted mono, and a check on the selected row). The trigger never changes size with the choice, so
6
+ // nothing beside it shifts. The choice is remembered in localStorage and shared by both screens.
7
+ //
8
+ // The row's cells follow the page direction (so the auto margin that pushes the library to the far
9
+ // edge mirrors in RTL); the Latin names inside them stay left to right.
10
+ //
11
+ // Keyboard (WAI-ARIA menu button + listbox):
12
+ // trigger ↓ ↑ Enter Space open the list on the selected language
13
+ // list ↓ ↑ move, Home / End jump, a letter jumps to the next language starting with it
14
+ // (typing more letters narrows), Enter / Space choose, Esc closes and returns focus
15
+ // to the trigger, Tab closes too. The chosen row carries aria-selected="true".
16
+ import { esc, icon } from './components.js';
17
+ import { t } from './i18n.js';
18
+ import { langIcon } from './lang-icons.js';
19
+ import { closePopover, openPopoverAt, place } from './popover.js';
20
+ import { pickerFormats } from './snippets.js';
21
+
22
+ const STORAGE_KEY = 'sendproof-code-language';
23
+ const DEFAULT_FORMAT = 'curl';
24
+ /** How long typed letters count as one search string. */
25
+ const TYPE_AHEAD_MS = 700;
26
+
27
+ /** The remembered language id (a picker format), or cURL when nothing valid is stored. */
28
+ export function getCodeFormat() {
29
+ try {
30
+ const stored = globalThis.localStorage?.getItem(STORAGE_KEY);
31
+ return pickerFormats.some(format => format.id === stored) ? stored : DEFAULT_FORMAT;
32
+ } catch {
33
+ return DEFAULT_FORMAT; // Storage can be blocked; the choice then lasts only for this page.
34
+ }
35
+ }
36
+
37
+ /** Remembers the language for the next render, on Docs and Try it alike. */
38
+ export function setCodeFormat(id) {
39
+ try { globalThis.localStorage?.setItem(STORAGE_KEY, id); } catch { /* Blocked storage: keep going. */ }
40
+ }
41
+
42
+ const formatOf = id => pickerFormats.find(format => format.id === id) ?? pickerFormats[0];
43
+
44
+ /** The inside of the trigger: mark, language, library, chevron. Names stay left to right in RTL. */
45
+ function triggerContent(format) {
46
+ return `${langIcon(format.icon)}<span class="lang-name ltr">${esc(format.label)}</span> <span class="lang-lib ltr" title="${esc(format.library)}">${esc(format.library)}</span>${icon('chevron-down', true, 'lang-chev')}`;
47
+ }
48
+
49
+ const triggerLabel = format => t('code.languageValue', { name: format.label, library: format.library });
50
+
51
+ /**
52
+ * The trigger button. `id` must be unique on the page (it is how focus finds the trigger again
53
+ * after a re-render).
54
+ */
55
+ export function codePicker({ id, value = getCodeFormat() }) {
56
+ const format = formatOf(value);
57
+ return `<div class="code-picker" data-code-picker><button type="button" class="btn btn-sm code-picker-trigger" id="${esc(id)}" data-code-trigger aria-haspopup="listbox" aria-expanded="false" aria-label="${esc(triggerLabel(format))}">${triggerContent(format)}</button></div>`;
58
+ }
59
+
60
+ /** Shows another language on a trigger without re-rendering anything around it. */
61
+ export function updateCodePicker(trigger, id) {
62
+ const format = formatOf(id);
63
+ trigger.innerHTML = triggerContent(format);
64
+ trigger.setAttribute('aria-label', triggerLabel(format));
65
+ }
66
+
67
+ const optionHtml = (format, selected) => `<div class="opt-row lang-row" role="option" id="lang-opt-${esc(format.id)}" tabindex="-1" data-lang="${esc(format.id)}" aria-selected="${selected}">${langIcon(format.icon)}<span class="main"><bdi class="ltr">${esc(format.label)}</bdi></span><span class="end lang-lib" title="${esc(format.library)}"><bdi class="ltr">${esc(format.library)}</bdi></span><span class="lang-check" aria-hidden="true">${selected ? icon('check', true) : ''}</span></div>`;
68
+
69
+ /**
70
+ * Wires every trigger under `root`. `onChange(id)` runs after the choice is stored and the list
71
+ * is closed; focus then returns to the trigger with that id (it may have been re-rendered).
72
+ */
73
+ export function bindCodePicker(root, { onChange }) {
74
+ for (const trigger of root.querySelectorAll('[data-code-trigger]')) {
75
+ trigger.addEventListener('click', () => {
76
+ // A second click on an open trigger closes the list.
77
+ if (trigger.getAttribute('aria-expanded') === 'true') closePopover(true);
78
+ else openList(trigger, onChange);
79
+ });
80
+ trigger.addEventListener('keydown', event => {
81
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
82
+ event.preventDefault();
83
+ openList(trigger, onChange);
84
+ }
85
+ });
86
+ }
87
+ }
88
+
89
+ function openList(trigger, onChange) {
90
+ closePopover();
91
+ const current = getCodeFormat();
92
+ const pop = openPopoverAt(trigger, `<div class="pop code-pop" role="listbox" aria-label="${esc(t('code.language'))}"><div class="pop-group">${pickerFormats.map(format => optionHtml(format, format.id === current)).join('')}</div></div>`,
93
+ { align: 'start', focus: false, kind: 'code-language' });
94
+ // The list is at least as wide as its trigger, so the right-aligned libraries line up under it.
95
+ pop.style.minInlineSize = `max(${trigger.offsetWidth}px, 21rem)`;
96
+ // On short screens the list scrolls inside the room on the roomier side of the trigger, so no row is cut off.
97
+ const box = trigger.getBoundingClientRect();
98
+ const room = Math.max(box.top, innerHeight - box.bottom) - 6 - 12 - 4;
99
+ pop.querySelector('.pop-group').style.maxBlockSize = `${Math.max(160, Math.min(room, 448))}px`;
100
+ place(trigger, pop, { align: 'start' });
101
+ const options = [...pop.querySelectorAll('[role="option"]')];
102
+ const focus = index => {
103
+ for (const [position, option] of options.entries()) option.classList.toggle('is-active', position === index);
104
+ options[index]?.focus({ preventScroll: false });
105
+ };
106
+ focus(Math.max(0, options.findIndex(option => option.dataset.lang === current)));
107
+
108
+ const choose = option => {
109
+ setCodeFormat(option.dataset.lang);
110
+ closePopover();
111
+ onChange(option.dataset.lang);
112
+ document.getElementById(trigger.id)?.focus();
113
+ };
114
+
115
+ let typed = '';
116
+ let typedAt = 0;
117
+ pop.addEventListener('keydown', event => {
118
+ const index = options.indexOf(document.activeElement);
119
+ const keys = { ArrowDown: Math.min(index + 1, options.length - 1), ArrowUp: Math.max(index - 1, 0), Home: 0, End: options.length - 1 };
120
+ if (event.key in keys) {
121
+ event.preventDefault();
122
+ focus(keys[event.key]);
123
+ } else if (event.key === 'Enter' || event.key === ' ') {
124
+ event.preventDefault();
125
+ if (index >= 0) choose(options[index]);
126
+ } else if (event.key === 'Tab') {
127
+ event.preventDefault();
128
+ closePopover(true);
129
+ } else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
130
+ // Type-ahead: letters typed in quick succession form a prefix; one letter repeated cycles.
131
+ const now = Date.now();
132
+ typed = now - typedAt > TYPE_AHEAD_MS ? event.key.toLowerCase() : typed + event.key.toLowerCase();
133
+ typedAt = now;
134
+ const cycling = typed.length > 1 && [...typed].every(letter => letter === typed[0]);
135
+ const prefix = cycling ? typed[0] : typed;
136
+ const start = cycling || typed.length === 1 ? index + 1 : index;
137
+ const ordered = [...options.slice(start), ...options.slice(0, start)];
138
+ const hit = ordered.find(option => formatOf(option.dataset.lang).label.toLowerCase().startsWith(prefix));
139
+ if (hit) {
140
+ event.preventDefault();
141
+ focus(options.indexOf(hit));
142
+ }
143
+ }
144
+ });
145
+ pop.addEventListener('click', event => {
146
+ const option = event.target.closest('[role="option"]');
147
+ if (option) choose(option);
148
+ });
149
+ }
@@ -0,0 +1,197 @@
1
+ import { t } from './i18n.js';
2
+ import { backTarget } from './router.js';
3
+ import { resultTabLabel } from './result-states.js';
4
+ import { matchesShortcut, shortcutLabel, SHORTCUTS } from './shortcuts.js';
5
+
6
+ function editing(target) {
7
+ return target?.closest?.('input, textarea, select, [contenteditable=true]');
8
+ }
9
+
10
+ /** Resolve the current command against the visible request, field and result. */
11
+ export function createCommands({ $, state, chooseTab, chooseResult, chooseOperation, fill, preview,
12
+ send, openPalette, openSheet, openSidebar, changePane, issues, addHeader, bulkEdit, toggleHeader, copyResponse,
13
+ openDisplay, openHistory, toggleTheme, toggleDocs, sidebarTab, modelBack, generate, toggleTrace, traceAvailable,
14
+ reloadSpec, canReload,
15
+ }) {
16
+ const click = selector => $(selector)?.click();
17
+ const requestTab = () => [...document.querySelectorAll('.request-tabs [data-request-tab]')];
18
+ const resultTab = () => [...document.querySelectorAll('.response .tabs [data-result-tab]')];
19
+ const moveOperation = step => {
20
+ const start = state.ops.indexOf(state.op);
21
+ if (state.ops.length) chooseOperation((start + step + state.ops.length) % state.ops.length);
22
+ };
23
+ const header = callback => {
24
+ changePane('request');
25
+ if (state.tab !== 'Headers') chooseTab('Headers');
26
+ callback();
27
+ };
28
+ const nextChange = step => {
29
+ const changes = [...document.querySelectorAll('.response .table-change')];
30
+ if (!changes.length) return;
31
+ const current = changes.indexOf(document.activeElement);
32
+ const next = changes[(current < 0 ? step > 0 ? 0 : changes.length - 1 :
33
+ (current + step + changes.length) % changes.length)];
34
+ next.tabIndex = -1;
35
+ next.focus();
36
+ };
37
+ const actions = {
38
+ palette: () => openPalette(),
39
+ shortcuts: () => openSheet(),
40
+ sidebar: () => openSidebar(),
41
+ display: () => openDisplay(),
42
+ theme: () => toggleTheme(),
43
+ history: () => openHistory(),
44
+ signin: () => click('.topbar [data-action="signin"]'),
45
+ docs: () => toggleDocs(),
46
+ 'sidebar-operations': () => sidebarTab('operations'),
47
+ 'sidebar-models': () => sidebarTab('models'),
48
+ 'model-back': () => modelBack(),
49
+ generate: target => generate(target, false),
50
+ 'generate-menu': target => generate(target, true),
51
+ 'field-info': target => {
52
+ const button = target.closest?.('.field')?.querySelector('.info-btn');
53
+ if (!button) return false;
54
+ button.click();
55
+ },
56
+ 'traced-send': () => toggleTrace(),
57
+ 'reload-spec': () => reloadSpec(),
58
+ filter: () => {
59
+ if (!$('#filter').getClientRects().length) openSidebar(true);
60
+ $('#filter').focus();
61
+ },
62
+ next: () => moveOperation(1),
63
+ previous: () => moveOperation(-1),
64
+ 'goto-operation': () => openPalette(false, 'Operations'),
65
+ 'focus-pane': target => changePane(target?.closest('.response') ? 'request' : 'response', true),
66
+ 'editor-mode': () => { changePane('request'); chooseTab(state.bodyMode === 'JSON' ? 'Form' : 'JSON', { focus: true }); },
67
+ 'issue-next': () => issues.step(1),
68
+ 'issue-previous': () => issues.step(-1),
69
+ 'copy-url': () => click('[data-action="copy-url"]'),
70
+ 'add-header': () => header(addHeader),
71
+ 'add-row': target => {
72
+ const list = target.closest('.list-input');
73
+ if (list) list.querySelector('button.add:not(:disabled)')?.click();
74
+ else if (target.closest('#header-list')) addHeader();
75
+ else return false;
76
+ },
77
+ 'remove-row': target => {
78
+ const row = target.closest('[data-header-kind="custom"]');
79
+ if (!row || [...row.querySelectorAll('input[data-header-field]')].some(input => input.value)) return false;
80
+ row.querySelector('[data-action="remove-header"]')?.click();
81
+ },
82
+ 'toggle-header': target => {
83
+ const id = target.closest('[data-header-row]')?.dataset.headerId;
84
+ if (!id) return false;
85
+ toggleHeader(id);
86
+ },
87
+ 'bulk-edit': () => header(bulkEdit),
88
+ 'header-presets': () => header(() => click('[data-header-command="presets"]')),
89
+ 'copy-curl': () => click('[data-action="copy-curl"]'),
90
+ 'copy-response': copyResponse,
91
+ 'find-response': () => {
92
+ if (state.resultTab !== 'Response') chooseResult('Response');
93
+ changePane('response');
94
+ click('[data-action="find-response"]');
95
+ },
96
+ 'follow-response': () => click('[data-follow-up], [data-location-open]'),
97
+ 'open-replacement': () => click('[data-replace-op]'),
98
+ 'fold-all': () => click('.response-viewer [data-fold-all]:not([hidden])'),
99
+ 'wrap-lines': () => click('.response-viewer [data-wrap]:not([hidden])'),
100
+ 'change-next': () => nextChange(1),
101
+ 'change-prev': () => nextChange(-1),
102
+ preview,
103
+ send,
104
+ };
105
+ for (const [id, definition] of Object.entries(SHORTCUTS)) {
106
+ if (definition.mode) actions[id] = () => fill(definition.mode);
107
+ }
108
+
109
+ const canRun = {
110
+ 'editor-mode': () => !!$('[data-request-tab="Body"]') && state.view === 'try',
111
+ docs: () => !!state.op && ['try', 'docs'].includes(state.view),
112
+ 'model-back': () => state.view === 'model' && !!backTarget(state.route),
113
+ generate: () => state.view === 'try',
114
+ 'generate-menu': () => state.view === 'try',
115
+ 'traced-send': () => traceAvailable(),
116
+ 'reload-spec': () => canReload(),
117
+ 'autofill-reuse': () => state.history.some(entry => entry.op === state.op),
118
+ 'issue-next': () => issues.active,
119
+ 'issue-previous': () => issues.active,
120
+ 'autofill-undo': () => state.canUndoAutofill,
121
+ 'copy-url': () => !!state.op,
122
+ 'add-header': () => !!state.op,
123
+ 'bulk-edit': () => !!state.op,
124
+ 'header-presets': () => !!state.op,
125
+ 'copy-curl': () => !!$('[data-action="copy-curl"]'),
126
+ 'copy-response': () => !!state.result?.raw,
127
+ 'find-response': () => !!state.result?.raw,
128
+ 'follow-response': () => !!$('[data-follow-up], [data-location-open]'),
129
+ 'open-replacement': () => !!$('[data-replace-op]'),
130
+ 'fold-all': () => !!$('.response-viewer [data-fold-all]:not([hidden])'),
131
+ 'wrap-lines': () => !!$('.response-viewer [data-wrap]:not([hidden])'),
132
+ 'change-next': () => !!$('.response .table-change'),
133
+ 'change-prev': () => !!$('.response .table-change'),
134
+ preview: () => !!$('.actionbar [data-action="preview"]:not(:disabled)'),
135
+ send: () => !!$('.actionbar [data-action="send"]:not(:disabled), [data-action="confirm-send"]'),
136
+ };
137
+ function tabCommands() {
138
+ return [...requestTab().map((button, index) => ({
139
+ id: 'request-tab-' + index, label: t('palette.goToTab', { tab: button.querySelector('span')?.textContent.trim() }), icon: 'list',
140
+ run: () => { changePane('request'); button.click(); },
141
+ })), ...resultTab().flatMap((button, index) => [{
142
+ id: 'result-tab-' + index, label: t('palette.showResult', { tab: button.dataset.resultTab === 'Headers' ? t('palette.responseHeaders') : resultTabLabel(button.dataset.resultTab) }),
143
+ icon: 'eye', group: 'Result',
144
+ run: () => { changePane('response'); chooseResult(button.dataset.resultTab, true); },
145
+ }])];
146
+ }
147
+
148
+ function available() {
149
+ return [...Object.entries(actions).flatMap(([id, action]) => {
150
+ const definition = SHORTCUTS[id];
151
+ if (!definition?.icon || id === 'palette' || (canRun[id] && !canRun[id]())) return [];
152
+ return [{ id, label: shortcutLabel(id), icon: definition.icon, group: definition.group, run: () => action(document.activeElement) }];
153
+ }), ...tabCommands()];
154
+ }
155
+
156
+ let sequenceAt = 0;
157
+ function handle(event) {
158
+ if (event.defaultPrevented || event.isComposing) return false;
159
+ const target = event.target;
160
+ const modal = target.closest?.('[aria-modal=true]');
161
+ if (modal && !(modal.classList.contains('palette') && matchesShortcut('shortcuts', event))) return false;
162
+
163
+ const isEditor = editing(target);
164
+ const local = new Set(['add-row', 'remove-row', 'toggle-header']);
165
+ for (const id of ['add-row', 'remove-row', 'toggle-header', ...Object.keys(actions).filter(id => !local.has(id))]) {
166
+ const definition = SHORTCUTS[id];
167
+ if (!definition?.chord || !matchesShortcut(id, event) || canRun[id] && !canRun[id]()) continue;
168
+ const bareKey = !definition.chord.includes('+');
169
+ if (isEditor && (bareKey || id === 'autofill-undo') && !local.has(id) && id !== 'shortcuts') continue;
170
+ if (id === 'shortcuts' && isEditor && !modal) continue;
171
+ if (actions[id](target) === false) continue;
172
+ event.preventDefault();
173
+ return true;
174
+ }
175
+ const tab = tabCommands().find(({ id }) => matchesShortcut(id, event));
176
+ if (tab) {
177
+ event.preventDefault();
178
+ tab.run();
179
+ return true;
180
+ }
181
+ // Two-key sequences such as G then O: the second key must follow within 900 ms.
182
+ if (!isEditor && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
183
+ const key = event.key.toUpperCase();
184
+ const sequences = Object.entries(SHORTCUTS).filter(([, definition]) => definition.sequence);
185
+ const pending = sequenceAt && performance.now() - sequenceAt.time < 900 ? sequenceAt.key : '';
186
+ const match = pending && sequences.find(([, definition]) => definition.sequence[0] === pending && definition.sequence[1] === key);
187
+ sequenceAt = sequences.some(([, definition]) => definition.sequence[0] === key) && !match ? { key, time: performance.now() } : 0;
188
+ if (match && actions[match[0]]) {
189
+ event.preventDefault();
190
+ actions[match[0]](target);
191
+ return true;
192
+ }
193
+ }
194
+ return false;
195
+ }
196
+ return { available, handle, labels: tabCommands };
197
+ }
@@ -0,0 +1,77 @@
1
+ // Small HTML builders shared by every view, matching the approved mock builders
2
+ // (mocks: shell.js `tab`, `kbd`, `copyBtn`, `copyTextBtn`, `state`). Every builder returns markup;
3
+ // callers escape data with esc() before passing it in.
4
+ import { formatNumber, t } from './i18n.js';
5
+ import { shortcutAttrs, shortcutHint } from './shortcuts.js';
6
+
7
+ const entities = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
8
+ /** Escapes text for HTML content and attribute values. */
9
+ export const esc = value => String(value ?? '').replace(/[&<>"']/g, char => entities[char]);
10
+
11
+ // Icons whose meaning has a direction mirror in right-to-left layouts.
12
+ const directional = new Set(['chevron-right', 'chevron-left', 'arrow-left', 'arrow-right', 'send', 'log-in', 'undo']);
13
+
14
+ /** A decorative icon from the sprite in icons.js. */
15
+ export const icon = (name, small = false, extra = '') =>
16
+ `<svg class="i${small ? ' i-sm' : ''}${directional.has(name) ? ' i-dir' : ''}${extra ? ' ' + extra : ''}" aria-hidden="true"><use href="#i-${esc(name)}"/></svg>`;
17
+
18
+ /** A status code's hue by class: 2xx success, 3xx info, 4xx warning, 5xx danger. */
19
+ export const statusTone = code => /^2/.test(String(code)) ? 'ok' : /^3/.test(String(code)) ? 'info' : /^4/.test(String(code)) ? 'warn' : /^5/.test(String(code)) ? 'danger' : 'muted';
20
+
21
+ /** An HTTP method badge. Always left to right. */
22
+ export const method = name => `<span class="method m-${esc(name.toLowerCase())}">${esc(name.toUpperCase())}</span>`;
23
+
24
+ /**
25
+ * The one tab component. `count` is a number, '–' (not known yet) or undefined (no badge).
26
+ * `flag` adds the issue dot and its accessible description; it never changes the tab's width.
27
+ */
28
+ export function tab(label, { selected = false, count, flag, flagSlot = false, id, controls, shortcut, data = '', icon: glyph, lang, labelClass } = {}) {
29
+ const badge = count === undefined ? ''
30
+ : count === '–' ? '<span class="n unknown" aria-hidden="true">–</span>'
31
+ : `<span class="n">${typeof count === 'number' ? formatNumber(count) : esc(count)}</span>`;
32
+ const description = flag ? `<span class="sr-only">, ${esc(flag)}</span>`
33
+ : count === '–' ? `<span class="sr-only">, ${esc(t('tab.notRun'))}</span>` : '';
34
+ return `<button type="button" class="tab" role="tab" aria-selected="${selected}" tabindex="${selected ? 0 : -1}"${id ? ` id="${esc(id)}"` : ''}${controls ? ` aria-controls="${esc(controls)}"` : ''} ${shortcut ? shortcutAttrs(shortcut) : ''} ${data}>${glyph ? icon(glyph, true) : ''}<span${lang ? ` lang="${lang}"` : ''}${labelClass ? ` class="${esc(labelClass)}"` : ''}>${esc(label)}</span>${badge}${flag || flagSlot ? `<span class="flag" aria-hidden="true"${flag ? '' : ' hidden'} data-tab-flag></span>` : ''}${flagSlot ? `<span class="sr-only" data-tab-flag-text>${flag ? `, ${esc(flag)}` : ''}</span>` : description}</button>`;
35
+ }
36
+
37
+ /**
38
+ * An icon copy button. The icon swaps to a check and a "Copied" bubble overlays it, so nothing
39
+ * moves. `action` is the data-action handled by the view; ui/copy.js gives the feedback.
40
+ */
41
+ export function copyButton(label, { action, size = 'btn-sm', shortcut, data = '' } = {}) {
42
+ return `<button type="button" class="btn btn-ghost btn-icon ${size} copy" aria-label="${esc(label)}" title="${esc(label)}"${action ? ` data-action="${esc(action)}"` : ''} ${shortcut ? shortcutAttrs(shortcut) : ''} ${data}>${icon('copy', true, 'i-idle')}${icon('check', true, 'i-done')}</button>`;
43
+ }
44
+
45
+ /** A text copy button: "Copy" and "Copied" share one grid cell, so its width never changes. */
46
+ export function copyTextButton(label, { action, cls = 'btn-sm', data = '' } = {}) {
47
+ return `<button type="button" class="btn ${cls} copy"${action ? ` data-action="${esc(action)}"` : ''} ${data}>${icon('copy', true, 'i-idle')}${icon('check', true, 'i-done')}<span class="copy-label"><span>${esc(label)}</span><span aria-hidden="true">${esc(t('copy.copied'))}</span></span></button>`;
48
+ }
49
+
50
+ /** A button with an optional icon and keycaps. `label` is escaped. */
51
+ export function button(label, { cls = 'btn-sm', glyph, shortcut, action, data = '', hint = true } = {}) {
52
+ return `<button type="button" class="btn ${cls}"${action ? ` data-action="${esc(action)}"` : ''} ${shortcut ? shortcutAttrs(shortcut) : ''} ${data}>${glyph ? icon(glyph, true) : ''}${esc(label)}${shortcut && hint ? ' ' + shortcutHint(shortcut) : ''}</button>`;
53
+ }
54
+
55
+ /**
56
+ * Empty, error and explanation states share one anatomy: icon tile, title, one or two sentences,
57
+ * an optional "why" note, actions and extra content such as steps or ghost rows.
58
+ * `title`, `body` and `why` are HTML (escape data first).
59
+ */
60
+ export function stateBlock({ glyph = 'info', tone = '', title, body = '', why = '', actions = [], extra = '', center = false, compact = false, heading = 'h3', role = '' }) {
61
+ return `<div class="state${center ? ' center' : ''}${compact ? ' compact' : ''}"${role ? ` role="${role}"` : ''}>
62
+ ${glyph ? `<span class="state-ico${tone ? ' ' + tone : ''}" aria-hidden="true">${icon(glyph)}</span>` : ''}
63
+ <${heading}>${title}</${heading}>
64
+ ${body ? `<p>${body}</p>` : ''}
65
+ ${why ? `<div class="why">${icon('info', true)}<span>${why}</span></div>` : ''}
66
+ ${actions.length ? `<div class="actions">${actions.join('')}</div>` : ''}
67
+ ${extra}
68
+ </div>`;
69
+ }
70
+
71
+ /** Faint placeholder rows that preview what a tab will show (not a skeleton: nothing loads). */
72
+ export const ghostRows = rows => `<div class="ghost" aria-hidden="true">${rows.map(([glyph, first, second]) =>
73
+ `<div class="ghost-row">${icon(glyph, true)}<span class="bar" style="inline-size:${first}"></span><span class="spacer"></span><span class="bar" style="inline-size:${second}"></span></div>`).join('')}</div>`;
74
+
75
+ /** An inline notice where a problem happened. It never replaces a pane. `html` is trusted. */
76
+ export const inlineNote = (html, { tone = '', flush = false, glyph = 'info', role = '', dismiss = false, extra = '' } = {}) =>
77
+ `<div class="inline-note${tone ? ' ' + tone : ''}${flush ? ' flush' : ''}"${role ? ` role="${role}"` : ''}>${icon(glyph, true)}<span>${html}</span>${extra}${dismiss ? `<button type="button" class="btn btn-ghost btn-icon btn-xs" data-dismiss-note aria-label="${esc(t('copy.dismiss'))}">${icon('x', true)}</button>` : ''}</div>`;