Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 2x 2x 2x 2x 2x 2x 2x 2x 12x 14x 14x 1x 1x 1x 1x 1x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 1x 1x 1x 1x 1x 1x 243x 243x 243x 716x 716x 716x 243x 243x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 3x 3x 3x 3x 83x 83x 86x 83x 86x 214x 214x 214x 68x 68x 214x 15x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 213x 213x 213x 213x 213x 213x 213x 213x 213x 213x 115x 115x 115x 213x 213x 213x 213x 114x 114x 114x 114x 213x 38x 38x 38x 38x 38x 38x 76x 76x 76x 76x 76x 76x 213x 39x 39x 39x 213x 3x 3x 3x 3x 3x 3x 36x 36x 36x 36x 36x 36x 48x 48x 36x 36x 36x 36x 36x 36x 36x 36x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 24x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 249x 249x 249x 249x 249x 249x 78x 78x 249x 249x 249x 249x 249x 249x 249x 249x 245x 245x 245x 245x 245x 245x 148x 245x 6x 245x 10x 10x 10x 10x 5x 5x 4x 2x 10x 9x 9x 1x 1x 1x 245x 81x 245x 249x 249x 249x 219x 140x 249x 249x 249x 219x 140x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 245x 245x 8x 8x 8x 245x 245x 245x 13x 13x 13x 13x 245x 245x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 249x 249x 249x 249x 249x 245x 13x 249x 249x 249x 219x 43x 43x 249x 249x 249x 243x 243x 243x 243x 24x 24x 243x 24x 24x 249x 249x 249x 249x 249x 154x 141x 249x 249x 249x 249x 249x 249x 249x 154x 141x 120x 249x 249x 249x 249x 249x 154x 141x 249x 249x 249x 249x 249x 249x 249x 249x 249x 245x 21x 21x 224x 245x 1x 1x 223x 249x 249x 249x 249x 245x 6x 6x 239x 249x 249x 249x 249x 249x 249x 249x 249x 70x 70x 70x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 202x 202x 78x 78x 78x 78x 78x 124x 124x 124x 124x 124x 124x 249x 249x 249x 249x 76x 76x 76x 76x 7x 4x 76x 1x 1x 75x 75x 75x 75x 76x 3x 3x 3x 3x 3x 75x 75x 75x 75x 75x 76x 3x 3x 3x 3x 3x 3x 3x 72x 76x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 49x 49x 25x 49x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 49x 42x 42x 42x 76x 11x 11x 11x 11x 11x 11x 3x 3x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 76x 76x 76x 76x 13x 13x 13x 2x 13x 13x 13x 76x 76x 249x 249x 249x 249x 4x 4x 4x 1x 4x 4x 4x 4x 3x 3x 3x 4x 4x 4x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 249x 249x 249x 14x 14x 14x 14x 4x 3x 14x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 14x 249x 249x 249x 4x 4x 4x 4x 4x 4x 249x 249x 249x 249x 249x 249x 249x 249x 249x 20x 20x 20x 20x 1x 20x 20x 20x 249x 249x 249x 11x 11x 11x 11x 11x 11x 249x 249x 249x 249x 7x 7x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 7x 7x 249x 249x 249x 249x 3x 3x 3x 3x 3x 3x 249x 249x 249x 1x 249x 249x 249x 2x 249x 249x 249x 11x 11x 11x 8x 11x 249x 249x 249x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x 249x | 'use client'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { GeneratedProblem } from '@/db/schema/session-plans'
// =============================================================================
// Types
// =============================================================================
/**
* Problem context passed as a prop - the single source of truth for what problem
* is currently being worked on. This is computed by the parent component from
* redoState + session plan, eliminating dual sources of truth.
*/
export interface ProblemContext {
/** The problem being solved */
problem: GeneratedProblem
/** Index in the current part (original slot index for redos) */
slotIndex: number
/** Part index in the session */
partIndex: number
}
/**
* Input-level state for a problem attempt.
* This is what the student is actively working on - their answer input.
*/
export interface AttemptInput {
/** The problem being solved */
problem: GeneratedProblem
/** Index in the current part */
slotIndex: number
/** Part index in the session */
partIndex: number
/** When the attempt started */
startTime: number
/** Accumulated time spent paused (ms) - subtract from elapsed time for actual response time */
accumulatedPauseMs: number
/** User's current answer input */
userAnswer: string
/** Number of times user used backspace or had digits rejected */
correctionCount: number
/** Whether manual submit is required (exceeded auto-submit threshold) */
manualSubmitRequired: boolean
/** Rejected digit to show as red X (null = no rejection) */
rejectedDigit: string | null
}
/**
* Context for help mode - computed when entering help
*/
export interface HelpContext {
/** Index of the term being helped with */
termIndex: number
/** Current running total before this term */
currentValue: number
/** Target value after adding this term */
targetValue: number
/** The term being added */
term: number
}
/**
* Snapshot of an attempt that's animating out during transition
*/
export interface OutgoingAttempt {
key: string
problem: GeneratedProblem
userAnswer: string
result: 'correct' | 'incorrect'
}
/**
* Context for the disambiguation phase - when user's input matches
* an intermediate prefix sum but could also be the start of the final answer
*/
export interface DisambiguationContext {
/** Index of the matched prefix sum */
matchedPrefixIndex: number
/** Term index to show help for if they want it */
helpTermIndex: number
/** When the disambiguation timer started */
timerStartedAt: number
}
/**
* Non-paused phases (used for resumePhase type)
*/
export type ActivePhase =
| { phase: 'loading' }
| { phase: 'inputting'; attempt: AttemptInput }
| {
phase: 'awaitingDisambiguation'
attempt: AttemptInput
disambiguationContext: DisambiguationContext
}
| { phase: 'helpMode'; attempt: AttemptInput; helpContext: HelpContext }
| { phase: 'submitting'; attempt: AttemptInput }
| {
phase: 'showingFeedback'
attempt: AttemptInput
result: 'correct' | 'incorrect'
}
| {
phase: 'transitioning'
outgoing: OutgoingAttempt
incoming: AttemptInput
}
| { phase: 'complete' }
/**
* Discriminated union representing all possible interaction phases.
* Each phase carries exactly the data needed for that phase.
*/
export type InteractionPhase =
| ActivePhase
// Session paused - remembers what phase to return to
| {
phase: 'paused'
resumePhase: ActivePhase
/** When the pause started (used to calculate pause duration on resume) */
pauseStartedAt: number
}
/** Threshold for correction count before requiring manual submit */
export const MANUAL_SUBMIT_THRESHOLD = 2
/** Time to wait before auto-triggering help in ambiguous cases (ms) */
export const AMBIGUOUS_HELP_DELAY_MS = 4000
// =============================================================================
// Helper Functions
// =============================================================================
/**
* Gets the active (non-paused) phase, unwrapping if paused.
*/
export function getActivePhase(phase: InteractionPhase): ActivePhase {
return phase.phase === 'paused' ? phase.resumePhase : phase
}
/**
* Applies a transformation to the active phase, preserving paused wrapper if present.
* If the transform returns null, the phase is unchanged.
*/
export function transformActivePhase(
phase: InteractionPhase,
transform: (active: ActivePhase) => ActivePhase | null
): InteractionPhase {
if (phase.phase === 'paused') {
const newResumePhase = transform(phase.resumePhase)
if (newResumePhase === null) return phase
return {
phase: 'paused',
resumePhase: newResumePhase,
pauseStartedAt: phase.pauseStartedAt,
}
}
const newPhase = transform(phase)
return newPhase === null ? phase : newPhase
}
/**
* Creates a fresh attempt input for a new problem
*/
export function createAttemptInput(
problem: GeneratedProblem,
slotIndex: number,
partIndex: number
): AttemptInput {
return {
problem,
slotIndex,
partIndex,
startTime: Date.now(),
accumulatedPauseMs: 0,
userAnswer: '',
correctionCount: 0,
manualSubmitRequired: false,
rejectedDigit: null,
}
}
/**
* Computes prefix sums for a problem's terms.
* prefixSums[i] = sum of terms[0..i] (inclusive)
*/
export function computePrefixSums(terms: number[]): number[] {
const sums: number[] = []
let total = 0
for (const term of terms) {
total += term
sums.push(total)
}
return sums
}
/**
* Checks if a digit would be consistent with any prefix sum.
*
* Leading zeros are allowed as a disambiguation mechanism:
* - Typing "0" when answer is empty is allowed (starts a multi-digit entry)
* - Typing "03" signals intent to enter a 2+ digit number ending in 3
* - The numeric value after stripping leading zeros must be consistent
*/
export function isDigitConsistent(
currentAnswer: string,
digit: string,
prefixSums: number[]
): boolean {
const newAnswer = currentAnswer + digit
// Allow leading zeros as disambiguation (e.g., "0" or "03" for 3)
// Strip leading zeros to get the numeric prefix we're building toward
const strippedAnswer = newAnswer.replace(/^0+/, '') || '0'
// If the result is just zeros, allow it (user is typing leading zeros)
if (strippedAnswer === '0' && newAnswer.length > 0) {
// Allow typing zeros as long as we haven't exceeded max answer length
const maxLength = Math.max(...prefixSums.map((s) => s.toString().length))
return newAnswer.length <= maxLength
}
const newAnswerNum = parseInt(strippedAnswer, 10)
if (Number.isNaN(newAnswerNum)) return false
for (const sum of prefixSums) {
const sumStr = sum.toString()
// Check if stripped answer is a prefix of any sum
if (sumStr.startsWith(strippedAnswer)) {
return true
}
}
return false
}
/**
* Result of checking for prefix sum matches
*/
export interface PrefixMatchResult {
/** Index of matched prefix sum (-1 if none) */
matchedIndex: number
/** Whether this is an ambiguous match (could be digit-prefix of final answer) */
isAmbiguous: boolean
/** The term index to show help for (matchedIndex + 1, since we help with the NEXT term) */
helpTermIndex: number
}
/**
* Finds which prefix sum the user's answer matches, if any.
* Also detects ambiguous cases where the input could be either:
* 1. An intermediate prefix sum (user is stuck)
* 2. The first digit(s) of a later prefix sum (user is still typing)
*
* Leading zeros disambiguate and REQUEST help:
* - "3" alone is ambiguous (could be prefix sum 3 OR first digit of 33)
* - "03" is unambiguous - user clearly wants help with prefix sum 3
*/
export function findMatchedPrefixIndex(
userAnswer: string,
prefixSums: number[]
): PrefixMatchResult {
const noMatch: PrefixMatchResult = {
matchedIndex: -1,
isAmbiguous: false,
helpTermIndex: -1,
}
if (!userAnswer) return noMatch
// Leading zeros indicate user is explicitly requesting help for that prefix sum
// "03" means "I want help with prefix sum 3" - this is NOT ambiguous
const hasLeadingZero = userAnswer.startsWith('0') && userAnswer.length > 1
const answerNum = parseInt(userAnswer, 10)
if (Number.isNaN(answerNum)) return noMatch
const finalAnswer = prefixSums[prefixSums.length - 1]
// Check if this is the final answer
if (answerNum === finalAnswer) {
return {
matchedIndex: prefixSums.length - 1,
isAmbiguous: false,
helpTermIndex: -1,
}
}
// Check if user's input matches an intermediate prefix sum
const matchedIndex = prefixSums.findIndex(
(sum, i) => i < prefixSums.length - 1 && sum === answerNum
)
if (matchedIndex === -1) return noMatch
// If they used leading zeros, they're explicitly requesting help - NOT ambiguous
// "03" clearly means "help me with prefix sum 3"
if (hasLeadingZero) {
return {
matchedIndex,
isAmbiguous: false, // Leading zero removes ambiguity - they want help
helpTermIndex: matchedIndex + 1,
}
}
// Check if user's input could be a digit-prefix of ANY later prefix sum
// For example, with prefix sums [2, 3, 33, 43, 44]:
// - "3" matches prefix sum at index 1, but could also be first digit of 33 or 43
// - So "3" is ambiguous
const couldBeLaterPrefixPrefix = prefixSums.slice(matchedIndex + 1).some((laterSum) => {
const laterSumStr = laterSum.toString()
return laterSumStr.startsWith(userAnswer)
})
return {
matchedIndex,
isAmbiguous: couldBeLaterPrefixPrefix,
helpTermIndex: matchedIndex + 1, // Help with the NEXT term after the matched sum
}
}
/**
* Computes help context for a given term index
*/
export function computeHelpContext(terms: number[], termIndex: number): HelpContext {
const sums = computePrefixSums(terms)
const currentValue = termIndex === 0 ? 0 : sums[termIndex - 1]
const targetValue = sums[termIndex]
const term = terms[termIndex]
return { termIndex, currentValue, targetValue, term }
}
// =============================================================================
// Hook
// =============================================================================
export interface InitialProblemData {
problem: GeneratedProblem
slotIndex: number
partIndex: number
}
/**
* Active problem context with a stable key for change detection.
* The key allows the hook to detect when the problem truly changes,
* not just when references change.
*/
export interface ActiveProblem {
problem: GeneratedProblem
slotIndex: number
partIndex: number
/** Stable identifier for this problem instance - changes when the problem changes */
key: string
}
export interface UseInteractionPhaseOptions {
/** Initial problem to hydrate with (for SSR) */
initialProblem?: InitialProblemData
/**
* Active problem context - derived from redoState + session plan.
* When the key changes, the hook automatically loads the new problem.
* This is the single source of truth for which problem is being worked on.
*/
activeProblem?: ActiveProblem | null
/** Called when auto-submit threshold is exceeded */
onManualSubmitRequired?: () => void
}
export interface UseInteractionPhaseReturn {
// Current phase
phase: InteractionPhase
// Extracted state from phase (single source of truth)
/** Current attempt being worked on (null in loading/complete phases) */
attempt: AttemptInput | null
/** Help context when in helpMode (null otherwise) */
helpContext: HelpContext | null
/** Outgoing attempt during transition animation (null otherwise) */
outgoingAttempt: OutgoingAttempt | null
// Derived predicates for UI
/** Can we accept keyboard/keypad input? */
canAcceptInput: boolean
/** Should the problem display show as completed? */
showAsCompleted: boolean
/** Should the help overlay be shown? */
showHelpOverlay: boolean
/** Should the input area (keypad/submit) be shown? */
showInputArea: boolean
/** Should the feedback message be shown? */
showFeedback: boolean
/** Is the input box focused? */
inputIsFocused: boolean
/** Are we currently in the transitioning phase? */
isTransitioning: boolean
/** Are we currently paused? */
isPaused: boolean
/** Are we currently submitting? */
isSubmitting: boolean
// Computed values (only valid when attempt exists)
/** Prefix sums for current problem */
prefixSums: number[]
/** Full prefix match result with ambiguity info */
prefixMatch: PrefixMatchResult
/** Matched prefix index (-1 if none) - shorthand for prefixMatch.matchedIndex */
matchedPrefixIndex: number
/** Can the submit button be pressed? */
canSubmit: boolean
/** Should auto-submit trigger? */
shouldAutoSubmit: boolean
// Ambiguous prefix state
/** Term index to show "need help?" prompt for (-1 if not in awaitingDisambiguation phase) */
ambiguousHelpTermIndex: number
// Actions
/** Load a new problem (loading → inputting) */
loadProblem: (problem: GeneratedProblem, slotIndex: number, partIndex: number) => void
/** Handle digit input */
handleDigit: (digit: string) => void
/** Handle backspace */
handleBackspace: () => void
/** Enter help mode (inputting → helpMode) */
enterHelpMode: (termIndex: number) => void
/** Exit help mode (helpMode → inputting) */
exitHelpMode: () => void
/** Clear the current answer (used after help overlay transition completes) */
clearAnswer: () => void
/** Set the answer to a specific value (used when showing target reached value) */
setAnswer: (value: string) => void
/** Submit answer (inputting/helpMode → submitting) */
startSubmit: () => void
/** Handle submit result (submitting → showingFeedback) */
completeSubmit: (result: 'correct' | 'incorrect') => void
/** Start transition to next problem (showingFeedback → transitioning) */
startTransition: (
nextProblem: GeneratedProblem,
nextSlotIndex: number,
nextPartIndex?: number
) => void
/** Complete transition (transitioning → inputting) */
completeTransition: () => void
/** Clear to loading state */
clearToLoading: () => void
/** Mark session as complete */
markComplete: () => void
/** Pause session (* → paused) */
pause: () => void
/** Resume session (paused → resumePhase) */
resume: () => void
/** Is the session complete? */
isComplete: boolean
}
export function useInteractionPhase(
options: UseInteractionPhaseOptions = {}
): UseInteractionPhaseReturn {
const { initialProblem, activeProblem, onManualSubmitRequired } = options
// Initialize state with problem if provided (for SSR hydration)
const [phase, setPhase] = useState<InteractionPhase>(() => {
if (initialProblem) {
const attempt = createAttemptInput(
initialProblem.problem,
initialProblem.slotIndex,
initialProblem.partIndex
)
return { phase: 'inputting', attempt }
}
return { phase: 'loading' }
})
// ==========================================================================
// Derived State
// ==========================================================================
// Extract attempt from phase if available
const attempt = useMemo((): AttemptInput | null => {
switch (phase.phase) {
case 'inputting':
case 'awaitingDisambiguation':
case 'helpMode':
case 'submitting':
case 'showingFeedback':
return phase.attempt
case 'transitioning':
return phase.incoming
case 'paused': {
// Recurse into resumePhase
const inner = phase.resumePhase
if (
inner.phase === 'inputting' ||
inner.phase === 'awaitingDisambiguation' ||
inner.phase === 'helpMode' ||
inner.phase === 'submitting' ||
inner.phase === 'showingFeedback'
) {
return inner.attempt
}
if (inner.phase === 'transitioning') {
return inner.incoming
}
return null
}
default:
return null
}
}, [phase])
const prefixSums = useMemo(() => {
if (!attempt) return []
return computePrefixSums(attempt.problem.terms)
}, [attempt])
const prefixMatch = useMemo((): PrefixMatchResult => {
if (!attempt) return { matchedIndex: -1, isAmbiguous: false, helpTermIndex: -1 }
return findMatchedPrefixIndex(attempt.userAnswer, prefixSums)
}, [attempt, prefixSums])
// Convenience shorthand - most callers only need the index
const matchedPrefixIndex = prefixMatch.matchedIndex
// ==========================================================================
// Disambiguation Timer (managed via phase state)
// ==========================================================================
// Timer ref for the disambiguation timeout
const disambiguationTimerRef = useRef<NodeJS.Timeout | null>(null)
// Manage disambiguation timer based on phase
useEffect(() => {
// Clear any existing timer
if (disambiguationTimerRef.current) {
clearTimeout(disambiguationTimerRef.current)
disambiguationTimerRef.current = null
}
// Only run timer when in awaitingDisambiguation phase
if (phase.phase !== 'awaitingDisambiguation') return
const ctx = phase.disambiguationContext
const elapsed = Date.now() - ctx.timerStartedAt
if (elapsed >= AMBIGUOUS_HELP_DELAY_MS) {
// Timer already elapsed - transition to help mode immediately
// Keep userAnswer during transition so it shows in answer boxes while fading out
const helpContext = computeHelpContext(phase.attempt.problem.terms, ctx.helpTermIndex)
setPhase({
phase: 'helpMode',
attempt: { ...phase.attempt, userAnswer: '' },
helpContext,
})
} else {
// Set timer for remaining time
const remaining = AMBIGUOUS_HELP_DELAY_MS - elapsed
disambiguationTimerRef.current = setTimeout(() => {
setPhase((prev) => {
if (prev.phase !== 'awaitingDisambiguation') return prev
const helpContext = computeHelpContext(
prev.attempt.problem.terms,
prev.disambiguationContext.helpTermIndex
)
return {
phase: 'helpMode',
attempt: { ...prev.attempt, userAnswer: '' },
helpContext,
}
})
}, remaining)
}
return () => {
if (disambiguationTimerRef.current) {
clearTimeout(disambiguationTimerRef.current)
}
}
}, [phase])
// Derive which term to show "need help?" prompt for from the phase
// Returns -1 when not in awaitingDisambiguation phase
const ambiguousHelpTermIndex = useMemo(() => {
if (phase.phase !== 'awaitingDisambiguation') return -1
return phase.disambiguationContext.helpTermIndex
}, [phase])
const canSubmit = useMemo(() => {
if (!attempt || !attempt.userAnswer) return false
const answerNum = parseInt(attempt.userAnswer, 10)
return !Number.isNaN(answerNum)
}, [attempt])
const shouldAutoSubmit = useMemo(() => {
// Don't auto-submit in awaitingDisambiguation - the input might be a prefix sum
if (phase.phase !== 'inputting' && phase.phase !== 'helpMode') return false
if (!attempt || !attempt.userAnswer) return false
if (attempt.correctionCount > MANUAL_SUBMIT_THRESHOLD) return false
const answerNum = parseInt(attempt.userAnswer, 10)
if (Number.isNaN(answerNum)) return false
return answerNum === attempt.problem.answer
}, [phase.phase, attempt])
// UI predicates
const canAcceptInput =
phase.phase === 'inputting' ||
phase.phase === 'awaitingDisambiguation' ||
phase.phase === 'helpMode'
const showAsCompleted = phase.phase === 'showingFeedback'
const showHelpOverlay = phase.phase === 'helpMode'
const showInputArea =
phase.phase === 'inputting' ||
phase.phase === 'awaitingDisambiguation' ||
phase.phase === 'helpMode' ||
phase.phase === 'submitting'
const showFeedback = phase.phase === 'showingFeedback' && phase.result === 'incorrect'
const inputIsFocused =
phase.phase === 'inputting' ||
phase.phase === 'awaitingDisambiguation' ||
phase.phase === 'helpMode'
const isTransitioning = phase.phase === 'transitioning'
const isPaused = phase.phase === 'paused'
const isSubmitting = phase.phase === 'submitting'
// Extract helpContext from phase
const helpContext = useMemo((): HelpContext | null => {
if (phase.phase === 'helpMode') {
return phase.helpContext
}
// Also check paused phase
if (phase.phase === 'paused' && phase.resumePhase.phase === 'helpMode') {
return phase.resumePhase.helpContext
}
return null
}, [phase])
// Extract outgoingAttempt from phase (only during transitions)
const outgoingAttempt = useMemo((): OutgoingAttempt | null => {
if (phase.phase === 'transitioning') {
return phase.outgoing
}
return null
}, [phase])
// ==========================================================================
// Actions
// ==========================================================================
const loadProblem = useCallback(
(problem: GeneratedProblem, slotIndex: number, partIndex: number) => {
const newAttempt = createAttemptInput(problem, slotIndex, partIndex)
setPhase({ phase: 'inputting', attempt: newAttempt })
},
[]
)
// ==========================================================================
// React to activeProblem changes (single source of truth)
// ==========================================================================
// This effect handles two cases:
// 1. activeProblem.key changes (redo mode, direct navigation, session plan advances)
// 2. Phase becomes 'loading' (need to reload current problem after incorrect answer or part transition)
const prevActiveProblemKeyRef = useRef<string | null>(null)
const hasMountedRef = useRef(false)
useEffect(() => {
// Skip on initial mount - let initialProblem handle hydration
if (!hasMountedRef.current) {
hasMountedRef.current = true
// Initialize the ref with current key
prevActiveProblemKeyRef.current = activeProblem?.key ?? null
return
}
// If no active problem, nothing to do
if (!activeProblem) {
prevActiveProblemKeyRef.current = null
return
}
const prevKey = prevActiveProblemKeyRef.current
const currentKey = activeProblem.key
const keyChanged = prevKey !== currentKey
// Case 1: Phase is 'loading' - need to load the problem
// This happens after incorrect answers or when returning from part transitions
if (phase.phase === 'loading') {
const newAttempt = createAttemptInput(
activeProblem.problem,
activeProblem.slotIndex,
activeProblem.partIndex
)
setPhase({ phase: 'inputting', attempt: newAttempt })
prevActiveProblemKeyRef.current = currentKey
return
}
// Case 2: Key changed - handle redo mode or session advancement
if (keyChanged) {
// CRITICAL: Don't interrupt normal progression flow
// If we're in showingFeedback, submitting, or transitioning, the normal flow
// (startTransition → completeTransition) handles advancing to the next problem.
const isInProgressionFlow =
phase.phase === 'showingFeedback' ||
phase.phase === 'submitting' ||
phase.phase === 'transitioning'
if (isInProgressionFlow) {
// Still update the ref so we track the change
prevActiveProblemKeyRef.current = currentKey
return
}
// Key changed and we're not in progression flow - load the new problem immediately
const newAttempt = createAttemptInput(
activeProblem.problem,
activeProblem.slotIndex,
activeProblem.partIndex
)
setPhase({ phase: 'inputting', attempt: newAttempt })
prevActiveProblemKeyRef.current = currentKey
}
}, [activeProblem, phase.phase])
const handleDigit = useCallback(
(digit: string) => {
setPhase((prev) => {
// Accept input in inputting, awaitingDisambiguation, or helpMode
if (
prev.phase !== 'inputting' &&
prev.phase !== 'awaitingDisambiguation' &&
prev.phase !== 'helpMode'
) {
return prev
}
// If in help mode, exit help mode and start fresh with the new digit
// We reset to an empty answer and fall through to the normal digit processing
// so that ambiguity checks (awaitingDisambiguation) still apply
if (prev.phase === 'helpMode') {
prev = {
phase: 'inputting',
attempt: { ...prev.attempt, userAnswer: '', rejectedDigit: null },
}
}
const attempt = prev.attempt
const sums = computePrefixSums(attempt.problem.terms)
// Once manual submit is required, accept any digit without validation
if (attempt.manualSubmitRequired) {
const updatedAttempt = {
...attempt,
userAnswer: attempt.userAnswer + digit,
rejectedDigit: null,
}
return { phase: 'inputting', attempt: updatedAttempt }
}
if (isDigitConsistent(attempt.userAnswer, digit, sums)) {
const updatedAttempt = {
...attempt,
userAnswer: attempt.userAnswer + digit,
rejectedDigit: null,
}
// Check if the new answer creates an ambiguous prefix match
const newPrefixMatch = findMatchedPrefixIndex(updatedAttempt.userAnswer, sums)
if (newPrefixMatch.isAmbiguous && newPrefixMatch.helpTermIndex >= 0) {
// Ambiguous match - transition to awaitingDisambiguation
return {
phase: 'awaitingDisambiguation',
attempt: updatedAttempt,
disambiguationContext: {
matchedPrefixIndex: newPrefixMatch.matchedIndex,
helpTermIndex: newPrefixMatch.helpTermIndex,
timerStartedAt: Date.now(),
},
}
} else if (
!newPrefixMatch.isAmbiguous &&
newPrefixMatch.matchedIndex >= 0 &&
newPrefixMatch.helpTermIndex >= 0
) {
// Unambiguous intermediate prefix match (e.g., "03" for prefix sum 3)
// Immediately enter help mode
// Keep userAnswer during transition so it shows in answer boxes while fading out
const helpContext = computeHelpContext(
attempt.problem.terms,
newPrefixMatch.helpTermIndex
)
return {
phase: 'helpMode',
attempt: { ...updatedAttempt, userAnswer: '' },
helpContext,
}
} else {
// No special prefix match - stay in inputting (or return to it from awaitingDisambiguation)
return { phase: 'inputting', attempt: updatedAttempt }
}
} else {
// Reject the digit
const newCorrectionCount = attempt.correctionCount + 1
const nowRequiresManualSubmit =
newCorrectionCount > MANUAL_SUBMIT_THRESHOLD && !attempt.manualSubmitRequired
if (nowRequiresManualSubmit) {
setTimeout(() => onManualSubmitRequired?.(), 0)
}
const updatedAttempt = {
...attempt,
rejectedDigit: digit,
correctionCount: newCorrectionCount,
manualSubmitRequired: attempt.manualSubmitRequired || nowRequiresManualSubmit,
}
// Keep the same phase type but update attempt
if (prev.phase === 'awaitingDisambiguation') {
return { ...prev, attempt: updatedAttempt }
}
return { ...prev, attempt: updatedAttempt }
}
})
// Clear rejected digit after animation
setTimeout(() => {
setPhase((prev) => {
if (
prev.phase !== 'inputting' &&
prev.phase !== 'awaitingDisambiguation' &&
prev.phase !== 'helpMode'
) {
return prev
}
return { ...prev, attempt: { ...prev.attempt, rejectedDigit: null } }
})
}, 300)
},
[onManualSubmitRequired]
)
const handleBackspace = useCallback(() => {
setPhase((prev) => {
if (
prev.phase !== 'inputting' &&
prev.phase !== 'awaitingDisambiguation' &&
prev.phase !== 'helpMode'
) {
return prev
}
const attempt = prev.attempt
if (attempt.userAnswer.length === 0) return prev
const newCorrectionCount = attempt.correctionCount + 1
const nowRequiresManualSubmit =
newCorrectionCount > MANUAL_SUBMIT_THRESHOLD && !attempt.manualSubmitRequired
if (nowRequiresManualSubmit) {
setTimeout(() => onManualSubmitRequired?.(), 0)
}
const updatedAttempt = {
...attempt,
userAnswer: attempt.userAnswer.slice(0, -1),
correctionCount: newCorrectionCount,
manualSubmitRequired: attempt.manualSubmitRequired || nowRequiresManualSubmit,
}
// After backspace, always return to inputting phase (no longer ambiguous)
return { phase: 'inputting', attempt: updatedAttempt }
})
}, [onManualSubmitRequired])
const enterHelpMode = useCallback((termIndex: number) => {
setPhase((prev) => {
// Allow entering help mode from inputting, awaitingDisambiguation, or helpMode (to navigate to a different term)
if (
prev.phase !== 'inputting' &&
prev.phase !== 'awaitingDisambiguation' &&
prev.phase !== 'helpMode'
) {
return prev
}
// Keep userAnswer during transition so it shows in answer boxes while fading out
const helpContext = computeHelpContext(prev.attempt.problem.terms, termIndex)
return {
phase: 'helpMode',
attempt: { ...prev.attempt, userAnswer: '' },
helpContext,
}
})
}, [])
const exitHelpMode = useCallback(() => {
setPhase((prev) => {
if (prev.phase === 'helpMode') {
const updatedAttempt = { ...prev.attempt, userAnswer: '' }
return { phase: 'inputting', attempt: updatedAttempt }
}
if (prev.phase === 'inputting') {
const updatedAttempt = { ...prev.attempt, userAnswer: '' }
return { phase: 'inputting', attempt: updatedAttempt }
}
return prev
})
}, [])
const clearAnswer = useCallback(() => {
setPhase((prev) => {
if (prev.phase !== 'helpMode') return prev
const updatedAttempt = { ...prev.attempt, userAnswer: '' }
return {
phase: 'helpMode',
attempt: updatedAttempt,
helpContext: prev.helpContext,
}
})
}, [])
const setAnswer = useCallback((value: string) => {
setPhase((prev) => {
if (prev.phase !== 'helpMode' && prev.phase !== 'inputting') return prev
const updatedAttempt = { ...prev.attempt, userAnswer: value }
if (prev.phase === 'helpMode') {
return {
phase: 'helpMode',
attempt: updatedAttempt,
helpContext: prev.helpContext,
}
}
return { phase: 'inputting', attempt: updatedAttempt }
})
}, [])
const startSubmit = useCallback(() => {
setPhase((prev) => {
// Allow submitting from inputting, awaitingDisambiguation, or helpMode
if (
prev.phase !== 'inputting' &&
prev.phase !== 'awaitingDisambiguation' &&
prev.phase !== 'helpMode'
) {
return prev
}
return { phase: 'submitting', attempt: prev.attempt }
})
}, [])
const completeSubmit = useCallback((result: 'correct' | 'incorrect') => {
setPhase((prev) =>
transformActivePhase(prev, (active) => {
if (active.phase !== 'submitting') return null
return { phase: 'showingFeedback', attempt: active.attempt, result }
})
)
}, [])
const startTransition = useCallback(
(nextProblem: GeneratedProblem, nextSlotIndex: number, nextPartIndex?: number) => {
setPhase((prev) => {
if (prev.phase !== 'showingFeedback') return prev
const outgoing: OutgoingAttempt = {
key: `${prev.attempt.partIndex}-${prev.attempt.slotIndex}`,
problem: prev.attempt.problem,
userAnswer: prev.attempt.userAnswer,
result: prev.result,
}
const incomingPartIndex = nextPartIndex ?? prev.attempt.partIndex
const incoming = createAttemptInput(nextProblem, nextSlotIndex, incomingPartIndex)
return { phase: 'transitioning', outgoing, incoming }
})
},
[]
)
const completeTransition = useCallback(() => {
setPhase((prev) =>
transformActivePhase(prev, (active) => {
if (active.phase !== 'transitioning') return null
return { phase: 'inputting', attempt: active.incoming }
})
)
}, [])
const clearToLoading = useCallback(() => {
setPhase({ phase: 'loading' })
}, [])
const markComplete = useCallback(() => {
setPhase({ phase: 'complete' })
}, [])
const pause = useCallback(() => {
setPhase((prev) => {
if (prev.phase === 'paused' || prev.phase === 'loading' || prev.phase === 'complete')
return prev
return { phase: 'paused', resumePhase: prev, pauseStartedAt: Date.now() }
})
}, [])
const resume = useCallback(() => {
setPhase((prev) => {
if (prev.phase !== 'paused') return prev
// Calculate how long we were paused
const pauseDuration = Date.now() - prev.pauseStartedAt
// Helper to add pause duration to an attempt
const addPauseDuration = (attempt: AttemptInput): AttemptInput => ({
...attempt,
accumulatedPauseMs: attempt.accumulatedPauseMs + pauseDuration,
})
// Update the attempt inside the resume phase to track accumulated pause time
const resumePhase = prev.resumePhase
switch (resumePhase.phase) {
case 'inputting':
return {
...resumePhase,
attempt: addPauseDuration(resumePhase.attempt),
}
case 'awaitingDisambiguation':
return {
...resumePhase,
attempt: addPauseDuration(resumePhase.attempt),
}
case 'helpMode':
return {
...resumePhase,
attempt: addPauseDuration(resumePhase.attempt),
}
case 'submitting':
return {
...resumePhase,
attempt: addPauseDuration(resumePhase.attempt),
}
case 'showingFeedback':
return {
...resumePhase,
attempt: addPauseDuration(resumePhase.attempt),
}
case 'transitioning':
// Update both outgoing (for accuracy of recorded time) and incoming
return {
...resumePhase,
incoming: addPauseDuration(resumePhase.incoming),
}
case 'loading':
case 'complete':
// No attempt to update
return resumePhase
}
})
}, [])
// Is the session complete?
const isComplete = phase.phase === 'complete'
return {
phase,
attempt,
helpContext,
outgoingAttempt,
canAcceptInput,
showAsCompleted,
showHelpOverlay,
showInputArea,
showFeedback,
inputIsFocused,
isTransitioning,
isPaused,
isSubmitting,
prefixSums,
prefixMatch,
matchedPrefixIndex,
canSubmit,
shouldAutoSubmit,
ambiguousHelpTermIndex,
loadProblem,
handleDigit,
handleBackspace,
enterHelpMode,
exitHelpMode,
clearAnswer,
setAnswer,
startSubmit,
completeSubmit,
startTransition,
completeTransition,
clearToLoading,
markComplete,
pause,
resume,
isComplete,
}
}
|