@linloir/limr 0.0.0-stage → 1.0.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 (473) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +123 -0
  3. package/README.md +122 -2
  4. package/benchmarks/results/browser.json +237 -0
  5. package/benchmarks/results/node.json +75 -0
  6. package/benchmarks/results/selection.json +172 -0
  7. package/dist/THIRD_PARTY_LICENSES.txt +117 -0
  8. package/dist/base.css +454 -0
  9. package/dist/chunk-3ILUZKDB.js +3130 -0
  10. package/dist/chunk-3ILUZKDB.js.map +1 -0
  11. package/dist/chunk-6N6TFHEN.js +83 -0
  12. package/dist/chunk-6N6TFHEN.js.map +1 -0
  13. package/dist/chunk-N77VD2YR.js +1238 -0
  14. package/dist/chunk-N77VD2YR.js.map +1 -0
  15. package/dist/chunk-TTISGBST.js +478 -0
  16. package/dist/chunk-TTISGBST.js.map +1 -0
  17. package/dist/chunk-V2OG4Y3F.js +1 -0
  18. package/dist/chunk-V2OG4Y3F.js.map +1 -0
  19. package/dist/core/index.d.ts +57 -0
  20. package/dist/core/index.js +39 -0
  21. package/dist/core/index.js.map +1 -0
  22. package/dist/engine-43u8B4yt.d.ts +172 -0
  23. package/dist/extensions/index.d.ts +130 -0
  24. package/dist/extensions/index.js +50 -0
  25. package/dist/extensions/index.js.map +1 -0
  26. package/dist/fonts/KaTeX_AMS-Regular.ttf +0 -0
  27. package/dist/fonts/KaTeX_AMS-Regular.woff +0 -0
  28. package/dist/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  29. package/dist/fonts/KaTeX_Caligraphic-Bold.ttf +0 -0
  30. package/dist/fonts/KaTeX_Caligraphic-Bold.woff +0 -0
  31. package/dist/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  32. package/dist/fonts/KaTeX_Caligraphic-Regular.ttf +0 -0
  33. package/dist/fonts/KaTeX_Caligraphic-Regular.woff +0 -0
  34. package/dist/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  35. package/dist/fonts/KaTeX_Fraktur-Bold.ttf +0 -0
  36. package/dist/fonts/KaTeX_Fraktur-Bold.woff +0 -0
  37. package/dist/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  38. package/dist/fonts/KaTeX_Fraktur-Regular.ttf +0 -0
  39. package/dist/fonts/KaTeX_Fraktur-Regular.woff +0 -0
  40. package/dist/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  41. package/dist/fonts/KaTeX_Main-Bold.ttf +0 -0
  42. package/dist/fonts/KaTeX_Main-Bold.woff +0 -0
  43. package/dist/fonts/KaTeX_Main-Bold.woff2 +0 -0
  44. package/dist/fonts/KaTeX_Main-BoldItalic.ttf +0 -0
  45. package/dist/fonts/KaTeX_Main-BoldItalic.woff +0 -0
  46. package/dist/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  47. package/dist/fonts/KaTeX_Main-Italic.ttf +0 -0
  48. package/dist/fonts/KaTeX_Main-Italic.woff +0 -0
  49. package/dist/fonts/KaTeX_Main-Italic.woff2 +0 -0
  50. package/dist/fonts/KaTeX_Main-Regular.ttf +0 -0
  51. package/dist/fonts/KaTeX_Main-Regular.woff +0 -0
  52. package/dist/fonts/KaTeX_Main-Regular.woff2 +0 -0
  53. package/dist/fonts/KaTeX_Math-BoldItalic.ttf +0 -0
  54. package/dist/fonts/KaTeX_Math-BoldItalic.woff +0 -0
  55. package/dist/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  56. package/dist/fonts/KaTeX_Math-Italic.ttf +0 -0
  57. package/dist/fonts/KaTeX_Math-Italic.woff +0 -0
  58. package/dist/fonts/KaTeX_Math-Italic.woff2 +0 -0
  59. package/dist/fonts/KaTeX_SansSerif-Bold.ttf +0 -0
  60. package/dist/fonts/KaTeX_SansSerif-Bold.woff +0 -0
  61. package/dist/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  62. package/dist/fonts/KaTeX_SansSerif-Italic.ttf +0 -0
  63. package/dist/fonts/KaTeX_SansSerif-Italic.woff +0 -0
  64. package/dist/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  65. package/dist/fonts/KaTeX_SansSerif-Regular.ttf +0 -0
  66. package/dist/fonts/KaTeX_SansSerif-Regular.woff +0 -0
  67. package/dist/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  68. package/dist/fonts/KaTeX_Script-Regular.ttf +0 -0
  69. package/dist/fonts/KaTeX_Script-Regular.woff +0 -0
  70. package/dist/fonts/KaTeX_Script-Regular.woff2 +0 -0
  71. package/dist/fonts/KaTeX_Size1-Regular.ttf +0 -0
  72. package/dist/fonts/KaTeX_Size1-Regular.woff +0 -0
  73. package/dist/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  74. package/dist/fonts/KaTeX_Size2-Regular.ttf +0 -0
  75. package/dist/fonts/KaTeX_Size2-Regular.woff +0 -0
  76. package/dist/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  77. package/dist/fonts/KaTeX_Size3-Regular.ttf +0 -0
  78. package/dist/fonts/KaTeX_Size3-Regular.woff +0 -0
  79. package/dist/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  80. package/dist/fonts/KaTeX_Size4-Regular.ttf +0 -0
  81. package/dist/fonts/KaTeX_Size4-Regular.woff +0 -0
  82. package/dist/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  83. package/dist/fonts/KaTeX_Typewriter-Regular.ttf +0 -0
  84. package/dist/fonts/KaTeX_Typewriter-Regular.woff +0 -0
  85. package/dist/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  86. package/dist/fonts/LICENSE.txt +93 -0
  87. package/dist/fonts/manifest.json +2204 -0
  88. package/dist/fonts/maple-7.9-bold-005-5530d8c1d6.woff2 +0 -0
  89. package/dist/fonts/maple-7.9-bold-00f-1179d800a7.woff2 +0 -0
  90. package/dist/fonts/maple-7.9-bold-010-9974a942b1.woff2 +0 -0
  91. package/dist/fonts/maple-7.9-bold-011-9b9230baf2.woff2 +0 -0
  92. package/dist/fonts/maple-7.9-bold-012-c2545292b1.woff2 +0 -0
  93. package/dist/fonts/maple-7.9-bold-013-877b19fe05.woff2 +0 -0
  94. package/dist/fonts/maple-7.9-bold-014-6acf4a4e92.woff2 +0 -0
  95. package/dist/fonts/maple-7.9-bold-015-c889146da3.woff2 +0 -0
  96. package/dist/fonts/maple-7.9-bold-018-419ad5f31f.woff2 +0 -0
  97. package/dist/fonts/maple-7.9-bold-027-dd414483da.woff2 +0 -0
  98. package/dist/fonts/maple-7.9-bold-028-263744fbc7.woff2 +0 -0
  99. package/dist/fonts/maple-7.9-bold-029-ae3a163d8b.woff2 +0 -0
  100. package/dist/fonts/maple-7.9-bold-02a-515f0a82c2.woff2 +0 -0
  101. package/dist/fonts/maple-7.9-bold-02b-0823c5133d.woff2 +0 -0
  102. package/dist/fonts/maple-7.9-bold-02c-296fd5db38.woff2 +0 -0
  103. package/dist/fonts/maple-7.9-bold-02d-0bb4734363.woff2 +0 -0
  104. package/dist/fonts/maple-7.9-bold-02e-25415fed50.woff2 +0 -0
  105. package/dist/fonts/maple-7.9-bold-02f-19ed79a84e.woff2 +0 -0
  106. package/dist/fonts/maple-7.9-bold-030-21962a0327.woff2 +0 -0
  107. package/dist/fonts/maple-7.9-bold-031-d216fc0d68.woff2 +0 -0
  108. package/dist/fonts/maple-7.9-bold-032-d90ba34901.woff2 +0 -0
  109. package/dist/fonts/maple-7.9-bold-033-55ea37ea00.woff2 +0 -0
  110. package/dist/fonts/maple-7.9-bold-034-bc8649f808.woff2 +0 -0
  111. package/dist/fonts/maple-7.9-bold-035-03604fe40b.woff2 +0 -0
  112. package/dist/fonts/maple-7.9-bold-036-44fc7f77b2.woff2 +0 -0
  113. package/dist/fonts/maple-7.9-bold-037-8a1440f155.woff2 +0 -0
  114. package/dist/fonts/maple-7.9-bold-038-c65a618d5c.woff2 +0 -0
  115. package/dist/fonts/maple-7.9-bold-039-be05db966d.woff2 +0 -0
  116. package/dist/fonts/maple-7.9-bold-03a-ca3a10002d.woff2 +0 -0
  117. package/dist/fonts/maple-7.9-bold-03b-067b32e10b.woff2 +0 -0
  118. package/dist/fonts/maple-7.9-bold-03c-4da4f84530.woff2 +0 -0
  119. package/dist/fonts/maple-7.9-bold-03d-f0fe6a68c8.woff2 +0 -0
  120. package/dist/fonts/maple-7.9-bold-03e-0e97f89433.woff2 +0 -0
  121. package/dist/fonts/maple-7.9-bold-03f-3289a5e3bc.woff2 +0 -0
  122. package/dist/fonts/maple-7.9-bold-040-232dcd0d7b.woff2 +0 -0
  123. package/dist/fonts/maple-7.9-bold-041-e25e9a9c41.woff2 +0 -0
  124. package/dist/fonts/maple-7.9-bold-042-d64a2b1824.woff2 +0 -0
  125. package/dist/fonts/maple-7.9-bold-043-2d01cf5e52.woff2 +0 -0
  126. package/dist/fonts/maple-7.9-bold-044-0ab808b5f1.woff2 +0 -0
  127. package/dist/fonts/maple-7.9-bold-045-e41dc814b4.woff2 +0 -0
  128. package/dist/fonts/maple-7.9-bold-046-d5fe26344d.woff2 +0 -0
  129. package/dist/fonts/maple-7.9-bold-047-f322ded671.woff2 +0 -0
  130. package/dist/fonts/maple-7.9-bold-048-0cdcf7257f.woff2 +0 -0
  131. package/dist/fonts/maple-7.9-bold-049-aa280ca08a.woff2 +0 -0
  132. package/dist/fonts/maple-7.9-bold-04a-f51ad4d92c.woff2 +0 -0
  133. package/dist/fonts/maple-7.9-bold-04b-4e8c6fa3ee.woff2 +0 -0
  134. package/dist/fonts/maple-7.9-bold-04c-9bfdf4d743.woff2 +0 -0
  135. package/dist/fonts/maple-7.9-bold-04d-83ac1f5bb3.woff2 +0 -0
  136. package/dist/fonts/maple-7.9-bold-04e-bcec89804a.woff2 +0 -0
  137. package/dist/fonts/maple-7.9-bold-04f-d31e83b6ce.woff2 +0 -0
  138. package/dist/fonts/maple-7.9-bold-070-8a3b0fdf98.woff2 +0 -0
  139. package/dist/fonts/maple-7.9-bold-071-5bee0a62c4.woff2 +0 -0
  140. package/dist/fonts/maple-7.9-bold-072-97d891eee4.woff2 +0 -0
  141. package/dist/fonts/maple-7.9-bold-073-4d4c36aca0.woff2 +0 -0
  142. package/dist/fonts/maple-7.9-bold-074-6d3cc01e90.woff2 +0 -0
  143. package/dist/fonts/maple-7.9-bold-075-eab42ad657.woff2 +0 -0
  144. package/dist/fonts/maple-7.9-bold-076-2b1f5c4a42.woff2 +0 -0
  145. package/dist/fonts/maple-7.9-bold-077-1db0d50873.woff2 +0 -0
  146. package/dist/fonts/maple-7.9-bold-078-bc6994a28f.woff2 +0 -0
  147. package/dist/fonts/maple-7.9-bold-079-ad6c1757ce.woff2 +0 -0
  148. package/dist/fonts/maple-7.9-bold-07a-d08ed2b87d.woff2 +0 -0
  149. package/dist/fonts/maple-7.9-bold-07f-2f4af46cc6.woff2 +0 -0
  150. package/dist/fonts/maple-7.9-bold-0fc-42ed90884c.woff2 +0 -0
  151. package/dist/fonts/maple-7.9-bold-780-261fac1b24.woff2 +0 -0
  152. package/dist/fonts/maple-7.9-bold-781-377319a91b.woff2 +0 -0
  153. package/dist/fonts/maple-7.9-bold-782-3106f0be62.woff2 +0 -0
  154. package/dist/fonts/maple-7.9-bold-783-74fbfa8648.woff2 +0 -0
  155. package/dist/fonts/maple-7.9-bold-784-8570270664.woff2 +0 -0
  156. package/dist/fonts/maple-7.9-bold-785-cee8de1ded.woff2 +0 -0
  157. package/dist/fonts/maple-7.9-bold-786-5ab5ff7149.woff2 +0 -0
  158. package/dist/fonts/maple-7.9-bold-787-844b4c4373.woff2 +0 -0
  159. package/dist/fonts/maple-7.9-bold-788-01731198ab.woff2 +0 -0
  160. package/dist/fonts/maple-7.9-bold-789-f4c75fa806.woff2 +0 -0
  161. package/dist/fonts/maple-7.9-bold-78a-4370321ec6.woff2 +0 -0
  162. package/dist/fonts/maple-7.9-bold-78b-5cd412b56f.woff2 +0 -0
  163. package/dist/fonts/maple-7.9-bold-78c-f88e331085.woff2 +0 -0
  164. package/dist/fonts/maple-7.9-bold-78d-1b9b77f6e8.woff2 +0 -0
  165. package/dist/fonts/maple-7.9-bold-latin-3b4b2831f3.woff2 +0 -0
  166. package/dist/fonts/maple-7.9-bolditalic-005-d59fef8639.woff2 +0 -0
  167. package/dist/fonts/maple-7.9-bolditalic-00f-1bbda7af69.woff2 +0 -0
  168. package/dist/fonts/maple-7.9-bolditalic-010-5cdd4b46a7.woff2 +0 -0
  169. package/dist/fonts/maple-7.9-bolditalic-011-0d1f1ae687.woff2 +0 -0
  170. package/dist/fonts/maple-7.9-bolditalic-012-4ceb000b2e.woff2 +0 -0
  171. package/dist/fonts/maple-7.9-bolditalic-013-ad0a4f4313.woff2 +0 -0
  172. package/dist/fonts/maple-7.9-bolditalic-014-94d54b71b3.woff2 +0 -0
  173. package/dist/fonts/maple-7.9-bolditalic-015-7aede280da.woff2 +0 -0
  174. package/dist/fonts/maple-7.9-bolditalic-018-f21221b1c2.woff2 +0 -0
  175. package/dist/fonts/maple-7.9-bolditalic-027-d23d0e80a4.woff2 +0 -0
  176. package/dist/fonts/maple-7.9-bolditalic-028-23bd6f24df.woff2 +0 -0
  177. package/dist/fonts/maple-7.9-bolditalic-029-c481c0ad50.woff2 +0 -0
  178. package/dist/fonts/maple-7.9-bolditalic-02a-1c134be68e.woff2 +0 -0
  179. package/dist/fonts/maple-7.9-bolditalic-02b-3feb29ecfd.woff2 +0 -0
  180. package/dist/fonts/maple-7.9-bolditalic-02c-de8cc5a063.woff2 +0 -0
  181. package/dist/fonts/maple-7.9-bolditalic-02d-ea25c21fad.woff2 +0 -0
  182. package/dist/fonts/maple-7.9-bolditalic-02e-e68d6bd335.woff2 +0 -0
  183. package/dist/fonts/maple-7.9-bolditalic-02f-c88d1e92dc.woff2 +0 -0
  184. package/dist/fonts/maple-7.9-bolditalic-030-f26fefe87e.woff2 +0 -0
  185. package/dist/fonts/maple-7.9-bolditalic-031-f2aa1b8e22.woff2 +0 -0
  186. package/dist/fonts/maple-7.9-bolditalic-032-c4fafc4aa6.woff2 +0 -0
  187. package/dist/fonts/maple-7.9-bolditalic-033-288a1639ca.woff2 +0 -0
  188. package/dist/fonts/maple-7.9-bolditalic-034-7c982125bc.woff2 +0 -0
  189. package/dist/fonts/maple-7.9-bolditalic-035-fd1575dea2.woff2 +0 -0
  190. package/dist/fonts/maple-7.9-bolditalic-036-f6bf406353.woff2 +0 -0
  191. package/dist/fonts/maple-7.9-bolditalic-037-8ac1466916.woff2 +0 -0
  192. package/dist/fonts/maple-7.9-bolditalic-038-e9f7fed6a6.woff2 +0 -0
  193. package/dist/fonts/maple-7.9-bolditalic-039-6f90d42310.woff2 +0 -0
  194. package/dist/fonts/maple-7.9-bolditalic-03a-30c9409a7e.woff2 +0 -0
  195. package/dist/fonts/maple-7.9-bolditalic-03b-4f1741e9e9.woff2 +0 -0
  196. package/dist/fonts/maple-7.9-bolditalic-03c-6551c74e78.woff2 +0 -0
  197. package/dist/fonts/maple-7.9-bolditalic-03d-c8e2b07106.woff2 +0 -0
  198. package/dist/fonts/maple-7.9-bolditalic-03e-c3e98613d4.woff2 +0 -0
  199. package/dist/fonts/maple-7.9-bolditalic-03f-f1c580bad4.woff2 +0 -0
  200. package/dist/fonts/maple-7.9-bolditalic-040-32e8260076.woff2 +0 -0
  201. package/dist/fonts/maple-7.9-bolditalic-041-39805a0ed7.woff2 +0 -0
  202. package/dist/fonts/maple-7.9-bolditalic-042-13b4d84cd3.woff2 +0 -0
  203. package/dist/fonts/maple-7.9-bolditalic-043-d85780d0bd.woff2 +0 -0
  204. package/dist/fonts/maple-7.9-bolditalic-044-1b5eb624d7.woff2 +0 -0
  205. package/dist/fonts/maple-7.9-bolditalic-045-ad0b4f8762.woff2 +0 -0
  206. package/dist/fonts/maple-7.9-bolditalic-046-9966021b3a.woff2 +0 -0
  207. package/dist/fonts/maple-7.9-bolditalic-047-100d4f6f4e.woff2 +0 -0
  208. package/dist/fonts/maple-7.9-bolditalic-048-a0a1e8b29c.woff2 +0 -0
  209. package/dist/fonts/maple-7.9-bolditalic-049-0806f9b3cc.woff2 +0 -0
  210. package/dist/fonts/maple-7.9-bolditalic-04a-28fdef78b3.woff2 +0 -0
  211. package/dist/fonts/maple-7.9-bolditalic-04b-6e93ef0086.woff2 +0 -0
  212. package/dist/fonts/maple-7.9-bolditalic-04c-50b8da6282.woff2 +0 -0
  213. package/dist/fonts/maple-7.9-bolditalic-04d-f93277723d.woff2 +0 -0
  214. package/dist/fonts/maple-7.9-bolditalic-04e-72e2644690.woff2 +0 -0
  215. package/dist/fonts/maple-7.9-bolditalic-04f-4f234f1802.woff2 +0 -0
  216. package/dist/fonts/maple-7.9-bolditalic-070-a3658a8a23.woff2 +0 -0
  217. package/dist/fonts/maple-7.9-bolditalic-071-4987e49732.woff2 +0 -0
  218. package/dist/fonts/maple-7.9-bolditalic-072-e587fa72cd.woff2 +0 -0
  219. package/dist/fonts/maple-7.9-bolditalic-073-2aca01fdf6.woff2 +0 -0
  220. package/dist/fonts/maple-7.9-bolditalic-074-ae89f99a60.woff2 +0 -0
  221. package/dist/fonts/maple-7.9-bolditalic-075-5a77191665.woff2 +0 -0
  222. package/dist/fonts/maple-7.9-bolditalic-076-4c54a87277.woff2 +0 -0
  223. package/dist/fonts/maple-7.9-bolditalic-077-e47dce25ee.woff2 +0 -0
  224. package/dist/fonts/maple-7.9-bolditalic-078-b0b720dab6.woff2 +0 -0
  225. package/dist/fonts/maple-7.9-bolditalic-079-316ee96f6a.woff2 +0 -0
  226. package/dist/fonts/maple-7.9-bolditalic-07a-b10ccb8107.woff2 +0 -0
  227. package/dist/fonts/maple-7.9-bolditalic-07d-5667cb3be1.woff2 +0 -0
  228. package/dist/fonts/maple-7.9-bolditalic-07f-2ac6735ff8.woff2 +0 -0
  229. package/dist/fonts/maple-7.9-bolditalic-0fc-52171ca01e.woff2 +0 -0
  230. package/dist/fonts/maple-7.9-bolditalic-780-3c090c5f89.woff2 +0 -0
  231. package/dist/fonts/maple-7.9-bolditalic-781-ca4077b4fa.woff2 +0 -0
  232. package/dist/fonts/maple-7.9-bolditalic-782-42c3d52206.woff2 +0 -0
  233. package/dist/fonts/maple-7.9-bolditalic-783-d72840dd37.woff2 +0 -0
  234. package/dist/fonts/maple-7.9-bolditalic-784-b9ca097e50.woff2 +0 -0
  235. package/dist/fonts/maple-7.9-bolditalic-785-b81dec6af9.woff2 +0 -0
  236. package/dist/fonts/maple-7.9-bolditalic-786-76c266f6f5.woff2 +0 -0
  237. package/dist/fonts/maple-7.9-bolditalic-787-403bd73766.woff2 +0 -0
  238. package/dist/fonts/maple-7.9-bolditalic-788-71a4b8c2c5.woff2 +0 -0
  239. package/dist/fonts/maple-7.9-bolditalic-789-94527f3fa4.woff2 +0 -0
  240. package/dist/fonts/maple-7.9-bolditalic-78a-81918568b8.woff2 +0 -0
  241. package/dist/fonts/maple-7.9-bolditalic-78b-d0302b4bfe.woff2 +0 -0
  242. package/dist/fonts/maple-7.9-bolditalic-78c-e864792049.woff2 +0 -0
  243. package/dist/fonts/maple-7.9-bolditalic-78d-105ff69bf4.woff2 +0 -0
  244. package/dist/fonts/maple-7.9-bolditalic-latin-96412d165b.woff2 +0 -0
  245. package/dist/fonts/maple-7.9-italic-005-23b09473f8.woff2 +0 -0
  246. package/dist/fonts/maple-7.9-italic-00f-e9bf4dd93c.woff2 +0 -0
  247. package/dist/fonts/maple-7.9-italic-010-22933d6d77.woff2 +0 -0
  248. package/dist/fonts/maple-7.9-italic-011-71b0157ddc.woff2 +0 -0
  249. package/dist/fonts/maple-7.9-italic-012-b751ab3752.woff2 +0 -0
  250. package/dist/fonts/maple-7.9-italic-013-530b1d3f8b.woff2 +0 -0
  251. package/dist/fonts/maple-7.9-italic-014-0e842f6749.woff2 +0 -0
  252. package/dist/fonts/maple-7.9-italic-015-642211b03a.woff2 +0 -0
  253. package/dist/fonts/maple-7.9-italic-018-0c5b0001c6.woff2 +0 -0
  254. package/dist/fonts/maple-7.9-italic-027-9a09afbbb1.woff2 +0 -0
  255. package/dist/fonts/maple-7.9-italic-028-93fea67326.woff2 +0 -0
  256. package/dist/fonts/maple-7.9-italic-029-7d7627d4cc.woff2 +0 -0
  257. package/dist/fonts/maple-7.9-italic-02a-88e76d051b.woff2 +0 -0
  258. package/dist/fonts/maple-7.9-italic-02b-7d9219748b.woff2 +0 -0
  259. package/dist/fonts/maple-7.9-italic-02c-049df19d84.woff2 +0 -0
  260. package/dist/fonts/maple-7.9-italic-02d-663fc73c6e.woff2 +0 -0
  261. package/dist/fonts/maple-7.9-italic-02e-a98ed33998.woff2 +0 -0
  262. package/dist/fonts/maple-7.9-italic-02f-8ef9d93d09.woff2 +0 -0
  263. package/dist/fonts/maple-7.9-italic-030-74885d994d.woff2 +0 -0
  264. package/dist/fonts/maple-7.9-italic-031-4cf66c5d65.woff2 +0 -0
  265. package/dist/fonts/maple-7.9-italic-032-a608b7aed4.woff2 +0 -0
  266. package/dist/fonts/maple-7.9-italic-033-2978f66e55.woff2 +0 -0
  267. package/dist/fonts/maple-7.9-italic-034-38f7a0bf87.woff2 +0 -0
  268. package/dist/fonts/maple-7.9-italic-035-5cc45cd3b7.woff2 +0 -0
  269. package/dist/fonts/maple-7.9-italic-036-ca92d327e5.woff2 +0 -0
  270. package/dist/fonts/maple-7.9-italic-037-f887681c7d.woff2 +0 -0
  271. package/dist/fonts/maple-7.9-italic-038-06150b88f8.woff2 +0 -0
  272. package/dist/fonts/maple-7.9-italic-039-761da333b7.woff2 +0 -0
  273. package/dist/fonts/maple-7.9-italic-03a-1408ddaf2c.woff2 +0 -0
  274. package/dist/fonts/maple-7.9-italic-03b-1542b3b67c.woff2 +0 -0
  275. package/dist/fonts/maple-7.9-italic-03c-479f2f5011.woff2 +0 -0
  276. package/dist/fonts/maple-7.9-italic-03d-0f10590b11.woff2 +0 -0
  277. package/dist/fonts/maple-7.9-italic-03e-8b93e0ee0e.woff2 +0 -0
  278. package/dist/fonts/maple-7.9-italic-03f-2bd8815e3e.woff2 +0 -0
  279. package/dist/fonts/maple-7.9-italic-040-b85023679a.woff2 +0 -0
  280. package/dist/fonts/maple-7.9-italic-041-eb881b7b92.woff2 +0 -0
  281. package/dist/fonts/maple-7.9-italic-042-01490a139e.woff2 +0 -0
  282. package/dist/fonts/maple-7.9-italic-043-ffb21b6c4c.woff2 +0 -0
  283. package/dist/fonts/maple-7.9-italic-044-05cd1a1b14.woff2 +0 -0
  284. package/dist/fonts/maple-7.9-italic-045-1270935363.woff2 +0 -0
  285. package/dist/fonts/maple-7.9-italic-046-857077eab1.woff2 +0 -0
  286. package/dist/fonts/maple-7.9-italic-047-ca57774cc3.woff2 +0 -0
  287. package/dist/fonts/maple-7.9-italic-048-20969d6307.woff2 +0 -0
  288. package/dist/fonts/maple-7.9-italic-049-4066aa1a18.woff2 +0 -0
  289. package/dist/fonts/maple-7.9-italic-04a-1ed360d580.woff2 +0 -0
  290. package/dist/fonts/maple-7.9-italic-04b-2eba62d76b.woff2 +0 -0
  291. package/dist/fonts/maple-7.9-italic-04c-2f4effc460.woff2 +0 -0
  292. package/dist/fonts/maple-7.9-italic-04d-d858c0a9c1.woff2 +0 -0
  293. package/dist/fonts/maple-7.9-italic-04e-a19eb0289f.woff2 +0 -0
  294. package/dist/fonts/maple-7.9-italic-04f-8addde15f2.woff2 +0 -0
  295. package/dist/fonts/maple-7.9-italic-070-f0bd641f1c.woff2 +0 -0
  296. package/dist/fonts/maple-7.9-italic-071-e6ac564431.woff2 +0 -0
  297. package/dist/fonts/maple-7.9-italic-072-e6fea65bca.woff2 +0 -0
  298. package/dist/fonts/maple-7.9-italic-073-71621c00dc.woff2 +0 -0
  299. package/dist/fonts/maple-7.9-italic-074-4bd488962a.woff2 +0 -0
  300. package/dist/fonts/maple-7.9-italic-075-2838d95bd6.woff2 +0 -0
  301. package/dist/fonts/maple-7.9-italic-076-94e02ecc03.woff2 +0 -0
  302. package/dist/fonts/maple-7.9-italic-077-32c536ab6b.woff2 +0 -0
  303. package/dist/fonts/maple-7.9-italic-078-18256447bd.woff2 +0 -0
  304. package/dist/fonts/maple-7.9-italic-079-7a735e61cf.woff2 +0 -0
  305. package/dist/fonts/maple-7.9-italic-07a-2b57a6a905.woff2 +0 -0
  306. package/dist/fonts/maple-7.9-italic-07d-8ba1bbfb50.woff2 +0 -0
  307. package/dist/fonts/maple-7.9-italic-07f-0240d80c69.woff2 +0 -0
  308. package/dist/fonts/maple-7.9-italic-0fc-e5b20a692e.woff2 +0 -0
  309. package/dist/fonts/maple-7.9-italic-780-093cc90a9b.woff2 +0 -0
  310. package/dist/fonts/maple-7.9-italic-781-f6ec357f6d.woff2 +0 -0
  311. package/dist/fonts/maple-7.9-italic-782-5ca2ef4ddd.woff2 +0 -0
  312. package/dist/fonts/maple-7.9-italic-783-7450baabee.woff2 +0 -0
  313. package/dist/fonts/maple-7.9-italic-784-14a93cc4bd.woff2 +0 -0
  314. package/dist/fonts/maple-7.9-italic-785-d62fb8b4d7.woff2 +0 -0
  315. package/dist/fonts/maple-7.9-italic-786-1d2959dc83.woff2 +0 -0
  316. package/dist/fonts/maple-7.9-italic-787-70ae947136.woff2 +0 -0
  317. package/dist/fonts/maple-7.9-italic-788-cf1f156ebf.woff2 +0 -0
  318. package/dist/fonts/maple-7.9-italic-789-f0b79f9680.woff2 +0 -0
  319. package/dist/fonts/maple-7.9-italic-78a-5a53fd7870.woff2 +0 -0
  320. package/dist/fonts/maple-7.9-italic-78b-40be093bfd.woff2 +0 -0
  321. package/dist/fonts/maple-7.9-italic-78c-3b11646f8e.woff2 +0 -0
  322. package/dist/fonts/maple-7.9-italic-78d-b13ed8c48b.woff2 +0 -0
  323. package/dist/fonts/maple-7.9-italic-latin-befeb2b610.woff2 +0 -0
  324. package/dist/fonts/maple-7.9-regular-005-90bff107ac.woff2 +0 -0
  325. package/dist/fonts/maple-7.9-regular-00f-001e503e53.woff2 +0 -0
  326. package/dist/fonts/maple-7.9-regular-010-374da1ebb4.woff2 +0 -0
  327. package/dist/fonts/maple-7.9-regular-011-8f91fcc9e7.woff2 +0 -0
  328. package/dist/fonts/maple-7.9-regular-012-e4ec3016ef.woff2 +0 -0
  329. package/dist/fonts/maple-7.9-regular-013-e779e13a12.woff2 +0 -0
  330. package/dist/fonts/maple-7.9-regular-014-6b833ad501.woff2 +0 -0
  331. package/dist/fonts/maple-7.9-regular-015-4e058c4c42.woff2 +0 -0
  332. package/dist/fonts/maple-7.9-regular-018-6f776bc19b.woff2 +0 -0
  333. package/dist/fonts/maple-7.9-regular-027-92c0be3439.woff2 +0 -0
  334. package/dist/fonts/maple-7.9-regular-028-154c8c3039.woff2 +0 -0
  335. package/dist/fonts/maple-7.9-regular-029-9d88470aca.woff2 +0 -0
  336. package/dist/fonts/maple-7.9-regular-02a-7a94cb26f2.woff2 +0 -0
  337. package/dist/fonts/maple-7.9-regular-02b-1725b841c2.woff2 +0 -0
  338. package/dist/fonts/maple-7.9-regular-02c-e080c435d6.woff2 +0 -0
  339. package/dist/fonts/maple-7.9-regular-02d-a6461c4708.woff2 +0 -0
  340. package/dist/fonts/maple-7.9-regular-02e-2e55d9b957.woff2 +0 -0
  341. package/dist/fonts/maple-7.9-regular-02f-858a76fa1f.woff2 +0 -0
  342. package/dist/fonts/maple-7.9-regular-030-bbbe80f8ad.woff2 +0 -0
  343. package/dist/fonts/maple-7.9-regular-031-cafc1258ad.woff2 +0 -0
  344. package/dist/fonts/maple-7.9-regular-032-0ca83ecceb.woff2 +0 -0
  345. package/dist/fonts/maple-7.9-regular-033-6cb995f2e7.woff2 +0 -0
  346. package/dist/fonts/maple-7.9-regular-034-5877222be6.woff2 +0 -0
  347. package/dist/fonts/maple-7.9-regular-035-988d8f2d26.woff2 +0 -0
  348. package/dist/fonts/maple-7.9-regular-036-e91853e3ca.woff2 +0 -0
  349. package/dist/fonts/maple-7.9-regular-037-3eed60f359.woff2 +0 -0
  350. package/dist/fonts/maple-7.9-regular-038-5681f42a4a.woff2 +0 -0
  351. package/dist/fonts/maple-7.9-regular-039-07036fe444.woff2 +0 -0
  352. package/dist/fonts/maple-7.9-regular-03a-5495eead93.woff2 +0 -0
  353. package/dist/fonts/maple-7.9-regular-03b-d07b1d6c1e.woff2 +0 -0
  354. package/dist/fonts/maple-7.9-regular-03c-6291400ee0.woff2 +0 -0
  355. package/dist/fonts/maple-7.9-regular-03d-3787a51772.woff2 +0 -0
  356. package/dist/fonts/maple-7.9-regular-03e-ce4d945844.woff2 +0 -0
  357. package/dist/fonts/maple-7.9-regular-03f-95e98b329c.woff2 +0 -0
  358. package/dist/fonts/maple-7.9-regular-040-693b769fe8.woff2 +0 -0
  359. package/dist/fonts/maple-7.9-regular-041-7b436d2c09.woff2 +0 -0
  360. package/dist/fonts/maple-7.9-regular-042-9ad884cd73.woff2 +0 -0
  361. package/dist/fonts/maple-7.9-regular-043-372231e8e2.woff2 +0 -0
  362. package/dist/fonts/maple-7.9-regular-044-9922b540b1.woff2 +0 -0
  363. package/dist/fonts/maple-7.9-regular-045-8a88a91c22.woff2 +0 -0
  364. package/dist/fonts/maple-7.9-regular-046-82859ede10.woff2 +0 -0
  365. package/dist/fonts/maple-7.9-regular-047-6532babd62.woff2 +0 -0
  366. package/dist/fonts/maple-7.9-regular-048-abfdc5d7ce.woff2 +0 -0
  367. package/dist/fonts/maple-7.9-regular-049-adb7fa9ed3.woff2 +0 -0
  368. package/dist/fonts/maple-7.9-regular-04a-f3f794b1cb.woff2 +0 -0
  369. package/dist/fonts/maple-7.9-regular-04b-715211b8dd.woff2 +0 -0
  370. package/dist/fonts/maple-7.9-regular-04c-c6f978d10d.woff2 +0 -0
  371. package/dist/fonts/maple-7.9-regular-04d-61019a1c8f.woff2 +0 -0
  372. package/dist/fonts/maple-7.9-regular-04e-806d6efe85.woff2 +0 -0
  373. package/dist/fonts/maple-7.9-regular-04f-99d19aa8db.woff2 +0 -0
  374. package/dist/fonts/maple-7.9-regular-070-e94ba9445d.woff2 +0 -0
  375. package/dist/fonts/maple-7.9-regular-071-057314b533.woff2 +0 -0
  376. package/dist/fonts/maple-7.9-regular-072-a7699beb84.woff2 +0 -0
  377. package/dist/fonts/maple-7.9-regular-073-ebe1bd9ef4.woff2 +0 -0
  378. package/dist/fonts/maple-7.9-regular-074-722db38100.woff2 +0 -0
  379. package/dist/fonts/maple-7.9-regular-075-150ff7187b.woff2 +0 -0
  380. package/dist/fonts/maple-7.9-regular-076-c14595e715.woff2 +0 -0
  381. package/dist/fonts/maple-7.9-regular-077-6c88302a32.woff2 +0 -0
  382. package/dist/fonts/maple-7.9-regular-078-549b294c78.woff2 +0 -0
  383. package/dist/fonts/maple-7.9-regular-079-5131c42759.woff2 +0 -0
  384. package/dist/fonts/maple-7.9-regular-07a-c0dad221b5.woff2 +0 -0
  385. package/dist/fonts/maple-7.9-regular-07f-5cf5ebe065.woff2 +0 -0
  386. package/dist/fonts/maple-7.9-regular-0fc-b644c0c6d9.woff2 +0 -0
  387. package/dist/fonts/maple-7.9-regular-780-c6000d472a.woff2 +0 -0
  388. package/dist/fonts/maple-7.9-regular-781-86409ab7f7.woff2 +0 -0
  389. package/dist/fonts/maple-7.9-regular-782-9cd950637c.woff2 +0 -0
  390. package/dist/fonts/maple-7.9-regular-783-105c4d02df.woff2 +0 -0
  391. package/dist/fonts/maple-7.9-regular-784-00c042af97.woff2 +0 -0
  392. package/dist/fonts/maple-7.9-regular-785-022568d0b8.woff2 +0 -0
  393. package/dist/fonts/maple-7.9-regular-786-90b6f3aef5.woff2 +0 -0
  394. package/dist/fonts/maple-7.9-regular-787-e2888596c9.woff2 +0 -0
  395. package/dist/fonts/maple-7.9-regular-788-3416e1fda3.woff2 +0 -0
  396. package/dist/fonts/maple-7.9-regular-789-9ffc917b0b.woff2 +0 -0
  397. package/dist/fonts/maple-7.9-regular-78a-4a921d07f6.woff2 +0 -0
  398. package/dist/fonts/maple-7.9-regular-78b-9d71c5327b.woff2 +0 -0
  399. package/dist/fonts/maple-7.9-regular-78c-9ec048314b.woff2 +0 -0
  400. package/dist/fonts/maple-7.9-regular-78d-46a2ebd113.woff2 +0 -0
  401. package/dist/fonts/maple-7.9-regular-latin-59c752ba1d.woff2 +0 -0
  402. package/dist/fonts/maple.css +315 -0
  403. package/dist/index.d.ts +9 -0
  404. package/dist/index.js +136 -0
  405. package/dist/index.js.map +1 -0
  406. package/dist/math-renderer-L6DOH4RX.js +21 -0
  407. package/dist/math-renderer-L6DOH4RX.js.map +1 -0
  408. package/dist/math.css +1 -0
  409. package/dist/react/index.d.ts +113 -0
  410. package/dist/react/index.js +59 -0
  411. package/dist/react/index.js.map +1 -0
  412. package/dist/styles.css +454 -0
  413. package/dist/translations-DHnYMg4h.d.ts +318 -0
  414. package/docs/README.md +13 -0
  415. package/docs/api.md +8 -0
  416. package/docs/assets/rendered.svg +9 -0
  417. package/docs/assets/source.svg +9 -0
  418. package/docs/en/README.md +26 -0
  419. package/docs/en/ai-skills.md +57 -0
  420. package/docs/en/annotations.md +84 -0
  421. package/docs/en/api.md +107 -0
  422. package/docs/en/architecture.md +33 -0
  423. package/docs/en/extensions.md +159 -0
  424. package/docs/en/getting-started.md +67 -0
  425. package/docs/en/integration.md +130 -0
  426. package/docs/en/modules.md +80 -0
  427. package/docs/en/performance.md +53 -0
  428. package/docs/en/plugin-packages.md +68 -0
  429. package/docs/en/styles.md +80 -0
  430. package/docs/en/syntax.md +352 -0
  431. package/docs/extensions.md +8 -0
  432. package/docs/implementation.md +8 -0
  433. package/docs/performance.md +8 -0
  434. package/docs/screenshots/blocks.png +0 -0
  435. package/docs/screenshots/dark.png +0 -0
  436. package/docs/screenshots/desktop.png +0 -0
  437. package/docs/screenshots/plugin-mobile.png +0 -0
  438. package/docs/styles.md +8 -0
  439. package/docs/visual-upgrade.md +8 -0
  440. package/docs/zh-CN/README.md +26 -0
  441. package/docs/zh-CN/ai-skills.md +57 -0
  442. package/docs/zh-CN/annotations.md +84 -0
  443. package/docs/zh-CN/api.md +107 -0
  444. package/docs/zh-CN/architecture.md +33 -0
  445. package/docs/zh-CN/extensions.md +159 -0
  446. package/docs/zh-CN/getting-started.md +67 -0
  447. package/docs/zh-CN/integration.md +130 -0
  448. package/docs/zh-CN/modules.md +80 -0
  449. package/docs/zh-CN/performance.md +53 -0
  450. package/docs/zh-CN/plugin-packages.md +68 -0
  451. package/docs/zh-CN/styles.md +80 -0
  452. package/docs/zh-CN/syntax.md +352 -0
  453. package/examples/assistant.tsx +52 -0
  454. package/examples/notes.tsx +80 -0
  455. package/examples/packages/paper-theme/index.css +25 -0
  456. package/examples/packages/paper-theme/package.json +7 -0
  457. package/examples/packages/reading-tools/index.d.ts +2 -0
  458. package/examples/packages/reading-tools/index.js +25 -0
  459. package/examples/packages/reading-tools/package.json +16 -0
  460. package/package.json +114 -3
  461. package/skills/limr-plugin-development/SKILL.md +22 -0
  462. package/skills/limr-plugin-development/agents/openai.yaml +4 -0
  463. package/skills/limr-plugin-development/assets/plugin-template/README.md +30 -0
  464. package/skills/limr-plugin-development/assets/plugin-template/package.json +36 -0
  465. package/skills/limr-plugin-development/assets/plugin-template/src/index.tsx +50 -0
  466. package/skills/limr-plugin-development/assets/plugin-template/src/styles.css +9 -0
  467. package/skills/limr-plugin-development/assets/plugin-template/tsconfig.json +20 -0
  468. package/skills/limr-plugin-development/assets/plugin-template/tsup.config.ts +8 -0
  469. package/skills/limr-plugin-development/references/contract.md +45 -0
  470. package/skills/limr-use/SKILL.md +23 -0
  471. package/skills/limr-use/agents/openai.yaml +4 -0
  472. package/skills/limr-use/references/integration.md +41 -0
  473. package/skills/limr-use/references/syntax.md +17 -0
@@ -0,0 +1,3130 @@
1
+ import {
2
+ annotationReferenceRange,
3
+ createDocument,
4
+ defaultHighlight,
5
+ intersects,
6
+ mapText,
7
+ rangeOf,
8
+ resolveAnnotationAnchors,
9
+ safeUrl,
10
+ sameRange,
11
+ selectionFromRange,
12
+ textContent,
13
+ walk
14
+ } from "./chunk-TTISGBST.js";
15
+ import {
16
+ ResourceCache
17
+ } from "./chunk-6N6TFHEN.js";
18
+
19
+ // src/react/motion.ts
20
+ var flights = /* @__PURE__ */ new WeakMap();
21
+ function scrollWithMotion(root, top) {
22
+ flights.get(root)?.();
23
+ const element = root instanceof Window ? root.document.documentElement : root;
24
+ const start = root instanceof Window ? root.scrollY : root.scrollTop;
25
+ const target = Math.max(0, Math.min(top, element.scrollHeight - (root instanceof Window ? root.innerHeight : root.clientHeight)));
26
+ if (matchMedia("(prefers-reduced-motion: reduce)").matches) {
27
+ root.scrollTo({ top: target, behavior: "instant" });
28
+ return;
29
+ }
30
+ const duration = Math.min(560, 220 + Math.abs(target - start) * 0.15);
31
+ let frame = 0, begun = 0;
32
+ const keyboard = (event) => {
33
+ if (["ArrowDown", "ArrowUp", "PageDown", "PageUp", "Home", "End", " "].includes(event.key)) stop();
34
+ };
35
+ const stop = () => {
36
+ cancelAnimationFrame(frame);
37
+ root.removeEventListener("wheel", stop);
38
+ root.removeEventListener("touchstart", stop);
39
+ root.removeEventListener("pointerdown", stop);
40
+ root.removeEventListener("keydown", keyboard);
41
+ flights.delete(root);
42
+ };
43
+ const step = (time) => {
44
+ begun ||= time;
45
+ const t = Math.min(1, (time - begun) / duration);
46
+ root.scrollTo({ top: start + (target - start) * (1 - Math.pow(1 - t, 4)), behavior: "instant" });
47
+ if (t < 1) frame = requestAnimationFrame(step);
48
+ else stop();
49
+ };
50
+ flights.set(root, stop);
51
+ root.addEventListener("wheel", stop, { passive: true });
52
+ root.addEventListener("touchstart", stop, { passive: true });
53
+ root.addEventListener("pointerdown", stop, { passive: true });
54
+ root.addEventListener("keydown", keyboard);
55
+ frame = requestAnimationFrame(step);
56
+ }
57
+
58
+ // src/react/runtime.ts
59
+ var english = {
60
+ language: "en",
61
+ citation: "Citation",
62
+ contents: "Contents",
63
+ annotations: "Annotations",
64
+ expand: "Expand",
65
+ collapse: "Collapse",
66
+ close: "Close",
67
+ copy: "Copy",
68
+ copied: "Copied",
69
+ copyFailed: "Copy failed",
70
+ copyImage: "Copy image URL",
71
+ copyFigures: "Copy figures Markdown",
72
+ loading: "Loading\u2026",
73
+ retry: "Retry",
74
+ unavailable: "Content unavailable",
75
+ footnotes: "Footnotes",
76
+ definition: "Definition",
77
+ question: "Question",
78
+ note: "Note",
79
+ extra: "Extended reading",
80
+ hint: "Hint",
81
+ answer: "Answer",
82
+ submit: "Submit",
83
+ correct: "Correct",
84
+ incorrect: "Try again",
85
+ play: "Play video",
86
+ highlight: "Highlight",
87
+ addHighlight: "Add highlight",
88
+ editHighlight: "Edit highlight",
89
+ highlightColor: "Color",
90
+ highlightStyle: "Style",
91
+ highlightBackground: "Background",
92
+ highlightUnderline: "Underline",
93
+ highlightDotted: "Dotted",
94
+ highlightWavy: "Wavy",
95
+ hideHighlight: "Hide highlight",
96
+ showHighlight: "Show highlight",
97
+ deleteAnnotations: "Delete",
98
+ deleteAnnotationsHint: "Deletes {count} annotations on this text and any highlight."
99
+ };
100
+ var chinese = {
101
+ language: "zh-CN",
102
+ citation: "\u5F15\u7528",
103
+ contents: "\u76EE\u5F55",
104
+ annotations: "\u6CE8\u91CA",
105
+ expand: "\u5C55\u5F00",
106
+ collapse: "\u6536\u8D77",
107
+ close: "\u5173\u95ED",
108
+ copy: "\u590D\u5236",
109
+ copied: "\u5DF2\u590D\u5236",
110
+ copyFailed: "\u590D\u5236\u5931\u8D25",
111
+ copyImage: "\u590D\u5236\u56FE\u7247 URL",
112
+ copyFigures: "\u590D\u5236\u56FE\u7EC4 Markdown",
113
+ loading: "\u52A0\u8F7D\u4E2D\u2026",
114
+ retry: "\u91CD\u8BD5",
115
+ unavailable: "\u6682\u65E0\u5185\u5BB9",
116
+ footnotes: "\u811A\u6CE8",
117
+ definition: "\u91CA\u4E49",
118
+ question: "\u63D0\u95EE",
119
+ note: "\u6CE8\u91CA",
120
+ extra: "\u62D3\u5C55\u9605\u8BFB",
121
+ hint: "\u63D0\u793A",
122
+ answer: "\u7B54\u6848",
123
+ submit: "\u63D0\u4EA4",
124
+ correct: "\u56DE\u7B54\u6B63\u786E",
125
+ incorrect: "\u518D\u8BD5\u4E00\u6B21",
126
+ play: "\u64AD\u653E\u89C6\u9891",
127
+ highlight: "\u9AD8\u4EAE",
128
+ addHighlight: "\u6DFB\u52A0\u9AD8\u4EAE",
129
+ editHighlight: "\u8C03\u6574\u9AD8\u4EAE",
130
+ highlightColor: "\u989C\u8272",
131
+ highlightStyle: "\u6837\u5F0F",
132
+ highlightBackground: "\u5E95\u8272",
133
+ highlightUnderline: "\u4E0B\u5212\u7EBF",
134
+ highlightDotted: "\u70B9\u7EBF",
135
+ highlightWavy: "\u6CE2\u6D6A\u7EBF",
136
+ hideHighlight: "\u9690\u85CF\u9AD8\u4EAE",
137
+ showHighlight: "\u663E\u793A\u9AD8\u4EAE",
138
+ deleteAnnotations: "\u5220\u9664",
139
+ deleteAnnotationsHint: "\u5C06\u5220\u9664\u8FD9\u6BB5\u6587\u5B57\u5173\u8054\u7684 {count} \u4E2A\u6CE8\u91CA\u53CA\u9AD8\u4EAE\u3002"
140
+ };
141
+ var Store = class {
142
+ constructor(value) {
143
+ this.value = value;
144
+ }
145
+ value;
146
+ listeners = /* @__PURE__ */ new Set();
147
+ get = () => this.value;
148
+ subscribe = (listener) => {
149
+ this.listeners.add(listener);
150
+ return () => this.listeners.delete(listener);
151
+ };
152
+ set(value) {
153
+ if (Object.is(this.value, value)) return;
154
+ this.value = value;
155
+ for (const listener of this.listeners) listener();
156
+ }
157
+ };
158
+ var EMPTY = Object.freeze([]);
159
+ var emptyDecorations = Object.freeze({ occurrences: EMPTY, highlights: EMPTY });
160
+ var ReaderRuntime = class {
161
+ document;
162
+ interaction = new Store({ selection: null, activeHeading: null, hovered: null, active: null, editing: null, activeHighlight: null, hoveredHighlight: null });
163
+ layout = new Store(0);
164
+ viewport = new Store(0);
165
+ documentOffset = new Store(0);
166
+ decorations = new Store({ annotations: /* @__PURE__ */ new Map(), highlights: /* @__PURE__ */ new Map(), occurrences: [], referenceRanges: /* @__PURE__ */ new Map(), byBlock: /* @__PURE__ */ new Map() });
167
+ configuration;
168
+ resources = new ResourceCache(128);
169
+ resourceVersions = new Store(/* @__PURE__ */ new Map());
170
+ resourceKeys = /* @__PURE__ */ new Map();
171
+ nextResource = 0;
172
+ anchors = /* @__PURE__ */ new Map();
173
+ blocks = /* @__PURE__ */ new Map();
174
+ headings = /* @__PURE__ */ new Map();
175
+ bindings = /* @__PURE__ */ new WeakMap();
176
+ textBinders = /* @__PURE__ */ new WeakMap();
177
+ components = {};
178
+ annotationTypes = /* @__PURE__ */ new Map();
179
+ resolvedTypes = /* @__PURE__ */ new WeakMap();
180
+ locale = english;
181
+ content = null;
182
+ selectionRange = null;
183
+ /** Live geometry supplied by the paint layer; independent of native selection. */
184
+ highlightReference = null;
185
+ layoutFrame = 0;
186
+ observer = null;
187
+ headingPositions = [];
188
+ localAnnotations = [];
189
+ pendingOpen = null;
190
+ pendingAnnotations;
191
+ taskController = new AbortController();
192
+ get signal() {
193
+ return this.taskController.signal;
194
+ }
195
+ commands = {
196
+ addAnnotation: (annotation, options = {}) => {
197
+ this.changeAnnotations((items) => {
198
+ const next = [...items.filter((item) => item.id !== annotation.id), annotation];
199
+ if (annotation.type !== "highlight" && options.highlight !== false && (options.highlight !== void 0 || this.annotationTypes.get(annotation.type)?.highlight !== "hover")) {
200
+ const doc = this.document.getSnapshot();
201
+ for (const anchor of resolveAnnotationAnchors(annotation, doc)) {
202
+ if (anchor.range.start === anchor.range.end || next.some((item) => item.type === "highlight" && resolveAnnotationAnchors(item, doc).some((other) => sameRange(other.range, anchor.range)))) continue;
203
+ next.push({ id: `highlight-${crypto.randomUUID()}`, type: "highlight", anchors: [{ ...anchor, id: void 0 }], data: { ...defaultHighlight, ...options.highlight } });
204
+ }
205
+ }
206
+ return next;
207
+ });
208
+ if (options.edit) this.commands.editAnnotation(annotation.id);
209
+ },
210
+ updateAnnotation: (id, update) => this.changeAnnotations((items) => items.map((item) => item.id === id ? { ...item, ...update, id } : item)),
211
+ removeAnnotation: (id) => this.changeAnnotations((items) => items.filter((item) => item.id !== id)),
212
+ removeAnnotationsAt: (ranges) => this.changeAnnotations((items) => items.flatMap((item) => {
213
+ const anchors = item.anchors ?? (item.range ? [{ range: item.range }] : []);
214
+ const keep = anchors.filter((anchor) => !resolveAnnotationAnchors({ ...item, range: void 0, anchors: [anchor] }, this.document.getSnapshot()).some((resolved) => ranges.some((range) => sameRange(range, resolved.range))));
215
+ if (keep.length === anchors.length) return [item];
216
+ return keep.length ? [{ ...item, range: void 0, anchors: keep }] : [];
217
+ })),
218
+ editAnnotation: (id) => {
219
+ this.updateInteraction({ editing: id });
220
+ if (id) this.commands.activateAnnotation(id);
221
+ },
222
+ activateAnnotation: (id) => {
223
+ const occurrence = this.decorations.get().occurrences.find((item) => item.id === id || item.annotationIds.includes(id ?? ""));
224
+ this.pendingOpen = id && !occurrence ? id : null;
225
+ this.activate(occurrence?.id ?? null);
226
+ }
227
+ };
228
+ changeAnnotations(update) {
229
+ const config = this.configuration.get();
230
+ const current = this.pendingAnnotations && this.pendingAnnotations.input === config.annotations ? this.pendingAnnotations.value : config.annotations ?? this.localAnnotations;
231
+ const next = update(current);
232
+ if (config.annotations !== void 0 && !config.onAnnotationsChange) throw new Error("Controlled annotations require onAnnotationsChange to accept edits.");
233
+ if (config.annotations === void 0) {
234
+ this.localAnnotations = next;
235
+ this.rebuildDecorations();
236
+ } else this.pendingAnnotations = { input: config.annotations, value: next };
237
+ config.onAnnotationsChange?.(next);
238
+ }
239
+ start() {
240
+ if (this.taskController.signal.aborted) this.taskController = new AbortController();
241
+ }
242
+ dispose() {
243
+ this.taskController.abort();
244
+ this.resources.invalidate();
245
+ this.resourceKeys.clear();
246
+ }
247
+ getResourceKey(annotation) {
248
+ const old = this.resourceKeys.get(annotation.id);
249
+ if (old?.annotation === annotation) return old.key;
250
+ if (old) this.resources.invalidate(old.key);
251
+ const key = `${annotation.id}:${++this.nextResource}`;
252
+ this.resourceKeys.set(annotation.id, { annotation, key });
253
+ return key;
254
+ }
255
+ invalidateAnnotation(id) {
256
+ const current = this.resourceKeys.get(id);
257
+ if (current) this.resources.invalidate(current.key);
258
+ const versions = new Map(this.resourceVersions.get());
259
+ versions.set(id, (versions.get(id) ?? 0) + 1);
260
+ this.resourceVersions.set(versions);
261
+ }
262
+ constructor(id, source, streaming, config) {
263
+ this.configuration = new Store(config);
264
+ this.installConfiguration(config);
265
+ this.document = createDocument(source, { id, streaming, extensions: config.extensions });
266
+ this.rebuildDecorations();
267
+ this.document.subscribe(() => {
268
+ this.rebuildDecorations();
269
+ const selection = this.interaction.get().selection;
270
+ if (selection && selection.raw.ranges.length === 1) {
271
+ const doc = this.document.getSnapshot(), range = selection.raw.ranges[0];
272
+ this.updateInteraction({ selection: doc.source.slice(range.start, range.end) === selection.raw.sourceText ? selectionFromRange(doc, range, { text: selection.text, quality: selection.quality, settled: selection.settled }) : null });
273
+ }
274
+ this.requestLayout();
275
+ this.configuration.get().onDocumentChange?.(this.document.getSnapshot());
276
+ });
277
+ }
278
+ installConfiguration(config) {
279
+ this.locale = { ...english, ...config.locale };
280
+ this.components = Object.assign({}, ...(config.extensions ?? []).map((ext) => ext.components), config.components);
281
+ const annotationTypes = [...(config.extensions ?? []).flatMap((ext) => [...ext.annotationTypes ?? []]), ...config.annotationTypes ?? []];
282
+ this.annotationTypes = new Map(annotationTypes.map((type) => {
283
+ if (typeof type.label === "string") return [type.type, type];
284
+ const label = type.label(this.locale);
285
+ const previous = this.resolvedTypes.get(type);
286
+ const resolved = previous?.label === label ? previous : { ...type, label };
287
+ this.resolvedTypes.set(type, resolved);
288
+ return [type.type, resolved];
289
+ }));
290
+ }
291
+ configure(config) {
292
+ const old = this.configuration.get();
293
+ if (this.pendingAnnotations?.input !== config.annotations) this.pendingAnnotations = void 0;
294
+ this.installConfiguration(config);
295
+ this.configuration.set(config);
296
+ if (old.extensions !== config.extensions) this.document.setExtensions(config.extensions ?? []);
297
+ else if (old.annotations !== config.annotations || old.annotationTypes !== config.annotationTypes) this.rebuildDecorations();
298
+ if (old.annotationTypes !== config.annotationTypes || old.extensions !== config.extensions) this.resources.invalidate();
299
+ }
300
+ updateInteraction(patch) {
301
+ const old = this.interaction.get();
302
+ if (Object.keys(patch).every((key) => Object.is(old[key], patch[key]))) return;
303
+ this.interaction.set({ ...old, ...patch });
304
+ if ("selection" in patch) this.configuration.get().onSelectionChange?.(patch.selection ?? null);
305
+ }
306
+ hover(id, source = "marker") {
307
+ this.updateInteraction({ hovered: id, hoverSource: id ? source : null });
308
+ this.configuration.get().onAnnotationHover?.(this.decorations.get().occurrences.find((item) => item.id === id) ?? null);
309
+ }
310
+ activate(id, source = "marker") {
311
+ this.updateInteraction({ active: id, activeSource: id ? source : null, hovered: null, hoverSource: null });
312
+ const occurrence = this.decorations.get().occurrences.find((item) => item.id === id);
313
+ if (occurrence) this.configuration.get().onAnnotationClick?.(occurrence);
314
+ }
315
+ hoverHighlight(id) {
316
+ if (this.interaction.get().hoveredHighlight === id) return;
317
+ this.updateInteraction({ hoveredHighlight: id });
318
+ this.configuration.get().onHighlightHover?.(id ? this.decorations.get().annotations.get(this.decorations.get().highlights.get(id)?.annotationId ?? "") ?? null : null);
319
+ }
320
+ activateHighlight(id) {
321
+ this.updateInteraction({ activeHighlight: id, selection: null });
322
+ const highlight = id && this.decorations.get().highlights.get(id);
323
+ if (highlight) this.configuration.get().onHighlightClick?.(this.decorations.get().annotations.get(highlight.annotationId));
324
+ else this.highlightReference = null;
325
+ }
326
+ clearSelection() {
327
+ this.selectionRange = null;
328
+ const selection = typeof window === "undefined" ? null : window.getSelection();
329
+ if (selection?.anchorNode && this.content?.contains(selection.anchorNode)) selection.removeAllRanges();
330
+ this.highlightReference = null;
331
+ this.updateInteraction({ selection: null, activeHighlight: null });
332
+ }
333
+ prepareTextBindings(element) {
334
+ const block = element.closest("[data-limr-block]");
335
+ const bind = block && this.textBinders.get(block);
336
+ if (bind) {
337
+ this.textBinders.delete(block);
338
+ bind();
339
+ }
340
+ }
341
+ rebuildDecorations() {
342
+ const doc = this.document.getSnapshot();
343
+ const config = this.configuration.get();
344
+ const previous = this.decorations.get();
345
+ const annotations = new Map(doc.annotations.map((annotation) => [annotation.id, annotation]));
346
+ for (const annotation of config.annotations ?? this.localAnnotations) annotations.set(annotation.id, annotation);
347
+ for (const [id, resource] of this.resourceKeys) if (!annotations.has(id)) {
348
+ this.resources.invalidate(resource.key);
349
+ this.resourceKeys.delete(id);
350
+ }
351
+ const versions = this.resourceVersions.get();
352
+ if ([...versions.keys()].some((id) => !annotations.has(id))) this.resourceVersions.set(new Map([...versions].filter(([id]) => annotations.has(id))));
353
+ const occurrences = [...doc.occurrences];
354
+ const allHighlights = [];
355
+ for (const annotation of config.annotations ?? this.localAnnotations) {
356
+ resolveAnnotationAnchors(annotation, doc).forEach((anchor, index) => {
357
+ if (annotation.type === "highlight") {
358
+ const id = index ? `${annotation.id}:${index}` : annotation.id;
359
+ const value = { ...annotation.data, id, annotationId: annotation.id, range: anchor.range };
360
+ const old = previous.highlights.get(id);
361
+ allHighlights.push(old && !old.occurrenceId && sameRange(old.range, value.range) && old.color === value.color && old.style === value.style && old.hidden === value.hidden ? old : value);
362
+ } else occurrences.push({ ...anchor, id: anchor.id ?? `${doc.id}-${annotation.id}-${index}`, annotationIds: [annotation.id] });
363
+ });
364
+ }
365
+ occurrences.sort((a, b) => a.range.end - b.range.end || a.id.localeCompare(b.id));
366
+ const referenceRanges = new Map(occurrences.map((occurrence) => [occurrence.id, annotationReferenceRange(doc, occurrence)]));
367
+ for (const occurrence of occurrences) {
368
+ const annotation = annotations.get(occurrence.annotationIds[0]);
369
+ const definition2 = annotation && this.annotationTypes.get(annotation.type);
370
+ if (!annotation || definition2?.highlight !== "hover") continue;
371
+ const range = referenceRanges.get(occurrence.id);
372
+ if (range.start === range.end) continue;
373
+ const id = `reference-${occurrence.id}`;
374
+ const value = { id, annotationId: annotation.id, occurrenceId: occurrence.id, range, color: definition2.color ?? defaultHighlight.color, style: "background" };
375
+ const old = previous.highlights.get(id);
376
+ allHighlights.push(old && old.occurrenceId === value.occurrenceId && old.annotationId === value.annotationId && sameRange(old.range, range) && old.color === value.color ? old : value);
377
+ }
378
+ const byBlock = /* @__PURE__ */ new Map();
379
+ for (const block of occurrences.length || allHighlights.length ? doc.blocks : []) {
380
+ const marks = occurrences.filter((item) => !item.embedded && item.range.end > block.range.start && item.range.end <= block.range.end);
381
+ const before = previous.byBlock.get(block.id) ?? emptyDecorations;
382
+ const old = before.occurrences;
383
+ const same = old && old.length === marks.length && old.every((item, index) => item.id === marks[index].id && item.range.start === marks[index].range.start && item.range.end === marks[index].range.end && item.annotationIds.join("\0") === marks[index].annotationIds.join("\0"));
384
+ const highlights2 = allHighlights.filter((item) => intersects(item.range, block.range));
385
+ const oldHighlights = before.highlights;
386
+ const sameHighlights = oldHighlights.length === highlights2.length && oldHighlights.every((item, i) => item === highlights2[i]);
387
+ if (marks.length || highlights2.length) byBlock.set(block.id, same && sameHighlights ? before : { occurrences: same ? old : marks, highlights: sameHighlights ? oldHighlights : highlights2 });
388
+ }
389
+ const sameBlocks = byBlock.size === previous.byBlock.size && [...byBlock].every(([id, value]) => previous.byBlock.get(id) === value);
390
+ const highlights = new Map(allHighlights.map((item) => [item.id, item]));
391
+ this.decorations.set({ annotations, highlights, occurrences, referenceRanges, byBlock: sameBlocks ? previous.byBlock : byBlock });
392
+ const state = this.interaction.get();
393
+ if (state.editing && !annotations.has(state.editing) && this.pendingOpen !== state.editing) this.updateInteraction({ editing: null });
394
+ if (state.activeHighlight && !highlights.has(state.activeHighlight)) this.activateHighlight(null);
395
+ if (state.hoveredHighlight && !highlights.has(state.hoveredHighlight)) this.hoverHighlight(null);
396
+ if (state.active && !occurrences.some((item) => item.id === state.active)) this.activate(null);
397
+ if (state.hovered && !occurrences.some((item) => item.id === state.hovered)) this.hover(null);
398
+ if (this.pendingOpen) {
399
+ const occurrence = occurrences.find((item) => item.id === this.pendingOpen || item.annotationIds.includes(this.pendingOpen));
400
+ if (occurrence) {
401
+ this.pendingOpen = null;
402
+ this.activate(occurrence.id);
403
+ }
404
+ }
405
+ }
406
+ registerAnchor(id, element) {
407
+ if (element) this.anchors.set(id, element);
408
+ else this.anchors.delete(id);
409
+ this.requestLayout();
410
+ }
411
+ registerHeading(id, element) {
412
+ if (element) this.headings.set(id, element);
413
+ else this.headings.delete(id);
414
+ this.requestLayout();
415
+ }
416
+ observeBlock(element) {
417
+ if (element) {
418
+ if (element.dataset.limrBlock) this.blocks.set(element.dataset.limrBlock, element);
419
+ this.observer?.observe(element);
420
+ }
421
+ }
422
+ unobserveBlock(element) {
423
+ if (element.dataset.limrBlock) this.blocks.delete(element.dataset.limrBlock);
424
+ this.observer?.unobserve(element);
425
+ }
426
+ getScrollTop() {
427
+ return this.configuration.get().scrollRoot?.scrollTop ?? (typeof window !== "undefined" ? window.scrollY : 0);
428
+ }
429
+ getViewportTop() {
430
+ return this.configuration.get().scrollRoot?.getBoundingClientRect().top ?? 0;
431
+ }
432
+ getContentOffset() {
433
+ const translate = this.content && getComputedStyle(this.content).translate;
434
+ return translate ? parseFloat(translate.split(" ")[1] ?? "0") || 0 : 0;
435
+ }
436
+ scrollTo(top, behavior = "smooth") {
437
+ const root = this.configuration.get().scrollRoot ?? window;
438
+ if (behavior === "smooth") scrollWithMotion(root, top);
439
+ else root.scrollTo({ top: Math.max(0, top), behavior });
440
+ }
441
+ scrollToHeading(id) {
442
+ const element = this.headings.get(id);
443
+ if (element) this.scrollTo(element.getBoundingClientRect().top - this.getViewportTop() + this.getScrollTop() - (this.configuration.get().scrollOffset ?? 24));
444
+ }
445
+ scrollToOccurrence(id) {
446
+ const element = this.anchors.get(id);
447
+ if (element) this.scrollTo(element.getBoundingClientRect().top - this.getViewportTop() + this.getScrollTop() - (this.configuration.get().scrollOffset ?? 24));
448
+ }
449
+ followFragment = (event) => {
450
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
451
+ const link = event.target instanceof Element ? event.target.closest("a[href]") : null;
452
+ if (!link || link.hasAttribute("download") || link.target && link.target !== "_self" || !this.content?.contains(link)) return;
453
+ const url = new URL(link.href, document.baseURI);
454
+ if (!url.hash || url.origin !== location.origin || url.pathname !== location.pathname || url.search !== location.search) return;
455
+ let id;
456
+ try {
457
+ id = decodeURIComponent(url.hash.slice(1));
458
+ } catch {
459
+ return;
460
+ }
461
+ const target = this.content.querySelector(`[id="${CSS.escape(id)}"]`);
462
+ if (!target) return;
463
+ event.preventDefault();
464
+ this.scrollTo(target.getBoundingClientRect().top - this.getViewportTop() + this.getScrollTop() - (this.configuration.get().scrollOffset ?? 24));
465
+ if (event.detail === 0) {
466
+ if (!target.hasAttribute("tabindex")) {
467
+ target.tabIndex = -1;
468
+ target.addEventListener("blur", () => target.removeAttribute("tabindex"), { once: true });
469
+ }
470
+ target.focus({ preventScroll: true });
471
+ }
472
+ };
473
+ requestLayout = () => {
474
+ if (typeof window === "undefined" || !this.content || this.layoutFrame) return;
475
+ this.layoutFrame = window.requestAnimationFrame(() => {
476
+ this.layoutFrame = 0;
477
+ const offset = this.getScrollTop() - this.getViewportTop();
478
+ this.headingPositions = [...this.headings].filter(([, element]) => !element.closest("[inert]")).map(([id, element]) => ({ id, top: element.getBoundingClientRect().top + offset })).sort((a, b) => a.top - b.top);
479
+ const state = this.interaction.get();
480
+ if (state.active && this.anchors.get(state.active)?.closest("[inert]")) this.activate(null);
481
+ if (state.hovered && this.anchors.get(state.hovered)?.closest("[inert]")) this.hover(null);
482
+ this.layout.set(this.layout.get() + 1);
483
+ this.trackHeading();
484
+ });
485
+ };
486
+ trackHeading = () => {
487
+ const positions = this.headingPositions;
488
+ const top = this.getScrollTop() + (this.configuration.get().scrollOffset ?? 24) + 2;
489
+ let lo = 0, hi = positions.length;
490
+ while (lo < hi) {
491
+ const mid = lo + hi >>> 1;
492
+ if (positions[mid].top <= top) lo = mid + 1;
493
+ else hi = mid;
494
+ }
495
+ const root = this.configuration.get().scrollRoot;
496
+ const maximum = (root?.scrollHeight ?? document.documentElement.scrollHeight) - (root?.clientHeight ?? window.innerHeight);
497
+ const atEnd = maximum > 0 && this.getScrollTop() >= maximum - 2;
498
+ this.updateInteraction({ activeHeading: positions[atEnd ? positions.length - 1 : Math.max(0, lo - 1)]?.id ?? null });
499
+ };
500
+ mountContent(element) {
501
+ this.content = element;
502
+ this.observer = new ResizeObserver(this.requestLayout);
503
+ this.observer.observe(element);
504
+ element.querySelectorAll("[data-limr-block]").forEach((block) => this.observer.observe(block));
505
+ let frame = 0;
506
+ const scroll = () => {
507
+ if (frame) return;
508
+ frame = requestAnimationFrame(() => {
509
+ frame = 0;
510
+ this.trackHeading();
511
+ this.viewport.set(this.viewport.get() + 1);
512
+ });
513
+ };
514
+ const scrollRoot = this.configuration.get().scrollRoot ?? window;
515
+ scrollRoot.addEventListener("scroll", scroll, { passive: true });
516
+ window.addEventListener("resize", this.requestLayout);
517
+ document.fonts?.addEventListener("loadingdone", this.requestLayout);
518
+ element.addEventListener("load", this.requestLayout, true);
519
+ element.addEventListener("click", this.followFragment);
520
+ this.requestLayout();
521
+ return () => {
522
+ this.content = null;
523
+ this.observer?.disconnect();
524
+ this.observer = null;
525
+ cancelAnimationFrame(frame);
526
+ cancelAnimationFrame(this.layoutFrame);
527
+ this.layoutFrame = 0;
528
+ scrollRoot.removeEventListener("scroll", scroll);
529
+ window.removeEventListener("resize", this.requestLayout);
530
+ document.fonts?.removeEventListener("loadingdone", this.requestLayout);
531
+ element.removeEventListener("load", this.requestLayout, true);
532
+ element.removeEventListener("click", this.followFragment);
533
+ };
534
+ }
535
+ };
536
+ var emptyList = EMPTY;
537
+
538
+ // src/extensions/gfm.ts
539
+ import { gfm as syntax } from "micromark-extension-gfm";
540
+ import { gfmFromMarkdown } from "mdast-util-gfm";
541
+ function gfm() {
542
+ return { name: "gfm", micromark: [syntax()], mdast: gfmFromMarkdown(), scope: "local" };
543
+ }
544
+
545
+ // src/extensions/math.tsx
546
+ import { lazy, Suspense } from "react";
547
+ import { math as syntax2 } from "micromark-extension-math";
548
+ import { mathFromMarkdown } from "mdast-util-math";
549
+
550
+ // src/components/CopyButton.tsx
551
+ import { useEffect as useEffect9, useRef as useRef12, useState as useState9 } from "react";
552
+
553
+ // src/react/context.tsx
554
+ import { createContext as createContext2, useCallback as useCallback2, useContext as useContext3, useEffect as useEffect8, useId, useLayoutEffect, useMemo as useMemo4, useRef as useRef11, useState as useState8, useSyncExternalStore } from "react";
555
+
556
+ // src/extensions/code.tsx
557
+ import { useEffect, useRef, useState } from "react";
558
+
559
+ // src/react/literal.ts
560
+ function literalValue(node) {
561
+ return (node.value ?? "").replace(/\r\n?|\n/g, node.type === "inlineCode" ? " " : "\n");
562
+ }
563
+ function mapLiteral(source, node) {
564
+ const range = rangeOf(node), raw = source.slice(range.start, range.end), value = literalValue(node);
565
+ const starts = [], ends = [];
566
+ if (node.type === "inlineCode") {
567
+ const fence = /^`+/.exec(raw)?.[0].length ?? 0;
568
+ let from = fence, until = raw.length - fence;
569
+ const normalized = raw.slice(from, until).replace(/\r\n?|\n/g, " ");
570
+ if (normalized.startsWith(" ") && normalized.endsWith(" ") && /[^ ]/.test(normalized)) {
571
+ from += raw.slice(from, from + 2) === "\r\n" ? 2 : 1;
572
+ until -= raw.slice(until - 2, until) === "\r\n" ? 2 : 1;
573
+ }
574
+ for (let at = from; at < until; at++) {
575
+ const length = raw[at] === "\r" && raw[at + 1] === "\n" ? 2 : 1;
576
+ starts.push(range.start + at);
577
+ ends.push(range.start + at + length);
578
+ at += length - 1;
579
+ }
580
+ return { starts, ends, exact: starts.length === value.length };
581
+ }
582
+ const lines = [...raw.matchAll(/[^\r\n]*(?:\r\n|\r|\n|$)/g)].filter((match) => match[0]);
583
+ const fenced = /^[ \t]*(?:`{3,}|~{3,})/.test(lines[0]?.[0] ?? "");
584
+ let index = fenced ? 1 : 0;
585
+ let exact = true;
586
+ const values = value.split("\n");
587
+ for (let line = 0; line < values.length; line++, index++) {
588
+ const match = lines[index], text = values[line];
589
+ const rawLine = (match?.[0] ?? "").replace(/[\r\n]+$/, "");
590
+ const at = rawLine.endsWith(text) ? rawLine.length - text.length : -1;
591
+ if (at < 0 || !match) exact = false;
592
+ const start = range.start + (match?.index ?? raw.length) + Math.max(0, at);
593
+ for (let unit = 0; unit < text.length; unit++) {
594
+ starts.push(start + unit);
595
+ ends.push(start + unit + 1);
596
+ }
597
+ if (line < values.length - 1) {
598
+ starts.push(range.start + (match?.index ?? 0) + rawLine.length);
599
+ ends.push(range.start + (match?.index ?? 0) + (match?.[0].length ?? rawLine.length));
600
+ }
601
+ }
602
+ return { starts, ends, exact };
603
+ }
604
+
605
+ // src/extensions/code.tsx
606
+ import { jsx, jsxs } from "react/jsx-runtime";
607
+ var cache = new ResourceCache(96);
608
+ var aliases = { js: "javascript", ts: "typescript", py: "python", sh: "bash", yml: "yaml", md: "markdown", rs: "rust", "c++": "cpp", text: "text", txt: "text" };
609
+ function codeHighlight(options = {}) {
610
+ function CodeNode({ node, pending, renderValue }) {
611
+ const runtime = useRuntime();
612
+ const code = literalValue(node);
613
+ const language = String(node.lang ?? "text").toLowerCase();
614
+ const normalized = aliases[language] ?? language;
615
+ const [result, setResult] = useState(null);
616
+ const [visible, setVisible] = useState(options.eager ?? false);
617
+ const ref = useRef(null);
618
+ useEffect(() => {
619
+ if (visible) return;
620
+ if (typeof IntersectionObserver === "undefined") {
621
+ setVisible(true);
622
+ return;
623
+ }
624
+ const observer = new IntersectionObserver((entries) => {
625
+ if (entries.some((entry) => entry.isIntersecting)) {
626
+ setVisible(true);
627
+ observer.disconnect();
628
+ }
629
+ }, { root: runtime.configuration.get().scrollRoot, rootMargin: "400px" });
630
+ if (ref.current) observer.observe(ref.current);
631
+ return () => observer.disconnect();
632
+ }, [visible, runtime]);
633
+ useEffect(() => {
634
+ if (!visible || code.length > (options.maxLength ?? 1e5)) return;
635
+ let disposed = false;
636
+ let release;
637
+ const timer = setTimeout(() => {
638
+ if (normalized === "text" || options.languages && !options.languages.includes(normalized)) return;
639
+ const request = cache.acquire(JSON.stringify([code, normalized, options.lightTheme, options.darkTheme]), async () => {
640
+ const shiki = await import("shiki");
641
+ if (!(normalized in shiki.bundledLanguages) && !(normalized in shiki.bundledLanguagesAlias)) return [];
642
+ const result2 = await shiki.codeToTokens(code, { lang: normalized, themes: { light: options.lightTheme ?? "github-light", dark: options.darkTheme ?? "github-dark" }, defaultColor: false });
643
+ let offset = 0;
644
+ return result2.tokens.flatMap((line, index) => {
645
+ const tokens2 = line.map((token) => {
646
+ const start = offset;
647
+ offset += token.content.length;
648
+ return { content: token.content, offset: start, style: token.htmlStyle };
649
+ });
650
+ if (index < result2.tokens.length - 1) {
651
+ tokens2.push({ content: "\n", offset: offset++ });
652
+ }
653
+ return tokens2;
654
+ });
655
+ });
656
+ release = request.release;
657
+ request.promise.then((tokens2) => {
658
+ if (!disposed) setResult({ code, tokens: tokens2 });
659
+ }).catch(() => {
660
+ });
661
+ }, pending ? 180 : 0);
662
+ return () => {
663
+ disposed = true;
664
+ clearTimeout(timer);
665
+ release?.();
666
+ };
667
+ }, [code, normalized, pending, visible]);
668
+ const tokens = result?.code === code ? result.tokens : void 0;
669
+ return /* @__PURE__ */ jsxs("div", { className: "limr-code-block", ref, children: [
670
+ /* @__PURE__ */ jsxs("div", { className: "limr-code-header", "data-limr-ignore": "true", children: [
671
+ /* @__PURE__ */ jsx("span", { children: language }),
672
+ /* @__PURE__ */ jsx(CopyButton, { value: code })
673
+ ] }),
674
+ /* @__PURE__ */ jsx("pre", { className: tokens?.length ? "shiki" : void 0, children: /* @__PURE__ */ jsx("code", { children: renderValue(tokens) }) })
675
+ ] });
676
+ }
677
+ return { name: "code-highlight", scope: "local", components: { code: CodeNode } };
678
+ }
679
+
680
+ // src/extensions/annotations.tsx
681
+ import { useMemo as useMemo2, useRef as useRef6 } from "react";
682
+ import { fromMarkdown } from "mdast-util-from-markdown";
683
+
684
+ // src/react/Markdown.tsx
685
+ import { useContext, useEffect as useEffect4, useRef as useRef4 } from "react";
686
+
687
+ // src/react/render.tsx
688
+ import { cloneElement, Component, createElement, Fragment, isValidElement, memo, useCallback, useMemo, useRef as useRef2 } from "react";
689
+
690
+ // src/react/text-binding.ts
691
+ var atomic = /* @__PURE__ */ new Set(["inlineCode", "code", "math", "inlineMath", "image", "imageReference", "html"]);
692
+ var hidden = /* @__PURE__ */ new Set(["definition", "footnoteDefinition", "annotationDefinition", "footnoteReference"]);
693
+ var ordinary = /* @__PURE__ */ new Set(["text", "paragraph", "heading", "strong", "emphasis", "delete", "blockquote", "list", "listItem", "link", "linkReference", "table", "tableRow", "tableCell", "thematicBreak", "break", "annotationReference"]);
694
+ function compactTextNodes(node, components) {
695
+ const texts = [];
696
+ let supported = true;
697
+ const visit = (node2) => {
698
+ if (node2.selection === "atomic" || atomic.has(node2.type) || hidden.has(node2.type)) return;
699
+ if (!ordinary.has(node2.type) || components[node2.type]) {
700
+ supported = false;
701
+ return;
702
+ }
703
+ if (node2.type === "text") {
704
+ if (node2.value) texts.push(node2);
705
+ return;
706
+ }
707
+ node2.children?.forEach(visit);
708
+ };
709
+ visit(node);
710
+ return supported ? texts : null;
711
+ }
712
+ function bindingFor(node, source) {
713
+ const range = rangeOf(node), value = node.value ?? "";
714
+ const raw = source.slice(range.start, range.end);
715
+ const direct = raw === value;
716
+ let mapping;
717
+ const mapped = () => mapping ??= mapText(raw, value, { start: 0, end: raw.length });
718
+ return {
719
+ range,
720
+ atomic: false,
721
+ get exact() {
722
+ return direct || mapped().exact;
723
+ },
724
+ resolve(offset, edge) {
725
+ const at = Math.max(0, Math.min(value.length, offset));
726
+ return direct ? range.start + at : range.start + (edge === "start" ? mapped().starts[at] ?? raw.length : mapped().ends[at - 1] ?? 0);
727
+ }
728
+ };
729
+ }
730
+ function bindCompactText(element, nodes, runtime) {
731
+ const bound = [];
732
+ const clear = () => bound.forEach((node) => runtime.bindings.delete(node));
733
+ const bindings = nodes.map((node) => bindingFor(node, runtime.document.getSnapshot().source));
734
+ const walker = element.ownerDocument.createTreeWalker(element, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
735
+ acceptNode(node) {
736
+ if (node.nodeType === Node.ELEMENT_NODE) {
737
+ const element2 = node;
738
+ return element2.hasAttribute("data-limr-ignore") || element2.hasAttribute("data-limr-text") || runtime.bindings.get(element2)?.atomic ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_SKIP;
739
+ }
740
+ return NodeFilter.FILTER_ACCEPT;
741
+ }
742
+ });
743
+ let index = 0, inValue = 0;
744
+ for (let text = walker.nextNode(); text; text = walker.nextNode()) {
745
+ const value = text.textContent ?? "";
746
+ if (!value) continue;
747
+ const parts2 = [];
748
+ for (let at = 0; at < value.length; ) {
749
+ const expected = nodes[index]?.value ?? "";
750
+ const size = Math.min(value.length - at, expected.length - inValue);
751
+ if (size <= 0 || value.slice(at, at + size) !== expected.slice(inValue, inValue + size)) {
752
+ clear();
753
+ return () => {
754
+ };
755
+ }
756
+ parts2.push({ start: at, end: at + size, offset: inValue, binding: bindings[index] });
757
+ at += size;
758
+ inValue += size;
759
+ if (inValue === expected.length) {
760
+ index++;
761
+ inValue = 0;
762
+ }
763
+ }
764
+ const first = parts2[0], last = parts2[parts2.length - 1];
765
+ runtime.bindings.set(text, parts2.length === 1 && first.offset === 0 && value === nodes[index - 1]?.value ? first.binding : {
766
+ range: { start: first.binding.range.start, end: last.binding.range.end },
767
+ atomic: false,
768
+ get exact() {
769
+ return parts2.every((part) => part.binding.exact);
770
+ },
771
+ resolve(offset, edge) {
772
+ const part = parts2.find((part2) => edge === "start" ? part2.end > offset : part2.end >= offset) ?? last;
773
+ return part.binding.resolve(part.offset + offset - part.start, edge);
774
+ }
775
+ });
776
+ bound.push(text);
777
+ }
778
+ return clear;
779
+ }
780
+
781
+ // src/react/render.tsx
782
+ import { Fragment as Fragment2, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
783
+ var blockAttributes = (block) => block ? { "data-limr-block": block.id, "data-source-start": block.range.start, "data-source-end": block.range.end, "data-pending": block.pending || void 0 } : {};
784
+ function AnnotationMarker({ occurrence }) {
785
+ const runtime = useRuntime();
786
+ const annotation = useStoreSelector(runtime.decorations, (state) => state.annotations.get(occurrence.annotationIds[0]));
787
+ const active = useStoreSelector(runtime.interaction, (state) => state.active === occurrence.id);
788
+ const hovered = useStoreSelector(runtime.interaction, (state) => state.hovered === occurrence.id);
789
+ const definition2 = useStoreSelector(runtime.configuration, () => runtime.annotationTypes.get(annotation?.type ?? "citation"));
790
+ const Icon = definition2?.icon;
791
+ const Custom = definition2?.Marker;
792
+ const icon = typeof Icon === "function" || Icon && typeof Icon === "object" && !isValidElement(Icon) && "$$typeof" in Icon ? createElement(Icon) : Icon;
793
+ return /* @__PURE__ */ jsx2("span", { className: "limr-mark-wrap", "data-limr-ignore": "true", "data-limr-marker": occurrence.id, "data-source-start": occurrence.range.start, "data-source-end": occurrence.range.end, children: /* @__PURE__ */ jsxs2(
794
+ "button",
795
+ {
796
+ type: "button",
797
+ ref: (element) => runtime.registerAnchor(occurrence.id, element),
798
+ className: "limr-mark",
799
+ "data-limr-anchor": occurrence.id,
800
+ "data-active": active || hovered || void 0,
801
+ style: { "--limr-mark-color": definition2?.color },
802
+ "aria-label": definition2?.label ?? annotation?.type ?? "Annotation",
803
+ "aria-expanded": active,
804
+ onPointerEnter: (event) => {
805
+ if (event.pointerType !== "touch") runtime.hover(occurrence.id);
806
+ },
807
+ onPointerLeave: (event) => {
808
+ if (event.pointerType !== "touch" && runtime.interaction.get().hovered === occurrence.id && runtime.interaction.get().hoverSource === "marker") runtime.hover(null);
809
+ },
810
+ onFocus: (event) => {
811
+ if (event.currentTarget.matches(":focus-visible")) runtime.hover(occurrence.id);
812
+ },
813
+ onBlur: (event) => {
814
+ if (event.relatedTarget instanceof Element && event.relatedTarget.closest("[data-occurrence]")?.getAttribute("data-occurrence") === occurrence.id) return;
815
+ if (runtime.interaction.get().hovered === occurrence.id && runtime.interaction.get().hoverSource === "marker") runtime.hover(null);
816
+ },
817
+ onClick: () => {
818
+ const hovering = runtime.interaction.get().hovered === occurrence.id;
819
+ runtime.activate(active ? null : occurrence.id);
820
+ if (hovering) runtime.hover(occurrence.id);
821
+ },
822
+ children: [
823
+ /* @__PURE__ */ jsx2("span", { className: "limr-mark-icon", children: Custom && annotation ? /* @__PURE__ */ jsx2(Custom, { annotation, active }) : icon ?? "\u2022" }),
824
+ occurrence.annotationIds.length > 1 && /* @__PURE__ */ jsx2("span", { className: "limr-mark-count", children: occurrence.annotationIds.length })
825
+ ]
826
+ }
827
+ ) });
828
+ }
829
+ function Text({ node, context, mapping: literalMapping, marks: literalMarks, style, className }) {
830
+ const { runtime } = context;
831
+ const value = node.value ?? "";
832
+ const range = rangeOf(node);
833
+ const source = runtime.document.getSnapshot().source;
834
+ const mapped = useMemo(() => {
835
+ let mapping2;
836
+ const raw = source.slice(range.start, range.end);
837
+ return () => {
838
+ if (literalMapping) return literalMapping;
839
+ if (!mapping2) {
840
+ const relative = mapText(raw, value, { start: 0, end: raw.length }, { escapes: node.verbatimEscapes !== true });
841
+ mapping2 = { starts: relative.starts.map((offset) => offset + range.start), ends: relative.ends.map((offset) => offset + range.start), exact: relative.exact };
842
+ }
843
+ return mapping2;
844
+ };
845
+ }, [node, literalMapping]);
846
+ const marks = literalMarks ?? context.marks.get(node) ?? emptyList;
847
+ const highlights = context.highlights.filter((highlight) => intersects(highlight.range, range));
848
+ if (!marks.length && !highlights.length) {
849
+ const direct = !literalMapping && source.slice(range.start, range.end) === value;
850
+ return /* @__PURE__ */ jsx2("span", { style, className, "data-limr-text": "", "data-source-start": range.start, "data-source-end": range.end, ref: (element) => {
851
+ if (element) runtime.bindings.set(element, {
852
+ range,
853
+ atomic: false,
854
+ get exact() {
855
+ return direct || mapped().exact;
856
+ },
857
+ resolve: (offset, edge) => direct ? Math.max(range.start, Math.min(range.end, range.start + offset)) : edge === "start" ? mapped().starts[offset] ?? range.end : mapped().ends[offset - 1] ?? range.start
858
+ });
859
+ }, children: value });
860
+ }
861
+ const mapping = mapped();
862
+ const markerAt = /* @__PURE__ */ new Map();
863
+ const boundaries = /* @__PURE__ */ new Set([0, value.length]);
864
+ for (const mark of marks) {
865
+ let index = mapping.ends.findIndex((end) => end >= mark.range.end);
866
+ index = index < 0 ? value.length : index + 1;
867
+ boundaries.add(index);
868
+ markerAt.set(index, [...markerAt.get(index) ?? [], mark]);
869
+ }
870
+ for (const highlight of highlights) {
871
+ const start = mapping.ends.findIndex((end2) => end2 > highlight.range.start);
872
+ const end = mapping.starts.findIndex((start2) => start2 >= highlight.range.end);
873
+ boundaries.add(Math.max(0, start));
874
+ boundaries.add(end < 0 ? value.length : end);
875
+ }
876
+ const points = [...boundaries].sort((a, b) => a - b);
877
+ return /* @__PURE__ */ jsx2(Fragment2, { children: points.slice(1).map((end, index) => {
878
+ const start = points[index];
879
+ const segmentRange = { start: mapping.starts[start] ?? range.start, end: mapping.ends[end - 1] ?? range.end };
880
+ const styles = highlights.filter((highlight) => intersects(highlight.range, segmentRange));
881
+ let text = value.slice(start, end);
882
+ for (const highlight of styles) text = /* @__PURE__ */ jsx2("mark", { "data-limr-highlight": highlight.id, "data-hidden": highlight.hidden || void 0, className: `limr-highlight limr-highlight-${highlight.style ?? "background"}`, style: { "--limr-highlight": highlight.color ?? "#f3ce7380" }, children: text }, highlight.id);
883
+ return /* @__PURE__ */ jsxs2("span", { style, className, ref: (element) => {
884
+ if (element) runtime.bindings.set(element, { range: segmentRange, atomic: false, exact: mapping.exact, resolve: (offset, edge) => {
885
+ const at = Math.max(start, Math.min(end, start + offset));
886
+ return edge === "start" ? mapping.starts[at] ?? segmentRange.end : mapping.ends[at - 1] ?? segmentRange.start;
887
+ } });
888
+ }, "data-limr-text": "", "data-source-start": segmentRange.start, "data-source-end": segmentRange.end, children: [
889
+ text,
890
+ markerAt.get(end)?.map((occurrence) => /* @__PURE__ */ jsx2(AnnotationMarker, { occurrence }, occurrence.id))
891
+ ] }, start);
892
+ }) });
893
+ }
894
+ function LiteralValue({ node, context, tokens }) {
895
+ const source = context.runtime.document.getSnapshot().source;
896
+ const mapping = useMemo(() => mapLiteral(source, node), [node]);
897
+ const value = literalValue(node);
898
+ const marks = context.marks.get(node) ?? emptyList;
899
+ const segments = tokens?.length ? tokens : [{ content: value, offset: 0 }];
900
+ return /* @__PURE__ */ jsx2(Fragment2, { children: segments.map((token, index) => {
901
+ const start = token.offset, end = start + token.content.length;
902
+ const mapped = { starts: mapping.starts.slice(start, end), ends: mapping.ends.slice(start, end), exact: mapping.exact };
903
+ const range = { start: mapped.starts[0] ?? rangeOf(node).start, end: mapped.ends.at(-1) ?? rangeOf(node).end };
904
+ const leaf = { type: "text", value: token.content, position: { start: { offset: range.start, line: 0, column: 0 }, end: { offset: range.end, line: 0, column: 0 } } };
905
+ return /* @__PURE__ */ jsx2(Text, { className: token.style ? "limr-code-token" : void 0, style: token.style, node: leaf, context, mapping: mapped, marks: marks.filter((mark) => mark.range.end > range.start && mark.range.end <= range.end) }, index);
906
+ }) });
907
+ }
908
+ function Atomic({ node, context, children, inline, blockElement }) {
909
+ const range = rangeOf(node);
910
+ const selected = useStoreSelector(context.runtime.interaction, (state) => state.selection?.raw.ranges.some((selection) => intersects(selection, range)) ?? false);
911
+ const highlights = context.highlights.filter((highlight) => !highlight.hidden && intersects(highlight.range, range));
912
+ const Tag = inline ? "span" : "div";
913
+ const image = ["image", "imageReference"].includes(node.type) || node.type === "component" && node.name === "img";
914
+ const corner = image || !inline;
915
+ const marks = [...context.marks.get(node) ?? [], ...corner ? context.afterMarks.get(node) ?? [] : []];
916
+ const markers = marks.map((occurrence) => /* @__PURE__ */ jsx2(AnnotationMarker, { occurrence }, occurrence.id));
917
+ return /* @__PURE__ */ jsxs2(Fragment2, { children: [
918
+ /* @__PURE__ */ jsxs2(
919
+ Tag,
920
+ {
921
+ ...blockAttributes(blockElement),
922
+ className: `limr-atomic${image ? " limr-atomic-image" : ""}${corner ? " limr-atomic-corner" : ""}${highlights.length ? " limr-atomic-highlight" : ""}`,
923
+ "data-selected": selected || void 0,
924
+ "data-limr-media": image ? "image" : void 0,
925
+ "data-limr-atomic": inline ? "inline" : "block",
926
+ "data-source-start": range.start,
927
+ "data-source-end": range.end,
928
+ style: { "--limr-highlight": highlights[0]?.color ?? "#f3ce7380" },
929
+ ref: (element) => {
930
+ if (element) context.runtime.bindings.set(element, { range, atomic: true });
931
+ blockElement?.ref(element);
932
+ },
933
+ children: [
934
+ children,
935
+ corner && !!marks.length && /* @__PURE__ */ jsx2("span", { className: "limr-corner-marks", "data-limr-ignore": "true", children: markers })
936
+ ]
937
+ }
938
+ ),
939
+ !corner && markers
940
+ ] });
941
+ }
942
+ function HeadingNode({ node, children, runtime, blockElement }) {
943
+ const id = (() => {
944
+ const doc = runtime.document.getSnapshot();
945
+ const offset = node.position?.start.offset ?? 0;
946
+ let lo = 0, hi = doc.headings.length;
947
+ while (lo < hi) {
948
+ const mid = lo + hi >>> 1;
949
+ if (doc.headings[mid].range.start < offset) lo = mid + 1;
950
+ else hi = mid;
951
+ }
952
+ return doc.headings[lo]?.range.start === offset ? doc.headings[lo].id : void 0;
953
+ })();
954
+ return createElement(`h${node.depth}`, { ...blockAttributes(blockElement), id, ref: (element) => {
955
+ if (id) runtime.registerHeading(id, element);
956
+ blockElement?.ref(element);
957
+ } }, children);
958
+ }
959
+ function Reference({ node, children, image }) {
960
+ const definition2 = useDocumentSelector((doc) => doc.definitions.get(String(node.identifier)));
961
+ if (!definition2) return /* @__PURE__ */ jsx2(Fragment2, { children: children || String(node.alt ?? node.label ?? "") });
962
+ return image ? /* @__PURE__ */ jsx2("img", { src: safeUrl(definition2.url, true), alt: String(node.alt ?? ""), title: definition2.title ? String(definition2.title) : void 0, loading: "lazy", decoding: "async" }) : /* @__PURE__ */ jsx2("a", { href: safeUrl(definition2.url), title: definition2.title ? String(definition2.title) : void 0, children });
963
+ }
964
+ function FootnoteReference({ node }) {
965
+ const runtime = useRuntime();
966
+ const identifier2 = String(node.identifier);
967
+ const number = useDocumentSelector((doc) => doc.footnoteOrder.indexOf(identifier2) + 1);
968
+ return /* @__PURE__ */ jsx2("sup", { "data-limr-ignore": "true", children: /* @__PURE__ */ jsx2("a", { href: `#${runtime.document.id}-fn-${encodeURIComponent(identifier2)}`, id: `${runtime.document.id}-fnref-${rangeOf(node).start}`, "aria-label": `Footnote ${number}`, children: number }) });
969
+ }
970
+ var ExtensionBoundary = class extends Component {
971
+ state = { failed: false };
972
+ static getDerivedStateFromError() {
973
+ return { failed: true };
974
+ }
975
+ componentDidCatch(_error, _info) {
976
+ }
977
+ componentDidUpdate(previous) {
978
+ if (this.state.failed && previous.fallback !== this.props.fallback) this.setState({ failed: false });
979
+ }
980
+ render() {
981
+ return this.state.failed ? /* @__PURE__ */ jsx2("pre", { className: "limr-extension-error", children: this.props.fallback }) : this.props.children;
982
+ }
983
+ };
984
+ function containsBlock(node) {
985
+ return node.type === "component" && !node.inline || ["math", "code", "list", "table", "blockquote"].includes(node.type) || (node.children?.some(containsBlock) ?? false);
986
+ }
987
+ function renderNode(node, context, index = 0, trailing) {
988
+ const { runtime } = context;
989
+ if (node.type === "text" && context.compact) return node.value ?? "";
990
+ const blockElement = node === context.block.node ? context.blockElement : void 0;
991
+ const key = `${node.type}-${node.position?.start.offset ?? index}-${index}`;
992
+ const childContext = node.type === "list" ? { ...context, tightList: !node.spread } : context;
993
+ const renderChildren = (nodes, options) => {
994
+ let last = -1;
995
+ nodes.forEach((child, i) => {
996
+ if (!["definition", "footnoteDefinition", "annotationDefinition"].includes(child.type)) last = i;
997
+ });
998
+ if (last < 0 && options?.trailing) return [/* @__PURE__ */ jsx2(Fragment, { children: options.trailing }, "trailing")];
999
+ return nodes.map((child, i) => renderNode(child, childContext, i, i === last ? options?.trailing : void 0));
1000
+ };
1001
+ const children = node.type === "table" ? [] : node.type === "listItem" && context.tightList ? (node.children ?? []).flatMap((child, index2) => child.type === "paragraph" ? renderChildren(child.children ?? []) : renderNode(child, context, index2)) : renderChildren(node.children ?? []);
1002
+ const Renderer = runtime.components[node.type === "component" ? node.name ?? "" : node.type];
1003
+ let element;
1004
+ if (Renderer) {
1005
+ const range = rangeOf(node);
1006
+ const renderAttribute = (name) => {
1007
+ const attribute = node.attributeNodes?.[name];
1008
+ if (!attribute) return String(node.attributes?.[name] ?? "");
1009
+ const range2 = rangeOf(attribute);
1010
+ return /* @__PURE__ */ jsx2(Text, { node: attribute, context, marks: context.occurrences.filter((item) => item.range.end > range2.start && item.range.end <= range2.end) });
1011
+ };
1012
+ element = /* @__PURE__ */ jsx2(ExtensionBoundary, { fallback: runtime.document.getSnapshot().source.slice(range.start, range.end), children: /* @__PURE__ */ jsx2(Renderer, { node, children, pending: context.block.pending, source: runtime.document.getSnapshot().source.slice(range.start, range.end), renderChildren, renderValue: (tokens) => /* @__PURE__ */ jsx2(LiteralValue, { node, context, tokens }), renderAttribute }) }, key);
1013
+ } else {
1014
+ switch (node.type) {
1015
+ case "text":
1016
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
1017
+ context.compact ? node.value ?? "" : /* @__PURE__ */ jsx2(Text, { node, context }),
1018
+ trailing
1019
+ ] }, key);
1020
+ case "paragraph":
1021
+ element = containsBlock(node) ? /* @__PURE__ */ jsxs2("div", { className: "limr-paragraph", children: [
1022
+ children,
1023
+ trailing
1024
+ ] }) : /* @__PURE__ */ jsxs2("p", { children: [
1025
+ children,
1026
+ trailing
1027
+ ] });
1028
+ trailing = void 0;
1029
+ break;
1030
+ case "heading":
1031
+ return /* @__PURE__ */ jsxs2(HeadingNode, { node, runtime, blockElement, children: [
1032
+ children,
1033
+ trailing
1034
+ ] }, key);
1035
+ case "strong":
1036
+ element = /* @__PURE__ */ jsx2("strong", { children });
1037
+ break;
1038
+ case "emphasis":
1039
+ element = /* @__PURE__ */ jsx2("em", { children });
1040
+ break;
1041
+ case "delete":
1042
+ element = /* @__PURE__ */ jsx2("del", { children });
1043
+ break;
1044
+ case "inlineCode":
1045
+ element = /* @__PURE__ */ jsx2("code", { className: "limr-inline-code", "data-limr-inline-syntax": "", "data-source-start": rangeOf(node).start, "data-source-end": rangeOf(node).end, children: /* @__PURE__ */ jsx2(LiteralValue, { node, context }) });
1046
+ break;
1047
+ case "code":
1048
+ element = /* @__PURE__ */ jsx2("pre", { children: /* @__PURE__ */ jsx2("code", { children: /* @__PURE__ */ jsx2(LiteralValue, { node, context }) }) });
1049
+ break;
1050
+ case "math":
1051
+ case "inlineMath":
1052
+ element = /* @__PURE__ */ jsx2("code", { children: node.value });
1053
+ break;
1054
+ case "blockquote":
1055
+ element = /* @__PURE__ */ jsxs2("blockquote", { className: "limr-note", children: [
1056
+ /* @__PURE__ */ jsx2("div", { className: "limr-card-label", "data-limr-ignore": "true", children: runtime.locale.note }),
1057
+ /* @__PURE__ */ jsx2("div", { className: "limr-block-content", children })
1058
+ ] });
1059
+ break;
1060
+ case "list":
1061
+ element = node.ordered ? /* @__PURE__ */ jsx2("ol", { start: Number(node.start ?? 1), children }) : /* @__PURE__ */ jsx2("ul", { children });
1062
+ break;
1063
+ case "listItem":
1064
+ element = /* @__PURE__ */ jsxs2("li", { className: typeof node.checked === "boolean" ? "limr-task-item" : void 0, children: [
1065
+ typeof node.checked === "boolean" && /* @__PURE__ */ jsx2("input", { type: "checkbox", checked: node.checked, disabled: true, "aria-label": "Task" }),
1066
+ children
1067
+ ] });
1068
+ break;
1069
+ case "link":
1070
+ element = /* @__PURE__ */ jsx2("a", { href: safeUrl(node.url), title: node.title ? String(node.title) : void 0, children });
1071
+ break;
1072
+ case "image":
1073
+ element = /* @__PURE__ */ jsx2("img", { src: safeUrl(node.url, true), alt: String(node.alt ?? ""), title: node.title ? String(node.title) : void 0, loading: "lazy", decoding: "async" });
1074
+ break;
1075
+ case "linkReference":
1076
+ element = /* @__PURE__ */ jsx2(Reference, { node, image: false, children });
1077
+ break;
1078
+ case "imageReference":
1079
+ element = /* @__PURE__ */ jsx2(Reference, { node, image: true, children });
1080
+ break;
1081
+ case "thematicBreak":
1082
+ element = /* @__PURE__ */ jsx2("hr", {});
1083
+ break;
1084
+ case "break":
1085
+ element = /* @__PURE__ */ jsx2("br", {});
1086
+ break;
1087
+ case "table": {
1088
+ const rows = node.children ?? [], alignment = node.align;
1089
+ element = /* @__PURE__ */ jsx2("div", { className: "limr-table-scroll", children: /* @__PURE__ */ jsxs2("table", { children: [
1090
+ /* @__PURE__ */ jsx2("thead", { children: rows.slice(0, 1).map((row, i) => /* @__PURE__ */ jsx2("tr", { children: row.children?.map((cell, j) => /* @__PURE__ */ jsx2("th", { style: { textAlign: alignment?.[j] }, children: renderChildren(cell.children ?? []) }, j)) }, i)) }),
1091
+ /* @__PURE__ */ jsx2("tbody", { children: rows.slice(1).map((row, i) => /* @__PURE__ */ jsx2("tr", { children: row.children?.map((cell, j) => /* @__PURE__ */ jsx2("td", { style: { textAlign: alignment?.[j] }, children: renderChildren(cell.children ?? []) }, j)) }, i)) })
1092
+ ] }) });
1093
+ break;
1094
+ }
1095
+ case "definition":
1096
+ case "footnoteDefinition":
1097
+ case "annotationDefinition":
1098
+ return null;
1099
+ case "footnoteReference":
1100
+ return /* @__PURE__ */ jsxs2(Fragment, { children: [
1101
+ /* @__PURE__ */ jsx2(FootnoteReference, { node }),
1102
+ trailing
1103
+ ] }, key);
1104
+ case "annotationReference": {
1105
+ const Tag = node.inline ? "span" : "div";
1106
+ element = /* @__PURE__ */ jsxs2(Tag, { children: [
1107
+ children,
1108
+ /* @__PURE__ */ jsx2(AnnotationMarker, { occurrence: { id: `${runtime.document.id}-ref-${rangeOf(node).start}`, range: rangeOf(node), annotationIds: node.annotationIds, embedded: true } })
1109
+ ] });
1110
+ break;
1111
+ }
1112
+ case "html":
1113
+ element = /* @__PURE__ */ jsx2("span", { className: "limr-literal", children: node.value });
1114
+ break;
1115
+ case "component":
1116
+ element = children;
1117
+ break;
1118
+ default:
1119
+ element = children.length ? children : node.value ?? null;
1120
+ }
1121
+ }
1122
+ const atomic2 = node.selection === "atomic" || ["math", "inlineMath", "image", "imageReference", "html"].includes(node.type);
1123
+ const corner = atomic2 && (!node.inline && !["inlineCode", "inlineMath", "html"].includes(node.type) || ["image", "imageReference"].includes(node.type) || node.name === "img");
1124
+ const after = corner ? void 0 : context.afterMarks.get(node);
1125
+ const withMarkers = (element2) => after?.length || trailing ? /* @__PURE__ */ jsxs2(Fragment, { children: [
1126
+ element2,
1127
+ after?.map((occurrence) => /* @__PURE__ */ jsx2(AnnotationMarker, { occurrence }, occurrence.id)),
1128
+ trailing
1129
+ ] }, key) : element2;
1130
+ if (atomic2) return withMarkers(/* @__PURE__ */ jsx2(Atomic, { node, context, blockElement, inline: node.inline || ["inlineCode", "inlineMath", "image", "imageReference", "html"].includes(node.type), children: element }, key));
1131
+ if (blockElement) {
1132
+ const attributes = { ...blockAttributes(blockElement), ref: blockElement.ref };
1133
+ return withMarkers(isValidElement(element) && typeof element.type === "string" ? cloneElement(element, { ...attributes, key }) : /* @__PURE__ */ jsx2("div", { ...attributes, children: element }, key));
1134
+ }
1135
+ return withMarkers(isValidElement(element) ? cloneElement(element, { key }) : /* @__PURE__ */ jsx2(Fragment, { children: element }, key));
1136
+ }
1137
+ var BlockView = memo(function BlockView2({ block, runtime, components, extensions, decorations, footnoteId }) {
1138
+ const element = useRef2(null);
1139
+ const clearBindings = useRef2(void 0);
1140
+ const { occurrences } = decorations;
1141
+ const highlights = useMemo(() => decorations.highlights.filter((highlight) => !highlight.occurrenceId), [decorations.highlights]);
1142
+ const root = useMemo(() => footnoteId ? { ...block.node, type: "listItem" } : block.node, [block, footnoteId]);
1143
+ const texts = useMemo(() => compactTextNodes(root, runtime.components), [root, runtime, components, extensions]);
1144
+ const compact = !!texts && !occurrences.length && !highlights.length;
1145
+ const observe = useCallback((next) => {
1146
+ clearBindings.current?.();
1147
+ clearBindings.current = void 0;
1148
+ if (element.current) runtime.textBinders.delete(element.current);
1149
+ if (element.current && element.current !== next) runtime.unobserveBlock(element.current);
1150
+ element.current = next;
1151
+ runtime.observeBlock(next);
1152
+ if (next && compact && texts.length) runtime.textBinders.set(next, () => {
1153
+ clearBindings.current = bindCompactText(next, texts, runtime);
1154
+ });
1155
+ }, [runtime, compact, texts]);
1156
+ const { marks, afterMarks } = useMemo(() => {
1157
+ const map = /* @__PURE__ */ new Map();
1158
+ const after = /* @__PURE__ */ new Map();
1159
+ if (!occurrences.length) return { marks: map, afterMarks: after };
1160
+ const leaves = [];
1161
+ const attributes = [];
1162
+ const paths = /* @__PURE__ */ new Map();
1163
+ const outside = /* @__PURE__ */ new Set(["strong", "emphasis", "delete", "link", "linkReference", "inlineCode", "code", "math", "inlineMath", "image", "imageReference", "html"]);
1164
+ function collect(node, ancestors = []) {
1165
+ if (node.attributeNodes) attributes.push(...Object.values(node.attributeNodes));
1166
+ const path = [...ancestors, node];
1167
+ if (node.selection === "atomic" || ["text", "inlineCode", "code", "math", "inlineMath", "image", "imageReference", "html"].includes(node.type)) {
1168
+ leaves.push(node);
1169
+ paths.set(node, path);
1170
+ } else node.children?.forEach((child) => collect(child, path));
1171
+ }
1172
+ collect(block.node);
1173
+ for (const occurrence of occurrences) {
1174
+ const target = [...leaves].reverse().find((node) => rangeOf(node).start < occurrence.range.end) ?? leaves[0];
1175
+ const image = target && (["image", "imageReference"].includes(target.type) || target.name === "img") && rangeOf(target).end >= occurrence.range.end;
1176
+ if (!image && attributes.some((attribute) => {
1177
+ const range = rangeOf(attribute);
1178
+ return occurrence.range.end > range.start && occurrence.range.end <= range.end;
1179
+ })) continue;
1180
+ if (target) {
1181
+ const outer = paths.get(target)?.find((node2) => (outside.has(node2.type) || node2.selection === "atomic") && rangeOf(node2).end <= occurrence.range.end);
1182
+ const destination = outer ? after : map, node = outer ?? target;
1183
+ destination.set(node, [...destination.get(node) ?? [], occurrence]);
1184
+ }
1185
+ }
1186
+ return { marks: map, afterMarks: after };
1187
+ }, [block, occurrences]);
1188
+ if (!footnoteId && ["definition", "footnoteDefinition", "annotationDefinition"].includes(block.node.type)) return null;
1189
+ const context = { runtime, block, marks, afterMarks, highlights, occurrences, compact, blockElement: { id: block.id, range: block.range, pending: block.pending, ref: observe } };
1190
+ if (footnoteId) return /* @__PURE__ */ jsx2("li", { id: `${runtime.document.id}-fn-${encodeURIComponent(footnoteId)}`, ...blockAttributes(context.blockElement), ref: observe, children: block.node.children?.map((child, index) => renderNode(child, { ...context, blockElement: void 0 }, index)) });
1191
+ return renderNode(block.node, context);
1192
+ });
1193
+ function Footnotes() {
1194
+ const runtime = useRuntime();
1195
+ const doc = useDocumentSelector((snapshot) => snapshot);
1196
+ const components = useStoreSelector(runtime.configuration, (config) => config.components);
1197
+ const extensions = useStoreSelector(runtime.configuration, (config) => config.extensions);
1198
+ const decorations = useStoreSelector(runtime.decorations, (state) => state.byBlock);
1199
+ const blocks = useMemo(() => new Map(doc.blocks.filter((block) => block.node.type === "footnoteDefinition").map((block) => [String(block.node.identifier), block])), [doc.blocks]);
1200
+ if (!doc.footnoteOrder.length) return null;
1201
+ return /* @__PURE__ */ jsxs2("section", { className: "limr-footnotes", "aria-label": runtime.locale.footnotes, children: [
1202
+ /* @__PURE__ */ jsx2("hr", {}),
1203
+ /* @__PURE__ */ jsx2("ol", { children: doc.footnoteOrder.map((id) => {
1204
+ const node = doc.footnotes.get(id);
1205
+ if (!node) return null;
1206
+ const block = blocks.get(id) ?? { id: `${doc.id}-fn-${id}`, range: rangeOf(node), node, pending: false };
1207
+ return /* @__PURE__ */ jsx2(BlockView, { block, runtime, components, extensions, footnoteId: id, decorations: decorations.get(block.id) ?? emptyDecorations }, id);
1208
+ }) })
1209
+ ] });
1210
+ }
1211
+
1212
+ // src/react/selection.ts
1213
+ import { useEffect as useEffect2 } from "react";
1214
+
1215
+ // src/react/source-geometry.ts
1216
+ function flowOf(element, container) {
1217
+ const known = element.closest("pre,p,figcaption,li,th,td,h1,h2,h3,h4,h5,h6,.limr-choice-text,.limr-definition-title,.limr-question-title,.limr-block-content");
1218
+ return known && container.contains(known) ? known : element.closest("[data-limr-block]") ?? container;
1219
+ }
1220
+ function leavesIn(block, runtime) {
1221
+ runtime.prepareTextBindings(block);
1222
+ const result = [];
1223
+ const visit = (node, inherited) => {
1224
+ if (node instanceof HTMLElement) {
1225
+ if (node !== block && node.hasAttribute("data-limr-document") || node.hasAttribute("inert")) return;
1226
+ const marker = node.dataset.limrMarker;
1227
+ const atomic2 = node.dataset.limrAtomic;
1228
+ if (marker || atomic2) {
1229
+ const image = node.dataset.limrMedia === "image";
1230
+ result.push({ node, kind: marker ? "marker" : image ? "image" : atomic2 === "block" ? "block" : "inline", range: { start: Number(node.dataset.sourceStart), end: Number(node.dataset.sourceEnd) }, flow: image ? node : flowOf(node, runtime.content), offset: 0 });
1231
+ return;
1232
+ }
1233
+ if (node.hasAttribute("data-limr-ignore")) return;
1234
+ const binding = runtime.bindings.get(node);
1235
+ if (binding) inherited = { binding, offset: 0 };
1236
+ }
1237
+ if (node.nodeType === Node.TEXT_NODE) {
1238
+ const binding = runtime.bindings.get(node) ?? inherited?.binding;
1239
+ const offset = runtime.bindings.has(node) ? 0 : inherited?.offset ?? 0;
1240
+ const length = node.textContent?.length ?? 0;
1241
+ if (binding?.resolve && length) result.push({ node, kind: "text", range: { start: binding.resolve(offset, "start"), end: binding.resolve(offset + length, "end") }, flow: flowOf(node.parentElement, runtime.content), binding, offset });
1242
+ if (inherited) inherited.offset += length;
1243
+ return;
1244
+ }
1245
+ node.childNodes.forEach((child) => visit(child, inherited));
1246
+ };
1247
+ visit(block);
1248
+ return result;
1249
+ }
1250
+ function textRange(leaf, source, viewport) {
1251
+ const node = leaf.node, length = node.length;
1252
+ const resolve = leaf.binding.resolve;
1253
+ let lo = 0, hi = length;
1254
+ while (lo < hi) {
1255
+ const mid = lo + hi >>> 1;
1256
+ if (resolve(leaf.offset + mid + 1, "end") <= source.start) lo = mid + 1;
1257
+ else hi = mid;
1258
+ }
1259
+ let start = lo;
1260
+ lo = start;
1261
+ hi = length;
1262
+ while (lo < hi) {
1263
+ const mid = lo + hi >>> 1;
1264
+ if (resolve(leaf.offset + mid, "start") < source.end) lo = mid + 1;
1265
+ else hi = mid;
1266
+ }
1267
+ if (start === lo) return null;
1268
+ let end = lo;
1269
+ const range = document.createRange();
1270
+ if (viewport && end - start > 1024) {
1271
+ range.setStart(node, start);
1272
+ range.setEnd(node, end);
1273
+ const box = range.getBoundingClientRect();
1274
+ if (box.height > viewport.bottom - viewport.top + 80) {
1275
+ lo = start;
1276
+ hi = end;
1277
+ while (lo < hi) {
1278
+ const mid = lo + hi >>> 1;
1279
+ range.setStart(node, mid);
1280
+ range.setEnd(node, mid + 1);
1281
+ if (range.getBoundingClientRect().bottom < viewport.top) lo = mid + 1;
1282
+ else hi = mid;
1283
+ }
1284
+ start = lo;
1285
+ hi = end;
1286
+ while (lo < hi) {
1287
+ const mid = lo + hi >>> 1;
1288
+ range.setStart(node, mid);
1289
+ range.setEnd(node, mid + 1);
1290
+ if (range.getBoundingClientRect().top <= viewport.bottom) lo = mid + 1;
1291
+ else hi = mid;
1292
+ }
1293
+ end = lo;
1294
+ }
1295
+ }
1296
+ if (start === end) return null;
1297
+ range.setStart(node, start);
1298
+ range.setEnd(node, end);
1299
+ return range;
1300
+ }
1301
+ function sourceRangeStartRect(runtime, source) {
1302
+ for (const block of runtime.document.getSnapshot().blocks) {
1303
+ if (!intersects(block.range, source)) continue;
1304
+ const element = runtime.blocks.get(block.id);
1305
+ if (!element) continue;
1306
+ for (const leaf of leavesIn(element, runtime)) {
1307
+ if (leaf.kind === "marker" || !intersects(leaf.range, source)) continue;
1308
+ if (leaf.kind === "text") {
1309
+ const range = textRange(leaf, source);
1310
+ if (!range) continue;
1311
+ const node = leaf.node, end = range.endOffset;
1312
+ for (let start = range.startOffset; start < end; ) {
1313
+ const next = Math.min(end, start + (node.data.codePointAt(start) > 65535 ? 2 : 1));
1314
+ range.setStart(node, start);
1315
+ range.setEnd(node, next);
1316
+ const rect = range.getBoundingClientRect();
1317
+ if (rect.width && rect.height) return rect;
1318
+ start = next;
1319
+ }
1320
+ } else {
1321
+ const node = leaf.node;
1322
+ const rect = (node.querySelector(leaf.kind === "image" ? "img" : "[data-limr-selection-surface]") ?? node).getBoundingClientRect();
1323
+ if (rect.width && rect.height) return rect;
1324
+ }
1325
+ }
1326
+ }
1327
+ return null;
1328
+ }
1329
+
1330
+ // src/react/selection.ts
1331
+ function visualSelection(runtime, native, options) {
1332
+ if (![...runtime.content.querySelectorAll('[data-limr-selection-order="visual"]')].some((element) => native.intersectsNode(element))) return;
1333
+ const blocks = [...runtime.blocks.values()].filter((block) => native.intersectsNode(block));
1334
+ blocks.sort((a, b) => a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
1335
+ const leaves = blocks.flatMap((block) => leavesIn(block, runtime)).filter((leaf) => leaf.kind !== "marker");
1336
+ const selected = [];
1337
+ for (const leaf of leaves) {
1338
+ if (!native.intersectsNode(leaf.node)) continue;
1339
+ if (leaf.kind !== "text") {
1340
+ selected.push(leaf.range);
1341
+ continue;
1342
+ }
1343
+ const node = leaf.node;
1344
+ const start = native.startContainer === node ? native.startOffset : 0;
1345
+ const end = native.endContainer === node ? native.endOffset : node.length;
1346
+ if (start < end) selected.push({ start: leaf.binding.resolve(leaf.offset + start, "start"), end: leaf.binding.resolve(leaf.offset + end, "end") });
1347
+ }
1348
+ if (!selected.length) return;
1349
+ const sourceOrder = leaves.map((leaf) => leaf.range).sort((a, b) => a.end - b.end);
1350
+ const ranges = [];
1351
+ for (const range of selected) {
1352
+ const previous = ranges.at(-1);
1353
+ let lo = 0, hi = sourceOrder.length;
1354
+ if (previous) while (lo < hi) {
1355
+ const mid = lo + hi >>> 1;
1356
+ if (sourceOrder[mid].end <= previous.end) lo = mid + 1;
1357
+ else hi = mid;
1358
+ }
1359
+ if (previous && range.start >= previous.end && (!sourceOrder[lo] || sourceOrder[lo].start >= range.start)) previous.end = range.end;
1360
+ else ranges.push({ ...range });
1361
+ }
1362
+ const snapshot = runtime.document.getSnapshot();
1363
+ const selections = ranges.map((range) => selectionFromRange(snapshot, range, options));
1364
+ const combine = (key) => {
1365
+ const seen = /* @__PURE__ */ new Set();
1366
+ const ranges2 = selections.flatMap((selection) => selection[key].ranges).filter((range) => {
1367
+ const key2 = `${range.start}:${range.end}`;
1368
+ if (seen.has(key2)) return false;
1369
+ seen.add(key2);
1370
+ return true;
1371
+ });
1372
+ return { ranges: ranges2, sourceText: ranges2.map((range) => snapshot.source.slice(range.start, range.end)).join("\n\n") };
1373
+ };
1374
+ return { ...selections[0], raw: combine("raw"), syntax: combine("syntax"), blocks: combine("blocks") };
1375
+ }
1376
+ function useSelectionTracking(runtime, enabled) {
1377
+ useEffect2(() => {
1378
+ const container = runtime.content;
1379
+ if (!container || !enabled) return;
1380
+ let frame = 0, dragging = false;
1381
+ let previous;
1382
+ function resolve(node, offset, edge) {
1383
+ let element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1384
+ if (!element || element.closest("[data-limr-document]") !== container || element.closest("[data-limr-ignore]")) return null;
1385
+ runtime.prepareTextBindings(element);
1386
+ const native = node.nodeType === Node.TEXT_NODE ? runtime.bindings.get(node) : void 0;
1387
+ if (native?.resolve) return { offset: native.resolve(offset, edge), atomic: false, exact: native.exact !== false };
1388
+ while (element && element !== container) {
1389
+ const binding = runtime.bindings.get(element);
1390
+ if (binding) {
1391
+ if (binding.atomic) return { offset: edge === "start" ? binding.range.start : binding.range.end, atomic: true, exact: true };
1392
+ const range = document.createRange();
1393
+ range.setStart(element, 0);
1394
+ try {
1395
+ range.setEnd(node, offset);
1396
+ } catch {
1397
+ return null;
1398
+ }
1399
+ const localOffset = range.toString().length;
1400
+ return { offset: binding.resolve?.(localOffset, edge) ?? (edge === "start" ? binding.range.start : binding.range.end), atomic: false, exact: binding.exact !== false };
1401
+ }
1402
+ element = element.parentElement;
1403
+ }
1404
+ const children = node.nodeType === Node.ELEMENT_NODE ? Array.from(node.childNodes) : [];
1405
+ const candidates = edge === "start" ? children.slice(offset) : children.slice(0, offset).reverse();
1406
+ const descend = (candidate) => {
1407
+ if (candidate.nodeType === Node.TEXT_NODE && candidate.textContent) return resolve(candidate, edge === "start" ? 0 : candidate.textContent.length, edge);
1408
+ if (candidate instanceof Element) {
1409
+ if (candidate.hasAttribute("data-limr-ignore") || candidate.hasAttribute("inert")) return null;
1410
+ const binding = runtime.bindings.get(candidate);
1411
+ if (binding?.atomic) return { offset: edge === "start" ? binding.range.start : binding.range.end, atomic: true, exact: true };
1412
+ }
1413
+ const list = Array.from(candidate.childNodes);
1414
+ if (edge === "end") list.reverse();
1415
+ for (const child of list) {
1416
+ const result = descend(child);
1417
+ if (result) return result;
1418
+ }
1419
+ return null;
1420
+ };
1421
+ for (const child of candidates) {
1422
+ const result = descend(child);
1423
+ if (result) return result;
1424
+ }
1425
+ return null;
1426
+ }
1427
+ function process() {
1428
+ frame = 0;
1429
+ if (!dragging && document.activeElement instanceof Element && document.activeElement.closest("[data-limr-selection-ui]")) return;
1430
+ const selection = window.getSelection();
1431
+ if (!selection || selection.isCollapsed || !selection.rangeCount) {
1432
+ if (!(document.activeElement instanceof Element) || !document.activeElement.closest("[data-limr-selection-ui]")) {
1433
+ previous = void 0;
1434
+ runtime.selectionRange = null;
1435
+ runtime.updateInteraction({ selection: null });
1436
+ }
1437
+ return;
1438
+ }
1439
+ const range = selection.getRangeAt(0);
1440
+ const revision = runtime.document.getSnapshot().revision;
1441
+ if (runtime.interaction.get().selection && previous?.startNode === range.startContainer && previous.start === range.startOffset && previous.endNode === range.endContainer && previous.end === range.endOffset && previous.revision === revision && previous.settled === !dragging) return;
1442
+ const start = resolve(range.startContainer, range.startOffset, "start");
1443
+ const end = resolve(range.endContainer, range.endOffset, "end");
1444
+ if (!start || !end) {
1445
+ previous = void 0;
1446
+ runtime.selectionRange = null;
1447
+ runtime.updateInteraction({ selection: null });
1448
+ return;
1449
+ }
1450
+ previous = { startNode: range.startContainer, start: range.startOffset, endNode: range.endContainer, end: range.endOffset, revision, settled: !dragging };
1451
+ runtime.selectionRange = range.cloneRange();
1452
+ runtime.highlightReference = null;
1453
+ const options = {
1454
+ text: selection.toString(),
1455
+ settled: !dragging,
1456
+ quality: !start.exact || !end.exact ? "unmapped" : start.atomic || end.atomic ? "atomic" : "exact"
1457
+ };
1458
+ runtime.updateInteraction({ activeHighlight: null, selection: visualSelection(runtime, range, options) ?? selectionFromRange(runtime.document.getSnapshot(), { start: start.offset, end: end.offset }, options) });
1459
+ }
1460
+ const schedule = () => {
1461
+ if (!frame) frame = requestAnimationFrame(process);
1462
+ };
1463
+ const down = () => {
1464
+ dragging = true;
1465
+ };
1466
+ const up = () => {
1467
+ dragging = false;
1468
+ schedule();
1469
+ };
1470
+ document.addEventListener("selectionchange", schedule);
1471
+ container.addEventListener("pointerdown", down);
1472
+ document.addEventListener("pointerup", up);
1473
+ document.addEventListener("pointercancel", up);
1474
+ document.addEventListener("keyup", schedule);
1475
+ if (window.getSelection()?.isCollapsed === false) schedule();
1476
+ return () => {
1477
+ cancelAnimationFrame(frame);
1478
+ document.removeEventListener("selectionchange", schedule);
1479
+ container.removeEventListener("pointerdown", down);
1480
+ document.removeEventListener("pointerup", up);
1481
+ document.removeEventListener("pointercancel", up);
1482
+ document.removeEventListener("keyup", schedule);
1483
+ };
1484
+ }, [runtime, enabled]);
1485
+ }
1486
+
1487
+ // src/react/selection-paint.tsx
1488
+ import { useEffect as useEffect3, useRef as useRef3 } from "react";
1489
+ import { jsx as jsx3 } from "react/jsx-runtime";
1490
+ function rectangles(leaves, source, viewport, measure) {
1491
+ const raw = [];
1492
+ const geometry = (leaf, rect, reference) => {
1493
+ const flowMetrics = measure(leaf.flow);
1494
+ const own = measure(reference?.element ?? (leaf.kind === "text" ? leaf.node.parentElement : leaf.flow));
1495
+ const baseline = reference ? reference.rect.top + own.ascent : leaf.kind === "text" ? rect.top + own.ascent : rect.bottom - flowMetrics.descent;
1496
+ return { left: rect.left, top: baseline - flowMetrics.ascent, width: rect.width, height: flowMetrics.height, baseline, flow: leaf.flow };
1497
+ };
1498
+ const neighbor = (index, direction) => {
1499
+ for (let at = index + direction; at >= 0 && at < leaves.length; at += direction) {
1500
+ const candidate = leaves[at];
1501
+ if (candidate.flow !== leaves[index].flow) return;
1502
+ if (candidate.kind === "text") {
1503
+ const value = candidate.node.textContent ?? "";
1504
+ if (value.trim()) return candidate;
1505
+ if (!value.includes("\n")) continue;
1506
+ }
1507
+ if (candidate.kind !== "marker") return;
1508
+ }
1509
+ };
1510
+ const edgeRect = (leaf, edge) => {
1511
+ const node = leaf.node;
1512
+ const range = document.createRange();
1513
+ const offset = edge === "first" ? 0 : Math.max(0, node.length - 1);
1514
+ range.setStart(node, offset);
1515
+ range.setEnd(node, Math.min(node.length, offset + 1));
1516
+ return range.getBoundingClientRect();
1517
+ };
1518
+ const referenceFor = (index, rect) => {
1519
+ const left = neighbor(index, -1), right = neighbor(index, 1);
1520
+ const candidates = [left && { rect: edgeRect(left, "last"), element: left.node.parentElement }, right && { rect: edgeRect(right, "first"), element: right.node.parentElement }].filter((value) => !!value);
1521
+ candidates.sort((a, b) => Math.abs(a.rect.bottom - rect.bottom) - Math.abs(b.rect.bottom - rect.bottom));
1522
+ const nearest = candidates[0];
1523
+ return nearest && Math.abs(nearest.rect.bottom - rect.bottom) < Math.max(rect.height, nearest.rect.height) ? nearest : void 0;
1524
+ };
1525
+ let first = 0, last = leaves.length;
1526
+ if (leaves.length > 80 && leaves[0].flow.tagName === "PRE" && leaves.at(-1)?.flow === leaves[0].flow) {
1527
+ const boxAt = (index) => {
1528
+ const leaf = leaves[index];
1529
+ if (leaf.kind !== "text") return leaf.node.getBoundingClientRect();
1530
+ const range = document.createRange();
1531
+ range.selectNodeContents(leaf.node);
1532
+ return range.getBoundingClientRect();
1533
+ };
1534
+ let lo = 0, hi = leaves.length;
1535
+ while (lo < hi) {
1536
+ const mid = lo + hi >>> 1;
1537
+ if (boxAt(mid).bottom < viewport.top) lo = mid + 1;
1538
+ else hi = mid;
1539
+ }
1540
+ first = lo;
1541
+ hi = leaves.length;
1542
+ while (lo < hi) {
1543
+ const mid = lo + hi >>> 1;
1544
+ if (boxAt(mid).top <= viewport.bottom) lo = mid + 1;
1545
+ else hi = mid;
1546
+ }
1547
+ last = lo;
1548
+ }
1549
+ for (let index = first; index < last; index++) {
1550
+ const leaf = leaves[index];
1551
+ if (leaf.kind === "marker") {
1552
+ const left = neighbor(index, -1), right = neighbor(index, 1);
1553
+ if (!left || !right || source.start >= left.range.end || source.end <= right.range.start) continue;
1554
+ const rect = leaf.node.getBoundingClientRect();
1555
+ if (!rect.width || !rect.height || rect.bottom < viewport.top || rect.top > viewport.bottom) continue;
1556
+ const item = geometry(leaf, rect, referenceFor(index, rect));
1557
+ raw.push({ ...item, marker: leaf.node.dataset.limrMarker });
1558
+ } else if (intersects(leaf.range, source)) {
1559
+ if (leaf.kind === "text") {
1560
+ const range = textRange(leaf, source, viewport);
1561
+ const shell = leaf.node.parentElement?.closest("[data-limr-inline-syntax]");
1562
+ const edges = shell ? Array.from(shell.getClientRects()) : [];
1563
+ const css = shell && getComputedStyle(shell);
1564
+ for (const rect of range?.getClientRects() ?? []) if (rect.width && rect.height && rect.bottom >= viewport.top && rect.top <= viewport.bottom) {
1565
+ const item = geometry(leaf, rect), first2 = edges[0], last2 = edges.at(-1);
1566
+ if (shell && css && first2 && source.start <= Number(shell.dataset.sourceStart) && Math.abs(first2.top - rect.top) < rect.height && Math.abs(rect.left - first2.left - parseFloat(css.paddingLeft)) < 1) {
1567
+ item.width += item.left - first2.left;
1568
+ item.left = first2.left;
1569
+ }
1570
+ if (shell && css && last2 && source.end >= Number(shell.dataset.sourceEnd) && Math.abs(last2.top - rect.top) < rect.height && Math.abs(last2.right - parseFloat(css.paddingRight) - rect.right) < 1) item.width = last2.right - item.left;
1571
+ raw.push(item);
1572
+ }
1573
+ } else {
1574
+ const element = leaf.node;
1575
+ const surface = leaf.kind === "image" ? element.querySelector("img") ?? element : leaf.kind === "block" ? element.querySelector("[data-limr-selection-surface]") ?? element : element;
1576
+ const rect = surface.getBoundingClientRect();
1577
+ if (!rect.width || !rect.height || rect.bottom < viewport.top || rect.top > viewport.bottom) continue;
1578
+ if (leaf.kind === "block" || leaf.kind === "image") raw.push({ left: rect.left, top: rect.top, width: rect.width, height: rect.height, atomic: true, image: leaf.kind === "image", baseline: rect.bottom, flow: leaf.kind === "image" ? element : surface, radius: getComputedStyle(surface).borderRadius });
1579
+ else {
1580
+ const item = geometry(leaf, rect, referenceFor(index, rect));
1581
+ raw.push({ ...item, atomic: true });
1582
+ }
1583
+ }
1584
+ }
1585
+ }
1586
+ const lines = /* @__PURE__ */ new Map();
1587
+ const aligned = raw.map((rect) => {
1588
+ if (rect.image || rect.atomic && rect.height > measure(rect.flow).height * 1.5) return rect;
1589
+ let flow = lines.get(rect.flow);
1590
+ if (!flow) {
1591
+ flow = /* @__PURE__ */ new Map();
1592
+ lines.set(rect.flow, flow);
1593
+ }
1594
+ const key = Math.floor(rect.baseline / 3);
1595
+ let line = [flow.get(key), flow.get(key - 1), flow.get(key + 1)].find((line2) => line2 && Math.abs(line2.baseline - rect.baseline) < 3);
1596
+ if (!line) {
1597
+ line = rect;
1598
+ flow.set(key, line);
1599
+ }
1600
+ return { ...rect, top: line.top, height: line.height };
1601
+ });
1602
+ const bridges = [];
1603
+ for (let i = 1; i < aligned.length; i++) {
1604
+ const left = aligned[i - 1], right = aligned[i];
1605
+ const gap = right.left - left.left - left.width;
1606
+ if (left.flow === right.flow && Math.abs(left.top - right.top) < 0.5 && gap > 0.1 && gap < left.height * 0.6) bridges.push({ left: left.left + left.width, top: left.top, width: gap, height: left.height, flow: left.flow });
1607
+ }
1608
+ return [...aligned, ...bridges];
1609
+ }
1610
+ function SelectionPaint({ runtime, interactive = true }) {
1611
+ const layer = useRef3(null);
1612
+ useEffect3(() => {
1613
+ const container = runtime.content, paint = layer.current;
1614
+ if (!container || !paint) return;
1615
+ let frame = 0, translating = false;
1616
+ let leavesCache = /* @__PURE__ */ new WeakMap();
1617
+ let metrics = /* @__PURE__ */ new WeakMap();
1618
+ const fontMetrics = /* @__PURE__ */ new Map();
1619
+ let blocks;
1620
+ let snapshot = runtime.document.getSnapshot();
1621
+ let lastSelection = runtime.interaction.get().selection;
1622
+ let lastDecorations = runtime.decorations.get().byBlock;
1623
+ let lastHovered = runtime.interaction.get().hoveredHighlight;
1624
+ let lastActive = runtime.interaction.get().activeHighlight;
1625
+ let lastAnnotation = runtime.interaction.get().active;
1626
+ let lastHoveredAnnotation = runtime.interaction.get().hovered;
1627
+ const highlightLayers = /* @__PURE__ */ new Map();
1628
+ let hits = [];
1629
+ const highlightRects = (id) => [...highlightLayers.values()].flatMap((layer2) => Array.from(layer2.children).filter((item) => item.dataset.paint === id).map((item) => item.getBoundingClientRect()));
1630
+ const focusedRange = () => {
1631
+ const state = runtime.interaction.get(), decorations = runtime.decorations.get();
1632
+ return decorations.referenceRanges.get(state.hovered ?? "") ?? (state.activeHighlight ? decorations.highlights.get(state.activeHighlight)?.range : void 0) ?? decorations.referenceRanges.get(state.active ?? "");
1633
+ };
1634
+ const referenceActive = (occurrenceId) => {
1635
+ const state = runtime.interaction.get(), decorations = runtime.decorations.get();
1636
+ if (occurrenceId === state.hovered) return true;
1637
+ if (occurrenceId !== state.active) return false;
1638
+ const hovered = decorations.highlights.get(`reference-${state.hovered}`);
1639
+ return !hovered?.occurrenceId || !sameRange(hovered.range, decorations.referenceRanges.get(occurrenceId));
1640
+ };
1641
+ const feedback = () => {
1642
+ const state = runtime.interaction.get();
1643
+ const decorations = runtime.decorations.get();
1644
+ const focused = focusedRange();
1645
+ for (const layer2 of highlightLayers.values()) for (const item of layer2.children) {
1646
+ item.toggleAttribute("data-hovered", item.dataset.paint === state.hoveredHighlight);
1647
+ const highlight = decorations.highlights.get(item.dataset.paint ?? "");
1648
+ if (highlight?.occurrenceId) {
1649
+ const active = referenceActive(highlight.occurrenceId);
1650
+ item.toggleAttribute("data-active", active);
1651
+ item.toggleAttribute("data-muted", !active);
1652
+ continue;
1653
+ }
1654
+ item.toggleAttribute("data-active", item.dataset.paint === state.activeHighlight || !!focused && !!highlight && sameRange(focused, highlight.range));
1655
+ item.toggleAttribute("data-muted", !!highlight?.hidden || !!focused && !!highlight && !sameRange(focused, highlight.range));
1656
+ }
1657
+ };
1658
+ const removeLayer = (host, layer2) => {
1659
+ layer2.remove();
1660
+ delete host.dataset.limrHighlightHost;
1661
+ delete host.dataset.limrHighlightPosition;
1662
+ highlightLayers.delete(host);
1663
+ };
1664
+ const canvas = document.createElement("canvas"), context = canvas.getContext("2d");
1665
+ const measure = (element) => {
1666
+ const saved = metrics.get(element);
1667
+ if (saved) return saved;
1668
+ const style = getComputedStyle(element), size = parseFloat(style.fontSize), lineHeight = parseFloat(style.lineHeight) || size * 1.5;
1669
+ const font = `${style.fontStyle} ${style.fontWeight} ${size}px ${style.fontFamily}`, key = `${font}/${lineHeight}`;
1670
+ let metric = fontMetrics.get(key);
1671
+ if (!metric) {
1672
+ if (context) context.font = font;
1673
+ const text = context?.measureText("Mg");
1674
+ const ascent = text?.fontBoundingBoxAscent ?? size * 0.9, descent = text?.fontBoundingBoxDescent ?? size * 0.25;
1675
+ const height = Math.min(ascent + descent, lineHeight - 0.5);
1676
+ metric = { ascent: ascent - Math.max(0, ascent + descent - height) / 2, descent, height };
1677
+ fontMetrics.set(key, metric);
1678
+ }
1679
+ metrics.set(element, metric);
1680
+ return metric;
1681
+ };
1682
+ const clear = () => {
1683
+ if (paint.childNodes.length) paint.replaceChildren();
1684
+ for (const [host, layer2] of highlightLayers) removeLayer(host, layer2);
1685
+ hits = [];
1686
+ };
1687
+ const render = () => {
1688
+ cancelAnimationFrame(frame);
1689
+ frame = 0;
1690
+ const selections = runtime.interaction.get().selection?.raw.ranges ?? [];
1691
+ const decorations = runtime.decorations.get().byBlock;
1692
+ if (!selections.length && ![...decorations.values()].some((value) => value.highlights.length)) {
1693
+ clear();
1694
+ return;
1695
+ }
1696
+ const doc = runtime.document.getSnapshot();
1697
+ if (doc !== snapshot) {
1698
+ snapshot = doc;
1699
+ blocks = void 0;
1700
+ }
1701
+ if (!blocks) {
1702
+ const notes = new Map(doc.blocks.filter((block) => block.node.type === "footnoteDefinition").map((block) => [String(block.node.identifier), block]));
1703
+ const ordered = [...doc.blocks.filter((block) => block.node.type !== "footnoteDefinition"), ...doc.footnoteOrder.flatMap((id) => {
1704
+ const block = notes.get(id), node = doc.footnotes.get(id);
1705
+ return block ? [block] : node ? [{ id: `${doc.id}-fn-${id}`, range: { start: node.position.start.offset, end: node.position.end.offset } }] : [];
1706
+ })];
1707
+ blocks = ordered.flatMap((block) => {
1708
+ const element = runtime.blocks.get(block.id);
1709
+ return element ? [{ element, range: block.range, id: block.id }] : [];
1710
+ });
1711
+ }
1712
+ const vv = window.visualViewport;
1713
+ const viewport = { top: vv?.offsetTop ?? 0, bottom: (vv?.offsetTop ?? 0) + (vv?.height ?? window.innerHeight), left: vv?.offsetLeft ?? 0, right: (vv?.offsetLeft ?? 0) + (vv?.width ?? window.innerWidth) };
1714
+ const root = runtime.configuration.get().scrollRoot;
1715
+ if (root) {
1716
+ const box = root.getBoundingClientRect();
1717
+ viewport.top = Math.max(viewport.top, box.top + root.clientTop);
1718
+ viewport.bottom = Math.min(viewport.bottom, box.top + root.clientTop + root.clientHeight);
1719
+ viewport.left = Math.max(viewport.left, box.left + root.clientLeft);
1720
+ viewport.right = Math.min(viewport.right, box.left + root.clientLeft + root.clientWidth);
1721
+ }
1722
+ let lo = 0, hi = blocks.length;
1723
+ while (lo < hi) {
1724
+ const mid = lo + hi >>> 1;
1725
+ if (blocks[mid].element.getBoundingClientRect().bottom < viewport.top - 32) lo = mid + 1;
1726
+ else hi = mid;
1727
+ }
1728
+ const origin = container.getBoundingClientRect();
1729
+ viewport.top = Math.max(viewport.top, origin.top);
1730
+ viewport.bottom = Math.min(viewport.bottom, origin.bottom);
1731
+ const scrollLeft = container.scrollLeft, scrollTop = container.scrollTop;
1732
+ const output = [];
1733
+ const clips = /* @__PURE__ */ new Map();
1734
+ const clipFor = (flow) => {
1735
+ const saved = clips.get(flow);
1736
+ if (saved) return saved;
1737
+ const clip = { ...viewport };
1738
+ for (let element = flow; element && element !== container; element = element.parentElement) {
1739
+ const css = getComputedStyle(element), box = element.getBoundingClientRect();
1740
+ if (/hidden|clip|auto|scroll/.test(css.overflowX)) {
1741
+ clip.left = Math.max(clip.left, box.left + element.clientLeft);
1742
+ clip.right = Math.min(clip.right, box.left + element.clientLeft + element.clientWidth);
1743
+ }
1744
+ if (/hidden|clip|auto|scroll/.test(css.overflowY)) {
1745
+ clip.top = Math.max(clip.top, box.top + element.clientTop);
1746
+ clip.bottom = Math.min(clip.bottom, box.top + element.clientTop + element.clientHeight);
1747
+ }
1748
+ }
1749
+ clips.set(flow, clip);
1750
+ return clip;
1751
+ };
1752
+ for (let index = lo; index < blocks.length; index++) {
1753
+ const block = blocks[index];
1754
+ if (block.element.getBoundingClientRect().top > viewport.bottom + 32) break;
1755
+ const tasks = [...decorations.get(block.id)?.highlights ?? []];
1756
+ for (const range of selections) if (intersects(range, block.range)) tasks.push({ id: "selection", range, selection: true });
1757
+ if (!tasks.length) continue;
1758
+ let leaves = leavesCache.get(block.element);
1759
+ if (!leaves) {
1760
+ leaves = leavesIn(block.element, runtime);
1761
+ leavesCache.set(block.element, leaves);
1762
+ }
1763
+ for (const task of tasks) {
1764
+ const rects = rectangles(leaves, task.range, { ...viewport, top: viewport.top - 32, bottom: viewport.bottom + 32 }, measure);
1765
+ for (const rect of rects) {
1766
+ const clip = clipFor(rect.flow);
1767
+ const left = Math.max(rect.left, clip.left), top = Math.max(rect.top, clip.top);
1768
+ const width = Math.min(rect.left + rect.width, clip.right) - left, height = Math.min(rect.top + rect.height, clip.bottom) - top;
1769
+ if (width <= 0 || height <= 0) continue;
1770
+ output.push({ rect: { ...rect, left: left - origin.left + scrollLeft, top: top - viewport.top, width, height }, task });
1771
+ }
1772
+ }
1773
+ }
1774
+ paint.style.top = `${viewport.top - origin.top + scrollTop}px`;
1775
+ paint.style.height = `${Math.max(0, viewport.bottom - viewport.top)}px`;
1776
+ const hostGeometry = /* @__PURE__ */ new Map();
1777
+ for (const { rect, task } of output) if (!task.selection && !hostGeometry.has(rect.flow)) {
1778
+ const host = rect.flow, box = host.getBoundingClientRect();
1779
+ hostGeometry.set(host, { box, top: Math.max(viewport.top, box.top) - box.top - host.clientTop + host.scrollTop, positioned: getComputedStyle(host).position !== "static" });
1780
+ }
1781
+ const counts = /* @__PURE__ */ new Map();
1782
+ const nextHits = [];
1783
+ output.forEach(({ rect, task }) => {
1784
+ let target = paint, left = rect.left, top = rect.top;
1785
+ if (!task.selection) {
1786
+ const host = rect.flow, geometry = hostGeometry.get(host);
1787
+ let layer2 = highlightLayers.get(host);
1788
+ if (!layer2) {
1789
+ layer2 = document.createElement("span");
1790
+ layer2.className = "limr-highlight-layer";
1791
+ layer2.dataset.limrIgnore = "true";
1792
+ layer2.setAttribute("aria-hidden", "true");
1793
+ host.dataset.limrHighlightHost = "true";
1794
+ if (!geometry.positioned) host.dataset.limrHighlightPosition = "true";
1795
+ host.append(layer2);
1796
+ highlightLayers.set(host, layer2);
1797
+ }
1798
+ layer2.style.top = `${geometry.top}px`;
1799
+ layer2.style.height = `${Math.max(0, Math.min(viewport.bottom, geometry.box.bottom) - Math.max(viewport.top, geometry.box.top))}px`;
1800
+ target = layer2;
1801
+ left += origin.left - geometry.box.left - host.clientLeft + host.scrollLeft;
1802
+ top += viewport.top - geometry.box.top - host.clientTop + host.scrollTop - geometry.top;
1803
+ nextHits.push({ id: task.id, rect: { left: rect.left + origin.left - scrollLeft, top: rect.top + viewport.top, width: rect.width, height: rect.height } });
1804
+ }
1805
+ const index = counts.get(target) ?? 0;
1806
+ counts.set(target, index + 1);
1807
+ const item = target.children[index] ?? document.createElement("span");
1808
+ const className = `limr-paint-rect limr-paint-${task.selection ? "selection" : task.style ?? "background"}`;
1809
+ if (item.className !== className) item.className = className;
1810
+ item.dataset.paint = task.id;
1811
+ item.toggleAttribute("data-reference", !!task.occurrenceId);
1812
+ if (rect.marker) item.dataset.marker = rect.marker;
1813
+ else delete item.dataset.marker;
1814
+ if (rect.atomic) item.dataset.atomic = "true";
1815
+ else delete item.dataset.atomic;
1816
+ if (rect.image) item.dataset.media = "image";
1817
+ else delete item.dataset.media;
1818
+ const css = `left:${left}px;top:${top}px;width:${rect.width}px;height:${rect.height}px;border-radius:${rect.radius ?? "0"};`;
1819
+ if (item.dataset.geometry !== css) {
1820
+ item.style.cssText = css;
1821
+ item.dataset.geometry = css;
1822
+ }
1823
+ if (!task.selection) item.style.setProperty("--limr-highlight", task.color ?? "#F2C744");
1824
+ if (task.occurrenceId) {
1825
+ const active2 = referenceActive(task.occurrenceId);
1826
+ item.toggleAttribute("data-active", active2);
1827
+ item.toggleAttribute("data-muted", !active2);
1828
+ }
1829
+ if (!item.parentNode) target.append(item);
1830
+ });
1831
+ for (const layer2 of [paint, ...highlightLayers.values()]) while (layer2.children.length > (counts.get(layer2) ?? 0)) layer2.lastChild.remove();
1832
+ for (const [host, layer2] of highlightLayers) if (!counts.has(layer2)) removeLayer(host, layer2);
1833
+ hits = nextHits;
1834
+ const active = runtime.interaction.get().activeHighlight;
1835
+ if (active && !hits.some((hit) => hit.id === active)) runtime.clearSelection();
1836
+ feedback();
1837
+ if (translating) {
1838
+ translating = container.getAnimations().some((animation) => animation instanceof CSSTransition && animation.transitionProperty === "translate" && animation.playState === "running");
1839
+ if (translating) schedule();
1840
+ }
1841
+ };
1842
+ const schedule = () => {
1843
+ if (!frame) frame = requestAnimationFrame(render);
1844
+ };
1845
+ const translate = (event) => {
1846
+ if (event.target !== container || event.propertyName !== "translate") return;
1847
+ translating = true;
1848
+ schedule();
1849
+ };
1850
+ container.addEventListener("transitionrun", translate);
1851
+ container.addEventListener("transitionend", translate);
1852
+ container.addEventListener("transitioncancel", translate);
1853
+ const invalidate = () => {
1854
+ blocks = void 0;
1855
+ metrics = /* @__PURE__ */ new WeakMap();
1856
+ schedule();
1857
+ };
1858
+ const fontsChanged = () => {
1859
+ fontMetrics.clear();
1860
+ invalidate();
1861
+ };
1862
+ const unsubscribers = [runtime.interaction.subscribe(() => {
1863
+ const state = runtime.interaction.get(), selection = state.selection;
1864
+ if (state.hoveredHighlight !== lastHovered || state.activeHighlight !== lastActive || state.active !== lastAnnotation || state.hovered !== lastHoveredAnnotation) {
1865
+ lastHovered = state.hoveredHighlight;
1866
+ lastActive = state.activeHighlight;
1867
+ lastAnnotation = state.active;
1868
+ lastHoveredAnnotation = state.hovered;
1869
+ feedback();
1870
+ }
1871
+ if (selection === lastSelection) return;
1872
+ lastSelection = selection;
1873
+ render();
1874
+ }), runtime.decorations.subscribe(() => {
1875
+ const decorations = runtime.decorations.get().byBlock;
1876
+ if (decorations === lastDecorations) return;
1877
+ lastDecorations = decorations;
1878
+ leavesCache = /* @__PURE__ */ new WeakMap();
1879
+ schedule();
1880
+ }), runtime.layout.subscribe(invalidate), runtime.documentOffset.subscribe(schedule), runtime.configuration.subscribe(invalidate)];
1881
+ const observer = new MutationObserver((records) => {
1882
+ let changed = false;
1883
+ for (const record of records) {
1884
+ const target = record.target instanceof Element ? record.target : record.target.parentElement;
1885
+ if (!target || target === paint || paint.contains(target) || target.closest(".limr-highlight-layer")) continue;
1886
+ if (record.type === "childList" && [...record.addedNodes, ...record.removedNodes].every((node) => node instanceof Element && node.classList.contains("limr-highlight-layer"))) continue;
1887
+ const block = target.closest("[data-limr-block]");
1888
+ if (block) leavesCache.delete(block);
1889
+ else blocks = void 0;
1890
+ changed = true;
1891
+ }
1892
+ if (changed) {
1893
+ metrics = /* @__PURE__ */ new WeakMap();
1894
+ schedule();
1895
+ }
1896
+ });
1897
+ observer.observe(container, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["class", "style", "inert", "open", "data-limr-theme", "data-limr-justify"] });
1898
+ const scroll = () => {
1899
+ runtime.hoverHighlight(null);
1900
+ schedule();
1901
+ };
1902
+ document.addEventListener("scroll", scroll, { capture: true, passive: true });
1903
+ window.visualViewport?.addEventListener("resize", schedule);
1904
+ window.visualViewport?.addEventListener("scroll", schedule);
1905
+ document.fonts?.addEventListener("loadingdone", fontsChanged);
1906
+ const hitAt = (event) => {
1907
+ const element = event.target instanceof Element ? event.target : null;
1908
+ if (!element || element.closest("[data-limr-document]") !== container || element.closest("button,input,textarea,select,[contenteditable],[data-limr-ignore]")) return null;
1909
+ const focused = focusedRange(), decorations = runtime.decorations.get();
1910
+ for (let index = hits.length - 1; index >= 0; index--) {
1911
+ const { rect, id } = hits[index];
1912
+ const highlight = decorations.highlights.get(id);
1913
+ if (highlight?.occurrenceId || highlight?.hidden || focused && highlight && !sameRange(focused, highlight.range)) continue;
1914
+ if (event.clientX >= rect.left && event.clientX <= rect.left + rect.width && event.clientY >= rect.top && event.clientY <= rect.top + rect.height) return id;
1915
+ }
1916
+ return null;
1917
+ };
1918
+ const move = (event) => {
1919
+ if (!event.buttons) runtime.hoverHighlight(hitAt(event));
1920
+ };
1921
+ const leave = () => runtime.hoverHighlight(null);
1922
+ let down = null;
1923
+ const pointerDown = (event) => {
1924
+ down = { x: event.clientX, y: event.clientY };
1925
+ };
1926
+ const click = (event) => {
1927
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || !down || Math.hypot(event.clientX - down.x, event.clientY - down.y) > 4 || window.getSelection()?.isCollapsed === false) return;
1928
+ const id = hitAt(event);
1929
+ if (!id) return;
1930
+ event.preventDefault();
1931
+ const highlight = runtime.decorations.get().highlights.get(id);
1932
+ const text = [];
1933
+ let atomic2 = false;
1934
+ for (const block of runtime.document.getSnapshot().blocks) {
1935
+ if (!intersects(block.range, highlight.range)) continue;
1936
+ const element = runtime.blocks.get(block.id);
1937
+ if (!element) continue;
1938
+ const parts2 = [];
1939
+ for (const leaf of leavesIn(element, runtime)) {
1940
+ if (!intersects(leaf.range, highlight.range) || leaf.kind === "marker") continue;
1941
+ if (leaf.kind !== "text") {
1942
+ atomic2 = true;
1943
+ continue;
1944
+ }
1945
+ const range = textRange(leaf, highlight.range, { top: -Infinity, bottom: Infinity, left: -Infinity, right: Infinity });
1946
+ if (range) parts2.push(range.toString());
1947
+ }
1948
+ if (parts2.length) text.push(parts2.join(""));
1949
+ }
1950
+ runtime.highlightReference = {
1951
+ text: !atomic2 && text.length ? text.join("\n\n") : void 0,
1952
+ getClientRects: () => highlightRects(id),
1953
+ getBoundingClientRect: () => {
1954
+ const rects = highlightRects(id);
1955
+ if (!rects.length) return new DOMRect();
1956
+ const left = Math.min(...rects.map((rect) => rect.left)), top = Math.min(...rects.map((rect) => rect.top));
1957
+ return new DOMRect(left, top, Math.max(...rects.map((rect) => rect.right)) - left, Math.max(...rects.map((rect) => rect.bottom)) - top);
1958
+ }
1959
+ };
1960
+ runtime.activateHighlight(id);
1961
+ };
1962
+ if (interactive) {
1963
+ container.addEventListener("pointermove", move);
1964
+ container.addEventListener("pointerleave", leave);
1965
+ container.addEventListener("pointerdown", pointerDown);
1966
+ container.addEventListener("click", click);
1967
+ }
1968
+ container.dataset.limrPainted = "true";
1969
+ schedule();
1970
+ return () => {
1971
+ cancelAnimationFrame(frame);
1972
+ observer.disconnect();
1973
+ unsubscribers.forEach((unsubscribe) => unsubscribe());
1974
+ document.removeEventListener("scroll", scroll, true);
1975
+ window.visualViewport?.removeEventListener("resize", schedule);
1976
+ window.visualViewport?.removeEventListener("scroll", schedule);
1977
+ document.fonts?.removeEventListener("loadingdone", fontsChanged);
1978
+ container.removeEventListener("transitionrun", translate);
1979
+ container.removeEventListener("transitionend", translate);
1980
+ container.removeEventListener("transitioncancel", translate);
1981
+ container.removeEventListener("pointermove", move);
1982
+ container.removeEventListener("pointerleave", leave);
1983
+ container.removeEventListener("pointerdown", pointerDown);
1984
+ container.removeEventListener("click", click);
1985
+ delete container.dataset.limrPainted;
1986
+ clear();
1987
+ };
1988
+ }, [runtime, interactive]);
1989
+ return /* @__PURE__ */ jsx3("div", { ref: layer, className: "limr-paint-layer", "data-limr-ignore": "true", "aria-hidden": "true" });
1990
+ }
1991
+
1992
+ // src/react/Markdown.tsx
1993
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
1994
+ function Markdown({ className, style, interactive = true, followOutput = false, justify, ...props }) {
1995
+ const parent = useContext(RuntimeContext);
1996
+ if (props.source !== void 0 || !parent) return /* @__PURE__ */ jsx4(DocumentProvider, { ...props, justify, children: /* @__PURE__ */ jsx4(MarkdownBody, { className, style, interactive, followOutput }) });
1997
+ return /* @__PURE__ */ jsx4(MarkdownBody, { className, style, interactive, followOutput, justify });
1998
+ }
1999
+ function MarkdownBody({ className, style, interactive, followOutput, justify }) {
2000
+ const runtime = useRuntime();
2001
+ const document2 = useDocument();
2002
+ const appearance = useAppearance();
2003
+ const theme = useStoreSelector(runtime.configuration, (config) => config.theme ?? "light");
2004
+ const configuredJustify = useStoreSelector(runtime.configuration, (config) => config.justify ?? false);
2005
+ const scrollRoot = useStoreSelector(runtime.configuration, (config) => config.scrollRoot);
2006
+ const offset = useStoreSelector(runtime.documentOffset, (value) => value);
2007
+ const components = useStoreSelector(runtime.configuration, (config) => config.components);
2008
+ const extensions = useStoreSelector(runtime.configuration, (config) => config.extensions);
2009
+ const decorations = useStoreSelector(runtime.decorations, (state) => state.byBlock);
2010
+ const ref = useRef4(null);
2011
+ const pinned = useRef4(true);
2012
+ useIsomorphicLayoutEffect(() => ref.current ? runtime.mountContent(ref.current) : void 0, [runtime, scrollRoot]);
2013
+ useIsomorphicLayoutEffect(() => runtime.requestLayout(), [runtime, justify, configuredJustify]);
2014
+ useSelectionTracking(runtime, interactive);
2015
+ useEffect4(() => {
2016
+ if (!followOutput) return;
2017
+ const root = scrollRoot ?? window;
2018
+ const onScroll = () => {
2019
+ const element = scrollRoot ?? window.document.documentElement;
2020
+ const viewport = scrollRoot?.clientHeight ?? window.innerHeight;
2021
+ pinned.current = element.scrollHeight - runtime.getScrollTop() - viewport < 48;
2022
+ };
2023
+ root.addEventListener("scroll", onScroll, { passive: true });
2024
+ return () => root.removeEventListener("scroll", onScroll);
2025
+ }, [runtime, followOutput, scrollRoot]);
2026
+ useIsomorphicLayoutEffect(() => {
2027
+ if (!followOutput || !document2.streaming || !pinned.current) return;
2028
+ const frame = requestAnimationFrame(() => runtime.scrollTo(scrollRoot?.scrollHeight ?? window.document.documentElement.scrollHeight, "instant"));
2029
+ return () => cancelAnimationFrame(frame);
2030
+ }, [document2, runtime, followOutput, scrollRoot]);
2031
+ return /* @__PURE__ */ jsxs3("article", { ref, className: `limr-prose ${className ?? ""}`, style: { ...style, translate: offset ? `0 ${offset}px` : style?.translate }, "data-limr-theme": theme, "data-limr-appearance": appearance, "data-limr-document": document2.id, "data-limr-justify": justify ?? configuredJustify, children: [
2032
+ document2.blocks.map((block) => /* @__PURE__ */ jsx4(BlockView, { block, runtime, components, extensions, decorations: decorations.get(block.id) ?? emptyDecorations }, block.id)),
2033
+ /* @__PURE__ */ jsx4(Footnotes, {}),
2034
+ /* @__PURE__ */ jsx4(SelectionPaint, { runtime, interactive })
2035
+ ] });
2036
+ }
2037
+
2038
+ // src/components/OverlayScrollArea.tsx
2039
+ import { useRef as useRef5 } from "react";
2040
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
2041
+ function OverlayScrollArea({ children, active, resetKey, label }) {
2042
+ const area = useRef5(null);
2043
+ const content = useRef5(null);
2044
+ const thumb = useRef5(null);
2045
+ const track = useRef5(null);
2046
+ const drag = useRef5(null);
2047
+ const show = useRef5(() => {
2048
+ });
2049
+ useIsomorphicLayoutEffect(() => {
2050
+ const element = area.current, wrapper = element.parentElement;
2051
+ delete wrapper.dataset.scrolling;
2052
+ if (!active) return;
2053
+ element.scrollTop = 0;
2054
+ let frame = 0, timeout, previous = 0;
2055
+ const update = () => {
2056
+ frame = 0;
2057
+ const height = track.current.clientHeight;
2058
+ const overflow = element.scrollHeight - element.clientHeight;
2059
+ const size = Math.min(height, Math.max(20, height * element.clientHeight / Math.max(1, element.scrollHeight)));
2060
+ wrapper.toggleAttribute("data-overflow", overflow > 1);
2061
+ thumb.current.style.height = `${size}px`;
2062
+ thumb.current.style.transform = `translateY(${overflow > 0 ? Math.max(0, Math.min(1, element.scrollTop / overflow)) * (height - size) : 0}px)`;
2063
+ };
2064
+ const schedule = () => {
2065
+ if (!frame) frame = requestAnimationFrame(update);
2066
+ };
2067
+ show.current = () => {
2068
+ clearTimeout(timeout);
2069
+ if (wrapper.closest("[data-motion]")) return;
2070
+ wrapper.dataset.scrolling = "true";
2071
+ timeout = setTimeout(() => {
2072
+ if (!drag.current) delete wrapper.dataset.scrolling;
2073
+ }, 800);
2074
+ };
2075
+ const scroll = () => {
2076
+ schedule();
2077
+ if (element.scrollTop === previous) return;
2078
+ previous = element.scrollTop;
2079
+ show.current();
2080
+ };
2081
+ const observer = new ResizeObserver(schedule);
2082
+ observer.observe(element);
2083
+ observer.observe(content.current);
2084
+ element.addEventListener("scroll", scroll, { passive: true });
2085
+ update();
2086
+ return () => {
2087
+ observer.disconnect();
2088
+ element.removeEventListener("scroll", scroll);
2089
+ cancelAnimationFrame(frame);
2090
+ clearTimeout(timeout);
2091
+ drag.current = null;
2092
+ show.current = () => {
2093
+ };
2094
+ delete wrapper.dataset.scrolling;
2095
+ };
2096
+ }, [active, resetKey]);
2097
+ const startDrag = (event) => {
2098
+ if (event.button !== 0) return;
2099
+ const element = area.current, bar = thumb.current;
2100
+ const travel = track.current.clientHeight - bar.offsetHeight;
2101
+ if (travel <= 0) return;
2102
+ event.preventDefault();
2103
+ event.currentTarget.setPointerCapture(event.pointerId);
2104
+ const scale = (element.scrollHeight - element.clientHeight) / travel;
2105
+ if (event.target !== bar) element.scrollTop = (event.clientY - track.current.getBoundingClientRect().top - bar.offsetHeight / 2) * scale;
2106
+ drag.current = { pointerId: event.pointerId, y: event.clientY, scroll: element.scrollTop, scale };
2107
+ show.current();
2108
+ };
2109
+ const move = (event) => {
2110
+ const current = drag.current;
2111
+ if (current?.pointerId === event.pointerId) area.current.scrollTop = current.scroll + (event.clientY - current.y) * current.scale;
2112
+ };
2113
+ const end = (event) => {
2114
+ if (drag.current?.pointerId !== event.pointerId) return;
2115
+ drag.current = null;
2116
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
2117
+ show.current();
2118
+ };
2119
+ return /* @__PURE__ */ jsxs4("div", { className: "limr-overlay-scroll", children: [
2120
+ /* @__PURE__ */ jsx5("div", { ref: area, className: "limr-overlay-content", "data-limr-card-body": "", tabIndex: 0, role: "region", "aria-label": label, children: /* @__PURE__ */ jsx5("div", { ref: content, className: "limr-overlay-scroll-inner", children }) }),
2121
+ /* @__PURE__ */ jsx5("div", { ref: track, className: "limr-overlay-scrollbar", "aria-hidden": "true", onPointerDown: startDrag, onPointerMove: move, onPointerUp: end, onPointerCancel: end, onLostPointerCapture: end, children: /* @__PURE__ */ jsx5("div", { ref: thumb, className: "limr-overlay-scroll-thumb" }) })
2122
+ ] });
2123
+ }
2124
+
2125
+ // src/components/AnnotationCard.tsx
2126
+ import { Fragment as Fragment3, jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
2127
+ function AnnotationCard({ title, bodyLabel, occurrence, expanded, pinned, canExpand, expand, collapse, close, children }) {
2128
+ const locale = useLocale();
2129
+ return /* @__PURE__ */ jsxs5(Fragment3, { children: [
2130
+ /* @__PURE__ */ jsxs5("div", { className: "limr-overlay-header", children: [
2131
+ /* @__PURE__ */ jsx6("span", { children: title }),
2132
+ /* @__PURE__ */ jsxs5("div", { className: "limr-overlay-controls", children: [
2133
+ expanded ? /* @__PURE__ */ jsx6("button", { type: "button", onClick: collapse, children: /* @__PURE__ */ jsx6("span", { className: "limr-underline", children: locale.collapse }) }) : canExpand && /* @__PURE__ */ jsx6("button", { type: "button", onClick: expand, children: /* @__PURE__ */ jsx6("span", { className: "limr-underline", children: locale.expand }) }),
2134
+ pinned && /* @__PURE__ */ jsx6("button", { type: "button", className: "limr-overlay-close", onClick: close, "aria-label": locale.close, children: "\xD7" })
2135
+ ] })
2136
+ ] }),
2137
+ /* @__PURE__ */ jsx6(OverlayScrollArea, { active: true, resetKey: occurrence.id, label: bodyLabel ?? (typeof title === "string" ? title : locale.annotations), children })
2138
+ ] });
2139
+ }
2140
+
2141
+ // src/extensions/annotations.tsx
2142
+ import { jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
2143
+ var CitationParagraph = ({ children }) => /* @__PURE__ */ jsx7("p", { children: /* @__PURE__ */ jsx7("span", { className: "limr-underline", children }) });
2144
+ function CitationIcon() {
2145
+ return /* @__PURE__ */ jsx7("svg", { viewBox: "0 0 16 16", "aria-hidden": "true", fill: "currentColor", children: /* @__PURE__ */ jsx7("path", { d: "M2.5 4.2h4.3v4.3c0 2.1-1.2 3.3-3.5 3.8l-.5-1.4c1.4-.4 2-1 2-2H2.5V4.2Zm6.7 0h4.3v4.3c0 2.1-1.2 3.3-3.5 3.8l-.5-1.4c1.4-.4 2-1 2-2H9.2V4.2Z" }) });
2146
+ }
2147
+ function AnnotationMarkdown({ source, className, ...props }) {
2148
+ const runtime = useRuntime();
2149
+ const config = useStoreSelector(runtime.configuration, (config2) => config2);
2150
+ return /* @__PURE__ */ jsx7(Markdown, { source, extensions: config.extensions, parameters: config.parameters, components: config.components, annotationTypes: config.annotationTypes, theme: config.theme, appearance: config.appearance, locale: config.locale, interactive: false, ...props, className: `limr-annotation-markdown ${className ?? ""}` });
2151
+ }
2152
+ function citation(options = {}) {
2153
+ function Preview({ annotations }) {
2154
+ const summary = useMemo2(() => annotations.filter((annotation) => annotation.type === (options.type ?? "citation")).map((annotation) => {
2155
+ const data = annotation.data;
2156
+ const source = data?.summary?.trim() || data?.description?.trim();
2157
+ if (source) return fromMarkdown(source).children?.map(textContent).join(" ").replace(/\s+/g, " ").trim();
2158
+ return safeUrl(data?.url) || data?.title;
2159
+ }).filter(Boolean).join(" \xB7 "), [annotations]);
2160
+ return summary ? /* @__PURE__ */ jsx7("span", { title: summary, children: summary }) : null;
2161
+ }
2162
+ function Card(props) {
2163
+ const locale = useLocale();
2164
+ return /* @__PURE__ */ jsx7(AnnotationCard, { ...props, title: locale.citation ?? locale.annotations });
2165
+ }
2166
+ function Content({ data }) {
2167
+ const runtime = useRuntime();
2168
+ const configured = useStoreSelector(runtime.configuration, () => runtime.components);
2169
+ const components = useMemo2(() => ({ ...configured, paragraph: configured.paragraph ?? CitationParagraph }), [configured]);
2170
+ const link = useRef6(null);
2171
+ const url = safeUrl(data?.url);
2172
+ return /* @__PURE__ */ jsxs6("div", { className: "limr-citation-content", "data-linked": !!url || void 0, onClick: (event) => {
2173
+ if (url && !event.defaultPrevented && !event.target.closest('a,button,input,textarea,select,summary,[role="button"],[contenteditable="true"],[data-limr-card-interactive]') && window.getSelection()?.isCollapsed !== false) link.current?.click();
2174
+ }, children: [
2175
+ /* @__PURE__ */ jsx7("a", { ref: link, className: "limr-citation-title", href: url, target: "_blank", rel: "noopener noreferrer", children: /* @__PURE__ */ jsx7("span", { className: "limr-underline", children: data?.title ?? data?.url ?? "Citation" }) }),
2176
+ (data?.description || data?.summary) && /* @__PURE__ */ jsx7(AnnotationMarkdown, { source: data.description || data.summary, components })
2177
+ ] });
2178
+ }
2179
+ return {
2180
+ name: "citation",
2181
+ tags: ["citation", "ref"],
2182
+ scope: "local",
2183
+ annotationTypes: [{ type: "citation", label: (locale) => locale.citation ?? "Citation", icon: CitationIcon, color: "#6366f1", highlight: "hover", Content, ...options, sidebar: { Preview, collapseOnContentClick: false, ...options.sidebar }, overlay: { Card, expand: false, ...options.overlay } }],
2184
+ transform(root) {
2185
+ walk(root, (node) => {
2186
+ if (node.type !== "component") return;
2187
+ if (node.name === "citation") {
2188
+ const attributes = node.attributes ?? {};
2189
+ const id = String(attributes["cite-id"] ?? attributes.id ?? "");
2190
+ node.type = "annotationDefinition";
2191
+ node.annotation = { id, type: "citation", data: { title: attributes.title, url: attributes.url, description: attributes.desc ?? attributes.description, summary: attributes.summary } };
2192
+ } else if (node.name === "ref") {
2193
+ const value = String(node.attributes?.["cite-from-ids"] ?? node.attributes?.ids ?? node.attributes?.id ?? "");
2194
+ let ids;
2195
+ try {
2196
+ const parsed = JSON.parse(value);
2197
+ ids = Array.isArray(parsed) ? parsed.map(String) : [String(parsed)];
2198
+ } catch {
2199
+ ids = value.split(",").map((id) => id.trim()).filter(Boolean);
2200
+ }
2201
+ node.type = "annotationReference";
2202
+ node.annotationIds = ids;
2203
+ }
2204
+ });
2205
+ }
2206
+ };
2207
+ }
2208
+
2209
+ // src/extensions/translations.tsx
2210
+ import { useRef as useRef8, useState as useState3 } from "react";
2211
+
2212
+ // src/components/InlineMarker.tsx
2213
+ import { forwardRef } from "react";
2214
+ import { jsx as jsx8 } from "react/jsx-runtime";
2215
+ var InlineMarker = forwardRef(function InlineMarker2({ label, color, children, className = "", style, ...props }, ref) {
2216
+ return /* @__PURE__ */ jsx8("span", { className: "limr-mark-wrap", "data-limr-ignore": "true", children: /* @__PURE__ */ jsx8(
2217
+ "button",
2218
+ {
2219
+ ...props,
2220
+ ref,
2221
+ type: "button",
2222
+ "aria-label": label,
2223
+ title: props.title ?? label,
2224
+ className: `limr-mark limr-action-mark ${className}`,
2225
+ style: { "--limr-mark-color": color, ...style },
2226
+ children: /* @__PURE__ */ jsx8("span", { className: "limr-mark-icon", children })
2227
+ }
2228
+ ) });
2229
+ });
2230
+
2231
+ // src/components/Collapse.tsx
2232
+ import { useRef as useRef7, useState as useState2 } from "react";
2233
+ import { jsx as jsx9 } from "react/jsx-runtime";
2234
+ function Collapse({ open, children, className = "", keepMounted = false }) {
2235
+ const [mounted, setMounted] = useState2(open);
2236
+ const [visible, setVisible] = useState2(open);
2237
+ const panel = useRef7(null);
2238
+ useIsomorphicLayoutEffect(() => {
2239
+ if (keepMounted) return;
2240
+ if (open) {
2241
+ if (!mounted) {
2242
+ setMounted(true);
2243
+ return;
2244
+ }
2245
+ panel.current?.getBoundingClientRect();
2246
+ setVisible(true);
2247
+ return;
2248
+ }
2249
+ setVisible(false);
2250
+ const timer = setTimeout(() => setMounted(false), 420);
2251
+ return () => clearTimeout(timer);
2252
+ }, [open, keepMounted, mounted]);
2253
+ return /* @__PURE__ */ jsx9("div", { ref: (element) => {
2254
+ panel.current = element;
2255
+ element?.toggleAttribute("inert", !open);
2256
+ }, className: `limr-collapse ${className}`, "data-open": (keepMounted ? open : visible) || void 0, "aria-hidden": !open, children: /* @__PURE__ */ jsx9("div", { className: "limr-collapse-inner", children: mounted || keepMounted ? children : null }) });
2257
+ }
2258
+
2259
+ // src/extensions/translations.tsx
2260
+ import { Fragment as Fragment4, jsx as jsx10, jsxs as jsxs7 } from "react/jsx-runtime";
2261
+ var modes = ["origin", "translation", "both"];
2262
+ var names = { origin: "\u539F\u6587", translation: "\u8BD1\u6587", both: "\u5BF9\u7167" };
2263
+ function TranslationIcon({ mode }) {
2264
+ return /* @__PURE__ */ jsx10("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: mode === "both" ? /* @__PURE__ */ jsxs7(Fragment4, { children: [
2265
+ /* @__PURE__ */ jsx10("rect", { x: "2.5", y: "4", width: "8", height: "16", rx: "2.5" }),
2266
+ /* @__PURE__ */ jsx10("rect", { x: "13.5", y: "4", width: "8", height: "16", rx: "2.5" }),
2267
+ /* @__PURE__ */ jsx10("path", { d: "M5 9h3M5 12h3M16 9h3M16 12h3" })
2268
+ ] }) : /* @__PURE__ */ jsxs7(Fragment4, { children: [
2269
+ /* @__PURE__ */ jsx10("rect", { x: "4.5", y: "3", width: "15", height: "18", rx: "3" }),
2270
+ mode === "origin" ? /* @__PURE__ */ jsx10("path", { d: "M8.5 8h7M8.5 12h7M8.5 16h4" }) : /* @__PURE__ */ jsx10("path", { d: "M8 8.5h8M12 6.5v2M14.5 8.5c-.5 4-3 6.5-6.5 8M9.5 11c1.2 2.5 3.2 4.2 6.5 5.5" })
2271
+ ] }) });
2272
+ }
2273
+ function modeOf(value, fallback) {
2274
+ return modes.includes(value) ? value : fallback;
2275
+ }
2276
+ function section(node, name) {
2277
+ for (const child of node.children ?? []) {
2278
+ if (child.name === name) return child;
2279
+ if (child.type === "paragraph") {
2280
+ const found = section(child, name);
2281
+ if (found) return found;
2282
+ }
2283
+ }
2284
+ }
2285
+ function translations(options = {}) {
2286
+ function Translations({ node, children, renderChildren }) {
2287
+ const origin = section(node, "origin"), translation = section(node, "translation");
2288
+ const [localMode, setLocalMode] = useState3();
2289
+ const globalMode = useRendererParameter("translationMode");
2290
+ const onGlobalChange = useRendererParameter("onTranslationModeChange");
2291
+ const requested = modeOf(globalMode ?? localMode ?? node.attributes?.default, options.defaultMode ?? "origin");
2292
+ const mode = !origin ? "translation" : !translation ? "origin" : requested;
2293
+ const next = modes[(modes.indexOf(mode) + 1) % modes.length];
2294
+ const marker = useRef8(null);
2295
+ const restoreFocus = useRef8(false);
2296
+ const locked = globalMode !== void 0 && !onGlobalChange;
2297
+ useIsomorphicLayoutEffect(() => {
2298
+ if (restoreFocus.current) {
2299
+ marker.current?.focus({ preventScroll: true });
2300
+ restoreFocus.current = false;
2301
+ }
2302
+ }, [mode]);
2303
+ if (!origin && !translation) return /* @__PURE__ */ jsx10(Fragment4, { children });
2304
+ const toggle = origin && translation ? /* @__PURE__ */ jsx10(
2305
+ InlineMarker,
2306
+ {
2307
+ ref: marker,
2308
+ "data-translation-switch": "",
2309
+ "data-mode": mode,
2310
+ color: "var(--limr-translation-accent, #6b8fb5)",
2311
+ disabled: locked,
2312
+ label: locked ? `\u5F53\u524D${names[mode]}\uFF0C\u7531\u5168\u5C40\u5C55\u793A\u6A21\u5F0F\u63A7\u5236` : `\u5F53\u524D${names[mode]}\uFF0C\u5207\u6362\u5230${names[next]}`,
2313
+ onClick: () => {
2314
+ restoreFocus.current = document.activeElement === marker.current;
2315
+ if (globalMode !== void 0) onGlobalChange?.(next);
2316
+ else setLocalMode(next);
2317
+ },
2318
+ children: /* @__PURE__ */ jsx10(TranslationIcon, { mode })
2319
+ }
2320
+ ) : void 0;
2321
+ return /* @__PURE__ */ jsxs7("div", { className: "limr-translations", "data-mode": mode, children: [
2322
+ translation && /* @__PURE__ */ jsx10(Collapse, { open: mode !== "origin", keepMounted: true, className: "limr-translation-panel", children: /* @__PURE__ */ jsx10("div", { className: "limr-translation-text", "data-language": "translation", children: renderChildren(translation.children ?? [], { trailing: mode === "translation" ? toggle : void 0 }) }) }),
2323
+ origin && /* @__PURE__ */ jsx10(Collapse, { open: mode !== "translation", keepMounted: true, className: "limr-translation-panel", children: /* @__PURE__ */ jsx10("div", { className: "limr-translation-text", "data-language": "origin", children: renderChildren(origin.children ?? [], { trailing: mode !== "translation" ? toggle : void 0 }) }) })
2324
+ ] });
2325
+ }
2326
+ return {
2327
+ name: "translations",
2328
+ tags: ["translations", "origin", "translation"],
2329
+ directives: ["translations", "origin", "translation"],
2330
+ display: "block",
2331
+ scope: "local",
2332
+ parameters: { translationMode: void 0, onTranslationModeChange: void 0 },
2333
+ components: { translations: Translations, origin: ({ children }) => /* @__PURE__ */ jsx10(Fragment4, { children }), translation: ({ children }) => /* @__PURE__ */ jsx10(Fragment4, { children }) }
2334
+ };
2335
+ }
2336
+
2337
+ // src/extensions/blocks.tsx
2338
+ import { useState as useState7 } from "react";
2339
+
2340
+ // src/extensions/define.ts
2341
+ function defineBlock({ name, component, tags = [name], directives = [name], selection = "content" }) {
2342
+ return { name, tags, directives, selection, display: "block", scope: "local", components: Object.fromEntries([.../* @__PURE__ */ new Set([...tags, ...directives])].map((tag) => [tag, component])) };
2343
+ }
2344
+ function defineAnnotation(type) {
2345
+ return { name: `annotation:${type.type}`, annotationTypes: [type], scope: "local" };
2346
+ }
2347
+ function defineExtension(extension) {
2348
+ return extension;
2349
+ }
2350
+
2351
+ // src/components/Disclosure.tsx
2352
+ import { useEffect as useEffect5, useState as useState4 } from "react";
2353
+ import { jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
2354
+ function Disclosure({ title, open, onChange, children }) {
2355
+ const [present, setPresent] = useState4(open);
2356
+ useEffect5(() => {
2357
+ if (open) {
2358
+ setPresent(true);
2359
+ return;
2360
+ }
2361
+ const timer = setTimeout(() => setPresent(false), 420);
2362
+ return () => clearTimeout(timer);
2363
+ }, [open]);
2364
+ return /* @__PURE__ */ jsxs8("details", { className: "limr-disclosure", open: present || open, "data-expanded": open || void 0, children: [
2365
+ /* @__PURE__ */ jsxs8("summary", { "aria-expanded": open, onClick: (event) => {
2366
+ event.preventDefault();
2367
+ onChange(!open);
2368
+ }, "data-limr-ignore": "true", children: [
2369
+ /* @__PURE__ */ jsx11("span", { className: "limr-underline", children: title }),
2370
+ /* @__PURE__ */ jsx11("svg", { viewBox: "0 0 20 20", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx11("path", { d: "m6 8 4 4 4-4" }) })
2371
+ ] }),
2372
+ /* @__PURE__ */ jsx11(Collapse, { open, keepMounted: true, children: /* @__PURE__ */ jsx11("div", { className: "limr-question-detail", children }) })
2373
+ ] });
2374
+ }
2375
+
2376
+ // src/components/DiamondCheck.tsx
2377
+ import { jsx as jsx12, jsxs as jsxs9 } from "react/jsx-runtime";
2378
+ function DiamondCheck({ checked }) {
2379
+ return /* @__PURE__ */ jsxs9("svg", { className: "limr-choice-diamond", width: "14", height: "14", viewBox: "0 0 18 18", fill: "none", "aria-hidden": "true", "data-limr-ignore": "true", "data-checked": checked || void 0, children: [
2380
+ /* @__PURE__ */ jsx12("path", { className: "limr-diamond-outline", d: "M9 1.5L16.5 9L9 16.5L1.5 9Z", fill: "none" }),
2381
+ /* @__PURE__ */ jsx12("path", { className: "limr-diamond-fill", d: "M9 5L13 9L9 13L5 9Z", fill: "currentColor" })
2382
+ ] });
2383
+ }
2384
+
2385
+ // src/extensions/video.tsx
2386
+ import { useEffect as useEffect6, useRef as useRef9, useState as useState5 } from "react";
2387
+ import { jsx as jsx13, jsxs as jsxs10 } from "react/jsx-runtime";
2388
+ function resolveVideo(source, provider = "auto") {
2389
+ const safe = safeUrl(source);
2390
+ if (!safe) return;
2391
+ let parsed;
2392
+ try {
2393
+ parsed = new URL(safe.startsWith("//") ? `https:${safe}` : safe);
2394
+ } catch {
2395
+ return provider === "auto" || provider === "native" ? { url: safe, native: true } : void 0;
2396
+ }
2397
+ if (!["https:", "http:"].includes(parsed.protocol)) return;
2398
+ const youtube = /(?:^|\.)(?:youtube\.com|youtube-nocookie\.com)$/.test(parsed.hostname) || parsed.hostname === "youtu.be";
2399
+ const bilibili = /(?:^|\.)bilibili\.com$/.test(parsed.hostname);
2400
+ const kind = provider === "auto" ? youtube ? "youtube" : bilibili ? "bilibili" : "native" : provider;
2401
+ if (kind === "native") return { url: safe, native: true };
2402
+ if (kind === "youtube" && youtube) {
2403
+ const id = parsed.hostname === "youtu.be" ? parsed.pathname.split("/")[1] : parsed.searchParams.get("v") ?? /^\/(?:embed|shorts|live)\/([\w-]+)/.exec(parsed.pathname)?.[1];
2404
+ if (id && /^[\w-]{11}$/.test(id)) {
2405
+ const embed = new URL(`https://www.youtube.com/embed/${id}`);
2406
+ const time = parsed.searchParams.get("start") ?? parsed.searchParams.get("t");
2407
+ if (time) {
2408
+ const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?$/.exec(time);
2409
+ const seconds = match ? Number(match[1] ?? 0) * 3600 + Number(match[2] ?? 0) * 60 + Number(match[3] ?? 0) : 0;
2410
+ if (seconds > 0) embed.searchParams.set("start", String(seconds));
2411
+ }
2412
+ return { url: embed.href, native: false };
2413
+ }
2414
+ }
2415
+ if (kind === "bilibili" && bilibili) {
2416
+ const id = /\/video\/(BV[\w]+|av\d+)(?:\/|$)/.exec(parsed.pathname)?.[1];
2417
+ const bvid = id?.startsWith("BV") ? id : parsed.hostname === "player.bilibili.com" ? parsed.searchParams.get("bvid") : null;
2418
+ const aid = id?.startsWith("av") ? id.slice(2) : parsed.hostname === "player.bilibili.com" ? parsed.searchParams.get("aid") : null;
2419
+ if (bvid && /^BV[\w]+$/.test(bvid) || aid && /^\d+$/.test(aid)) {
2420
+ const embed = new URL("https://player.bilibili.com/player.html");
2421
+ embed.searchParams.set(bvid ? "bvid" : "aid", bvid || aid);
2422
+ embed.searchParams.set("autoplay", "0");
2423
+ embed.searchParams.set("high_quality", "1");
2424
+ embed.searchParams.set("danmaku", "0");
2425
+ const part = parsed.searchParams.get("p") ?? parsed.searchParams.get("page");
2426
+ if (part && /^[1-9]\d*$/.test(part)) embed.searchParams.set("page", part);
2427
+ return { url: embed.href, native: false };
2428
+ }
2429
+ }
2430
+ }
2431
+ function video(options = {}) {
2432
+ function Video({ node, source: markdown, renderAttribute }) {
2433
+ const runtime = useRuntime();
2434
+ const scrollRoot = useStoreSelector(runtime.configuration, (config) => config.scrollRoot);
2435
+ const element = useRef9(null);
2436
+ const [visible, setVisible] = useState5(false);
2437
+ const [playing, setPlaying] = useState5(false);
2438
+ const [failed, setFailed] = useState5(false);
2439
+ const provider = String(node.attributes?.provider ?? "auto");
2440
+ const source = String(node.attributes?.url ?? node.attributes?.src ?? "");
2441
+ const requested = node.attributes?.loading ?? options.loading ?? "visible";
2442
+ const loading2 = requested === "click" || requested === "eager" ? requested : "visible";
2443
+ const resolved = options.resolveUrl?.(provider, source);
2444
+ const media = resolved && safeUrl(resolved) ? { url: safeUrl(resolved), native: provider === "native" } : resolveVideo(source, provider);
2445
+ useEffect6(() => {
2446
+ setFailed(false);
2447
+ setPlaying(false);
2448
+ }, [source, provider]);
2449
+ useEffect6(() => {
2450
+ if (visible || loading2 !== "visible" || !element.current) return;
2451
+ if (typeof IntersectionObserver === "undefined") {
2452
+ setVisible(true);
2453
+ return;
2454
+ }
2455
+ const observer = new IntersectionObserver((entries) => {
2456
+ if (entries.some((entry) => entry.isIntersecting)) {
2457
+ setVisible(true);
2458
+ observer.disconnect();
2459
+ }
2460
+ }, { root: scrollRoot, rootMargin: "200px" });
2461
+ observer.observe(element.current);
2462
+ return () => observer.disconnect();
2463
+ }, [visible, loading2, scrollRoot]);
2464
+ const enabled = loading2 === "eager" || loading2 === "visible" && visible || playing;
2465
+ const title = String(node.attributes?.title ?? `${provider === "auto" ? "Video" : provider} video`);
2466
+ const original = safeUrl(source);
2467
+ return /* @__PURE__ */ jsxs10("div", { ref: element, className: "limr-video", "data-limr-selection-surface": "", "data-loading": loading2, children: [
2468
+ /* @__PURE__ */ jsx13("div", { className: "limr-video-frame", children: !media || failed ? /* @__PURE__ */ jsxs10("div", { className: "limr-video-error", children: [
2469
+ /* @__PURE__ */ jsx13("span", { children: runtime.locale.unavailable }),
2470
+ original && /* @__PURE__ */ jsx13("a", { href: original, target: "_blank", rel: "noopener noreferrer", children: source })
2471
+ ] }) : enabled ? media.native ? /* @__PURE__ */ jsx13("video", { controls: true, playsInline: true, preload: "metadata", src: media.url, "aria-label": title, onError: () => setFailed(true) }) : /* @__PURE__ */ jsx13("iframe", { src: media.url, title, allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share", allowFullScreen: true, referrerPolicy: "strict-origin-when-cross-origin", onError: () => setFailed(true) }) : /* @__PURE__ */ jsx13("button", { type: "button", className: "limr-video-play", onClick: () => setPlaying(true), "aria-label": runtime.locale.play, children: /* @__PURE__ */ jsx13("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", children: /* @__PURE__ */ jsx13("path", { d: "m8 5 11 7-11 7Z", fill: "currentColor" }) }) }) }),
2472
+ node.attributes?.title && /* @__PURE__ */ jsx13("div", { className: "limr-video-title", children: renderAttribute("title") }),
2473
+ /* @__PURE__ */ jsx13(CopyButton, { className: "limr-video-copy", variant: "glass", value: markdown })
2474
+ ] });
2475
+ }
2476
+ return defineBlock({ name: "video", tags: ["video", "md-video"], component: options.component ?? Video, selection: "atomic" });
2477
+ }
2478
+
2479
+ // src/extensions/figures.tsx
2480
+ import { createContext, useContext as useContext2, useEffect as useEffect7, useMemo as useMemo3, useRef as useRef10, useState as useState6 } from "react";
2481
+
2482
+ // src/extensions/figure-layout.ts
2483
+ var defaultFigureLimits = { minWidth: 220, maxWidth: 560, minHeight: 120, maxHeight: 480 };
2484
+ function figureWidths({ ratio, limits }) {
2485
+ const maximum = Math.min(limits.maxWidth, limits.maxHeight * ratio);
2486
+ return { maximum, minimum: Math.min(maximum, Math.max(limits.minWidth, limits.minHeight * ratio)) };
2487
+ }
2488
+ function figureColumns(width, items, gap, requested, responsive = true) {
2489
+ if (!items.length || width <= 0) return 1;
2490
+ const bounds = items.map(figureWidths);
2491
+ const fits = (count2) => {
2492
+ const slot = (width - (count2 - 1) * gap) / count2;
2493
+ return bounds.every((item) => slot >= item.minimum);
2494
+ };
2495
+ if (requested) {
2496
+ let count2 = Math.max(1, Math.min(24, Math.floor(requested)));
2497
+ if (responsive) while (count2 > 1 && !fits(count2)) count2--;
2498
+ return count2;
2499
+ }
2500
+ const maximum = Math.max(...bounds.map((item) => item.maximum));
2501
+ const minimum = Math.max(...bounds.map((item) => item.minimum));
2502
+ let count = 1;
2503
+ while (count < items.length && count < 24 && width >= count * maximum + count * gap + minimum && fits(count + 1)) count++;
2504
+ return count;
2505
+ }
2506
+ function dimension(value, fallback, optional = false) {
2507
+ if (optional && (value === false || value === "false" || value === "none")) return Infinity;
2508
+ if (typeof value !== "number" && (typeof value !== "string" || !/^\d+(?:\.\d+)?(?:px)?$/.test(value))) return fallback;
2509
+ const number = typeof value === "number" ? value : parseFloat(value);
2510
+ return Number.isFinite(number) && number >= 0 ? number : fallback;
2511
+ }
2512
+ function figureLimits(attributes = {}, defaults2 = defaultFigureLimits) {
2513
+ return {
2514
+ minWidth: dimension(attributes["min-width"], defaults2.minWidth),
2515
+ maxWidth: dimension(attributes["max-width"], defaults2.maxWidth, true),
2516
+ minHeight: dimension(attributes["min-height"], defaults2.minHeight),
2517
+ maxHeight: dimension(attributes["max-height"], defaults2.maxHeight, true)
2518
+ };
2519
+ }
2520
+
2521
+ // src/extensions/figures.tsx
2522
+ import { jsx as jsx14, jsxs as jsxs11 } from "react/jsx-runtime";
2523
+ var FigureContext = createContext(defaultFigureLimits);
2524
+ var captionNode = (node) => node.name === "figcaption" || node.name === "caption";
2525
+ var flatten = (nodes) => nodes.flatMap((node) => node.type === "paragraph" && node.children?.some((child) => child.name === "figure" || captionNode(child)) ? node.children : [node]);
2526
+ var identifier = (node) => node.attributes?.id ? String(node.attributes.id) : void 0;
2527
+ var ratioOf = (width, height) => {
2528
+ const ratio = Number(width) / Number(height);
2529
+ return Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
2530
+ };
2531
+ function figures(options = {}) {
2532
+ const defaults2 = figureLimits({ "min-width": options.minWidth, "max-width": options.maxWidth, "min-height": options.minHeight, "max-height": options.maxHeight });
2533
+ function Figures({ node, renderChildren, renderAttribute, source }) {
2534
+ const locale = useLocale();
2535
+ const nodes = flatten(node.children ?? []);
2536
+ const panels = nodes.filter((child) => child.name === "figure");
2537
+ const captions = nodes.filter(captionNode);
2538
+ const body = nodes.filter((child) => !captionNode(child));
2539
+ const limits = useMemo3(() => figureLimits(node.attributes, defaults2), [node.attributes]);
2540
+ const grid = useRef10(null);
2541
+ const [columns, setColumns] = useState6(1);
2542
+ const gap = Math.min(100, dimension(node.attributes?.gap, options.gap ?? 16));
2543
+ const rows = dimension(node.attributes?.rows, options.rows ?? 0);
2544
+ const requested = dimension(node.attributes?.columns ?? node.attributes?.cols, options.columns ?? 0) || (rows > 0 ? Math.ceil(panels.length / rows) : void 0);
2545
+ const responsive = String(node.attributes?.responsive ?? options.responsive ?? true) !== "false";
2546
+ useEffect7(() => {
2547
+ const element = grid.current;
2548
+ if (!element) return;
2549
+ const measure = () => {
2550
+ const elements = [...element.querySelectorAll(":scope > .limr-figure")];
2551
+ const items = panels.map((panel, index) => {
2552
+ const image = elements[index]?.querySelector("img");
2553
+ const ratio = image?.naturalWidth && image.naturalHeight ? image.naturalWidth / image.naturalHeight : ratioOf(panel.attributes?.width, panel.attributes?.height);
2554
+ return { ratio, limits: figureLimits(panel.attributes, limits) };
2555
+ });
2556
+ setColumns(figureColumns(element.clientWidth, items, gap, requested, responsive));
2557
+ };
2558
+ const observer = new ResizeObserver(measure);
2559
+ observer.observe(element);
2560
+ element.addEventListener("load", measure, true);
2561
+ element.addEventListener("error", measure, true);
2562
+ measure();
2563
+ return () => {
2564
+ observer.disconnect();
2565
+ element.removeEventListener("load", measure, true);
2566
+ element.removeEventListener("error", measure, true);
2567
+ };
2568
+ }, [node, limits, gap, requested, responsive]);
2569
+ return /* @__PURE__ */ jsxs11("figure", { id: identifier(node), className: "limr-figures", "data-limr-selection-order": "visual", "data-columns": columns, "data-responsive": responsive, children: [
2570
+ /* @__PURE__ */ jsx14(CopyButton, { value: source, label: locale.copyFigures, variant: "glass", className: "limr-figures-copy" }),
2571
+ /* @__PURE__ */ jsx14(FigureContext.Provider, { value: limits, children: /* @__PURE__ */ jsx14("div", { ref: grid, className: "limr-figures-grid", style: { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`, gridTemplateRows: rows ? `repeat(${Math.max(1, Math.min(24, Math.floor(rows)))}, auto auto)` : void 0, gap }, children: renderChildren(body) }) }),
2572
+ captions.length ? renderChildren(captions) : node.attributes?.caption ? /* @__PURE__ */ jsx14("figcaption", { children: renderAttribute("caption") }) : null
2573
+ ] });
2574
+ }
2575
+ function Figure({ node, renderChildren, renderAttribute }) {
2576
+ const locale = useLocale();
2577
+ const inherited = useContext2(FigureContext);
2578
+ const limits = figureLimits(node.attributes, inherited === defaultFigureLimits ? defaults2 : inherited);
2579
+ const media = useRef10(null);
2580
+ const [ratio, setRatio] = useState6(ratioOf(node.attributes?.width, node.attributes?.height));
2581
+ const nodes = flatten(node.children ?? []);
2582
+ const captions = nodes.filter(captionNode);
2583
+ const body = nodes.filter((child) => !captionNode(child));
2584
+ useEffect7(() => {
2585
+ const element = media.current;
2586
+ if (!element) return;
2587
+ const measure = () => {
2588
+ const image = element.querySelector("img");
2589
+ if (image?.naturalWidth && image.naturalHeight) setRatio(image.naturalWidth / image.naturalHeight);
2590
+ };
2591
+ measure();
2592
+ element.addEventListener("load", measure, true);
2593
+ return () => element.removeEventListener("load", measure, true);
2594
+ }, [node]);
2595
+ const maximum = figureWidths({ ratio, limits }).maximum;
2596
+ return /* @__PURE__ */ jsxs11("figure", { id: identifier(node), className: "limr-figure", "data-limr-selection-order": "visual", style: {
2597
+ "--limr-figure-width": Number.isFinite(maximum) ? `${maximum}px` : "100%",
2598
+ "--limr-figure-min-height": `${Math.min(limits.minHeight, limits.maxHeight)}px`,
2599
+ "--limr-figure-max-height": Number.isFinite(limits.maxHeight) ? `${limits.maxHeight}px` : "none"
2600
+ }, children: [
2601
+ /* @__PURE__ */ jsx14("div", { ref: media, className: "limr-figure-media", children: renderChildren(body) }),
2602
+ /* @__PURE__ */ jsx14(CopyButton, { onCopy: async () => {
2603
+ const url = media.current?.querySelector("img")?.getAttribute("src");
2604
+ if (!url) throw new Error("Image URL unavailable");
2605
+ await navigator.clipboard.writeText(url);
2606
+ }, label: locale.copyImage, variant: "glass", className: "limr-figure-copy" }),
2607
+ captions.length ? renderChildren(captions) : node.attributes?.caption ? /* @__PURE__ */ jsx14("figcaption", { children: renderAttribute("caption") }) : null
2608
+ ] });
2609
+ }
2610
+ const Caption = ({ children }) => /* @__PURE__ */ jsx14("figcaption", { children });
2611
+ return {
2612
+ name: "figures",
2613
+ tags: ["figures", "figure", "figcaption", "caption", "img"],
2614
+ directives: ["figures", "figure", "figcaption"],
2615
+ scope: "local",
2616
+ display: "block",
2617
+ components: {
2618
+ figures: Figures,
2619
+ figure: Figure,
2620
+ figcaption: Caption,
2621
+ caption: Caption,
2622
+ img: ({ node }) => /* @__PURE__ */ jsx14("img", { src: safeUrl(node.attributes?.src, true), alt: String(node.attributes?.alt ?? ""), loading: "lazy", decoding: "async" })
2623
+ },
2624
+ transform(root) {
2625
+ const visit = (node) => {
2626
+ if (node.type === "component" && node.name === "img") {
2627
+ node.selection = "atomic";
2628
+ node.inline = true;
2629
+ }
2630
+ if (node.type === "component" && node.name === "figure" && (node.attributes?.src || node.attributes?.url)) {
2631
+ const image = node.attributeNodes?.[node.attributes.src ? "src" : "url"];
2632
+ node.children = [{ type: "image", url: node.attributes.src ?? node.attributes.url, alt: node.attributes.alt ?? "", position: image?.position ?? node.position }, ...node.children ?? []];
2633
+ }
2634
+ node.children?.forEach(visit);
2635
+ };
2636
+ visit(root);
2637
+ }
2638
+ };
2639
+ }
2640
+
2641
+ // src/extensions/blocks.tsx
2642
+ import { Fragment as Fragment5, jsx as jsx15, jsxs as jsxs12 } from "react/jsx-runtime";
2643
+ function parts(node, name) {
2644
+ const result = [];
2645
+ walk(node, (child) => {
2646
+ if (child !== node && child.name === name) result.push(child);
2647
+ });
2648
+ return result;
2649
+ }
2650
+ var PassThrough = ({ children }) => /* @__PURE__ */ jsx15(Fragment5, { children });
2651
+ function definition(options = {}) {
2652
+ function Definition({ node, children, renderChildren, renderAttribute }) {
2653
+ const runtime = useRuntime();
2654
+ const title = parts(node, "title")[0];
2655
+ const content = parts(node, "content")[0];
2656
+ return /* @__PURE__ */ jsxs12("aside", { className: "limr-definition", children: [
2657
+ /* @__PURE__ */ jsx15("div", { className: "limr-card-label", "data-limr-ignore": "true", children: runtime.locale.definition }),
2658
+ (title || node.attributes?.title) && /* @__PURE__ */ jsx15("div", { className: "limr-definition-title", children: title ? renderChildren(title.children ?? []) : renderAttribute("title") }),
2659
+ /* @__PURE__ */ jsx15("div", { className: "limr-block-content", children: content ? renderChildren(content.children ?? []) : children })
2660
+ ] });
2661
+ }
2662
+ return { ...defineBlock({ name: "definition", component: options.component ?? Definition }), tags: ["definition", "title", "content"], components: { definition: options.component ?? Definition, title: PassThrough, content: PassThrough } };
2663
+ }
2664
+ function question(options = {}) {
2665
+ function Question({ node, children, renderChildren, renderAttribute }) {
2666
+ const runtime = useRuntime();
2667
+ const [showHint, setHint] = useState7(false), [showAnswer, setAnswer] = useState7(false);
2668
+ const [selected, setSelected] = useState7([]), [checked, setChecked] = useState7(false);
2669
+ const content = parts(node, "question-content")[0];
2670
+ const hint = parts(node, "question-hint")[0];
2671
+ const answer = parts(node, "question-answer")[0];
2672
+ const group = parts(node, "question-sel-grp")[0];
2673
+ const selections = parts(node, "question-sel");
2674
+ const multi = String(group?.attributes?.multi ?? node.attributes?.multi ?? "false") === "true";
2675
+ let correct = [];
2676
+ try {
2677
+ const value = JSON.parse(String(group?.attributes?.answer ?? node.attributes?.answer ?? "[]"));
2678
+ correct = (Array.isArray(value) ? value : [value]).map(Number);
2679
+ } catch {
2680
+ }
2681
+ const success = correct.length === selected.length && correct.every((index) => selected.includes(index));
2682
+ return /* @__PURE__ */ jsxs12("section", { className: "limr-question", children: [
2683
+ /* @__PURE__ */ jsx15("div", { className: "limr-card-label", "data-limr-ignore": "true", children: runtime.locale.question }),
2684
+ node.attributes?.title && /* @__PURE__ */ jsx15("div", { className: "limr-question-title", children: renderAttribute("title") }),
2685
+ /* @__PURE__ */ jsx15("div", { className: "limr-block-content", children: content ? renderChildren(content.children ?? []) : !selections.length && !hint && !answer ? children : null }),
2686
+ selections.length > 0 && /* @__PURE__ */ jsxs12("fieldset", { className: "limr-question-options", children: [
2687
+ /* @__PURE__ */ jsx15("legend", { className: "limr-sr-only", children: String(node.attributes?.title ?? runtime.locale.question) }),
2688
+ selections.map((selection, index) => /* @__PURE__ */ jsxs12("label", { "data-selected": selected.includes(index) || void 0, "data-result": checked ? correct.includes(index) ? "correct" : selected.includes(index) ? "incorrect" : void 0 : void 0, children: [
2689
+ /* @__PURE__ */ jsx15("input", { type: multi ? "checkbox" : "radio", name: `${runtime.document.id}-question-${rangeOf(node).start}`, checked: selected.includes(index), disabled: checked, onChange: () => {
2690
+ setSelected(multi ? selected.includes(index) ? selected.filter((item) => item !== index) : [...selected, index] : [index]);
2691
+ } }),
2692
+ /* @__PURE__ */ jsx15(DiamondCheck, { checked: selected.includes(index) || checked && correct.includes(index) }),
2693
+ /* @__PURE__ */ jsx15("span", { className: "limr-choice-text", children: renderChildren(selection.children ?? []) })
2694
+ ] }, index))
2695
+ ] }),
2696
+ selections.length > 0 && correct.length > 0 && /* @__PURE__ */ jsxs12("div", { className: "limr-question-actions", "data-limr-ignore": "true", children: [
2697
+ /* @__PURE__ */ jsx15("button", { type: "button", "data-checked": checked || void 0, disabled: !checked && !selected.length, onClick: () => {
2698
+ if (checked) {
2699
+ setChecked(false);
2700
+ setSelected([]);
2701
+ setAnswer(false);
2702
+ } else {
2703
+ setChecked(true);
2704
+ setAnswer(true);
2705
+ }
2706
+ }, children: /* @__PURE__ */ jsx15("span", { className: "limr-button-label", children: checked ? runtime.locale.retry : runtime.locale.submit }, checked ? "retry" : "submit") }),
2707
+ /* @__PURE__ */ jsx15(Collapse, { open: checked, children: /* @__PURE__ */ jsx15("span", { role: "status", className: `limr-question-result ${success ? "limr-success" : "limr-error"}`, children: success ? runtime.locale.correct : runtime.locale.incorrect }) })
2708
+ ] }),
2709
+ hint && /* @__PURE__ */ jsx15(Disclosure, { title: runtime.locale.hint, open: showHint, onChange: setHint, children: renderChildren(hint.children ?? []) }),
2710
+ answer && /* @__PURE__ */ jsx15(Disclosure, { title: runtime.locale.answer, open: showAnswer, onChange: setAnswer, children: renderChildren(answer.children ?? []) })
2711
+ ] });
2712
+ }
2713
+ const names2 = ["question-content", "question-hint", "question-answer", "question-sel-grp", "question-sel"];
2714
+ return { ...defineBlock({ name: "question", component: options.component ?? Question }), tags: ["question", ...names2], components: { question: options.component ?? Question, ...Object.fromEntries(names2.map((name) => [name, PassThrough])) } };
2715
+ }
2716
+ function extras(options = {}) {
2717
+ const Extra = ({ node, children, renderAttribute }) => /* @__PURE__ */ jsxs12("div", { className: "limr-extra", children: [
2718
+ /* @__PURE__ */ jsxs12("a", { className: "limr-extra-link", href: safeUrl(node.attributes?.url), target: "_blank", rel: "noreferrer", children: [
2719
+ /* @__PURE__ */ jsx15("span", { className: "limr-underline", children: renderAttribute(node.attributes?.title ? "title" : "url") }),
2720
+ node.attributes?.desc && /* @__PURE__ */ jsx15("p", { children: /* @__PURE__ */ jsx15("span", { className: "limr-underline", children: renderAttribute("desc") }) })
2721
+ ] }),
2722
+ children
2723
+ ] });
2724
+ const Extras = ({ children }) => {
2725
+ const runtime = useRuntime();
2726
+ return /* @__PURE__ */ jsxs12("aside", { className: "limr-extras", children: [
2727
+ /* @__PURE__ */ jsx15("div", { className: "limr-card-label", "data-limr-ignore": "true", children: runtime.locale.extra }),
2728
+ children
2729
+ ] });
2730
+ };
2731
+ return { ...defineBlock({ name: "extras", component: options.component ?? Extras }), tags: ["extras", "extra"], components: { extras: options.component ?? Extras, extra: Extra } };
2732
+ }
2733
+
2734
+ // src/extensions/standard.ts
2735
+ function standard() {
2736
+ return [gfm(), math(), codeHighlight(), definition(), question(), extras(), video(), figures(), citation(), translations()];
2737
+ }
2738
+
2739
+ // src/react/context.tsx
2740
+ import { jsx as jsx16 } from "react/jsx-runtime";
2741
+ var defaults;
2742
+ var RuntimeContext = createContext2(null);
2743
+ var useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect8;
2744
+ function DocumentProvider({ children, source = "", streaming = false, documentId, ...options }) {
2745
+ const generatedId = useId();
2746
+ const extensions = useMemo4(() => {
2747
+ const base = options.extensions ?? (defaults ??= standard());
2748
+ return options.plugins?.length ? [...base, ...options.plugins] : base;
2749
+ }, [options.extensions, options.plugins]);
2750
+ const config = { ...options, extensions };
2751
+ const [runtime] = useState8(() => new ReaderRuntime(documentId ?? `limr-${generatedId.replace(/[^a-z\d_-]/gi, "")}`, source, streaming, config));
2752
+ const previous = useRef11({ source, streaming, config });
2753
+ useIsomorphicLayoutEffect(() => {
2754
+ const old = previous.current;
2755
+ const changed = Object.keys({ ...old.config, ...config }).some((key) => old.config[key] !== config[key]);
2756
+ if (changed) runtime.configure(config);
2757
+ if (old.source !== source || old.streaming !== streaming) runtime.document.update(source, { streaming });
2758
+ previous.current = { source, streaming, config };
2759
+ });
2760
+ useEffect8(() => {
2761
+ runtime.start();
2762
+ return () => runtime.dispose();
2763
+ }, [runtime]);
2764
+ return /* @__PURE__ */ jsx16(RuntimeContext.Provider, { value: runtime, children });
2765
+ }
2766
+ function useRuntime() {
2767
+ const runtime = useContext3(RuntimeContext);
2768
+ if (!runtime) throw new Error("This LiMR component needs a DocumentProvider or Reader. Markdown can also be used on its own.");
2769
+ return runtime;
2770
+ }
2771
+ function useRendererParameter(name) {
2772
+ const runtime = useRuntime();
2773
+ return useStoreSelector(runtime.configuration, (config) => {
2774
+ if (config.parameters?.[name] !== void 0) return config.parameters[name];
2775
+ for (let index = (config.extensions?.length ?? 0) - 1; index >= 0; index--) {
2776
+ const parameters = config.extensions[index].parameters;
2777
+ if (parameters && name in parameters) return parameters[name];
2778
+ }
2779
+ return void 0;
2780
+ });
2781
+ }
2782
+ function useStoreSelector(store, select) {
2783
+ const selectRef = useRef11(select);
2784
+ selectRef.current = select;
2785
+ const cache2 = useRef11(void 0);
2786
+ const get = useCallback2(() => {
2787
+ const state = store.get();
2788
+ if (cache2.current && cache2.current.state === state && cache2.current.select === selectRef.current) return cache2.current.value;
2789
+ const value = selectRef.current(state);
2790
+ cache2.current = { state, select: selectRef.current, value };
2791
+ return value;
2792
+ }, [store]);
2793
+ return useSyncExternalStore(store.subscribe, get, get);
2794
+ }
2795
+ function useDocument() {
2796
+ const runtime = useRuntime();
2797
+ return useSyncExternalStore(runtime.document.subscribe, runtime.document.getSnapshot, runtime.document.getSnapshot);
2798
+ }
2799
+ function useDocumentSelector(select) {
2800
+ const runtime = useRuntime();
2801
+ const store = useMemo4(() => ({ subscribe: runtime.document.subscribe, get: runtime.document.getSnapshot }), [runtime]);
2802
+ return useStoreSelector(store, select);
2803
+ }
2804
+ function useSelection() {
2805
+ return useStoreSelector(useRuntime().interaction, (state) => state.selection);
2806
+ }
2807
+ function useTheme() {
2808
+ return useStoreSelector(useRuntime().configuration, (config) => config.theme ?? "light");
2809
+ }
2810
+ function useAppearance() {
2811
+ return useStoreSelector(useRuntime().configuration, (config) => config.appearance ?? "classic");
2812
+ }
2813
+ function useLocale() {
2814
+ const runtime = useRuntime();
2815
+ useStoreSelector(runtime.configuration, (config) => config.locale);
2816
+ return runtime.locale;
2817
+ }
2818
+ function useAnnotation(id) {
2819
+ return useStoreSelector(useRuntime().decorations, (state) => state.annotations.get(id));
2820
+ }
2821
+ function useAnnotations() {
2822
+ const state = useStoreSelector(useRuntime().decorations, (state2) => state2);
2823
+ return useMemo4(() => ({ annotations: state.annotations, occurrences: state.occurrences }), [state.annotations, state.occurrences]);
2824
+ }
2825
+ function useAnnotationState() {
2826
+ const runtime = useRuntime();
2827
+ const active = useStoreSelector(runtime.interaction, (state) => state.active);
2828
+ const hovered = useStoreSelector(runtime.interaction, (state) => state.hovered);
2829
+ return { active, hovered, activate: (id) => runtime.activate(id), hover: (id) => runtime.hover(id) };
2830
+ }
2831
+ function useAnchor(id) {
2832
+ const runtime = useRuntime();
2833
+ useSyncExternalStore(runtime.layout.subscribe, runtime.layout.get, runtime.layout.get);
2834
+ useSyncExternalStore(runtime.viewport.subscribe, runtime.viewport.get, runtime.viewport.get);
2835
+ const element = runtime.anchors.get(id);
2836
+ return { element: element ?? null, rect: element?.getBoundingClientRect() ?? null, contentRect: runtime.content?.getBoundingClientRect() ?? null };
2837
+ }
2838
+ function useLiMR() {
2839
+ const runtime = useRuntime();
2840
+ return useMemo4(() => ({
2841
+ ...runtime.commands,
2842
+ document: runtime.document,
2843
+ get signal() {
2844
+ return runtime.signal;
2845
+ },
2846
+ clearSelection: () => runtime.clearSelection(),
2847
+ scrollToHeading: (id) => runtime.scrollToHeading(id),
2848
+ scrollToAnnotation: (id) => runtime.scrollToOccurrence(id),
2849
+ invalidateAnnotation: (id) => runtime.invalidateAnnotation(id)
2850
+ }), [runtime]);
2851
+ }
2852
+
2853
+ // src/components/CopyButton.tsx
2854
+ import { jsx as jsx17, jsxs as jsxs13 } from "react/jsx-runtime";
2855
+ function CopyButton({ value = "", onCopy, label, variant = "plain", className = "" }) {
2856
+ const locale = useLocale();
2857
+ const [status, setStatus] = useState9("idle");
2858
+ const timer = useRef12(void 0);
2859
+ const mounted = useRef12(true);
2860
+ const title = status === "copied" ? locale.copied : status === "error" ? locale.copyFailed : label ?? locale.copy;
2861
+ useEffect9(() => {
2862
+ mounted.current = true;
2863
+ return () => {
2864
+ mounted.current = false;
2865
+ clearTimeout(timer.current);
2866
+ };
2867
+ }, []);
2868
+ const copy = async () => {
2869
+ try {
2870
+ if (onCopy) await onCopy();
2871
+ else await navigator.clipboard.writeText(value);
2872
+ if (!mounted.current) return;
2873
+ setStatus("copied");
2874
+ } catch {
2875
+ if (!mounted.current) return;
2876
+ setStatus("error");
2877
+ }
2878
+ clearTimeout(timer.current);
2879
+ timer.current = setTimeout(() => setStatus("idle"), 2200);
2880
+ };
2881
+ return /* @__PURE__ */ jsxs13(
2882
+ "button",
2883
+ {
2884
+ type: "button",
2885
+ className: `limr-copy-button ${className}`,
2886
+ "data-variant": variant,
2887
+ "data-status": status,
2888
+ "data-limr-ignore": "true",
2889
+ "aria-label": title,
2890
+ title,
2891
+ onClick: copy,
2892
+ children: [
2893
+ /* @__PURE__ */ jsxs13("svg", { className: "limr-copy-glyph", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: [
2894
+ /* @__PURE__ */ jsxs13("g", { className: "limr-copy-sheets", children: [
2895
+ /* @__PURE__ */ jsx17("rect", { x: "8.5", y: "8", width: "10.5", height: "12", rx: "3" }),
2896
+ /* @__PURE__ */ jsx17("path", { d: "M15.5 8V6.8A2.8 2.8 0 0 0 12.7 4H7A3 3 0 0 0 4 7v6a3 3 0 0 0 3 3h1.5" })
2897
+ ] }),
2898
+ /* @__PURE__ */ jsx17("path", { className: "limr-copy-check", d: "m5.5 12 4.2 4.2 8.8-9", pathLength: "1" })
2899
+ ] }),
2900
+ /* @__PURE__ */ jsx17("span", { className: status === "error" ? "limr-copy-error" : "limr-sr-only", role: "status", children: status === "copied" ? locale.copied : status === "error" ? locale.copyFailed : "" })
2901
+ ]
2902
+ }
2903
+ );
2904
+ }
2905
+
2906
+ // src/extensions/math.tsx
2907
+ import { jsx as jsx18, jsxs as jsxs14 } from "react/jsx-runtime";
2908
+ var loaded;
2909
+ var loading;
2910
+ var load = () => loading ??= import("./math-renderer-L6DOH4RX.js").then((module) => {
2911
+ loaded = module.default;
2912
+ return module;
2913
+ });
2914
+ var MathContent = lazy(load);
2915
+ async function preloadMath() {
2916
+ await load();
2917
+ }
2918
+ function math(options = {}) {
2919
+ function MathNode({ node }) {
2920
+ const display = node.type === "math";
2921
+ const fallback = /* @__PURE__ */ jsx18("code", { className: "limr-math-source", children: node.value });
2922
+ const Renderer = loaded ?? MathContent;
2923
+ const content = /* @__PURE__ */ jsx18(Suspense, { fallback, children: /* @__PURE__ */ jsx18(Renderer, { value: node.value ?? "", display, options }) });
2924
+ return display ? /* @__PURE__ */ jsxs14("div", { className: "limr-math-block", children: [
2925
+ content,
2926
+ /* @__PURE__ */ jsx18(CopyButton, { className: "limr-math-copy", variant: "glass", label: "Copy LaTeX", value: `$$
2927
+ ${node.value ?? ""}
2928
+ $$` })
2929
+ ] }) : content;
2930
+ }
2931
+ return { name: "math", micromark: [syntax2()], mdast: [mathFromMarkdown()], scope: "local", components: { math: MathNode, inlineMath: MathNode } };
2932
+ }
2933
+
2934
+ // src/components/ToolIcon.tsx
2935
+ import { Fragment as Fragment6, jsx as jsx19, jsxs as jsxs15 } from "react/jsx-runtime";
2936
+ function ToolIcon({ name, ...props }) {
2937
+ return /* @__PURE__ */ jsx19("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", ...props, children: /* @__PURE__ */ jsxs15("g", { transform: name === "highlight" ? "translate(0 -1.25)" : name === "comment" ? "translate(0 -.5)" : void 0, children: [
2938
+ (name === "eye" || name === "eye-off") && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2939
+ /* @__PURE__ */ jsx19("path", { d: "M3 12s3.3-6 9-6 9 6 9 6-3.3 6-9 6-9-6-9-6Z" }),
2940
+ /* @__PURE__ */ jsx19("circle", { cx: "12", cy: "12", r: "2.7" }),
2941
+ name === "eye-off" && /* @__PURE__ */ jsx19("path", { d: "m4 4 16 16" })
2942
+ ] }),
2943
+ name === "question" && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2944
+ /* @__PURE__ */ jsx19("circle", { cx: "12", cy: "12", r: "8.5" }),
2945
+ /* @__PURE__ */ jsx19("path", { d: "M9.4 9a2.7 2.7 0 0 1 5.2 1c0 1.8-2.6 2-2.6 3.7M12 17h.01" })
2946
+ ] }),
2947
+ name === "highlight" && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2948
+ /* @__PURE__ */ jsx19("path", { d: "m8 15 7.6-9a2 2 0 0 1 2.8-.2l.8.7a2 2 0 0 1 .2 2.8L12 18l-4-3Z" }),
2949
+ /* @__PURE__ */ jsx19("path", { d: "m8 15-2 3 3 1 3-1M4 21h10M14 8l4 3.5" })
2950
+ ] }),
2951
+ name === "edit" && /* @__PURE__ */ jsx19(Fragment6, { children: /* @__PURE__ */ jsx19("path", { d: "m14.5 5.5 4 4M4.5 19.5l4.5-1 11-11a2.1 2.1 0 0 0 0-3 2.1 2.1 0 0 0-3 0l-11 11-1.5 4Z" }) }),
2952
+ name === "close" && /* @__PURE__ */ jsx19("path", { d: "m6 6 12 12M18 6 6 18" }),
2953
+ name === "copy" && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2954
+ /* @__PURE__ */ jsx19("rect", { x: "8.5", y: "8", width: "10.5", height: "12", rx: "3" }),
2955
+ /* @__PURE__ */ jsx19("path", { d: "M15.5 8V6.8A2.8 2.8 0 0 0 12.7 4H7A3 3 0 0 0 4 7v6a3 3 0 0 0 3 3h1.5" })
2956
+ ] }),
2957
+ ["background", "underline", "dotted", "wavy"].includes(name) && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2958
+ name === "background" && /* @__PURE__ */ jsx19("rect", { x: "3", y: "3", width: "18", height: "18", rx: "5", fill: "currentColor", fillOpacity: ".13", stroke: "none" }),
2959
+ /* @__PURE__ */ jsx19("path", { d: "m8 15 3-8a1.05 1.05 0 0 1 2 0l3 8M9.2 12h5.6" }),
2960
+ name === "background" && /* @__PURE__ */ jsx19("path", { d: "M7 19h10", strokeWidth: "2.5" }),
2961
+ name === "underline" && /* @__PURE__ */ jsx19("path", { d: "M5 20h14" }),
2962
+ name === "dotted" && /* @__PURE__ */ jsx19("path", { d: "M5 20h14", strokeDasharray: ".1 3.4", strokeWidth: "2.4" }),
2963
+ name === "wavy" && /* @__PURE__ */ jsx19("path", { d: "M4 20c1.3-2 2.7-2 4 0s2.7 2 4 0 2.7-2 4 0 2.7 2 4 0" })
2964
+ ] }),
2965
+ name === "chevron" && /* @__PURE__ */ jsx19("path", { d: "m8 10 4 4 4-4" }),
2966
+ name === "check" && /* @__PURE__ */ jsx19("path", { d: "m5.5 12 4.2 4.2 8.8-9" }),
2967
+ name === "trash" && /* @__PURE__ */ jsx19(Fragment6, { children: /* @__PURE__ */ jsx19("path", { d: "M4.5 7h15M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M7 7l.7 12a2 2 0 0 0 2 2h4.6a2 2 0 0 0 2-2L17 7M10 11v6M14 11v6" }) }),
2968
+ name === "note" && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2969
+ /* @__PURE__ */ jsx19("path", { d: "M14 3H7a3 3 0 0 0-3 3v12a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3V9l-6-6Z" }),
2970
+ /* @__PURE__ */ jsx19("path", { d: "M14 3v4a2 2 0 0 0 2 2h4M8 13h8M8 17h5" })
2971
+ ] }),
2972
+ name === "comment" && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2973
+ /* @__PURE__ */ jsx19("path", { d: "M8 19 4 21V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3H8Z" }),
2974
+ /* @__PURE__ */ jsx19("path", { d: "M8 9h8M8 13h5" })
2975
+ ] }),
2976
+ name === "footnote" && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2977
+ /* @__PURE__ */ jsx19("path", { d: "M5 7h9M5 11h12M5 15h8M5 20h14M18 4h2v5" }),
2978
+ /* @__PURE__ */ jsx19("path", { d: "M17.5 9h4" })
2979
+ ] }),
2980
+ name === "sparkles" && /* @__PURE__ */ jsxs15(Fragment6, { children: [
2981
+ /* @__PURE__ */ jsx19("path", { d: "m10.5 4 1.8 4.8 4.7 1.7-4.7 1.8-1.8 4.7-1.7-4.7L4 10.5l4.8-1.7L10.5 4Z" }),
2982
+ /* @__PURE__ */ jsx19("path", { d: "m19 15 .8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8L19 15ZM19 3v4M17 5h4" })
2983
+ ] })
2984
+ ] }) });
2985
+ }
2986
+
2987
+ // src/extensions/selection-actions.tsx
2988
+ import { jsx as jsx20, jsxs as jsxs16 } from "react/jsx-runtime";
2989
+ var highlightColors = [
2990
+ { color: "#E57373", label: "Rose", labelZh: "\u73AB\u7470" },
2991
+ { color: "#F2C744", label: "Gold", labelZh: "\u6696\u9EC4" },
2992
+ { color: "#81B29A", label: "Sage", labelZh: "\u9F20\u5C3E\u8349" },
2993
+ { color: "#6B9BD2", label: "Blue", labelZh: "\u96FE\u84DD" },
2994
+ { color: "#B39DDB", label: "Lavender", labelZh: "\u85B0\u8863\u8349" },
2995
+ { color: "#E5A06E", label: "Apricot", labelZh: "\u674F\u6A59" },
2996
+ { color: "#61AAA5", label: "Teal", labelZh: "\u9752\u74F7" }
2997
+ ];
2998
+ function copyText(options = {}) {
2999
+ return {
3000
+ id: `copy-${options.format ?? "text"}`,
3001
+ label: options.label ?? ((context) => context.locale.copy),
3002
+ icon: /* @__PURE__ */ jsx20(ToolIcon, { name: "copy" }),
3003
+ successLabel: (context) => context.locale.copied,
3004
+ successIcon: /* @__PURE__ */ jsx20(ToolIcon, { name: "check" }),
3005
+ run: async ({ selection }) => {
3006
+ const format = options.format ?? "text";
3007
+ await navigator.clipboard.writeText(format === "text" ? selection.text : selection[format].sourceText);
3008
+ }
3009
+ };
3010
+ }
3011
+ function HighlightSettings({ context, options }) {
3012
+ const { locale, highlight, highlightAppearance } = context;
3013
+ const color = highlightAppearance.color ?? defaultHighlight.color;
3014
+ const style = highlightAppearance.style ?? "background";
3015
+ const styles = [
3016
+ ["background", locale.highlightBackground],
3017
+ ["underline", locale.highlightUnderline],
3018
+ ["dotted", locale.highlightDotted],
3019
+ ["wavy", locale.highlightWavy]
3020
+ ];
3021
+ const change = (nextColor, nextStyle) => {
3022
+ const appearance = { ...highlightAppearance, color: nextColor, style: nextStyle };
3023
+ context.setHighlightAppearance(appearance);
3024
+ if (highlight) void context.run((current) => current.updateAnnotation(highlight.id, { data: appearance }));
3025
+ };
3026
+ return /* @__PURE__ */ jsxs16("div", { className: "limr-highlight-settings", children: [
3027
+ /* @__PURE__ */ jsxs16("fieldset", { disabled: context.busy, children: [
3028
+ /* @__PURE__ */ jsx20("legend", { children: locale.highlightStyle }),
3029
+ /* @__PURE__ */ jsx20("div", { className: "limr-highlight-styles", children: styles.map(([value, label]) => /* @__PURE__ */ jsxs16("button", { type: "button", "aria-pressed": style === value, onClick: () => change(color, value), children: [
3030
+ /* @__PURE__ */ jsx20(ToolIcon, { name: value }),
3031
+ /* @__PURE__ */ jsx20("span", { className: "limr-highlight-style-label", children: /* @__PURE__ */ jsx20("span", { className: "limr-underline", children: label }) })
3032
+ ] }, value)) })
3033
+ ] }),
3034
+ /* @__PURE__ */ jsxs16("fieldset", { disabled: context.busy, children: [
3035
+ /* @__PURE__ */ jsx20("legend", { children: locale.highlightColor }),
3036
+ /* @__PURE__ */ jsx20("div", { className: "limr-highlight-colors", children: (options.colors ?? highlightColors).map((item) => /* @__PURE__ */ jsx20("button", { type: "button", className: "limr-color-swatch", "aria-label": locale.highlight === "\u9AD8\u4EAE" ? item.labelZh ?? item.label : item.label, title: locale.highlight === "\u9AD8\u4EAE" ? item.labelZh ?? item.label : item.label, "aria-pressed": color.toLowerCase() === item.color.toLowerCase(), style: { "--swatch": item.color }, onClick: () => change(item.color, style), children: /* @__PURE__ */ jsx20(ToolIcon, { name: "check" }) }, item.color)) })
3037
+ ] })
3038
+ ] });
3039
+ }
3040
+ function highlightPalette(options = {}) {
3041
+ return {
3042
+ id: "highlight-palette",
3043
+ label: (context) => context.locale.editHighlight,
3044
+ icon: /* @__PURE__ */ jsx20(ToolIcon, { name: "background" }),
3045
+ placement: "start",
3046
+ render: (context) => /* @__PURE__ */ jsx20("button", { type: "button", className: "limr-toolbar-swatch", "aria-label": context.locale.editHighlight, "aria-expanded": context.expanded, disabled: context.busy, onClick: () => context.expanded ? context.collapse() : context.expand(), style: { "--swatch": context.highlightAppearance.color ?? defaultHighlight.color } }),
3047
+ renderExpanded: (context) => /* @__PURE__ */ jsx20(HighlightSettings, { context, options })
3048
+ };
3049
+ }
3050
+ function highlightSelection() {
3051
+ return {
3052
+ id: "highlight",
3053
+ label: (context) => !context.highlight ? context.locale.addHighlight : context.highlight.data?.hidden ? context.locale.showHighlight : context.locale.hideHighlight,
3054
+ icon: (context) => /* @__PURE__ */ jsx20(ToolIcon, { name: !context.highlight ? "highlight" : context.highlight.data?.hidden ? "eye" : "eye-off" }),
3055
+ visible: (context) => !context.highlight || context.annotations.some((annotation) => annotation.type !== "highlight"),
3056
+ run: (context) => {
3057
+ if (context.highlight) context.updateAnnotation(context.highlight.id, { data: { ...context.highlight.data, hidden: !context.highlight.data?.hidden } });
3058
+ else {
3059
+ context.addAnnotation({ id: `highlight-${crypto.randomUUID()}`, type: "highlight", data: { ...context.highlightAppearance, hidden: false }, anchors: context.selection.syntax.ranges.map((range) => ({ range, documentId: context.document.id, quote: context.document.source.slice(range.start, range.end) })) });
3060
+ context.clearSelection();
3061
+ }
3062
+ }
3063
+ };
3064
+ }
3065
+ function deleteAnnotations() {
3066
+ return {
3067
+ id: "delete-annotations",
3068
+ label: (context) => context.locale.deleteAnnotations,
3069
+ icon: /* @__PURE__ */ jsx20(ToolIcon, { name: "trash" }),
3070
+ placement: "end",
3071
+ tone: "danger",
3072
+ visible: (context) => context.annotations.length > 0,
3073
+ run: (context) => {
3074
+ context.removeAnnotationsAt([...context.selection.raw.ranges, ...context.selection.syntax.ranges]);
3075
+ context.activateAnnotation(null);
3076
+ context.clearSelection();
3077
+ }
3078
+ };
3079
+ }
3080
+
3081
+ export {
3082
+ scrollWithMotion,
3083
+ english,
3084
+ chinese,
3085
+ gfm,
3086
+ preloadMath,
3087
+ math,
3088
+ codeHighlight,
3089
+ sourceRangeStartRect,
3090
+ Markdown,
3091
+ OverlayScrollArea,
3092
+ AnnotationCard,
3093
+ AnnotationMarkdown,
3094
+ citation,
3095
+ InlineMarker,
3096
+ Collapse,
3097
+ translations,
3098
+ defineBlock,
3099
+ defineAnnotation,
3100
+ defineExtension,
3101
+ video,
3102
+ figures,
3103
+ definition,
3104
+ question,
3105
+ extras,
3106
+ standard,
3107
+ useIsomorphicLayoutEffect,
3108
+ DocumentProvider,
3109
+ useRuntime,
3110
+ useRendererParameter,
3111
+ useStoreSelector,
3112
+ useDocument,
3113
+ useDocumentSelector,
3114
+ useSelection,
3115
+ useTheme,
3116
+ useAppearance,
3117
+ useLocale,
3118
+ useAnnotation,
3119
+ useAnnotations,
3120
+ useAnnotationState,
3121
+ useAnchor,
3122
+ useLiMR,
3123
+ ToolIcon,
3124
+ highlightColors,
3125
+ copyText,
3126
+ highlightPalette,
3127
+ highlightSelection,
3128
+ deleteAnnotations
3129
+ };
3130
+ //# sourceMappingURL=chunk-3ILUZKDB.js.map