index.html 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  6. <title>Text</title>
  7. <script src="../script/jquery.min.js"></script>
  8. <script src="../script/ao_module.js"></script>
  9. <script src="lib/marked.min.js"></script>
  10. <script src="lib/turndown.min.js"></script>
  11. <script src="lib/turndown-plugin-gfm.min.js"></script>
  12. <script src="lib/pdf-lib.min.js"></script>
  13. <script src="highlighter.js"></script>
  14. <script src="rtf.js"></script>
  15. <style>
  16. *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  17. :root {
  18. --toolbar-h: 42px;
  19. --statusbar-h: 22px;
  20. --bg: #e4e9f2;
  21. --toolbar-bg: #f6f7fb;
  22. --toolbar-bdr: #e2e4ec;
  23. --editor-bg: #ffffff;
  24. --text: #2b2f38;
  25. --text2: #8a90a2;
  26. --accent: #2f6bd8;
  27. --accent-soft: rgba(47,107,216,.12);
  28. --sep: #d7dbe6;
  29. --hover: rgba(0,0,0,.06);
  30. --btn-active-bg:#2f6bd8;
  31. --btn-active-fg:#fff;
  32. --dirty-color: #2f6bd8;
  33. --code-bg: #f1f3f8;
  34. --quote-bdr: #d2d8e6;
  35. --table-bdr: #dfe3ec;
  36. --shadow: 0 10px 40px rgba(30,40,70,.18);
  37. --hl-com: #6a9955;
  38. --hl-str: #b5402a;
  39. --hl-num: #1c7d4d;
  40. --hl-kw: #1f4fce;
  41. --hl-typ: #117a8b;
  42. --hl-fn: #8a5a18;
  43. }
  44. body.dark {
  45. --bg: #0f131b;
  46. --toolbar-bg: #161c27;
  47. --toolbar-bdr: #232c3b;
  48. --editor-bg: #121722;
  49. --text: #d6def0;
  50. --text2: #6b7793;
  51. --accent: #5b9cf6;
  52. --accent-soft: rgba(91,156,246,.16);
  53. --sep: #2a3445;
  54. --hover: rgba(255,255,255,.07);
  55. --btn-active-bg:#5b9cf6;
  56. --btn-active-fg:#0f131b;
  57. --dirty-color: #5b9cf6;
  58. --code-bg: #1b2230;
  59. --quote-bdr: #313c50;
  60. --table-bdr: #2a3445;
  61. --shadow: 0 10px 40px rgba(0,0,0,.55);
  62. --hl-com: #6a9955;
  63. --hl-str: #ce9178;
  64. --hl-num: #b5cea8;
  65. --hl-kw: #569cd6;
  66. --hl-typ: #4ec9b0;
  67. --hl-fn: #dcdcaa;
  68. }
  69. html, body {
  70. height: 100%;
  71. background: var(--bg);
  72. color: var(--text);
  73. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  74. font-size: 13px;
  75. }
  76. #app { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
  77. /* ── Toolbar ──────────────────────────────────────────────────────── */
  78. #toolbar {
  79. display: flex; align-items: center; gap: 1px; flex-shrink: 0;
  80. height: var(--toolbar-h); padding: 0 8px;
  81. background: var(--toolbar-bg);
  82. border-bottom: 1px solid var(--toolbar-bdr);
  83. box-shadow: 0 1px 4px rgba(0,0,0,.06);
  84. overflow-x: auto; overflow-y: hidden; position: relative; z-index: 5;
  85. scrollbar-width: thin;
  86. }
  87. #toolbar::-webkit-scrollbar { height: 4px; }
  88. #toolbar::-webkit-scrollbar-thumb { background: var(--sep); border-radius: 3px; }
  89. .tb-btn {
  90. display: inline-flex; align-items: center; gap: 4px; height: 28px;
  91. padding: 0 8px; border: none; border-radius: 6px; background: none;
  92. color: var(--text); font-size: 12px; font-family: inherit; cursor: pointer;
  93. white-space: nowrap; flex-shrink: 0; transition: background .1s; user-select: none;
  94. }
  95. .tb-btn:hover { background: var(--hover); }
  96. .tb-btn.active { background: var(--btn-active-bg); color: var(--btn-active-fg); }
  97. .tb-btn svg { display: block; }
  98. .tb-btn .glyph { width: 15px; text-align: center; font-size: 13px; line-height: 1; }
  99. .tb-sep { width: 1px; height: 20px; background: var(--sep); flex-shrink: 0; margin: 0 4px; }
  100. .tb-spacer { flex: 1 1 auto; min-width: 6px; }
  101. .tb-label { font-size: 11px; color: var(--text2); flex-shrink: 0; white-space: nowrap; }
  102. .tb-select {
  103. height: 26px; padding: 0 6px; border: 1px solid var(--toolbar-bdr);
  104. border-radius: 6px; background: var(--editor-bg); color: var(--text);
  105. font-size: 12px; font-family: inherit; outline: none; cursor: pointer;
  106. flex-shrink: 0; transition: border-color .1s;
  107. }
  108. .tb-select:focus { border-color: var(--accent); }
  109. /* dropdown menu (export / image) */
  110. .menu-wrap { position: relative; flex-shrink: 0; }
  111. .menu {
  112. display: none; position: fixed; min-width: 180px;
  113. background: var(--editor-bg); border: 1px solid var(--toolbar-bdr);
  114. border-radius: 10px; box-shadow: var(--shadow); padding: 6px; z-index: 120;
  115. }
  116. .menu.show { display: block; }
  117. .menu-item {
  118. display: flex; align-items: center; gap: 9px; width: 100%; padding: 8px 10px;
  119. border: none; background: none; color: var(--text); font-size: 12.5px;
  120. font-family: inherit; border-radius: 7px; cursor: pointer; text-align: left;
  121. }
  122. .menu-item:hover { background: var(--accent-soft); }
  123. .menu-item svg { flex-shrink: 0; color: var(--text2); }
  124. /* hide markdown-only controls when editing plain text */
  125. body.mode-txt .md-only { display: none !important; }
  126. /* rich-text (RTF) mode: its own formatting controls, minus markdown-only ones */
  127. body.mode-rtf .no-rtf { display: none !important; }
  128. body:not(.mode-rtf) .rtf-only { display: none !important; }
  129. /* colour swatch dropdowns (RTF text colour / highlight) */
  130. .swatch-menu { min-width: 0; width: 176px; }
  131. .swatch-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 5px; padding: 4px 2px 2px; }
  132. .swatch {
  133. width: 22px; height: 22px; border-radius: 5px; cursor: pointer; padding: 0;
  134. border: 1px solid rgba(0,0,0,.18);
  135. }
  136. .swatch:hover { transform: scale(1.12); }
  137. .glyph-color { display: inline-flex; flex-direction: column; align-items: center; width: 15px; line-height: 1; }
  138. .glyph-color b { font-size: 13px; }
  139. .glyph-color i { display: block; width: 14px; height: 3px; border-radius: 1px; margin-top: 1px; }
  140. /* ── Editor surfaces ──────────────────────────────────────────────── */
  141. #editor-scroll {
  142. flex: 1; min-height: 0; overflow-y: auto; background: var(--editor-bg);
  143. transition: background .2s, color .2s; position: relative;
  144. }
  145. #rich, #plain {
  146. max-width: 820px; margin: 0 auto; min-height: 100%;
  147. padding: 40px clamp(18px, 6vw, 60px) 120px;
  148. outline: none; color: var(--text); line-height: 1.7;
  149. font-size: 16px; word-wrap: break-word;
  150. }
  151. #plain {
  152. display: none; width: 100%; border: none; resize: none; background: none;
  153. font-family: 'SF Mono', 'Consolas', 'Courier New', monospace;
  154. font-size: 14px; white-space: pre-wrap; tab-size: 4; -moz-tab-size: 4;
  155. }
  156. body.mode-txt #rich { display: none; }
  157. body.mode-txt #plain { display: block; }
  158. /* RTF keeps spaces and tabs significant */
  159. body.mode-rtf #rich p, body.mode-rtf #rich li, body.mode-rtf #rich td, body.mode-rtf #rich th,
  160. body.mode-rtf #rich h1, body.mode-rtf #rich h2, body.mode-rtf #rich h3,
  161. body.mode-rtf #rich h4, body.mode-rtf #rich h5, body.mode-rtf #rich h6 { white-space: pre-wrap; tab-size: 4; }
  162. /* keep highlighted runs readable on the dark theme */
  163. body.dark.mode-rtf #rich [style*="background-color"] { color: #1d2230; }
  164. #rich:empty::before, #rich.is-empty::before {
  165. content: attr(data-ph); color: var(--text2); pointer-events: none;
  166. }
  167. /* ── Markdown content typography (shared by editor + export) ──────── */
  168. .md-content h1, .md-content h2, .md-content h3,
  169. .md-content h4, .md-content h5, .md-content h6 {
  170. font-weight: 700; line-height: 1.3; margin: 1.4em 0 .6em;
  171. }
  172. .md-content h1 { font-size: 2em; border-bottom: 1px solid var(--sep); padding-bottom: .25em; }
  173. .md-content h2 { font-size: 1.6em; border-bottom: 1px solid var(--sep); padding-bottom: .2em; }
  174. .md-content h3 { font-size: 1.3em; }
  175. .md-content h4 { font-size: 1.1em; }
  176. .md-content h5 { font-size: 1em; }
  177. .md-content h6 { font-size: .9em; color: var(--text2); }
  178. .md-content p { margin: .55em 0; }
  179. .md-content a { color: var(--accent); text-decoration: none; }
  180. .md-content a:hover { text-decoration: underline; }
  181. .md-content ul, .md-content ol { margin: .5em 0; padding-left: 1.7em; }
  182. .md-content li { margin: .25em 0; }
  183. .md-content blockquote {
  184. margin: .8em 0; padding: .2em 1em; color: var(--text2);
  185. border-left: 3px solid var(--quote-bdr); background: var(--accent-soft);
  186. border-radius: 0 6px 6px 0;
  187. }
  188. .md-content code {
  189. font-family: 'SF Mono', 'Consolas', 'Courier New', monospace; font-size: .88em;
  190. background: var(--code-bg); padding: .15em .4em; border-radius: 4px;
  191. }
  192. .md-content pre {
  193. margin: .8em 0; padding: 14px 16px; background: var(--code-bg);
  194. border-radius: 8px; overflow-x: auto; position: relative;
  195. }
  196. .md-content pre code { background: none; padding: 0; font-size: .85em; line-height: 1.55; }
  197. /* syntax highlight tokens (see highlighter.js) — theme-aware via vars */
  198. .hl-com { color: var(--hl-com); font-style: italic; }
  199. .hl-str { color: var(--hl-str); }
  200. .hl-num { color: var(--hl-num); }
  201. .hl-kw { color: var(--hl-kw); }
  202. .hl-typ { color: var(--hl-typ); }
  203. .hl-fn { color: var(--hl-fn); }
  204. .md-content hr { border: none; border-top: 1px solid var(--sep); margin: 1.6em 0; }
  205. .md-content img { max-width: 100%; border-radius: 6px; vertical-align: middle; }
  206. .md-content table { border-collapse: collapse; margin: .8em 0; width: auto; max-width: 100%; }
  207. .md-content th, .md-content td { border: 1px solid var(--table-bdr); padding: 6px 12px; }
  208. .md-content th { background: var(--code-bg); font-weight: 600; }
  209. .md-content ul.contains-task-list { list-style: none; padding-left: 1.2em; }
  210. .md-content li.task-list-item { list-style: none; }
  211. .md-content input[type=checkbox] { margin-right: .5em; }
  212. /* ── Markdown source-mark hints (Typora-style reveal) ─────────────────
  213. Shown via pseudo-elements gated by the .md-active class, which is set
  214. on the active block (or every block, in "always" mode) by
  215. updateActiveBlock(). Because these are pseudo-elements they never enter
  216. the DOM model — serialization, word count and editing are untouched. */
  217. #rich h1.md-active::before { content: "# "; }
  218. #rich h2.md-active::before { content: "## "; }
  219. #rich h3.md-active::before { content: "### "; }
  220. #rich h4.md-active::before { content: "#### "; }
  221. #rich h5.md-active::before { content: "##### "; }
  222. #rich h6.md-active::before { content: "###### "; }
  223. #rich blockquote.md-active > *:first-child::before { content: "> "; }
  224. #rich .md-active strong::before, #rich .md-active strong::after,
  225. #rich .md-active b::before, #rich .md-active b::after { content: "**"; }
  226. #rich .md-active em::before, #rich .md-active em::after,
  227. #rich .md-active i::before, #rich .md-active i::after { content: "*"; }
  228. #rich .md-active del::before, #rich .md-active del::after,
  229. #rich .md-active s::before, #rich .md-active s::after,
  230. #rich .md-active strike::before, #rich .md-active strike::after { content: "~~"; }
  231. #rich .md-active code::before, #rich .md-active code::after { content: "`"; }
  232. #rich .md-active a::before { content: "["; }
  233. /* shared mark appearance: muted + semi-transparent so it reads as a hint
  234. and never as content; not selectable since it's a pseudo-element. */
  235. #rich .md-active::before, #rich .md-active::after,
  236. #rich .md-active *::before, #rich .md-active *::after {
  237. color: var(--text2); opacity: .42; font-weight: 400; font-style: normal;
  238. }
  239. /* <img> is a replaced element and can't host pseudo-content, so its
  240. ![alt](src) mark is a real, editable label inserted above the image by
  241. updateActiveBlock(). Editing it re-points the image (see syncImgFromSyn);
  242. it is stripped from the document on serialize. */
  243. #rich .md-imgsyn {
  244. display: block; width: fit-content; max-width: 100%;
  245. font-family: 'SF Mono','Consolas','Courier New',monospace;
  246. font-size: .78em; color: var(--text2); opacity: .62;
  247. margin-bottom: 5px; padding: 1px 4px; line-height: 1.4;
  248. word-break: break-all; outline: none; cursor: text; border-radius: 4px;
  249. }
  250. #rich .md-imgsyn:hover { opacity: .85; }
  251. #rich .md-imgsyn:focus {
  252. opacity: 1; color: var(--text); background: var(--code-bg);
  253. box-shadow: inset 0 0 0 1px var(--accent);
  254. }
  255. /* <a>'s closing "](url)" mark — unlike the rest of the bracket hints
  256. this needs to be real, editable text (not a pseudo-element) so the
  257. URL itself is directly clickable/editable, same idea as md-imgsyn
  258. but inline since a link sits inside a run of prose. */
  259. #rich .md-linksyn {
  260. font-family: 'SF Mono','Consolas','Courier New',monospace;
  261. font-size: .85em; color: var(--text2); opacity: .55;
  262. outline: none; cursor: text; border-radius: 3px; padding: 0 1px;
  263. }
  264. #rich .md-linksyn:hover { opacity: .8; }
  265. #rich .md-linksyn:focus {
  266. opacity: 1; color: var(--text); background: var(--code-bg);
  267. box-shadow: inset 0 0 0 1px var(--accent);
  268. }
  269. /* code-block language picker — a real, interactive <select> pinned to
  270. the block's top-right corner while the caret is inside it (see
  271. syncLangSelector); a contenteditable="false" island appended after
  272. <code> so it never disturbs the caret and is invisible to turndown
  273. (which only reads pre's firstChild). Stripped on serialize. */
  274. #rich .md-langsel { position: absolute; top: 6px; right: 6px; z-index: 2; }
  275. #rich .md-langsel-select {
  276. height: 22px; padding: 0 4px; border: 1px solid var(--toolbar-bdr);
  277. border-radius: 5px; background: var(--editor-bg); color: var(--text2);
  278. font-size: 11px; font-family: inherit; outline: none; cursor: pointer;
  279. opacity: .55; transition: opacity .15s;
  280. }
  281. #rich .md-langsel-select:hover, #rich .md-langsel-select:focus {
  282. opacity: 1; color: var(--text); border-color: var(--accent);
  283. }
  284. /* ── Status bar ───────────────────────────────────────────────────── */
  285. #statusbar {
  286. flex-shrink: 0; height: var(--statusbar-h); display: flex; align-items: center;
  287. justify-content: space-between; padding: 0 12px; background: var(--toolbar-bg);
  288. border-top: 1px solid var(--toolbar-bdr); font-size: 10.5px; color: var(--text2);
  289. }
  290. #status-msg.dirty { color: var(--dirty-color); }
  291. #status-msg.error { color: #d9534f; }
  292. #status-right { display: flex; gap: 12px; align-items: center; }
  293. /* ── Settings panel ───────────────────────────────────────────────── */
  294. .overlay {
  295. display: none; position: fixed; inset: 0; background: rgba(10,15,25,.45);
  296. backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px);
  297. z-index: 200; align-items: center; justify-content: center; padding: 20px;
  298. }
  299. .overlay.show { display: flex; }
  300. #settings-box {
  301. background: var(--editor-bg); border: 1px solid var(--toolbar-bdr);
  302. border-radius: 14px; box-shadow: var(--shadow); width: 760px; max-width: 100%;
  303. height: 520px; max-height: 90vh; display: flex; overflow: hidden;
  304. }
  305. #settings-nav {
  306. width: 180px; flex-shrink: 0; background: var(--toolbar-bg);
  307. border-right: 1px solid var(--toolbar-bdr); padding: 14px 10px; overflow-y: auto;
  308. }
  309. #settings-nav .nav-title { font-size: 13px; font-weight: 700; padding: 4px 10px 12px; }
  310. .nav-item {
  311. display: flex; align-items: center; gap: 9px; width: 100%; padding: 9px 10px;
  312. border: none; background: none; color: var(--text); font-size: 13px;
  313. font-family: inherit; border-radius: 8px; cursor: pointer; text-align: left; margin-bottom: 2px;
  314. }
  315. .nav-item:hover { background: var(--hover); }
  316. .nav-item.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
  317. .nav-item svg { flex-shrink: 0; }
  318. #settings-body { flex: 1; padding: 22px 26px; overflow-y: auto; }
  319. .settings-section { display: none; }
  320. .settings-section.active { display: block; }
  321. .settings-section h2 { font-size: 16px; font-weight: 700; margin-bottom: 4px; }
  322. .settings-section .sub { font-size: 12px; color: var(--text2); margin-bottom: 18px; }
  323. .set-row {
  324. display: flex; align-items: center; justify-content: space-between;
  325. gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--toolbar-bdr);
  326. }
  327. .set-row:last-child { border-bottom: none; }
  328. .set-label { font-size: 13px; font-weight: 600; }
  329. .set-desc { font-size: 11.5px; color: var(--text2); margin-top: 2px; }
  330. .set-ctl { flex-shrink: 0; }
  331. .set-input, .set-select {
  332. height: 30px; padding: 0 8px; border: 1px solid var(--toolbar-bdr);
  333. border-radius: 7px; background: var(--editor-bg); color: var(--text);
  334. font-size: 12.5px; font-family: inherit; outline: none;
  335. }
  336. .set-input:focus, .set-select:focus { border-color: var(--accent); }
  337. .set-input.num { width: 76px; }
  338. /* toggle switch */
  339. .switch { position: relative; display: inline-block; width: 42px; height: 24px; flex-shrink: 0; }
  340. .switch input { opacity: 0; width: 0; height: 0; }
  341. .slider {
  342. position: absolute; cursor: pointer; inset: 0; background: var(--sep);
  343. border-radius: 24px; transition: .2s;
  344. }
  345. .slider::before {
  346. content: ""; position: absolute; height: 18px; width: 18px; left: 3px; bottom: 3px;
  347. background: #fff; border-radius: 50%; transition: .2s; box-shadow: 0 1px 3px rgba(0,0,0,.3);
  348. }
  349. .switch input:checked + .slider { background: var(--accent); }
  350. .switch input:checked + .slider::before { transform: translateX(18px); }
  351. /* segmented control (mode) */
  352. .seg { display: inline-flex; border: 1px solid var(--toolbar-bdr); border-radius: 8px; overflow: hidden; }
  353. .seg button {
  354. border: none; background: var(--editor-bg); color: var(--text); font-family: inherit;
  355. font-size: 12.5px; padding: 7px 14px; cursor: pointer;
  356. }
  357. .seg button.active { background: var(--accent); color: #fff; }
  358. /* shortcuts list */
  359. .key-row {
  360. display: flex; align-items: center; justify-content: space-between;
  361. padding: 9px 0; border-bottom: 1px solid var(--toolbar-bdr);
  362. }
  363. .key-row .key-name { font-size: 13px; }
  364. .key-cap {
  365. min-width: 120px; text-align: center; padding: 6px 10px; border-radius: 7px;
  366. border: 1px solid var(--toolbar-bdr); background: var(--code-bg); color: var(--text);
  367. font-size: 12px; font-family: 'SF Mono','Consolas',monospace; cursor: pointer;
  368. }
  369. .key-cap:hover { border-color: var(--accent); }
  370. .key-cap.recording { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
  371. .range-wrap { display: flex; align-items: center; gap: 10px; }
  372. input[type=range] { accent-color: var(--accent); }
  373. .btn-text {
  374. border: 1px solid var(--toolbar-bdr); background: var(--editor-bg); color: var(--text);
  375. font-family: inherit; font-size: 12.5px; padding: 7px 14px; border-radius: 8px; cursor: pointer;
  376. }
  377. .btn-text:hover { background: var(--hover); }
  378. .btn-text.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
  379. #settings-foot {
  380. display: flex; justify-content: flex-end; gap: 8px; padding-top: 16px; margin-top: 8px;
  381. }
  382. /* ── Confirm dialog ───────────────────────────────────────────────── */
  383. #confirm-box {
  384. background: var(--editor-bg); border: 1px solid var(--toolbar-bdr);
  385. border-radius: 13px; padding: 24px 24px 18px; width: 320px; box-shadow: var(--shadow);
  386. }
  387. #confirm-box h3 { font-size: 15px; font-weight: 700; margin-bottom: 8px; }
  388. #confirm-box p { font-size: 12.5px; color: var(--text2); line-height: 1.55; margin-bottom: 18px; }
  389. .confirm-row { display: flex; gap: 8px; justify-content: flex-end; }
  390. .cbtn {
  391. padding: 7px 14px; border-radius: 7px; font-size: 12.5px; font-weight: 600;
  392. font-family: inherit; cursor: pointer; border: none; transition: opacity .1s;
  393. }
  394. .cbtn:hover { opacity: .88; }
  395. .cbtn-cancel { background: var(--hover); color: var(--text); border: 1px solid var(--toolbar-bdr); }
  396. .cbtn-discard { background: rgba(217,83,79,.14); color: #d9534f; border: 1px solid rgba(217,83,79,.32); }
  397. .cbtn-save { background: var(--accent); color: #fff; }
  398. /* ── Link editor dialog ───────────────────────────────────────────── */
  399. #link-box {
  400. background: var(--editor-bg); border: 1px solid var(--toolbar-bdr);
  401. border-radius: 13px; padding: 24px 24px 18px; width: 340px; box-shadow: var(--shadow);
  402. }
  403. #link-box h3 { font-size: 15px; font-weight: 700; margin-bottom: 14px; }
  404. .link-field { margin-bottom: 12px; }
  405. .link-field label { display: block; font-size: 11.5px; color: var(--text2); margin-bottom: 5px; }
  406. .link-field input {
  407. width: 100%; box-sizing: border-box; padding: 8px 10px; border-radius: 7px;
  408. border: 1px solid var(--toolbar-bdr); background: var(--code-bg); color: var(--text);
  409. font-family: inherit; font-size: 13px; outline: none;
  410. }
  411. .link-field input:focus { border-color: var(--accent); }
  412. .link-row { display: flex; gap: 8px; justify-content: flex-end; }
  413. .link-row .cbtn-discard { margin-right: auto; }
  414. /* busy spinner for export */
  415. #busy {
  416. display: none; position: fixed; inset: 0; z-index: 400; align-items: center;
  417. justify-content: center; background: rgba(10,15,25,.4); color: #fff; font-size: 13px;
  418. flex-direction: column; gap: 14px;
  419. }
  420. #busy.show { display: flex; }
  421. .spin {
  422. width: 34px; height: 34px; border: 3px solid rgba(255,255,255,.25);
  423. border-top-color: #fff; border-radius: 50%; animation: spin .8s linear infinite;
  424. }
  425. @keyframes spin { to { transform: rotate(360deg); } }
  426. /* ── Responsive ───────────────────────────────────────────────────── */
  427. @media (max-width: 680px) {
  428. .tb-label, .tb-btn .tb-text { display: none; }
  429. #toolbar {
  430. height: auto;
  431. padding: 6px;
  432. gap: 4px;
  433. flex-wrap: wrap;
  434. align-content: flex-start;
  435. justify-content: flex-start;
  436. overflow-x: hidden;
  437. overflow-y: auto;
  438. }
  439. .tb-btn {
  440. min-width: 34px;
  441. min-height: 34px;
  442. padding: 0 9px;
  443. }
  444. .tb-select {
  445. height: 34px;
  446. max-width: 100%;
  447. }
  448. .tb-sep, .tb-spacer { display: none; }
  449. .menu-wrap { display: inline-flex; }
  450. #settings-box { flex-direction: column; height: 92vh; }
  451. #settings-nav {
  452. width: 100%; display: flex; gap: 4px; overflow-x: auto; padding: 8px;
  453. border-right: none; border-bottom: 1px solid var(--toolbar-bdr);
  454. }
  455. #settings-nav .nav-title { display: none; }
  456. .nav-item { width: auto; white-space: nowrap; margin-bottom: 0; }
  457. #rich, #plain { padding: 24px 16px 100px; font-size: 15px; }
  458. .set-row { flex-direction: column; align-items: stretch; }
  459. .set-ctl { align-self: flex-start; }
  460. }
  461. @media (max-width: 480px) {
  462. /*#sel-head {
  463. flex: 1 1 100%;
  464. width: 100% !important;
  465. }*/
  466. }
  467. @media print {
  468. #toolbar, #statusbar, .overlay, #busy { display: none !important; }
  469. #editor-scroll { overflow: visible; }
  470. #rich, #plain { max-width: 100%; padding: 0; }
  471. }
  472. </style>
  473. </head>
  474. <body>
  475. <div id="app">
  476. <!-- ── Toolbar ──────────────────────────────────────────────────────── -->
  477. <div id="toolbar">
  478. <button class="tb-btn" onclick="openFile()" title="Open file">
  479. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
  480. <!-- <span class="tb-text">Open</span> -->
  481. </button>
  482. <button class="tb-btn" onclick="saveFile()" title="Save (Ctrl+S)">
  483. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
  484. <!-- <span class="tb-text">Save</span> -->
  485. </button>
  486. <div class="tb-sep md-only"></div>
  487. <!-- Heading / block format -->
  488. <select id="sel-head" class="tb-select md-only" style="width:104px;" onchange="onHeadingSelect()" title="Paragraph style">
  489. <option value="p">Paragraph</option>
  490. <option value="h1">Heading 1</option>
  491. <option value="h2">Heading 2</option>
  492. <option value="h3">Heading 3</option>
  493. <option value="h4">Heading 4</option>
  494. <option value="h5">Heading 5</option>
  495. <option value="h6">Heading 6</option>
  496. </select>
  497. <div class="tb-sep md-only"></div>
  498. <button class="tb-btn md-only" id="btn-bold" onclick="actBold()" title="Bold"><span class="glyph"><strong>B</strong></span></button>
  499. <button class="tb-btn md-only" id="btn-italic" onclick="actItalic()" title="Italic"><span class="glyph"><em>I</em></span></button>
  500. <button class="tb-btn md-only" id="btn-strike" onclick="actStrike()" title="Strikethrough"><span class="glyph"><s>S</s></span></button>
  501. <button class="tb-btn rtf-only" id="btn-underline" onclick="actUnderline()" title="Underline"><span class="glyph"><u>U</u></span></button>
  502. <button class="tb-btn md-only no-rtf" id="btn-code" onclick="actInlineCode()" title="Inline code"><span class="glyph" style="font-family:monospace;">&lt;&gt;</span></button>
  503. <div class="menu-wrap rtf-only">
  504. <button class="tb-btn" onclick="toggleMenu('fore-menu')" title="Text colour">
  505. <span class="glyph-color"><b>A</b><i id="fore-bar" style="background:#c00000;"></i></span>
  506. </button>
  507. <div class="menu swatch-menu" id="fore-menu"></div>
  508. </div>
  509. <div class="menu-wrap rtf-only">
  510. <button class="tb-btn" onclick="toggleMenu('back-menu')" title="Highlight colour">
  511. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l-6 6v3h9l3-3"/><path d="M22 12l-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"/></svg>
  512. </button>
  513. <div class="menu swatch-menu" id="back-menu"></div>
  514. </div>
  515. <select id="sel-size" class="tb-select rtf-only" style="width:58px;" onchange="actFontSize()" title="Font size (pt)">
  516. <option value="">Size</option>
  517. <option>8</option><option>9</option><option>10</option><option>11</option><option>12</option>
  518. <option>14</option><option>16</option><option>18</option><option>20</option><option>24</option>
  519. <option>28</option><option>36</option><option>48</option><option>72</option>
  520. </select>
  521. <div class="tb-sep rtf-only"></div>
  522. <button class="tb-btn rtf-only" id="btn-align-left" onclick="actAlign('Left')" title="Align left">
  523. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="15" y2="12"/><line x1="3" y1="18" x2="18" y2="18"/></svg>
  524. </button>
  525. <button class="tb-btn rtf-only" id="btn-align-center" onclick="actAlign('Center')" title="Center">
  526. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="7" y1="12" x2="17" y2="12"/><line x1="5" y1="18" x2="19" y2="18"/></svg>
  527. </button>
  528. <button class="tb-btn rtf-only" id="btn-align-right" onclick="actAlign('Right')" title="Align right">
  529. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="9" y1="12" x2="21" y2="12"/><line x1="6" y1="18" x2="21" y2="18"/></svg>
  530. </button>
  531. <button class="tb-btn rtf-only" id="btn-align-full" onclick="actAlign('Full')" title="Justify">
  532. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
  533. </button>
  534. <div class="tb-sep md-only"></div>
  535. <button class="tb-btn md-only no-rtf" onclick="actQuote()" title="Blockquote">
  536. <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M7 7h4v4H8.5c0 1.4.6 2 2 2v2c-2.5 0-3.5-1.5-3.5-4V7zm7 0h4v4h-2.5c0 1.4.6 2 2 2v2c-2.5 0-3.5-1.5-3.5-4V7z"/></svg>
  537. </button>
  538. <button class="tb-btn md-only" onclick="actBullet()" title="Bullet list">
  539. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4" cy="6" r="1.3" fill="currentColor" stroke="none"/><circle cx="4" cy="12" r="1.3" fill="currentColor" stroke="none"/><circle cx="4" cy="18" r="1.3" fill="currentColor" stroke="none"/></svg>
  540. </button>
  541. <button class="tb-btn md-only" onclick="actNumber()" title="Numbered list">
  542. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="10" y1="6" x2="20" y2="6"/><line x1="10" y1="12" x2="20" y2="12"/><line x1="10" y1="18" x2="20" y2="18"/><text x="2" y="8" font-size="7" fill="currentColor" stroke="none">1</text><text x="2" y="14" font-size="7" fill="currentColor" stroke="none">2</text><text x="2" y="20" font-size="7" fill="currentColor" stroke="none">3</text></svg>
  543. </button>
  544. <button class="tb-btn md-only no-rtf" onclick="actCodeBlock()" title="Code block">
  545. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
  546. </button>
  547. <div class="tb-sep md-only"></div>
  548. <button class="tb-btn md-only" onclick="actLink()" title="Link">
  549. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1.5-1.5"/></svg>
  550. </button>
  551. <div class="menu-wrap md-only">
  552. <button class="tb-btn" id="btn-image" onclick="toggleMenu('img-menu')" title="Insert image">
  553. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
  554. </button>
  555. <div class="menu" id="img-menu">
  556. <button class="menu-item" onclick="hideMenus();pickDeviceImage()">
  557. <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
  558. From this device
  559. </button>
  560. <button class="menu-item" onclick="hideMenus();pickServerImage()">
  561. <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
  562. From server
  563. </button>
  564. <!-- <button class="menu-item" onclick="hideMenus();insertImageByUrl()">
  565. <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1.5 1.5"/></svg>
  566. By URL
  567. </button> -->
  568. </div>
  569. </div>
  570. <div class="tb-spacer"></div>
  571. <button class="tb-btn" id="theme-btn" onclick="toggleTheme()" title="Toggle theme">
  572. <svg id="icon-sun" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
  573. <svg id="icon-moon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
  574. </button>
  575. <div class="menu-wrap">
  576. <button class="tb-btn" onclick="toggleMenu('export-menu')" title="Export">
  577. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
  578. <span class="tb-text">Export</span>
  579. </button>
  580. <div class="menu" id="export-menu">
  581. <button class="menu-item" onclick="hideMenus();savePDFToArozOS()">
  582. <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/></svg>
  583. Save as PDF…
  584. </button>
  585. <button class="menu-item" id="mi-download" onclick="hideMenus();exportDocument()">
  586. <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
  587. <span id="mi-download-lbl">Download document</span>
  588. </button>
  589. <button class="menu-item" onclick="hideMenus();exportHTML()">
  590. <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
  591. Export as HTML
  592. </button>
  593. <button class="menu-item" onclick="hideMenus();exportPDF()">
  594. <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
  595. Export as PDF
  596. </button>
  597. </div>
  598. </div>
  599. <button class="tb-btn" onclick="openSettings()" title="Settings">
  600. <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
  601. </button>
  602. </div>
  603. <!-- ── Editor ───────────────────────────────────────────────────────── -->
  604. <div id="editor-scroll">
  605. <div id="rich" class="md-content" contenteditable="true" spellcheck="false"
  606. data-ph="Start writing… type # for a heading, ** for bold"></div>
  607. <textarea id="plain" spellcheck="false" placeholder="Start typing…"></textarea>
  608. </div>
  609. <!-- ── Status bar ───────────────────────────────────────────────────── -->
  610. <div id="statusbar">
  611. <span id="status-msg">Ready</span>
  612. <div id="status-right">
  613. <span id="stat-mode">Markdown</span>
  614. <span id="stat-count">0 words</span>
  615. </div>
  616. </div>
  617. </div>
  618. <!-- hidden file input for device image picking -->
  619. <input type="file" id="device-file" accept="image/*" style="display:none;">
  620. <!-- ── Settings overlay ─────────────────────────────────────────────────── -->
  621. <div class="overlay" id="settings-overlay">
  622. <div id="settings-box">
  623. <div id="settings-nav">
  624. <div class="nav-title">Preferences</div>
  625. <button class="nav-item active" data-sec="general" onclick="showSection('general')">
  626. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
  627. General
  628. </button>
  629. <button class="nav-item" data-sec="keys" onclick="showSection('keys')">
  630. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="12" rx="2"/><line x1="6" y1="10" x2="6" y2="10"/><line x1="10" y1="10" x2="10" y2="10"/><line x1="14" y1="10" x2="14" y2="10"/><line x1="8" y1="14" x2="16" y2="14"/></svg>
  631. Shortcuts
  632. </button>
  633. <button class="nav-item" data-sec="images" onclick="showSection('images')">
  634. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
  635. Images
  636. </button>
  637. </div>
  638. <div id="settings-body">
  639. <!-- General -->
  640. <div class="settings-section active" id="sec-general">
  641. <h2>General</h2>
  642. <div class="sub">Editor behaviour and appearance.</div>
  643. <div class="set-row">
  644. <div><div class="set-label">Document mode</div><div class="set-desc">Markdown enables live formatting; Rich text saves as RTF (fonts, colours, alignment); Plain text edits raw characters.</div></div>
  645. <div class="set-ctl"><div class="seg" id="seg-mode">
  646. <button data-mode="md" onclick="setMode('md')">Markdown</button>
  647. <button data-mode="rtf" onclick="setMode('rtf')">Rich text</button>
  648. <button data-mode="txt" onclick="setMode('txt')">Plain text</button>
  649. </div></div>
  650. </div>
  651. <div class="set-row md-only no-rtf">
  652. <div><div class="set-label">Markdown syntax</div><div class="set-desc">Reveal the markdown marks (#, **, &gt;, …) so you can see and edit the source.</div></div>
  653. <div class="set-ctl"><select class="set-select" id="set-syntax" onchange="applySyntaxMode()">
  654. <option value="active">Show on selected line</option>
  655. <option value="always">Always show</option>
  656. <option value="none">Always hide</option>
  657. </select></div>
  658. </div>
  659. <div class="set-row">
  660. <div><div class="set-label">Dark theme</div><div class="set-desc">Match a dark workspace.</div></div>
  661. <div class="set-ctl"><label class="switch"><input type="checkbox" id="set-dark" onchange="setTheme(this.checked)"><span class="slider"></span></label></div>
  662. </div>
  663. <div class="set-row">
  664. <div><div class="set-label">Editor font</div></div>
  665. <div class="set-ctl"><select class="set-select" id="set-font" onchange="applyTypography()">
  666. <option value="system">System Default</option>
  667. <option value="serif">Serif</option>
  668. <option value="mono">Monospace</option>
  669. <option value="georgia">Georgia</option>
  670. <option value="times">Times New Roman</option>
  671. </select></div>
  672. </div>
  673. <div class="set-row">
  674. <div><div class="set-label">Font size</div></div>
  675. <div class="set-ctl"><input type="number" min="11" max="32" class="set-input num" id="set-fontsize" onchange="applyTypography()"> px</div>
  676. </div>
  677. <div class="set-row">
  678. <div><div class="set-label">Line spacing</div></div>
  679. <div class="set-ctl"><select class="set-select" id="set-lh" onchange="applyTypography()">
  680. <option value="1.4">Compact</option>
  681. <option value="1.7">Relaxed</option>
  682. <option value="2.0">Double</option>
  683. </select></div>
  684. </div>
  685. </div>
  686. <!-- Shortcuts -->
  687. <div class="settings-section" id="sec-keys">
  688. <h2>Keyboard Shortcuts</h2>
  689. <div class="sub">Click a shortcut, then press the new key combination. Press Esc to cancel.</div>
  690. <div id="keys-list"></div>
  691. <div id="settings-foot">
  692. <button class="btn-text" onclick="resetKeys()">Reset to defaults</button>
  693. </div>
  694. </div>
  695. <!-- Images -->
  696. <div class="settings-section" id="sec-images">
  697. <h2>Images</h2>
  698. <div class="sub">How imported images are stored next to your document.</div>
  699. <div class="set-row">
  700. <div><div class="set-label">Store directory</div><div class="set-desc">Relative to the document. Use {name} for the document name.</div></div>
  701. <div class="set-ctl"><input type="text" class="set-input" id="set-imgdir" style="width:150px;" onchange="saveImgPrefs()"></div>
  702. </div>
  703. <div class="set-row">
  704. <div><div class="set-label">Compress images</div><div class="set-desc">Re-encode large images before storing to save space.</div></div>
  705. <div class="set-ctl"><label class="switch"><input type="checkbox" id="set-compress" onchange="onCompressToggle()"><span class="slider"></span></label></div>
  706. </div>
  707. <div class="set-row" id="row-quality">
  708. <div><div class="set-label">Quality</div><div class="set-desc">Lower = smaller file.</div></div>
  709. <div class="set-ctl"><div class="range-wrap">
  710. <input type="range" min="30" max="100" id="set-quality" oninput="onQualityInput()" onchange="saveImgPrefs()">
  711. <span id="quality-val" style="width:38px;">80%</span>
  712. </div></div>
  713. </div>
  714. <div class="set-row" id="row-maxw">
  715. <div><div class="set-label">Max width</div><div class="set-desc">Larger images are scaled down to this width (px). 0 = keep.</div></div>
  716. <div class="set-ctl"><input type="number" min="0" max="8000" class="set-input num" id="set-maxw" onchange="saveImgPrefs()"> px</div>
  717. </div>
  718. </div>
  719. </div>
  720. </div>
  721. </div>
  722. <!-- ── Unsaved-changes dialog ────────────────────────────────────────────── -->
  723. <div class="overlay" id="confirm-overlay">
  724. <div id="confirm-box">
  725. <h3>Unsaved Changes</h3>
  726. <p id="confirm-msg">Your changes haven't been saved. Save before closing?</p>
  727. <div class="confirm-row">
  728. <button class="cbtn cbtn-cancel" onclick="dlgCancel()">Cancel</button>
  729. <button class="cbtn cbtn-discard" onclick="dlgDiscard()">Discard</button>
  730. <button class="cbtn cbtn-save" onclick="dlgSave()">Save</button>
  731. </div>
  732. </div>
  733. </div>
  734. <!-- ── Link editor dialog ───────────────────────────────────────────────── -->
  735. <div class="overlay" id="link-overlay">
  736. <div id="link-box">
  737. <h3 id="link-box-title">Insert Link</h3>
  738. <div class="link-field">
  739. <label for="link-text-input">Text</label>
  740. <input type="text" id="link-text-input" placeholder="Link text" autocomplete="off" spellcheck="false">
  741. </div>
  742. <div class="link-field">
  743. <label for="link-url-input">URL</label>
  744. <input type="text" id="link-url-input" placeholder="https://" autocomplete="off" spellcheck="false">
  745. </div>
  746. <div class="link-row">
  747. <button class="cbtn cbtn-discard" id="link-remove-btn" onclick="linkDlgRemove()">Remove link</button>
  748. <button class="cbtn cbtn-cancel" onclick="linkDlgCancel()">Cancel</button>
  749. <button class="cbtn cbtn-save" onclick="linkDlgOk()">OK</button>
  750. </div>
  751. </div>
  752. </div>
  753. <div id="busy"><div class="spin"></div><span id="busy-msg">Working…</span></div>
  754. <script>
  755. "use strict";
  756. /* ════════════════════════════════════════════════════════════════════════
  757. Text — Typora-style editor for ArozOS
  758. ════════════════════════════════════════════════════════════════════════ */
  759. // ── State ───────────────────────────────────────────────────────────────
  760. var filepath = "";
  761. var filename = "";
  762. var isTxtMode = false; // false = markdown WYSIWYG, true = plain text
  763. var isRtfMode = false; // rich surface saved as RTF instead of markdown (never with isTxtMode)
  764. var rtfDoc = { baseSize:24, baseFont:"" }; // defaults of the loaded .rtf, kept on save
  765. var isDark = false;
  766. var dirtyFlag = false;
  767. var dlgCallback = null;
  768. var pendingClose = null;
  769. var recordingAction = null; // shortcut currently being re-bound
  770. var rich = document.getElementById("rich");
  771. var plain = document.getElementById("plain");
  772. // ── Settings (defaults) ─────────────────────────────────────────────────
  773. var settings = {
  774. font: "system", fontSize: 16, lineHeight: "1.7", syntax: "active",
  775. imgDir: "img/{name}", compress: false, quality: 80, maxWidth: 1600
  776. };
  777. var FONT_MAP = {
  778. system: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
  779. serif: "Georgia, 'Times New Roman', serif",
  780. mono: "'SF Mono', 'Consolas', 'Courier New', monospace",
  781. georgia: "Georgia, serif",
  782. times: "'Times New Roman', Times, serif"
  783. };
  784. // ── Shortcuts ───────────────────────────────────────────────────────────
  785. var DEFAULT_KEYS = {
  786. save:"ctrl+s", bold:"ctrl+b", italic:"ctrl+i", underline:"ctrl+u", strike:"ctrl+shift+x", inlineCode:"ctrl+e",
  787. h1:"ctrl+1", h2:"ctrl+2", h3:"ctrl+3", h4:"ctrl+4", h5:"ctrl+5", h6:"ctrl+6", paragraph:"ctrl+0",
  788. blockquote:"ctrl+shift+q", bulletList:"ctrl+shift+u", orderedList:"ctrl+shift+o",
  789. codeBlock:"ctrl+shift+k", link:"ctrl+k", image:"ctrl+shift+i", hr:"ctrl+shift+h"
  790. };
  791. var ACTIONS = {
  792. save: { label:"Save", fn:saveFile, md:false },
  793. bold: { label:"Bold", fn:actBold, md:true },
  794. italic: { label:"Italic", fn:actItalic, md:true },
  795. underline: { label:"Underline (rich text)", fn:actUnderline, md:true },
  796. strike: { label:"Strikethrough", fn:actStrike, md:true },
  797. inlineCode:{ label:"Inline code", fn:actInlineCode, md:true, rtf:false },
  798. h1: { label:"Heading 1", fn:function(){setBlock("h1");}, md:true },
  799. h2: { label:"Heading 2", fn:function(){setBlock("h2");}, md:true },
  800. h3: { label:"Heading 3", fn:function(){setBlock("h3");}, md:true },
  801. h4: { label:"Heading 4", fn:function(){setBlock("h4");}, md:true },
  802. h5: { label:"Heading 5", fn:function(){setBlock("h5");}, md:true },
  803. h6: { label:"Heading 6", fn:function(){setBlock("h6");}, md:true },
  804. paragraph: { label:"Paragraph", fn:function(){setBlock("p");}, md:true },
  805. blockquote:{ label:"Blockquote", fn:actQuote, md:true, rtf:false },
  806. bulletList:{ label:"Bullet list", fn:actBullet, md:true },
  807. orderedList:{label:"Numbered list", fn:actNumber, md:true },
  808. codeBlock: { label:"Code block", fn:actCodeBlock, md:true, rtf:false },
  809. link: { label:"Link", fn:actLink, md:true },
  810. image: { label:"Insert image", fn:function(){pickDeviceImage();}, md:true },
  811. hr: { label:"Horizontal rule", fn:actHr, md:true }
  812. };
  813. var keymap = JSON.parse(JSON.stringify(DEFAULT_KEYS));
  814. // ── Turndown (HTML → Markdown) ──────────────────────────────────────────
  815. var td = new TurndownService({
  816. headingStyle:"atx", codeBlockStyle:"fenced", bulletListMarker:"-",
  817. emDelimiter:"*", strongDelimiter:"**", hr:"---"
  818. });
  819. if (window.turndownPluginGfm) td.use(turndownPluginGfm.gfm);
  820. // GFM plugin emits single-tilde strikethrough; marked only renders double-tilde
  821. td.addRule("strike2", {
  822. filter:["del","s","strike"],
  823. replacement:function(content){ return "~~" + content + "~~"; }
  824. });
  825. td.addRule("relimg", {
  826. filter:"img",
  827. replacement:function(content, node){
  828. var alt = node.getAttribute("alt") || "";
  829. var src = node.getAttribute("data-rel") || node.getAttribute("src") || "";
  830. var ttl = node.getAttribute("title");
  831. return "![" + alt + "](" + mdLinkDest(src) + (ttl ? ' "'+ttl+'"' : "") + ")";
  832. }
  833. });
  834. // Plain markdown collapses any run of blank lines to a single paragraph
  835. // break, so an intentional run of several empty paragraphs would be lost on
  836. // reload. Mark each one with a ZWSP sentinel here — invisible, and never
  837. // written to the saved file, since expandBlankSentinels() (called from
  838. // getContent()) converts it into the exact bare-newline run that
  839. // renderWithBlankRuns() (called from setContent()) measures back into the
  840. // same paragraph count on load.
  841. td.addRule("emptyPara", {
  842. filter:function(node){
  843. return node.nodeName === "P"
  844. && !node.querySelector("img,hr,table,pre,code")
  845. && node.textContent.replace(/[\s ​]+/g, "") === "";
  846. },
  847. replacement:function(){ return "\n\n​\n\n"; }
  848. });
  849. // A markdown link/image destination containing spaces or parentheses must be
  850. // wrapped in angle brackets, otherwise parsers (marked) treat it as plain text
  851. // and the image never becomes an <img> — which is why such images appeared as
  852. // literal "![](path)" markdown when exported. The raw path is kept inside the
  853. // brackets so mediaURLFor() can still percent-encode it for the media endpoint.
  854. function mdLinkDest(src){
  855. return /[\s()]/.test(src) ? "<" + src + ">" : src;
  856. }
  857. // ════════════════════════════════════════════════════════════════════════
  858. // Init
  859. // ════════════════════════════════════════════════════════════════════════
  860. $(function(){
  861. if (document.execCommand) {
  862. try { document.execCommand("defaultParagraphSeparator", false, "p"); } catch(e){}
  863. try { document.execCommand("styleWithCSS", false, false); } catch(e){}
  864. }
  865. loadPrefs();
  866. var files = ao_module_loadInputFiles();
  867. if (files && files.length > 0){
  868. filepath = files[0].filepath;
  869. filename = files[0].filename;
  870. modeForFile(filename);
  871. applyMode();
  872. loadFile();
  873. } else {
  874. isTxtMode = false; isRtfMode = false;
  875. applyMode();
  876. updateTitle();
  877. }
  878. // editor events
  879. $("#rich").on("input", onRichInput);
  880. $("#rich").on("keydown", onRichKeydown);
  881. $("#rich").on("paste", onRichPaste);
  882. $("#rich").on("drop", onRichDrop);
  883. $("#rich").on("dragover", function(e){ e.preventDefault(); });
  884. // clicking an image doesn't always move the caret, so nudge it to the
  885. // image's block and reveal that block's ![alt](src) mark
  886. $("#rich").on("click", function(e){
  887. if (e.target && e.target.tagName === "IMG"){
  888. var r = document.createRange(); r.selectNode(e.target); r.collapse(false);
  889. var s = getSel(); s.removeAllRanges(); s.addRange(r);
  890. updateActiveBlock();
  891. return;
  892. }
  893. // clicking empty space below a trailing code block has nowhere else to
  894. // land, so the browser puts the caret back inside <code> — same trap
  895. // exitCodeBlockDown() escapes for the Down key, but for a mouse click
  896. escapeTrailingCodeBlockClick(e);
  897. });
  898. $(document).on("selectionchange", debounce(function(){ updateToolbarState(); updateActiveBlock(); syncCodeHighlight(); syncLangSelector(); }, 80));
  899. $("#plain").on("input", function(){ markDirty(); updateStatBar(); });
  900. // global keydown for shortcuts
  901. $(document).on("keydown", globalKeydown);
  902. // device file input
  903. document.getElementById("device-file").addEventListener("change", onDeviceFileChosen);
  904. // close menus when clicking elsewhere
  905. document.addEventListener("click", function(e){
  906. if (!e.target.closest(".menu-wrap")) hideMenus();
  907. });
  908. // keep selection alive when clicking toolbar buttons
  909. document.getElementById("toolbar").addEventListener("mousedown", function(e){
  910. if (e.target.closest(".tb-btn, .swatch") && !e.target.closest("select")) e.preventDefault();
  911. });
  912. buildSwatches();
  913. buildKeyList();
  914. syncSettingsUI();
  915. applyTypography();
  916. updateStatBar();
  917. });
  918. function isMarkdownExt(name){
  919. var ext = (name.split(".").pop() || "").toLowerCase();
  920. return ext === "md" || ext === "markdown" || ext === "mdown" || ext === "mkd";
  921. }
  922. function isRtfExt(name){
  923. return (name.split(".").pop() || "").toLowerCase() === "rtf";
  924. }
  925. // pick the editing surface from the file extension
  926. function modeForFile(name){
  927. isRtfMode = isRtfExt(name);
  928. isTxtMode = !isRtfMode && !isMarkdownExt(name);
  929. }
  930. function modeName(){ return isTxtMode ? "txt" : (isRtfMode ? "rtf" : "md"); }
  931. function defaultNewName(){ return "Untitled." + modeName(); }
  932. // ════════════════════════════════════════════════════════════════════════
  933. // File load / save
  934. // ════════════════════════════════════════════════════════════════════════
  935. function loadFile(){
  936. // strong cache-buster: unique nonce + jQuery cache:false so the browser
  937. // always fetches the freshly-saved file, never a stale cached copy
  938. var nonce = Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
  939. if (isRtfMode){
  940. // RTF may carry raw code-page bytes, so read it byte-for-byte rather
  941. // than letting the browser decode it as UTF-8
  942. fetch(ao_root + "media?file=" + encodeURIComponent(filepath) + "&nocache=" + nonce, { cache:"no-store", credentials:"same-origin" })
  943. .then(function(r){ if (!r.ok) throw new Error("HTTP " + r.status); return r.arrayBuffer(); })
  944. .then(function(buf){
  945. setContent(bytesToBinary(new Uint8Array(buf)));
  946. dirtyFlag = false;
  947. updateTitle(); updateStatBar();
  948. }).catch(function(){ setStatus("Failed to load file", "error"); });
  949. return;
  950. }
  951. $.ajax({
  952. url: ao_root + "media?file=" + encodeURIComponent(filepath) + "&nocache=" + nonce,
  953. method: "GET",
  954. dataType: "text",
  955. cache: false,
  956. success: function(data){
  957. if (typeof data !== "string") data = JSON.stringify(data, null, 2);
  958. setContent(data);
  959. dirtyFlag = false;
  960. updateTitle(); updateStatBar();
  961. },
  962. error: function(){ setStatus("Failed to load file", "error"); }
  963. });
  964. }
  965. function bytesToBinary(u8){
  966. var parts = [];
  967. for (var i = 0; i < u8.length; i += 0x8000) parts.push(String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)));
  968. return parts.join("");
  969. }
  970. function setContent(text){
  971. if (isTxtMode){
  972. plain.value = text;
  973. } else if (isRtfMode){
  974. var res;
  975. try { res = TextRTF.toHTML(text || ""); }
  976. catch(e){ console.error(e); setStatus("Could not read this RTF file", "error"); res = { html:"<p><br></p>", baseSize:24, baseFont:"" }; }
  977. rtfDoc = { baseSize:res.baseSize, baseFont:res.baseFont };
  978. rich.innerHTML = res.html;
  979. refreshEmptyState();
  980. updateActiveBlock();
  981. } else {
  982. rich.innerHTML = renderWithBlankRuns(text || "");
  983. normalizeEmptyParas(rich);
  984. rewriteImageSrcs(rich);
  985. refreshEmptyState();
  986. updateActiveBlock();
  987. syncCodeHighlight();
  988. syncLangSelector();
  989. }
  990. }
  991. // marked collapses any run of blank lines in the source to a single
  992. // paragraph break (standard CommonMark behaviour), so this rebuilds the HTML
  993. // token-by-token instead of via one marked.parse() call, reinserting the
  994. // extra empty paragraphs a blank-line run actually represents. The count is
  995. // read off each lexer "space" token's raw text, which is naturally
  996. // fence-aware (blank lines inside a fenced code block are absorbed into that
  997. // block's own "code" token, never reported as "space"). A run at the very
  998. // start/end of the document has no separator contributed by a block on the
  999. // outside, so it is measured against a different baseline than a run between
  1000. // two real blocks — see expandBlankSentinels(), the save-side counterpart.
  1001. function renderWithBlankRuns(text){
  1002. var tokens = marked.lexer(text);
  1003. var html = "";
  1004. for (var i = 0; i < tokens.length; i++){
  1005. var tok = tokens[i];
  1006. if (tok.type === "space"){
  1007. var nl = (tok.raw.match(/\n/g) || []).length;
  1008. var edge = (i === 0) || (i === tokens.length - 1);
  1009. var extra = edge ? Math.floor(nl / 2) : (nl - 2);
  1010. for (var k = 0; k < extra; k++) html += "<p><br></p>";
  1011. } else {
  1012. html += marked.parser([tok]);
  1013. }
  1014. }
  1015. return html;
  1016. }
  1017. // turn any non-blank-but-invisible-looking placeholder paragraph into a clean
  1018. // empty line, so they edit naturally and round-trip stably
  1019. function normalizeEmptyParas(root){
  1020. var ps = root.querySelectorAll("p");
  1021. for (var i = 0; i < ps.length; i++){
  1022. var p = ps[i];
  1023. if (!p.querySelector("img,hr,table,pre,code,br") &&
  1024. p.textContent.replace(/[\s ​]+/g, "") === ""){
  1025. p.innerHTML = "<br>";
  1026. }
  1027. }
  1028. }
  1029. function getContent(){
  1030. if (isTxtMode) return plain.value;
  1031. if (isRtfMode) return TextRTF.fromHTML(richClone(), rtfDoc);
  1032. return richMarkdown();
  1033. }
  1034. // like getContent(), but RTF first embeds every image (fetched + inlined as
  1035. // PNG/JPEG) — use this for anything that writes the document out
  1036. function getContentAsync(){
  1037. if (!isRtfMode) return Promise.resolve(getContent());
  1038. return TextRTF.inlineImages(richClone()).then(function(root){ return TextRTF.fromHTML(root, rtfDoc); });
  1039. }
  1040. // the rich surface without its editing decorations
  1041. function richClone(){
  1042. var src = rich.cloneNode(true);
  1043. var syns = src.querySelectorAll(".md-imgsyn, .md-linksyn, .md-langsel");
  1044. for (var i = 0; i < syns.length; i++) syns[i].parentNode.removeChild(syns[i]);
  1045. return src;
  1046. }
  1047. // the rich surface as markdown (also feeds PDF export in rich-text mode)
  1048. function richMarkdown(){
  1049. var src = rich.cloneNode(true);
  1050. var syns = src.querySelectorAll(".md-imgsyn, .md-linksyn, .md-langsel");
  1051. for (var i = 0; i < syns.length; i++) syns[i].parentNode.removeChild(syns[i]);
  1052. normalizeSerializableCodeBlocks(src);
  1053. var html = src.innerHTML.replace(/​/g, "");
  1054. var md = td.turndown(html);
  1055. return expandBlankSentinels(tidyMarkdown(md)) + "\n";
  1056. }
  1057. // converts each emptyPara ZWSP sentinel (see the turndown rule above) into
  1058. // the bare-newline run renderWithBlankRuns() expects on load. Turndown only
  1059. // contributes a separator newline between two blocks, so a sentinel run at
  1060. // the very start/end of the document — with no block on the outside — comes
  1061. // out short of as many raw newlines as one in the middle would; the two
  1062. // anchored passes below restore exactly the newlines such a leading/trailing
  1063. // run is missing before the catch-all pass removes each middle sentinel's
  1064. // shared newline.
  1065. function expandBlankSentinels(md){
  1066. md = md.replace(/^(​\n\n)+/, function(run){ return run.replace(/​/g, ""); });
  1067. md = md.replace(/(?:​\n\n)*​$/, function(run){ return run.replace(/​/g, ""); });
  1068. md = md.replace(/​\n\n/g, "\n");
  1069. return md;
  1070. }
  1071. function normalizeSerializableCodeBlocks(root){
  1072. var pres = root.querySelectorAll("pre");
  1073. for (var i = 0; i < pres.length; i++){
  1074. var pre = pres[i];
  1075. var codes = [];
  1076. for (var j = 0; j < pre.children.length; j++){
  1077. if (pre.children[j].tagName === "CODE") codes.push(pre.children[j]);
  1078. }
  1079. if (codes.length <= 1) continue;
  1080. var lang = pre.getAttribute("data-lang") || "";
  1081. var parts = [];
  1082. for (var k = 0; k < codes.length; k++){
  1083. var cls = codes[k].getAttribute("class") || "";
  1084. if (!lang){
  1085. var m = cls.match(/(?:^|\s)language-([A-Za-z0-9+#_-]+)/);
  1086. if (m) lang = m[1].toLowerCase();
  1087. }
  1088. parts.push(codes[k].textContent || "");
  1089. }
  1090. while (pre.firstChild) pre.removeChild(pre.firstChild);
  1091. var merged = document.createElement("code");
  1092. if (lang) merged.className = "language-" + lang;
  1093. merged.textContent = parts.join("").replace(/​/g, "");
  1094. pre.appendChild(merged);
  1095. }
  1096. }
  1097. // collapse runs of blank lines (turndown can emit extra) and trim the document
  1098. // edges — but never touch the inside of a fenced code block, where blank lines
  1099. // are significant content
  1100. function tidyMarkdown(md){
  1101. var parts = md.split(/(```[\s\S]*?\n```)/g);
  1102. for (var i = 0; i < parts.length; i++){
  1103. if (i % 2 === 0) parts[i] = parts[i].replace(/\n{3,}/g, "\n\n"); // prose only
  1104. }
  1105. return parts.join("").replace(/^\s+|\s+$/g, "");
  1106. }
  1107. // rich.textContent minus the decoration marks (used for word count / empty state)
  1108. function richPlainText(){
  1109. if (!rich.querySelector(".md-imgsyn, .md-linksyn, .md-langsel")) return rich.textContent.replace(/​/g, "");
  1110. var clone = rich.cloneNode(true);
  1111. var syns = clone.querySelectorAll(".md-imgsyn, .md-linksyn, .md-langsel");
  1112. for (var i = 0; i < syns.length; i++) syns[i].parentNode.removeChild(syns[i]);
  1113. return clone.textContent.replace(/​/g, "");
  1114. }
  1115. function saveFile(){
  1116. if (!filepath){
  1117. var def = defaultNewName();
  1118. ao_module_openFileSelector(handleSaveAs, "user:/Desktop", "new", false, { defaultName: def });
  1119. return;
  1120. }
  1121. doSave();
  1122. }
  1123. function handleSaveAs(fd){
  1124. if (!fd || !fd.length) return;
  1125. filepath = fd[0].filepath; filename = fd[0].filename;
  1126. doSave();
  1127. }
  1128. function doSave(callback){
  1129. getContentAsync().then(function(content){
  1130. ao_module_agirun("Text/backend/filesaver.agi", { filepath: filepath, content: content }, function(data){
  1131. if (data && data.error){
  1132. setStatus("Save failed: " + data.error, "error");
  1133. } else {
  1134. dirtyFlag = false; updateTitle(); setStatus("Saved");
  1135. if (callback) callback();
  1136. }
  1137. }, function(){ setStatus("Save failed", "error"); });
  1138. }).catch(function(err){ console.error(err); setStatus("Save failed", "error"); });
  1139. }
  1140. function openFile(){
  1141. ao_module_openFileSelector(handleOpenFile, "user:/", "file", false, {
  1142. filter: ["txt","md","markdown","rtf","csv","log","ini","conf","json","xml","html","css","js","py","sh","yaml","yml"]
  1143. });
  1144. }
  1145. function handleOpenFile(fd){
  1146. if (!fd || !fd.length) return;
  1147. filepath = fd[0].filepath; filename = fd[0].filename;
  1148. modeForFile(filename);
  1149. applyMode();
  1150. dirtyFlag = false;
  1151. loadFile();
  1152. }
  1153. // ════════════════════════════════════════════════════════════════════════
  1154. // Mode (markdown / plain text)
  1155. // ════════════════════════════════════════════════════════════════════════
  1156. function applyMode(){
  1157. document.body.classList.toggle("mode-txt", isTxtMode);
  1158. document.body.classList.toggle("mode-rtf", isRtfMode);
  1159. $("#stat-mode").text(isTxtMode ? "Plain text" : (isRtfMode ? "Rich text" : "Markdown"));
  1160. $("#mi-download-lbl").text("Download ." + modeName());
  1161. $("#rich").attr("data-ph", isRtfMode ? "Start writing…" : "Start writing… type # for a heading, ** for bold");
  1162. $("#seg-mode button").removeClass("active");
  1163. $('#seg-mode button[data-mode="' + modeName() + '"]').addClass("active");
  1164. applyTypography();
  1165. updateActiveBlock();
  1166. }
  1167. // invoked from the settings segmented control — converts current content
  1168. function setMode(mode){
  1169. var from = modeName();
  1170. if (mode === from) return;
  1171. function to(m){ isTxtMode = (m === "txt"); isRtfMode = (m === "rtf"); applyMode(); }
  1172. if (from !== "txt" && mode !== "txt"){
  1173. // markdown <-> rich text share the same WYSIWYG surface: keep the DOM
  1174. if (mode === "rtf"){ clearDecorations(); clearLangSelectors(); tidyRichForRtf(); }
  1175. to(mode);
  1176. markDirty(); updateStatBar();
  1177. return;
  1178. }
  1179. getContentAsync().then(function(current){ // serialise from the current surface
  1180. to(mode);
  1181. setContent(current); // re-hydrate into the new surface
  1182. markDirty(); updateStatBar();
  1183. });
  1184. }
  1185. // marked's HTML carries layout newlines (between blocks, soft line breaks);
  1186. // rich-text mode shows whitespace literally, so flatten them first
  1187. function tidyRichForRtf(){
  1188. var walker = document.createTreeWalker(rich, NodeFilter.SHOW_TEXT, null, false);
  1189. var n, dead = [];
  1190. while ((n = walker.nextNode())){
  1191. if (n.parentNode.closest && n.parentNode.closest("pre")) continue;
  1192. if (n.nodeValue.indexOf("\n") < 0) continue;
  1193. if (/^\s*$/.test(n.nodeValue)) dead.push(n);
  1194. else n.nodeValue = n.nodeValue.replace(/\s*\n\s*/g, " ");
  1195. }
  1196. dead.forEach(function(d){ d.parentNode.removeChild(d); });
  1197. }
  1198. // ════════════════════════════════════════════════════════════════════════
  1199. // WYSIWYG editing
  1200. // ════════════════════════════════════════════════════════════════════════
  1201. function onRichInput(){
  1202. var syn = activeImgSyn();
  1203. if (syn){ syncImgFromSyn(syn); return; } // editing an image mark, not prose
  1204. var lsyn = activeLinkSyn();
  1205. if (lsyn){ syncLinkFromSyn(lsyn); return; } // editing a link's URL mark, not prose
  1206. var code = activeCodeBlock();
  1207. if (code){ // typing code: re-highlight live, no autoformat
  1208. relightCode(code);
  1209. markDirty(); updateStatBar(); return;
  1210. }
  1211. markDirty();
  1212. inlineAutoformat();
  1213. refreshEmptyState();
  1214. updateActiveBlock();
  1215. updateStatBar();
  1216. }
  1217. function refreshEmptyState(){
  1218. var t = richPlainText().trim();
  1219. rich.classList.toggle("is-empty", t === "" && rich.children.length <= 1 && rich.querySelector("img,hr,table") === null);
  1220. }
  1221. function onRichKeydown(e){
  1222. // a keydown originating from the language <select> (arrow keys to change
  1223. // value, Enter/Space to open, typing to jump to an option, …) bubbles up
  1224. // from inside #rich — let the browser handle it natively instead of
  1225. // running block/code-block logic against the (unrelated) text selection
  1226. if (e.target && e.target.tagName === "SELECT") return;
  1227. // editing an image mark: Enter/Esc commit, everything else types normally
  1228. var syn = activeImgSyn();
  1229. if (syn){
  1230. if (e.key === "Enter" || e.key === "Escape"){ e.preventDefault(); commitImgSyn(syn); }
  1231. return;
  1232. }
  1233. var lsyn = activeLinkSyn();
  1234. if (lsyn){
  1235. if (e.key === "Enter" || e.key === "Escape"){ e.preventDefault(); commitLinkSyn(lsyn); }
  1236. return;
  1237. }
  1238. // block-level transforms triggered by Space / Enter (no modifier)
  1239. if (e.ctrlKey || e.metaKey || e.altKey) return;
  1240. // editable source marks: clicking a heading's "#" puts the caret at the
  1241. // block start, where typing "#" goes a level deeper and Backspace goes
  1242. // shallower / strips it. Backspace also unwraps a blockquote's "> " mark.
  1243. if (e.key === "#" && editHeadingMark(1)){ e.preventDefault(); return; }
  1244. if (e.key === "Backspace" && backspaceAtBlockStart()){ e.preventDefault(); return; }
  1245. if ((e.key === "Backspace" || e.key === "Delete") && deleteInCode(e.key === "Delete")){ e.preventDefault(); return; }
  1246. if (e.key === "ArrowDown" && !e.shiftKey && exitCodeBlockDown()){ e.preventDefault(); return; }
  1247. if (e.key === "Enter" && activeCodeBlock()){ e.preventDefault(); insertNewlineInCode(); return; }
  1248. if (e.key === " "){
  1249. if (blockTransformOnSpace()) e.preventDefault();
  1250. } else if (e.key === "Enter"){
  1251. if (blockTransformOnEnter()) e.preventDefault();
  1252. }
  1253. }
  1254. // caret sits at the very start of the block (ignoring the ZWSP spacer)?
  1255. function caretAtBlockStart(block){
  1256. var sel = getSel();
  1257. if (!sel.rangeCount || !sel.isCollapsed) return false;
  1258. return textBeforeCaret(block).replace(/​/g, "") === "";
  1259. }
  1260. // typing "#" on a heading's leading mark: h1->h2 … h5->h6 (dir = 1).
  1261. function editHeadingMark(dir){
  1262. var block = currentBlock();
  1263. if (!block || !/^H[1-6]$/.test(block.tagName)) return false;
  1264. if (!caretAtBlockStart(block)) return false;
  1265. var lvl = parseInt(block.tagName.charAt(1), 10) + dir;
  1266. if (lvl < 1 || lvl > 6) return true; // clamp: swallow the key, no change
  1267. changeBlockTag(block, "h" + lvl);
  1268. return true;
  1269. }
  1270. // Backspace on a block's leading mark: heading -> shallower / paragraph,
  1271. // blockquote's first paragraph -> unwrapped paragraph.
  1272. function backspaceAtBlockStart(){
  1273. var block = currentBlock();
  1274. if (!block || !caretAtBlockStart(block)) return false;
  1275. if (/^H[1-6]$/.test(block.tagName)){
  1276. var lvl = parseInt(block.tagName.charAt(1), 10) - 1;
  1277. changeBlockTag(block, lvl >= 1 ? "h" + lvl : "p");
  1278. return true;
  1279. }
  1280. var bq = block.parentNode;
  1281. if (block.tagName === "P" && bq && bq.tagName === "BLOCKQUOTE" && block === bq.firstElementChild){
  1282. unwrapBlockquote(bq);
  1283. return true;
  1284. }
  1285. return false;
  1286. }
  1287. function unwrapBlockquote(bq){
  1288. var frag = document.createDocumentFragment();
  1289. while (bq.firstChild) frag.appendChild(bq.firstChild);
  1290. var first = frag.firstChild;
  1291. bq.parentNode.replaceChild(frag, bq);
  1292. if (first) placeCaretAtStart(first);
  1293. markDirty(); updateActiveBlock();
  1294. }
  1295. function getSel(){ return window.getSelection(); }
  1296. function currentBlock(){
  1297. var sel = getSel();
  1298. if (!sel.rangeCount) return null;
  1299. var n = sel.getRangeAt(0).startContainer;
  1300. if (n.nodeType === 3) n = n.parentNode;
  1301. while (n && n !== rich){
  1302. if (/^(P|H[1-6]|LI|BLOCKQUOTE|PRE|DIV)$/.test(n.tagName)) return n;
  1303. n = n.parentNode;
  1304. }
  1305. return null;
  1306. }
  1307. // text in the current block, from its start to the caret
  1308. function textBeforeCaret(block){
  1309. var sel = getSel();
  1310. if (!sel.rangeCount) return "";
  1311. var r = sel.getRangeAt(0);
  1312. var pre = document.createRange();
  1313. pre.selectNodeContents(block);
  1314. try { pre.setEnd(r.startContainer, r.startOffset); } catch(err){ return ""; }
  1315. return pre.toString();
  1316. }
  1317. // text in the current block from the caret to its end
  1318. function textAfterCaret(block){
  1319. var sel = getSel();
  1320. if (!sel.rangeCount) return "";
  1321. var r = sel.getRangeAt(0);
  1322. var post = document.createRange();
  1323. post.selectNodeContents(block);
  1324. try { post.setStart(r.endContainer, r.endOffset); } catch(err){ return ""; }
  1325. return post.toString();
  1326. }
  1327. function blockTransformOnSpace(){
  1328. var block = currentBlock();
  1329. if (!block || block.tagName === "PRE") return false;
  1330. var pre = textBeforeCaret(block);
  1331. var li = (block.tagName === "LI");
  1332. if (/^#{1,6}$/.test(pre) && !li){
  1333. clearMarkers(block, pre.length); changeBlockTag(block, "h" + pre.length); return true;
  1334. }
  1335. if (pre === ">" && !li){
  1336. clearMarkers(block, 1); wrapBlockquote(block); return true;
  1337. }
  1338. if ((pre === "-" || pre === "*" || pre === "+") && !li){
  1339. clearMarkers(block, 1); makeList(block, false); return true;
  1340. }
  1341. if (/^\d+\.$/.test(pre) && !li){
  1342. clearMarkers(block, pre.length); makeList(block, true); return true;
  1343. }
  1344. return false;
  1345. }
  1346. // turn a block into a single-item list, merging with an adjacent list of the same kind
  1347. function makeList(block, ordered){
  1348. var tag = ordered ? "ol" : "ul";
  1349. var li = document.createElement("li");
  1350. while (block.firstChild) li.appendChild(block.firstChild);
  1351. if (!li.firstChild) li.appendChild(document.createElement("br"));
  1352. var prev = block.previousElementSibling;
  1353. if (prev && prev.tagName.toLowerCase() === tag){
  1354. prev.appendChild(li);
  1355. block.parentNode.removeChild(block);
  1356. } else {
  1357. var list = document.createElement(tag);
  1358. list.appendChild(li);
  1359. block.parentNode.replaceChild(list, block);
  1360. }
  1361. placeCaretAtStart(li); markDirty();
  1362. }
  1363. function blockTransformOnEnter(){
  1364. var block = currentBlock();
  1365. if (!block) return false;
  1366. var pre = textBeforeCaret(block).trim();
  1367. var whole = block.textContent.trim();
  1368. var fence = whole.match(/^```([A-Za-z0-9+#_-]*)$/);
  1369. if (block.tagName !== "PRE" && fence){
  1370. block.textContent = ""; insertCodeBlockAt(block, fence[1]); return true;
  1371. }
  1372. if (block.tagName !== "PRE" && (whole === "---" || whole === "***" || whole === "___")){
  1373. var hr = document.createElement("hr");
  1374. var p = document.createElement("p"); p.appendChild(document.createElement("br"));
  1375. block.parentNode.replaceChild(p, block);
  1376. p.parentNode.insertBefore(hr, p);
  1377. placeCaretAtStart(p); markDirty(); return true;
  1378. }
  1379. // pressing Enter at the end of a heading starts a normal paragraph
  1380. if (/^H[1-6]$/.test(block.tagName) && pre === whole){
  1381. var np = document.createElement("p"); np.appendChild(document.createElement("br"));
  1382. if (block.nextSibling) block.parentNode.insertBefore(np, block.nextSibling);
  1383. else block.parentNode.appendChild(np);
  1384. placeCaretAtStart(np); markDirty(); return true;
  1385. }
  1386. return false;
  1387. }
  1388. // remove the first `count` characters (markdown markers) from a block
  1389. function clearMarkers(block, count){
  1390. var r = document.createRange();
  1391. r.selectNodeContents(block);
  1392. var walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, null);
  1393. var first = walker.nextNode();
  1394. if (first){
  1395. r.setStart(first, 0);
  1396. r.setEnd(first, Math.min(count, first.data.length));
  1397. r.deleteContents();
  1398. } else {
  1399. block.textContent = "";
  1400. }
  1401. }
  1402. function changeBlockTag(block, tag){
  1403. var nb = document.createElement(tag);
  1404. while (block.firstChild) nb.appendChild(block.firstChild);
  1405. if (!nb.firstChild) nb.appendChild(document.createElement("br"));
  1406. block.parentNode.replaceChild(nb, block);
  1407. placeCaretAtStart(nb); markDirty(); updateActiveBlock();
  1408. }
  1409. function wrapBlockquote(block){
  1410. var bq = document.createElement("blockquote");
  1411. var p = document.createElement("p");
  1412. while (block.firstChild) p.appendChild(block.firstChild);
  1413. if (!p.firstChild) p.appendChild(document.createElement("br"));
  1414. bq.appendChild(p);
  1415. block.parentNode.replaceChild(bq, block);
  1416. placeCaretAtStart(p); markDirty();
  1417. }
  1418. function insertCodeBlockAt(block, lang){
  1419. var pre = document.createElement("pre");
  1420. var code = document.createElement("code");
  1421. if (lang){ code.className = "language-" + lang.toLowerCase(); }
  1422. pre.setAttribute("data-lang", lang ? lang.toLowerCase() : "");
  1423. code.appendChild(document.createTextNode("​"));
  1424. pre.appendChild(code);
  1425. block.parentNode.replaceChild(pre, block);
  1426. var r = document.createRange();
  1427. r.setStart(code.firstChild, 1); r.collapse(true);
  1428. var s = getSel(); s.removeAllRanges(); s.addRange(r);
  1429. markDirty();
  1430. }
  1431. // pressing Down on the last line of a code block leaves it instead of wrapping
  1432. // back to the top: move to the following block, creating a paragraph if needed
  1433. function exitCodeBlockDown(){
  1434. var block = currentBlock();
  1435. if (!block || block.tagName !== "PRE") return false;
  1436. var code = block.querySelector("code");
  1437. if (code && textAfterCaret(code).replace(/​/g, "").indexOf("\n") >= 0) return false; // more lines below
  1438. var next = block.nextElementSibling;
  1439. if (next){
  1440. placeCaretAtStart(next);
  1441. } else {
  1442. var p = document.createElement("p");
  1443. p.appendChild(document.createElement("br"));
  1444. block.parentNode.appendChild(p);
  1445. placeCaretAtStart(p); markDirty();
  1446. }
  1447. return true;
  1448. }
  1449. // a code block with nothing after it has no element below for the browser to
  1450. // place the caret into, so clicking the empty area under it just re-enters
  1451. // <code> — same trap exitCodeBlockDown() escapes for the Down key. Detected
  1452. // after the native click already moved the caret: if it landed back inside
  1453. // the last block's code, the click must have missed all real content.
  1454. function escapeTrailingCodeBlockClick(e){
  1455. var last = rich.lastElementChild;
  1456. if (!last || last.tagName !== "PRE") return;
  1457. var code = last.querySelector("code");
  1458. if (!code || activeCodeBlock() !== code) return;
  1459. if (e.target !== rich && code.contains(e.target)) return; // genuine click inside the code text
  1460. var p = document.createElement("p");
  1461. p.appendChild(document.createElement("br"));
  1462. rich.appendChild(p);
  1463. placeCaretAtStart(p); markDirty();
  1464. updateActiveBlock(); syncCodeHighlight(); syncLangSelector();
  1465. }
  1466. // ── Code-block syntax highlighting ──────────────────────────────────────
  1467. // Code stays highlighted while you type: every edit re-renders the block's
  1468. // <span class="hl-*"> wrappers from its plain text and restores the caret by
  1469. // character offset (stable across highlighting, since spans add no text — see
  1470. // caretOffsetIn/restoreCaretIn). syncCodeHighlight() runs on selection change
  1471. // and after content loads, via the cheap highlightCode() (skips blocks already
  1472. // rendered); relightCode() forces a fresh render and is used right after an
  1473. // edit changes a block's text. Serialization is unaffected: turndown reads the
  1474. // code's full textContent plus its language-xxx class regardless of the inner
  1475. // spans.
  1476. function codeLang(code){
  1477. var m = (code.getAttribute("class") || "").match(/language-([A-Za-z0-9+#_-]+)/);
  1478. return m ? m[1].toLowerCase() : "";
  1479. }
  1480. function activeCodeBlock(){
  1481. var sel = getSel();
  1482. var n = sel && sel.anchorNode;
  1483. if (!n) return null;
  1484. if (n.nodeType === 3) n = n.parentNode;
  1485. var pre = (n && n.closest) ? n.closest("pre") : null;
  1486. if (!pre || !rich.contains(pre)) return null;
  1487. return pre.querySelector("code");
  1488. }
  1489. function syncPreLang(code){
  1490. var pre = code.parentNode;
  1491. if (pre && pre.tagName === "PRE") pre.setAttribute("data-lang", codeLang(code));
  1492. }
  1493. // character offset of the caret within an element (stable across highlighting,
  1494. // since the spans add no text)
  1495. function caretOffsetIn(el){
  1496. var sel = getSel();
  1497. if (!sel.rangeCount) return null;
  1498. var r = sel.getRangeAt(0);
  1499. if (!el.contains(r.startContainer)) return null;
  1500. var pre = document.createRange();
  1501. pre.selectNodeContents(el);
  1502. try { pre.setEnd(r.startContainer, r.startOffset); } catch(e){ return null; }
  1503. return pre.toString().length;
  1504. }
  1505. // end-of-selection counterpart to caretOffsetIn, so a non-collapsed selection
  1506. // (the user dragging across highlighted text) can be restored as a range
  1507. // instead of collapsing to its start once the spans are stripped
  1508. function selectionEndOffsetIn(el){
  1509. var sel = getSel();
  1510. if (!sel.rangeCount) return null;
  1511. var r = sel.getRangeAt(0);
  1512. if (!el.contains(r.endContainer)) return el.contains(r.startContainer) ? el.textContent.length : null;
  1513. var pre = document.createRange();
  1514. pre.selectNodeContents(el);
  1515. try { pre.setEnd(r.endContainer, r.endOffset); } catch(e){ return el.textContent.length; }
  1516. return pre.toString().length;
  1517. }
  1518. function pointAtOffset(el, offset){
  1519. var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null);
  1520. var node, count = 0;
  1521. while ((node = walker.nextNode())){
  1522. var len = node.data.length;
  1523. if (count + len >= offset) return { node: node, offset: Math.max(0, offset - count) };
  1524. count += len;
  1525. }
  1526. return null;
  1527. }
  1528. // restores a caret at `offset`, or — when `endOffset` is also given and
  1529. // differs — a full selection from offset to endOffset (see selectionEndOffsetIn)
  1530. function restoreCaretIn(el, offset, endOffset){
  1531. if (offset == null) return;
  1532. var r = document.createRange();
  1533. var start = pointAtOffset(el, offset);
  1534. if (start) r.setStart(start.node, start.offset);
  1535. else { r.selectNodeContents(el); r.collapse(false); }
  1536. if (endOffset != null && endOffset !== offset){
  1537. var end = pointAtOffset(el, endOffset);
  1538. if (end) r.setEnd(end.node, end.offset);
  1539. }
  1540. var s = getSel(); s.removeAllRanges(); s.addRange(r);
  1541. }
  1542. // cheap/idempotent: skips blocks that already look rendered (right language
  1543. // or already plain) — safe to call on every block on every selection change
  1544. function highlightCode(code){
  1545. var lang = codeLang(code);
  1546. var hasSpans = !!code.querySelector("*");
  1547. var canHighlight = lang && typeof TextHL !== "undefined" && TextHL.supports(lang) &&
  1548. code.textContent.replace(/​/g, "").trim() !== "";
  1549. if (hasSpans === canHighlight) { syncPreLang(code); return; } // already in the right state
  1550. relightCode(code);
  1551. }
  1552. // forces a fresh render from the block's current text — use right after an
  1553. // edit (typing, Enter, Delete, language change) so it never goes stale
  1554. function relightCode(code){
  1555. var lang = codeLang(code);
  1556. var text = code.textContent.replace(/​/g, "");
  1557. var canHighlight = lang && typeof TextHL !== "undefined" && TextHL.supports(lang) && text.trim() !== "";
  1558. if (!canHighlight && !code.querySelector("*")){
  1559. syncPreLang(code); return; // already plain, nothing to recompute
  1560. }
  1561. var off = caretOffsetIn(code);
  1562. var endOff = selectionEndOffsetIn(code);
  1563. if (canHighlight) code.innerHTML = TextHL.highlight(text, lang);
  1564. else code.textContent = text; // unsupported / empty → flatten stale spans
  1565. if (off != null) restoreCaretIn(code, off, endOff);
  1566. syncPreLang(code);
  1567. }
  1568. function syncCodeHighlight(){
  1569. if (isTxtMode) return;
  1570. var codes = rich.querySelectorAll("pre > code");
  1571. for (var i = 0; i < codes.length; i++) highlightCode(codes[i]);
  1572. }
  1573. // Enter inside a code block inserts a real newline (not a <div>/<br>), so the
  1574. // text stays line-accurate for highlighting and serialization. Splices the
  1575. // string and reassigns textContent (rather than Range.insertNode, which
  1576. // fragments the element into several sibling Text nodes) so the caret offset
  1577. // computed before the edit stays valid after it — that fragmentation was the
  1578. // root cause of the caret not following Enter on a code block's last line and
  1579. // of Delete misbehaving across the resulting node boundary.
  1580. function insertNewlineInCode(){
  1581. var code = activeCodeBlock();
  1582. if (!code) return false;
  1583. var sel = getSel();
  1584. if (!sel.rangeCount) return false;
  1585. if (!sel.isCollapsed) sel.getRangeAt(0).deleteContents();
  1586. var offset = caretOffsetIn(code);
  1587. if (offset == null) return false;
  1588. var raw = code.textContent;
  1589. var atEnd = raw.slice(offset).replace(/​/g, "") === "";
  1590. var insert = atEnd ? "\n​" : "\n"; // pad a trailing line so it shows
  1591. code.textContent = raw.slice(0, offset) + insert + raw.slice(offset);
  1592. restoreCaretIn(code, offset + 1);
  1593. relightCode(code);
  1594. markDirty();
  1595. return true;
  1596. }
  1597. // Backspace/Delete inside a code block, rewritten on the same string-splice
  1598. // principle as insertNewlineInCode so multi-line content always stays a
  1599. // single Text node (see above) — native deletion across the \n character a
  1600. // fenced block contains is unreliable once that node gets fragmented.
  1601. function deleteInCode(forward){
  1602. var code = activeCodeBlock();
  1603. if (!code) return false;
  1604. var sel = getSel();
  1605. if (!sel.rangeCount) return false;
  1606. // an empty code block has nothing left to delete — Backspace/Delete on it
  1607. // removes the block instead of resetting the ZWSP placeholder, which used
  1608. // to leave it stuck forever as a permanent empty grey box
  1609. if (sel.isCollapsed && code.textContent.replace(/​/g, "") === ""){
  1610. return exitEmptyCodeBlock(code);
  1611. }
  1612. if (!sel.isCollapsed){
  1613. sel.getRangeAt(0).deleteContents();
  1614. relightCode(code);
  1615. markDirty();
  1616. return true;
  1617. }
  1618. var offset = caretOffsetIn(code);
  1619. if (offset == null) return false;
  1620. var raw = code.textContent;
  1621. var delAt = forward ? offset : offset - 1;
  1622. if (delAt < 0 || delAt >= raw.length) return false;
  1623. var next = raw.slice(0, delAt) + raw.slice(delAt + 1);
  1624. if (next.replace(/​/g, "") === ""){
  1625. return exitEmptyCodeBlock(code);
  1626. }
  1627. code.textContent = next;
  1628. restoreCaretIn(code, delAt);
  1629. relightCode(code);
  1630. markDirty();
  1631. return true;
  1632. }
  1633. // replaces an emptied-out code block with a plain empty paragraph, so it
  1634. // can be backspaced/deleted away instead of sitting there forever
  1635. function exitEmptyCodeBlock(code){
  1636. var pre = code.parentNode;
  1637. var p = document.createElement("p");
  1638. p.appendChild(document.createElement("br"));
  1639. pre.parentNode.replaceChild(p, pre);
  1640. placeCaretAtStart(p); markDirty(); updateActiveBlock();
  1641. return true;
  1642. }
  1643. // ── Code-block language picker ────────────────────────────────────────────
  1644. // A real <select> pinned to the top-right corner of the block the caret is
  1645. // currently in, so the language stays changeable after creation (unlike the
  1646. // old ```lang fence-text mark, which only captured it once). It is a
  1647. // contenteditable="false" island appended AFTER <code> — turndown's fenced
  1648. // rule only reads pre.firstChild, so anything after <code> is invisible to
  1649. // it — and is stripped from clones before serialize/word-count regardless
  1650. // (see getContent/richPlainText) so it can never leak into saved markdown.
  1651. function langSelectOptions(){
  1652. var langs = (typeof TextHL !== "undefined" && TextHL.languages) ? TextHL.languages() : [];
  1653. var html = '<option value="">Plain text</option>';
  1654. for (var i = 0; i < langs.length; i++){
  1655. html += '<option value="' + langs[i].id + '">' + langs[i].label + '</option>';
  1656. }
  1657. return html;
  1658. }
  1659. function onLangSelectChange(e){
  1660. var sel = e.target;
  1661. var pre = sel.closest("pre");
  1662. var code = pre ? pre.querySelector("code") : null;
  1663. if (!code) return;
  1664. code.className = sel.value ? "language-" + sel.value : "";
  1665. syncPreLang(code);
  1666. relightCode(code);
  1667. markDirty();
  1668. }
  1669. function ensureLangSelector(code){
  1670. var pre = code.parentNode;
  1671. if (!pre || pre.tagName !== "PRE") return;
  1672. var wrap = pre.querySelector(".md-langsel");
  1673. if (!wrap){
  1674. wrap = document.createElement("div");
  1675. wrap.className = "md-langsel";
  1676. wrap.setAttribute("contenteditable", "false");
  1677. var sel = document.createElement("select");
  1678. sel.className = "md-langsel-select";
  1679. sel.title = "Code block language";
  1680. sel.innerHTML = langSelectOptions();
  1681. sel.addEventListener("mousedown", function(e){ e.stopPropagation(); });
  1682. sel.addEventListener("change", onLangSelectChange);
  1683. wrap.appendChild(sel);
  1684. pre.appendChild(wrap);
  1685. }
  1686. wrap.querySelector("select").value = codeLang(code);
  1687. }
  1688. function clearLangSelectors(){
  1689. var wraps = rich.querySelectorAll(".md-langsel");
  1690. for (var i = 0; i < wraps.length; i++) wraps[i].parentNode.removeChild(wraps[i]);
  1691. }
  1692. function syncLangSelector(){
  1693. if (isTxtMode) return;
  1694. clearLangSelectors();
  1695. var code = activeCodeBlock();
  1696. if (code) ensureLangSelector(code);
  1697. }
  1698. function placeCaretAtStart(el){
  1699. var r = document.createRange();
  1700. r.setStart(el, 0); r.collapse(true);
  1701. var s = getSel(); s.removeAllRanges(); s.addRange(r);
  1702. rich.focus();
  1703. }
  1704. // inline autoformat: **bold** *italic* `code` ~~strike~~
  1705. function inlineAutoformat(){
  1706. var sel = getSel();
  1707. if (!sel.rangeCount || !sel.isCollapsed) return;
  1708. var node = sel.getRangeAt(0).startContainer;
  1709. if (node.nodeType !== 3) return;
  1710. var offset = sel.getRangeAt(0).startOffset;
  1711. var text = node.data.substring(0, offset);
  1712. var patterns = [
  1713. { re:/\*\*([^*\s][^*]*?)\*\*$/, tag:"strong" },
  1714. { re:/__([^_\s][^_]*?)__$/, tag:"strong" },
  1715. { re:/`([^`]+?)`$/, tag:"code" },
  1716. { re:/~~([^~\s][^~]*?)~~$/, tag:"del" },
  1717. { re:/(?<![*\w])\*([^*\s][^*]*?)\*$/, tag:"em" },
  1718. { re:/(?<![_\w])_([^_\s][^_]*?)_$/, tag:"em" }
  1719. ];
  1720. for (var i = 0; i < patterns.length; i++){
  1721. var m = patterns[i].re.exec(text);
  1722. if (m){
  1723. applyInline(node, offset - m[0].length, offset, m[1], patterns[i].tag);
  1724. return;
  1725. }
  1726. }
  1727. }
  1728. function applyInline(node, start, end, inner, tag){
  1729. var r = document.createRange();
  1730. r.setStart(node, start); r.setEnd(node, end);
  1731. r.deleteContents();
  1732. var el = document.createElement(tag);
  1733. el.textContent = inner;
  1734. r.insertNode(el);
  1735. // exit the formatted span with a zero-width spacer so typing continues plain
  1736. var after = document.createTextNode("​");
  1737. el.parentNode.insertBefore(after, el.nextSibling);
  1738. var nr = document.createRange();
  1739. nr.setStart(after, 1); nr.collapse(true);
  1740. var s = getSel(); s.removeAllRanges(); s.addRange(nr);
  1741. markDirty();
  1742. }
  1743. // ── Toolbar actions ─────────────────────────────────────────────────────
  1744. function exec(cmd, val){
  1745. rich.focus();
  1746. document.execCommand(cmd, false, val || null);
  1747. markDirty(); updateStatBar(); updateToolbarState(); updateActiveBlock();
  1748. }
  1749. function actBold(){ if(isTxtMode) return; exec("bold"); }
  1750. function actItalic(){ if(isTxtMode) return; exec("italic"); }
  1751. function actStrike(){ if(isTxtMode) return; exec("strikeThrough"); }
  1752. function actUnderline(){ if(isRtfMode) exec("underline"); } // markdown has no underline
  1753. function actBullet(){ if(isTxtMode) return; exec("insertUnorderedList"); }
  1754. function actNumber(){ if(isTxtMode) return; exec("insertOrderedList"); }
  1755. function actInlineCode(){ if(isTxtMode) return; wrapSelection("code"); }
  1756. function actQuote(){
  1757. if(isTxtMode) return;
  1758. var b = currentBlock();
  1759. if (b && b.closest("blockquote")){ exec("formatBlock", "p"); }
  1760. else { exec("formatBlock", "blockquote"); }
  1761. }
  1762. function actCodeBlock(){
  1763. if(isTxtMode) return;
  1764. var b = currentBlock(); if (!b) { rich.focus(); b = currentBlock(); }
  1765. if (b) insertCodeBlockAt(b);
  1766. }
  1767. function actHr(){
  1768. if(isTxtMode) return;
  1769. rich.focus();
  1770. document.execCommand("insertHTML", false, "<hr><p><br></p>");
  1771. markDirty();
  1772. }
  1773. // the <a> the caret is currently in or out (including while inside its
  1774. // .md-linksyn URL mark), if any — used to decide insert vs. edit mode
  1775. function currentLinkAtCaret(){
  1776. var sel = getSel();
  1777. var n = sel && sel.anchorNode;
  1778. if (!n) return null;
  1779. if (n.nodeType === 3) n = n.parentNode;
  1780. if (!n || !n.closest) return null;
  1781. var syn = n.closest(".md-linksyn");
  1782. if (syn && rich.contains(syn)) return synLink(syn);
  1783. var a = n.closest("a");
  1784. return (a && rich.contains(a)) ? a : null;
  1785. }
  1786. var linkDlgTarget = null; // <a> being edited, or null when inserting a new one
  1787. var linkDlgRange = null; // selection in #rich saved before the dialog stole focus
  1788. function actLink(){
  1789. if (isTxtMode) return;
  1790. rich.focus();
  1791. var sel = getSel();
  1792. linkDlgRange = (sel && sel.rangeCount) ? sel.getRangeAt(0).cloneRange() : null;
  1793. var a = currentLinkAtCaret();
  1794. if (a){
  1795. linkDlgTarget = a;
  1796. openLinkDialog("Edit Link", a.textContent, a.getAttribute("href") || "", true);
  1797. } else {
  1798. linkDlgTarget = null;
  1799. var selectedText = (sel && !sel.isCollapsed) ? sel.toString() : "";
  1800. openLinkDialog("Insert Link", selectedText, "https://", false);
  1801. }
  1802. }
  1803. function openLinkDialog(title, text, url, showRemove){
  1804. $("#link-box-title").text(title);
  1805. $("#link-text-input").val(text);
  1806. $("#link-url-input").val(url);
  1807. $("#link-remove-btn").css("display", showRemove ? "" : "none");
  1808. $("#link-overlay").addClass("show");
  1809. setTimeout(function(){ $("#link-url-input")[0].focus(); $("#link-url-input")[0].select(); }, 30);
  1810. }
  1811. function hideLinkDialog(){ $("#link-overlay").removeClass("show"); }
  1812. function linkDlgCancel(){
  1813. hideLinkDialog();
  1814. rich.focus();
  1815. if (linkDlgRange){ var s = getSel(); s.removeAllRanges(); s.addRange(linkDlgRange); }
  1816. linkDlgTarget = null; linkDlgRange = null;
  1817. }
  1818. function linkDlgRemove(){
  1819. if (linkDlgTarget){
  1820. var t = linkDlgTarget, parent = t.parentNode;
  1821. while (t.firstChild) parent.insertBefore(t.firstChild, t);
  1822. parent.removeChild(t);
  1823. var r = document.createRange(); r.selectNodeContents(parent); r.collapse(false);
  1824. rich.focus();
  1825. var s = getSel(); s.removeAllRanges(); s.addRange(r);
  1826. markDirty(); updateActiveBlock();
  1827. }
  1828. hideLinkDialog();
  1829. linkDlgTarget = null; linkDlgRange = null;
  1830. }
  1831. function linkDlgOk(){
  1832. var text = $("#link-text-input").val();
  1833. var url = ($("#link-url-input").val() || "").trim();
  1834. hideLinkDialog();
  1835. if (!url){ linkDlgTarget = null; linkDlgRange = null; return; }
  1836. rich.focus();
  1837. if (linkDlgTarget){
  1838. var a = linkDlgTarget;
  1839. a.setAttribute("href", url);
  1840. if (text && text !== a.textContent) a.textContent = text;
  1841. var r = document.createRange(); r.selectNodeContents(a); r.collapse(false);
  1842. var s = getSel(); s.removeAllRanges(); s.addRange(r);
  1843. } else {
  1844. var sel = getSel();
  1845. sel.removeAllRanges();
  1846. if (linkDlgRange) sel.addRange(linkDlgRange);
  1847. if (sel.rangeCount && !sel.isCollapsed){
  1848. // wrap the existing selection in place — preserves surrounding
  1849. // whitespace, unlike deleting it and re-inserting raw HTML
  1850. document.execCommand("createLink", false, url);
  1851. var newA = currentLinkAtCaret();
  1852. if (newA && text && text !== newA.textContent) newA.textContent = text;
  1853. } else {
  1854. var label = text || url;
  1855. document.execCommand("insertHTML", false, '<a href="'+escapeAttr(url)+'">'+escapeHtml(label)+'</a>');
  1856. }
  1857. }
  1858. linkDlgTarget = null; linkDlgRange = null;
  1859. markDirty(); updateActiveBlock(); updateStatBar();
  1860. }
  1861. function setBlock(tag){
  1862. if(isTxtMode) return;
  1863. // pressing the same heading shortcut again strips the syntax (h1 -> paragraph)
  1864. if (/^h[1-6]$/.test(tag)){
  1865. var b = currentBlock();
  1866. if (b && b.tagName.toLowerCase() === tag) tag = "p";
  1867. }
  1868. exec("formatBlock", tag);
  1869. }
  1870. function onHeadingSelect(){
  1871. setBlock($("#sel-head").val());
  1872. }
  1873. // ── Rich text (RTF) formatting ──────────────────────────────────────────
  1874. var FORE_SWATCHES = ["#000000","#595959","#a6a6a6","#c00000","#e36c09","#bf8f00",
  1875. "#00b050","#0f7c80","#0070c0","#002060","#7030a0","#d6337a"];
  1876. var BACK_SWATCHES = ["#ffff00","#00ff00","#00ffff","#ff00ff","#ffc000","#ff9999",
  1877. "#b4c7e7","#c5e0b4","#d9d9d9","#a9d18e","#f4b183","#ffe699"];
  1878. var AUTO_SENTINEL = "#010203"; // marks "automatic colour" runs for clean-up
  1879. function buildSwatches(){
  1880. function fill(id, list, kind, noneLabel){
  1881. var html = '<button class="menu-item swatch-none" onclick="hideMenus();actColor(\'' + kind + '\', null)">' + noneLabel + '</button><div class="swatch-grid">';
  1882. list.forEach(function(c){
  1883. html += '<button class="swatch" title="' + c + '" style="background:' + c + ';" onclick="hideMenus();actColor(\'' + kind + '\', \'' + c + '\')"></button>';
  1884. });
  1885. document.getElementById(id).innerHTML = html + "</div>";
  1886. }
  1887. fill("fore-menu", FORE_SWATCHES, "fore", "Automatic");
  1888. fill("back-menu", BACK_SWATCHES, "back", "No highlight");
  1889. }
  1890. // text / highlight colour of the selection; null = automatic / none
  1891. function actColor(kind, color){
  1892. if (!isRtfMode) return;
  1893. rich.focus();
  1894. try { document.execCommand("styleWithCSS", false, true); } catch(e){}
  1895. if (kind === "fore"){
  1896. document.execCommand("foreColor", false, color || AUTO_SENTINEL);
  1897. if (color) $("#fore-bar").css("background", color);
  1898. else stripSentinelColor();
  1899. } else {
  1900. document.execCommand("hiliteColor", false, color || "transparent");
  1901. }
  1902. try { document.execCommand("styleWithCSS", false, false); } catch(e){}
  1903. markDirty(); updateStatBar();
  1904. }
  1905. function stripSentinelColor(){
  1906. $(rich).find('[style*="rgb(1, 2, 3)"], font[color="' + AUTO_SENTINEL + '"]').each(function(){
  1907. this.style.color = "";
  1908. this.removeAttribute("color");
  1909. if ((this.tagName === "SPAN" || this.tagName === "FONT") && !this.getAttribute("style") && this.attributes.length <= 1) $(this).contents().unwrap();
  1910. });
  1911. }
  1912. function actAlign(dir){
  1913. if (!isRtfMode) return;
  1914. exec("justify" + dir);
  1915. }
  1916. // font size in points; a collapsed caret gets an empty sized span to type into
  1917. function actFontSize(){
  1918. var pt = $("#sel-size").val();
  1919. if (!isRtfMode || !pt) return;
  1920. rich.focus();
  1921. var sel = getSel();
  1922. if (!sel.rangeCount || !rich.contains(sel.anchorNode)) return;
  1923. if (sel.isCollapsed){
  1924. var span = document.createElement("span");
  1925. span.style.fontSize = pt + "pt";
  1926. span.appendChild(document.createTextNode("​"));
  1927. var r = sel.getRangeAt(0);
  1928. r.insertNode(span);
  1929. var nr = document.createRange(); nr.setStart(span.firstChild, 1); nr.collapse(true);
  1930. sel.removeAllRanges(); sel.addRange(nr);
  1931. } else {
  1932. document.execCommand("fontSize", false, "7");
  1933. $(rich).find('font[size="7"]').each(function(){
  1934. var sp = document.createElement("span");
  1935. sp.style.fontSize = pt + "pt";
  1936. while (this.firstChild) sp.appendChild(this.firstChild);
  1937. // the new size wins over any size set inside the selection
  1938. $(sp).find("[style]").each(function(){ this.style.fontSize = ""; });
  1939. $(sp).find("font[size]").each(function(){ this.removeAttribute("size"); });
  1940. this.parentNode.replaceChild(sp, this);
  1941. });
  1942. }
  1943. markDirty(); updateStatBar();
  1944. }
  1945. // image picked / pasted / dropped in rich-text mode: embed it in the document
  1946. function insertEmbeddedImage(file){
  1947. prepareBlob(file, function(blob){
  1948. var fr = new FileReader();
  1949. fr.onload = function(){
  1950. rich.focus();
  1951. document.execCommand("insertHTML", false, '<img src="' + escapeAttr(fr.result) + '" alt="">');
  1952. refreshEmptyState(); markDirty(); setStatus("Image inserted");
  1953. };
  1954. fr.onerror = function(){ setStatus("Could not read the image", "error"); };
  1955. fr.readAsDataURL(blob);
  1956. });
  1957. }
  1958. function updateRtfToolbarState(){
  1959. try { $("#btn-underline").toggleClass("active", document.queryCommandState("underline")); } catch(e){}
  1960. var n = getSel().anchorNode;
  1961. if (n && n.nodeType === 3) n = n.parentNode;
  1962. if (!n || !rich.contains(n)) return;
  1963. // queryCommandState("justify…") is unreliable, so read the block's alignment
  1964. var b = currentBlock();
  1965. var ta = b ? getComputedStyle(b).textAlign : "left";
  1966. var cur = ta === "center" ? "center" : (ta === "right" || ta === "end") ? "right" : ta === "justify" ? "full" : "left";
  1967. ["left","center","right","full"].forEach(function(d){ $("#btn-align-" + d).toggleClass("active", d === cur); });
  1968. var pt = Math.round(parseFloat(getComputedStyle(n).fontSize) * 0.75 * 2) / 2;
  1969. var opt = $('#sel-size option').filter(function(){ return this.value === String(pt); });
  1970. $("#sel-size").val(opt.length ? String(pt) : "");
  1971. }
  1972. function wrapSelection(tag){
  1973. rich.focus();
  1974. var sel = getSel();
  1975. if (!sel.rangeCount) return;
  1976. var r = sel.getRangeAt(0);
  1977. var el = document.createElement(tag);
  1978. if (r.collapsed){
  1979. el.appendChild(document.createTextNode("​"));
  1980. r.insertNode(el);
  1981. var nr = document.createRange(); nr.setStart(el.firstChild, 1); nr.collapse(true);
  1982. sel.removeAllRanges(); sel.addRange(nr);
  1983. } else {
  1984. el.appendChild(r.extractContents());
  1985. r.insertNode(el);
  1986. }
  1987. markDirty();
  1988. }
  1989. function updateToolbarState(){
  1990. if (isTxtMode) return;
  1991. if (!rich.contains(getSel().anchorNode)) return;
  1992. try {
  1993. $("#btn-bold").toggleClass("active", document.queryCommandState("bold"));
  1994. $("#btn-italic").toggleClass("active", document.queryCommandState("italic"));
  1995. $("#btn-strike").toggleClass("active", document.queryCommandState("strikeThrough"));
  1996. } catch(e){}
  1997. var b = currentBlock();
  1998. var tag = b ? b.tagName.toLowerCase() : "p";
  1999. if (!/^h[1-6]$/.test(tag)) tag = "p";
  2000. $("#sel-head").val(tag);
  2001. $("#btn-code").toggleClass("active", !!(getSel().anchorNode && getSel().anchorNode.parentNode && getSel().anchorNode.parentNode.closest("code")));
  2002. if (isRtfMode) updateRtfToolbarState();
  2003. }
  2004. // ── Markdown source-mark reveal ─────────────────────────────────────────
  2005. // Adds/removes the .md-active class that drives the pseudo-element marks. In
  2006. // "active" mode only the block at the caret is marked; in "always" mode every
  2007. // block is. This only toggles a class, so it never mutates the document model
  2008. // (no dirty flag, no effect on serialization or word count).
  2009. function clearDecorations(){
  2010. var prev = rich.querySelectorAll(".md-active");
  2011. for (var i = 0; i < prev.length; i++) prev[i].classList.remove("md-active");
  2012. var syns = rich.querySelectorAll(".md-imgsyn, .md-linksyn");
  2013. for (var j = 0; j < syns.length; j++) syns[j].parentNode.removeChild(syns[j]);
  2014. }
  2015. // the canonical ![alt](src) text for an image's editable mark
  2016. function imgSynText(img){
  2017. var rel = img.getAttribute("data-rel") || img.getAttribute("src") || "";
  2018. var alt = img.getAttribute("alt") || "";
  2019. return "![" + alt + "](" + rel + ")";
  2020. }
  2021. // the canonical closing "](url)" text for a link's editable mark
  2022. function linkSynText(a){
  2023. return "](" + (a.getAttribute("href") || "") + ")";
  2024. }
  2025. // light up a block's marks; if it owns an image, add an editable ![alt](src)
  2026. // label, and give every link an editable closing "](url)" mark right after it
  2027. function decorateBlock(el){
  2028. // code blocks get a language <select> instead of a source-mark reveal
  2029. // (see syncLangSelector) — and must never get .md-active, since the
  2030. // generic inline-code mark rule (`.md-active code::before/after`) would
  2031. // otherwise wrap the fenced content in a stray backtick pair
  2032. if (el.tagName === "PRE") return;
  2033. el.classList.add("md-active");
  2034. if (el.tagName === "BLOCKQUOTE") return;
  2035. var img = el.querySelector ? el.querySelector("img") : null;
  2036. if (img && !el.querySelector(".md-imgsyn")){
  2037. var span = document.createElement("span");
  2038. span.className = "md-imgsyn";
  2039. span.setAttribute("contenteditable", "true");
  2040. span.setAttribute("spellcheck", "false");
  2041. span.setAttribute("title", "Edit the image reference — change the path to swap the image");
  2042. span.textContent = imgSynText(img);
  2043. el.insertBefore(span, el.firstChild); // render above the image
  2044. }
  2045. var links = el.querySelectorAll ? el.querySelectorAll("a") : [];
  2046. for (var i = 0; i < links.length; i++){
  2047. var a = links[i], next = a.nextSibling;
  2048. if (next && next.nodeType === 1 && next.classList && next.classList.contains("md-linksyn")) continue;
  2049. var lspan = document.createElement("span");
  2050. lspan.className = "md-linksyn";
  2051. lspan.setAttribute("contenteditable", "true");
  2052. lspan.setAttribute("spellcheck", "false");
  2053. lspan.setAttribute("title", "Edit the link URL");
  2054. lspan.textContent = linkSynText(a);
  2055. a.parentNode.insertBefore(lspan, a.nextSibling);
  2056. }
  2057. }
  2058. function updateActiveBlock(){
  2059. if (isTxtMode) return;
  2060. if (activeImgSyn() || activeLinkSyn()) return; // never tear down a mark being edited
  2061. clearDecorations();
  2062. if (settings.syntax === "none" || isRtfMode) return; // Always hide / no markdown marks in RTF
  2063. if (settings.syntax === "always"){
  2064. var all = rich.querySelectorAll("h1,h2,h3,h4,h5,h6,p,li,blockquote");
  2065. for (var j = 0; j < all.length; j++) decorateBlock(all[j]);
  2066. return;
  2067. }
  2068. var sel = getSel();
  2069. if (!sel.rangeCount || !rich.contains(sel.anchorNode)) return;
  2070. var b = currentBlock();
  2071. if (!b) return;
  2072. decorateBlock(b);
  2073. // a blockquote's marks live on the wrapper, so light it up too
  2074. var bq = b.closest ? b.closest("blockquote") : null;
  2075. if (bq && rich.contains(bq)) bq.classList.add("md-active");
  2076. }
  2077. // the editable image-mark label the caret is currently inside, if any
  2078. function activeImgSyn(){
  2079. var sel = getSel();
  2080. var n = sel && sel.anchorNode;
  2081. if (!n) return null;
  2082. if (n.nodeType === 3) n = n.parentNode;
  2083. return (n && n.closest) ? n.closest(".md-imgsyn") : null;
  2084. }
  2085. function synImage(syn){
  2086. var block = syn.parentNode;
  2087. return block ? block.querySelector("img") : null;
  2088. }
  2089. // the editable link-mark label the caret is currently inside, if any
  2090. function activeLinkSyn(){
  2091. var sel = getSel();
  2092. var n = sel && sel.anchorNode;
  2093. if (!n) return null;
  2094. if (n.nodeType === 3) n = n.parentNode;
  2095. return (n && n.closest) ? n.closest(".md-linksyn") : null;
  2096. }
  2097. function synLink(syn){
  2098. var a = syn.previousElementSibling;
  2099. return (a && a.tagName === "A") ? a : null;
  2100. }
  2101. // re-point a link from its edited "](url)" label (live, as the user types)
  2102. function syncLinkFromSyn(syn){
  2103. var a = synLink(syn);
  2104. if (!a) return;
  2105. var m = /^\]\(([^)]*)\)\s*$/.exec((syn.textContent || "").trim());
  2106. if (!m) return; // not a complete mark yet — wait
  2107. a.setAttribute("href", m[1].trim().replace(/^<|>$/g, ""));
  2108. markDirty();
  2109. }
  2110. // finish editing: snap the label back to the canonical text and drop focus
  2111. function commitLinkSyn(syn){
  2112. syncLinkFromSyn(syn);
  2113. var a = synLink(syn), block = syn.parentNode;
  2114. if (a) syn.textContent = linkSynText(a);
  2115. rich.focus();
  2116. if (block){
  2117. var r = document.createRange(); r.selectNodeContents(block); r.collapse(false);
  2118. var s = getSel(); s.removeAllRanges(); s.addRange(r);
  2119. }
  2120. updateActiveBlock();
  2121. }
  2122. // re-point an image from its edited ![alt](src) label (live, as the user types)
  2123. function syncImgFromSyn(syn){
  2124. var img = synImage(syn);
  2125. if (!img) return;
  2126. var m = /^!\[([^\]]*)\]\(([^)]*)\)\s*$/.exec((syn.textContent || "").trim());
  2127. if (!m) return; // not a complete mark yet — wait
  2128. var alt = m[1];
  2129. var rawSrc = m[2].trim().replace(/^<|>$/g, "");
  2130. img.setAttribute("alt", alt);
  2131. if (/^(https?:|data:|blob:)/i.test(rawSrc)){
  2132. img.removeAttribute("data-rel");
  2133. img.setAttribute("src", rawSrc);
  2134. } else {
  2135. var rel = rawSrc.replace(/^\.?\/+/, "");
  2136. img.setAttribute("data-rel", rel);
  2137. img.setAttribute("src", filepath ? mediaURLFor(rel) : rel);
  2138. }
  2139. markDirty();
  2140. }
  2141. // finish editing: snap the label back to the canonical text and drop focus
  2142. function commitImgSyn(syn){
  2143. syncImgFromSyn(syn);
  2144. var img = synImage(syn), block = syn.parentNode;
  2145. if (img) syn.textContent = imgSynText(img);
  2146. rich.focus();
  2147. if (block){
  2148. var r = document.createRange(); r.selectNodeContents(block); r.collapse(false);
  2149. var s = getSel(); s.removeAllRanges(); s.addRange(r);
  2150. }
  2151. updateActiveBlock();
  2152. }
  2153. function applySyntaxMode(){
  2154. settings.syntax = $("#set-syntax").val() || "active";
  2155. updateActiveBlock();
  2156. savePrefs();
  2157. }
  2158. // ════════════════════════════════════════════════════════════════════════
  2159. // Shortcuts
  2160. // ════════════════════════════════════════════════════════════════════════
  2161. function comboFromEvent(e){
  2162. var parts = [];
  2163. if (e.ctrlKey || e.metaKey) parts.push("ctrl");
  2164. if (e.shiftKey) parts.push("shift");
  2165. if (e.altKey) parts.push("alt");
  2166. var k = e.key;
  2167. if (k === " ") k = "space";
  2168. else if (k.length === 1) k = k.toLowerCase();
  2169. else k = k.toLowerCase();
  2170. if (["control","shift","alt","meta"].indexOf(k) >= 0) return null;
  2171. parts.push(k);
  2172. return parts.join("+");
  2173. }
  2174. function globalKeydown(e){
  2175. if (recordingAction){ recordKey(e); return; }
  2176. if ($("#settings-overlay").hasClass("show")) {
  2177. if (e.key === "Escape") closeSettings();
  2178. return;
  2179. }
  2180. if ($("#link-overlay").hasClass("show")) {
  2181. if (e.key === "Escape") linkDlgCancel();
  2182. else if (e.key === "Enter") { e.preventDefault(); linkDlgOk(); }
  2183. return;
  2184. }
  2185. var combo = comboFromEvent(e);
  2186. if (!combo) return;
  2187. for (var action in keymap){
  2188. if (keymap[action] === combo){
  2189. var def = ACTIONS[action];
  2190. if (!def) continue;
  2191. if (def.md && isTxtMode) continue; // markdown-only action in txt mode
  2192. if (def.rtf === false && isRtfMode) continue; // no RTF equivalent
  2193. if (def.md && (activeImgSyn() || activeLinkSyn())) continue; // don't format inside a source mark
  2194. e.preventDefault();
  2195. def.fn();
  2196. return;
  2197. }
  2198. }
  2199. }
  2200. function prettyCombo(c){
  2201. return c.split("+").map(function(p){
  2202. if (p === "ctrl") return "Ctrl";
  2203. if (p === "shift") return "Shift";
  2204. if (p === "alt") return "Alt";
  2205. if (p === "space") return "Space";
  2206. return p.length === 1 ? p.toUpperCase() : p.charAt(0).toUpperCase() + p.slice(1);
  2207. }).join(" + ");
  2208. }
  2209. function buildKeyList(){
  2210. var html = "";
  2211. for (var action in ACTIONS){
  2212. html += '<div class="key-row"><span class="key-name">' + escapeHtml(ACTIONS[action].label) +
  2213. '</span><button class="key-cap" data-action="' + action + '" onclick="startRecord(\'' + action + '\')">' +
  2214. escapeHtml(prettyCombo(keymap[action] || "")) + '</button></div>';
  2215. }
  2216. document.getElementById("keys-list").innerHTML = html;
  2217. }
  2218. function startRecord(action){
  2219. if (recordingAction){
  2220. $('.key-cap[data-action="'+recordingAction+'"]').removeClass("recording")
  2221. .text(prettyCombo(keymap[recordingAction]));
  2222. }
  2223. recordingAction = action;
  2224. $('.key-cap[data-action="'+action+'"]').addClass("recording").text("Press keys…");
  2225. }
  2226. function recordKey(e){
  2227. e.preventDefault();
  2228. if (e.key === "Escape"){
  2229. $('.key-cap[data-action="'+recordingAction+'"]').removeClass("recording")
  2230. .text(prettyCombo(keymap[recordingAction]));
  2231. recordingAction = null;
  2232. return;
  2233. }
  2234. var combo = comboFromEvent(e);
  2235. if (!combo || ["ctrl","shift","alt"].indexOf(combo) >= 0) return; // wait for a real key
  2236. // free the combo from any other action
  2237. for (var a in keymap){ if (keymap[a] === combo && a !== recordingAction) keymap[a] = ""; }
  2238. keymap[recordingAction] = combo;
  2239. recordingAction = null;
  2240. savePrefs();
  2241. buildKeyList();
  2242. }
  2243. function resetKeys(){
  2244. keymap = JSON.parse(JSON.stringify(DEFAULT_KEYS));
  2245. savePrefs(); buildKeyList();
  2246. }
  2247. // ════════════════════════════════════════════════════════════════════════
  2248. // Images
  2249. // ════════════════════════════════════════════════════════════════════════
  2250. function docDir(){
  2251. var i = filepath.lastIndexOf("/");
  2252. return i < 0 ? "" : filepath.substring(0, i);
  2253. }
  2254. function docName(){
  2255. var n = filename.replace(/\.[^.]+$/, "");
  2256. return n || "document";
  2257. }
  2258. function relDir(){
  2259. return settings.imgDir.replace(/\{name\}/g, docName()).replace(/^\.?\/+/, "");
  2260. }
  2261. function mediaURLFor(rel){
  2262. rel = rel.replace(/^\.?\/+/, "");
  2263. return ao_root + "media?file=" + encodeURIComponent(docDir() + "/" + rel);
  2264. }
  2265. function rewriteImageSrcs(root){
  2266. if (!filepath) return;
  2267. $(root).find("img").each(function(){
  2268. var src = this.getAttribute("src") || "";
  2269. if (/^(https?:|data:|blob:)/i.test(src) || src.indexOf("media?file=") >= 0) return;
  2270. var rel = src.replace(/^\.?\/+/, "");
  2271. this.setAttribute("data-rel", rel);
  2272. this.setAttribute("src", mediaURLFor(rel));
  2273. });
  2274. }
  2275. function makeImgName(orig, forceExt){
  2276. var base = (orig || "image").replace(/\.[^.]+$/, "").replace(/[^a-zA-Z0-9_\-]+/g, "_").substr(0, 40) || "image";
  2277. var ext = forceExt || ((orig || "").split(".").pop() || "png").toLowerCase();
  2278. var ts = Date.now().toString(36);
  2279. return base + "-" + ts + "." + ext;
  2280. }
  2281. // ensure the image folder exists on the server, then run cb(reldir)
  2282. function ensureImgDir(cb){
  2283. if (!filepath){
  2284. alert("Please save the document first — images are stored in a folder next to it.");
  2285. return;
  2286. }
  2287. var rel = relDir();
  2288. ao_module_agirun("Text/backend/imgtool.agi", { action:"mkdir", docpath:filepath, reldir:rel }, function(data){
  2289. if (data && data.error){ setStatus("Image folder error: " + data.error, "error"); return; }
  2290. cb(rel);
  2291. }, function(){ setStatus("Could not prepare image folder", "error"); });
  2292. }
  2293. function pickDeviceImage(){
  2294. if (isTxtMode) return;
  2295. if (!filepath && !isRtfMode){ alert("Please save the document first."); return; }
  2296. document.getElementById("device-file").click();
  2297. }
  2298. function onDeviceFileChosen(e){
  2299. var file = e.target.files[0];
  2300. e.target.value = "";
  2301. if (!file) return;
  2302. if (isRtfMode){ insertEmbeddedImage(file); return; }
  2303. ensureImgDir(function(rel){
  2304. prepareBlob(file, function(blob, ext){
  2305. var fname = makeImgName(file.name, ext);
  2306. setStatus("Uploading image…");
  2307. ao_module_uploadFile(new File([blob], fname), docDir() + "/" + rel, function(){
  2308. insertImage(rel + "/" + fname, docName());
  2309. setStatus("Image inserted");
  2310. }, undefined, function(){ setStatus("Image upload failed", "error"); });
  2311. });
  2312. });
  2313. }
  2314. // client-side compression via canvas (only when enabled)
  2315. function prepareBlob(file, cb){
  2316. if (!settings.compress || !/^image\//.test(file.type) || file.type === "image/gif"){
  2317. cb(file, (file.name.split(".").pop() || "png").toLowerCase());
  2318. return;
  2319. }
  2320. var img = new Image();
  2321. img.onload = function(){
  2322. var w = img.naturalWidth, h = img.naturalHeight;
  2323. var maxW = settings.maxWidth;
  2324. if (maxW > 0 && w > maxW){ h = Math.round(h * (maxW / w)); w = maxW; }
  2325. var c = document.createElement("canvas");
  2326. c.width = w; c.height = h;
  2327. c.getContext("2d").drawImage(img, 0, 0, w, h);
  2328. c.toBlob(function(blob){
  2329. URL.revokeObjectURL(img.src);
  2330. if (blob) cb(blob, "jpg");
  2331. else cb(file, (file.name.split(".").pop() || "png").toLowerCase());
  2332. }, "image/jpeg", settings.quality / 100);
  2333. };
  2334. img.onerror = function(){ cb(file, (file.name.split(".").pop() || "png").toLowerCase()); };
  2335. img.src = URL.createObjectURL(file);
  2336. }
  2337. function pickServerImage(){
  2338. if (isTxtMode) return;
  2339. if (!filepath && !isRtfMode){ alert("Please save the document first."); return; }
  2340. ao_module_openFileSelector(handleServerImage, "user:/", "file", false, {
  2341. filter: ["jpg","jpeg","png","gif","webp","bmp","svg"]
  2342. });
  2343. }
  2344. function handleServerImage(fd){
  2345. if (!fd || !fd.length) return;
  2346. var src = fd[0].filepath, name = fd[0].filename;
  2347. if (isRtfMode){
  2348. setStatus("Importing image…");
  2349. fetch(ao_root + "media?file=" + encodeURIComponent(src), { credentials:"same-origin" })
  2350. .then(function(r){ if (!r.ok) throw new Error("HTTP " + r.status); return r.blob(); })
  2351. .then(function(b){ insertEmbeddedImage(new File([b], name, { type:b.type })); })
  2352. .catch(function(){ setStatus("Image import failed", "error"); });
  2353. return;
  2354. }
  2355. var rel = relDir();
  2356. var dest = makeImgName(name, settings.compress ? "jpg" : null);
  2357. setStatus("Importing image…");
  2358. ao_module_agirun("Text/backend/imgtool.agi", {
  2359. action:"import", docpath:filepath, reldir:rel, src:src, destname:dest,
  2360. compress: settings.compress ? "true" : "false", maxwidth: settings.maxWidth
  2361. }, function(data){
  2362. if (data && data.error){ setStatus("Import failed: " + data.error, "error"); return; }
  2363. insertImage(data.rel || (rel + "/" + dest), docName());
  2364. setStatus("Image inserted");
  2365. }, function(){ setStatus("Image import failed", "error"); });
  2366. }
  2367. function insertImageByUrl(){
  2368. if (isTxtMode) return;
  2369. var url = prompt("Image URL:", "https://");
  2370. if (!url) return;
  2371. rich.focus();
  2372. document.execCommand("insertHTML", false, '<img src="'+escapeAttr(url)+'" alt="">');
  2373. markDirty();
  2374. }
  2375. // insert an image referencing a path relative to the document
  2376. function insertImage(rel, alt){
  2377. if (isTxtMode){
  2378. insertAtTextarea(plain, "![" + (alt||"") + "](" + mdLinkDest(rel) + ")");
  2379. markDirty(); return;
  2380. }
  2381. rich.focus();
  2382. var html = '<img src="'+escapeAttr(mediaURLFor(rel))+'" data-rel="'+escapeAttr(rel)+'" alt="'+escapeAttr(alt||"")+'">';
  2383. document.execCommand("insertHTML", false, html);
  2384. refreshEmptyState(); markDirty();
  2385. }
  2386. function insertAtTextarea(ta, text){
  2387. var s = ta.selectionStart, e = ta.selectionEnd;
  2388. ta.value = ta.value.substring(0, s) + text + ta.value.substring(e);
  2389. ta.selectionStart = ta.selectionEnd = s + text.length;
  2390. ta.focus();
  2391. }
  2392. // paste / drop images straight into the editor
  2393. function onRichPaste(e){
  2394. var items = (e.originalEvent || e).clipboardData && (e.originalEvent || e).clipboardData.items;
  2395. if (!items) return;
  2396. for (var i = 0; i < items.length; i++){
  2397. if (items[i].type && items[i].type.indexOf("image") === 0){
  2398. var file = items[i].getAsFile();
  2399. if (file){ e.preventDefault(); handleDroppedImage(file); return; }
  2400. }
  2401. }
  2402. }
  2403. function onRichDrop(e){
  2404. var dt = (e.originalEvent || e).dataTransfer;
  2405. if (dt && dt.files && dt.files.length && /^image\//.test(dt.files[0].type)){
  2406. e.preventDefault(); handleDroppedImage(dt.files[0]);
  2407. }
  2408. }
  2409. function handleDroppedImage(file){
  2410. if (isRtfMode){ insertEmbeddedImage(file); return; }
  2411. if (!filepath){ alert("Please save the document first to store pasted images."); return; }
  2412. ensureImgDir(function(rel){
  2413. prepareBlob(file, function(blob, ext){
  2414. var fname = makeImgName(file.name || "pasted.png", ext);
  2415. setStatus("Uploading image…");
  2416. ao_module_uploadFile(new File([blob], fname), docDir() + "/" + rel, function(){
  2417. insertImage(rel + "/" + fname, docName());
  2418. setStatus("Image inserted");
  2419. }, undefined, function(){ setStatus("Image upload failed", "error"); });
  2420. });
  2421. });
  2422. }
  2423. // ════════════════════════════════════════════════════════════════════════
  2424. // Export
  2425. // ════════════════════════════════════════════════════════════════════════
  2426. function renderedHTML(){
  2427. if (isTxtMode) return "<pre>" + escapeHtml(plain.value) + "</pre>";
  2428. if (isRtfMode) return richClone().innerHTML.replace(/​/g, "");
  2429. return renderWithBlankRuns(getContent());
  2430. }
  2431. // collect the CSS that styles .md-content so exports match the editor
  2432. function exportCSS(){
  2433. var bg = getCss("--editor-bg"), text = getCss("--text"), accent = getCss("--accent");
  2434. var code = getCss("--code-bg"), sep = getCss("--sep"), quote = getCss("--quote-bdr");
  2435. var tbl = getCss("--table-bdr"), text2 = getCss("--text2");
  2436. return [
  2437. "body{margin:0;background:"+bg+";color:"+text+";font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;line-height:"+settings.lineHeight+";}",
  2438. ".md-content{max-width:820px;margin:0 auto;padding:48px 40px;font-size:"+settings.fontSize+"px;word-wrap:break-word;}",
  2439. ".md-content h1,.md-content h2,.md-content h3,.md-content h4,.md-content h5,.md-content h6{font-weight:700;line-height:1.3;margin:1.4em 0 .6em;}",
  2440. ".md-content h1{font-size:2em;border-bottom:1px solid "+sep+";padding-bottom:.25em;}",
  2441. ".md-content h2{font-size:1.6em;border-bottom:1px solid "+sep+";padding-bottom:.2em;}",
  2442. ".md-content h3{font-size:1.3em;} .md-content h4{font-size:1.1em;} .md-content h6{color:"+text2+";}",
  2443. ".md-content p{margin:.55em 0;} .md-content a{color:"+accent+";text-decoration:none;}",
  2444. ".md-content ul,.md-content ol{margin:.5em 0;padding-left:1.7em;} .md-content li{margin:.25em 0;}",
  2445. ".md-content blockquote{margin:.8em 0;padding:.2em 1em;color:"+text2+";border-left:3px solid "+quote+";border-radius:0 6px 6px 0;}",
  2446. ".md-content code{font-family:'SF Mono',Consolas,monospace;font-size:.88em;background:"+code+";padding:.15em .4em;border-radius:4px;}",
  2447. ".md-content pre{margin:.8em 0;padding:14px 16px;background:"+code+";border-radius:8px;overflow-x:auto;}",
  2448. ".md-content pre code{background:none;padding:0;} .md-content hr{border:none;border-top:1px solid "+sep+";margin:1.6em 0;}",
  2449. ".md-content img{max-width:100%;border-radius:6px;}",
  2450. ".md-content table{border-collapse:collapse;margin:.8em 0;} .md-content th,.md-content td{border:1px solid "+tbl+";padding:6px 12px;} .md-content th{background:"+code+";}",
  2451. ".hl-com{color:"+getCss("--hl-com")+";font-style:italic;} .hl-str{color:"+getCss("--hl-str")+";} .hl-num{color:"+getCss("--hl-num")+";}",
  2452. ".hl-kw{color:"+getCss("--hl-kw")+";} .hl-typ{color:"+getCss("--hl-typ")+";} .hl-fn{color:"+getCss("--hl-fn")+";}"
  2453. ].join("\n");
  2454. }
  2455. function getCss(v){ return getComputedStyle(document.body).getPropertyValue(v).trim(); }
  2456. // apply syntax highlighting to an export's fenced code blocks
  2457. function highlightExportCode(root){
  2458. if (typeof TextHL === "undefined") return;
  2459. var codes = root.querySelectorAll("pre > code");
  2460. for (var i = 0; i < codes.length; i++){
  2461. var lang = codeLang(codes[i]);
  2462. if (lang && TextHL.supports(lang)) codes[i].innerHTML = TextHL.highlight(codes[i].textContent, lang);
  2463. }
  2464. }
  2465. // fetch a same-origin image and return a data URL (for self-contained export)
  2466. function inlineImage(url){
  2467. return new Promise(function(resolve){
  2468. var xhr = new XMLHttpRequest();
  2469. xhr.open("GET", url, true); xhr.responseType = "blob";
  2470. xhr.onload = function(){
  2471. if (xhr.status === 200){
  2472. var fr = new FileReader();
  2473. fr.onloadend = function(){ resolve(fr.result); };
  2474. fr.onerror = function(){ resolve(url); };
  2475. fr.readAsDataURL(xhr.response);
  2476. } else resolve(url);
  2477. };
  2478. xhr.onerror = function(){ resolve(url); };
  2479. xhr.send();
  2480. });
  2481. }
  2482. // build an offscreen DOM with all images inlined as data URLs
  2483. function buildExportContainer(){
  2484. var div = document.createElement("div");
  2485. div.className = "md-content";
  2486. div.innerHTML = renderedHTML();
  2487. highlightExportCode(div); // colour fenced code so exports match the screen
  2488. // resolve relative srcs to media URLs first
  2489. $(div).find("img").each(function(){
  2490. var rel = this.getAttribute("data-rel");
  2491. var src = this.getAttribute("src") || "";
  2492. if (rel) this.setAttribute("src", mediaURLFor(rel));
  2493. else if (!/^(https?:|data:)/i.test(src) && filepath) this.setAttribute("src", mediaURLFor(src));
  2494. });
  2495. var imgs = Array.prototype.slice.call(div.querySelectorAll("img"));
  2496. return Promise.all(imgs.map(function(im){
  2497. return inlineImage(im.getAttribute("src")).then(function(d){ im.setAttribute("src", d); });
  2498. })).then(function(){ return div; });
  2499. }
  2500. function downloadBlob(blob, name){
  2501. var a = document.createElement("a");
  2502. a.href = URL.createObjectURL(blob);
  2503. a.download = name;
  2504. document.body.appendChild(a); a.click();
  2505. setTimeout(function(){ URL.revokeObjectURL(a.href); a.remove(); }, 1000);
  2506. }
  2507. function exportHTML(){
  2508. showBusy("Building HTML…");
  2509. buildExportContainer().then(function(div){
  2510. var title = escapeHtml(docName());
  2511. var doc = "<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>" +
  2512. title + "</title>\n<style>\n" + exportCSS() + "\n</style></head>\n<body>\n" +
  2513. div.outerHTML + "\n</body></html>";
  2514. downloadBlob(new Blob([doc], { type:"text/html" }), docName() + ".html");
  2515. hideBusy(); setStatus("Exported HTML");
  2516. }).catch(function(err){ hideBusy(); setStatus("HTML export failed", "error"); console.error(err); });
  2517. }
  2518. // ── Download the raw document (.md / .txt), zipping it with its images ─────
  2519. function collectDocImages(){
  2520. var seen = {}, out = [];
  2521. function add(p){
  2522. if (!p) return;
  2523. p = p.replace(/^\.?\/+/, "");
  2524. if (/^(https?:|data:)/i.test(p) || p.indexOf("media?file=") >= 0) return;
  2525. if (!seen[p]){ seen[p] = 1; out.push(p); }
  2526. }
  2527. if (isTxtMode){
  2528. // capture both bare and angle-bracket-wrapped destinations (the latter
  2529. // is used when a path contains spaces)
  2530. var re = /!\[[^\]]*\]\(\s*(?:<([^>]+)>|([^)\s]+))/g, m;
  2531. while ((m = re.exec(plain.value))) add(m[1] || m[2]);
  2532. } else {
  2533. $(rich).find("img").each(function(){
  2534. add(this.getAttribute("data-rel") || this.getAttribute("src"));
  2535. });
  2536. }
  2537. return out;
  2538. }
  2539. function exportDocument(){
  2540. if (isRtfMode){ // images are embedded in the RTF itself
  2541. showBusy("Building document…");
  2542. getContentAsync().then(function(rtf){
  2543. hideBusy();
  2544. downloadBlob(new Blob([rtf], { type:"application/rtf" }), docName() + ".rtf");
  2545. setStatus("Downloaded " + docName() + ".rtf");
  2546. }).catch(function(){ hideBusy(); setStatus("Export failed", "error"); });
  2547. return;
  2548. }
  2549. var content = getContent();
  2550. var ext = isTxtMode ? "txt" : "md";
  2551. var name = docName() + "." + ext;
  2552. var imgs = collectDocImages();
  2553. if (imgs.length === 0){
  2554. downloadBlob(new Blob([content], { type: isTxtMode ? "text/plain" : "text/markdown" }), name);
  2555. setStatus("Downloaded " + name);
  2556. return;
  2557. }
  2558. if (!filepath){ alert("Please save the document first so its images can be bundled."); return; }
  2559. showBusy("Bundling document…");
  2560. ao_module_agirun("Text/backend/export.agi", {
  2561. action:"zip", docpath:filepath, name:name, content:content, images:JSON.stringify(imgs)
  2562. }, function(data){
  2563. if (!data || data.error){ hideBusy(); setStatus("Export failed: " + ((data && data.error) || "unknown"), "error"); return; }
  2564. var url = ao_root + "media/download/?file=" + encodeURIComponent(data.zip);
  2565. fetch(url).then(function(r){ return r.blob(); }).then(function(blob){
  2566. downloadBlob(blob, docName() + ".zip");
  2567. hideBusy(); setStatus("Downloaded " + docName() + ".zip");
  2568. // best-effort temp cleanup
  2569. ao_module_agirun("Text/backend/export.agi", { action:"cleanup", zip:data.zip, workdir:data.workdir }, function(){}, function(){});
  2570. }).catch(function(){ hideBusy(); setStatus("Export download failed", "error"); });
  2571. }, function(){ hideBusy(); setStatus("Export failed", "error"); });
  2572. }
  2573. // ════════════════════════════════════════════════════════════════════════
  2574. // Text-based PDF export (pdf-lib): real selectable text + embedded images.
  2575. // Mirrors the PDF Tool editor — standard fonts for encodable text,
  2576. // rasterise fallback for glyphs the standard fonts can't encode (e.g. CJK).
  2577. // ════════════════════════════════════════════════════════════════════════
  2578. function exportPDF(){
  2579. showBusy("Rendering PDF…");
  2580. pdfBuild().then(function(bytes){
  2581. downloadBlob(new Blob([bytes], { type:"application/pdf" }), docName() + ".pdf");
  2582. hideBusy(); setStatus("Exported PDF");
  2583. }).catch(function(err){ hideBusy(); setStatus("PDF export failed", "error"); console.error(err); });
  2584. }
  2585. // Save the rendered PDF straight into ArozOS instead of the browser's download
  2586. // folder. Uses the "new file" mode of the shared file selector so the user
  2587. // picks a destination folder + filename; the callback is a named, window-scoped
  2588. // function (not an inline closure) since ao_module_openFileSelector calls it
  2589. // back by name once the virtual-desktop file-selector window closes.
  2590. function savePDFToArozOS(){
  2591. ao_module_openFileSelector(handlePDFSaveTarget, "user:/Desktop", "new", false, { defaultName: docName() + ".pdf" });
  2592. }
  2593. function handlePDFSaveTarget(fd){
  2594. if (!fd || !fd.length) return;
  2595. var targetName = fd[0].filename;
  2596. var targetDir = fd[0].filepath.substring(0, fd[0].filepath.length - targetName.length - 1);
  2597. showBusy("Rendering PDF…");
  2598. pdfBuild().then(function(bytes){
  2599. var file = new File([bytes], targetName, { type: "application/pdf" });
  2600. ao_module_uploadFile(file, targetDir, function(){
  2601. hideBusy(); setStatus("Saved " + targetName + " to " + targetDir);
  2602. }, undefined, function(){
  2603. hideBusy(); setStatus("Save to ArozOS failed", "error");
  2604. });
  2605. }).catch(function(err){ hideBusy(); setStatus("PDF export failed", "error"); console.error(err); });
  2606. }
  2607. var _measureCtx = null;
  2608. function measureCtx(){ if (!_measureCtx) _measureCtx = document.createElement("canvas").getContext("2d"); return _measureCtx; }
  2609. function PDF_COLORS(){
  2610. var rgb = PDFLib.rgb;
  2611. return {
  2612. text: rgb(0.16, 0.18, 0.22),
  2613. head: rgb(0.10, 0.12, 0.16),
  2614. accent: rgb(0.16, 0.40, 0.82),
  2615. muted: rgb(0.45, 0.49, 0.57),
  2616. code: rgb(0.20, 0.22, 0.30),
  2617. codebg: rgb(0.96, 0.97, 0.99),
  2618. rule: rgb(0.85, 0.87, 0.91),
  2619. quote: rgb(0.74, 0.78, 0.85),
  2620. tline: rgb(0.80, 0.83, 0.88),
  2621. thead: rgb(0.95, 0.96, 0.98)
  2622. };
  2623. }
  2624. function assignStyle(a, b){ var o = {}; for (var k in a) o[k] = a[k]; for (var k in b) o[k] = b[k]; return o; }
  2625. function mkRun(text, s){ s = s || {}; return { text: text, bold:!!s.bold, italic:!!s.italic, mono:!!s.mono, code:!!s.code, link:!!s.link, strike:!!s.strike }; }
  2626. function decodeEntities(s){ var ta = document.createElement("textarea"); ta.innerHTML = s || ""; return ta.value; }
  2627. function stripTags(s){ return (s || "").replace(/<[^>]*>/g, ""); }
  2628. // flatten marked inline tokens into styled runs
  2629. function inlineRuns(tokens, style){
  2630. style = style || {};
  2631. var out = [];
  2632. (tokens || []).forEach(function(t){
  2633. switch (t.type){
  2634. case "text":
  2635. if (t.tokens && t.tokens.length) out = out.concat(inlineRuns(t.tokens, style));
  2636. else out.push(mkRun(decodeEntities(t.text), style));
  2637. break;
  2638. case "strong": out = out.concat(inlineRuns(t.tokens, assignStyle(style, { bold:true }))); break;
  2639. case "em": out = out.concat(inlineRuns(t.tokens, assignStyle(style, { italic:true }))); break;
  2640. case "del": out = out.concat(inlineRuns(t.tokens, assignStyle(style, { strike:true }))); break;
  2641. case "codespan": out.push(mkRun(decodeEntities(t.text), assignStyle(style, { mono:true, code:true }))); break;
  2642. case "link": out = out.concat(inlineRuns(t.tokens, assignStyle(style, { link:true }))); break;
  2643. case "image": out.push({ image:true, href:t.href, alt:t.text || "" }); break;
  2644. case "br": out.push({ brk:true }); break;
  2645. case "escape": out.push(mkRun(t.text, style)); break;
  2646. case "html": out.push(mkRun(stripTags(t.text), style)); break;
  2647. default: if (t.text) out.push(mkRun(decodeEntities(t.text), style)); break;
  2648. }
  2649. });
  2650. return out;
  2651. }
  2652. function pdfPickFont(P, run){
  2653. if (run.mono) return run.bold ? P.fonts.monoBold : P.fonts.mono;
  2654. if (run.bold && run.italic) return P.fonts.bi;
  2655. if (run.bold) return P.fonts.bold;
  2656. if (run.italic) return P.fonts.ital;
  2657. return P.fonts.reg;
  2658. }
  2659. function pdfNewCursor(P){
  2660. var c = { pageW:595.28, pageH:841.89, margin:56, y:0, page:null };
  2661. c.page = P.pdf.addPage([c.pageW, c.pageH]);
  2662. c.y = c.pageH - c.margin;
  2663. return c;
  2664. }
  2665. function pdfEnsure(P, h){
  2666. var c = P.cur;
  2667. if (c.y - h < c.margin){ c.page = P.pdf.addPage([c.pageW, c.pageH]); c.y = c.pageH - c.margin; }
  2668. }
  2669. function pdfRule(P){
  2670. var c = P.cur;
  2671. c.page.drawLine({ start:{x:c.margin, y:c.y}, end:{x:c.pageW - c.margin, y:c.y}, thickness:0.7, color:P.col.rule });
  2672. }
  2673. function pdfColToCss(col){
  2674. if (!col) return "#2a2e38";
  2675. return "rgb(" + Math.round((col.red||0)*255) + "," + Math.round((col.green||0)*255) + "," + Math.round((col.blue||0)*255) + ")";
  2676. }
  2677. // split text for wrapping: whole words, runs of spaces, and individual CJK chars
  2678. function tokenizeWrap(text){
  2679. return (text || "").match(/[ -〿぀-ヿ㐀-䶿一-鿿豈-﫿＀-￯가-힯]|\s+|[^\s -〿぀-ヿ㐀-䶿一-鿿豈-﫿＀-￯가-힯]+/g) || [];
  2680. }
  2681. function canvasToEmbeddedPng(pdf, canvas){
  2682. return new Promise(function(res, rej){
  2683. canvas.toBlob(function(b){
  2684. if (!b){ rej(new Error("canvas")); return; }
  2685. var fr = new FileReader();
  2686. fr.onload = function(){ pdf.embedPng(new Uint8Array(fr.result)).then(res, rej); };
  2687. fr.onerror = rej;
  2688. fr.readAsArrayBuffer(b);
  2689. }, "image/png");
  2690. });
  2691. }
  2692. // draw one word as real text; on encoding failure, rasterise it and place as image
  2693. function pdfDrawWord(P, font, word, size, x, color, strike){
  2694. var c = P.cur;
  2695. try {
  2696. var w = font.widthOfTextAtSize(word, size);
  2697. c.page.drawText(word, { x:x, y:c.y - size*0.80, size:size, font:font, color:color });
  2698. if (strike) c.page.drawLine({ start:{x:x, y:c.y - size*0.45}, end:{x:x + w, y:c.y - size*0.45}, thickness:0.6, color:color });
  2699. return Promise.resolve(w);
  2700. } catch (e){
  2701. return pdfDrawRasterWord(P, word, size, x, color);
  2702. }
  2703. }
  2704. function pdfDrawRasterWord(P, word, size, x, color){
  2705. var c = P.cur, k = 3;
  2706. var ctx = measureCtx(); ctx.font = size + "px sans-serif";
  2707. var wPt = Math.max(1, ctx.measureText(word).width), hPt = size * 1.2;
  2708. var cv = document.createElement("canvas");
  2709. cv.width = Math.ceil(wPt * k); cv.height = Math.ceil(hPt * k);
  2710. var cx = cv.getContext("2d");
  2711. cx.scale(k, k); cx.fillStyle = pdfColToCss(color); cx.textBaseline = "alphabetic"; cx.font = size + "px sans-serif";
  2712. cx.fillText(word, 0, size * 0.92);
  2713. return canvasToEmbeddedPng(P.pdf, cv).then(function(png){
  2714. c.page.drawImage(png, { x:x, y:c.y - size, width:wPt, height:hPt });
  2715. return wPt;
  2716. });
  2717. }
  2718. // flow styled runs with word wrapping; returns a promise (images/raster are async)
  2719. function pdfFlow(P, runs, startX, fontSize, lineH, baseColor){
  2720. var c = P.cur, maxX = c.pageW - c.margin, x = startX;
  2721. pdfEnsure(P, lineH);
  2722. function nl(){ c.y -= lineH; x = startX; pdfEnsure(P, lineH); }
  2723. var i = 0, words = [], wi = 0, run = null, font = null, size = 0, color = null;
  2724. function nextRun(){
  2725. if (i >= runs.length) return null;
  2726. return runs[i++];
  2727. }
  2728. function step(){
  2729. // advance through words of the current run
  2730. while (run && wi < words.length){
  2731. var word = words[wi++];
  2732. if (/^\s+$/.test(word)){ if (x === startX) continue; word = " "; }
  2733. var ww;
  2734. try { ww = font.widthOfTextAtSize(word, size); }
  2735. catch (e){ var ctx = measureCtx(); ctx.font = size + "px sans-serif"; ww = ctx.measureText(word).width; }
  2736. if (word !== " " && x + ww > maxX && x > startX) nl();
  2737. var px = x;
  2738. x += ww;
  2739. return pdfDrawWord(P, font, word, size, px, color, run.strike).then(function(realW){
  2740. x = px + realW; return step();
  2741. });
  2742. }
  2743. // current run done — get next
  2744. run = nextRun();
  2745. if (!run){ c.y -= lineH; return Promise.resolve(); } // consume final line
  2746. if (run.brk){ nl(); return step(); }
  2747. if (run.image){
  2748. if (x > startX){ c.y -= lineH; x = startX; }
  2749. return pdfDrawImage(P, run.href, startX).then(step);
  2750. }
  2751. font = pdfPickFont(P, run);
  2752. size = run.mono ? fontSize * 0.94 : fontSize;
  2753. color = run.link ? P.col.accent : (run.code ? P.col.code : baseColor);
  2754. words = tokenizeWrap(run.text); wi = 0;
  2755. return step();
  2756. }
  2757. return step();
  2758. }
  2759. function fetchBytes(url){
  2760. return fetch(url).then(function(r){ if (!r.ok) throw new Error("HTTP " + r.status); return r.arrayBuffer(); })
  2761. .then(function(b){ return new Uint8Array(b); });
  2762. }
  2763. function pdfResolveSrc(href){
  2764. if (/^(https?:|data:)/i.test(href)) return href;
  2765. return filepath ? mediaURLFor(href) : href;
  2766. }
  2767. function pdfEmbedBytes(pdf, bytes){
  2768. if (bytes[0] === 0x89 && bytes[1] === 0x50) return pdf.embedPng(bytes);
  2769. if (bytes[0] === 0xFF && bytes[1] === 0xD8) return pdf.embedJpg(bytes);
  2770. return new Promise(function(res, rej){ // gif/webp/svg/bmp → rasterise
  2771. var im = new Image();
  2772. im.onload = function(){
  2773. var cv = document.createElement("canvas");
  2774. cv.width = im.naturalWidth || 300; cv.height = im.naturalHeight || 150;
  2775. cv.getContext("2d").drawImage(im, 0, 0);
  2776. canvasToEmbeddedPng(pdf, cv).then(res, rej);
  2777. };
  2778. im.onerror = function(){ rej(new Error("image decode")); };
  2779. im.src = URL.createObjectURL(new Blob([bytes]));
  2780. });
  2781. }
  2782. function pdfDrawImage(P, href, startX){
  2783. var c = P.cur;
  2784. return fetchBytes(pdfResolveSrc(href)).then(function(bytes){ return pdfEmbedBytes(P.pdf, bytes); }).then(function(img){
  2785. var natW = img.width, natH = img.height;
  2786. var dispW = Math.min(natW, c.pageW - c.margin - startX), dispH = natH * (dispW / natW);
  2787. var maxH = c.pageH - 2 * c.margin;
  2788. if (dispH > maxH){ dispH = maxH; dispW = natW * (dispH / natH); }
  2789. pdfEnsure(P, dispH + 8);
  2790. c.page.drawImage(img, { x:startX, y:c.y - dispH, width:dispW, height:dispH });
  2791. c.y -= dispH + 8;
  2792. }).catch(function(){
  2793. c.page.drawText("[image]", { x:startX, y:c.y - 11, size:11, font:P.fonts.ital, color:P.col.muted });
  2794. c.y -= 18;
  2795. });
  2796. }
  2797. function pdfHeading(P, token){
  2798. var c = P.cur;
  2799. var sizes = [23, 19, 16, 14, 12.5, 11.5], fs = sizes[(token.depth || 1) - 1] || 12;
  2800. c.y -= fs * 0.8;
  2801. return pdfFlow(P, inlineRuns(token.tokens || [{ type:"text", text:token.text }], { bold:true }), c.margin, fs, fs * 1.32, P.col.head)
  2802. .then(function(){
  2803. if ((token.depth || 1) <= 2){ c.y += 4; pdfEnsure(P, 6); pdfRule(P); c.y -= 8; }
  2804. c.y -= fs * 0.25;
  2805. });
  2806. }
  2807. function pdfParagraph(P, token){
  2808. var c = P.cur; c.y -= 3;
  2809. return pdfFlow(P, inlineRuns(token.tokens || [{ type:"text", text:token.text }], {}), c.margin, 11, 16.5, P.col.text)
  2810. .then(function(){ c.y -= 4; });
  2811. }
  2812. function pdfHr(P){ var c = P.cur; c.y -= 8; pdfEnsure(P, 8); pdfRule(P); c.y -= 10; }
  2813. function pdfList(P, token, depth){
  2814. var c = P.cur, indent = c.margin + depth * 18, idx = token.start || 1;
  2815. var chain = Promise.resolve();
  2816. token.items.forEach(function(item){
  2817. var n = idx++;
  2818. chain = chain.then(function(){
  2819. pdfEnsure(P, 11 * 1.5);
  2820. if (item.task){
  2821. c.page.drawRectangle({ x:indent, y:c.y - 10, width:9, height:9, borderWidth:0.9, borderColor:P.col.muted, color: item.checked ? P.col.accent : undefined });
  2822. } else if (token.ordered){
  2823. try { c.page.drawText(n + ".", { x:indent, y:c.y - 11*0.80, size:11, font:P.fonts.reg, color:P.col.text }); } catch(e){}
  2824. } else {
  2825. c.page.drawCircle({ x:indent + 3, y:c.y - 7, size:1.7, color:P.col.text });
  2826. }
  2827. return pdfListItem(P, item, indent + 16, depth);
  2828. });
  2829. });
  2830. return chain.then(function(){ c.y -= 3; });
  2831. }
  2832. function pdfListItem(P, item, startX, depth){
  2833. var toks = item.tokens || [];
  2834. if (toks.length === 0) return pdfFlow(P, inlineRuns([{ type:"text", text:item.text || "" }], {}), startX, 11, 16.5, P.col.text);
  2835. var chain = Promise.resolve();
  2836. toks.forEach(function(t){
  2837. chain = chain.then(function(){
  2838. if (t.type === "list") return pdfList(P, t, depth + 1);
  2839. if (t.type === "code") return pdfCode(P, t, startX);
  2840. if (t.type === "blockquote") return pdfBlockquote(P, t);
  2841. var rr = inlineRuns(t.tokens || [{ type:"text", text:t.text || "" }], {});
  2842. return pdfFlow(P, rr, startX, 11, 16.5, P.col.text);
  2843. });
  2844. });
  2845. return chain;
  2846. }
  2847. function pdfBlockquote(P, token){
  2848. var c = P.cur; c.y -= 3;
  2849. var startY = c.y, startPage = c.page, x = c.margin + 16;
  2850. var chain = Promise.resolve();
  2851. (token.tokens || []).forEach(function(t){
  2852. chain = chain.then(function(){
  2853. if (t.type === "list") return pdfList(P, t, 1);
  2854. if (t.type === "code") return pdfCode(P, t, x);
  2855. var rr = inlineRuns(t.tokens || [{ type:"text", text:t.text || "" }], {});
  2856. return pdfFlow(P, rr, x, 11, 16.5, P.col.muted);
  2857. });
  2858. });
  2859. return chain.then(function(){
  2860. if (c.page === startPage) c.page.drawRectangle({ x:c.margin + 4, y:c.y + 6, width:2.5, height:Math.max(2, startY - c.y), color:P.col.quote });
  2861. c.y -= 4;
  2862. });
  2863. }
  2864. function pdfCode(P, token, startX){
  2865. var c = P.cur; startX = startX || c.margin;
  2866. var size = 9.5, lh = 12.5, pad = 8, font = P.fonts.mono;
  2867. var charW = font.widthOfTextAtSize("m", size);
  2868. var maxChars = Math.max(8, Math.floor((c.pageW - c.margin - startX - 2 * pad) / charW));
  2869. var lines = [];
  2870. (token.text || "").replace(/\n$/, "").split("\n").forEach(function(ln){
  2871. if (ln.length <= maxChars) lines.push(ln);
  2872. else for (var i = 0; i < ln.length; i += maxChars) lines.push(ln.substr(i, maxChars));
  2873. });
  2874. if (lines.length === 0) lines = [""];
  2875. c.y -= 4;
  2876. var chain = Promise.resolve();
  2877. lines.forEach(function(txt){
  2878. chain = chain.then(function(){
  2879. pdfEnsure(P, lh);
  2880. c.page.drawRectangle({ x:startX, y:c.y - lh + 2, width:c.pageW - c.margin - startX, height:lh, color:P.col.codebg });
  2881. try { c.page.drawText(txt, { x:startX + pad, y:c.y - lh + 3.5, size:size, font:font, color:P.col.code }); return; }
  2882. catch (e){ return pdfDrawRasterWord(P, txt, size, startX + pad, P.col.code).then(function(){}); }
  2883. }).then(function(){ c.y -= lh; });
  2884. });
  2885. return chain.then(function(){ c.y -= 6; });
  2886. }
  2887. function pdfTable(P, token){
  2888. var c = P.cur; c.y -= 4;
  2889. var cols = (token.header && token.header.length) || 1;
  2890. var colW = (c.pageW - 2 * c.margin) / cols, size = 10, pad = 5, rowH = 18;
  2891. function fit(font, txt, maxW){
  2892. try { if (font.widthOfTextAtSize(txt, size) <= maxW) return txt; } catch (e){ return txt; }
  2893. var s = txt;
  2894. while (s.length > 1){ s = s.slice(0, -1); try { if (font.widthOfTextAtSize(s + "…", size) <= maxW) return s + "…"; } catch (e){ break; } }
  2895. return s;
  2896. }
  2897. function row(cells, header){
  2898. pdfEnsure(P, rowH);
  2899. var x = c.margin;
  2900. for (var i = 0; i < cols; i++){
  2901. var cell = cells[i] || { text:"" };
  2902. if (header) c.page.drawRectangle({ x:x, y:c.y - rowH, width:colW, height:rowH, color:P.col.thead });
  2903. c.page.drawRectangle({ x:x, y:c.y - rowH, width:colW, height:rowH, borderWidth:0.6, borderColor:P.col.tline });
  2904. var f = header ? P.fonts.bold : P.fonts.reg;
  2905. var txt = fit(f, decodeEntities(cell.text || ""), colW - 2 * pad);
  2906. try { c.page.drawText(txt, { x:x + pad, y:c.y - rowH + 6, size:size, font:f, color:P.col.text }); } catch (e){}
  2907. x += colW;
  2908. }
  2909. c.y -= rowH;
  2910. }
  2911. row(token.header, true);
  2912. (token.rows || []).forEach(function(r){ row(r, false); });
  2913. c.y -= 6;
  2914. }
  2915. function pdfRenderTokens(P, tokens){
  2916. var chain = Promise.resolve();
  2917. tokens.forEach(function(t){
  2918. chain = chain.then(function(){
  2919. switch (t.type){
  2920. case "heading": return pdfHeading(P, t);
  2921. case "paragraph": return pdfParagraph(P, t);
  2922. case "list": return pdfList(P, t, 0);
  2923. case "blockquote": return pdfBlockquote(P, t);
  2924. case "code": return pdfCode(P, t, P.cur.margin);
  2925. case "hr": pdfHr(P); return;
  2926. case "table": return pdfTable(P, t);
  2927. case "space": P.cur.y -= 6; return;
  2928. case "html": return;
  2929. default: if (t.tokens) return pdfParagraph(P, t); if (t.text) return pdfParagraph(P, { text:t.text }); return;
  2930. }
  2931. });
  2932. });
  2933. return chain;
  2934. }
  2935. function pdfBuild(){
  2936. var L = PDFLib, SF = L.StandardFonts, pdf;
  2937. return L.PDFDocument.create().then(function(d){
  2938. pdf = d;
  2939. return Promise.all([
  2940. pdf.embedFont(SF.Helvetica), pdf.embedFont(SF.HelveticaBold),
  2941. pdf.embedFont(SF.HelveticaOblique), pdf.embedFont(SF.HelveticaBoldOblique),
  2942. pdf.embedFont(SF.Courier), pdf.embedFont(SF.CourierBold)
  2943. ]);
  2944. }).then(function(f){
  2945. var P = { pdf:pdf, col:PDF_COLORS(), fonts:{
  2946. reg:f[0], bold:f[1], ital:f[2], bi:f[3], mono:f[4], monoBold:f[5]
  2947. }, cur:null };
  2948. P.cur = pdfNewCursor(P);
  2949. if (isTxtMode){
  2950. var chain = Promise.resolve();
  2951. plain.value.split("\n").forEach(function(ln){
  2952. chain = chain.then(function(){ return pdfFlow(P, [mkRun(ln || " ", { mono:true })], P.cur.margin, 10, 13.5, P.col.text); });
  2953. });
  2954. return chain.then(function(){ return pdf.save(); });
  2955. }
  2956. return pdfRenderTokens(P, marked.lexer(isRtfMode ? richMarkdown() : getContent())).then(function(){ return pdf.save(); });
  2957. });
  2958. }
  2959. // ════════════════════════════════════════════════════════════════════════
  2960. // Settings panel
  2961. // ════════════════════════════════════════════════════════════════════════
  2962. function openSettings(){ syncSettingsUI(); $("#settings-overlay").addClass("show"); }
  2963. function closeSettings(){ $("#settings-overlay").removeClass("show"); }
  2964. $(function(){
  2965. $("#settings-overlay").on("click", function(e){ if (e.target === this) closeSettings(); });
  2966. $("#link-overlay").on("click", function(e){ if (e.target === this) linkDlgCancel(); });
  2967. });
  2968. function showSection(sec){
  2969. $(".nav-item").removeClass("active");
  2970. $('.nav-item[data-sec="'+sec+'"]').addClass("active");
  2971. $(".settings-section").removeClass("active");
  2972. $("#sec-" + sec).addClass("active");
  2973. }
  2974. function syncSettingsUI(){
  2975. $("#set-dark").prop("checked", isDark);
  2976. $("#set-font").val(settings.font);
  2977. $("#set-fontsize").val(settings.fontSize);
  2978. $("#set-lh").val(settings.lineHeight);
  2979. $("#set-syntax").val(settings.syntax);
  2980. $("#set-imgdir").val(settings.imgDir);
  2981. $("#set-compress").prop("checked", settings.compress);
  2982. $("#set-quality").val(settings.quality);
  2983. $("#quality-val").text(settings.quality + "%");
  2984. $("#set-maxw").val(settings.maxWidth);
  2985. $("#seg-mode button").removeClass("active");
  2986. $('#seg-mode button[data-mode="'+modeName()+'"]').addClass("active");
  2987. onCompressToggle(true);
  2988. }
  2989. function applyTypography(){
  2990. settings.font = $("#set-font").val() || settings.font;
  2991. settings.fontSize = parseInt($("#set-fontsize").val()) || settings.fontSize;
  2992. settings.lineHeight = $("#set-lh").val() || settings.lineHeight;
  2993. var fam = FONT_MAP[settings.font] || FONT_MAP.system;
  2994. [rich, plain].forEach(function(el){
  2995. el.style.fontFamily = (el === plain ? FONT_MAP.mono : fam);
  2996. el.style.fontSize = (el === plain ? (settings.fontSize - 1) : settings.fontSize) + "px";
  2997. el.style.lineHeight = settings.lineHeight;
  2998. });
  2999. savePrefs();
  3000. }
  3001. function saveImgPrefs(){
  3002. settings.imgDir = $("#set-imgdir").val().trim() || "img/{name}";
  3003. settings.quality = parseInt($("#set-quality").val()) || 80;
  3004. settings.maxWidth = parseInt($("#set-maxw").val()); if (isNaN(settings.maxWidth)) settings.maxWidth = 0;
  3005. settings.compress = $("#set-compress").prop("checked");
  3006. savePrefs();
  3007. }
  3008. function onCompressToggle(silent){
  3009. settings.compress = $("#set-compress").prop("checked");
  3010. var on = settings.compress;
  3011. $("#row-quality").css("display", on ? "" : "none");
  3012. $("#row-maxw").css("display", on ? "" : "none");
  3013. if (!silent) saveImgPrefs();
  3014. }
  3015. function onQualityInput(){
  3016. $("#quality-val").text($("#set-quality").val() + "%");
  3017. }
  3018. // ════════════════════════════════════════════════════════════════════════
  3019. // Theme
  3020. // ════════════════════════════════════════════════════════════════════════
  3021. function setTheme(dark){
  3022. isDark = dark;
  3023. document.body.classList.toggle("dark", isDark);
  3024. $("#icon-sun").toggle(!isDark); $("#icon-moon").toggle(isDark);
  3025. $("#set-dark").prop("checked", isDark);
  3026. try { ao_module_setWindowTheme(isDark ? "dark" : "light"); } catch(e){}
  3027. savePrefs();
  3028. }
  3029. function toggleTheme(){ setTheme(!isDark); }
  3030. // ════════════════════════════════════════════════════════════════════════
  3031. // Preferences persistence (localStorage + ao_module_storage)
  3032. // ════════════════════════════════════════════════════════════════════════
  3033. function prefsObject(){
  3034. return { settings: settings, keymap: keymap, isDark: isDark };
  3035. }
  3036. function savePrefs(){
  3037. var json = JSON.stringify(prefsObject());
  3038. try { localStorage.setItem("text_prefs", json); } catch(e){}
  3039. try { ao_module_storage.setStorage("Text", "prefs", json); } catch(e){}
  3040. }
  3041. function applyPrefs(obj){
  3042. if (!obj) return;
  3043. if (obj.settings) for (var k in obj.settings) settings[k] = obj.settings[k];
  3044. if (obj.keymap){
  3045. keymap = JSON.parse(JSON.stringify(DEFAULT_KEYS));
  3046. for (var a in obj.keymap) if (a in keymap) keymap[a] = obj.keymap[a];
  3047. }
  3048. if (typeof obj.isDark === "boolean") setTheme(obj.isDark);
  3049. }
  3050. function loadPrefs(){
  3051. var local = null;
  3052. try { local = JSON.parse(localStorage.getItem("text_prefs")); } catch(e){}
  3053. if (local) applyPrefs(local);
  3054. // async server copy (per-user) overrides local if present
  3055. try {
  3056. ao_module_storage.loadStorage("Text", "prefs", function(val){
  3057. if (val && typeof val === "string" && val.charAt(0) === "{"){
  3058. try {
  3059. var obj = JSON.parse(val);
  3060. applyPrefs(obj);
  3061. buildKeyList(); syncSettingsUI(); applyTypography();
  3062. } catch(e){}
  3063. }
  3064. });
  3065. } catch(e){}
  3066. }
  3067. // ════════════════════════════════════════════════════════════════════════
  3068. // Status bar, title, dirty tracking
  3069. // ════════════════════════════════════════════════════════════════════════
  3070. function markDirty(){ if (!dirtyFlag){ dirtyFlag = true; updateTitle(); } }
  3071. function isDirty(){ return dirtyFlag; }
  3072. function updateTitle(){
  3073. var title = !filepath ? "Untitled" : (isDirty() ? filename + " — Edited" : filename);
  3074. try { ao_module_setWindowTitle(title); } catch(e){}
  3075. document.title = title;
  3076. if (isDirty()) setStatus("Unsaved changes", "dirty");
  3077. else if (filepath) setStatus("Saved");
  3078. else setStatus("Ready");
  3079. }
  3080. function setStatus(msg, cls){
  3081. var el = $("#status-msg");
  3082. el.text(msg).attr("class", cls || "");
  3083. if (cls === "error") setTimeout(updateTitle, 3500);
  3084. }
  3085. function updateStatBar(){
  3086. var txt = isTxtMode ? plain.value : richPlainText();
  3087. var words = txt.trim() ? txt.trim().split(/\s+/).length : 0;
  3088. var chars = txt.length;
  3089. $("#stat-count").text(words + " word" + (words !== 1 ? "s" : "") + " · " + chars + " chars");
  3090. }
  3091. // ════════════════════════════════════════════════════════════════════════
  3092. // Menus / busy / dialog
  3093. // ════════════════════════════════════════════════════════════════════════
  3094. function toggleMenu(id){
  3095. var m = document.getElementById(id);
  3096. var show = !m.classList.contains("show");
  3097. hideMenus();
  3098. if (show){ m.classList.add("show"); positionMenu(m); }
  3099. }
  3100. // position a fixed dropdown just below its trigger, right-aligned, so it is not
  3101. // clipped by the toolbar's horizontal-scroll overflow
  3102. function positionMenu(m){
  3103. var btn = m.parentElement.querySelector(".tb-btn");
  3104. if (!btn) return;
  3105. var r = btn.getBoundingClientRect();
  3106. m.style.top = (r.bottom + 4) + "px";
  3107. m.style.left = "auto";
  3108. m.style.right = Math.max(6, window.innerWidth - r.right) + "px";
  3109. }
  3110. function hideMenus(){ $(".menu").removeClass("show"); }
  3111. function showBusy(msg){ $("#busy-msg").text(msg || "Working…"); $("#busy").addClass("show"); }
  3112. function hideBusy(){ $("#busy").removeClass("show"); }
  3113. // ── helpers ─────────────────────────────────────────────────────────────
  3114. function escapeHtml(s){ return String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
  3115. function escapeAttr(s){ return escapeHtml(s).replace(/"/g,"&quot;"); }
  3116. function debounce(fn, ms){ var t; return function(){ clearTimeout(t); var a=arguments,c=this; t=setTimeout(function(){ fn.apply(c,a); }, ms); }; }
  3117. // ════════════════════════════════════════════════════════════════════════
  3118. // Close handling (unsaved changes)
  3119. // ════════════════════════════════════════════════════════════════════════
  3120. function showDialog(cb){ dlgCallback = cb; $("#confirm-overlay").addClass("show"); }
  3121. function hideDialog(){ $("#confirm-overlay").removeClass("show"); }
  3122. function dlgCancel(){ var cb=dlgCallback; hideDialog(); dlgCallback=null; if(cb) cb("cancel"); }
  3123. function dlgDiscard(){ var cb=dlgCallback; hideDialog(); dlgCallback=null; if(cb) cb("discard"); }
  3124. function dlgSave(){
  3125. pendingClose = dlgCallback; dlgCallback = null; hideDialog();
  3126. if (!filepath){
  3127. var def = defaultNewName();
  3128. ao_module_openFileSelector(handleDlgSaveAs, "user:/Desktop", "new", false, { defaultName: def });
  3129. } else {
  3130. doSave(function(){ if (pendingClose){ pendingClose("saved"); pendingClose=null; } });
  3131. }
  3132. }
  3133. function handleDlgSaveAs(fd){
  3134. if (!fd || !fd.length){ pendingClose = null; return; }
  3135. filepath = fd[0].filepath; filename = fd[0].filename;
  3136. doSave(function(){ if (pendingClose){ pendingClose("saved"); pendingClose=null; } });
  3137. }
  3138. function ao_module_close(){
  3139. if (!isDirty()){ ao_module_closeHandler(); return; }
  3140. showDialog(function(result){
  3141. if (result === "saved" || result === "discard") ao_module_closeHandler();
  3142. });
  3143. }
  3144. if (!ao_module_virtualDesktop){
  3145. window.onbeforeunload = function(){ if (isDirty()) return "You have unsaved changes. Leave anyway?"; };
  3146. }
  3147. </script>
  3148. </body>
  3149. </html>