@bytechain.cn/colamd 1.5.0 → 1.5.1

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 (196) hide show
  1. package/.trae/specs/optimize-theme-loading/checklist.md +20 -0
  2. package/.trae/specs/optimize-theme-loading/spec.md +103 -0
  3. package/.trae/specs/optimize-theme-loading/tasks.md +40 -0
  4. package/CHANGELOG.md +320 -0
  5. package/CLAUDE.md +56 -0
  6. package/README.md +498 -26
  7. package/README_CN.md +554 -27
  8. package/android/app/build/.npmkeep +0 -0
  9. package/android/app/build.gradle +76 -0
  10. package/android/app/capacitor.build.gradle +24 -0
  11. package/android/app/proguard-rules.pro +21 -0
  12. package/android/app/release.keystore +0 -0
  13. package/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java +26 -0
  14. package/android/app/src/main/AndroidManifest.xml +64 -0
  15. package/android/app/src/main/java/cn/bytechain/colamd/MainActivity.java +180 -0
  16. package/android/app/src/main/res/drawable/ic_launcher_background.xml +170 -0
  17. package/android/app/src/main/res/drawable/splash.png +0 -0
  18. package/android/app/src/main/res/drawable-land-hdpi/splash.png +0 -0
  19. package/android/app/src/main/res/drawable-land-mdpi/splash.png +0 -0
  20. package/android/app/src/main/res/drawable-land-xhdpi/splash.png +0 -0
  21. package/android/app/src/main/res/drawable-land-xxhdpi/splash.png +0 -0
  22. package/android/app/src/main/res/drawable-land-xxxhdpi/splash.png +0 -0
  23. package/android/app/src/main/res/drawable-port-hdpi/splash.png +0 -0
  24. package/android/app/src/main/res/drawable-port-mdpi/splash.png +0 -0
  25. package/android/app/src/main/res/drawable-port-xhdpi/splash.png +0 -0
  26. package/android/app/src/main/res/drawable-port-xxhdpi/splash.png +0 -0
  27. package/android/app/src/main/res/drawable-port-xxxhdpi/splash.png +0 -0
  28. package/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml +34 -0
  29. package/android/app/src/main/res/layout/activity_main.xml +12 -0
  30. package/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml +5 -0
  31. package/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml +5 -0
  32. package/android/app/src/main/res/mipmap-hdpi/ic_launcher.png +0 -0
  33. package/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png +0 -0
  34. package/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png +0 -0
  35. package/android/app/src/main/res/mipmap-mdpi/ic_launcher.png +0 -0
  36. package/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png +0 -0
  37. package/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png +0 -0
  38. package/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png +0 -0
  39. package/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png +0 -0
  40. package/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png +0 -0
  41. package/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png +0 -0
  42. package/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png +0 -0
  43. package/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  44. package/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
  45. package/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png +0 -0
  46. package/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  47. package/android/app/src/main/res/values/ic_launcher_background.xml +4 -0
  48. package/android/app/src/main/res/values/strings.xml +7 -0
  49. package/android/app/src/main/res/values/styles.xml +22 -0
  50. package/android/app/src/main/res/xml/file_paths.xml +5 -0
  51. package/android/app/src/main/res/xml/network_security_config.xml +8 -0
  52. package/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java +18 -0
  53. package/android/build.gradle +29 -0
  54. package/android/capacitor.settings.gradle +21 -0
  55. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  56. package/android/gradle/wrapper/gradle-wrapper.properties +7 -0
  57. package/android/gradle.properties +22 -0
  58. package/android/gradlew +248 -0
  59. package/android/gradlew.bat +92 -0
  60. package/android/settings.gradle +5 -0
  61. package/android/variables.gradle +16 -0
  62. package/capacitor.config.js +29 -0
  63. package/capacitor.config.ts +30 -0
  64. package/demo.md +191 -484
  65. package/dist/main/index.js +91 -51
  66. package/dist/preload/index.js +1 -1
  67. package/dist/renderer/assets/{arc-tTbbM8LO.js → arc-_lugyDzx.js} +1 -1
  68. package/dist/renderer/assets/{architectureDiagram-3BPJPVTR-CEgYow6c.js → architectureDiagram-3BPJPVTR-DDfP-F9D.js} +4 -3
  69. package/dist/renderer/assets/{blockDiagram-GPEHLZMM-LHyVtPwW.js → blockDiagram-GPEHLZMM-DOETUKma.js} +5 -4
  70. package/dist/renderer/assets/{c4Diagram-AAUBKEIU-C1P1eJrf.js → c4Diagram-AAUBKEIU-kAmLfVtk.js} +3 -2
  71. package/dist/renderer/assets/{channel-upve91Tq.js → channel-CD4vJFwr.js} +1 -1
  72. package/dist/renderer/assets/{chunk-2J33WTMH-lag2vhq9.js → chunk-2J33WTMH-DkVrgw4l.js} +1 -1
  73. package/dist/renderer/assets/{chunk-4BX2VUAB-BXJ8Ggh-.js → chunk-4BX2VUAB-JTZ-VKNX.js} +1 -1
  74. package/dist/renderer/assets/{chunk-55IACEB6-CiBpxRa1.js → chunk-55IACEB6-Di_O5box.js} +1 -1
  75. package/dist/renderer/assets/{chunk-727SXJPM-ODeKQFXC.js → chunk-727SXJPM-BgKvwR8w.js} +5 -5
  76. package/dist/renderer/assets/{chunk-AQP2D5EJ-BK7xJolB.js → chunk-AQP2D5EJ-DonSXCCQ.js} +3 -3
  77. package/dist/renderer/assets/{chunk-FMBD7UC4-BxpCZPtz.js → chunk-FMBD7UC4-CsV8Lmy6.js} +1 -1
  78. package/dist/renderer/assets/{chunk-ND2GUHAM-CqqaU9Ue.js → chunk-ND2GUHAM-C_-_dlq7.js} +1 -1
  79. package/dist/renderer/assets/{chunk-QZHKN3VN-Biq_K124.js → chunk-QZHKN3VN-aCmcDsfu.js} +1 -1
  80. package/dist/renderer/assets/{classDiagram-v2-Q7XG4LA2-Cq95X99o.js → classDiagram-4FO5ZUOK-nuHQLjzM.js} +7 -6
  81. package/dist/renderer/assets/{classDiagram-4FO5ZUOK-Cq95X99o.js → classDiagram-v2-Q7XG4LA2-nuHQLjzM.js} +7 -6
  82. package/dist/renderer/assets/{cose-bilkent-S5V4N54A-XasiD0bu.js → cose-bilkent-S5V4N54A-Di1_SXt9.js} +2 -1
  83. package/dist/renderer/assets/{dagre-BM42HDAG-Nq84Gfx4.js → dagre-BM42HDAG-CqOUIYsL.js} +4 -3
  84. package/dist/renderer/assets/{diagram-2AECGRRQ-DwuB1GWt.js → diagram-2AECGRRQ-F-fP19TC.js} +4 -3
  85. package/dist/renderer/assets/{diagram-5GNKFQAL-C2tgeI1h.js → diagram-5GNKFQAL-BD5XZc8G.js} +5 -4
  86. package/dist/renderer/assets/{diagram-KO2AKTUF-D5KzjNBc.js → diagram-KO2AKTUF-Qa3ZxA67.js} +4 -3
  87. package/dist/renderer/assets/{diagram-LMA3HP47-C12xHS1c.js → diagram-LMA3HP47-DqDnw2RA.js} +4 -3
  88. package/dist/renderer/assets/{diagram-OG6HWLK6-CnxI9oEa.js → diagram-OG6HWLK6-BH4Elzby.js} +5 -4
  89. package/dist/renderer/assets/{erDiagram-TEJ5UH35-D_uPaKwn.js → erDiagram-TEJ5UH35-CaKZCewa.js} +5 -4
  90. package/dist/renderer/assets/{flowDiagram-I6XJVG4X-B6q_1-tE.js → flowDiagram-I6XJVG4X-C8znUgyL.js} +7 -6
  91. package/dist/renderer/assets/{ganttDiagram-6RSMTGT7-CFo7ifF9.js → ganttDiagram-6RSMTGT7-DnRvbMnU.js} +3 -2
  92. package/dist/renderer/assets/{gitGraphDiagram-PVQCEYII-WSexHTnq.js → gitGraphDiagram-PVQCEYII-CZuRZzk4.js} +5 -4
  93. package/dist/renderer/assets/{graph-DyX_9f6d.js → graph-CYiEKt0j.js} +1 -1
  94. package/dist/renderer/assets/index-B4uDgADr.js +530 -0
  95. package/dist/renderer/assets/{index-DW7LS8C1.js → index-BX6JHKv6.js} +1430 -408
  96. package/dist/renderer/assets/index-CBcVpA3d.js +30 -0
  97. package/dist/renderer/assets/index-CGj1spkU.js +27 -0
  98. package/dist/renderer/assets/{index-dyHEFYvY.css → index-CcwAgVRi.css} +442 -400
  99. package/dist/renderer/assets/index-D4CPFkph.js +9 -0
  100. package/dist/renderer/assets/index-DxOzbfR-.js +110 -0
  101. package/dist/renderer/assets/index-Y89U1ptl.js +9 -0
  102. package/dist/renderer/assets/{infoDiagram-5YYISTIA-DaeJdLRq.js → infoDiagram-5YYISTIA-BlBUdqMb.js} +3 -2
  103. package/dist/renderer/assets/{ishikawaDiagram-YF4QCWOH-DDCZc35f.js → ishikawaDiagram-YF4QCWOH-TeVytCrP.js} +2 -1
  104. package/dist/renderer/assets/{journeyDiagram-JHISSGLW-BEdmpAgl.js → journeyDiagram-JHISSGLW-BLZa3jnX.js} +5 -4
  105. package/dist/renderer/assets/{kanban-definition-UN3LZRKU-BEFtQcFb.js → kanban-definition-UN3LZRKU-foVxWrJn.js} +3 -2
  106. package/dist/renderer/assets/{layout-CAJgQHdw.js → layout-DOAlFUVb.js} +2 -2
  107. package/dist/renderer/assets/{linear-B2ggJ8Am.js → linear-BMBn6kVq.js} +1 -1
  108. package/dist/renderer/assets/{mindmap-definition-RKZ34NQL-DSxVgHB5.js → mindmap-definition-RKZ34NQL-5pGeNCcp.js} +4 -3
  109. package/dist/renderer/assets/{pieDiagram-4H26LBE5-CwYoJBuL.js → pieDiagram-4H26LBE5-N9aAUxfr.js} +5 -4
  110. package/dist/renderer/assets/preload-helper-tXtZnHb0.js +88 -0
  111. package/dist/renderer/assets/{quadrantDiagram-W4KKPZXB-CST9Fvg9.js → quadrantDiagram-W4KKPZXB-BPxbtjga.js} +3 -2
  112. package/dist/renderer/assets/{requirementDiagram-4Y6WPE33-DtrH52jS.js → requirementDiagram-4Y6WPE33-CK1LrJyG.js} +4 -3
  113. package/dist/renderer/assets/{sankeyDiagram-5OEKKPKP-ca1tPzJ_.js → sankeyDiagram-5OEKKPKP-BNj7Sqii.js} +2 -1
  114. package/dist/renderer/assets/{sequenceDiagram-3UESZ5HK-Dfp1EJZ7.js → sequenceDiagram-3UESZ5HK-B-r7lNhI.js} +4 -3
  115. package/dist/renderer/assets/{stateDiagram-AJRCARHV-Bha2QoNB.js → stateDiagram-AJRCARHV-wrWE0MRa.js} +7 -6
  116. package/dist/renderer/assets/{stateDiagram-v2-BHNVJYJU-DWgFUYu1.js → stateDiagram-v2-BHNVJYJU-CE-Lqo2d.js} +5 -4
  117. package/dist/renderer/assets/{timeline-definition-PNZ67QCA-C3h_-OTj.js → timeline-definition-PNZ67QCA-BkeMGH4J.js} +3 -2
  118. package/dist/renderer/assets/{vennDiagram-CIIHVFJN-DFzjSrZi.js → vennDiagram-CIIHVFJN-BTxVzto3.js} +2 -1
  119. package/dist/renderer/assets/{wardley-L42UT6IY-Cx-VbqoS.js → wardley-L42UT6IY-b-_GPpqL.js} +1 -1
  120. package/dist/renderer/assets/{wardleyDiagram-YWT4CUSO-S2D9XqX6.js → wardleyDiagram-YWT4CUSO-D2r5dVGW.js} +4 -3
  121. package/dist/renderer/assets/web-BKE0SH0E.js +36 -0
  122. package/dist/renderer/assets/web-CBsFp24u.js +564 -0
  123. package/dist/renderer/assets/web-Dc8YgoHP.js +24 -0
  124. package/dist/renderer/assets/web-TfDzToU7.js +58 -0
  125. package/dist/renderer/assets/{xychartDiagram-2RQKCTM6-Cfxigbts.js → xychartDiagram-2RQKCTM6-BHQdINVc.js} +3 -2
  126. package/dist/renderer/index.html +62 -3
  127. package/docs/RELEASE_NOTES_v1.5.1.md +382 -0
  128. package/docs/academic-demo.md +567 -0
  129. package/docs/demo.html +748 -0
  130. package/docs/demo.md +546 -0
  131. package/docs/demo.pdf +0 -0
  132. package/docs/theme-paradigm.md +797 -0
  133. package/electron-builder.yml +7 -0
  134. package/electron.vite.config.js +31 -0
  135. package/electron.vite.config.ts +1 -1
  136. package/ios/App/App/AppDelegate.swift +49 -0
  137. package/ios/App/App/Assets.xcassets/AppIcon.appiconset/AppIcon-512@2x.png +0 -0
  138. package/ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json +14 -0
  139. package/ios/App/App/Assets.xcassets/Contents.json +6 -0
  140. package/ios/App/App/Assets.xcassets/Splash.imageset/Contents.json +23 -0
  141. package/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png +0 -0
  142. package/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png +0 -0
  143. package/ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png +0 -0
  144. package/ios/App/App/Base.lproj/LaunchScreen.storyboard +32 -0
  145. package/ios/App/App/Base.lproj/Main.storyboard +19 -0
  146. package/ios/App/App/Info.plist +49 -0
  147. package/ios/App/App.xcodeproj/project.pbxproj +408 -0
  148. package/ios/App/App.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +8 -0
  149. package/ios/App/Podfile +28 -0
  150. package/package.json +23 -3
  151. package/resources/templates/slides/template-forest-ink.html +540 -0
  152. package/scripts/generate-icons.js +102 -0
  153. package/src/main/index.ts +106 -68
  154. package/src/preload/index.d.ts +51 -0
  155. package/src/preload/index.js +70 -0
  156. package/src/preload/index.ts +2 -2
  157. package/src/renderer/capacitor-api.ts +713 -0
  158. package/src/renderer/editor/editor.ts +102 -19
  159. package/src/renderer/editor/plugins/index.ts +42 -32
  160. package/src/renderer/editor/plugins/math-plugin.ts +9 -1
  161. package/src/renderer/editor/plugins/mermaid-plugin-custom.css +13 -398
  162. package/src/renderer/editor/plugins/mermaid-plugin.ts +72 -71
  163. package/src/renderer/editor/plugins/themes/base/dark.css +23 -0
  164. package/src/renderer/editor/plugins/themes/base/elegant.css +32 -0
  165. package/src/renderer/editor/plugins/themes/base/light.css +20 -0
  166. package/src/renderer/editor/plugins/themes/base/newsprint.css +27 -0
  167. package/src/renderer/editor/plugins/themes/components/mermaid/academic.css +43 -0
  168. package/src/renderer/editor/plugins/themes/components/mermaid/dark.css +20 -0
  169. package/src/renderer/editor/plugins/themes/components/mermaid/elegant.css +24 -0
  170. package/src/renderer/editor/plugins/themes/components/mermaid/light.css +21 -0
  171. package/src/renderer/editor/plugins/themes/components/mermaid/newsprint.css +26 -0
  172. package/src/renderer/editor/plugins/themes/components/mermaid/variables.css +592 -0
  173. package/src/renderer/editor/plugins/themes/foundation.css +143 -0
  174. package/src/renderer/editor/plugins/themes/theme-manager.ts +133 -0
  175. package/src/renderer/env.d.ts +4 -1
  176. package/src/renderer/index.html +59 -1
  177. package/src/renderer/main.ts +581 -109
  178. package/src/renderer/mobile.css +428 -0
  179. package/themes/README.md +20 -0
  180. package/themes/academic-paper-pt.css +1321 -0
  181. package/themes/academic-paper.css +1416 -0
  182. package/themes/elegant.css +14 -7
  183. package/themes/forest-ink.css +664 -0
  184. package/themes/pixso-design.css +1261 -0
  185. package/themes/swiss-design.css +596 -0
  186. package/themes/template.css +498 -0
  187. package/tsconfig.main.json +1 -0
  188. package/tsconfig.main.tsbuildinfo +1 -0
  189. package/tsconfig.preload.json +1 -0
  190. package/tsconfig.preload.tsbuildinfo +1 -0
  191. package/tsconfig.renderer.json +1 -0
  192. package/tsconfig.renderer.tsbuildinfo +1 -0
  193. package/tsconfig.tsbuildinfo +1 -0
  194. package/.trae/documents/fix-mermaid-colors-and-sankey.md +0 -50
  195. package/src/renderer/themes/theme-manager.ts +0 -40
  196. /package/src/renderer/{themes → editor/plugins/themes}/base.css +0 -0
@@ -1,10 +1,84 @@
1
- import { createEditor, getMarkdown, getHTML, setMarkdown, togglePluginMode } from './editor/editor'
2
- import { applyTheme, loadSavedTheme } from './themes/theme-manager'
3
- import { getAllPlugins, togglePlugin, findPluginBySelector, findExportCapabilities } from './editor/plugins'
4
- import './themes/base.css'
1
+ import { createEditor, getMarkdown, getHTML, getLiveHTML, setMarkdown, togglePluginMode } from './editor/editor'
2
+ import { applyTheme, loadSavedTheme, setCachedCustomTheme, getActiveCustomThemeCSS, extractPrintCSSFromSheet } from './editor/plugins/themes/theme-manager'
3
+ import { getAllPlugins, togglePlugin, findPluginBySelector, findExportCapabilities, getContextMenuSelector } from './editor/plugins'
4
+ import './editor/plugins/math-plugin'
5
+ import './editor/plugins/mermaid-plugin'
6
+ import { createCapacitorAPI } from './capacitor-api'
7
+ import './editor/plugins/themes/base.css'
8
+ import './mobile.css'
9
+
10
+ /**
11
+ * Show a brief toast notification. Used for save/export feedback.
12
+ */
13
+ function showToast(message: string, duration = 2000): void {
14
+ const existing = document.querySelector('.cola-toast')
15
+ if (existing) existing.remove()
16
+
17
+ const toast = document.createElement('div')
18
+ toast.className = 'cola-toast'
19
+ toast.textContent = message
20
+ toast.style.cssText =
21
+ 'position:fixed;top:56px;left:50%;transform:translateX(-50%);' +
22
+ 'background:rgba(0,0,0,0.8);color:#fff;padding:10px 20px;' +
23
+ 'border-radius:8px;font-size:14px;z-index:9999;pointer-events:none;'
24
+ document.body.appendChild(toast)
25
+
26
+ setTimeout(() => {
27
+ toast.style.opacity = '0'
28
+ toast.style.transition = 'opacity 0.3s'
29
+ setTimeout(() => toast.remove(), 300)
30
+ }, duration)
31
+ }
32
+
33
+ /**
34
+ * 调用原生桥接层检查是否有通过文件管理器 Intent 待打开的文件。
35
+ * 使用 pull 模式:JS 主动向 Java 查询,避免注入时序问题。
36
+ */
37
+ function checkAndOpenPendingFile(api?: any): void {
38
+ const bridge = (window as any).ColaMDNative
39
+ if (!bridge || typeof bridge.checkPendingFile !== 'function') return
40
+ try {
41
+ const result = bridge.checkPendingFile()
42
+ if (result && result !== 'null') {
43
+ const data = JSON.parse(result)
44
+ if (data && data.content) {
45
+ setContent(data.content)
46
+ if (data.name && api?.setCurrentFile) {
47
+ api.setCurrentFile(data.name)
48
+ }
49
+ }
50
+ }
51
+ } catch (e) { /* ignore */ }
52
+ }
53
+
54
+ /**
55
+ * 轮询原生桥接层,获取待打开的文件。
56
+ * Android onNewIntent 在 WebView 重载前触发,需要轮询等待。
57
+ */
58
+ function processPendingIntentFile(api?: any): void {
59
+ checkAndOpenPendingFile(api)
60
+ }
61
+
62
+ // Eagerly load all plugin modules for side-effect registration (registerPluginModule)
63
+ const _pluginRegistry = import.meta.glob<{ default?: unknown }>('./editor/plugins/*-plugin.ts', { eager: true })
64
+ Object.keys(_pluginRegistry)
65
+
66
+ /** Call ensureRendered on all enabled plugins that support it. Used before export. */
67
+ async function ensureAllPluginsRendered(): Promise<void> {
68
+ for (const p of getAllPlugins()) {
69
+ if (p.enabled && p.ensureRendered) await p.ensureRendered()
70
+ }
71
+ }
5
72
 
6
- const pluginModules = import.meta.glob<{ default?: unknown }>('./editor/plugins/*-plugin.ts', { eager: true })
7
- Object.keys(pluginModules)
73
+ /** Re-render nodes of plugins that react to theme changes (e.g. mermaid). */
74
+ function refreshThemeSensitivePlugins(): void {
75
+ for (const p of getAllPlugins()) {
76
+ if (p.enabled && p.nodeTypes && p.onThemeChange) {
77
+ togglePluginMode(p.nodeTypes, 'raw')
78
+ requestAnimationFrame(() => togglePluginMode(p.nodeTypes, 'rendered'))
79
+ }
80
+ }
81
+ }
8
82
 
9
83
  function isSlidesContent(content: string): boolean {
10
84
  return /^---\s*\n[\s\S]*?(kicker|chip):/m.test(content)
@@ -45,36 +119,98 @@ function getContent(): string {
45
119
  return getMarkdown()
46
120
  }
47
121
 
122
+ function syncRawEdits(): void {
123
+ const selectors = getAllPlugins()
124
+ .filter((p) => p.enabled)
125
+ .flatMap((p) => p.rawSelectors || [])
126
+ .join(',')
127
+ if (selectors) {
128
+ document.querySelectorAll(selectors).forEach((el) => {
129
+ if ((el as HTMLElement).matches(':focus')) (el as HTMLElement).blur()
130
+ })
131
+ }
132
+ }
133
+
134
+ function restoreRenderedMode(api: any): void {
135
+ for (const p of getAllPlugins()) {
136
+ if (!p.enabled) {
137
+ p.enabled = true
138
+ togglePluginMode(p.nodeTypes || [], 'rendered')
139
+ api.syncPluginState(p.id, true)
140
+ }
141
+ }
142
+ }
143
+
48
144
  async function init(): Promise<void> {
49
- const api = window.electronAPI
50
- const savedTheme = loadSavedTheme()
51
- applyTheme(savedTheme)
52
-
53
- if (savedTheme.startsWith('custom:')) {
54
- const fileName = savedTheme.slice(7)
55
- const css = await api.loadThemeCSS(fileName)
56
- if (css) applyTheme(savedTheme, css)
145
+ const api = window.electronAPI || await createCapacitorAPI()
146
+
147
+ let editorReady = false
148
+ let pendingFileContent: string | null = null
149
+
150
+ // Register file-open listener AS EARLY AS POSSIBLE
151
+ api.onFileOpened((data) => {
152
+ if (editorReady) {
153
+ setContent(data.content)
154
+ } else {
155
+ pendingFileContent = data.content
156
+ }
157
+ })
158
+
159
+ let savedTheme = loadSavedTheme()
160
+
161
+ try {
162
+ if (savedTheme.startsWith('custom:')) {
163
+ const fileName = savedTheme.slice(7)
164
+ const css = await api.loadThemeCSS(fileName)
165
+ if (css) {
166
+ setCachedCustomTheme(fileName, css)
167
+ applyTheme(savedTheme)
168
+ } else {
169
+ applyTheme('elegant')
170
+ }
171
+ } else {
172
+ applyTheme(savedTheme)
173
+ }
174
+ } catch (e) {
175
+ console.error('Theme initialization failed, falling back to elegant:', e)
176
+ applyTheme('elegant')
177
+ }
178
+
179
+ try {
180
+ await createEditor('editor')
181
+ } catch (e) {
182
+ console.error('Editor initialization failed:', e)
57
183
  }
184
+ editorReady = true
58
185
 
59
- await createEditor('editor')
186
+ if (pendingFileContent !== null) {
187
+ setContent(pendingFileContent)
188
+ pendingFileContent = null
189
+ }
60
190
 
61
- // Run plugin init hooks (mermaid initialize, etc.)
62
191
  for (const p of getAllPlugins()) p.onInit?.()
192
+ checkAndOpenPendingFile(api)
63
193
 
64
- // Send plugin list to main process for menu
65
194
  api.registerPlugins(getAllPlugins().map((p) => ({ id: p.id, name: p.name, enabled: p.enabled })))
66
195
 
67
- // Handle plugin toggle from menu
68
196
  api.onMenuTogglePlugin((id) => {
69
- togglePlugin(id)
70
197
  const p = getAllPlugins().find((x) => x.id === id)
71
198
  if (p) {
199
+ togglePlugin(id, !p.enabled)
72
200
  const mode = p.enabled ? 'rendered' : 'raw'
73
- togglePluginMode(p.nodeTypes, mode)
201
+ togglePluginMode(p.nodeTypes || [], mode)
74
202
  api.syncPluginState(p.id, p.enabled)
75
203
  }
76
204
  })
77
205
 
206
+ // ─── Mobile menu setup ───
207
+ setupMobileMenu(api, savedTheme)
208
+
209
+ // Continuously check for Intent files (Android only, APP already running)
210
+ if (!window.electronAPI) {
211
+ setInterval(() => processPendingIntentFile(api), 3000)
212
+ }
213
+
78
214
  // Slides button — open as slides
79
215
  slidesBtnEl().addEventListener('click', () => api.openAsSlides(getContent()))
80
216
 
@@ -83,97 +219,58 @@ async function init(): Promise<void> {
83
219
  if (result) setContent(result.content)
84
220
  })
85
221
 
86
- function syncRawEdits(): void {
87
- document.querySelectorAll('.math-block-raw, .math-inline-raw, .mermaid-source').forEach((el) => {
88
- if ((el as HTMLElement).matches(':focus')) (el as HTMLElement).blur()
89
- })
90
- }
91
-
92
- function restoreRenderedMode(): void {
93
- for (const p of getAllPlugins()) {
94
- if (!p.enabled) {
95
- p.enabled = true
96
- togglePluginMode(p.nodeTypes, 'rendered')
97
- api.syncPluginState(p.id, true)
98
- }
99
- }
100
- }
101
-
102
222
  api.onMenuSave(async () => {
103
223
  syncRawEdits()
104
224
  const ok = await api.saveFile(getContent())
105
- if (ok) restoreRenderedMode()
225
+ if (ok) {
226
+ showToast('Saved')
227
+ restoreRenderedMode(api)
228
+ } else {
229
+ showToast('Save failed')
230
+ }
106
231
  })
107
232
  api.onMenuSaveAs(async () => {
108
233
  syncRawEdits()
109
234
  const ok = await api.saveFileAs(getContent())
110
- if (ok) restoreRenderedMode()
235
+ if (ok) {
236
+ showToast('Saved')
237
+ restoreRenderedMode(api)
238
+ } else {
239
+ showToast('Save cancelled or failed')
240
+ }
111
241
  })
112
242
  api.onMenuExportPDF(async () => {
113
243
  syncRawEdits()
114
- restoreRenderedMode()
115
- await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))
116
- await api.exportPDF()
117
- })
118
- api.onMenuExportHTML(() => {
119
- const s = getComputedStyle(document.body)
120
- const v = (name: string) => s.getPropertyValue(name).trim()
121
- const bgColor = v('--bg-color')
122
- const textColor = v('--text-color')
123
- const textMuted = v('--text-muted')
124
- const borderColor = v('--border-color')
125
- const linkColor = v('--link-color')
126
- const codeBg = v('--code-bg')
127
- const codeBlockBg = v('--code-block-bg')
128
- const codeBlockText = v('--code-block-text') || textColor
129
- const blockquoteBorder = v('--blockquote-border')
130
- const blockquoteBg = v('--blockquote-bg') || 'transparent'
131
- const tableHeaderBg = v('--table-header-bg')
132
- const selectionBg = v('--selection-bg')
133
-
134
- const editor = document.querySelector('#editor .ProseMirror')
135
- const fontFamily = editor ? getComputedStyle(editor).fontFamily : '-apple-system,BlinkMacSystemFont,sans-serif'
136
-
137
- const getElColor = (selector: string, fallback: string): string => {
138
- const el = document.querySelector(`#editor .ProseMirror ${selector}`)
139
- return el ? getComputedStyle(el).color : fallback
244
+ restoreRenderedMode(api)
245
+ await ensureAllPluginsRendered()
246
+ await new Promise(r => setTimeout(r, 300))
247
+ // 从自定义主题 CSSOM 提取 @media print 规则,注入 DOM 供 printToPDF 使用
248
+ const printCSS = extractPrintCSSFromSheet()
249
+ let printStyleEl: HTMLStyleElement | null = null
250
+ if (printCSS) {
251
+ printStyleEl = document.createElement('style')
252
+ printStyleEl.textContent = printCSS
253
+ document.head.appendChild(printStyleEl)
254
+ // 等待样式生效再导出
255
+ await new Promise(r => requestAnimationFrame(r))
140
256
  }
141
- const strongColor = getElColor('strong', textColor)
142
- const codeColor = getElColor('code', textColor)
143
-
144
- const html = `<!DOCTYPE html>
145
- <html><head><meta charset="utf-8"><title>ColaMD Export</title>
146
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.46/dist/katex.min.css">
147
- <style>
148
- body{max-width:780px;margin:40px auto;padding:20px;font-family:${fontFamily};line-height:1.75;background:${bgColor};color:${textColor}}
149
- h1{font-size:2em;font-weight:700;border-bottom:1px solid ${borderColor};padding-bottom:.3em}
150
- h2{font-size:1.5em;font-weight:600;border-bottom:1px solid ${borderColor};padding-bottom:.25em}
151
- h3{font-size:1.25em;font-weight:600}
152
- strong{color:${strongColor}}
153
- a{color:${linkColor};text-decoration:none}
154
- code{background:${codeBg};color:${codeColor};padding:2px 6px;border-radius:3px;font-size:.875em;font-family:'SF Mono','Fira Code',Menlo,monospace}
155
- pre{background:${codeBlockBg};color:${codeBlockText};padding:16px;border-radius:6px;overflow-x:auto;margin:1em 0}
156
- pre code{background:none;padding:0;color:inherit}
157
- blockquote{border-left:4px solid ${blockquoteBorder};background:${blockquoteBg};padding-left:16px;margin:1em 0;color:${textMuted}}
158
- table{border-collapse:collapse;width:100%;margin:1em 0}
159
- th,td{border:1px solid ${borderColor};padding:8px 12px}
160
- th{background:${tableHeaderBg};font-weight:600}
161
- hr{border:none;border-top:2px solid ${borderColor};margin:2em 0}
162
- img{max-width:100%}
163
- ::selection{background:${selectionBg}}
164
- .math-inline{display:inline;padding:2px 4px;border-radius:3px;background:${codeBg}}
165
- .math-block{display:block;padding:16px;margin:1em 0;border-radius:6px;background:${codeBlockBg};text-align:center;overflow-x:auto}
166
- .mermaid-block{display:block;padding:16px;margin:1em 0;border-radius:6px;background:${codeBlockBg};border:1px solid ${borderColor}}
167
- .mermaid-preview{display:flex;justify-content:center;align-items:center}
168
- .mermaid-preview svg{max-width:100%;height:auto}
169
- .mermaid-preview svg .label text,.mermaid-preview svg .nodeLabel text,.mermaid-preview svg .state-title,.mermaid-preview svg .state-description,.mermaid-preview svg .pieTitleText,.mermaid-preview svg .titleText{transform:translateY(-2px)}.mermaid-preview svg .nodeLabel,.mermaid-preview svg .edgeLabel{display:inline-block;position:relative;top:-2px}
170
- </style>
171
- </head><body>${getHTML()}</body></html>`
172
- api.exportHTML(html)
257
+ // 传递 CSS 到主进程作为保险(insertCSS 双重注入)
258
+ await api.exportPDF(printCSS || undefined)
259
+ if (printStyleEl) printStyleEl.remove()
260
+ setTimeout(() => {
261
+ document.querySelectorAll('.mermaid-loading, .mermaid-error')
262
+ .forEach(el => (el as HTMLElement).style.display = 'none')
263
+ }, 1000)
264
+ })
265
+ api.onMenuExportHTML(async () => {
266
+ syncRawEdits()
267
+ restoreRenderedMode(api)
268
+ await ensureAllPluginsRendered()
269
+ await new Promise(r => setTimeout(r, 200))
270
+ api.exportHTML(buildExportHTML())
173
271
  })
174
272
 
175
273
  api.onNewFile(() => { exitSourceMode(); setMarkdown('') })
176
- api.onFileOpened((data) => setContent(data.content))
177
274
  api.onFileChanged((content) => {
178
275
  if (sourceModeActive) {
179
276
  sourceEl().value = content
@@ -181,20 +278,25 @@ img{max-width:100%}
181
278
  setMarkdown(content)
182
279
  }
183
280
  })
184
- api.onSetTheme((theme) => {
281
+ let pendingThemeChange: string | null = null
282
+ let themeChangeTimer: ReturnType<typeof setTimeout> | null = null
283
+
284
+ function applyThemeChange(theme: string): void {
285
+ pendingThemeChange = null
185
286
  applyTheme(theme)
186
- // Notify all plugins of theme change
187
287
  for (const p of getAllPlugins()) p.onThemeChange?.(theme)
188
- // Force re-render all enabled plugin nodes so they pick up the new theme
189
- for (const p of getAllPlugins()) {
190
- if (p.enabled) {
191
- togglePluginMode(p.nodeTypes, 'raw')
192
- requestAnimationFrame(() => togglePluginMode(p.nodeTypes, 'rendered'))
193
- }
194
- }
288
+ refreshThemeSensitivePlugins()
289
+ }
290
+
291
+ api.onSetTheme((theme) => {
292
+ if (themeChangeTimer) clearTimeout(themeChangeTimer)
293
+ pendingThemeChange = theme
294
+ themeChangeTimer = setTimeout(() => {
295
+ if (pendingThemeChange) applyThemeChange(pendingThemeChange)
296
+ }, 50)
195
297
  })
196
298
  api.onSetCustomCSS((css) => {
197
- const theme = loadSavedTheme()
299
+ const theme = pendingThemeChange || loadSavedTheme()
198
300
  applyTheme(theme, css)
199
301
  })
200
302
 
@@ -216,7 +318,10 @@ img{max-width:100%}
216
318
 
217
319
  api.onMenuImportTheme(async () => {
218
320
  const result = await api.loadCustomTheme()
219
- if (result) applyTheme(`custom:${result.name}`, result.css)
321
+ if (result) {
322
+ setCachedCustomTheme(result.name, result.css)
323
+ applyTheme(`custom:${result.name}`)
324
+ }
220
325
  })
221
326
 
222
327
  const agentDot = document.getElementById('agent-dot')
@@ -257,7 +362,7 @@ img{max-width:100%}
257
362
 
258
363
  document.addEventListener('contextmenu', (e) => {
259
364
  if ((e.target as Element).matches('textarea, input, [contenteditable="true"]')) return
260
- const target = (e.target as Element).closest('.mermaid-block, .math-block') as HTMLElement | null
365
+ const target = (e.target as Element).closest(getContextMenuSelector()) as HTMLElement | null
261
366
  if (!target) return
262
367
  const capabilities = findExportCapabilities(target.className)
263
368
  if (!capabilities.length) return
@@ -300,4 +405,371 @@ img{max-width:100%}
300
405
  })
301
406
  }
302
407
 
408
+ /**
409
+ * 初始化移动端侧边栏菜单的交互逻辑。
410
+ * 包括菜单开关、主题切换、插件开关、文件操作等。
411
+ * @param api 平台 API(Electron 或 Capacitor)
412
+ * @param currentTheme 当前激活的主题名称
413
+ */
414
+ function setupMobileMenu(api: any, currentTheme: string): void {
415
+ const menuEl = document.getElementById('mobile-menu')!
416
+ const menuBtn = document.getElementById('menu-btn')!
417
+ const closeBtn = document.getElementById('menu-close-btn')
418
+ const overlay = document.getElementById('menu-overlay')
419
+ if (!menuEl || !menuBtn) return
420
+
421
+ function openMenu(): void {
422
+ menuEl.classList.add('open')
423
+ }
424
+
425
+ function closeMenu(): void {
426
+ menuEl.classList.remove('open')
427
+ }
428
+
429
+ menuBtn.addEventListener('click', openMenu)
430
+ closeBtn?.addEventListener('click', closeMenu)
431
+ overlay?.addEventListener('click', closeMenu)
432
+
433
+ // 主题列表
434
+ const themes = [
435
+ { key: 'light', label: 'Light' },
436
+ { key: 'dark', label: 'Dark' },
437
+ { key: 'elegant', label: 'Elegant' },
438
+ { key: 'newsprint', label: 'Newsprint' },
439
+ ]
440
+
441
+ const themeListEl = document.getElementById('menu-theme-list')
442
+ if (themeListEl) {
443
+ themeListEl.innerHTML = themes.map((t) =>
444
+ `<div class="menu-theme-item${t.key === currentTheme ? ' active' : ''}" data-theme="${t.key}">${t.label}</div>`
445
+ ).join('')
446
+
447
+ themeListEl.querySelectorAll('.menu-theme-item').forEach((el) => {
448
+ el.addEventListener('click', () => {
449
+ const theme = (el as HTMLElement).dataset.theme!
450
+ applyTheme(theme)
451
+ for (const p of getAllPlugins()) p.onThemeChange?.(theme)
452
+ refreshThemeSensitivePlugins()
453
+ themeListEl.querySelectorAll('.menu-theme-item').forEach((e) => e.classList.remove('active'))
454
+ el.classList.add('active')
455
+ closeMenu()
456
+ })
457
+ })
458
+ }
459
+
460
+ // 插件列表
461
+ const pluginsSection = document.getElementById('menu-plugins-section')
462
+ const pluginListEl = document.getElementById('menu-plugin-list')
463
+ const plugins = getAllPlugins()
464
+ if (pluginsSection && pluginListEl && plugins.length > 0) {
465
+ pluginsSection.style.display = ''
466
+ pluginListEl.innerHTML = plugins.map((p) =>
467
+ `<div class="menu-plugin-item" data-plugin-id="${p.id}"><span>${p.name}</span><div class="menu-plugin-toggle${p.enabled ? ' on' : ''}"></div></div>`
468
+ ).join('')
469
+
470
+ pluginListEl.querySelectorAll('.menu-plugin-item').forEach((el) => {
471
+ el.addEventListener('click', () => {
472
+ const id = (el as HTMLElement).dataset.pluginId!
473
+ const p = getAllPlugins().find((x) => x.id === id)
474
+ if (p) {
475
+ togglePlugin(id, !p.enabled)
476
+ const mode = p.enabled ? 'rendered' : 'raw'
477
+ togglePluginMode(p.nodeTypes || [], mode)
478
+ api.syncPluginState(p.id, p.enabled)
479
+ const toggle = el.querySelector('.menu-plugin-toggle')
480
+ toggle?.classList.toggle('on', p.enabled)
481
+ }
482
+ })
483
+ })
484
+ }
485
+
486
+ // 菜单操作按钮
487
+ menuEl.querySelectorAll('.menu-item').forEach((el) => {
488
+ el.addEventListener('click', async () => {
489
+ const action = (el as HTMLElement).dataset.action
490
+ if (!action) return
491
+ closeMenu()
492
+
493
+ switch (action) {
494
+ case 'new':
495
+ exitSourceMode()
496
+ setMarkdown('')
497
+ break
498
+ case 'open': {
499
+ const result = await api.openFile()
500
+ if (result) setContent(result.content)
501
+ break
502
+ }
503
+ case 'save':
504
+ syncRawEdits()
505
+ {
506
+ const ok = await api.saveFile(getContent())
507
+ if (ok) {
508
+ showToast('Saved')
509
+ restoreRenderedMode(api)
510
+ } else {
511
+ showToast('Save failed')
512
+ }
513
+ }
514
+ break
515
+ case 'save-as':
516
+ syncRawEdits()
517
+ {
518
+ const ok = await api.saveFileAs(getContent())
519
+ if (ok) {
520
+ showToast('Saved')
521
+ restoreRenderedMode(api)
522
+ } else {
523
+ showToast('Save cancelled or failed')
524
+ }
525
+ }
526
+ break
527
+ case 'export-pdf':
528
+ syncRawEdits()
529
+ restoreRenderedMode(api)
530
+ await ensureAllPluginsRendered()
531
+ await new Promise(r => setTimeout(r, 300))
532
+ // 从自定义主题 CSSOM 提取 @media print 规则,注入 DOM 供 printToPDF 使用
533
+ const printCSS = extractPrintCSSFromSheet()
534
+ let printStyleEl: HTMLStyleElement | null = null
535
+ if (printCSS) {
536
+ printStyleEl = document.createElement('style')
537
+ printStyleEl.textContent = printCSS
538
+ document.head.appendChild(printStyleEl)
539
+ // 等待样式生效再导出
540
+ await new Promise(r => requestAnimationFrame(r))
541
+ }
542
+ // 传递 CSS 到主进程作为保险(insertCSS 双重注入)
543
+ await api.exportPDF(printCSS || undefined)
544
+ if (printStyleEl) printStyleEl.remove()
545
+ setTimeout(() => {
546
+ document.querySelectorAll('.mermaid-loading, .mermaid-error')
547
+ .forEach(el => (el as HTMLElement).style.display = 'none')
548
+ }, 1000)
549
+ break
550
+ case 'export-html':
551
+ syncRawEdits()
552
+ restoreRenderedMode(api)
553
+ await ensureAllPluginsRendered()
554
+ await new Promise(r => setTimeout(r, 200))
555
+ api.exportHTML(buildExportHTML())
556
+ break
557
+ case 'export-slides':
558
+ await api.exportSlides(getContent())
559
+ break
560
+ case 'new-slides': {
561
+ const template = await api.newSlides()
562
+ if (template) enterSourceMode(template)
563
+ break
564
+ }
565
+ case 'open-as-slides':
566
+ await api.openAsSlides(getContent())
567
+ break
568
+ case 'import-theme': {
569
+ const result = await api.loadCustomTheme()
570
+ if (result) {
571
+ setCachedCustomTheme(result.name, result.css)
572
+ applyTheme(`custom:${result.name}`)
573
+ }
574
+ break
575
+ }
576
+ case 'about':
577
+ api.openExternal('https://github.com/byteuser1977/ColaMD-extend')
578
+ break
579
+ case 'exit':
580
+ try {
581
+ const { App } = await import('@capacitor/app')
582
+ await App.exitApp()
583
+ } catch {
584
+ window.close()
585
+ }
586
+ break
587
+ }
588
+ })
589
+ })
590
+ }
591
+
592
+ /**
593
+ * 构建导出用的 HTML 字符串,包含当前主题完整样式。
594
+ * 会自动注入自定义主题 CSS、计算实际字号、包含 Mermaid 样式。
595
+ * @returns 完整的 HTML 文档字符串
596
+ */
597
+ function buildExportHTML(): string {
598
+ const bodyStyle = getComputedStyle(document.body)
599
+ const v = (name: string) => bodyStyle.getPropertyValue(name).trim()
600
+
601
+ const bgColor = v('--bg-color')
602
+ const textColor = v('--text-color')
603
+ const textMuted = v('--text-muted')
604
+ const borderColor = v('--border-color')
605
+ const linkColor = v('--link-color')
606
+ const codeBg = v('--code-bg')
607
+ const codeBlockBg = v('--code-block-bg')
608
+ const codeBlockText = v('--code-block-text') || textColor
609
+ const blockquoteBorder = v('--blockquote-border')
610
+ const blockquoteBg = v('--blockquote-bg') || 'transparent'
611
+ const tableHeaderBg = v('--table-header-bg')
612
+ const selectionBg = v('--selection-bg')
613
+
614
+ // ── Read actual computed font metrics from editor ──
615
+ const editor = document.querySelector('#editor .ProseMirror')
616
+ const editorStyle = editor ? getComputedStyle(editor) : bodyStyle
617
+ const fontFamily = editorStyle.fontFamily || '-apple-system,BlinkMacSystemFont,sans-serif'
618
+ const bodyFontSize = editorStyle.fontSize || '16px'
619
+ const bodyLineHeight = editorStyle.lineHeight || '1.75'
620
+
621
+ const getElFontSize = (tag: string, fallback: string): string => {
622
+ const el = document.querySelector(`#editor .ProseMirror ${tag}`)
623
+ return el ? getComputedStyle(el).fontSize : fallback
624
+ }
625
+ const getElFontWeight = (tag: string, fallback: string): string => {
626
+ const el = document.querySelector(`#editor .ProseMirror ${tag}`)
627
+ return el ? getComputedStyle(el).fontWeight : fallback
628
+ }
629
+ const getElColor = (selector: string, fallback: string): string => {
630
+ const el = document.querySelector(`#editor .ProseMirror ${selector}`)
631
+ return el ? getComputedStyle(el).color : fallback
632
+ }
633
+ const strongColor = getElColor('strong', textColor)
634
+ const codeColor = getElColor('code', textColor)
635
+
636
+ // ── Collect CSS custom properties as :root block ──
637
+ const cssVarLines = collectExportCSSVariables(v)
638
+
639
+ // ── Collect plugin export styles ──
640
+ let pluginCSS = ''
641
+ for (const p of getAllPlugins()) {
642
+ if (p.enabled && p.exportStyles) {
643
+ pluginCSS += `\n/* === ${p.name} === */\n${p.exportStyles}\n`
644
+ }
645
+ }
646
+
647
+ // ── Collect active theme CSS ──
648
+ let themeCSS = ''
649
+ let bodyClass = ''
650
+
651
+ if (document.body.classList.contains('theme-custom')) {
652
+ bodyClass = 'theme-custom'
653
+ // Inject full custom theme CSS
654
+ const customCSS = getActiveCustomThemeCSS()
655
+ if (customCSS) {
656
+ themeCSS += `\n/* === Custom Theme: ${loadSavedTheme()} === */\n${customCSS}\n`
657
+ }
658
+ // Inject Mermaid custom theme text styling
659
+ themeCSS += `\n/* === Mermaid Custom Text Styles === */\n${getMermaidCustomCSS()}\n`
660
+ } else {
661
+ for (const cls of ['theme-light', 'theme-dark', 'theme-elegant', 'theme-newsprint']) {
662
+ if (document.body.classList.contains(cls)) {
663
+ bodyClass = cls
664
+ break
665
+ }
666
+ }
667
+ }
668
+ const isCustomTheme = bodyClass === 'theme-custom'
669
+
670
+ return `<!DOCTYPE html>
671
+ <html><head><meta charset="utf-8"><title>ColaMD Export</title>
672
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.46/dist/katex.min.css">
673
+ <style>
674
+ :root {
675
+ ${cssVarLines}
676
+ }
677
+ ${themeCSS}
678
+ ${pluginCSS}
679
+ /* === Base Element Styles === */
680
+ body{max-width:780px;margin:40px auto;padding:20px;font-size:${bodyFontSize};font-family:${fontFamily};line-height:${bodyLineHeight};background:${bgColor};color:${textColor}}
681
+ ${isCustomTheme ? '' : `h1{font-size:${getElFontSize('h1', '2em')};font-weight:${getElFontWeight('h1', '700')};border-bottom:1px solid ${borderColor};padding-bottom:.3em}
682
+ h2{font-size:${getElFontSize('h2', '1.5em')};font-weight:${getElFontWeight('h2', '600')};border-bottom:1px solid ${borderColor};padding-bottom:.25em}
683
+ h3{font-size:${getElFontSize('h3', '1.25em')};font-weight:${getElFontWeight('h3', '600')}}
684
+ h4{font-size:${getElFontSize('h4', '1.1em')};font-weight:${getElFontWeight('h4', '600')}}
685
+ h5{font-size:${getElFontSize('h5', '1em')};font-weight:${getElFontWeight('h5', '600')}}
686
+ h6{font-size:${getElFontSize('h6', '0.9em')};font-weight:${getElFontWeight('h6', '600')}}
687
+ strong{color:${strongColor}}
688
+ a{color:${linkColor};text-decoration:none}
689
+ code{background:${codeBg};color:${codeColor};padding:2px 6px;border-radius:3px;font-size:.875em;font-family:'SF Mono','Fira Code',Menlo,monospace}
690
+ pre{background:${codeBlockBg};color:${codeBlockText};padding:16px;border-radius:6px;overflow-x:auto;margin:1em 0}
691
+ pre code{background:none;padding:0;color:inherit}
692
+ blockquote{border-left:4px solid ${blockquoteBorder};background:${blockquoteBg};padding-left:16px;margin:1em 0;color:${textMuted}}
693
+ table{border-collapse:collapse;width:100%;margin:1em 0}
694
+ th,td{border:1px solid ${borderColor};padding:8px 12px}
695
+ th{background:${tableHeaderBg};font-weight:600}
696
+ hr{border:none;border-top:2px solid ${borderColor};margin:2em 0}`}
697
+ img{max-width:100%}
698
+ ::selection{background:${selectionBg}}
699
+ ${(() => {
700
+ if (isCustomTheme) {
701
+ console.log('[buildExportHTML] Custom theme — skipping hardcoded @page/@media print, using theme CSS rules')
702
+ return ''
703
+ }
704
+ console.log('[buildExportHTML] Built-in theme — emitting hardcoded @page/@media print fallback')
705
+ return `@page{margin:15mm;size:A4}
706
+ @media print{body{max-width:none;margin:0;padding:20px}#editor{position:static!important;overflow:visible!important}}`
707
+ })()}
708
+ </style>
709
+ </head><body class="${bodyClass}">${getLiveHTML()}</body></html>`
710
+ }
711
+
712
+ /** 收集当前主题的 CSS 自定义属性,作为 :root 兜底变量 */
713
+ function collectExportCSSVariables(v: (name: string) => string): string {
714
+ const varNames = [
715
+ '--seed-accent', '--seed-accent-light', '--seed-accent-dark',
716
+ '--seed-surface', '--seed-panel', '--seed-panel-alt',
717
+ '--seed-ink', '--seed-ink-muted', '--seed-ink-dim',
718
+ '--seed-border', '--seed-border-strong',
719
+ '--font-size-root',
720
+ '--font-scale-h1', '--font-scale-h2', '--font-scale-h3',
721
+ '--font-scale-h4', '--font-scale-h5', '--font-scale-h6',
722
+ '--font-size-mermaid',
723
+ '--line-height-body', '--line-height-heading', '--line-height-code',
724
+ '--bg-color', '--text-color', '--heading-color', '--text-muted', '--text-dim',
725
+ '--link-color', '--accent-color', '--accent-dark', '--accent-light', '--selection-bg',
726
+ '--border-color', '--blockquote-border', '--hr-color',
727
+ '--code-bg', '--code-color', '--code-block-bg', '--code-block-text',
728
+ '--blockquote-bg', '--table-header-bg', '--table-header-text', '--table-border',
729
+ '--scrollbar-thumb', '--scrollbar-thumb-hover',
730
+ '--surface-color', '--surface-alt',
731
+ '--mermaid-background', '--mermaid-border-color', '--mermaid-border-radius', '--mermaid-padding',
732
+ '--mermaid-font-family', '--mermaid-font-size',
733
+ '--mermaid-node-fill', '--mermaid-node-stroke', '--mermaid-node-stroke-width', '--mermaid-node-text',
734
+ '--mermaid-edge-stroke', '--mermaid-edge-stroke-width',
735
+ '--mermaid-cluster-fill', '--mermaid-cluster-stroke',
736
+ '--mermaid-label-text', '--mermaid-edge-label-text', '--mermaid-edge-label-bg',
737
+ '--mermaid-title-text', '--mermaid-axis-text', '--mermaid-highlight',
738
+ '--mermaid-person-stroke', '--mermaid-person-fill',
739
+ '--mermaid-label-offset-y',
740
+ '--radius-sm', '--radius-md', '--radius-lg', '--content-width'
741
+ ]
742
+ const lines: string[] = []
743
+ for (const name of varNames) {
744
+ const val = v(name)
745
+ if (val) lines.push(` ${name}: ${val};`)
746
+ }
747
+ return lines.join('\n')
748
+ }
749
+
750
+ /** Mermaid 自定义主题 SVG 文字样式,注入到导出 HTML 中 */
751
+ function getMermaidCustomCSS(): string {
752
+ return `.theme-custom .mermaid-preview svg text {
753
+ fill: var(--mermaid-text-color, var(--text-color)) !important;
754
+ font-family: var(--mermaid-font-family, inherit) !important;
755
+ font-size: var(--mermaid-font-size, 12px) !important;
756
+ }
757
+ .theme-custom .mermaid-preview svg foreignObject span {
758
+ color: var(--mermaid-text-color, var(--text-color)) !important;
759
+ font-family: var(--mermaid-font-family, inherit) !important;
760
+ font-size: var(--mermaid-font-size, 14px) !important;
761
+ }
762
+ .theme-custom .mermaid-preview svg .person-man text { fill: #ffffff !important; }
763
+ .theme-custom .mermaid-preview svg .person-man span { color: #ffffff !important; }
764
+ .theme-custom .mermaid-preview svg .label text,
765
+ .theme-custom .mermaid-preview svg .nodeLabel text,
766
+ .theme-custom .mermaid-preview svg .state-title,
767
+ .theme-custom .mermaid-preview svg .state-description,
768
+ .theme-custom .mermaid-preview svg .pieTitleText,
769
+ .theme-custom .mermaid-preview svg .titleText { transform: translateY(-3px) !important; }
770
+ .theme-custom .mermaid-preview svg .xychart .axis text { transform: translateY(0) !important; }
771
+ .theme-custom .mermaid-preview svg .nodeLabel,
772
+ .theme-custom .mermaid-preview svg .edgeLabel { display: inline-block !important; position: relative !important; top: -3px !important; }
773
+ `
774
+ }
303
775
  init().catch((e) => console.error('ColaMD init failed:', e))