logic-atlas 0.27.0 → 0.28.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 (235) hide show
  1. package/CITATION.cff +2 -2
  2. package/README.md +12 -3
  3. package/dist/case-preload.node.js +1 -1
  4. package/dist/case.js +2 -2
  5. package/dist/cases/{billy-suzy-early-preemption-CRfOz7Bt.js → billy-suzy-early-preemption-VMIzpY1n.js} +6 -6
  6. package/dist/cases/{billy-suzy-early-preemption-CRfOz7Bt.js.map → billy-suzy-early-preemption-VMIzpY1n.js.map} +1 -1
  7. package/dist/cases/{billy-suzy-overdetermination-B2ZuwqYR.js → billy-suzy-overdetermination-DoLzBeAz.js} +7 -7
  8. package/dist/cases/{billy-suzy-overdetermination-B2ZuwqYR.js.map → billy-suzy-overdetermination-DoLzBeAz.js.map} +1 -1
  9. package/dist/cases/{bodyguard-omission-BElbBkSw.js → bodyguard-omission-CN8QsSEB.js} +5 -5
  10. package/dist/cases/{bodyguard-omission-BElbBkSw.js.map → bodyguard-omission-CN8QsSEB.js.map} +1 -1
  11. package/dist/cases/{bogus-prevention-DuWQ6iVk.js → bogus-prevention-DiKPp-a5.js} +4 -4
  12. package/dist/cases/{bogus-prevention-DuWQ6iVk.js.map → bogus-prevention-DiKPp-a5.js.map} +1 -1
  13. package/dist/cases/{cable-cut-three-scenarios-Ddthb0un.js → cable-cut-three-scenarios-CW-zKG1G.js} +5 -5
  14. package/dist/cases/{cable-cut-three-scenarios-Ddthb0un.js.map → cable-cut-three-scenarios-CW-zKG1G.js.map} +1 -1
  15. package/dist/cases/{double-prevention-bomber-PvPhPQ2s.js → double-prevention-bomber-C7uLwNXo.js} +5 -5
  16. package/dist/cases/{double-prevention-bomber-PvPhPQ2s.js.map → double-prevention-bomber-C7uLwNXo.js.map} +1 -1
  17. package/dist/cases/{farmer-pesticide-barrel-doctor-cMLTNJp3.js → farmer-pesticide-barrel-doctor-CaU8E3En.js} +5 -5
  18. package/dist/cases/{farmer-pesticide-barrel-doctor-cMLTNJp3.js.map → farmer-pesticide-barrel-doctor-CaU8E3En.js.map} +1 -1
  19. package/dist/cases/{firing-squad-D4Yp8GZ8.js → firing-squad-CQ1d4kmG.js} +4 -4
  20. package/dist/cases/{firing-squad-D4Yp8GZ8.js.map → firing-squad-CQ1d4kmG.js.map} +1 -1
  21. package/dist/cases/{fishing-port-joss-paper-TbZhNtht.js → fishing-port-joss-paper-C8XEFRqd.js} +5 -5
  22. package/dist/cases/{fishing-port-joss-paper-TbZhNtht.js.map → fishing-port-joss-paper-C8XEFRqd.js.map} +1 -1
  23. package/dist/cases/{forest-fire-conjunctive-ulNESjJ5.js → forest-fire-conjunctive-ByJFxr3e.js} +5 -5
  24. package/dist/cases/{forest-fire-conjunctive-ulNESjJ5.js.map → forest-fire-conjunctive-ByJFxr3e.js.map} +1 -1
  25. package/dist/cases/{forest-fire-disjunctive-CGd1W8od.js → forest-fire-disjunctive-vKQTGAI5.js} +5 -5
  26. package/dist/cases/{forest-fire-disjunctive-CGd1W8od.js.map → forest-fire-disjunctive-vKQTGAI5.js.map} +1 -1
  27. package/dist/cases/{forgetful-drunk-gardener-cZvuR4Gu.js → forgetful-drunk-gardener-CSA-WgBo.js} +6 -6
  28. package/dist/cases/{forgetful-drunk-gardener-cZvuR4Gu.js.map → forgetful-drunk-gardener-CSA-WgBo.js.map} +1 -1
  29. package/dist/cases/{frankfurt-jones-black-BAriyrst.js → frankfurt-jones-black-DjMof3iS.js} +6 -6
  30. package/dist/cases/{frankfurt-jones-black-BAriyrst.js.map → frankfurt-jones-black-DjMof3iS.js.map} +1 -1
  31. package/dist/cases/{frankfurt-style-omission-fsoc-B9ml6z0U.js → frankfurt-style-omission-fsoc-BJ304WKN.js} +5 -5
  32. package/dist/cases/{frankfurt-style-omission-fsoc-B9ml6z0U.js.map → frankfurt-style-omission-fsoc-BJ304WKN.js.map} +1 -1
  33. package/dist/cases/{gardener-queen-D_G9qm3z.js → gardener-queen-ItlN_OGG.js} +5 -5
  34. package/dist/cases/{gardener-queen-D_G9qm3z.js.map → gardener-queen-ItlN_OGG.js.map} +1 -1
  35. package/dist/cases/{half-poison-twice-CF1ytMLh.js → half-poison-twice-CGCLQrmI.js} +4 -4
  36. package/dist/cases/{half-poison-twice-CF1ytMLh.js.map → half-poison-twice-CGCLQrmI.js.map} +1 -1
  37. package/dist/cases/{harassment-and-dress-CsAP591f.js → harassment-and-dress-Yk0Jbv30.js} +3 -3
  38. package/dist/cases/{harassment-and-dress-CsAP591f.js.map → harassment-and-dress-Yk0Jbv30.js.map} +1 -1
  39. package/dist/cases/{hit-and-abandon-9_rV57bi.js → hit-and-abandon-Z-Hz1vkC.js} +7 -7
  40. package/dist/cases/{hit-and-abandon-9_rV57bi.js.map → hit-and-abandon-Z-Hz1vkC.js.map} +1 -1
  41. package/dist/cases/{india-famine-D2Nrut-V.js → india-famine-rJzNppu5.js} +5 -5
  42. package/dist/cases/{india-famine-D2Nrut-V.js.map → india-famine-rJzNppu5.js.map} +1 -1
  43. package/dist/cases/{intern-doctor-pharmacist-Dc1snaQa.js → intern-doctor-pharmacist-RTjMrdU4.js} +5 -5
  44. package/dist/cases/{intern-doctor-pharmacist-Dc1snaQa.js.map → intern-doctor-pharmacist-RTjMrdU4.js.map} +1 -1
  45. package/dist/cases/{murder-lesion-yTnWn4To.js → murder-lesion-B7NjxE9w.js} +9 -9
  46. package/dist/cases/{murder-lesion-yTnWn4To.js.map → murder-lesion-B7NjxE9w.js.map} +1 -1
  47. package/dist/cases/{newcomb-Cl1gd6uf.js → newcomb-NY0Rx28u.js} +5 -5
  48. package/dist/cases/{newcomb-Cl1gd6uf.js.map → newcomb-NY0Rx28u.js.map} +1 -1
  49. package/dist/cases/{palsgraf-NfvM1K9U.js → palsgraf-_7Z1FMjh.js} +4 -4
  50. package/dist/cases/{palsgraf-NfvM1K9U.js.map → palsgraf-_7Z1FMjh.js.map} +1 -1
  51. package/dist/cases/{pen-case-both-permitted-BNqPBJct.js → pen-case-both-permitted-CoIRwdKp.js} +3 -3
  52. package/dist/cases/{pen-case-both-permitted-BNqPBJct.js.map → pen-case-both-permitted-CoIRwdKp.js.map} +1 -1
  53. package/dist/cases/{pen-case-professor-assistant-CVQnSN5y.js → pen-case-professor-assistant-Ctee0F13.js} +3 -3
  54. package/dist/cases/{pen-case-professor-assistant-CVQnSN5y.js.map → pen-case-professor-assistant-Ctee0F13.js.map} +1 -1
  55. package/dist/cases/{pen-fiasco-funding-loss-DgGrOlqy.js → pen-fiasco-funding-loss-CLkFPBlt.js} +5 -5
  56. package/dist/cases/{pen-fiasco-funding-loss-DgGrOlqy.js.map → pen-fiasco-funding-loss-CLkFPBlt.js.map} +1 -1
  57. package/dist/cases/{penned-in-sharks-BlHMXii-.js → penned-in-sharks-D8TKXF4a.js} +4 -4
  58. package/dist/cases/{penned-in-sharks-BlHMXii-.js.map → penned-in-sharks-D8TKXF4a.js.map} +1 -1
  59. package/dist/cases/{planted-sharks-D6mI-GlJ.js → planted-sharks-B8xKu9ND.js} +3 -3
  60. package/dist/cases/{planted-sharks-D6mI-GlJ.js.map → planted-sharks-B8xKu9ND.js.map} +1 -1
  61. package/dist/cases/{prince-of-wales-pancakes-DLaLe7aZ.js → prince-of-wales-pancakes-BCdorj3d.js} +5 -5
  62. package/dist/cases/{prince-of-wales-pancakes-DLaLe7aZ.js.map → prince-of-wales-pancakes-BCdorj3d.js.map} +1 -1
  63. package/dist/cases/{psychopath-button-C0zEz5cq.js → psychopath-button-BHCfQc-X.js} +5 -5
  64. package/dist/cases/{psychopath-button-C0zEz5cq.js.map → psychopath-button-BHCfQc-X.js.map} +1 -1
  65. package/dist/cases/{red-light-collision-DLwpoJpK.js → red-light-collision-BUXK1_UY.js} +12 -12
  66. package/dist/cases/{red-light-collision-DLwpoJpK.js.map → red-light-collision-BUXK1_UY.js.map} +1 -1
  67. package/dist/cases/{rental-car-double-omission-ClAcUXpU.js → rental-car-double-omission-CHEQ_rIR.js} +9 -9
  68. package/dist/cases/{rental-car-double-omission-ClAcUXpU.js.map → rental-car-double-omission-CHEQ_rIR.js.map} +1 -1
  69. package/dist/cases/{rock-throwing-b9OWOyAi.js → rock-throwing-DsQv5Kpy.js} +3 -3
  70. package/dist/cases/{rock-throwing-b9OWOyAi.js.map → rock-throwing-DsQv5Kpy.js.map} +1 -1
  71. package/dist/cases/{school-lunch-poisoning-BphWQpQm.js → school-lunch-poisoning-DFas2ts3.js} +4 -4
  72. package/dist/cases/{school-lunch-poisoning-BphWQpQm.js.map → school-lunch-poisoning-DFas2ts3.js.map} +1 -1
  73. package/dist/cases/{sharks-Cwd6PSFD.js → sharks-CtuoEhjg.js} +5 -5
  74. package/dist/cases/{sharks-Cwd6PSFD.js.map → sharks-CtuoEhjg.js.map} +1 -1
  75. package/dist/cases/{smoking-lesion-DTJJDKMu.js → smoking-lesion-DZUES09g.js} +4 -4
  76. package/dist/cases/{smoking-lesion-DTJJDKMu.js.map → smoking-lesion-DZUES09g.js.map} +1 -1
  77. package/dist/cases/{snakebite-doctor-entGsPZe.js → snakebite-doctor-Cg5_kKNT.js} +4 -4
  78. package/dist/cases/{snakebite-doctor-entGsPZe.js.map → snakebite-doctor-Cg5_kKNT.js.map} +1 -1
  79. package/dist/cases/{styrofoam-fire-B86b_qDD.js → styrofoam-fire-DAwmSPQG.js} +4 -4
  80. package/dist/cases/{styrofoam-fire-B86b_qDD.js.map → styrofoam-fire-DAwmSPQG.js.map} +1 -1
  81. package/dist/cases/{summers-v-tice-7qnTEtJs.js → summers-v-tice-CwytFrog.js} +4 -4
  82. package/dist/cases/{summers-v-tice-7qnTEtJs.js.map → summers-v-tice-CwytFrog.js.map} +1 -1
  83. package/dist/cases/{taroko-derailment-2021-FgwyGqHj.js → taroko-derailment-2021-DM81_snE.js} +5 -5
  84. package/dist/cases/{taroko-derailment-2021-FgwyGqHj.js.map → taroko-derailment-2021-DM81_snE.js.map} +1 -1
  85. package/dist/cases/{train-switching-DolPBKWM.js → train-switching-CkdcZaFU.js} +5 -5
  86. package/dist/cases/{train-switching-DolPBKWM.js.map → train-switching-CkdcZaFU.js.map} +1 -1
  87. package/dist/cases/{trumping-merlin-morgana-u2OmSCY2.js → trumping-merlin-morgana-CDdsbYUt.js} +5 -5
  88. package/dist/cases/{trumping-merlin-morgana-u2OmSCY2.js.map → trumping-merlin-morgana-CDdsbYUt.js.map} +1 -1
  89. package/dist/cases/{voting-11-voters-NQUw6ak4.js → voting-11-voters-CbyuCjdx.js} +4 -4
  90. package/dist/cases/{voting-11-voters-NQUw6ak4.js.map → voting-11-voters-CbyuCjdx.js.map} +1 -1
  91. package/dist/cases/{xi-antidote-Ciuul3cR.js → xi-antidote-Dl9SHP_s.js} +5 -5
  92. package/dist/cases/{xi-antidote-Ciuul3cR.js.map → xi-antidote-Dl9SHP_s.js.map} +1 -1
  93. package/dist/cases/{yard-vs-pitch-dodge-BQVdnACx.js → yard-vs-pitch-dodge-WH2MpQ9z.js} +7 -7
  94. package/dist/cases/{yard-vs-pitch-dodge-BQVdnACx.js.map → yard-vs-pitch-dodge-WH2MpQ9z.js.map} +1 -1
  95. package/dist/chunks/{CasePage-D9w8opn_.js → CasePage-DEwqO60i.js} +11 -11
  96. package/dist/chunks/{CasePage-D9w8opn_.js.map → CasePage-DEwqO60i.js.map} +1 -1
  97. package/dist/chunks/{CausalPlayground-DAItu6zY.js → CausalPlayground-DdQzYdty.js} +13 -13
  98. package/dist/chunks/{CausalPlayground-DAItu6zY.js.map → CausalPlayground-DdQzYdty.js.map} +1 -1
  99. package/dist/chunks/{CiteBlock-CxIS70aQ.js → CiteBlock-Dyoxi5xH.js} +4 -4
  100. package/dist/chunks/{CiteBlock-CxIS70aQ.js.map → CiteBlock-Dyoxi5xH.js.map} +1 -1
  101. package/dist/chunks/{ConservativeExtension-Cofe92ak.js → ConservativeExtension-DfWICJpA.js} +7 -7
  102. package/dist/chunks/{ConservativeExtension-Cofe92ak.js.map → ConservativeExtension-DfWICJpA.js.map} +1 -1
  103. package/dist/chunks/{ExpectedUtility-DtgptRz5.js → ExpectedUtility-CQpxO_12.js} +2 -2
  104. package/dist/chunks/{ExpectedUtility-DtgptRz5.js.map → ExpectedUtility-CQpxO_12.js.map} +1 -1
  105. package/dist/chunks/{ExportMenu-Bku7BhiT.js → ExportMenu-BfJpW1GU.js} +6 -6
  106. package/dist/chunks/{ExportMenu-Bku7BhiT.js.map → ExportMenu-BfJpW1GU.js.map} +1 -1
  107. package/dist/chunks/{FigureTabs-Dl3RgQQa.js → FigureTabs-BeRdG4gw.js} +4 -4
  108. package/dist/chunks/{FigureTabs-Dl3RgQQa.js.map → FigureTabs-BeRdG4gw.js.map} +1 -1
  109. package/dist/chunks/{GraphBox-K7ziPIVx.js → GraphBox-BrZcffUQ.js} +8 -8
  110. package/dist/chunks/{GraphBox-K7ziPIVx.js.map → GraphBox-BrZcffUQ.js.map} +1 -1
  111. package/dist/chunks/{IdentifyPanel-DNFM0h2W.js → IdentifyPanel-BJuWlA_m.js} +8 -8
  112. package/dist/chunks/{IdentifyPanel-DNFM0h2W.js.map → IdentifyPanel-BJuWlA_m.js.map} +1 -1
  113. package/dist/chunks/{ModelEditor-DskhGLjq.js → ModelEditor-GIpyJVnY.js} +9 -9
  114. package/dist/chunks/{ModelEditor-DskhGLjq.js.map → ModelEditor-GIpyJVnY.js.map} +1 -1
  115. package/dist/chunks/{ProbabilityPanel-7YIOtAmh.js → ProbabilityPanel-CEwVYKlE.js} +11 -11
  116. package/dist/chunks/{ProbabilityPanel-7YIOtAmh.js.map → ProbabilityPanel-CEwVYKlE.js.map} +1 -1
  117. package/dist/chunks/{RulesPanel-BXh_JKrO.js → RulesPanel-728s_fj5.js} +7 -7
  118. package/dist/chunks/{RulesPanel-BXh_JKrO.js.map → RulesPanel-728s_fj5.js.map} +1 -1
  119. package/dist/chunks/{SignalGraph-CWPf_sG8.js → SignalGraph-lk-qJzvX.js} +4 -4
  120. package/dist/chunks/{SignalGraph-CWPf_sG8.js.map → SignalGraph-lk-qJzvX.js.map} +1 -1
  121. package/dist/chunks/{SliderList-DmDURTeF.js → SliderList-BBGoo3ht.js} +5 -5
  122. package/dist/chunks/{SliderList-DmDURTeF.js.map → SliderList-BBGoo3ht.js.map} +1 -1
  123. package/dist/chunks/{Story-BaEwzLZ9.js → Story-wOKV92ch.js} +3 -3
  124. package/dist/chunks/{Story-BaEwzLZ9.js.map → Story-wOKV92ch.js.map} +1 -1
  125. package/dist/chunks/{Supplement-DPsflADp.js → Supplement-PjboAohM.js} +3 -3
  126. package/dist/chunks/{Supplement-DPsflADp.js.map → Supplement-PjboAohM.js.map} +1 -1
  127. package/dist/chunks/{WorldLanes-C6xXmN-Y.js → WorldLanes-D6igoh5O.js} +7 -7
  128. package/dist/chunks/{WorldLanes-C6xXmN-Y.js.map → WorldLanes-D6igoh5O.js.map} +1 -1
  129. package/dist/chunks/cases-BKdIGCvu.js +96 -0
  130. package/dist/chunks/{cases-dHdtbyLY.js.map → cases-BKdIGCvu.js.map} +1 -1
  131. package/dist/chunks/{cases-of-DpCMbUyl.js → cases-of-RC69Nnop.js} +2 -2
  132. package/dist/chunks/{cases-of-DpCMbUyl.js.map → cases-of-RC69Nnop.js.map} +1 -1
  133. package/dist/chunks/{cite-qX7YWepK.js → cite-pzfVBLCy.js} +3 -3
  134. package/dist/chunks/{cite-qX7YWepK.js.map → cite-pzfVBLCy.js.map} +1 -1
  135. package/dist/chunks/{doc-case-YauWsu0F.js → doc-case-MXrxY2zP.js} +3 -3
  136. package/dist/chunks/{doc-case-YauWsu0F.js.map → doc-case-MXrxY2zP.js.map} +1 -1
  137. package/dist/chunks/{export-image-DRX4_diW.js → export-image-C5hq83bR.js} +5 -5
  138. package/dist/chunks/{export-image-DRX4_diW.js.map → export-image-C5hq83bR.js.map} +1 -1
  139. package/dist/chunks/{messages-ZiFmPfDY.js → messages-CesXO6XJ.js} +45 -45
  140. package/dist/chunks/messages-CesXO6XJ.js.map +1 -0
  141. package/dist/chunks/{model-doc-NQlyTjL9.js → model-doc-beFVLMDG.js} +46 -46
  142. package/dist/chunks/{model-doc-NQlyTjL9.js.map → model-doc-beFVLMDG.js.map} +1 -1
  143. package/dist/chunks/{parts-8cUsl2jJ.js → parts-DzneR5ak.js} +2 -2
  144. package/dist/chunks/{parts-8cUsl2jJ.js.map → parts-DzneR5ak.js.map} +1 -1
  145. package/dist/chunks/{url-state-DWdnkiC2.js → url-state-C4DxGvUy.js} +3 -3
  146. package/dist/chunks/{url-state-DWdnkiC2.js.map → url-state-C4DxGvUy.js.map} +1 -1
  147. package/dist/chunks/{use-node-menu-DJISBUAm.js → use-node-menu-aBrt_arL.js} +4 -4
  148. package/dist/chunks/{use-node-menu-DJISBUAm.js.map → use-node-menu-aBrt_arL.js.map} +1 -1
  149. package/dist/cite.js +1 -1
  150. package/dist/data.js +2 -2
  151. package/dist/editor.js +1 -1
  152. package/dist/extension.js +2 -2
  153. package/dist/ground-cases.js +1 -779
  154. package/dist/ground-cases.js.map +1 -1
  155. package/dist/ground-chunks/download-graph-2ohIYT24.js +2 -0
  156. package/dist/ground-chunks/download-graph-2ohIYT24.js.map +1 -0
  157. package/dist/ground-chunks/identity-element-C-XNXkKl.js +2 -0
  158. package/dist/ground-chunks/identity-element-C-XNXkKl.js.map +1 -0
  159. package/dist/ground-chunks/messages-DJDddmqv.js +2 -0
  160. package/dist/ground-chunks/messages-DJDddmqv.js.map +1 -0
  161. package/dist/ground-chunks/root-C202UeBo.js +2 -0
  162. package/dist/ground-chunks/root-C202UeBo.js.map +1 -0
  163. package/dist/ground-pairing-cases.js +2 -0
  164. package/dist/ground-pairing-cases.js.map +1 -0
  165. package/dist/ground-pairing.js +2 -0
  166. package/dist/ground-pairing.js.map +1 -0
  167. package/dist/ground-spacetime-cases.js +2 -0
  168. package/dist/ground-spacetime-cases.js.map +1 -0
  169. package/dist/ground-spacetime.js +2 -0
  170. package/dist/ground-spacetime.js.map +1 -0
  171. package/dist/ground-structure-cases.js +788 -0
  172. package/dist/ground-structure-cases.js.map +1 -0
  173. package/dist/ground-structure.css +2 -0
  174. package/dist/ground-structure.js +1390 -0
  175. package/dist/ground-structure.js.map +1 -0
  176. package/dist/ground.css +1 -1
  177. package/dist/ground.js +1 -4007
  178. package/dist/ground.js.map +1 -1
  179. package/dist/i18n.js +1 -1
  180. package/dist/identify.js +2 -2
  181. package/dist/index.js +11 -11
  182. package/dist/lanes.js +2 -2
  183. package/dist/modal.js.map +1 -1
  184. package/dist/playground.js +2 -2
  185. package/dist/probability.js +2 -2
  186. package/dist/supplement.js +1 -1
  187. package/dist/types/ground/cases/extensions/identity-element.d.ts +160 -0
  188. package/dist/types/ground/cases/index.d.ts +159 -0
  189. package/dist/types/ground/components/CorrespondenceView.d.ts +7 -0
  190. package/dist/types/ground/components/IdentityHypotheses.d.ts +8 -0
  191. package/dist/types/ground/components/ParticleArrangements.d.ts +7 -0
  192. package/dist/types/ground/components/ProposalTable.d.ts +7 -0
  193. package/dist/types/ground/components/parts.d.ts +1 -14
  194. package/dist/types/ground/components/root.d.ts +20 -0
  195. package/dist/types/ground/data/finite-figures.d.ts +21 -0
  196. package/dist/types/ground/data/schema.d.ts +11 -4
  197. package/dist/types/ground/engine/classifications.d.ts +20 -0
  198. package/dist/types/ground/engine/correspondence.d.ts +3 -0
  199. package/dist/types/ground/engine/errors.d.ts +4 -0
  200. package/dist/types/ground/engine/finite-problems.d.ts +45 -0
  201. package/dist/types/ground/engine/particle-orbits.d.ts +5 -0
  202. package/dist/types/ground/engine/proposals.d.ts +7 -4
  203. package/dist/types/ground/i18n/pairing.d.ts +99 -0
  204. package/dist/types/ground/i18n/spacetime.d.ts +12 -0
  205. package/dist/types/ground/i18n/zh.d.ts +4 -1
  206. package/dist/types/ground/pairing/cases/index.d.ts +4 -0
  207. package/dist/types/ground/pairing/index.d.ts +9 -0
  208. package/dist/types/ground/spacetime/LightConeView.d.ts +7 -0
  209. package/dist/types/ground/spacetime/cases/index.d.ts +107 -0
  210. package/dist/types/ground/spacetime/index.d.ts +5 -0
  211. package/dist/types/ground/spacetime/interval.d.ts +12 -0
  212. package/dist/types/ground/spacetime/model.d.ts +25 -0
  213. package/dist/types/ground/structure/cases/index.d.ts +7 -0
  214. package/dist/types/ground/structure/components/GroundStructureView.d.ts +15 -0
  215. package/dist/types/ground/structure/components/ParthoodView.d.ts +17 -0
  216. package/dist/types/ground/structure/components/frame.d.ts +48 -0
  217. package/dist/types/ground/structure/components/grounding-layout.d.ts +67 -0
  218. package/dist/types/ground/structure/components/hasse-layout.d.ts +43 -0
  219. package/dist/types/ground/structure/components/layered-layout.d.ts +31 -0
  220. package/dist/types/ground/structure/components/use-structure-doc.d.ts +15 -0
  221. package/dist/types/ground/structure/data/load.d.ts +39 -0
  222. package/dist/types/ground/structure/data/problems.d.ts +58 -0
  223. package/dist/types/ground/structure/data/schema.d.ts +240 -0
  224. package/dist/types/ground/structure/engine/grounding.d.ts +61 -0
  225. package/dist/types/ground/structure/engine/parthood.d.ts +46 -0
  226. package/dist/types/ground/structure/i18n/en.d.ts +3 -0
  227. package/dist/types/ground/structure/i18n/messages.d.ts +8 -0
  228. package/dist/types/ground/structure/i18n/zh.d.ts +64 -0
  229. package/dist/types/ground/structure/index.d.ts +19 -0
  230. package/dist/types/logic/relations.d.ts +35 -0
  231. package/package.json +28 -3
  232. package/dist/chunks/cases-dHdtbyLY.js +0 -96
  233. package/dist/chunks/messages-ZiFmPfDY.js.map +0 -1
  234. /package/dist/{ground-chunks → ground-structure-chunks}/download-graph-GJWXyNLP.js +0 -0
  235. /package/dist/{ground-chunks → ground-structure-chunks}/download-graph-GJWXyNLP.js.map +0 -0
package/dist/modal.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"modal.js","names":["pos","list","set","KINDS","_Fragment","LINE","GAP","MARGIN","KINDS","KINDS","KINDS","_Fragment","KINDS","KINDS","_Fragment","_Fragment","katex","Fragment$1","zhTW","texHtml","tex","Tex","text","modalProblem","where","at","p","MODAL_PROBLEMS_EN","message","modalProblemText","wording","ModalError","modalProblemOf","error","ModalEvaluator","model","options","w","world","succ","system","byWorld","f","cached","value","outer","antecedentWorlds","v","a","sphere","s","selected","failures","b","accessible","children","deciding","c","step","set","holds","intension","ev","truthSet","explain","MODERN_TEXT","MODERN_LATEX","NOTATIONS","LEVEL","bracket","child","parent","side","atomText","id","atomLatex","head","rest","base","write","go","g","atom","sym","inner","open","close","l","r","left","right","formulaText","notation","formulaLatex","printFormula","formulaKey","operatorSymbol","op","ATOM_PATTERN","RESERVED","SYMBOLS","tokenize","tokens","i","source","ch","word","symbol","kind","cp","OP_TEXT","Parser","extra","kinds","next","t","parseFormula","isAtomId","atomsOf","out","walk","isTruthFunctional","F","MAX_ENGINE_WORLDS","checkWorlds","worlds","seen","known","accessFromPairs","pairs","list","x","y","accessPairs","frame","kripkeModel","input","atoms","valuation","frameOf","checkSystem","spheres","centering","sphereModel","access","ordered","collapseSpheres","weightOf","distances","here","center","laws","similarity","there","mismatches","violations","law","d","similaritySpheres","ds","own","withSimilaritySpheres","valueIn","values","equationOrder","equations","order","state","visit","path","literalsOf","add","surgery","intervention","solved","background","worldWith","modalTextSchema","z","worldId","pos$1","atomSchema","worldSchema","frameWorldSchema","layoutSchema","common","kripkeDocSchema","frameDocSchema","lawSchema","spheresDocSchema","modalDocSchema","MAX_DOC_WORLDS","zhIssue","schemaProblems","zh","issue","attempt","parseInto","problems","truthFunctional","checkModalDoc","doc","knownWorld","k","checkSpheres","systems","before","structuralEquations","parseModalJson","raw","parsed","frameOfDoc","similarityOf","weights","modelOfDoc","startWorld","modalText","locale","DEFAULT_LOCALE","LANGUAGE_NAMES","LocaleContext","createContext","LocaleProvider","createElement","LocaleScope","useLocale","useContext","list$1","xs","set$1","MODAL_EN","EN_PROBLEMS","n","arg","name","trueAt","ws","names","bad","aFalse","pattern","title","vals","pos","MODAL_MESSAGES","useModalMessages","modalProblemMessage","modalErrorMessage","worldNames","namesOf","ids","boxLines","not","lines","trueHere","showFalse","docGraphInput","explanationText","marksFor","marks","valueOrUndefined","ModalRoot","RootBox","caption","ModalProblems","FormulaMath","formula","TruthMark","UnknownMark","AtomLegend","counterfactualView","semantics","problem","sphereWorlds","worldSetLatex","useModalDoc","useMemo","result","parseAll","sources","unknownAtomProblem","formulas","IntensionTable","props","IntensionBody","KINDS$6","loaded","IntensionLoaded","setWorld","useState","row","setRow","picked","textBox","x0","anchor","width","size","rectBox","h","segmentHitsBox","t0","t1","dx","dy","q","box","around","cx","half","cy","intersects","pad","firstClear","candidates","obstacles","o","textWidth","code","digitSubscript","match","unit","arrowHead","len","ux","uy","bx","tip","by","LINE$1","ATOM_SIZE","NAME_SIZE","GAP$1","MARGIN$1","boxSize","widest","centres","wide","sizes","tall","stepX","stepY","depth","start","queue","last","column","col","mates","border","gap","fmt","edgeGeometry","top","x1","x2","ox","offset","oy","ca","cb","heads","both","nameCandidates","make","layoutWorldGraph","boxes","byId","has","edges","segments","loops","from","to","reverse","free","label","all","y0","y1","UNDERSCORE_IDENT","IDENT_TOKEN","SUB_DY","subscriptParts","m","explicit","parts","sub","Fragment","LINE","PAD","WorldGraph","key","e","onSelect","layout","active","mark","worldLabel","line","KripkeView","KripkeBody","KINDS$5","KripkeLoaded","focus","setFocus","setShowFalse","setExtra","draft","setDraft","setValuation","setPairs","mergeSymmetric","focused","explanation","FormulaValue","editable","EditTables","ps","onAtom","onPair","Segmented","className","onChange","OkIcon","NoIcon","HOLDS","fails","witness","relates","checkRelation","property","axiom","AXIOMS","CONDITION_AXIOM","FRAME_CONDITIONS","checkCondition","condition","MAX_ASSIGNMENTS","compileFrame","index","maskOf","validOnFrame","count","subsets","masks","SYSTEM_CONDITIONS","SYSTEMS","systemsOf","met","FrameConditions","FrameBody","KINDS$4","FrameLoaded","conditions","rows","axioms","Verdict","ok","jsx","StrictImplication","StrictBody","KINDS$3","missing","StrictLoaded","material","strict","materialValue","strictValue","TCS_PATTERNS","negate","tcsInference","third","checkInferenceAt","premises","inference","conclusion","checkInference","DOT","NAME","DETAIL","GAP","MARGIN","layoutSpheres","r0","radii","ringOf","placed","push","fresh","sphereLabels","SphereDiagram","sphereName","TcsCheck","TcsBody","initial","collapsed","setCollapsed","items","TcsCard","item","KINDS$2","heading","TcsColumns","flat","shown","cf","showStrict","InferenceColumn","verdict","SphereView","SphereBody","KINDS$1","SphereLoaded","setSemantics","semanticsSwitch","SurgeryVsSimilarity","SurgeryBody","KINDS","firstConditional","fallback","SurgeryLoaded","setWeights","costs","setCosts","docWithCosts","view","solvedWorld","surgeryValue","Weights","old","useId","Slider","onWeight","onCost"],"sources":["../src/components/text/tex-html.ts","../src/components/text/Tex.tsx","../src/modal/engine/errors.ts","../src/modal/engine/evaluate.ts","../src/modal/engine/print.ts","../src/modal/engine/formula.ts","../src/modal/engine/model.ts","../src/modal/engine/similarity.ts","../src/modal/engine/surgery.ts","../src/modal/data/schema.ts","../src/modal/data/load.ts","../src/components/i18n/messages.ts","../src/modal/i18n/en.ts","../src/modal/i18n/zh.ts","../src/modal/i18n/messages.ts","../src/modal/components/doc-graph.ts","../src/modal/components/explain-text.ts","../src/modal/components/parts.tsx","../src/modal/components/sphere-view-model.ts","../src/modal/components/use-doc.ts","../src/modal/components/IntensionTable.tsx","../src/components/graph/graph-labels.ts","../src/components/text/text-measure.ts","../src/engine/identifier-format.ts","../src/components/graph/signal-shapes.ts","../src/modal/components/world-graph.ts","../src/components/text/subscript.ts","../src/components/text/svg-text.tsx","../src/modal/components/WorldGraph.tsx","../src/modal/components/KripkeView.tsx","../src/components/shared/parts.tsx","../src/logic/relations.ts","../src/modal/engine/frames.ts","../src/modal/components/FrameConditions.tsx","../src/modal/components/StrictImplication.tsx","../src/modal/engine/inference.ts","../src/modal/components/sphere-graph.ts","../src/modal/components/SphereDiagram.tsx","../src/modal/components/TcsCheck.tsx","../src/modal/components/SphereView.tsx","../src/modal/components/SurgeryVsSimilarity.tsx"],"sourcesContent":["import katex from 'katex'\n\n/** LaTeX to KaTeX HTML. Server-safe; a bad input comes back as `katex-error` markup rather than throwing. */\nexport function texHtml(tex: string): string {\n return katex.renderToString(tex, { throwOnError: false, output: 'html', strict: 'ignore', trust: false })\n}\n\n","import { texHtml } from './tex-html.ts'\n\nexport interface TexProps {\n readonly tex: string\n /** The plain-text form, read by screen readers and kept as `data-text` for copying. */\n readonly text: string\n}\n\n/** One typeset formula. Needs the KaTeX stylesheet (see the README). */\nexport function Tex({ tex, text }: TexProps) {\n return <span className=\"ca-tex\" role=\"math\" aria-label={text} data-text={text} data-tex={tex} dangerouslySetInnerHTML={{ __html: texHtml(tex) }} />\n}\n","/**\n * Every error the modal engine and its data layer raise has a stable code and its parameters, so an\n * interface can word it in its own language. `Error.message` is the English wording below.\n */\n\n/** Parameters per problem code. */\nexport interface ModalProblemParams {\n // formula syntax; positions are 0-based character offsets into `source`\n readonly 'parse-unexpected-character': { readonly source: string; readonly position: number; readonly character: string }\n readonly 'parse-unexpected-token': { readonly source: string; readonly position: number; readonly token: string }\n readonly 'parse-unexpected-end': { readonly source: string; readonly position: number }\n readonly 'parse-expected': { readonly source: string; readonly position: number; readonly expected: string }\n /** `>` beside `⊃` or `≡`, or `≡` chained, without brackets. */\n readonly 'ambiguous-mix': { readonly source: string; readonly position: number; readonly operators: string }\n readonly 'reserved-atom': { readonly atom: string }\n // models\n readonly 'unknown-atom': { readonly atom: string }\n readonly 'unknown-world': { readonly world: string }\n readonly 'duplicate-world': { readonly world: string }\n readonly 'duplicate-atom': { readonly atom: string }\n readonly 'no-worlds': Record<string, never>\n readonly 'too-many-worlds': { readonly count: number; readonly limit: number }\n readonly 'missing-position': { readonly world: string }\n readonly 'no-sphere-system': { readonly world: string }\n /** Sphere `index` (1-based, innermost is 1) does not contain the sphere inside it. */\n readonly 'spheres-not-nested': { readonly world: string; readonly index: number }\n readonly 'empty-sphere': { readonly world: string; readonly index: number }\n /** Strong: the innermost sphere is not exactly {world}; weak: world is not in it. */\n readonly centering: { readonly world: string; readonly centering: 'strong' | 'weak' }\n readonly 'spheres-source': Record<string, never>\n // evaluation\n /** Stalnaker's selection is undefined: the closest antecedent worlds are several. */\n readonly 'not-unique': { readonly world: string; readonly candidates: readonly string[] }\n readonly 'too-many-assignments': { readonly count: number; readonly limit: number }\n // structural equations\n readonly 'cyclic-equations': { readonly cycle: readonly string[] }\n readonly 'not-truth-functional': { readonly formula: string }\n readonly 'surgery-antecedent': { readonly formula: string }\n /** The surgery figure's document lacks its centre, similarity or structural equations. */\n readonly 'needs-similarity': Record<string, never>\n // documents\n readonly 'not-json': { readonly detail: string }\n readonly 'too-large': Record<string, never>\n /** A component given a document of a kind it does not draw. */\n readonly 'wrong-kind': { readonly kind: string; readonly expected: readonly string[] }\n /** Any other schema complaint, already worded per locale. */\n readonly schema: { readonly message: { readonly 'zh-TW': string; readonly en: string } }\n}\n\nexport type ModalProblemCode = keyof ModalProblemParams\n\n/** One problem: its code, parameters and, when known, where it sits (a path into the document, e.g. `formulas.1`). */\nexport type ModalProblem = {\n readonly [K in ModalProblemCode]: { readonly code: K; readonly params: ModalProblemParams[K]; readonly where?: string }\n}[ModalProblemCode]\n\nexport function modalProblem<K extends ModalProblemCode>(code: K, params: ModalProblemParams[K], where?: string): ModalProblem {\n return (where === undefined ? { code, params } : { code, params, where }) as ModalProblem\n}\n\n/** Wording per code; the interface supplies one per locale. */\nexport interface ModalProblemWording {\n readonly messages: { readonly [K in ModalProblemCode]: (params: ModalProblemParams[K]) => string }\n /** Joins a `where` path and the message. */\n readonly join: (where: string, message: string) => string\n}\n\nconst at = (p: { readonly source: string; readonly position: number }): string => ` at position ${p.position + 1} of ${JSON.stringify(p.source)}`\n\nexport const MODAL_PROBLEMS_EN: ModalProblemWording = {\n join: (where, message) => `${where}: ${message}`,\n messages: {\n 'parse-unexpected-character': (p) => `unexpected character ${p.character}${at(p)}`,\n 'parse-unexpected-token': (p) => `unexpected ${p.token}${at(p)}`,\n 'parse-unexpected-end': (p) => `the formula ends too early${at(p)}`,\n 'parse-expected': (p) => `expected ${p.expected}${at(p)}`,\n 'ambiguous-mix': (p) => `add brackets: ${p.operators} cannot stand side by side unbracketed${at(p)}`,\n 'reserved-atom': (p) => `${p.atom} is a reserved word, not an atom`,\n 'unknown-atom': (p) => `no atom ${p.atom}`,\n 'unknown-world': (p) => `no world ${p.world}`,\n 'duplicate-world': (p) => `world ${p.world} is listed twice`,\n 'duplicate-atom': (p) => `atom ${p.atom} is listed twice`,\n 'no-worlds': () => 'the model has no worlds',\n 'too-many-worlds': (p) => `${p.count} worlds; the limit is ${p.limit}`,\n 'missing-position': (p) => `world ${p.world} has no position, which the manual layout needs`,\n 'no-sphere-system': (p) => `world ${p.world} has no system of spheres`,\n 'spheres-not-nested': (p) => `sphere ${p.index} around ${p.world} does not contain the sphere inside it`,\n 'empty-sphere': (p) => `sphere ${p.index} around ${p.world} is empty`,\n centering: (p) =>\n p.centering === 'strong' ? `the innermost sphere around ${p.world} must be exactly {${p.world}}` : `the innermost sphere around ${p.world} must contain ${p.world}`,\n 'spheres-source': () => 'give exactly one of: center with spheres, center with similarity, or systems',\n 'not-unique': (p) => `Stalnaker's selection is undefined at ${p.world}: the closest antecedent worlds are ${p.candidates.join(', ')}`,\n 'too-many-assignments': (p) => `${p.count} assignments to enumerate; the limit is ${p.limit}`,\n 'cyclic-equations': (p) => `the equations form a cycle: ${p.cycle.join(' → ')}`,\n 'not-truth-functional': (p) => `${p.formula} must be truth-functional (no □, ◇ or >)`,\n 'surgery-antecedent': (p) => `${p.formula} is not a conjunction of atoms and negated atoms, which surgery needs`,\n 'needs-similarity': () => 'this figure needs a spheres document with center, similarity and structural equations',\n 'not-json': (p) => `not JSON: ${p.detail}`,\n 'too-large': () => 'the document is too large',\n 'wrong-kind': (p) => `this figure needs a ${p.expected.join(' or ')} document, not ${p.kind}`,\n schema: (p) => p.message.en,\n },\n}\n\n/** The problem worded by `wording` (English by default). */\nexport function modalProblemText(p: ModalProblem, wording: ModalProblemWording = MODAL_PROBLEMS_EN): string {\n const message = (wording.messages[p.code] as (params: unknown) => string)(p.params)\n return p.where === undefined ? message : wording.join(p.where, message)\n}\n\n/** An error carrying a {@link ModalProblem}; its message is the English wording. */\nexport class ModalError extends Error {\n readonly problem: ModalProblem\n\n constructor(p: ModalProblem) {\n super(modalProblemText(p))\n this.name = 'ModalError'\n this.problem = p\n }\n}\n\n/** The problem behind `error`, when it is one of ours. */\nexport function modalProblemOf(error: unknown): ModalProblem | undefined {\n return error instanceof ModalError ? error.problem : undefined\n}\n","import { ModalError, modalProblem } from './errors.ts'\nimport type { Formula } from './formula.ts'\nimport type { ModalModel } from './model.ts'\n\n/**\n * Truth at a world, by Garson's truth conditions (Modal Logic for Philosophers, 2nd ed., pp. 59–66),\n * and the counterfactual `>` on systems of spheres (pp. 455–459):\n *\n * - a_w(□A) = T iff a_v(A) = T for every v with wRv; a_w(◇A) = T iff a_v(A) = T for some such v.\n * - Lewis: A > B is true at w iff no sphere around w holds an A-world (vacuously), or the smallest\n * sphere S that does has every A-world in it a B-world. Finite systems always have that smallest\n * sphere, so the limit assumption holds.\n * - Stalnaker: the same, but S ∩ |A| must be one world; when it is several, the selection is\n * undefined and the engine reports `not-unique` with the candidates instead of choosing.\n */\n\nexport type ConditionalSemantics = 'lewis' | 'stalnaker'\n\nexport interface EvalOptions {\n /** How `>` is read; default `lewis`. */\n readonly semantics?: ConditionalSemantics\n}\n\n/** How a counterfactual A > B came out at one world. */\nexport interface CounterfactualStep {\n /** The A-worlds any sphere around the world reaches, in world order. */\n readonly antecedentWorlds: readonly string[]\n /** Index (0 = innermost) of the smallest sphere holding an A-world; undefined when none does. */\n readonly sphere: number | undefined\n /** The selection f(|A|, w) = S ∩ |A|: the closest A-worlds. Empty when vacuous. */\n readonly selected: readonly string[]\n /** The selected worlds where B is false. */\n readonly failures: readonly string[]\n /** No sphere holds an A-world, so A > B is true vacuously. */\n readonly vacuous: boolean\n readonly value: boolean\n}\n\n/** Why a formula has its value at a world: the values of its parts, and the worlds that decide modal steps. */\nexport interface Explanation {\n readonly formula: Formula\n readonly world: string\n readonly value: boolean\n /** The parts' explanations: for □ and ◇ the argument at every accessible world; for > the consequent at every selected world. */\n readonly children: readonly Explanation[]\n /** □ and ◇: the worlds this world can see. */\n readonly accessible?: readonly string[]\n /** □ false: an accessible world where the argument is false; ◇ true: one where it is true. */\n readonly witness?: string\n readonly counterfactual?: CounterfactualStep\n}\n\n/** Evaluates formulas on one model, remembering each (formula, world) value. */\nexport class ModalEvaluator {\n private readonly memo = new Map<Formula, Map<string, boolean>>()\n private readonly atomSets: ReadonlyMap<string, ReadonlySet<string>>\n readonly semantics: ConditionalSemantics\n readonly model: ModalModel\n\n constructor(model: ModalModel, options: EvalOptions = {}) {\n this.model = model\n this.semantics = options.semantics ?? 'lewis'\n this.atomSets = new Map(model.worlds.map((w) => [w, new Set(model.valuation[w] ?? [])]))\n }\n\n /** The worlds `world` can see; throws when R is not defined there. */\n accessible(world: string): readonly string[] {\n this.known(world)\n const succ = this.model.access[world]\n if (succ === undefined) throw new ModalError(modalProblem('no-sphere-system', { world }))\n return succ\n }\n\n /** The spheres around `world`, innermost first; throws when it has none. */\n spheres(world: string): readonly (readonly string[])[] {\n this.known(world)\n const system = this.model.spheres?.[world]\n if (system === undefined) throw new ModalError(modalProblem('no-sphere-system', { world }))\n return system\n }\n\n holds(f: Formula, world: string): boolean {\n let byWorld = this.memo.get(f)\n if (byWorld === undefined) {\n byWorld = new Map()\n this.memo.set(f, byWorld)\n }\n const cached = byWorld.get(world)\n if (cached !== undefined) return cached\n const value = this.compute(f, world)\n byWorld.set(world, value)\n return value\n }\n\n /** The worlds where `f` is true, in world order: |f|. */\n truthSet(f: Formula): string[] {\n return this.model.worlds.filter((w) => this.holds(f, w))\n }\n\n counterfactual(a: Formula, b: Formula, world: string): CounterfactualStep {\n const system = this.spheres(world)\n const outer = system[system.length - 1] as readonly string[]\n const antecedentWorlds = this.model.worlds.filter((v) => outer.includes(v) && this.holds(a, v))\n const sphere = system.findIndex((s) => s.some((v) => antecedentWorlds.includes(v)))\n if (sphere < 0) return { antecedentWorlds, sphere: undefined, selected: [], failures: [], vacuous: true, value: true }\n const s = system[sphere] as readonly string[]\n const selected = antecedentWorlds.filter((v) => s.includes(v))\n if (this.semantics === 'stalnaker' && selected.length > 1) {\n throw new ModalError(modalProblem('not-unique', { world, candidates: selected }))\n }\n const failures = selected.filter((v) => !this.holds(b, v))\n return { antecedentWorlds, sphere, selected, failures, vacuous: false, value: failures.length === 0 }\n }\n\n explain(f: Formula, world: string): Explanation {\n const value = this.holds(f, world)\n switch (f.kind) {\n case 'atom':\n case 'top':\n case 'bot':\n return { formula: f, world, value, children: [] }\n case 'not':\n return { formula: f, world, value, children: [this.explain(f.arg, world)] }\n case 'box':\n case 'dia': {\n const accessible = this.accessible(world)\n const children = accessible.map((v) => this.explain(f.arg, v))\n const deciding = f.kind === 'box' ? (value ? undefined : children.find((c) => !c.value)) : value ? children.find((c) => c.value) : undefined\n return deciding === undefined ? { formula: f, world, value, children, accessible } : { formula: f, world, value, children, accessible, witness: deciding.world }\n }\n case 'cf': {\n const step = this.counterfactual(f.left, f.right, world)\n return { formula: f, world, value, children: step.selected.map((v) => this.explain(f.right, v)), counterfactual: step }\n }\n default:\n return { formula: f, world, value, children: [this.explain(f.left, world), this.explain(f.right, world)] }\n }\n }\n\n private known(world: string): void {\n if (!this.atomSets.has(world)) throw new ModalError(modalProblem('unknown-world', { world }))\n }\n\n private compute(f: Formula, world: string): boolean {\n switch (f.kind) {\n case 'atom': {\n const set = this.atomSets.get(world)\n if (set === undefined) throw new ModalError(modalProblem('unknown-world', { world }))\n if (!this.model.atoms.includes(f.id)) throw new ModalError(modalProblem('unknown-atom', { atom: f.id }))\n return set.has(f.id)\n }\n case 'top':\n return true\n case 'bot':\n return false\n case 'not':\n return !this.holds(f.arg, world)\n case 'and':\n return this.holds(f.left, world) && this.holds(f.right, world)\n case 'or':\n return this.holds(f.left, world) || this.holds(f.right, world)\n case 'imp':\n return !this.holds(f.left, world) || this.holds(f.right, world)\n case 'iff':\n return this.holds(f.left, world) === this.holds(f.right, world)\n case 'box':\n return this.accessible(world).every((v) => this.holds(f.arg, v))\n case 'dia':\n return this.accessible(world).some((v) => this.holds(f.arg, v))\n case 'cf':\n return this.counterfactual(f.left, f.right, world).value\n }\n }\n}\n\n/** a_w(f): whether `f` is true at `world`. */\nexport function holds(model: ModalModel, f: Formula, world: string, options?: EvalOptions): boolean {\n return new ModalEvaluator(model, options).holds(f, world)\n}\n\n/** The intension of `f`: each world with the truth value `f` has there. */\nexport function intension(model: ModalModel, f: Formula, options?: EvalOptions): Record<string, boolean> {\n const ev = new ModalEvaluator(model, options)\n return Object.fromEntries(model.worlds.map((w) => [w, ev.holds(f, w)]))\n}\n\n/** |f|: the worlds where `f` is true. */\nexport function truthSet(model: ModalModel, f: Formula, options?: EvalOptions): string[] {\n return new ModalEvaluator(model, options).truthSet(f)\n}\n\n/** The value of `f` at `world` with its explanation tree. */\nexport function explain(model: ModalModel, f: Formula, world: string, options?: EvalOptions): Explanation {\n return new ModalEvaluator(model, options).explain(f, world)\n}\n","import type { BinaryKind, Formula, UnaryKind } from './formula.ts'\n\n/**\n * Formulas written out for display: plain text and LaTeX, in one of the notation sets. Brackets are\n * the fewest that parse back to the same tree, except that a conditional inside a conditional keeps\n * them (□(p ⊃ q) ⊃ (□p ⊃ □q)). `ascii` writes the authoring syntax.\n */\n\n/** `modern`: ¬ ∧ ∨ ⊃ ≡ □ ◇ > (the default); `garson`: Garson's ~ and &; `ascii`: the authoring syntax. */\nexport type ModalNotation = 'modern' | 'garson' | 'ascii'\n\ntype Op = UnaryKind | BinaryKind | 'top' | 'bot'\n\ninterface Symbols {\n readonly text: Readonly<Record<Op, string>>\n readonly latex: Readonly<Record<Op, string>>\n}\n\nconst MODERN_TEXT: Readonly<Record<Op, string>> = { not: '¬', box: '□', dia: '◇', and: '∧', or: '∨', imp: '⊃', iff: '≡', cf: '>', top: '⊤', bot: '⊥' }\nconst MODERN_LATEX: Readonly<Record<Op, string>> = {\n not: '\\\\neg ',\n box: '\\\\Box ',\n dia: '\\\\Diamond ',\n and: '\\\\land',\n or: '\\\\lor',\n imp: '\\\\supset',\n iff: '\\\\equiv',\n cf: '>',\n top: '\\\\top',\n bot: '\\\\bot',\n}\n\nexport const NOTATIONS: Readonly<Record<ModalNotation, Symbols>> = {\n modern: { text: MODERN_TEXT, latex: MODERN_LATEX },\n garson: {\n text: { ...MODERN_TEXT, not: '~', and: '&' },\n latex: { ...MODERN_LATEX, not: '{\\\\sim}', and: '\\\\mathbin{\\\\&}' },\n },\n ascii: {\n text: { not: '~', box: '[]', dia: '<>', and: '&', or: '|', imp: '->', iff: '<->', cf: '>', top: 'true', bot: 'false' },\n latex: MODERN_LATEX,\n },\n}\n\n/** Binding strength: higher binds tighter. */\nconst LEVEL: Readonly<Record<Formula['kind'], number>> = { atom: 5, top: 5, bot: 5, not: 5, box: 5, dia: 5, and: 4, or: 3, cf: 2, imp: 1, iff: 1 }\n\n/** Whether `child` needs brackets as the `side` operand of a `parent` binary node. */\nfunction bracket(parent: BinaryKind, child: Formula, side: 'left' | 'right'): boolean {\n const c = LEVEL[child.kind]\n const p = LEVEL[parent]\n if (c > p) {\n // Unbracketed `>` may not stand beside ⊃ or ≡.\n return child.kind === 'cf' && (parent === 'imp' || parent === 'iff')\n }\n if (c < p) return true\n // Same level: ∧ and ∨ chain to the left unbracketed; nested conditionals keep their brackets on either side, as textbooks write them.\n if (parent === 'and' || parent === 'or') return side === 'right'\n return true\n}\n\nfunction atomText(id: string): string {\n return id\n}\n\n/** `rain` → \\mathit{rain}; `p_1` → p_{1}; `p` → p. */\nfunction atomLatex(id: string): string {\n const [head = id, ...rest] = id.split('_')\n const base = head.length > 1 ? `\\\\mathit{${head}}` : head\n return rest.length === 0 ? base : `${base}_{${rest.join('\\\\_')}}`\n}\n\nfunction write(f: Formula, sym: Readonly<Record<Op, string>>, atom: (id: string) => string, open: string, close: string): string {\n const go = (g: Formula): string => {\n switch (g.kind) {\n case 'atom':\n return atom(g.id)\n case 'top':\n case 'bot':\n return sym[g.kind]\n case 'not':\n case 'box':\n case 'dia': {\n const inner = go(g.arg)\n return LEVEL[g.arg.kind] < 5 ? `${sym[g.kind]}${open}${inner}${close}` : `${sym[g.kind]}${inner}`\n }\n default: {\n const l = go(g.left)\n const r = go(g.right)\n const left = bracket(g.kind, g.left, 'left') ? `${open}${l}${close}` : l\n const right = bracket(g.kind, g.right, 'right') ? `${open}${r}${close}` : r\n return `${left} ${sym[g.kind]} ${right}`\n }\n }\n }\n return go(f)\n}\n\n/** The formula as plain text. */\nexport function formulaText(f: Formula, notation: ModalNotation = 'modern'): string {\n return write(f, NOTATIONS[notation].text, atomText, '(', ')')\n}\n\n/** The formula as LaTeX. */\nexport function formulaLatex(f: Formula, notation: ModalNotation = 'modern'): string {\n return write(f, NOTATIONS[notation].latex, atomLatex, '(', ')')\n}\n\n/** Both forms at once. */\nexport function printFormula(f: Formula, notation: ModalNotation = 'modern'): { readonly text: string; readonly latex: string } {\n return { text: formulaText(f, notation), latex: formulaLatex(f, notation) }\n}\n\n/** A canonical key: the ASCII text, equal for equal trees. */\nexport function formulaKey(f: Formula): string {\n return formulaText(f, 'ascii')\n}\n\n/** An operator's symbol in a notation, for legends and headings. */\nexport function operatorSymbol(op: Op, notation: ModalNotation = 'modern'): { readonly text: string; readonly latex: string } {\n return { text: NOTATIONS[notation].text[op], latex: NOTATIONS[notation].latex[op] }\n}\n","import { ModalError, modalProblem } from './errors.ts'\n\n/**\n * Propositional modal formulas: their syntax tree and the parser for the authoring syntax, which takes\n * ASCII and Unicode alike (`~p`, `¬p`; `p & q`, `p ∧ q`; `p | q`, `p ∨ q`; `p -> q`, `p ⊃ q`;\n * `p <-> q`, `p ≡ q`; `[]p`, `□p`; `<>p`, `◇p`; `p > q`, `p □→ q`; `true`, `⊤`; `false`, `⊥`).\n *\n * Binding, tightest first: the unary operators (¬ □ ◇), then ∧, ∨, the counterfactual >, and last ⊃\n * and ≡. ∧ and ∨ group to the left, ⊃ and > to the right. `>` beside `⊃` or `≡`, and `≡` beside `⊃`\n * or another `≡`, need brackets: the parser reports `ambiguous-mix` rather than guess.\n */\n\nexport type BinaryKind = 'and' | 'or' | 'imp' | 'iff' | 'cf'\nexport type UnaryKind = 'not' | 'box' | 'dia'\n\nexport type Formula =\n | { readonly kind: 'atom'; readonly id: string }\n | { readonly kind: 'top' }\n | { readonly kind: 'bot' }\n | { readonly kind: UnaryKind; readonly arg: Formula }\n | { readonly kind: BinaryKind; readonly left: Formula; readonly right: Formula }\n\n/** An atom: a lowercase letter, then letters, digits or underscores. */\nexport const ATOM_PATTERN = /^[a-z][A-Za-z0-9_]*$/\n\nconst RESERVED = new Set(['true', 'false'])\n\ntype TokenKind = 'atom' | 'top' | 'bot' | UnaryKind | BinaryKind | '(' | ')'\n\ninterface Token {\n readonly kind: TokenKind\n readonly text: string\n readonly position: number\n}\n\n/** Symbols longest first, so `<->` wins over `<>` and `□→` over `□`. */\nconst SYMBOLS: readonly (readonly [string, TokenKind])[] = [\n ['<->', 'iff'],\n ['->', 'imp'],\n ['<>', 'dia'],\n ['[]', 'box'],\n ['□→', 'cf'],\n ['~', 'not'],\n ['¬', 'not'],\n ['&', 'and'],\n ['∧', 'and'],\n ['|', 'or'],\n ['∨', 'or'],\n ['⊃', 'imp'],\n ['→', 'imp'],\n ['≡', 'iff'],\n ['↔', 'iff'],\n ['□', 'box'],\n ['◻', 'box'],\n ['◇', 'dia'],\n ['◊', 'dia'],\n ['>', 'cf'],\n ['⊤', 'top'],\n ['⊥', 'bot'],\n ['(', '('],\n [')', ')'],\n]\n\nfunction tokenize(source: string): Token[] {\n const tokens: Token[] = []\n let i = 0\n outer: while (i < source.length) {\n const ch = source[i] as string\n if (/\\s/.test(ch)) {\n i += 1\n continue\n }\n const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i))\n if (word !== null) {\n const text = word[0]\n if (text === 'true') tokens.push({ kind: 'top', text, position: i })\n else if (text === 'false') tokens.push({ kind: 'bot', text, position: i })\n else if (ATOM_PATTERN.test(text)) tokens.push({ kind: 'atom', text, position: i })\n else throw new ModalError(modalProblem('parse-unexpected-character', { source, position: i, character: text[0] as string }))\n i += text.length\n continue\n }\n for (const [symbol, kind] of SYMBOLS) {\n if (source.startsWith(symbol, i)) {\n tokens.push({ kind, text: symbol, position: i })\n i += symbol.length\n continue outer\n }\n }\n const cp = String.fromCodePoint(source.codePointAt(i) as number)\n throw new ModalError(modalProblem('parse-unexpected-character', { source, position: i, character: cp }))\n }\n return tokens\n}\n\n/** The text of each operator kind in the ambiguity message. */\nconst OP_TEXT: Readonly<Record<BinaryKind, string>> = { and: '∧', or: '∨', imp: '⊃', iff: '≡', cf: '>' }\n\nclass Parser {\n private i = 0\n /** Nodes written inside brackets: they may stand beside any operator. */\n private readonly bracketed = new WeakSet<Formula>()\n private readonly source: string\n private readonly tokens: readonly Token[]\n\n constructor(source: string, tokens: readonly Token[]) {\n this.source = source\n this.tokens = tokens\n }\n\n parse(): Formula {\n if (this.tokens.length === 0) throw new ModalError(modalProblem('parse-unexpected-end', { source: this.source, position: 0 }))\n const f = this.implication()\n const extra = this.tokens[this.i]\n if (extra !== undefined) {\n throw new ModalError(modalProblem('parse-unexpected-token', { source: this.source, position: extra.position, token: extra.text }))\n }\n return f\n }\n\n private peek(): Token | undefined {\n return this.tokens[this.i]\n }\n\n private end(): number {\n return this.source.length\n }\n\n /** A bare (unbracketed) binary node of one of `kinds`. */\n private bare(f: Formula, kinds: readonly BinaryKind[]): boolean {\n return (kinds as readonly string[]).includes(f.kind) && !this.bracketed.has(f)\n }\n\n private ambiguous(position: number, a: BinaryKind, b: BinaryKind): never {\n throw new ModalError(modalProblem('ambiguous-mix', { source: this.source, position, operators: `${OP_TEXT[a]} ${OP_TEXT[b]}` }))\n }\n\n /** ⊃ (right-grouping) and ≡ (no grouping): the loosest level. */\n private implication(): Formula {\n const left = this.counterfactual()\n const op = this.peek()\n if (op === undefined || (op.kind !== 'imp' && op.kind !== 'iff')) return left\n this.i += 1\n if (this.bare(left, ['cf'])) this.ambiguous(op.position, 'cf', op.kind)\n const right = op.kind === 'imp' ? this.implication() : this.counterfactual()\n if (this.bare(right, ['cf'])) this.ambiguous(op.position, op.kind, 'cf')\n if (op.kind === 'imp' && this.bare(right, ['iff'])) this.ambiguous(op.position, 'imp', 'iff')\n const next = this.peek()\n if (op.kind === 'iff' && next !== undefined && (next.kind === 'iff' || next.kind === 'imp')) this.ambiguous(next.position, 'iff', next.kind)\n return { kind: op.kind, left, right }\n }\n\n /** > (right-grouping). */\n private counterfactual(): Formula {\n const left = this.disjunction()\n const op = this.peek()\n if (op === undefined || op.kind !== 'cf') return left\n this.i += 1\n const right = this.counterfactual()\n return { kind: 'cf', left, right }\n }\n\n private disjunction(): Formula {\n let f = this.conjunction()\n while (this.peek()?.kind === 'or') {\n this.i += 1\n f = { kind: 'or', left: f, right: this.conjunction() }\n }\n return f\n }\n\n private conjunction(): Formula {\n let f = this.unary()\n while (this.peek()?.kind === 'and') {\n this.i += 1\n f = { kind: 'and', left: f, right: this.unary() }\n }\n return f\n }\n\n private unary(): Formula {\n const t = this.peek()\n if (t !== undefined && (t.kind === 'not' || t.kind === 'box' || t.kind === 'dia')) {\n this.i += 1\n return { kind: t.kind, arg: this.unary() }\n }\n return this.primary()\n }\n\n private primary(): Formula {\n const t = this.peek()\n if (t === undefined) throw new ModalError(modalProblem('parse-unexpected-end', { source: this.source, position: this.end() }))\n this.i += 1\n switch (t.kind) {\n case 'atom':\n return { kind: 'atom', id: t.text }\n case 'top':\n return { kind: 'top' }\n case 'bot':\n return { kind: 'bot' }\n case '(': {\n const inner = this.implication()\n const close = this.peek()\n if (close === undefined) throw new ModalError(modalProblem('parse-expected', { source: this.source, position: this.end(), expected: ')' }))\n if (close.kind !== ')') throw new ModalError(modalProblem('parse-expected', { source: this.source, position: close.position, expected: ')' }))\n this.i += 1\n this.bracketed.add(inner)\n return inner\n }\n default:\n throw new ModalError(modalProblem('parse-unexpected-token', { source: this.source, position: t.position, token: t.text }))\n }\n }\n}\n\n/** Parse a formula; throws {@link ModalError} with the position of the first problem. */\nexport function parseFormula(source: string): Formula {\n return new Parser(source, tokenize(source)).parse()\n}\n\n/** Whether `id` can name an atom. */\nexport function isAtomId(id: string): boolean {\n return ATOM_PATTERN.test(id) && !RESERVED.has(id)\n}\n\n/** The atoms of `f`, in order of first appearance. */\nexport function atomsOf(f: Formula): string[] {\n const out: string[] = []\n const walk = (g: Formula): void => {\n switch (g.kind) {\n case 'atom':\n if (!out.includes(g.id)) out.push(g.id)\n return\n case 'top':\n case 'bot':\n return\n case 'not':\n case 'box':\n case 'dia':\n walk(g.arg)\n return\n default:\n walk(g.left)\n walk(g.right)\n }\n }\n walk(f)\n return out\n}\n\n/** Whether `f` uses no □, ◇ or >. */\nexport function isTruthFunctional(f: Formula): boolean {\n switch (f.kind) {\n case 'atom':\n case 'top':\n case 'bot':\n return true\n case 'box':\n case 'dia':\n case 'cf':\n return false\n case 'not':\n return isTruthFunctional(f.arg)\n default:\n return isTruthFunctional(f.left) && isTruthFunctional(f.right)\n }\n}\n\n/** Formulas built in code, for the axiom schemas and inference patterns. */\nexport const F = {\n atom: (id: string): Formula => ({ kind: 'atom', id }),\n not: (arg: Formula): Formula => ({ kind: 'not', arg }),\n box: (arg: Formula): Formula => ({ kind: 'box', arg }),\n dia: (arg: Formula): Formula => ({ kind: 'dia', arg }),\n and: (left: Formula, right: Formula): Formula => ({ kind: 'and', left, right }),\n or: (left: Formula, right: Formula): Formula => ({ kind: 'or', left, right }),\n imp: (left: Formula, right: Formula): Formula => ({ kind: 'imp', left, right }),\n cf: (left: Formula, right: Formula): Formula => ({ kind: 'cf', left, right }),\n /** Strict implication: □(a ⊃ b). */\n strict: (left: Formula, right: Formula): Formula => ({ kind: 'box', arg: { kind: 'imp', left, right } }),\n}\n","import { ModalError, modalProblem } from './errors.ts'\n\n/**\n * A finite model ⟨W, R, a⟩ restricted to atoms: worlds, the atoms true at each, each world's\n * R-successors and, for conditionals, each world's system of spheres (innermost first). A world\n * with no `access` entry has no R defined there; one with no `spheres` entry has no system.\n */\nexport interface ModalModel {\n readonly worlds: readonly string[]\n readonly atoms: readonly string[]\n /** World → the atoms true there; every other atom is false there. */\n readonly valuation: Readonly<Record<string, readonly string[]>>\n /** World → the worlds it can see. */\n readonly access: Readonly<Record<string, readonly string[]>>\n /** World → its spheres, innermost first, each containing the one before. */\n readonly spheres?: Readonly<Record<string, readonly (readonly string[])[]>>\n}\n\n/** A frame ⟨W, R⟩: a model with no atoms. */\nexport interface Frame {\n readonly worlds: readonly string[]\n readonly access: Readonly<Record<string, readonly string[]>>\n}\n\n/** The engine's own limit, so a set of worlds fits a 30-bit mask. Documents allow fewer (see the schema). */\nexport const MAX_ENGINE_WORLDS = 30\n\nfunction checkWorlds(worlds: readonly string[]): void {\n if (worlds.length === 0) throw new ModalError(modalProblem('no-worlds', {}))\n if (worlds.length > MAX_ENGINE_WORLDS) throw new ModalError(modalProblem('too-many-worlds', { count: worlds.length, limit: MAX_ENGINE_WORLDS }))\n const seen = new Set<string>()\n for (const w of worlds) {\n if (seen.has(w)) throw new ModalError(modalProblem('duplicate-world', { world: w }))\n seen.add(w)\n }\n}\n\nfunction known(worlds: ReadonlySet<string>, w: string): void {\n if (!worlds.has(w)) throw new ModalError(modalProblem('unknown-world', { world: w }))\n}\n\n/** Successor lists from pairs, every world listed (with no successors when it has none). */\nexport function accessFromPairs(worlds: readonly string[], pairs: readonly (readonly [string, string])[]): Record<string, string[]> {\n const set = new Set(worlds)\n const out: Record<string, string[]> = Object.fromEntries(worlds.map((w) => [w, [] as string[]]))\n for (const [a, b] of pairs) {\n known(set, a)\n known(set, b)\n const list = out[a] as string[]\n if (!list.includes(b)) list.push(b)\n }\n for (const w of worlds) (out[w] as string[]).sort((x, y) => worlds.indexOf(x) - worlds.indexOf(y))\n return out\n}\n\n/** R as pairs, in world order. */\nexport function accessPairs(frame: Frame): [string, string][] {\n return frame.worlds.flatMap((w) => (frame.access[w] ?? []).map((v) => [w, v] as [string, string]))\n}\n\n/** A Kripke model from worlds with their true atoms and R as pairs. */\nexport function kripkeModel(input: {\n readonly atoms: readonly string[]\n readonly worlds: readonly { readonly id: string; readonly true?: readonly string[] }[]\n readonly access: readonly (readonly [string, string])[]\n}): ModalModel {\n const worlds = input.worlds.map((w) => w.id)\n checkWorlds(worlds)\n const atoms = new Set(input.atoms)\n const valuation: Record<string, string[]> = {}\n for (const w of input.worlds) {\n for (const a of w.true ?? []) if (!atoms.has(a)) throw new ModalError(modalProblem('unknown-atom', { atom: a }))\n valuation[w.id] = [...(w.true ?? [])]\n }\n return { worlds, atoms: [...input.atoms], valuation, access: accessFromPairs(worlds, input.access) }\n}\n\n/** A frame from world ids and R as pairs. */\nexport function frameOf(worlds: readonly string[], pairs: readonly (readonly [string, string])[]): Frame {\n checkWorlds(worlds)\n return { worlds: [...worlds], access: accessFromPairs(worlds, pairs) }\n}\n\n/**\n * Check one system of spheres around `world`: known worlds, none empty, each containing the one\n * before, and centred (`strong`: the innermost is exactly {world}; `weak`: it contains world).\n */\nexport function checkSystem(worlds: readonly string[], world: string, spheres: readonly (readonly string[])[], centering: 'strong' | 'weak'): void {\n const set = new Set(worlds)\n known(set, world)\n if (spheres.length === 0) throw new ModalError(modalProblem('empty-sphere', { world, index: 1 }))\n spheres.forEach((s, i) => {\n if (s.length === 0) throw new ModalError(modalProblem('empty-sphere', { world, index: i + 1 }))\n for (const v of s) known(set, v)\n if (i > 0 && !(spheres[i - 1] as readonly string[]).every((v) => s.includes(v))) {\n throw new ModalError(modalProblem('spheres-not-nested', { world, index: i + 1 }))\n }\n })\n const inner = spheres[0] as readonly string[]\n const centred = centering === 'strong' ? inner.length === 1 && inner[0] === world : inner.includes(world)\n if (!centred) throw new ModalError(modalProblem('centering', { world, centering }))\n}\n\n/**\n * A model for conditionals: worlds with their true atoms and a system of spheres per world (a world\n * may have none). R at a world with a system is its outermost sphere, so □ ranges over every world\n * the spheres reach and strict implication is the one-sphere case of `>`.\n */\nexport function sphereModel(input: {\n readonly atoms: readonly string[]\n readonly worlds: readonly { readonly id: string; readonly true?: readonly string[] }[]\n readonly systems: Readonly<Record<string, readonly (readonly string[])[]>>\n readonly centering?: 'strong' | 'weak'\n}): ModalModel {\n const base = kripkeModel({ atoms: input.atoms, worlds: input.worlds, access: [] })\n const spheres: Record<string, string[][]> = {}\n const access: Record<string, string[]> = {}\n for (const [w, system] of Object.entries(input.systems)) {\n checkSystem(base.worlds, w, system, input.centering ?? 'strong')\n const ordered = system.map((s) => base.worlds.filter((v) => s.includes(v)))\n spheres[w] = ordered\n access[w] = ordered[ordered.length - 1] as string[]\n }\n return { ...base, access, spheres }\n}\n\n/** The same model with every system pressed into one sphere, its outermost: `>` then reads as strict implication. */\nexport function collapseSpheres(model: ModalModel): ModalModel {\n if (model.spheres === undefined) return model\n const spheres = Object.fromEntries(Object.entries(model.spheres).map(([w, s]) => [w, [s[s.length - 1] as readonly string[]]]))\n return { ...model, spheres }\n}\n","import { ModalEvaluator } from './evaluate.ts'\nimport type { Formula } from './formula.ts'\nimport type { ModalModel } from './model.ts'\nimport { checkSystem } from './model.ts'\n\n/**\n * Spheres from a numeric similarity: each atom has a weight for matching the centre's particular fact,\n * and each law a cost for violating it (a \"miracle\"). A world's distance from the centre is the sum of\n * the weights of the atoms on which it differs from the centre plus the costs of the laws false at it.\n * Worlds at the same distance share a ring, and the rings stacked from near to far are the spheres.\n *\n * This is only a numeric stand-in for Lewis's (1979) priorities among kinds of similarity, there so a\n * reader can move the weights and watch Fine's Nixon counterexample appear and disappear.\n */\n\nexport interface Law {\n readonly formula: Formula\n /** Default 1. */\n readonly cost?: number\n}\n\nexport interface Similarity {\n /** Atom → weight for differing from the centre on it; an atom left out weighs 1. */\n readonly weights?: Readonly<Record<string, number>>\n readonly laws?: readonly Law[]\n}\n\n/** How far one world lies from the centre, and why. */\nexport interface WorldDistance {\n readonly world: string\n readonly distance: number\n /** Atoms on which it differs from the centre. */\n readonly mismatches: readonly string[]\n /** Indexes (into `laws`) of the laws false at it. */\n readonly violations: readonly number[]\n}\n\nconst weightOf = (s: Similarity, atom: string): number => s.weights?.[atom] ?? 1\n\n/** Each world's distance from `center`, in world order. */\nexport function distances(model: ModalModel, center: string, similarity: Similarity): WorldDistance[] {\n const ev = new ModalEvaluator(model)\n const here = new Set(model.valuation[center] ?? [])\n const laws = similarity.laws ?? []\n return model.worlds.map((world) => {\n const there = new Set(model.valuation[world] ?? [])\n const mismatches = model.atoms.filter((a) => here.has(a) !== there.has(a))\n const violations = laws.flatMap((law, i) => (ev.holds(law.formula, world) ? [] : [i]))\n const distance = mismatches.reduce((d, a) => d + weightOf(similarity, a), 0) + violations.reduce((d, i) => d + ((laws[i] as Law).cost ?? 1), 0)\n return { world, distance, mismatches, violations }\n })\n}\n\n/**\n * The spheres around `center`, innermost first: the k-th holds every world within the k-th smallest\n * distance. The innermost is the centre's ring (the centre and anything no farther than it); it is\n * {center} alone, strongly centred, when every other world is farther.\n */\nexport function similaritySpheres(model: ModalModel, center: string, similarity: Similarity): string[][] {\n const ds = distances(model, center, similarity)\n const own = (ds.find((d) => d.world === center) as WorldDistance).distance\n const radii = [...new Set(ds.map((d) => Math.max(d.distance, own)))].sort((x, y) => x - y)\n const spheres = radii.map((r) => ds.filter((d) => d.distance <= r).map((d) => d.world))\n checkSystem(model.worlds, center, spheres, 'weak')\n return spheres\n}\n\n/** The same model with `center`'s spheres drawn from `similarity` (R there: every world). */\nexport function withSimilaritySpheres(model: ModalModel, center: string, similarity: Similarity): ModalModel {\n const spheres = similaritySpheres(model, center, similarity)\n return {\n ...model,\n spheres: { ...model.spheres, [center]: spheres },\n access: { ...model.access, [center]: spheres[spheres.length - 1] as string[] },\n }\n}\n","import { ModalError, modalProblem } from './errors.ts'\nimport type { Formula } from './formula.ts'\nimport { atomsOf, isTruthFunctional } from './formula.ts'\nimport { formulaText } from './print.ts'\n\n/**\n * Pearl's minimal surgery on boolean structural equations: an intervention replaces the equations of\n * the atoms it sets with constants and keeps every other equation; atoms without an equation are\n * background and keep their value at the centre world. The equations must be acyclic, so the\n * submodel has exactly one solution. No probabilities, abduction or many-valued variables: those\n * belong to the causal engine.\n */\n\n/** Atom → its truth-functional equation, e.g. war := press ∧ connected. */\nexport type Equations = Readonly<Record<string, Formula>>\n\n/** An atom assignment: atom → value. */\nexport type AtomValues = Readonly<Record<string, boolean>>\n\nfunction valueIn(f: Formula, values: AtomValues): boolean {\n switch (f.kind) {\n case 'atom':\n return values[f.id] === true\n case 'top':\n return true\n case 'bot':\n return false\n case 'not':\n return !valueIn(f.arg, values)\n case 'and':\n return valueIn(f.left, values) && valueIn(f.right, values)\n case 'or':\n return valueIn(f.left, values) || valueIn(f.right, values)\n case 'imp':\n return !valueIn(f.left, values) || valueIn(f.right, values)\n case 'iff':\n return valueIn(f.left, values) === valueIn(f.right, values)\n default:\n throw new ModalError(modalProblem('not-truth-functional', { formula: formulaText(f) }))\n }\n}\n\n/** The atoms in solving order: each after every atom its equation reads; throws `cyclic-equations` on a cycle. */\nexport function equationOrder(atoms: readonly string[], equations: Equations): string[] {\n for (const [atom, f] of Object.entries(equations)) {\n if (!atoms.includes(atom)) throw new ModalError(modalProblem('unknown-atom', { atom }))\n if (!isTruthFunctional(f)) throw new ModalError(modalProblem('not-truth-functional', { formula: formulaText(f) }))\n for (const a of atomsOf(f)) if (!atoms.includes(a)) throw new ModalError(modalProblem('unknown-atom', { atom: a }))\n }\n const order: string[] = []\n const state = new Map<string, 'open' | 'done'>()\n const visit = (atom: string, path: readonly string[]): void => {\n if (state.get(atom) === 'done') return\n if (state.get(atom) === 'open') {\n const cycle = [...path.slice(path.indexOf(atom)), atom]\n throw new ModalError(modalProblem('cyclic-equations', { cycle }))\n }\n state.set(atom, 'open')\n const f = equations[atom]\n if (f !== undefined) for (const a of atomsOf(f)) visit(a, [...path, atom])\n state.set(atom, 'done')\n order.push(atom)\n }\n for (const a of atoms) visit(a, [])\n return order\n}\n\n/**\n * The antecedent as an intervention, when it is a conjunction of atoms and negated atoms (`press`,\n * `press ∧ ¬connected`); otherwise undefined. A conjunction setting one atom both ways is undefined too.\n */\nexport function literalsOf(f: Formula): AtomValues | undefined {\n const out: Record<string, boolean> = {}\n const add = (g: Formula): boolean => {\n if (g.kind === 'and') return add(g.left) && add(g.right)\n const [atom, value] = g.kind === 'atom' ? [g.id, true] : g.kind === 'not' && g.arg.kind === 'atom' ? [g.arg.id, false] : [undefined, false]\n if (atom === undefined) return false\n if (out[atom] !== undefined && out[atom] !== value) return false\n out[atom] = value\n return true\n }\n return add(f) ? out : undefined\n}\n\nexport interface SurgeryResult {\n /** Every atom's value in the submodel's solution. */\n readonly values: AtomValues\n /** The atoms the intervention set. */\n readonly set: readonly string[]\n /** Atoms with an equation that the intervention left in place, in solving order. */\n readonly solved: readonly string[]\n}\n\n/**\n * Solve the submodel: `intervention` fixes its atoms, every other atom with an equation follows it\n * in solving order, and every atom without one keeps its value in `background` (the centre world's\n * true atoms).\n */\nexport function surgery(atoms: readonly string[], equations: Equations, background: readonly string[], intervention: AtomValues): SurgeryResult {\n for (const a of Object.keys(intervention)) if (!atoms.includes(a)) throw new ModalError(modalProblem('unknown-atom', { atom: a }))\n const order = equationOrder(atoms, equations)\n const values: Record<string, boolean> = {}\n const solved: string[] = []\n for (const atom of order) {\n const set = intervention[atom]\n const f = equations[atom]\n if (set !== undefined) values[atom] = set\n else if (f !== undefined) {\n values[atom] = valueIn(f, values)\n solved.push(atom)\n } else values[atom] = background.includes(atom)\n }\n return { values, set: atoms.filter((a) => intervention[a] !== undefined), solved }\n}\n\n/** The world of `worlds` whose true atoms are exactly those `values` makes true, if any. */\nexport function worldWith(worlds: readonly { readonly id: string; readonly true: readonly string[] }[], atoms: readonly string[], values: AtomValues): string | undefined {\n return worlds.find((w) => atoms.every((a) => w.true.includes(a) === (values[a] === true)))?.id\n}\n","import { z } from 'zod'\nimport { ATOM_PATTERN } from '../engine/formula.ts'\n\n/**\n * Modal documents, as hosts write them in JSON: a Kripke model, a frame, or a model with systems of\n * spheres. Formulas are strings in the authoring syntax (see `parseFormula`). The schema checks the\n * shape; `checkModalDoc` checks what the shape cannot say (known ids, nesting, formulas that parse).\n */\n\n/** Text in both languages, or one string for both. */\nexport const modalTextSchema = z.union([z.string(), z.object({ 'zh-TW': z.string(), en: z.string() }).strict()])\n\n/** World ids: a letter, then letters, digits or underscores (`w`, `v1`, `noon`). */\nexport const WORLD_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/\n\nconst worldId = z.string().regex(WORLD_PATTERN)\nconst pos = z.object({ x: z.number(), y: z.number() }).strict()\n\nconst atomSchema = z\n .object({\n id: z.string().regex(ATOM_PATTERN),\n label: modalTextSchema.optional(),\n })\n .strict()\n\nconst worldSchema = z\n .object({\n id: worldId,\n /** The atoms true here; every other atom is false here. */\n true: z.array(z.string()).default([]),\n label: modalTextSchema.optional(),\n pos: pos.optional(),\n })\n .strict()\n\nconst frameWorldSchema = worldSchema.omit({ true: true })\n\nconst layoutSchema = z.enum(['manual', 'circle', 'line', 'layers'])\n\nconst common = {\n id: z.string().optional(),\n title: modalTextSchema.optional(),\n /** Formulas listed by default. */\n formulas: z.array(z.string()).optional(),\n}\n\nexport const kripkeDocSchema = z\n .object({\n kind: z.literal('kripke'),\n ...common,\n atoms: z.array(atomSchema).default([]),\n worlds: z.array(worldSchema).min(1),\n access: z.array(z.tuple([worldId, worldId])).default([]),\n /** The actual world, selected first. */\n actual: worldId.optional(),\n layout: layoutSchema.default('circle'),\n })\n .strict()\n\nexport const frameDocSchema = z\n .object({\n kind: z.literal('frame'),\n id: common.id,\n title: common.title,\n worlds: z.array(frameWorldSchema).min(1),\n access: z.array(z.tuple([worldId, worldId])).default([]),\n actual: worldId.optional(),\n layout: layoutSchema.default('circle'),\n })\n .strict()\n\nconst lawSchema = z\n .object({\n formula: z.string(),\n /** The cost of a world where the law is false (a miracle); default 1. */\n cost: z.number().nonnegative().default(1),\n label: modalTextSchema.optional(),\n })\n .strict()\n\nexport const spheresDocSchema = z\n .object({\n kind: z.literal('spheres'),\n ...common,\n atoms: z.array(atomSchema).default([]),\n worlds: z.array(worldSchema).min(1),\n /** The world the spheres are drawn around. */\n center: worldId.optional(),\n /** The centre's spheres, innermost first. */\n spheres: z.array(z.array(worldId)).optional(),\n /** A system per world, for nested counterfactuals; instead of `center` and `spheres`. */\n systems: z.record(z.string(), z.array(z.array(worldId))).optional(),\n /** Spheres around `center` from weights and laws, instead of `spheres`. */\n similarity: z\n .object({\n weights: z.record(z.string(), z.number().nonnegative()).default({}),\n laws: z.array(lawSchema).default([]),\n })\n .strict()\n .optional(),\n centering: z.enum(['strong', 'weak']).default('strong'),\n /** Boolean structural equations for minimal surgery: atom → formula. */\n structural: z.object({ equations: z.record(z.string(), z.string()) }).strict().optional(),\n })\n .strict()\n\nexport const modalDocSchema = z.discriminatedUnion('kind', [kripkeDocSchema, frameDocSchema, spheresDocSchema])\n\nexport type ModalText = z.infer<typeof modalTextSchema>\nexport type KripkeDoc = z.infer<typeof kripkeDocSchema>\nexport type FrameDoc = z.infer<typeof frameDocSchema>\nexport type SpheresDoc = z.infer<typeof spheresDocSchema>\n/** A checked document. */\nexport type ModalDoc = z.infer<typeof modalDocSchema>\n/** A document as written, before defaults are filled in. */\nexport type ModalDocInput = z.input<typeof modalDocSchema>\nexport type KripkeDocInput = z.input<typeof kripkeDocSchema>\nexport type FrameDocInput = z.input<typeof frameDocSchema>\nexport type SpheresDocInput = z.input<typeof spheresDocSchema>\n","import type { z } from 'zod'\nimport zhTW from 'zod/v4/locales/zh-TW.js'\nimport type { Locale } from '../../engine/types.ts'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblem, modalProblemOf } from '../engine/errors.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport { isAtomId, isTruthFunctional, parseFormula } from '../engine/formula.ts'\nimport type { Frame, ModalModel } from '../engine/model.ts'\nimport { checkSystem, frameOf, kripkeModel, sphereModel } from '../engine/model.ts'\nimport { formulaText } from '../engine/print.ts'\nimport type { Similarity } from '../engine/similarity.ts'\nimport { withSimilaritySpheres } from '../engine/similarity.ts'\nimport { equationOrder } from '../engine/surgery.ts'\nimport type { FrameDoc, KripkeDoc, ModalDoc, ModalText, SpheresDoc } from './schema.ts'\nimport { modalDocSchema } from './schema.ts'\n\n/** The most worlds a document may draw. */\nexport const MAX_DOC_WORLDS = 12\n\n/** The longest JSON text `parseModalJson` reads. */\nexport const MAX_MODAL_DOC_CHARS = 200_000\n\nexport type ModalImportResult = { readonly ok: true; readonly doc: ModalDoc } | { readonly ok: false; readonly errors: readonly ModalProblem[] }\n\nconst zhIssue = zhTW().localeError\n\nfunction schemaProblems(error: { readonly issues: readonly z.core.$ZodIssue[] }): ModalProblem[] {\n return error.issues.map((issue) => {\n const zh = zhIssue(issue as unknown as z.core.$ZodRawIssue)\n const zhText = typeof zh === 'string' ? zh : (zh?.message ?? issue.message)\n return modalProblem('schema', { message: { 'zh-TW': zhText, en: issue.message } }, issue.path.map(String).join('.'))\n })\n}\n\n/** Runs `f`; one of our errors comes back as a problem at `where`. */\nfunction attempt(problems: ModalProblem[], where: string, f: () => void): void {\n try {\n f()\n } catch (error) {\n const p = modalProblemOf(error)\n if (p === undefined) throw error\n problems.push({ ...p, where })\n }\n}\n\nfunction parseInto(problems: ModalProblem[], where: string, text: string, truthFunctional = false): void {\n attempt(problems, where, () => {\n const f = parseFormula(text)\n if (truthFunctional && !isTruthFunctional(f)) problems.push(modalProblem('not-truth-functional', { formula: formulaText(f) }, where))\n })\n}\n\n/** Everything the schema cannot say: known and unique ids, nesting and centring, formulas that parse. */\nexport function checkModalDoc(doc: ModalDoc): ModalProblem[] {\n const problems: ModalProblem[] = []\n const worlds = doc.worlds.map((w) => w.id)\n if (worlds.length > MAX_DOC_WORLDS) problems.push(modalProblem('too-many-worlds', { count: worlds.length, limit: MAX_DOC_WORLDS }, 'worlds'))\n const seen = new Set<string>()\n doc.worlds.forEach((w, i) => {\n if (seen.has(w.id)) problems.push(modalProblem('duplicate-world', { world: w.id }, `worlds.${i}.id`))\n seen.add(w.id)\n if (doc.kind !== 'spheres' && doc.layout === 'manual' && w.pos === undefined) problems.push(modalProblem('missing-position', { world: w.id }, `worlds.${i}.pos`))\n })\n const knownWorld = (w: string, where: string): void => {\n if (!seen.has(w)) problems.push(modalProblem('unknown-world', { world: w }, where))\n }\n if (doc.kind !== 'frame') {\n const atoms = new Set<string>()\n doc.atoms.forEach((a, i) => {\n if (!isAtomId(a.id)) problems.push(modalProblem('reserved-atom', { atom: a.id }, `atoms.${i}.id`))\n if (atoms.has(a.id)) problems.push(modalProblem('duplicate-atom', { atom: a.id }, `atoms.${i}.id`))\n atoms.add(a.id)\n })\n doc.worlds.forEach((w, i) => {\n w.true.forEach((a, k) => {\n if (!atoms.has(a)) problems.push(modalProblem('unknown-atom', { atom: a }, `worlds.${i}.true.${k}`))\n })\n })\n doc.formulas?.forEach((text, i) => parseInto(problems, `formulas.${i}`, text))\n }\n if (doc.kind === 'kripke' || doc.kind === 'frame') {\n doc.access.forEach(([a, b], i) => {\n knownWorld(a, `access.${i}.0`)\n knownWorld(b, `access.${i}.1`)\n })\n if (doc.actual !== undefined) knownWorld(doc.actual, 'actual')\n return problems\n }\n checkSpheres(doc, worlds, problems, knownWorld)\n return problems\n}\n\nfunction checkSpheres(doc: SpheresDoc, worlds: readonly string[], problems: ModalProblem[], knownWorld: (w: string, where: string) => void): void {\n const sources = [doc.spheres !== undefined, doc.systems !== undefined, doc.similarity !== undefined].filter(Boolean).length\n if (sources !== 1 || (doc.systems === undefined) !== (doc.center !== undefined)) {\n problems.push(modalProblem('spheres-source', {}))\n }\n if (doc.center !== undefined) knownWorld(doc.center, 'center')\n if (problems.length > 0) return\n const systems: Record<string, readonly (readonly string[])[]> = doc.systems ?? (doc.spheres !== undefined && doc.center !== undefined ? { [doc.center]: doc.spheres } : {})\n for (const [w, system] of Object.entries(systems)) {\n const where = doc.systems !== undefined ? `systems.${w}` : 'spheres'\n attempt(problems, where, () => checkSystem(worlds, w, system, doc.centering))\n }\n doc.similarity?.laws.forEach((law, i) => parseInto(problems, `similarity.laws.${i}.formula`, law.formula, true))\n const atoms = new Set(doc.atoms.map((a) => a.id))\n for (const atom of Object.keys(doc.similarity?.weights ?? {})) {\n if (!atoms.has(atom)) problems.push(modalProblem('unknown-atom', { atom }, `similarity.weights.${atom}`))\n }\n if (doc.structural !== undefined) {\n const before = problems.length\n for (const [atom, text] of Object.entries(doc.structural.equations)) parseInto(problems, `structural.equations.${atom}`, text, true)\n if (problems.length === before) {\n attempt(problems, 'structural.equations', () => {\n equationOrder(doc.atoms.map((a) => a.id), structuralEquations(doc))\n })\n }\n }\n}\n\n/**\n * Read a document from JSON text or an already parsed value. Never throws: what is wrong comes back as\n * `errors`, each a {@link ModalProblem} with the path where it sits.\n */\nexport function parseModalJson(input: string | unknown): ModalImportResult {\n let raw: unknown = input\n if (typeof input === 'string') {\n if (input.length > MAX_MODAL_DOC_CHARS) return { ok: false, errors: [modalProblem('too-large', {})] }\n try {\n raw = JSON.parse(input)\n } catch (error) {\n return { ok: false, errors: [modalProblem('not-json', { detail: (error as Error).message })] }\n }\n }\n const parsed = modalDocSchema.safeParse(raw)\n if (!parsed.success) return { ok: false, errors: schemaProblems(parsed.error) }\n const problems = checkModalDoc(parsed.data)\n return problems.length > 0 ? { ok: false, errors: problems } : { ok: true, doc: parsed.data }\n}\n\n/** A frame document, or a Kripke document with its valuation ignored, as a frame. */\nexport function frameOfDoc(doc: FrameDoc | KripkeDoc): Frame {\n return frameOf(\n doc.worlds.map((w) => w.id),\n doc.access,\n )\n}\n\n/** The similarity a spheres document gives, with `weights` overriding its own. */\nexport function similarityOf(doc: SpheresDoc, weights?: Readonly<Record<string, number>>): Similarity {\n return {\n weights: { ...doc.similarity?.weights, ...weights },\n laws: (doc.similarity?.laws ?? []).map((law) => ({ formula: parseFormula(law.formula), cost: law.cost })),\n }\n}\n\n/** The structural equations of a spheres document, parsed. */\nexport function structuralEquations(doc: SpheresDoc): Record<string, Formula> {\n return Object.fromEntries(Object.entries(doc.structural?.equations ?? {}).map(([atom, text]) => [atom, parseFormula(text)]))\n}\n\n/**\n * The model a checked document describes. A frame has no atoms. A spheres document gets its systems\n * as written, or the centre's spheres from its similarity (with `weights` overriding the document's).\n */\nexport function modelOfDoc(doc: ModalDoc, weights?: Readonly<Record<string, number>>): ModalModel {\n const atoms = doc.kind === 'frame' ? [] : doc.atoms.map((a) => a.id)\n const worlds = doc.worlds.map((w) => ({ id: w.id, true: 'true' in w ? w.true : [] }))\n if (doc.kind !== 'spheres') return kripkeModel({ atoms, worlds, access: doc.access })\n if (doc.similarity !== undefined && doc.center !== undefined) {\n return withSimilaritySpheres(sphereModel({ atoms, worlds, systems: {} }), doc.center, similarityOf(doc, weights))\n }\n const systems = doc.systems ?? (doc.center !== undefined && doc.spheres !== undefined ? { [doc.center]: doc.spheres } : {})\n return sphereModel({ atoms, worlds, systems, centering: doc.centering })\n}\n\n/** The world a figure starts at: `actual`, the centre, or the first world. */\nexport function startWorld(doc: ModalDoc): string {\n if (doc.kind === 'spheres') return doc.center ?? (Object.keys(doc.systems ?? {})[0] as string | undefined) ?? (doc.worlds[0] as { id: string }).id\n return doc.actual ?? (doc.worlds[0] as { id: string }).id\n}\n\n/** Document text in `locale`. */\nexport function modalText(text: ModalText | undefined, locale: Locale): string | undefined {\n if (text === undefined) return undefined\n return typeof text === 'string' ? text : text[locale]\n}\n","import type { ReactNode } from 'react'\nimport { createContext, createElement, useContext } from 'react'\nimport type { Problem } from '../../engine/errors.ts'\nimport { problemText } from '../../engine/errors.ts'\nimport type { Locale } from '../../engine/types.ts'\nimport type { DraftIssue } from './common.ts'\nimport { EN } from './en.ts'\nimport type { Messages } from './zh.ts'\nimport { ZH } from './zh.ts'\n\n/**\n * Every piece of interface text, in Traditional Chinese (the default, zh.ts) and English (en.ts).\n * Components take their table from {@link useMessages}; pure helpers take it as an argument.\n */\n\nexport type { Locale }\nexport type { DraftIssue, NodeToggle } from './common.ts'\nexport { AUTHOR_EN, AUTHOR_ZH } from './common.ts'\nexport type { Messages } from './zh.ts'\n\nexport const DEFAULT_LOCALE: Locale = 'zh-TW'\n\n/** Each language by its own name, for language switches. */\nexport const LANGUAGE_NAMES: Readonly<Record<Locale, string>> = { 'zh-TW': '中文', en: 'English' }\n\nexport const MESSAGES: Readonly<Record<Locale, Messages>> = { 'zh-TW': ZH, en: EN }\n\nexport function messagesFor(locale: Locale): Messages {\n return MESSAGES[locale]\n}\n\n/** A problem from the engine or the data layer, worded in the table's language. */\nexport function problemMessage(p: Problem, t: Messages): string {\n return problemText(p, t.problems)\n}\n\n/** Any thrown value as text: our problems per locale, anything else by its own message. */\nexport function errorMessage(error: unknown, t: Messages): string {\n if (typeof error === 'object' && error !== null && 'problem' in error) {\n return problemMessage((error as { problem: Problem }).problem, t)\n }\n return error instanceof Error ? error.message : String(error)\n}\n\nexport function draftIssueMessage(issue: DraftIssue, t: Messages): string {\n return (t.draft[issue.code] as (i: DraftIssue) => string)(issue)\n}\n\nconst LocaleContext = createContext<Locale>(DEFAULT_LOCALE)\n\n/** Sets the language for every logic-atlas component inside it; a component's own `locale` prop wins. */\nexport function LocaleProvider({ locale, children }: { readonly locale: Locale; readonly children?: ReactNode }) {\n return createElement(LocaleContext.Provider, { value: locale }, children)\n}\n\n/** Wraps `children` in `locale` when given, else leaves the surrounding language in force. */\nexport function LocaleScope({ locale, children }: { readonly locale?: Locale; readonly children?: ReactNode }) {\n return locale === undefined ? children : createElement(LocaleContext.Provider, { value: locale }, children)\n}\n\n/** The language in force. */\nexport function useLocale(): Locale {\n return useContext(LocaleContext)\n}\n\nexport function useMessages(): Messages {\n return MESSAGES[useContext(LocaleContext)]\n}\n","import type { ModalProblemWording } from '../engine/errors.ts'\nimport { MODAL_PROBLEMS_EN } from '../engine/errors.ts'\nimport type { FrameCondition, ModalSystem } from '../engine/frames.ts'\nimport type { TcsPattern } from '../engine/inference.ts'\nimport type { ModalMessages } from './zh.ts'\n\n/** The modal components' interface text in English. */\n\nconst list = (xs: readonly string[]): string => (xs.length <= 2 ? xs.join(' and ') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`)\nconst set = (xs: readonly string[]): string => (xs.length === 0 ? '∅' : `{${xs.join(', ')}}`)\n\nconst EN_PROBLEMS: ModalProblemWording = MODAL_PROBLEMS_EN\n\nexport const MODAL_EN: ModalMessages = {\n locale: 'en',\n problems: EN_PROBLEMS,\n docInvalid: 'This model cannot be drawn:',\n trueWord: 'true',\n falseWord: 'false',\n world: 'World',\n formula: 'Formula',\n formulas: 'Formulas',\n truthSet: 'Truth set',\n intensionCaption: 'Intension: each world gives the sentence a truth value',\n selectWorld: (w) => `Select world ${w}`,\n selectFormula: (f) => `Select formula ${f}`,\n worldGraph: (n) => `Possible worlds, ${n} ${n === 1 ? 'world' : 'worlds'}`,\n worldState: (w, atoms) => (atoms.length === 0 ? `World ${w}: no atom true` : `World ${w}: ${list(atoms)} true`),\n atomsHeading: 'Atoms',\n at: (w) => `At ${w}`,\n noAccess: (w) => `${w} sees no world`,\n boxTrue: (w, arg, seen) => (seen.length === 0 ? `${w} sees no world, so □${arg} is vacuously true.` : `Every world ${w} sees (${list(seen)}) makes ${arg} true.`),\n boxFalse: (w, arg, v) => `${w} sees ${v}, where ${arg} is false: a counterexample.`,\n diaTrue: (w, arg, v) => `${w} sees ${v}, where ${arg} is true: a witness.`,\n diaFalse: (w, arg, seen) => (seen.length === 0 ? `${w} sees no world, so ◇${arg} is false.` : `Every world ${w} sees (${list(seen)}) makes ${arg} false.`),\n plainValue: (w, value) => `${value ? 'True' : 'False'} at ${w}.`,\n customFormula: 'Type a formula',\n add: 'Add',\n editHeading: 'Edit the model',\n accessHeading: 'Accessibility',\n accessToggle: (a, b) => `${a} sees ${b}`,\n atomToggle: (w, atom) => `${atom} true at ${w}`,\n showFalse: 'Also list false atoms',\n conditionHeading: 'Frame condition',\n holdsHeading: 'Holds',\n axiomHeading: 'Axiom',\n validHeading: 'Valid on the frame',\n conditionName: { serial: 'serial', reflexive: 'reflexive', transitive: 'transitive', symmetric: 'symmetric', euclidean: 'euclidean' } satisfies Readonly<Record<FrameCondition, string>>,\n conditionRule: {\n serial: 'every world sees some world',\n reflexive: 'every world sees itself',\n transitive: 'if wRv and vRu, then wRu',\n symmetric: 'if wRv, then vRw',\n euclidean: 'if wRv and wRu, then vRu',\n } satisfies Readonly<Record<FrameCondition, string>>,\n conditionWitness: (c, w) => {\n const [a = '', b = '', d = ''] = w\n switch (c) {\n case 'serial':\n return `${a} sees no world`\n case 'reflexive':\n return `${a} does not see itself`\n case 'symmetric':\n return `${a}R${b} but not ${b}R${a}`\n case 'transitive':\n return `${a}R${b} and ${b}R${d} but not ${a}R${d}`\n case 'euclidean':\n return `${a}R${b} and ${a}R${d} but not ${b}R${d}`\n }\n },\n axiomName: (name) => (name === 'M' ? 'M (also called T)' : name),\n axiomCounterexample: (trueAt, w) =>\n `with ${Object.entries(trueAt)\n .map(([a, ws]) => `${a} true exactly at ${set(ws)}`)\n .join(' and ')}, the axiom is false at ${w}`,\n yes: 'yes',\n no: 'no',\n systemName: (s: ModalSystem) => (s === 'M' ? 'M (also called T)' : s),\n systemsLine: (names) => `This frame is in the frame classes of ${list(names)}.`,\n materialHeading: 'Material conditional',\n strictHeading: 'Strict implication',\n strictTrue: (w) => `At every world ${w} sees where the antecedent is true, the consequent is true too.`,\n strictFalse: (w, bad) => `${w} sees ${list(bad)}, where the antecedent is true and the consequent false.`,\n materialTrue: (w, aFalse) => (aFalse ? `At ${w} the antecedent is false, so the material conditional is true.` : `At ${w} antecedent and consequent are both true.`),\n materialFalse: (w) => `At ${w} the antecedent is true and the consequent false.`,\n patternName: { transitivity: 'Transitivity', contraposition: 'Contraposition', strengthening: 'Strengthening the antecedent' } satisfies Readonly<Record<TcsPattern, string>>,\n exampleTitle: (pattern, title) => `${pattern}: ${title}`,\n premise: 'Premise',\n conclusion: 'Conclusion',\n counterfactualHeading: 'Spheres (counterfactual)',\n collapse: 'Press into one sphere',\n collapseHint: 'Press all spheres into the outermost one: every antecedent then uses the same range of worlds, and the counterfactual becomes strict implication.',\n inferenceCounterexample: (w) => `At ${w} the premises are true and the conclusion false: the inference fails.`,\n inferenceHolds: (w) => `At ${w} no premise set is true with the conclusion false: the inference holds.`,\n inferenceVacuous: (w) => `At ${w} not every premise is true, so there is no counterexample here.`,\n semanticsLabel: 'Semantics for conditionals',\n sphereName: (i) => `S${i + 1}`,\n center: 'centre',\n antecedentWorlds: 'Antecedent worlds',\n closestWorlds: 'Closest antecedent worlds',\n closestList: (ws) => `Closest antecedent worlds: ${list(ws)}`,\n vacuous: 'No sphere holds an antecedent world, so the conditional is vacuously true.',\n smallestSphere: (s, ws) => `The smallest sphere holding an antecedent world is ${s}; its antecedent worlds are ${list(ws)}.`,\n cfTrue: 'Every closest antecedent world makes the consequent true, so the conditional is true.',\n cfFalse: (ws) => `${list(ws)} ${ws.length === 1 ? 'makes' : 'make'} the consequent false, so the conditional is false.`,\n notUnique: (ws) => `Stalnaker's selection function is undefined here: the closest antecedent worlds are ${list(ws)}, more than one. Conditional excluded middle is not guaranteed.`,\n needsConditional: 'Choose a formula of the form A > B.',\n similarityHeading: 'By similarity (Lewis)',\n surgeryHeading: 'Minimal surgery (Pearl)',\n weightsHeading: 'Weights',\n weightLabel: (atom) => `differs from the actual ${atom}`,\n lawLabel: (law) => `violates ${law}`,\n distance: 'Distance',\n approxNote: 'Distance as a sum of weights is only a numeric stand-in for Lewis’s (1979) priorities of similarity.',\n intervention: (vals) => `Intervention: ${vals} replaced by constants, every other equation kept; atoms without an equation keep their value at the centre.`,\n solution: 'The submodel’s solution',\n solutionWorld: (w) => (w === undefined ? 'No world in the model matches this solution.' : `This solution is world ${w}.`),\n agree: 'The two semantics agree.',\n diverge: 'The two semantics disagree.',\n equationsHeading: 'Structural equations',\n}\n","import type { Locale } from '../../engine/types.ts'\nimport type { ModalProblemWording } from '../engine/errors.ts'\nimport type { FrameCondition, ModalSystem } from '../engine/frames.ts'\nimport type { TcsPattern } from '../engine/inference.ts'\n\n/** The modal components' interface text in Traditional Chinese, the default; its shape is the {@link ModalMessages} type. */\n\nconst list = (xs: readonly string[]): string => xs.join('、')\nconst set = (xs: readonly string[]): string => (xs.length === 0 ? '∅' : `{${xs.join(', ')}}`)\nconst pos = (p: { readonly position: number }): string => `(第 ${p.position + 1} 個字)`\n\nconst ZH_PROBLEMS: ModalProblemWording = {\n join: (where, message) => `${where}:${message}`,\n messages: {\n 'parse-unexpected-character': (p) => `看不懂字元 ${p.character}${pos(p)}`,\n 'parse-unexpected-token': (p) => `多出了 ${p.token}${pos(p)}`,\n 'parse-unexpected-end': (p) => `公式還沒寫完${pos(p)}`,\n 'parse-expected': (p) => `這裡要有 ${p.expected}${pos(p)}`,\n 'ambiguous-mix': (p) => `${p.operators} 並列時要加括號${pos(p)}`,\n 'reserved-atom': (p) => `${p.atom} 是保留字,不能當原子`,\n 'unknown-atom': (p) => `沒有原子 ${p.atom}`,\n 'unknown-world': (p) => `沒有世界 ${p.world}`,\n 'duplicate-world': (p) => `世界 ${p.world} 重複了`,\n 'duplicate-atom': (p) => `原子 ${p.atom} 重複了`,\n 'no-worlds': () => '模型裡沒有世界',\n 'too-many-worlds': (p) => `有 ${p.count} 個世界,上限是 ${p.limit} 個`,\n 'missing-position': (p) => `手動版面需要世界 ${p.world} 的位置`,\n 'no-sphere-system': (p) => `世界 ${p.world} 沒有同心球系統`,\n 'spheres-not-nested': (p) => `${p.world} 的第 ${p.index} 層同心球沒有包含內層`,\n 'empty-sphere': (p) => `${p.world} 的第 ${p.index} 層同心球是空的`,\n centering: (p) => (p.centering === 'strong' ? `${p.world} 的最內層同心球必須恰為 {${p.world}}` : `${p.world} 的最內層同心球必須包含 ${p.world}`),\n 'spheres-source': () => '同心球只能用一種方式給:center 加 spheres、center 加 similarity,或 systems',\n 'not-unique': (p) => `Stalnaker 的選擇在 ${p.world} 沒有定義:最接近的前件世界有 ${list(p.candidates)}`,\n 'too-many-assignments': (p) => `要窮舉 ${p.count.toLocaleString('en-US')} 種指派,上限是 ${p.limit.toLocaleString('en-US')} 種`,\n 'cyclic-equations': (p) => `方程繞成一圈:${p.cycle.join(' → ')}`,\n 'not-truth-functional': (p) => `${p.formula} 只能用真值函數連接詞(不能有 □、◇ 或 >)`,\n 'surgery-antecedent': (p) => `小手術需要原子或否定原子的連言,${p.formula} 不是`,\n 'needs-similarity': () => '這張圖需要有 center、similarity 與 structural 結構方程的同心球文件',\n 'not-json': (p) => `不是 JSON:${p.detail}`,\n 'too-large': () => '文件太大了',\n 'wrong-kind': (p) => `這張圖需要 ${p.expected.join(' 或 ')} 文件,不是 ${p.kind}`,\n schema: (p) => p.message['zh-TW'],\n },\n}\n\nexport const MODAL_ZH = {\n locale: 'zh-TW' as Locale,\n problems: ZH_PROBLEMS,\n docInvalid: '這個模型無法繪出:',\n trueWord: '真',\n falseWord: '假',\n world: '世界',\n formula: '公式',\n formulas: '公式',\n truthSet: '真值集合',\n intensionCaption: '內涵:每個世界各給句子一個真值',\n selectWorld: (w: string) => `選擇世界 ${w}`,\n selectFormula: (f: string) => `選擇公式 ${f}`,\n worldGraph: (n: number) => `可能世界圖,${n} 個世界`,\n worldState: (w: string, atoms: readonly string[]) => (atoms.length === 0 ? `世界 ${w}:沒有原子為真` : `世界 ${w}:${list(atoms)} 為真`),\n atomsHeading: '原子',\n at: (w: string) => `在 ${w}`,\n noAccess: (w: string) => `${w} 沒有可及的世界`,\n boxTrue: (w: string, arg: string, seen: readonly string[]) =>\n seen.length === 0 ? `${w} 沒有可及的世界,所以 □${arg} 空真。` : `${w} 可及的每個世界(${list(seen)})都使 ${arg} 為真。`,\n boxFalse: (w: string, arg: string, v: string) => `${w} 可及 ${v},而 ${arg} 在 ${v} 為假:這是反例。`,\n diaTrue: (w: string, arg: string, v: string) => `${w} 可及 ${v},而 ${arg} 在 ${v} 為真:這是證人。`,\n diaFalse: (w: string, arg: string, seen: readonly string[]) =>\n seen.length === 0 ? `${w} 沒有可及的世界,所以 ◇${arg} 為假。` : `${w} 可及的世界(${list(seen)})都使 ${arg} 為假。`,\n plainValue: (w: string, value: boolean) => `在 ${w} 為${value ? '真' : '假'}。`,\n customFormula: '自己輸入公式',\n add: '加入',\n editHeading: '編輯模型',\n accessHeading: '可及關係',\n accessToggle: (a: string, b: string) => `${a} 可及 ${b}`,\n atomToggle: (w: string, atom: string) => `${atom} 在 ${w} 為真`,\n showFalse: '也列出為假的原子',\n // frames\n conditionHeading: '框架條件',\n holdsHeading: '成立',\n axiomHeading: '對應公理',\n validHeading: '在框架上有效',\n conditionName: { serial: '序列的', reflexive: '自反的', transitive: '遞移的', symmetric: '對稱的', euclidean: '歐氏的' } as Readonly<Record<FrameCondition, string>>,\n conditionRule: {\n serial: '每個世界至少可及一個世界',\n reflexive: '每個世界都可及自己',\n transitive: '若 wRv 且 vRu,則 wRu',\n symmetric: '若 wRv,則 vRw',\n euclidean: '若 wRv 且 wRu,則 vRu',\n } as Readonly<Record<FrameCondition, string>>,\n conditionWitness: (c: FrameCondition, w: readonly string[]): string => {\n const [a = '', b = '', d = ''] = w\n switch (c) {\n case 'serial':\n return `${a} 看不到任何世界`\n case 'reflexive':\n return `${a} 看不到自己`\n case 'symmetric':\n return `${a}R${b},但沒有 ${b}R${a}`\n case 'transitive':\n return `${a}R${b}、${b}R${d},但沒有 ${a}R${d}`\n case 'euclidean':\n return `${a}R${b}、${a}R${d},但沒有 ${b}R${d}`\n }\n },\n axiomName: (name: string) => (name === 'M' ? 'M(又稱 T)' : name),\n axiomCounterexample: (trueAt: Readonly<Record<string, readonly string[]>>, w: string) =>\n `${Object.entries(trueAt)\n .map(([a, ws]) => `${a} 只在 ${set(ws)} 為真`)\n .join('、')}時,公理在 ${w} 為假`,\n yes: '是',\n no: '否',\n systemName: (s: ModalSystem) => (s === 'M' ? 'M(又稱 T)' : s),\n systemsLine: (names: readonly string[]) => `這個框架屬於 ${list(names)} 的框架類。`,\n // strict implication\n materialHeading: '實質蘊涵',\n strictHeading: '嚴格蘊涵',\n strictTrue: (w: string) => `${w} 可及的每個前件為真的世界,後件也為真。`,\n strictFalse: (w: string, bad: readonly string[]) => `${w} 可及的 ${list(bad)} 使前件為真、後件為假。`,\n materialTrue: (w: string, aFalse: boolean) => (aFalse ? `在 ${w} 前件為假,所以實質條件句為真。` : `在 ${w} 前件與後件都為真。`),\n materialFalse: (w: string) => `在 ${w} 前件為真、後件為假。`,\n // TCS\n patternName: { transitivity: '傳遞', contraposition: '換質換位', strengthening: '加強前件' } as Readonly<Record<TcsPattern, string>>,\n exampleTitle: (pattern: string, title: string) => `${pattern}:${title}`,\n premise: '前提',\n conclusion: '結論',\n counterfactualHeading: '同心球(反事實條件句)',\n collapse: '壓成一層',\n collapseHint: '把所有同心球壓成最外層的一個:每個前件都用同一個可及範圍,反事實條件句就變成嚴格蘊涵。',\n inferenceCounterexample: (w: string) => `在 ${w} 前提都為真、結論為假:推論失效。`,\n inferenceHolds: (w: string) => `在 ${w} 沒有前提真而結論假:推論成立。`,\n inferenceVacuous: (w: string) => `在 ${w} 前提不全為真,這裡找不到反例。`,\n // spheres\n semanticsLabel: '條件句語意',\n sphereName: (i: number) => `S${i + 1}`,\n center: '中心',\n antecedentWorlds: '前件世界',\n closestWorlds: '最接近的前件世界',\n closestList: (ws: readonly string[]) => `最接近的前件世界:${list(ws)}`,\n vacuous: '沒有任何同心球含前件世界,所以條件句空真。',\n smallestSphere: (s: string, ws: readonly string[]) => `含前件世界的最小同心球是 ${s},其中的前件世界是 ${list(ws)}。`,\n cfTrue: '最接近的前件世界都使後件為真,所以條件句為真。',\n cfFalse: (ws: readonly string[]) => `${list(ws)} 使後件為假,所以條件句為假。`,\n notUnique: (ws: readonly string[]) => `Stalnaker 的選擇函數在這裡沒有定義:最接近的前件世界有 ${list(ws)},不只一個。條件排中律因此不保證成立。`,\n needsConditional: '請選擇一個 A > B 形式的公式。',\n // surgery\n similarityHeading: '依相似度(Lewis)',\n surgeryHeading: '小手術(Pearl)',\n weightsHeading: '權重',\n weightLabel: (atom: string) => `與實際的 ${atom} 不同`,\n lawLabel: (law: string) => `違反 ${law}`,\n distance: '距離',\n approxNote: '以權重加總計算距離,只是 Lewis(1979)相似度優先序的數值近似。',\n intervention: (vals: string) => `干預:把 ${vals} 換成常數,其他方程保留;沒有方程的原子固定在中心世界的值。`,\n solution: '子模型的解',\n solutionWorld: (w: string | undefined) => (w === undefined ? '模型裡沒有與這個解相同的世界。' : `這個解就是世界 ${w}。`),\n agree: '兩種語意給出相同的判斷。',\n diverge: '兩種語意給出不同的判斷。',\n equationsHeading: '結構方程',\n} as const\n\nexport type ModalMessages = {\n readonly [K in keyof typeof MODAL_ZH]: K extends 'locale'\n ? Locale\n : (typeof MODAL_ZH)[K] extends (...args: infer A) => infer R ? (...args: A) => R extends string ? string : R : (typeof MODAL_ZH)[K] extends string ? string : (typeof MODAL_ZH)[K]\n}\n","import type { Locale } from '../../engine/types.ts'\nimport { useLocale } from '../../components/i18n/messages.ts'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblemOf, modalProblemText } from '../engine/errors.ts'\nimport { MODAL_EN } from './en.ts'\nimport type { ModalMessages } from './zh.ts'\nimport { MODAL_ZH } from './zh.ts'\n\n/**\n * The modal components' text, in Traditional Chinese (zh.ts, the default) and English (en.ts). The\n * language comes from the same {@link useLocale} as the causal components, so one `LocaleProvider`\n * sets both; the tables stay apart so neither family loads the other's.\n */\n\nexport type { ModalMessages }\n\nexport const MODAL_MESSAGES: Readonly<Record<Locale, ModalMessages>> = { 'zh-TW': MODAL_ZH, en: MODAL_EN }\n\nexport function useModalMessages(): ModalMessages {\n return MODAL_MESSAGES[useLocale()]\n}\n\nexport function modalProblemMessage(p: ModalProblem, t: ModalMessages): string {\n return modalProblemText(p, t.problems)\n}\n\n/** Any thrown value as text: our problems per locale, anything else by its own message. */\nexport function modalErrorMessage(error: unknown, t: ModalMessages): string {\n const p = modalProblemOf(error)\n if (p !== undefined) return modalProblemMessage(p, t)\n return error instanceof Error ? error.message : String(error)\n}\n","import type { Locale } from '../../engine/types.ts'\nimport type { ModalNotation } from '../engine/print.ts'\nimport { operatorSymbol } from '../engine/print.ts'\nimport { modalText } from '../data/load.ts'\nimport type { FrameDoc, KripkeDoc, SpheresDoc } from '../data/schema.ts'\nimport type { GraphInput } from './world-graph.ts'\n\n/** From a checked document to what the pictures draw: world names and box lines. Pure. */\n\ntype AnyDoc = KripkeDoc | FrameDoc | SpheresDoc\n\n/** Each world's display name: its label in `locale`, else its id. */\nexport function worldNames(doc: AnyDoc, locale: Locale): ReadonlyMap<string, string> {\n return new Map(doc.worlds.map((w) => [w.id, modalText(w.label, locale) ?? w.id]))\n}\n\n/** The names of `ids`, in order. */\nexport function namesOf(names: ReadonlyMap<string, string>, ids: readonly string[]): string[] {\n return ids.map((id) => names.get(id) ?? id)\n}\n\n/** The lines in a world's box: its true atoms, then (when asked) its false ones negated. */\nexport function boxLines(atoms: readonly string[], trueHere: readonly string[], showFalse: boolean, notation: ModalNotation): string[] {\n const not = operatorSymbol('not', notation).text\n const lines = atoms.filter((a) => trueHere.includes(a))\n return showFalse ? [...lines, ...atoms.filter((a) => !trueHere.includes(a)).map((a) => `${not}${a}`)] : lines\n}\n\n/** The graph a Kripke or frame document draws, with `valuation` and `pairs` overriding its own (the editor's state). */\nexport function docGraphInput(\n doc: KripkeDoc | FrameDoc,\n locale: Locale,\n options: {\n readonly showFalse: boolean\n readonly notation: ModalNotation\n readonly mergeSymmetric: boolean\n readonly valuation?: Readonly<Record<string, readonly string[]>>\n readonly pairs?: readonly (readonly [string, string])[]\n },\n): GraphInput {\n const names = worldNames(doc, locale)\n const atoms = doc.kind === 'kripke' ? doc.atoms.map((a) => a.id) : []\n return {\n worlds: doc.worlds.map((w) => ({\n id: w.id,\n name: names.get(w.id) ?? w.id,\n lines: boxLines(atoms, options.valuation?.[w.id] ?? ('true' in w ? w.true : []), options.showFalse, options.notation),\n pos: w.pos,\n })),\n pairs: options.pairs ?? doc.access,\n layout: doc.layout,\n root: doc.actual,\n mergeSymmetric: options.mergeSymmetric,\n }\n}\n","import type { Explanation, ModalEvaluator } from '../engine/evaluate.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport { formulaText } from '../engine/print.ts'\nimport type { ModalMessages } from '../i18n/messages.ts'\nimport { namesOf } from './doc-graph.ts'\nimport type { ParsedFormula } from './use-doc.ts'\nimport type { WorldMark } from './WorldGraph.tsx'\n\n/** Words and marks for a formula's value at a world. Pure. */\n\n/** The sentence that says why `e` has its value. */\nexport function explanationText(e: Explanation, names: ReadonlyMap<string, string>, t: ModalMessages, notation: 'modern' | 'garson'): string {\n const name = (id: string) => names.get(id) ?? id\n const f = e.formula\n if (f.kind !== 'box' && f.kind !== 'dia') return t.plainValue(name(e.world), e.value)\n const arg = formulaText(f.arg, notation)\n const seen = namesOf(names, e.accessible ?? [])\n if (f.kind === 'box') return e.value ? t.boxTrue(name(e.world), arg, seen) : t.boxFalse(name(e.world), arg, name(e.witness ?? ''))\n return e.value ? t.diaTrue(name(e.world), arg, name(e.witness ?? '')) : t.diaFalse(name(e.world), arg, seen)\n}\n\n/** Marks for the focused formula: the selected world's view for □ and ◇, else every world's value. */\nexport function marksFor(e: Explanation | undefined, ev: ModalEvaluator | undefined, f: Formula | undefined): Map<string, WorldMark> {\n const marks = new Map<string, WorldMark>()\n if (e === undefined || ev === undefined || f === undefined) return marks\n if (f.kind === 'box' || f.kind === 'dia') {\n for (const c of e.children) marks.set(c.world, c.value ? 'true' : 'false')\n if (e.witness !== undefined) marks.set(e.witness, f.kind === 'box' ? 'counter' : 'witness')\n return marks\n }\n for (const w of ev.model.worlds) marks.set(w, ev.holds(f, w) ? 'true' : 'false')\n return marks\n}\n\n/** A parsed formula's value at `world`, or undefined when it does not parse or cannot be evaluated there. */\nexport function valueOrUndefined(parsed: ParsedFormula, ev: ModalEvaluator, world: string): boolean | undefined {\n if (!parsed.ok) return undefined\n try {\n return ev.holds(parsed.formula, world)\n } catch {\n return undefined\n }\n}\n","import type { ReactNode } from 'react'\nimport type { Locale } from '../../engine/types.ts'\nimport { LocaleScope } from '../../components/i18n/messages.ts'\nimport { Tex } from '../../components/text/Tex.tsx'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport type { ModalNotation } from '../engine/print.ts'\nimport { formulaLatex, formulaText } from '../engine/print.ts'\nimport { modalText } from '../data/load.ts'\nimport type { ModalDocInput, ModalText } from '../data/schema.ts'\nimport { modalProblemMessage, useModalMessages } from '../i18n/messages.ts'\n\n/** Pieces every modal component shares: the root box, problems, formulas and truth marks. */\n\n/** A document as a component takes it: a value (as written, or checked) or JSON text. The component checks it and shows the problems when it cannot draw it. */\nexport type ModalModelInput = ModalDocInput | string\n\n/** Props every modal component takes. */\nexport interface ModalCommonProps {\n /** Interface language; default the surrounding `LocaleProvider`'s, else zh-TW. */\n readonly locale?: Locale\n /** Display notation: `modern` (¬ ∧ ∨ ⊃, the default) or `garson` (~ and &). */\n readonly notation?: Exclude<ModalNotation, 'ascii'>\n /** A caption under the figure. */\n readonly caption?: ReactNode\n}\n\n/** The language scope and the root box with the component's class. */\nexport function ModalRoot({ locale, name, caption, children }: { readonly locale?: Locale; readonly name: string; readonly caption?: ReactNode; readonly children: ReactNode }) {\n return (\n <LocaleScope locale={locale}>\n <RootBox name={name} caption={caption}>\n {children}\n </RootBox>\n </LocaleScope>\n )\n}\n\nfunction RootBox({ name, caption, children }: { readonly name: string; readonly caption?: ReactNode; readonly children: ReactNode }) {\n const t = useModalMessages()\n return (\n <figure className={`ca-root not-prose ca-modal ca-modal-${name}`} lang={t.locale}>\n {children}\n {caption !== undefined && <figcaption className=\"ca-modal-caption ca-muted\">{caption}</figcaption>}\n </figure>\n )\n}\n\n/** A document that could not be drawn: every problem with its code (the first as `data-code`). */\nexport function ModalProblems({ problems }: { readonly problems: readonly ModalProblem[] }) {\n const t = useModalMessages()\n return (\n <div className=\"ca-editor-errors ca-doc-error\" role=\"alert\" data-code={problems[0]?.code}>\n <p>{t.docInvalid}</p>\n <ul>\n {problems.map((p, i) => (\n <li key={`${p.code}-${i}`}>\n <code className=\"ca-mono\">{p.code}</code> {modalProblemMessage(p, t)}\n </li>\n ))}\n </ul>\n </div>\n )\n}\n\n/** One typeset formula; its plain text stays in `aria-label` and `data-text`. */\nexport function FormulaMath({ formula, notation = 'modern' }: { readonly formula: Formula; readonly notation?: ModalNotation }) {\n return <Tex tex={formulaLatex(formula, notation)} text={formulaText(formula, notation)} />\n}\n\n/** Garson's truth values: T and F, with the word for screen readers. */\nexport function TruthMark({ value }: { readonly value: boolean }) {\n const t = useModalMessages()\n return (\n <span className=\"ca-modal-truth\" data-value={value ? 'T' : 'F'} aria-label={value ? t.trueWord : t.falseWord}>\n <span aria-hidden=\"true\">{value ? 'T' : 'F'}</span>\n </span>\n )\n}\n\n/** A value that cannot be given: the formula does not parse, or is undefined at the world. */\nexport function UnknownMark() {\n return (\n <span className=\"ca-modal-truth\" data-value=\"error\" aria-hidden=\"true\">\n ?\n </span>\n )\n}\n\n/** The atoms and what each says, when the document labels them. */\nexport function AtomLegend({ atoms }: { readonly atoms: readonly { readonly id: string; readonly label?: ModalText }[] }) {\n const t = useModalMessages()\n if (!atoms.some((a) => a.label !== undefined)) return null\n return (\n <dl className=\"ca-modal-atoms ca-small\" aria-label={t.atomsHeading}>\n {atoms.map((a) => (\n <div key={a.id}>\n <dt className=\"ca-mono\">{a.id}</dt>\n <dd>{modalText(a.label, t.locale) ?? a.id}</dd>\n </div>\n ))}\n </dl>\n )\n}\n","import type { Locale } from '../../engine/types.ts'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblemOf } from '../engine/errors.ts'\nimport type { ConditionalSemantics, CounterfactualStep } from '../engine/evaluate.ts'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport type { ModalModel } from '../engine/model.ts'\nimport type { SpheresDoc } from '../data/schema.ts'\nimport { worldNames } from './doc-graph.ts'\nimport type { SphereWorld } from './sphere-graph.ts'\nimport type { SphereMark } from './SphereDiagram.tsx'\n\n/** What a sphere picture shows for one counterfactual at one world. Pure. */\n\nexport interface CounterfactualView {\n /** The step under Lewis's reading, which is always defined; under Stalnaker the same worlds, but the value may be undefined. */\n readonly step: CounterfactualStep\n /** Undefined when Stalnaker's selection is not unique. */\n readonly value: boolean | undefined\n readonly problem?: ModalProblem\n readonly marks: ReadonlyMap<string, SphereMark>\n}\n\n/** A counterfactual a > b at `world`, read by `semantics`. */\nexport function counterfactualView(model: ModalModel, a: Formula, b: Formula, world: string, semantics: ConditionalSemantics): CounterfactualView {\n const step = new ModalEvaluator(model).counterfactual(a, b, world)\n const marks = new Map<string, SphereMark>()\n for (const v of step.antecedentWorlds) marks.set(v, 'antecedent')\n for (const v of step.selected) marks.set(v, 'selected')\n for (const v of step.failures) marks.set(v, 'counter')\n if (semantics === 'lewis') return { step, value: step.value, marks }\n try {\n return { step, value: new ModalEvaluator(model, { semantics }).counterfactual(a, b, world).value, marks }\n } catch (error) {\n const problem = modalProblemOf(error)\n if (problem === undefined) throw error\n return { step, value: undefined, problem, marks }\n }\n}\n\n/** The worlds a sphere picture draws: names and their true atoms. */\nexport function sphereWorlds(doc: SpheresDoc, locale: Locale): SphereWorld[] {\n const names = worldNames(doc, locale)\n return doc.worlds.map((w) => ({ id: w.id, name: names.get(w.id) ?? w.id, detail: w.true.join(', ') }))\n}\n\n/** LaTeX for a set of world names. */\nexport function worldSetLatex(names: readonly string[]): string {\n return `\\\\{${names.map((n) => `\\\\text{${n.replace(/[\\\\{}]/g, '')}}`).join(', ')}\\\\}`\n}\n","import { useMemo } from 'react'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblem } from '../engine/errors.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport { atomsOf, parseFormula } from '../engine/formula.ts'\nimport { parseModalJson } from '../data/load.ts'\nimport type { ModalDoc, ModalDocInput } from '../data/schema.ts'\n\n/** Loading a component's document and its formulas. */\n\nexport type Loaded<K extends ModalDoc['kind']> = { readonly ok: true; readonly doc: Extract<ModalDoc, { kind: K }> } | { readonly ok: false; readonly errors: readonly ModalProblem[] }\n\n/** The document checked once per value, narrowed to the kinds the component draws (`kinds`: a module constant). */\nexport function useModalDoc<K extends ModalDoc['kind']>(model: ModalDocInput | string, kinds: readonly K[]): Loaded<K> {\n return useMemo(() => {\n const result = parseModalJson(model)\n if (!result.ok) return result\n if (!(kinds as readonly string[]).includes(result.doc.kind)) {\n return { ok: false, errors: [modalProblem('wrong-kind', { kind: result.doc.kind, expected: kinds }, 'kind')] }\n }\n return { ok: true, doc: result.doc as Extract<ModalDoc, { kind: K }> }\n }, [model, kinds])\n}\n\nexport type ParsedFormula = { readonly ok: true; readonly source: string; readonly formula: Formula } | { readonly ok: false; readonly source: string; readonly error: unknown }\n\n/** Parse a list of formula sources, keeping each failure in place. */\nexport function parseAll(sources: readonly string[]): ParsedFormula[] {\n return sources.map((source) => {\n try {\n return { ok: true, source, formula: parseFormula(source) }\n } catch (error) {\n return { ok: false, source, error }\n }\n })\n}\n\n/** The first atom of `formulas` the document does not have, as a problem. */\nexport function unknownAtomProblem(formulas: readonly Formula[], atoms: readonly string[]): ModalProblem | undefined {\n for (const f of formulas) for (const a of atomsOf(f)) if (!atoms.includes(a)) return modalProblem('unknown-atom', { atom: a })\n return undefined\n}\n","import { useMemo, useState } from 'react'\nimport { Tex } from '../../components/text/Tex.tsx'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport { formulaLatex, formulaText } from '../engine/print.ts'\nimport { modelOfDoc, startWorld } from '../data/load.ts'\nimport type { KripkeDoc } from '../data/schema.ts'\nimport { useModalMessages } from '../i18n/messages.ts'\nimport { namesOf, worldNames } from './doc-graph.ts'\nimport { valueOrUndefined } from './explain-text.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark, UnknownMark } from './parts.tsx'\nimport { worldSetLatex } from './sphere-view-model.ts'\nimport { parseAll, useModalDoc } from './use-doc.ts'\n\nexport interface IntensionTableProps extends ModalCommonProps {\n /** A `kripke` document (JSON text or value); R is needed only for formulas with □ or ◇. */\n readonly model: ModalModelInput\n /** Formulas, one per row, replacing the document's. */\n readonly formulas?: readonly string[]\n /** The world whose column is picked first; default the document's `actual`. */\n readonly highlight?: string\n}\n\n/**\n * Intensions as functions from worlds to truth values: one row per sentence, one column per world.\n * Pick a world to read a_w(A) down its column; pick a sentence to see its truth set |A|.\n */\nexport function IntensionTable(props: IntensionTableProps) {\n return (\n <ModalRoot locale={props.locale} name=\"intension\" caption={props.caption}>\n <IntensionBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['kripke'] as const\n\nfunction IntensionBody(props: IntensionTableProps) {\n const loaded = useModalDoc(props.model, KINDS)\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n return <IntensionLoaded {...props} doc={loaded.doc} />\n}\n\nfunction IntensionLoaded(props: IntensionTableProps & { readonly doc: KripkeDoc }) {\n const { doc, notation = 'modern' } = props\n const t = useModalMessages()\n const ev = useMemo(() => new ModalEvaluator(modelOfDoc(doc)), [doc])\n const formulas = useMemo(() => parseAll(props.formulas ?? doc.formulas ?? doc.atoms.map((a) => a.id)), [props.formulas, doc])\n const [world, setWorld] = useState(() => (props.highlight !== undefined && doc.worlds.some((w) => w.id === props.highlight) ? props.highlight : startWorld(doc)))\n const [row, setRow] = useState(0)\n const names = worldNames(doc, t.locale)\n const ids = doc.worlds.map((w) => w.id)\n const picked = formulas[row]\n const value = picked === undefined ? undefined : valueOrUndefined(picked, ev, world)\n return (\n <>\n <p className=\"ca-modal-reading\" aria-live=\"polite\">\n {picked?.ok === true && value !== undefined && (\n <Tex\n tex={`a_{\\\\text{${names.get(world) ?? world}}}(${formulaLatex(picked.formula, notation)}) = \\\\mathrm{${value ? 'T' : 'F'}}`}\n text={`a_${names.get(world) ?? world}(${formulaText(picked.formula, notation)}) = ${value ? 'T' : 'F'}`}\n />\n )}\n </p>\n <div className=\"ca-modal-scroll\">\n <table className=\"ca-modal-table ca-modal-intension\">\n <caption>{t.intensionCaption}</caption>\n <thead>\n <tr>\n <th scope=\"col\">{t.formula}</th>\n {ids.map((w) => (\n <th key={w} scope=\"col\" data-selected={w === world ? 'true' : undefined}>\n <button type=\"button\" className=\"ca-modal-pick\" aria-pressed={w === world} aria-label={t.selectWorld(names.get(w) ?? w)} onClick={() => setWorld(w)}>\n {names.get(w) ?? w}\n </button>\n </th>\n ))}\n <th scope=\"col\">{t.truthSet}</th>\n </tr>\n </thead>\n <tbody>\n {formulas.map((f, i) => {\n let set: string[] | undefined\n try {\n set = f.ok ? ev.truthSet(f.formula) : undefined\n } catch {\n set = undefined\n }\n return (\n <tr key={`${f.source}-${i}`} data-selected={i === row ? 'true' : undefined}>\n <th scope=\"row\">\n <button type=\"button\" className=\"ca-modal-pick\" aria-pressed={i === row} onClick={() => setRow(i)}>\n {f.ok ? <FormulaMath formula={f.formula} notation={notation} /> : <code className=\"ca-mono\">{f.source}</code>}\n </button>\n </th>\n {ids.map((w) => {\n const v = valueOrUndefined(f, ev, w)\n return (\n <td key={w} data-selected={w === world ? 'true' : undefined} data-in-set={i === row && set?.includes(w) ? 'true' : undefined}>\n {v === undefined ? <UnknownMark /> : <TruthMark value={v} />}\n </td>\n )\n })}\n <td>{set !== undefined && <Tex tex={worldSetLatex(namesOf(names, set))} text={`{${namesOf(names, set).join(', ')}}`} />}</td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n <AtomLegend atoms={doc.atoms} />\n </>\n )\n}\n","/** Placing small SVG labels so they do not sit on nodes, node labels or other labels. */\n\nexport interface Box {\n readonly x0: number\n readonly y0: number\n readonly x1: number\n readonly y1: number\n}\n\nexport type Anchor = 'start' | 'middle' | 'end'\n\n/** The box a single line of text covers: `y` is the baseline, `size` the font size in px. */\nexport function textBox(x: number, y: number, anchor: Anchor, width: number, size: number): Box {\n const x0 = anchor === 'start' ? x : anchor === 'end' ? x - width : x - width / 2\n return { x0, y0: y - size * 0.85, x1: x0 + width, y1: y + size * 0.25 }\n}\n\n/** A box from its top-left corner and size. */\nexport function rectBox(x: number, y: number, w: number, h: number): Box {\n return { x0: x, y0: y, x1: x + w, y1: y + h }\n}\n\n/** Whether the segment a–b passes through the box. */\nexport function segmentHitsBox(a: { readonly x: number; readonly y: number }, b: { readonly x: number; readonly y: number }, box: Box): boolean {\n let t0 = 0\n let t1 = 1\n const dx = b.x - a.x\n const dy = b.y - a.y\n for (const [p, q] of [\n [-dx, a.x - box.x0],\n [dx, box.x1 - a.x],\n [-dy, a.y - box.y0],\n [dy, box.y1 - a.y],\n ] as const) {\n if (p === 0) {\n if (q < 0) return false\n continue\n }\n const r = q / p\n if (p < 0) t0 = Math.max(t0, r)\n else t1 = Math.min(t1, r)\n if (t0 > t1) return false\n }\n return true\n}\n\n/** A square around a centre. */\nexport function around(cx: number, cy: number, half: number): Box {\n return { x0: cx - half, y0: cy - half, x1: cx + half, y1: cy + half }\n}\n\nexport function shifted(b: Box, dx: number, dy: number): Box {\n return { x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy }\n}\n\nexport function intersects(a: Box, b: Box, pad = 2): boolean {\n return a.x0 < b.x1 + pad && b.x0 < a.x1 + pad && a.y0 < b.y1 + pad && b.y0 < a.y1 + pad\n}\n\nexport interface Placed {\n readonly x: number\n readonly y: number\n readonly anchor: Anchor\n readonly box: Box\n}\n\n/** The first candidate that clears every obstacle; the first one when all of them collide. */\nexport function firstClear(candidates: readonly Placed[], obstacles: readonly Box[]): Placed {\n const clear = candidates.find((c) => !obstacles.some((o) => intersects(c.box, o)))\n return clear ?? candidates[0]\n}\n","/** Estimated text widths, and the per-value bars laid out to fit their labels. */\n\n/** Geometry of one node's per-value bars (a chart `width` wide, `barW` bars every `pitch`, in px). */\nexport interface BarLayout {\n readonly pitch: number\n readonly barW: number\n readonly width: number\n /** False when the value labels would touch: only the first and last are written. */\n readonly labelsFit: boolean\n}\n\nconst BAR_MAX_WIDTH = 126\n\n/** Lay out one bar per value, in `size`-px labels, within BAR_MAX_WIDTH. */\nexport function barLayout(labels: readonly string[], size: number): BarLayout {\n const widest = Math.max(0, ...labels.map((l) => textWidth(l, size)))\n const wanted = Math.max(14, Math.ceil(widest) + 5)\n const pitch = Math.min(wanted, BAR_MAX_WIDTH / Math.max(1, labels.length))\n return { pitch, barW: Math.max(3, Math.min(12, pitch - 5)), width: pitch * labels.length, labelsFit: pitch >= widest + 2 }\n}\n\n/** Estimated text width in px: CJK and full-width punctuation are one em, the rest about 0.6 em. */\nexport function textWidth(s: string, size: number): number {\n let w = 0\n for (const ch of s) {\n const code = ch.codePointAt(0) ?? 0\n w += code > 0x2e7f || ',。:;()「」?!…—=/、《》・'.includes(ch) ? size : size * 0.6\n }\n return w\n}\n","/** A digit suffix is a subscript only on an identifier that has no explicit underscore. */\nexport function digitSubscript(id: string): { readonly head: string; readonly sub: string } | undefined {\n const match = /^([A-Za-z][A-Za-z0-9]*?)(\\d+)$/.exec(id)\n return match === null ? undefined : { head: match[1], sub: match[2] }\n}\n","import type { Anchor, Box, Placed } from './graph-labels.ts'\nimport { rectBox, textBox } from './graph-labels.ts'\nimport { textWidth } from '../text/text-measure.ts'\nimport type { Value } from '../../engine/index.ts'\nimport { formatValue } from '../../engine/values.ts'\nimport type { Messages } from '../i18n/messages.ts'\nimport { probText } from '../model/wording.ts'\n\n/** The shapes a signal graph draws with: a node's label block and its readout, and the path strings of arrowheads, clamps and dashed rings. Pure. */\n\nconst SNAP = 0.25\n/** Per-value bars: tallest bar, the gap to the label above them, and the value label size. */\nexport const BAR_H = 24\nexport const BAR_GAP = 10\nexport const BAR_LABEL = 11\n\n/** What sits under a node's label: nothing, one number, or one bar per value (with the largest probability). */\nexport type Readout =\n | { readonly kind: 'none'; readonly noteW?: number; readonly note2W?: number }\n | { readonly kind: 'number'; readonly noteW?: number; readonly numberW?: number }\n | { readonly kind: 'bars'; readonly width: number; readonly maxW: number; readonly noteW?: number }\n\n/** Where a label block sits round its node: under or over the disc, beside it, or off one of its corners. */\nexport type BlockSide = 'below' | 'above' | 'right' | 'left' | 'below-right' | 'below-left' | 'above-right' | 'above-left'\n\n/** A node's label and its readout as one block, in offsets from the node's centre. */\nexport interface Block {\n readonly side: BlockSide\n /** The block's middle line: every text in it is centred on `cx`. */\n readonly cx: number\n /** Whether the label is wrapped onto two lines; the second has its baseline at `label2Y`. */\n readonly wrapped: boolean\n /** Baselines of the label (and of its second line), the number and the note (and a second note line). */\n readonly labelY: number\n readonly label2Y: number\n readonly numberY: number\n readonly noteY: number\n readonly note2Y: number\n /** Bars: left edge and the baseline the bars stand on. */\n readonly x0: number\n readonly baseline: number\n readonly boxes: readonly Box[]\n}\n\n/** The width a node's number reserves under its label: a probability of `digits` decimals at 16 px. */\nexport function numberWidth(digits = 2): number {\n return textWidth(`0.${'0'.repeat(digits)}`, 16) + 4\n}\n\n/** What a probability node shows as its number: a small prefix and the text. `settled` nodes (observed or do()) carry no 原本 note. */\nexport interface NodeReadout {\n readonly prefix: string\n readonly text: string\n readonly settled: boolean\n}\n\nexport function nodeReadout(\n t: Messages,\n digits: number,\n p: number | undefined,\n forced: Value | undefined,\n seen: Value | undefined,\n): NodeReadout {\n if (forced !== undefined) return { prefix: '', text: t.nodeReadout.intervened(formatValue(forced)), settled: true }\n if (seen !== undefined) return { prefix: '', text: t.nodeReadout.observed(formatValue(seen)), settled: true }\n return { prefix: `${t.nodeReadout.unknown} `, text: probText(p ?? Number.NaN, digits), settled: false }\n}\n\n/** The width a readout reserves: the number at 16 px, or the settled text at 14 px, after its prefix at 11 px. */\nexport function readoutWidth(r: NodeReadout, digits: number): number {\n const prefixW = r.prefix === '' ? 0 : textWidth(r.prefix, 11)\n return prefixW + (r.settled ? textWidth(r.text, 14) + 4 : numberWidth(digits))\n}\n\n/** A label's width on one line, and on two when it can be wrapped. */\nexport interface LabelSize {\n readonly width: number\n readonly lines?: readonly [number, number]\n}\n\n/** Between the baselines of a wrapped label's two lines, in px. */\nexport const LABEL_LEADING = 17\n\n/** The block with its top edge at `top`, centred on `cx`; its label on two lines when `wrapped`. */\nfunction blockAt(top: number, side: BlockSide, label: LabelSize, readout: Readout, cx = 0, wrapped = false): Block {\n const labelY = top + 12\n const lines = wrapped ? label.lines : undefined\n // A wrapped label claims one box over both its lines, as wide as the longer one.\n const label2Y = lines === undefined ? labelY : labelY + LABEL_LEADING\n const labelBox = textBox(cx, labelY, 'middle', lines === undefined ? label.width : Math.max(...lines), 14)\n const boxes: Box[] = [{ ...labelBox, y1: labelBox.y1 + label2Y - labelY }]\n let numberY = label2Y\n let noteY = label2Y\n let x0 = cx\n let baseline = label2Y\n let note2Y = label2Y\n const last = label2Y\n if (readout.kind === 'none' && (readout.noteW !== undefined || readout.note2W !== undefined)) {\n noteY = last + 17\n note2Y = readout.noteW === undefined ? noteY : noteY + 18\n if (readout.noteW !== undefined) boxes.push(textBox(cx, noteY, 'middle', readout.noteW, 12))\n if (readout.note2W !== undefined) boxes.push(textBox(cx, note2Y, 'middle', readout.note2W + 8, 14))\n } else if (readout.kind === 'number') {\n numberY = last + 22\n noteY = numberY + 19\n boxes.push(textBox(cx, numberY, 'middle', readout.numberW ?? numberWidth(), 16))\n if (readout.noteW !== undefined) boxes.push(textBox(cx, noteY, 'middle', readout.noteW, 12))\n } else if (readout.kind === 'bars') {\n const chartTop = last + BAR_GAP\n x0 = cx - readout.width / 2\n baseline = chartTop + BAR_H\n noteY = baseline + BAR_LABEL + 16\n boxes.push(rectBox(x0, chartTop, readout.width, BAR_H + BAR_LABEL + 6))\n boxes.push(textBox(x0 - 5, chartTop + 8, 'end', readout.maxW, 11))\n if (readout.noteW !== undefined) boxes.push(textBox(cx, noteY, 'middle', readout.noteW, 12))\n }\n return { side, cx, wrapped: lines !== undefined, labelY, label2Y, numberY, noteY, note2Y, x0, baseline, boxes }\n}\n\n/**\n * Where a node of radius `r` may put its label block, best first: under the disc, over it, beside\n * it on the right and on the left (level with its centre), then off each of the disc's four\n * corners, last because a block there may read as its neighbour's. Each spot is followed by the\n * same spot with the label on two lines, when it can be wrapped, so a long label wraps where it is\n * before it moves to another side.\n */\nexport function blockOptions(r: number, label: number | LabelSize, readout: Readout): readonly Block[] {\n const size: LabelSize = typeof label === 'number' ? { width: label } : label\n const at = (wrapped: boolean): { readonly sides: Block[]; readonly corners: Block[] } => {\n const probe = blockAt(0, 'below', size, readout, 0, wrapped)\n const height = Math.max(...probe.boxes.map((b) => b.y1))\n const minX = Math.min(...probe.boxes.map((b) => b.x0))\n const maxX = Math.max(...probe.boxes.map((b) => b.x1))\n const below = r + 12\n const above = -r - 10 - height\n // Beside the disc: the label's line level with the node's centre, the block's near edge 10 px off the rim.\n const beside = -Math.max(8, height / 2)\n const right = r + 10 - minX\n const left = -r - 10 - maxX\n // Off a corner: the block's near corner just past the square round the disc.\n const d = r + 4\n return {\n sides: [\n blockAt(below, 'below', size, readout, 0, wrapped),\n blockAt(above, 'above', size, readout, 0, wrapped),\n blockAt(beside, 'right', size, readout, right, wrapped),\n blockAt(beside, 'left', size, readout, left, wrapped),\n ],\n corners: [\n blockAt(d, 'below-right', size, readout, d - minX, wrapped),\n blockAt(d, 'below-left', size, readout, -d - maxX, wrapped),\n blockAt(-d - height, 'above-right', size, readout, d - minX, wrapped),\n blockAt(-d - height, 'above-left', size, readout, -d - maxX, wrapped),\n ],\n }\n }\n const one = at(false)\n const spots = [...one.sides, ...one.corners]\n if (size.lines === undefined) return spots\n const two = at(true)\n const wrapped = [...two.sides, ...two.corners]\n return spots.flatMap((b, i) => [b, wrapped[i]])\n}\n\n/**\n * Where a small 12 px note of width `w` (原本 v) may go beside a node of radius `r` with label block\n * `block`, best first, in offsets from the node's centre: right past the block's far edge from the\n * disc (under a block beside the disc), on the label's own line after or before it, beside the\n * disc, then on the disc's other side.\n */\nexport function noteSpots(block: Block, r: number, w: number): readonly (Placed & { readonly box: Box })[] {\n const top = Math.min(...block.boxes.map((b) => b.y0))\n const bottom = Math.max(...block.boxes.map((b) => b.y1))\n const label = block.boxes[0]\n const spot = (x: number, y: number, anchor: Anchor) => ({ x, y, anchor, box: textBox(x, y, anchor, w, 12) })\n const under = block.side === 'below' || block.side.startsWith('below-') || block.side === 'right' || block.side === 'left'\n const outer = under ? spot(block.cx, bottom + 13, 'middle') : spot(block.cx, top - 5, 'middle')\n const across = under ? spot(0, -r - 8, 'middle') : spot(0, r + 17, 'middle')\n return [\n outer,\n spot(label.x1 + 6, block.labelY, 'start'),\n spot(label.x0 - 6, block.labelY, 'end'),\n spot(r + 8, 4, 'start'),\n spot(-r - 8, 4, 'end'),\n across,\n ]\n}\n\nexport function snap(v: number): number {\n return Math.round(v / SNAP) * SNAP\n}\n\n\nexport interface Point {\n readonly x: number\n readonly y: number\n}\n\nexport function unit(a: Point, b: Point): { ux: number; uy: number; d: number } {\n const dx = b.x - a.x\n const dy = b.y - a.y\n const d = Math.hypot(dx, dy) || 1\n return { ux: dx / d, uy: dy / d, d }\n}\n\n/**\n * The dashes of an exogenous node's outline: whole dashes round the circle, so the ring has no\n * seam. (Dashes in px, not `pathLength`, so a viewer that ignores that attribute still draws them.)\n */\nexport function exoDash(r: number): string {\n const c = 2 * Math.PI * r\n const unitLength = c / Math.max(6, Math.round(c / 11))\n return `${(unitLength * 0.6).toFixed(2)} ${(unitLength * 0.4).toFixed(2)}`\n}\n\n/** How far an exogenous node's fill sits inside its dashed outline, in px. */\nexport const EXO_INSET = 4.5\n\n/** An arrowhead with its tip at `tip`, pointing along (`dx`, `dy`). */\nexport function arrowHead(tip: Point, dx: number, dy: number): string {\n const len = Math.hypot(dx, dy) || 1\n const ux = dx / len\n const uy = dy / len\n const bx = tip.x - 9 * ux\n const by = tip.y - 9 * uy\n return `M${tip.x} ${tip.y}L${bx - 3.6 * uy} ${by + 3.6 * ux}L${bx + 3.6 * uy} ${by - 3.6 * ux}z`\n}\n\nexport function clampPath(r: number): string {\n const o = r + 8\n const s = 14\n return `M${-o} ${-o + s}v${-s}h${s}M${o - s} ${-o}h${s}v${s}M${o} ${o - s}v${s}h${-s}M${-o + s} ${o}h${-s}v${-s}`\n}\n","import type { Box, Placed } from '../../components/graph/graph-labels.ts'\nimport { firstClear, intersects, rectBox, segmentHitsBox, textBox } from '../../components/graph/graph-labels.ts'\nimport type { Point } from '../../components/graph/signal-shapes.ts'\nimport { arrowHead, unit } from '../../components/graph/signal-shapes.ts'\nimport { textWidth } from '../../components/text/text-measure.ts'\n\n/**\n * The geometry of a Kripke picture, computed on the server without the DOM: each world a Garson-style\n * box listing its atoms, its name beside the box where no arrow or other box covers it, and the\n * accessibility arrows from border to border (self-loops on the top edge, a symmetric pair merged into\n * one double-headed arrow when asked). Pure.\n */\n\nexport type GraphLayoutKind = 'manual' | 'circle' | 'line' | 'layers'\n\nexport interface GraphWorld {\n readonly id: string\n /** The name written beside the box. */\n readonly name: string\n /** The lines written inside the box (true atoms, and false ones as ¬p when shown). */\n readonly lines: readonly string[]\n /** Manual layout units: x across, y down. */\n readonly pos?: { readonly x: number; readonly y: number }\n}\n\nexport interface GraphInput {\n readonly worlds: readonly GraphWorld[]\n readonly pairs: readonly (readonly [string, string])[]\n readonly layout: GraphLayoutKind\n /** Where `layers` starts: the actual world. */\n readonly root?: string\n /** Draw wRv and vRw as one double-headed arrow. */\n readonly mergeSymmetric: boolean\n}\n\nexport interface PlacedWorld {\n readonly id: string\n readonly cx: number\n readonly cy: number\n readonly w: number\n readonly h: number\n readonly lines: readonly string[]\n readonly name: string\n readonly label: Placed\n}\n\nexport interface PlacedEdge {\n readonly from: string\n readonly to: string\n /** Also vRw, drawn in the same path. */\n readonly both: boolean\n readonly path: string\n readonly heads: readonly string[]\n}\n\nexport interface GraphLayout {\n readonly worlds: readonly PlacedWorld[]\n readonly edges: readonly PlacedEdge[]\n readonly viewBox: string\n readonly width: number\n readonly height: number\n}\n\nconst LINE = 17\nconst ATOM_SIZE = 13\nconst NAME_SIZE = 13\nconst PAD = 10\nconst GAP = 3\nconst MARGIN = 14\n\nfunction boxSize(w: GraphWorld): { readonly w: number; readonly h: number } {\n const widest = Math.max(0, ...w.lines.map((l) => textWidth(l, ATOM_SIZE)))\n return { w: Math.max(40, Math.ceil(widest) + 2 * PAD), h: Math.max(28, w.lines.length * LINE + 2 * PAD - 6) }\n}\n\nfunction centres(input: GraphInput, sizes: readonly { w: number; h: number }[]): Point[] {\n const n = input.worlds.length\n const wide = Math.max(...sizes.map((s) => s.w))\n const tall = Math.max(...sizes.map((s) => s.h))\n const stepX = Math.max(130, wide + 80)\n const stepY = Math.max(96, tall + 56)\n switch (input.layout) {\n case 'manual':\n return input.worlds.map((w) => ({ x: (w.pos?.x ?? 0) * (stepX * 0.6), y: (w.pos?.y ?? 0) * (stepY * 0.6) }))\n case 'line':\n return input.worlds.map((_, i) => ({ x: i * stepX, y: 0 }))\n case 'circle': {\n if (n <= 2) return input.worlds.map((_, i) => ({ x: i * stepX, y: 0 }))\n const r = Math.max(stepY * 0.75, (stepX * n) / (2 * Math.PI))\n return input.worlds.map((_, i) => {\n const a = -Math.PI / 2 + (2 * Math.PI * i) / n\n return { x: r * Math.cos(a), y: r * Math.sin(a) }\n })\n }\n case 'layers': {\n const ids = input.worlds.map((w) => w.id)\n const depth = new Map<string, number>()\n const start = input.root ?? ids[0]\n if (start !== undefined) depth.set(start, 0)\n const queue = start === undefined ? [] : [start]\n while (queue.length > 0) {\n const a = queue.shift() as string\n for (const [x, y] of input.pairs) {\n if (x === a && !depth.has(y)) {\n depth.set(y, (depth.get(a) as number) + 1)\n queue.push(y)\n }\n }\n }\n const last = Math.max(0, ...depth.values()) + 1\n const column = ids.map((id) => depth.get(id) ?? last)\n return ids.map((id, i) => {\n const col = column[i] as number\n const mates = ids.filter((_, k) => column[k] === col)\n const row = mates.indexOf(id)\n return { x: col * stepX, y: (row - (mates.length - 1) / 2) * stepY }\n })\n }\n }\n}\n\n/** Where the ray from the box centre along (ux, uy) leaves the box, `gap` px further out. */\nfunction border(c: Point, w: number, h: number, ux: number, uy: number, gap: number): Point {\n const t = Math.min(ux === 0 ? Infinity : w / 2 / Math.abs(ux), uy === 0 ? Infinity : h / 2 / Math.abs(uy))\n return { x: c.x + ux * (t + gap), y: c.y + uy * (t + gap) }\n}\n\nconst fmt = (v: number): string => (Math.round(v * 10) / 10).toString()\n\ninterface Shape {\n readonly id: string\n readonly cx: number\n readonly cy: number\n readonly w: number\n readonly h: number\n}\n\nfunction edgeGeometry(a: Shape, b: Shape, both: boolean, offset: number): { path: string; heads: string[]; seg: [Point, Point] } {\n if (a.id === b.id) {\n const top = a.cy - a.h / 2\n const x1 = a.cx - 9\n const x2 = a.cx + 9\n const path = `M${fmt(x1)} ${fmt(top - GAP)}C${fmt(x1 - 14)} ${fmt(top - 34)} ${fmt(x2 + 14)} ${fmt(top - 34)} ${fmt(x2)} ${fmt(top - GAP)}`\n return { path, heads: [arrowHead({ x: x2, y: top - GAP }, -2, 8)], seg: [{ x: x1 - 16, y: top - 34 }, { x: x2 + 16, y: top }] }\n }\n const { ux, uy } = unit({ x: a.cx, y: a.cy }, { x: b.cx, y: b.cy })\n const ox = -uy * offset\n const oy = ux * offset\n const ca = { x: a.cx + ox, y: a.cy + oy }\n const cb = { x: b.cx + ox, y: b.cy + oy }\n const p = border(ca, a.w, a.h, ux, uy, GAP)\n const q = border(cb, b.w, b.h, -ux, -uy, GAP)\n const heads = [arrowHead(q, ux, uy)]\n if (both) heads.push(arrowHead(p, -ux, -uy))\n return { path: `M${fmt(p.x)} ${fmt(p.y)}L${fmt(q.x)} ${fmt(q.y)}`, heads, seg: [p, q] }\n}\n\nfunction nameCandidates(cx: number, cy: number, w: number, h: number, width: number): Placed[] {\n const make = (x: number, y: number, anchor: 'start' | 'middle' | 'end'): Placed => ({ x, y, anchor, box: textBox(x, y, anchor, width, NAME_SIZE) })\n return [\n make(cx, cy - h / 2 - 7, 'middle'),\n make(cx, cy + h / 2 + NAME_SIZE + 3, 'middle'),\n make(cx - w / 2 - 6, cy + 4, 'end'),\n make(cx + w / 2 + 6, cy + 4, 'start'),\n make(cx - w / 2, cy - h / 2 - 7, 'start'),\n make(cx + w / 2, cy + h / 2 + NAME_SIZE + 3, 'end'),\n ]\n}\n\nexport function layoutWorldGraph(input: GraphInput): GraphLayout {\n const sizes = input.worlds.map(boxSize)\n const at = centres(input, sizes)\n const boxes = input.worlds.map((w, i) => {\n const c = at[i] as Point\n const s = sizes[i] as { w: number; h: number }\n return { id: w.id, cx: c.x, cy: c.y, w: s.w, h: s.h, lines: w.lines, name: w.name }\n })\n const byId = new Map(boxes.map((b) => [b.id, b]))\n const has = new Set(input.pairs.map(([a, b]) => `${a}\\u0000${b}`))\n const edges: PlacedEdge[] = []\n const segments: [Point, Point][] = []\n /** Self-loops, as the boxes they cover. */\n const loops: Box[] = []\n for (const [from, to] of input.pairs) {\n const reverse = from !== to && has.has(`${to}\\u0000${from}`)\n if (reverse && input.mergeSymmetric && input.worlds.findIndex((w) => w.id === from) > input.worlds.findIndex((w) => w.id === to)) continue\n const a = byId.get(from)\n const b = byId.get(to)\n if (a === undefined || b === undefined) continue\n const both = reverse && input.mergeSymmetric\n const g = edgeGeometry(a, b, both, reverse && !both ? 4 : 0)\n edges.push({ from, to, both, path: g.path, heads: g.heads })\n if (from === to) loops.push({ x0: g.seg[0].x, y0: g.seg[0].y, x1: g.seg[1].x, y1: g.seg[1].y })\n else segments.push(g.seg)\n }\n const obstacles: Box[] = [...boxes.map((b) => rectBox(b.cx - b.w / 2, b.cy - b.h / 2, b.w, b.h)), ...loops]\n const worlds: PlacedWorld[] = boxes.map((b) => {\n const width = textWidth(b.name, NAME_SIZE)\n const candidates = nameCandidates(b.cx, b.cy, b.w, b.h, width)\n const free = candidates.filter((c) => !segments.some(([p, q]) => segmentHitsBox(p, q, c.box)))\n const label = firstClear(free.length > 0 ? free : candidates, obstacles)\n obstacles.push(label.box)\n return { ...b, label }\n })\n const all = [...obstacles, ...segments.map(([p, q]) => ({ x0: Math.min(p.x, q.x), y0: Math.min(p.y, q.y), x1: Math.max(p.x, q.x), y1: Math.max(p.y, q.y) }))]\n const x0 = Math.min(...all.map((b) => b.x0)) - MARGIN\n const y0 = Math.min(...all.map((b) => b.y0)) - MARGIN\n const x1 = Math.max(...all.map((b) => b.x1)) + MARGIN\n const y1 = Math.max(...all.map((b) => b.y1)) + MARGIN\n return { worlds, edges, viewBox: `${fmt(x0)} ${fmt(y0)} ${fmt(x1 - x0)} ${fmt(y1 - y0)}`, width: Math.round(x1 - x0), height: Math.round(y1 - y0) }\n}\n\n/** Whether two placed labels overlap: for tests. */\nexport function labelsOverlap(layout: GraphLayout): boolean {\n return layout.worlds.some((a, i) => layout.worlds.some((b, k) => k > i && intersects(a.label.box, b.label.box, 0)))\n}\n","import { digitSubscript } from '../../engine/identifier-format.ts'\n\n/** `X_Y` identifiers drawn as X with a smaller, lowered Y; shared by the live SVG labels and the exported images. */\n\n/** The head and the subscript of an `X_Y` identifier, at word boundaries. */\nconst UNDERSCORE_IDENT = /([A-Za-z]+)_([A-Za-z0-9]+)/\nexport const SUB_IDENT = new RegExp(`(?<![A-Za-z0-9_])${UNDERSCORE_IDENT.source}(?![A-Za-z0-9_])`, 'g')\nconst IDENT_TOKEN = /(?<![A-Za-z0-9_])[A-Za-z][A-Za-z0-9_]*/g\nexport const SUB_DY = '0.25em'\nexport const SUB_SIZE = '70%'\n/** A zero-width space carries the baseline-restoring `dy` after a subscript. */\nexport const ZWSP = '\\u200b'\n\nexport type SubPart = string | { readonly head: string; readonly sub: string }\n\n/** Formula or identifier-label text split into plain runs and `X_Y` or `X1` identifiers. */\nexport function subscriptParts(text: string): SubPart[] {\n const out: SubPart[] = []\n let last = 0\n for (const m of text.matchAll(IDENT_TOKEN)) {\n const id = m[0]\n const explicit = UNDERSCORE_IDENT.exec(id)\n const parts = explicit?.[0] === id ? { head: explicit[1], sub: explicit[2] } : digitSubscript(id)\n if (parts === undefined) continue\n if (m.index > last) out.push(text.slice(last, m.index))\n out.push(parts)\n last = m.index + m[0].length\n }\n if (last < text.length) out.push(text.slice(last))\n return out\n}\n","import type { ReactNode } from 'react'\nimport { Fragment } from 'react'\nimport { SUB_DY, SUB_SIZE, ZWSP, subscriptParts } from './subscript.ts'\n\n/**\n * SVG text with `X_Y` identifiers drawn as X with a smaller, lowered Y (`dy` pairs, which every SVG\n * renderer honours). The plain text stays in the aria-label and `data-*` attributes.\n */\nexport function sub(text: string): ReactNode {\n const parts = subscriptParts(text)\n if (parts.length === 1 && typeof parts[0] === 'string') return text\n return parts.map((p, i) =>\n typeof p === 'string' ? (\n p\n ) : (\n <Fragment key={i}>\n {p.head}\n <tspan dy={SUB_DY} fontSize={SUB_SIZE}>\n {p.sub}\n </tspan>\n <tspan dy={`-${SUB_DY}`}>{ZWSP}</tspan>\n </Fragment>\n ),\n )\n}\n","import type { KeyboardEvent } from 'react'\nimport { sub } from '../../components/text/svg-text.tsx'\nimport type { GraphLayout } from './world-graph.ts'\n\n/** How a world is marked: its value under the formula in focus, or its part in a modal step. */\nexport type WorldMark = 'true' | 'false' | 'witness' | 'counter' | 'dim'\n\nexport interface WorldGraphProps {\n readonly layout: GraphLayout\n /** The accessible name of the picture. */\n readonly label: string\n readonly selected?: string\n readonly marks?: ReadonlyMap<string, WorldMark>\n /** Each world's accessible name. */\n readonly worldLabel: (id: string) => string\n /** Makes each world a button that selects it. */\n readonly onSelect?: (id: string) => void\n}\n\nconst LINE = 17\nconst PAD = 10\n\n/** A Kripke picture: Garson-style world boxes and accessibility arrows; the selected world's arrows are drawn strong. */\nexport function WorldGraph({ layout, label, selected, marks, worldLabel, onSelect }: WorldGraphProps) {\n const key = (id: string) => (e: KeyboardEvent<SVGGElement>) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n onSelect?.(id)\n }\n }\n return (\n <svg className=\"ca-modal-graph\" viewBox={layout.viewBox} width={layout.width} role=\"group\" aria-label={label}>\n <g className=\"ca-modal-edges\" aria-hidden=\"true\">\n {layout.edges.map((e) => {\n const active = selected !== undefined && (e.from === selected || (e.both && e.to === selected))\n return (\n <g key={`${e.from}-${e.to}`} className=\"ca-modal-edge\" data-from={e.from} data-to={e.to} data-active={active ? 'true' : undefined}>\n <path d={e.path} fill=\"none\" />\n {e.heads.map((h, i) => (\n <path key={i} d={h} className=\"ca-modal-head\" />\n ))}\n </g>\n )\n })}\n </g>\n {layout.worlds.map((w) => {\n const mark = marks?.get(w.id)\n const top = w.cy - w.h / 2\n return (\n <g\n key={w.id}\n className=\"ca-modal-world\"\n data-world={w.id}\n data-mark={mark}\n data-selected={w.id === selected ? 'true' : undefined}\n role={onSelect === undefined ? 'img' : 'button'}\n tabIndex={onSelect === undefined ? undefined : 0}\n aria-label={worldLabel(w.id)}\n aria-pressed={onSelect === undefined ? undefined : w.id === selected}\n onClick={onSelect === undefined ? undefined : () => onSelect(w.id)}\n onKeyDown={onSelect === undefined ? undefined : key(w.id)}\n >\n <rect x={w.cx - w.w / 2} y={top} width={w.w} height={w.h} rx=\"3\" className=\"ca-modal-box\" />\n {w.lines.map((line, i) => (\n <text key={line} x={w.cx} y={top + PAD + i * LINE + 9} textAnchor=\"middle\" className=\"ca-modal-atom\" data-negated={line.startsWith('¬') || line.startsWith('~') ? 'true' : undefined}>\n {sub(line)}\n </text>\n ))}\n <text x={w.label.x} y={w.label.y} textAnchor={w.label.anchor} className=\"ca-modal-name\">\n {sub(w.name)}\n </text>\n </g>\n )\n })}\n </svg>\n )\n}\n","import { useMemo, useState } from 'react'\nimport type { Explanation } from '../engine/evaluate.ts'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport { kripkeModel } from '../engine/model.ts'\nimport { startWorld } from '../data/load.ts'\nimport type { KripkeDoc } from '../data/schema.ts'\nimport type { ModalMessages } from '../i18n/messages.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { docGraphInput, worldNames } from './doc-graph.ts'\nimport { explanationText, marksFor, valueOrUndefined } from './explain-text.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark, UnknownMark } from './parts.tsx'\nimport type { ParsedFormula } from './use-doc.ts'\nimport { parseAll, useModalDoc } from './use-doc.ts'\nimport { layoutWorldGraph } from './world-graph.ts'\nimport { WorldGraph } from './WorldGraph.tsx'\n\nexport interface KripkeViewProps extends ModalCommonProps {\n /** A `kripke` document (JSON text or value). */\n readonly model: ModalModelInput\n /** Formulas to list, replacing the document's. */\n readonly formulas?: readonly string[]\n /** The world selected first; default the document's `actual`, else its first world. */\n readonly world?: string\n /** Explain the focused formula's value in words; default true. */\n readonly explain?: boolean\n /** Let the reader toggle atoms and arrows and type formulas; default false. */\n readonly editable?: boolean\n /** Draw wRv and vRw as one double-headed arrow; default true. */\n readonly mergeSymmetric?: boolean\n /** List false atoms as ¬p in the boxes at first; default false. */\n readonly showFalse?: boolean\n}\n\n/**\n * ⟨W, R, a⟩ drawn as Garson's boxes and arrows. Pick a world to see each formula's value there; pick\n * a formula to see, for □ and ◇, the worlds the selected one sees, the witness or the counterexample.\n */\nexport function KripkeView(props: KripkeViewProps) {\n return (\n <ModalRoot locale={props.locale} name=\"kripke\" caption={props.caption}>\n <KripkeBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['kripke'] as const\n\nfunction KripkeBody(props: KripkeViewProps) {\n const loaded = useModalDoc(props.model, KINDS)\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n return <KripkeLoaded {...props} doc={loaded.doc} />\n}\n\nfunction KripkeLoaded(props: KripkeViewProps & { readonly doc: KripkeDoc }) {\n const { doc, editable = false, explain = true, mergeSymmetric = true, notation = 'modern' } = props\n const t = useModalMessages()\n const [world, setWorld] = useState(() => (props.world !== undefined && doc.worlds.some((w) => w.id === props.world) ? props.world : startWorld(doc)))\n const [focus, setFocus] = useState(0)\n const [showFalse, setShowFalse] = useState(props.showFalse ?? false)\n const [extra, setExtra] = useState<readonly string[]>([])\n const [draft, setDraft] = useState('')\n const [valuation, setValuation] = useState<Readonly<Record<string, readonly string[]>>>(() => Object.fromEntries(doc.worlds.map((w) => [w.id, w.true])))\n const [pairs, setPairs] = useState<readonly (readonly [string, string])[]>(doc.access)\n const atoms = useMemo(() => doc.atoms.map((a) => a.id), [doc])\n const names = worldNames(doc, t.locale)\n const ev = useMemo(() => new ModalEvaluator(kripkeModel({ atoms, worlds: doc.worlds.map((w) => ({ id: w.id, true: valuation[w.id] ?? [] })), access: pairs })), [atoms, doc, valuation, pairs])\n const formulas: ParsedFormula[] = useMemo(() => parseAll([...(props.formulas ?? doc.formulas ?? []), ...extra]), [props.formulas, doc, extra])\n const layout = useMemo(() => layoutWorldGraph(docGraphInput(doc, t.locale, { showFalse, notation, mergeSymmetric, valuation, pairs })), [doc, t.locale, showFalse, notation, mergeSymmetric, valuation, pairs])\n const focused = formulas[focus]\n let explanation: Explanation | undefined\n let problem: string | undefined\n if (focused?.ok === true) {\n try {\n explanation = ev.explain(focused.formula, world)\n } catch (error) {\n problem = modalErrorMessage(error, t)\n }\n }\n const marks = marksFor(explanation, ev, focused?.ok === true ? focused.formula : undefined)\n const togglePair = (a: string, b: string): void =>\n setPairs((ps) => (ps.some(([x, y]) => x === a && y === b) ? ps.filter(([x, y]) => !(x === a && y === b)) : [...ps, [a, b] as const]))\n const toggleAtom = (w: string, atom: string): void =>\n setValuation((v) => ({ ...v, [w]: (v[w] ?? []).includes(atom) ? (v[w] ?? []).filter((a) => a !== atom) : [...(v[w] ?? []), atom] }))\n return (\n <div className=\"ca-modal-split\">\n <div className=\"ca-modal-figure\">\n <WorldGraph\n layout={layout}\n label={t.worldGraph(doc.worlds.length)}\n selected={world}\n marks={marks}\n worldLabel={(id) => `${t.selectWorld(names.get(id) ?? id)}. ${t.worldState(names.get(id) ?? id, valuation[id] ?? [])}`}\n onSelect={setWorld}\n />\n </div>\n <div className=\"ca-modal-side\">\n <p className=\"ca-modal-at ca-h3\">{t.at(names.get(world) ?? world)}</p>\n <ul className=\"ca-modal-formulas\" aria-label={t.formulas}>\n {formulas.map((f, i) => (\n <li key={`${f.source}-${i}`}>\n <button type=\"button\" className=\"ca-modal-formula\" aria-pressed={i === focus} onClick={() => setFocus(i)}>\n {f.ok ? <FormulaMath formula={f.formula} notation={notation} /> : <code className=\"ca-mono\">{f.source}</code>}\n <FormulaValue parsed={f} ev={ev} world={world} />\n </button>\n </li>\n ))}\n </ul>\n {explain && explanation !== undefined && (\n <p className=\"ca-modal-explain\" aria-live=\"polite\">\n {explanationText(explanation, names, t, notation)}\n </p>\n )}\n {problem !== undefined && (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {problem}\n </p>\n )}\n {focused !== undefined && !focused.ok && (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(focused.error, t)}\n </p>\n )}\n <AtomLegend atoms={doc.atoms} />\n <label className=\"ca-modal-check\">\n <input type=\"checkbox\" checked={showFalse} onChange={(e) => setShowFalse(e.currentTarget.checked)} /> {t.showFalse}\n </label>\n {editable && (\n <form\n className=\"ca-modal-add\"\n onSubmit={(e) => {\n e.preventDefault()\n if (draft.trim() === '') return\n setExtra((xs) => [...xs, draft.trim()])\n setFocus(formulas.length)\n setDraft('')\n }}\n >\n <input className=\"ca-modal-input ca-mono\" aria-label={t.customFormula} placeholder={t.customFormula} value={draft} onChange={(e) => setDraft(e.currentTarget.value)} />\n <button type=\"submit\" className=\"ca-modal-button\">\n {t.add}\n </button>\n </form>\n )}\n </div>\n {editable && (\n <details className=\"ca-modal-edit\">\n <summary>{t.editHeading}</summary>\n <EditTables doc={doc} atoms={atoms} names={names} valuation={valuation} pairs={pairs} onAtom={toggleAtom} onPair={togglePair} t={t} />\n </details>\n )}\n </div>\n )\n}\n\nfunction FormulaValue({ parsed, ev, world }: { readonly parsed: ParsedFormula; readonly ev: ModalEvaluator; readonly world: string }) {\n const value = valueOrUndefined(parsed, ev, world)\n return value === undefined ? <UnknownMark /> : <TruthMark value={value} />\n}\n\nfunction EditTables(props: {\n readonly doc: KripkeDoc\n readonly atoms: readonly string[]\n readonly names: ReadonlyMap<string, string>\n readonly valuation: Readonly<Record<string, readonly string[]>>\n readonly pairs: readonly (readonly [string, string])[]\n readonly onAtom: (w: string, atom: string) => void\n readonly onPair: (a: string, b: string) => void\n readonly t: ModalMessages\n}) {\n const { doc, atoms, names, valuation, pairs, onAtom, onPair, t } = props\n const ids = doc.worlds.map((w) => w.id)\n const name = (id: string) => names.get(id) ?? id\n return (\n <div className=\"ca-modal-edit-tables\">\n {atoms.length > 0 && (\n <table className=\"ca-modal-table\">\n <caption>{t.atomsHeading}</caption>\n <thead>\n <tr>\n <th scope=\"col\">{t.world}</th>\n {atoms.map((a) => (\n <th key={a} scope=\"col\" className=\"ca-mono\">\n {a}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {ids.map((w) => (\n <tr key={w}>\n <th scope=\"row\">{name(w)}</th>\n {atoms.map((a) => (\n <td key={a}>\n <input type=\"checkbox\" aria-label={t.atomToggle(name(w), a)} checked={(valuation[w] ?? []).includes(a)} onChange={() => onAtom(w, a)} />\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n )}\n <table className=\"ca-modal-table\">\n <caption>{t.accessHeading}</caption>\n <thead>\n <tr>\n <th scope=\"col\">R</th>\n {ids.map((w) => (\n <th key={w} scope=\"col\">\n {name(w)}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {ids.map((a) => (\n <tr key={a}>\n <th scope=\"row\">{name(a)}</th>\n {ids.map((b) => (\n <td key={b}>\n <input type=\"checkbox\" aria-label={t.accessToggle(name(a), name(b))} checked={pairs.some(([x, y]) => x === a && y === b)} onChange={() => onPair(a, b)} />\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )\n}\n","import type { ReactNode } from 'react'\nimport { useEffect, useId, useRef, useState } from 'react'\nimport type { Problem } from '../../engine/index.ts'\nimport { problemMessage, useMessages } from '../i18n/messages.ts'\n\n/** Small shared pieces: segmented control, disclosure, progress, icons, tags. */\n\nexport interface SegmentedProps<T extends string> {\n readonly label: string\n readonly options: readonly { readonly value: T; readonly label: string }[]\n readonly value: T\n readonly onChange: (value: T) => void\n readonly className?: string\n}\n\nexport function Segmented<T extends string>({ label, options, value, onChange, className }: SegmentedProps<T>) {\n return (\n <div className={`ca-seg ${className ?? ''}`} role=\"group\" aria-label={label}>\n {options.map((o) => (\n <button\n key={o.value}\n type=\"button\"\n className=\"ca-seg-item\"\n aria-pressed={o.value === value}\n onClick={() => onChange(o.value)}\n >\n {o.label}\n </button>\n ))}\n </div>\n )\n}\n\nexport interface DisclosureProps {\n /** Small label before the title; default 補充 / More. Empty for none. */\n readonly kicker?: string\n readonly title: ReactNode\n readonly children: ReactNode\n readonly defaultOpen?: boolean\n readonly className?: string\n}\n\n/** A box that stays closed until asked; the header button carries aria-expanded. */\nexport function Disclosure({ kicker: kickerProp, title, children, defaultOpen = false, className }: DisclosureProps) {\n const t = useMessages()\n const kicker = kickerProp ?? t.more\n const [open, setOpen] = useState(defaultOpen)\n const id = useId()\n return (\n <section className={`ca-disclosure ${className ?? ''}`} data-open={open ? 'true' : 'false'}>\n <button\n type=\"button\"\n className=\"ca-disclosure-head\"\n aria-expanded={open}\n aria-controls={id}\n onClick={() => setOpen((o) => !o)}\n >\n {kicker !== '' && <span className=\"ca-disclosure-kicker\">{kicker}</span>}\n <span className=\"ca-disclosure-title\">{title}</span>\n <PlusMinus open={open} />\n </button>\n <div id={id} className=\"ca-disclosure-body\" hidden={!open}>\n {open && children}\n </div>\n </section>\n )\n}\n\nexport interface TipProps {\n /** What the tooltip explains; shown on hover, keyboard focus or a tap. */\n readonly tip: ReactNode\n /** The trigger's own content; default a small ⓘ mark. */\n readonly children?: ReactNode\n /** Accessible name of the default mark. */\n readonly label?: string\n readonly className?: string\n}\n\n/**\n * The one tooltip primitive: a focusable trigger described by (`aria-describedby`) a\n * `role=\"tooltip\"` element. Hover or focus shows it, a tap or click toggles it, Escape or leaving\n * hides it. Short on-graph notes stay as they are; anything longer goes in here.\n */\nexport function Tip({ tip, children, label, className }: TipProps) {\n const id = useId()\n const [open, setOpen] = useState(false)\n const ref = useRef<HTMLSpanElement>(null)\n useEffect(() => {\n if (!open) return\n const outside = (e: Event): void => {\n if (e.target instanceof Node && ref.current?.contains(e.target) !== true) setOpen(false)\n }\n document.addEventListener('pointerdown', outside)\n return () => document.removeEventListener('pointerdown', outside)\n }, [open])\n return (\n <span className={`ca-tip ${className ?? ''}`} ref={ref} onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>\n <span\n className={`ca-tip-trigger${children === undefined ? ' is-mark' : ''}`}\n role={children === undefined ? 'button' : undefined}\n tabIndex={0}\n aria-label={children === undefined ? label : undefined}\n aria-describedby={id}\n onFocus={() => setOpen(true)}\n onBlur={() => setOpen(false)}\n onClick={() => setOpen((o) => !o)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') {\n if (open) e.stopPropagation()\n setOpen(false)\n }\n else if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n setOpen((o) => !o)\n }\n }}\n >\n {children ?? <span aria-hidden=\"true\">ⓘ</span>}\n </span>\n <span id={id} role=\"tooltip\" className=\"ca-tip-body\" hidden={!open}>\n {tip}\n </span>\n </span>\n )\n}\n\nfunction PlusMinus({ open }: { readonly open: boolean }) {\n return (\n <svg className=\"ca-icon\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d={open ? 'M2 8h12' : 'M2 8h12M8 2v12'} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n </svg>\n )\n}\n\nexport function Arrow() {\n return (\n <svg className=\"ca-icon ca-arrow\" width=\"26\" height=\"14\" viewBox=\"0 0 26 14\" aria-hidden=\"true\">\n <path d=\"M1 7h23m-6-6l6 6l-6 6\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n </svg>\n )\n}\n\nexport function OkIcon({ size = 20 }: { readonly size?: number }) {\n return (\n <svg className=\"ca-icon ca-ok\" width={size} height={size} viewBox=\"-10 -10 20 20\" aria-hidden=\"true\">\n <circle r=\"10\" className=\"ca-fill-green\" />\n <path d=\"M-5 0l4 4l6-8\" fill=\"none\" className=\"ca-stroke-on-green\" strokeWidth=\"2\" />\n </svg>\n )\n}\n\nexport function NoIcon({ size = 20 }: { readonly size?: number }) {\n return (\n <svg className=\"ca-icon ca-no\" width={size} height={size} viewBox=\"-11 -11 22 22\" aria-hidden=\"true\">\n <circle r=\"9.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n <path d=\"M-4 -4l8 8m0-8l-8 8\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n </svg>\n )\n}\n\nexport function PartIcon({ size = 20 }: { readonly size?: number }) {\n return (\n <svg className=\"ca-icon ca-part\" width={size} height={size} viewBox=\"-11 -11 22 22\" aria-hidden=\"true\">\n <circle r=\"9.5\" fill=\"none\" className=\"ca-stroke-green\" strokeWidth=\"1.75\" />\n <path d=\"M0 -9.5A9.5 9.5 0 0 1 0 9.5z\" className=\"ca-fill-green\" />\n </svg>\n )\n}\n\nexport function Pin() {\n return (\n <svg className=\"ca-icon\" width=\"10\" height=\"14\" viewBox=\"-5 -7 10 14\" aria-hidden=\"true\">\n <circle cy=\"-2.5\" r=\"3.5\" className=\"ca-fill-amber-mark\" />\n <path d=\"M0 0v6.5\" className=\"ca-stroke-amber\" strokeWidth=\"1.75\" strokeLinecap=\"round\" />\n </svg>\n )\n}\n\nexport function Progress({ step, total }: { readonly step: number; readonly total: number }) {\n const t = useMessages()\n return (\n <span className=\"ca-progress\" role=\"img\" aria-label={t.stepOf(step, total)}>\n {Array.from({ length: total }, (_, i) => (\n <span key={i} className=\"ca-progress-dot\" data-on={i < step ? 'true' : 'false'} />\n ))}\n <span className=\"ca-progress-text ca-mono\" aria-hidden=\"true\">\n {step}/{total}\n </span>\n </span>\n )\n}\n\nexport type TagTone = 'fg' | 'slate' | 'accent' | 'chip' | 'line' | 'amber' | 'outline'\n\nexport function Tag({ tone, children, mono }: { readonly tone: TagTone; readonly children: ReactNode; readonly mono?: boolean }) {\n return <span className={`ca-tag ca-tag-${tone}${mono === true ? ' ca-mono' : ''}`}>{children}</span>\n}\n\n/** A model document that could not be drawn: every problem with its stable code (and the first as `data-code`). */\nexport function DocProblems({ problems }: { readonly problems: readonly Problem[] }) {\n const t = useMessages()\n return (\n <div className=\"ca-root not-prose ca-editor-errors ca-doc-error\" role=\"alert\" data-code={problems[0]?.code} lang={t.locale}>\n <p>{t.docInvalid}</p>\n <ul>\n {problems.map((p, i) => (\n <li key={`${p.code}-${i}`}>\n <code className=\"ca-mono\">{p.code}</code> {problemMessage(p, t)}\n </li>\n ))}\n </ul>\n </div>\n )\n}\n","/**\n * Properties of a finite binary relation R ⊆ X × X, each with the elements that witness a failure.\n * Shared by the modal frame conditions and, later, the set-theory relation views. Pure.\n */\n\nexport interface FiniteRelation {\n /** The carrier X, in a fixed order. */\n readonly elements: readonly string[]\n /** The pairs (a, b) with a R b. */\n readonly pairs: readonly (readonly [string, string])[]\n}\n\n/** A property's verdict: `witness` lists the elements that break it, in the order the property names them. */\nexport type RelationCheck = { readonly holds: true } | { readonly holds: false; readonly witness: readonly string[] }\n\nexport type RelationProperty = 'serial' | 'reflexive' | 'irreflexive' | 'symmetric' | 'transitive' | 'euclidean'\n\n/** Every property this module checks. */\nexport const RELATION_PROPERTIES: readonly RelationProperty[] = ['serial', 'reflexive', 'irreflexive', 'symmetric', 'transitive', 'euclidean']\n\nconst HOLDS: RelationCheck = { holds: true }\n\nfunction fails(...witness: string[]): RelationCheck {\n return { holds: false, witness }\n}\n\n/** Membership test for the pairs. */\nfunction relates(r: FiniteRelation): (a: string, b: string) => boolean {\n const set = new Set(r.pairs.map(([a, b]) => `${a}\\u0000${b}`))\n return (a, b) => set.has(`${a}\\u0000${b}`)\n}\n\n/**\n * Whether `r` has `property`. Witnesses: serial, reflexive and irreflexive name the one element x\n * (no x R y; not x R x; x R x); symmetric names (x, y) with x R y but not y R x; transitive names\n * (x, y, z) with x R y, y R z but not x R z; euclidean names (x, y, z) with x R y, x R z but not y R z.\n * The first witness in the element order is returned.\n */\nexport function checkRelation(r: FiniteRelation, property: RelationProperty): RelationCheck {\n const has = relates(r)\n const xs = r.elements\n switch (property) {\n case 'serial':\n for (const x of xs) if (!xs.some((y) => has(x, y))) return fails(x)\n return HOLDS\n case 'reflexive':\n for (const x of xs) if (!has(x, x)) return fails(x)\n return HOLDS\n case 'irreflexive':\n for (const x of xs) if (has(x, x)) return fails(x)\n return HOLDS\n case 'symmetric':\n for (const x of xs) for (const y of xs) if (has(x, y) && !has(y, x)) return fails(x, y)\n return HOLDS\n case 'transitive':\n for (const x of xs) for (const y of xs) for (const z of xs) if (has(x, y) && has(y, z) && !has(x, z)) return fails(x, y, z)\n return HOLDS\n case 'euclidean':\n for (const x of xs) for (const y of xs) for (const z of xs) if (has(x, y) && has(x, z) && !has(y, z)) return fails(x, y, z)\n return HOLDS\n }\n}\n","import type { RelationCheck } from '../../logic/relations.ts'\nimport { checkRelation } from '../../logic/relations.ts'\nimport { ModalError, modalProblem } from './errors.ts'\nimport type { Formula } from './formula.ts'\nimport { atomsOf, parseFormula } from './formula.ts'\nimport type { Frame } from './model.ts'\nimport { accessPairs } from './model.ts'\n\n/**\n * Frame conditions and the axioms they correspond to (Garson, pp. 112–113): an axiom is valid on a\n * frame (true at every world under every assignment) exactly when the frame meets its condition.\n */\n\nexport type FrameCondition = 'serial' | 'reflexive' | 'transitive' | 'symmetric' | 'euclidean'\n\n/** The axioms the first phase shows. Garson's M is the T of most texts. */\nexport type AxiomName = 'K' | 'D' | 'M' | '4' | 'B' | '5'\n\nexport interface AxiomInfo {\n readonly name: AxiomName\n /** The axiom in the authoring syntax. */\n readonly source: string\n readonly formula: Formula\n /** The frame condition it corresponds to; K has none: it is valid on every frame. */\n readonly condition: FrameCondition | undefined\n}\n\nconst axiom = (name: AxiomName, source: string, condition: FrameCondition | undefined): AxiomInfo => ({ name, source, formula: parseFormula(source), condition })\n\nexport const AXIOMS: Readonly<Record<AxiomName, AxiomInfo>> = {\n K: axiom('K', '[](p -> q) -> ([]p -> []q)', undefined),\n D: axiom('D', '[]p -> <>p', 'serial'),\n M: axiom('M', '[]p -> p', 'reflexive'),\n '4': axiom('4', '[]p -> [][]p', 'transitive'),\n B: axiom('B', 'p -> []<>p', 'symmetric'),\n '5': axiom('5', '<>p -> []<>p', 'euclidean'),\n}\n\n/** The conditions in the order the components list them, with their axioms. */\nexport const CONDITION_AXIOM: Readonly<Record<FrameCondition, AxiomName>> = { serial: 'D', reflexive: 'M', transitive: '4', symmetric: 'B', euclidean: '5' }\nexport const FRAME_CONDITIONS: readonly FrameCondition[] = ['serial', 'reflexive', 'transitive', 'symmetric', 'euclidean']\n\n/**\n * Whether the frame's R meets `condition`. A failure names the worlds that break it: serial and\n * reflexive one world w; symmetric (w, v) with wRv, not vRw; transitive (w, v, u) with wRv, vRu,\n * not wRu; euclidean (w, v, u) with wRv, wRu, not vRu.\n */\nexport function checkCondition(frame: Frame, condition: FrameCondition): RelationCheck {\n return checkRelation({ elements: frame.worlds, pairs: accessPairs(frame) }, condition)\n}\n\n/** Assignments `validOnFrame` enumerates at most: 2^16, e.g. two atoms on eight worlds. */\nexport const MAX_ASSIGNMENTS = 65_536\n\n/** A failed axiom instance: the assignment (each atom with the worlds where it is true) and the world where the formula is false. */\nexport interface FrameCounterexample {\n readonly world: string\n readonly trueAt: Readonly<Record<string, readonly string[]>>\n}\n\nexport type FrameValidity = { readonly valid: true } | { readonly valid: false; readonly counterexample: FrameCounterexample }\n\n/** Truth sets as bit masks over the frame's worlds: fast enough to try every assignment. */\nfunction compileFrame(frame: Frame): { readonly n: number; readonly all: number; readonly succ: readonly number[] } {\n const n = frame.worlds.length\n const index = new Map(frame.worlds.map((w, i) => [w, i]))\n const succ = frame.worlds.map((w) => (frame.access[w] ?? []).reduce((m, v) => m | (1 << (index.get(v) as number)), 0))\n return { n, all: n === 0 ? 0 : (2 ** n - 1) | 0, succ }\n}\n\nfunction maskOf(f: Formula, atoms: ReadonlyMap<string, number>, c: ReturnType<typeof compileFrame>): number {\n switch (f.kind) {\n case 'atom':\n return atoms.get(f.id) as number\n case 'top':\n return c.all\n case 'bot':\n return 0\n case 'not':\n return c.all & ~maskOf(f.arg, atoms, c)\n case 'and':\n return maskOf(f.left, atoms, c) & maskOf(f.right, atoms, c)\n case 'or':\n return maskOf(f.left, atoms, c) | maskOf(f.right, atoms, c)\n case 'imp':\n return (c.all & ~maskOf(f.left, atoms, c)) | maskOf(f.right, atoms, c)\n case 'iff':\n return c.all & ~(maskOf(f.left, atoms, c) ^ maskOf(f.right, atoms, c))\n case 'box': {\n const a = maskOf(f.arg, atoms, c)\n let out = 0\n for (let i = 0; i < c.n; i += 1) if (((c.succ[i] as number) & ~a) === 0) out |= 1 << i\n return out\n }\n case 'dia': {\n const a = maskOf(f.arg, atoms, c)\n let out = 0\n for (let i = 0; i < c.n; i += 1) if (((c.succ[i] as number) & a) !== 0) out |= 1 << i\n return out\n }\n case 'cf':\n return 0\n }\n}\n\n/**\n * Whether `formula` is valid on the frame: true at every world under every assignment of its atoms.\n * Tries all (2^|W|)^atoms assignments, at most {@link MAX_ASSIGNMENTS}; a failure returns the first\n * assignment and world that falsify it.\n */\nexport function validOnFrame(frame: Frame, formula: Formula): FrameValidity {\n if (JSON.stringify(formula).includes('\"kind\":\"cf\"')) throw new ModalError(modalProblem('no-sphere-system', { world: frame.worlds[0] as string }))\n const atoms = atomsOf(formula)\n const c = compileFrame(frame)\n const count = 2 ** (c.n * atoms.length)\n if (count > MAX_ASSIGNMENTS) throw new ModalError(modalProblem('too-many-assignments', { count, limit: MAX_ASSIGNMENTS }))\n const subsets = 2 ** c.n\n const masks = new Map<string, number>()\n for (let code = 0; code < count; code += 1) {\n let rest = code\n for (const a of atoms) {\n masks.set(a, rest % subsets)\n rest = Math.floor(rest / subsets)\n }\n const value = maskOf(formula, masks, c)\n if (value !== c.all) {\n const i = frame.worlds.findIndex((_, k) => (value & (1 << k)) === 0)\n const trueAt = Object.fromEntries(atoms.map((a) => [a, frame.worlds.filter((_, k) => ((masks.get(a) as number) & (1 << k)) !== 0)]))\n return { valid: false, counterexample: { world: frame.worlds[i] as string, trueAt } }\n }\n }\n return { valid: true }\n}\n\n/** The normal systems whose frame classes the first phase names. */\nexport type ModalSystem = 'K' | 'D' | 'M' | 'S4' | 'B' | 'S5'\n\n/** Each system with the conditions that define its frames (Garson, pp. 112–113). */\nexport const SYSTEM_CONDITIONS: Readonly<Record<ModalSystem, readonly FrameCondition[]>> = {\n K: [],\n D: ['serial'],\n M: ['reflexive'],\n S4: ['reflexive', 'transitive'],\n B: ['reflexive', 'symmetric'],\n S5: ['reflexive', 'symmetric', 'transitive'],\n}\n\nexport const SYSTEMS: readonly ModalSystem[] = ['K', 'D', 'M', 'S4', 'B', 'S5']\n\n/** The systems whose frame class contains this frame: every theorem of each is valid on it. */\nexport function systemsOf(frame: Frame): ModalSystem[] {\n const met = new Set(FRAME_CONDITIONS.filter((c) => checkCondition(frame, c).holds))\n return SYSTEMS.filter((s) => SYSTEM_CONDITIONS[s].every((c) => met.has(c)))\n}\n","import { useMemo, useState } from 'react'\nimport { NoIcon, OkIcon } from '../../components/shared/parts.tsx'\nimport type { RelationCheck } from '../../logic/relations.ts'\nimport type { FrameCondition, FrameValidity } from '../engine/frames.ts'\nimport { AXIOMS, CONDITION_AXIOM, FRAME_CONDITIONS, checkCondition, systemsOf, validOnFrame } from '../engine/frames.ts'\nimport { frameOfDoc } from '../data/load.ts'\nimport type { FrameDoc, KripkeDoc } from '../data/schema.ts'\nimport { useModalMessages } from '../i18n/messages.ts'\nimport { docGraphInput, namesOf, worldNames } from './doc-graph.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { FormulaMath, ModalProblems, ModalRoot } from './parts.tsx'\nimport { useModalDoc } from './use-doc.ts'\nimport { layoutWorldGraph } from './world-graph.ts'\nimport type { WorldMark } from './WorldGraph.tsx'\nimport { WorldGraph } from './WorldGraph.tsx'\n\nexport interface FrameConditionsProps extends ModalCommonProps {\n /** A `frame` document, or a `kripke` one whose valuation is ignored (JSON text or value). */\n readonly frame: ModalModelInput\n /** The conditions to list, in this order; default serial, reflexive, transitive, symmetric, euclidean. */\n readonly conditions?: readonly FrameCondition[]\n /** Show each condition's axiom and whether it is valid on the frame; default true. */\n readonly axioms?: boolean\n /** Name the systems whose frame class holds the frame; default true. */\n readonly systems?: boolean\n /** The condition picked first; its counterexample is marked in the picture. */\n readonly initial?: FrameCondition\n}\n\n/**\n * A frame's conditions beside their axioms: whether R is serial, reflexive, transitive, symmetric and\n * euclidean, each failure with the worlds that break it, and whether D, M, 4, B and 5 are valid on the\n * frame, each failure with the assignment and world that falsify it. The two columns always agree.\n */\nexport function FrameConditions(props: FrameConditionsProps) {\n return (\n <ModalRoot locale={props.locale} name=\"frame\" caption={props.caption}>\n <FrameBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['frame', 'kripke'] as const\n\nfunction FrameBody(props: FrameConditionsProps) {\n const loaded = useModalDoc(props.frame, KINDS)\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n return <FrameLoaded {...props} doc={loaded.doc} />\n}\n\ninterface Row {\n readonly condition: FrameCondition\n readonly check: RelationCheck\n readonly validity: FrameValidity\n}\n\nfunction FrameLoaded(props: FrameConditionsProps & { readonly doc: FrameDoc | KripkeDoc }) {\n const { doc, notation = 'modern', axioms = true, systems = true } = props\n const t = useModalMessages()\n const conditions = props.conditions ?? FRAME_CONDITIONS\n const frame = useMemo(() => frameOfDoc(doc), [doc])\n const rows: Row[] = useMemo(\n () => conditions.map((condition) => ({ condition, check: checkCondition(frame, condition), validity: validOnFrame(frame, AXIOMS[CONDITION_AXIOM[condition]].formula) })),\n [frame, conditions],\n )\n const [focus, setFocus] = useState<FrameCondition | undefined>(props.initial)\n const names = worldNames(doc, t.locale)\n const layout = useMemo(() => layoutWorldGraph(docGraphInput({ ...doc, kind: 'frame' } as FrameDoc, t.locale, { showFalse: false, notation, mergeSymmetric: true })), [doc, t.locale, notation])\n const focused = rows.find((r) => r.condition === focus)\n const marks = new Map<string, WorldMark>()\n if (focused !== undefined && !focused.check.holds) for (const w of focused.check.witness) marks.set(w, 'counter')\n const name = (id: string) => names.get(id) ?? id\n return (\n <div className=\"ca-modal-stack\">\n <div className=\"ca-modal-figure\">\n <WorldGraph layout={layout} label={t.worldGraph(doc.worlds.length)} marks={marks} worldLabel={(id) => name(id)} />\n </div>\n <div className=\"ca-modal-side\">\n <div className=\"ca-modal-scroll\">\n <table className=\"ca-modal-table ca-modal-conditions\">\n <thead>\n <tr>\n <th scope=\"col\">{t.conditionHeading}</th>\n <th scope=\"col\">{t.holdsHeading}</th>\n {axioms && <th scope=\"col\">{t.axiomHeading}</th>}\n {axioms && <th scope=\"col\">{t.validHeading}</th>}\n </tr>\n </thead>\n <tbody>\n {rows.map((r) => {\n const axiom = AXIOMS[CONDITION_AXIOM[r.condition]]\n return (\n <tr key={r.condition} data-condition={r.condition} data-selected={r.condition === focus ? 'true' : undefined} data-holds={r.check.holds ? 'true' : 'false'}>\n <th scope=\"row\">\n <button type=\"button\" className=\"ca-modal-pick\" aria-pressed={r.condition === focus} onClick={() => setFocus(r.condition === focus ? undefined : r.condition)}>\n {t.conditionName[r.condition]}\n </button>\n <span className=\"ca-modal-rule ca-small ca-muted\">{t.conditionRule[r.condition]}</span>\n </th>\n <td>\n <Verdict ok={r.check.holds} text={r.check.holds ? t.yes : t.conditionWitness(r.condition, namesOf(names, r.check.witness))} />\n </td>\n {axioms && (\n <td>\n <span className=\"ca-modal-axiom\">{t.axiomName(axiom.name)}</span> <FormulaMath formula={axiom.formula} notation={notation} />\n </td>\n )}\n {axioms && (\n <td>\n <Verdict\n ok={r.validity.valid}\n text={\n r.validity.valid\n ? t.yes\n : t.axiomCounterexample(\n Object.fromEntries(Object.entries(r.validity.counterexample.trueAt).map(([a, ws]) => [a, namesOf(names, ws)])),\n name(r.validity.counterexample.world),\n )\n }\n />\n </td>\n )}\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n {systems && <p className=\"ca-modal-systems\">{t.systemsLine(systemsOf(frame).map((s) => t.systemName(s)))}</p>}\n </div>\n </div>\n )\n}\n\nfunction Verdict({ ok, text }: { readonly ok: boolean; readonly text: string }) {\n return (\n <span className=\"ca-modal-verdict\" data-ok={ok ? 'true' : 'false'}>\n {ok ? <OkIcon size={16} /> : <NoIcon size={16} />} <span>{text}</span>\n </span>\n )\n}\n","import { useMemo, useState } from 'react'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport { F } from '../engine/formula.ts'\nimport { modelOfDoc, startWorld } from '../data/load.ts'\nimport type { KripkeDoc } from '../data/schema.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { docGraphInput, namesOf, worldNames } from './doc-graph.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark } from './parts.tsx'\nimport { parseAll, unknownAtomProblem, useModalDoc } from './use-doc.ts'\nimport { layoutWorldGraph } from './world-graph.ts'\nimport type { WorldMark } from './WorldGraph.tsx'\nimport { WorldGraph } from './WorldGraph.tsx'\n\nexport interface StrictImplicationProps extends ModalCommonProps {\n /** A `kripke` document (JSON text or value). */\n readonly model: ModalModelInput\n readonly antecedent: string\n readonly consequent: string\n /** The world selected first; default the document's `actual`. */\n readonly world?: string\n}\n\n/**\n * The material conditional A ⊃ B beside the strict one □(A ⊃ B) on one model: the material one asks\n * only about the selected world, the strict one about every world it sees, and the picture marks the\n * accessible worlds where A is true and B false.\n */\nexport function StrictImplication(props: StrictImplicationProps) {\n return (\n <ModalRoot locale={props.locale} name=\"strict\" caption={props.caption}>\n <StrictBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['kripke'] as const\n\nfunction StrictBody(props: StrictImplicationProps) {\n const t = useModalMessages()\n const loaded = useModalDoc(props.model, KINDS)\n const [a, b] = useMemo(() => parseAll([props.antecedent, props.consequent]), [props.antecedent, props.consequent])\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n for (const f of [a, b]) {\n if (f !== undefined && !f.ok) {\n return (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(f.error, t)}\n </p>\n )\n }\n }\n if (a?.ok !== true || b?.ok !== true) return null\n const missing = unknownAtomProblem([a.formula, b.formula], loaded.doc.atoms.map((x) => x.id))\n if (missing !== undefined) return <ModalProblems problems={[missing]} />\n return <StrictLoaded {...props} doc={loaded.doc} a={a.formula} b={b.formula} />\n}\n\nfunction StrictLoaded(props: StrictImplicationProps & { readonly doc: KripkeDoc; readonly a: Formula; readonly b: Formula }) {\n const { doc, a, b, notation = 'modern' } = props\n const t = useModalMessages()\n const ev = useMemo(() => new ModalEvaluator(modelOfDoc(doc)), [doc])\n const [world, setWorld] = useState(() => (props.world !== undefined && doc.worlds.some((w) => w.id === props.world) ? props.world : startWorld(doc)))\n const names = worldNames(doc, t.locale)\n const name = (id: string) => names.get(id) ?? id\n const layout = useMemo(() => layoutWorldGraph(docGraphInput(doc, t.locale, { showFalse: true, notation, mergeSymmetric: true })), [doc, t.locale, notation])\n const material = F.imp(a, b)\n const strict = F.strict(a, b)\n let seen: readonly string[] = []\n let problem: string | undefined\n try {\n seen = ev.accessible(world)\n } catch (error) {\n problem = modalErrorMessage(error, t)\n }\n const bad = seen.filter((v) => ev.holds(a, v) && !ev.holds(b, v))\n const marks = new Map<string, WorldMark>(seen.map((v) => [v, bad.includes(v) ? 'counter' : 'true']))\n const materialValue = ev.holds(material, world)\n const strictValue = bad.length === 0\n return (\n <div className=\"ca-modal-split\">\n <div className=\"ca-modal-figure\">\n <WorldGraph\n layout={layout}\n label={t.worldGraph(doc.worlds.length)}\n selected={world}\n marks={marks}\n worldLabel={(id) => `${t.selectWorld(name(id))}. ${t.worldState(name(id), doc.worlds.find((w) => w.id === id)?.true ?? [])}`}\n onSelect={setWorld}\n />\n </div>\n <div className=\"ca-modal-side\">\n <p className=\"ca-modal-at ca-h3\">{t.at(name(world))}</p>\n <dl className=\"ca-modal-pair\">\n <div data-kind=\"material\">\n <dt>{t.materialHeading}</dt>\n <dd>\n <FormulaMath formula={material} notation={notation} /> <TruthMark value={materialValue} />\n <p className=\"ca-small\">{materialValue ? t.materialTrue(name(world), !ev.holds(a, world)) : t.materialFalse(name(world))}</p>\n </dd>\n </div>\n <div data-kind=\"strict\">\n <dt>{t.strictHeading}</dt>\n <dd>\n <FormulaMath formula={strict} notation={notation} /> <TruthMark value={strictValue} />\n <p className=\"ca-small\">{strictValue ? t.strictTrue(name(world)) : t.strictFalse(name(world), namesOf(names, bad))}</p>\n </dd>\n </div>\n </dl>\n {problem !== undefined && (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {problem}\n </p>\n )}\n <div className=\"ca-modal-scroll\">\n <table className=\"ca-modal-table\">\n <thead>\n <tr>\n <th scope=\"col\">{t.world}</th>\n <th scope=\"col\">\n <FormulaMath formula={a} notation={notation} />\n </th>\n <th scope=\"col\">\n <FormulaMath formula={b} notation={notation} />\n </th>\n <th scope=\"col\">\n <FormulaMath formula={material} notation={notation} />\n </th>\n </tr>\n </thead>\n <tbody>\n {doc.worlds.map((w) => (\n <tr key={w.id} data-selected={w.id === world ? 'true' : undefined} data-seen={seen.includes(w.id) ? 'true' : undefined}>\n <th scope=\"row\">{name(w.id)}</th>\n <td>\n <TruthMark value={ev.holds(a, w.id)} />\n </td>\n <td>\n <TruthMark value={ev.holds(b, w.id)} />\n </td>\n <td>\n <TruthMark value={ev.holds(material, w.id)} />\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n <AtomLegend atoms={doc.atoms} />\n </div>\n </div>\n )\n}\n","import type { EvalOptions } from './evaluate.ts'\nimport { ModalEvaluator } from './evaluate.ts'\nimport type { Formula } from './formula.ts'\nimport { F } from './formula.ts'\nimport type { ModalModel } from './model.ts'\n\n/**\n * The three inferences that hold for strict implication and fail for counterfactuals (Garson §20.5):\n * transitivity, contraposition and strengthening the antecedent, written with `>` or with the strict\n * conditional □(A ⊃ B), and checked world by world.\n */\n\nexport type TcsPattern = 'transitivity' | 'contraposition' | 'strengthening'\n\nexport const TCS_PATTERNS: readonly TcsPattern[] = ['transitivity', 'contraposition', 'strengthening']\n\n/** Which conditional an inference is written with. */\nexport type ConditionalKind = 'counterfactual' | 'strict'\n\nexport interface Inference {\n readonly premises: readonly Formula[]\n readonly conclusion: Formula\n}\n\n/** ¬f, writing ¬¬g as g (equivalent, and how the contrapositive is read aloud). */\nfunction negate(f: Formula): Formula {\n return f.kind === 'not' ? f.arg : F.not(f)\n}\n\n/**\n * The inference `pattern` with the conditional `kind`, on formulas a, b and c:\n * transitivity a→b, b→c ∴ a→c; contraposition a→b ∴ ¬b→¬a (a negated formula loses its ¬ instead\n * of gaining a second); strengthening a→b ∴ (a ∧ c)→b.\n * `c` is needed for transitivity and strengthening.\n */\nexport function tcsInference(pattern: TcsPattern, kind: ConditionalKind, a: Formula, b: Formula, c?: Formula): Inference {\n const to = kind === 'strict' ? F.strict : F.cf\n const third = c ?? b\n switch (pattern) {\n case 'transitivity':\n return { premises: [to(a, b), to(b, third)], conclusion: to(a, third) }\n case 'contraposition':\n return { premises: [to(a, b)], conclusion: to(negate(b), negate(a)) }\n case 'strengthening':\n return { premises: [to(a, b)], conclusion: to(F.and(a, third), b) }\n }\n}\n\n/** An inference at one world: the premises' values, the conclusion's, and whether this world is a counterexample. */\nexport interface InferenceAt {\n readonly world: string\n readonly premises: readonly boolean[]\n readonly conclusion: boolean\n /** Every premise true and the conclusion false. */\n readonly counterexample: boolean\n}\n\nexport function checkInferenceAt(model: ModalModel, inference: Inference, world: string, options?: EvalOptions): InferenceAt {\n const ev = new ModalEvaluator(model, options)\n const premises = inference.premises.map((p) => ev.holds(p, world))\n const conclusion = ev.holds(inference.conclusion, world)\n return { world, premises, conclusion, counterexample: premises.every(Boolean) && !conclusion }\n}\n\n/** The inference at every world of `worlds` (default: every world with a system of spheres, or every world). */\nexport function checkInference(model: ModalModel, inference: Inference, options?: EvalOptions & { readonly worlds?: readonly string[] }): InferenceAt[] {\n const worlds = options?.worlds ?? (model.spheres === undefined ? model.worlds : model.worlds.filter((w) => model.spheres?.[w] !== undefined))\n return worlds.map((w) => checkInferenceAt(model, inference, w, options))\n}\n","import type { Box, Placed } from '../../components/graph/graph-labels.ts'\nimport { around, firstClear, textBox } from '../../components/graph/graph-labels.ts'\nimport { textWidth } from '../../components/text/text-measure.ts'\n\n/**\n * The geometry of a system of spheres around one world: concentric circles, innermost first, each\n * world drawn as a dot in the ring between the smallest sphere holding it and the one inside, with its\n * name and true atoms beside it where no other dot or label sits. Pure; no DOM.\n */\n\nexport interface SphereWorld {\n readonly id: string\n readonly name: string\n /** A second, smaller line: the atoms true there. */\n readonly detail: string\n}\n\nexport interface PlacedSphereWorld extends SphereWorld {\n readonly x: number\n readonly y: number\n /** Index of the smallest sphere holding it. */\n readonly ring: number\n readonly label: Placed\n readonly detailAt: { readonly x: number; readonly y: number }\n}\n\nexport interface SphereLayout {\n readonly radii: readonly number[]\n readonly worlds: readonly PlacedSphereWorld[]\n readonly sphereLabels: readonly { readonly x: number; readonly y: number }[]\n readonly viewBox: string\n readonly width: number\n}\n\nconst DOT = 6\nconst NAME = 13\nconst DETAIL = 11\nconst GAP = 58\nconst MARGIN = 12\n\nexport function layoutSpheres(spheres: readonly (readonly string[])[], center: string, worlds: readonly SphereWorld[]): SphereLayout {\n const innerAlone = spheres[0]?.length === 1 && spheres[0][0] === center\n const r0 = innerAlone ? 24 : 52\n // Many spheres (a similarity with many distances) sit closer together.\n const gap = spheres.length > 4 ? Math.max(34, GAP - (spheres.length - 4) * 6) : GAP\n const radii = spheres.map((_, i) => r0 + i * gap)\n const ringOf = (id: string): number => spheres.findIndex((s) => s.includes(id))\n const byId = new Map(worlds.map((w) => [w.id, w]))\n const placed: { w: SphereWorld; x: number; y: number; ring: number }[] = []\n const push = (id: string, r: number, a: number, ring: number): void => {\n const w = byId.get(id)\n if (w !== undefined) placed.push({ w, x: r * Math.cos(a), y: r * Math.sin(a), ring })\n }\n spheres.forEach((s, i) => {\n const fresh = s.filter((id) => ringOf(id) === i)\n if (i === 0) {\n if (fresh.includes(center)) push(center, 0, 0, 0)\n const rest = fresh.filter((id) => id !== center)\n rest.forEach((id, k) => push(id, r0 * 0.6, -Math.PI / 2 + (2 * Math.PI * k) / rest.length, 0))\n return\n }\n const r = ((radii[i - 1] as number) + (radii[i] as number)) / 2\n fresh.forEach((id, k) => push(id, r, -Math.PI / 2 + i * 0.55 + (2 * Math.PI * k) / fresh.length, i))\n })\n const obstacles: Box[] = placed.map((p) => around(p.x, p.y, DOT + 1))\n const out: PlacedSphereWorld[] = placed.map((p) => {\n const width = Math.max(textWidth(p.w.name, NAME), textWidth(p.w.detail, DETAIL))\n const tall = p.w.detail === '' ? NAME : NAME + DETAIL + 3\n const make = (x: number, y: number, anchor: 'start' | 'middle' | 'end'): Placed => ({\n x,\n y,\n anchor,\n box: { ...textBox(x, y, anchor, width, NAME), y1: y + tall - NAME + NAME * 0.25 },\n })\n const label = firstClear(\n [make(p.x + DOT + 4, p.y + 4, 'start'), make(p.x - DOT - 4, p.y + 4, 'end'), make(p.x, p.y - DOT - 6 - (tall - NAME), 'middle'), make(p.x, p.y + DOT + NAME + 2, 'middle')],\n obstacles,\n )\n obstacles.push(label.box)\n return { ...p.w, x: p.x, y: p.y, ring: p.ring, label, detailAt: { x: label.x, y: label.y + DETAIL + 3 } }\n })\n const outer = radii[radii.length - 1] ?? r0\n const sphereLabels = radii.map((r) => ({ x: r * Math.cos(-Math.PI / 4) + 3, y: r * Math.sin(-Math.PI / 4) - 3 }))\n const boxes = [...obstacles, { x0: -outer, y0: -outer, x1: outer, y1: outer }, ...sphereLabels.map((l) => textBox(l.x, l.y, 'start', 22, 12))]\n const x0 = Math.min(...boxes.map((b) => b.x0)) - MARGIN\n const y0 = Math.min(...boxes.map((b) => b.y0)) - MARGIN\n const x1 = Math.max(...boxes.map((b) => b.x1)) + MARGIN\n const y1 = Math.max(...boxes.map((b) => b.y1)) + MARGIN\n const f = (v: number) => Math.round(v * 10) / 10\n return { radii, worlds: out, sphereLabels, viewBox: `${f(x0)} ${f(y0)} ${f(x1 - x0)} ${f(y1 - y0)}`, width: Math.round(x1 - x0) }\n}\n","import type { KeyboardEvent } from 'react'\nimport { sub } from '../../components/text/svg-text.tsx'\nimport type { SphereLayout } from './sphere-graph.ts'\n\n/** A world's part in a counterfactual: an antecedent world, one of the closest, one where the consequent fails. */\nexport type SphereMark = 'antecedent' | 'selected' | 'counter'\n\nexport interface SphereDiagramProps {\n readonly layout: SphereLayout\n readonly label: string\n readonly center: string\n readonly marks?: ReadonlyMap<string, SphereMark>\n /** The sphere drawn strong: the smallest holding an antecedent world. */\n readonly sphere?: number\n readonly sphereName: (i: number) => string\n readonly worldLabel: (id: string) => string\n readonly onSelect?: (id: string) => void\n}\n\n/** Concentric spheres around a world, with the worlds in their rings. */\nexport function SphereDiagram({ layout, label, center, marks, sphere, sphereName, worldLabel, onSelect }: SphereDiagramProps) {\n const key = (id: string) => (e: KeyboardEvent<SVGGElement>) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n onSelect?.(id)\n }\n }\n return (\n <svg className=\"ca-modal-spheres\" viewBox={layout.viewBox} width={layout.width} role=\"group\" aria-label={label}>\n <g aria-hidden=\"true\">\n {[...layout.radii].reverse().map((r, k) => {\n const i = layout.radii.length - 1 - k\n return <circle key={i} r={r} className=\"ca-modal-sphere\" data-sphere={i} data-active={i === sphere ? 'true' : undefined} />\n })}\n {layout.sphereLabels.map((l, i) => (\n <text key={i} x={l.x} y={l.y} className=\"ca-modal-sphere-name\" data-active={i === sphere ? 'true' : undefined}>\n {sphereName(i)}\n </text>\n ))}\n </g>\n {layout.worlds.map((w) => (\n <g\n key={w.id}\n className=\"ca-modal-dot\"\n data-world={w.id}\n data-mark={marks?.get(w.id)}\n data-center={w.id === center ? 'true' : undefined}\n role={onSelect === undefined ? 'img' : 'button'}\n tabIndex={onSelect === undefined ? undefined : 0}\n aria-label={worldLabel(w.id)}\n onClick={onSelect === undefined ? undefined : () => onSelect(w.id)}\n onKeyDown={onSelect === undefined ? undefined : key(w.id)}\n >\n <circle cx={w.x} cy={w.y} r={6} />\n <text x={w.label.x} y={w.label.y} textAnchor={w.label.anchor} className=\"ca-modal-name\">\n {sub(w.name)}\n </text>\n {w.detail !== '' && (\n <text x={w.detailAt.x} y={w.detailAt.y} textAnchor={w.label.anchor} className=\"ca-modal-detail\">\n {w.detail}\n </text>\n )}\n </g>\n ))}\n </svg>\n )\n}\n","import { useMemo, useState } from 'react'\nimport type { Formula } from '../engine/formula.ts'\nimport type { Inference, InferenceAt, TcsPattern } from '../engine/inference.ts'\nimport { checkInferenceAt, tcsInference } from '../engine/inference.ts'\nimport type { ModalModel } from '../engine/model.ts'\nimport { collapseSpheres } from '../engine/model.ts'\nimport type { ModalNotation } from '../engine/print.ts'\nimport { modalText, modelOfDoc, startWorld } from '../data/load.ts'\nimport type { ModalText, SpheresDoc } from '../data/schema.ts'\nimport type { ModalMessages } from '../i18n/messages.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { worldNames } from './doc-graph.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark } from './parts.tsx'\nimport { layoutSpheres } from './sphere-graph.ts'\nimport { sphereWorlds } from './sphere-view-model.ts'\nimport { SphereDiagram } from './SphereDiagram.tsx'\nimport { parseAll, unknownAtomProblem, useModalDoc } from './use-doc.ts'\n\n/** One inference to check: its pattern, the spheres model and the formulas A, B (and C for transitivity and strengthening). */\nexport interface TcsItem {\n readonly pattern: TcsPattern\n readonly model: ModalModelInput\n readonly a: string\n readonly b: string\n readonly c?: string\n /** A heading for the example; default the document's title. */\n readonly title?: ModalText\n}\n\nexport interface TcsCheckProps extends ModalCommonProps {\n readonly items: readonly TcsItem[]\n /** Show the strict-implication column; default true. */\n readonly showStrict?: boolean\n /** Start with the spheres pressed into one; default false. */\n readonly collapsed?: boolean\n}\n\n/**\n * Transitivity, contraposition and strengthening the antecedent, each on its own spheres model:\n * with strict implication the inference holds; with the counterfactual on spheres a counterexample\n * appears at the centre. Pressing the spheres into one makes the counterfactual strict, and the\n * counterexample goes away.\n */\nexport function TcsCheck(props: TcsCheckProps) {\n return (\n <ModalRoot locale={props.locale} name=\"tcs\" caption={props.caption}>\n <TcsBody {...props} />\n </ModalRoot>\n )\n}\n\nfunction TcsBody({ items, showStrict = true, collapsed: initial = false, notation = 'modern' }: TcsCheckProps) {\n const t = useModalMessages()\n const [collapsed, setCollapsed] = useState(initial)\n return (\n <>\n <label className=\"ca-modal-check\">\n <input type=\"checkbox\" checked={collapsed} onChange={(e) => setCollapsed(e.currentTarget.checked)} /> {t.collapse}\n </label>\n <p className=\"ca-small ca-muted\">{t.collapseHint}</p>\n <div className=\"ca-modal-cards\">\n {items.map((item, i) => (\n <TcsCard key={`${item.pattern}-${i}`} item={item} showStrict={showStrict} collapsed={collapsed} notation={notation} />\n ))}\n </div>\n </>\n )\n}\n\nconst KINDS = ['spheres'] as const\n\nfunction TcsCard({ item, showStrict, collapsed, notation }: { readonly item: TcsItem; readonly showStrict: boolean; readonly collapsed: boolean; readonly notation: Exclude<ModalNotation, 'ascii'> }) {\n const t = useModalMessages()\n const loaded = useModalDoc(item.model, KINDS)\n const parsed = useMemo(() => parseAll(item.c === undefined ? [item.a, item.b] : [item.a, item.b, item.c]), [item.a, item.b, item.c])\n const title = modalText(item.title ?? (loaded.ok ? loaded.doc.title : undefined), t.locale)\n const heading = <h3 className=\"ca-h3\">{title === undefined ? t.patternName[item.pattern] : t.exampleTitle(t.patternName[item.pattern], title)}</h3>\n if (!loaded.ok) {\n return (\n <section className=\"ca-modal-card\" data-pattern={item.pattern}>\n {heading}\n <ModalProblems problems={loaded.errors} />\n </section>\n )\n }\n const bad = parsed.find((p) => !p.ok)\n if (bad !== undefined && !bad.ok) {\n return (\n <section className=\"ca-modal-card\" data-pattern={item.pattern}>\n {heading}\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(bad.error, t)}\n </p>\n </section>\n )\n }\n const [a, b, c] = parsed.map((p) => (p.ok ? p.formula : undefined)) as [Formula, Formula, Formula | undefined]\n const missing = unknownAtomProblem([a, b, ...(c === undefined ? [] : [c])], loaded.doc.atoms.map((x) => x.id))\n return (\n <section className=\"ca-modal-card\" data-pattern={item.pattern}>\n {heading}\n {missing !== undefined ? <ModalProblems problems={[missing]} /> : <TcsColumns doc={loaded.doc} pattern={item.pattern} a={a} b={b} c={c} showStrict={showStrict} collapsed={collapsed} notation={notation} t={t} />}\n </section>\n )\n}\n\nfunction TcsColumns(props: {\n readonly doc: SpheresDoc\n readonly pattern: TcsPattern\n readonly a: Formula\n readonly b: Formula\n readonly c: Formula | undefined\n readonly showStrict: boolean\n readonly collapsed: boolean\n readonly notation: Exclude<ModalNotation, 'ascii'>\n readonly t: ModalMessages\n}) {\n const { doc, pattern, a, b, c, showStrict, collapsed, notation, t } = props\n const model = useMemo(() => modelOfDoc(doc), [doc])\n const flat = useMemo(() => collapseSpheres(model), [model])\n const world = startWorld(doc)\n const shown: ModalModel = collapsed ? flat : model\n const layout = useMemo(() => layoutSpheres(shown.spheres?.[world] ?? [], world, sphereWorlds(doc, t.locale)), [shown, world, doc, t.locale])\n const names = worldNames(doc, t.locale)\n const strict = tcsInference(pattern, 'strict', a, b, c)\n const cf = tcsInference(pattern, 'counterfactual', a, b, c)\n return (\n <>\n <SphereDiagram layout={layout} label={t.worldGraph(doc.worlds.length)} center={world} sphereName={t.sphereName} worldLabel={(id) => t.worldState(names.get(id) ?? id, doc.worlds.find((w) => w.id === id)?.true ?? [])} />\n <div className=\"ca-modal-columns\">\n {showStrict && <InferenceColumn heading={t.strictHeading} kind=\"strict\" inference={strict} at={checkInferenceAt(flat, strict, world)} world={names.get(world) ?? world} notation={notation} t={t} />}\n <InferenceColumn heading={t.counterfactualHeading} kind=\"counterfactual\" inference={cf} at={checkInferenceAt(shown, cf, world)} world={names.get(world) ?? world} notation={notation} t={t} />\n </div>\n <AtomLegend atoms={doc.atoms} />\n </>\n )\n}\n\nfunction InferenceColumn(props: {\n readonly heading: string\n readonly kind: 'strict' | 'counterfactual'\n readonly inference: Inference\n readonly at: InferenceAt\n readonly world: string\n readonly notation: Exclude<ModalNotation, 'ascii'>\n readonly t: ModalMessages\n}) {\n const { heading, kind, inference, at, world, notation, t } = props\n const verdict = at.counterexample ? t.inferenceCounterexample(world) : at.premises.every(Boolean) ? t.inferenceHolds(world) : t.inferenceVacuous(world)\n return (\n <div className=\"ca-modal-column\" data-kind={kind} data-counterexample={at.counterexample ? 'true' : 'false'}>\n <h4 className=\"ca-modal-column-head\">{heading}</h4>\n <ol className=\"ca-modal-inference\">\n {inference.premises.map((p, i) => (\n <li key={i}>\n <span className=\"ca-small ca-muted\">{t.premise}</span> <FormulaMath formula={p} notation={notation} /> <TruthMark value={at.premises[i] as boolean} />\n </li>\n ))}\n <li data-conclusion=\"true\">\n <span className=\"ca-small ca-muted\">{t.conclusion}</span> <FormulaMath formula={inference.conclusion} notation={notation} /> <TruthMark value={at.conclusion} />\n </li>\n </ol>\n <p className=\"ca-small\">{verdict}</p>\n </div>\n )\n}\n","import { useMemo, useState } from 'react'\nimport { Segmented } from '../../components/shared/parts.tsx'\nimport { Tex } from '../../components/text/Tex.tsx'\nimport type { ConditionalSemantics } from '../engine/evaluate.ts'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport { formulaLatex } from '../engine/print.ts'\nimport { modelOfDoc, startWorld } from '../data/load.ts'\nimport type { SpheresDoc } from '../data/schema.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { namesOf, worldNames } from './doc-graph.ts'\nimport { valueOrUndefined } from './explain-text.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark, UnknownMark } from './parts.tsx'\nimport { layoutSpheres } from './sphere-graph.ts'\nimport { counterfactualView, sphereWorlds, worldSetLatex } from './sphere-view-model.ts'\nimport type { SphereMark } from './SphereDiagram.tsx'\nimport { SphereDiagram } from './SphereDiagram.tsx'\nimport { parseAll, useModalDoc } from './use-doc.ts'\n\nexport interface SphereViewProps extends ModalCommonProps {\n /** A `spheres` document (JSON text or value). */\n readonly model: ModalModelInput\n /** Formulas to list, replacing the document's; pick an A > B to see its closest antecedent worlds. */\n readonly formulas?: readonly string[]\n /** How `>` is read at first; default `lewis`. */\n readonly semantics?: ConditionalSemantics\n /** Show the Lewis/Stalnaker switch; default true. */\n readonly semanticsSwitch?: boolean\n /** Whose spheres to draw; default the document's centre. */\n readonly world?: string\n}\n\n/**\n * The spheres around a world: pick a counterfactual A > B to see |A|, the smallest sphere holding an\n * A-world, the closest A-worlds f(|A|, w) and the verdict, by Lewis or by Stalnaker.\n */\nexport function SphereView(props: SphereViewProps) {\n return (\n <ModalRoot locale={props.locale} name=\"spheres\" caption={props.caption}>\n <SphereBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['spheres'] as const\n\nfunction SphereBody(props: SphereViewProps) {\n const loaded = useModalDoc(props.model, KINDS)\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n return <SphereLoaded {...props} doc={loaded.doc} />\n}\n\nfunction SphereLoaded(props: SphereViewProps & { readonly doc: SpheresDoc }) {\n const { doc, notation = 'modern', semanticsSwitch = true } = props\n const t = useModalMessages()\n const model = useMemo(() => modelOfDoc(doc), [doc])\n const world = props.world !== undefined && model.spheres?.[props.world] !== undefined ? props.world : startWorld(doc)\n const [semantics, setSemantics] = useState<ConditionalSemantics>(props.semantics ?? 'lewis')\n const formulas = useMemo(() => parseAll(props.formulas ?? doc.formulas ?? []), [props.formulas, doc])\n const [focus, setFocus] = useState(() => Math.max(0, formulas.findIndex((f) => f.ok && f.formula.kind === 'cf')))\n const names = worldNames(doc, t.locale)\n const layout = useMemo(() => layoutSpheres(model.spheres?.[world] ?? [], world, sphereWorlds(doc, t.locale)), [model, world, doc, t.locale])\n const ev = useMemo(() => new ModalEvaluator(model, { semantics }), [model, semantics])\n const focused = formulas[focus]\n const cf = focused?.ok === true && focused.formula.kind === 'cf' ? counterfactualView(model, focused.formula.left, focused.formula.right, world, semantics) : undefined\n let marks: ReadonlyMap<string, SphereMark> | undefined = cf?.marks\n if (cf === undefined && focused?.ok === true) {\n try {\n marks = new Map(ev.truthSet(focused.formula).map((w) => [w, 'antecedent'] as const))\n } catch {\n marks = undefined\n }\n }\n const name = (id: string) => names.get(id) ?? id\n const sphereName = (i: number) => t.sphereName(i)\n return (\n <div className=\"ca-modal-split\">\n <div className=\"ca-modal-figure\">\n <SphereDiagram\n layout={layout}\n label={t.worldGraph(doc.worlds.length)}\n center={world}\n marks={marks}\n sphere={cf?.step.sphere}\n sphereName={sphereName}\n worldLabel={(id) => t.worldState(name(id), doc.worlds.find((w) => w.id === id)?.true ?? [])}\n />\n <ul className=\"ca-modal-legend\" aria-hidden=\"true\">\n <li data-mark=\"antecedent\">{t.antecedentWorlds}</li>\n <li data-mark=\"selected\">{t.closestWorlds}</li>\n </ul>\n </div>\n <div className=\"ca-modal-side\">\n {semanticsSwitch && (\n <Segmented<ConditionalSemantics>\n label={t.semanticsLabel}\n options={[\n { value: 'lewis', label: 'Lewis' },\n { value: 'stalnaker', label: 'Stalnaker' },\n ]}\n value={semantics}\n onChange={setSemantics}\n />\n )}\n <p className=\"ca-modal-at ca-h3\">{t.at(name(world))}</p>\n <ul className=\"ca-modal-formulas\" aria-label={t.formulas}>\n {formulas.map((f, i) => {\n const value = valueOrUndefined(f, ev, world)\n return (\n <li key={`${f.source}-${i}`}>\n <button type=\"button\" className=\"ca-modal-formula\" aria-pressed={i === focus} onClick={() => setFocus(i)}>\n {f.ok ? <FormulaMath formula={f.formula} notation={notation} /> : <code className=\"ca-mono\">{f.source}</code>}\n {value === undefined ? <UnknownMark /> : <TruthMark value={value} />}\n </button>\n </li>\n )\n })}\n </ul>\n {cf !== undefined && focused?.ok === true && focused.formula.kind === 'cf' && (\n <div className=\"ca-modal-explain\" aria-live=\"polite\">\n {cf.step.vacuous ? (\n <p>{t.vacuous}</p>\n ) : (\n <>\n <p>{t.smallestSphere(sphereName(cf.step.sphere as number), namesOf(names, cf.step.selected))}</p>\n <p>\n <Tex\n tex={`f(|${formulaLatex(focused.formula.left, notation)}|, \\\\text{${name(world)}}) = ${worldSetLatex(namesOf(names, cf.step.selected))}`}\n text={`f(|A|, ${name(world)}) = {${namesOf(names, cf.step.selected).join(', ')}}`}\n />\n </p>\n {cf.problem !== undefined ? <p className=\"ca-modal-problem\">{t.notUnique(namesOf(names, cf.step.selected))}</p> : <p>{cf.value === true ? t.cfTrue : t.cfFalse(namesOf(names, cf.step.failures))}</p>}\n </>\n )}\n </div>\n )}\n <AtomLegend atoms={doc.atoms} />\n {focused !== undefined && !focused.ok && (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(focused.error, t)}\n </p>\n )}\n </div>\n </div>\n )\n}\n","import { useId, useMemo, useState } from 'react'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblem } from '../engine/errors.ts'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport { kripkeModel } from '../engine/model.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport type { ModalNotation } from '../engine/print.ts'\nimport { formulaText } from '../engine/print.ts'\nimport { distances } from '../engine/similarity.ts'\nimport type { AtomValues } from '../engine/surgery.ts'\nimport { literalsOf, surgery, worldWith } from '../engine/surgery.ts'\nimport { modelOfDoc, similarityOf, structuralEquations } from '../data/load.ts'\nimport type { SpheresDoc } from '../data/schema.ts'\nimport type { ModalMessages } from '../i18n/messages.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { namesOf, worldNames } from './doc-graph.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark } from './parts.tsx'\nimport { layoutSpheres } from './sphere-graph.ts'\nimport { counterfactualView, sphereWorlds } from './sphere-view-model.ts'\nimport { SphereDiagram } from './SphereDiagram.tsx'\nimport { parseAll, unknownAtomProblem, useModalDoc } from './use-doc.ts'\n\nexport interface SurgeryVsSimilarityProps extends ModalCommonProps {\n /** A `spheres` document with `center`, `similarity` and `structural` equations (JSON text or value). */\n readonly model: ModalModelInput\n /** The antecedent, a conjunction of atoms and negated atoms (`press`); default that of the document's first A > B. */\n readonly antecedent?: string\n /** The consequent; default that of the document's first A > B. */\n readonly consequent?: string\n /** Weights to start from, overriding the document's. */\n readonly weights?: Readonly<Record<string, number>>\n}\n\n/**\n * Fine's Nixon example: on the left Lewis's closest antecedent worlds by a weighted similarity the\n * reader can adjust, on the right Pearl's minimal surgery on the boolean structural equations. Move the\n * weights to see when the two verdicts on A > B part.\n */\nexport function SurgeryVsSimilarity(props: SurgeryVsSimilarityProps) {\n return (\n <ModalRoot locale={props.locale} name=\"surgery\" caption={props.caption}>\n <SurgeryBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['spheres'] as const\n\nfunction firstConditional(doc: SpheresDoc): { a?: string; b?: string } {\n for (const p of parseAll(doc.formulas ?? [])) {\n if (p.ok && p.formula.kind === 'cf') return { a: formulaText(p.formula.left, 'ascii'), b: formulaText(p.formula.right, 'ascii') }\n }\n return {}\n}\n\nfunction SurgeryBody(props: SurgeryVsSimilarityProps) {\n const t = useModalMessages()\n const loaded = useModalDoc(props.model, KINDS)\n const doc = loaded.ok ? loaded.doc : undefined\n const sources = useMemo(() => {\n const fallback = doc === undefined ? {} : firstConditional(doc)\n return [props.antecedent ?? fallback.a ?? '', props.consequent ?? fallback.b ?? '']\n }, [doc, props.antecedent, props.consequent])\n const [a, b] = useMemo(() => parseAll(sources), [sources])\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n if (loaded.doc.center === undefined || loaded.doc.similarity === undefined || loaded.doc.structural === undefined) return <ModalProblems problems={[modalProblem('needs-similarity', {})]} />\n for (const f of [a, b]) {\n if (f !== undefined && !f.ok) {\n return (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(f.error, t)}\n </p>\n )\n }\n }\n if (a?.ok !== true || b?.ok !== true) return null\n const atoms = loaded.doc.atoms.map((x) => x.id)\n const intervention = literalsOf(a.formula)\n const problems: ModalProblem[] = []\n const missing = unknownAtomProblem([a.formula, b.formula], atoms)\n if (missing !== undefined) problems.push(missing)\n if (intervention === undefined) problems.push(modalProblem('surgery-antecedent', { formula: formulaText(a.formula, props.notation ?? 'modern') }))\n if (problems.length > 0 || intervention === undefined) return <ModalProblems problems={problems} />\n return <SurgeryLoaded {...props} doc={loaded.doc} center={loaded.doc.center} a={a.formula} b={b.formula} intervention={intervention} />\n}\n\nfunction SurgeryLoaded(props: SurgeryVsSimilarityProps & { readonly doc: SpheresDoc; readonly center: string; readonly a: Formula; readonly b: Formula; readonly intervention: AtomValues }) {\n const { doc, center, a, b, intervention, notation = 'modern' } = props\n const t = useModalMessages()\n const atoms = doc.atoms.map((x) => x.id)\n const [weights, setWeights] = useState<Readonly<Record<string, number>>>(() => Object.fromEntries(atoms.map((x) => [x, props.weights?.[x] ?? doc.similarity?.weights[x] ?? 1])))\n const [costs, setCosts] = useState<readonly number[]>(() => (doc.similarity?.laws ?? []).map((l) => l.cost))\n const docWithCosts = useMemo(\n () => ({ ...doc, similarity: { weights, laws: (doc.similarity?.laws ?? []).map((l, i) => ({ ...l, cost: costs[i] ?? l.cost })) } }),\n [doc, weights, costs],\n )\n const model = useMemo(() => modelOfDoc(docWithCosts), [docWithCosts])\n const names = worldNames(doc, t.locale)\n const name = (id: string) => names.get(id) ?? id\n const layout = useMemo(() => layoutSpheres(model.spheres?.[center] ?? [], center, sphereWorlds(doc, t.locale)), [model, center, doc, t.locale])\n const view = counterfactualView(model, a, b, center, 'lewis')\n const ds = useMemo(() => [...distances(model, center, similarityOf(docWithCosts))].sort((x, y) => x.distance - y.distance), [model, center, docWithCosts])\n const equations = useMemo(() => structuralEquations(doc), [doc])\n const solved = surgery(atoms, equations, doc.worlds.find((w) => w.id === center)?.true ?? [], intervention)\n const solvedWorld = worldWith(doc.worlds, atoms, solved.values)\n // The consequent in the submodel's one solution.\n const surgeryValue = new ModalEvaluator(kripkeModel({ atoms, worlds: [{ id: 'solution', true: atoms.filter((x) => solved.values[x]) }], access: [] })).holds(b, 'solution')\n return (\n <>\n <div className=\"ca-modal-columns\">\n <section className=\"ca-modal-column\" data-kind=\"similarity\">\n <h3 className=\"ca-modal-column-head\">{t.similarityHeading}</h3>\n <SphereDiagram\n layout={layout}\n label={t.worldGraph(doc.worlds.length)}\n center={center}\n marks={view.marks}\n sphere={view.step.sphere}\n sphereName={t.sphereName}\n worldLabel={(id) => t.worldState(name(id), doc.worlds.find((w) => w.id === id)?.true ?? [])}\n />\n <p>\n <FormulaMath formula={{ kind: 'cf', left: a, right: b }} notation={notation} /> <TruthMark value={view.step.value} />\n </p>\n <p className=\"ca-small\">{view.step.vacuous ? t.vacuous : t.closestList(namesOf(names, view.step.selected))}</p>\n <Weights atoms={atoms} weights={weights} costs={costs} doc={doc} notation={notation} onWeight={(x, v) => setWeights((w) => ({ ...w, [x]: v }))} onCost={(i, v) => setCosts((c) => c.map((old, k) => (k === i ? v : old)))} t={t} />\n <table className=\"ca-modal-table ca-small\">\n <thead>\n <tr>\n <th scope=\"col\">{t.world}</th>\n <th scope=\"col\">{t.distance}</th>\n </tr>\n </thead>\n <tbody>\n {ds.map((d) => (\n <tr key={d.world} data-selected={view.step.selected.includes(d.world) ? 'true' : undefined}>\n <th scope=\"row\">{name(d.world)}</th>\n <td className=\"ca-mono\">{d.distance}</td>\n </tr>\n ))}\n </tbody>\n </table>\n <p className=\"ca-small ca-muted\">{t.approxNote}</p>\n </section>\n <section className=\"ca-modal-column\" data-kind=\"surgery\">\n <h3 className=\"ca-modal-column-head\">{t.surgeryHeading}</h3>\n <h4 className=\"ca-small\">{t.equationsHeading}</h4>\n <ul className=\"ca-modal-equations\">\n {Object.entries(equations).map(([atom, f]) => (\n <li key={atom}>\n <span className=\"ca-mono\">{atom}</span> := <FormulaMath formula={f} notation={notation} />\n </li>\n ))}\n </ul>\n <p className=\"ca-small\">{t.intervention(Object.entries(intervention).map(([x, v]) => `${x} = ${v ? 'T' : 'F'}`).join(', '))}</p>\n <h4 className=\"ca-small\">{t.solution}</h4>\n <ul className=\"ca-modal-solution\">\n {atoms.map((x) => (\n <li key={x} data-set={solved.set.includes(x) ? 'true' : undefined}>\n <span className=\"ca-mono\">{x}</span> <TruthMark value={solved.values[x] === true} />\n </li>\n ))}\n </ul>\n <p className=\"ca-small\">{t.solutionWorld(solvedWorld === undefined ? undefined : name(solvedWorld))}</p>\n <p>\n <FormulaMath formula={b} notation={notation} /> <TruthMark value={surgeryValue} />\n </p>\n </section>\n </div>\n <p className=\"ca-modal-agree\" data-agree={surgeryValue === view.step.value ? 'true' : 'false'} aria-live=\"polite\">\n {surgeryValue === view.step.value ? t.agree : t.diverge}\n </p>\n <AtomLegend atoms={doc.atoms} />\n </>\n )\n}\n\nfunction Weights(props: {\n readonly atoms: readonly string[]\n readonly weights: Readonly<Record<string, number>>\n readonly costs: readonly number[]\n readonly doc: SpheresDoc\n readonly notation: Exclude<ModalNotation, 'ascii'>\n readonly onWeight: (atom: string, value: number) => void\n readonly onCost: (law: number, value: number) => void\n readonly t: ModalMessages\n}) {\n const { atoms, weights, costs, doc, notation, onWeight, onCost, t } = props\n const base = useId()\n const laws = parseAll((doc.similarity?.laws ?? []).map((l) => l.formula))\n return (\n <fieldset className=\"ca-modal-weights\">\n <legend>{t.weightsHeading}</legend>\n {atoms.map((x) => (\n <Slider key={x} id={`${base}-w-${x}`} label={t.weightLabel(x)} value={weights[x] ?? 1} onChange={(v) => onWeight(x, v)} />\n ))}\n {laws.map((law, i) => (\n <Slider key={i} id={`${base}-l-${i}`} label={t.lawLabel(law.ok ? formulaText(law.formula, notation) : law.source)} value={costs[i] ?? 1} onChange={(v) => onCost(i, v)} />\n ))}\n </fieldset>\n )\n}\n\nfunction Slider({ id, label, value, onChange }: { readonly id: string; readonly label: string; readonly value: number; readonly onChange: (v: number) => void }) {\n return (\n <div className=\"ca-modal-slider\">\n <label htmlFor={id}>{label}</label>\n <input id={id} type=\"range\" min={0} max={12} step={0.5} value={value} onChange={(e) => onChange(Number(e.currentTarget.value))} />\n <output htmlFor={id} className=\"ca-mono\">\n {value}\n </output>\n </div>\n )\n}\n"],"mappings":";;;;;;AAGA,SAAgBmB,EAAQ,GAAqB;CAC3C,OAAOH,EAAM,eAAeI,GAAK;EAAE,cAAc;EAAO,QAAQ;EAAQ,QAAQ;EAAU,OAAO;CAAM,CAAC;AAC1G;;ACIA,SAAgBC,EAAI,EAAE,QAAK,WAAkB;CAC3C,OAAO,kBAAC,QAAD;EAAM,WAAU;EAAS,MAAK;EAAO,cAAYC;EAAM,aAAWA;EAAM,YAAUF;EAAK,yBAAyB,EAAE,QAAQD,EAAQC,CAAG,EAAE;CAAI,CAAA;AACpJ;;AC6CA,SAAgBG,EAAyC,GAAS,GAA+B,GAA8B;CAC7H,OAAQC,MAAU,KAAA,IAAY;EAAE;EAAM;CAAO,IAAI;EAAE;EAAM;EAAQ;CAAM;AACzE;AASA,IAAMC,KAAM,MAAsE,gBAAgBC,EAAE,WAAW,EAAE,MAAM,KAAK,UAAUA,EAAE,MAAM,KAEjIC,IAAyC;CACpD,OAAO,GAAO,MAAY,GAAGH,EAAM,IAAII;CACvC,UAAU;EACR,+BAA+B,MAAM,wBAAwBF,EAAE,YAAYD,EAAGC,CAAC;EAC/E,2BAA2B,MAAM,cAAcA,EAAE,QAAQD,EAAGC,CAAC;EAC7D,yBAAyB,MAAM,6BAA6BD,EAAGC,CAAC;EAChE,mBAAmB,MAAM,YAAYA,EAAE,WAAWD,EAAGC,CAAC;EACtD,kBAAkB,MAAM,iBAAiBA,EAAE,UAAU,wCAAwCD,EAAGC,CAAC;EACjG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GACAoB,EAAK,KAAK,GAAK,MACd,kBAAC6X,IAAD;IAAgB,IAAI,GAAGtc,EAAK,KAAKyB;IAAK,OAAOY,EAAE,SAASyC,EAAI,KAAKjE,EAAYiE,EAAI,SAAShE,CAAQ,IAAIgE,EAAI,MAAM;IAAG,OAAO+W,EAAMpa,MAAM;IAAG,WAAW,MAAM+a,EAAO/a,GAAGxD,CAAC;GAAI,GAA5JwD,CAA4J,CAC1K;EACO;;AAEd;AAEA,SAAS6a,GAAO,EAAE,OAAI,UAAO,UAAO,eAA6H;CAC/J,OACE,kBAAC,OAAD;EAAK,WAAU;EAAf,UAAA;GACE,kBAAC,SAAD;IAAO,SAAS1c;IAAK,UAAA8S;GAAa,CAAA;GAClC,kBAAC,SAAD;IAAW;IAAI,MAAK;IAAQ,KAAK;IAAG,KAAK;IAAI,MAAM;IAAY;IAAO,WAAW,MAAM+C,EAAS,OAAO,EAAE,cAAc,KAAK,CAAC;GAAI,CAAA;GACjI,kBAAC,UAAD;IAAQ,SAAS7V;IAAI,WAAU;IAC5B,UAAA9B;GACK,CAAA;EACL;;AAET"}
1
+ {"version":3,"file":"modal.js","names":["pos","list","set","KINDS","_Fragment","LINE","GAP","MARGIN","KINDS","KINDS","KINDS","_Fragment","KINDS","KINDS","_Fragment","_Fragment","katex","Fragment$1","zhTW","texHtml","tex","Tex","text","modalProblem","where","at","p","MODAL_PROBLEMS_EN","message","modalProblemText","wording","ModalError","modalProblemOf","error","ModalEvaluator","model","options","w","world","succ","system","byWorld","f","cached","value","outer","antecedentWorlds","v","a","sphere","s","selected","failures","b","accessible","children","deciding","c","step","set","holds","intension","ev","truthSet","explain","MODERN_TEXT","MODERN_LATEX","NOTATIONS","LEVEL","bracket","child","parent","side","atomText","id","atomLatex","head","rest","base","write","go","g","atom","sym","inner","open","close","l","r","left","right","formulaText","notation","formulaLatex","printFormula","formulaKey","operatorSymbol","op","ATOM_PATTERN","RESERVED","SYMBOLS","tokenize","tokens","i","source","ch","word","symbol","kind","cp","OP_TEXT","Parser","extra","kinds","next","t","parseFormula","isAtomId","atomsOf","out","walk","isTruthFunctional","F","MAX_ENGINE_WORLDS","checkWorlds","worlds","seen","known","accessFromPairs","pairs","list","x","y","accessPairs","frame","kripkeModel","input","atoms","valuation","frameOf","checkSystem","spheres","centering","sphereModel","access","ordered","collapseSpheres","weightOf","distances","here","center","laws","similarity","there","mismatches","violations","law","d","similaritySpheres","ds","own","withSimilaritySpheres","valueIn","values","equationOrder","equations","order","state","visit","path","literalsOf","add","surgery","intervention","solved","background","worldWith","modalTextSchema","z","worldId","pos$1","atomSchema","worldSchema","frameWorldSchema","layoutSchema","common","kripkeDocSchema","frameDocSchema","lawSchema","spheresDocSchema","modalDocSchema","MAX_DOC_WORLDS","zhIssue","schemaProblems","zh","issue","attempt","parseInto","problems","truthFunctional","checkModalDoc","doc","knownWorld","k","checkSpheres","systems","before","structuralEquations","parseModalJson","raw","parsed","frameOfDoc","similarityOf","weights","modelOfDoc","startWorld","modalText","locale","DEFAULT_LOCALE","LANGUAGE_NAMES","LocaleContext","createContext","LocaleProvider","createElement","LocaleScope","useLocale","useContext","list$1","xs","set$1","MODAL_EN","EN_PROBLEMS","n","arg","name","trueAt","ws","names","bad","aFalse","pattern","title","vals","pos","MODAL_MESSAGES","useModalMessages","modalProblemMessage","modalErrorMessage","worldNames","namesOf","ids","boxLines","not","lines","trueHere","showFalse","docGraphInput","explanationText","marksFor","marks","valueOrUndefined","ModalRoot","RootBox","caption","ModalProblems","FormulaMath","formula","TruthMark","UnknownMark","AtomLegend","counterfactualView","semantics","problem","sphereWorlds","worldSetLatex","useModalDoc","useMemo","result","parseAll","sources","unknownAtomProblem","formulas","IntensionTable","props","IntensionBody","KINDS$6","loaded","IntensionLoaded","setWorld","useState","row","setRow","picked","textBox","x0","anchor","width","size","rectBox","h","segmentHitsBox","t0","t1","dx","dy","q","box","around","cx","half","cy","intersects","pad","firstClear","candidates","obstacles","o","textWidth","code","digitSubscript","match","unit","arrowHead","len","ux","uy","bx","tip","by","LINE$1","ATOM_SIZE","NAME_SIZE","GAP$1","MARGIN$1","boxSize","widest","centres","wide","sizes","tall","stepX","stepY","depth","start","queue","last","column","col","mates","border","gap","fmt","edgeGeometry","top","x1","x2","ox","offset","oy","ca","cb","heads","both","nameCandidates","make","layoutWorldGraph","boxes","byId","has","edges","segments","loops","from","to","reverse","free","label","all","y0","y1","UNDERSCORE_IDENT","IDENT_TOKEN","SUB_DY","subscriptParts","m","explicit","parts","sub","Fragment","LINE","PAD","WorldGraph","key","e","onSelect","layout","active","mark","worldLabel","line","KripkeView","KripkeBody","KINDS$5","KripkeLoaded","focus","setFocus","setShowFalse","setExtra","draft","setDraft","setValuation","setPairs","mergeSymmetric","focused","explanation","FormulaValue","editable","EditTables","ps","onAtom","onPair","Segmented","className","onChange","OkIcon","NoIcon","HOLDS","fails","witness","relates","checkRelation","property","axiom","AXIOMS","CONDITION_AXIOM","FRAME_CONDITIONS","checkCondition","condition","MAX_ASSIGNMENTS","compileFrame","index","maskOf","validOnFrame","count","subsets","masks","SYSTEM_CONDITIONS","SYSTEMS","systemsOf","met","FrameConditions","FrameBody","KINDS$4","FrameLoaded","conditions","rows","axioms","Verdict","ok","jsx","StrictImplication","StrictBody","KINDS$3","missing","StrictLoaded","material","strict","materialValue","strictValue","TCS_PATTERNS","negate","tcsInference","third","checkInferenceAt","premises","inference","conclusion","checkInference","DOT","NAME","DETAIL","GAP","MARGIN","layoutSpheres","r0","radii","ringOf","placed","push","fresh","sphereLabels","SphereDiagram","sphereName","TcsCheck","TcsBody","initial","collapsed","setCollapsed","items","TcsCard","item","KINDS$2","heading","TcsColumns","flat","shown","cf","showStrict","InferenceColumn","verdict","SphereView","SphereBody","KINDS$1","SphereLoaded","setSemantics","semanticsSwitch","SurgeryVsSimilarity","SurgeryBody","KINDS","firstConditional","fallback","SurgeryLoaded","setWeights","costs","setCosts","docWithCosts","view","solvedWorld","surgeryValue","Weights","old","useId","Slider","onWeight","onCost"],"sources":["../src/components/text/tex-html.ts","../src/components/text/Tex.tsx","../src/modal/engine/errors.ts","../src/modal/engine/evaluate.ts","../src/modal/engine/print.ts","../src/modal/engine/formula.ts","../src/modal/engine/model.ts","../src/modal/engine/similarity.ts","../src/modal/engine/surgery.ts","../src/modal/data/schema.ts","../src/modal/data/load.ts","../src/components/i18n/messages.ts","../src/modal/i18n/en.ts","../src/modal/i18n/zh.ts","../src/modal/i18n/messages.ts","../src/modal/components/doc-graph.ts","../src/modal/components/explain-text.ts","../src/modal/components/parts.tsx","../src/modal/components/sphere-view-model.ts","../src/modal/components/use-doc.ts","../src/modal/components/IntensionTable.tsx","../src/components/graph/graph-labels.ts","../src/components/text/text-measure.ts","../src/engine/identifier-format.ts","../src/components/graph/signal-shapes.ts","../src/modal/components/world-graph.ts","../src/components/text/subscript.ts","../src/components/text/svg-text.tsx","../src/modal/components/WorldGraph.tsx","../src/modal/components/KripkeView.tsx","../src/components/shared/parts.tsx","../src/logic/relations.ts","../src/modal/engine/frames.ts","../src/modal/components/FrameConditions.tsx","../src/modal/components/StrictImplication.tsx","../src/modal/engine/inference.ts","../src/modal/components/sphere-graph.ts","../src/modal/components/SphereDiagram.tsx","../src/modal/components/TcsCheck.tsx","../src/modal/components/SphereView.tsx","../src/modal/components/SurgeryVsSimilarity.tsx"],"sourcesContent":["import katex from 'katex'\n\n/** LaTeX to KaTeX HTML. Server-safe; a bad input comes back as `katex-error` markup rather than throwing. */\nexport function texHtml(tex: string): string {\n return katex.renderToString(tex, { throwOnError: false, output: 'html', strict: 'ignore', trust: false })\n}\n\n","import { texHtml } from './tex-html.ts'\n\nexport interface TexProps {\n readonly tex: string\n /** The plain-text form, read by screen readers and kept as `data-text` for copying. */\n readonly text: string\n}\n\n/** One typeset formula. Needs the KaTeX stylesheet (see the README). */\nexport function Tex({ tex, text }: TexProps) {\n return <span className=\"ca-tex\" role=\"math\" aria-label={text} data-text={text} data-tex={tex} dangerouslySetInnerHTML={{ __html: texHtml(tex) }} />\n}\n","/**\n * Every error the modal engine and its data layer raise has a stable code and its parameters, so an\n * interface can word it in its own language. `Error.message` is the English wording below.\n */\n\n/** Parameters per problem code. */\nexport interface ModalProblemParams {\n // formula syntax; positions are 0-based character offsets into `source`\n readonly 'parse-unexpected-character': { readonly source: string; readonly position: number; readonly character: string }\n readonly 'parse-unexpected-token': { readonly source: string; readonly position: number; readonly token: string }\n readonly 'parse-unexpected-end': { readonly source: string; readonly position: number }\n readonly 'parse-expected': { readonly source: string; readonly position: number; readonly expected: string }\n /** `>` beside `⊃` or `≡`, or `≡` chained, without brackets. */\n readonly 'ambiguous-mix': { readonly source: string; readonly position: number; readonly operators: string }\n readonly 'reserved-atom': { readonly atom: string }\n // models\n readonly 'unknown-atom': { readonly atom: string }\n readonly 'unknown-world': { readonly world: string }\n readonly 'duplicate-world': { readonly world: string }\n readonly 'duplicate-atom': { readonly atom: string }\n readonly 'no-worlds': Record<string, never>\n readonly 'too-many-worlds': { readonly count: number; readonly limit: number }\n readonly 'missing-position': { readonly world: string }\n readonly 'no-sphere-system': { readonly world: string }\n /** Sphere `index` (1-based, innermost is 1) does not contain the sphere inside it. */\n readonly 'spheres-not-nested': { readonly world: string; readonly index: number }\n readonly 'empty-sphere': { readonly world: string; readonly index: number }\n /** Strong: the innermost sphere is not exactly {world}; weak: world is not in it. */\n readonly centering: { readonly world: string; readonly centering: 'strong' | 'weak' }\n readonly 'spheres-source': Record<string, never>\n // evaluation\n /** Stalnaker's selection is undefined: the closest antecedent worlds are several. */\n readonly 'not-unique': { readonly world: string; readonly candidates: readonly string[] }\n readonly 'too-many-assignments': { readonly count: number; readonly limit: number }\n // structural equations\n readonly 'cyclic-equations': { readonly cycle: readonly string[] }\n readonly 'not-truth-functional': { readonly formula: string }\n readonly 'surgery-antecedent': { readonly formula: string }\n /** The surgery figure's document lacks its centre, similarity or structural equations. */\n readonly 'needs-similarity': Record<string, never>\n // documents\n readonly 'not-json': { readonly detail: string }\n readonly 'too-large': Record<string, never>\n /** A component given a document of a kind it does not draw. */\n readonly 'wrong-kind': { readonly kind: string; readonly expected: readonly string[] }\n /** Any other schema complaint, already worded per locale. */\n readonly schema: { readonly message: { readonly 'zh-TW': string; readonly en: string } }\n}\n\nexport type ModalProblemCode = keyof ModalProblemParams\n\n/** One problem: its code, parameters and, when known, where it sits (a path into the document, e.g. `formulas.1`). */\nexport type ModalProblem = {\n readonly [K in ModalProblemCode]: { readonly code: K; readonly params: ModalProblemParams[K]; readonly where?: string }\n}[ModalProblemCode]\n\nexport function modalProblem<K extends ModalProblemCode>(code: K, params: ModalProblemParams[K], where?: string): ModalProblem {\n return (where === undefined ? { code, params } : { code, params, where }) as ModalProblem\n}\n\n/** Wording per code; the interface supplies one per locale. */\nexport interface ModalProblemWording {\n readonly messages: { readonly [K in ModalProblemCode]: (params: ModalProblemParams[K]) => string }\n /** Joins a `where` path and the message. */\n readonly join: (where: string, message: string) => string\n}\n\nconst at = (p: { readonly source: string; readonly position: number }): string => ` at position ${p.position + 1} of ${JSON.stringify(p.source)}`\n\nexport const MODAL_PROBLEMS_EN: ModalProblemWording = {\n join: (where, message) => `${where}: ${message}`,\n messages: {\n 'parse-unexpected-character': (p) => `unexpected character ${p.character}${at(p)}`,\n 'parse-unexpected-token': (p) => `unexpected ${p.token}${at(p)}`,\n 'parse-unexpected-end': (p) => `the formula ends too early${at(p)}`,\n 'parse-expected': (p) => `expected ${p.expected}${at(p)}`,\n 'ambiguous-mix': (p) => `add brackets: ${p.operators} cannot stand side by side unbracketed${at(p)}`,\n 'reserved-atom': (p) => `${p.atom} is a reserved word, not an atom`,\n 'unknown-atom': (p) => `no atom ${p.atom}`,\n 'unknown-world': (p) => `no world ${p.world}`,\n 'duplicate-world': (p) => `world ${p.world} is listed twice`,\n 'duplicate-atom': (p) => `atom ${p.atom} is listed twice`,\n 'no-worlds': () => 'the model has no worlds',\n 'too-many-worlds': (p) => `${p.count} worlds; the limit is ${p.limit}`,\n 'missing-position': (p) => `world ${p.world} has no position, which the manual layout needs`,\n 'no-sphere-system': (p) => `world ${p.world} has no system of spheres`,\n 'spheres-not-nested': (p) => `sphere ${p.index} around ${p.world} does not contain the sphere inside it`,\n 'empty-sphere': (p) => `sphere ${p.index} around ${p.world} is empty`,\n centering: (p) =>\n p.centering === 'strong' ? `the innermost sphere around ${p.world} must be exactly {${p.world}}` : `the innermost sphere around ${p.world} must contain ${p.world}`,\n 'spheres-source': () => 'give exactly one of: center with spheres, center with similarity, or systems',\n 'not-unique': (p) => `Stalnaker's selection is undefined at ${p.world}: the closest antecedent worlds are ${p.candidates.join(', ')}`,\n 'too-many-assignments': (p) => `${p.count} assignments to enumerate; the limit is ${p.limit}`,\n 'cyclic-equations': (p) => `the equations form a cycle: ${p.cycle.join(' → ')}`,\n 'not-truth-functional': (p) => `${p.formula} must be truth-functional (no □, ◇ or >)`,\n 'surgery-antecedent': (p) => `${p.formula} is not a conjunction of atoms and negated atoms, which surgery needs`,\n 'needs-similarity': () => 'this figure needs a spheres document with center, similarity and structural equations',\n 'not-json': (p) => `not JSON: ${p.detail}`,\n 'too-large': () => 'the document is too large',\n 'wrong-kind': (p) => `this figure needs a ${p.expected.join(' or ')} document, not ${p.kind}`,\n schema: (p) => p.message.en,\n },\n}\n\n/** The problem worded by `wording` (English by default). */\nexport function modalProblemText(p: ModalProblem, wording: ModalProblemWording = MODAL_PROBLEMS_EN): string {\n const message = (wording.messages[p.code] as (params: unknown) => string)(p.params)\n return p.where === undefined ? message : wording.join(p.where, message)\n}\n\n/** An error carrying a {@link ModalProblem}; its message is the English wording. */\nexport class ModalError extends Error {\n readonly problem: ModalProblem\n\n constructor(p: ModalProblem) {\n super(modalProblemText(p))\n this.name = 'ModalError'\n this.problem = p\n }\n}\n\n/** The problem behind `error`, when it is one of ours. */\nexport function modalProblemOf(error: unknown): ModalProblem | undefined {\n return error instanceof ModalError ? error.problem : undefined\n}\n","import { ModalError, modalProblem } from './errors.ts'\nimport type { Formula } from './formula.ts'\nimport type { ModalModel } from './model.ts'\n\n/**\n * Truth at a world, by Garson's truth conditions (Modal Logic for Philosophers, 2nd ed., pp. 59–66),\n * and the counterfactual `>` on systems of spheres (pp. 455–459):\n *\n * - a_w(□A) = T iff a_v(A) = T for every v with wRv; a_w(◇A) = T iff a_v(A) = T for some such v.\n * - Lewis: A > B is true at w iff no sphere around w holds an A-world (vacuously), or the smallest\n * sphere S that does has every A-world in it a B-world. Finite systems always have that smallest\n * sphere, so the limit assumption holds.\n * - Stalnaker: the same, but S ∩ |A| must be one world; when it is several, the selection is\n * undefined and the engine reports `not-unique` with the candidates instead of choosing.\n */\n\nexport type ConditionalSemantics = 'lewis' | 'stalnaker'\n\nexport interface EvalOptions {\n /** How `>` is read; default `lewis`. */\n readonly semantics?: ConditionalSemantics\n}\n\n/** How a counterfactual A > B came out at one world. */\nexport interface CounterfactualStep {\n /** The A-worlds any sphere around the world reaches, in world order. */\n readonly antecedentWorlds: readonly string[]\n /** Index (0 = innermost) of the smallest sphere holding an A-world; undefined when none does. */\n readonly sphere: number | undefined\n /** The selection f(|A|, w) = S ∩ |A|: the closest A-worlds. Empty when vacuous. */\n readonly selected: readonly string[]\n /** The selected worlds where B is false. */\n readonly failures: readonly string[]\n /** No sphere holds an A-world, so A > B is true vacuously. */\n readonly vacuous: boolean\n readonly value: boolean\n}\n\n/** Why a formula has its value at a world: the values of its parts, and the worlds that decide modal steps. */\nexport interface Explanation {\n readonly formula: Formula\n readonly world: string\n readonly value: boolean\n /** The parts' explanations: for □ and ◇ the argument at every accessible world; for > the consequent at every selected world. */\n readonly children: readonly Explanation[]\n /** □ and ◇: the worlds this world can see. */\n readonly accessible?: readonly string[]\n /** □ false: an accessible world where the argument is false; ◇ true: one where it is true. */\n readonly witness?: string\n readonly counterfactual?: CounterfactualStep\n}\n\n/** Evaluates formulas on one model, remembering each (formula, world) value. */\nexport class ModalEvaluator {\n private readonly memo = new Map<Formula, Map<string, boolean>>()\n private readonly atomSets: ReadonlyMap<string, ReadonlySet<string>>\n readonly semantics: ConditionalSemantics\n readonly model: ModalModel\n\n constructor(model: ModalModel, options: EvalOptions = {}) {\n this.model = model\n this.semantics = options.semantics ?? 'lewis'\n this.atomSets = new Map(model.worlds.map((w) => [w, new Set(model.valuation[w] ?? [])]))\n }\n\n /** The worlds `world` can see; throws when R is not defined there. */\n accessible(world: string): readonly string[] {\n this.known(world)\n const succ = this.model.access[world]\n if (succ === undefined) throw new ModalError(modalProblem('no-sphere-system', { world }))\n return succ\n }\n\n /** The spheres around `world`, innermost first; throws when it has none. */\n spheres(world: string): readonly (readonly string[])[] {\n this.known(world)\n const system = this.model.spheres?.[world]\n if (system === undefined) throw new ModalError(modalProblem('no-sphere-system', { world }))\n return system\n }\n\n holds(f: Formula, world: string): boolean {\n let byWorld = this.memo.get(f)\n if (byWorld === undefined) {\n byWorld = new Map()\n this.memo.set(f, byWorld)\n }\n const cached = byWorld.get(world)\n if (cached !== undefined) return cached\n const value = this.compute(f, world)\n byWorld.set(world, value)\n return value\n }\n\n /** The worlds where `f` is true, in world order: |f|. */\n truthSet(f: Formula): string[] {\n return this.model.worlds.filter((w) => this.holds(f, w))\n }\n\n counterfactual(a: Formula, b: Formula, world: string): CounterfactualStep {\n const system = this.spheres(world)\n const outer = system[system.length - 1] as readonly string[]\n const antecedentWorlds = this.model.worlds.filter((v) => outer.includes(v) && this.holds(a, v))\n const sphere = system.findIndex((s) => s.some((v) => antecedentWorlds.includes(v)))\n if (sphere < 0) return { antecedentWorlds, sphere: undefined, selected: [], failures: [], vacuous: true, value: true }\n const s = system[sphere] as readonly string[]\n const selected = antecedentWorlds.filter((v) => s.includes(v))\n if (this.semantics === 'stalnaker' && selected.length > 1) {\n throw new ModalError(modalProblem('not-unique', { world, candidates: selected }))\n }\n const failures = selected.filter((v) => !this.holds(b, v))\n return { antecedentWorlds, sphere, selected, failures, vacuous: false, value: failures.length === 0 }\n }\n\n explain(f: Formula, world: string): Explanation {\n const value = this.holds(f, world)\n switch (f.kind) {\n case 'atom':\n case 'top':\n case 'bot':\n return { formula: f, world, value, children: [] }\n case 'not':\n return { formula: f, world, value, children: [this.explain(f.arg, world)] }\n case 'box':\n case 'dia': {\n const accessible = this.accessible(world)\n const children = accessible.map((v) => this.explain(f.arg, v))\n const deciding = f.kind === 'box' ? (value ? undefined : children.find((c) => !c.value)) : value ? children.find((c) => c.value) : undefined\n return deciding === undefined ? { formula: f, world, value, children, accessible } : { formula: f, world, value, children, accessible, witness: deciding.world }\n }\n case 'cf': {\n const step = this.counterfactual(f.left, f.right, world)\n return { formula: f, world, value, children: step.selected.map((v) => this.explain(f.right, v)), counterfactual: step }\n }\n default:\n return { formula: f, world, value, children: [this.explain(f.left, world), this.explain(f.right, world)] }\n }\n }\n\n private known(world: string): void {\n if (!this.atomSets.has(world)) throw new ModalError(modalProblem('unknown-world', { world }))\n }\n\n private compute(f: Formula, world: string): boolean {\n switch (f.kind) {\n case 'atom': {\n const set = this.atomSets.get(world)\n if (set === undefined) throw new ModalError(modalProblem('unknown-world', { world }))\n if (!this.model.atoms.includes(f.id)) throw new ModalError(modalProblem('unknown-atom', { atom: f.id }))\n return set.has(f.id)\n }\n case 'top':\n return true\n case 'bot':\n return false\n case 'not':\n return !this.holds(f.arg, world)\n case 'and':\n return this.holds(f.left, world) && this.holds(f.right, world)\n case 'or':\n return this.holds(f.left, world) || this.holds(f.right, world)\n case 'imp':\n return !this.holds(f.left, world) || this.holds(f.right, world)\n case 'iff':\n return this.holds(f.left, world) === this.holds(f.right, world)\n case 'box':\n return this.accessible(world).every((v) => this.holds(f.arg, v))\n case 'dia':\n return this.accessible(world).some((v) => this.holds(f.arg, v))\n case 'cf':\n return this.counterfactual(f.left, f.right, world).value\n }\n }\n}\n\n/** a_w(f): whether `f` is true at `world`. */\nexport function holds(model: ModalModel, f: Formula, world: string, options?: EvalOptions): boolean {\n return new ModalEvaluator(model, options).holds(f, world)\n}\n\n/** The intension of `f`: each world with the truth value `f` has there. */\nexport function intension(model: ModalModel, f: Formula, options?: EvalOptions): Record<string, boolean> {\n const ev = new ModalEvaluator(model, options)\n return Object.fromEntries(model.worlds.map((w) => [w, ev.holds(f, w)]))\n}\n\n/** |f|: the worlds where `f` is true. */\nexport function truthSet(model: ModalModel, f: Formula, options?: EvalOptions): string[] {\n return new ModalEvaluator(model, options).truthSet(f)\n}\n\n/** The value of `f` at `world` with its explanation tree. */\nexport function explain(model: ModalModel, f: Formula, world: string, options?: EvalOptions): Explanation {\n return new ModalEvaluator(model, options).explain(f, world)\n}\n","import type { BinaryKind, Formula, UnaryKind } from './formula.ts'\n\n/**\n * Formulas written out for display: plain text and LaTeX, in one of the notation sets. Brackets are\n * the fewest that parse back to the same tree, except that a conditional inside a conditional keeps\n * them (□(p ⊃ q) ⊃ (□p ⊃ □q)). `ascii` writes the authoring syntax.\n */\n\n/** `modern`: ¬ ∧ ∨ ⊃ ≡ □ ◇ > (the default); `garson`: Garson's ~ and &; `ascii`: the authoring syntax. */\nexport type ModalNotation = 'modern' | 'garson' | 'ascii'\n\ntype Op = UnaryKind | BinaryKind | 'top' | 'bot'\n\ninterface Symbols {\n readonly text: Readonly<Record<Op, string>>\n readonly latex: Readonly<Record<Op, string>>\n}\n\nconst MODERN_TEXT: Readonly<Record<Op, string>> = { not: '¬', box: '□', dia: '◇', and: '∧', or: '∨', imp: '⊃', iff: '≡', cf: '>', top: '⊤', bot: '⊥' }\nconst MODERN_LATEX: Readonly<Record<Op, string>> = {\n not: '\\\\neg ',\n box: '\\\\Box ',\n dia: '\\\\Diamond ',\n and: '\\\\land',\n or: '\\\\lor',\n imp: '\\\\supset',\n iff: '\\\\equiv',\n cf: '>',\n top: '\\\\top',\n bot: '\\\\bot',\n}\n\nexport const NOTATIONS: Readonly<Record<ModalNotation, Symbols>> = {\n modern: { text: MODERN_TEXT, latex: MODERN_LATEX },\n garson: {\n text: { ...MODERN_TEXT, not: '~', and: '&' },\n latex: { ...MODERN_LATEX, not: '{\\\\sim}', and: '\\\\mathbin{\\\\&}' },\n },\n ascii: {\n text: { not: '~', box: '[]', dia: '<>', and: '&', or: '|', imp: '->', iff: '<->', cf: '>', top: 'true', bot: 'false' },\n latex: MODERN_LATEX,\n },\n}\n\n/** Binding strength: higher binds tighter. */\nconst LEVEL: Readonly<Record<Formula['kind'], number>> = { atom: 5, top: 5, bot: 5, not: 5, box: 5, dia: 5, and: 4, or: 3, cf: 2, imp: 1, iff: 1 }\n\n/** Whether `child` needs brackets as the `side` operand of a `parent` binary node. */\nfunction bracket(parent: BinaryKind, child: Formula, side: 'left' | 'right'): boolean {\n const c = LEVEL[child.kind]\n const p = LEVEL[parent]\n if (c > p) {\n // Unbracketed `>` may not stand beside ⊃ or ≡.\n return child.kind === 'cf' && (parent === 'imp' || parent === 'iff')\n }\n if (c < p) return true\n // Same level: ∧ and ∨ chain to the left unbracketed; nested conditionals keep their brackets on either side, as textbooks write them.\n if (parent === 'and' || parent === 'or') return side === 'right'\n return true\n}\n\nfunction atomText(id: string): string {\n return id\n}\n\n/** `rain` → \\mathit{rain}; `p_1` → p_{1}; `p` → p. */\nfunction atomLatex(id: string): string {\n const [head = id, ...rest] = id.split('_')\n const base = head.length > 1 ? `\\\\mathit{${head}}` : head\n return rest.length === 0 ? base : `${base}_{${rest.join('\\\\_')}}`\n}\n\nfunction write(f: Formula, sym: Readonly<Record<Op, string>>, atom: (id: string) => string, open: string, close: string): string {\n const go = (g: Formula): string => {\n switch (g.kind) {\n case 'atom':\n return atom(g.id)\n case 'top':\n case 'bot':\n return sym[g.kind]\n case 'not':\n case 'box':\n case 'dia': {\n const inner = go(g.arg)\n return LEVEL[g.arg.kind] < 5 ? `${sym[g.kind]}${open}${inner}${close}` : `${sym[g.kind]}${inner}`\n }\n default: {\n const l = go(g.left)\n const r = go(g.right)\n const left = bracket(g.kind, g.left, 'left') ? `${open}${l}${close}` : l\n const right = bracket(g.kind, g.right, 'right') ? `${open}${r}${close}` : r\n return `${left} ${sym[g.kind]} ${right}`\n }\n }\n }\n return go(f)\n}\n\n/** The formula as plain text. */\nexport function formulaText(f: Formula, notation: ModalNotation = 'modern'): string {\n return write(f, NOTATIONS[notation].text, atomText, '(', ')')\n}\n\n/** The formula as LaTeX. */\nexport function formulaLatex(f: Formula, notation: ModalNotation = 'modern'): string {\n return write(f, NOTATIONS[notation].latex, atomLatex, '(', ')')\n}\n\n/** Both forms at once. */\nexport function printFormula(f: Formula, notation: ModalNotation = 'modern'): { readonly text: string; readonly latex: string } {\n return { text: formulaText(f, notation), latex: formulaLatex(f, notation) }\n}\n\n/** A canonical key: the ASCII text, equal for equal trees. */\nexport function formulaKey(f: Formula): string {\n return formulaText(f, 'ascii')\n}\n\n/** An operator's symbol in a notation, for legends and headings. */\nexport function operatorSymbol(op: Op, notation: ModalNotation = 'modern'): { readonly text: string; readonly latex: string } {\n return { text: NOTATIONS[notation].text[op], latex: NOTATIONS[notation].latex[op] }\n}\n","import { ModalError, modalProblem } from './errors.ts'\n\n/**\n * Propositional modal formulas: their syntax tree and the parser for the authoring syntax, which takes\n * ASCII and Unicode alike (`~p`, `¬p`; `p & q`, `p ∧ q`; `p | q`, `p ∨ q`; `p -> q`, `p ⊃ q`;\n * `p <-> q`, `p ≡ q`; `[]p`, `□p`; `<>p`, `◇p`; `p > q`, `p □→ q`; `true`, `⊤`; `false`, `⊥`).\n *\n * Binding, tightest first: the unary operators (¬ □ ◇), then ∧, ∨, the counterfactual >, and last ⊃\n * and ≡. ∧ and ∨ group to the left, ⊃ and > to the right. `>` beside `⊃` or `≡`, and `≡` beside `⊃`\n * or another `≡`, need brackets: the parser reports `ambiguous-mix` rather than guess.\n */\n\nexport type BinaryKind = 'and' | 'or' | 'imp' | 'iff' | 'cf'\nexport type UnaryKind = 'not' | 'box' | 'dia'\n\nexport type Formula =\n | { readonly kind: 'atom'; readonly id: string }\n | { readonly kind: 'top' }\n | { readonly kind: 'bot' }\n | { readonly kind: UnaryKind; readonly arg: Formula }\n | { readonly kind: BinaryKind; readonly left: Formula; readonly right: Formula }\n\n/** An atom: a lowercase letter, then letters, digits or underscores. */\nexport const ATOM_PATTERN = /^[a-z][A-Za-z0-9_]*$/\n\nconst RESERVED = new Set(['true', 'false'])\n\ntype TokenKind = 'atom' | 'top' | 'bot' | UnaryKind | BinaryKind | '(' | ')'\n\ninterface Token {\n readonly kind: TokenKind\n readonly text: string\n readonly position: number\n}\n\n/** Symbols longest first, so `<->` wins over `<>` and `□→` over `□`. */\nconst SYMBOLS: readonly (readonly [string, TokenKind])[] = [\n ['<->', 'iff'],\n ['->', 'imp'],\n ['<>', 'dia'],\n ['[]', 'box'],\n ['□→', 'cf'],\n ['~', 'not'],\n ['¬', 'not'],\n ['&', 'and'],\n ['∧', 'and'],\n ['|', 'or'],\n ['∨', 'or'],\n ['⊃', 'imp'],\n ['→', 'imp'],\n ['≡', 'iff'],\n ['↔', 'iff'],\n ['□', 'box'],\n ['◻', 'box'],\n ['◇', 'dia'],\n ['◊', 'dia'],\n ['>', 'cf'],\n ['⊤', 'top'],\n ['⊥', 'bot'],\n ['(', '('],\n [')', ')'],\n]\n\nfunction tokenize(source: string): Token[] {\n const tokens: Token[] = []\n let i = 0\n outer: while (i < source.length) {\n const ch = source[i] as string\n if (/\\s/.test(ch)) {\n i += 1\n continue\n }\n const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i))\n if (word !== null) {\n const text = word[0]\n if (text === 'true') tokens.push({ kind: 'top', text, position: i })\n else if (text === 'false') tokens.push({ kind: 'bot', text, position: i })\n else if (ATOM_PATTERN.test(text)) tokens.push({ kind: 'atom', text, position: i })\n else throw new ModalError(modalProblem('parse-unexpected-character', { source, position: i, character: text[0] as string }))\n i += text.length\n continue\n }\n for (const [symbol, kind] of SYMBOLS) {\n if (source.startsWith(symbol, i)) {\n tokens.push({ kind, text: symbol, position: i })\n i += symbol.length\n continue outer\n }\n }\n const cp = String.fromCodePoint(source.codePointAt(i) as number)\n throw new ModalError(modalProblem('parse-unexpected-character', { source, position: i, character: cp }))\n }\n return tokens\n}\n\n/** The text of each operator kind in the ambiguity message. */\nconst OP_TEXT: Readonly<Record<BinaryKind, string>> = { and: '∧', or: '∨', imp: '⊃', iff: '≡', cf: '>' }\n\nclass Parser {\n private i = 0\n /** Nodes written inside brackets: they may stand beside any operator. */\n private readonly bracketed = new WeakSet<Formula>()\n private readonly source: string\n private readonly tokens: readonly Token[]\n\n constructor(source: string, tokens: readonly Token[]) {\n this.source = source\n this.tokens = tokens\n }\n\n parse(): Formula {\n if (this.tokens.length === 0) throw new ModalError(modalProblem('parse-unexpected-end', { source: this.source, position: 0 }))\n const f = this.implication()\n const extra = this.tokens[this.i]\n if (extra !== undefined) {\n throw new ModalError(modalProblem('parse-unexpected-token', { source: this.source, position: extra.position, token: extra.text }))\n }\n return f\n }\n\n private peek(): Token | undefined {\n return this.tokens[this.i]\n }\n\n private end(): number {\n return this.source.length\n }\n\n /** A bare (unbracketed) binary node of one of `kinds`. */\n private bare(f: Formula, kinds: readonly BinaryKind[]): boolean {\n return (kinds as readonly string[]).includes(f.kind) && !this.bracketed.has(f)\n }\n\n private ambiguous(position: number, a: BinaryKind, b: BinaryKind): never {\n throw new ModalError(modalProblem('ambiguous-mix', { source: this.source, position, operators: `${OP_TEXT[a]} ${OP_TEXT[b]}` }))\n }\n\n /** ⊃ (right-grouping) and ≡ (no grouping): the loosest level. */\n private implication(): Formula {\n const left = this.counterfactual()\n const op = this.peek()\n if (op === undefined || (op.kind !== 'imp' && op.kind !== 'iff')) return left\n this.i += 1\n if (this.bare(left, ['cf'])) this.ambiguous(op.position, 'cf', op.kind)\n const right = op.kind === 'imp' ? this.implication() : this.counterfactual()\n if (this.bare(right, ['cf'])) this.ambiguous(op.position, op.kind, 'cf')\n if (op.kind === 'imp' && this.bare(right, ['iff'])) this.ambiguous(op.position, 'imp', 'iff')\n const next = this.peek()\n if (op.kind === 'iff' && next !== undefined && (next.kind === 'iff' || next.kind === 'imp')) this.ambiguous(next.position, 'iff', next.kind)\n return { kind: op.kind, left, right }\n }\n\n /** > (right-grouping). */\n private counterfactual(): Formula {\n const left = this.disjunction()\n const op = this.peek()\n if (op === undefined || op.kind !== 'cf') return left\n this.i += 1\n const right = this.counterfactual()\n return { kind: 'cf', left, right }\n }\n\n private disjunction(): Formula {\n let f = this.conjunction()\n while (this.peek()?.kind === 'or') {\n this.i += 1\n f = { kind: 'or', left: f, right: this.conjunction() }\n }\n return f\n }\n\n private conjunction(): Formula {\n let f = this.unary()\n while (this.peek()?.kind === 'and') {\n this.i += 1\n f = { kind: 'and', left: f, right: this.unary() }\n }\n return f\n }\n\n private unary(): Formula {\n const t = this.peek()\n if (t !== undefined && (t.kind === 'not' || t.kind === 'box' || t.kind === 'dia')) {\n this.i += 1\n return { kind: t.kind, arg: this.unary() }\n }\n return this.primary()\n }\n\n private primary(): Formula {\n const t = this.peek()\n if (t === undefined) throw new ModalError(modalProblem('parse-unexpected-end', { source: this.source, position: this.end() }))\n this.i += 1\n switch (t.kind) {\n case 'atom':\n return { kind: 'atom', id: t.text }\n case 'top':\n return { kind: 'top' }\n case 'bot':\n return { kind: 'bot' }\n case '(': {\n const inner = this.implication()\n const close = this.peek()\n if (close === undefined) throw new ModalError(modalProblem('parse-expected', { source: this.source, position: this.end(), expected: ')' }))\n if (close.kind !== ')') throw new ModalError(modalProblem('parse-expected', { source: this.source, position: close.position, expected: ')' }))\n this.i += 1\n this.bracketed.add(inner)\n return inner\n }\n default:\n throw new ModalError(modalProblem('parse-unexpected-token', { source: this.source, position: t.position, token: t.text }))\n }\n }\n}\n\n/** Parse a formula; throws {@link ModalError} with the position of the first problem. */\nexport function parseFormula(source: string): Formula {\n return new Parser(source, tokenize(source)).parse()\n}\n\n/** Whether `id` can name an atom. */\nexport function isAtomId(id: string): boolean {\n return ATOM_PATTERN.test(id) && !RESERVED.has(id)\n}\n\n/** The atoms of `f`, in order of first appearance. */\nexport function atomsOf(f: Formula): string[] {\n const out: string[] = []\n const walk = (g: Formula): void => {\n switch (g.kind) {\n case 'atom':\n if (!out.includes(g.id)) out.push(g.id)\n return\n case 'top':\n case 'bot':\n return\n case 'not':\n case 'box':\n case 'dia':\n walk(g.arg)\n return\n default:\n walk(g.left)\n walk(g.right)\n }\n }\n walk(f)\n return out\n}\n\n/** Whether `f` uses no □, ◇ or >. */\nexport function isTruthFunctional(f: Formula): boolean {\n switch (f.kind) {\n case 'atom':\n case 'top':\n case 'bot':\n return true\n case 'box':\n case 'dia':\n case 'cf':\n return false\n case 'not':\n return isTruthFunctional(f.arg)\n default:\n return isTruthFunctional(f.left) && isTruthFunctional(f.right)\n }\n}\n\n/** Formulas built in code, for the axiom schemas and inference patterns. */\nexport const F = {\n atom: (id: string): Formula => ({ kind: 'atom', id }),\n not: (arg: Formula): Formula => ({ kind: 'not', arg }),\n box: (arg: Formula): Formula => ({ kind: 'box', arg }),\n dia: (arg: Formula): Formula => ({ kind: 'dia', arg }),\n and: (left: Formula, right: Formula): Formula => ({ kind: 'and', left, right }),\n or: (left: Formula, right: Formula): Formula => ({ kind: 'or', left, right }),\n imp: (left: Formula, right: Formula): Formula => ({ kind: 'imp', left, right }),\n cf: (left: Formula, right: Formula): Formula => ({ kind: 'cf', left, right }),\n /** Strict implication: □(a ⊃ b). */\n strict: (left: Formula, right: Formula): Formula => ({ kind: 'box', arg: { kind: 'imp', left, right } }),\n}\n","import { ModalError, modalProblem } from './errors.ts'\n\n/**\n * A finite model ⟨W, R, a⟩ restricted to atoms: worlds, the atoms true at each, each world's\n * R-successors and, for conditionals, each world's system of spheres (innermost first). A world\n * with no `access` entry has no R defined there; one with no `spheres` entry has no system.\n */\nexport interface ModalModel {\n readonly worlds: readonly string[]\n readonly atoms: readonly string[]\n /** World → the atoms true there; every other atom is false there. */\n readonly valuation: Readonly<Record<string, readonly string[]>>\n /** World → the worlds it can see. */\n readonly access: Readonly<Record<string, readonly string[]>>\n /** World → its spheres, innermost first, each containing the one before. */\n readonly spheres?: Readonly<Record<string, readonly (readonly string[])[]>>\n}\n\n/** A frame ⟨W, R⟩: a model with no atoms. */\nexport interface Frame {\n readonly worlds: readonly string[]\n readonly access: Readonly<Record<string, readonly string[]>>\n}\n\n/** The engine's own limit, so a set of worlds fits a 30-bit mask. Documents allow fewer (see the schema). */\nexport const MAX_ENGINE_WORLDS = 30\n\nfunction checkWorlds(worlds: readonly string[]): void {\n if (worlds.length === 0) throw new ModalError(modalProblem('no-worlds', {}))\n if (worlds.length > MAX_ENGINE_WORLDS) throw new ModalError(modalProblem('too-many-worlds', { count: worlds.length, limit: MAX_ENGINE_WORLDS }))\n const seen = new Set<string>()\n for (const w of worlds) {\n if (seen.has(w)) throw new ModalError(modalProblem('duplicate-world', { world: w }))\n seen.add(w)\n }\n}\n\nfunction known(worlds: ReadonlySet<string>, w: string): void {\n if (!worlds.has(w)) throw new ModalError(modalProblem('unknown-world', { world: w }))\n}\n\n/** Successor lists from pairs, every world listed (with no successors when it has none). */\nexport function accessFromPairs(worlds: readonly string[], pairs: readonly (readonly [string, string])[]): Record<string, string[]> {\n const set = new Set(worlds)\n const out: Record<string, string[]> = Object.fromEntries(worlds.map((w) => [w, [] as string[]]))\n for (const [a, b] of pairs) {\n known(set, a)\n known(set, b)\n const list = out[a] as string[]\n if (!list.includes(b)) list.push(b)\n }\n for (const w of worlds) (out[w] as string[]).sort((x, y) => worlds.indexOf(x) - worlds.indexOf(y))\n return out\n}\n\n/** R as pairs, in world order. */\nexport function accessPairs(frame: Frame): [string, string][] {\n return frame.worlds.flatMap((w) => (frame.access[w] ?? []).map((v) => [w, v] as [string, string]))\n}\n\n/** A Kripke model from worlds with their true atoms and R as pairs. */\nexport function kripkeModel(input: {\n readonly atoms: readonly string[]\n readonly worlds: readonly { readonly id: string; readonly true?: readonly string[] }[]\n readonly access: readonly (readonly [string, string])[]\n}): ModalModel {\n const worlds = input.worlds.map((w) => w.id)\n checkWorlds(worlds)\n const atoms = new Set(input.atoms)\n const valuation: Record<string, string[]> = {}\n for (const w of input.worlds) {\n for (const a of w.true ?? []) if (!atoms.has(a)) throw new ModalError(modalProblem('unknown-atom', { atom: a }))\n valuation[w.id] = [...(w.true ?? [])]\n }\n return { worlds, atoms: [...input.atoms], valuation, access: accessFromPairs(worlds, input.access) }\n}\n\n/** A frame from world ids and R as pairs. */\nexport function frameOf(worlds: readonly string[], pairs: readonly (readonly [string, string])[]): Frame {\n checkWorlds(worlds)\n return { worlds: [...worlds], access: accessFromPairs(worlds, pairs) }\n}\n\n/**\n * Check one system of spheres around `world`: known worlds, none empty, each containing the one\n * before, and centred (`strong`: the innermost is exactly {world}; `weak`: it contains world).\n */\nexport function checkSystem(worlds: readonly string[], world: string, spheres: readonly (readonly string[])[], centering: 'strong' | 'weak'): void {\n const set = new Set(worlds)\n known(set, world)\n if (spheres.length === 0) throw new ModalError(modalProblem('empty-sphere', { world, index: 1 }))\n spheres.forEach((s, i) => {\n if (s.length === 0) throw new ModalError(modalProblem('empty-sphere', { world, index: i + 1 }))\n for (const v of s) known(set, v)\n if (i > 0 && !(spheres[i - 1] as readonly string[]).every((v) => s.includes(v))) {\n throw new ModalError(modalProblem('spheres-not-nested', { world, index: i + 1 }))\n }\n })\n const inner = spheres[0] as readonly string[]\n const centred = centering === 'strong' ? inner.length === 1 && inner[0] === world : inner.includes(world)\n if (!centred) throw new ModalError(modalProblem('centering', { world, centering }))\n}\n\n/**\n * A model for conditionals: worlds with their true atoms and a system of spheres per world (a world\n * may have none). R at a world with a system is its outermost sphere, so □ ranges over every world\n * the spheres reach and strict implication is the one-sphere case of `>`.\n */\nexport function sphereModel(input: {\n readonly atoms: readonly string[]\n readonly worlds: readonly { readonly id: string; readonly true?: readonly string[] }[]\n readonly systems: Readonly<Record<string, readonly (readonly string[])[]>>\n readonly centering?: 'strong' | 'weak'\n}): ModalModel {\n const base = kripkeModel({ atoms: input.atoms, worlds: input.worlds, access: [] })\n const spheres: Record<string, string[][]> = {}\n const access: Record<string, string[]> = {}\n for (const [w, system] of Object.entries(input.systems)) {\n checkSystem(base.worlds, w, system, input.centering ?? 'strong')\n const ordered = system.map((s) => base.worlds.filter((v) => s.includes(v)))\n spheres[w] = ordered\n access[w] = ordered[ordered.length - 1] as string[]\n }\n return { ...base, access, spheres }\n}\n\n/** The same model with every system pressed into one sphere, its outermost: `>` then reads as strict implication. */\nexport function collapseSpheres(model: ModalModel): ModalModel {\n if (model.spheres === undefined) return model\n const spheres = Object.fromEntries(Object.entries(model.spheres).map(([w, s]) => [w, [s[s.length - 1] as readonly string[]]]))\n return { ...model, spheres }\n}\n","import { ModalEvaluator } from './evaluate.ts'\nimport type { Formula } from './formula.ts'\nimport type { ModalModel } from './model.ts'\nimport { checkSystem } from './model.ts'\n\n/**\n * Spheres from a numeric similarity: each atom has a weight for matching the centre's particular fact,\n * and each law a cost for violating it (a \"miracle\"). A world's distance from the centre is the sum of\n * the weights of the atoms on which it differs from the centre plus the costs of the laws false at it.\n * Worlds at the same distance share a ring, and the rings stacked from near to far are the spheres.\n *\n * This is only a numeric stand-in for Lewis's (1979) priorities among kinds of similarity, there so a\n * reader can move the weights and watch Fine's Nixon counterexample appear and disappear.\n */\n\nexport interface Law {\n readonly formula: Formula\n /** Default 1. */\n readonly cost?: number\n}\n\nexport interface Similarity {\n /** Atom → weight for differing from the centre on it; an atom left out weighs 1. */\n readonly weights?: Readonly<Record<string, number>>\n readonly laws?: readonly Law[]\n}\n\n/** How far one world lies from the centre, and why. */\nexport interface WorldDistance {\n readonly world: string\n readonly distance: number\n /** Atoms on which it differs from the centre. */\n readonly mismatches: readonly string[]\n /** Indexes (into `laws`) of the laws false at it. */\n readonly violations: readonly number[]\n}\n\nconst weightOf = (s: Similarity, atom: string): number => s.weights?.[atom] ?? 1\n\n/** Each world's distance from `center`, in world order. */\nexport function distances(model: ModalModel, center: string, similarity: Similarity): WorldDistance[] {\n const ev = new ModalEvaluator(model)\n const here = new Set(model.valuation[center] ?? [])\n const laws = similarity.laws ?? []\n return model.worlds.map((world) => {\n const there = new Set(model.valuation[world] ?? [])\n const mismatches = model.atoms.filter((a) => here.has(a) !== there.has(a))\n const violations = laws.flatMap((law, i) => (ev.holds(law.formula, world) ? [] : [i]))\n const distance = mismatches.reduce((d, a) => d + weightOf(similarity, a), 0) + violations.reduce((d, i) => d + ((laws[i] as Law).cost ?? 1), 0)\n return { world, distance, mismatches, violations }\n })\n}\n\n/**\n * The spheres around `center`, innermost first: the k-th holds every world within the k-th smallest\n * distance. The innermost is the centre's ring (the centre and anything no farther than it); it is\n * {center} alone, strongly centred, when every other world is farther.\n */\nexport function similaritySpheres(model: ModalModel, center: string, similarity: Similarity): string[][] {\n const ds = distances(model, center, similarity)\n const own = (ds.find((d) => d.world === center) as WorldDistance).distance\n const radii = [...new Set(ds.map((d) => Math.max(d.distance, own)))].sort((x, y) => x - y)\n const spheres = radii.map((r) => ds.filter((d) => d.distance <= r).map((d) => d.world))\n checkSystem(model.worlds, center, spheres, 'weak')\n return spheres\n}\n\n/** The same model with `center`'s spheres drawn from `similarity` (R there: every world). */\nexport function withSimilaritySpheres(model: ModalModel, center: string, similarity: Similarity): ModalModel {\n const spheres = similaritySpheres(model, center, similarity)\n return {\n ...model,\n spheres: { ...model.spheres, [center]: spheres },\n access: { ...model.access, [center]: spheres[spheres.length - 1] as string[] },\n }\n}\n","import { ModalError, modalProblem } from './errors.ts'\nimport type { Formula } from './formula.ts'\nimport { atomsOf, isTruthFunctional } from './formula.ts'\nimport { formulaText } from './print.ts'\n\n/**\n * Pearl's minimal surgery on boolean structural equations: an intervention replaces the equations of\n * the atoms it sets with constants and keeps every other equation; atoms without an equation are\n * background and keep their value at the centre world. The equations must be acyclic, so the\n * submodel has exactly one solution. No probabilities, abduction or many-valued variables: those\n * belong to the causal engine.\n */\n\n/** Atom → its truth-functional equation, e.g. war := press ∧ connected. */\nexport type Equations = Readonly<Record<string, Formula>>\n\n/** An atom assignment: atom → value. */\nexport type AtomValues = Readonly<Record<string, boolean>>\n\nfunction valueIn(f: Formula, values: AtomValues): boolean {\n switch (f.kind) {\n case 'atom':\n return values[f.id] === true\n case 'top':\n return true\n case 'bot':\n return false\n case 'not':\n return !valueIn(f.arg, values)\n case 'and':\n return valueIn(f.left, values) && valueIn(f.right, values)\n case 'or':\n return valueIn(f.left, values) || valueIn(f.right, values)\n case 'imp':\n return !valueIn(f.left, values) || valueIn(f.right, values)\n case 'iff':\n return valueIn(f.left, values) === valueIn(f.right, values)\n default:\n throw new ModalError(modalProblem('not-truth-functional', { formula: formulaText(f) }))\n }\n}\n\n/** The atoms in solving order: each after every atom its equation reads; throws `cyclic-equations` on a cycle. */\nexport function equationOrder(atoms: readonly string[], equations: Equations): string[] {\n for (const [atom, f] of Object.entries(equations)) {\n if (!atoms.includes(atom)) throw new ModalError(modalProblem('unknown-atom', { atom }))\n if (!isTruthFunctional(f)) throw new ModalError(modalProblem('not-truth-functional', { formula: formulaText(f) }))\n for (const a of atomsOf(f)) if (!atoms.includes(a)) throw new ModalError(modalProblem('unknown-atom', { atom: a }))\n }\n const order: string[] = []\n const state = new Map<string, 'open' | 'done'>()\n const visit = (atom: string, path: readonly string[]): void => {\n if (state.get(atom) === 'done') return\n if (state.get(atom) === 'open') {\n const cycle = [...path.slice(path.indexOf(atom)), atom]\n throw new ModalError(modalProblem('cyclic-equations', { cycle }))\n }\n state.set(atom, 'open')\n const f = equations[atom]\n if (f !== undefined) for (const a of atomsOf(f)) visit(a, [...path, atom])\n state.set(atom, 'done')\n order.push(atom)\n }\n for (const a of atoms) visit(a, [])\n return order\n}\n\n/**\n * The antecedent as an intervention, when it is a conjunction of atoms and negated atoms (`press`,\n * `press ∧ ¬connected`); otherwise undefined. A conjunction setting one atom both ways is undefined too.\n */\nexport function literalsOf(f: Formula): AtomValues | undefined {\n const out: Record<string, boolean> = {}\n const add = (g: Formula): boolean => {\n if (g.kind === 'and') return add(g.left) && add(g.right)\n const [atom, value] = g.kind === 'atom' ? [g.id, true] : g.kind === 'not' && g.arg.kind === 'atom' ? [g.arg.id, false] : [undefined, false]\n if (atom === undefined) return false\n if (out[atom] !== undefined && out[atom] !== value) return false\n out[atom] = value\n return true\n }\n return add(f) ? out : undefined\n}\n\nexport interface SurgeryResult {\n /** Every atom's value in the submodel's solution. */\n readonly values: AtomValues\n /** The atoms the intervention set. */\n readonly set: readonly string[]\n /** Atoms with an equation that the intervention left in place, in solving order. */\n readonly solved: readonly string[]\n}\n\n/**\n * Solve the submodel: `intervention` fixes its atoms, every other atom with an equation follows it\n * in solving order, and every atom without one keeps its value in `background` (the centre world's\n * true atoms).\n */\nexport function surgery(atoms: readonly string[], equations: Equations, background: readonly string[], intervention: AtomValues): SurgeryResult {\n for (const a of Object.keys(intervention)) if (!atoms.includes(a)) throw new ModalError(modalProblem('unknown-atom', { atom: a }))\n const order = equationOrder(atoms, equations)\n const values: Record<string, boolean> = {}\n const solved: string[] = []\n for (const atom of order) {\n const set = intervention[atom]\n const f = equations[atom]\n if (set !== undefined) values[atom] = set\n else if (f !== undefined) {\n values[atom] = valueIn(f, values)\n solved.push(atom)\n } else values[atom] = background.includes(atom)\n }\n return { values, set: atoms.filter((a) => intervention[a] !== undefined), solved }\n}\n\n/** The world of `worlds` whose true atoms are exactly those `values` makes true, if any. */\nexport function worldWith(worlds: readonly { readonly id: string; readonly true: readonly string[] }[], atoms: readonly string[], values: AtomValues): string | undefined {\n return worlds.find((w) => atoms.every((a) => w.true.includes(a) === (values[a] === true)))?.id\n}\n","import { z } from 'zod'\nimport { ATOM_PATTERN } from '../engine/formula.ts'\n\n/**\n * Modal documents, as hosts write them in JSON: a Kripke model, a frame, or a model with systems of\n * spheres. Formulas are strings in the authoring syntax (see `parseFormula`). The schema checks the\n * shape; `checkModalDoc` checks what the shape cannot say (known ids, nesting, formulas that parse).\n */\n\n/** Text in both languages, or one string for both. */\nexport const modalTextSchema = z.union([z.string(), z.object({ 'zh-TW': z.string(), en: z.string() }).strict()])\n\n/** World ids: a letter, then letters, digits or underscores (`w`, `v1`, `noon`). */\nexport const WORLD_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/\n\nconst worldId = z.string().regex(WORLD_PATTERN)\nconst pos = z.object({ x: z.number(), y: z.number() }).strict()\n\nconst atomSchema = z\n .object({\n id: z.string().regex(ATOM_PATTERN),\n label: modalTextSchema.optional(),\n })\n .strict()\n\nconst worldSchema = z\n .object({\n id: worldId,\n /** The atoms true here; every other atom is false here. */\n true: z.array(z.string()).default([]),\n label: modalTextSchema.optional(),\n pos: pos.optional(),\n })\n .strict()\n\nconst frameWorldSchema = worldSchema.omit({ true: true })\n\nconst layoutSchema = z.enum(['manual', 'circle', 'line', 'layers'])\n\nconst common = {\n id: z.string().optional(),\n title: modalTextSchema.optional(),\n /** Formulas listed by default. */\n formulas: z.array(z.string()).optional(),\n}\n\nexport const kripkeDocSchema = z\n .object({\n kind: z.literal('kripke'),\n ...common,\n atoms: z.array(atomSchema).default([]),\n worlds: z.array(worldSchema).min(1),\n access: z.array(z.tuple([worldId, worldId])).default([]),\n /** The actual world, selected first. */\n actual: worldId.optional(),\n layout: layoutSchema.default('circle'),\n })\n .strict()\n\nexport const frameDocSchema = z\n .object({\n kind: z.literal('frame'),\n id: common.id,\n title: common.title,\n worlds: z.array(frameWorldSchema).min(1),\n access: z.array(z.tuple([worldId, worldId])).default([]),\n actual: worldId.optional(),\n layout: layoutSchema.default('circle'),\n })\n .strict()\n\nconst lawSchema = z\n .object({\n formula: z.string(),\n /** The cost of a world where the law is false (a miracle); default 1. */\n cost: z.number().nonnegative().default(1),\n label: modalTextSchema.optional(),\n })\n .strict()\n\nexport const spheresDocSchema = z\n .object({\n kind: z.literal('spheres'),\n ...common,\n atoms: z.array(atomSchema).default([]),\n worlds: z.array(worldSchema).min(1),\n /** The world the spheres are drawn around. */\n center: worldId.optional(),\n /** The centre's spheres, innermost first. */\n spheres: z.array(z.array(worldId)).optional(),\n /** A system per world, for nested counterfactuals; instead of `center` and `spheres`. */\n systems: z.record(z.string(), z.array(z.array(worldId))).optional(),\n /** Spheres around `center` from weights and laws, instead of `spheres`. */\n similarity: z\n .object({\n weights: z.record(z.string(), z.number().nonnegative()).default({}),\n laws: z.array(lawSchema).default([]),\n })\n .strict()\n .optional(),\n centering: z.enum(['strong', 'weak']).default('strong'),\n /** Boolean structural equations for minimal surgery: atom → formula. */\n structural: z.object({ equations: z.record(z.string(), z.string()) }).strict().optional(),\n })\n .strict()\n\nexport const modalDocSchema = z.discriminatedUnion('kind', [kripkeDocSchema, frameDocSchema, spheresDocSchema])\n\nexport type ModalText = z.infer<typeof modalTextSchema>\nexport type KripkeDoc = z.infer<typeof kripkeDocSchema>\nexport type FrameDoc = z.infer<typeof frameDocSchema>\nexport type SpheresDoc = z.infer<typeof spheresDocSchema>\n/** A checked document. */\nexport type ModalDoc = z.infer<typeof modalDocSchema>\n/** A document as written, before defaults are filled in. */\nexport type ModalDocInput = z.input<typeof modalDocSchema>\nexport type KripkeDocInput = z.input<typeof kripkeDocSchema>\nexport type FrameDocInput = z.input<typeof frameDocSchema>\nexport type SpheresDocInput = z.input<typeof spheresDocSchema>\n","import type { z } from 'zod'\nimport zhTW from 'zod/v4/locales/zh-TW.js'\nimport type { Locale } from '../../engine/types.ts'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblem, modalProblemOf } from '../engine/errors.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport { isAtomId, isTruthFunctional, parseFormula } from '../engine/formula.ts'\nimport type { Frame, ModalModel } from '../engine/model.ts'\nimport { checkSystem, frameOf, kripkeModel, sphereModel } from '../engine/model.ts'\nimport { formulaText } from '../engine/print.ts'\nimport type { Similarity } from '../engine/similarity.ts'\nimport { withSimilaritySpheres } from '../engine/similarity.ts'\nimport { equationOrder } from '../engine/surgery.ts'\nimport type { FrameDoc, KripkeDoc, ModalDoc, ModalText, SpheresDoc } from './schema.ts'\nimport { modalDocSchema } from './schema.ts'\n\n/** The most worlds a document may draw. */\nexport const MAX_DOC_WORLDS = 12\n\n/** The longest JSON text `parseModalJson` reads. */\nexport const MAX_MODAL_DOC_CHARS = 200_000\n\nexport type ModalImportResult = { readonly ok: true; readonly doc: ModalDoc } | { readonly ok: false; readonly errors: readonly ModalProblem[] }\n\nconst zhIssue = zhTW().localeError\n\nfunction schemaProblems(error: { readonly issues: readonly z.core.$ZodIssue[] }): ModalProblem[] {\n return error.issues.map((issue) => {\n const zh = zhIssue(issue as unknown as z.core.$ZodRawIssue)\n const zhText = typeof zh === 'string' ? zh : (zh?.message ?? issue.message)\n return modalProblem('schema', { message: { 'zh-TW': zhText, en: issue.message } }, issue.path.map(String).join('.'))\n })\n}\n\n/** Runs `f`; one of our errors comes back as a problem at `where`. */\nfunction attempt(problems: ModalProblem[], where: string, f: () => void): void {\n try {\n f()\n } catch (error) {\n const p = modalProblemOf(error)\n if (p === undefined) throw error\n problems.push({ ...p, where })\n }\n}\n\nfunction parseInto(problems: ModalProblem[], where: string, text: string, truthFunctional = false): void {\n attempt(problems, where, () => {\n const f = parseFormula(text)\n if (truthFunctional && !isTruthFunctional(f)) problems.push(modalProblem('not-truth-functional', { formula: formulaText(f) }, where))\n })\n}\n\n/** Everything the schema cannot say: known and unique ids, nesting and centring, formulas that parse. */\nexport function checkModalDoc(doc: ModalDoc): ModalProblem[] {\n const problems: ModalProblem[] = []\n const worlds = doc.worlds.map((w) => w.id)\n if (worlds.length > MAX_DOC_WORLDS) problems.push(modalProblem('too-many-worlds', { count: worlds.length, limit: MAX_DOC_WORLDS }, 'worlds'))\n const seen = new Set<string>()\n doc.worlds.forEach((w, i) => {\n if (seen.has(w.id)) problems.push(modalProblem('duplicate-world', { world: w.id }, `worlds.${i}.id`))\n seen.add(w.id)\n if (doc.kind !== 'spheres' && doc.layout === 'manual' && w.pos === undefined) problems.push(modalProblem('missing-position', { world: w.id }, `worlds.${i}.pos`))\n })\n const knownWorld = (w: string, where: string): void => {\n if (!seen.has(w)) problems.push(modalProblem('unknown-world', { world: w }, where))\n }\n if (doc.kind !== 'frame') {\n const atoms = new Set<string>()\n doc.atoms.forEach((a, i) => {\n if (!isAtomId(a.id)) problems.push(modalProblem('reserved-atom', { atom: a.id }, `atoms.${i}.id`))\n if (atoms.has(a.id)) problems.push(modalProblem('duplicate-atom', { atom: a.id }, `atoms.${i}.id`))\n atoms.add(a.id)\n })\n doc.worlds.forEach((w, i) => {\n w.true.forEach((a, k) => {\n if (!atoms.has(a)) problems.push(modalProblem('unknown-atom', { atom: a }, `worlds.${i}.true.${k}`))\n })\n })\n doc.formulas?.forEach((text, i) => parseInto(problems, `formulas.${i}`, text))\n }\n if (doc.kind === 'kripke' || doc.kind === 'frame') {\n doc.access.forEach(([a, b], i) => {\n knownWorld(a, `access.${i}.0`)\n knownWorld(b, `access.${i}.1`)\n })\n if (doc.actual !== undefined) knownWorld(doc.actual, 'actual')\n return problems\n }\n checkSpheres(doc, worlds, problems, knownWorld)\n return problems\n}\n\nfunction checkSpheres(doc: SpheresDoc, worlds: readonly string[], problems: ModalProblem[], knownWorld: (w: string, where: string) => void): void {\n const sources = [doc.spheres !== undefined, doc.systems !== undefined, doc.similarity !== undefined].filter(Boolean).length\n if (sources !== 1 || (doc.systems === undefined) !== (doc.center !== undefined)) {\n problems.push(modalProblem('spheres-source', {}))\n }\n if (doc.center !== undefined) knownWorld(doc.center, 'center')\n if (problems.length > 0) return\n const systems: Record<string, readonly (readonly string[])[]> = doc.systems ?? (doc.spheres !== undefined && doc.center !== undefined ? { [doc.center]: doc.spheres } : {})\n for (const [w, system] of Object.entries(systems)) {\n const where = doc.systems !== undefined ? `systems.${w}` : 'spheres'\n attempt(problems, where, () => checkSystem(worlds, w, system, doc.centering))\n }\n doc.similarity?.laws.forEach((law, i) => parseInto(problems, `similarity.laws.${i}.formula`, law.formula, true))\n const atoms = new Set(doc.atoms.map((a) => a.id))\n for (const atom of Object.keys(doc.similarity?.weights ?? {})) {\n if (!atoms.has(atom)) problems.push(modalProblem('unknown-atom', { atom }, `similarity.weights.${atom}`))\n }\n if (doc.structural !== undefined) {\n const before = problems.length\n for (const [atom, text] of Object.entries(doc.structural.equations)) parseInto(problems, `structural.equations.${atom}`, text, true)\n if (problems.length === before) {\n attempt(problems, 'structural.equations', () => {\n equationOrder(doc.atoms.map((a) => a.id), structuralEquations(doc))\n })\n }\n }\n}\n\n/**\n * Read a document from JSON text or an already parsed value. Never throws: what is wrong comes back as\n * `errors`, each a {@link ModalProblem} with the path where it sits.\n */\nexport function parseModalJson(input: string | unknown): ModalImportResult {\n let raw: unknown = input\n if (typeof input === 'string') {\n if (input.length > MAX_MODAL_DOC_CHARS) return { ok: false, errors: [modalProblem('too-large', {})] }\n try {\n raw = JSON.parse(input)\n } catch (error) {\n return { ok: false, errors: [modalProblem('not-json', { detail: (error as Error).message })] }\n }\n }\n const parsed = modalDocSchema.safeParse(raw)\n if (!parsed.success) return { ok: false, errors: schemaProblems(parsed.error) }\n const problems = checkModalDoc(parsed.data)\n return problems.length > 0 ? { ok: false, errors: problems } : { ok: true, doc: parsed.data }\n}\n\n/** A frame document, or a Kripke document with its valuation ignored, as a frame. */\nexport function frameOfDoc(doc: FrameDoc | KripkeDoc): Frame {\n return frameOf(\n doc.worlds.map((w) => w.id),\n doc.access,\n )\n}\n\n/** The similarity a spheres document gives, with `weights` overriding its own. */\nexport function similarityOf(doc: SpheresDoc, weights?: Readonly<Record<string, number>>): Similarity {\n return {\n weights: { ...doc.similarity?.weights, ...weights },\n laws: (doc.similarity?.laws ?? []).map((law) => ({ formula: parseFormula(law.formula), cost: law.cost })),\n }\n}\n\n/** The structural equations of a spheres document, parsed. */\nexport function structuralEquations(doc: SpheresDoc): Record<string, Formula> {\n return Object.fromEntries(Object.entries(doc.structural?.equations ?? {}).map(([atom, text]) => [atom, parseFormula(text)]))\n}\n\n/**\n * The model a checked document describes. A frame has no atoms. A spheres document gets its systems\n * as written, or the centre's spheres from its similarity (with `weights` overriding the document's).\n */\nexport function modelOfDoc(doc: ModalDoc, weights?: Readonly<Record<string, number>>): ModalModel {\n const atoms = doc.kind === 'frame' ? [] : doc.atoms.map((a) => a.id)\n const worlds = doc.worlds.map((w) => ({ id: w.id, true: 'true' in w ? w.true : [] }))\n if (doc.kind !== 'spheres') return kripkeModel({ atoms, worlds, access: doc.access })\n if (doc.similarity !== undefined && doc.center !== undefined) {\n return withSimilaritySpheres(sphereModel({ atoms, worlds, systems: {} }), doc.center, similarityOf(doc, weights))\n }\n const systems = doc.systems ?? (doc.center !== undefined && doc.spheres !== undefined ? { [doc.center]: doc.spheres } : {})\n return sphereModel({ atoms, worlds, systems, centering: doc.centering })\n}\n\n/** The world a figure starts at: `actual`, the centre, or the first world. */\nexport function startWorld(doc: ModalDoc): string {\n if (doc.kind === 'spheres') return doc.center ?? (Object.keys(doc.systems ?? {})[0] as string | undefined) ?? (doc.worlds[0] as { id: string }).id\n return doc.actual ?? (doc.worlds[0] as { id: string }).id\n}\n\n/** Document text in `locale`. */\nexport function modalText(text: ModalText | undefined, locale: Locale): string | undefined {\n if (text === undefined) return undefined\n return typeof text === 'string' ? text : text[locale]\n}\n","import type { ReactNode } from 'react'\nimport { createContext, createElement, useContext } from 'react'\nimport type { Problem } from '../../engine/errors.ts'\nimport { problemText } from '../../engine/errors.ts'\nimport type { Locale } from '../../engine/types.ts'\nimport type { DraftIssue } from './common.ts'\nimport { EN } from './en.ts'\nimport type { Messages } from './zh.ts'\nimport { ZH } from './zh.ts'\n\n/**\n * Every piece of interface text, in Traditional Chinese (the default, zh.ts) and English (en.ts).\n * Components take their table from {@link useMessages}; pure helpers take it as an argument.\n */\n\nexport type { Locale }\nexport type { DraftIssue, NodeToggle } from './common.ts'\nexport { AUTHOR_EN, AUTHOR_ZH } from './common.ts'\nexport type { Messages } from './zh.ts'\n\nexport const DEFAULT_LOCALE: Locale = 'zh-TW'\n\n/** Each language by its own name, for language switches. */\nexport const LANGUAGE_NAMES: Readonly<Record<Locale, string>> = { 'zh-TW': '中文', en: 'English' }\n\nexport const MESSAGES: Readonly<Record<Locale, Messages>> = { 'zh-TW': ZH, en: EN }\n\nexport function messagesFor(locale: Locale): Messages {\n return MESSAGES[locale]\n}\n\n/** A problem from the engine or the data layer, worded in the table's language. */\nexport function problemMessage(p: Problem, t: Messages): string {\n return problemText(p, t.problems)\n}\n\n/** Any thrown value as text: our problems per locale, anything else by its own message. */\nexport function errorMessage(error: unknown, t: Messages): string {\n if (typeof error === 'object' && error !== null && 'problem' in error) {\n return problemMessage((error as { problem: Problem }).problem, t)\n }\n return error instanceof Error ? error.message : String(error)\n}\n\nexport function draftIssueMessage(issue: DraftIssue, t: Messages): string {\n return (t.draft[issue.code] as (i: DraftIssue) => string)(issue)\n}\n\nconst LocaleContext = createContext<Locale>(DEFAULT_LOCALE)\n\n/** Sets the language for every logic-atlas component inside it; a component's own `locale` prop wins. */\nexport function LocaleProvider({ locale, children }: { readonly locale: Locale; readonly children?: ReactNode }) {\n return createElement(LocaleContext.Provider, { value: locale }, children)\n}\n\n/** Wraps `children` in `locale` when given, else leaves the surrounding language in force. */\nexport function LocaleScope({ locale, children }: { readonly locale?: Locale; readonly children?: ReactNode }) {\n return locale === undefined ? children : createElement(LocaleContext.Provider, { value: locale }, children)\n}\n\n/** The language in force. */\nexport function useLocale(): Locale {\n return useContext(LocaleContext)\n}\n\nexport function useMessages(): Messages {\n return MESSAGES[useContext(LocaleContext)]\n}\n","import type { ModalProblemWording } from '../engine/errors.ts'\nimport { MODAL_PROBLEMS_EN } from '../engine/errors.ts'\nimport type { FrameCondition, ModalSystem } from '../engine/frames.ts'\nimport type { TcsPattern } from '../engine/inference.ts'\nimport type { ModalMessages } from './zh.ts'\n\n/** The modal components' interface text in English. */\n\nconst list = (xs: readonly string[]): string => (xs.length <= 2 ? xs.join(' and ') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`)\nconst set = (xs: readonly string[]): string => (xs.length === 0 ? '∅' : `{${xs.join(', ')}}`)\n\nconst EN_PROBLEMS: ModalProblemWording = MODAL_PROBLEMS_EN\n\nexport const MODAL_EN: ModalMessages = {\n locale: 'en',\n problems: EN_PROBLEMS,\n docInvalid: 'This model cannot be drawn:',\n trueWord: 'true',\n falseWord: 'false',\n world: 'World',\n formula: 'Formula',\n formulas: 'Formulas',\n truthSet: 'Truth set',\n intensionCaption: 'Intension: each world gives the sentence a truth value',\n selectWorld: (w) => `Select world ${w}`,\n selectFormula: (f) => `Select formula ${f}`,\n worldGraph: (n) => `Possible worlds, ${n} ${n === 1 ? 'world' : 'worlds'}`,\n worldState: (w, atoms) => (atoms.length === 0 ? `World ${w}: no atom true` : `World ${w}: ${list(atoms)} true`),\n atomsHeading: 'Atoms',\n at: (w) => `At ${w}`,\n noAccess: (w) => `${w} sees no world`,\n boxTrue: (w, arg, seen) => (seen.length === 0 ? `${w} sees no world, so □${arg} is vacuously true.` : `Every world ${w} sees (${list(seen)}) makes ${arg} true.`),\n boxFalse: (w, arg, v) => `${w} sees ${v}, where ${arg} is false: a counterexample.`,\n diaTrue: (w, arg, v) => `${w} sees ${v}, where ${arg} is true: a witness.`,\n diaFalse: (w, arg, seen) => (seen.length === 0 ? `${w} sees no world, so ◇${arg} is false.` : `Every world ${w} sees (${list(seen)}) makes ${arg} false.`),\n plainValue: (w, value) => `${value ? 'True' : 'False'} at ${w}.`,\n customFormula: 'Type a formula',\n add: 'Add',\n editHeading: 'Edit the model',\n accessHeading: 'Accessibility',\n accessToggle: (a, b) => `${a} sees ${b}`,\n atomToggle: (w, atom) => `${atom} true at ${w}`,\n showFalse: 'Also list false atoms',\n conditionHeading: 'Frame condition',\n holdsHeading: 'Holds',\n axiomHeading: 'Axiom',\n validHeading: 'Valid on the frame',\n conditionName: { serial: 'serial', reflexive: 'reflexive', transitive: 'transitive', symmetric: 'symmetric', euclidean: 'euclidean' } satisfies Readonly<Record<FrameCondition, string>>,\n conditionRule: {\n serial: 'every world sees some world',\n reflexive: 'every world sees itself',\n transitive: 'if wRv and vRu, then wRu',\n symmetric: 'if wRv, then vRw',\n euclidean: 'if wRv and wRu, then vRu',\n } satisfies Readonly<Record<FrameCondition, string>>,\n conditionWitness: (c, w) => {\n const [a = '', b = '', d = ''] = w\n switch (c) {\n case 'serial':\n return `${a} sees no world`\n case 'reflexive':\n return `${a} does not see itself`\n case 'symmetric':\n return `${a}R${b} but not ${b}R${a}`\n case 'transitive':\n return `${a}R${b} and ${b}R${d} but not ${a}R${d}`\n case 'euclidean':\n return `${a}R${b} and ${a}R${d} but not ${b}R${d}`\n }\n },\n axiomName: (name) => (name === 'M' ? 'M (also called T)' : name),\n axiomCounterexample: (trueAt, w) =>\n `with ${Object.entries(trueAt)\n .map(([a, ws]) => `${a} true exactly at ${set(ws)}`)\n .join(' and ')}, the axiom is false at ${w}`,\n yes: 'yes',\n no: 'no',\n systemName: (s: ModalSystem) => (s === 'M' ? 'M (also called T)' : s),\n systemsLine: (names) => `This frame is in the frame classes of ${list(names)}.`,\n materialHeading: 'Material conditional',\n strictHeading: 'Strict implication',\n strictTrue: (w) => `At every world ${w} sees where the antecedent is true, the consequent is true too.`,\n strictFalse: (w, bad) => `${w} sees ${list(bad)}, where the antecedent is true and the consequent false.`,\n materialTrue: (w, aFalse) => (aFalse ? `At ${w} the antecedent is false, so the material conditional is true.` : `At ${w} antecedent and consequent are both true.`),\n materialFalse: (w) => `At ${w} the antecedent is true and the consequent false.`,\n patternName: { transitivity: 'Transitivity', contraposition: 'Contraposition', strengthening: 'Strengthening the antecedent' } satisfies Readonly<Record<TcsPattern, string>>,\n exampleTitle: (pattern, title) => `${pattern}: ${title}`,\n premise: 'Premise',\n conclusion: 'Conclusion',\n counterfactualHeading: 'Spheres (counterfactual)',\n collapse: 'Press into one sphere',\n collapseHint: 'Press all spheres into the outermost one: every antecedent then uses the same range of worlds, and the counterfactual becomes strict implication.',\n inferenceCounterexample: (w) => `At ${w} the premises are true and the conclusion false: the inference fails.`,\n inferenceHolds: (w) => `At ${w} no premise set is true with the conclusion false: the inference holds.`,\n inferenceVacuous: (w) => `At ${w} not every premise is true, so there is no counterexample here.`,\n semanticsLabel: 'Semantics for conditionals',\n sphereName: (i) => `S${i + 1}`,\n center: 'centre',\n antecedentWorlds: 'Antecedent worlds',\n closestWorlds: 'Closest antecedent worlds',\n closestList: (ws) => `Closest antecedent worlds: ${list(ws)}`,\n vacuous: 'No sphere holds an antecedent world, so the conditional is vacuously true.',\n smallestSphere: (s, ws) => `The smallest sphere holding an antecedent world is ${s}; its antecedent worlds are ${list(ws)}.`,\n cfTrue: 'Every closest antecedent world makes the consequent true, so the conditional is true.',\n cfFalse: (ws) => `${list(ws)} ${ws.length === 1 ? 'makes' : 'make'} the consequent false, so the conditional is false.`,\n notUnique: (ws) => `Stalnaker's selection function is undefined here: the closest antecedent worlds are ${list(ws)}, more than one. Conditional excluded middle is not guaranteed.`,\n needsConditional: 'Choose a formula of the form A > B.',\n similarityHeading: 'By similarity (Lewis)',\n surgeryHeading: 'Minimal surgery (Pearl)',\n weightsHeading: 'Weights',\n weightLabel: (atom) => `differs from the actual ${atom}`,\n lawLabel: (law) => `violates ${law}`,\n distance: 'Distance',\n approxNote: 'Distance as a sum of weights is only a numeric stand-in for Lewis’s (1979) priorities of similarity.',\n intervention: (vals) => `Intervention: ${vals} replaced by constants, every other equation kept; atoms without an equation keep their value at the centre.`,\n solution: 'The submodel’s solution',\n solutionWorld: (w) => (w === undefined ? 'No world in the model matches this solution.' : `This solution is world ${w}.`),\n agree: 'The two semantics agree.',\n diverge: 'The two semantics disagree.',\n equationsHeading: 'Structural equations',\n}\n","import type { Locale } from '../../engine/types.ts'\nimport type { ModalProblemWording } from '../engine/errors.ts'\nimport type { FrameCondition, ModalSystem } from '../engine/frames.ts'\nimport type { TcsPattern } from '../engine/inference.ts'\n\n/** The modal components' interface text in Traditional Chinese, the default; its shape is the {@link ModalMessages} type. */\n\nconst list = (xs: readonly string[]): string => xs.join('、')\nconst set = (xs: readonly string[]): string => (xs.length === 0 ? '∅' : `{${xs.join(', ')}}`)\nconst pos = (p: { readonly position: number }): string => `(第 ${p.position + 1} 個字)`\n\nconst ZH_PROBLEMS: ModalProblemWording = {\n join: (where, message) => `${where}:${message}`,\n messages: {\n 'parse-unexpected-character': (p) => `看不懂字元 ${p.character}${pos(p)}`,\n 'parse-unexpected-token': (p) => `多出了 ${p.token}${pos(p)}`,\n 'parse-unexpected-end': (p) => `公式還沒寫完${pos(p)}`,\n 'parse-expected': (p) => `這裡要有 ${p.expected}${pos(p)}`,\n 'ambiguous-mix': (p) => `${p.operators} 並列時要加括號${pos(p)}`,\n 'reserved-atom': (p) => `${p.atom} 是保留字,不能當原子`,\n 'unknown-atom': (p) => `沒有原子 ${p.atom}`,\n 'unknown-world': (p) => `沒有世界 ${p.world}`,\n 'duplicate-world': (p) => `世界 ${p.world} 重複了`,\n 'duplicate-atom': (p) => `原子 ${p.atom} 重複了`,\n 'no-worlds': () => '模型裡沒有世界',\n 'too-many-worlds': (p) => `有 ${p.count} 個世界,上限是 ${p.limit} 個`,\n 'missing-position': (p) => `手動版面需要世界 ${p.world} 的位置`,\n 'no-sphere-system': (p) => `世界 ${p.world} 沒有同心球系統`,\n 'spheres-not-nested': (p) => `${p.world} 的第 ${p.index} 層同心球沒有包含內層`,\n 'empty-sphere': (p) => `${p.world} 的第 ${p.index} 層同心球是空的`,\n centering: (p) => (p.centering === 'strong' ? `${p.world} 的最內層同心球必須恰為 {${p.world}}` : `${p.world} 的最內層同心球必須包含 ${p.world}`),\n 'spheres-source': () => '同心球只能用一種方式給:center 加 spheres、center 加 similarity,或 systems',\n 'not-unique': (p) => `Stalnaker 的選擇在 ${p.world} 沒有定義:最接近的前件世界有 ${list(p.candidates)}`,\n 'too-many-assignments': (p) => `要窮舉 ${p.count.toLocaleString('en-US')} 種指派,上限是 ${p.limit.toLocaleString('en-US')} 種`,\n 'cyclic-equations': (p) => `方程繞成一圈:${p.cycle.join(' → ')}`,\n 'not-truth-functional': (p) => `${p.formula} 只能用真值函數連接詞(不能有 □、◇ 或 >)`,\n 'surgery-antecedent': (p) => `小手術需要原子或否定原子的連言,${p.formula} 不是`,\n 'needs-similarity': () => '這張圖需要有 center、similarity 與 structural 結構方程的同心球文件',\n 'not-json': (p) => `不是 JSON:${p.detail}`,\n 'too-large': () => '文件太大了',\n 'wrong-kind': (p) => `這張圖需要 ${p.expected.join(' 或 ')} 文件,不是 ${p.kind}`,\n schema: (p) => p.message['zh-TW'],\n },\n}\n\nexport const MODAL_ZH = {\n locale: 'zh-TW' as Locale,\n problems: ZH_PROBLEMS,\n docInvalid: '這個模型無法繪出:',\n trueWord: '真',\n falseWord: '假',\n world: '世界',\n formula: '公式',\n formulas: '公式',\n truthSet: '真值集合',\n intensionCaption: '內涵:每個世界各給句子一個真值',\n selectWorld: (w: string) => `選擇世界 ${w}`,\n selectFormula: (f: string) => `選擇公式 ${f}`,\n worldGraph: (n: number) => `可能世界圖,${n} 個世界`,\n worldState: (w: string, atoms: readonly string[]) => (atoms.length === 0 ? `世界 ${w}:沒有原子為真` : `世界 ${w}:${list(atoms)} 為真`),\n atomsHeading: '原子',\n at: (w: string) => `在 ${w}`,\n noAccess: (w: string) => `${w} 沒有可及的世界`,\n boxTrue: (w: string, arg: string, seen: readonly string[]) =>\n seen.length === 0 ? `${w} 沒有可及的世界,所以 □${arg} 空真。` : `${w} 可及的每個世界(${list(seen)})都使 ${arg} 為真。`,\n boxFalse: (w: string, arg: string, v: string) => `${w} 可及 ${v},而 ${arg} 在 ${v} 為假:這是反例。`,\n diaTrue: (w: string, arg: string, v: string) => `${w} 可及 ${v},而 ${arg} 在 ${v} 為真:這是證人。`,\n diaFalse: (w: string, arg: string, seen: readonly string[]) =>\n seen.length === 0 ? `${w} 沒有可及的世界,所以 ◇${arg} 為假。` : `${w} 可及的世界(${list(seen)})都使 ${arg} 為假。`,\n plainValue: (w: string, value: boolean) => `在 ${w} 為${value ? '真' : '假'}。`,\n customFormula: '自己輸入公式',\n add: '加入',\n editHeading: '編輯模型',\n accessHeading: '可及關係',\n accessToggle: (a: string, b: string) => `${a} 可及 ${b}`,\n atomToggle: (w: string, atom: string) => `${atom} 在 ${w} 為真`,\n showFalse: '也列出為假的原子',\n // frames\n conditionHeading: '框架條件',\n holdsHeading: '成立',\n axiomHeading: '對應公理',\n validHeading: '在框架上有效',\n conditionName: { serial: '序列的', reflexive: '自反的', transitive: '遞移的', symmetric: '對稱的', euclidean: '歐氏的' } as Readonly<Record<FrameCondition, string>>,\n conditionRule: {\n serial: '每個世界至少可及一個世界',\n reflexive: '每個世界都可及自己',\n transitive: '若 wRv 且 vRu,則 wRu',\n symmetric: '若 wRv,則 vRw',\n euclidean: '若 wRv 且 wRu,則 vRu',\n } as Readonly<Record<FrameCondition, string>>,\n conditionWitness: (c: FrameCondition, w: readonly string[]): string => {\n const [a = '', b = '', d = ''] = w\n switch (c) {\n case 'serial':\n return `${a} 看不到任何世界`\n case 'reflexive':\n return `${a} 看不到自己`\n case 'symmetric':\n return `${a}R${b},但沒有 ${b}R${a}`\n case 'transitive':\n return `${a}R${b}、${b}R${d},但沒有 ${a}R${d}`\n case 'euclidean':\n return `${a}R${b}、${a}R${d},但沒有 ${b}R${d}`\n }\n },\n axiomName: (name: string) => (name === 'M' ? 'M(又稱 T)' : name),\n axiomCounterexample: (trueAt: Readonly<Record<string, readonly string[]>>, w: string) =>\n `${Object.entries(trueAt)\n .map(([a, ws]) => `${a} 只在 ${set(ws)} 為真`)\n .join('、')}時,公理在 ${w} 為假`,\n yes: '是',\n no: '否',\n systemName: (s: ModalSystem) => (s === 'M' ? 'M(又稱 T)' : s),\n systemsLine: (names: readonly string[]) => `這個框架屬於 ${list(names)} 的框架類。`,\n // strict implication\n materialHeading: '實質蘊涵',\n strictHeading: '嚴格蘊涵',\n strictTrue: (w: string) => `${w} 可及的每個前件為真的世界,後件也為真。`,\n strictFalse: (w: string, bad: readonly string[]) => `${w} 可及的 ${list(bad)} 使前件為真、後件為假。`,\n materialTrue: (w: string, aFalse: boolean) => (aFalse ? `在 ${w} 前件為假,所以實質條件句為真。` : `在 ${w} 前件與後件都為真。`),\n materialFalse: (w: string) => `在 ${w} 前件為真、後件為假。`,\n // TCS\n patternName: { transitivity: '傳遞', contraposition: '換質換位', strengthening: '加強前件' } as Readonly<Record<TcsPattern, string>>,\n exampleTitle: (pattern: string, title: string) => `${pattern}:${title}`,\n premise: '前提',\n conclusion: '結論',\n counterfactualHeading: '同心球(反事實條件句)',\n collapse: '壓成一層',\n collapseHint: '把所有同心球壓成最外層的一個:每個前件都用同一個可及範圍,反事實條件句就變成嚴格蘊涵。',\n inferenceCounterexample: (w: string) => `在 ${w} 前提都為真、結論為假:推論失效。`,\n inferenceHolds: (w: string) => `在 ${w} 沒有前提真而結論假:推論成立。`,\n inferenceVacuous: (w: string) => `在 ${w} 前提不全為真,這裡找不到反例。`,\n // spheres\n semanticsLabel: '條件句語意',\n sphereName: (i: number) => `S${i + 1}`,\n center: '中心',\n antecedentWorlds: '前件世界',\n closestWorlds: '最接近的前件世界',\n closestList: (ws: readonly string[]) => `最接近的前件世界:${list(ws)}`,\n vacuous: '沒有任何同心球含前件世界,所以條件句空真。',\n smallestSphere: (s: string, ws: readonly string[]) => `含前件世界的最小同心球是 ${s},其中的前件世界是 ${list(ws)}。`,\n cfTrue: '最接近的前件世界都使後件為真,所以條件句為真。',\n cfFalse: (ws: readonly string[]) => `${list(ws)} 使後件為假,所以條件句為假。`,\n notUnique: (ws: readonly string[]) => `Stalnaker 的選擇函數在這裡沒有定義:最接近的前件世界有 ${list(ws)},不只一個。條件排中律因此不保證成立。`,\n needsConditional: '請選擇一個 A > B 形式的公式。',\n // surgery\n similarityHeading: '依相似度(Lewis)',\n surgeryHeading: '小手術(Pearl)',\n weightsHeading: '權重',\n weightLabel: (atom: string) => `與實際的 ${atom} 不同`,\n lawLabel: (law: string) => `違反 ${law}`,\n distance: '距離',\n approxNote: '以權重加總計算距離,只是 Lewis(1979)相似度優先序的數值近似。',\n intervention: (vals: string) => `干預:把 ${vals} 換成常數,其他方程保留;沒有方程的原子固定在中心世界的值。`,\n solution: '子模型的解',\n solutionWorld: (w: string | undefined) => (w === undefined ? '模型裡沒有與這個解相同的世界。' : `這個解就是世界 ${w}。`),\n agree: '兩種語意給出相同的判斷。',\n diverge: '兩種語意給出不同的判斷。',\n equationsHeading: '結構方程',\n} as const\n\nexport type ModalMessages = {\n readonly [K in keyof typeof MODAL_ZH]: K extends 'locale'\n ? Locale\n : (typeof MODAL_ZH)[K] extends (...args: infer A) => infer R ? (...args: A) => R extends string ? string : R : (typeof MODAL_ZH)[K] extends string ? string : (typeof MODAL_ZH)[K]\n}\n","import type { Locale } from '../../engine/types.ts'\nimport { useLocale } from '../../components/i18n/messages.ts'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblemOf, modalProblemText } from '../engine/errors.ts'\nimport { MODAL_EN } from './en.ts'\nimport type { ModalMessages } from './zh.ts'\nimport { MODAL_ZH } from './zh.ts'\n\n/**\n * The modal components' text, in Traditional Chinese (zh.ts, the default) and English (en.ts). The\n * language comes from the same {@link useLocale} as the causal components, so one `LocaleProvider`\n * sets both; the tables stay apart so neither family loads the other's.\n */\n\nexport type { ModalMessages }\n\nexport const MODAL_MESSAGES: Readonly<Record<Locale, ModalMessages>> = { 'zh-TW': MODAL_ZH, en: MODAL_EN }\n\nexport function useModalMessages(): ModalMessages {\n return MODAL_MESSAGES[useLocale()]\n}\n\nexport function modalProblemMessage(p: ModalProblem, t: ModalMessages): string {\n return modalProblemText(p, t.problems)\n}\n\n/** Any thrown value as text: our problems per locale, anything else by its own message. */\nexport function modalErrorMessage(error: unknown, t: ModalMessages): string {\n const p = modalProblemOf(error)\n if (p !== undefined) return modalProblemMessage(p, t)\n return error instanceof Error ? error.message : String(error)\n}\n","import type { Locale } from '../../engine/types.ts'\nimport type { ModalNotation } from '../engine/print.ts'\nimport { operatorSymbol } from '../engine/print.ts'\nimport { modalText } from '../data/load.ts'\nimport type { FrameDoc, KripkeDoc, SpheresDoc } from '../data/schema.ts'\nimport type { GraphInput } from './world-graph.ts'\n\n/** From a checked document to what the pictures draw: world names and box lines. Pure. */\n\ntype AnyDoc = KripkeDoc | FrameDoc | SpheresDoc\n\n/** Each world's display name: its label in `locale`, else its id. */\nexport function worldNames(doc: AnyDoc, locale: Locale): ReadonlyMap<string, string> {\n return new Map(doc.worlds.map((w) => [w.id, modalText(w.label, locale) ?? w.id]))\n}\n\n/** The names of `ids`, in order. */\nexport function namesOf(names: ReadonlyMap<string, string>, ids: readonly string[]): string[] {\n return ids.map((id) => names.get(id) ?? id)\n}\n\n/** The lines in a world's box: its true atoms, then (when asked) its false ones negated. */\nexport function boxLines(atoms: readonly string[], trueHere: readonly string[], showFalse: boolean, notation: ModalNotation): string[] {\n const not = operatorSymbol('not', notation).text\n const lines = atoms.filter((a) => trueHere.includes(a))\n return showFalse ? [...lines, ...atoms.filter((a) => !trueHere.includes(a)).map((a) => `${not}${a}`)] : lines\n}\n\n/** The graph a Kripke or frame document draws, with `valuation` and `pairs` overriding its own (the editor's state). */\nexport function docGraphInput(\n doc: KripkeDoc | FrameDoc,\n locale: Locale,\n options: {\n readonly showFalse: boolean\n readonly notation: ModalNotation\n readonly mergeSymmetric: boolean\n readonly valuation?: Readonly<Record<string, readonly string[]>>\n readonly pairs?: readonly (readonly [string, string])[]\n },\n): GraphInput {\n const names = worldNames(doc, locale)\n const atoms = doc.kind === 'kripke' ? doc.atoms.map((a) => a.id) : []\n return {\n worlds: doc.worlds.map((w) => ({\n id: w.id,\n name: names.get(w.id) ?? w.id,\n lines: boxLines(atoms, options.valuation?.[w.id] ?? ('true' in w ? w.true : []), options.showFalse, options.notation),\n pos: w.pos,\n })),\n pairs: options.pairs ?? doc.access,\n layout: doc.layout,\n root: doc.actual,\n mergeSymmetric: options.mergeSymmetric,\n }\n}\n","import type { Explanation, ModalEvaluator } from '../engine/evaluate.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport { formulaText } from '../engine/print.ts'\nimport type { ModalMessages } from '../i18n/messages.ts'\nimport { namesOf } from './doc-graph.ts'\nimport type { ParsedFormula } from './use-doc.ts'\nimport type { WorldMark } from './WorldGraph.tsx'\n\n/** Words and marks for a formula's value at a world. Pure. */\n\n/** The sentence that says why `e` has its value. */\nexport function explanationText(e: Explanation, names: ReadonlyMap<string, string>, t: ModalMessages, notation: 'modern' | 'garson'): string {\n const name = (id: string) => names.get(id) ?? id\n const f = e.formula\n if (f.kind !== 'box' && f.kind !== 'dia') return t.plainValue(name(e.world), e.value)\n const arg = formulaText(f.arg, notation)\n const seen = namesOf(names, e.accessible ?? [])\n if (f.kind === 'box') return e.value ? t.boxTrue(name(e.world), arg, seen) : t.boxFalse(name(e.world), arg, name(e.witness ?? ''))\n return e.value ? t.diaTrue(name(e.world), arg, name(e.witness ?? '')) : t.diaFalse(name(e.world), arg, seen)\n}\n\n/** Marks for the focused formula: the selected world's view for □ and ◇, else every world's value. */\nexport function marksFor(e: Explanation | undefined, ev: ModalEvaluator | undefined, f: Formula | undefined): Map<string, WorldMark> {\n const marks = new Map<string, WorldMark>()\n if (e === undefined || ev === undefined || f === undefined) return marks\n if (f.kind === 'box' || f.kind === 'dia') {\n for (const c of e.children) marks.set(c.world, c.value ? 'true' : 'false')\n if (e.witness !== undefined) marks.set(e.witness, f.kind === 'box' ? 'counter' : 'witness')\n return marks\n }\n for (const w of ev.model.worlds) marks.set(w, ev.holds(f, w) ? 'true' : 'false')\n return marks\n}\n\n/** A parsed formula's value at `world`, or undefined when it does not parse or cannot be evaluated there. */\nexport function valueOrUndefined(parsed: ParsedFormula, ev: ModalEvaluator, world: string): boolean | undefined {\n if (!parsed.ok) return undefined\n try {\n return ev.holds(parsed.formula, world)\n } catch {\n return undefined\n }\n}\n","import type { ReactNode } from 'react'\nimport type { Locale } from '../../engine/types.ts'\nimport { LocaleScope } from '../../components/i18n/messages.ts'\nimport { Tex } from '../../components/text/Tex.tsx'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport type { ModalNotation } from '../engine/print.ts'\nimport { formulaLatex, formulaText } from '../engine/print.ts'\nimport { modalText } from '../data/load.ts'\nimport type { ModalDocInput, ModalText } from '../data/schema.ts'\nimport { modalProblemMessage, useModalMessages } from '../i18n/messages.ts'\n\n/** Pieces every modal component shares: the root box, problems, formulas and truth marks. */\n\n/** A document as a component takes it: a value (as written, or checked) or JSON text. The component checks it and shows the problems when it cannot draw it. */\nexport type ModalModelInput = ModalDocInput | string\n\n/** Props every modal component takes. */\nexport interface ModalCommonProps {\n /** Interface language; default the surrounding `LocaleProvider`'s, else zh-TW. */\n readonly locale?: Locale\n /** Display notation: `modern` (¬ ∧ ∨ ⊃, the default) or `garson` (~ and &). */\n readonly notation?: Exclude<ModalNotation, 'ascii'>\n /** A caption under the figure. */\n readonly caption?: ReactNode\n}\n\n/** The language scope and the root box with the component's class. */\nexport function ModalRoot({ locale, name, caption, children }: { readonly locale?: Locale; readonly name: string; readonly caption?: ReactNode; readonly children: ReactNode }) {\n return (\n <LocaleScope locale={locale}>\n <RootBox name={name} caption={caption}>\n {children}\n </RootBox>\n </LocaleScope>\n )\n}\n\nfunction RootBox({ name, caption, children }: { readonly name: string; readonly caption?: ReactNode; readonly children: ReactNode }) {\n const t = useModalMessages()\n return (\n <figure className={`ca-root not-prose ca-modal ca-modal-${name}`} lang={t.locale}>\n {children}\n {caption !== undefined && <figcaption className=\"ca-modal-caption ca-muted\">{caption}</figcaption>}\n </figure>\n )\n}\n\n/** A document that could not be drawn: every problem with its code (the first as `data-code`). */\nexport function ModalProblems({ problems }: { readonly problems: readonly ModalProblem[] }) {\n const t = useModalMessages()\n return (\n <div className=\"ca-editor-errors ca-doc-error\" role=\"alert\" data-code={problems[0]?.code}>\n <p>{t.docInvalid}</p>\n <ul>\n {problems.map((p, i) => (\n <li key={`${p.code}-${i}`}>\n <code className=\"ca-mono\">{p.code}</code> {modalProblemMessage(p, t)}\n </li>\n ))}\n </ul>\n </div>\n )\n}\n\n/** One typeset formula; its plain text stays in `aria-label` and `data-text`. */\nexport function FormulaMath({ formula, notation = 'modern' }: { readonly formula: Formula; readonly notation?: ModalNotation }) {\n return <Tex tex={formulaLatex(formula, notation)} text={formulaText(formula, notation)} />\n}\n\n/** Garson's truth values: T and F, with the word for screen readers. */\nexport function TruthMark({ value }: { readonly value: boolean }) {\n const t = useModalMessages()\n return (\n <span className=\"ca-modal-truth\" data-value={value ? 'T' : 'F'} aria-label={value ? t.trueWord : t.falseWord}>\n <span aria-hidden=\"true\">{value ? 'T' : 'F'}</span>\n </span>\n )\n}\n\n/** A value that cannot be given: the formula does not parse, or is undefined at the world. */\nexport function UnknownMark() {\n return (\n <span className=\"ca-modal-truth\" data-value=\"error\" aria-hidden=\"true\">\n ?\n </span>\n )\n}\n\n/** The atoms and what each says, when the document labels them. */\nexport function AtomLegend({ atoms }: { readonly atoms: readonly { readonly id: string; readonly label?: ModalText }[] }) {\n const t = useModalMessages()\n if (!atoms.some((a) => a.label !== undefined)) return null\n return (\n <dl className=\"ca-modal-atoms ca-small\" aria-label={t.atomsHeading}>\n {atoms.map((a) => (\n <div key={a.id}>\n <dt className=\"ca-mono\">{a.id}</dt>\n <dd>{modalText(a.label, t.locale) ?? a.id}</dd>\n </div>\n ))}\n </dl>\n )\n}\n","import type { Locale } from '../../engine/types.ts'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblemOf } from '../engine/errors.ts'\nimport type { ConditionalSemantics, CounterfactualStep } from '../engine/evaluate.ts'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport type { ModalModel } from '../engine/model.ts'\nimport type { SpheresDoc } from '../data/schema.ts'\nimport { worldNames } from './doc-graph.ts'\nimport type { SphereWorld } from './sphere-graph.ts'\nimport type { SphereMark } from './SphereDiagram.tsx'\n\n/** What a sphere picture shows for one counterfactual at one world. Pure. */\n\nexport interface CounterfactualView {\n /** The step under Lewis's reading, which is always defined; under Stalnaker the same worlds, but the value may be undefined. */\n readonly step: CounterfactualStep\n /** Undefined when Stalnaker's selection is not unique. */\n readonly value: boolean | undefined\n readonly problem?: ModalProblem\n readonly marks: ReadonlyMap<string, SphereMark>\n}\n\n/** A counterfactual a > b at `world`, read by `semantics`. */\nexport function counterfactualView(model: ModalModel, a: Formula, b: Formula, world: string, semantics: ConditionalSemantics): CounterfactualView {\n const step = new ModalEvaluator(model).counterfactual(a, b, world)\n const marks = new Map<string, SphereMark>()\n for (const v of step.antecedentWorlds) marks.set(v, 'antecedent')\n for (const v of step.selected) marks.set(v, 'selected')\n for (const v of step.failures) marks.set(v, 'counter')\n if (semantics === 'lewis') return { step, value: step.value, marks }\n try {\n return { step, value: new ModalEvaluator(model, { semantics }).counterfactual(a, b, world).value, marks }\n } catch (error) {\n const problem = modalProblemOf(error)\n if (problem === undefined) throw error\n return { step, value: undefined, problem, marks }\n }\n}\n\n/** The worlds a sphere picture draws: names and their true atoms. */\nexport function sphereWorlds(doc: SpheresDoc, locale: Locale): SphereWorld[] {\n const names = worldNames(doc, locale)\n return doc.worlds.map((w) => ({ id: w.id, name: names.get(w.id) ?? w.id, detail: w.true.join(', ') }))\n}\n\n/** LaTeX for a set of world names. */\nexport function worldSetLatex(names: readonly string[]): string {\n return `\\\\{${names.map((n) => `\\\\text{${n.replace(/[\\\\{}]/g, '')}}`).join(', ')}\\\\}`\n}\n","import { useMemo } from 'react'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblem } from '../engine/errors.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport { atomsOf, parseFormula } from '../engine/formula.ts'\nimport { parseModalJson } from '../data/load.ts'\nimport type { ModalDoc, ModalDocInput } from '../data/schema.ts'\n\n/** Loading a component's document and its formulas. */\n\nexport type Loaded<K extends ModalDoc['kind']> = { readonly ok: true; readonly doc: Extract<ModalDoc, { kind: K }> } | { readonly ok: false; readonly errors: readonly ModalProblem[] }\n\n/** The document checked once per value, narrowed to the kinds the component draws (`kinds`: a module constant). */\nexport function useModalDoc<K extends ModalDoc['kind']>(model: ModalDocInput | string, kinds: readonly K[]): Loaded<K> {\n return useMemo(() => {\n const result = parseModalJson(model)\n if (!result.ok) return result\n if (!(kinds as readonly string[]).includes(result.doc.kind)) {\n return { ok: false, errors: [modalProblem('wrong-kind', { kind: result.doc.kind, expected: kinds }, 'kind')] }\n }\n return { ok: true, doc: result.doc as Extract<ModalDoc, { kind: K }> }\n }, [model, kinds])\n}\n\nexport type ParsedFormula = { readonly ok: true; readonly source: string; readonly formula: Formula } | { readonly ok: false; readonly source: string; readonly error: unknown }\n\n/** Parse a list of formula sources, keeping each failure in place. */\nexport function parseAll(sources: readonly string[]): ParsedFormula[] {\n return sources.map((source) => {\n try {\n return { ok: true, source, formula: parseFormula(source) }\n } catch (error) {\n return { ok: false, source, error }\n }\n })\n}\n\n/** The first atom of `formulas` the document does not have, as a problem. */\nexport function unknownAtomProblem(formulas: readonly Formula[], atoms: readonly string[]): ModalProblem | undefined {\n for (const f of formulas) for (const a of atomsOf(f)) if (!atoms.includes(a)) return modalProblem('unknown-atom', { atom: a })\n return undefined\n}\n","import { useMemo, useState } from 'react'\nimport { Tex } from '../../components/text/Tex.tsx'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport { formulaLatex, formulaText } from '../engine/print.ts'\nimport { modelOfDoc, startWorld } from '../data/load.ts'\nimport type { KripkeDoc } from '../data/schema.ts'\nimport { useModalMessages } from '../i18n/messages.ts'\nimport { namesOf, worldNames } from './doc-graph.ts'\nimport { valueOrUndefined } from './explain-text.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark, UnknownMark } from './parts.tsx'\nimport { worldSetLatex } from './sphere-view-model.ts'\nimport { parseAll, useModalDoc } from './use-doc.ts'\n\nexport interface IntensionTableProps extends ModalCommonProps {\n /** A `kripke` document (JSON text or value); R is needed only for formulas with □ or ◇. */\n readonly model: ModalModelInput\n /** Formulas, one per row, replacing the document's. */\n readonly formulas?: readonly string[]\n /** The world whose column is picked first; default the document's `actual`. */\n readonly highlight?: string\n}\n\n/**\n * Intensions as functions from worlds to truth values: one row per sentence, one column per world.\n * Pick a world to read a_w(A) down its column; pick a sentence to see its truth set |A|.\n */\nexport function IntensionTable(props: IntensionTableProps) {\n return (\n <ModalRoot locale={props.locale} name=\"intension\" caption={props.caption}>\n <IntensionBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['kripke'] as const\n\nfunction IntensionBody(props: IntensionTableProps) {\n const loaded = useModalDoc(props.model, KINDS)\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n return <IntensionLoaded {...props} doc={loaded.doc} />\n}\n\nfunction IntensionLoaded(props: IntensionTableProps & { readonly doc: KripkeDoc }) {\n const { doc, notation = 'modern' } = props\n const t = useModalMessages()\n const ev = useMemo(() => new ModalEvaluator(modelOfDoc(doc)), [doc])\n const formulas = useMemo(() => parseAll(props.formulas ?? doc.formulas ?? doc.atoms.map((a) => a.id)), [props.formulas, doc])\n const [world, setWorld] = useState(() => (props.highlight !== undefined && doc.worlds.some((w) => w.id === props.highlight) ? props.highlight : startWorld(doc)))\n const [row, setRow] = useState(0)\n const names = worldNames(doc, t.locale)\n const ids = doc.worlds.map((w) => w.id)\n const picked = formulas[row]\n const value = picked === undefined ? undefined : valueOrUndefined(picked, ev, world)\n return (\n <>\n <p className=\"ca-modal-reading\" aria-live=\"polite\">\n {picked?.ok === true && value !== undefined && (\n <Tex\n tex={`a_{\\\\text{${names.get(world) ?? world}}}(${formulaLatex(picked.formula, notation)}) = \\\\mathrm{${value ? 'T' : 'F'}}`}\n text={`a_${names.get(world) ?? world}(${formulaText(picked.formula, notation)}) = ${value ? 'T' : 'F'}`}\n />\n )}\n </p>\n <div className=\"ca-modal-scroll\">\n <table className=\"ca-modal-table ca-modal-intension\">\n <caption>{t.intensionCaption}</caption>\n <thead>\n <tr>\n <th scope=\"col\">{t.formula}</th>\n {ids.map((w) => (\n <th key={w} scope=\"col\" data-selected={w === world ? 'true' : undefined}>\n <button type=\"button\" className=\"ca-modal-pick\" aria-pressed={w === world} aria-label={t.selectWorld(names.get(w) ?? w)} onClick={() => setWorld(w)}>\n {names.get(w) ?? w}\n </button>\n </th>\n ))}\n <th scope=\"col\">{t.truthSet}</th>\n </tr>\n </thead>\n <tbody>\n {formulas.map((f, i) => {\n let set: string[] | undefined\n try {\n set = f.ok ? ev.truthSet(f.formula) : undefined\n } catch {\n set = undefined\n }\n return (\n <tr key={`${f.source}-${i}`} data-selected={i === row ? 'true' : undefined}>\n <th scope=\"row\">\n <button type=\"button\" className=\"ca-modal-pick\" aria-pressed={i === row} onClick={() => setRow(i)}>\n {f.ok ? <FormulaMath formula={f.formula} notation={notation} /> : <code className=\"ca-mono\">{f.source}</code>}\n </button>\n </th>\n {ids.map((w) => {\n const v = valueOrUndefined(f, ev, w)\n return (\n <td key={w} data-selected={w === world ? 'true' : undefined} data-in-set={i === row && set?.includes(w) ? 'true' : undefined}>\n {v === undefined ? <UnknownMark /> : <TruthMark value={v} />}\n </td>\n )\n })}\n <td>{set !== undefined && <Tex tex={worldSetLatex(namesOf(names, set))} text={`{${namesOf(names, set).join(', ')}}`} />}</td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n <AtomLegend atoms={doc.atoms} />\n </>\n )\n}\n","/** Placing small SVG labels so they do not sit on nodes, node labels or other labels. */\n\nexport interface Box {\n readonly x0: number\n readonly y0: number\n readonly x1: number\n readonly y1: number\n}\n\nexport type Anchor = 'start' | 'middle' | 'end'\n\n/** The box a single line of text covers: `y` is the baseline, `size` the font size in px. */\nexport function textBox(x: number, y: number, anchor: Anchor, width: number, size: number): Box {\n const x0 = anchor === 'start' ? x : anchor === 'end' ? x - width : x - width / 2\n return { x0, y0: y - size * 0.85, x1: x0 + width, y1: y + size * 0.25 }\n}\n\n/** A box from its top-left corner and size. */\nexport function rectBox(x: number, y: number, w: number, h: number): Box {\n return { x0: x, y0: y, x1: x + w, y1: y + h }\n}\n\n/** Whether the segment a–b passes through the box. */\nexport function segmentHitsBox(a: { readonly x: number; readonly y: number }, b: { readonly x: number; readonly y: number }, box: Box): boolean {\n let t0 = 0\n let t1 = 1\n const dx = b.x - a.x\n const dy = b.y - a.y\n for (const [p, q] of [\n [-dx, a.x - box.x0],\n [dx, box.x1 - a.x],\n [-dy, a.y - box.y0],\n [dy, box.y1 - a.y],\n ] as const) {\n if (p === 0) {\n if (q < 0) return false\n continue\n }\n const r = q / p\n if (p < 0) t0 = Math.max(t0, r)\n else t1 = Math.min(t1, r)\n if (t0 > t1) return false\n }\n return true\n}\n\n/** A square around a centre. */\nexport function around(cx: number, cy: number, half: number): Box {\n return { x0: cx - half, y0: cy - half, x1: cx + half, y1: cy + half }\n}\n\nexport function shifted(b: Box, dx: number, dy: number): Box {\n return { x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy }\n}\n\nexport function intersects(a: Box, b: Box, pad = 2): boolean {\n return a.x0 < b.x1 + pad && b.x0 < a.x1 + pad && a.y0 < b.y1 + pad && b.y0 < a.y1 + pad\n}\n\nexport interface Placed {\n readonly x: number\n readonly y: number\n readonly anchor: Anchor\n readonly box: Box\n}\n\n/** The first candidate that clears every obstacle; the first one when all of them collide. */\nexport function firstClear(candidates: readonly Placed[], obstacles: readonly Box[]): Placed {\n const clear = candidates.find((c) => !obstacles.some((o) => intersects(c.box, o)))\n return clear ?? candidates[0]\n}\n","/** Estimated text widths, and the per-value bars laid out to fit their labels. */\n\n/** Geometry of one node's per-value bars (a chart `width` wide, `barW` bars every `pitch`, in px). */\nexport interface BarLayout {\n readonly pitch: number\n readonly barW: number\n readonly width: number\n /** False when the value labels would touch: only the first and last are written. */\n readonly labelsFit: boolean\n}\n\nconst BAR_MAX_WIDTH = 126\n\n/** Lay out one bar per value, in `size`-px labels, within BAR_MAX_WIDTH. */\nexport function barLayout(labels: readonly string[], size: number): BarLayout {\n const widest = Math.max(0, ...labels.map((l) => textWidth(l, size)))\n const wanted = Math.max(14, Math.ceil(widest) + 5)\n const pitch = Math.min(wanted, BAR_MAX_WIDTH / Math.max(1, labels.length))\n return { pitch, barW: Math.max(3, Math.min(12, pitch - 5)), width: pitch * labels.length, labelsFit: pitch >= widest + 2 }\n}\n\n/** Estimated text width in px: CJK and full-width punctuation are one em, the rest about 0.6 em. */\nexport function textWidth(s: string, size: number): number {\n let w = 0\n for (const ch of s) {\n const code = ch.codePointAt(0) ?? 0\n w += code > 0x2e7f || ',。:;()「」?!…—=/、《》・'.includes(ch) ? size : size * 0.6\n }\n return w\n}\n","/** A digit suffix is a subscript only on an identifier that has no explicit underscore. */\nexport function digitSubscript(id: string): { readonly head: string; readonly sub: string } | undefined {\n const match = /^([A-Za-z][A-Za-z0-9]*?)(\\d+)$/.exec(id)\n return match === null ? undefined : { head: match[1], sub: match[2] }\n}\n","import type { Anchor, Box, Placed } from './graph-labels.ts'\nimport { rectBox, textBox } from './graph-labels.ts'\nimport { textWidth } from '../text/text-measure.ts'\nimport type { Value } from '../../engine/index.ts'\nimport { formatValue } from '../../engine/values.ts'\nimport type { Messages } from '../i18n/messages.ts'\nimport { probText } from '../model/wording.ts'\n\n/** The shapes a signal graph draws with: a node's label block and its readout, and the path strings of arrowheads, clamps and dashed rings. Pure. */\n\nconst SNAP = 0.25\n/** Per-value bars: tallest bar, the gap to the label above them, and the value label size. */\nexport const BAR_H = 24\nexport const BAR_GAP = 10\nexport const BAR_LABEL = 11\n\n/** What sits under a node's label: nothing, one number, or one bar per value (with the largest probability). */\nexport type Readout =\n | { readonly kind: 'none'; readonly noteW?: number; readonly note2W?: number }\n | { readonly kind: 'number'; readonly noteW?: number; readonly numberW?: number }\n | { readonly kind: 'bars'; readonly width: number; readonly maxW: number; readonly noteW?: number }\n\n/** Where a label block sits round its node: under or over the disc, beside it, or off one of its corners. */\nexport type BlockSide = 'below' | 'above' | 'right' | 'left' | 'below-right' | 'below-left' | 'above-right' | 'above-left'\n\n/** A node's label and its readout as one block, in offsets from the node's centre. */\nexport interface Block {\n readonly side: BlockSide\n /** The block's middle line: every text in it is centred on `cx`. */\n readonly cx: number\n /** Whether the label is wrapped onto two lines; the second has its baseline at `label2Y`. */\n readonly wrapped: boolean\n /** Baselines of the label (and of its second line), the number and the note (and a second note line). */\n readonly labelY: number\n readonly label2Y: number\n readonly numberY: number\n readonly noteY: number\n readonly note2Y: number\n /** Bars: left edge and the baseline the bars stand on. */\n readonly x0: number\n readonly baseline: number\n readonly boxes: readonly Box[]\n}\n\n/** The width a node's number reserves under its label: a probability of `digits` decimals at 16 px. */\nexport function numberWidth(digits = 2): number {\n return textWidth(`0.${'0'.repeat(digits)}`, 16) + 4\n}\n\n/** What a probability node shows as its number: a small prefix and the text. `settled` nodes (observed or do()) carry no 原本 note. */\nexport interface NodeReadout {\n readonly prefix: string\n readonly text: string\n readonly settled: boolean\n}\n\nexport function nodeReadout(\n t: Messages,\n digits: number,\n p: number | undefined,\n forced: Value | undefined,\n seen: Value | undefined,\n): NodeReadout {\n if (forced !== undefined) return { prefix: '', text: t.nodeReadout.intervened(formatValue(forced)), settled: true }\n if (seen !== undefined) return { prefix: '', text: t.nodeReadout.observed(formatValue(seen)), settled: true }\n return { prefix: `${t.nodeReadout.unknown} `, text: probText(p ?? Number.NaN, digits), settled: false }\n}\n\n/** The width a readout reserves: the number at 16 px, or the settled text at 14 px, after its prefix at 11 px. */\nexport function readoutWidth(r: NodeReadout, digits: number): number {\n const prefixW = r.prefix === '' ? 0 : textWidth(r.prefix, 11)\n return prefixW + (r.settled ? textWidth(r.text, 14) + 4 : numberWidth(digits))\n}\n\n/** A label's width on one line, and on two when it can be wrapped. */\nexport interface LabelSize {\n readonly width: number\n readonly lines?: readonly [number, number]\n}\n\n/** Between the baselines of a wrapped label's two lines, in px. */\nexport const LABEL_LEADING = 17\n\n/** The block with its top edge at `top`, centred on `cx`; its label on two lines when `wrapped`. */\nfunction blockAt(top: number, side: BlockSide, label: LabelSize, readout: Readout, cx = 0, wrapped = false): Block {\n const labelY = top + 12\n const lines = wrapped ? label.lines : undefined\n // A wrapped label claims one box over both its lines, as wide as the longer one.\n const label2Y = lines === undefined ? labelY : labelY + LABEL_LEADING\n const labelBox = textBox(cx, labelY, 'middle', lines === undefined ? label.width : Math.max(...lines), 14)\n const boxes: Box[] = [{ ...labelBox, y1: labelBox.y1 + label2Y - labelY }]\n let numberY = label2Y\n let noteY = label2Y\n let x0 = cx\n let baseline = label2Y\n let note2Y = label2Y\n const last = label2Y\n if (readout.kind === 'none' && (readout.noteW !== undefined || readout.note2W !== undefined)) {\n noteY = last + 17\n note2Y = readout.noteW === undefined ? noteY : noteY + 18\n if (readout.noteW !== undefined) boxes.push(textBox(cx, noteY, 'middle', readout.noteW, 12))\n if (readout.note2W !== undefined) boxes.push(textBox(cx, note2Y, 'middle', readout.note2W + 8, 14))\n } else if (readout.kind === 'number') {\n numberY = last + 22\n noteY = numberY + 19\n boxes.push(textBox(cx, numberY, 'middle', readout.numberW ?? numberWidth(), 16))\n if (readout.noteW !== undefined) boxes.push(textBox(cx, noteY, 'middle', readout.noteW, 12))\n } else if (readout.kind === 'bars') {\n const chartTop = last + BAR_GAP\n x0 = cx - readout.width / 2\n baseline = chartTop + BAR_H\n noteY = baseline + BAR_LABEL + 16\n boxes.push(rectBox(x0, chartTop, readout.width, BAR_H + BAR_LABEL + 6))\n boxes.push(textBox(x0 - 5, chartTop + 8, 'end', readout.maxW, 11))\n if (readout.noteW !== undefined) boxes.push(textBox(cx, noteY, 'middle', readout.noteW, 12))\n }\n return { side, cx, wrapped: lines !== undefined, labelY, label2Y, numberY, noteY, note2Y, x0, baseline, boxes }\n}\n\n/**\n * Where a node of radius `r` may put its label block, best first: under the disc, over it, beside\n * it on the right and on the left (level with its centre), then off each of the disc's four\n * corners, last because a block there may read as its neighbour's. Each spot is followed by the\n * same spot with the label on two lines, when it can be wrapped, so a long label wraps where it is\n * before it moves to another side.\n */\nexport function blockOptions(r: number, label: number | LabelSize, readout: Readout): readonly Block[] {\n const size: LabelSize = typeof label === 'number' ? { width: label } : label\n const at = (wrapped: boolean): { readonly sides: Block[]; readonly corners: Block[] } => {\n const probe = blockAt(0, 'below', size, readout, 0, wrapped)\n const height = Math.max(...probe.boxes.map((b) => b.y1))\n const minX = Math.min(...probe.boxes.map((b) => b.x0))\n const maxX = Math.max(...probe.boxes.map((b) => b.x1))\n const below = r + 12\n const above = -r - 10 - height\n // Beside the disc: the label's line level with the node's centre, the block's near edge 10 px off the rim.\n const beside = -Math.max(8, height / 2)\n const right = r + 10 - minX\n const left = -r - 10 - maxX\n // Off a corner: the block's near corner just past the square round the disc.\n const d = r + 4\n return {\n sides: [\n blockAt(below, 'below', size, readout, 0, wrapped),\n blockAt(above, 'above', size, readout, 0, wrapped),\n blockAt(beside, 'right', size, readout, right, wrapped),\n blockAt(beside, 'left', size, readout, left, wrapped),\n ],\n corners: [\n blockAt(d, 'below-right', size, readout, d - minX, wrapped),\n blockAt(d, 'below-left', size, readout, -d - maxX, wrapped),\n blockAt(-d - height, 'above-right', size, readout, d - minX, wrapped),\n blockAt(-d - height, 'above-left', size, readout, -d - maxX, wrapped),\n ],\n }\n }\n const one = at(false)\n const spots = [...one.sides, ...one.corners]\n if (size.lines === undefined) return spots\n const two = at(true)\n const wrapped = [...two.sides, ...two.corners]\n return spots.flatMap((b, i) => [b, wrapped[i]])\n}\n\n/**\n * Where a small 12 px note of width `w` (原本 v) may go beside a node of radius `r` with label block\n * `block`, best first, in offsets from the node's centre: right past the block's far edge from the\n * disc (under a block beside the disc), on the label's own line after or before it, beside the\n * disc, then on the disc's other side.\n */\nexport function noteSpots(block: Block, r: number, w: number): readonly (Placed & { readonly box: Box })[] {\n const top = Math.min(...block.boxes.map((b) => b.y0))\n const bottom = Math.max(...block.boxes.map((b) => b.y1))\n const label = block.boxes[0]\n const spot = (x: number, y: number, anchor: Anchor) => ({ x, y, anchor, box: textBox(x, y, anchor, w, 12) })\n const under = block.side === 'below' || block.side.startsWith('below-') || block.side === 'right' || block.side === 'left'\n const outer = under ? spot(block.cx, bottom + 13, 'middle') : spot(block.cx, top - 5, 'middle')\n const across = under ? spot(0, -r - 8, 'middle') : spot(0, r + 17, 'middle')\n return [\n outer,\n spot(label.x1 + 6, block.labelY, 'start'),\n spot(label.x0 - 6, block.labelY, 'end'),\n spot(r + 8, 4, 'start'),\n spot(-r - 8, 4, 'end'),\n across,\n ]\n}\n\nexport function snap(v: number): number {\n return Math.round(v / SNAP) * SNAP\n}\n\n\nexport interface Point {\n readonly x: number\n readonly y: number\n}\n\nexport function unit(a: Point, b: Point): { ux: number; uy: number; d: number } {\n const dx = b.x - a.x\n const dy = b.y - a.y\n const d = Math.hypot(dx, dy) || 1\n return { ux: dx / d, uy: dy / d, d }\n}\n\n/**\n * The dashes of an exogenous node's outline: whole dashes round the circle, so the ring has no\n * seam. (Dashes in px, not `pathLength`, so a viewer that ignores that attribute still draws them.)\n */\nexport function exoDash(r: number): string {\n const c = 2 * Math.PI * r\n const unitLength = c / Math.max(6, Math.round(c / 11))\n return `${(unitLength * 0.6).toFixed(2)} ${(unitLength * 0.4).toFixed(2)}`\n}\n\n/** How far an exogenous node's fill sits inside its dashed outline, in px. */\nexport const EXO_INSET = 4.5\n\n/** An arrowhead with its tip at `tip`, pointing along (`dx`, `dy`). */\nexport function arrowHead(tip: Point, dx: number, dy: number): string {\n const len = Math.hypot(dx, dy) || 1\n const ux = dx / len\n const uy = dy / len\n const bx = tip.x - 9 * ux\n const by = tip.y - 9 * uy\n return `M${tip.x} ${tip.y}L${bx - 3.6 * uy} ${by + 3.6 * ux}L${bx + 3.6 * uy} ${by - 3.6 * ux}z`\n}\n\nexport function clampPath(r: number): string {\n const o = r + 8\n const s = 14\n return `M${-o} ${-o + s}v${-s}h${s}M${o - s} ${-o}h${s}v${s}M${o} ${o - s}v${s}h${-s}M${-o + s} ${o}h${-s}v${-s}`\n}\n","import type { Box, Placed } from '../../components/graph/graph-labels.ts'\nimport { firstClear, intersects, rectBox, segmentHitsBox, textBox } from '../../components/graph/graph-labels.ts'\nimport type { Point } from '../../components/graph/signal-shapes.ts'\nimport { arrowHead, unit } from '../../components/graph/signal-shapes.ts'\nimport { textWidth } from '../../components/text/text-measure.ts'\n\n/**\n * The geometry of a Kripke picture, computed on the server without the DOM: each world a Garson-style\n * box listing its atoms, its name beside the box where no arrow or other box covers it, and the\n * accessibility arrows from border to border (self-loops on the top edge, a symmetric pair merged into\n * one double-headed arrow when asked). Pure.\n */\n\nexport type GraphLayoutKind = 'manual' | 'circle' | 'line' | 'layers'\n\nexport interface GraphWorld {\n readonly id: string\n /** The name written beside the box. */\n readonly name: string\n /** The lines written inside the box (true atoms, and false ones as ¬p when shown). */\n readonly lines: readonly string[]\n /** Manual layout units: x across, y down. */\n readonly pos?: { readonly x: number; readonly y: number }\n}\n\nexport interface GraphInput {\n readonly worlds: readonly GraphWorld[]\n readonly pairs: readonly (readonly [string, string])[]\n readonly layout: GraphLayoutKind\n /** Where `layers` starts: the actual world. */\n readonly root?: string\n /** Draw wRv and vRw as one double-headed arrow. */\n readonly mergeSymmetric: boolean\n}\n\nexport interface PlacedWorld {\n readonly id: string\n readonly cx: number\n readonly cy: number\n readonly w: number\n readonly h: number\n readonly lines: readonly string[]\n readonly name: string\n readonly label: Placed\n}\n\nexport interface PlacedEdge {\n readonly from: string\n readonly to: string\n /** Also vRw, drawn in the same path. */\n readonly both: boolean\n readonly path: string\n readonly heads: readonly string[]\n}\n\nexport interface GraphLayout {\n readonly worlds: readonly PlacedWorld[]\n readonly edges: readonly PlacedEdge[]\n readonly viewBox: string\n readonly width: number\n readonly height: number\n}\n\nconst LINE = 17\nconst ATOM_SIZE = 13\nconst NAME_SIZE = 13\nconst PAD = 10\nconst GAP = 3\nconst MARGIN = 14\n\nfunction boxSize(w: GraphWorld): { readonly w: number; readonly h: number } {\n const widest = Math.max(0, ...w.lines.map((l) => textWidth(l, ATOM_SIZE)))\n return { w: Math.max(40, Math.ceil(widest) + 2 * PAD), h: Math.max(28, w.lines.length * LINE + 2 * PAD - 6) }\n}\n\nfunction centres(input: GraphInput, sizes: readonly { w: number; h: number }[]): Point[] {\n const n = input.worlds.length\n const wide = Math.max(...sizes.map((s) => s.w))\n const tall = Math.max(...sizes.map((s) => s.h))\n const stepX = Math.max(130, wide + 80)\n const stepY = Math.max(96, tall + 56)\n switch (input.layout) {\n case 'manual':\n return input.worlds.map((w) => ({ x: (w.pos?.x ?? 0) * (stepX * 0.6), y: (w.pos?.y ?? 0) * (stepY * 0.6) }))\n case 'line':\n return input.worlds.map((_, i) => ({ x: i * stepX, y: 0 }))\n case 'circle': {\n if (n <= 2) return input.worlds.map((_, i) => ({ x: i * stepX, y: 0 }))\n const r = Math.max(stepY * 0.75, (stepX * n) / (2 * Math.PI))\n return input.worlds.map((_, i) => {\n const a = -Math.PI / 2 + (2 * Math.PI * i) / n\n return { x: r * Math.cos(a), y: r * Math.sin(a) }\n })\n }\n case 'layers': {\n const ids = input.worlds.map((w) => w.id)\n const depth = new Map<string, number>()\n const start = input.root ?? ids[0]\n if (start !== undefined) depth.set(start, 0)\n const queue = start === undefined ? [] : [start]\n while (queue.length > 0) {\n const a = queue.shift() as string\n for (const [x, y] of input.pairs) {\n if (x === a && !depth.has(y)) {\n depth.set(y, (depth.get(a) as number) + 1)\n queue.push(y)\n }\n }\n }\n const last = Math.max(0, ...depth.values()) + 1\n const column = ids.map((id) => depth.get(id) ?? last)\n return ids.map((id, i) => {\n const col = column[i] as number\n const mates = ids.filter((_, k) => column[k] === col)\n const row = mates.indexOf(id)\n return { x: col * stepX, y: (row - (mates.length - 1) / 2) * stepY }\n })\n }\n }\n}\n\n/** Where the ray from the box centre along (ux, uy) leaves the box, `gap` px further out. */\nfunction border(c: Point, w: number, h: number, ux: number, uy: number, gap: number): Point {\n const t = Math.min(ux === 0 ? Infinity : w / 2 / Math.abs(ux), uy === 0 ? Infinity : h / 2 / Math.abs(uy))\n return { x: c.x + ux * (t + gap), y: c.y + uy * (t + gap) }\n}\n\nconst fmt = (v: number): string => (Math.round(v * 10) / 10).toString()\n\ninterface Shape {\n readonly id: string\n readonly cx: number\n readonly cy: number\n readonly w: number\n readonly h: number\n}\n\nfunction edgeGeometry(a: Shape, b: Shape, both: boolean, offset: number): { path: string; heads: string[]; seg: [Point, Point] } {\n if (a.id === b.id) {\n const top = a.cy - a.h / 2\n const x1 = a.cx - 9\n const x2 = a.cx + 9\n const path = `M${fmt(x1)} ${fmt(top - GAP)}C${fmt(x1 - 14)} ${fmt(top - 34)} ${fmt(x2 + 14)} ${fmt(top - 34)} ${fmt(x2)} ${fmt(top - GAP)}`\n return { path, heads: [arrowHead({ x: x2, y: top - GAP }, -2, 8)], seg: [{ x: x1 - 16, y: top - 34 }, { x: x2 + 16, y: top }] }\n }\n const { ux, uy } = unit({ x: a.cx, y: a.cy }, { x: b.cx, y: b.cy })\n const ox = -uy * offset\n const oy = ux * offset\n const ca = { x: a.cx + ox, y: a.cy + oy }\n const cb = { x: b.cx + ox, y: b.cy + oy }\n const p = border(ca, a.w, a.h, ux, uy, GAP)\n const q = border(cb, b.w, b.h, -ux, -uy, GAP)\n const heads = [arrowHead(q, ux, uy)]\n if (both) heads.push(arrowHead(p, -ux, -uy))\n return { path: `M${fmt(p.x)} ${fmt(p.y)}L${fmt(q.x)} ${fmt(q.y)}`, heads, seg: [p, q] }\n}\n\nfunction nameCandidates(cx: number, cy: number, w: number, h: number, width: number): Placed[] {\n const make = (x: number, y: number, anchor: 'start' | 'middle' | 'end'): Placed => ({ x, y, anchor, box: textBox(x, y, anchor, width, NAME_SIZE) })\n return [\n make(cx, cy - h / 2 - 7, 'middle'),\n make(cx, cy + h / 2 + NAME_SIZE + 3, 'middle'),\n make(cx - w / 2 - 6, cy + 4, 'end'),\n make(cx + w / 2 + 6, cy + 4, 'start'),\n make(cx - w / 2, cy - h / 2 - 7, 'start'),\n make(cx + w / 2, cy + h / 2 + NAME_SIZE + 3, 'end'),\n ]\n}\n\nexport function layoutWorldGraph(input: GraphInput): GraphLayout {\n const sizes = input.worlds.map(boxSize)\n const at = centres(input, sizes)\n const boxes = input.worlds.map((w, i) => {\n const c = at[i] as Point\n const s = sizes[i] as { w: number; h: number }\n return { id: w.id, cx: c.x, cy: c.y, w: s.w, h: s.h, lines: w.lines, name: w.name }\n })\n const byId = new Map(boxes.map((b) => [b.id, b]))\n const has = new Set(input.pairs.map(([a, b]) => `${a}\\u0000${b}`))\n const edges: PlacedEdge[] = []\n const segments: [Point, Point][] = []\n /** Self-loops, as the boxes they cover. */\n const loops: Box[] = []\n for (const [from, to] of input.pairs) {\n const reverse = from !== to && has.has(`${to}\\u0000${from}`)\n if (reverse && input.mergeSymmetric && input.worlds.findIndex((w) => w.id === from) > input.worlds.findIndex((w) => w.id === to)) continue\n const a = byId.get(from)\n const b = byId.get(to)\n if (a === undefined || b === undefined) continue\n const both = reverse && input.mergeSymmetric\n const g = edgeGeometry(a, b, both, reverse && !both ? 4 : 0)\n edges.push({ from, to, both, path: g.path, heads: g.heads })\n if (from === to) loops.push({ x0: g.seg[0].x, y0: g.seg[0].y, x1: g.seg[1].x, y1: g.seg[1].y })\n else segments.push(g.seg)\n }\n const obstacles: Box[] = [...boxes.map((b) => rectBox(b.cx - b.w / 2, b.cy - b.h / 2, b.w, b.h)), ...loops]\n const worlds: PlacedWorld[] = boxes.map((b) => {\n const width = textWidth(b.name, NAME_SIZE)\n const candidates = nameCandidates(b.cx, b.cy, b.w, b.h, width)\n const free = candidates.filter((c) => !segments.some(([p, q]) => segmentHitsBox(p, q, c.box)))\n const label = firstClear(free.length > 0 ? free : candidates, obstacles)\n obstacles.push(label.box)\n return { ...b, label }\n })\n const all = [...obstacles, ...segments.map(([p, q]) => ({ x0: Math.min(p.x, q.x), y0: Math.min(p.y, q.y), x1: Math.max(p.x, q.x), y1: Math.max(p.y, q.y) }))]\n const x0 = Math.min(...all.map((b) => b.x0)) - MARGIN\n const y0 = Math.min(...all.map((b) => b.y0)) - MARGIN\n const x1 = Math.max(...all.map((b) => b.x1)) + MARGIN\n const y1 = Math.max(...all.map((b) => b.y1)) + MARGIN\n return { worlds, edges, viewBox: `${fmt(x0)} ${fmt(y0)} ${fmt(x1 - x0)} ${fmt(y1 - y0)}`, width: Math.round(x1 - x0), height: Math.round(y1 - y0) }\n}\n\n/** Whether two placed labels overlap: for tests. */\nexport function labelsOverlap(layout: GraphLayout): boolean {\n return layout.worlds.some((a, i) => layout.worlds.some((b, k) => k > i && intersects(a.label.box, b.label.box, 0)))\n}\n","import { digitSubscript } from '../../engine/identifier-format.ts'\n\n/** `X_Y` identifiers drawn as X with a smaller, lowered Y; shared by the live SVG labels and the exported images. */\n\n/** The head and the subscript of an `X_Y` identifier, at word boundaries. */\nconst UNDERSCORE_IDENT = /([A-Za-z]+)_([A-Za-z0-9]+)/\nexport const SUB_IDENT = new RegExp(`(?<![A-Za-z0-9_])${UNDERSCORE_IDENT.source}(?![A-Za-z0-9_])`, 'g')\nconst IDENT_TOKEN = /(?<![A-Za-z0-9_])[A-Za-z][A-Za-z0-9_]*/g\nexport const SUB_DY = '0.25em'\nexport const SUB_SIZE = '70%'\n/** A zero-width space carries the baseline-restoring `dy` after a subscript. */\nexport const ZWSP = '\\u200b'\n\nexport type SubPart = string | { readonly head: string; readonly sub: string }\n\n/** Formula or identifier-label text split into plain runs and `X_Y` or `X1` identifiers. */\nexport function subscriptParts(text: string): SubPart[] {\n const out: SubPart[] = []\n let last = 0\n for (const m of text.matchAll(IDENT_TOKEN)) {\n const id = m[0]\n const explicit = UNDERSCORE_IDENT.exec(id)\n const parts = explicit?.[0] === id ? { head: explicit[1], sub: explicit[2] } : digitSubscript(id)\n if (parts === undefined) continue\n if (m.index > last) out.push(text.slice(last, m.index))\n out.push(parts)\n last = m.index + m[0].length\n }\n if (last < text.length) out.push(text.slice(last))\n return out\n}\n","import type { ReactNode } from 'react'\nimport { Fragment } from 'react'\nimport { SUB_DY, SUB_SIZE, ZWSP, subscriptParts } from './subscript.ts'\n\n/**\n * SVG text with `X_Y` identifiers drawn as X with a smaller, lowered Y (`dy` pairs, which every SVG\n * renderer honours). The plain text stays in the aria-label and `data-*` attributes.\n */\nexport function sub(text: string): ReactNode {\n const parts = subscriptParts(text)\n if (parts.length === 1 && typeof parts[0] === 'string') return text\n return parts.map((p, i) =>\n typeof p === 'string' ? (\n p\n ) : (\n <Fragment key={i}>\n {p.head}\n <tspan dy={SUB_DY} fontSize={SUB_SIZE}>\n {p.sub}\n </tspan>\n <tspan dy={`-${SUB_DY}`}>{ZWSP}</tspan>\n </Fragment>\n ),\n )\n}\n","import type { KeyboardEvent } from 'react'\nimport { sub } from '../../components/text/svg-text.tsx'\nimport type { GraphLayout } from './world-graph.ts'\n\n/** How a world is marked: its value under the formula in focus, or its part in a modal step. */\nexport type WorldMark = 'true' | 'false' | 'witness' | 'counter' | 'dim'\n\nexport interface WorldGraphProps {\n readonly layout: GraphLayout\n /** The accessible name of the picture. */\n readonly label: string\n readonly selected?: string\n readonly marks?: ReadonlyMap<string, WorldMark>\n /** Each world's accessible name. */\n readonly worldLabel: (id: string) => string\n /** Makes each world a button that selects it. */\n readonly onSelect?: (id: string) => void\n}\n\nconst LINE = 17\nconst PAD = 10\n\n/** A Kripke picture: Garson-style world boxes and accessibility arrows; the selected world's arrows are drawn strong. */\nexport function WorldGraph({ layout, label, selected, marks, worldLabel, onSelect }: WorldGraphProps) {\n const key = (id: string) => (e: KeyboardEvent<SVGGElement>) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n onSelect?.(id)\n }\n }\n return (\n <svg className=\"ca-modal-graph\" viewBox={layout.viewBox} width={layout.width} role=\"group\" aria-label={label}>\n <g className=\"ca-modal-edges\" aria-hidden=\"true\">\n {layout.edges.map((e) => {\n const active = selected !== undefined && (e.from === selected || (e.both && e.to === selected))\n return (\n <g key={`${e.from}-${e.to}`} className=\"ca-modal-edge\" data-from={e.from} data-to={e.to} data-active={active ? 'true' : undefined}>\n <path d={e.path} fill=\"none\" />\n {e.heads.map((h, i) => (\n <path key={i} d={h} className=\"ca-modal-head\" />\n ))}\n </g>\n )\n })}\n </g>\n {layout.worlds.map((w) => {\n const mark = marks?.get(w.id)\n const top = w.cy - w.h / 2\n return (\n <g\n key={w.id}\n className=\"ca-modal-world\"\n data-world={w.id}\n data-mark={mark}\n data-selected={w.id === selected ? 'true' : undefined}\n role={onSelect === undefined ? 'img' : 'button'}\n tabIndex={onSelect === undefined ? undefined : 0}\n aria-label={worldLabel(w.id)}\n aria-pressed={onSelect === undefined ? undefined : w.id === selected}\n onClick={onSelect === undefined ? undefined : () => onSelect(w.id)}\n onKeyDown={onSelect === undefined ? undefined : key(w.id)}\n >\n <rect x={w.cx - w.w / 2} y={top} width={w.w} height={w.h} rx=\"3\" className=\"ca-modal-box\" />\n {w.lines.map((line, i) => (\n <text key={line} x={w.cx} y={top + PAD + i * LINE + 9} textAnchor=\"middle\" className=\"ca-modal-atom\" data-negated={line.startsWith('¬') || line.startsWith('~') ? 'true' : undefined}>\n {sub(line)}\n </text>\n ))}\n <text x={w.label.x} y={w.label.y} textAnchor={w.label.anchor} className=\"ca-modal-name\">\n {sub(w.name)}\n </text>\n </g>\n )\n })}\n </svg>\n )\n}\n","import { useMemo, useState } from 'react'\nimport type { Explanation } from '../engine/evaluate.ts'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport { kripkeModel } from '../engine/model.ts'\nimport { startWorld } from '../data/load.ts'\nimport type { KripkeDoc } from '../data/schema.ts'\nimport type { ModalMessages } from '../i18n/messages.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { docGraphInput, worldNames } from './doc-graph.ts'\nimport { explanationText, marksFor, valueOrUndefined } from './explain-text.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark, UnknownMark } from './parts.tsx'\nimport type { ParsedFormula } from './use-doc.ts'\nimport { parseAll, useModalDoc } from './use-doc.ts'\nimport { layoutWorldGraph } from './world-graph.ts'\nimport { WorldGraph } from './WorldGraph.tsx'\n\nexport interface KripkeViewProps extends ModalCommonProps {\n /** A `kripke` document (JSON text or value). */\n readonly model: ModalModelInput\n /** Formulas to list, replacing the document's. */\n readonly formulas?: readonly string[]\n /** The world selected first; default the document's `actual`, else its first world. */\n readonly world?: string\n /** Explain the focused formula's value in words; default true. */\n readonly explain?: boolean\n /** Let the reader toggle atoms and arrows and type formulas; default false. */\n readonly editable?: boolean\n /** Draw wRv and vRw as one double-headed arrow; default true. */\n readonly mergeSymmetric?: boolean\n /** List false atoms as ¬p in the boxes at first; default false. */\n readonly showFalse?: boolean\n}\n\n/**\n * ⟨W, R, a⟩ drawn as Garson's boxes and arrows. Pick a world to see each formula's value there; pick\n * a formula to see, for □ and ◇, the worlds the selected one sees, the witness or the counterexample.\n */\nexport function KripkeView(props: KripkeViewProps) {\n return (\n <ModalRoot locale={props.locale} name=\"kripke\" caption={props.caption}>\n <KripkeBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['kripke'] as const\n\nfunction KripkeBody(props: KripkeViewProps) {\n const loaded = useModalDoc(props.model, KINDS)\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n return <KripkeLoaded {...props} doc={loaded.doc} />\n}\n\nfunction KripkeLoaded(props: KripkeViewProps & { readonly doc: KripkeDoc }) {\n const { doc, editable = false, explain = true, mergeSymmetric = true, notation = 'modern' } = props\n const t = useModalMessages()\n const [world, setWorld] = useState(() => (props.world !== undefined && doc.worlds.some((w) => w.id === props.world) ? props.world : startWorld(doc)))\n const [focus, setFocus] = useState(0)\n const [showFalse, setShowFalse] = useState(props.showFalse ?? false)\n const [extra, setExtra] = useState<readonly string[]>([])\n const [draft, setDraft] = useState('')\n const [valuation, setValuation] = useState<Readonly<Record<string, readonly string[]>>>(() => Object.fromEntries(doc.worlds.map((w) => [w.id, w.true])))\n const [pairs, setPairs] = useState<readonly (readonly [string, string])[]>(doc.access)\n const atoms = useMemo(() => doc.atoms.map((a) => a.id), [doc])\n const names = worldNames(doc, t.locale)\n const ev = useMemo(() => new ModalEvaluator(kripkeModel({ atoms, worlds: doc.worlds.map((w) => ({ id: w.id, true: valuation[w.id] ?? [] })), access: pairs })), [atoms, doc, valuation, pairs])\n const formulas: ParsedFormula[] = useMemo(() => parseAll([...(props.formulas ?? doc.formulas ?? []), ...extra]), [props.formulas, doc, extra])\n const layout = useMemo(() => layoutWorldGraph(docGraphInput(doc, t.locale, { showFalse, notation, mergeSymmetric, valuation, pairs })), [doc, t.locale, showFalse, notation, mergeSymmetric, valuation, pairs])\n const focused = formulas[focus]\n let explanation: Explanation | undefined\n let problem: string | undefined\n if (focused?.ok === true) {\n try {\n explanation = ev.explain(focused.formula, world)\n } catch (error) {\n problem = modalErrorMessage(error, t)\n }\n }\n const marks = marksFor(explanation, ev, focused?.ok === true ? focused.formula : undefined)\n const togglePair = (a: string, b: string): void =>\n setPairs((ps) => (ps.some(([x, y]) => x === a && y === b) ? ps.filter(([x, y]) => !(x === a && y === b)) : [...ps, [a, b] as const]))\n const toggleAtom = (w: string, atom: string): void =>\n setValuation((v) => ({ ...v, [w]: (v[w] ?? []).includes(atom) ? (v[w] ?? []).filter((a) => a !== atom) : [...(v[w] ?? []), atom] }))\n return (\n <div className=\"ca-modal-split\">\n <div className=\"ca-modal-figure\">\n <WorldGraph\n layout={layout}\n label={t.worldGraph(doc.worlds.length)}\n selected={world}\n marks={marks}\n worldLabel={(id) => `${t.selectWorld(names.get(id) ?? id)}. ${t.worldState(names.get(id) ?? id, valuation[id] ?? [])}`}\n onSelect={setWorld}\n />\n </div>\n <div className=\"ca-modal-side\">\n <p className=\"ca-modal-at ca-h3\">{t.at(names.get(world) ?? world)}</p>\n <ul className=\"ca-modal-formulas\" aria-label={t.formulas}>\n {formulas.map((f, i) => (\n <li key={`${f.source}-${i}`}>\n <button type=\"button\" className=\"ca-modal-formula\" aria-pressed={i === focus} onClick={() => setFocus(i)}>\n {f.ok ? <FormulaMath formula={f.formula} notation={notation} /> : <code className=\"ca-mono\">{f.source}</code>}\n <FormulaValue parsed={f} ev={ev} world={world} />\n </button>\n </li>\n ))}\n </ul>\n {explain && explanation !== undefined && (\n <p className=\"ca-modal-explain\" aria-live=\"polite\">\n {explanationText(explanation, names, t, notation)}\n </p>\n )}\n {problem !== undefined && (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {problem}\n </p>\n )}\n {focused !== undefined && !focused.ok && (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(focused.error, t)}\n </p>\n )}\n <AtomLegend atoms={doc.atoms} />\n <label className=\"ca-modal-check\">\n <input type=\"checkbox\" checked={showFalse} onChange={(e) => setShowFalse(e.currentTarget.checked)} /> {t.showFalse}\n </label>\n {editable && (\n <form\n className=\"ca-modal-add\"\n onSubmit={(e) => {\n e.preventDefault()\n if (draft.trim() === '') return\n setExtra((xs) => [...xs, draft.trim()])\n setFocus(formulas.length)\n setDraft('')\n }}\n >\n <input className=\"ca-modal-input ca-mono\" aria-label={t.customFormula} placeholder={t.customFormula} value={draft} onChange={(e) => setDraft(e.currentTarget.value)} />\n <button type=\"submit\" className=\"ca-modal-button\">\n {t.add}\n </button>\n </form>\n )}\n </div>\n {editable && (\n <details className=\"ca-modal-edit\">\n <summary>{t.editHeading}</summary>\n <EditTables doc={doc} atoms={atoms} names={names} valuation={valuation} pairs={pairs} onAtom={toggleAtom} onPair={togglePair} t={t} />\n </details>\n )}\n </div>\n )\n}\n\nfunction FormulaValue({ parsed, ev, world }: { readonly parsed: ParsedFormula; readonly ev: ModalEvaluator; readonly world: string }) {\n const value = valueOrUndefined(parsed, ev, world)\n return value === undefined ? <UnknownMark /> : <TruthMark value={value} />\n}\n\nfunction EditTables(props: {\n readonly doc: KripkeDoc\n readonly atoms: readonly string[]\n readonly names: ReadonlyMap<string, string>\n readonly valuation: Readonly<Record<string, readonly string[]>>\n readonly pairs: readonly (readonly [string, string])[]\n readonly onAtom: (w: string, atom: string) => void\n readonly onPair: (a: string, b: string) => void\n readonly t: ModalMessages\n}) {\n const { doc, atoms, names, valuation, pairs, onAtom, onPair, t } = props\n const ids = doc.worlds.map((w) => w.id)\n const name = (id: string) => names.get(id) ?? id\n return (\n <div className=\"ca-modal-edit-tables\">\n {atoms.length > 0 && (\n <table className=\"ca-modal-table\">\n <caption>{t.atomsHeading}</caption>\n <thead>\n <tr>\n <th scope=\"col\">{t.world}</th>\n {atoms.map((a) => (\n <th key={a} scope=\"col\" className=\"ca-mono\">\n {a}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {ids.map((w) => (\n <tr key={w}>\n <th scope=\"row\">{name(w)}</th>\n {atoms.map((a) => (\n <td key={a}>\n <input type=\"checkbox\" aria-label={t.atomToggle(name(w), a)} checked={(valuation[w] ?? []).includes(a)} onChange={() => onAtom(w, a)} />\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n )}\n <table className=\"ca-modal-table\">\n <caption>{t.accessHeading}</caption>\n <thead>\n <tr>\n <th scope=\"col\">R</th>\n {ids.map((w) => (\n <th key={w} scope=\"col\">\n {name(w)}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {ids.map((a) => (\n <tr key={a}>\n <th scope=\"row\">{name(a)}</th>\n {ids.map((b) => (\n <td key={b}>\n <input type=\"checkbox\" aria-label={t.accessToggle(name(a), name(b))} checked={pairs.some(([x, y]) => x === a && y === b)} onChange={() => onPair(a, b)} />\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )\n}\n","import type { ReactNode } from 'react'\nimport { useEffect, useId, useRef, useState } from 'react'\nimport type { Problem } from '../../engine/index.ts'\nimport { problemMessage, useMessages } from '../i18n/messages.ts'\n\n/** Small shared pieces: segmented control, disclosure, progress, icons, tags. */\n\nexport interface SegmentedProps<T extends string> {\n readonly label: string\n readonly options: readonly { readonly value: T; readonly label: string }[]\n readonly value: T\n readonly onChange: (value: T) => void\n readonly className?: string\n}\n\nexport function Segmented<T extends string>({ label, options, value, onChange, className }: SegmentedProps<T>) {\n return (\n <div className={`ca-seg ${className ?? ''}`} role=\"group\" aria-label={label}>\n {options.map((o) => (\n <button\n key={o.value}\n type=\"button\"\n className=\"ca-seg-item\"\n aria-pressed={o.value === value}\n onClick={() => onChange(o.value)}\n >\n {o.label}\n </button>\n ))}\n </div>\n )\n}\n\nexport interface DisclosureProps {\n /** Small label before the title; default 補充 / More. Empty for none. */\n readonly kicker?: string\n readonly title: ReactNode\n readonly children: ReactNode\n readonly defaultOpen?: boolean\n readonly className?: string\n}\n\n/** A box that stays closed until asked; the header button carries aria-expanded. */\nexport function Disclosure({ kicker: kickerProp, title, children, defaultOpen = false, className }: DisclosureProps) {\n const t = useMessages()\n const kicker = kickerProp ?? t.more\n const [open, setOpen] = useState(defaultOpen)\n const id = useId()\n return (\n <section className={`ca-disclosure ${className ?? ''}`} data-open={open ? 'true' : 'false'}>\n <button\n type=\"button\"\n className=\"ca-disclosure-head\"\n aria-expanded={open}\n aria-controls={id}\n onClick={() => setOpen((o) => !o)}\n >\n {kicker !== '' && <span className=\"ca-disclosure-kicker\">{kicker}</span>}\n <span className=\"ca-disclosure-title\">{title}</span>\n <PlusMinus open={open} />\n </button>\n <div id={id} className=\"ca-disclosure-body\" hidden={!open}>\n {open && children}\n </div>\n </section>\n )\n}\n\nexport interface TipProps {\n /** What the tooltip explains; shown on hover, keyboard focus or a tap. */\n readonly tip: ReactNode\n /** The trigger's own content; default a small ⓘ mark. */\n readonly children?: ReactNode\n /** Accessible name of the default mark. */\n readonly label?: string\n readonly className?: string\n}\n\n/**\n * The one tooltip primitive: a focusable trigger described by (`aria-describedby`) a\n * `role=\"tooltip\"` element. Hover or focus shows it, a tap or click toggles it, Escape or leaving\n * hides it. Short on-graph notes stay as they are; anything longer goes in here.\n */\nexport function Tip({ tip, children, label, className }: TipProps) {\n const id = useId()\n const [open, setOpen] = useState(false)\n const ref = useRef<HTMLSpanElement>(null)\n useEffect(() => {\n if (!open) return\n const outside = (e: Event): void => {\n if (e.target instanceof Node && ref.current?.contains(e.target) !== true) setOpen(false)\n }\n document.addEventListener('pointerdown', outside)\n return () => document.removeEventListener('pointerdown', outside)\n }, [open])\n return (\n <span className={`ca-tip ${className ?? ''}`} ref={ref} onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>\n <span\n className={`ca-tip-trigger${children === undefined ? ' is-mark' : ''}`}\n role={children === undefined ? 'button' : undefined}\n tabIndex={0}\n aria-label={children === undefined ? label : undefined}\n aria-describedby={id}\n onFocus={() => setOpen(true)}\n onBlur={() => setOpen(false)}\n onClick={() => setOpen((o) => !o)}\n onKeyDown={(e) => {\n if (e.key === 'Escape') {\n if (open) e.stopPropagation()\n setOpen(false)\n }\n else if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n setOpen((o) => !o)\n }\n }}\n >\n {children ?? <span aria-hidden=\"true\">ⓘ</span>}\n </span>\n <span id={id} role=\"tooltip\" className=\"ca-tip-body\" hidden={!open}>\n {tip}\n </span>\n </span>\n )\n}\n\nfunction PlusMinus({ open }: { readonly open: boolean }) {\n return (\n <svg className=\"ca-icon\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d={open ? 'M2 8h12' : 'M2 8h12M8 2v12'} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n </svg>\n )\n}\n\nexport function Arrow() {\n return (\n <svg className=\"ca-icon ca-arrow\" width=\"26\" height=\"14\" viewBox=\"0 0 26 14\" aria-hidden=\"true\">\n <path d=\"M1 7h23m-6-6l6 6l-6 6\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n </svg>\n )\n}\n\nexport function OkIcon({ size = 20 }: { readonly size?: number }) {\n return (\n <svg className=\"ca-icon ca-ok\" width={size} height={size} viewBox=\"-10 -10 20 20\" aria-hidden=\"true\">\n <circle r=\"10\" className=\"ca-fill-green\" />\n <path d=\"M-5 0l4 4l6-8\" fill=\"none\" className=\"ca-stroke-on-green\" strokeWidth=\"2\" />\n </svg>\n )\n}\n\nexport function NoIcon({ size = 20 }: { readonly size?: number }) {\n return (\n <svg className=\"ca-icon ca-no\" width={size} height={size} viewBox=\"-11 -11 22 22\" aria-hidden=\"true\">\n <circle r=\"9.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n <path d=\"M-4 -4l8 8m0-8l-8 8\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n </svg>\n )\n}\n\nexport function PartIcon({ size = 20 }: { readonly size?: number }) {\n return (\n <svg className=\"ca-icon ca-part\" width={size} height={size} viewBox=\"-11 -11 22 22\" aria-hidden=\"true\">\n <circle r=\"9.5\" fill=\"none\" className=\"ca-stroke-green\" strokeWidth=\"1.75\" />\n <path d=\"M0 -9.5A9.5 9.5 0 0 1 0 9.5z\" className=\"ca-fill-green\" />\n </svg>\n )\n}\n\nexport function Pin() {\n return (\n <svg className=\"ca-icon\" width=\"10\" height=\"14\" viewBox=\"-5 -7 10 14\" aria-hidden=\"true\">\n <circle cy=\"-2.5\" r=\"3.5\" className=\"ca-fill-amber-mark\" />\n <path d=\"M0 0v6.5\" className=\"ca-stroke-amber\" strokeWidth=\"1.75\" strokeLinecap=\"round\" />\n </svg>\n )\n}\n\nexport function Progress({ step, total }: { readonly step: number; readonly total: number }) {\n const t = useMessages()\n return (\n <span className=\"ca-progress\" role=\"img\" aria-label={t.stepOf(step, total)}>\n {Array.from({ length: total }, (_, i) => (\n <span key={i} className=\"ca-progress-dot\" data-on={i < step ? 'true' : 'false'} />\n ))}\n <span className=\"ca-progress-text ca-mono\" aria-hidden=\"true\">\n {step}/{total}\n </span>\n </span>\n )\n}\n\nexport type TagTone = 'fg' | 'slate' | 'accent' | 'chip' | 'line' | 'amber' | 'outline'\n\nexport function Tag({ tone, children, mono }: { readonly tone: TagTone; readonly children: ReactNode; readonly mono?: boolean }) {\n return <span className={`ca-tag ca-tag-${tone}${mono === true ? ' ca-mono' : ''}`}>{children}</span>\n}\n\n/** A model document that could not be drawn: every problem with its stable code (and the first as `data-code`). */\nexport function DocProblems({ problems }: { readonly problems: readonly Problem[] }) {\n const t = useMessages()\n return (\n <div className=\"ca-root not-prose ca-editor-errors ca-doc-error\" role=\"alert\" data-code={problems[0]?.code} lang={t.locale}>\n <p>{t.docInvalid}</p>\n <ul>\n {problems.map((p, i) => (\n <li key={`${p.code}-${i}`}>\n <code className=\"ca-mono\">{p.code}</code> {problemMessage(p, t)}\n </li>\n ))}\n </ul>\n </div>\n )\n}\n","/**\n * Properties of a finite binary relation R ⊆ X × X, each with the elements that witness a failure.\n * Shared by the modal frame conditions and, later, the set-theory relation views. Pure.\n */\n\nexport interface FiniteRelation {\n /** The carrier X, in a fixed order. */\n readonly elements: readonly string[]\n /** The pairs (a, b) with a R b. */\n readonly pairs: readonly (readonly [string, string])[]\n}\n\n/** A typed relation between two finite concepts. The concepts can overlap. */\nexport interface Correspondence {\n readonly left: readonly string[]\n readonly right: readonly string[]\n readonly pairs: readonly (readonly [string, string])[]\n}\n\nexport interface PartnerIssue {\n readonly side: 'left' | 'right'\n readonly element: string\n readonly degree: number\n}\n\n/** Functional and injective mean at most one partner; a bijection needs exactly one on each side. */\nexport function checkCorrespondence(r: Correspondence) {\n const partners = (xs: readonly string[]) => new Map(xs.map(x => [x, new Set<string>()]))\n const left = partners(r.left), right = partners(r.right)\n if (left.size !== r.left.length || right.size !== r.right.length) throw new RangeError('duplicate concept member')\n for (const [x,y] of r.pairs) {\n if (!left.has(x) || !right.has(y)) throw new RangeError('pair outside the concepts')\n left.get(x)!.add(y)\n right.get(y)!.add(x)\n }\n const issues: PartnerIssue[] = []\n for (const [side, members] of [['left',left],['right',right]] as const) {\n for (const [element,p] of members) if (p.size !== 1) issues.push({ side, element, degree: p.size })\n }\n return { functional: !issues.some(i => i.side === 'left' && i.degree > 1), injective: !issues.some(i => i.side === 'right' && i.degree > 1), bijection: !issues.length, issues }\n}\n\n/** A property's verdict: `witness` lists the elements that break it, in the order the property names them. */\nexport type RelationCheck = { readonly holds: true } | { readonly holds: false; readonly witness: readonly string[] }\n\nexport type RelationProperty = 'serial' | 'reflexive' | 'irreflexive' | 'symmetric' | 'transitive' | 'euclidean'\n\n/** Every property this module checks. */\nexport const RELATION_PROPERTIES: readonly RelationProperty[] = ['serial', 'reflexive', 'irreflexive', 'symmetric', 'transitive', 'euclidean']\n\nconst HOLDS: RelationCheck = { holds: true }\n\nfunction fails(...witness: string[]): RelationCheck {\n return { holds: false, witness }\n}\n\n/** Membership test for the pairs. */\nfunction relates(r: FiniteRelation): (a: string, b: string) => boolean {\n const set = new Set(r.pairs.map(([a, b]) => `${a}\\u0000${b}`))\n return (a, b) => set.has(`${a}\\u0000${b}`)\n}\n\n/**\n * Whether `r` has `property`. Witnesses: serial, reflexive and irreflexive name the one element x\n * (no x R y; not x R x; x R x); symmetric names (x, y) with x R y but not y R x; transitive names\n * (x, y, z) with x R y, y R z but not x R z; euclidean names (x, y, z) with x R y, x R z but not y R z.\n * The first witness in the element order is returned.\n */\nexport function checkRelation(r: FiniteRelation, property: RelationProperty): RelationCheck {\n const has = relates(r)\n const xs = r.elements\n switch (property) {\n case 'serial':\n for (const x of xs) if (!xs.some((y) => has(x, y))) return fails(x)\n return HOLDS\n case 'reflexive':\n for (const x of xs) if (!has(x, x)) return fails(x)\n return HOLDS\n case 'irreflexive':\n for (const x of xs) if (has(x, x)) return fails(x)\n return HOLDS\n case 'symmetric':\n for (const x of xs) for (const y of xs) if (has(x, y) && !has(y, x)) return fails(x, y)\n return HOLDS\n case 'transitive':\n for (const x of xs) for (const y of xs) for (const z of xs) if (has(x, y) && has(y, z) && !has(x, z)) return fails(x, y, z)\n return HOLDS\n case 'euclidean':\n for (const x of xs) for (const y of xs) for (const z of xs) if (has(x, y) && has(x, z) && !has(y, z)) return fails(x, y, z)\n return HOLDS\n }\n}\n\n// Antisymmetry, transitive closure and reduction: the Hasse diagram of a parthood model (Varzi, SEP\n// \"Mereology\", Figs 2–3). Kept apart from `checkRelation` so the entries that only check frame\n// conditions do not carry them.\n\n/** Whether `r` is antisymmetric; a failure names the first (x, y) in the element order with x ≠ y, x R y and y R x. */\nexport function checkAntisymmetry(r: FiniteRelation): RelationCheck {\n const has = relates(r)\n for (const x of r.elements) for (const y of r.elements) if (x !== y && has(x, y) && has(y, x)) return fails(x, y)\n return HOLDS\n}\n\n/** The transitive closure of `r` (Warshall): its pairs row by row in the element order. */\nexport function transitiveClosure(r: FiniteRelation): FiniteRelation {\n const reach = reachability(r)\n const xs = r.elements\n return { elements: xs, pairs: xs.flatMap((x, i) => xs.flatMap((y, j) => (reach[i]?.[j] ? [[x, y] as const] : []))) }\n}\n\n/** The lines of a Hasse diagram of `r`, read through its reflexive and transitive closure R*. */\nexport interface RelationReduction {\n /**\n * Pairs (a, b) with a below b: a R* b, not b R* a, and nothing strictly between them. Elements that\n * are R*-related both ways count as one point; a cover of such a class links the members the\n * input relates directly (else its first members).\n */\n readonly covers: readonly (readonly [string, string])[]\n /** Distinct elements related both ways (the failures of antisymmetry): each class as a path of consecutive members. */\n readonly mutual: readonly (readonly [string, string])[]\n}\n\n/** The transitive reduction of `r`'s reflexive and transitive closure: what a Hasse diagram draws. */\nexport function transitiveReduction(r: FiniteRelation): RelationReduction {\n const xs = r.elements\n const reach = reachability(r)\n const at = (i: number, j: number) => i === j || (reach[i]?.[j] ?? false)\n // Classes of mutually related elements, in the order of their first member.\n const classOf = xs.map(() => -1)\n const classes: number[][] = []\n xs.forEach((_, i) => {\n if ((classOf[i] as number) >= 0) return\n const members = xs.map((_, j) => j).filter((j) => at(i, j) && at(j, i))\n for (const j of members) classOf[j] = classes.length\n classes.push(members)\n })\n const rep = (c: number) => (classes[c] as number[])[0] as number\n const below = (c: number, d: number) => c !== d && at(rep(c), rep(d))\n const covers: (readonly [string, string])[] = []\n classes.forEach((_, c) => {\n classes.forEach((upper, d) => {\n if (!below(c, d) || classes.some((_, e) => below(c, e) && below(e, d))) return\n const lower = classes[c] as number[]\n const direct = r.pairs.find(([a, b]) => lower.includes(xs.indexOf(a)) && upper.includes(xs.indexOf(b)))\n covers.push(direct ?? [xs[rep(c)] as string, xs[rep(d)] as string])\n })\n })\n const mutual = classes.flatMap((members) => members.slice(1).map((j, k) => [xs[members[k] as number] as string, xs[j] as string] as const))\n return { covers, mutual }\n}\n\n/** reach[i][j]: element j is reached from element i by one or more steps of `r`. */\nfunction reachability(r: FiniteRelation): boolean[][] {\n const xs = r.elements\n const index = new Map(xs.map((x, i) => [x, i]))\n const reach = xs.map(() => xs.map(() => false))\n for (const [a, b] of r.pairs) {\n const i = index.get(a)\n const j = index.get(b)\n if (i !== undefined && j !== undefined) (reach[i] as boolean[])[j] = true\n }\n for (let k = 0; k < xs.length; k++) {\n for (let i = 0; i < xs.length; i++) {\n if (!reach[i]?.[k]) continue\n for (let j = 0; j < xs.length; j++) if (reach[k]?.[j]) (reach[i] as boolean[])[j] = true\n }\n }\n return reach\n}\n","import type { RelationCheck } from '../../logic/relations.ts'\nimport { checkRelation } from '../../logic/relations.ts'\nimport { ModalError, modalProblem } from './errors.ts'\nimport type { Formula } from './formula.ts'\nimport { atomsOf, parseFormula } from './formula.ts'\nimport type { Frame } from './model.ts'\nimport { accessPairs } from './model.ts'\n\n/**\n * Frame conditions and the axioms they correspond to (Garson, pp. 112–113): an axiom is valid on a\n * frame (true at every world under every assignment) exactly when the frame meets its condition.\n */\n\nexport type FrameCondition = 'serial' | 'reflexive' | 'transitive' | 'symmetric' | 'euclidean'\n\n/** The axioms the first phase shows. Garson's M is the T of most texts. */\nexport type AxiomName = 'K' | 'D' | 'M' | '4' | 'B' | '5'\n\nexport interface AxiomInfo {\n readonly name: AxiomName\n /** The axiom in the authoring syntax. */\n readonly source: string\n readonly formula: Formula\n /** The frame condition it corresponds to; K has none: it is valid on every frame. */\n readonly condition: FrameCondition | undefined\n}\n\nconst axiom = (name: AxiomName, source: string, condition: FrameCondition | undefined): AxiomInfo => ({ name, source, formula: parseFormula(source), condition })\n\nexport const AXIOMS: Readonly<Record<AxiomName, AxiomInfo>> = {\n K: axiom('K', '[](p -> q) -> ([]p -> []q)', undefined),\n D: axiom('D', '[]p -> <>p', 'serial'),\n M: axiom('M', '[]p -> p', 'reflexive'),\n '4': axiom('4', '[]p -> [][]p', 'transitive'),\n B: axiom('B', 'p -> []<>p', 'symmetric'),\n '5': axiom('5', '<>p -> []<>p', 'euclidean'),\n}\n\n/** The conditions in the order the components list them, with their axioms. */\nexport const CONDITION_AXIOM: Readonly<Record<FrameCondition, AxiomName>> = { serial: 'D', reflexive: 'M', transitive: '4', symmetric: 'B', euclidean: '5' }\nexport const FRAME_CONDITIONS: readonly FrameCondition[] = ['serial', 'reflexive', 'transitive', 'symmetric', 'euclidean']\n\n/**\n * Whether the frame's R meets `condition`. A failure names the worlds that break it: serial and\n * reflexive one world w; symmetric (w, v) with wRv, not vRw; transitive (w, v, u) with wRv, vRu,\n * not wRu; euclidean (w, v, u) with wRv, wRu, not vRu.\n */\nexport function checkCondition(frame: Frame, condition: FrameCondition): RelationCheck {\n return checkRelation({ elements: frame.worlds, pairs: accessPairs(frame) }, condition)\n}\n\n/** Assignments `validOnFrame` enumerates at most: 2^16, e.g. two atoms on eight worlds. */\nexport const MAX_ASSIGNMENTS = 65_536\n\n/** A failed axiom instance: the assignment (each atom with the worlds where it is true) and the world where the formula is false. */\nexport interface FrameCounterexample {\n readonly world: string\n readonly trueAt: Readonly<Record<string, readonly string[]>>\n}\n\nexport type FrameValidity = { readonly valid: true } | { readonly valid: false; readonly counterexample: FrameCounterexample }\n\n/** Truth sets as bit masks over the frame's worlds: fast enough to try every assignment. */\nfunction compileFrame(frame: Frame): { readonly n: number; readonly all: number; readonly succ: readonly number[] } {\n const n = frame.worlds.length\n const index = new Map(frame.worlds.map((w, i) => [w, i]))\n const succ = frame.worlds.map((w) => (frame.access[w] ?? []).reduce((m, v) => m | (1 << (index.get(v) as number)), 0))\n return { n, all: n === 0 ? 0 : (2 ** n - 1) | 0, succ }\n}\n\nfunction maskOf(f: Formula, atoms: ReadonlyMap<string, number>, c: ReturnType<typeof compileFrame>): number {\n switch (f.kind) {\n case 'atom':\n return atoms.get(f.id) as number\n case 'top':\n return c.all\n case 'bot':\n return 0\n case 'not':\n return c.all & ~maskOf(f.arg, atoms, c)\n case 'and':\n return maskOf(f.left, atoms, c) & maskOf(f.right, atoms, c)\n case 'or':\n return maskOf(f.left, atoms, c) | maskOf(f.right, atoms, c)\n case 'imp':\n return (c.all & ~maskOf(f.left, atoms, c)) | maskOf(f.right, atoms, c)\n case 'iff':\n return c.all & ~(maskOf(f.left, atoms, c) ^ maskOf(f.right, atoms, c))\n case 'box': {\n const a = maskOf(f.arg, atoms, c)\n let out = 0\n for (let i = 0; i < c.n; i += 1) if (((c.succ[i] as number) & ~a) === 0) out |= 1 << i\n return out\n }\n case 'dia': {\n const a = maskOf(f.arg, atoms, c)\n let out = 0\n for (let i = 0; i < c.n; i += 1) if (((c.succ[i] as number) & a) !== 0) out |= 1 << i\n return out\n }\n case 'cf':\n return 0\n }\n}\n\n/**\n * Whether `formula` is valid on the frame: true at every world under every assignment of its atoms.\n * Tries all (2^|W|)^atoms assignments, at most {@link MAX_ASSIGNMENTS}; a failure returns the first\n * assignment and world that falsify it.\n */\nexport function validOnFrame(frame: Frame, formula: Formula): FrameValidity {\n if (JSON.stringify(formula).includes('\"kind\":\"cf\"')) throw new ModalError(modalProblem('no-sphere-system', { world: frame.worlds[0] as string }))\n const atoms = atomsOf(formula)\n const c = compileFrame(frame)\n const count = 2 ** (c.n * atoms.length)\n if (count > MAX_ASSIGNMENTS) throw new ModalError(modalProblem('too-many-assignments', { count, limit: MAX_ASSIGNMENTS }))\n const subsets = 2 ** c.n\n const masks = new Map<string, number>()\n for (let code = 0; code < count; code += 1) {\n let rest = code\n for (const a of atoms) {\n masks.set(a, rest % subsets)\n rest = Math.floor(rest / subsets)\n }\n const value = maskOf(formula, masks, c)\n if (value !== c.all) {\n const i = frame.worlds.findIndex((_, k) => (value & (1 << k)) === 0)\n const trueAt = Object.fromEntries(atoms.map((a) => [a, frame.worlds.filter((_, k) => ((masks.get(a) as number) & (1 << k)) !== 0)]))\n return { valid: false, counterexample: { world: frame.worlds[i] as string, trueAt } }\n }\n }\n return { valid: true }\n}\n\n/** The normal systems whose frame classes the first phase names. */\nexport type ModalSystem = 'K' | 'D' | 'M' | 'S4' | 'B' | 'S5'\n\n/** Each system with the conditions that define its frames (Garson, pp. 112–113). */\nexport const SYSTEM_CONDITIONS: Readonly<Record<ModalSystem, readonly FrameCondition[]>> = {\n K: [],\n D: ['serial'],\n M: ['reflexive'],\n S4: ['reflexive', 'transitive'],\n B: ['reflexive', 'symmetric'],\n S5: ['reflexive', 'symmetric', 'transitive'],\n}\n\nexport const SYSTEMS: readonly ModalSystem[] = ['K', 'D', 'M', 'S4', 'B', 'S5']\n\n/** The systems whose frame class contains this frame: every theorem of each is valid on it. */\nexport function systemsOf(frame: Frame): ModalSystem[] {\n const met = new Set(FRAME_CONDITIONS.filter((c) => checkCondition(frame, c).holds))\n return SYSTEMS.filter((s) => SYSTEM_CONDITIONS[s].every((c) => met.has(c)))\n}\n","import { useMemo, useState } from 'react'\nimport { NoIcon, OkIcon } from '../../components/shared/parts.tsx'\nimport type { RelationCheck } from '../../logic/relations.ts'\nimport type { FrameCondition, FrameValidity } from '../engine/frames.ts'\nimport { AXIOMS, CONDITION_AXIOM, FRAME_CONDITIONS, checkCondition, systemsOf, validOnFrame } from '../engine/frames.ts'\nimport { frameOfDoc } from '../data/load.ts'\nimport type { FrameDoc, KripkeDoc } from '../data/schema.ts'\nimport { useModalMessages } from '../i18n/messages.ts'\nimport { docGraphInput, namesOf, worldNames } from './doc-graph.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { FormulaMath, ModalProblems, ModalRoot } from './parts.tsx'\nimport { useModalDoc } from './use-doc.ts'\nimport { layoutWorldGraph } from './world-graph.ts'\nimport type { WorldMark } from './WorldGraph.tsx'\nimport { WorldGraph } from './WorldGraph.tsx'\n\nexport interface FrameConditionsProps extends ModalCommonProps {\n /** A `frame` document, or a `kripke` one whose valuation is ignored (JSON text or value). */\n readonly frame: ModalModelInput\n /** The conditions to list, in this order; default serial, reflexive, transitive, symmetric, euclidean. */\n readonly conditions?: readonly FrameCondition[]\n /** Show each condition's axiom and whether it is valid on the frame; default true. */\n readonly axioms?: boolean\n /** Name the systems whose frame class holds the frame; default true. */\n readonly systems?: boolean\n /** The condition picked first; its counterexample is marked in the picture. */\n readonly initial?: FrameCondition\n}\n\n/**\n * A frame's conditions beside their axioms: whether R is serial, reflexive, transitive, symmetric and\n * euclidean, each failure with the worlds that break it, and whether D, M, 4, B and 5 are valid on the\n * frame, each failure with the assignment and world that falsify it. The two columns always agree.\n */\nexport function FrameConditions(props: FrameConditionsProps) {\n return (\n <ModalRoot locale={props.locale} name=\"frame\" caption={props.caption}>\n <FrameBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['frame', 'kripke'] as const\n\nfunction FrameBody(props: FrameConditionsProps) {\n const loaded = useModalDoc(props.frame, KINDS)\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n return <FrameLoaded {...props} doc={loaded.doc} />\n}\n\ninterface Row {\n readonly condition: FrameCondition\n readonly check: RelationCheck\n readonly validity: FrameValidity\n}\n\nfunction FrameLoaded(props: FrameConditionsProps & { readonly doc: FrameDoc | KripkeDoc }) {\n const { doc, notation = 'modern', axioms = true, systems = true } = props\n const t = useModalMessages()\n const conditions = props.conditions ?? FRAME_CONDITIONS\n const frame = useMemo(() => frameOfDoc(doc), [doc])\n const rows: Row[] = useMemo(\n () => conditions.map((condition) => ({ condition, check: checkCondition(frame, condition), validity: validOnFrame(frame, AXIOMS[CONDITION_AXIOM[condition]].formula) })),\n [frame, conditions],\n )\n const [focus, setFocus] = useState<FrameCondition | undefined>(props.initial)\n const names = worldNames(doc, t.locale)\n const layout = useMemo(() => layoutWorldGraph(docGraphInput({ ...doc, kind: 'frame' } as FrameDoc, t.locale, { showFalse: false, notation, mergeSymmetric: true })), [doc, t.locale, notation])\n const focused = rows.find((r) => r.condition === focus)\n const marks = new Map<string, WorldMark>()\n if (focused !== undefined && !focused.check.holds) for (const w of focused.check.witness) marks.set(w, 'counter')\n const name = (id: string) => names.get(id) ?? id\n return (\n <div className=\"ca-modal-stack\">\n <div className=\"ca-modal-figure\">\n <WorldGraph layout={layout} label={t.worldGraph(doc.worlds.length)} marks={marks} worldLabel={(id) => name(id)} />\n </div>\n <div className=\"ca-modal-side\">\n <div className=\"ca-modal-scroll\">\n <table className=\"ca-modal-table ca-modal-conditions\">\n <thead>\n <tr>\n <th scope=\"col\">{t.conditionHeading}</th>\n <th scope=\"col\">{t.holdsHeading}</th>\n {axioms && <th scope=\"col\">{t.axiomHeading}</th>}\n {axioms && <th scope=\"col\">{t.validHeading}</th>}\n </tr>\n </thead>\n <tbody>\n {rows.map((r) => {\n const axiom = AXIOMS[CONDITION_AXIOM[r.condition]]\n return (\n <tr key={r.condition} data-condition={r.condition} data-selected={r.condition === focus ? 'true' : undefined} data-holds={r.check.holds ? 'true' : 'false'}>\n <th scope=\"row\">\n <button type=\"button\" className=\"ca-modal-pick\" aria-pressed={r.condition === focus} onClick={() => setFocus(r.condition === focus ? undefined : r.condition)}>\n {t.conditionName[r.condition]}\n </button>\n <span className=\"ca-modal-rule ca-small ca-muted\">{t.conditionRule[r.condition]}</span>\n </th>\n <td>\n <Verdict ok={r.check.holds} text={r.check.holds ? t.yes : t.conditionWitness(r.condition, namesOf(names, r.check.witness))} />\n </td>\n {axioms && (\n <td>\n <span className=\"ca-modal-axiom\">{t.axiomName(axiom.name)}</span> <FormulaMath formula={axiom.formula} notation={notation} />\n </td>\n )}\n {axioms && (\n <td>\n <Verdict\n ok={r.validity.valid}\n text={\n r.validity.valid\n ? t.yes\n : t.axiomCounterexample(\n Object.fromEntries(Object.entries(r.validity.counterexample.trueAt).map(([a, ws]) => [a, namesOf(names, ws)])),\n name(r.validity.counterexample.world),\n )\n }\n />\n </td>\n )}\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n {systems && <p className=\"ca-modal-systems\">{t.systemsLine(systemsOf(frame).map((s) => t.systemName(s)))}</p>}\n </div>\n </div>\n )\n}\n\nfunction Verdict({ ok, text }: { readonly ok: boolean; readonly text: string }) {\n return (\n <span className=\"ca-modal-verdict\" data-ok={ok ? 'true' : 'false'}>\n {ok ? <OkIcon size={16} /> : <NoIcon size={16} />} <span>{text}</span>\n </span>\n )\n}\n","import { useMemo, useState } from 'react'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport { F } from '../engine/formula.ts'\nimport { modelOfDoc, startWorld } from '../data/load.ts'\nimport type { KripkeDoc } from '../data/schema.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { docGraphInput, namesOf, worldNames } from './doc-graph.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark } from './parts.tsx'\nimport { parseAll, unknownAtomProblem, useModalDoc } from './use-doc.ts'\nimport { layoutWorldGraph } from './world-graph.ts'\nimport type { WorldMark } from './WorldGraph.tsx'\nimport { WorldGraph } from './WorldGraph.tsx'\n\nexport interface StrictImplicationProps extends ModalCommonProps {\n /** A `kripke` document (JSON text or value). */\n readonly model: ModalModelInput\n readonly antecedent: string\n readonly consequent: string\n /** The world selected first; default the document's `actual`. */\n readonly world?: string\n}\n\n/**\n * The material conditional A ⊃ B beside the strict one □(A ⊃ B) on one model: the material one asks\n * only about the selected world, the strict one about every world it sees, and the picture marks the\n * accessible worlds where A is true and B false.\n */\nexport function StrictImplication(props: StrictImplicationProps) {\n return (\n <ModalRoot locale={props.locale} name=\"strict\" caption={props.caption}>\n <StrictBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['kripke'] as const\n\nfunction StrictBody(props: StrictImplicationProps) {\n const t = useModalMessages()\n const loaded = useModalDoc(props.model, KINDS)\n const [a, b] = useMemo(() => parseAll([props.antecedent, props.consequent]), [props.antecedent, props.consequent])\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n for (const f of [a, b]) {\n if (f !== undefined && !f.ok) {\n return (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(f.error, t)}\n </p>\n )\n }\n }\n if (a?.ok !== true || b?.ok !== true) return null\n const missing = unknownAtomProblem([a.formula, b.formula], loaded.doc.atoms.map((x) => x.id))\n if (missing !== undefined) return <ModalProblems problems={[missing]} />\n return <StrictLoaded {...props} doc={loaded.doc} a={a.formula} b={b.formula} />\n}\n\nfunction StrictLoaded(props: StrictImplicationProps & { readonly doc: KripkeDoc; readonly a: Formula; readonly b: Formula }) {\n const { doc, a, b, notation = 'modern' } = props\n const t = useModalMessages()\n const ev = useMemo(() => new ModalEvaluator(modelOfDoc(doc)), [doc])\n const [world, setWorld] = useState(() => (props.world !== undefined && doc.worlds.some((w) => w.id === props.world) ? props.world : startWorld(doc)))\n const names = worldNames(doc, t.locale)\n const name = (id: string) => names.get(id) ?? id\n const layout = useMemo(() => layoutWorldGraph(docGraphInput(doc, t.locale, { showFalse: true, notation, mergeSymmetric: true })), [doc, t.locale, notation])\n const material = F.imp(a, b)\n const strict = F.strict(a, b)\n let seen: readonly string[] = []\n let problem: string | undefined\n try {\n seen = ev.accessible(world)\n } catch (error) {\n problem = modalErrorMessage(error, t)\n }\n const bad = seen.filter((v) => ev.holds(a, v) && !ev.holds(b, v))\n const marks = new Map<string, WorldMark>(seen.map((v) => [v, bad.includes(v) ? 'counter' : 'true']))\n const materialValue = ev.holds(material, world)\n const strictValue = bad.length === 0\n return (\n <div className=\"ca-modal-split\">\n <div className=\"ca-modal-figure\">\n <WorldGraph\n layout={layout}\n label={t.worldGraph(doc.worlds.length)}\n selected={world}\n marks={marks}\n worldLabel={(id) => `${t.selectWorld(name(id))}. ${t.worldState(name(id), doc.worlds.find((w) => w.id === id)?.true ?? [])}`}\n onSelect={setWorld}\n />\n </div>\n <div className=\"ca-modal-side\">\n <p className=\"ca-modal-at ca-h3\">{t.at(name(world))}</p>\n <dl className=\"ca-modal-pair\">\n <div data-kind=\"material\">\n <dt>{t.materialHeading}</dt>\n <dd>\n <FormulaMath formula={material} notation={notation} /> <TruthMark value={materialValue} />\n <p className=\"ca-small\">{materialValue ? t.materialTrue(name(world), !ev.holds(a, world)) : t.materialFalse(name(world))}</p>\n </dd>\n </div>\n <div data-kind=\"strict\">\n <dt>{t.strictHeading}</dt>\n <dd>\n <FormulaMath formula={strict} notation={notation} /> <TruthMark value={strictValue} />\n <p className=\"ca-small\">{strictValue ? t.strictTrue(name(world)) : t.strictFalse(name(world), namesOf(names, bad))}</p>\n </dd>\n </div>\n </dl>\n {problem !== undefined && (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {problem}\n </p>\n )}\n <div className=\"ca-modal-scroll\">\n <table className=\"ca-modal-table\">\n <thead>\n <tr>\n <th scope=\"col\">{t.world}</th>\n <th scope=\"col\">\n <FormulaMath formula={a} notation={notation} />\n </th>\n <th scope=\"col\">\n <FormulaMath formula={b} notation={notation} />\n </th>\n <th scope=\"col\">\n <FormulaMath formula={material} notation={notation} />\n </th>\n </tr>\n </thead>\n <tbody>\n {doc.worlds.map((w) => (\n <tr key={w.id} data-selected={w.id === world ? 'true' : undefined} data-seen={seen.includes(w.id) ? 'true' : undefined}>\n <th scope=\"row\">{name(w.id)}</th>\n <td>\n <TruthMark value={ev.holds(a, w.id)} />\n </td>\n <td>\n <TruthMark value={ev.holds(b, w.id)} />\n </td>\n <td>\n <TruthMark value={ev.holds(material, w.id)} />\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n <AtomLegend atoms={doc.atoms} />\n </div>\n </div>\n )\n}\n","import type { EvalOptions } from './evaluate.ts'\nimport { ModalEvaluator } from './evaluate.ts'\nimport type { Formula } from './formula.ts'\nimport { F } from './formula.ts'\nimport type { ModalModel } from './model.ts'\n\n/**\n * The three inferences that hold for strict implication and fail for counterfactuals (Garson §20.5):\n * transitivity, contraposition and strengthening the antecedent, written with `>` or with the strict\n * conditional □(A ⊃ B), and checked world by world.\n */\n\nexport type TcsPattern = 'transitivity' | 'contraposition' | 'strengthening'\n\nexport const TCS_PATTERNS: readonly TcsPattern[] = ['transitivity', 'contraposition', 'strengthening']\n\n/** Which conditional an inference is written with. */\nexport type ConditionalKind = 'counterfactual' | 'strict'\n\nexport interface Inference {\n readonly premises: readonly Formula[]\n readonly conclusion: Formula\n}\n\n/** ¬f, writing ¬¬g as g (equivalent, and how the contrapositive is read aloud). */\nfunction negate(f: Formula): Formula {\n return f.kind === 'not' ? f.arg : F.not(f)\n}\n\n/**\n * The inference `pattern` with the conditional `kind`, on formulas a, b and c:\n * transitivity a→b, b→c ∴ a→c; contraposition a→b ∴ ¬b→¬a (a negated formula loses its ¬ instead\n * of gaining a second); strengthening a→b ∴ (a ∧ c)→b.\n * `c` is needed for transitivity and strengthening.\n */\nexport function tcsInference(pattern: TcsPattern, kind: ConditionalKind, a: Formula, b: Formula, c?: Formula): Inference {\n const to = kind === 'strict' ? F.strict : F.cf\n const third = c ?? b\n switch (pattern) {\n case 'transitivity':\n return { premises: [to(a, b), to(b, third)], conclusion: to(a, third) }\n case 'contraposition':\n return { premises: [to(a, b)], conclusion: to(negate(b), negate(a)) }\n case 'strengthening':\n return { premises: [to(a, b)], conclusion: to(F.and(a, third), b) }\n }\n}\n\n/** An inference at one world: the premises' values, the conclusion's, and whether this world is a counterexample. */\nexport interface InferenceAt {\n readonly world: string\n readonly premises: readonly boolean[]\n readonly conclusion: boolean\n /** Every premise true and the conclusion false. */\n readonly counterexample: boolean\n}\n\nexport function checkInferenceAt(model: ModalModel, inference: Inference, world: string, options?: EvalOptions): InferenceAt {\n const ev = new ModalEvaluator(model, options)\n const premises = inference.premises.map((p) => ev.holds(p, world))\n const conclusion = ev.holds(inference.conclusion, world)\n return { world, premises, conclusion, counterexample: premises.every(Boolean) && !conclusion }\n}\n\n/** The inference at every world of `worlds` (default: every world with a system of spheres, or every world). */\nexport function checkInference(model: ModalModel, inference: Inference, options?: EvalOptions & { readonly worlds?: readonly string[] }): InferenceAt[] {\n const worlds = options?.worlds ?? (model.spheres === undefined ? model.worlds : model.worlds.filter((w) => model.spheres?.[w] !== undefined))\n return worlds.map((w) => checkInferenceAt(model, inference, w, options))\n}\n","import type { Box, Placed } from '../../components/graph/graph-labels.ts'\nimport { around, firstClear, textBox } from '../../components/graph/graph-labels.ts'\nimport { textWidth } from '../../components/text/text-measure.ts'\n\n/**\n * The geometry of a system of spheres around one world: concentric circles, innermost first, each\n * world drawn as a dot in the ring between the smallest sphere holding it and the one inside, with its\n * name and true atoms beside it where no other dot or label sits. Pure; no DOM.\n */\n\nexport interface SphereWorld {\n readonly id: string\n readonly name: string\n /** A second, smaller line: the atoms true there. */\n readonly detail: string\n}\n\nexport interface PlacedSphereWorld extends SphereWorld {\n readonly x: number\n readonly y: number\n /** Index of the smallest sphere holding it. */\n readonly ring: number\n readonly label: Placed\n readonly detailAt: { readonly x: number; readonly y: number }\n}\n\nexport interface SphereLayout {\n readonly radii: readonly number[]\n readonly worlds: readonly PlacedSphereWorld[]\n readonly sphereLabels: readonly { readonly x: number; readonly y: number }[]\n readonly viewBox: string\n readonly width: number\n}\n\nconst DOT = 6\nconst NAME = 13\nconst DETAIL = 11\nconst GAP = 58\nconst MARGIN = 12\n\nexport function layoutSpheres(spheres: readonly (readonly string[])[], center: string, worlds: readonly SphereWorld[]): SphereLayout {\n const innerAlone = spheres[0]?.length === 1 && spheres[0][0] === center\n const r0 = innerAlone ? 24 : 52\n // Many spheres (a similarity with many distances) sit closer together.\n const gap = spheres.length > 4 ? Math.max(34, GAP - (spheres.length - 4) * 6) : GAP\n const radii = spheres.map((_, i) => r0 + i * gap)\n const ringOf = (id: string): number => spheres.findIndex((s) => s.includes(id))\n const byId = new Map(worlds.map((w) => [w.id, w]))\n const placed: { w: SphereWorld; x: number; y: number; ring: number }[] = []\n const push = (id: string, r: number, a: number, ring: number): void => {\n const w = byId.get(id)\n if (w !== undefined) placed.push({ w, x: r * Math.cos(a), y: r * Math.sin(a), ring })\n }\n spheres.forEach((s, i) => {\n const fresh = s.filter((id) => ringOf(id) === i)\n if (i === 0) {\n if (fresh.includes(center)) push(center, 0, 0, 0)\n const rest = fresh.filter((id) => id !== center)\n rest.forEach((id, k) => push(id, r0 * 0.6, -Math.PI / 2 + (2 * Math.PI * k) / rest.length, 0))\n return\n }\n const r = ((radii[i - 1] as number) + (radii[i] as number)) / 2\n fresh.forEach((id, k) => push(id, r, -Math.PI / 2 + i * 0.55 + (2 * Math.PI * k) / fresh.length, i))\n })\n const obstacles: Box[] = placed.map((p) => around(p.x, p.y, DOT + 1))\n const out: PlacedSphereWorld[] = placed.map((p) => {\n const width = Math.max(textWidth(p.w.name, NAME), textWidth(p.w.detail, DETAIL))\n const tall = p.w.detail === '' ? NAME : NAME + DETAIL + 3\n const make = (x: number, y: number, anchor: 'start' | 'middle' | 'end'): Placed => ({\n x,\n y,\n anchor,\n box: { ...textBox(x, y, anchor, width, NAME), y1: y + tall - NAME + NAME * 0.25 },\n })\n const label = firstClear(\n [make(p.x + DOT + 4, p.y + 4, 'start'), make(p.x - DOT - 4, p.y + 4, 'end'), make(p.x, p.y - DOT - 6 - (tall - NAME), 'middle'), make(p.x, p.y + DOT + NAME + 2, 'middle')],\n obstacles,\n )\n obstacles.push(label.box)\n return { ...p.w, x: p.x, y: p.y, ring: p.ring, label, detailAt: { x: label.x, y: label.y + DETAIL + 3 } }\n })\n const outer = radii[radii.length - 1] ?? r0\n const sphereLabels = radii.map((r) => ({ x: r * Math.cos(-Math.PI / 4) + 3, y: r * Math.sin(-Math.PI / 4) - 3 }))\n const boxes = [...obstacles, { x0: -outer, y0: -outer, x1: outer, y1: outer }, ...sphereLabels.map((l) => textBox(l.x, l.y, 'start', 22, 12))]\n const x0 = Math.min(...boxes.map((b) => b.x0)) - MARGIN\n const y0 = Math.min(...boxes.map((b) => b.y0)) - MARGIN\n const x1 = Math.max(...boxes.map((b) => b.x1)) + MARGIN\n const y1 = Math.max(...boxes.map((b) => b.y1)) + MARGIN\n const f = (v: number) => Math.round(v * 10) / 10\n return { radii, worlds: out, sphereLabels, viewBox: `${f(x0)} ${f(y0)} ${f(x1 - x0)} ${f(y1 - y0)}`, width: Math.round(x1 - x0) }\n}\n","import type { KeyboardEvent } from 'react'\nimport { sub } from '../../components/text/svg-text.tsx'\nimport type { SphereLayout } from './sphere-graph.ts'\n\n/** A world's part in a counterfactual: an antecedent world, one of the closest, one where the consequent fails. */\nexport type SphereMark = 'antecedent' | 'selected' | 'counter'\n\nexport interface SphereDiagramProps {\n readonly layout: SphereLayout\n readonly label: string\n readonly center: string\n readonly marks?: ReadonlyMap<string, SphereMark>\n /** The sphere drawn strong: the smallest holding an antecedent world. */\n readonly sphere?: number\n readonly sphereName: (i: number) => string\n readonly worldLabel: (id: string) => string\n readonly onSelect?: (id: string) => void\n}\n\n/** Concentric spheres around a world, with the worlds in their rings. */\nexport function SphereDiagram({ layout, label, center, marks, sphere, sphereName, worldLabel, onSelect }: SphereDiagramProps) {\n const key = (id: string) => (e: KeyboardEvent<SVGGElement>) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault()\n onSelect?.(id)\n }\n }\n return (\n <svg className=\"ca-modal-spheres\" viewBox={layout.viewBox} width={layout.width} role=\"group\" aria-label={label}>\n <g aria-hidden=\"true\">\n {[...layout.radii].reverse().map((r, k) => {\n const i = layout.radii.length - 1 - k\n return <circle key={i} r={r} className=\"ca-modal-sphere\" data-sphere={i} data-active={i === sphere ? 'true' : undefined} />\n })}\n {layout.sphereLabels.map((l, i) => (\n <text key={i} x={l.x} y={l.y} className=\"ca-modal-sphere-name\" data-active={i === sphere ? 'true' : undefined}>\n {sphereName(i)}\n </text>\n ))}\n </g>\n {layout.worlds.map((w) => (\n <g\n key={w.id}\n className=\"ca-modal-dot\"\n data-world={w.id}\n data-mark={marks?.get(w.id)}\n data-center={w.id === center ? 'true' : undefined}\n role={onSelect === undefined ? 'img' : 'button'}\n tabIndex={onSelect === undefined ? undefined : 0}\n aria-label={worldLabel(w.id)}\n onClick={onSelect === undefined ? undefined : () => onSelect(w.id)}\n onKeyDown={onSelect === undefined ? undefined : key(w.id)}\n >\n <circle cx={w.x} cy={w.y} r={6} />\n <text x={w.label.x} y={w.label.y} textAnchor={w.label.anchor} className=\"ca-modal-name\">\n {sub(w.name)}\n </text>\n {w.detail !== '' && (\n <text x={w.detailAt.x} y={w.detailAt.y} textAnchor={w.label.anchor} className=\"ca-modal-detail\">\n {w.detail}\n </text>\n )}\n </g>\n ))}\n </svg>\n )\n}\n","import { useMemo, useState } from 'react'\nimport type { Formula } from '../engine/formula.ts'\nimport type { Inference, InferenceAt, TcsPattern } from '../engine/inference.ts'\nimport { checkInferenceAt, tcsInference } from '../engine/inference.ts'\nimport type { ModalModel } from '../engine/model.ts'\nimport { collapseSpheres } from '../engine/model.ts'\nimport type { ModalNotation } from '../engine/print.ts'\nimport { modalText, modelOfDoc, startWorld } from '../data/load.ts'\nimport type { ModalText, SpheresDoc } from '../data/schema.ts'\nimport type { ModalMessages } from '../i18n/messages.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { worldNames } from './doc-graph.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark } from './parts.tsx'\nimport { layoutSpheres } from './sphere-graph.ts'\nimport { sphereWorlds } from './sphere-view-model.ts'\nimport { SphereDiagram } from './SphereDiagram.tsx'\nimport { parseAll, unknownAtomProblem, useModalDoc } from './use-doc.ts'\n\n/** One inference to check: its pattern, the spheres model and the formulas A, B (and C for transitivity and strengthening). */\nexport interface TcsItem {\n readonly pattern: TcsPattern\n readonly model: ModalModelInput\n readonly a: string\n readonly b: string\n readonly c?: string\n /** A heading for the example; default the document's title. */\n readonly title?: ModalText\n}\n\nexport interface TcsCheckProps extends ModalCommonProps {\n readonly items: readonly TcsItem[]\n /** Show the strict-implication column; default true. */\n readonly showStrict?: boolean\n /** Start with the spheres pressed into one; default false. */\n readonly collapsed?: boolean\n}\n\n/**\n * Transitivity, contraposition and strengthening the antecedent, each on its own spheres model:\n * with strict implication the inference holds; with the counterfactual on spheres a counterexample\n * appears at the centre. Pressing the spheres into one makes the counterfactual strict, and the\n * counterexample goes away.\n */\nexport function TcsCheck(props: TcsCheckProps) {\n return (\n <ModalRoot locale={props.locale} name=\"tcs\" caption={props.caption}>\n <TcsBody {...props} />\n </ModalRoot>\n )\n}\n\nfunction TcsBody({ items, showStrict = true, collapsed: initial = false, notation = 'modern' }: TcsCheckProps) {\n const t = useModalMessages()\n const [collapsed, setCollapsed] = useState(initial)\n return (\n <>\n <label className=\"ca-modal-check\">\n <input type=\"checkbox\" checked={collapsed} onChange={(e) => setCollapsed(e.currentTarget.checked)} /> {t.collapse}\n </label>\n <p className=\"ca-small ca-muted\">{t.collapseHint}</p>\n <div className=\"ca-modal-cards\">\n {items.map((item, i) => (\n <TcsCard key={`${item.pattern}-${i}`} item={item} showStrict={showStrict} collapsed={collapsed} notation={notation} />\n ))}\n </div>\n </>\n )\n}\n\nconst KINDS = ['spheres'] as const\n\nfunction TcsCard({ item, showStrict, collapsed, notation }: { readonly item: TcsItem; readonly showStrict: boolean; readonly collapsed: boolean; readonly notation: Exclude<ModalNotation, 'ascii'> }) {\n const t = useModalMessages()\n const loaded = useModalDoc(item.model, KINDS)\n const parsed = useMemo(() => parseAll(item.c === undefined ? [item.a, item.b] : [item.a, item.b, item.c]), [item.a, item.b, item.c])\n const title = modalText(item.title ?? (loaded.ok ? loaded.doc.title : undefined), t.locale)\n const heading = <h3 className=\"ca-h3\">{title === undefined ? t.patternName[item.pattern] : t.exampleTitle(t.patternName[item.pattern], title)}</h3>\n if (!loaded.ok) {\n return (\n <section className=\"ca-modal-card\" data-pattern={item.pattern}>\n {heading}\n <ModalProblems problems={loaded.errors} />\n </section>\n )\n }\n const bad = parsed.find((p) => !p.ok)\n if (bad !== undefined && !bad.ok) {\n return (\n <section className=\"ca-modal-card\" data-pattern={item.pattern}>\n {heading}\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(bad.error, t)}\n </p>\n </section>\n )\n }\n const [a, b, c] = parsed.map((p) => (p.ok ? p.formula : undefined)) as [Formula, Formula, Formula | undefined]\n const missing = unknownAtomProblem([a, b, ...(c === undefined ? [] : [c])], loaded.doc.atoms.map((x) => x.id))\n return (\n <section className=\"ca-modal-card\" data-pattern={item.pattern}>\n {heading}\n {missing !== undefined ? <ModalProblems problems={[missing]} /> : <TcsColumns doc={loaded.doc} pattern={item.pattern} a={a} b={b} c={c} showStrict={showStrict} collapsed={collapsed} notation={notation} t={t} />}\n </section>\n )\n}\n\nfunction TcsColumns(props: {\n readonly doc: SpheresDoc\n readonly pattern: TcsPattern\n readonly a: Formula\n readonly b: Formula\n readonly c: Formula | undefined\n readonly showStrict: boolean\n readonly collapsed: boolean\n readonly notation: Exclude<ModalNotation, 'ascii'>\n readonly t: ModalMessages\n}) {\n const { doc, pattern, a, b, c, showStrict, collapsed, notation, t } = props\n const model = useMemo(() => modelOfDoc(doc), [doc])\n const flat = useMemo(() => collapseSpheres(model), [model])\n const world = startWorld(doc)\n const shown: ModalModel = collapsed ? flat : model\n const layout = useMemo(() => layoutSpheres(shown.spheres?.[world] ?? [], world, sphereWorlds(doc, t.locale)), [shown, world, doc, t.locale])\n const names = worldNames(doc, t.locale)\n const strict = tcsInference(pattern, 'strict', a, b, c)\n const cf = tcsInference(pattern, 'counterfactual', a, b, c)\n return (\n <>\n <SphereDiagram layout={layout} label={t.worldGraph(doc.worlds.length)} center={world} sphereName={t.sphereName} worldLabel={(id) => t.worldState(names.get(id) ?? id, doc.worlds.find((w) => w.id === id)?.true ?? [])} />\n <div className=\"ca-modal-columns\">\n {showStrict && <InferenceColumn heading={t.strictHeading} kind=\"strict\" inference={strict} at={checkInferenceAt(flat, strict, world)} world={names.get(world) ?? world} notation={notation} t={t} />}\n <InferenceColumn heading={t.counterfactualHeading} kind=\"counterfactual\" inference={cf} at={checkInferenceAt(shown, cf, world)} world={names.get(world) ?? world} notation={notation} t={t} />\n </div>\n <AtomLegend atoms={doc.atoms} />\n </>\n )\n}\n\nfunction InferenceColumn(props: {\n readonly heading: string\n readonly kind: 'strict' | 'counterfactual'\n readonly inference: Inference\n readonly at: InferenceAt\n readonly world: string\n readonly notation: Exclude<ModalNotation, 'ascii'>\n readonly t: ModalMessages\n}) {\n const { heading, kind, inference, at, world, notation, t } = props\n const verdict = at.counterexample ? t.inferenceCounterexample(world) : at.premises.every(Boolean) ? t.inferenceHolds(world) : t.inferenceVacuous(world)\n return (\n <div className=\"ca-modal-column\" data-kind={kind} data-counterexample={at.counterexample ? 'true' : 'false'}>\n <h4 className=\"ca-modal-column-head\">{heading}</h4>\n <ol className=\"ca-modal-inference\">\n {inference.premises.map((p, i) => (\n <li key={i}>\n <span className=\"ca-small ca-muted\">{t.premise}</span> <FormulaMath formula={p} notation={notation} /> <TruthMark value={at.premises[i] as boolean} />\n </li>\n ))}\n <li data-conclusion=\"true\">\n <span className=\"ca-small ca-muted\">{t.conclusion}</span> <FormulaMath formula={inference.conclusion} notation={notation} /> <TruthMark value={at.conclusion} />\n </li>\n </ol>\n <p className=\"ca-small\">{verdict}</p>\n </div>\n )\n}\n","import { useMemo, useState } from 'react'\nimport { Segmented } from '../../components/shared/parts.tsx'\nimport { Tex } from '../../components/text/Tex.tsx'\nimport type { ConditionalSemantics } from '../engine/evaluate.ts'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport { formulaLatex } from '../engine/print.ts'\nimport { modelOfDoc, startWorld } from '../data/load.ts'\nimport type { SpheresDoc } from '../data/schema.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { namesOf, worldNames } from './doc-graph.ts'\nimport { valueOrUndefined } from './explain-text.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark, UnknownMark } from './parts.tsx'\nimport { layoutSpheres } from './sphere-graph.ts'\nimport { counterfactualView, sphereWorlds, worldSetLatex } from './sphere-view-model.ts'\nimport type { SphereMark } from './SphereDiagram.tsx'\nimport { SphereDiagram } from './SphereDiagram.tsx'\nimport { parseAll, useModalDoc } from './use-doc.ts'\n\nexport interface SphereViewProps extends ModalCommonProps {\n /** A `spheres` document (JSON text or value). */\n readonly model: ModalModelInput\n /** Formulas to list, replacing the document's; pick an A > B to see its closest antecedent worlds. */\n readonly formulas?: readonly string[]\n /** How `>` is read at first; default `lewis`. */\n readonly semantics?: ConditionalSemantics\n /** Show the Lewis/Stalnaker switch; default true. */\n readonly semanticsSwitch?: boolean\n /** Whose spheres to draw; default the document's centre. */\n readonly world?: string\n}\n\n/**\n * The spheres around a world: pick a counterfactual A > B to see |A|, the smallest sphere holding an\n * A-world, the closest A-worlds f(|A|, w) and the verdict, by Lewis or by Stalnaker.\n */\nexport function SphereView(props: SphereViewProps) {\n return (\n <ModalRoot locale={props.locale} name=\"spheres\" caption={props.caption}>\n <SphereBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['spheres'] as const\n\nfunction SphereBody(props: SphereViewProps) {\n const loaded = useModalDoc(props.model, KINDS)\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n return <SphereLoaded {...props} doc={loaded.doc} />\n}\n\nfunction SphereLoaded(props: SphereViewProps & { readonly doc: SpheresDoc }) {\n const { doc, notation = 'modern', semanticsSwitch = true } = props\n const t = useModalMessages()\n const model = useMemo(() => modelOfDoc(doc), [doc])\n const world = props.world !== undefined && model.spheres?.[props.world] !== undefined ? props.world : startWorld(doc)\n const [semantics, setSemantics] = useState<ConditionalSemantics>(props.semantics ?? 'lewis')\n const formulas = useMemo(() => parseAll(props.formulas ?? doc.formulas ?? []), [props.formulas, doc])\n const [focus, setFocus] = useState(() => Math.max(0, formulas.findIndex((f) => f.ok && f.formula.kind === 'cf')))\n const names = worldNames(doc, t.locale)\n const layout = useMemo(() => layoutSpheres(model.spheres?.[world] ?? [], world, sphereWorlds(doc, t.locale)), [model, world, doc, t.locale])\n const ev = useMemo(() => new ModalEvaluator(model, { semantics }), [model, semantics])\n const focused = formulas[focus]\n const cf = focused?.ok === true && focused.formula.kind === 'cf' ? counterfactualView(model, focused.formula.left, focused.formula.right, world, semantics) : undefined\n let marks: ReadonlyMap<string, SphereMark> | undefined = cf?.marks\n if (cf === undefined && focused?.ok === true) {\n try {\n marks = new Map(ev.truthSet(focused.formula).map((w) => [w, 'antecedent'] as const))\n } catch {\n marks = undefined\n }\n }\n const name = (id: string) => names.get(id) ?? id\n const sphereName = (i: number) => t.sphereName(i)\n return (\n <div className=\"ca-modal-split\">\n <div className=\"ca-modal-figure\">\n <SphereDiagram\n layout={layout}\n label={t.worldGraph(doc.worlds.length)}\n center={world}\n marks={marks}\n sphere={cf?.step.sphere}\n sphereName={sphereName}\n worldLabel={(id) => t.worldState(name(id), doc.worlds.find((w) => w.id === id)?.true ?? [])}\n />\n <ul className=\"ca-modal-legend\" aria-hidden=\"true\">\n <li data-mark=\"antecedent\">{t.antecedentWorlds}</li>\n <li data-mark=\"selected\">{t.closestWorlds}</li>\n </ul>\n </div>\n <div className=\"ca-modal-side\">\n {semanticsSwitch && (\n <Segmented<ConditionalSemantics>\n label={t.semanticsLabel}\n options={[\n { value: 'lewis', label: 'Lewis' },\n { value: 'stalnaker', label: 'Stalnaker' },\n ]}\n value={semantics}\n onChange={setSemantics}\n />\n )}\n <p className=\"ca-modal-at ca-h3\">{t.at(name(world))}</p>\n <ul className=\"ca-modal-formulas\" aria-label={t.formulas}>\n {formulas.map((f, i) => {\n const value = valueOrUndefined(f, ev, world)\n return (\n <li key={`${f.source}-${i}`}>\n <button type=\"button\" className=\"ca-modal-formula\" aria-pressed={i === focus} onClick={() => setFocus(i)}>\n {f.ok ? <FormulaMath formula={f.formula} notation={notation} /> : <code className=\"ca-mono\">{f.source}</code>}\n {value === undefined ? <UnknownMark /> : <TruthMark value={value} />}\n </button>\n </li>\n )\n })}\n </ul>\n {cf !== undefined && focused?.ok === true && focused.formula.kind === 'cf' && (\n <div className=\"ca-modal-explain\" aria-live=\"polite\">\n {cf.step.vacuous ? (\n <p>{t.vacuous}</p>\n ) : (\n <>\n <p>{t.smallestSphere(sphereName(cf.step.sphere as number), namesOf(names, cf.step.selected))}</p>\n <p>\n <Tex\n tex={`f(|${formulaLatex(focused.formula.left, notation)}|, \\\\text{${name(world)}}) = ${worldSetLatex(namesOf(names, cf.step.selected))}`}\n text={`f(|A|, ${name(world)}) = {${namesOf(names, cf.step.selected).join(', ')}}`}\n />\n </p>\n {cf.problem !== undefined ? <p className=\"ca-modal-problem\">{t.notUnique(namesOf(names, cf.step.selected))}</p> : <p>{cf.value === true ? t.cfTrue : t.cfFalse(namesOf(names, cf.step.failures))}</p>}\n </>\n )}\n </div>\n )}\n <AtomLegend atoms={doc.atoms} />\n {focused !== undefined && !focused.ok && (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(focused.error, t)}\n </p>\n )}\n </div>\n </div>\n )\n}\n","import { useId, useMemo, useState } from 'react'\nimport type { ModalProblem } from '../engine/errors.ts'\nimport { modalProblem } from '../engine/errors.ts'\nimport { ModalEvaluator } from '../engine/evaluate.ts'\nimport { kripkeModel } from '../engine/model.ts'\nimport type { Formula } from '../engine/formula.ts'\nimport type { ModalNotation } from '../engine/print.ts'\nimport { formulaText } from '../engine/print.ts'\nimport { distances } from '../engine/similarity.ts'\nimport type { AtomValues } from '../engine/surgery.ts'\nimport { literalsOf, surgery, worldWith } from '../engine/surgery.ts'\nimport { modelOfDoc, similarityOf, structuralEquations } from '../data/load.ts'\nimport type { SpheresDoc } from '../data/schema.ts'\nimport type { ModalMessages } from '../i18n/messages.ts'\nimport { modalErrorMessage, useModalMessages } from '../i18n/messages.ts'\nimport { namesOf, worldNames } from './doc-graph.ts'\nimport type { ModalCommonProps, ModalModelInput } from './parts.tsx'\nimport { AtomLegend, FormulaMath, ModalProblems, ModalRoot, TruthMark } from './parts.tsx'\nimport { layoutSpheres } from './sphere-graph.ts'\nimport { counterfactualView, sphereWorlds } from './sphere-view-model.ts'\nimport { SphereDiagram } from './SphereDiagram.tsx'\nimport { parseAll, unknownAtomProblem, useModalDoc } from './use-doc.ts'\n\nexport interface SurgeryVsSimilarityProps extends ModalCommonProps {\n /** A `spheres` document with `center`, `similarity` and `structural` equations (JSON text or value). */\n readonly model: ModalModelInput\n /** The antecedent, a conjunction of atoms and negated atoms (`press`); default that of the document's first A > B. */\n readonly antecedent?: string\n /** The consequent; default that of the document's first A > B. */\n readonly consequent?: string\n /** Weights to start from, overriding the document's. */\n readonly weights?: Readonly<Record<string, number>>\n}\n\n/**\n * Fine's Nixon example: on the left Lewis's closest antecedent worlds by a weighted similarity the\n * reader can adjust, on the right Pearl's minimal surgery on the boolean structural equations. Move the\n * weights to see when the two verdicts on A > B part.\n */\nexport function SurgeryVsSimilarity(props: SurgeryVsSimilarityProps) {\n return (\n <ModalRoot locale={props.locale} name=\"surgery\" caption={props.caption}>\n <SurgeryBody {...props} />\n </ModalRoot>\n )\n}\n\nconst KINDS = ['spheres'] as const\n\nfunction firstConditional(doc: SpheresDoc): { a?: string; b?: string } {\n for (const p of parseAll(doc.formulas ?? [])) {\n if (p.ok && p.formula.kind === 'cf') return { a: formulaText(p.formula.left, 'ascii'), b: formulaText(p.formula.right, 'ascii') }\n }\n return {}\n}\n\nfunction SurgeryBody(props: SurgeryVsSimilarityProps) {\n const t = useModalMessages()\n const loaded = useModalDoc(props.model, KINDS)\n const doc = loaded.ok ? loaded.doc : undefined\n const sources = useMemo(() => {\n const fallback = doc === undefined ? {} : firstConditional(doc)\n return [props.antecedent ?? fallback.a ?? '', props.consequent ?? fallback.b ?? '']\n }, [doc, props.antecedent, props.consequent])\n const [a, b] = useMemo(() => parseAll(sources), [sources])\n if (!loaded.ok) return <ModalProblems problems={loaded.errors} />\n if (loaded.doc.center === undefined || loaded.doc.similarity === undefined || loaded.doc.structural === undefined) return <ModalProblems problems={[modalProblem('needs-similarity', {})]} />\n for (const f of [a, b]) {\n if (f !== undefined && !f.ok) {\n return (\n <p className=\"ca-modal-problem\" role=\"alert\">\n {modalErrorMessage(f.error, t)}\n </p>\n )\n }\n }\n if (a?.ok !== true || b?.ok !== true) return null\n const atoms = loaded.doc.atoms.map((x) => x.id)\n const intervention = literalsOf(a.formula)\n const problems: ModalProblem[] = []\n const missing = unknownAtomProblem([a.formula, b.formula], atoms)\n if (missing !== undefined) problems.push(missing)\n if (intervention === undefined) problems.push(modalProblem('surgery-antecedent', { formula: formulaText(a.formula, props.notation ?? 'modern') }))\n if (problems.length > 0 || intervention === undefined) return <ModalProblems problems={problems} />\n return <SurgeryLoaded {...props} doc={loaded.doc} center={loaded.doc.center} a={a.formula} b={b.formula} intervention={intervention} />\n}\n\nfunction SurgeryLoaded(props: SurgeryVsSimilarityProps & { readonly doc: SpheresDoc; readonly center: string; readonly a: Formula; readonly b: Formula; readonly intervention: AtomValues }) {\n const { doc, center, a, b, intervention, notation = 'modern' } = props\n const t = useModalMessages()\n const atoms = doc.atoms.map((x) => x.id)\n const [weights, setWeights] = useState<Readonly<Record<string, number>>>(() => Object.fromEntries(atoms.map((x) => [x, props.weights?.[x] ?? doc.similarity?.weights[x] ?? 1])))\n const [costs, setCosts] = useState<readonly number[]>(() => (doc.similarity?.laws ?? []).map((l) => l.cost))\n const docWithCosts = useMemo(\n () => ({ ...doc, similarity: { weights, laws: (doc.similarity?.laws ?? []).map((l, i) => ({ ...l, cost: costs[i] ?? l.cost })) } }),\n [doc, weights, costs],\n )\n const model = useMemo(() => modelOfDoc(docWithCosts), [docWithCosts])\n const names = worldNames(doc, t.locale)\n const name = (id: string) => names.get(id) ?? id\n const layout = useMemo(() => layoutSpheres(model.spheres?.[center] ?? [], center, sphereWorlds(doc, t.locale)), [model, center, doc, t.locale])\n const view = counterfactualView(model, a, b, center, 'lewis')\n const ds = useMemo(() => [...distances(model, center, similarityOf(docWithCosts))].sort((x, y) => x.distance - y.distance), [model, center, docWithCosts])\n const equations = useMemo(() => structuralEquations(doc), [doc])\n const solved = surgery(atoms, equations, doc.worlds.find((w) => w.id === center)?.true ?? [], intervention)\n const solvedWorld = worldWith(doc.worlds, atoms, solved.values)\n // The consequent in the submodel's one solution.\n const surgeryValue = new ModalEvaluator(kripkeModel({ atoms, worlds: [{ id: 'solution', true: atoms.filter((x) => solved.values[x]) }], access: [] })).holds(b, 'solution')\n return (\n <>\n <div className=\"ca-modal-columns\">\n <section className=\"ca-modal-column\" data-kind=\"similarity\">\n <h3 className=\"ca-modal-column-head\">{t.similarityHeading}</h3>\n <SphereDiagram\n layout={layout}\n label={t.worldGraph(doc.worlds.length)}\n center={center}\n marks={view.marks}\n sphere={view.step.sphere}\n sphereName={t.sphereName}\n worldLabel={(id) => t.worldState(name(id), doc.worlds.find((w) => w.id === id)?.true ?? [])}\n />\n <p>\n <FormulaMath formula={{ kind: 'cf', left: a, right: b }} notation={notation} /> <TruthMark value={view.step.value} />\n </p>\n <p className=\"ca-small\">{view.step.vacuous ? t.vacuous : t.closestList(namesOf(names, view.step.selected))}</p>\n <Weights atoms={atoms} weights={weights} costs={costs} doc={doc} notation={notation} onWeight={(x, v) => setWeights((w) => ({ ...w, [x]: v }))} onCost={(i, v) => setCosts((c) => c.map((old, k) => (k === i ? v : old)))} t={t} />\n <table className=\"ca-modal-table ca-small\">\n <thead>\n <tr>\n <th scope=\"col\">{t.world}</th>\n <th scope=\"col\">{t.distance}</th>\n </tr>\n </thead>\n <tbody>\n {ds.map((d) => (\n <tr key={d.world} data-selected={view.step.selected.includes(d.world) ? 'true' : undefined}>\n <th scope=\"row\">{name(d.world)}</th>\n <td className=\"ca-mono\">{d.distance}</td>\n </tr>\n ))}\n </tbody>\n </table>\n <p className=\"ca-small ca-muted\">{t.approxNote}</p>\n </section>\n <section className=\"ca-modal-column\" data-kind=\"surgery\">\n <h3 className=\"ca-modal-column-head\">{t.surgeryHeading}</h3>\n <h4 className=\"ca-small\">{t.equationsHeading}</h4>\n <ul className=\"ca-modal-equations\">\n {Object.entries(equations).map(([atom, f]) => (\n <li key={atom}>\n <span className=\"ca-mono\">{atom}</span> := <FormulaMath formula={f} notation={notation} />\n </li>\n ))}\n </ul>\n <p className=\"ca-small\">{t.intervention(Object.entries(intervention).map(([x, v]) => `${x} = ${v ? 'T' : 'F'}`).join(', '))}</p>\n <h4 className=\"ca-small\">{t.solution}</h4>\n <ul className=\"ca-modal-solution\">\n {atoms.map((x) => (\n <li key={x} data-set={solved.set.includes(x) ? 'true' : undefined}>\n <span className=\"ca-mono\">{x}</span> <TruthMark value={solved.values[x] === true} />\n </li>\n ))}\n </ul>\n <p className=\"ca-small\">{t.solutionWorld(solvedWorld === undefined ? undefined : name(solvedWorld))}</p>\n <p>\n <FormulaMath formula={b} notation={notation} /> <TruthMark value={surgeryValue} />\n </p>\n </section>\n </div>\n <p className=\"ca-modal-agree\" data-agree={surgeryValue === view.step.value ? 'true' : 'false'} aria-live=\"polite\">\n {surgeryValue === view.step.value ? t.agree : t.diverge}\n </p>\n <AtomLegend atoms={doc.atoms} />\n </>\n )\n}\n\nfunction Weights(props: {\n readonly atoms: readonly string[]\n readonly weights: Readonly<Record<string, number>>\n readonly costs: readonly number[]\n readonly doc: SpheresDoc\n readonly notation: Exclude<ModalNotation, 'ascii'>\n readonly onWeight: (atom: string, value: number) => void\n readonly onCost: (law: number, value: number) => void\n readonly t: ModalMessages\n}) {\n const { atoms, weights, costs, doc, notation, onWeight, onCost, t } = props\n const base = useId()\n const laws = parseAll((doc.similarity?.laws ?? []).map((l) => l.formula))\n return (\n <fieldset className=\"ca-modal-weights\">\n <legend>{t.weightsHeading}</legend>\n {atoms.map((x) => (\n <Slider key={x} id={`${base}-w-${x}`} label={t.weightLabel(x)} value={weights[x] ?? 1} onChange={(v) => onWeight(x, v)} />\n ))}\n {laws.map((law, i) => (\n <Slider key={i} id={`${base}-l-${i}`} label={t.lawLabel(law.ok ? formulaText(law.formula, notation) : law.source)} value={costs[i] ?? 1} onChange={(v) => onCost(i, v)} />\n ))}\n </fieldset>\n )\n}\n\nfunction Slider({ id, label, value, onChange }: { readonly id: string; readonly label: string; readonly value: number; readonly onChange: (v: number) => void }) {\n return (\n <div className=\"ca-modal-slider\">\n <label htmlFor={id}>{label}</label>\n <input id={id} type=\"range\" min={0} max={12} step={0.5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