@wix/himalaya-cli 0.1979.0 → 0.1980.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.
@@ -1,14 +1,18 @@
1
1
  // The FAQ as a registrable service: one worker for the himi_faq screen and for a migrated page's FAQ section.
2
- // registerFaqList(name) -> the screen: every question, search, categories (the himi_faq bundle is this call);
3
- // registerFaqList(name, options) -> a section: `limit` (the source's NumberOfFAQs), `showCategories`, `firstOpen`, `oneAtATime`, `showSearch`.
2
+ // registerFaqList(name) -> the screen: every question, search, categories (the himi_faq bundle is this call). A section's
3
+ // View All opens it with that section's filters and chosen chip as `himi.open` input (`faqFilters`,
4
+ // `categoryId`), read on every load.
5
+ // registerFaqList(name, options) -> a section: `limit` (the source's NumberOfFAQs), `showCategories`, `categoryFilter`, `allChip`,
6
+ // `hiddenCategoryIds`, `firstOpen`, `oneAtATime`, `showSearch`, `viewAllScreen`.
4
7
  // State and flags are the screen's own (`loadingHidden`, `errorHidden`, ...), so the faq-list recipe and the himi_faq descriptor bind the same names.
5
- import { defineService } from "@himalaya/state";
8
+ import { defineService, navigate } from "@himalaya/state";
6
9
  import {
7
10
  queryCategories,
8
11
  queryQuestionEntries,
9
12
  type WixCategory,
10
13
  type WixQuestionEntry,
11
14
  } from "@himalaya/wix-faq";
15
+ import { copyParam, stashCopy } from "../_shared/himi-copy.js";
12
16
  import { openRichLink } from "../_shared/rich-content-link.js";
13
17
  import { richBody, ROW_IMAGE_WIDTH } from "../_shared/rich-body.js";
14
18
 
@@ -53,6 +57,13 @@ interface FaqDisplayRow extends QuestionRow {
53
57
  categoryHeaderHidden: boolean;
54
58
  }
55
59
 
60
+ /** One chip of the category picker: All, or a category with how many of its questions match. */
61
+ interface CategoryChip {
62
+ id: string;
63
+ label: string;
64
+ count: number;
65
+ }
66
+
56
67
  interface FaqState {
57
68
  status: "loading" | "ready" | "error" | "forbidden" | "notInstalled";
58
69
  categories: FaqCategory[];
@@ -70,6 +81,13 @@ interface FaqState {
70
81
  notInstalledHidden: boolean;
71
82
  /** The section's search field is off (the source's showSearchBar is false). */
72
83
  searchHidden: boolean;
84
+ /** The chosen chip of the category picker: `ALL_CHIP` or a category id; "" with no picker. */
85
+ categoryId: string;
86
+ categoryChips: CategoryChip[];
87
+ /** No category picker: the screen's headings, a flat list, or no categories to pick from. */
88
+ chipsHidden: boolean;
89
+ /** No View All: the section shows every question, has no screen to open, or has nothing to show. */
90
+ viewAllHidden: boolean;
73
91
  }
74
92
 
75
93
  /** What a source FAQ section sets. Every option defaults to what the himi_faq screen does. */
@@ -84,8 +102,25 @@ export interface FaqListOptions {
84
102
  oneAtATime?: boolean;
85
103
  /** false: no search field. */
86
104
  showSearch?: boolean;
105
+ /** The One App category picker: a chip per category (with All first when `allChip`), and only the chosen chip's questions, with no
106
+ * headings. Off (the himi_faq screen's own layout): every category's questions under its heading. Ignored when `showCategories` is false. */
107
+ categoryFilter?: boolean;
108
+ /** The picker starts with an All chip: every shown category's questions (the source's ShowAllCategoriesLabel, on by default).
109
+ * false: the first shown category is chosen. */
110
+ allChip?: boolean;
111
+ /** Categories the source turned off (its `categories` map's false entries): their questions are never shown or counted. */
112
+ hiddenCategoryIds?: string[];
113
+ /** The full FAQ screen the section's View All opens (with `limit`), with these options and the chosen chip. */
114
+ viewAllScreen?: string;
87
115
  }
88
116
 
117
+ /** The All chip's id. A category id is a GUID, so it never collides. */
118
+ export const ALL_CHIP = "all";
119
+ /** The `himi.open` input key that carries a section's filters to the screen its View All opens. */
120
+ const FILTERS_INPUT = "faqFilters";
121
+ /** The `himi.open` input key naming one View All tap: a new value is a new View All, the same one is the screen shown again. */
122
+ const OPEN_INPUT = "faqOpen";
123
+
89
124
  const PAGE_SIZE = 100;
90
125
 
91
126
  /** Caps on the static pairs, matching `BRANDED_LITE_FAQ_LIMITS` in the app contract. The
@@ -143,15 +178,33 @@ function uniqueById<T extends { id: string }>(rows: T[]): T[] {
143
178
  return [...new Map(rows.filter((row) => row.id).map((row) => [row.id, row])).values()];
144
179
  }
145
180
 
146
- function sectionsFor(state: Pick<FaqState, "categories" | "questions" | "query" | "expandedIds" | "otherTitle">, limit?: number): CategorySection[] {
181
+ /** The categories the reader may see: every one but those the source turned off. */
182
+ function shownCategories(state: Pick<FaqState, "categories">, options: FaqListOptions): FaqCategory[] {
183
+ const hidden = new Set(options.hiddenCategoryIds ?? []);
184
+ return state.categories.filter((category) => !hidden.has(category.id)).slice().sort(sortByWixOrder);
185
+ }
186
+
187
+ /** The picker is on: the source shows categories as chips, and there are named categories to pick (the static fallback has none). */
188
+ function picking(state: Pick<FaqState, "categories">, options: FaqListOptions): boolean {
189
+ return options.categoryFilter === true && options.showCategories !== false && shownCategories(state, options).some((category) => category.title);
190
+ }
191
+
192
+ /** The chip a load or a tap lands on: the wanted one when it is still a chip, else All (or, without it, the first category). */
193
+ function chosenChip(state: Pick<FaqState, "categories">, options: FaqListOptions, wanted: string): string {
194
+ if (!picking(state, options)) return "";
195
+ const ids = shownCategories(state, options).map((category) => category.id);
196
+ if (wanted && (ids.includes(wanted) || (wanted === ALL_CHIP && options.allChip !== false))) return wanted;
197
+ return options.allChip !== false ? ALL_CHIP : ids[0] ?? "";
198
+ }
199
+
200
+ function sectionsFor(state: Pick<FaqState, "categories" | "questions" | "query" | "expandedIds" | "otherTitle" | "categoryId">, options: FaqListOptions = {}): CategorySection[] {
147
201
  const needle = state.query.trim().toLowerCase();
148
202
  const visible = state.questions
149
203
  .filter((row) => row.status.toUpperCase() !== "HIDDEN")
150
204
  .filter((row) => !needle || `${row.question}\n${row.answer}`.toLowerCase().includes(needle))
151
- .sort(sortByWixOrder)
152
- .slice(0, limit ?? Number.POSITIVE_INFINITY);
205
+ .sort(sortByWixOrder);
153
206
  const expanded = new Set(state.expandedIds);
154
- const known = new Set(state.categories.map((category) => category.id));
207
+ const shown = shownCategories(state, options);
155
208
  const row = (question: FaqQuestion): QuestionRow => ({
156
209
  id: question.id,
157
210
  title: question.question,
@@ -160,33 +213,89 @@ function sectionsFor(state: Pick<FaqState, "categories" | "questions" | "query"
160
213
  hasAnswerJson: question.hasAnswerJson,
161
214
  expanded: expanded.has(question.id),
162
215
  });
163
- const sections = state.categories
164
- .slice()
165
- .sort(sortByWixOrder)
216
+ let sections = shown
166
217
  .map((category) => ({
167
218
  id: category.id,
168
219
  title: category.title,
169
220
  questions: visible.filter((question) => question.categoryId === category.id).map(row),
170
221
  }))
171
222
  .filter((section) => section.questions.length > 0);
172
- const orphaned = visible.filter((question) => !known.has(question.categoryId));
173
- if (orphaned.length) sections.push({ id: "other", title: state.otherTitle, questions: orphaned.map(row) });
174
- return sections;
223
+ if (picking(state, options)) {
224
+ // The picker shows one chip's questions; All is every shown category's, in category order. A question in no category is not
225
+ // under any chip, as in the source.
226
+ if (state.categoryId !== ALL_CHIP) sections = sections.filter((section) => section.id === state.categoryId);
227
+ } else {
228
+ const known = new Set(state.categories.map((category) => category.id));
229
+ const orphaned = visible.filter((question) => !known.has(question.categoryId));
230
+ if (orphaned.length) sections.push({ id: "other", title: state.otherTitle, questions: orphaned.map(row) });
231
+ }
232
+ // The limit caps the questions in the order the reader sees them.
233
+ let left = options.limit ?? Number.POSITIVE_INFINITY;
234
+ return sections
235
+ .map((section) => {
236
+ const questions = section.questions.slice(0, Math.max(0, left));
237
+ left -= questions.length;
238
+ return { ...section, questions };
239
+ })
240
+ .filter((section) => section.questions.length > 0);
241
+ }
242
+
243
+ /** A multi-language app's generated section passes the All chip's catalog key flat (`"collection.all": "$t:collection.all"`):
244
+ * the chip shows the key, and the renderer translates it from the app's catalog in the reader's language (a worker-emitted
245
+ * `$t:` key, as the business chat does). */
246
+ const ALL_COPY_KEY = "collection.all";
247
+ let flatAllKey = "";
248
+
249
+ /** A fallback no copy pack holds: `copyParam` returns it only when the pack has no entry for the key. */
250
+ const NO_PACK_ENTRY = "\u0000";
251
+
252
+ /** The All chip's label: an explicit copy pack entry (even one that is exactly "All"), else the pinned language's
253
+ * translation, else the flat `$t:` key a multi-language app passed, else the stock English. */
254
+ function allChipLabel(): string {
255
+ if (copyParam(ALL_COPY_KEY, NO_PACK_ENTRY) !== NO_PACK_ENTRY) return copyParam(ALL_COPY_KEY, "All");
256
+ // The key stays a literal: the stock-key check and `one-app generate` read it from this source.
257
+ const label = copyParam("collection.all", "All");
258
+ return label !== "All" || !flatAllKey ? label : flatAllKey;
259
+ }
260
+
261
+ /** The flat `$t:` key a load passed for the All chip. A load that carries params without it clears it, as a current copy
262
+ * pack replaces the last one; a load with no params at all (a retry) keeps it. */
263
+ function stashFlatAllKey(arg: unknown): void {
264
+ if (!arg || typeof arg !== "object") return;
265
+ const value = (arg as Record<string, unknown>)[ALL_COPY_KEY];
266
+ flatAllKey = value === `$t:${ALL_COPY_KEY}` ? value : "";
267
+ }
268
+
269
+ /** One chip per shown category with its matching questions counted (All counts them all), or none without the picker. */
270
+ function chipsFor(state: FaqState, options: FaqListOptions): CategoryChip[] {
271
+ if (!picking(state, options)) return [];
272
+ const counted = sectionsFor({ ...state, categoryId: ALL_CHIP }, { ...options, limit: undefined });
273
+ const count = (id: string) => counted.find((section) => section.id === id)?.questions.length ?? 0;
274
+ const chips = shownCategories(state, options).map((category) => ({ id: category.id, label: category.title, count: count(category.id) }));
275
+ if (options.allChip === false) return chips;
276
+ return [{ id: ALL_CHIP, label: allChipLabel(), count: chips.reduce((sum, chip) => sum + chip.count, 0) }, ...chips];
175
277
  }
176
278
 
177
279
  function ready(state: FaqState, options: FaqListOptions = {}): FaqState {
178
- const sections = sectionsFor(state, options.limit);
280
+ const categoryId = chosenChip(state, options, state.categoryId);
281
+ const chose = { ...state, categoryId };
282
+ const sections = sectionsFor(chose, options);
283
+ const chipped = categoryId !== "";
179
284
  const rows = sections.flatMap((section) => section.questions.map((question, index) => ({
180
285
  ...question,
181
286
  categoryTitle: section.title,
182
- // An untitled section (the static fallback's) has no header to show.
183
- categoryHeaderHidden: options.showCategories === false || index !== 0 || !section.title,
287
+ // An untitled section (the static fallback's) has no header to show; the picker's chips stand in for the headings.
288
+ categoryHeaderHidden: options.showCategories === false || chipped || index !== 0 || !section.title,
184
289
  })));
185
290
  return {
186
- ...state,
291
+ ...chose,
187
292
  status: "ready",
188
293
  sections,
189
294
  rows,
295
+ categoryChips: chipsFor(chose, options),
296
+ chipsHidden: !chipped,
297
+ // As in the source, a limited section offers View All whenever it shows questions.
298
+ viewAllHidden: !options.viewAllScreen || options.limit === undefined || sections.length === 0,
190
299
  loadingHidden: true,
191
300
  contentHidden: sections.length === 0,
192
301
  emptyHidden: sections.length > 0,
@@ -204,6 +313,9 @@ function failure(state: FaqState, status: FaqState["status"]): FaqState {
204
313
  questions: [],
205
314
  sections: [],
206
315
  rows: [],
316
+ categoryChips: [],
317
+ chipsHidden: true,
318
+ viewAllHidden: true,
207
319
  loadingHidden: true,
208
320
  contentHidden: true,
209
321
  emptyHidden: true,
@@ -282,29 +394,43 @@ async function entriesIn(contentFormat: "PLAIN_TEXT" | "RICH_CONTENT"): Promise<
282
394
 
283
395
  async function allQuestions(): Promise<FaqQuestion[]> {
284
396
  // Both formats are read in parallel, each paged on its own. PLAIN_TEXT is the list; a RICH_CONTENT read
285
- // that fails only costs the documents — every answer keeps its plain text.
397
+ // that fails only costs the documents (and the rich-only questions below) — every listed answer keeps its plain text.
286
398
  const [plain, rich] = await Promise.all([
287
399
  entriesIn("PLAIN_TEXT"),
288
400
  entriesIn("RICH_CONTENT").catch(() => [] as WixQuestionEntry[]),
289
401
  ]);
290
402
  const richById = new Map(rich.map((question: WixQuestionEntry) => [question.id ?? "", question.richContent]));
403
+ const toRow = (question: WixQuestionEntry, answer: string, answerJson: string): FaqQuestion => ({
404
+ id: question.id ?? "",
405
+ categoryId: question.categoryId ?? "",
406
+ question: (question.question ?? "").trim(),
407
+ answer,
408
+ answerJson,
409
+ hasAnswerJson: answerJson !== "",
410
+ ...(typeof question.sortOrder === "number" ? { sortOrder: question.sortOrder } : {}),
411
+ status: question.status ?? "UNKNOWN",
412
+ });
291
413
  const rows = plain.map((question: WixQuestionEntry) => {
292
414
  const answer = (question.plainText ?? "").trim();
293
- const answerJson = richAnswer(answer, richById.get(question.id ?? ""));
294
- return {
295
- id: question.id ?? "",
296
- categoryId: question.categoryId ?? "",
297
- question: (question.question ?? "").trim(),
298
- answer,
299
- answerJson,
300
- hasAnswerJson: answerJson !== "",
301
- ...(typeof question.sortOrder === "number" ? { sortOrder: question.sortOrder } : {}),
302
- status: question.status ?? "UNKNOWN",
303
- };
304
- }).filter((question) =>
415
+ const rich = richById.get(question.id ?? "");
416
+ if (answer) return toRow(question, answer, richAnswer(answer, rich));
417
+ // No plain answer to check the document against: the document is the answer, as for a rich-only question.
418
+ const { bodyJson, bodyText } = richBody(rich, "", ROW_IMAGE_WIDTH);
419
+ return toRow(question, bodyText.trim(), bodyJson);
420
+ });
421
+ // A question written as a rich document only is not in the PLAIN_TEXT read at all: the site's FAQ (and the One App) lists it, so it
422
+ // is listed from the RICH_CONTENT read. Its document is the only answer there is, so it is shown as is, its text the plain fallback.
423
+ const listed = new Set(rows.map((row) => row.id));
424
+ for (const question of rich) {
425
+ if (!question.id || listed.has(question.id)) continue;
426
+ const { bodyJson, bodyText } = richBody(question.richContent, "", ROW_IMAGE_WIDTH);
427
+ // A document the viewer cannot draw (too deep, over its limits) leaves no answer to show: the row is left out.
428
+ if (!bodyJson && !bodyText.trim()) continue;
429
+ rows.push(toRow(question, bodyText.trim(), bodyJson));
430
+ }
431
+ return uniqueById(rows.filter((question) =>
305
432
  question.id && question.question && question.status.toUpperCase() !== "HIDDEN",
306
- );
307
- return uniqueById(rows);
433
+ ));
308
434
  }
309
435
 
310
436
  const INITIAL: FaqState = {
@@ -323,9 +449,54 @@ const INITIAL: FaqState = {
323
449
  forbiddenHidden: true,
324
450
  notInstalledHidden: true,
325
451
  searchHidden: false,
452
+ categoryId: "",
453
+ categoryChips: [],
454
+ chipsHidden: true,
455
+ viewAllHidden: true,
326
456
  };
327
457
 
328
- export function registerFaqList(serviceName: string, options: FaqListOptions = {}) {
458
+ /** A section's filters as the screen its View All opens takes them (`himi.open` input is string-valued). */
459
+ function filtersInput(options: FaqListOptions): string {
460
+ return JSON.stringify({
461
+ ...(options.showCategories === false ? { showCategories: false } : {}),
462
+ ...(options.categoryFilter ? { categoryFilter: true } : {}),
463
+ ...(options.allChip === false ? { allChip: false } : {}),
464
+ ...(options.hiddenCategoryIds?.length ? { hiddenCategoryIds: options.hiddenCategoryIds } : {}),
465
+ ...(options.firstOpen ? { firstOpen: true } : {}),
466
+ ...(options.oneAtATime ? { oneAtATime: true } : {}),
467
+ });
468
+ }
469
+
470
+ /** The filters a section's View All sent the screen, re-bounded: a worker must not trust input it did not build. Unknown keys and
471
+ * wrong types are dropped, so a malformed input is the screen's own layout. */
472
+ function parseFiltersInput(raw: unknown): FaqListOptions {
473
+ let parsed: unknown;
474
+ try { parsed = typeof raw === "string" ? JSON.parse(raw) : undefined; } catch { return {}; }
475
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
476
+ const row = parsed as Record<string, unknown>;
477
+ const flag = (key: string): boolean | undefined => typeof row[key] === "boolean" ? row[key] as boolean : undefined;
478
+ const hidden = Array.isArray(row.hiddenCategoryIds) ? row.hiddenCategoryIds.filter((id): id is string => typeof id === "string" && id !== "").slice(0, 200) : [];
479
+ const out: FaqListOptions = {};
480
+ for (const key of ["showCategories", "categoryFilter", "allChip", "firstOpen", "oneAtATime"] as const) {
481
+ const value = flag(key);
482
+ if (value !== undefined) out[key] = value;
483
+ }
484
+ if (hidden.length) out.hiddenCategoryIds = hidden;
485
+ return out;
486
+ }
487
+
488
+ /** The screen's `himi.open` input: the filters and chip a section's View All sent, or nothing when the screen was opened on its own. */
489
+ function navInput(): { options: FaqListOptions; categoryId: string; open: string } {
490
+ const input = (globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input ?? {};
491
+ const categoryId = typeof input.categoryId === "string" ? input.categoryId.slice(0, 128) : "";
492
+ const open = typeof input[OPEN_INPUT] === "string" ? (input[OPEN_INPUT] as string).slice(0, 64) : "";
493
+ return { options: parseFiltersInput(input[FILTERS_INPUT]), categoryId, open };
494
+ }
495
+
496
+ export function registerFaqList(serviceName: string, sectionOptions?: FaqListOptions) {
497
+ /** The himi_faq screen (no section options) follows the filters its opener sent; a section follows its own. */
498
+ const isScreen = sectionOptions === undefined;
499
+ let options: FaqListOptions = sectionOptions ?? {};
329
500
  /** The site's own FAQ pairs: the FALLBACK shown only when the FAQ app yields no visible question (see parseStaticFaq). */
330
501
  let staticQuestions: FaqQuestion[] = [];
331
502
  const initial: FaqState = { ...INITIAL, searchHidden: options.showSearch === false };
@@ -333,6 +504,16 @@ export function registerFaqList(serviceName: string, options: FaqListOptions = {
333
504
  let loadGeneration = 0;
334
505
  /** The reader opened or closed a question: `firstOpen` then stops deciding what is open. */
335
506
  let touched = false;
507
+ /** The screen's last applied `himi.open` input. The same input again (a retry, the screen shown again, a pooled worker
508
+ * reused) keeps the reader's own chip; each View All tap sends a fresh `faqOpen`, so a new tap always differs. */
509
+ let appliedInput: string | undefined;
510
+ /** View All taps from this section, for the `faqOpen` token. */
511
+ let opens = 0;
512
+ /** The chip a new input sent, kept until a load lands it: a failed or overtaken load must not lose it. */
513
+ let pendingChip: string | undefined;
514
+ /** A new View All starts clean (no search, nothing open, firstOpen deciding again), applied when a load lands. A search the
515
+ * reader types before that (over the loading or failure card) is theirs, so it lifts the search half. */
516
+ let pendingReset: { query: boolean; expanded: boolean } | undefined;
336
517
 
337
518
  const settle = (state: FaqState): FaqState => ready(state, options);
338
519
 
@@ -352,17 +533,46 @@ export function registerFaqList(serviceName: string, options: FaqListOptions = {
352
533
  // Only when the caller passed the param: `retry` is dispatched with no params and must keep
353
534
  // the pairs the screen's onAppear delivered.
354
535
  if (arg && "staticFaq" in arg) staticQuestions = parseStaticFaq(arg.staticFaq);
536
+ // The app's copy pack and language (the All chip's label), as every shared section takes them, and a multi-language
537
+ // app's flat `$t:` key for the All chip.
538
+ stashCopy(arg);
539
+ stashFlatAllKey(arg);
540
+ // The screen re-reads its input on every load: the host changes it before a View All opens the screen. A new View All
541
+ // (a new `faqOpen`) lands on the chip it sent and starts clean, as the source's standalone screen does: no search, nothing
542
+ // open, firstOpen deciding again. The same input (a retry, the screen shown again) keeps what the reader did since.
543
+ if (isScreen) {
544
+ // A View All from a multi-language section brings the All chip's key with it.
545
+ const viewAllKey = (globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input?.[ALL_COPY_KEY];
546
+ if (viewAllKey === `$t:${ALL_COPY_KEY}`) flatAllKey = viewAllKey;
547
+ const nav = navInput();
548
+ const input = JSON.stringify(nav);
549
+ if (input !== appliedInput) {
550
+ appliedInput = input;
551
+ options = nav.options;
552
+ pendingChip = nav.categoryId;
553
+ touched = false;
554
+ pendingReset = { query: true, expanded: true };
555
+ }
556
+ }
355
557
  const generation = ++loadGeneration;
356
558
  try {
357
559
  const [categories, questions] = await Promise.all([allCategories(), allQuestions()]);
358
560
  if (generation !== loadGeneration) return latestState;
359
561
  const otherTitle = String(arg?.otherCategory ?? latestState.otherTitle).trim() || latestState.otherTitle;
360
- let live = settle({ ...latestState, categories, questions, otherTitle });
361
- const first = live.sections[0]?.questions[0]?.id;
362
- if (options.firstOpen && !touched && !live.expandedIds.length && first) live = settle({ ...live, expandedIds: [first] });
562
+ // The chip is read after the reads: one the reader picked while they were out stands, unless a new input sent another.
563
+ const clean = {
564
+ ...(pendingReset?.query ? { query: "" } : {}),
565
+ ...(pendingReset?.expanded ? { expandedIds: [] as string[] } : {}),
566
+ };
567
+ let live = settle({ ...latestState, ...clean, categories, questions, otherTitle, categoryId: pendingChip ?? latestState.categoryId });
568
+ pendingChip = undefined;
569
+ pendingReset = undefined;
363
570
  // The Wix FAQ app answered but holds nothing a visitor can see — the site's own pairs,
364
571
  // when it has any, instead of an empty state over a site whose FAQ is right there.
365
- if (questions.length === 0) return commit(staticFallback(live) ?? live);
572
+ if (questions.length === 0) live = staticFallback(live) ?? live;
573
+ // `firstOpen` opens the first question the reader sees: the site's own pairs too.
574
+ const first = live.sections[0]?.questions[0]?.id;
575
+ if (options.firstOpen && !touched && !live.expandedIds.length && first) live = settle({ ...live, expandedIds: [first] });
366
576
  return commit(live);
367
577
  } catch (error) {
368
578
  if (generation !== loadGeneration) return latestState;
@@ -381,11 +591,43 @@ export function registerFaqList(serviceName: string, options: FaqListOptions = {
381
591
  actions: {
382
592
  load: loadFaq,
383
593
  retry: loadFaq,
384
- search: (state: FaqState, arg?: { value?: string }) => commit(settle({ ...state, query: String(arg?.value ?? "").slice(0, 256) })),
594
+ search: (state: FaqState, arg?: { value?: string }) => {
595
+ const query = String(arg?.value ?? "").slice(0, 256);
596
+ // Only a search the reader changes is theirs: a field that sends its value again keeps the reset.
597
+ if (pendingReset && query !== state.query) pendingReset = { ...pendingReset, query: false };
598
+ // Typed while loading or over a failure card: kept for the next load, and the card (and its Retry) stays.
599
+ if (state.status !== "ready") return commit({ ...state, query });
600
+ return commit(settle({ ...state, query }));
601
+ },
602
+ // A chip of the category picker (FilterChips' `{ selectedIds }`): its questions, with what was open closed, as in the source.
603
+ selectCategory: (state: FaqState, arg?: { selectedIds?: unknown; selectedId?: unknown }) => {
604
+ const raw = Array.isArray(arg?.selectedIds) ? arg.selectedIds[0] : arg?.selectedId;
605
+ const wanted = typeof raw === "string" ? raw : "";
606
+ // Tapping the chosen chip again deselects it in FilterChips; the picker always has one chip chosen.
607
+ // A chip tap that lands after a failed read leaves its card (and Retry) alone.
608
+ if (state.status !== "ready") return state;
609
+ if (!wanted || wanted === state.categoryId) return commit(settle(state));
610
+ let next = settle({ ...state, categoryId: wanted, expandedIds: [] });
611
+ const first = next.sections[0]?.questions[0]?.id;
612
+ if (options.firstOpen && first) next = settle({ ...next, expandedIds: [first] });
613
+ return commit(next);
614
+ },
615
+ // The source's View All: the full FAQ screen with this section's filters, on the chip the reader chose.
616
+ viewAll: (state: FaqState) => {
617
+ if (!options.viewAllScreen) return state;
618
+ opens += 1;
619
+ return navigate(state, { screenId: options.viewAllScreen, args: {
620
+ [FILTERS_INPUT]: filtersInput(options), categoryId: state.categoryId, [OPEN_INPUT]: `${serviceName}:${Date.now()}:${opens}`,
621
+ // The screen shows the same All chip: a multi-language section's `$t:` key goes along.
622
+ ...(flatAllKey ? { [ALL_COPY_KEY]: flatAllKey } : {}),
623
+ } });
624
+ },
385
625
  toggle: (state: FaqState, arg?: { id?: string }) => {
386
626
  const id = String(arg?.id ?? "");
387
627
  if (!id || !state.questions.some((question) => question.id === id)) return state;
388
628
  touched = true;
629
+ // A question the reader opens or closes before a new View All lands is theirs: the reset leaves what is open alone.
630
+ if (pendingReset) pendingReset = { ...pendingReset, expanded: false };
389
631
  const open = state.expandedIds.includes(id);
390
632
  const expandedIds = open
391
633
  ? state.expandedIds.filter((candidate) => candidate !== id)