| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
- <title>Text</title>
- <script src="../script/jquery.min.js"></script>
- <script src="../script/ao_module.js"></script>
- <script src="lib/marked.min.js"></script>
- <script src="lib/turndown.min.js"></script>
- <script src="lib/turndown-plugin-gfm.min.js"></script>
- <script src="lib/pdf-lib.min.js"></script>
- <script src="highlighter.js"></script>
- <script src="rtf.js"></script>
- <style>
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
- :root {
- --toolbar-h: 42px;
- --statusbar-h: 22px;
- --bg: #e4e9f2;
- --toolbar-bg: #f6f7fb;
- --toolbar-bdr: #e2e4ec;
- --editor-bg: #ffffff;
- --text: #2b2f38;
- --text2: #8a90a2;
- --accent: #2f6bd8;
- --accent-soft: rgba(47,107,216,.12);
- --sep: #d7dbe6;
- --hover: rgba(0,0,0,.06);
- --btn-active-bg:#2f6bd8;
- --btn-active-fg:#fff;
- --dirty-color: #2f6bd8;
- --code-bg: #f1f3f8;
- --quote-bdr: #d2d8e6;
- --table-bdr: #dfe3ec;
- --shadow: 0 10px 40px rgba(30,40,70,.18);
- --hl-com: #6a9955;
- --hl-str: #b5402a;
- --hl-num: #1c7d4d;
- --hl-kw: #1f4fce;
- --hl-typ: #117a8b;
- --hl-fn: #8a5a18;
- }
- body.dark {
- --bg: #0f131b;
- --toolbar-bg: #161c27;
- --toolbar-bdr: #232c3b;
- --editor-bg: #121722;
- --text: #d6def0;
- --text2: #6b7793;
- --accent: #5b9cf6;
- --accent-soft: rgba(91,156,246,.16);
- --sep: #2a3445;
- --hover: rgba(255,255,255,.07);
- --btn-active-bg:#5b9cf6;
- --btn-active-fg:#0f131b;
- --dirty-color: #5b9cf6;
- --code-bg: #1b2230;
- --quote-bdr: #313c50;
- --table-bdr: #2a3445;
- --shadow: 0 10px 40px rgba(0,0,0,.55);
- --hl-com: #6a9955;
- --hl-str: #ce9178;
- --hl-num: #b5cea8;
- --hl-kw: #569cd6;
- --hl-typ: #4ec9b0;
- --hl-fn: #dcdcaa;
- }
- html, body {
- height: 100%;
- background: var(--bg);
- color: var(--text);
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- font-size: 13px;
- }
- #app { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
- /* ── Toolbar ──────────────────────────────────────────────────────── */
- #toolbar {
- display: flex; align-items: center; gap: 1px; flex-shrink: 0;
- height: var(--toolbar-h); padding: 0 8px;
- background: var(--toolbar-bg);
- border-bottom: 1px solid var(--toolbar-bdr);
- box-shadow: 0 1px 4px rgba(0,0,0,.06);
- overflow-x: auto; overflow-y: hidden; position: relative; z-index: 5;
- scrollbar-width: thin;
- }
- #toolbar::-webkit-scrollbar { height: 4px; }
- #toolbar::-webkit-scrollbar-thumb { background: var(--sep); border-radius: 3px; }
- .tb-btn {
- display: inline-flex; align-items: center; gap: 4px; height: 28px;
- padding: 0 8px; border: none; border-radius: 6px; background: none;
- color: var(--text); font-size: 12px; font-family: inherit; cursor: pointer;
- white-space: nowrap; flex-shrink: 0; transition: background .1s; user-select: none;
- }
- .tb-btn:hover { background: var(--hover); }
- .tb-btn.active { background: var(--btn-active-bg); color: var(--btn-active-fg); }
- .tb-btn svg { display: block; }
- .tb-btn .glyph { width: 15px; text-align: center; font-size: 13px; line-height: 1; }
- .tb-sep { width: 1px; height: 20px; background: var(--sep); flex-shrink: 0; margin: 0 4px; }
- .tb-spacer { flex: 1 1 auto; min-width: 6px; }
- .tb-label { font-size: 11px; color: var(--text2); flex-shrink: 0; white-space: nowrap; }
- .tb-select {
- height: 26px; padding: 0 6px; border: 1px solid var(--toolbar-bdr);
- border-radius: 6px; background: var(--editor-bg); color: var(--text);
- font-size: 12px; font-family: inherit; outline: none; cursor: pointer;
- flex-shrink: 0; transition: border-color .1s;
- }
- .tb-select:focus { border-color: var(--accent); }
- /* dropdown menu (export / image) */
- .menu-wrap { position: relative; flex-shrink: 0; }
- .menu {
- display: none; position: fixed; min-width: 180px;
- background: var(--editor-bg); border: 1px solid var(--toolbar-bdr);
- border-radius: 10px; box-shadow: var(--shadow); padding: 6px; z-index: 120;
- }
- .menu.show { display: block; }
- .menu-item {
- display: flex; align-items: center; gap: 9px; width: 100%; padding: 8px 10px;
- border: none; background: none; color: var(--text); font-size: 12.5px;
- font-family: inherit; border-radius: 7px; cursor: pointer; text-align: left;
- }
- .menu-item:hover { background: var(--accent-soft); }
- .menu-item svg { flex-shrink: 0; color: var(--text2); }
- /* hide markdown-only controls when editing plain text */
- body.mode-txt .md-only { display: none !important; }
- /* rich-text (RTF) mode: its own formatting controls, minus markdown-only ones */
- body.mode-rtf .no-rtf { display: none !important; }
- body:not(.mode-rtf) .rtf-only { display: none !important; }
- /* colour swatch dropdowns (RTF text colour / highlight) */
- .swatch-menu { min-width: 0; width: 176px; }
- .swatch-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 5px; padding: 4px 2px 2px; }
- .swatch {
- width: 22px; height: 22px; border-radius: 5px; cursor: pointer; padding: 0;
- border: 1px solid rgba(0,0,0,.18);
- }
- .swatch:hover { transform: scale(1.12); }
- .glyph-color { display: inline-flex; flex-direction: column; align-items: center; width: 15px; line-height: 1; }
- .glyph-color b { font-size: 13px; }
- .glyph-color i { display: block; width: 14px; height: 3px; border-radius: 1px; margin-top: 1px; }
- /* ── Editor surfaces ──────────────────────────────────────────────── */
- #editor-scroll {
- flex: 1; min-height: 0; overflow-y: auto; background: var(--editor-bg);
- transition: background .2s, color .2s; position: relative;
- }
- #rich, #plain {
- max-width: 820px; margin: 0 auto; min-height: 100%;
- padding: 40px clamp(18px, 6vw, 60px) 120px;
- outline: none; color: var(--text); line-height: 1.7;
- font-size: 16px; word-wrap: break-word;
- }
- #plain {
- display: none; width: 100%; border: none; resize: none; background: none;
- font-family: 'SF Mono', 'Consolas', 'Courier New', monospace;
- font-size: 14px; white-space: pre-wrap; tab-size: 4; -moz-tab-size: 4;
- }
- body.mode-txt #rich { display: none; }
- body.mode-txt #plain { display: block; }
- /* RTF keeps spaces and tabs significant */
- body.mode-rtf #rich p, body.mode-rtf #rich li, body.mode-rtf #rich td, body.mode-rtf #rich th,
- body.mode-rtf #rich h1, body.mode-rtf #rich h2, body.mode-rtf #rich h3,
- body.mode-rtf #rich h4, body.mode-rtf #rich h5, body.mode-rtf #rich h6 { white-space: pre-wrap; tab-size: 4; }
- /* keep highlighted runs readable on the dark theme */
- body.dark.mode-rtf #rich [style*="background-color"] { color: #1d2230; }
- #rich:empty::before, #rich.is-empty::before {
- content: attr(data-ph); color: var(--text2); pointer-events: none;
- }
- /* ── Markdown content typography (shared by editor + export) ──────── */
- .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;
- }
- .md-content h1 { font-size: 2em; border-bottom: 1px solid var(--sep); padding-bottom: .25em; }
- .md-content h2 { font-size: 1.6em; border-bottom: 1px solid var(--sep); padding-bottom: .2em; }
- .md-content h3 { font-size: 1.3em; }
- .md-content h4 { font-size: 1.1em; }
- .md-content h5 { font-size: 1em; }
- .md-content h6 { font-size: .9em; color: var(--text2); }
- .md-content p { margin: .55em 0; }
- .md-content a { color: var(--accent); text-decoration: none; }
- .md-content a:hover { text-decoration: underline; }
- .md-content ul, .md-content ol { margin: .5em 0; padding-left: 1.7em; }
- .md-content li { margin: .25em 0; }
- .md-content blockquote {
- margin: .8em 0; padding: .2em 1em; color: var(--text2);
- border-left: 3px solid var(--quote-bdr); background: var(--accent-soft);
- border-radius: 0 6px 6px 0;
- }
- .md-content code {
- font-family: 'SF Mono', 'Consolas', 'Courier New', monospace; font-size: .88em;
- background: var(--code-bg); padding: .15em .4em; border-radius: 4px;
- }
- .md-content pre {
- margin: .8em 0; padding: 14px 16px; background: var(--code-bg);
- border-radius: 8px; overflow-x: auto; position: relative;
- }
- .md-content pre code { background: none; padding: 0; font-size: .85em; line-height: 1.55; }
- /* syntax highlight tokens (see highlighter.js) — theme-aware via vars */
- .hl-com { color: var(--hl-com); font-style: italic; }
- .hl-str { color: var(--hl-str); }
- .hl-num { color: var(--hl-num); }
- .hl-kw { color: var(--hl-kw); }
- .hl-typ { color: var(--hl-typ); }
- .hl-fn { color: var(--hl-fn); }
- .md-content hr { border: none; border-top: 1px solid var(--sep); margin: 1.6em 0; }
- .md-content img { max-width: 100%; border-radius: 6px; vertical-align: middle; }
- .md-content table { border-collapse: collapse; margin: .8em 0; width: auto; max-width: 100%; }
- .md-content th, .md-content td { border: 1px solid var(--table-bdr); padding: 6px 12px; }
- .md-content th { background: var(--code-bg); font-weight: 600; }
- .md-content ul.contains-task-list { list-style: none; padding-left: 1.2em; }
- .md-content li.task-list-item { list-style: none; }
- .md-content input[type=checkbox] { margin-right: .5em; }
- /* ── Markdown source-mark hints (Typora-style reveal) ─────────────────
- Shown via pseudo-elements gated by the .md-active class, which is set
- on the active block (or every block, in "always" mode) by
- updateActiveBlock(). Because these are pseudo-elements they never enter
- the DOM model — serialization, word count and editing are untouched. */
- #rich h1.md-active::before { content: "# "; }
- #rich h2.md-active::before { content: "## "; }
- #rich h3.md-active::before { content: "### "; }
- #rich h4.md-active::before { content: "#### "; }
- #rich h5.md-active::before { content: "##### "; }
- #rich h6.md-active::before { content: "###### "; }
- #rich blockquote.md-active > *:first-child::before { content: "> "; }
- #rich .md-active strong::before, #rich .md-active strong::after,
- #rich .md-active b::before, #rich .md-active b::after { content: "**"; }
- #rich .md-active em::before, #rich .md-active em::after,
- #rich .md-active i::before, #rich .md-active i::after { content: "*"; }
- #rich .md-active del::before, #rich .md-active del::after,
- #rich .md-active s::before, #rich .md-active s::after,
- #rich .md-active strike::before, #rich .md-active strike::after { content: "~~"; }
- #rich .md-active code::before, #rich .md-active code::after { content: "`"; }
- #rich .md-active a::before { content: "["; }
- /* shared mark appearance: muted + semi-transparent so it reads as a hint
- and never as content; not selectable since it's a pseudo-element. */
- #rich .md-active::before, #rich .md-active::after,
- #rich .md-active *::before, #rich .md-active *::after {
- color: var(--text2); opacity: .42; font-weight: 400; font-style: normal;
- }
- /* <img> is a replaced element and can't host pseudo-content, so its
-  mark is a real, editable label inserted above the image by
- updateActiveBlock(). Editing it re-points the image (see syncImgFromSyn);
- it is stripped from the document on serialize. */
- #rich .md-imgsyn {
- display: block; width: fit-content; max-width: 100%;
- font-family: 'SF Mono','Consolas','Courier New',monospace;
- font-size: .78em; color: var(--text2); opacity: .62;
- margin-bottom: 5px; padding: 1px 4px; line-height: 1.4;
- word-break: break-all; outline: none; cursor: text; border-radius: 4px;
- }
- #rich .md-imgsyn:hover { opacity: .85; }
- #rich .md-imgsyn:focus {
- opacity: 1; color: var(--text); background: var(--code-bg);
- box-shadow: inset 0 0 0 1px var(--accent);
- }
- /* <a>'s closing "](url)" mark — unlike the rest of the bracket hints
- this needs to be real, editable text (not a pseudo-element) so the
- URL itself is directly clickable/editable, same idea as md-imgsyn
- but inline since a link sits inside a run of prose. */
- #rich .md-linksyn {
- font-family: 'SF Mono','Consolas','Courier New',monospace;
- font-size: .85em; color: var(--text2); opacity: .55;
- outline: none; cursor: text; border-radius: 3px; padding: 0 1px;
- }
- #rich .md-linksyn:hover { opacity: .8; }
- #rich .md-linksyn:focus {
- opacity: 1; color: var(--text); background: var(--code-bg);
- box-shadow: inset 0 0 0 1px var(--accent);
- }
- /* code-block language picker — a real, interactive <select> pinned to
- the block's top-right corner while the caret is inside it (see
- syncLangSelector); a contenteditable="false" island appended after
- <code> so it never disturbs the caret and is invisible to turndown
- (which only reads pre's firstChild). Stripped on serialize. */
- #rich .md-langsel { position: absolute; top: 6px; right: 6px; z-index: 2; }
- #rich .md-langsel-select {
- height: 22px; padding: 0 4px; border: 1px solid var(--toolbar-bdr);
- border-radius: 5px; background: var(--editor-bg); color: var(--text2);
- font-size: 11px; font-family: inherit; outline: none; cursor: pointer;
- opacity: .55; transition: opacity .15s;
- }
- #rich .md-langsel-select:hover, #rich .md-langsel-select:focus {
- opacity: 1; color: var(--text); border-color: var(--accent);
- }
- /* ── Status bar ───────────────────────────────────────────────────── */
- #statusbar {
- flex-shrink: 0; height: var(--statusbar-h); display: flex; align-items: center;
- justify-content: space-between; padding: 0 12px; background: var(--toolbar-bg);
- border-top: 1px solid var(--toolbar-bdr); font-size: 10.5px; color: var(--text2);
- }
- #status-msg.dirty { color: var(--dirty-color); }
- #status-msg.error { color: #d9534f; }
- #status-right { display: flex; gap: 12px; align-items: center; }
- /* ── Settings panel ───────────────────────────────────────────────── */
- .overlay {
- display: none; position: fixed; inset: 0; background: rgba(10,15,25,.45);
- backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px);
- z-index: 200; align-items: center; justify-content: center; padding: 20px;
- }
- .overlay.show { display: flex; }
- #settings-box {
- background: var(--editor-bg); border: 1px solid var(--toolbar-bdr);
- border-radius: 14px; box-shadow: var(--shadow); width: 760px; max-width: 100%;
- height: 520px; max-height: 90vh; display: flex; overflow: hidden;
- }
- #settings-nav {
- width: 180px; flex-shrink: 0; background: var(--toolbar-bg);
- border-right: 1px solid var(--toolbar-bdr); padding: 14px 10px; overflow-y: auto;
- }
- #settings-nav .nav-title { font-size: 13px; font-weight: 700; padding: 4px 10px 12px; }
- .nav-item {
- display: flex; align-items: center; gap: 9px; width: 100%; padding: 9px 10px;
- border: none; background: none; color: var(--text); font-size: 13px;
- font-family: inherit; border-radius: 8px; cursor: pointer; text-align: left; margin-bottom: 2px;
- }
- .nav-item:hover { background: var(--hover); }
- .nav-item.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
- .nav-item svg { flex-shrink: 0; }
- #settings-body { flex: 1; padding: 22px 26px; overflow-y: auto; }
- .settings-section { display: none; }
- .settings-section.active { display: block; }
- .settings-section h2 { font-size: 16px; font-weight: 700; margin-bottom: 4px; }
- .settings-section .sub { font-size: 12px; color: var(--text2); margin-bottom: 18px; }
- .set-row {
- display: flex; align-items: center; justify-content: space-between;
- gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--toolbar-bdr);
- }
- .set-row:last-child { border-bottom: none; }
- .set-label { font-size: 13px; font-weight: 600; }
- .set-desc { font-size: 11.5px; color: var(--text2); margin-top: 2px; }
- .set-ctl { flex-shrink: 0; }
- .set-input, .set-select {
- height: 30px; padding: 0 8px; border: 1px solid var(--toolbar-bdr);
- border-radius: 7px; background: var(--editor-bg); color: var(--text);
- font-size: 12.5px; font-family: inherit; outline: none;
- }
- .set-input:focus, .set-select:focus { border-color: var(--accent); }
- .set-input.num { width: 76px; }
- /* toggle switch */
- .switch { position: relative; display: inline-block; width: 42px; height: 24px; flex-shrink: 0; }
- .switch input { opacity: 0; width: 0; height: 0; }
- .slider {
- position: absolute; cursor: pointer; inset: 0; background: var(--sep);
- border-radius: 24px; transition: .2s;
- }
- .slider::before {
- content: ""; position: absolute; height: 18px; width: 18px; left: 3px; bottom: 3px;
- background: #fff; border-radius: 50%; transition: .2s; box-shadow: 0 1px 3px rgba(0,0,0,.3);
- }
- .switch input:checked + .slider { background: var(--accent); }
- .switch input:checked + .slider::before { transform: translateX(18px); }
- /* segmented control (mode) */
- .seg { display: inline-flex; border: 1px solid var(--toolbar-bdr); border-radius: 8px; overflow: hidden; }
- .seg button {
- border: none; background: var(--editor-bg); color: var(--text); font-family: inherit;
- font-size: 12.5px; padding: 7px 14px; cursor: pointer;
- }
- .seg button.active { background: var(--accent); color: #fff; }
- /* shortcuts list */
- .key-row {
- display: flex; align-items: center; justify-content: space-between;
- padding: 9px 0; border-bottom: 1px solid var(--toolbar-bdr);
- }
- .key-row .key-name { font-size: 13px; }
- .key-cap {
- min-width: 120px; text-align: center; padding: 6px 10px; border-radius: 7px;
- border: 1px solid var(--toolbar-bdr); background: var(--code-bg); color: var(--text);
- font-size: 12px; font-family: 'SF Mono','Consolas',monospace; cursor: pointer;
- }
- .key-cap:hover { border-color: var(--accent); }
- .key-cap.recording { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
- .range-wrap { display: flex; align-items: center; gap: 10px; }
- input[type=range] { accent-color: var(--accent); }
- .btn-text {
- border: 1px solid var(--toolbar-bdr); background: var(--editor-bg); color: var(--text);
- font-family: inherit; font-size: 12.5px; padding: 7px 14px; border-radius: 8px; cursor: pointer;
- }
- .btn-text:hover { background: var(--hover); }
- .btn-text.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
- #settings-foot {
- display: flex; justify-content: flex-end; gap: 8px; padding-top: 16px; margin-top: 8px;
- }
- /* ── Confirm dialog ───────────────────────────────────────────────── */
- #confirm-box {
- background: var(--editor-bg); border: 1px solid var(--toolbar-bdr);
- border-radius: 13px; padding: 24px 24px 18px; width: 320px; box-shadow: var(--shadow);
- }
- #confirm-box h3 { font-size: 15px; font-weight: 700; margin-bottom: 8px; }
- #confirm-box p { font-size: 12.5px; color: var(--text2); line-height: 1.55; margin-bottom: 18px; }
- .confirm-row { display: flex; gap: 8px; justify-content: flex-end; }
- .cbtn {
- padding: 7px 14px; border-radius: 7px; font-size: 12.5px; font-weight: 600;
- font-family: inherit; cursor: pointer; border: none; transition: opacity .1s;
- }
- .cbtn:hover { opacity: .88; }
- .cbtn-cancel { background: var(--hover); color: var(--text); border: 1px solid var(--toolbar-bdr); }
- .cbtn-discard { background: rgba(217,83,79,.14); color: #d9534f; border: 1px solid rgba(217,83,79,.32); }
- .cbtn-save { background: var(--accent); color: #fff; }
- /* ── Link editor dialog ───────────────────────────────────────────── */
- #link-box {
- background: var(--editor-bg); border: 1px solid var(--toolbar-bdr);
- border-radius: 13px; padding: 24px 24px 18px; width: 340px; box-shadow: var(--shadow);
- }
- #link-box h3 { font-size: 15px; font-weight: 700; margin-bottom: 14px; }
- .link-field { margin-bottom: 12px; }
- .link-field label { display: block; font-size: 11.5px; color: var(--text2); margin-bottom: 5px; }
- .link-field input {
- width: 100%; box-sizing: border-box; padding: 8px 10px; border-radius: 7px;
- border: 1px solid var(--toolbar-bdr); background: var(--code-bg); color: var(--text);
- font-family: inherit; font-size: 13px; outline: none;
- }
- .link-field input:focus { border-color: var(--accent); }
- .link-row { display: flex; gap: 8px; justify-content: flex-end; }
- .link-row .cbtn-discard { margin-right: auto; }
- /* busy spinner for export */
- #busy {
- display: none; position: fixed; inset: 0; z-index: 400; align-items: center;
- justify-content: center; background: rgba(10,15,25,.4); color: #fff; font-size: 13px;
- flex-direction: column; gap: 14px;
- }
- #busy.show { display: flex; }
- .spin {
- width: 34px; height: 34px; border: 3px solid rgba(255,255,255,.25);
- border-top-color: #fff; border-radius: 50%; animation: spin .8s linear infinite;
- }
- @keyframes spin { to { transform: rotate(360deg); } }
- /* ── Responsive ───────────────────────────────────────────────────── */
- @media (max-width: 680px) {
- .tb-label, .tb-btn .tb-text { display: none; }
- #toolbar {
- height: auto;
- padding: 6px;
- gap: 4px;
- flex-wrap: wrap;
- align-content: flex-start;
- justify-content: flex-start;
- overflow-x: hidden;
- overflow-y: auto;
- }
- .tb-btn {
- min-width: 34px;
- min-height: 34px;
- padding: 0 9px;
- }
- .tb-select {
- height: 34px;
- max-width: 100%;
- }
- .tb-sep, .tb-spacer { display: none; }
- .menu-wrap { display: inline-flex; }
- #settings-box { flex-direction: column; height: 92vh; }
- #settings-nav {
- width: 100%; display: flex; gap: 4px; overflow-x: auto; padding: 8px;
- border-right: none; border-bottom: 1px solid var(--toolbar-bdr);
- }
- #settings-nav .nav-title { display: none; }
- .nav-item { width: auto; white-space: nowrap; margin-bottom: 0; }
- #rich, #plain { padding: 24px 16px 100px; font-size: 15px; }
- .set-row { flex-direction: column; align-items: stretch; }
- .set-ctl { align-self: flex-start; }
- }
- @media (max-width: 480px) {
- /*#sel-head {
- flex: 1 1 100%;
- width: 100% !important;
- }*/
- }
- @media print {
- #toolbar, #statusbar, .overlay, #busy { display: none !important; }
- #editor-scroll { overflow: visible; }
- #rich, #plain { max-width: 100%; padding: 0; }
- }
- </style>
- </head>
- <body>
- <div id="app">
- <!-- ── Toolbar ──────────────────────────────────────────────────────── -->
- <div id="toolbar">
- <button class="tb-btn" onclick="openFile()" title="Open file">
- <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>
- <!-- <span class="tb-text">Open</span> -->
- </button>
- <button class="tb-btn" onclick="saveFile()" title="Save (Ctrl+S)">
- <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>
- <!-- <span class="tb-text">Save</span> -->
- </button>
- <div class="tb-sep md-only"></div>
- <!-- Heading / block format -->
- <select id="sel-head" class="tb-select md-only" style="width:104px;" onchange="onHeadingSelect()" title="Paragraph style">
- <option value="p">Paragraph</option>
- <option value="h1">Heading 1</option>
- <option value="h2">Heading 2</option>
- <option value="h3">Heading 3</option>
- <option value="h4">Heading 4</option>
- <option value="h5">Heading 5</option>
- <option value="h6">Heading 6</option>
- </select>
- <div class="tb-sep md-only"></div>
- <button class="tb-btn md-only" id="btn-bold" onclick="actBold()" title="Bold"><span class="glyph"><strong>B</strong></span></button>
- <button class="tb-btn md-only" id="btn-italic" onclick="actItalic()" title="Italic"><span class="glyph"><em>I</em></span></button>
- <button class="tb-btn md-only" id="btn-strike" onclick="actStrike()" title="Strikethrough"><span class="glyph"><s>S</s></span></button>
- <button class="tb-btn rtf-only" id="btn-underline" onclick="actUnderline()" title="Underline"><span class="glyph"><u>U</u></span></button>
- <button class="tb-btn md-only no-rtf" id="btn-code" onclick="actInlineCode()" title="Inline code"><span class="glyph" style="font-family:monospace;"><></span></button>
- <div class="menu-wrap rtf-only">
- <button class="tb-btn" onclick="toggleMenu('fore-menu')" title="Text colour">
- <span class="glyph-color"><b>A</b><i id="fore-bar" style="background:#c00000;"></i></span>
- </button>
- <div class="menu swatch-menu" id="fore-menu"></div>
- </div>
- <div class="menu-wrap rtf-only">
- <button class="tb-btn" onclick="toggleMenu('back-menu')" title="Highlight colour">
- <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>
- </button>
- <div class="menu swatch-menu" id="back-menu"></div>
- </div>
- <select id="sel-size" class="tb-select rtf-only" style="width:58px;" onchange="actFontSize()" title="Font size (pt)">
- <option value="">Size</option>
- <option>8</option><option>9</option><option>10</option><option>11</option><option>12</option>
- <option>14</option><option>16</option><option>18</option><option>20</option><option>24</option>
- <option>28</option><option>36</option><option>48</option><option>72</option>
- </select>
- <div class="tb-sep rtf-only"></div>
- <button class="tb-btn rtf-only" id="btn-align-left" onclick="actAlign('Left')" title="Align left">
- <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>
- </button>
- <button class="tb-btn rtf-only" id="btn-align-center" onclick="actAlign('Center')" title="Center">
- <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>
- </button>
- <button class="tb-btn rtf-only" id="btn-align-right" onclick="actAlign('Right')" title="Align right">
- <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>
- </button>
- <button class="tb-btn rtf-only" id="btn-align-full" onclick="actAlign('Full')" title="Justify">
- <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>
- </button>
- <div class="tb-sep md-only"></div>
- <button class="tb-btn md-only no-rtf" onclick="actQuote()" title="Blockquote">
- <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>
- </button>
- <button class="tb-btn md-only" onclick="actBullet()" title="Bullet list">
- <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>
- </button>
- <button class="tb-btn md-only" onclick="actNumber()" title="Numbered list">
- <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>
- </button>
- <button class="tb-btn md-only no-rtf" onclick="actCodeBlock()" title="Code block">
- <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>
- </button>
- <div class="tb-sep md-only"></div>
- <button class="tb-btn md-only" onclick="actLink()" title="Link">
- <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>
- </button>
- <div class="menu-wrap md-only">
- <button class="tb-btn" id="btn-image" onclick="toggleMenu('img-menu')" title="Insert image">
- <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>
- </button>
- <div class="menu" id="img-menu">
- <button class="menu-item" onclick="hideMenus();pickDeviceImage()">
- <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>
- From this device
- </button>
- <button class="menu-item" onclick="hideMenus();pickServerImage()">
- <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>
- From server
- </button>
- <!-- <button class="menu-item" onclick="hideMenus();insertImageByUrl()">
- <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>
- By URL
- </button> -->
- </div>
- </div>
- <div class="tb-spacer"></div>
- <button class="tb-btn" id="theme-btn" onclick="toggleTheme()" title="Toggle theme">
- <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>
- <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>
- </button>
- <div class="menu-wrap">
- <button class="tb-btn" onclick="toggleMenu('export-menu')" title="Export">
- <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>
- <span class="tb-text">Export</span>
- </button>
- <div class="menu" id="export-menu">
- <button class="menu-item" onclick="hideMenus();savePDFToArozOS()">
- <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>
- Save as PDF…
- </button>
- <button class="menu-item" id="mi-download" onclick="hideMenus();exportDocument()">
- <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>
- <span id="mi-download-lbl">Download document</span>
- </button>
- <button class="menu-item" onclick="hideMenus();exportHTML()">
- <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>
- Export as HTML
- </button>
- <button class="menu-item" onclick="hideMenus();exportPDF()">
- <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>
- Export as PDF
- </button>
- </div>
- </div>
- <button class="tb-btn" onclick="openSettings()" title="Settings">
- <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>
- </button>
- </div>
- <!-- ── Editor ───────────────────────────────────────────────────────── -->
- <div id="editor-scroll">
- <div id="rich" class="md-content" contenteditable="true" spellcheck="false"
- data-ph="Start writing… type # for a heading, ** for bold"></div>
- <textarea id="plain" spellcheck="false" placeholder="Start typing…"></textarea>
- </div>
- <!-- ── Status bar ───────────────────────────────────────────────────── -->
- <div id="statusbar">
- <span id="status-msg">Ready</span>
- <div id="status-right">
- <span id="stat-mode">Markdown</span>
- <span id="stat-count">0 words</span>
- </div>
- </div>
- </div>
- <!-- hidden file input for device image picking -->
- <input type="file" id="device-file" accept="image/*" style="display:none;">
- <!-- ── Settings overlay ─────────────────────────────────────────────────── -->
- <div class="overlay" id="settings-overlay">
- <div id="settings-box">
- <div id="settings-nav">
- <div class="nav-title">Preferences</div>
- <button class="nav-item active" data-sec="general" onclick="showSection('general')">
- <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>
- General
- </button>
- <button class="nav-item" data-sec="keys" onclick="showSection('keys')">
- <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>
- Shortcuts
- </button>
- <button class="nav-item" data-sec="images" onclick="showSection('images')">
- <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>
- Images
- </button>
- </div>
- <div id="settings-body">
- <!-- General -->
- <div class="settings-section active" id="sec-general">
- <h2>General</h2>
- <div class="sub">Editor behaviour and appearance.</div>
- <div class="set-row">
- <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>
- <div class="set-ctl"><div class="seg" id="seg-mode">
- <button data-mode="md" onclick="setMode('md')">Markdown</button>
- <button data-mode="rtf" onclick="setMode('rtf')">Rich text</button>
- <button data-mode="txt" onclick="setMode('txt')">Plain text</button>
- </div></div>
- </div>
- <div class="set-row md-only no-rtf">
- <div><div class="set-label">Markdown syntax</div><div class="set-desc">Reveal the markdown marks (#, **, >, …) so you can see and edit the source.</div></div>
- <div class="set-ctl"><select class="set-select" id="set-syntax" onchange="applySyntaxMode()">
- <option value="active">Show on selected line</option>
- <option value="always">Always show</option>
- <option value="none">Always hide</option>
- </select></div>
- </div>
- <div class="set-row">
- <div><div class="set-label">Dark theme</div><div class="set-desc">Match a dark workspace.</div></div>
- <div class="set-ctl"><label class="switch"><input type="checkbox" id="set-dark" onchange="setTheme(this.checked)"><span class="slider"></span></label></div>
- </div>
- <div class="set-row">
- <div><div class="set-label">Editor font</div></div>
- <div class="set-ctl"><select class="set-select" id="set-font" onchange="applyTypography()">
- <option value="system">System Default</option>
- <option value="serif">Serif</option>
- <option value="mono">Monospace</option>
- <option value="georgia">Georgia</option>
- <option value="times">Times New Roman</option>
- </select></div>
- </div>
- <div class="set-row">
- <div><div class="set-label">Font size</div></div>
- <div class="set-ctl"><input type="number" min="11" max="32" class="set-input num" id="set-fontsize" onchange="applyTypography()"> px</div>
- </div>
- <div class="set-row">
- <div><div class="set-label">Line spacing</div></div>
- <div class="set-ctl"><select class="set-select" id="set-lh" onchange="applyTypography()">
- <option value="1.4">Compact</option>
- <option value="1.7">Relaxed</option>
- <option value="2.0">Double</option>
- </select></div>
- </div>
- </div>
- <!-- Shortcuts -->
- <div class="settings-section" id="sec-keys">
- <h2>Keyboard Shortcuts</h2>
- <div class="sub">Click a shortcut, then press the new key combination. Press Esc to cancel.</div>
- <div id="keys-list"></div>
- <div id="settings-foot">
- <button class="btn-text" onclick="resetKeys()">Reset to defaults</button>
- </div>
- </div>
- <!-- Images -->
- <div class="settings-section" id="sec-images">
- <h2>Images</h2>
- <div class="sub">How imported images are stored next to your document.</div>
- <div class="set-row">
- <div><div class="set-label">Store directory</div><div class="set-desc">Relative to the document. Use {name} for the document name.</div></div>
- <div class="set-ctl"><input type="text" class="set-input" id="set-imgdir" style="width:150px;" onchange="saveImgPrefs()"></div>
- </div>
- <div class="set-row">
- <div><div class="set-label">Compress images</div><div class="set-desc">Re-encode large images before storing to save space.</div></div>
- <div class="set-ctl"><label class="switch"><input type="checkbox" id="set-compress" onchange="onCompressToggle()"><span class="slider"></span></label></div>
- </div>
- <div class="set-row" id="row-quality">
- <div><div class="set-label">Quality</div><div class="set-desc">Lower = smaller file.</div></div>
- <div class="set-ctl"><div class="range-wrap">
- <input type="range" min="30" max="100" id="set-quality" oninput="onQualityInput()" onchange="saveImgPrefs()">
- <span id="quality-val" style="width:38px;">80%</span>
- </div></div>
- </div>
- <div class="set-row" id="row-maxw">
- <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>
- <div class="set-ctl"><input type="number" min="0" max="8000" class="set-input num" id="set-maxw" onchange="saveImgPrefs()"> px</div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <!-- ── Unsaved-changes dialog ────────────────────────────────────────────── -->
- <div class="overlay" id="confirm-overlay">
- <div id="confirm-box">
- <h3>Unsaved Changes</h3>
- <p id="confirm-msg">Your changes haven't been saved. Save before closing?</p>
- <div class="confirm-row">
- <button class="cbtn cbtn-cancel" onclick="dlgCancel()">Cancel</button>
- <button class="cbtn cbtn-discard" onclick="dlgDiscard()">Discard</button>
- <button class="cbtn cbtn-save" onclick="dlgSave()">Save</button>
- </div>
- </div>
- </div>
- <!-- ── Link editor dialog ───────────────────────────────────────────────── -->
- <div class="overlay" id="link-overlay">
- <div id="link-box">
- <h3 id="link-box-title">Insert Link</h3>
- <div class="link-field">
- <label for="link-text-input">Text</label>
- <input type="text" id="link-text-input" placeholder="Link text" autocomplete="off" spellcheck="false">
- </div>
- <div class="link-field">
- <label for="link-url-input">URL</label>
- <input type="text" id="link-url-input" placeholder="https://" autocomplete="off" spellcheck="false">
- </div>
- <div class="link-row">
- <button class="cbtn cbtn-discard" id="link-remove-btn" onclick="linkDlgRemove()">Remove link</button>
- <button class="cbtn cbtn-cancel" onclick="linkDlgCancel()">Cancel</button>
- <button class="cbtn cbtn-save" onclick="linkDlgOk()">OK</button>
- </div>
- </div>
- </div>
- <div id="busy"><div class="spin"></div><span id="busy-msg">Working…</span></div>
- <script>
- "use strict";
- /* ════════════════════════════════════════════════════════════════════════
- Text — Typora-style editor for ArozOS
- ════════════════════════════════════════════════════════════════════════ */
- // ── State ───────────────────────────────────────────────────────────────
- var filepath = "";
- var filename = "";
- var isTxtMode = false; // false = markdown WYSIWYG, true = plain text
- var isRtfMode = false; // rich surface saved as RTF instead of markdown (never with isTxtMode)
- var rtfDoc = { baseSize:24, baseFont:"" }; // defaults of the loaded .rtf, kept on save
- var isDark = false;
- var dirtyFlag = false;
- var dlgCallback = null;
- var pendingClose = null;
- var recordingAction = null; // shortcut currently being re-bound
- var rich = document.getElementById("rich");
- var plain = document.getElementById("plain");
- // ── Settings (defaults) ─────────────────────────────────────────────────
- var settings = {
- font: "system", fontSize: 16, lineHeight: "1.7", syntax: "active",
- imgDir: "img/{name}", compress: false, quality: 80, maxWidth: 1600
- };
- var FONT_MAP = {
- system: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
- serif: "Georgia, 'Times New Roman', serif",
- mono: "'SF Mono', 'Consolas', 'Courier New', monospace",
- georgia: "Georgia, serif",
- times: "'Times New Roman', Times, serif"
- };
- // ── Shortcuts ───────────────────────────────────────────────────────────
- var DEFAULT_KEYS = {
- save:"ctrl+s", bold:"ctrl+b", italic:"ctrl+i", underline:"ctrl+u", strike:"ctrl+shift+x", inlineCode:"ctrl+e",
- h1:"ctrl+1", h2:"ctrl+2", h3:"ctrl+3", h4:"ctrl+4", h5:"ctrl+5", h6:"ctrl+6", paragraph:"ctrl+0",
- blockquote:"ctrl+shift+q", bulletList:"ctrl+shift+u", orderedList:"ctrl+shift+o",
- codeBlock:"ctrl+shift+k", link:"ctrl+k", image:"ctrl+shift+i", hr:"ctrl+shift+h"
- };
- var ACTIONS = {
- save: { label:"Save", fn:saveFile, md:false },
- bold: { label:"Bold", fn:actBold, md:true },
- italic: { label:"Italic", fn:actItalic, md:true },
- underline: { label:"Underline (rich text)", fn:actUnderline, md:true },
- strike: { label:"Strikethrough", fn:actStrike, md:true },
- inlineCode:{ label:"Inline code", fn:actInlineCode, md:true, rtf:false },
- h1: { label:"Heading 1", fn:function(){setBlock("h1");}, md:true },
- h2: { label:"Heading 2", fn:function(){setBlock("h2");}, md:true },
- h3: { label:"Heading 3", fn:function(){setBlock("h3");}, md:true },
- h4: { label:"Heading 4", fn:function(){setBlock("h4");}, md:true },
- h5: { label:"Heading 5", fn:function(){setBlock("h5");}, md:true },
- h6: { label:"Heading 6", fn:function(){setBlock("h6");}, md:true },
- paragraph: { label:"Paragraph", fn:function(){setBlock("p");}, md:true },
- blockquote:{ label:"Blockquote", fn:actQuote, md:true, rtf:false },
- bulletList:{ label:"Bullet list", fn:actBullet, md:true },
- orderedList:{label:"Numbered list", fn:actNumber, md:true },
- codeBlock: { label:"Code block", fn:actCodeBlock, md:true, rtf:false },
- link: { label:"Link", fn:actLink, md:true },
- image: { label:"Insert image", fn:function(){pickDeviceImage();}, md:true },
- hr: { label:"Horizontal rule", fn:actHr, md:true }
- };
- var keymap = JSON.parse(JSON.stringify(DEFAULT_KEYS));
- // ── Turndown (HTML → Markdown) ──────────────────────────────────────────
- var td = new TurndownService({
- headingStyle:"atx", codeBlockStyle:"fenced", bulletListMarker:"-",
- emDelimiter:"*", strongDelimiter:"**", hr:"---"
- });
- if (window.turndownPluginGfm) td.use(turndownPluginGfm.gfm);
- // GFM plugin emits single-tilde strikethrough; marked only renders double-tilde
- td.addRule("strike2", {
- filter:["del","s","strike"],
- replacement:function(content){ return "~~" + content + "~~"; }
- });
- td.addRule("relimg", {
- filter:"img",
- replacement:function(content, node){
- var alt = node.getAttribute("alt") || "";
- var src = node.getAttribute("data-rel") || node.getAttribute("src") || "";
- var ttl = node.getAttribute("title");
- return " + (ttl ? ' "'+ttl+'"' : "") + ")";
- }
- });
- // Plain markdown collapses any run of blank lines to a single paragraph
- // break, so an intentional run of several empty paragraphs would be lost on
- // reload. Mark each one with a ZWSP sentinel here — invisible, and never
- // written to the saved file, since expandBlankSentinels() (called from
- // getContent()) converts it into the exact bare-newline run that
- // renderWithBlankRuns() (called from setContent()) measures back into the
- // same paragraph count on load.
- td.addRule("emptyPara", {
- filter:function(node){
- return node.nodeName === "P"
- && !node.querySelector("img,hr,table,pre,code")
- && node.textContent.replace(/[\s ]+/g, "") === "";
- },
- replacement:function(){ return "\n\n\n\n"; }
- });
- // A markdown link/image destination containing spaces or parentheses must be
- // wrapped in angle brackets, otherwise parsers (marked) treat it as plain text
- // and the image never becomes an <img> — which is why such images appeared as
- // literal "" markdown when exported. The raw path is kept inside the
- // brackets so mediaURLFor() can still percent-encode it for the media endpoint.
- function mdLinkDest(src){
- return /[\s()]/.test(src) ? "<" + src + ">" : src;
- }
- // ════════════════════════════════════════════════════════════════════════
- // Init
- // ════════════════════════════════════════════════════════════════════════
- $(function(){
- if (document.execCommand) {
- try { document.execCommand("defaultParagraphSeparator", false, "p"); } catch(e){}
- try { document.execCommand("styleWithCSS", false, false); } catch(e){}
- }
- loadPrefs();
- var files = ao_module_loadInputFiles();
- if (files && files.length > 0){
- filepath = files[0].filepath;
- filename = files[0].filename;
- modeForFile(filename);
- applyMode();
- loadFile();
- } else {
- isTxtMode = false; isRtfMode = false;
- applyMode();
- updateTitle();
- }
- // editor events
- $("#rich").on("input", onRichInput);
- $("#rich").on("keydown", onRichKeydown);
- $("#rich").on("paste", onRichPaste);
- $("#rich").on("drop", onRichDrop);
- $("#rich").on("dragover", function(e){ e.preventDefault(); });
- // clicking an image doesn't always move the caret, so nudge it to the
- // image's block and reveal that block's  mark
- $("#rich").on("click", function(e){
- if (e.target && e.target.tagName === "IMG"){
- var r = document.createRange(); r.selectNode(e.target); r.collapse(false);
- var s = getSel(); s.removeAllRanges(); s.addRange(r);
- updateActiveBlock();
- return;
- }
- // clicking empty space below a trailing code block has nowhere else to
- // land, so the browser puts the caret back inside <code> — same trap
- // exitCodeBlockDown() escapes for the Down key, but for a mouse click
- escapeTrailingCodeBlockClick(e);
- });
- $(document).on("selectionchange", debounce(function(){ updateToolbarState(); updateActiveBlock(); syncCodeHighlight(); syncLangSelector(); }, 80));
- $("#plain").on("input", function(){ markDirty(); updateStatBar(); });
- // global keydown for shortcuts
- $(document).on("keydown", globalKeydown);
- // device file input
- document.getElementById("device-file").addEventListener("change", onDeviceFileChosen);
- // close menus when clicking elsewhere
- document.addEventListener("click", function(e){
- if (!e.target.closest(".menu-wrap")) hideMenus();
- });
- // keep selection alive when clicking toolbar buttons
- document.getElementById("toolbar").addEventListener("mousedown", function(e){
- if (e.target.closest(".tb-btn, .swatch") && !e.target.closest("select")) e.preventDefault();
- });
- buildSwatches();
- buildKeyList();
- syncSettingsUI();
- applyTypography();
- updateStatBar();
- });
- function isMarkdownExt(name){
- var ext = (name.split(".").pop() || "").toLowerCase();
- return ext === "md" || ext === "markdown" || ext === "mdown" || ext === "mkd";
- }
- function isRtfExt(name){
- return (name.split(".").pop() || "").toLowerCase() === "rtf";
- }
- // pick the editing surface from the file extension
- function modeForFile(name){
- isRtfMode = isRtfExt(name);
- isTxtMode = !isRtfMode && !isMarkdownExt(name);
- }
- function modeName(){ return isTxtMode ? "txt" : (isRtfMode ? "rtf" : "md"); }
- function defaultNewName(){ return "Untitled." + modeName(); }
- // ════════════════════════════════════════════════════════════════════════
- // File load / save
- // ════════════════════════════════════════════════════════════════════════
- function loadFile(){
- // strong cache-buster: unique nonce + jQuery cache:false so the browser
- // always fetches the freshly-saved file, never a stale cached copy
- var nonce = Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
- if (isRtfMode){
- // RTF may carry raw code-page bytes, so read it byte-for-byte rather
- // than letting the browser decode it as UTF-8
- fetch(ao_root + "media?file=" + encodeURIComponent(filepath) + "&nocache=" + nonce, { cache:"no-store", credentials:"same-origin" })
- .then(function(r){ if (!r.ok) throw new Error("HTTP " + r.status); return r.arrayBuffer(); })
- .then(function(buf){
- setContent(bytesToBinary(new Uint8Array(buf)));
- dirtyFlag = false;
- updateTitle(); updateStatBar();
- }).catch(function(){ setStatus("Failed to load file", "error"); });
- return;
- }
- $.ajax({
- url: ao_root + "media?file=" + encodeURIComponent(filepath) + "&nocache=" + nonce,
- method: "GET",
- dataType: "text",
- cache: false,
- success: function(data){
- if (typeof data !== "string") data = JSON.stringify(data, null, 2);
- setContent(data);
- dirtyFlag = false;
- updateTitle(); updateStatBar();
- },
- error: function(){ setStatus("Failed to load file", "error"); }
- });
- }
- function bytesToBinary(u8){
- var parts = [];
- for (var i = 0; i < u8.length; i += 0x8000) parts.push(String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)));
- return parts.join("");
- }
- function setContent(text){
- if (isTxtMode){
- plain.value = text;
- } else if (isRtfMode){
- var res;
- try { res = TextRTF.toHTML(text || ""); }
- catch(e){ console.error(e); setStatus("Could not read this RTF file", "error"); res = { html:"<p><br></p>", baseSize:24, baseFont:"" }; }
- rtfDoc = { baseSize:res.baseSize, baseFont:res.baseFont };
- rich.innerHTML = res.html;
- refreshEmptyState();
- updateActiveBlock();
- } else {
- rich.innerHTML = renderWithBlankRuns(text || "");
- normalizeEmptyParas(rich);
- rewriteImageSrcs(rich);
- refreshEmptyState();
- updateActiveBlock();
- syncCodeHighlight();
- syncLangSelector();
- }
- }
- // marked collapses any run of blank lines in the source to a single
- // paragraph break (standard CommonMark behaviour), so this rebuilds the HTML
- // token-by-token instead of via one marked.parse() call, reinserting the
- // extra empty paragraphs a blank-line run actually represents. The count is
- // read off each lexer "space" token's raw text, which is naturally
- // fence-aware (blank lines inside a fenced code block are absorbed into that
- // block's own "code" token, never reported as "space"). A run at the very
- // start/end of the document has no separator contributed by a block on the
- // outside, so it is measured against a different baseline than a run between
- // two real blocks — see expandBlankSentinels(), the save-side counterpart.
- function renderWithBlankRuns(text){
- var tokens = marked.lexer(text);
- var html = "";
- for (var i = 0; i < tokens.length; i++){
- var tok = tokens[i];
- if (tok.type === "space"){
- var nl = (tok.raw.match(/\n/g) || []).length;
- var edge = (i === 0) || (i === tokens.length - 1);
- var extra = edge ? Math.floor(nl / 2) : (nl - 2);
- for (var k = 0; k < extra; k++) html += "<p><br></p>";
- } else {
- html += marked.parser([tok]);
- }
- }
- return html;
- }
- // turn any non-blank-but-invisible-looking placeholder paragraph into a clean
- // empty line, so they edit naturally and round-trip stably
- function normalizeEmptyParas(root){
- var ps = root.querySelectorAll("p");
- for (var i = 0; i < ps.length; i++){
- var p = ps[i];
- if (!p.querySelector("img,hr,table,pre,code,br") &&
- p.textContent.replace(/[\s ]+/g, "") === ""){
- p.innerHTML = "<br>";
- }
- }
- }
- function getContent(){
- if (isTxtMode) return plain.value;
- if (isRtfMode) return TextRTF.fromHTML(richClone(), rtfDoc);
- return richMarkdown();
- }
- // like getContent(), but RTF first embeds every image (fetched + inlined as
- // PNG/JPEG) — use this for anything that writes the document out
- function getContentAsync(){
- if (!isRtfMode) return Promise.resolve(getContent());
- return TextRTF.inlineImages(richClone()).then(function(root){ return TextRTF.fromHTML(root, rtfDoc); });
- }
- // the rich surface without its editing decorations
- function richClone(){
- var src = rich.cloneNode(true);
- var syns = src.querySelectorAll(".md-imgsyn, .md-linksyn, .md-langsel");
- for (var i = 0; i < syns.length; i++) syns[i].parentNode.removeChild(syns[i]);
- return src;
- }
- // the rich surface as markdown (also feeds PDF export in rich-text mode)
- function richMarkdown(){
- var src = rich.cloneNode(true);
- var syns = src.querySelectorAll(".md-imgsyn, .md-linksyn, .md-langsel");
- for (var i = 0; i < syns.length; i++) syns[i].parentNode.removeChild(syns[i]);
- normalizeSerializableCodeBlocks(src);
- var html = src.innerHTML.replace(//g, "");
- var md = td.turndown(html);
- return expandBlankSentinels(tidyMarkdown(md)) + "\n";
- }
- // converts each emptyPara ZWSP sentinel (see the turndown rule above) into
- // the bare-newline run renderWithBlankRuns() expects on load. Turndown only
- // contributes a separator newline between two blocks, so a sentinel run at
- // the very start/end of the document — with no block on the outside — comes
- // out short of as many raw newlines as one in the middle would; the two
- // anchored passes below restore exactly the newlines such a leading/trailing
- // run is missing before the catch-all pass removes each middle sentinel's
- // shared newline.
- function expandBlankSentinels(md){
- md = md.replace(/^(\n\n)+/, function(run){ return run.replace(//g, ""); });
- md = md.replace(/(?:\n\n)*$/, function(run){ return run.replace(//g, ""); });
- md = md.replace(/\n\n/g, "\n");
- return md;
- }
- function normalizeSerializableCodeBlocks(root){
- var pres = root.querySelectorAll("pre");
- for (var i = 0; i < pres.length; i++){
- var pre = pres[i];
- var codes = [];
- for (var j = 0; j < pre.children.length; j++){
- if (pre.children[j].tagName === "CODE") codes.push(pre.children[j]);
- }
- if (codes.length <= 1) continue;
- var lang = pre.getAttribute("data-lang") || "";
- var parts = [];
- for (var k = 0; k < codes.length; k++){
- var cls = codes[k].getAttribute("class") || "";
- if (!lang){
- var m = cls.match(/(?:^|\s)language-([A-Za-z0-9+#_-]+)/);
- if (m) lang = m[1].toLowerCase();
- }
- parts.push(codes[k].textContent || "");
- }
- while (pre.firstChild) pre.removeChild(pre.firstChild);
- var merged = document.createElement("code");
- if (lang) merged.className = "language-" + lang;
- merged.textContent = parts.join("").replace(//g, "");
- pre.appendChild(merged);
- }
- }
- // collapse runs of blank lines (turndown can emit extra) and trim the document
- // edges — but never touch the inside of a fenced code block, where blank lines
- // are significant content
- function tidyMarkdown(md){
- var parts = md.split(/(```[\s\S]*?\n```)/g);
- for (var i = 0; i < parts.length; i++){
- if (i % 2 === 0) parts[i] = parts[i].replace(/\n{3,}/g, "\n\n"); // prose only
- }
- return parts.join("").replace(/^\s+|\s+$/g, "");
- }
- // rich.textContent minus the decoration marks (used for word count / empty state)
- function richPlainText(){
- if (!rich.querySelector(".md-imgsyn, .md-linksyn, .md-langsel")) return rich.textContent.replace(//g, "");
- var clone = rich.cloneNode(true);
- var syns = clone.querySelectorAll(".md-imgsyn, .md-linksyn, .md-langsel");
- for (var i = 0; i < syns.length; i++) syns[i].parentNode.removeChild(syns[i]);
- return clone.textContent.replace(//g, "");
- }
- function saveFile(){
- if (!filepath){
- var def = defaultNewName();
- ao_module_openFileSelector(handleSaveAs, "user:/Desktop", "new", false, { defaultName: def });
- return;
- }
- doSave();
- }
- function handleSaveAs(fd){
- if (!fd || !fd.length) return;
- filepath = fd[0].filepath; filename = fd[0].filename;
- doSave();
- }
- function doSave(callback){
- getContentAsync().then(function(content){
- ao_module_agirun("Text/backend/filesaver.agi", { filepath: filepath, content: content }, function(data){
- if (data && data.error){
- setStatus("Save failed: " + data.error, "error");
- } else {
- dirtyFlag = false; updateTitle(); setStatus("Saved");
- if (callback) callback();
- }
- }, function(){ setStatus("Save failed", "error"); });
- }).catch(function(err){ console.error(err); setStatus("Save failed", "error"); });
- }
- function openFile(){
- ao_module_openFileSelector(handleOpenFile, "user:/", "file", false, {
- filter: ["txt","md","markdown","rtf","csv","log","ini","conf","json","xml","html","css","js","py","sh","yaml","yml"]
- });
- }
- function handleOpenFile(fd){
- if (!fd || !fd.length) return;
- filepath = fd[0].filepath; filename = fd[0].filename;
- modeForFile(filename);
- applyMode();
- dirtyFlag = false;
- loadFile();
- }
- // ════════════════════════════════════════════════════════════════════════
- // Mode (markdown / plain text)
- // ════════════════════════════════════════════════════════════════════════
- function applyMode(){
- document.body.classList.toggle("mode-txt", isTxtMode);
- document.body.classList.toggle("mode-rtf", isRtfMode);
- $("#stat-mode").text(isTxtMode ? "Plain text" : (isRtfMode ? "Rich text" : "Markdown"));
- $("#mi-download-lbl").text("Download ." + modeName());
- $("#rich").attr("data-ph", isRtfMode ? "Start writing…" : "Start writing… type # for a heading, ** for bold");
- $("#seg-mode button").removeClass("active");
- $('#seg-mode button[data-mode="' + modeName() + '"]').addClass("active");
- applyTypography();
- updateActiveBlock();
- }
- // invoked from the settings segmented control — converts current content
- function setMode(mode){
- var from = modeName();
- if (mode === from) return;
- function to(m){ isTxtMode = (m === "txt"); isRtfMode = (m === "rtf"); applyMode(); }
- if (from !== "txt" && mode !== "txt"){
- // markdown <-> rich text share the same WYSIWYG surface: keep the DOM
- if (mode === "rtf"){ clearDecorations(); clearLangSelectors(); tidyRichForRtf(); }
- to(mode);
- markDirty(); updateStatBar();
- return;
- }
- getContentAsync().then(function(current){ // serialise from the current surface
- to(mode);
- setContent(current); // re-hydrate into the new surface
- markDirty(); updateStatBar();
- });
- }
- // marked's HTML carries layout newlines (between blocks, soft line breaks);
- // rich-text mode shows whitespace literally, so flatten them first
- function tidyRichForRtf(){
- var walker = document.createTreeWalker(rich, NodeFilter.SHOW_TEXT, null, false);
- var n, dead = [];
- while ((n = walker.nextNode())){
- if (n.parentNode.closest && n.parentNode.closest("pre")) continue;
- if (n.nodeValue.indexOf("\n") < 0) continue;
- if (/^\s*$/.test(n.nodeValue)) dead.push(n);
- else n.nodeValue = n.nodeValue.replace(/\s*\n\s*/g, " ");
- }
- dead.forEach(function(d){ d.parentNode.removeChild(d); });
- }
- // ════════════════════════════════════════════════════════════════════════
- // WYSIWYG editing
- // ════════════════════════════════════════════════════════════════════════
- function onRichInput(){
- var syn = activeImgSyn();
- if (syn){ syncImgFromSyn(syn); return; } // editing an image mark, not prose
- var lsyn = activeLinkSyn();
- if (lsyn){ syncLinkFromSyn(lsyn); return; } // editing a link's URL mark, not prose
- var code = activeCodeBlock();
- if (code){ // typing code: re-highlight live, no autoformat
- relightCode(code);
- markDirty(); updateStatBar(); return;
- }
- markDirty();
- inlineAutoformat();
- refreshEmptyState();
- updateActiveBlock();
- updateStatBar();
- }
- function refreshEmptyState(){
- var t = richPlainText().trim();
- rich.classList.toggle("is-empty", t === "" && rich.children.length <= 1 && rich.querySelector("img,hr,table") === null);
- }
- function onRichKeydown(e){
- // a keydown originating from the language <select> (arrow keys to change
- // value, Enter/Space to open, typing to jump to an option, …) bubbles up
- // from inside #rich — let the browser handle it natively instead of
- // running block/code-block logic against the (unrelated) text selection
- if (e.target && e.target.tagName === "SELECT") return;
- // editing an image mark: Enter/Esc commit, everything else types normally
- var syn = activeImgSyn();
- if (syn){
- if (e.key === "Enter" || e.key === "Escape"){ e.preventDefault(); commitImgSyn(syn); }
- return;
- }
- var lsyn = activeLinkSyn();
- if (lsyn){
- if (e.key === "Enter" || e.key === "Escape"){ e.preventDefault(); commitLinkSyn(lsyn); }
- return;
- }
- // block-level transforms triggered by Space / Enter (no modifier)
- if (e.ctrlKey || e.metaKey || e.altKey) return;
- // editable source marks: clicking a heading's "#" puts the caret at the
- // block start, where typing "#" goes a level deeper and Backspace goes
- // shallower / strips it. Backspace also unwraps a blockquote's "> " mark.
- if (e.key === "#" && editHeadingMark(1)){ e.preventDefault(); return; }
- if (e.key === "Backspace" && backspaceAtBlockStart()){ e.preventDefault(); return; }
- if ((e.key === "Backspace" || e.key === "Delete") && deleteInCode(e.key === "Delete")){ e.preventDefault(); return; }
- if (e.key === "ArrowDown" && !e.shiftKey && exitCodeBlockDown()){ e.preventDefault(); return; }
- if (e.key === "Enter" && activeCodeBlock()){ e.preventDefault(); insertNewlineInCode(); return; }
- if (e.key === " "){
- if (blockTransformOnSpace()) e.preventDefault();
- } else if (e.key === "Enter"){
- if (blockTransformOnEnter()) e.preventDefault();
- }
- }
- // caret sits at the very start of the block (ignoring the ZWSP spacer)?
- function caretAtBlockStart(block){
- var sel = getSel();
- if (!sel.rangeCount || !sel.isCollapsed) return false;
- return textBeforeCaret(block).replace(//g, "") === "";
- }
- // typing "#" on a heading's leading mark: h1->h2 … h5->h6 (dir = 1).
- function editHeadingMark(dir){
- var block = currentBlock();
- if (!block || !/^H[1-6]$/.test(block.tagName)) return false;
- if (!caretAtBlockStart(block)) return false;
- var lvl = parseInt(block.tagName.charAt(1), 10) + dir;
- if (lvl < 1 || lvl > 6) return true; // clamp: swallow the key, no change
- changeBlockTag(block, "h" + lvl);
- return true;
- }
- // Backspace on a block's leading mark: heading -> shallower / paragraph,
- // blockquote's first paragraph -> unwrapped paragraph.
- function backspaceAtBlockStart(){
- var block = currentBlock();
- if (!block || !caretAtBlockStart(block)) return false;
- if (/^H[1-6]$/.test(block.tagName)){
- var lvl = parseInt(block.tagName.charAt(1), 10) - 1;
- changeBlockTag(block, lvl >= 1 ? "h" + lvl : "p");
- return true;
- }
- var bq = block.parentNode;
- if (block.tagName === "P" && bq && bq.tagName === "BLOCKQUOTE" && block === bq.firstElementChild){
- unwrapBlockquote(bq);
- return true;
- }
- return false;
- }
- function unwrapBlockquote(bq){
- var frag = document.createDocumentFragment();
- while (bq.firstChild) frag.appendChild(bq.firstChild);
- var first = frag.firstChild;
- bq.parentNode.replaceChild(frag, bq);
- if (first) placeCaretAtStart(first);
- markDirty(); updateActiveBlock();
- }
- function getSel(){ return window.getSelection(); }
- function currentBlock(){
- var sel = getSel();
- if (!sel.rangeCount) return null;
- var n = sel.getRangeAt(0).startContainer;
- if (n.nodeType === 3) n = n.parentNode;
- while (n && n !== rich){
- if (/^(P|H[1-6]|LI|BLOCKQUOTE|PRE|DIV)$/.test(n.tagName)) return n;
- n = n.parentNode;
- }
- return null;
- }
- // text in the current block, from its start to the caret
- function textBeforeCaret(block){
- var sel = getSel();
- if (!sel.rangeCount) return "";
- var r = sel.getRangeAt(0);
- var pre = document.createRange();
- pre.selectNodeContents(block);
- try { pre.setEnd(r.startContainer, r.startOffset); } catch(err){ return ""; }
- return pre.toString();
- }
- // text in the current block from the caret to its end
- function textAfterCaret(block){
- var sel = getSel();
- if (!sel.rangeCount) return "";
- var r = sel.getRangeAt(0);
- var post = document.createRange();
- post.selectNodeContents(block);
- try { post.setStart(r.endContainer, r.endOffset); } catch(err){ return ""; }
- return post.toString();
- }
- function blockTransformOnSpace(){
- var block = currentBlock();
- if (!block || block.tagName === "PRE") return false;
- var pre = textBeforeCaret(block);
- var li = (block.tagName === "LI");
- if (/^#{1,6}$/.test(pre) && !li){
- clearMarkers(block, pre.length); changeBlockTag(block, "h" + pre.length); return true;
- }
- if (pre === ">" && !li){
- clearMarkers(block, 1); wrapBlockquote(block); return true;
- }
- if ((pre === "-" || pre === "*" || pre === "+") && !li){
- clearMarkers(block, 1); makeList(block, false); return true;
- }
- if (/^\d+\.$/.test(pre) && !li){
- clearMarkers(block, pre.length); makeList(block, true); return true;
- }
- return false;
- }
- // turn a block into a single-item list, merging with an adjacent list of the same kind
- function makeList(block, ordered){
- var tag = ordered ? "ol" : "ul";
- var li = document.createElement("li");
- while (block.firstChild) li.appendChild(block.firstChild);
- if (!li.firstChild) li.appendChild(document.createElement("br"));
- var prev = block.previousElementSibling;
- if (prev && prev.tagName.toLowerCase() === tag){
- prev.appendChild(li);
- block.parentNode.removeChild(block);
- } else {
- var list = document.createElement(tag);
- list.appendChild(li);
- block.parentNode.replaceChild(list, block);
- }
- placeCaretAtStart(li); markDirty();
- }
- function blockTransformOnEnter(){
- var block = currentBlock();
- if (!block) return false;
- var pre = textBeforeCaret(block).trim();
- var whole = block.textContent.trim();
- var fence = whole.match(/^```([A-Za-z0-9+#_-]*)$/);
- if (block.tagName !== "PRE" && fence){
- block.textContent = ""; insertCodeBlockAt(block, fence[1]); return true;
- }
- if (block.tagName !== "PRE" && (whole === "---" || whole === "***" || whole === "___")){
- var hr = document.createElement("hr");
- var p = document.createElement("p"); p.appendChild(document.createElement("br"));
- block.parentNode.replaceChild(p, block);
- p.parentNode.insertBefore(hr, p);
- placeCaretAtStart(p); markDirty(); return true;
- }
- // pressing Enter at the end of a heading starts a normal paragraph
- if (/^H[1-6]$/.test(block.tagName) && pre === whole){
- var np = document.createElement("p"); np.appendChild(document.createElement("br"));
- if (block.nextSibling) block.parentNode.insertBefore(np, block.nextSibling);
- else block.parentNode.appendChild(np);
- placeCaretAtStart(np); markDirty(); return true;
- }
- return false;
- }
- // remove the first `count` characters (markdown markers) from a block
- function clearMarkers(block, count){
- var r = document.createRange();
- r.selectNodeContents(block);
- var walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, null);
- var first = walker.nextNode();
- if (first){
- r.setStart(first, 0);
- r.setEnd(first, Math.min(count, first.data.length));
- r.deleteContents();
- } else {
- block.textContent = "";
- }
- }
- function changeBlockTag(block, tag){
- var nb = document.createElement(tag);
- while (block.firstChild) nb.appendChild(block.firstChild);
- if (!nb.firstChild) nb.appendChild(document.createElement("br"));
- block.parentNode.replaceChild(nb, block);
- placeCaretAtStart(nb); markDirty(); updateActiveBlock();
- }
- function wrapBlockquote(block){
- var bq = document.createElement("blockquote");
- var p = document.createElement("p");
- while (block.firstChild) p.appendChild(block.firstChild);
- if (!p.firstChild) p.appendChild(document.createElement("br"));
- bq.appendChild(p);
- block.parentNode.replaceChild(bq, block);
- placeCaretAtStart(p); markDirty();
- }
- function insertCodeBlockAt(block, lang){
- var pre = document.createElement("pre");
- var code = document.createElement("code");
- if (lang){ code.className = "language-" + lang.toLowerCase(); }
- pre.setAttribute("data-lang", lang ? lang.toLowerCase() : "");
- code.appendChild(document.createTextNode(""));
- pre.appendChild(code);
- block.parentNode.replaceChild(pre, block);
- var r = document.createRange();
- r.setStart(code.firstChild, 1); r.collapse(true);
- var s = getSel(); s.removeAllRanges(); s.addRange(r);
- markDirty();
- }
- // pressing Down on the last line of a code block leaves it instead of wrapping
- // back to the top: move to the following block, creating a paragraph if needed
- function exitCodeBlockDown(){
- var block = currentBlock();
- if (!block || block.tagName !== "PRE") return false;
- var code = block.querySelector("code");
- if (code && textAfterCaret(code).replace(//g, "").indexOf("\n") >= 0) return false; // more lines below
- var next = block.nextElementSibling;
- if (next){
- placeCaretAtStart(next);
- } else {
- var p = document.createElement("p");
- p.appendChild(document.createElement("br"));
- block.parentNode.appendChild(p);
- placeCaretAtStart(p); markDirty();
- }
- return true;
- }
- // a code block with nothing after it has no element below for the browser to
- // place the caret into, so clicking the empty area under it just re-enters
- // <code> — same trap exitCodeBlockDown() escapes for the Down key. Detected
- // after the native click already moved the caret: if it landed back inside
- // the last block's code, the click must have missed all real content.
- function escapeTrailingCodeBlockClick(e){
- var last = rich.lastElementChild;
- if (!last || last.tagName !== "PRE") return;
- var code = last.querySelector("code");
- if (!code || activeCodeBlock() !== code) return;
- if (e.target !== rich && code.contains(e.target)) return; // genuine click inside the code text
- var p = document.createElement("p");
- p.appendChild(document.createElement("br"));
- rich.appendChild(p);
- placeCaretAtStart(p); markDirty();
- updateActiveBlock(); syncCodeHighlight(); syncLangSelector();
- }
- // ── Code-block syntax highlighting ──────────────────────────────────────
- // Code stays highlighted while you type: every edit re-renders the block's
- // <span class="hl-*"> wrappers from its plain text and restores the caret by
- // character offset (stable across highlighting, since spans add no text — see
- // caretOffsetIn/restoreCaretIn). syncCodeHighlight() runs on selection change
- // and after content loads, via the cheap highlightCode() (skips blocks already
- // rendered); relightCode() forces a fresh render and is used right after an
- // edit changes a block's text. Serialization is unaffected: turndown reads the
- // code's full textContent plus its language-xxx class regardless of the inner
- // spans.
- function codeLang(code){
- var m = (code.getAttribute("class") || "").match(/language-([A-Za-z0-9+#_-]+)/);
- return m ? m[1].toLowerCase() : "";
- }
- function activeCodeBlock(){
- var sel = getSel();
- var n = sel && sel.anchorNode;
- if (!n) return null;
- if (n.nodeType === 3) n = n.parentNode;
- var pre = (n && n.closest) ? n.closest("pre") : null;
- if (!pre || !rich.contains(pre)) return null;
- return pre.querySelector("code");
- }
- function syncPreLang(code){
- var pre = code.parentNode;
- if (pre && pre.tagName === "PRE") pre.setAttribute("data-lang", codeLang(code));
- }
- // character offset of the caret within an element (stable across highlighting,
- // since the spans add no text)
- function caretOffsetIn(el){
- var sel = getSel();
- if (!sel.rangeCount) return null;
- var r = sel.getRangeAt(0);
- if (!el.contains(r.startContainer)) return null;
- var pre = document.createRange();
- pre.selectNodeContents(el);
- try { pre.setEnd(r.startContainer, r.startOffset); } catch(e){ return null; }
- return pre.toString().length;
- }
- // end-of-selection counterpart to caretOffsetIn, so a non-collapsed selection
- // (the user dragging across highlighted text) can be restored as a range
- // instead of collapsing to its start once the spans are stripped
- function selectionEndOffsetIn(el){
- var sel = getSel();
- if (!sel.rangeCount) return null;
- var r = sel.getRangeAt(0);
- if (!el.contains(r.endContainer)) return el.contains(r.startContainer) ? el.textContent.length : null;
- var pre = document.createRange();
- pre.selectNodeContents(el);
- try { pre.setEnd(r.endContainer, r.endOffset); } catch(e){ return el.textContent.length; }
- return pre.toString().length;
- }
- function pointAtOffset(el, offset){
- var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null);
- var node, count = 0;
- while ((node = walker.nextNode())){
- var len = node.data.length;
- if (count + len >= offset) return { node: node, offset: Math.max(0, offset - count) };
- count += len;
- }
- return null;
- }
- // restores a caret at `offset`, or — when `endOffset` is also given and
- // differs — a full selection from offset to endOffset (see selectionEndOffsetIn)
- function restoreCaretIn(el, offset, endOffset){
- if (offset == null) return;
- var r = document.createRange();
- var start = pointAtOffset(el, offset);
- if (start) r.setStart(start.node, start.offset);
- else { r.selectNodeContents(el); r.collapse(false); }
- if (endOffset != null && endOffset !== offset){
- var end = pointAtOffset(el, endOffset);
- if (end) r.setEnd(end.node, end.offset);
- }
- var s = getSel(); s.removeAllRanges(); s.addRange(r);
- }
- // cheap/idempotent: skips blocks that already look rendered (right language
- // or already plain) — safe to call on every block on every selection change
- function highlightCode(code){
- var lang = codeLang(code);
- var hasSpans = !!code.querySelector("*");
- var canHighlight = lang && typeof TextHL !== "undefined" && TextHL.supports(lang) &&
- code.textContent.replace(//g, "").trim() !== "";
- if (hasSpans === canHighlight) { syncPreLang(code); return; } // already in the right state
- relightCode(code);
- }
- // forces a fresh render from the block's current text — use right after an
- // edit (typing, Enter, Delete, language change) so it never goes stale
- function relightCode(code){
- var lang = codeLang(code);
- var text = code.textContent.replace(//g, "");
- var canHighlight = lang && typeof TextHL !== "undefined" && TextHL.supports(lang) && text.trim() !== "";
- if (!canHighlight && !code.querySelector("*")){
- syncPreLang(code); return; // already plain, nothing to recompute
- }
- var off = caretOffsetIn(code);
- var endOff = selectionEndOffsetIn(code);
- if (canHighlight) code.innerHTML = TextHL.highlight(text, lang);
- else code.textContent = text; // unsupported / empty → flatten stale spans
- if (off != null) restoreCaretIn(code, off, endOff);
- syncPreLang(code);
- }
- function syncCodeHighlight(){
- if (isTxtMode) return;
- var codes = rich.querySelectorAll("pre > code");
- for (var i = 0; i < codes.length; i++) highlightCode(codes[i]);
- }
- // Enter inside a code block inserts a real newline (not a <div>/<br>), so the
- // text stays line-accurate for highlighting and serialization. Splices the
- // string and reassigns textContent (rather than Range.insertNode, which
- // fragments the element into several sibling Text nodes) so the caret offset
- // computed before the edit stays valid after it — that fragmentation was the
- // root cause of the caret not following Enter on a code block's last line and
- // of Delete misbehaving across the resulting node boundary.
- function insertNewlineInCode(){
- var code = activeCodeBlock();
- if (!code) return false;
- var sel = getSel();
- if (!sel.rangeCount) return false;
- if (!sel.isCollapsed) sel.getRangeAt(0).deleteContents();
- var offset = caretOffsetIn(code);
- if (offset == null) return false;
- var raw = code.textContent;
- var atEnd = raw.slice(offset).replace(//g, "") === "";
- var insert = atEnd ? "\n" : "\n"; // pad a trailing line so it shows
- code.textContent = raw.slice(0, offset) + insert + raw.slice(offset);
- restoreCaretIn(code, offset + 1);
- relightCode(code);
- markDirty();
- return true;
- }
- // Backspace/Delete inside a code block, rewritten on the same string-splice
- // principle as insertNewlineInCode so multi-line content always stays a
- // single Text node (see above) — native deletion across the \n character a
- // fenced block contains is unreliable once that node gets fragmented.
- function deleteInCode(forward){
- var code = activeCodeBlock();
- if (!code) return false;
- var sel = getSel();
- if (!sel.rangeCount) return false;
- // an empty code block has nothing left to delete — Backspace/Delete on it
- // removes the block instead of resetting the ZWSP placeholder, which used
- // to leave it stuck forever as a permanent empty grey box
- if (sel.isCollapsed && code.textContent.replace(//g, "") === ""){
- return exitEmptyCodeBlock(code);
- }
- if (!sel.isCollapsed){
- sel.getRangeAt(0).deleteContents();
- relightCode(code);
- markDirty();
- return true;
- }
- var offset = caretOffsetIn(code);
- if (offset == null) return false;
- var raw = code.textContent;
- var delAt = forward ? offset : offset - 1;
- if (delAt < 0 || delAt >= raw.length) return false;
- var next = raw.slice(0, delAt) + raw.slice(delAt + 1);
- if (next.replace(//g, "") === ""){
- return exitEmptyCodeBlock(code);
- }
- code.textContent = next;
- restoreCaretIn(code, delAt);
- relightCode(code);
- markDirty();
- return true;
- }
- // replaces an emptied-out code block with a plain empty paragraph, so it
- // can be backspaced/deleted away instead of sitting there forever
- function exitEmptyCodeBlock(code){
- var pre = code.parentNode;
- var p = document.createElement("p");
- p.appendChild(document.createElement("br"));
- pre.parentNode.replaceChild(p, pre);
- placeCaretAtStart(p); markDirty(); updateActiveBlock();
- return true;
- }
- // ── Code-block language picker ────────────────────────────────────────────
- // A real <select> pinned to the top-right corner of the block the caret is
- // currently in, so the language stays changeable after creation (unlike the
- // old ```lang fence-text mark, which only captured it once). It is a
- // contenteditable="false" island appended AFTER <code> — turndown's fenced
- // rule only reads pre.firstChild, so anything after <code> is invisible to
- // it — and is stripped from clones before serialize/word-count regardless
- // (see getContent/richPlainText) so it can never leak into saved markdown.
- function langSelectOptions(){
- var langs = (typeof TextHL !== "undefined" && TextHL.languages) ? TextHL.languages() : [];
- var html = '<option value="">Plain text</option>';
- for (var i = 0; i < langs.length; i++){
- html += '<option value="' + langs[i].id + '">' + langs[i].label + '</option>';
- }
- return html;
- }
- function onLangSelectChange(e){
- var sel = e.target;
- var pre = sel.closest("pre");
- var code = pre ? pre.querySelector("code") : null;
- if (!code) return;
- code.className = sel.value ? "language-" + sel.value : "";
- syncPreLang(code);
- relightCode(code);
- markDirty();
- }
- function ensureLangSelector(code){
- var pre = code.parentNode;
- if (!pre || pre.tagName !== "PRE") return;
- var wrap = pre.querySelector(".md-langsel");
- if (!wrap){
- wrap = document.createElement("div");
- wrap.className = "md-langsel";
- wrap.setAttribute("contenteditable", "false");
- var sel = document.createElement("select");
- sel.className = "md-langsel-select";
- sel.title = "Code block language";
- sel.innerHTML = langSelectOptions();
- sel.addEventListener("mousedown", function(e){ e.stopPropagation(); });
- sel.addEventListener("change", onLangSelectChange);
- wrap.appendChild(sel);
- pre.appendChild(wrap);
- }
- wrap.querySelector("select").value = codeLang(code);
- }
- function clearLangSelectors(){
- var wraps = rich.querySelectorAll(".md-langsel");
- for (var i = 0; i < wraps.length; i++) wraps[i].parentNode.removeChild(wraps[i]);
- }
- function syncLangSelector(){
- if (isTxtMode) return;
- clearLangSelectors();
- var code = activeCodeBlock();
- if (code) ensureLangSelector(code);
- }
- function placeCaretAtStart(el){
- var r = document.createRange();
- r.setStart(el, 0); r.collapse(true);
- var s = getSel(); s.removeAllRanges(); s.addRange(r);
- rich.focus();
- }
- // inline autoformat: **bold** *italic* `code` ~~strike~~
- function inlineAutoformat(){
- var sel = getSel();
- if (!sel.rangeCount || !sel.isCollapsed) return;
- var node = sel.getRangeAt(0).startContainer;
- if (node.nodeType !== 3) return;
- var offset = sel.getRangeAt(0).startOffset;
- var text = node.data.substring(0, offset);
- var patterns = [
- { re:/\*\*([^*\s][^*]*?)\*\*$/, tag:"strong" },
- { re:/__([^_\s][^_]*?)__$/, tag:"strong" },
- { re:/`([^`]+?)`$/, tag:"code" },
- { re:/~~([^~\s][^~]*?)~~$/, tag:"del" },
- { re:/(?<![*\w])\*([^*\s][^*]*?)\*$/, tag:"em" },
- { re:/(?<![_\w])_([^_\s][^_]*?)_$/, tag:"em" }
- ];
- for (var i = 0; i < patterns.length; i++){
- var m = patterns[i].re.exec(text);
- if (m){
- applyInline(node, offset - m[0].length, offset, m[1], patterns[i].tag);
- return;
- }
- }
- }
- function applyInline(node, start, end, inner, tag){
- var r = document.createRange();
- r.setStart(node, start); r.setEnd(node, end);
- r.deleteContents();
- var el = document.createElement(tag);
- el.textContent = inner;
- r.insertNode(el);
- // exit the formatted span with a zero-width spacer so typing continues plain
- var after = document.createTextNode("");
- el.parentNode.insertBefore(after, el.nextSibling);
- var nr = document.createRange();
- nr.setStart(after, 1); nr.collapse(true);
- var s = getSel(); s.removeAllRanges(); s.addRange(nr);
- markDirty();
- }
- // ── Toolbar actions ─────────────────────────────────────────────────────
- function exec(cmd, val){
- rich.focus();
- document.execCommand(cmd, false, val || null);
- markDirty(); updateStatBar(); updateToolbarState(); updateActiveBlock();
- }
- function actBold(){ if(isTxtMode) return; exec("bold"); }
- function actItalic(){ if(isTxtMode) return; exec("italic"); }
- function actStrike(){ if(isTxtMode) return; exec("strikeThrough"); }
- function actUnderline(){ if(isRtfMode) exec("underline"); } // markdown has no underline
- function actBullet(){ if(isTxtMode) return; exec("insertUnorderedList"); }
- function actNumber(){ if(isTxtMode) return; exec("insertOrderedList"); }
- function actInlineCode(){ if(isTxtMode) return; wrapSelection("code"); }
- function actQuote(){
- if(isTxtMode) return;
- var b = currentBlock();
- if (b && b.closest("blockquote")){ exec("formatBlock", "p"); }
- else { exec("formatBlock", "blockquote"); }
- }
- function actCodeBlock(){
- if(isTxtMode) return;
- var b = currentBlock(); if (!b) { rich.focus(); b = currentBlock(); }
- if (b) insertCodeBlockAt(b);
- }
- function actHr(){
- if(isTxtMode) return;
- rich.focus();
- document.execCommand("insertHTML", false, "<hr><p><br></p>");
- markDirty();
- }
- // the <a> the caret is currently in or out (including while inside its
- // .md-linksyn URL mark), if any — used to decide insert vs. edit mode
- function currentLinkAtCaret(){
- var sel = getSel();
- var n = sel && sel.anchorNode;
- if (!n) return null;
- if (n.nodeType === 3) n = n.parentNode;
- if (!n || !n.closest) return null;
- var syn = n.closest(".md-linksyn");
- if (syn && rich.contains(syn)) return synLink(syn);
- var a = n.closest("a");
- return (a && rich.contains(a)) ? a : null;
- }
- var linkDlgTarget = null; // <a> being edited, or null when inserting a new one
- var linkDlgRange = null; // selection in #rich saved before the dialog stole focus
- function actLink(){
- if (isTxtMode) return;
- rich.focus();
- var sel = getSel();
- linkDlgRange = (sel && sel.rangeCount) ? sel.getRangeAt(0).cloneRange() : null;
- var a = currentLinkAtCaret();
- if (a){
- linkDlgTarget = a;
- openLinkDialog("Edit Link", a.textContent, a.getAttribute("href") || "", true);
- } else {
- linkDlgTarget = null;
- var selectedText = (sel && !sel.isCollapsed) ? sel.toString() : "";
- openLinkDialog("Insert Link", selectedText, "https://", false);
- }
- }
- function openLinkDialog(title, text, url, showRemove){
- $("#link-box-title").text(title);
- $("#link-text-input").val(text);
- $("#link-url-input").val(url);
- $("#link-remove-btn").css("display", showRemove ? "" : "none");
- $("#link-overlay").addClass("show");
- setTimeout(function(){ $("#link-url-input")[0].focus(); $("#link-url-input")[0].select(); }, 30);
- }
- function hideLinkDialog(){ $("#link-overlay").removeClass("show"); }
- function linkDlgCancel(){
- hideLinkDialog();
- rich.focus();
- if (linkDlgRange){ var s = getSel(); s.removeAllRanges(); s.addRange(linkDlgRange); }
- linkDlgTarget = null; linkDlgRange = null;
- }
- function linkDlgRemove(){
- if (linkDlgTarget){
- var t = linkDlgTarget, parent = t.parentNode;
- while (t.firstChild) parent.insertBefore(t.firstChild, t);
- parent.removeChild(t);
- var r = document.createRange(); r.selectNodeContents(parent); r.collapse(false);
- rich.focus();
- var s = getSel(); s.removeAllRanges(); s.addRange(r);
- markDirty(); updateActiveBlock();
- }
- hideLinkDialog();
- linkDlgTarget = null; linkDlgRange = null;
- }
- function linkDlgOk(){
- var text = $("#link-text-input").val();
- var url = ($("#link-url-input").val() || "").trim();
- hideLinkDialog();
- if (!url){ linkDlgTarget = null; linkDlgRange = null; return; }
- rich.focus();
- if (linkDlgTarget){
- var a = linkDlgTarget;
- a.setAttribute("href", url);
- if (text && text !== a.textContent) a.textContent = text;
- var r = document.createRange(); r.selectNodeContents(a); r.collapse(false);
- var s = getSel(); s.removeAllRanges(); s.addRange(r);
- } else {
- var sel = getSel();
- sel.removeAllRanges();
- if (linkDlgRange) sel.addRange(linkDlgRange);
- if (sel.rangeCount && !sel.isCollapsed){
- // wrap the existing selection in place — preserves surrounding
- // whitespace, unlike deleting it and re-inserting raw HTML
- document.execCommand("createLink", false, url);
- var newA = currentLinkAtCaret();
- if (newA && text && text !== newA.textContent) newA.textContent = text;
- } else {
- var label = text || url;
- document.execCommand("insertHTML", false, '<a href="'+escapeAttr(url)+'">'+escapeHtml(label)+'</a>');
- }
- }
- linkDlgTarget = null; linkDlgRange = null;
- markDirty(); updateActiveBlock(); updateStatBar();
- }
- function setBlock(tag){
- if(isTxtMode) return;
- // pressing the same heading shortcut again strips the syntax (h1 -> paragraph)
- if (/^h[1-6]$/.test(tag)){
- var b = currentBlock();
- if (b && b.tagName.toLowerCase() === tag) tag = "p";
- }
- exec("formatBlock", tag);
- }
- function onHeadingSelect(){
- setBlock($("#sel-head").val());
- }
- // ── Rich text (RTF) formatting ──────────────────────────────────────────
- var FORE_SWATCHES = ["#000000","#595959","#a6a6a6","#c00000","#e36c09","#bf8f00",
- "#00b050","#0f7c80","#0070c0","#002060","#7030a0","#d6337a"];
- var BACK_SWATCHES = ["#ffff00","#00ff00","#00ffff","#ff00ff","#ffc000","#ff9999",
- "#b4c7e7","#c5e0b4","#d9d9d9","#a9d18e","#f4b183","#ffe699"];
- var AUTO_SENTINEL = "#010203"; // marks "automatic colour" runs for clean-up
- function buildSwatches(){
- function fill(id, list, kind, noneLabel){
- var html = '<button class="menu-item swatch-none" onclick="hideMenus();actColor(\'' + kind + '\', null)">' + noneLabel + '</button><div class="swatch-grid">';
- list.forEach(function(c){
- html += '<button class="swatch" title="' + c + '" style="background:' + c + ';" onclick="hideMenus();actColor(\'' + kind + '\', \'' + c + '\')"></button>';
- });
- document.getElementById(id).innerHTML = html + "</div>";
- }
- fill("fore-menu", FORE_SWATCHES, "fore", "Automatic");
- fill("back-menu", BACK_SWATCHES, "back", "No highlight");
- }
- // text / highlight colour of the selection; null = automatic / none
- function actColor(kind, color){
- if (!isRtfMode) return;
- rich.focus();
- try { document.execCommand("styleWithCSS", false, true); } catch(e){}
- if (kind === "fore"){
- document.execCommand("foreColor", false, color || AUTO_SENTINEL);
- if (color) $("#fore-bar").css("background", color);
- else stripSentinelColor();
- } else {
- document.execCommand("hiliteColor", false, color || "transparent");
- }
- try { document.execCommand("styleWithCSS", false, false); } catch(e){}
- markDirty(); updateStatBar();
- }
- function stripSentinelColor(){
- $(rich).find('[style*="rgb(1, 2, 3)"], font[color="' + AUTO_SENTINEL + '"]').each(function(){
- this.style.color = "";
- this.removeAttribute("color");
- if ((this.tagName === "SPAN" || this.tagName === "FONT") && !this.getAttribute("style") && this.attributes.length <= 1) $(this).contents().unwrap();
- });
- }
- function actAlign(dir){
- if (!isRtfMode) return;
- exec("justify" + dir);
- }
- // font size in points; a collapsed caret gets an empty sized span to type into
- function actFontSize(){
- var pt = $("#sel-size").val();
- if (!isRtfMode || !pt) return;
- rich.focus();
- var sel = getSel();
- if (!sel.rangeCount || !rich.contains(sel.anchorNode)) return;
- if (sel.isCollapsed){
- var span = document.createElement("span");
- span.style.fontSize = pt + "pt";
- span.appendChild(document.createTextNode(""));
- var r = sel.getRangeAt(0);
- r.insertNode(span);
- var nr = document.createRange(); nr.setStart(span.firstChild, 1); nr.collapse(true);
- sel.removeAllRanges(); sel.addRange(nr);
- } else {
- document.execCommand("fontSize", false, "7");
- $(rich).find('font[size="7"]').each(function(){
- var sp = document.createElement("span");
- sp.style.fontSize = pt + "pt";
- while (this.firstChild) sp.appendChild(this.firstChild);
- // the new size wins over any size set inside the selection
- $(sp).find("[style]").each(function(){ this.style.fontSize = ""; });
- $(sp).find("font[size]").each(function(){ this.removeAttribute("size"); });
- this.parentNode.replaceChild(sp, this);
- });
- }
- markDirty(); updateStatBar();
- }
- // image picked / pasted / dropped in rich-text mode: embed it in the document
- function insertEmbeddedImage(file){
- prepareBlob(file, function(blob){
- var fr = new FileReader();
- fr.onload = function(){
- rich.focus();
- document.execCommand("insertHTML", false, '<img src="' + escapeAttr(fr.result) + '" alt="">');
- refreshEmptyState(); markDirty(); setStatus("Image inserted");
- };
- fr.onerror = function(){ setStatus("Could not read the image", "error"); };
- fr.readAsDataURL(blob);
- });
- }
- function updateRtfToolbarState(){
- try { $("#btn-underline").toggleClass("active", document.queryCommandState("underline")); } catch(e){}
- var n = getSel().anchorNode;
- if (n && n.nodeType === 3) n = n.parentNode;
- if (!n || !rich.contains(n)) return;
- // queryCommandState("justify…") is unreliable, so read the block's alignment
- var b = currentBlock();
- var ta = b ? getComputedStyle(b).textAlign : "left";
- var cur = ta === "center" ? "center" : (ta === "right" || ta === "end") ? "right" : ta === "justify" ? "full" : "left";
- ["left","center","right","full"].forEach(function(d){ $("#btn-align-" + d).toggleClass("active", d === cur); });
- var pt = Math.round(parseFloat(getComputedStyle(n).fontSize) * 0.75 * 2) / 2;
- var opt = $('#sel-size option').filter(function(){ return this.value === String(pt); });
- $("#sel-size").val(opt.length ? String(pt) : "");
- }
- function wrapSelection(tag){
- rich.focus();
- var sel = getSel();
- if (!sel.rangeCount) return;
- var r = sel.getRangeAt(0);
- var el = document.createElement(tag);
- if (r.collapsed){
- el.appendChild(document.createTextNode(""));
- r.insertNode(el);
- var nr = document.createRange(); nr.setStart(el.firstChild, 1); nr.collapse(true);
- sel.removeAllRanges(); sel.addRange(nr);
- } else {
- el.appendChild(r.extractContents());
- r.insertNode(el);
- }
- markDirty();
- }
- function updateToolbarState(){
- if (isTxtMode) return;
- if (!rich.contains(getSel().anchorNode)) return;
- try {
- $("#btn-bold").toggleClass("active", document.queryCommandState("bold"));
- $("#btn-italic").toggleClass("active", document.queryCommandState("italic"));
- $("#btn-strike").toggleClass("active", document.queryCommandState("strikeThrough"));
- } catch(e){}
- var b = currentBlock();
- var tag = b ? b.tagName.toLowerCase() : "p";
- if (!/^h[1-6]$/.test(tag)) tag = "p";
- $("#sel-head").val(tag);
- $("#btn-code").toggleClass("active", !!(getSel().anchorNode && getSel().anchorNode.parentNode && getSel().anchorNode.parentNode.closest("code")));
- if (isRtfMode) updateRtfToolbarState();
- }
- // ── Markdown source-mark reveal ─────────────────────────────────────────
- // Adds/removes the .md-active class that drives the pseudo-element marks. In
- // "active" mode only the block at the caret is marked; in "always" mode every
- // block is. This only toggles a class, so it never mutates the document model
- // (no dirty flag, no effect on serialization or word count).
- function clearDecorations(){
- var prev = rich.querySelectorAll(".md-active");
- for (var i = 0; i < prev.length; i++) prev[i].classList.remove("md-active");
- var syns = rich.querySelectorAll(".md-imgsyn, .md-linksyn");
- for (var j = 0; j < syns.length; j++) syns[j].parentNode.removeChild(syns[j]);
- }
- // the canonical  text for an image's editable mark
- function imgSynText(img){
- var rel = img.getAttribute("data-rel") || img.getAttribute("src") || "";
- var alt = img.getAttribute("alt") || "";
- return "";
- }
- // the canonical closing "](url)" text for a link's editable mark
- function linkSynText(a){
- return "](" + (a.getAttribute("href") || "") + ")";
- }
- // light up a block's marks; if it owns an image, add an editable 
- // label, and give every link an editable closing "](url)" mark right after it
- function decorateBlock(el){
- // code blocks get a language <select> instead of a source-mark reveal
- // (see syncLangSelector) — and must never get .md-active, since the
- // generic inline-code mark rule (`.md-active code::before/after`) would
- // otherwise wrap the fenced content in a stray backtick pair
- if (el.tagName === "PRE") return;
- el.classList.add("md-active");
- if (el.tagName === "BLOCKQUOTE") return;
- var img = el.querySelector ? el.querySelector("img") : null;
- if (img && !el.querySelector(".md-imgsyn")){
- var span = document.createElement("span");
- span.className = "md-imgsyn";
- span.setAttribute("contenteditable", "true");
- span.setAttribute("spellcheck", "false");
- span.setAttribute("title", "Edit the image reference — change the path to swap the image");
- span.textContent = imgSynText(img);
- el.insertBefore(span, el.firstChild); // render above the image
- }
- var links = el.querySelectorAll ? el.querySelectorAll("a") : [];
- for (var i = 0; i < links.length; i++){
- var a = links[i], next = a.nextSibling;
- if (next && next.nodeType === 1 && next.classList && next.classList.contains("md-linksyn")) continue;
- var lspan = document.createElement("span");
- lspan.className = "md-linksyn";
- lspan.setAttribute("contenteditable", "true");
- lspan.setAttribute("spellcheck", "false");
- lspan.setAttribute("title", "Edit the link URL");
- lspan.textContent = linkSynText(a);
- a.parentNode.insertBefore(lspan, a.nextSibling);
- }
- }
- function updateActiveBlock(){
- if (isTxtMode) return;
- if (activeImgSyn() || activeLinkSyn()) return; // never tear down a mark being edited
- clearDecorations();
- if (settings.syntax === "none" || isRtfMode) return; // Always hide / no markdown marks in RTF
- if (settings.syntax === "always"){
- var all = rich.querySelectorAll("h1,h2,h3,h4,h5,h6,p,li,blockquote");
- for (var j = 0; j < all.length; j++) decorateBlock(all[j]);
- return;
- }
- var sel = getSel();
- if (!sel.rangeCount || !rich.contains(sel.anchorNode)) return;
- var b = currentBlock();
- if (!b) return;
- decorateBlock(b);
- // a blockquote's marks live on the wrapper, so light it up too
- var bq = b.closest ? b.closest("blockquote") : null;
- if (bq && rich.contains(bq)) bq.classList.add("md-active");
- }
- // the editable image-mark label the caret is currently inside, if any
- function activeImgSyn(){
- var sel = getSel();
- var n = sel && sel.anchorNode;
- if (!n) return null;
- if (n.nodeType === 3) n = n.parentNode;
- return (n && n.closest) ? n.closest(".md-imgsyn") : null;
- }
- function synImage(syn){
- var block = syn.parentNode;
- return block ? block.querySelector("img") : null;
- }
- // the editable link-mark label the caret is currently inside, if any
- function activeLinkSyn(){
- var sel = getSel();
- var n = sel && sel.anchorNode;
- if (!n) return null;
- if (n.nodeType === 3) n = n.parentNode;
- return (n && n.closest) ? n.closest(".md-linksyn") : null;
- }
- function synLink(syn){
- var a = syn.previousElementSibling;
- return (a && a.tagName === "A") ? a : null;
- }
- // re-point a link from its edited "](url)" label (live, as the user types)
- function syncLinkFromSyn(syn){
- var a = synLink(syn);
- if (!a) return;
- var m = /^\]\(([^)]*)\)\s*$/.exec((syn.textContent || "").trim());
- if (!m) return; // not a complete mark yet — wait
- a.setAttribute("href", m[1].trim().replace(/^<|>$/g, ""));
- markDirty();
- }
- // finish editing: snap the label back to the canonical text and drop focus
- function commitLinkSyn(syn){
- syncLinkFromSyn(syn);
- var a = synLink(syn), block = syn.parentNode;
- if (a) syn.textContent = linkSynText(a);
- rich.focus();
- if (block){
- var r = document.createRange(); r.selectNodeContents(block); r.collapse(false);
- var s = getSel(); s.removeAllRanges(); s.addRange(r);
- }
- updateActiveBlock();
- }
- // re-point an image from its edited  label (live, as the user types)
- function syncImgFromSyn(syn){
- var img = synImage(syn);
- if (!img) return;
- var m = /^!\[([^\]]*)\]\(([^)]*)\)\s*$/.exec((syn.textContent || "").trim());
- if (!m) return; // not a complete mark yet — wait
- var alt = m[1];
- var rawSrc = m[2].trim().replace(/^<|>$/g, "");
- img.setAttribute("alt", alt);
- if (/^(https?:|data:|blob:)/i.test(rawSrc)){
- img.removeAttribute("data-rel");
- img.setAttribute("src", rawSrc);
- } else {
- var rel = rawSrc.replace(/^\.?\/+/, "");
- img.setAttribute("data-rel", rel);
- img.setAttribute("src", filepath ? mediaURLFor(rel) : rel);
- }
- markDirty();
- }
- // finish editing: snap the label back to the canonical text and drop focus
- function commitImgSyn(syn){
- syncImgFromSyn(syn);
- var img = synImage(syn), block = syn.parentNode;
- if (img) syn.textContent = imgSynText(img);
- rich.focus();
- if (block){
- var r = document.createRange(); r.selectNodeContents(block); r.collapse(false);
- var s = getSel(); s.removeAllRanges(); s.addRange(r);
- }
- updateActiveBlock();
- }
- function applySyntaxMode(){
- settings.syntax = $("#set-syntax").val() || "active";
- updateActiveBlock();
- savePrefs();
- }
- // ════════════════════════════════════════════════════════════════════════
- // Shortcuts
- // ════════════════════════════════════════════════════════════════════════
- function comboFromEvent(e){
- var parts = [];
- if (e.ctrlKey || e.metaKey) parts.push("ctrl");
- if (e.shiftKey) parts.push("shift");
- if (e.altKey) parts.push("alt");
- var k = e.key;
- if (k === " ") k = "space";
- else if (k.length === 1) k = k.toLowerCase();
- else k = k.toLowerCase();
- if (["control","shift","alt","meta"].indexOf(k) >= 0) return null;
- parts.push(k);
- return parts.join("+");
- }
- function globalKeydown(e){
- if (recordingAction){ recordKey(e); return; }
- if ($("#settings-overlay").hasClass("show")) {
- if (e.key === "Escape") closeSettings();
- return;
- }
- if ($("#link-overlay").hasClass("show")) {
- if (e.key === "Escape") linkDlgCancel();
- else if (e.key === "Enter") { e.preventDefault(); linkDlgOk(); }
- return;
- }
- var combo = comboFromEvent(e);
- if (!combo) return;
- for (var action in keymap){
- if (keymap[action] === combo){
- var def = ACTIONS[action];
- if (!def) continue;
- if (def.md && isTxtMode) continue; // markdown-only action in txt mode
- if (def.rtf === false && isRtfMode) continue; // no RTF equivalent
- if (def.md && (activeImgSyn() || activeLinkSyn())) continue; // don't format inside a source mark
- e.preventDefault();
- def.fn();
- return;
- }
- }
- }
- function prettyCombo(c){
- return c.split("+").map(function(p){
- if (p === "ctrl") return "Ctrl";
- if (p === "shift") return "Shift";
- if (p === "alt") return "Alt";
- if (p === "space") return "Space";
- return p.length === 1 ? p.toUpperCase() : p.charAt(0).toUpperCase() + p.slice(1);
- }).join(" + ");
- }
- function buildKeyList(){
- var html = "";
- for (var action in ACTIONS){
- html += '<div class="key-row"><span class="key-name">' + escapeHtml(ACTIONS[action].label) +
- '</span><button class="key-cap" data-action="' + action + '" onclick="startRecord(\'' + action + '\')">' +
- escapeHtml(prettyCombo(keymap[action] || "")) + '</button></div>';
- }
- document.getElementById("keys-list").innerHTML = html;
- }
- function startRecord(action){
- if (recordingAction){
- $('.key-cap[data-action="'+recordingAction+'"]').removeClass("recording")
- .text(prettyCombo(keymap[recordingAction]));
- }
- recordingAction = action;
- $('.key-cap[data-action="'+action+'"]').addClass("recording").text("Press keys…");
- }
- function recordKey(e){
- e.preventDefault();
- if (e.key === "Escape"){
- $('.key-cap[data-action="'+recordingAction+'"]').removeClass("recording")
- .text(prettyCombo(keymap[recordingAction]));
- recordingAction = null;
- return;
- }
- var combo = comboFromEvent(e);
- if (!combo || ["ctrl","shift","alt"].indexOf(combo) >= 0) return; // wait for a real key
- // free the combo from any other action
- for (var a in keymap){ if (keymap[a] === combo && a !== recordingAction) keymap[a] = ""; }
- keymap[recordingAction] = combo;
- recordingAction = null;
- savePrefs();
- buildKeyList();
- }
- function resetKeys(){
- keymap = JSON.parse(JSON.stringify(DEFAULT_KEYS));
- savePrefs(); buildKeyList();
- }
- // ════════════════════════════════════════════════════════════════════════
- // Images
- // ════════════════════════════════════════════════════════════════════════
- function docDir(){
- var i = filepath.lastIndexOf("/");
- return i < 0 ? "" : filepath.substring(0, i);
- }
- function docName(){
- var n = filename.replace(/\.[^.]+$/, "");
- return n || "document";
- }
- function relDir(){
- return settings.imgDir.replace(/\{name\}/g, docName()).replace(/^\.?\/+/, "");
- }
- function mediaURLFor(rel){
- rel = rel.replace(/^\.?\/+/, "");
- return ao_root + "media?file=" + encodeURIComponent(docDir() + "/" + rel);
- }
- function rewriteImageSrcs(root){
- if (!filepath) return;
- $(root).find("img").each(function(){
- var src = this.getAttribute("src") || "";
- if (/^(https?:|data:|blob:)/i.test(src) || src.indexOf("media?file=") >= 0) return;
- var rel = src.replace(/^\.?\/+/, "");
- this.setAttribute("data-rel", rel);
- this.setAttribute("src", mediaURLFor(rel));
- });
- }
- function makeImgName(orig, forceExt){
- var base = (orig || "image").replace(/\.[^.]+$/, "").replace(/[^a-zA-Z0-9_\-]+/g, "_").substr(0, 40) || "image";
- var ext = forceExt || ((orig || "").split(".").pop() || "png").toLowerCase();
- var ts = Date.now().toString(36);
- return base + "-" + ts + "." + ext;
- }
- // ensure the image folder exists on the server, then run cb(reldir)
- function ensureImgDir(cb){
- if (!filepath){
- alert("Please save the document first — images are stored in a folder next to it.");
- return;
- }
- var rel = relDir();
- ao_module_agirun("Text/backend/imgtool.agi", { action:"mkdir", docpath:filepath, reldir:rel }, function(data){
- if (data && data.error){ setStatus("Image folder error: " + data.error, "error"); return; }
- cb(rel);
- }, function(){ setStatus("Could not prepare image folder", "error"); });
- }
- function pickDeviceImage(){
- if (isTxtMode) return;
- if (!filepath && !isRtfMode){ alert("Please save the document first."); return; }
- document.getElementById("device-file").click();
- }
- function onDeviceFileChosen(e){
- var file = e.target.files[0];
- e.target.value = "";
- if (!file) return;
- if (isRtfMode){ insertEmbeddedImage(file); return; }
- ensureImgDir(function(rel){
- prepareBlob(file, function(blob, ext){
- var fname = makeImgName(file.name, ext);
- setStatus("Uploading image…");
- ao_module_uploadFile(new File([blob], fname), docDir() + "/" + rel, function(){
- insertImage(rel + "/" + fname, docName());
- setStatus("Image inserted");
- }, undefined, function(){ setStatus("Image upload failed", "error"); });
- });
- });
- }
- // client-side compression via canvas (only when enabled)
- function prepareBlob(file, cb){
- if (!settings.compress || !/^image\//.test(file.type) || file.type === "image/gif"){
- cb(file, (file.name.split(".").pop() || "png").toLowerCase());
- return;
- }
- var img = new Image();
- img.onload = function(){
- var w = img.naturalWidth, h = img.naturalHeight;
- var maxW = settings.maxWidth;
- if (maxW > 0 && w > maxW){ h = Math.round(h * (maxW / w)); w = maxW; }
- var c = document.createElement("canvas");
- c.width = w; c.height = h;
- c.getContext("2d").drawImage(img, 0, 0, w, h);
- c.toBlob(function(blob){
- URL.revokeObjectURL(img.src);
- if (blob) cb(blob, "jpg");
- else cb(file, (file.name.split(".").pop() || "png").toLowerCase());
- }, "image/jpeg", settings.quality / 100);
- };
- img.onerror = function(){ cb(file, (file.name.split(".").pop() || "png").toLowerCase()); };
- img.src = URL.createObjectURL(file);
- }
- function pickServerImage(){
- if (isTxtMode) return;
- if (!filepath && !isRtfMode){ alert("Please save the document first."); return; }
- ao_module_openFileSelector(handleServerImage, "user:/", "file", false, {
- filter: ["jpg","jpeg","png","gif","webp","bmp","svg"]
- });
- }
- function handleServerImage(fd){
- if (!fd || !fd.length) return;
- var src = fd[0].filepath, name = fd[0].filename;
- if (isRtfMode){
- setStatus("Importing image…");
- fetch(ao_root + "media?file=" + encodeURIComponent(src), { credentials:"same-origin" })
- .then(function(r){ if (!r.ok) throw new Error("HTTP " + r.status); return r.blob(); })
- .then(function(b){ insertEmbeddedImage(new File([b], name, { type:b.type })); })
- .catch(function(){ setStatus("Image import failed", "error"); });
- return;
- }
- var rel = relDir();
- var dest = makeImgName(name, settings.compress ? "jpg" : null);
- setStatus("Importing image…");
- ao_module_agirun("Text/backend/imgtool.agi", {
- action:"import", docpath:filepath, reldir:rel, src:src, destname:dest,
- compress: settings.compress ? "true" : "false", maxwidth: settings.maxWidth
- }, function(data){
- if (data && data.error){ setStatus("Import failed: " + data.error, "error"); return; }
- insertImage(data.rel || (rel + "/" + dest), docName());
- setStatus("Image inserted");
- }, function(){ setStatus("Image import failed", "error"); });
- }
- function insertImageByUrl(){
- if (isTxtMode) return;
- var url = prompt("Image URL:", "https://");
- if (!url) return;
- rich.focus();
- document.execCommand("insertHTML", false, '<img src="'+escapeAttr(url)+'" alt="">');
- markDirty();
- }
- // insert an image referencing a path relative to the document
- function insertImage(rel, alt){
- if (isTxtMode){
- insertAtTextarea(plain, " + ")");
- markDirty(); return;
- }
- rich.focus();
- var html = '<img src="'+escapeAttr(mediaURLFor(rel))+'" data-rel="'+escapeAttr(rel)+'" alt="'+escapeAttr(alt||"")+'">';
- document.execCommand("insertHTML", false, html);
- refreshEmptyState(); markDirty();
- }
- function insertAtTextarea(ta, text){
- var s = ta.selectionStart, e = ta.selectionEnd;
- ta.value = ta.value.substring(0, s) + text + ta.value.substring(e);
- ta.selectionStart = ta.selectionEnd = s + text.length;
- ta.focus();
- }
- // paste / drop images straight into the editor
- function onRichPaste(e){
- var items = (e.originalEvent || e).clipboardData && (e.originalEvent || e).clipboardData.items;
- if (!items) return;
- for (var i = 0; i < items.length; i++){
- if (items[i].type && items[i].type.indexOf("image") === 0){
- var file = items[i].getAsFile();
- if (file){ e.preventDefault(); handleDroppedImage(file); return; }
- }
- }
- }
- function onRichDrop(e){
- var dt = (e.originalEvent || e).dataTransfer;
- if (dt && dt.files && dt.files.length && /^image\//.test(dt.files[0].type)){
- e.preventDefault(); handleDroppedImage(dt.files[0]);
- }
- }
- function handleDroppedImage(file){
- if (isRtfMode){ insertEmbeddedImage(file); return; }
- if (!filepath){ alert("Please save the document first to store pasted images."); return; }
- ensureImgDir(function(rel){
- prepareBlob(file, function(blob, ext){
- var fname = makeImgName(file.name || "pasted.png", ext);
- setStatus("Uploading image…");
- ao_module_uploadFile(new File([blob], fname), docDir() + "/" + rel, function(){
- insertImage(rel + "/" + fname, docName());
- setStatus("Image inserted");
- }, undefined, function(){ setStatus("Image upload failed", "error"); });
- });
- });
- }
- // ════════════════════════════════════════════════════════════════════════
- // Export
- // ════════════════════════════════════════════════════════════════════════
- function renderedHTML(){
- if (isTxtMode) return "<pre>" + escapeHtml(plain.value) + "</pre>";
- if (isRtfMode) return richClone().innerHTML.replace(//g, "");
- return renderWithBlankRuns(getContent());
- }
- // collect the CSS that styles .md-content so exports match the editor
- function exportCSS(){
- var bg = getCss("--editor-bg"), text = getCss("--text"), accent = getCss("--accent");
- var code = getCss("--code-bg"), sep = getCss("--sep"), quote = getCss("--quote-bdr");
- var tbl = getCss("--table-bdr"), text2 = getCss("--text2");
- return [
- "body{margin:0;background:"+bg+";color:"+text+";font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;line-height:"+settings.lineHeight+";}",
- ".md-content{max-width:820px;margin:0 auto;padding:48px 40px;font-size:"+settings.fontSize+"px;word-wrap:break-word;}",
- ".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;}",
- ".md-content h1{font-size:2em;border-bottom:1px solid "+sep+";padding-bottom:.25em;}",
- ".md-content h2{font-size:1.6em;border-bottom:1px solid "+sep+";padding-bottom:.2em;}",
- ".md-content h3{font-size:1.3em;} .md-content h4{font-size:1.1em;} .md-content h6{color:"+text2+";}",
- ".md-content p{margin:.55em 0;} .md-content a{color:"+accent+";text-decoration:none;}",
- ".md-content ul,.md-content ol{margin:.5em 0;padding-left:1.7em;} .md-content li{margin:.25em 0;}",
- ".md-content blockquote{margin:.8em 0;padding:.2em 1em;color:"+text2+";border-left:3px solid "+quote+";border-radius:0 6px 6px 0;}",
- ".md-content code{font-family:'SF Mono',Consolas,monospace;font-size:.88em;background:"+code+";padding:.15em .4em;border-radius:4px;}",
- ".md-content pre{margin:.8em 0;padding:14px 16px;background:"+code+";border-radius:8px;overflow-x:auto;}",
- ".md-content pre code{background:none;padding:0;} .md-content hr{border:none;border-top:1px solid "+sep+";margin:1.6em 0;}",
- ".md-content img{max-width:100%;border-radius:6px;}",
- ".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+";}",
- ".hl-com{color:"+getCss("--hl-com")+";font-style:italic;} .hl-str{color:"+getCss("--hl-str")+";} .hl-num{color:"+getCss("--hl-num")+";}",
- ".hl-kw{color:"+getCss("--hl-kw")+";} .hl-typ{color:"+getCss("--hl-typ")+";} .hl-fn{color:"+getCss("--hl-fn")+";}"
- ].join("\n");
- }
- function getCss(v){ return getComputedStyle(document.body).getPropertyValue(v).trim(); }
- // apply syntax highlighting to an export's fenced code blocks
- function highlightExportCode(root){
- if (typeof TextHL === "undefined") return;
- var codes = root.querySelectorAll("pre > code");
- for (var i = 0; i < codes.length; i++){
- var lang = codeLang(codes[i]);
- if (lang && TextHL.supports(lang)) codes[i].innerHTML = TextHL.highlight(codes[i].textContent, lang);
- }
- }
- // fetch a same-origin image and return a data URL (for self-contained export)
- function inlineImage(url){
- return new Promise(function(resolve){
- var xhr = new XMLHttpRequest();
- xhr.open("GET", url, true); xhr.responseType = "blob";
- xhr.onload = function(){
- if (xhr.status === 200){
- var fr = new FileReader();
- fr.onloadend = function(){ resolve(fr.result); };
- fr.onerror = function(){ resolve(url); };
- fr.readAsDataURL(xhr.response);
- } else resolve(url);
- };
- xhr.onerror = function(){ resolve(url); };
- xhr.send();
- });
- }
- // build an offscreen DOM with all images inlined as data URLs
- function buildExportContainer(){
- var div = document.createElement("div");
- div.className = "md-content";
- div.innerHTML = renderedHTML();
- highlightExportCode(div); // colour fenced code so exports match the screen
- // resolve relative srcs to media URLs first
- $(div).find("img").each(function(){
- var rel = this.getAttribute("data-rel");
- var src = this.getAttribute("src") || "";
- if (rel) this.setAttribute("src", mediaURLFor(rel));
- else if (!/^(https?:|data:)/i.test(src) && filepath) this.setAttribute("src", mediaURLFor(src));
- });
- var imgs = Array.prototype.slice.call(div.querySelectorAll("img"));
- return Promise.all(imgs.map(function(im){
- return inlineImage(im.getAttribute("src")).then(function(d){ im.setAttribute("src", d); });
- })).then(function(){ return div; });
- }
- function downloadBlob(blob, name){
- var a = document.createElement("a");
- a.href = URL.createObjectURL(blob);
- a.download = name;
- document.body.appendChild(a); a.click();
- setTimeout(function(){ URL.revokeObjectURL(a.href); a.remove(); }, 1000);
- }
- function exportHTML(){
- showBusy("Building HTML…");
- buildExportContainer().then(function(div){
- var title = escapeHtml(docName());
- var doc = "<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>" +
- title + "</title>\n<style>\n" + exportCSS() + "\n</style></head>\n<body>\n" +
- div.outerHTML + "\n</body></html>";
- downloadBlob(new Blob([doc], { type:"text/html" }), docName() + ".html");
- hideBusy(); setStatus("Exported HTML");
- }).catch(function(err){ hideBusy(); setStatus("HTML export failed", "error"); console.error(err); });
- }
- // ── Download the raw document (.md / .txt), zipping it with its images ─────
- function collectDocImages(){
- var seen = {}, out = [];
- function add(p){
- if (!p) return;
- p = p.replace(/^\.?\/+/, "");
- if (/^(https?:|data:)/i.test(p) || p.indexOf("media?file=") >= 0) return;
- if (!seen[p]){ seen[p] = 1; out.push(p); }
- }
- if (isTxtMode){
- // capture both bare and angle-bracket-wrapped destinations (the latter
- // is used when a path contains spaces)
- var re = /!\[[^\]]*\]\(\s*(?:<([^>]+)>|([^)\s]+))/g, m;
- while ((m = re.exec(plain.value))) add(m[1] || m[2]);
- } else {
- $(rich).find("img").each(function(){
- add(this.getAttribute("data-rel") || this.getAttribute("src"));
- });
- }
- return out;
- }
- function exportDocument(){
- if (isRtfMode){ // images are embedded in the RTF itself
- showBusy("Building document…");
- getContentAsync().then(function(rtf){
- hideBusy();
- downloadBlob(new Blob([rtf], { type:"application/rtf" }), docName() + ".rtf");
- setStatus("Downloaded " + docName() + ".rtf");
- }).catch(function(){ hideBusy(); setStatus("Export failed", "error"); });
- return;
- }
- var content = getContent();
- var ext = isTxtMode ? "txt" : "md";
- var name = docName() + "." + ext;
- var imgs = collectDocImages();
- if (imgs.length === 0){
- downloadBlob(new Blob([content], { type: isTxtMode ? "text/plain" : "text/markdown" }), name);
- setStatus("Downloaded " + name);
- return;
- }
- if (!filepath){ alert("Please save the document first so its images can be bundled."); return; }
- showBusy("Bundling document…");
- ao_module_agirun("Text/backend/export.agi", {
- action:"zip", docpath:filepath, name:name, content:content, images:JSON.stringify(imgs)
- }, function(data){
- if (!data || data.error){ hideBusy(); setStatus("Export failed: " + ((data && data.error) || "unknown"), "error"); return; }
- var url = ao_root + "media/download/?file=" + encodeURIComponent(data.zip);
- fetch(url).then(function(r){ return r.blob(); }).then(function(blob){
- downloadBlob(blob, docName() + ".zip");
- hideBusy(); setStatus("Downloaded " + docName() + ".zip");
- // best-effort temp cleanup
- ao_module_agirun("Text/backend/export.agi", { action:"cleanup", zip:data.zip, workdir:data.workdir }, function(){}, function(){});
- }).catch(function(){ hideBusy(); setStatus("Export download failed", "error"); });
- }, function(){ hideBusy(); setStatus("Export failed", "error"); });
- }
- // ════════════════════════════════════════════════════════════════════════
- // Text-based PDF export (pdf-lib): real selectable text + embedded images.
- // Mirrors the PDF Tool editor — standard fonts for encodable text,
- // rasterise fallback for glyphs the standard fonts can't encode (e.g. CJK).
- // ════════════════════════════════════════════════════════════════════════
- function exportPDF(){
- showBusy("Rendering PDF…");
- pdfBuild().then(function(bytes){
- downloadBlob(new Blob([bytes], { type:"application/pdf" }), docName() + ".pdf");
- hideBusy(); setStatus("Exported PDF");
- }).catch(function(err){ hideBusy(); setStatus("PDF export failed", "error"); console.error(err); });
- }
- // Save the rendered PDF straight into ArozOS instead of the browser's download
- // folder. Uses the "new file" mode of the shared file selector so the user
- // picks a destination folder + filename; the callback is a named, window-scoped
- // function (not an inline closure) since ao_module_openFileSelector calls it
- // back by name once the virtual-desktop file-selector window closes.
- function savePDFToArozOS(){
- ao_module_openFileSelector(handlePDFSaveTarget, "user:/Desktop", "new", false, { defaultName: docName() + ".pdf" });
- }
- function handlePDFSaveTarget(fd){
- if (!fd || !fd.length) return;
- var targetName = fd[0].filename;
- var targetDir = fd[0].filepath.substring(0, fd[0].filepath.length - targetName.length - 1);
- showBusy("Rendering PDF…");
- pdfBuild().then(function(bytes){
- var file = new File([bytes], targetName, { type: "application/pdf" });
- ao_module_uploadFile(file, targetDir, function(){
- hideBusy(); setStatus("Saved " + targetName + " to " + targetDir);
- }, undefined, function(){
- hideBusy(); setStatus("Save to ArozOS failed", "error");
- });
- }).catch(function(err){ hideBusy(); setStatus("PDF export failed", "error"); console.error(err); });
- }
- var _measureCtx = null;
- function measureCtx(){ if (!_measureCtx) _measureCtx = document.createElement("canvas").getContext("2d"); return _measureCtx; }
- function PDF_COLORS(){
- var rgb = PDFLib.rgb;
- return {
- text: rgb(0.16, 0.18, 0.22),
- head: rgb(0.10, 0.12, 0.16),
- accent: rgb(0.16, 0.40, 0.82),
- muted: rgb(0.45, 0.49, 0.57),
- code: rgb(0.20, 0.22, 0.30),
- codebg: rgb(0.96, 0.97, 0.99),
- rule: rgb(0.85, 0.87, 0.91),
- quote: rgb(0.74, 0.78, 0.85),
- tline: rgb(0.80, 0.83, 0.88),
- thead: rgb(0.95, 0.96, 0.98)
- };
- }
- 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; }
- 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 }; }
- function decodeEntities(s){ var ta = document.createElement("textarea"); ta.innerHTML = s || ""; return ta.value; }
- function stripTags(s){ return (s || "").replace(/<[^>]*>/g, ""); }
- // flatten marked inline tokens into styled runs
- function inlineRuns(tokens, style){
- style = style || {};
- var out = [];
- (tokens || []).forEach(function(t){
- switch (t.type){
- case "text":
- if (t.tokens && t.tokens.length) out = out.concat(inlineRuns(t.tokens, style));
- else out.push(mkRun(decodeEntities(t.text), style));
- break;
- case "strong": out = out.concat(inlineRuns(t.tokens, assignStyle(style, { bold:true }))); break;
- case "em": out = out.concat(inlineRuns(t.tokens, assignStyle(style, { italic:true }))); break;
- case "del": out = out.concat(inlineRuns(t.tokens, assignStyle(style, { strike:true }))); break;
- case "codespan": out.push(mkRun(decodeEntities(t.text), assignStyle(style, { mono:true, code:true }))); break;
- case "link": out = out.concat(inlineRuns(t.tokens, assignStyle(style, { link:true }))); break;
- case "image": out.push({ image:true, href:t.href, alt:t.text || "" }); break;
- case "br": out.push({ brk:true }); break;
- case "escape": out.push(mkRun(t.text, style)); break;
- case "html": out.push(mkRun(stripTags(t.text), style)); break;
- default: if (t.text) out.push(mkRun(decodeEntities(t.text), style)); break;
- }
- });
- return out;
- }
- function pdfPickFont(P, run){
- if (run.mono) return run.bold ? P.fonts.monoBold : P.fonts.mono;
- if (run.bold && run.italic) return P.fonts.bi;
- if (run.bold) return P.fonts.bold;
- if (run.italic) return P.fonts.ital;
- return P.fonts.reg;
- }
- function pdfNewCursor(P){
- var c = { pageW:595.28, pageH:841.89, margin:56, y:0, page:null };
- c.page = P.pdf.addPage([c.pageW, c.pageH]);
- c.y = c.pageH - c.margin;
- return c;
- }
- function pdfEnsure(P, h){
- var c = P.cur;
- if (c.y - h < c.margin){ c.page = P.pdf.addPage([c.pageW, c.pageH]); c.y = c.pageH - c.margin; }
- }
- function pdfRule(P){
- var c = P.cur;
- 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 });
- }
- function pdfColToCss(col){
- if (!col) return "#2a2e38";
- return "rgb(" + Math.round((col.red||0)*255) + "," + Math.round((col.green||0)*255) + "," + Math.round((col.blue||0)*255) + ")";
- }
- // split text for wrapping: whole words, runs of spaces, and individual CJK chars
- function tokenizeWrap(text){
- return (text || "").match(/[ -〿-ヿ㐀-䶿一-鿿豈--가-]|\s+|[^\s -〿-ヿ㐀-䶿一-鿿豈--가-]+/g) || [];
- }
- function canvasToEmbeddedPng(pdf, canvas){
- return new Promise(function(res, rej){
- canvas.toBlob(function(b){
- if (!b){ rej(new Error("canvas")); return; }
- var fr = new FileReader();
- fr.onload = function(){ pdf.embedPng(new Uint8Array(fr.result)).then(res, rej); };
- fr.onerror = rej;
- fr.readAsArrayBuffer(b);
- }, "image/png");
- });
- }
- // draw one word as real text; on encoding failure, rasterise it and place as image
- function pdfDrawWord(P, font, word, size, x, color, strike){
- var c = P.cur;
- try {
- var w = font.widthOfTextAtSize(word, size);
- c.page.drawText(word, { x:x, y:c.y - size*0.80, size:size, font:font, color:color });
- 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 });
- return Promise.resolve(w);
- } catch (e){
- return pdfDrawRasterWord(P, word, size, x, color);
- }
- }
- function pdfDrawRasterWord(P, word, size, x, color){
- var c = P.cur, k = 3;
- var ctx = measureCtx(); ctx.font = size + "px sans-serif";
- var wPt = Math.max(1, ctx.measureText(word).width), hPt = size * 1.2;
- var cv = document.createElement("canvas");
- cv.width = Math.ceil(wPt * k); cv.height = Math.ceil(hPt * k);
- var cx = cv.getContext("2d");
- cx.scale(k, k); cx.fillStyle = pdfColToCss(color); cx.textBaseline = "alphabetic"; cx.font = size + "px sans-serif";
- cx.fillText(word, 0, size * 0.92);
- return canvasToEmbeddedPng(P.pdf, cv).then(function(png){
- c.page.drawImage(png, { x:x, y:c.y - size, width:wPt, height:hPt });
- return wPt;
- });
- }
- // flow styled runs with word wrapping; returns a promise (images/raster are async)
- function pdfFlow(P, runs, startX, fontSize, lineH, baseColor){
- var c = P.cur, maxX = c.pageW - c.margin, x = startX;
- pdfEnsure(P, lineH);
- function nl(){ c.y -= lineH; x = startX; pdfEnsure(P, lineH); }
- var i = 0, words = [], wi = 0, run = null, font = null, size = 0, color = null;
- function nextRun(){
- if (i >= runs.length) return null;
- return runs[i++];
- }
- function step(){
- // advance through words of the current run
- while (run && wi < words.length){
- var word = words[wi++];
- if (/^\s+$/.test(word)){ if (x === startX) continue; word = " "; }
- var ww;
- try { ww = font.widthOfTextAtSize(word, size); }
- catch (e){ var ctx = measureCtx(); ctx.font = size + "px sans-serif"; ww = ctx.measureText(word).width; }
- if (word !== " " && x + ww > maxX && x > startX) nl();
- var px = x;
- x += ww;
- return pdfDrawWord(P, font, word, size, px, color, run.strike).then(function(realW){
- x = px + realW; return step();
- });
- }
- // current run done — get next
- run = nextRun();
- if (!run){ c.y -= lineH; return Promise.resolve(); } // consume final line
- if (run.brk){ nl(); return step(); }
- if (run.image){
- if (x > startX){ c.y -= lineH; x = startX; }
- return pdfDrawImage(P, run.href, startX).then(step);
- }
- font = pdfPickFont(P, run);
- size = run.mono ? fontSize * 0.94 : fontSize;
- color = run.link ? P.col.accent : (run.code ? P.col.code : baseColor);
- words = tokenizeWrap(run.text); wi = 0;
- return step();
- }
- return step();
- }
- function fetchBytes(url){
- return fetch(url).then(function(r){ if (!r.ok) throw new Error("HTTP " + r.status); return r.arrayBuffer(); })
- .then(function(b){ return new Uint8Array(b); });
- }
- function pdfResolveSrc(href){
- if (/^(https?:|data:)/i.test(href)) return href;
- return filepath ? mediaURLFor(href) : href;
- }
- function pdfEmbedBytes(pdf, bytes){
- if (bytes[0] === 0x89 && bytes[1] === 0x50) return pdf.embedPng(bytes);
- if (bytes[0] === 0xFF && bytes[1] === 0xD8) return pdf.embedJpg(bytes);
- return new Promise(function(res, rej){ // gif/webp/svg/bmp → rasterise
- var im = new Image();
- im.onload = function(){
- var cv = document.createElement("canvas");
- cv.width = im.naturalWidth || 300; cv.height = im.naturalHeight || 150;
- cv.getContext("2d").drawImage(im, 0, 0);
- canvasToEmbeddedPng(pdf, cv).then(res, rej);
- };
- im.onerror = function(){ rej(new Error("image decode")); };
- im.src = URL.createObjectURL(new Blob([bytes]));
- });
- }
- function pdfDrawImage(P, href, startX){
- var c = P.cur;
- return fetchBytes(pdfResolveSrc(href)).then(function(bytes){ return pdfEmbedBytes(P.pdf, bytes); }).then(function(img){
- var natW = img.width, natH = img.height;
- var dispW = Math.min(natW, c.pageW - c.margin - startX), dispH = natH * (dispW / natW);
- var maxH = c.pageH - 2 * c.margin;
- if (dispH > maxH){ dispH = maxH; dispW = natW * (dispH / natH); }
- pdfEnsure(P, dispH + 8);
- c.page.drawImage(img, { x:startX, y:c.y - dispH, width:dispW, height:dispH });
- c.y -= dispH + 8;
- }).catch(function(){
- c.page.drawText("[image]", { x:startX, y:c.y - 11, size:11, font:P.fonts.ital, color:P.col.muted });
- c.y -= 18;
- });
- }
- function pdfHeading(P, token){
- var c = P.cur;
- var sizes = [23, 19, 16, 14, 12.5, 11.5], fs = sizes[(token.depth || 1) - 1] || 12;
- c.y -= fs * 0.8;
- return pdfFlow(P, inlineRuns(token.tokens || [{ type:"text", text:token.text }], { bold:true }), c.margin, fs, fs * 1.32, P.col.head)
- .then(function(){
- if ((token.depth || 1) <= 2){ c.y += 4; pdfEnsure(P, 6); pdfRule(P); c.y -= 8; }
- c.y -= fs * 0.25;
- });
- }
- function pdfParagraph(P, token){
- var c = P.cur; c.y -= 3;
- return pdfFlow(P, inlineRuns(token.tokens || [{ type:"text", text:token.text }], {}), c.margin, 11, 16.5, P.col.text)
- .then(function(){ c.y -= 4; });
- }
- function pdfHr(P){ var c = P.cur; c.y -= 8; pdfEnsure(P, 8); pdfRule(P); c.y -= 10; }
- function pdfList(P, token, depth){
- var c = P.cur, indent = c.margin + depth * 18, idx = token.start || 1;
- var chain = Promise.resolve();
- token.items.forEach(function(item){
- var n = idx++;
- chain = chain.then(function(){
- pdfEnsure(P, 11 * 1.5);
- if (item.task){
- 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 });
- } else if (token.ordered){
- 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){}
- } else {
- c.page.drawCircle({ x:indent + 3, y:c.y - 7, size:1.7, color:P.col.text });
- }
- return pdfListItem(P, item, indent + 16, depth);
- });
- });
- return chain.then(function(){ c.y -= 3; });
- }
- function pdfListItem(P, item, startX, depth){
- var toks = item.tokens || [];
- if (toks.length === 0) return pdfFlow(P, inlineRuns([{ type:"text", text:item.text || "" }], {}), startX, 11, 16.5, P.col.text);
- var chain = Promise.resolve();
- toks.forEach(function(t){
- chain = chain.then(function(){
- if (t.type === "list") return pdfList(P, t, depth + 1);
- if (t.type === "code") return pdfCode(P, t, startX);
- if (t.type === "blockquote") return pdfBlockquote(P, t);
- var rr = inlineRuns(t.tokens || [{ type:"text", text:t.text || "" }], {});
- return pdfFlow(P, rr, startX, 11, 16.5, P.col.text);
- });
- });
- return chain;
- }
- function pdfBlockquote(P, token){
- var c = P.cur; c.y -= 3;
- var startY = c.y, startPage = c.page, x = c.margin + 16;
- var chain = Promise.resolve();
- (token.tokens || []).forEach(function(t){
- chain = chain.then(function(){
- if (t.type === "list") return pdfList(P, t, 1);
- if (t.type === "code") return pdfCode(P, t, x);
- var rr = inlineRuns(t.tokens || [{ type:"text", text:t.text || "" }], {});
- return pdfFlow(P, rr, x, 11, 16.5, P.col.muted);
- });
- });
- return chain.then(function(){
- 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 });
- c.y -= 4;
- });
- }
- function pdfCode(P, token, startX){
- var c = P.cur; startX = startX || c.margin;
- var size = 9.5, lh = 12.5, pad = 8, font = P.fonts.mono;
- var charW = font.widthOfTextAtSize("m", size);
- var maxChars = Math.max(8, Math.floor((c.pageW - c.margin - startX - 2 * pad) / charW));
- var lines = [];
- (token.text || "").replace(/\n$/, "").split("\n").forEach(function(ln){
- if (ln.length <= maxChars) lines.push(ln);
- else for (var i = 0; i < ln.length; i += maxChars) lines.push(ln.substr(i, maxChars));
- });
- if (lines.length === 0) lines = [""];
- c.y -= 4;
- var chain = Promise.resolve();
- lines.forEach(function(txt){
- chain = chain.then(function(){
- pdfEnsure(P, lh);
- c.page.drawRectangle({ x:startX, y:c.y - lh + 2, width:c.pageW - c.margin - startX, height:lh, color:P.col.codebg });
- try { c.page.drawText(txt, { x:startX + pad, y:c.y - lh + 3.5, size:size, font:font, color:P.col.code }); return; }
- catch (e){ return pdfDrawRasterWord(P, txt, size, startX + pad, P.col.code).then(function(){}); }
- }).then(function(){ c.y -= lh; });
- });
- return chain.then(function(){ c.y -= 6; });
- }
- function pdfTable(P, token){
- var c = P.cur; c.y -= 4;
- var cols = (token.header && token.header.length) || 1;
- var colW = (c.pageW - 2 * c.margin) / cols, size = 10, pad = 5, rowH = 18;
- function fit(font, txt, maxW){
- try { if (font.widthOfTextAtSize(txt, size) <= maxW) return txt; } catch (e){ return txt; }
- var s = txt;
- while (s.length > 1){ s = s.slice(0, -1); try { if (font.widthOfTextAtSize(s + "…", size) <= maxW) return s + "…"; } catch (e){ break; } }
- return s;
- }
- function row(cells, header){
- pdfEnsure(P, rowH);
- var x = c.margin;
- for (var i = 0; i < cols; i++){
- var cell = cells[i] || { text:"" };
- if (header) c.page.drawRectangle({ x:x, y:c.y - rowH, width:colW, height:rowH, color:P.col.thead });
- c.page.drawRectangle({ x:x, y:c.y - rowH, width:colW, height:rowH, borderWidth:0.6, borderColor:P.col.tline });
- var f = header ? P.fonts.bold : P.fonts.reg;
- var txt = fit(f, decodeEntities(cell.text || ""), colW - 2 * pad);
- try { c.page.drawText(txt, { x:x + pad, y:c.y - rowH + 6, size:size, font:f, color:P.col.text }); } catch (e){}
- x += colW;
- }
- c.y -= rowH;
- }
- row(token.header, true);
- (token.rows || []).forEach(function(r){ row(r, false); });
- c.y -= 6;
- }
- function pdfRenderTokens(P, tokens){
- var chain = Promise.resolve();
- tokens.forEach(function(t){
- chain = chain.then(function(){
- switch (t.type){
- case "heading": return pdfHeading(P, t);
- case "paragraph": return pdfParagraph(P, t);
- case "list": return pdfList(P, t, 0);
- case "blockquote": return pdfBlockquote(P, t);
- case "code": return pdfCode(P, t, P.cur.margin);
- case "hr": pdfHr(P); return;
- case "table": return pdfTable(P, t);
- case "space": P.cur.y -= 6; return;
- case "html": return;
- default: if (t.tokens) return pdfParagraph(P, t); if (t.text) return pdfParagraph(P, { text:t.text }); return;
- }
- });
- });
- return chain;
- }
- function pdfBuild(){
- var L = PDFLib, SF = L.StandardFonts, pdf;
- return L.PDFDocument.create().then(function(d){
- pdf = d;
- return Promise.all([
- pdf.embedFont(SF.Helvetica), pdf.embedFont(SF.HelveticaBold),
- pdf.embedFont(SF.HelveticaOblique), pdf.embedFont(SF.HelveticaBoldOblique),
- pdf.embedFont(SF.Courier), pdf.embedFont(SF.CourierBold)
- ]);
- }).then(function(f){
- var P = { pdf:pdf, col:PDF_COLORS(), fonts:{
- reg:f[0], bold:f[1], ital:f[2], bi:f[3], mono:f[4], monoBold:f[5]
- }, cur:null };
- P.cur = pdfNewCursor(P);
- if (isTxtMode){
- var chain = Promise.resolve();
- plain.value.split("\n").forEach(function(ln){
- chain = chain.then(function(){ return pdfFlow(P, [mkRun(ln || " ", { mono:true })], P.cur.margin, 10, 13.5, P.col.text); });
- });
- return chain.then(function(){ return pdf.save(); });
- }
- return pdfRenderTokens(P, marked.lexer(isRtfMode ? richMarkdown() : getContent())).then(function(){ return pdf.save(); });
- });
- }
- // ════════════════════════════════════════════════════════════════════════
- // Settings panel
- // ════════════════════════════════════════════════════════════════════════
- function openSettings(){ syncSettingsUI(); $("#settings-overlay").addClass("show"); }
- function closeSettings(){ $("#settings-overlay").removeClass("show"); }
- $(function(){
- $("#settings-overlay").on("click", function(e){ if (e.target === this) closeSettings(); });
- $("#link-overlay").on("click", function(e){ if (e.target === this) linkDlgCancel(); });
- });
- function showSection(sec){
- $(".nav-item").removeClass("active");
- $('.nav-item[data-sec="'+sec+'"]').addClass("active");
- $(".settings-section").removeClass("active");
- $("#sec-" + sec).addClass("active");
- }
- function syncSettingsUI(){
- $("#set-dark").prop("checked", isDark);
- $("#set-font").val(settings.font);
- $("#set-fontsize").val(settings.fontSize);
- $("#set-lh").val(settings.lineHeight);
- $("#set-syntax").val(settings.syntax);
- $("#set-imgdir").val(settings.imgDir);
- $("#set-compress").prop("checked", settings.compress);
- $("#set-quality").val(settings.quality);
- $("#quality-val").text(settings.quality + "%");
- $("#set-maxw").val(settings.maxWidth);
- $("#seg-mode button").removeClass("active");
- $('#seg-mode button[data-mode="'+modeName()+'"]').addClass("active");
- onCompressToggle(true);
- }
- function applyTypography(){
- settings.font = $("#set-font").val() || settings.font;
- settings.fontSize = parseInt($("#set-fontsize").val()) || settings.fontSize;
- settings.lineHeight = $("#set-lh").val() || settings.lineHeight;
- var fam = FONT_MAP[settings.font] || FONT_MAP.system;
- [rich, plain].forEach(function(el){
- el.style.fontFamily = (el === plain ? FONT_MAP.mono : fam);
- el.style.fontSize = (el === plain ? (settings.fontSize - 1) : settings.fontSize) + "px";
- el.style.lineHeight = settings.lineHeight;
- });
- savePrefs();
- }
- function saveImgPrefs(){
- settings.imgDir = $("#set-imgdir").val().trim() || "img/{name}";
- settings.quality = parseInt($("#set-quality").val()) || 80;
- settings.maxWidth = parseInt($("#set-maxw").val()); if (isNaN(settings.maxWidth)) settings.maxWidth = 0;
- settings.compress = $("#set-compress").prop("checked");
- savePrefs();
- }
- function onCompressToggle(silent){
- settings.compress = $("#set-compress").prop("checked");
- var on = settings.compress;
- $("#row-quality").css("display", on ? "" : "none");
- $("#row-maxw").css("display", on ? "" : "none");
- if (!silent) saveImgPrefs();
- }
- function onQualityInput(){
- $("#quality-val").text($("#set-quality").val() + "%");
- }
- // ════════════════════════════════════════════════════════════════════════
- // Theme
- // ════════════════════════════════════════════════════════════════════════
- function setTheme(dark){
- isDark = dark;
- document.body.classList.toggle("dark", isDark);
- $("#icon-sun").toggle(!isDark); $("#icon-moon").toggle(isDark);
- $("#set-dark").prop("checked", isDark);
- try { ao_module_setWindowTheme(isDark ? "dark" : "light"); } catch(e){}
- savePrefs();
- }
- function toggleTheme(){ setTheme(!isDark); }
- // ════════════════════════════════════════════════════════════════════════
- // Preferences persistence (localStorage + ao_module_storage)
- // ════════════════════════════════════════════════════════════════════════
- function prefsObject(){
- return { settings: settings, keymap: keymap, isDark: isDark };
- }
- function savePrefs(){
- var json = JSON.stringify(prefsObject());
- try { localStorage.setItem("text_prefs", json); } catch(e){}
- try { ao_module_storage.setStorage("Text", "prefs", json); } catch(e){}
- }
- function applyPrefs(obj){
- if (!obj) return;
- if (obj.settings) for (var k in obj.settings) settings[k] = obj.settings[k];
- if (obj.keymap){
- keymap = JSON.parse(JSON.stringify(DEFAULT_KEYS));
- for (var a in obj.keymap) if (a in keymap) keymap[a] = obj.keymap[a];
- }
- if (typeof obj.isDark === "boolean") setTheme(obj.isDark);
- }
- function loadPrefs(){
- var local = null;
- try { local = JSON.parse(localStorage.getItem("text_prefs")); } catch(e){}
- if (local) applyPrefs(local);
- // async server copy (per-user) overrides local if present
- try {
- ao_module_storage.loadStorage("Text", "prefs", function(val){
- if (val && typeof val === "string" && val.charAt(0) === "{"){
- try {
- var obj = JSON.parse(val);
- applyPrefs(obj);
- buildKeyList(); syncSettingsUI(); applyTypography();
- } catch(e){}
- }
- });
- } catch(e){}
- }
- // ════════════════════════════════════════════════════════════════════════
- // Status bar, title, dirty tracking
- // ════════════════════════════════════════════════════════════════════════
- function markDirty(){ if (!dirtyFlag){ dirtyFlag = true; updateTitle(); } }
- function isDirty(){ return dirtyFlag; }
- function updateTitle(){
- var title = !filepath ? "Untitled" : (isDirty() ? filename + " — Edited" : filename);
- try { ao_module_setWindowTitle(title); } catch(e){}
- document.title = title;
- if (isDirty()) setStatus("Unsaved changes", "dirty");
- else if (filepath) setStatus("Saved");
- else setStatus("Ready");
- }
- function setStatus(msg, cls){
- var el = $("#status-msg");
- el.text(msg).attr("class", cls || "");
- if (cls === "error") setTimeout(updateTitle, 3500);
- }
- function updateStatBar(){
- var txt = isTxtMode ? plain.value : richPlainText();
- var words = txt.trim() ? txt.trim().split(/\s+/).length : 0;
- var chars = txt.length;
- $("#stat-count").text(words + " word" + (words !== 1 ? "s" : "") + " · " + chars + " chars");
- }
- // ════════════════════════════════════════════════════════════════════════
- // Menus / busy / dialog
- // ════════════════════════════════════════════════════════════════════════
- function toggleMenu(id){
- var m = document.getElementById(id);
- var show = !m.classList.contains("show");
- hideMenus();
- if (show){ m.classList.add("show"); positionMenu(m); }
- }
- // position a fixed dropdown just below its trigger, right-aligned, so it is not
- // clipped by the toolbar's horizontal-scroll overflow
- function positionMenu(m){
- var btn = m.parentElement.querySelector(".tb-btn");
- if (!btn) return;
- var r = btn.getBoundingClientRect();
- m.style.top = (r.bottom + 4) + "px";
- m.style.left = "auto";
- m.style.right = Math.max(6, window.innerWidth - r.right) + "px";
- }
- function hideMenus(){ $(".menu").removeClass("show"); }
- function showBusy(msg){ $("#busy-msg").text(msg || "Working…"); $("#busy").addClass("show"); }
- function hideBusy(){ $("#busy").removeClass("show"); }
- // ── helpers ─────────────────────────────────────────────────────────────
- function escapeHtml(s){ return String(s).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"); }
- function escapeAttr(s){ return escapeHtml(s).replace(/"/g,"""); }
- function debounce(fn, ms){ var t; return function(){ clearTimeout(t); var a=arguments,c=this; t=setTimeout(function(){ fn.apply(c,a); }, ms); }; }
- // ════════════════════════════════════════════════════════════════════════
- // Close handling (unsaved changes)
- // ════════════════════════════════════════════════════════════════════════
- function showDialog(cb){ dlgCallback = cb; $("#confirm-overlay").addClass("show"); }
- function hideDialog(){ $("#confirm-overlay").removeClass("show"); }
- function dlgCancel(){ var cb=dlgCallback; hideDialog(); dlgCallback=null; if(cb) cb("cancel"); }
- function dlgDiscard(){ var cb=dlgCallback; hideDialog(); dlgCallback=null; if(cb) cb("discard"); }
- function dlgSave(){
- pendingClose = dlgCallback; dlgCallback = null; hideDialog();
- if (!filepath){
- var def = defaultNewName();
- ao_module_openFileSelector(handleDlgSaveAs, "user:/Desktop", "new", false, { defaultName: def });
- } else {
- doSave(function(){ if (pendingClose){ pendingClose("saved"); pendingClose=null; } });
- }
- }
- function handleDlgSaveAs(fd){
- if (!fd || !fd.length){ pendingClose = null; return; }
- filepath = fd[0].filepath; filename = fd[0].filename;
- doSave(function(){ if (pendingClose){ pendingClose("saved"); pendingClose=null; } });
- }
- function ao_module_close(){
- if (!isDirty()){ ao_module_closeHandler(); return; }
- showDialog(function(result){
- if (result === "saved" || result === "discard") ao_module_closeHandler();
- });
- }
- if (!ao_module_virtualDesktop){
- window.onbeforeunload = function(){ if (isDirty()) return "You have unsaved changes. Leave anyway?"; };
- }
- </script>
- </body>
- </html>
|