@mailwoman/react 10.7.0 → 10.8.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 (56) hide show
  1. package/README.md +6 -3
  2. package/fonts.css +7 -129
  3. package/lib/map/Geocoder.tsx +35 -18
  4. package/lib/map/GeocoderControls.tsx +27 -14
  5. package/lib/map/MapCanvas.tsx +25 -1
  6. package/lib/map/PlaceMarker.tsx +4 -2
  7. package/lib/map/ResultOverlay.tsx +5 -2
  8. package/lib/map/StarfieldLayer.tsx +114 -0
  9. package/lib/map/starfield.ts +335 -0
  10. package/lib/map/types.ts +7 -3
  11. package/lib/pipeline/CandidatePicker.tsx +8 -1
  12. package/lib/pipeline/ResolvedPlace.tsx +1 -1
  13. package/lib/poi/runtime.ts +1 -1
  14. package/lib/search/SearchModal.tsx +56 -9
  15. package/lib/search/search.css +62 -62
  16. package/out/map/Geocoder.d.ts.map +1 -1
  17. package/out/map/Geocoder.js +16 -3
  18. package/out/map/Geocoder.js.map +1 -1
  19. package/out/map/GeocoderControls.d.ts.map +1 -1
  20. package/out/map/GeocoderControls.js +26 -14
  21. package/out/map/GeocoderControls.js.map +1 -1
  22. package/out/map/MapCanvas.d.ts +11 -1
  23. package/out/map/MapCanvas.d.ts.map +1 -1
  24. package/out/map/MapCanvas.js +34 -3
  25. package/out/map/MapCanvas.js.map +1 -1
  26. package/out/map/PlaceMarker.d.ts.map +1 -1
  27. package/out/map/PlaceMarker.js +17 -2
  28. package/out/map/PlaceMarker.js.map +1 -1
  29. package/out/map/ResultOverlay.d.ts.map +1 -1
  30. package/out/map/ResultOverlay.js +10 -2
  31. package/out/map/ResultOverlay.js.map +1 -1
  32. package/out/map/StarfieldLayer.d.ts +24 -0
  33. package/out/map/StarfieldLayer.d.ts.map +1 -0
  34. package/out/map/StarfieldLayer.js +75 -0
  35. package/out/map/StarfieldLayer.js.map +1 -0
  36. package/out/map/starfield.d.ts +124 -0
  37. package/out/map/starfield.d.ts.map +1 -0
  38. package/out/map/starfield.js +200 -0
  39. package/out/map/starfield.js.map +1 -0
  40. package/out/map/types.d.ts +7 -3
  41. package/out/map/types.d.ts.map +1 -1
  42. package/out/pipeline/CandidatePicker.d.ts.map +1 -1
  43. package/out/pipeline/CandidatePicker.js +7 -1
  44. package/out/pipeline/CandidatePicker.js.map +1 -1
  45. package/out/pipeline/ResolvedPlace.js +1 -1
  46. package/out/pipeline/ResolvedPlace.js.map +1 -1
  47. package/out/poi/runtime.js +1 -1
  48. package/out/poi/runtime.js.map +1 -1
  49. package/out/search/SearchModal.d.ts.map +1 -1
  50. package/out/search/SearchModal.js +39 -9
  51. package/out/search/SearchModal.js.map +1 -1
  52. package/package.json +23 -21
  53. package/styles.css +436 -450
  54. package/tokens/index.css +600 -129
  55. package/tokens/tokens.json +1736 -539
  56. package/tokens/tokens.resolver.json +272 -138
@@ -0,0 +1,335 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * A procedural star sky for the globe projection, and the camera math that places it on screen.
7
+ *
8
+ * Stars are unit vectors fixed to the Earth's frame, so the sky turns with the globe as the camera orbits it. Their
9
+ * magnitudes follow the naked-eye count law, where each fainter magnitude holds about 3.2 times the star count,
10
+ * and a share of them crowd a band along the real galactic plane. The catalog is seeded, so every render of the
11
+ * same options draws the same sky.
12
+ *
13
+ * This module touches no DOM or WebGL at import, so node tests can load it.
14
+ */
15
+
16
+ import { mulberry32 } from "@mailwoman/core/random"
17
+
18
+ /**
19
+ * The options that shape a generated sky.
20
+ */
21
+ export interface StarfieldOptions {
22
+ /**
23
+ * The number of stars to generate.
24
+ *
25
+ * MapLibre's vertical field of view is about 37°, so roughly 6% of the sphere is on screen at once.
26
+ *
27
+ * @defaultValue 20000
28
+ */
29
+ count?: number
30
+ /**
31
+ * Seed for the generator.
32
+ * The same seed draws the same sky.
33
+ *
34
+ * @defaultValue 1
35
+ */
36
+ seed?: number
37
+ /**
38
+ * Share of stars drawn into the Milky Way band, from 0 to 1.
39
+ *
40
+ * @defaultValue 0.35
41
+ */
42
+ bandShare?: number
43
+ /**
44
+ * Fill painted behind the stars, or `null` to leave the canvas transparent.
45
+ *
46
+ * @defaultValue `"#02030a"`
47
+ */
48
+ background?: string | null
49
+ }
50
+
51
+ /**
52
+ * A generated sky.
53
+ *
54
+ * Each star occupies one stride of `STAR_STRIDE` floats in `data`: x, y, z,
55
+ * radius in CSS pixels, alpha, then red, green and blue from 0 to 255.
56
+ */
57
+ export interface StarCatalog {
58
+ count: number
59
+ data: Float32Array
60
+ }
61
+
62
+ /**
63
+ * The number of floats each star occupies in `StarCatalog.data`.
64
+ */
65
+ export const STAR_STRIDE = 8
66
+
67
+ /**
68
+ * The camera state the sky projection reads, in MapLibre's units.
69
+ */
70
+ export interface SkyCamera {
71
+ /**
72
+ * Map center longitude in degrees.
73
+ */
74
+ lng: number
75
+ /**
76
+ * Map center latitude in degrees.
77
+ */
78
+ lat: number
79
+ /**
80
+ * Degrees clockwise from north.
81
+ */
82
+ bearing: number
83
+ /**
84
+ * Degrees of tilt away from looking straight down.
85
+ */
86
+ pitch: number
87
+ /**
88
+ * Vertical field of view in degrees.
89
+ */
90
+ fov: number
91
+ }
92
+
93
+ type Vec3 = readonly [number, number, number]
94
+
95
+ const DEG = Math.PI / 180
96
+
97
+ // The brightest and faintest magnitudes drawn.
98
+ // Sirius sits near -1.5, and 6.5 is the naked-eye limit under a dark sky.
99
+ const MAG_BRIGHT = -1.5
100
+ const MAG_FAINT = 6.5
101
+ // N(<m) grows as 10^(K·m).
102
+ // K = 0.5 roughly matches the bright-star catalog counts between magnitudes 0 and 6.5.
103
+ const MAG_SLOPE = 0.5
104
+
105
+ // The galactic north pole and the galactic center in equatorial coordinates (J2000),
106
+ // treating right ascension as a longitude on the Earth-fixed sphere.
107
+ const GALACTIC_POLE = unitVector(192.859, 27.128)
108
+ const GALACTIC_CENTER = unitVector(266.405, -28.936)
109
+ const GALACTIC_THIRD = cross(GALACTIC_POLE, GALACTIC_CENTER)
110
+ // Below this radius in CSS pixels a star is drawn as one whole pixel rather than a disc.
111
+ const POINT_RADIUS = 0.9
112
+
113
+ // Standard deviation, in degrees of galactic latitude, of a band star's distance from the plane.
114
+ const BAND_WIDTH = 9
115
+
116
+ // Star colors by B−V color index, from hot blue stars to cool red ones.
117
+ const COLOR_STOPS: readonly (readonly [number, number, number, number])[] = [
118
+ [-0.3, 155, 176, 255],
119
+ [0, 202, 215, 255],
120
+ [0.3, 248, 247, 255],
121
+ [0.6, 255, 244, 234],
122
+ [0.9, 255, 222, 180],
123
+ [1.4, 255, 196, 130],
124
+ [2, 255, 170, 100],
125
+ ]
126
+
127
+ /**
128
+ * Converts a longitude and latitude in degrees to a unit vector in the Earth-fixed frame.
129
+ */
130
+ export function unitVector(lng: number, lat: number): Vec3 {
131
+ const cosLat = Math.cos(lat * DEG)
132
+
133
+ return [cosLat * Math.cos(lng * DEG), cosLat * Math.sin(lng * DEG), Math.sin(lat * DEG)]
134
+ }
135
+
136
+ function cross(a: Vec3, b: Vec3): Vec3 {
137
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
138
+ }
139
+
140
+ function gaussian(random: () => number): number {
141
+ const u = Math.max(random(), Number.EPSILON)
142
+
143
+ return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * random())
144
+ }
145
+
146
+ /**
147
+ * Draws a magnitude from the count law by inverting its cumulative distribution over the drawn range.
148
+ */
149
+ function sampleMagnitude(u: number): number {
150
+ const span = 10 ** (MAG_SLOPE * (MAG_FAINT - MAG_BRIGHT)) - 1
151
+
152
+ return MAG_BRIGHT + Math.log10(1 + u * span) / MAG_SLOPE
153
+ }
154
+
155
+ /**
156
+ * Draws a B−V index from a mixture weighted toward the sun-like and orange
157
+ * stars that dominate a naked-eye sky.
158
+ */
159
+ function sampleColorIndex(random: () => number): number {
160
+ const value = 0.55 + 0.45 * gaussian(random)
161
+
162
+ return Math.min(2, Math.max(-0.3, value))
163
+ }
164
+
165
+ /**
166
+ * Interpolates the RGB color of a star from its B−V index.
167
+ */
168
+ export function starColor(colorIndex: number): [number, number, number] {
169
+ const last = COLOR_STOPS.at(-1)!
170
+
171
+ if (colorIndex >= last[0]) return [last[1], last[2], last[3]]
172
+
173
+ for (let i = 1; i < COLOR_STOPS.length; i++) {
174
+ const upper = COLOR_STOPS[i]!
175
+
176
+ if (colorIndex > upper[0]) continue
177
+
178
+ const lower = COLOR_STOPS[i - 1]!
179
+ const t = Math.max(0, (colorIndex - lower[0]) / (upper[0] - lower[0]))
180
+
181
+ return [
182
+ lower[1] + (upper[1] - lower[1]) * t,
183
+ lower[2] + (upper[2] - lower[2]) * t,
184
+ lower[3] + (upper[3] - lower[3]) * t,
185
+ ]
186
+ }
187
+
188
+ const first = COLOR_STOPS[0]!
189
+
190
+ return [first[1], first[2], first[3]]
191
+ }
192
+
193
+ /**
194
+ * Generates a seeded star catalog.
195
+ */
196
+ export function generateStarfield(options: StarfieldOptions = {}): StarCatalog {
197
+ const count = options.count ?? 20_000
198
+ const bandShare = options.bandShare ?? 0.35
199
+ const random = mulberry32(options.seed ?? 1)
200
+ const data = new Float32Array(count * STAR_STRIDE)
201
+
202
+ for (let i = 0; i < count; i++) {
203
+ const galacticLng = random() * 2 * Math.PI
204
+
205
+ const galacticLat =
206
+ random() < bandShare
207
+ ? Math.max(-Math.PI / 2, Math.min(Math.PI / 2, gaussian(random) * BAND_WIDTH * DEG))
208
+ : Math.asin(2 * random() - 1)
209
+
210
+ const cosB = Math.cos(galacticLat)
211
+ const a = cosB * Math.cos(galacticLng)
212
+ const b = cosB * Math.sin(galacticLng)
213
+ const c = Math.sin(galacticLat)
214
+
215
+ const magnitude = sampleMagnitude(random())
216
+ // Brightness runs from 0 at the naked-eye limit to 1 at the brightest drawn star.
217
+ const brightness = (MAG_FAINT - magnitude) / (MAG_FAINT - MAG_BRIGHT)
218
+ const [red, green, blue] = starColor(sampleColorIndex(random))
219
+
220
+ const offset = i * STAR_STRIDE
221
+ data[offset] = a * GALACTIC_CENTER[0] + b * GALACTIC_THIRD[0] + c * GALACTIC_POLE[0]
222
+ data[offset + 1] = a * GALACTIC_CENTER[1] + b * GALACTIC_THIRD[1] + c * GALACTIC_POLE[1]
223
+ data[offset + 2] = a * GALACTIC_CENTER[2] + b * GALACTIC_THIRD[2] + c * GALACTIC_POLE[2]
224
+ // Most stars sit near the faint limit, so the floors keep them visible as single-pixel points on a display.
225
+ data[offset + 3] = 0.6 + 1.6 * brightness ** 2
226
+ data[offset + 4] = 0.45 + 0.55 * Math.sqrt(brightness)
227
+ data[offset + 5] = red
228
+ data[offset + 6] = green
229
+ data[offset + 7] = blue
230
+ }
231
+
232
+ return { count, data }
233
+ }
234
+
235
+ /**
236
+ * The camera's right, up and forward axes in the Earth-fixed frame.
237
+ *
238
+ * The camera sits above the map center and looks toward the Earth.
239
+ * Pitch tilts the view from straight down toward the heading.
240
+ *
241
+ * The map's rotation angle turns the heading clockwise from north.
242
+ */
243
+ export interface CameraBasis {
244
+ right: Vec3
245
+ up: Vec3
246
+ forward: Vec3
247
+ }
248
+
249
+ /**
250
+ * Computes the camera axes for a MapLibre camera state.
251
+ */
252
+ export function cameraBasis(camera: SkyCamera): CameraBasis {
253
+ const lng = camera.lng * DEG
254
+ const lat = camera.lat * DEG
255
+ const bearing = camera.bearing * DEG
256
+ const pitch = camera.pitch * DEG
257
+
258
+ const zenith = unitVector(camera.lng, camera.lat)
259
+ const east: Vec3 = [-Math.sin(lng), Math.cos(lng), 0]
260
+ const north: Vec3 = [-Math.sin(lat) * Math.cos(lng), -Math.sin(lat) * Math.sin(lng), Math.cos(lat)]
261
+
262
+ const cosB = Math.cos(bearing)
263
+ const sinB = Math.sin(bearing)
264
+ const heading = combine(north, cosB, east, sinB)
265
+ const right = combine(east, cosB, north, -sinB)
266
+
267
+ const cosP = Math.cos(pitch)
268
+ const sinP = Math.sin(pitch)
269
+
270
+ return {
271
+ right,
272
+ up: combine(zenith, sinP, heading, cosP),
273
+ forward: combine(zenith, -cosP, heading, sinP),
274
+ }
275
+ }
276
+
277
+ function combine(a: Vec3, wa: number, b: Vec3, wb: number): Vec3 {
278
+ return [a[0] * wa + b[0] * wb, a[1] * wa + b[1] * wb, a[2] * wa + b[2] * wb]
279
+ }
280
+
281
+ /**
282
+ * Paints the catalog onto a 2D context for one camera state.
283
+ *
284
+ * `width` and `height` are the canvas size in CSS pixels.
285
+ * The caller scales the context for the device pixel ratio.
286
+ */
287
+ export function drawStarfield(
288
+ context: CanvasRenderingContext2D,
289
+ catalog: StarCatalog,
290
+ camera: SkyCamera,
291
+ width: number,
292
+ height: number,
293
+ background: string | null
294
+ ): void {
295
+ context.clearRect(0, 0, width, height)
296
+
297
+ if (background) {
298
+ context.fillStyle = background
299
+ context.fillRect(0, 0, width, height)
300
+ }
301
+
302
+ const { right, up, forward } = cameraBasis(camera)
303
+ const focal = height / 2 / Math.tan((camera.fov * DEG) / 2)
304
+ const centerX = width / 2
305
+ const centerY = height / 2
306
+ const { data } = catalog
307
+
308
+ for (let i = 0; i < catalog.count; i++) {
309
+ const offset = i * STAR_STRIDE
310
+ const x = data[offset]!
311
+ const y = data[offset + 1]!
312
+ const z = data[offset + 2]!
313
+
314
+ const depth = x * forward[0] + y * forward[1] + z * forward[2]
315
+
316
+ if (depth <= 0) continue
317
+
318
+ const screenX = centerX + (focal * (x * right[0] + y * right[1] + z * right[2])) / depth
319
+ const screenY = centerY - (focal * (x * up[0] + y * up[1] + z * up[2])) / depth
320
+ const radius = data[offset + 3]!
321
+
322
+ if (screenX < -radius || screenX > width + radius || screenY < -radius || screenY > height + radius) continue
323
+
324
+ context.fillStyle = `rgb(${data[offset + 5]} ${data[offset + 6]} ${data[offset + 7]} / ${data[offset + 4]})`
325
+
326
+ // A sub-pixel square anti-aliases into a smear across four pixels, so faint stars snap to one whole pixel.
327
+ if (radius < POINT_RADIUS) {
328
+ context.fillRect(Math.round(screenX), Math.round(screenY), 1, 1)
329
+ } else {
330
+ context.beginPath()
331
+ context.arc(screenX, screenY, radius, 0, 2 * Math.PI)
332
+ context.fill()
333
+ }
334
+ }
335
+ }
package/lib/map/types.ts CHANGED
@@ -89,9 +89,13 @@ export interface VersionOption {
89
89
  */
90
90
  export interface GeocoderRuntime extends PipelineRuntime {
91
91
  /**
92
- * The composed basemap style (URL or `StyleSpecification`).
92
+ * The composed basemap style (URL or `StyleSpecification`), or `null`
93
+ * while the host is still composing it.
94
+ *
95
+ * The map mounts once the style is set.
96
+ * A host that waits for its inputs hands the map one style, so MapLibre never rebuilds it.
93
97
  */
94
- mapStyle: MapCanvasStyle
98
+ mapStyle: MapCanvasStyle | null
95
99
  overlays?: OverlaySpec[]
96
100
  /**
97
101
  * Initial map center as `[lon, lat]`.
@@ -116,7 +120,7 @@ export interface GeocoderRuntime extends PipelineRuntime {
116
120
  /**
117
121
  * Maps a raw model score to a calibrated one; `null` when no calibration table is loaded.
118
122
  */
119
- calibrator?: (raw: number) => number | null
123
+ calibrator?: ((raw: number) => number | null) | null
120
124
  /**
121
125
  * Enrich the selected candidate into the richer {@link ResolvedMapPlace} the declarative
122
126
  * map render consumes (bbox, street tier + uncertainty, a pre-fetched crisp polygon) —
@@ -28,6 +28,13 @@ export interface CandidatePickerProps {
28
28
  onSelect: (index: number) => void
29
29
  }
30
30
 
31
+ /**
32
+ * The score as the row's tooltip shows it, or `unscored` when the resolver recorded none.
33
+ */
34
+ function scoreLabel(score: number | null): string {
35
+ return score == null ? "unscored" : `score ${score.toFixed(3)}`
36
+ }
37
+
31
38
  export function CandidatePicker({ candidates, selectedIndex, onSelect }: CandidatePickerProps): ReactNode {
32
39
  return (
33
40
  <div className="mw-candidates">
@@ -39,7 +46,7 @@ export function CandidatePicker({ candidates, selectedIndex, onSelect }: Candida
39
46
  type="button"
40
47
  className={cx("mw-candidates__btn", { "mw-candidates__btn--active": i === selectedIndex })}
41
48
  onClick={() => onSelect(i)}
42
- title={`${candidate.placetype} • WOF ${candidate.id} • score ${candidate.score.toFixed(3)}`}
49
+ title={`${candidate.placetype} • WOF ${candidate.id} • ${scoreLabel(candidate.score)}`}
43
50
  >
44
51
  <span className="mw-candidates__rank">#{i + 1}</span>
45
52
  <span className="mw-candidates__name">{candidate.name}</span>
@@ -45,7 +45,7 @@ export function ResolvedPlace({ place, dualRoles }: ResolvedPlaceProps): ReactNo
45
45
  {place.lat.toFixed(4)}, {place.lon.toFixed(4)}
46
46
  </dd>
47
47
  <dt>score</dt>
48
- <dd>{place.score.toFixed(3)}</dd>
48
+ <dd>{place.score == null ? "unscored" : place.score.toFixed(3)}</dd>
49
49
  </dl>
50
50
  {dualRoles && dualRoles.length ? (
51
51
  <p className="mw-resolved__dual">
@@ -34,7 +34,7 @@ export async function loadPOIRuntime(): Promise<POIRuntime> {
34
34
  categoryID: match.category.id,
35
35
  matchedPhrase: match.matchedPhrase,
36
36
  confidence: match.confidence,
37
- mechanism: "exact",
37
+ mechanism: match.phraseSource === "short-label" ? "short_label" : "exact",
38
38
  inputPhrase: phrase,
39
39
  wikidata: null,
40
40
  reading: "preference",
@@ -12,7 +12,17 @@
12
12
  */
13
13
 
14
14
  import { stringifyJSON, tryParsingJSON } from "@mailwoman/core/json"
15
- import { type KeyboardEvent, type MouseEvent, type ReactNode, useEffect, useId, useMemo, useRef, useState } from "react"
15
+ import {
16
+ type KeyboardEvent,
17
+ type MouseEvent,
18
+ type ReactNode,
19
+ useEffect,
20
+ useEffectEvent,
21
+ useId,
22
+ useMemo,
23
+ useRef,
24
+ useState,
25
+ } from "react"
16
26
 
17
27
  import { useDebouncedValue } from "#common/useDebouncedValue"
18
28
 
@@ -197,6 +207,11 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
197
207
  const listboxID = `${baseID}-listbox`
198
208
  const [query, setQuery] = useState("")
199
209
  const [settled, setSettled] = useState<Status>({ kind: "idle" })
210
+ // The query whose request settled `settled`, so a hit on screen can be matched to the query in the field.
211
+ const [answered, setAnswered] = useState("")
212
+ // The query of an Enter pressed while the hits on screen answered an earlier query.
213
+ // The response to that query opens its first hit.
214
+ const pendingEnter = useRef<string | null>(null)
200
215
  const [selected, setSelected] = useState(0)
201
216
  const [loading, setLoading] = useState(false)
202
217
  const [recent, setRecent] = useState<RecentHit[]>([])
@@ -217,6 +232,9 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
217
232
  }
218
233
  }, [open, recentKey])
219
234
 
235
+ // The search effect opens a hit for a pending Enter with the render's current recent hits and callbacks.
236
+ const openHit = useEffectEvent((hit: RecentHit) => go(hit))
237
+
220
238
  useEffect(() => {
221
239
  if (debounced === "") return
222
240
 
@@ -231,7 +249,18 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
231
249
  clearTimeout(loadingTimer)
232
250
  setLoading(false)
233
251
  setSettled({ kind: "results", response })
252
+ setAnswered(debounced)
234
253
  setSelected(0)
254
+
255
+ if (pendingEnter.current === debounced) {
256
+ pendingEnter.current = null
257
+ // The first option in display order is the first hit, because its category's group comes first.
258
+ const first = response.hits[0]
259
+
260
+ if (first) {
261
+ openHit(first)
262
+ }
263
+ }
235
264
  },
236
265
  () => {
237
266
  if (controller.signal.aborted) return
@@ -239,6 +268,11 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
239
268
  clearTimeout(loadingTimer)
240
269
  setLoading(false)
241
270
  setSettled({ kind: "failed" })
271
+ setAnswered(debounced)
272
+
273
+ if (pendingEnter.current === debounced) {
274
+ pendingEnter.current = null
275
+ }
242
276
  }
243
277
  )
244
278
 
@@ -251,7 +285,7 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
251
285
 
252
286
  // An empty query shows no results, whatever the last settled response was.
253
287
  const status: Status = debounced === "" ? { kind: "idle" } : settled
254
- const response = status.kind === "results" ? status.response : undefined
288
+ const response = status.kind === "results" ? status.response : null
255
289
  // The announcement reports a slow request while the last results stay on screen.
256
290
  const announced: Status = loading && debounced !== "" ? { kind: "loading" } : status
257
291
 
@@ -281,6 +315,9 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
281
315
  ? recent.map((hit, order) => ({ hit, order }))
282
316
  : groups.flatMap((group) => group.entries)
283
317
 
318
+ // The options on screen answer the field's query once the debounce has settled and that query's request has returned.
319
+ const answersField = showRecent || (trimmed === debounced && answered === debounced)
320
+
284
321
  const optionID = (order: number) => `${baseID}-option-${order}`
285
322
  const emphasis = response?.corrected ?? debounced
286
323
 
@@ -317,6 +354,14 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
317
354
  // A key that commits or edits an IME composition is not a command.
318
355
  if (event.nativeEvent.isComposing) return
319
356
 
357
+ // The options on screen, if any, answer an earlier query, so the Enter waits for the field's query to settle.
358
+ if (event.key === "Enter" && !answersField) {
359
+ event.preventDefault()
360
+ pendingEnter.current = trimmed
361
+
362
+ return
363
+ }
364
+
320
365
  if (!ordered.length) return
321
366
 
322
367
  // Delete removes the selected recent hit.
@@ -347,18 +392,15 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
347
392
  ? 0
348
393
  : event.key === "End"
349
394
  ? last
350
- : undefined
395
+ : null
351
396
 
352
- if (next !== undefined) {
397
+ if (typeof next === "number") {
353
398
  event.preventDefault()
354
399
  setSelected(next)
355
400
  document.getElementById(optionID(next))?.scrollIntoView({ block: "nearest" })
356
401
  } else if (event.key === "Enter") {
357
402
  event.preventDefault()
358
403
 
359
- // The hits on screen answer an earlier query until the debounce settles.
360
- if (trimmed !== debounced) return
361
-
362
404
  const entry = ordered[selected]
363
405
 
364
406
  if (entry) {
@@ -401,7 +443,7 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
401
443
  )
402
444
  }
403
445
 
404
- const noResults = response !== undefined && response.hits.length === 0
446
+ const noResults = response && response.hits.length === 0
405
447
 
406
448
  return (
407
449
  <dialog
@@ -412,6 +454,7 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
412
454
  // The next open starts on the recent hits rather than the last query.
413
455
  setQuery("")
414
456
  setSelected(0)
457
+ pendingEnter.current = null
415
458
  onClose()
416
459
  }}
417
460
  onClick={onDialogClick}
@@ -434,7 +477,11 @@ export function SearchModal({ open, onClose, onNavigate, search, recentKey }: Se
434
477
  maxLength={MAX_QUERY_LENGTH}
435
478
  placeholder="Search the documentation"
436
479
  value={query}
437
- onChange={(event) => setQuery(event.target.value)}
480
+ onChange={(event) => {
481
+ // A further keystroke replaces the query an earlier Enter waited for.
482
+ pendingEnter.current = null
483
+ setQuery(event.target.value)
484
+ }}
438
485
  onKeyDown={onKeyDown}
439
486
  />
440
487
  </label>