@wix/himalaya-cli 0.1796.0 → 0.1797.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 (74) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/wix-sdk/online-programs/src/index.d.ts +6 -0
  2. package/dist/cli.mjs +1 -0
  3. package/guides/sdk-reference.json +2 -2
  4. package/package.json +2 -2
  5. package/templates/beauty-salon/l10n/en.json +1 -1
  6. package/templates/branded-lite/dev/index.ts +483 -0
  7. package/templates/branded-lite/l10n/ar.json +66 -0
  8. package/templates/branded-lite/l10n/cs.json +66 -0
  9. package/templates/branded-lite/l10n/da.json +66 -0
  10. package/templates/branded-lite/l10n/de.json +66 -0
  11. package/templates/branded-lite/l10n/el.json +66 -0
  12. package/templates/branded-lite/l10n/en.json +8 -1
  13. package/templates/branded-lite/l10n/es.json +66 -0
  14. package/templates/branded-lite/l10n/fi.json +66 -0
  15. package/templates/branded-lite/l10n/fr.json +66 -0
  16. package/templates/branded-lite/l10n/he.json +53 -0
  17. package/templates/branded-lite/l10n/hu.json +66 -0
  18. package/templates/branded-lite/l10n/id.json +66 -0
  19. package/templates/branded-lite/l10n/it.json +66 -0
  20. package/templates/branded-lite/l10n/ja.json +66 -0
  21. package/templates/branded-lite/l10n/ko.json +66 -0
  22. package/templates/branded-lite/l10n/lt.json +66 -0
  23. package/templates/branded-lite/l10n/nl.json +66 -0
  24. package/templates/branded-lite/l10n/no.json +66 -0
  25. package/templates/branded-lite/l10n/pl.json +66 -0
  26. package/templates/branded-lite/l10n/pt.json +66 -0
  27. package/templates/branded-lite/l10n/ru.json +66 -0
  28. package/templates/branded-lite/l10n/sv.json +66 -0
  29. package/templates/branded-lite/l10n/th.json +66 -0
  30. package/templates/branded-lite/l10n/tr.json +66 -0
  31. package/templates/branded-lite/l10n/uk.json +66 -0
  32. package/templates/branded-lite/l10n/vi.json +66 -0
  33. package/templates/branded-lite/l10n/zh.json +66 -0
  34. package/templates/branded-lite/tier5-src/himi-branded-lite-program-step/index.ts +396 -14
  35. package/templates/branded-lite/tier5-src/himi-branded-lite-program-step/quiz.ts +114 -0
  36. package/templates/community-club/l10n/en.json +1 -1
  37. package/templates/events-meetups/l10n/en.json +1 -1
  38. package/templates/gym-fitness/l10n/en.json +1 -1
  39. package/templates/nonprofit-cause/l10n/en.json +1 -1
  40. package/templates/podcast-creator/l10n/en.json +1 -1
  41. package/templates/portfolio-creative/l10n/en.json +1 -1
  42. package/templates/restaurant/l10n/en.json +1 -1
  43. package/templates/retail-store/l10n/en.json +1 -1
  44. package/templates/yoga-studio/dev/index.ts +483 -0
  45. package/templates/yoga-studio/l10n/ar.json +66 -0
  46. package/templates/yoga-studio/l10n/cs.json +66 -0
  47. package/templates/yoga-studio/l10n/da.json +66 -0
  48. package/templates/yoga-studio/l10n/de.json +66 -0
  49. package/templates/yoga-studio/l10n/el.json +66 -0
  50. package/templates/yoga-studio/l10n/en.json +8 -1
  51. package/templates/yoga-studio/l10n/es.json +66 -0
  52. package/templates/yoga-studio/l10n/fi.json +66 -0
  53. package/templates/yoga-studio/l10n/fr.json +66 -0
  54. package/templates/yoga-studio/l10n/he.json +53 -0
  55. package/templates/yoga-studio/l10n/hu.json +66 -0
  56. package/templates/yoga-studio/l10n/id.json +66 -0
  57. package/templates/yoga-studio/l10n/it.json +66 -0
  58. package/templates/yoga-studio/l10n/ja.json +66 -0
  59. package/templates/yoga-studio/l10n/ko.json +66 -0
  60. package/templates/yoga-studio/l10n/lt.json +66 -0
  61. package/templates/yoga-studio/l10n/nl.json +66 -0
  62. package/templates/yoga-studio/l10n/no.json +66 -0
  63. package/templates/yoga-studio/l10n/pl.json +66 -0
  64. package/templates/yoga-studio/l10n/pt.json +66 -0
  65. package/templates/yoga-studio/l10n/ru.json +66 -0
  66. package/templates/yoga-studio/l10n/sv.json +66 -0
  67. package/templates/yoga-studio/l10n/th.json +66 -0
  68. package/templates/yoga-studio/l10n/tr.json +66 -0
  69. package/templates/yoga-studio/l10n/uk.json +66 -0
  70. package/templates/yoga-studio/l10n/vi.json +66 -0
  71. package/templates/yoga-studio/l10n/zh.json +66 -0
  72. package/templates/yoga-studio/tier5-src/_shared/branded-form.ts +321 -0
  73. package/templates/yoga-studio/tier5-src/himi-branded-lite-program-step/index.ts +396 -14
  74. package/templates/yoga-studio/tier5-src/himi-branded-lite-program-step/quiz.ts +114 -0
@@ -4370,6 +4370,12 @@
4370
4370
  "translation": "在網站上開啟",
4371
4371
  "origin": "machine"
4372
4372
  },
4373
+ "h_988c413069b4": {
4374
+ "key": "programStep.quizSubmitCta",
4375
+ "source": "Submit answers",
4376
+ "translation": "提交答案",
4377
+ "origin": "machine"
4378
+ },
4373
4379
  "h_1e9b74b4dda5": {
4374
4380
  "source": "Show all ({count})",
4375
4381
  "translation": "查看全部({count})",
@@ -9639,6 +9645,66 @@
9639
9645
  "source": "Take this quiz on the program's website.",
9640
9646
  "translation": "請在計劃的網站上完成此測驗。",
9641
9647
  "origin": "machine"
9648
+ },
9649
+ "h_00ece1813f9b": {
9650
+ "source": "Your score: {score}%. You need {grade}% to pass.",
9651
+ "translation": "你的得分:{score}%。需要 {grade}% 才能通过。",
9652
+ "origin": "machine"
9653
+ },
9654
+ "h_0919ff29cabe": {
9655
+ "source": "Your score: {score}%.",
9656
+ "translation": "你的得分:{score}%。",
9657
+ "origin": "machine"
9658
+ },
9659
+ "h_18055b22e15a": {
9660
+ "source": "Not passed yet",
9661
+ "translation": "尚未通过",
9662
+ "origin": "machine"
9663
+ },
9664
+ "h_2074225eafe0": {
9665
+ "source": "Answer this question.",
9666
+ "translation": "请回答这个问题。",
9667
+ "origin": "machine"
9668
+ },
9669
+ "h_4f2c8699ab7e": {
9670
+ "source": "Your answers couldn't be sent. Try again.",
9671
+ "translation": "无法发送你的答案。请重试。",
9672
+ "origin": "machine"
9673
+ },
9674
+ "h_88c50a39ee12": {
9675
+ "source": "Answer every question, then submit. You need {grade}% to pass.",
9676
+ "translation": "回答所有问题后提交。需要 {grade}% 才能通过。",
9677
+ "origin": "machine"
9678
+ },
9679
+ "h_8c0dcd675b14": {
9680
+ "source": "This quiz couldn't be loaded.",
9681
+ "translation": "无法加载此测验。",
9682
+ "origin": "machine"
9683
+ },
9684
+ "h_a29a7f00b389": {
9685
+ "source": "Answer every question, then submit.",
9686
+ "translation": "回答所有问题后提交。",
9687
+ "origin": "machine"
9688
+ },
9689
+ "h_ad0ea8d557ca": {
9690
+ "source": "You have no attempts left for this quiz.",
9691
+ "translation": "你已没有此测验的作答次数。",
9692
+ "origin": "machine"
9693
+ },
9694
+ "h_c11b283297f8": {
9695
+ "source": "Answer every question to submit.",
9696
+ "translation": "请回答所有问题后再提交。",
9697
+ "origin": "machine"
9698
+ },
9699
+ "h_c290e238a3da": {
9700
+ "source": "You passed",
9701
+ "translation": "你已通过",
9702
+ "origin": "machine"
9703
+ },
9704
+ "h_cb2c18904fad": {
9705
+ "source": "{correct} of {total} answers were right.",
9706
+ "translation": "{total} 个答案中有 {correct} 个正确。",
9707
+ "origin": "machine"
9642
9708
  }
9643
9709
  }
9644
9710
  }
@@ -3,18 +3,24 @@
3
3
  //
4
4
  // The step's title, section and place ("Step 2 of 3"), then its content: an article is its rich
5
5
  // description; a video plays in the core Video player above it, and a video with no public address
6
- // (a Wix Video, a deleted one) opens the program on the website instead, as does a quiz until the app
7
- // takes quizzes (B5). The member completes the step, or undoes it, and walks to the previous or the
8
- // next step in place. A completion says what it finished: the step, its whole section, or the program.
6
+ // (a Wix Video, a deleted one) opens the program on the website instead. A quiz step shows its
7
+ // questions with the core form controls; Submit sends the answers, the result says the score and
8
+ // whether it passed, Try again starts over after a fail, and a pass completes the step. A quiz the app
9
+ // cannot fill (a file upload, an image choice) or cannot read opens on the website. The member
10
+ // completes the step, or undoes it, and walks to the previous or the next step in place. A completion
11
+ // says what it finished: the step, its whole section, or the program.
9
12
  //
10
13
  // Reads (member identity): getProgram → getMyMember → the member's participation (Search
11
14
  // Participants) → in parallel the program's sections, its steps (EXTENDED: the description and the
12
15
  // video address) and the participant's resolved steps. Writes: Upsert Resolved Step (complete) and
13
- // Delete Resolved Step (undo). Undo stops once the participation is COMPLETED: on amit1 an undo after
16
+ // Delete Resolved Step (undo). A quiz: Get Form (the quiz is a Wix Forms form; the quiz route itself
17
+ // refuses a member), Create Quiz Submission, then Upsert Resolved Step with the submission, which the
18
+ // site resolves to COMPLETED or FAILED with the score (quiz.ts). Undo stops once the participation is COMPLETED: on amit1 an undo after
14
19
  // the last step left the participation COMPLETED at 2 of 3 steps (2026-11-18), as the One App knows.
15
20
  import { connectivity, defineService as registerService, navigate } from "@himalaya/state";
16
21
  import {
17
22
  completeStep,
23
+ createQuizSubmission,
18
24
  listSections,
19
25
  participationsByProgram,
20
26
  searchMemberParticipation,
@@ -24,6 +30,7 @@ import {
24
30
  type WixStep,
25
31
  } from "@himalaya/wix-online-programs";
26
32
  import { getMyMember } from "@himalaya/wix-members";
33
+ import { getForm } from "@himalaya/wix-forms";
27
34
  import { i18n } from "@himalaya/wix-platform";
28
35
  import { open, defaultMode } from "@himalaya/open-url";
29
36
  import { descriptionBody } from "../_shared/rich-body.js";
@@ -38,11 +45,31 @@ import { contentReadability, sectionTitle, stepKind, stepTitle } from "../_share
38
45
  import { allResolved, allSteps, fetchProgram, gateTextOf, isRefused } from "../_shared/program-reads.js";
39
46
  import { markProgress } from "../_shared/program-progress-mark.js";
40
47
  import { completionOf, placeSteps, programWebUrl, videoUrlOf, type Completion, type PlacedStep } from "./model.js";
48
+ import { isAttemptsExhausted, parseQuiz, quizAnswers, quizResult, unansweredTargets, type QuizModel, type QuizResult } from "./quiz.js";
49
+ import { EMPTY_VALUE, type FieldValue } from "../_shared/branded-form.js";
50
+ import { isNotFoundError } from "../_shared/detail-presence.js";
41
51
 
42
52
  export const SERVICE = "himiBrandedProgramStep";
43
53
 
44
54
  type Access = "member" | "signIn" | "notJoined";
45
55
 
56
+ interface QuizOptionRow { id: string; target: string; value: string; label: string; selected: boolean }
57
+ /** One question of a quiz step. hiddenWhen hides on TRUE: one "not" flag per field kind. */
58
+ interface QuizRow {
59
+ id: string;
60
+ target: string;
61
+ label: string;
62
+ value: string;
63
+ options: QuizOptionRow[];
64
+ notChoice: boolean;
65
+ notMulti: boolean;
66
+ notText: boolean;
67
+ notArea: boolean;
68
+ notNumber: boolean;
69
+ error: string;
70
+ noError: boolean;
71
+ }
72
+
46
73
  interface State {
47
74
  status: "loading" | "ready" | "error";
48
75
  /** ErrorState variant: "offline" or "server". */
@@ -89,6 +116,20 @@ interface State {
89
116
  sheetBody: string;
90
117
  hideSheetNext: boolean;
91
118
  hideSheetBack: boolean;
119
+ /** A quiz step: its questions while the member answers, and the line above them. */
120
+ quizRows: QuizRow[];
121
+ quizIntro: string;
122
+ hideQuiz: boolean;
123
+ hideQuizLoading: boolean;
124
+ /** Unanswered questions, a quiz that could not be read, or a failed send. */
125
+ quizError: string;
126
+ /** The quiz's last result: passed or not, the score, and Try again. */
127
+ hideResult: boolean;
128
+ hideResultPass: boolean;
129
+ hideResultFail: boolean;
130
+ resultTitle: string;
131
+ resultBody: string;
132
+ hideRetry: boolean;
92
133
  /** Why a member who is not in the program sees no step. */
93
134
  gateText: string;
94
135
  /** The step is not in the program (removed, or another program's), or the steps cannot be read. */
@@ -111,6 +152,8 @@ interface Loaded {
111
152
  standing: Standing;
112
153
  placed: PlacedStep[];
113
154
  done: Map<string, WixResolvedStep>;
155
+ /** Quiz steps whose last submission failed (the site resolves them FAILED, which is not done). */
156
+ failed: Map<string, WixResolvedStep>;
114
157
  /** The participation's own step count: a completion is the program's only when no step is missing from the list. */
115
158
  reportedTotal: number;
116
159
  /** The program has ended: its steps can't be changed, whatever the participation says. */
@@ -133,6 +176,37 @@ let writes = 0;
133
176
  /** The step the screen was opened with on the last load; a new one replaces the step the member walked to. */
134
177
  let askedStep = "";
135
178
 
179
+ // The quiz of a quiz step. The answers live here, not in the state: a keystroke never re-renders the
180
+ // questions. They belong to the step on screen and start over when the member walks or tries again.
181
+ /** Read quizzes by quiz id; "web" is one the app cannot fill or may not read: it opens on the website. */
182
+ const quizzes = new Map<string, QuizModel | "web">();
183
+ const quizReads = new Set<string>();
184
+ /** Quiz ids whose read failed for another reason (offline, a 5xx): Try again reads them again. */
185
+ const quizReadFailed = new Set<string>();
186
+ let answers: Record<string, FieldValue> = {};
187
+ /** Questions Submit found unanswered; cleared as each is answered. */
188
+ let unanswered = new Set<string>();
189
+ /** Bumped on Try again: new row ids make a native text field mount empty. */
190
+ let answerRound = 0;
191
+ /** This visit's results by step: the submission marks each question, a resolved step does not. */
192
+ const results = new Map<string, QuizResult & { submissionId: string }>();
193
+ /** Steps the member is taking again after a fail. */
194
+ const retaking = new Set<string>();
195
+ /** Steps whose quiz the site refused with "attempts limit": no more tries. */
196
+ const exhausted = new Set<string>();
197
+ /** A failed send, shown under the questions until the next try. */
198
+ let quizSendError = "";
199
+ /** A submission Wix took whose step resolve failed, by step. The submission IS the attempt (Wix graded it and
200
+ * counted it): the step shows its result with "couldn't be saved", and Try again saves the same submission,
201
+ * never a new one. It outlives walks, edits and new pages; only another member drops it, or a resolved step
202
+ * the site shows with this very submission. */
203
+ const unresolved = new Map<string, { id: string; result: QuizResult }>();
204
+
205
+ /** The member the quiz state above belongs to (email and scope); another member starts with none of it. */
206
+ let quizOwner: { email: string; scope: unknown } | undefined;
207
+
208
+ const quizIdOf = (step: { quizOptions?: { id?: string } } | undefined): string => String(step?.quizOptions?.id ?? "");
209
+
136
210
  function input(): { id: string; stepId: string } {
137
211
  const value = (globalThis as { himalaya?: { input?: { id?: unknown; stepId?: unknown } } }).himalaya?.input;
138
212
  return { id: typeof value?.id === "string" ? value.id : "", stepId: typeof value?.stepId === "string" ? value.stepId : "" };
@@ -156,10 +230,14 @@ function derive(state: State): State {
156
230
  };
157
231
  }
158
232
 
233
+ const NO_QUIZ = {
234
+ quizRows: [] as QuizRow[], quizIntro: "", hideQuiz: true, hideQuizLoading: true, quizError: "",
235
+ hideResult: true, hideResultPass: true, hideResultFail: true, resultTitle: "", resultBody: "", hideRetry: true,
236
+ };
159
237
  const EMPTY_STEP = {
160
238
  sectionTitle: "", title: "", kindLabel: "", kindIcon: "", positionLabel: "", bodyText: "", bodyJson: "", hideBodyText: true,
161
239
  videoUrl: "", hideVideo: true, webText: "", hideWeb: true, hideWebButton: true, lockedLine: "", done: false, hideComplete: true, hideDone: true, hideUndo: true,
162
- frozenLine: "", hidePrevious: true, hideNext: true, hideNav: true,
240
+ frozenLine: "", hidePrevious: true, hideNext: true, hideNav: true, ...NO_QUIZ,
163
241
  };
164
242
  const CLOSED_SHEET = { sheetOpen: false, sheetIcon: "success", sheetTitle: "", sheetBody: "", hideSheetNext: true, hideSheetBack: true };
165
243
 
@@ -178,12 +256,14 @@ function stepView(data: Loaded, stepId: string): Partial<State> {
178
256
  const kind = stepKind(step);
179
257
  const body = descriptionBody(step.description?.details, "");
180
258
  const videoUrl = type === "VIDEO" ? videoUrlOf(step) : "";
181
- // A quiz is taken on the website until the app takes quizzes, and so is a video the app cannot play.
259
+ const quiz = type === "QUIZ";
260
+ // A quiz the app cannot fill or read is taken on the website, and so is a video the app cannot play.
182
261
  // With no website address the card still says why the step has no action.
183
- const onWeb = !locked && (type === "QUIZ" || (type === "VIDEO" && !videoUrl));
262
+ // A kept graded attempt is shown (and saved) here whatever the form read says: saving needs only its id.
263
+ const quizOnWeb = quiz && !unresolved.has(stepId) && (!quizIdOf(step) || quizzes.get(quizIdOf(step)) === "web");
264
+ const onWeb = !locked && (quizOnWeb || (type === "VIDEO" && !videoUrl));
184
265
  const done = data.done.has(stepId);
185
266
  const ended = data.ended;
186
- const quiz = type === "QUIZ";
187
267
  // A video the app cannot play on a program with no website: the member has no way to see it, so it cannot be completed here.
188
268
  const unviewable = unviewableStep(step, data);
189
269
  // A COMPLETED participation stays COMPLETED after an undo (amit1), and the One App never undoes a FAILED one.
@@ -213,7 +293,8 @@ function stepView(data: Loaded, stepId: string): Partial<State> {
213
293
  done,
214
294
  // A quiz completes with its submission (B5), never with a plain Complete.
215
295
  hideComplete: done || locked || ended || quiz || unviewable,
216
- hideDone: !done,
296
+ // A passed quiz says so on its result card, with the score; one taken on the website keeps the done line.
297
+ hideDone: !done || (quiz && !quizOnWeb),
217
298
  // A quiz's resolved step comes from its submission, and an unviewable video cannot be completed here:
218
299
  // undoing either would leave a step no Complete can redo.
219
300
  hideUndo: !done || ended || programDone || quiz || unviewable,
@@ -221,6 +302,7 @@ function stepView(data: Loaded, stepId: string): Partial<State> {
221
302
  hidePrevious: index === 0,
222
303
  hideNext: index === data.placed.length - 1,
223
304
  hideNav: !nav,
305
+ ...(quiz && !locked && !quizOnWeb ? quizView(data, stepId) : NO_QUIZ),
224
306
  };
225
307
  }
226
308
 
@@ -229,6 +311,130 @@ function unviewableStep(step: WixStep, data: Loaded): boolean {
229
311
  return String(step.stepType ?? "").toUpperCase() === "VIDEO" && !videoUrlOf(step) && !data.webUrl;
230
312
  }
231
313
 
314
+ /** What a quiz step shows under its content: its questions, a skeleton while they load, or its last result. */
315
+ function quizView(data: Loaded, stepId: string): Partial<State> {
316
+ const own = data.placed.find((p) => p.step.id === stepId);
317
+ const quizId = quizIdOf(own?.step);
318
+ const record = data.done.get(stepId) ?? data.failed.get(stepId);
319
+ const passed = data.done.has(stepId);
320
+ const kept = passed ? undefined : unresolved.get(stepId);
321
+ // This visit's result (it marks each answer) is shown only while the site's record is that same submission:
322
+ // a later try elsewhere (a pass, or another fail) is the site's, and outranks it.
323
+ const mine = results.get(stepId);
324
+ const session = mine && (!record?.quizSubmissionId || record.quizSubmissionId === mine.submissionId) && !(passed && !mine.passed) ? mine : undefined;
325
+ const last = kept?.result ?? session ?? (record ? quizResult(record) : undefined);
326
+ if (kept) {
327
+ // Wix graded this attempt, but the step was not saved: its result, and Try again saves it.
328
+ return {
329
+ ...NO_QUIZ,
330
+ hideResult: false,
331
+ hideResultPass: !kept.result.passed,
332
+ hideResultFail: kept.result.passed,
333
+ resultTitle: kept.result.passed ? copyParam("programStep.quizPassedTitle", "You passed") : copyParam("programStep.quizFailedTitle", "Not passed yet"),
334
+ resultBody: kept.result.passingGrade > 0
335
+ ? copyTemplate("programStep.quizScoreLine", "Your score: {score}%. You need {grade}% to pass.", { score: kept.result.score, grade: kept.result.passingGrade })
336
+ : copyTemplate("programStep.quizScoreOnly", "Your score: {score}%.", { score: kept.result.score }),
337
+ // While a save of it runs, the card says nothing failed.
338
+ quizError: busy ? "" : copyParam("programStep.completeFailed", "This step couldn't be saved. Try again."),
339
+ hideRetry: data.ended,
340
+ };
341
+ }
342
+ if (passed || (last && !retaking.has(stepId)) || exhausted.has(stepId)) {
343
+ const scoreLine = !last ? ""
344
+ : last.passingGrade > 0
345
+ ? copyTemplate("programStep.quizScoreLine", "Your score: {score}%. You need {grade}% to pass.", { score: last.score, grade: last.passingGrade })
346
+ : copyTemplate("programStep.quizScoreOnly", "Your score: {score}%.", { score: last.score });
347
+ const rightLine = last && last.marked > 0
348
+ ? copyTemplate("programStep.quizRightLine", "{correct} of {total} answers were right.", { correct: last.correct, total: last.marked })
349
+ : "";
350
+ const noTries = !passed && exhausted.has(stepId) ? copyParam("programStep.quizNoAttempts", "You have no attempts left for this quiz.") : "";
351
+ return {
352
+ ...NO_QUIZ,
353
+ hideResult: false,
354
+ hideResultPass: !passed,
355
+ hideResultFail: passed,
356
+ resultTitle: passed ? copyParam("programStep.quizPassedTitle", "You passed") : copyParam("programStep.quizFailedTitle", "Not passed yet"),
357
+ resultBody: [scoreLine, rightLine, noTries].filter(Boolean).join(" "),
358
+ // A pass completes the step; a fail can be tried again until the site says no tries are left.
359
+ hideRetry: passed || data.ended || exhausted.has(stepId),
360
+ };
361
+ }
362
+ // An ended program takes no answers: its frozen line says so.
363
+ if (data.ended) return NO_QUIZ;
364
+ if (quizReadFailed.has(quizId)) {
365
+ return { ...NO_QUIZ, quizError: copyParam("programStep.quizLoadFailed", "This quiz couldn't be loaded."), hideRetry: false, hideResult: true };
366
+ }
367
+ const model = quizzes.get(quizId);
368
+ if (!model || model === "web") return { ...NO_QUIZ, hideQuizLoading: false };
369
+ return {
370
+ ...NO_QUIZ,
371
+ quizRows: model.questions.map(quizRow),
372
+ quizIntro: model.passingGrade > 0
373
+ ? copyTemplate("programStep.quizIntro", "Answer every question, then submit. You need {grade}% to pass.", { grade: model.passingGrade })
374
+ : copyParam("programStep.quizIntroNoGrade", "Answer every question, then submit."),
375
+ hideQuiz: false,
376
+ quizError: quizSendError || (unanswered.size ? copyParam("programStep.quizUnanswered", "Answer every question to submit.") : ""),
377
+ };
378
+ }
379
+
380
+ function quizRow(question: QuizModel["questions"][number]): QuizRow {
381
+ const value = answers[question.target] ?? EMPTY_VALUE;
382
+ const id = `${question.id}_${answerRound}`;
383
+ const error = unanswered.has(question.target) ? copyParam("programStep.quizAnswerThis", "Answer this question.") : "";
384
+ return {
385
+ id, target: question.target, label: question.label, value: value.text,
386
+ options: question.options.map((o, i) => ({ id: `${id}_${i}`, target: question.target, value: o.value, label: o.label, selected: value.selected.includes(o.value) })),
387
+ notChoice: question.kind !== "choice", notMulti: question.kind !== "multi",
388
+ notText: question.kind !== "text", notArea: question.kind !== "area", notNumber: question.kind !== "number",
389
+ error, noError: !error,
390
+ };
391
+ }
392
+
393
+ /** Reads the quiz of the step on screen once, then redraws that step if the member is still on it. */
394
+ async function readQuiz(stepId: string): Promise<void> {
395
+ const data = loaded;
396
+ const own = data?.placed.find((p) => p.step.id === stepId);
397
+ const quizId = quizIdOf(own?.step);
398
+ if (!data || !own || own.locked || !isQuizStep(own.step) || !quizId) return;
399
+ if (quizzes.has(quizId) || quizReads.has(quizId)) return;
400
+ quizReads.add(quizId);
401
+ quizReadFailed.delete(quizId);
402
+ try {
403
+ const model = parseQuiz(await getForm(quizId));
404
+ quizzes.set(quizId, model.unsupported ? "web" : model);
405
+ } catch (error) {
406
+ // A quiz the member may not read (or one that is gone) is taken on the website; anything else can be tried again.
407
+ if (isRefused(error) || isNotFoundError(error)) quizzes.set(quizId, "web");
408
+ else quizReadFailed.add(quizId);
409
+ } finally {
410
+ quizReads.delete(quizId);
411
+ }
412
+ const now = loaded;
413
+ if (now && svc.getState().stepId === stepId) void svc.publish(stepView(now, stepId));
414
+ }
415
+
416
+ /** A new step on screen, or a new try: no answers, no marks. */
417
+ function resetAnswers(): void {
418
+ answers = {};
419
+ unanswered = new Set();
420
+ quizSendError = "";
421
+ answerRound += 1;
422
+ }
423
+
424
+ /** A new page (or another member): no read quiz, result, try or answer of the last visit is kept. A submission
425
+ * still to be saved stays for the same member: it is a real attempt. */
426
+ function forgetQuizzes(memberChanged = false): void {
427
+ quizzes.clear();
428
+ quizReadFailed.clear();
429
+ if (memberChanged) unresolved.clear();
430
+ results.clear();
431
+ retaking.clear();
432
+ exhausted.clear();
433
+ resetAnswers();
434
+ }
435
+
436
+ const isQuizStep = (step: { stepType?: string } | undefined): boolean => String(step?.stepType ?? "").toUpperCase() === "QUIZ";
437
+
232
438
  /** The completion sheet for `kind`, about the step on screen. */
233
439
  function sheetView(data: Loaded, kind: Completion | undefined, stepId: string): Partial<State> {
234
440
  if (!kind) return CLOSED_SHEET;
@@ -268,6 +474,9 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
268
474
  if (!samePage) {
269
475
  pageSeq += 1;
270
476
  completion = undefined;
477
+ // A new page reads its quizzes and their results again: the owner may have changed the questions, a refused
478
+ // read may now pass, and the site's resolved steps (read below) are the result, not the last visit's.
479
+ forgetQuizzes();
271
480
  void svc.publish({ status: "loading", programId: id, stepId, ...CLOSED_SHEET });
272
481
  }
273
482
  let member: MemberAccess | undefined;
@@ -284,10 +493,14 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
284
493
  ]);
285
494
  member = identity;
286
495
  if (!current()) return undefined;
496
+ // The quiz state is the member's own: another member (or a scope change) never sees it, whatever `loaded` holds.
497
+ if (quizOwner && member.email && (quizOwner.email !== member.email || quizOwner.scope !== member.scope)) forgetQuizzes(true);
498
+ quizOwner = member.email ? { email: member.email, scope: member.scope } : undefined;
287
499
  if (!member.email) {
288
500
  access = "signIn";
289
501
  loaded = undefined;
290
502
  completion = undefined;
503
+ forgetQuizzes(true);
291
504
  void svc.publish({ programId: id, stepId, status: "ready", ...CLOSED_SHEET });
292
505
  return undefined;
293
506
  }
@@ -339,13 +552,20 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
339
552
  // A complete or an undo landed while these reads ran: they predate it, so read again.
340
553
  if (writes !== writesAtStart) { void svc.load(); return undefined; }
341
554
  const placed = placeSteps(sections ?? [], steps, participant, Date.now());
342
- loaded = { member, participant, standing, placed, done: readable.done,
555
+ // Another member's results never carry over (a sign-out and a sign-in as someone else).
556
+ // A kept submission the site shows resolved (the resolve landed after all) is done with. Only a record with
557
+ // that very submission counts: an earlier try's FAILED record does not resolve a later attempt.
558
+ for (const [stepKey, kept] of [...unresolved]) {
559
+ if ((resolved ?? []).some((r) => r.programStepId === stepKey && r.quizSubmissionId === kept.id)) unresolved.delete(stepKey);
560
+ }
561
+ loaded = { member, participant, standing, placed, done: readable.done, failed: failedQuizzes(resolved ?? [], readable.done),
343
562
  reportedTotal: readable.reportedTotal, ended: isProgramEnded(program), name, webUrl, locale };
344
563
  // A refresh lands on the step the member is on NOW: they may have walked while it ran. A screen
345
564
  // opened with no step (a link with only the program) lands on the next step to take, else the first.
346
565
  const fallback = stepId || (placed.find((p) => !p.locked && !readable.done.has(p.step.id!)) ?? placed[0])?.step.id || "";
347
566
  const shown = samePage ? svc.getState().stepId || fallback : fallback;
348
567
  void svc.publish({ programId: id, programName: name, status: "ready", writeError: "", ...stepView(loaded, shown), ...sheetView(loaded, completion, shown) });
568
+ void readQuiz(shown);
349
569
  } catch (error) {
350
570
  if (!current()) return undefined;
351
571
  const changed = await memberChanged(member, error);
@@ -355,6 +575,7 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
355
575
  loaded = undefined;
356
576
  completion = undefined;
357
577
  access = "member";
578
+ forgetQuizzes(true);
358
579
  void svc.publish({ status: "loading", programId: "", ...EMPTY_STEP, ...CLOSED_SHEET });
359
580
  void svc.load();
360
581
  return undefined;
@@ -403,7 +624,7 @@ async function complete(state: State): Promise<undefined> {
403
624
  // One publish when the write settles: two publishes in one turn both start from the same state.
404
625
  let patch: Partial<State> = {};
405
626
  try {
406
- if (!own || own.locked || data.done.has(stepId) || data.ended || String(own.step.stepType ?? "").toUpperCase() === "QUIZ" || unviewableStep(own.step, data)) return undefined;
627
+ if (!own || own.locked || data.done.has(stepId) || data.ended || isQuizStep(own.step) || unviewableStep(own.step, data)) return undefined;
407
628
  // No status: the spec lists none, and the upsert answers COMPLETED for a plain completion (amit1, 2026-11-18).
408
629
  const response = await completeStep(data.participant.id, stepId);
409
630
  writes += 1;
@@ -435,7 +656,7 @@ async function undo(state: State): Promise<undefined> {
435
656
  try {
436
657
  const record = data.done.get(stepId);
437
658
  const own = data.placed.find((p) => p.step.id === stepId);
438
- if (!record || data.ended || ["COMPLETED", "FAILED"].includes(String(data.participant.progressStatus ?? "").toUpperCase()) || String(own?.step.stepType ?? "").toUpperCase() === "QUIZ" || (own && unviewableStep(own.step, data))) return undefined;
659
+ if (!record || data.ended || ["COMPLETED", "FAILED"].includes(String(data.participant.progressStatus ?? "").toUpperCase()) || isQuizStep(own?.step) || (own && unviewableStep(own.step, data))) return undefined;
439
660
  // The upsert answer carries the record's id; a record read without one is found again.
440
661
  const resolvedId = record.id || (await allResolved(data.participant.id)).find((r) => r.programStepId === stepId)?.id;
441
662
  if (!resolvedId) throw new Error("Resolved step unavailable");
@@ -455,6 +676,134 @@ async function undo(state: State): Promise<undefined> {
455
676
  return undefined;
456
677
  }
457
678
 
679
+ /** The quiz steps whose resolved step is FAILED: the last try did not pass. A done step is never failed. */
680
+ function failedQuizzes(resolved: readonly WixResolvedStep[], done: ReadonlyMap<string, WixResolvedStep>): Map<string, WixResolvedStep> {
681
+ const failed = new Map<string, WixResolvedStep>();
682
+ for (const record of resolved) {
683
+ if (record.programStepId && !done.has(record.programStepId) && String(record.status ?? "").toUpperCase() === "FAILED") failed.set(record.programStepId, record);
684
+ }
685
+ return failed;
686
+ }
687
+
688
+ /** Submit: send the answers, then resolve the step with the submission. The site decides the result:
689
+ * COMPLETED (passed: the step is done, and the completion sheet shows) or FAILED (the result card and Try again). */
690
+ async function submitQuiz(state: State): Promise<undefined> {
691
+ const data = loaded;
692
+ const stepId = state.stepId;
693
+ const own = data?.placed.find((p) => p.step.id === stepId);
694
+ const quizId = quizIdOf(own?.step);
695
+ const model = quizzes.get(quizId);
696
+ if (!data || !own || own.locked || !isQuizStep(own.step) || data.done.has(stepId) || data.ended) return undefined;
697
+ // A kept submission (its resolve failed) is saved as it is, with no form; a new one needs the read quiz.
698
+ const kept = unresolved.get(stepId);
699
+ if (!kept && (!model || model === "web" || exhausted.has(stepId))) return undefined;
700
+ // Every question first: the site would refuse the send anyway.
701
+ const missing = kept || !model || model === "web" ? [] : unansweredTargets(model, answers);
702
+ if (missing.length) {
703
+ unanswered = new Set(missing);
704
+ quizSendError = "";
705
+ void svc.publish(stepView(data, stepId));
706
+ return undefined;
707
+ }
708
+ const writing = await writable(state);
709
+ if (!writing) return undefined;
710
+ const page = pageSeq;
711
+ let patch: Partial<State> = {};
712
+ // The graded attempt, once Wix took it. It is kept (unresolved) only if its resolve then fails, so no redraw
713
+ // during the save shows "couldn't be saved".
714
+ let sentNow = kept;
715
+ try {
716
+ if (!sentNow) {
717
+ if (!model || model === "web") throw new Error("Quiz unavailable");
718
+ const sent = await createQuizSubmission({ quizId, groupId: writing.participant.id, answers: quizAnswers(model, answers) });
719
+ // The site answers the submission twice, as `quizSubmission` and as `submission` (amit1).
720
+ const submission = sent.quizSubmission ?? (sent as { submission?: typeof sent.quizSubmission }).submission;
721
+ if (!submission?.id) throw new Error("Quiz submission unavailable");
722
+ sentNow = { id: submission.id, result: quizResult(submission) };
723
+ }
724
+ const response = await completeStep(writing.participant.id, stepId, { quizSubmissionId: sentNow.id });
725
+ unresolved.delete(stepId);
726
+ writes += 1;
727
+ await markProgress(state.programId);
728
+ const target = writeTarget(writing, page);
729
+ if (!target) { void svc.load(); return undefined; }
730
+ const result = sentNow.result;
731
+ const record = response.resolvedStep ?? { programStepId: stepId, participantId: target.participant.id, status: result.passed ? "COMPLETED" : "FAILED" };
732
+ results.set(stepId, { ...result, submissionId: sentNow.id });
733
+ retaking.delete(stepId);
734
+ resetAnswers();
735
+ // The resolved step's status is the site's verdict; a record with no status follows the submission.
736
+ const status = String(record.status ?? "").toUpperCase();
737
+ if (status === "COMPLETED" || (!status && result.passed)) {
738
+ target.failed.delete(stepId);
739
+ target.done.set(stepId, record);
740
+ completion = completionOf(target.placed, new Set(target.done.keys()), stepId, target.reportedTotal);
741
+ if (completion === "program") target.participant = { ...target.participant, progressStatus: "COMPLETED" };
742
+ } else if (status === "FAILED" || !status) {
743
+ target.failed.set(stepId, record);
744
+ } else {
745
+ // Any other status (a quiz waiting for review) is neither a pass nor a fail, as a reload reads it:
746
+ // the step shows its questions again, with no verdict.
747
+ target.failed.delete(stepId);
748
+ results.delete(stepId);
749
+ }
750
+ patch = { ...stepView(target, svc.getState().stepId), ...sheetView(target, completion, stepId) };
751
+ } catch (error) {
752
+ // The send is over: the view below must not read it as still saving.
753
+ busy = false;
754
+ // Wix took the attempt but the step was not saved: keep it, so Try again saves this very submission.
755
+ if (sentNow && !isAttemptsExhausted(error)) unresolved.set(stepId, sentNow);
756
+ // Another page replaced this one while the send ran: the failure is not its to show.
757
+ const target = writeTarget(writing, page);
758
+ if (isAttemptsExhausted(error)) {
759
+ exhausted.add(stepId);
760
+ retaking.delete(stepId);
761
+ } else if (target && !unresolved.has(stepId)) {
762
+ // Nothing reached Wix: the answers stay for the next Submit. (A kept submission shows its own card.)
763
+ quizSendError = writeErrorOf(error, copyParam("programStep.quizSendFailed", "Your answers couldn't be sent. Try again."));
764
+ }
765
+ if (target) patch = stepView(target, svc.getState().stepId);
766
+ } finally {
767
+ busy = false;
768
+ void svc.publish({ ...patch, busy: false });
769
+ }
770
+ return undefined;
771
+ }
772
+
773
+ /** Try again: after a fail, the questions come back empty; after a failed read, the quiz is read again. */
774
+ function retryQuiz(state: State): State {
775
+ const data = loaded;
776
+ const own = data?.placed.find((p) => p.step.id === state.stepId);
777
+ if (!data || !own || busy || !isQuizStep(own.step)) return state;
778
+ // Try again on a kept submission saves that submission: a new one would spend another attempt.
779
+ if (unresolved.has(state.stepId)) { void submitQuiz(state); return state; }
780
+ const quizId = quizIdOf(own.step);
781
+ if (quizReadFailed.has(quizId)) {
782
+ quizReadFailed.delete(quizId);
783
+ void readQuiz(state.stepId);
784
+ }
785
+ // A new try after a fail: the questions come back (once read) instead of the fail card.
786
+ if (!data.done.has(state.stepId) && !data.ended && !exhausted.has(state.stepId)) {
787
+ retaking.add(state.stepId);
788
+ results.delete(state.stepId);
789
+ }
790
+ resetAnswers();
791
+ return derive({ ...state, ...stepView(data, state.stepId) });
792
+ }
793
+
794
+ /** An answer changed: store it, and redraw only when a choice shows (a mark) or an error clears. */
795
+ function answer(state: State, target: string, change: (value: FieldValue) => FieldValue, redraw: boolean): State {
796
+ const data = loaded;
797
+ // An answer changed while a send runs is kept too: the screen shows it, so the next Submit sends it.
798
+ if (!data || !target) return state;
799
+ answers = { ...answers, [target]: change(answers[target] ?? EMPTY_VALUE) };
800
+ const cleared = unanswered.delete(target);
801
+ if (!redraw && !cleared) return state;
802
+ return derive({ ...state, ...stepView(data, state.stepId) });
803
+ }
804
+
805
+ const argOf = (arg: unknown): Record<string, unknown> => (arg && typeof arg === "object" ? arg as Record<string, unknown> : {});
806
+
458
807
  function writeErrorOf(error: unknown, fallback: string): string {
459
808
  return !connectivity().online || String(error).includes(offlineWriteMessage) ? offlineWriteMessage : fallback;
460
809
  }
@@ -467,6 +816,8 @@ function walk(state: State, by: number): State {
467
816
  const target = data.placed[index + by];
468
817
  if (index < 0 || !target?.step.id) return state;
469
818
  completion = undefined;
819
+ resetAnswers();
820
+ void readQuiz(target.step.id);
470
821
  return derive({ ...state, ...stepView(data, target.step.id), ...CLOSED_SHEET, writeError: "" });
471
822
  }
472
823
 
@@ -482,10 +833,15 @@ type Actions = {
482
833
  backToProgram: (state: State) => State;
483
834
  openWeb: (state: State) => Promise<undefined>;
484
835
  openLink: (state: State, arg?: unknown) => Promise<undefined>;
836
+ submitQuiz: (state: State) => Promise<undefined>;
837
+ retryQuiz: (state: State) => State;
838
+ chooseAnswer: (state: State, arg?: unknown) => State;
839
+ toggleAnswer: (state: State, arg?: unknown) => State;
840
+ setAnswer: (state: State, arg?: unknown) => State;
485
841
  };
486
842
 
487
- // Complete and undo need the network: offline, they say so and change nothing.
488
- const defineService = withOnlineWrites<State>(registerService, ["complete", "undo"], { derive, messageFields: ["writeError"] });
843
+ // Complete, undo and a quiz submission need the network: offline, they say so and change nothing.
844
+ const defineService = withOnlineWrites<State>(registerService, ["complete", "undo", "submitQuiz"], { derive, messageFields: ["writeError"] });
489
845
 
490
846
  const svc = defineService<State, Actions>(SERVICE, {
491
847
  state: INITIAL_STATE,
@@ -513,6 +869,32 @@ const svc = defineService<State, Actions>(SERVICE, {
513
869
  return undefined;
514
870
  },
515
871
  openLink: async (_state, arg) => { await openRichLink(arg); return undefined; },
872
+ submitQuiz,
873
+ retryQuiz,
874
+ // A single choice keeps one option; a multi choice adds or drops each one; a typed answer is its text.
875
+ // The control reports its new state as `value`: it is followed when present, so an extra event can
876
+ // never leave the answer out of step with the box on screen. Without it the option toggles.
877
+ chooseAnswer: (state, arg) => {
878
+ const a = argOf(arg);
879
+ const option = String(a.option ?? "");
880
+ if (!option || a.value === false) return state;
881
+ return answer(state, String(a.target ?? ""), (v) => ({ ...v, selected: [option] }), true);
882
+ },
883
+ toggleAnswer: (state, arg) => {
884
+ const a = argOf(arg);
885
+ const option = String(a.option ?? "");
886
+ if (!option) return state;
887
+ return answer(state, String(a.target ?? ""), (v) => {
888
+ const on = typeof a.value === "boolean" ? a.value : !v.selected.includes(option);
889
+ const rest = v.selected.filter((o) => o !== option);
890
+ return { ...v, selected: on ? [...rest, option] : rest };
891
+ }, true);
892
+ },
893
+ setAnswer: (state, arg) => {
894
+ const a = argOf(arg);
895
+ const text = typeof a.value === "string" ? a.value : typeof a.text === "string" ? a.text : "";
896
+ return answer(state, String(a.target ?? ""), (v) => ({ ...v, text }), false);
897
+ },
516
898
  },
517
899
  });
518
900