@specbook/ui 0.2.0 → 0.3.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.
Files changed (68) hide show
  1. package/dist-viewer/assets/Host-Cq-4gDuM.js +41 -0
  2. package/dist-viewer/assets/index-BBlFcQUE.js +1 -0
  3. package/dist-viewer/assets/main-CSkB-O_8.js +14 -0
  4. package/dist-viewer/assets/{mount-CGL2tOpN.js → mount-DfwluJy4.js} +2 -2
  5. package/dist-viewer/assets/{panel-C8Ve3LeS.js → panel-9eYU7Gz6.js} +1 -1
  6. package/dist-viewer/assets/panel-hNOojwiM.css +1 -0
  7. package/dist-viewer/assets/registry-DIHX11uY.js +2 -0
  8. package/dist-viewer/assets/worker-BmvGpsJS.js +181 -0
  9. package/dist-viewer/index.html +4 -4
  10. package/dist-viewer/specbook.js +1 -1
  11. package/package.json +6 -5
  12. package/src/app.tsx +65 -12
  13. package/src/branding.ts +12 -4
  14. package/src/components/Catalog.tsx +128 -51
  15. package/src/components/EnvBadge.tsx +21 -3
  16. package/src/components/EnvironmentMenu.tsx +237 -127
  17. package/src/components/Fields.tsx +18 -1
  18. package/src/components/NewEnvironmentDialog.tsx +118 -0
  19. package/src/components/Palette.tsx +7 -2
  20. package/src/custom-environments.ts +63 -0
  21. package/src/embed/panel.tsx +286 -44
  22. package/src/embed/styles.ts +2 -0
  23. package/src/embed/target.ts +82 -0
  24. package/src/embed/theme.ts +75 -0
  25. package/src/embed.ts +44 -15
  26. package/src/engine.ts +274 -32
  27. package/src/environment-list.ts +16 -0
  28. package/src/main.tsx +7 -2
  29. package/src/nav.ts +12 -1
  30. package/src/oauth.ts +9 -8
  31. package/src/panel/Body.tsx +27 -4
  32. package/src/panel/Checks.tsx +79 -0
  33. package/src/panel/CodeSample.tsx +16 -9
  34. package/src/panel/Combo.tsx +52 -13
  35. package/src/panel/ControlsGrid.tsx +54 -9
  36. package/src/panel/ErrorBoundary.tsx +36 -0
  37. package/src/panel/Host.tsx +14 -2
  38. package/src/panel/OAuthSignIn.tsx +6 -2
  39. package/src/panel/Panel.tsx +43 -10
  40. package/src/panel/ParamGrid.tsx +15 -8
  41. package/src/panel/RequestPanel.tsx +91 -36
  42. package/src/panel/RequestView.tsx +2 -1
  43. package/src/panel/ResponseView.tsx +25 -14
  44. package/src/panel/SecretsBar.tsx +10 -9
  45. package/src/panel/SequenceDocs.tsx +7 -6
  46. package/src/panel/SequencePanel.tsx +124 -32
  47. package/src/panel/announce.ts +17 -0
  48. package/src/panel/icons.tsx +9 -0
  49. package/src/panel/short.ts +24 -0
  50. package/src/routing.ts +0 -9
  51. package/src/runtime.ts +19 -1
  52. package/src/secrets.ts +4 -2
  53. package/src/storage.ts +58 -0
  54. package/src/store.ts +8 -0
  55. package/src/styles/app.css +69 -6
  56. package/src/styles/embed.css +116 -0
  57. package/src/styles/panel.css +233 -0
  58. package/src/viewer/manifests.ts +2 -0
  59. package/src/viewer/protocol.ts +6 -0
  60. package/src/viewer/registry.ts +46 -10
  61. package/src/viewer/worker.ts +9 -1
  62. package/src/virtual.d.ts +8 -0
  63. package/dist-viewer/assets/Host-CSrM9wY1.js +0 -37
  64. package/dist-viewer/assets/index-ez9c20v3.js +0 -1
  65. package/dist-viewer/assets/main-38QGGpNT.js +0 -14
  66. package/dist-viewer/assets/panel-C-vBZrep.css +0 -1
  67. package/dist-viewer/assets/registry-ChKCFBt1.js +0 -2
  68. package/dist-viewer/assets/worker-ClGb0tE1.js +0 -181
@@ -1,6 +1,10 @@
1
1
  import type { ComponentChildren } from 'preact'
2
- import { useEffect, useLayoutEffect, useRef } from 'preact/hooks'
2
+ import { useEffect, useLayoutEffect, useMemo, useRef } from 'preact/hooks'
3
3
  import { env, environmentNote, environments } from '../store'
4
+ import { announcement } from './announce'
5
+ import { ErrorBoundary } from './ErrorBoundary'
6
+
7
+ let panelIds = 0
4
8
 
5
9
  interface Props {
6
10
  title: string
@@ -9,6 +13,8 @@ interface Props {
9
13
  flush?: boolean
10
14
  /** dims the page and traps focus (embeds); the standalone site leaves its list usable beside the panel */
11
15
  modal?: boolean
16
+ /** `popover`: a centered dialog on a desktop and a bottom sheet on a phone; `side` is the app's sheet from the right */
17
+ variant?: 'side' | 'popover'
12
18
  onPrev?: () => void
13
19
  onNext?: () => void
14
20
  onClose: () => void
@@ -24,12 +30,22 @@ export function Panel({
24
30
  subtitle,
25
31
  flush,
26
32
  modal = true,
33
+ variant = 'side',
27
34
  onPrev,
28
35
  onNext,
29
36
  onClose,
30
37
  children,
31
38
  }: Props) {
32
39
  const aside = useRef<HTMLElement>(null)
40
+ const titleId = useMemo(() => `sb-panel-title-${++panelIds}`, [])
41
+
42
+ // what was announced for one run is not read out again when the next panel opens
43
+ useEffect(
44
+ () => () => {
45
+ announcement.value = ''
46
+ },
47
+ [],
48
+ )
33
49
 
34
50
  useEffect(() => {
35
51
  const root = aside.current?.getRootNode() as Document | ShadowRoot
@@ -63,14 +79,23 @@ export function Panel({
63
79
  const top = vv?.offsetTop ?? 0
64
80
  const height = vv?.height ?? innerHeight
65
81
  const at = field.getBoundingClientRect().top
66
- const want = top + height * 0.2
67
- if (at > top + height * 0.4 || at < top) box.scrollTop += at - want
82
+ // a dropdown field needs its list visible too, and picking from it needs no keyboard: it is moved
83
+ // only when it is down where the keyboard would be, and not as far
84
+ const dropdown = field.getAttribute('role') === 'combobox'
85
+ const want = top + height * (dropdown ? 0.3 : 0.2)
86
+ if (at > top + height * (dropdown ? 0.55 : 0.4) || at < top) box.scrollTop += at - want
68
87
  }
69
88
  const focusin = (e: Event) => {
70
89
  const field = e.target as HTMLElement
71
90
  if (!phone.matches || !field.matches?.(FIELD)) return
72
91
  const box = scroller(field)
73
- if (box && padded?.box !== box) {
92
+ // a dropdown field high enough on the screen is not moved, so it needs no room below (which would
93
+ // only show a scrollbar)
94
+ const vv = typeof visualViewport === 'undefined' ? undefined : visualViewport
95
+ const low =
96
+ field.getBoundingClientRect().top >
97
+ (vv?.offsetTop ?? 0) + (vv?.height ?? innerHeight) * 0.55
98
+ if (box && padded?.box !== box && (field.getAttribute('role') !== 'combobox' || low)) {
74
99
  if (padded) padded.box.style.paddingBottom = padded.was
75
100
  padded = { box, was: box.style.paddingBottom }
76
101
  box.style.paddingBottom = '70vh'
@@ -121,15 +146,18 @@ export function Panel({
121
146
  first.focus()
122
147
  }
123
148
  }
124
- addEventListener('keydown', key)
125
- return () => removeEventListener('keydown', key)
149
+ // a dialog over someone else's page listens on itself (focus is trapped in it), not on the window; the app's
150
+ // docked panel keeps its window-wide Escape
151
+ const target: EventTarget = modal && aside.current ? aside.current : window
152
+ target.addEventListener('keydown', key as EventListener)
153
+ return () => target.removeEventListener('keydown', key as EventListener)
126
154
  }, [onClose, modal])
127
155
 
128
156
  // a dialog when it dims the page (embeds), a complementary region when docked beside the list
129
157
  const attrs = {
130
- class: `panel ${modal ? '' : 'docked'}`,
158
+ class: `panel ${modal ? '' : 'docked'} ${variant === 'popover' ? 'popover' : ''}`,
131
159
  part: 'panel',
132
- 'aria-label': title,
160
+ 'aria-labelledby': titleId,
133
161
  'aria-modal': modal ? true : undefined,
134
162
  role: (modal ? 'dialog' : 'complementary') as 'dialog',
135
163
  tabIndex: -1,
@@ -143,7 +171,7 @@ export function Panel({
143
171
  <section {...attrs} ref={aside}>
144
172
  <header class="panel-head" part="header">
145
173
  <div class="panel-title">
146
- <h2>{title}</h2>
174
+ <h2 id={titleId}>{title}</h2>
147
175
  {subtitle && <div class="muted small">{subtitle}</div>}
148
176
  </div>
149
177
  <span class="spacer" />
@@ -190,7 +218,12 @@ export function Panel({
190
218
  ×
191
219
  </button>
192
220
  </header>
193
- <div class={`panel-body ${flush ? 'flush' : ''}`}>{children}</div>
221
+ <div class={`panel-body ${flush ? 'flush' : ''}`}>
222
+ <ErrorBoundary>{children}</ErrorBoundary>
223
+ </div>
224
+ <div class="visually-hidden" role="status" aria-live="polite" aria-atomic="true">
225
+ {announcement.value}
226
+ </div>
194
227
  </section>
195
228
  </>
196
229
  )
@@ -2,6 +2,7 @@ import { signal } from '@preact/signals'
2
2
  import { useEffect, useRef } from 'preact/hooks'
3
3
  import type { FieldDoc } from '../fielddoc'
4
4
  import { inlineSummary, plainText } from '../markdown'
5
+ import { kv } from '../storage'
5
6
  import { Combo } from './Combo'
6
7
  import type { FieldRow } from './draft'
7
8
 
@@ -28,6 +29,8 @@ interface Props {
28
29
  placeholder?: string
29
30
  /** the grid sits under a tab that already names it */
30
31
  bare?: boolean
32
+ /** values are shown, not edited (a saved request carries its own) */
33
+ readOnly?: boolean
31
34
  }
32
35
 
33
36
  type Shown = FieldRow & { virtual?: true }
@@ -41,7 +44,7 @@ const cols = signal(loadCols())
41
44
 
42
45
  function loadCols(): { key: number; val: number } {
43
46
  try {
44
- const c = JSON.parse(localStorage.getItem(COLS_KEY) ?? 'null')
47
+ const c = JSON.parse(kv.local.getItem(COLS_KEY) ?? 'null')
45
48
  if (c && c.key >= MIN_COL && c.val >= MIN_COL && c.key + c.val <= 100 - MIN_COL) return c
46
49
  } catch {
47
50
  /* fall through */
@@ -55,8 +58,8 @@ function setCols(next: { key: number; val: number } | undefined) {
55
58
  const val = Math.min(100 - key - MIN_COL, Math.max(MIN_COL, c.val))
56
59
  cols.value = { key: Math.round(key * 10) / 10, val: Math.round(val * 10) / 10 }
57
60
  try {
58
- if (next) localStorage.setItem(COLS_KEY, JSON.stringify(cols.value))
59
- else localStorage.removeItem(COLS_KEY)
61
+ if (next) kv.local.setItem(COLS_KEY, JSON.stringify(cols.value))
62
+ else kv.local.removeItem(COLS_KEY)
60
63
  } catch {
61
64
  /* optional */
62
65
  }
@@ -167,6 +170,7 @@ export function ParamGrid({
167
170
  bad,
168
171
  placeholder,
169
172
  bare,
173
+ readOnly,
170
174
  }: Props) {
171
175
  const root = useRef<HTMLElement>(null)
172
176
  const table = useRef<HTMLTableElement>(null)
@@ -252,7 +256,7 @@ export function ParamGrid({
252
256
  {all.map((r, i) => {
253
257
  const d = docOf(r.key)
254
258
  const isFile = info(r.key)?.file
255
- const locked = fixed || r.virtual || info(r.key)
259
+ const locked = fixed || readOnly || r.virtual || info(r.key)
256
260
  return (
257
261
  <tr class={`${r.enabled ? '' : 'off'} ${bad === r.key ? 'bad' : ''}`} key={i}>
258
262
  <td class="g-check">
@@ -260,7 +264,7 @@ export function ParamGrid({
260
264
  type="checkbox"
261
265
  aria-label={`Send ${r.key}`}
262
266
  checked={r.enabled}
263
- disabled={fixed}
267
+ disabled={fixed || readOnly}
264
268
  onChange={(e) => patch(i, { enabled: (e.target as HTMLInputElement).checked })}
265
269
  />
266
270
  </td>
@@ -292,6 +296,7 @@ export function ParamGrid({
292
296
  <label class="file-cell">
293
297
  <input
294
298
  type="file"
299
+ disabled={readOnly}
295
300
  aria-label={`File for ${r.key}`}
296
301
  onChange={(e) => {
297
302
  const file = (e.target as HTMLInputElement).files?.[0]
@@ -306,6 +311,7 @@ export function ParamGrid({
306
311
  options={d.enum.map(String)}
307
312
  label={r.key}
308
313
  cell={`${i}:${VALUE}`}
314
+ readOnly={readOnly}
309
315
  placeholder="value"
310
316
  onKeyDown={keys(i, VALUE)}
311
317
  onChange={(value) => patch(i, { value, enabled: true })}
@@ -315,6 +321,7 @@ export function ParamGrid({
315
321
  class="cell"
316
322
  data-cell={`${i}:${VALUE}`}
317
323
  value={r.value}
324
+ readOnly={readOnly}
318
325
  placeholder={placeholder ?? 'value'}
319
326
  aria-label={`Value of ${r.key}`}
320
327
  onInput={(e) =>
@@ -336,7 +343,7 @@ export function ParamGrid({
336
343
  )}
337
344
  </td>
338
345
  <td class="g-act">
339
- {!fixed && r.key && (
346
+ {!fixed && !readOnly && r.key && (
340
347
  <button
341
348
  type="button"
342
349
  class="icon"
@@ -347,7 +354,7 @@ export function ParamGrid({
347
354
  <Icon d="M5.5 5.5h7v7h-7zM3.5 10.5v-7h7" />
348
355
  </button>
349
356
  )}
350
- {!fixed && !r.virtual && (
357
+ {!fixed && !readOnly && !r.virtual && (
351
358
  <button
352
359
  type="button"
353
360
  class="icon"
@@ -362,7 +369,7 @@ export function ParamGrid({
362
369
  </tr>
363
370
  )
364
371
  })}
365
- {!fixed && (
372
+ {!fixed && !readOnly && (
366
373
  <tr class="ghost" key={ghost}>
367
374
  <td class="g-check" />
368
375
  <td class="g-key">
@@ -1,17 +1,19 @@
1
1
  import { collectPlaceholders, type Encoding, type Example, type RunResult } from '@specbook/core'
2
- import { useEffect, useMemo, useState } from 'preact/hooks'
2
+ import { useEffect, useMemo, useRef, useState } from 'preact/hooks'
3
3
  import { EnvBadge } from '../components/EnvBadge'
4
4
  import type { Variant } from '../engine'
5
5
  import { fieldDoc, withNote } from '../fielddoc'
6
6
  import { engine, isStatic, registry, saveFile } from '../runtime'
7
7
  import { type Defs, type JsonSchema, propsOf, unwrap } from '../schema'
8
8
  import { statusClass, statusName } from '../status'
9
- import { env, locale, seed, version } from '../store'
9
+ import { kv } from '../storage'
10
+ import { env, envSettingsOpen, envVarsVersion, features, locale, seed, version } from '../store'
11
+ import { announcement, describeRun } from './announce'
10
12
  import { Body } from './Body'
11
13
  import { DraftCodeSample } from './CodeSample'
12
14
  import { type Draft, draftFrom, forStorage, previewUrl, requestParts } from './draft'
13
15
  import { useOperationNotes } from './fieldnotes'
14
- import { PaperPlane } from './icons'
16
+ import { PaperPlane, StopSquare } from './icons'
15
17
  import { type Documented, ParamGrid } from './ParamGrid'
16
18
  import { RequestView } from './RequestView'
17
19
  import { ResponseView } from './ResponseView'
@@ -33,6 +35,8 @@ interface Props {
33
35
  variants: Variant[]
34
36
  /** example name to open, '' for the first */
35
37
  initial: string
38
+ /** run once as soon as the request is ready (an embed that asks for it, never against production) */
39
+ autoRun?: boolean
36
40
  }
37
41
 
38
42
  const storeKey = (key: string, sel: string) => `specbook:draft:${key}:${sel}`
@@ -44,7 +48,7 @@ const slug = (s: string) =>
44
48
 
45
49
  function readDraft(key: string): Draft | undefined {
46
50
  try {
47
- const raw = localStorage.getItem(key)
51
+ const raw = kv.local.getItem(key)
48
52
  return raw ? (JSON.parse(raw) as Draft) : undefined
49
53
  } catch {
50
54
  return undefined
@@ -64,21 +68,28 @@ interface SavedExample {
64
68
 
65
69
  function takeSaved(key: string): SavedExample | undefined {
66
70
  try {
67
- const raw = sessionStorage.getItem(SAVED_KEY)
71
+ const raw = kv.session.getItem(SAVED_KEY)
68
72
  const saved = raw ? (JSON.parse(raw) as SavedExample) : undefined
69
73
  if (saved?.key !== key) return undefined
70
- sessionStorage.removeItem(SAVED_KEY)
74
+ kv.session.removeItem(SAVED_KEY)
71
75
  return saved
72
76
  } catch {
73
77
  return undefined
74
78
  }
75
79
  }
76
80
 
77
- export function RequestPanel({ service, op, variants, initial }: Props) {
81
+ export function RequestPanel({ service, op, variants, initial, autoRun }: Props) {
78
82
  const key = `${service}/${op.id}`
83
+ const panelRoot = useRef<HTMLDivElement>(null)
84
+ const autoRan = useRef(false)
85
+ /** ends the request that is out: a person pressing Stop, so a request that never answers is not the end of the panel */
86
+ const stopper = useRef<AbortController | undefined>(undefined)
79
87
  const examples = engine.examplesOf(key)
80
88
  const [notice, setNotice] = useState<SavedExample | undefined>(() => takeSaved(key))
81
89
  const [sel, setSel] = useState(() => {
90
+ // a link to a saved request ("saved:<file>") opens on it
91
+ if (initial?.startsWith('saved:') && variants.some((v) => `saved:${v.file}` === initial))
92
+ return initial
82
93
  const named = examples.find((e) => e.name === (notice?.name ?? initial))
83
94
  return named
84
95
  ? `ex:${named.name}`
@@ -110,11 +121,27 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
110
121
  const [baseUrl, setBaseUrl] = useState('')
111
122
  const [known, setKnown] = useState<string[]>()
112
123
 
124
+ const [addressError, setAddressError] = useState<string>()
113
125
  useEffect(() => {
126
+ let on = true
127
+ setAddressError(undefined)
128
+ // mock has no address; elsewhere it is whatever this environment's variables make it
129
+ if (env.value === 'mock') {
130
+ setBaseUrl('')
131
+ return
132
+ }
114
133
  engine
115
- .config(version.value)
116
- .then((c) => setBaseUrl(c.services?.[service]?.baseUrl?.[env.value] ?? ''))
117
- }, [service, env.value])
134
+ .baseUrlOf(service, env.value, version.value)
135
+ .then((url) => on && setBaseUrl(url ?? ''))
136
+ .catch((e: unknown) => {
137
+ if (!on) return
138
+ setBaseUrl('')
139
+ setAddressError(e instanceof Error ? e.message : String(e))
140
+ })
141
+ return () => {
142
+ on = false
143
+ }
144
+ }, [service, env.value, version.value, envVarsVersion.value])
118
145
 
119
146
  useEffect(() => {
120
147
  let live = true
@@ -174,8 +201,8 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
174
201
  try {
175
202
  const k = storeKey(key, sel)
176
203
  if (baseDraft && JSON.stringify(forStorage(d)) === JSON.stringify(forStorage(baseDraft)))
177
- localStorage.removeItem(k)
178
- else localStorage.setItem(k, JSON.stringify(forStorage(d)))
204
+ kv.local.removeItem(k)
205
+ else kv.local.setItem(k, JSON.stringify(forStorage(d)))
179
206
  } catch {
180
207
  /* optional */
181
208
  }
@@ -217,37 +244,49 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
217
244
 
218
245
  // placeholders nothing supplies: not in config or the environment's files. They stay listed while
219
246
  // you type, so the field you are filling does not disappear under you.
220
- const needed = known ? placeholders.filter((n) => !known.includes(n)) : []
247
+ // a saved request brings the values of its own `init`: they are what a run uses, so nothing is missing
248
+ const own = Object.keys(saved?.def.input.init ?? {})
249
+ const needed = known ? placeholders.filter((n) => !known.includes(n) && !own.includes(n)) : []
221
250
  const unfilled = needed.filter((n) => (vars[n] ?? '') === '')
222
251
 
223
252
  const play = async (forceStatus?: number) => {
224
- if (!draft) return
253
+ if (!draft || stopper.current) return
225
254
  setError(undefined)
226
255
  setRunning(true)
256
+ const stop = new AbortController()
257
+ stopper.current = stop
227
258
  try {
228
259
  const def = saved
229
260
  ? saved.def
230
261
  : await engine.operationRequest(key, version.value, requestParts(draft, encoding))
231
- setResult(
232
- await engine.run(def, {
233
- env: env.value,
234
- version: version.value,
235
- mockStatus: env.value === 'mock' ? (forceStatus ?? forced) : undefined,
236
- locale: locale.value,
237
- seed: seed.value,
238
- vars: Object.fromEntries(Object.entries(vars).filter(([, v]) => v !== '')),
239
- fileDir: base?.dir,
240
- }),
241
- )
262
+ const ran = await engine.run(def, {
263
+ env: env.value,
264
+ version: version.value,
265
+ mockStatus: env.value === 'mock' ? (forceStatus ?? forced) : undefined,
266
+ locale: locale.value,
267
+ seed: seed.value,
268
+ vars: Object.fromEntries(Object.entries(vars).filter(([, v]) => v !== '')),
269
+ fileDir: base?.dir,
270
+ signal: stop.signal,
271
+ })
272
+ setResult(ran)
273
+ announcement.value = describeRun(ran)
242
274
  } catch (e) {
243
275
  setError(e instanceof Error ? e.message : String(e))
244
276
  } finally {
277
+ stopper.current = undefined
245
278
  setRunning(false)
246
279
  // what you sent a request to see is the response, so show it (the tab stays one click away)
247
280
  setTab('response')
248
281
  }
249
282
  }
250
283
 
284
+ useEffect(() => {
285
+ if (!autoRun || !draft || autoRan.current) return
286
+ autoRan.current = true
287
+ void play()
288
+ }, [draft])
289
+
251
290
  const saveExample = async (name: string) => {
252
291
  if (!draft) return
253
292
  const parts = requestParts(draft, encoding)
@@ -265,7 +304,7 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
265
304
  // set before writing: the watcher reloads the page as soon as the file lands
266
305
  const saved: SavedExample = { key, path, name: file }
267
306
  try {
268
- sessionStorage.setItem(SAVED_KEY, JSON.stringify(saved))
307
+ kv.session.setItem(SAVED_KEY, JSON.stringify(saved))
269
308
  } catch {
270
309
  /* the confirmation below still shows when there is no reload */
271
310
  }
@@ -301,12 +340,14 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
301
340
  play()
302
341
  }
303
342
  }
304
- addEventListener('keydown', send)
305
- return () => removeEventListener('keydown', send)
343
+ // on the page's own root (a shadow root in an embed), not the window, so a host page's keys are left alone
344
+ const root: EventTarget = panelRoot.current?.getRootNode() ?? window
345
+ root.addEventListener('keydown', send as EventListener)
346
+ return () => root.removeEventListener('keydown', send as EventListener)
306
347
  })
307
348
 
308
349
  return (
309
- <div class="request-panel" data-op={key}>
350
+ <div class="request-panel" data-op={key} ref={panelRoot}>
310
351
  <div class="rq">
311
352
  <div class="rq-bar">
312
353
  <span class={`method ${op.method}`}>{op.method}</span>
@@ -332,15 +373,26 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
332
373
  <button
333
374
  type="button"
334
375
  class="btn primary send"
335
- title="Send (⌘/Ctrl + Enter)"
336
- aria-label="Send"
337
- disabled={running || !draft}
338
- onClick={() => play()}
376
+ title={running ? 'Stop' : 'Send (⌘/Ctrl + Enter)'}
377
+ aria-label={running ? 'Stop' : 'Send'}
378
+ disabled={!running && !draft}
379
+ onClick={() => (running ? stopper.current?.abort() : play())}
339
380
  >
340
- {running ? '…' : <PaperPlane />}
381
+ {running ? <StopSquare /> : <PaperPlane />}
341
382
  </button>
342
383
  </div>
343
384
 
385
+ {addressError && (
386
+ <p class="envmenu-warn" role="alert">
387
+ {addressError}.{' '}
388
+ {features.value.environmentSettings && (
389
+ <button type="button" class="link" onClick={() => (envSettingsOpen.value = true)}>
390
+ Open Environment settings
391
+ </button>
392
+ )}
393
+ </p>
394
+ )}
395
+
344
396
  {requestNote && (
345
397
  <details class="step-about" key={saved?.file}>
346
398
  <summary>About this request</summary>
@@ -468,8 +520,7 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
468
520
 
469
521
  {saved && (
470
522
  <p class="muted lock">
471
- A saved request: its own values, checks and mock responses apply, and it is read-only
472
- here.
523
+ A saved request: its own values, checks and mock hook apply, and it is read-only here.
473
524
  </p>
474
525
  )}
475
526
 
@@ -540,6 +591,7 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
540
591
  title="Query"
541
592
  rows={draft.query}
542
593
  documented={sections.query}
594
+ readOnly={!!saved}
543
595
  onChange={(query) => edit({ ...draft, query })}
544
596
  />
545
597
  )}
@@ -549,6 +601,7 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
549
601
  rows={draft.path}
550
602
  documented={sections.path}
551
603
  fixed
604
+ readOnly={!!saved}
552
605
  onChange={(path) => edit({ ...draft, path })}
553
606
  />
554
607
  )}
@@ -559,6 +612,7 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
559
612
  title="Headers"
560
613
  rows={draft.headers}
561
614
  documented={sections.headers}
615
+ readOnly={!!saved}
562
616
  onChange={(headers) => edit({ ...draft, headers })}
563
617
  />
564
618
  )}
@@ -573,6 +627,7 @@ export function RequestPanel({ service, op, variants, initial }: Props) {
573
627
  defs={defs}
574
628
  files={meta?.files}
575
629
  notes={opNotes.notes}
630
+ readOnly={!!saved}
576
631
  />
577
632
  )}
578
633
  </div>
@@ -4,8 +4,9 @@ import { fieldDoc, withNote } from '../fielddoc'
4
4
  import { type Defs, type JsonSchema, linePaths, pathString } from '../schema'
5
5
  import { BodyEditor } from './BodyEditor'
6
6
  import { FieldDoc } from './FieldDoc'
7
+ import { show } from './short'
7
8
 
8
- const pretty = (v: unknown) => (typeof v === 'string' ? v : JSON.stringify(v, null, 2))
9
+ const pretty = (v: unknown) => (typeof v === 'string' ? v : show(v, 2))
9
10
 
10
11
  /** Repeated keys for arrays, as the transport sends them. */
11
12
  export function queryString(query: Record<string, string | string[]>) {
@@ -1,12 +1,14 @@
1
1
  import type { StepResult } from '@specbook/core'
2
- import { useMemo, useState } from 'preact/hooks'
2
+ import { useEffect, useMemo, useState } from 'preact/hooks'
3
3
  import { fieldDoc } from '../fielddoc'
4
4
  import { type Defs, type JsonSchema, linePaths, validate } from '../schema'
5
5
  import { statusClass, statusName } from '../status'
6
6
  import { BodyEditor } from './BodyEditor'
7
+ import { Checks } from './Checks'
7
8
  import { FieldDoc } from './FieldDoc'
8
9
  import { PaperPlane } from './icons'
9
10
  import { queryString } from './RequestView'
11
+ import { show } from './short'
10
12
 
11
13
  interface Props {
12
14
  step?: StepResult
@@ -17,7 +19,7 @@ interface Props {
17
19
  hideRequest?: boolean
18
20
  }
19
21
 
20
- const pretty = (v: unknown) => JSON.stringify(v, null, 2)
22
+ const pretty = (v: unknown) => show(v, 2)
21
23
  const size = (n: number) => (n < 1024 ? `${n} B` : `${(n / 1024).toFixed(1)} KB`)
22
24
 
23
25
  export function ResponseView({ step, error, schemas, defs, hideRequest }: Props) {
@@ -25,10 +27,14 @@ export function ResponseView({ step, error, schemas, defs, hideRequest }: Props)
25
27
  const [line, setLine] = useState(0)
26
28
  const response = step?.response
27
29
  const schema = response ? (schemas?.[String(response.status)] ?? schemas?.default) : undefined
28
- const issues = useMemo(
29
- () => (response && schema ? validate(response.body, schema, defs, { reportExtra: true }) : []),
30
- [response, schema, defs],
31
- )
30
+ const issues = useMemo(() => {
31
+ try {
32
+ return response && schema ? validate(response.body, schema, defs, { reportExtra: true }) : []
33
+ } catch {
34
+ // an answer the schema check cannot make sense of is shown as it came, without the check
35
+ return []
36
+ }
37
+ }, [response, schema, defs])
32
38
  const text =
33
39
  response === undefined || response.body === undefined || response.body === ''
34
40
  ? ''
@@ -42,6 +48,10 @@ export function ResponseView({ step, error, schemas, defs, hideRequest }: Props)
42
48
  }, [paths, line, schema, defs])
43
49
  const checks = step?.assertions ?? []
44
50
  const failed = checks.filter((a) => !a.pass).length
51
+ // a run that failed a check opens on it: that is what the person came to see
52
+ useEffect(() => {
53
+ if (step && failed > 0) setTab('checks')
54
+ }, [step])
45
55
  const headers = Object.entries(response?.headers ?? {})
46
56
  const empty = !response && !error && !step?.error
47
57
 
@@ -112,7 +122,14 @@ export function ResponseView({ step, error, schemas, defs, hideRequest }: Props)
112
122
  >
113
123
  {label}
114
124
  {n > 0 && (
115
- <span class={`count ${id === 'checks' && failed ? 'bad' : ''}`}>{n}</span>
125
+ <span
126
+ class={`count ${id === 'checks' && failed ? 'bad' : ''}`}
127
+ title={
128
+ id === 'checks' && failed ? `${failed} of ${n} checks failed` : undefined
129
+ }
130
+ >
131
+ {id === 'checks' && failed ? failed : n}
132
+ </span>
116
133
  )}
117
134
  </button>
118
135
  ))}
@@ -165,13 +182,7 @@ export function ResponseView({ step, error, schemas, defs, hideRequest }: Props)
165
182
  {checks.length === 0 ? (
166
183
  <p class="muted">This request has no checks.</p>
167
184
  ) : (
168
- <ul class="checks">
169
- {checks.map((a) => (
170
- <li class={a.pass ? 'ok' : 'bad'}>
171
- {a.pass ? '✓' : '✗'} {a.label}
172
- </li>
173
- ))}
174
- </ul>
185
+ <Checks assertions={checks} />
175
186
  )}
176
187
  </div>
177
188
  </div>
@@ -1,10 +1,9 @@
1
- import type { AuthProfile, OAuthSettings } from '@specbook/core'
1
+ import { absoluteBase, type OAuthSettings } from '@specbook/core'
2
2
  import { useEffect, useState } from 'preact/hooks'
3
3
  import { expiryOf, noteExpiry } from '../oauth'
4
- import { absoluteBase } from '../routing'
5
4
  import { engine } from '../runtime'
6
5
  import { originOf, SECRET_PLACEHOLDER, secretStore } from '../secrets'
7
- import { env, version } from '../store'
6
+ import { env, envVarsVersion, version } from '../store'
8
7
  import { OAuthSignIn } from './OAuthSignIn'
9
8
 
10
9
  interface Need {
@@ -60,15 +59,17 @@ export function SecretsBar({
60
59
  }
61
60
  let on = true
62
61
  if (!supplied) engine.managedSecrets(env.value).then((m) => on && setManaged(m))
63
- engine.config(version.value).then((cfg) => {
64
- if (!on) return
62
+ engine.config(version.value).then(async (cfg) => {
65
63
  const out: Need[] = []
64
+ const where = await engine.addressesIn(cfg, env.value)
66
65
  for (const [service, s] of Object.entries(cfg.services ?? {})) {
67
66
  if (services && !services.includes(service)) continue
68
67
  const profile = s.auth ? cfg.auth?.[s.auth] : undefined
69
- const base = s.baseUrl?.[env.value]
68
+ // the address this environment's variables give; one that cannot be worked out has no origin
69
+ const base = where.baseUrl(service)
70
70
  const origin = originOf(base ? absoluteBase(base, globalThis.location?.href) : undefined)
71
71
  if (!profile || !origin) continue
72
+ const oauth = s.auth ? where.oauth(s.auth) : undefined
72
73
  const names = [
73
74
  ...new Set(
74
75
  [...JSON.stringify(profile.apply).matchAll(SECRET_PLACEHOLDER)].map(
@@ -83,15 +84,15 @@ export function SecretsBar({
83
84
  title: profile.title ?? s.auth ?? '',
84
85
  names,
85
86
  profile: s.auth as string,
86
- oauth: (profile as AuthProfile).oauth,
87
+ oauth,
87
88
  })
88
89
  }
89
- setNeeds(out)
90
+ if (on) setNeeds(out)
90
91
  })
91
92
  return () => {
92
93
  on = false
93
94
  }
94
- }, [live, env.value, wanted, version.value])
95
+ }, [live, env.value, wanted, version.value, envVarsVersion.value])
95
96
 
96
97
  if (!live || needs.length === 0) return null
97
98
  const have = (n: Need, name: string) =>