docs.js 257 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571
  1. /*
  2. ArozOS Office - Docs (word processor)
  3. =====================================
  4. Requires (loaded by index.html): jquery, ao_module, ../common/office.js,
  5. ../common/lib/marked.min.js (Markdown import).
  6. Envelope "body" schema (what serialize() returns / deserialize() accepts):
  7. {
  8. html: "<sanitized editor innerHTML>", // rich text content
  9. page: {
  10. size: "A4" | "Letter" | "Legal",
  11. orientation: "portrait" | "landscape",
  12. margins: { top: 20, right: 20, bottom: 20, left: 20 } // millimetres
  13. },
  14. header: "plain text repeated in every page's top margin",
  15. footer: "plain text repeated in every page's bottom margin",
  16. hfMode: "all" | "except-first" | "none", // which pages show them
  17. pageNumbers: false, // print page numbers (best-effort @page margin box)
  18. comments: [ { id, text, at, resolved } ], // review comments; anchored
  19. // in html as <span class="doc-cmt" data-cid>
  20. trackChanges: false // "suggest edits" mode; pending suggestions
  21. // live in html as ins.doc-ins / del.doc-del
  22. }
  23. Notes:
  24. - html is produced by cleanedHtml(): find/replace highlight spans and
  25. image-selection classes are stripped before serialisation.
  26. - Known allowed classes inside html: doc-title (title paragraph),
  27. of-checklist (on UL), checked (on LI), of-table (on TABLE),
  28. doc-cmt (comment anchor), doc-ins / doc-del (tracked changes),
  29. doc-pagebreak (explicit page break block; exports as a real
  30. <w:br w:type="page"/> and is sized on screen by layoutPageBreaks).
  31. - The .docx keeps comments and suggestions as Word comments and
  32. tracked changes (mod/office docx/review.go). Foreign exports
  33. (odt/html/md/txt) use resolvedHtml(): suggestions applied as if
  34. accepted, comment anchors unwrapped.
  35. */
  36. (function () {
  37. "use strict";
  38. /* ================= constants ================= */
  39. var PAGE_SIZES = {
  40. "A4": { w: 210, h: 297 },
  41. "Letter": { w: 215.9, h: 279.4 },
  42. "Legal": { w: 215.9, h: 355.6 }
  43. };
  44. // OfficeFonts (common/fonts.js) owns the list so that the families the
  45. // suite ships with itself are on it - see the note there
  46. var FONTS = OfficeFonts.MENU;
  47. var FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
  48. var LINE_SPACINGS = ["1", "1.15", "1.5", "2"];
  49. // which pages carry the header / footer text
  50. var HF_MODES = ["all", "except-first", "none"];
  51. var PARA_STYLES = [
  52. { v: "p", label: "Normal text" },
  53. { v: "title", label: "Title" },
  54. { v: "h1", label: "Heading 1" },
  55. { v: "h2", label: "Heading 2" },
  56. { v: "h3", label: "Heading 3" },
  57. { v: "h4", label: "Heading 4" }
  58. ];
  59. // (a column section and a page spacer are layout, not blocks of the text)
  60. var BLOCK_SEL = "p,h1,h2,h3,h4,h5,h6,li,blockquote,pre,div:not(.doc-colsec):not(.doc-autobreak)";
  61. /* Special characters palette - every glyph is generated at runtime from
  62. code points (never a literal emoji in this source file). */
  63. var CHAR_TABS = [
  64. { name: "Smileys", cps: [
  65. 0x1F600, 0x1F601, 0x1F602, 0x1F603, 0x1F604, 0x1F605, 0x1F606, 0x1F607,
  66. 0x1F609, 0x1F60A, 0x1F60B, 0x1F60D, 0x1F60E, 0x1F60F, 0x1F610, 0x1F612,
  67. 0x1F614, 0x1F618, 0x1F61C, 0x1F621, 0x1F622, 0x1F625, 0x1F62D, 0x1F631,
  68. 0x1F634, 0x1F637, 0x1F642, 0x1F643, 0x1F644, 0x1F914, 0x1F917, 0x1F929,
  69. 0x1F970, 0x1F973, 0x1F44D, 0x1F44E, 0x1F44F, 0x1F64F, 0x1F4AA, 0x1F389] },
  70. { name: "Objects", cps: [
  71. 0x1F4C1, 0x1F4C2, 0x1F4C4, 0x1F4C5, 0x1F4C8, 0x1F4C9, 0x1F4CA, 0x1F4CB,
  72. 0x1F4CC, 0x1F4CD, 0x1F4CE, 0x1F4DD, 0x1F4E6, 0x1F4E7, 0x1F4F1, 0x1F4BB,
  73. 0x1F4BE, 0x1F4BC, 0x1F50D, 0x1F511, 0x1F512, 0x1F513, 0x1F514, 0x1F4A1,
  74. 0x1F527, 0x1F528, 0x2699, 0x23F0, 0x1F3C6, 0x2B50, 0x2764, 0x2705,
  75. 0x274C, 0x26A0, 0x2B55, 0x1F6A9] },
  76. { name: "Arrows", cps: [
  77. 0x2190, 0x2191, 0x2192, 0x2193, 0x2194, 0x2195, 0x2196, 0x2197,
  78. 0x2198, 0x2199, 0x21A9, 0x21AA, 0x21B5, 0x21C4, 0x21C6, 0x21D0,
  79. 0x21D1, 0x21D2, 0x21D3, 0x21D4, 0x2794, 0x27A1, 0x2B05, 0x2B06,
  80. 0x2B07, 0x2B95, 0x21E7, 0x21E9] },
  81. { name: "Math", cps: [
  82. 0x00B1, 0x00D7, 0x00F7, 0x2212, 0x2260, 0x2264, 0x2265, 0x2248,
  83. 0x221E, 0x2211, 0x220F, 0x221A, 0x222B, 0x2202, 0x2206, 0x2207,
  84. 0x03C0, 0x03B1, 0x03B2, 0x03B3, 0x03B8, 0x03BB, 0x03BC, 0x03C3,
  85. 0x03C6, 0x03A9, 0x2208, 0x2209, 0x2229, 0x222A, 0x2282, 0x2283,
  86. 0x2200, 0x2203, 0x00B0, 0x00B2, 0x00B3, 0x00BD, 0x00BC, 0x00BE,
  87. 0x2032, 0x2033] },
  88. { name: "Symbols", cps: [
  89. 0x00A9, 0x00AE, 0x2122, 0x00A7, 0x00B6, 0x2020, 0x2021, 0x2022,
  90. 0x2026, 0x2030, 0x20AC, 0x00A3, 0x00A5, 0x00A2, 0x00A1, 0x00BF,
  91. 0x00AB, 0x00BB, 0x2018, 0x2019, 0x201C, 0x201D, 0x2013, 0x2014,
  92. 0x2713, 0x2717, 0x2605, 0x2606, 0x25CF, 0x25CB, 0x25A0, 0x25A1,
  93. 0x2660, 0x2663, 0x2665, 0x2666, 0x266A, 0x266B] }
  94. ];
  95. /* ================= state ================= */
  96. var editor, headerEl, footerEl, pageEl, workspaceEl;
  97. var savedRange = null; // last selection range inside the editor
  98. var selectedImg = null; // currently selected <img>
  99. var imgHandle = null; // floating resize handle element
  100. var pageConf = defaultPageConf();
  101. var undo = null;
  102. var countTimer = null;
  103. var stateTimer = null;
  104. var $fontSel, $sizeSel, $styleSel;
  105. var findState = { hits: [], cur: -1 };
  106. var hfClones = []; // header/footer copies for pages 2..n
  107. var hfContent = { header: "", footer: "" }; // header/footer HTML
  108. var footnotes = {}; // footnote id -> HTML (body.footnotes)
  109. var comments = []; // review comments [{id,text,at,resolved}]
  110. var suggesting = false; // track-changes ("suggest edits") mode
  111. function defaultPageConf() {
  112. return {
  113. size: "A4",
  114. orientation: "portrait",
  115. margins: { top: 20, right: 20, bottom: 20, left: 20 },
  116. headerDist: 12.7, // header distance from the top edge, mm
  117. footerDist: 12.7, // footer distance from the bottom edge, mm
  118. lineSpacing: 1.15, // multiple of single spacing for paragraphs
  119. // that do not state their own (data-ls)
  120. pageNumbers: false,
  121. hfMode: "all", // header/footer on: all | except-first | none
  122. columns: 1, // 1-3 text columns (2 = IEEE-style)
  123. colGap: 8 // gap between columns, mm
  124. };
  125. }
  126. function num(v, def) {
  127. var n = parseFloat(v);
  128. return isNaN(n) ? def : n;
  129. }
  130. function esc(t) { return OfficeApp.escapeHtml(t); }
  131. /* ================= selection helpers ================= */
  132. function trackSelection() {
  133. document.addEventListener("selectionchange", function () {
  134. var sel = window.getSelection();
  135. if (sel && sel.rangeCount > 0) {
  136. var r = sel.getRangeAt(0);
  137. if (editor.contains(r.commonAncestorContainer)) {
  138. savedRange = r.cloneRange();
  139. scheduleToolbarState();
  140. scheduleTocOverlay();
  141. } else if (tocOverlay && tocOverlay.style.display !== "none") {
  142. scheduleTocOverlay();
  143. }
  144. }
  145. });
  146. }
  147. function restoreSel() {
  148. editor.focus();
  149. if (savedRange) {
  150. var sel = window.getSelection();
  151. sel.removeAllRanges();
  152. sel.addRange(savedRange);
  153. }
  154. }
  155. function placeCaretAtEnd() {
  156. try {
  157. var r = document.createRange();
  158. r.selectNodeContents(editor);
  159. r.collapse(false);
  160. var sel = window.getSelection();
  161. sel.removeAllRanges();
  162. sel.addRange(r);
  163. savedRange = r.cloneRange();
  164. } catch (e) { }
  165. }
  166. function inHeaderFooter() {
  167. var ae = document.activeElement;
  168. return !!(ae && ae.classList && ae.classList.contains("doc-hf"));
  169. }
  170. function getSelectedBlocks() {
  171. var out = [];
  172. var range = null;
  173. var sel = window.getSelection();
  174. if (sel && sel.rangeCount > 0 && editor.contains(sel.getRangeAt(0).commonAncestorContainer)) {
  175. range = sel.getRangeAt(0);
  176. } else {
  177. range = savedRange;
  178. }
  179. if (!range) return out;
  180. if (range.collapsed) {
  181. var n = range.startContainer;
  182. while (n && n !== editor) {
  183. if (n.nodeType === 1 && n.matches && n.matches(BLOCK_SEL)) { out.push(n); break; }
  184. n = n.parentNode;
  185. }
  186. return out;
  187. }
  188. var cand = editor.querySelectorAll(BLOCK_SEL);
  189. for (var i = 0; i < cand.length; i++) {
  190. try { if (range.intersectsNode(cand[i])) out.push(cand[i]); } catch (e) { }
  191. }
  192. // keep only the deepest blocks (drop ancestors of other selected blocks)
  193. return out.filter(function (b) {
  194. for (var j = 0; j < out.length; j++) {
  195. if (out[j] !== b && b.contains(out[j])) return false;
  196. }
  197. return true;
  198. });
  199. }
  200. /* ================= sanitizer ================= */
  201. function sanitizeHtml(html, opts) {
  202. opts = opts || {};
  203. var doc;
  204. try {
  205. doc = new DOMParser().parseFromString(String(html || ""), "text/html");
  206. } catch (e) { return ""; }
  207. var root = doc.body;
  208. var bad = root.querySelectorAll(
  209. "script,style,link,meta,base,iframe,frame,frameset,object,embed,applet,form,noscript,title,svg foreignObject");
  210. var i;
  211. for (i = bad.length - 1; i >= 0; i--) {
  212. if (bad[i].parentNode) bad[i].parentNode.removeChild(bad[i]);
  213. }
  214. // layout-only pieces copied out of a paginated document
  215. var layout = root.querySelectorAll(".doc-autobreak");
  216. for (i = layout.length - 1; i >= 0; i--) {
  217. if (layout[i].parentNode) layout[i].parentNode.removeChild(layout[i]);
  218. }
  219. var all = root.querySelectorAll("*");
  220. for (i = 0; i < all.length; i++) {
  221. var el = all[i];
  222. el.removeAttribute("data-split");
  223. el.removeAttribute("data-split-of");
  224. el.removeAttribute("data-pair");
  225. // the PNG a save rendered for the writers, not part of the text
  226. el.removeAttribute("data-export-src");
  227. el.classList.remove("doc-split-head", "doc-split-tail");
  228. for (var a = el.attributes.length - 1; a >= 0; a--) {
  229. var at = el.attributes[a];
  230. var n = at.name.toLowerCase();
  231. if (n.indexOf("on") === 0) {
  232. el.removeAttribute(at.name);
  233. } else if ((n === "href" || n === "src" || n === "xlink:href" || n === "action" || n === "formaction") &&
  234. /^\s*(javascript|vbscript|data\s*:\s*text\/html)/i.test(at.value)) {
  235. el.removeAttribute(at.name);
  236. } else if (!opts.keepClasses && (n === "class" || n === "id")) {
  237. el.removeAttribute(at.name);
  238. }
  239. }
  240. }
  241. return root.innerHTML;
  242. }
  243. /* ================= serialize / deserialize ================= */
  244. /* Everything the layout engine computes (px line heights, tab widths,
  245. list markers, spacer elements) is derived from the document and made
  246. again on load - it is never saved. */
  247. function stripLayoutArtifacts(root) {
  248. removeAutoBreaks(root);
  249. DocsLayout.restoreTablePadding(root);
  250. DocsLayout.restorePictureLines(root);
  251. var styled = root.querySelectorAll("[style]");
  252. for (var i = 0; i < styled.length; i++) {
  253. var el = styled[i];
  254. el.style.lineHeight = "";
  255. if (el.classList.contains("doc-tab")) {
  256. el.style.width = "";
  257. el.style.display = "";
  258. }
  259. if (el.classList.contains("doc-pagebreak")) el.style.height = "";
  260. if (!el.getAttribute("style")) el.removeAttribute("style");
  261. }
  262. var marked = root.querySelectorAll("[data-marker],[data-n],[data-leader]");
  263. for (i = 0; i < marked.length; i++) {
  264. marked[i].removeAttribute("data-marker");
  265. marked[i].removeAttribute("data-n");
  266. marked[i].removeAttribute("data-leader");
  267. }
  268. }
  269. function cleanedHtml() {
  270. var clone = editor.cloneNode(true);
  271. // strip layout-only spacers and computed layout values
  272. stripLayoutArtifacts(clone);
  273. // strip find highlight spans
  274. var hits = clone.querySelectorAll("span.of-find-hit");
  275. for (var i = 0; i < hits.length; i++) {
  276. var s = hits[i];
  277. while (s.firstChild) s.parentNode.insertBefore(s.firstChild, s);
  278. s.parentNode.removeChild(s);
  279. }
  280. // strip image selection marker
  281. var imgs = clone.querySelectorAll("img.of-selimg");
  282. for (i = 0; i < imgs.length; i++) {
  283. imgs[i].classList.remove("of-selimg");
  284. if (!imgs[i].getAttribute("class")) imgs[i].removeAttribute("class");
  285. }
  286. // after every style change above: Firefox would drop it again
  287. imgs = clone.querySelectorAll("img[data-crop]");
  288. for (i = 0; i < imgs.length; i++) canonicalCrop(imgs[i]);
  289. clone.normalize();
  290. return clone.innerHTML;
  291. }
  292. function hfText(html) {
  293. var div = document.createElement("div");
  294. div.innerHTML = html || "";
  295. var f = div.querySelectorAll(".doc-field");
  296. for (var i = 0; i < f.length; i++) f[i].parentNode.removeChild(f[i]);
  297. return (div.textContent || "").replace(/\s+/g, " ").trim();
  298. }
  299. // header/footer HTML worth saving as rich content: anything beyond a
  300. // single run of plain text
  301. function hfIsRich(html) {
  302. return /<(p|div|h\d|img|span|b|i|u|table|ul|ol|br)\b/i.test(html || "");
  303. }
  304. function currentBody() {
  305. return {
  306. html: cleanedHtml(),
  307. page: {
  308. size: pageConf.size,
  309. orientation: pageConf.orientation,
  310. margins: {
  311. top: pageConf.margins.top, right: pageConf.margins.right,
  312. bottom: pageConf.margins.bottom, left: pageConf.margins.left
  313. },
  314. columns: pageConf.columns,
  315. colGap: pageConf.colGap,
  316. headerDist: pageConf.headerDist,
  317. footerDist: pageConf.footerDist
  318. },
  319. header: hfText(hfContent.header),
  320. footer: hfText(hfContent.footer),
  321. headerHtml: hfIsRich(hfContent.header) ? hfContent.header : undefined,
  322. footerHtml: hfIsRich(hfContent.footer) ? hfContent.footer : undefined,
  323. footnotes: currentFootnotes(),
  324. lineSpacing: docLineSpacing(),
  325. hfMode: pageConf.hfMode,
  326. pageNumbers: !!pageConf.pageNumbers,
  327. comments: JSON.parse(JSON.stringify(comments)),
  328. trackChanges: suggesting
  329. };
  330. }
  331. // the footnotes the text still references, in reference order
  332. function currentFootnotes() {
  333. var out = [];
  334. var seen = {};
  335. var refs = editor.querySelectorAll("sup.doc-fnref");
  336. for (var i = 0; i < refs.length; i++) {
  337. var id = refs[i].getAttribute("data-fn");
  338. if (seen[id]) continue;
  339. seen[id] = true;
  340. out.push({ id: id, html: footnotes[id] || "" });
  341. }
  342. return out.length ? out : undefined;
  343. }
  344. function loadBody(b) {
  345. b = b || {};
  346. dirtyFromY = null;
  347. lastPages = [];
  348. closeFind();
  349. deselectImage();
  350. editor.innerHTML = sanitizeHtml(b.html || "<p><br></p>", { keepClasses: true }) || "<p><br></p>";
  351. upgradeCrops(editor);
  352. normalizePageBreaks();
  353. hfContent.header = b.headerHtml ? sanitizeHtml(b.headerHtml, { keepClasses: true }) : esc(b.header || "");
  354. hfContent.footer = b.footerHtml ? sanitizeHtml(b.footerHtml, { keepClasses: true }) : esc(b.footer || "");
  355. headerEl.innerHTML = hfContent.header;
  356. footerEl.innerHTML = hfContent.footer;
  357. footnotes = {};
  358. (Array.isArray(b.footnotes) ? b.footnotes : []).forEach(function (fn) {
  359. if (fn && fn.id !== undefined) footnotes[String(fn.id)] = sanitizeHtml(fn.html || "", { keepClasses: true });
  360. });
  361. var p = b.page || {};
  362. pageConf.size = PAGE_SIZES[p.size] ? p.size : "A4";
  363. pageConf.orientation = (p.orientation === "landscape") ? "landscape" : "portrait";
  364. var m = p.margins || {};
  365. pageConf.margins = {
  366. top: num(m.top, 20), right: num(m.right, 20),
  367. bottom: num(m.bottom, 20), left: num(m.left, 20)
  368. };
  369. pageConf.columns = Math.min(3, Math.max(1, Math.round(num(p.columns, 1))));
  370. pageConf.colGap = Math.min(30, Math.max(2, num(p.colGap, 8)));
  371. pageConf.headerDist = Math.min(80, Math.max(0, num(p.headerDist, 12.7)));
  372. pageConf.footerDist = Math.min(80, Math.max(0, num(p.footerDist, 12.7)));
  373. pageConf.lineSpacing = Math.min(5, Math.max(0.5, num(b.lineSpacing, 1.15)));
  374. pageConf.pageNumbers = !!b.pageNumbers;
  375. pageConf.hfMode = (HF_MODES.indexOf(b.hfMode) >= 0) ? b.hfMode : "all";
  376. comments = Array.isArray(b.comments) ?
  377. JSON.parse(JSON.stringify(b.comments)) : [];
  378. suggesting = !!b.trackChanges;
  379. // fonts the document names that this machine lacks get a stand-in
  380. // with the original's width and line metrics, so lines and pages
  381. // break where they did in Word; once it is in, lay out again
  382. if (window.OfficeFonts && OfficeFonts.substitute) {
  383. OfficeFonts.substitute(OfficeFonts.familiesIn((b.html || "") + (b.headerHtml || "") +
  384. (b.footerHtml || "") + JSON.stringify(b.footnotes || []))).then(function (changed) {
  385. if (!changed) return;
  386. DocsLayout.clearMetrics();
  387. scheduleRelayout();
  388. });
  389. }
  390. applyPageSetup();
  391. updateCounts();
  392. renderCommentsPanel();
  393. updateSuggestStatus();
  394. }
  395. /* ================= undo / redo ================= */
  396. function snapshot() {
  397. return JSON.stringify(currentBody());
  398. }
  399. function applySnapshot(s) {
  400. try {
  401. loadBody(JSON.parse(s));
  402. } catch (e) { return; }
  403. OfficeApp.markDirty();
  404. placeCaretAtEnd();
  405. updateToolbarState();
  406. }
  407. function doUndo() { undo.flushDebounced(snapshot); undo.undo(); }
  408. function doRedo() { undo.redo(); }
  409. /* after any user edit: dirty flag, counters, undo bookkeeping */
  410. function afterEdit(immediate) {
  411. upgradeCrops(editor);
  412. OfficeApp.markDirty();
  413. scheduleCounts();
  414. scheduleToolbarState();
  415. if (immediate) undo.push(snapshot());
  416. else undo.pushDebounced(snapshot, 600);
  417. }
  418. /* ================= editing commands ================= */
  419. var PICTURE_ALIGN = { justifyLeft: "left", justifyCenter: "center", justifyRight: "right", justifyFull: "justify" };
  420. function exec(cmd, val) {
  421. if (inHeaderFooter()) return; // header/footer are plain text only
  422. // a selected picture is aligned as a picture (see alignPicture)
  423. if (selectedImg && PICTURE_ALIGN[cmd] && editor.contains(selectedImg)) {
  424. alignPicture(selectedImg, PICTURE_ALIGN[cmd]);
  425. return;
  426. }
  427. restoreSel();
  428. try {
  429. document.execCommand(cmd, false, val === undefined ? null : val);
  430. } catch (e) { }
  431. afterEdit(true);
  432. }
  433. /* execCommand("fontName") writes <font face="...">, naming one family and
  434. nothing else - a character that family has no glyph for then falls to
  435. whatever the machine happens to have. Tag the new nodes, then rewrite
  436. them to carry the full stack from OfficeFonts, so the shipped faces
  437. are behind every choice the user makes. */
  438. var FONT_MARK = "__ofdocfont__";
  439. function applyFontFamily(name, noCommit) {
  440. if (inHeaderFooter()) return;
  441. restoreSel();
  442. var stack = OfficeFonts.stack(name);
  443. try {
  444. // styleWithCSS is on for the editor, which would make this a
  445. // span whose font-family is the marker instead of a <font face>
  446. document.execCommand("styleWithCSS", false, false);
  447. document.execCommand("fontName", false, FONT_MARK);
  448. } catch (e) { }
  449. try { document.execCommand("styleWithCSS", false, true); } catch (e) { }
  450. var tagged = editor.querySelectorAll("font[face], [style*='font-family']");
  451. for (var i = 0; i < tagged.length; i++) {
  452. var el = tagged[i];
  453. var isMark = el.getAttribute("face") === FONT_MARK ||
  454. (el.style.fontFamily || "").indexOf(FONT_MARK) >= 0;
  455. if (!isMark) continue;
  456. el.removeAttribute("face");
  457. el.style.fontFamily = stack;
  458. // runs inside that name their own font (imported text) would win
  459. var inner = el.querySelectorAll("font[face], [style*='font-family']");
  460. for (var j = 0; j < inner.length; j++) {
  461. inner[j].removeAttribute("face");
  462. inner[j].style.removeProperty("font-family");
  463. if (!inner[j].getAttribute("style")) inner[j].removeAttribute("style");
  464. }
  465. }
  466. if (!noCommit) afterEdit(true);
  467. }
  468. /* wrapSelection puts the selected text in spans of its own and hands
  469. them back: execCommand marks it with the one size nothing else uses,
  470. in as many pieces as the markup needs, and the marks become spans.
  471. The selection is left over the new spans. */
  472. function wrapSelection() {
  473. try {
  474. document.execCommand("styleWithCSS", false, false);
  475. document.execCommand("fontSize", false, "7");
  476. } catch (e) { }
  477. try { document.execCommand("styleWithCSS", false, true); } catch (e) { }
  478. var out = [], i;
  479. var fonts = editor.querySelectorAll('font[size="7"]');
  480. for (i = 0; i < fonts.length; i++) {
  481. var f = fonts[i];
  482. var span = document.createElement("span");
  483. while (f.firstChild) span.appendChild(f.firstChild);
  484. f.parentNode.replaceChild(span, f);
  485. out.push(span);
  486. }
  487. var spans = editor.querySelectorAll("span");
  488. for (i = 0; i < spans.length; i++) {
  489. if (spans[i].style && spans[i].style.fontSize === "xxx-large") {
  490. spans[i].style.fontSize = "";
  491. out.push(spans[i]);
  492. }
  493. }
  494. if (out.length) {
  495. var r = document.createRange();
  496. r.setStartBefore(out[0]);
  497. r.setEndAfter(out[out.length - 1]);
  498. var sel = window.getSelection();
  499. sel.removeAllRanges();
  500. sel.addRange(r);
  501. savedRange = r.cloneRange();
  502. }
  503. return out;
  504. }
  505. function applyFontSize(pt, noCommit) {
  506. if (inHeaderFooter()) return;
  507. restoreSel();
  508. var spans = wrapSelection();
  509. spans.forEach(function (span) { span.style.fontSize = pt + "pt"; });
  510. // (a preview while the size box is typed in commits nothing; the
  511. // lines follow at once either way)
  512. relayoutNow(spans.map(function (sp) { return sp.closest(BLOCK_SEL); }));
  513. if (!noCommit) afterEdit(true);
  514. }
  515. /* A paragraph style applies to whole paragraphs, except when the
  516. selection is part of one paragraph: then it styles just those
  517. characters, the way Word's linked styles (Title, Heading 1-4) do. */
  518. function applyParagraphStyle(v) {
  519. if (inHeaderFooter()) return;
  520. restoreSel();
  521. var sel = window.getSelection();
  522. var range = sel && sel.rangeCount ? sel.getRangeAt(0) : savedRange;
  523. var blocks = getSelectedBlocks();
  524. if (range && !range.collapsed) {
  525. // a block the selection only touches at its very start is not in it
  526. blocks = blocks.filter(function (b) { return /\S/.test(partOf(range, b).toString()); });
  527. }
  528. var touched = blocks.slice();
  529. if (range && !range.collapsed && blocks.length === 1 &&
  530. partOf(range, blocks[0]).toString().trim().length < blocks[0].textContent.trim().length) {
  531. applyCharStyle(v, blocks[0]);
  532. } else if (range) {
  533. var start = [range.startContainer, range.startOffset], end = [range.endContainer, range.endOffset];
  534. touched = blocks.map(function (b) {
  535. var nb = restyleBlock(b, v);
  536. if (start[0] === b) start[0] = nb;
  537. if (end[0] === b) end[0] = nb;
  538. return nb;
  539. });
  540. // the block's children moved, which resets a live selection
  541. try {
  542. var r = document.createRange();
  543. r.setStart(start[0], start[1]);
  544. r.setEnd(end[0], end[1]);
  545. sel.removeAllRanges();
  546. sel.addRange(r);
  547. savedRange = r.cloneRange();
  548. } catch (e) { }
  549. }
  550. relayoutNow(touched);
  551. afterEdit(true);
  552. }
  553. // the part of a range that falls inside one block
  554. function partOf(range, block) {
  555. var r = document.createRange();
  556. r.selectNodeContents(block);
  557. if (range.compareBoundaryPoints(Range.START_TO_START, r) > 0) r.setStart(range.startContainer, range.startOffset);
  558. if (range.compareBoundaryPoints(Range.END_TO_END, r) < 0) r.setEnd(range.endContainer, range.endOffset);
  559. return r;
  560. }
  561. /* restyleBlock gives a paragraph a style. It is the same paragraph
  562. afterwards: its spacing (data-ls), alignment, indents and everything
  563. else it carries move to the new element (execCommand's formatBlock
  564. makes a bare one, which is how a 1.5-spaced paragraph used to come
  565. back single-spaced). Returns the block that holds the text now. */
  566. function restyleBlock(b, v) {
  567. var tag = v === "title" ? "H1" : v.toUpperCase();
  568. if (!/^(P|H[1-6])$/.test(b.tagName)) {
  569. // a list item, quote or cell keeps its own element
  570. var r = document.createRange();
  571. r.selectNodeContents(b);
  572. var sel = window.getSelection();
  573. sel.removeAllRanges();
  574. sel.addRange(r);
  575. try { document.execCommand("formatBlock", false, "<" + tag.toLowerCase() + ">"); } catch (e) { }
  576. var inner = b.querySelector(tag.toLowerCase());
  577. if (inner) {
  578. inner.classList.toggle("doc-title", v === "title");
  579. if (!inner.getAttribute("class")) inner.removeAttribute("class");
  580. }
  581. return b;
  582. }
  583. var nb = b;
  584. if (b.tagName !== tag) {
  585. nb = document.createElement(tag);
  586. for (var i = 0; i < b.attributes.length; i++) nb.setAttribute(b.attributes[i].name, b.attributes[i].value);
  587. while (b.firstChild) nb.appendChild(b.firstChild);
  588. b.parentNode.replaceChild(nb, b);
  589. }
  590. nb.classList.toggle("doc-title", v === "title");
  591. if (!nb.getAttribute("class")) nb.removeAttribute("class");
  592. return nb;
  593. }
  594. /* styleLook reads what a paragraph style looks like from the
  595. stylesheet: a hidden paragraph of that style, measured in place */
  596. function styleLook(v) {
  597. var probe = document.createElement(v === "title" ? "h1" : v);
  598. if (v === "title") probe.className = "doc-title";
  599. probe.style.cssText = "position:absolute;left:-10000px;top:0;visibility:hidden;margin:0;";
  600. probe.textContent = "x";
  601. editor.appendChild(probe);
  602. var cs = window.getComputedStyle(probe);
  603. var look = {
  604. size: Math.round(parseFloat(cs.fontSize) * 72 / 96 * 10) / 10 + "pt",
  605. weight: cs.fontWeight,
  606. style: cs.fontStyle,
  607. color: cssColorHex(cs.color)
  608. };
  609. editor.removeChild(probe);
  610. return look;
  611. }
  612. function cssColorHex(c) {
  613. var m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(String(c || ""));
  614. if (!m) return c;
  615. return "#" + [m[1], m[2], m[3]].map(function (x) {
  616. return ("0" + parseInt(x, 10).toString(16)).slice(-2);
  617. }).join("");
  618. }
  619. /* applyCharStyle gives the selected characters a style's look - its
  620. size, weight, slant and colour - as their own formatting, marked
  621. data-cstyle so the style list can name it again. Inside, the text
  622. takes the style's size throughout: an earlier style run or a run's
  623. own size would otherwise poke through. Normal text in a normal
  624. paragraph is simply the paragraph's own look, so it leaves no span. */
  625. function applyCharStyle(v, block) {
  626. var look = styleLook(v);
  627. var plain = v === "p" && block.tagName === "P" && !block.classList.contains("doc-title");
  628. wrapSelection().forEach(function (span) {
  629. var olds = span.querySelectorAll("span[data-cstyle]");
  630. for (var i = olds.length - 1; i >= 0; i--) unwrapEl(olds[i]);
  631. var sized = span.querySelectorAll("[style]");
  632. for (i = 0; i < sized.length; i++) {
  633. sized[i].style.removeProperty("font-size");
  634. if (!sized[i].getAttribute("style")) sized[i].removeAttribute("style");
  635. }
  636. var outer = span.parentNode && span.parentNode.closest ? span.parentNode.closest("span[data-cstyle]") : null;
  637. if (plain && !(outer && block.contains(outer))) {
  638. unwrapEl(span);
  639. return;
  640. }
  641. span.setAttribute("data-cstyle", v);
  642. span.style.fontSize = look.size;
  643. span.style.fontWeight = look.weight;
  644. span.style.fontStyle = look.style;
  645. span.style.color = look.color;
  646. });
  647. }
  648. function unwrapEl(el) {
  649. var p = el.parentNode;
  650. if (!p) return;
  651. while (el.firstChild) p.insertBefore(el.firstChild, el);
  652. p.removeChild(el);
  653. }
  654. function setLineSpacing(v) {
  655. if (inHeaderFooter()) return;
  656. restoreSel();
  657. var blocks = getSelectedBlocks();
  658. blocks.forEach(function (b) {
  659. b.setAttribute("data-ls", v);
  660. b.removeAttribute("data-lsexact");
  661. b.removeAttribute("data-lsmin");
  662. });
  663. relayoutNow(blocks);
  664. afterEdit(true);
  665. }
  666. function currentLineSpacing() {
  667. var blocks = getSelectedBlocks();
  668. if (!blocks.length) return "";
  669. var v = blocks[0].getAttribute("data-ls");
  670. return v ? String(parseFloat(v)) : String(docLineSpacing());
  671. }
  672. function toggleChecklist() {
  673. if (inHeaderFooter()) return;
  674. restoreSel();
  675. var li = null;
  676. getSelectedBlocks().forEach(function (b) { if (b.tagName === "LI") li = b; });
  677. var list = li ? li.closest("ul,ol") : null;
  678. try {
  679. if (list && list.tagName === "UL" && list.classList.contains("of-checklist")) {
  680. // toggle the whole list back off
  681. document.execCommand("insertUnorderedList");
  682. } else if (list && list.tagName === "UL") {
  683. list.classList.add("of-checklist");
  684. } else {
  685. document.execCommand("insertUnorderedList");
  686. var sel = window.getSelection();
  687. var n = sel.anchorNode;
  688. while (n && n !== editor) {
  689. if (n.nodeType === 1 && n.tagName === "UL") { n.classList.add("of-checklist"); break; }
  690. n = n.parentNode;
  691. }
  692. }
  693. } catch (e) { }
  694. afterEdit(true);
  695. }
  696. function clearFormatting() {
  697. if (inHeaderFooter()) return;
  698. restoreSel();
  699. try {
  700. document.execCommand("removeFormat");
  701. document.execCommand("formatBlock", false, "<p>");
  702. } catch (e) { }
  703. var cleared = getSelectedBlocks();
  704. cleared.forEach(function (b) {
  705. b.removeAttribute("style");
  706. b.classList.remove("doc-title");
  707. if (!b.getAttribute("class")) b.removeAttribute("class");
  708. });
  709. relayoutNow(cleared);
  710. afterEdit(true);
  711. }
  712. function selectAll() {
  713. editor.focus();
  714. var r = document.createRange();
  715. r.selectNodeContents(editor);
  716. var sel = window.getSelection();
  717. sel.removeAllRanges();
  718. sel.addRange(r);
  719. savedRange = r.cloneRange();
  720. }
  721. /* ================= ribbon ================= */
  722. /* The ribbon (common/ribbon.js) holds every command the editor has, in
  723. the tabs Word puts them in: Home, Insert, Draw, Layout, References,
  724. Review and View. File stays a menu (office.js). Buttons keep the
  725. editor's selection (mousedown is swallowed), and each command puts
  726. the saved range back before it runs (restoreSel). */
  727. var STYLE_TILES = PARA_STYLES.concat([
  728. { v: "blockquote", label: "Quote" },
  729. { v: "pre", label: "Code" }
  730. ]);
  731. var currentStyle = "p";
  732. function buildToolbar() {
  733. var R = OfficeRibbon;
  734. var B = R.button, D = R.dropdown;
  735. // hidden file input for Insert > Pictures > From this device
  736. $("#deviceImageInput").on("change", function () {
  737. var files = this.files;
  738. for (var i = 0; i < files.length; i++) {
  739. (function (f) {
  740. OfficeApp.blobToSrc(f, f.name || "image.png", function (src) {
  741. insertImage(src);
  742. }, function (msg) {
  743. OfficeApp.toast(msg, "error");
  744. });
  745. })(files[i]);
  746. }
  747. this.value = "";
  748. });
  749. // paragraph style: the styles gallery on a desktop, this select on
  750. // a phone (where galleries are left out)
  751. $styleSel = $('<select class="of-tselect tb-style" title="Paragraph style" data-desktop="hide"></select>');
  752. STYLE_TILES.forEach(function (s) {
  753. $styleSel.append($("<option></option>").attr("value", s.v).text(s.label));
  754. });
  755. $styleSel.on("change", function () { applyParagraphStyle(this.value); });
  756. $fontSel = $('<select class="of-tselect tb-font" title="Font"></select>');
  757. FONTS.forEach(function (f) {
  758. $fontSel.append($("<option></option>").attr("value", f).text(f).css("font-family", OfficeFonts.stack(f)));
  759. });
  760. $fontSel.on("change", function () { applyFontFamily(this.value); });
  761. $sizeSel = $('<select class="of-tselect tb-size" title="Font size (pt)"></select>');
  762. FONT_SIZES.forEach(function (s) {
  763. $sizeSel.append($("<option></option>").attr("value", String(s)).text(s));
  764. });
  765. $sizeSel.val("11");
  766. $sizeSel.on("change", function () { applyFontSize(parseInt(this.value, 10)); });
  767. var cmdBtn = function (icon, title, key, cmd, svg) {
  768. return B({
  769. icon: svg ? null : icon, svg: svg, title: title, key: key, cmd: cmd,
  770. onClick: function () { exec(cmd); }
  771. });
  772. };
  773. /* ---------- Home ---------- */
  774. var home = R.tab("home", "Home");
  775. R.clipboardGroup(home, {
  776. pasteMenu: function () {
  777. return [
  778. { label: "Keep source formatting", icon: "paste", key: "Ctrl+V", action: function () { pasteFromMenu(false); } },
  779. { label: "Keep text only", icon: "file alternate outline", key: "Ctrl+Shift+V", action: function () { pasteFromMenu(true); } }
  780. ];
  781. },
  782. copyMenu: function () {
  783. return [
  784. { label: "Copy", icon: "copy", key: "Ctrl+C", action: function () { menuCutCopy(false); } },
  785. { label: "Copy as plain text", icon: "file alternate outline", action: copyPlainText }
  786. ];
  787. },
  788. painter: {
  789. id: "docPainter", title: "Format Painter - click, then select the text to format (double-click to keep it on)",
  790. active: function () { return !!painter; },
  791. start: startPainter
  792. }
  793. });
  794. var font = home.group({ id: "font", label: "Font", icon: "font", priority: 9 });
  795. font.row([$fontSel, $sizeSel,
  796. B({ svg: "growFont", title: "Increase font size", key: "Ctrl+]", onClick: function () { stepFontSize(1); } }),
  797. B({ svg: "shrinkFont", title: "Decrease font size", key: "Ctrl+[", onClick: function () { stepFontSize(-1); } }),
  798. D({ svg: "changeCase", title: "Change case", mobile: false, menu: caseMenuItems }),
  799. B({ svg: "clearFormat", title: "Clear formatting", onClick: clearFormatting })
  800. ]);
  801. font.row([
  802. cmdBtn("bold", "Bold", "Ctrl+B", "bold"),
  803. cmdBtn("italic", "Italic", "Ctrl+I", "italic"),
  804. cmdBtn("underline", "Underline", "Ctrl+U", "underline"),
  805. cmdBtn("strikethrough", "Strikethrough", "Ctrl+Shift+X", "strikeThrough"),
  806. cmdBtn(null, "Subscript", "Ctrl+,", "subscript", "subscript"),
  807. cmdBtn(null, "Superscript", "Ctrl+.", "superscript", "superscript"),
  808. "|",
  809. R.colorButton({
  810. id: "docHilite", svg: "highlighter", title: "Text highlight color", value: "#ffff00",
  811. allowNone: true, noneLabel: "No highlight", onPick: applyHighlight
  812. }),
  813. R.colorButton({
  814. id: "docFontColor", svg: "fontColor", title: "Font color", value: "#d0342c",
  815. onPick: applyFontColor
  816. })
  817. ]);
  818. var para = home.group({ id: "paragraph", label: "Paragraph", icon: "paragraph", priority: 8 });
  819. para.row([
  820. cmdBtn("list ul", "Bulleted list", "Ctrl+Shift+8", "insertUnorderedList"),
  821. cmdBtn("list ol", "Numbered list", "Ctrl+Shift+7", "insertOrderedList"),
  822. B({ icon: "check square outline", title: "Checklist", cmd: "checklist", onClick: toggleChecklist }),
  823. "|",
  824. B({ icon: "outdent", title: "Decrease indent", onClick: function () { exec("outdent"); } }),
  825. B({ icon: "indent", title: "Increase indent", key: "Tab", onClick: function () { exec("indent"); } }),
  826. "|",
  827. B({ svg: "sortAZ", title: "Sort the selected paragraphs A to Z", mobile: false, onClick: sortParagraphs }),
  828. B({ svg: "marks", title: "Show formatting marks", mobile: false, active: marksOn, onClick: toggleMarks })
  829. ]);
  830. para.row([
  831. cmdBtn("align left", "Align left", null, "justifyLeft"),
  832. cmdBtn("align center", "Center", null, "justifyCenter"),
  833. cmdBtn("align right", "Align right", null, "justifyRight"),
  834. cmdBtn("align justify", "Justify", null, "justifyFull"),
  835. "|",
  836. D({ svg: "lineSpacing", title: "Line and paragraph spacing", menu: lineSpacingItems }),
  837. R.colorButton({
  838. id: "docShading", svg: "fill", title: "Shading", value: "#fff2cc",
  839. allowNone: true, noneLabel: "No colour", mobile: false, onPick: applyShading
  840. }),
  841. D({ svg: "borderBottom", title: "Borders", mobile: false, menu: borderItems })
  842. ]);
  843. home.group({ id: "styles", label: "Styles", icon: "paragraph", priority: 4 })
  844. .add(R.gallery({
  845. id: "docStyles", cls: "doc-styles", tileW: 80, visible: 6, minVisible: 2,
  846. moreTitle: "All styles",
  847. items: STYLE_TILES.map(function (s) {
  848. return {
  849. key: s.v, label: s.label,
  850. html: '<span class="doc-gs-prev doc-gs-' + s.v + '">AaBbCc</span>' +
  851. '<span class="doc-gs-name">' + esc(s.label) + "</span>",
  852. active: function () { return currentStyle === s.v; },
  853. onClick: function () { applyParagraphStyle(s.v); }
  854. };
  855. })
  856. }))
  857. .add($styleSel);
  858. home.group({ id: "editing", label: "Editing", icon: "search", priority: 2 }).stack([
  859. B({ icon: "search", label: "Find", showLabel: true, key: "Ctrl+F", onClick: function () { openFind(false); } }),
  860. B({ icon: "exchange", label: "Replace", showLabel: true, key: "Ctrl+H", onClick: function () { openFind(true); } }),
  861. B({ icon: "i cursor", label: "Select all", showLabel: true, key: "Ctrl+A", onClick: selectAll })
  862. ]);
  863. /* ---------- Insert ---------- */
  864. var ins = R.tab("insert", "Insert");
  865. ins.group({ id: "pages", label: "Pages", svg: "pageBreak" })
  866. .add(R.big({ svg: "pageBreak", label: "Page break", key: "Ctrl+Enter", onClick: insertPageBreak }));
  867. ins.group({ id: "tables", label: "Tables", svg: "table" })
  868. .add(R.big({ svg: "table", label: "Table", onClick: insertTableDialog }));
  869. ins.group({ id: "illustrations", label: "Illustrations", svg: "picture" })
  870. .add(R.big({ svg: "picture", label: "Pictures", menu: imageMenuItems }))
  871. .add(R.big({ svg: "drawing", label: "Drawing", onClick: function () { drawingDialog(); } }));
  872. ins.group({ id: "links", label: "Links", svg: "link" })
  873. .add(R.big({ svg: "link", label: "Link", key: "Ctrl+K", onClick: linkDialog }))
  874. .add(R.big({ svg: "newComment", label: "Comment", key: "Ctrl+Alt+M", onClick: function () { commentDialog(null); } }));
  875. ins.group({ id: "hf", label: "Header & Footer", svg: "headerFooter" })
  876. .add(R.big({ svg: "headerFooter", label: "Header & footer", menu: hfMenuItems }))
  877. .add(R.big({ svg: "pageNumbers", label: "Page numbers", active: function () { return !!pageConf.pageNumbers; }, onClick: togglePageNumbers }));
  878. ins.group({ id: "text", label: "Text", icon: "font" }).stack([
  879. B({ svg: "hrule", label: "Horizontal line", showLabel: true, onClick: function () { exec("insertHorizontalRule"); } }),
  880. B({ icon: "quote left", label: "Quote", showLabel: true, onClick: function () { applyParagraphStyle("blockquote"); } }),
  881. B({ icon: "code", label: "Code block", showLabel: true, onClick: function () { applyParagraphStyle("pre"); } })
  882. ]);
  883. ins.group({ id: "symbols", label: "Symbols", svg: "symbol" })
  884. .add(R.big({ svg: "symbol", label: "Symbol", title: "Special characters", onClick: specialCharsDialog }))
  885. .add(R.big({ svg: "footnote", label: "Footnote", key: "Ctrl+Alt+F", onClick: insertFootnote }));
  886. /* ---------- Draw ---------- */
  887. var draw = R.tab("draw", "Draw");
  888. var pens = draw.group({ id: "pens", label: "Pens", svg: "pen" });
  889. OfficeSketch.PENS.forEach(function (p) {
  890. pens.add(R.big({
  891. iconHtml: OfficeSketch.penIcon(p), label: p.label,
  892. title: "Draw with the " + p.label.toLowerCase(),
  893. onClick: function () { drawingDialog(p.id); }
  894. }));
  895. });
  896. draw.group({ id: "canvas", label: "Canvas", svg: "drawing" })
  897. .add(R.big({ svg: "drawing", label: "Drawing canvas", onClick: function () { drawingDialog(); } }));
  898. /* ---------- Layout ---------- */
  899. var lay = R.tab("layout", "Layout");
  900. lay.group({ id: "setup", label: "Page Setup", svg: "margins", priority: 5 })
  901. .add(R.big({ svg: "margins", label: "Margins", menu: marginItems }))
  902. .add(R.big({ svg: "orientation", label: "Orientation", menu: orientationItems }))
  903. .add(R.big({ svg: "pageSize", label: "Size", menu: sizeItems }))
  904. .add(R.big({ svg: "columns", label: "Columns", menu: layoutMenuItems }))
  905. .add(R.big({
  906. svg: "pageBreak", label: "Breaks", menu: function () {
  907. return [{ label: "Page break", icon: "file outline", key: "Ctrl+Enter", action: insertPageBreak }];
  908. }
  909. }));
  910. lay.group({ id: "hf", label: "Header & Footer", svg: "headerFooter" })
  911. .add(R.big({ svg: "headerFooter", label: "Header & footer", menu: hfMenuItems }))
  912. .add(R.big({ svg: "pageNumbers", label: "Page numbers", active: function () { return !!pageConf.pageNumbers; }, onClick: togglePageNumbers }));
  913. lay.group({ id: "paragraph", label: "Paragraph", svg: "lineSpacing" }).stack([
  914. D({ svg: "lineSpacing", label: "Line spacing", showLabel: true, menu: lineSpacingItems }),
  915. B({ icon: "indent", label: "Increase indent", showLabel: true, onClick: function () { exec("indent"); } }),
  916. B({ icon: "outdent", label: "Decrease indent", showLabel: true, onClick: function () { exec("outdent"); } })
  917. ]);
  918. lay.group({ id: "dialog", label: "Page setup", svg: "pageSetup" })
  919. .add(R.big({ svg: "pageSetup", label: "Page setup", onClick: pageSetupDialog }));
  920. /* ---------- References ---------- */
  921. var refs = R.tab("references", "References");
  922. refs.group({ id: "toc", label: "Table of Contents", svg: "toc" })
  923. .add(R.big({ svg: "toc", label: "Table of contents", title: "Insert a table of contents built from the headings", onClick: insertToc }))
  924. .add(R.big({ svg: "tocUpdate", label: "Update table", enabled: hasToc, onClick: updateToc }));
  925. refs.group({ id: "footnotes", label: "Footnotes", svg: "footnote" })
  926. .add(R.big({ svg: "footnote", label: "Insert footnote", key: "Ctrl+Alt+F", onClick: insertFootnote }));
  927. /* ---------- Review ---------- */
  928. var rev = R.tab("review", "Review");
  929. rev.group({ id: "proofing", label: "Proofing", svg: "spelling" })
  930. .add(R.big({ svg: "spelling", label: "Spelling", title: "Check spelling as you type", active: function () { return editor.spellcheck; }, onClick: toggleSpellcheck }))
  931. .add(R.big({ svg: "wordCount", label: "Word count", onClick: wordCountDialog }));
  932. rev.group({ id: "comments", label: "Comments", svg: "comments" })
  933. .add(R.big({ svg: "newComment", label: "New comment", key: "Ctrl+Alt+M", onClick: function () { commentDialog(null); } }))
  934. .add(R.big({
  935. svg: "comments", label: "Show comments", active: commentsPanelVisible,
  936. onClick: function () { showCommentsPanel(!commentsPanelVisible()); OfficeRibbon.refresh(); }
  937. }));
  938. rev.group({ id: "tracking", label: "Tracking", svg: "trackChanges" })
  939. .add(R.big({
  940. svg: "trackChanges", label: "Suggest edits", title: "Track changes as suggestions",
  941. active: function () { return suggesting; },
  942. onClick: function () { setSuggesting(!suggesting); OfficeRibbon.refresh(); }
  943. }));
  944. rev.group({ id: "changes", label: "Changes", svg: "accept" })
  945. .add(R.big({
  946. svg: "accept", label: "Accept all", enabled: function () { return allSuggestions().length > 0; },
  947. onClick: function () { resolveAllSuggestions(true); OfficeRibbon.refresh(); }
  948. }))
  949. .add(R.big({
  950. svg: "reject", label: "Reject all", enabled: function () { return allSuggestions().length > 0; },
  951. onClick: function () { resolveAllSuggestions(false); OfficeRibbon.refresh(); }
  952. }));
  953. /* ---------- View ---------- */
  954. var view = R.tab("view", "View");
  955. view.group({ id: "show", label: "Show", svg: "marks" })
  956. .add(R.big({ svg: "marks", label: "Formatting marks", active: marksOn, onClick: toggleMarks }))
  957. .add(R.big({
  958. svg: "layoutBoxes", label: "Layout boxes",
  959. active: function () { return document.body.classList.contains("doc-show-boxes"); },
  960. onClick: function () { toggleLayoutBoxes(); OfficeRibbon.refresh(); }
  961. }))
  962. .add(R.big({
  963. svg: "comments", label: "Comments", active: commentsPanelVisible,
  964. onClick: function () { showCommentsPanel(!commentsPanelVisible()); OfficeRibbon.refresh(); }
  965. }));
  966. view.group({ id: "zoom", label: "Zoom", svg: "zoomIn" })
  967. .add(R.big({ svg: "zoomOut", label: "Zoom out", key: "Ctrl+-", onClick: function () { OfficeApp.zoomOut(); } }))
  968. .add(R.big({ svg: "zoom100", label: "100%", key: "Ctrl+0", onClick: function () { OfficeApp.setZoom(100); } }))
  969. .add(R.big({ svg: "zoomIn", label: "Zoom in", key: "Ctrl+=", onClick: function () { OfficeApp.zoomIn(); } }))
  970. .add(R.big({ svg: "pageWidth", label: "Page width", onClick: function () { fitPageWidth(false); } }));
  971. view.group({ id: "appearance", label: "Appearance", svg: "darkTheme" })
  972. .add(R.big({
  973. svg: "darkTheme", label: "Dark theme", active: function () { return OfficeApp.isDark(); },
  974. onClick: function () { OfficeApp.toggleTheme(); OfficeRibbon.refresh(); }
  975. }));
  976. /* ---------- Picture Format (contextual) ---------- */
  977. var pf = R.tab("pictureformat", "Picture Format", {
  978. contextual: true,
  979. when: function () { return !!selectedImg && editor.contains(selectedImg); }
  980. });
  981. pf.group({ id: "adjust", label: "Adjust", svg: "crop" })
  982. .add(R.big({ svg: "crop", label: "Crop", onClick: function () { cropPictureDialog(selectedImg); } }))
  983. .add(R.big({ svg: "resetPicture", label: "Reset picture", title: "Remove the crop and border and restore the original size", onClick: function () { resetPicture(selectedImg); } }));
  984. pf.group({ id: "border", label: "Picture Border", svg: "outline" })
  985. .add(R.colorButton({ id: "docImgBorder", big: true, svg: "outline", label: "Border", title: "Picture border", value: "#000000", allowNone: true, noneLabel: "No border", onPick: applyPictureBorderColor }))
  986. .add(R.big({ svg: "lineWeight", label: "Weight", menu: pictureWeightItems }));
  987. pf.group({ id: "arrange", label: "Arrange", svg: "arrange" })
  988. .add(R.big({ svg: "wrapText", label: "Wrap text", menu: pictureWrapItems }))
  989. .add(R.big({ svg: "alignObjects", label: "Align", menu: pictureAlignItems }));
  990. pf.group({ id: "size", label: "Size", svg: "formatPane" })
  991. .add(R.big({ svg: "formatPane", label: "Size & properties", onClick: function () { imageSizeDialog(selectedImg); } }));
  992. }
  993. /* ---------- Home: font ---------- */
  994. function currentFontPt() {
  995. var v = parseInt($sizeSel.val(), 10);
  996. var n = savedRange ? savedRange.startContainer : null;
  997. if (n && n.nodeType === 3) n = n.parentNode;
  998. if (n && n.nodeType === 1 && editor.contains(n)) {
  999. var px = parseFloat(window.getComputedStyle(n).fontSize);
  1000. if (px > 0) v = Math.round(px * 72 / 96);
  1001. }
  1002. return v || 11;
  1003. }
  1004. // the next size on the list up or down, as Word's grow / shrink do
  1005. function stepFontSize(dir) {
  1006. var cur = currentFontPt(), next = cur;
  1007. var i;
  1008. if (dir > 0) {
  1009. next = cur + 10;
  1010. for (i = 0; i < FONT_SIZES.length; i++) if (FONT_SIZES[i] > cur) { next = FONT_SIZES[i]; break; }
  1011. next = Math.min(400, next);
  1012. } else {
  1013. next = Math.max(1, cur - 1);
  1014. for (i = FONT_SIZES.length - 1; i >= 0; i--) if (FONT_SIZES[i] < cur) { next = FONT_SIZES[i]; break; }
  1015. }
  1016. if (next === cur) return;
  1017. applyFontSize(next);
  1018. if ($sizeSel.find('option[value="' + next + '"]').length) $sizeSel.val(String(next));
  1019. }
  1020. var CASES = [
  1021. { key: "sentence", label: "Sentence case." },
  1022. { key: "lower", label: "lowercase" },
  1023. { key: "upper", label: "UPPERCASE" },
  1024. { key: "title", label: "Capitalize Each Word" },
  1025. { key: "toggle", label: "tOGGLE cASE" }
  1026. ];
  1027. function caseMenuItems() {
  1028. return CASES.map(function (c) {
  1029. return { label: c.label, action: function () { changeCase(c.key); } };
  1030. });
  1031. }
  1032. /* Change case rewrites the characters of the selected text nodes in
  1033. place, one for one, so the formatting runs, the selection and the
  1034. undo snapshot all stay where they were. A character whose other
  1035. case is longer (German sharp s) is left as it is. */
  1036. function changeCase(mode) {
  1037. if (inHeaderFooter()) return;
  1038. restoreSel();
  1039. var sel = window.getSelection();
  1040. if (!sel || !sel.rangeCount) return;
  1041. var range = sel.getRangeAt(0);
  1042. if (!editor.contains(range.commonAncestorContainer)) return;
  1043. if (range.collapsed) {
  1044. OfficeApp.setStatus("Select the text to change first", "info", 3000);
  1045. return;
  1046. }
  1047. var rootEl = range.commonAncestorContainer.nodeType === 3 ?
  1048. range.commonAncestorContainer.parentNode : range.commonAncestorContainer;
  1049. var walker = document.createTreeWalker(rootEl, NodeFilter.SHOW_TEXT, null);
  1050. var nodes = [];
  1051. while (walker.nextNode()) {
  1052. if (range.intersectsNode(walker.currentNode)) nodes.push(walker.currentNode);
  1053. }
  1054. var one = function (c, f) {
  1055. var r = f(c);
  1056. return r.length === 1 ? r : c;
  1057. };
  1058. var up = function (c) { return one(c, function (x) { return x.toUpperCase(); }); };
  1059. var low = function (c) { return one(c, function (x) { return x.toLowerCase(); }); };
  1060. var isLetter = function (c) { return c.toUpperCase() !== c.toLowerCase(); };
  1061. var wordStart = true, sentenceStart = true;
  1062. nodes.forEach(function (tn) {
  1063. var t = tn.nodeValue;
  1064. var a = tn === range.startContainer ? range.startOffset : 0;
  1065. var b = tn === range.endContainer ? range.endOffset : t.length;
  1066. var out = "";
  1067. for (var i = a; i < b; i++) {
  1068. var c = t.charAt(i), r = c;
  1069. if (mode === "lower") r = low(c);
  1070. else if (mode === "upper") r = up(c);
  1071. else if (mode === "toggle") r = (c === up(c)) ? low(c) : up(c);
  1072. else if (mode === "title") r = wordStart ? up(c) : low(c);
  1073. else if (mode === "sentence") r = (sentenceStart && isLetter(c)) ? up(c) : low(c);
  1074. if (isLetter(c)) { wordStart = false; sentenceStart = false; }
  1075. else if (/\s/.test(c)) wordStart = true;
  1076. if (/[.!?]/.test(c)) sentenceStart = true;
  1077. out += r;
  1078. }
  1079. if (out !== t.substring(a, b)) tn.nodeValue = t.substring(0, a) + out + t.substring(b);
  1080. });
  1081. try {
  1082. sel.removeAllRanges();
  1083. sel.addRange(range);
  1084. savedRange = range.cloneRange();
  1085. } catch (e) { }
  1086. afterEdit(true);
  1087. }
  1088. function applyHighlight(v) {
  1089. if (inHeaderFooter()) return;
  1090. restoreSel();
  1091. try {
  1092. if (!document.execCommand("hiliteColor", false, v || "transparent")) {
  1093. document.execCommand("backColor", false, v || "transparent");
  1094. }
  1095. } catch (e) {
  1096. try { document.execCommand("backColor", false, v || "transparent"); } catch (e2) { }
  1097. }
  1098. afterEdit(true);
  1099. }
  1100. function applyFontColor(v) {
  1101. if (inHeaderFooter() || !v) return;
  1102. restoreSel();
  1103. try { document.execCommand("foreColor", false, v); } catch (e) { }
  1104. afterEdit(true);
  1105. }
  1106. /* ---------- Home: paragraph ---------- */
  1107. function lineSpacingItems() {
  1108. var cur = currentLineSpacing();
  1109. return LINE_SPACINGS.map(function (v) {
  1110. return {
  1111. label: v === "1" ? "Single (1.0)" : v,
  1112. checked: cur === v,
  1113. action: function () { setLineSpacing(v); }
  1114. };
  1115. });
  1116. }
  1117. // paragraph shading: the block's background, which the .docx writer
  1118. // turns into the paragraph's w:shd
  1119. function applyShading(v) {
  1120. if (inHeaderFooter()) return;
  1121. restoreSel();
  1122. var blocks = getSelectedBlocks();
  1123. if (!blocks.length) return;
  1124. blocks.forEach(function (b) {
  1125. b.style.backgroundColor = v || "";
  1126. if (!b.getAttribute("style")) b.removeAttribute("style");
  1127. });
  1128. afterEdit(true);
  1129. updatePageGuides();
  1130. }
  1131. /* Paragraph borders as Word draws them: a 0.75pt rule a point away from
  1132. the text (border-* + padding-*, which the .docx writer turns into
  1133. w:pBdr with that w:space). */
  1134. var BORDER_RULE = "0.75pt solid #000000";
  1135. function setBlockBorders(sides) {
  1136. if (inHeaderFooter()) return;
  1137. restoreSel();
  1138. var blocks = getSelectedBlocks();
  1139. if (!blocks.length) return;
  1140. var all = ["top", "right", "bottom", "left"];
  1141. blocks.forEach(function (b, i) {
  1142. all.forEach(function (s) {
  1143. // a box around several paragraphs: no rules between them
  1144. var on = sides.indexOf(s) >= 0;
  1145. if (sides.join() === "top,right,bottom,left" && blocks.length > 1) {
  1146. if (s === "top" && i > 0) on = false;
  1147. if (s === "bottom" && i < blocks.length - 1) on = false;
  1148. }
  1149. b.style["border" + s.charAt(0).toUpperCase() + s.substring(1)] = on ? BORDER_RULE : "";
  1150. b.style["padding" + s.charAt(0).toUpperCase() + s.substring(1)] = on ? "1pt" : "";
  1151. });
  1152. if (!b.getAttribute("style")) b.removeAttribute("style");
  1153. });
  1154. afterEdit(true);
  1155. updatePageGuides();
  1156. }
  1157. function borderItems() {
  1158. return [
  1159. { label: "Bottom border", html: OfficeIcons.get("borderBottom") + "<span>Bottom border</span>", action: function () { setBlockBorders(["bottom"]); } },
  1160. { label: "Top border", html: OfficeIcons.get("borderTop") + "<span>Top border</span>", action: function () { setBlockBorders(["top"]); } },
  1161. { label: "Outside borders", html: OfficeIcons.get("borderOutside") + "<span>Outside borders</span>", action: function () { setBlockBorders(["top", "right", "bottom", "left"]); } },
  1162. { label: "No border", html: OfficeIcons.get("borderNone") + "<span>No border</span>", action: function () { setBlockBorders([]); } }
  1163. ];
  1164. }
  1165. function sortParagraphs() {
  1166. if (inHeaderFooter()) return;
  1167. restoreSel();
  1168. var blocks = getSelectedBlocks().filter(function (b) {
  1169. return !b.classList.contains("doc-pagebreak") && b.tagName !== "TABLE";
  1170. });
  1171. if (blocks.length < 2) {
  1172. OfficeApp.setStatus("Select two or more paragraphs to sort", "info", 3000);
  1173. return;
  1174. }
  1175. var parent = blocks[0].parentNode;
  1176. if (!blocks.every(function (b) { return b.parentNode === parent; })) {
  1177. OfficeApp.setStatus("Sort works on paragraphs next to each other", "error", 4000);
  1178. return;
  1179. }
  1180. var anchor = blocks[blocks.length - 1].nextSibling;
  1181. var sorted = blocks.slice().sort(function (a, b) {
  1182. return (a.textContent || "").trim().localeCompare((b.textContent || "").trim(), undefined,
  1183. { numeric: true, sensitivity: "base" });
  1184. });
  1185. sorted.forEach(function (b) { parent.insertBefore(b, anchor); });
  1186. afterEdit(true);
  1187. updatePageGuides();
  1188. }
  1189. function marksOn() { return document.body.classList.contains("doc-show-marks"); }
  1190. function toggleMarks() {
  1191. var on = !marksOn();
  1192. document.body.classList.toggle("doc-show-marks", on);
  1193. OfficeApp.setSetting("marks", on);
  1194. OfficeRibbon.refresh();
  1195. }
  1196. /* ---------- Home: format painter ----------
  1197. Picks up the look of the text at the caret (font, size, colour,
  1198. highlight, bold / italic / underline / strike) and lays it on the
  1199. next selection made in the document. A double-click keeps it on
  1200. until Escape or another click on the button. */
  1201. var painter = null;
  1202. function readCaretFormat() {
  1203. var n = savedRange ? savedRange.startContainer : null;
  1204. if (n && n.nodeType === 3) n = n.parentNode;
  1205. if (!n || n.nodeType !== 1 || !editor.contains(n)) return null;
  1206. var cs = window.getComputedStyle(n);
  1207. var deco = "";
  1208. for (var e = n; e && e !== editor; e = e.parentNode) {
  1209. if (e.nodeType === 1) deco += " " + (window.getComputedStyle(e).textDecorationLine || "");
  1210. }
  1211. var bg = "";
  1212. for (var h = n; h && h !== editor; h = h.parentNode) {
  1213. if (h.nodeType !== 1 || /^(P|H[1-6]|LI|DIV|BLOCKQUOTE|PRE|TD|TH)$/.test(h.tagName)) break;
  1214. var c = window.getComputedStyle(h).backgroundColor;
  1215. if (c && c !== "transparent" && !/rgba\(0, 0, 0, 0\)/.test(c)) { bg = c; break; }
  1216. }
  1217. var fam = String(cs.fontFamily || "").replace(/['"]/g, "").split(",")[0].trim();
  1218. return {
  1219. family: fam,
  1220. pt: Math.round(parseFloat(cs.fontSize) * 72 / 96),
  1221. bold: (parseInt(cs.fontWeight, 10) || 400) >= 600,
  1222. italic: cs.fontStyle === "italic",
  1223. underline: deco.indexOf("underline") >= 0,
  1224. strike: deco.indexOf("line-through") >= 0,
  1225. color: cs.color,
  1226. highlight: bg
  1227. };
  1228. }
  1229. function startPainter(sticky) {
  1230. if (painter && !sticky) { stopPainter(); return; }
  1231. var f = readCaretFormat();
  1232. if (!f) {
  1233. OfficeApp.setStatus("Put the cursor in the text whose format to copy", "info", 3000);
  1234. return;
  1235. }
  1236. painter = { fmt: f, sticky: !!sticky };
  1237. document.body.classList.add("doc-painting");
  1238. OfficeApp.setStatus(sticky ? "Format painter on - select text to format, Esc to stop" :
  1239. "Select the text to format", "info", 4000);
  1240. OfficeRibbon.refresh();
  1241. }
  1242. function stopPainter() {
  1243. painter = null;
  1244. document.body.classList.remove("doc-painting");
  1245. OfficeRibbon.refresh();
  1246. }
  1247. function applyPainter() {
  1248. if (!painter) return;
  1249. var sel = window.getSelection();
  1250. if (!sel || sel.isCollapsed || !sel.rangeCount || !editor.contains(sel.getRangeAt(0).commonAncestorContainer)) return;
  1251. savedRange = sel.getRangeAt(0).cloneRange();
  1252. var f = painter.fmt;
  1253. try {
  1254. document.execCommand("removeFormat");
  1255. if (f.bold) document.execCommand("bold");
  1256. if (f.italic) document.execCommand("italic");
  1257. if (f.underline) document.execCommand("underline");
  1258. if (f.strike) document.execCommand("strikeThrough");
  1259. if (f.color) document.execCommand("foreColor", false, f.color);
  1260. if (f.highlight) document.execCommand("hiliteColor", false, f.highlight);
  1261. } catch (e) { }
  1262. savedRange = sel.rangeCount ? sel.getRangeAt(0).cloneRange() : savedRange;
  1263. if (f.family && FONTS.indexOf(f.family) >= 0) applyFontFamily(f.family, true);
  1264. if (f.pt) applyFontSize(f.pt, true);
  1265. afterEdit(true);
  1266. if (!painter.sticky) stopPainter();
  1267. }
  1268. /* ---------- Insert / Layout: page ---------- */
  1269. function togglePageNumbers() {
  1270. pageConf.pageNumbers = !pageConf.pageNumbers;
  1271. applyPageSetup();
  1272. afterEdit(true);
  1273. OfficeRibbon.refresh();
  1274. }
  1275. function hfMenuItems() {
  1276. return [
  1277. { label: "Same on all pages", checked: pageConf.hfMode === "all", action: function () { setHfMode("all"); } },
  1278. { label: "All pages except the first", checked: pageConf.hfMode === "except-first", action: function () { setHfMode("except-first"); } },
  1279. { label: "None", checked: pageConf.hfMode === "none", action: function () { setHfMode("none"); } }
  1280. ];
  1281. }
  1282. // Word's margin presets, in millimetres
  1283. var MARGIN_PRESETS = [
  1284. { label: "Normal", sub: "2.54 cm all round", m: { top: 25.4, right: 25.4, bottom: 25.4, left: 25.4 } },
  1285. { label: "Narrow", sub: "1.27 cm all round", m: { top: 12.7, right: 12.7, bottom: 12.7, left: 12.7 } },
  1286. { label: "Moderate", sub: "2.54 cm top and bottom, 1.91 cm sides", m: { top: 25.4, right: 19.05, bottom: 25.4, left: 19.05 } },
  1287. { label: "Wide", sub: "2.54 cm top and bottom, 5.08 cm sides", m: { top: 25.4, right: 50.8, bottom: 25.4, left: 50.8 } },
  1288. { label: "Compact", sub: "2 cm all round", m: { top: 20, right: 20, bottom: 20, left: 20 } }
  1289. ];
  1290. function marginItems() {
  1291. var m = pageConf.margins;
  1292. var items = MARGIN_PRESETS.map(function (p) {
  1293. var same = Math.abs(m.top - p.m.top) < 0.1 && Math.abs(m.right - p.m.right) < 0.1 &&
  1294. Math.abs(m.bottom - p.m.bottom) < 0.1 && Math.abs(m.left - p.m.left) < 0.1;
  1295. return {
  1296. label: p.label + " (" + p.sub + ")", checked: same,
  1297. action: function () {
  1298. pageConf.margins = { top: p.m.top, right: p.m.right, bottom: p.m.bottom, left: p.m.left };
  1299. applyPageSetup();
  1300. afterEdit(true);
  1301. }
  1302. };
  1303. });
  1304. items.push({ sep: true });
  1305. items.push({ label: "Custom margins...", icon: "sliders horizontal", action: pageSetupDialog });
  1306. return items;
  1307. }
  1308. function orientationItems() {
  1309. return [["portrait", "Portrait"], ["landscape", "Landscape"]].map(function (o) {
  1310. return {
  1311. label: o[1], checked: pageConf.orientation === o[0],
  1312. action: function () { pageConf.orientation = o[0]; applyPageSetup(); afterEdit(true); }
  1313. };
  1314. });
  1315. }
  1316. function sizeItems() {
  1317. return Object.keys(PAGE_SIZES).map(function (k) {
  1318. var d = PAGE_SIZES[k];
  1319. return {
  1320. label: k + " (" + d.w + " x " + d.h + " mm)", checked: pageConf.size === k,
  1321. action: function () { pageConf.size = k; applyPageSetup(); afterEdit(true); }
  1322. };
  1323. });
  1324. }
  1325. /* ---------- References ---------- */
  1326. // a footnote: the reference in the text, its note under a rule at the
  1327. // foot of the page (renderFootnoteAreas), where it is typed
  1328. function insertFootnote() {
  1329. if (inHeaderFooter()) return;
  1330. restoreSel();
  1331. var sel = window.getSelection();
  1332. if (!sel || !sel.rangeCount || !editor.contains(sel.getRangeAt(0).startContainer)) return;
  1333. var id = "fn" + Date.now().toString(36) + Math.random().toString(36).substring(2, 5);
  1334. footnotes[id] = "<p><br></p>";
  1335. // placed with a Range, not insertHTML: Chrome lifts a non-editable
  1336. // element out of the paragraph it is inserted into
  1337. var range = sel.getRangeAt(0);
  1338. range.deleteContents();
  1339. var ref = document.createElement("sup");
  1340. ref.className = "doc-fnref";
  1341. ref.setAttribute("data-fn", id);
  1342. ref.setAttribute("contenteditable", "false");
  1343. ref.textContent = "*";
  1344. range.insertNode(ref);
  1345. range.setStartAfter(ref);
  1346. range.collapse(true);
  1347. sel.removeAllRanges();
  1348. sel.addRange(range);
  1349. savedRange = range.cloneRange();
  1350. afterEdit(true);
  1351. // lay the pages out now rather than on the counter's timer, which
  1352. // would redraw the note areas - and drop the caret - after it is
  1353. // put in the new note
  1354. clearTimeout(countTimer);
  1355. updateCounts();
  1356. var fn = pageEl.querySelector('.doc-fn-area .doc-fn[data-fn="' + id + '"]');
  1357. if (!fn) return;
  1358. fn.focus();
  1359. try {
  1360. var r = document.createRange();
  1361. r.selectNodeContents(fn.querySelector("p") || fn);
  1362. r.collapse(false);
  1363. var s = window.getSelection();
  1364. s.removeAllRanges();
  1365. s.addRange(r);
  1366. } catch (err) { }
  1367. fn.scrollIntoView({ block: "nearest" });
  1368. }
  1369. /* A table of contents is ordinary paragraphs: a "Contents" title, then
  1370. each heading's text, a right tab with a dot leader at the margin, and
  1371. the page it is on as the layout has it now. That is what Word stores
  1372. once a TOC field is updated, so the layout, the PDF and the writers
  1373. treat it as plain text with real tab stops (the DOCX writer wraps it
  1374. in a TOC field Word can update). The .doc-toc class marks the lines,
  1375. data-toc-level the heading level of an entry and data-toc-max the
  1376. deepest heading the table lists (3 when absent; an imported table
  1377. keeps its own range, Google Docs lists 1-6); a run of them is one
  1378. table, which the editor frames with an "Update table" tab on top
  1379. while the caret or the mouse is in it (tocOverlay, not saved). */
  1380. var ZWSP = String.fromCharCode(0x200B);
  1381. function tocSelector(max) {
  1382. var sel = ["h1:not(.doc-title)"];
  1383. for (var l = 2; l <= max; l++) sel.push("h" + l);
  1384. return sel.join(", ");
  1385. }
  1386. // the deepest heading level a table lists
  1387. function tocMaxOf(lines) {
  1388. var max = 0;
  1389. (lines || []).forEach(function (p) {
  1390. var v = parseInt(p.getAttribute("data-toc-max"), 10);
  1391. if (v > max) max = v;
  1392. });
  1393. return max >= 1 ? Math.min(6, max) : 3;
  1394. }
  1395. function hasToc() { return !!editor.querySelector("p.doc-toc"); }
  1396. // a heading's text, all of it when a page boundary divides it
  1397. function headingText(h) {
  1398. var parts = [];
  1399. var el = h;
  1400. for (var guard = 0; el && guard < 50; guard++) {
  1401. var c = el.cloneNode(true);
  1402. var drop = c.querySelectorAll("sup.doc-fnref, .doc-autobreak");
  1403. for (var i = 0; i < drop.length; i++) drop[i].parentNode.removeChild(drop[i]);
  1404. parts.push(c.textContent || "");
  1405. var tok = el.getAttribute("data-split");
  1406. el = tok ? editor.querySelector('[data-split-of="' + tok + '"]') : null;
  1407. }
  1408. return parts.join("").split(ZWSP).join("").replace(/\s+/g, " ").trim();
  1409. }
  1410. function tocEntries(max) {
  1411. var heads = editor.querySelectorAll(tocSelector(max || 3));
  1412. var out = [];
  1413. for (var i = 0; i < heads.length; i++) {
  1414. var h = heads[i];
  1415. if (h.closest(".doc-fn-area, .doc-hf") || h.classList.contains("doc-split-tail")) continue;
  1416. var text = headingText(h);
  1417. if (!text) continue;
  1418. out.push({
  1419. level: parseInt(h.tagName.substring(1), 10),
  1420. text: text,
  1421. page: pageIndexAt(offsetTopInPage(h)) + 1
  1422. });
  1423. }
  1424. return out;
  1425. }
  1426. function tocLinesHtml(entries, max) {
  1427. max = max || 3;
  1428. var geo = pageGeometry();
  1429. var tabPt = Math.round(geo.contentW * 0.75 * 10) / 10;
  1430. var maxAttr = max !== 3 ? ' data-toc-max="' + max + '"' : "";
  1431. if (!entries.length) {
  1432. return '<p class="doc-toc" data-toc-level="0"' + maxAttr + ' style="margin-bottom:3pt;color:#80868b;">' +
  1433. esc("No headings found - use Heading 1-" + max + " for the lines this table should list") + "</p>";
  1434. }
  1435. // the top level present starts at the margin (a document whose
  1436. // chapters are Heading 2 has no empty first step)
  1437. var top = 9;
  1438. entries.forEach(function (e) { top = Math.min(top, e.level); });
  1439. var html = "";
  1440. for (var i = 0; i < entries.length; i++) {
  1441. var e = entries[i];
  1442. html += '<p class="doc-toc" data-toc-level="' + e.level + '"' + maxAttr + ' data-tabs="right:' + tabPt + ':dot" style="margin-left:' +
  1443. ((e.level - top) * 14) + 'pt;margin-bottom:3pt;">' + esc(e.text) + '<span class="doc-tab"></span>' + e.page + "</p>";
  1444. }
  1445. return html;
  1446. }
  1447. function tocSignature(entries) {
  1448. return entries.map(function (e) { return e.level + "|" + e.page + "|" + e.text; }).join("\n");
  1449. }
  1450. /* the tables in the document: each a run of .doc-toc paragraphs that
  1451. follow one another (a page spacer between two of them is the layout's) */
  1452. function tocGroups() {
  1453. var groups = [];
  1454. var cur = null, last = null;
  1455. var lines = editor.querySelectorAll("p.doc-toc");
  1456. for (var i = 0; i < lines.length; i++) {
  1457. var p = lines[i];
  1458. if (p.closest(".doc-hf")) continue;
  1459. var prev = p.previousElementSibling;
  1460. while (prev && prev.classList.contains("doc-autobreak")) prev = prev.previousElementSibling;
  1461. if (!cur || prev !== last) {
  1462. cur = [];
  1463. groups.push(cur);
  1464. }
  1465. cur.push(p);
  1466. last = p;
  1467. }
  1468. return groups;
  1469. }
  1470. function tocGroupOf(node) {
  1471. var p = node && node.nodeType === 1 ? node : (node ? node.parentNode : null);
  1472. p = p && p.closest ? p.closest("p.doc-toc") : null;
  1473. if (!p || !editor.contains(p)) return null;
  1474. var groups = tocGroups();
  1475. for (var i = 0; i < groups.length; i++) {
  1476. if (groups[i].indexOf(p) >= 0) return groups[i];
  1477. }
  1478. return null;
  1479. }
  1480. function insertToc() {
  1481. if (inHeaderFooter()) return;
  1482. if (hasToc()) { updateToc(); return; }
  1483. var entries = tocEntries();
  1484. restoreSel();
  1485. try {
  1486. document.execCommand("insertHTML", false,
  1487. '<p class="doc-toc doc-toc-title" style="font-size:16pt;margin-bottom:6pt;">Contents</p>' +
  1488. tocLinesHtml(entries) + "<p><br></p>");
  1489. } catch (e) { return; }
  1490. afterEdit(true);
  1491. updatePageGuides();
  1492. // the table itself moved the headings: number it again
  1493. updateToc(true);
  1494. if (!entries.length) OfficeApp.setStatus("Table of contents added - give your headings a Heading 1-3 style, then click Update table", "info", 6000);
  1495. }
  1496. function updateTocQuiet() { updateToc(true); }
  1497. /* updateToc rebuilds every table (or only `only`, one group) from the
  1498. headings. The new lines can push the headings to other pages, so the
  1499. numbers are taken again until they stop changing. */
  1500. function updateToc(quiet, only) {
  1501. if (!hasToc()) return;
  1502. var groups = tocGroups();
  1503. if (only) {
  1504. var first = only[0];
  1505. groups = groups.filter(function (g) { return g.indexOf(first) >= 0; });
  1506. }
  1507. if (!groups.length) return;
  1508. // the headings each table lists, from the pages as laid out now
  1509. var maxes = groups.map(tocMaxOf);
  1510. function entriesByMax() {
  1511. var out = {};
  1512. maxes.forEach(function (m) { if (!out[m]) out[m] = tocEntries(m); });
  1513. return out;
  1514. }
  1515. var entries = entriesByMax();
  1516. // then every page split is undone: the lines replaced may be cut in two
  1517. removeAutoBreaks(editor);
  1518. groups = tocGroups();
  1519. if (only) groups = groups.filter(function (g) { return g.indexOf(first) >= 0; });
  1520. if (!groups.length) return;
  1521. // where each table goes once its lines are gone: the first old line
  1522. var anchors = groups.map(function (g, i) {
  1523. var lines = g.filter(function (p) { return !p.classList.contains("doc-toc-title"); });
  1524. var title = g.filter(function (p) { return p.classList.contains("doc-toc-title"); })[0] || null;
  1525. return { lines: lines, after: title, before: lines.length ? lines[0] : null, max: maxes[i] || 3 };
  1526. });
  1527. var caretInside = groups.some(function (g) {
  1528. var sel = window.getSelection();
  1529. return sel && sel.rangeCount && g.some(function (p) { return p.contains(sel.anchorNode); });
  1530. });
  1531. var sig = null;
  1532. for (var pass = 0; pass < 4; pass++) {
  1533. if (pass > 0) entries = entriesByMax();
  1534. var s = Object.keys(entries).sort().map(function (m) { return m + ":" + tocSignature(entries[m]); }).join("\n");
  1535. if (s === sig) break;
  1536. sig = s;
  1537. anchors.forEach(function (a) {
  1538. var holder = document.createElement("div");
  1539. holder.innerHTML = tocLinesHtml(entries[a.max], a.max);
  1540. var fresh = Array.prototype.slice.call(holder.children);
  1541. var ref = a.before || (a.after ? a.after.nextSibling : null);
  1542. var parent = (a.before || a.after).parentNode;
  1543. fresh.forEach(function (n) { parent.insertBefore(n, ref); });
  1544. a.lines.forEach(function (p) { if (p.parentNode) p.parentNode.removeChild(p); });
  1545. a.lines = fresh;
  1546. a.before = fresh[0] || null;
  1547. });
  1548. dirtyFromY = null;
  1549. updatePageGuides();
  1550. }
  1551. if (caretInside && anchors[0].lines[0]) {
  1552. // the caret's line is gone: put it at the start of the new table
  1553. try {
  1554. var r = document.createRange();
  1555. r.setStart(anchors[0].lines[0], 0);
  1556. r.collapse(true);
  1557. var sel = window.getSelection();
  1558. sel.removeAllRanges();
  1559. sel.addRange(r);
  1560. savedRange = r.cloneRange();
  1561. } catch (err) { }
  1562. }
  1563. afterEdit(true);
  1564. scheduleTocOverlay();
  1565. if (quiet !== true) OfficeApp.setStatus("Table of contents updated");
  1566. }
  1567. // Ctrl+click on an entry: go to the heading it lists
  1568. function followTocEntry(p) {
  1569. if (p.classList.contains("doc-toc-title")) return false;
  1570. var level = parseInt(p.getAttribute("data-toc-level"), 10);
  1571. if (level === 0) return false; // the "no headings" line
  1572. var hit = null;
  1573. // an imported entry links to its heading's bookmark
  1574. var link = p.querySelector('a[href^="#"]');
  1575. if (link) {
  1576. try {
  1577. var target = editor.querySelector("#" + CSS.escape(decodeURIComponent(link.getAttribute("href").substring(1))));
  1578. if (target && /^H[1-6]$/.test(target.tagName)) hit = target;
  1579. } catch (err) { }
  1580. }
  1581. var c = p.cloneNode(true);
  1582. var tabs = c.querySelectorAll(".doc-tab");
  1583. if (tabs.length) {
  1584. // the text before the tab; the page number follows it
  1585. var t = tabs[tabs.length - 1];
  1586. var cut = document.createRange();
  1587. cut.setStartBefore(t);
  1588. cut.setEndAfter(c.lastChild);
  1589. cut.deleteContents();
  1590. }
  1591. var want = (c.textContent || "").split(ZWSP).join("").replace(/\s+/g, " ").trim();
  1592. var heads = editor.querySelectorAll("h1, h2, h3, h4, h5, h6");
  1593. for (var i = 0; i < heads.length && !hit; i++) {
  1594. var h = heads[i];
  1595. if (h.classList.contains("doc-split-tail") || headingText(h) !== want) continue;
  1596. if (!(level > 0) || parseInt(h.tagName.substring(1), 10) === level) hit = h;
  1597. }
  1598. if (!hit) {
  1599. OfficeApp.setStatus("That heading is not in the document any more - update the table", "info", 4000);
  1600. return true;
  1601. }
  1602. try {
  1603. var r = document.createRange();
  1604. r.setStart(hit, 0);
  1605. r.collapse(true);
  1606. var sel = window.getSelection();
  1607. sel.removeAllRanges();
  1608. sel.addRange(r);
  1609. savedRange = r.cloneRange();
  1610. } catch (err) { }
  1611. hit.scrollIntoView({ block: "start" });
  1612. return true;
  1613. }
  1614. /* The frame and tab of the table the caret or the mouse is in: drawn
  1615. in #page (layout px, zoomed with it) above the text, one box per
  1616. page the table covers, the tab above the first. Editor chrome only -
  1617. the PDF exporter skips .doc-toc-frame and print hides it. */
  1618. var tocOverlay = null, tocHover = null, tocHoverTimer = null, tocOverlayTimer = null;
  1619. function scheduleTocOverlay() {
  1620. if (tocOverlayTimer) return;
  1621. tocOverlayTimer = setTimeout(function () {
  1622. tocOverlayTimer = null;
  1623. drawTocOverlay();
  1624. }, 0);
  1625. }
  1626. function caretTocGroup() {
  1627. var sel = window.getSelection();
  1628. if (!sel || !sel.rangeCount || !editor.contains(sel.anchorNode)) return null;
  1629. return tocGroupOf(sel.anchorNode);
  1630. }
  1631. function drawTocOverlay() {
  1632. if (!pageEl) return;
  1633. var group = caretTocGroup();
  1634. var active = !!group;
  1635. if (!group && tocHover && tocHover[0] && tocHover[0].isConnected) group = tocGroupOf(tocHover[0]);
  1636. if (!group) {
  1637. if (tocOverlay) tocOverlay.style.display = "none";
  1638. return;
  1639. }
  1640. if (!tocOverlay) {
  1641. tocOverlay = document.createElement("div");
  1642. tocOverlay.className = "doc-toc-frame of-noprint";
  1643. tocOverlay.addEventListener("mouseenter", function () { clearTimeout(tocHoverTimer); });
  1644. tocOverlay.addEventListener("mouseleave", leaveTocHover);
  1645. pageEl.appendChild(tocOverlay);
  1646. }
  1647. tocOverlay.style.display = "";
  1648. tocOverlay.classList.toggle("active", active);
  1649. // one box per page the table is on
  1650. var boxes = [];
  1651. group.forEach(function (p) {
  1652. var top = offsetTopInPage(p);
  1653. var pg = pageIndexAt(top);
  1654. var b = boxes.length ? boxes[boxes.length - 1] : null;
  1655. if (!b || b.page !== pg) boxes.push(b = { page: pg, top: top, bottom: top });
  1656. b.bottom = Math.max(b.bottom, top + p.offsetHeight);
  1657. });
  1658. var left = editor.offsetLeft - 6;
  1659. var width = editor.offsetWidth + 12;
  1660. var html = "";
  1661. boxes.forEach(function (b, i) {
  1662. html += '<div class="doc-toc-box" style="left:' + left + "px;top:" + (b.top - 4) + "px;width:" + width +
  1663. "px;height:" + (b.bottom - b.top + 8) + 'px;"></div>';
  1664. if (i === 0) {
  1665. html += '<div class="doc-toc-tab" style="left:' + left + "px;top:" + (b.top - 4) + 'px;">' +
  1666. '<button type="button" class="doc-toc-update" title="Update the table from the headings (Ctrl+click an entry to go to its heading)">' +
  1667. '<i class="sync alternate icon"></i>Update table</button></div>';
  1668. }
  1669. });
  1670. tocOverlay.innerHTML = html;
  1671. var btn = tocOverlay.querySelector(".doc-toc-update");
  1672. // keep the caret where it is: the button never takes the focus
  1673. btn.addEventListener("mousedown", function (e) { e.preventDefault(); });
  1674. btn.addEventListener("click", function (e) {
  1675. e.preventDefault();
  1676. var g = caretTocGroup() || (tocHover && tocHover[0] && tocHover[0].isConnected ? tocGroupOf(tocHover[0]) : null);
  1677. updateToc(false, g || undefined);
  1678. });
  1679. }
  1680. function leaveTocHover() {
  1681. clearTimeout(tocHoverTimer);
  1682. // time to cross from the lines to the tab above them
  1683. tocHoverTimer = setTimeout(function () {
  1684. tocHover = null;
  1685. scheduleTocOverlay();
  1686. }, 400);
  1687. }
  1688. function trackTocHover(e) {
  1689. var p = e.target && e.target.closest ? e.target.closest("p.doc-toc") : null;
  1690. if (p && editor.contains(p)) {
  1691. clearTimeout(tocHoverTimer);
  1692. if (!tocHover || tocHover.indexOf(p) < 0) {
  1693. tocHover = tocGroupOf(p);
  1694. scheduleTocOverlay();
  1695. }
  1696. } else if (tocHover && !(e.target.closest && e.target.closest(".doc-toc-frame"))) {
  1697. leaveTocHover();
  1698. }
  1699. }
  1700. /* ---------- Review / View ---------- */
  1701. function toggleSpellcheck() {
  1702. editor.spellcheck = !editor.spellcheck;
  1703. OfficeApp.setSetting("spellcheck", editor.spellcheck);
  1704. editor.focus();
  1705. OfficeRibbon.refresh();
  1706. }
  1707. function wordCountDialog() {
  1708. var text = editor.innerText || "";
  1709. var sel = window.getSelection();
  1710. var selText = (sel && !sel.isCollapsed && sel.rangeCount && editor.contains(sel.getRangeAt(0).commonAncestorContainer)) ?
  1711. sel.toString() : "";
  1712. var count = function (t) {
  1713. return {
  1714. words: (t.match(/\S+/g) || []).length,
  1715. chars: t.replace(/\n/g, "").length,
  1716. charsNoSp: t.replace(/\s/g, "").length,
  1717. paras: (t.split(/\n+/).filter(function (x) { return x.trim(); })).length
  1718. };
  1719. };
  1720. var all = count(text);
  1721. var rows = [
  1722. ["Pages", String(lastPages.length || 1)],
  1723. ["Words", all.words],
  1724. ["Characters (no spaces)", all.charsNoSp],
  1725. ["Characters (with spaces)", all.chars],
  1726. ["Paragraphs", all.paras]
  1727. ];
  1728. if (selText) {
  1729. var s = count(selText);
  1730. rows.push(["Words in the selection", s.words]);
  1731. }
  1732. var html = '<table class="doc-wc">' + rows.map(function (r) {
  1733. return "<tr><td>" + esc(r[0]) + "</td><td>" + esc(String(r[1])) + "</td></tr>";
  1734. }).join("") + "</table>";
  1735. OfficeApp.dialog({ title: "Word count", body: html, buttons: [{ label: "Close", primary: true }] });
  1736. }
  1737. // fit the page to the window's width; transient = not the person's
  1738. // chosen zoom (a phone does this by itself)
  1739. function fitPageWidth(transient) {
  1740. var avail = workspaceEl.clientWidth - 28;
  1741. var w = pageEl.offsetWidth;
  1742. if (!(avail > 0 && w > 0)) return;
  1743. var z = Math.floor(avail / w * 100);
  1744. OfficeApp.setZoom(Math.max(25, Math.min(transient ? 100 : 400, z)), { transient: !!transient });
  1745. }
  1746. /* ---------- Insert / Draw: drawings ---------- */
  1747. function drawingDialog(penId) {
  1748. if (inHeaderFooter()) return;
  1749. OfficeSketch.open({
  1750. title: "Drawing", pen: penId,
  1751. onInsert: function (blob, w, h) {
  1752. OfficeApp.blobToSrc(blob, "drawing.png", function (src) {
  1753. // shown at the size it was drawn, never wider than the text
  1754. var geo = pageGeometry();
  1755. var scale = Math.min(1, geo.contentW / w);
  1756. insertImage(src, w * scale, h * scale);
  1757. }, function (msg) { OfficeApp.toast(msg, "error"); });
  1758. }
  1759. });
  1760. }
  1761. function scheduleToolbarState() {
  1762. clearTimeout(stateTimer);
  1763. stateTimer = setTimeout(updateToolbarState, 90);
  1764. }
  1765. function updateToolbarState() {
  1766. var states = ["bold", "italic", "underline", "strikeThrough", "subscript", "superscript",
  1767. "justifyLeft", "justifyCenter", "justifyRight", "justifyFull",
  1768. "insertUnorderedList", "insertOrderedList"];
  1769. // by class rather than under #toolbar: a folded ribbon group shows
  1770. // its buttons in a popup outside it
  1771. var picAlign = selectedImg && editor.contains(selectedImg) ? pictureAlign(selectedImg) : null;
  1772. states.forEach(function (c) {
  1773. var on = false;
  1774. if (picAlign && PICTURE_ALIGN[c]) {
  1775. $('.of-rb-btn[data-cmd="' + c + '"]').toggleClass("active", PICTURE_ALIGN[c] === picAlign);
  1776. return;
  1777. }
  1778. try { on = document.queryCommandState(c); } catch (e) { }
  1779. $('.of-rb-btn[data-cmd="' + c + '"]').toggleClass("active", !!on);
  1780. });
  1781. // font family
  1782. var fn = "";
  1783. try { fn = document.queryCommandValue("fontName") || ""; } catch (e) { }
  1784. fn = String(fn).replace(/['"]/g, "").split(",")[0].trim();
  1785. if (fn && $fontSel.find('option[value="' + fn + '"]').length) $fontSel.val(fn);
  1786. // font size + paragraph style from the caret position
  1787. var n = savedRange ? savedRange.startContainer : null;
  1788. // a selection that starts between nodes is about the node after it
  1789. if (n && n.nodeType === 1 && !savedRange.collapsed && savedRange.startOffset < n.childNodes.length) {
  1790. n = n.childNodes[savedRange.startOffset];
  1791. }
  1792. if (n && n.nodeType === 3) n = n.parentNode;
  1793. if (n && n.nodeType === 1 && editor.contains(n)) {
  1794. try {
  1795. var px = parseFloat(window.getComputedStyle(n).fontSize);
  1796. var pt = String(Math.round(px * 72 / 96));
  1797. if ($sizeSel.find('option[value="' + pt + '"]').length) $sizeSel.val(pt);
  1798. } catch (e) { }
  1799. var b = n.closest ? n.closest("h1,h2,h3,h4,p,pre,blockquote,li,div") : null;
  1800. var v = "p";
  1801. if (b && editor.contains(b)) {
  1802. if (b.classList.contains("doc-title")) v = "title";
  1803. else if (/^H[1-4]$/.test(b.tagName)) v = b.tagName.toLowerCase();
  1804. // characters given a style of their own (applyCharStyle)
  1805. var cst = n.closest("span[data-cstyle]");
  1806. if (cst && b.contains(cst)) v = cst.getAttribute("data-cstyle");
  1807. }
  1808. if (b && editor.contains(b)) {
  1809. if (b.tagName === "BLOCKQUOTE" || b.closest("blockquote")) v = v === "p" ? "blockquote" : v;
  1810. if (b.tagName === "PRE") v = "pre";
  1811. }
  1812. $styleSel.val(v);
  1813. currentStyle = v;
  1814. // checklist button state
  1815. var li = n.closest ? n.closest("li") : null;
  1816. var inCheck = !!(li && li.parentElement && li.parentElement.classList.contains("of-checklist"));
  1817. $('.of-rb-btn[data-cmd="checklist"]').toggleClass("active", inCheck);
  1818. if (inCheck) $('.of-rb-btn[data-cmd="insertUnorderedList"]').removeClass("active");
  1819. }
  1820. if (window.OfficeRibbon) OfficeRibbon.refresh();
  1821. }
  1822. /* ================= links ================= */
  1823. // unwrap a link, keeping its text
  1824. function removeLink(a) {
  1825. if (!a || !a.parentNode) return;
  1826. while (a.firstChild) a.parentNode.insertBefore(a.firstChild, a);
  1827. a.parentNode.removeChild(a);
  1828. afterEdit(true);
  1829. }
  1830. function linkDialog() {
  1831. if (inHeaderFooter()) return;
  1832. var existing = null;
  1833. var n = savedRange ? savedRange.commonAncestorContainer : null;
  1834. while (n && n !== editor) {
  1835. if (n.nodeType === 1 && n.tagName === "A") { existing = n; break; }
  1836. n = n.parentNode;
  1837. }
  1838. var initText = existing ? existing.textContent : (savedRange ? savedRange.toString() : "");
  1839. var initUrl = existing ? (existing.getAttribute("href") || "") : "";
  1840. var $b = $("<div></div>");
  1841. $b.append("<label>Text to display</label>");
  1842. var $text = $('<input type="text" class="lnk-text">').val(initText);
  1843. $b.append($text);
  1844. $b.append("<label>Link URL</label>");
  1845. var $url = $('<input type="text" class="lnk-url" placeholder="https://example.com">').val(initUrl);
  1846. $b.append($url);
  1847. var buttons = [{ label: "Cancel" }];
  1848. if (existing) {
  1849. buttons.push({
  1850. label: "Remove link", danger: true,
  1851. action: function (close) {
  1852. close();
  1853. removeLink(existing);
  1854. }
  1855. });
  1856. }
  1857. buttons.push({
  1858. label: existing ? "Apply" : "Insert", primary: true,
  1859. action: function (close, $body) {
  1860. var text = $body.find(".lnk-text").val().trim();
  1861. var href = $body.find(".lnk-url").val().trim();
  1862. close();
  1863. if (!href) return;
  1864. if (!/^([a-z][a-z0-9+.-]*:|\/|#)/i.test(href)) href = "https://" + href;
  1865. if (existing) {
  1866. existing.setAttribute("href", href);
  1867. if (text) existing.textContent = text;
  1868. afterEdit(true);
  1869. } else {
  1870. restoreSel();
  1871. var html = '<a href="' + esc(href) + '">' + esc(text || href) + "</a>";
  1872. try { document.execCommand("insertHTML", false, html); } catch (e) { }
  1873. afterEdit(true);
  1874. }
  1875. }
  1876. });
  1877. var d = OfficeApp.dialog({
  1878. title: existing ? "Edit link" : "Insert link",
  1879. body: $b,
  1880. buttons: buttons
  1881. });
  1882. d.body.find(".lnk-url").trigger("focus");
  1883. }
  1884. /* ================= images ================= */
  1885. function imageMenuItems() {
  1886. var items = [];
  1887. // no ArozOS storage to browse in the standalone web edition
  1888. if (OfficePlatform.hasBackend()) {
  1889. items.push({ label: "From ArozOS storage...", icon: "hdd outline", action: insertImageFromStorage });
  1890. }
  1891. items.push({ label: "From this device...", icon: "upload", action: function () { $("#deviceImageInput").trigger("click"); } });
  1892. items.push({ label: "From URL...", icon: "world", action: insertImageFromUrl });
  1893. return items;
  1894. }
  1895. function insertImage(src, w, h) {
  1896. if (!src) return;
  1897. restoreSel();
  1898. // the document states picture sizes in points
  1899. var size = (w > 0 && h > 0) ?
  1900. "width:" + Math.round(w * 0.75 * 10) / 10 + "pt;height:" + Math.round(h * 0.75 * 10) / 10 + "pt;" : "";
  1901. try {
  1902. document.execCommand("insertHTML", false,
  1903. '<img src="' + esc(src) + '" style="' + size + 'max-width:100%;">');
  1904. } catch (e) { }
  1905. afterEdit(true);
  1906. }
  1907. function insertImageFromStorage() {
  1908. try {
  1909. OfficePlatform.pickOpen({
  1910. filter: ["png", "jpg", "jpeg", "gif", "webp", "bmp", "svg"],
  1911. memoryKey: "media"
  1912. }, function (files) {
  1913. // reference the storage file - the server reads it into the
  1914. // saved file, keeping edits and saves lightweight
  1915. insertImage(OfficeApp.mediaUrl(files[0].filepath));
  1916. });
  1917. } catch (e) {
  1918. OfficeApp.toast("File selector unavailable outside ArozOS", "error");
  1919. }
  1920. }
  1921. function insertImageFromUrl() {
  1922. OfficeApp.prompt("Insert image from URL", "Image URL", "", function (v) {
  1923. if (v) insertImage(v.trim());
  1924. });
  1925. }
  1926. function selectImage(img) {
  1927. deselectImage();
  1928. selectedImg = img;
  1929. img.classList.add("of-selimg");
  1930. // put the caret right after the image so Delete/typing behaves naturally
  1931. try {
  1932. var r = document.createRange();
  1933. r.setStartAfter(img);
  1934. r.collapse(true);
  1935. var sel = window.getSelection();
  1936. sel.removeAllRanges();
  1937. sel.addRange(r);
  1938. savedRange = r.cloneRange();
  1939. } catch (e) { }
  1940. imgHandle = document.createElement("div");
  1941. imgHandle.className = "of-img-handle of-noprint";
  1942. imgHandle.title = "Drag to resize";
  1943. document.body.appendChild(imgHandle);
  1944. positionImgHandle();
  1945. imgHandle.addEventListener("pointerdown", startImgResize);
  1946. if (window.OfficeTextEditBar && OfficeTextEditBar.isVisible()) OfficeTextEditBar.hide();
  1947. // the Picture Format tab comes and goes with the selection
  1948. if (window.OfficeRibbon) OfficeRibbon.refresh();
  1949. scheduleToolbarState();
  1950. }
  1951. function deselectImage() {
  1952. if (selectedImg) {
  1953. selectedImg.classList.remove("of-selimg");
  1954. if (!selectedImg.getAttribute("class")) selectedImg.removeAttribute("class");
  1955. selectedImg = null;
  1956. }
  1957. var had = !!imgHandle;
  1958. if (imgHandle) {
  1959. if (imgHandle.parentNode) imgHandle.parentNode.removeChild(imgHandle);
  1960. imgHandle = null;
  1961. }
  1962. if (had && window.OfficeRibbon) OfficeRibbon.refresh();
  1963. }
  1964. function positionImgHandle() {
  1965. if (!selectedImg || !imgHandle) return;
  1966. var r = selectedImg.getBoundingClientRect();
  1967. imgHandle.style.left = (r.right - 7) + "px";
  1968. imgHandle.style.top = (r.bottom - 7) + "px";
  1969. }
  1970. function startImgResize(e) {
  1971. if (!selectedImg) return;
  1972. e.preventDefault();
  1973. e.stopPropagation();
  1974. var startX = e.clientX;
  1975. var startW = selectedImg.getBoundingClientRect().width; // visual px
  1976. var z = (OfficeApp.getZoom() || 100) / 100;
  1977. // keep the frame's own shape: a cropped (or stretched) picture is
  1978. // not the shape of its source, which height:auto would bring back
  1979. var cs = window.getComputedStyle(selectedImg);
  1980. var cw = parseFloat(cs.width), ch = parseFloat(cs.height);
  1981. var ratio = cw > 0 && ch > 0 ? ch / cw : 0;
  1982. function move(ev) {
  1983. var w = Math.max(24, (startW + (ev.clientX - startX)) / z);
  1984. selectedImg.style.width = Math.round(w) + "px";
  1985. selectedImg.style.height = ratio ? Math.round(w * ratio) + "px" : "auto";
  1986. positionImgHandle();
  1987. }
  1988. var realign = keepPictureAlign(selectedImg);
  1989. function up() {
  1990. document.removeEventListener("pointermove", move);
  1991. document.removeEventListener("pointerup", up);
  1992. afterEdit(true);
  1993. realign();
  1994. }
  1995. document.addEventListener("pointermove", move);
  1996. document.addEventListener("pointerup", up);
  1997. }
  1998. /* ================= picture format =================
  1999. What the Picture Format tab, the picture context menu and a double
  2000. click work with. Everything is stored the way the .docx reader and
  2001. writer already speak it, so it saves and reopens unchanged:
  2002. size width / height on the img
  2003. crop object-fit:fill + object-view-box:inset(t% r% b% l%)
  2004. (DrawingML srcRect)
  2005. border border:<w>pt solid <color> (the picture outline)
  2006. wrap inline (no class), or img.doc-anchor: display:block (top
  2007. and bottom, placed by margin-left) or float:left/right
  2008. (square) - see the docx reader's anchor import */
  2009. function pictureZoom() { return (OfficeApp.getZoom() || 100) / 100; }
  2010. /* object-view-box is Chromium only: Firefox and Safari drop it from the
  2011. style, so there the crop lives in data-crop (the same inset() text)
  2012. and is painted as the picture's background instead - the picture's
  2013. own content is pushed out of its box. cleanedHtml turns it back into
  2014. object-view-box, so the saved document is the same in every browser. */
  2015. var NATIVE_CROP = !!(window.CSS && CSS.supports && CSS.supports("object-view-box", "inset(1%)"));
  2016. var CROP_PAINT_PROPS = ["object-fit", "object-position", "background-image", "background-repeat",
  2017. "background-origin", "background-clip", "background-size", "background-position"];
  2018. var INSET_RE = /inset\(\s*([-\d.]+)%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*\)/;
  2019. function rawViewBox(img) {
  2020. var m = /object-view-box\s*:\s*(inset\([^)]*\))/i.exec(img.getAttribute("style") || "");
  2021. return m ? m[1] : "";
  2022. }
  2023. function paintCropFallback(img, c) {
  2024. var w = 100 - c[1] - c[3], h = 100 - c[0] - c[2];
  2025. var f = function (v) { return Math.round(v * 1000) / 1000 + "%"; };
  2026. img.style.setProperty("object-fit", "none");
  2027. img.style.setProperty("object-position", "-100000px -100000px");
  2028. img.style.setProperty("background-image", 'url("' + String(img.src).replace(/"/g, "%22") + '")');
  2029. img.style.setProperty("background-repeat", "no-repeat");
  2030. img.style.setProperty("background-origin", "content-box");
  2031. img.style.setProperty("background-clip", "content-box");
  2032. img.style.setProperty("background-size", f(10000 / w) + " " + f(10000 / h));
  2033. img.style.setProperty("background-position",
  2034. f(c[1] + c[3] > 0 ? 100 * c[3] / (c[1] + c[3]) : 0) + " " +
  2035. f(c[0] + c[2] > 0 ? 100 * c[0] / (c[0] + c[2]) : 0));
  2036. }
  2037. // pictures loaded or pasted with an object-view-box crop the browser
  2038. // cannot show get the fallback painting
  2039. function upgradeCrops(root) {
  2040. if (NATIVE_CROP || !root) return;
  2041. var list = root.querySelectorAll('img[style*="object-view-box"]:not([data-crop])');
  2042. for (var i = 0; i < list.length; i++) {
  2043. var v = rawViewBox(list[i]);
  2044. if (!v) continue;
  2045. list[i].setAttribute("data-crop", v);
  2046. paintCropFallback(list[i], pictureCrop(list[i]));
  2047. }
  2048. }
  2049. // the saved form of a fallback-painted crop (on a copy of the picture)
  2050. function canonicalCrop(img) {
  2051. var v = img.getAttribute("data-crop");
  2052. if (v === null) return;
  2053. img.removeAttribute("data-crop");
  2054. CROP_PAINT_PROPS.forEach(function (p) { img.style.removeProperty(p); });
  2055. var st = (img.getAttribute("style") || "").replace(/\s*;?\s*$/, "");
  2056. img.setAttribute("style", (st ? st + "; " : "") + "object-fit: fill; object-view-box: " + v + ";");
  2057. }
  2058. function pictureCrop(img) {
  2059. var m = INSET_RE.exec(img.getAttribute("data-crop") ||
  2060. img.style.getPropertyValue("object-view-box") || rawViewBox(img));
  2061. if (!m) return [0, 0, 0, 0];
  2062. var t = parseFloat(m[1]) || 0;
  2063. var r = m[2] !== undefined ? parseFloat(m[2]) || 0 : t;
  2064. var b = m[3] !== undefined ? parseFloat(m[3]) || 0 : t;
  2065. var l = m[4] !== undefined ? parseFloat(m[4]) || 0 : r;
  2066. return [t, r, b, l];
  2067. }
  2068. function setPictureCrop(img, c) {
  2069. if (c[0] <= 0 && c[1] <= 0 && c[2] <= 0 && c[3] <= 0) {
  2070. img.style.removeProperty("object-view-box");
  2071. img.style.removeProperty("object-fit");
  2072. if (img.hasAttribute("data-crop")) {
  2073. img.removeAttribute("data-crop");
  2074. CROP_PAINT_PROPS.forEach(function (p) { img.style.removeProperty(p); });
  2075. }
  2076. return;
  2077. }
  2078. var f = function (v) { return Math.round(v * 1000) / 1000 + "%"; };
  2079. if (!NATIVE_CROP) {
  2080. img.setAttribute("data-crop", "inset(" + f(c[0]) + " " + f(c[1]) + " " + f(c[2]) + " " + f(c[3]) + ")");
  2081. paintCropFallback(img, c);
  2082. return;
  2083. }
  2084. img.style.setProperty("object-fit", "fill");
  2085. img.style.setProperty("object-view-box", "inset(" + f(c[0]) + " " + f(c[1]) + " " + f(c[2]) + " " + f(c[3]) + ")");
  2086. }
  2087. // the picture's wrapping: "inline", "top" (top and bottom), "left" or
  2088. // "right" (text flows round it)
  2089. function pictureWrap(img) {
  2090. if (!img.classList.contains("doc-anchor")) return "inline";
  2091. var fl = img.style.cssFloat || img.style.float;
  2092. return fl === "left" || fl === "right" ? fl : "top";
  2093. }
  2094. // the width the picture lays out in (layout px, unzoomed)
  2095. function pictureColumnWidth(img) {
  2096. var host = img.parentElement;
  2097. while (host && host !== editor && window.getComputedStyle(host).display.indexOf("inline") === 0) {
  2098. host = host.parentElement;
  2099. }
  2100. host = host || editor;
  2101. var cs = window.getComputedStyle(host);
  2102. return host.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0);
  2103. }
  2104. function pictureAlign(img) {
  2105. var wrap = pictureWrap(img);
  2106. if (wrap === "left" || wrap === "right") return wrap;
  2107. if (wrap === "top") {
  2108. // placed by its margin: compare it with the room beside it
  2109. var mlv = img.style.marginLeft || "";
  2110. var ml = (parseFloat(mlv) || 0) * (/pt$/.test(mlv) ? 4 / 3 : 1);
  2111. var free = pictureColumnWidth(img) - img.offsetWidth;
  2112. if (free <= 3) return "left";
  2113. if (Math.abs(ml - free / 2) < 3) return "center";
  2114. return ml >= free - 3 ? "right" : "left";
  2115. }
  2116. var blk = pictureBlock(img, false);
  2117. var ta = blk ? window.getComputedStyle(blk).textAlign : "left";
  2118. if (ta === "center") return "center";
  2119. if (ta === "right" || ta === "end") return "right";
  2120. return "left";
  2121. }
  2122. // the paragraph an inline picture sits in (made when create is set and
  2123. // the picture has none, e.g. one dropped straight into the body)
  2124. function pictureBlock(img, create) {
  2125. var n = img.parentElement;
  2126. while (n && n !== editor) {
  2127. if (/^(P|DIV|H[1-6]|LI|TD|TH|BLOCKQUOTE|PRE)$/.test(n.tagName)) return n;
  2128. n = n.parentElement;
  2129. }
  2130. if (!create) return null;
  2131. var p = document.createElement("p");
  2132. img.parentNode.insertBefore(p, img);
  2133. p.appendChild(img);
  2134. return p;
  2135. }
  2136. /* Align a picture. An inline one follows its paragraph's alignment; an
  2137. anchored one is its own box, which text-align cannot move (that was
  2138. the bug: Center wrote text-align onto the img and nothing happened),
  2139. so it is placed by its margin - the docx writer's horizontal offset -
  2140. or by the side it floats to. */
  2141. function alignPicture(img, how) {
  2142. if (!img) return;
  2143. var wrap = pictureWrap(img);
  2144. if (wrap === "inline") {
  2145. var blk = pictureBlock(img, true);
  2146. blk.style.textAlign = how === "justify" ? "left" : how;
  2147. } else if (wrap === "left" || wrap === "right") {
  2148. if (how === "center") {
  2149. setPictureWrap(img, "top");
  2150. alignPicture(img, "center");
  2151. return;
  2152. }
  2153. setPictureWrap(img, how === "right" ? "right" : "left");
  2154. } else {
  2155. var free = Math.max(0, pictureColumnWidth(img) - img.offsetWidth);
  2156. var x = how === "center" ? free / 2 : how === "right" ? free : 0;
  2157. if (x > 0) img.style.marginLeft = Math.round(x * 0.75 * 10) / 10 + "pt";
  2158. else img.style.removeProperty("margin-left");
  2159. }
  2160. positionImgHandle();
  2161. afterEdit(true);
  2162. OfficeRibbon.refresh();
  2163. }
  2164. function setPictureWrap(img, wrap) {
  2165. var s = img.style;
  2166. ["float", "display", "margin-left", "margin-right", "margin-top", "max-width"].forEach(function (p) {
  2167. s.removeProperty(p);
  2168. });
  2169. if (wrap === "inline") {
  2170. img.classList.remove("doc-anchor");
  2171. } else {
  2172. img.classList.add("doc-anchor");
  2173. s.maxWidth = "none";
  2174. if (wrap === "left" || wrap === "right") {
  2175. s.cssFloat = wrap;
  2176. s.marginLeft = "9pt";
  2177. s.marginRight = "9pt";
  2178. } else {
  2179. s.display = "block";
  2180. }
  2181. }
  2182. }
  2183. function applyPictureWrap(wrap) {
  2184. var img = selectedImg;
  2185. if (!img) return;
  2186. setPictureWrap(img, wrap);
  2187. positionImgHandle();
  2188. afterEdit(true);
  2189. OfficeRibbon.refresh();
  2190. }
  2191. function pictureBorder(img) {
  2192. var w = parseFloat(img.style.borderTopWidth) || 0;
  2193. if (!w || img.style.borderTopStyle === "none") return null;
  2194. var unitPt = /pt$/.test(img.style.borderTopWidth) ? 1 : 0.75;
  2195. return { w: Math.round(w * unitPt * 100) / 100, color: img.style.borderTopColor || "#000000" };
  2196. }
  2197. function setPictureBorder(img, w, color) {
  2198. if (!w || color === null) {
  2199. img.style.removeProperty("border");
  2200. } else {
  2201. img.style.border = w + "pt solid " + (color || "#000000");
  2202. }
  2203. }
  2204. function applyPictureBorderColor(c) {
  2205. var img = selectedImg;
  2206. if (!img) return;
  2207. var cur = pictureBorder(img);
  2208. setPictureBorder(img, c ? (cur ? cur.w : 1) : 0, c || null);
  2209. afterEdit(true);
  2210. positionImgHandle();
  2211. }
  2212. function pictureWeightItems() {
  2213. return [0.75, 1.5, 2.25, 3, 4.5, 6].map(function (w) {
  2214. return {
  2215. label: w + " pt", checked: function () { var b = selectedImg && pictureBorder(selectedImg); return !!b && Math.abs(b.w - w) < 0.01; },
  2216. action: function () {
  2217. var img = selectedImg;
  2218. if (!img) return;
  2219. var cur = pictureBorder(img);
  2220. setPictureBorder(img, w, cur ? img.style.borderTopColor : "#000000");
  2221. afterEdit(true);
  2222. positionImgHandle();
  2223. }
  2224. };
  2225. }).concat([{ sep: true }, {
  2226. label: "No border", action: function () {
  2227. if (!selectedImg) return;
  2228. setPictureBorder(selectedImg, 0);
  2229. afterEdit(true);
  2230. }
  2231. }]);
  2232. }
  2233. function pictureWrapItems() {
  2234. var opt = function (wrap, label, icon) {
  2235. return {
  2236. label: label, icon: icon,
  2237. checked: function () { return !!selectedImg && pictureWrap(selectedImg) === wrap; },
  2238. action: function () { applyPictureWrap(wrap); }
  2239. };
  2240. };
  2241. return [
  2242. opt("inline", "In line with text", "align left"),
  2243. opt("left", "Square, on the left", "indent"),
  2244. opt("right", "Square, on the right", "outdent"),
  2245. opt("top", "Top and bottom", "bars")
  2246. ];
  2247. }
  2248. function pictureAlignItems() {
  2249. var opt = function (how, label, icon) {
  2250. return {
  2251. label: label, icon: icon,
  2252. checked: function () { return !!selectedImg && pictureAlign(selectedImg) === how; },
  2253. action: function () { alignPicture(selectedImg, how); }
  2254. };
  2255. };
  2256. return [opt("left", "Align left", "align left"), opt("center", "Center", "align center"),
  2257. opt("right", "Align right", "align right")];
  2258. }
  2259. // Reset picture: no crop, no border, its own size (within the column)
  2260. function resetPicture(img) {
  2261. if (!img) return;
  2262. var realign = keepPictureAlign(img);
  2263. setPictureCrop(img, [0, 0, 0, 0]);
  2264. setPictureBorder(img, 0);
  2265. if (img.naturalWidth > 0) {
  2266. img.style.width = Math.round(img.naturalWidth * 0.75 * 10) / 10 + "pt";
  2267. img.style.height = Math.round(img.naturalHeight * 0.75 * 10) / 10 + "pt";
  2268. } else {
  2269. img.style.removeProperty("width");
  2270. img.style.removeProperty("height");
  2271. }
  2272. positionImgHandle();
  2273. afterEdit(true);
  2274. realign();
  2275. }
  2276. // an anchored picture is placed by its margin, so one centred or set
  2277. // right has to be placed again once its width changes
  2278. function keepPictureAlign(img) {
  2279. var al = pictureWrap(img) === "top" ? pictureAlign(img) : null;
  2280. return function () { if (al && al !== "left") alignPicture(img, al); };
  2281. }
  2282. function deleteSelectedPicture() {
  2283. var img = selectedImg;
  2284. if (!img) return;
  2285. deselectImage();
  2286. if (img.parentNode) img.parentNode.removeChild(img);
  2287. afterEdit(true);
  2288. }
  2289. /* Crop: the whole picture in a dialog, with the kept part as a box to
  2290. drag (by its edges, corners or middle) or to type in. The frame on
  2291. the page shrinks with the crop, as Word's does, so what is left keeps
  2292. its scale. */
  2293. function cropPictureDialog(img) {
  2294. if (!img) return;
  2295. var start = pictureCrop(img);
  2296. var crop = start.slice();
  2297. var $b = $('<div class="doc-crop"></div>');
  2298. var $stage = $('<div class="doc-crop-stage"></div>');
  2299. var $pic = $('<img class="doc-crop-img" alt="">').attr("src", img.src);
  2300. var $box = $('<div class="doc-crop-box"></div>');
  2301. ["n", "s", "e", "w", "ne", "nw", "se", "sw"].forEach(function (h) {
  2302. $box.append($('<span class="doc-crop-h"></span>').attr("data-h", h));
  2303. });
  2304. $stage.append($pic, $box);
  2305. var $fields = $('<div class="doc-crop-fields"></div>');
  2306. var names = ["Top", "Right", "Bottom", "Left"];
  2307. names.forEach(function (n, i) {
  2308. $fields.append($("<label></label>").text(n + " %").append(
  2309. $('<input type="number" min="0" max="95" step="0.5">').attr("data-i", i)));
  2310. });
  2311. $b.append($stage, $fields);
  2312. var W = 0, H = 0;
  2313. function layout() {
  2314. var nw = $pic[0].naturalWidth || 400, nh = $pic[0].naturalHeight || 300;
  2315. var k = Math.min(440 / nw, 320 / nh, 1.5);
  2316. W = Math.round(nw * k); H = Math.round(nh * k);
  2317. $stage.css({ width: W + "px", height: H + "px" });
  2318. $pic.css({ width: W + "px", height: H + "px" });
  2319. draw();
  2320. }
  2321. function draw() {
  2322. var bl = crop[3] * W / 100, bt = crop[0] * H / 100;
  2323. // the kept part shows at full strength: the picture as the box's
  2324. // background, shifted back by where the box sits (and its border)
  2325. $box.css({
  2326. left: bl + "px", top: bt + "px",
  2327. right: (crop[1] * W / 100) + "px", bottom: (crop[2] * H / 100) + "px",
  2328. backgroundImage: 'url("' + String(img.src).replace(/"/g, "%22") + '")',
  2329. backgroundSize: W + "px " + H + "px",
  2330. backgroundPosition: (-bl - 2) + "px " + (-bt - 2) + "px"
  2331. });
  2332. $fields.find("input").each(function () {
  2333. var i = +this.getAttribute("data-i");
  2334. if (document.activeElement !== this) this.value = Math.round(crop[i] * 10) / 10;
  2335. });
  2336. }
  2337. // keep at least 5% of the picture each way
  2338. function clampCrop() {
  2339. for (var i = 0; i < 4; i++) crop[i] = Math.max(0, Math.min(95, crop[i]));
  2340. if (crop[0] + crop[2] > 95) crop[2] = 95 - crop[0];
  2341. if (crop[1] + crop[3] > 95) crop[1] = 95 - crop[3];
  2342. }
  2343. $fields.on("input", "input", function () {
  2344. var v = parseFloat(this.value);
  2345. crop[+this.getAttribute("data-i")] = isNaN(v) ? 0 : v;
  2346. clampCrop();
  2347. draw();
  2348. });
  2349. $stage.on("pointerdown", function (e) {
  2350. var h = $(e.target).attr("data-h") || (e.target === $box[0] ? "move" : null);
  2351. if (!h) return;
  2352. e.preventDefault();
  2353. var sx = e.clientX, sy = e.clientY, c0 = crop.slice();
  2354. OfficeApp.beginDrag(e, {
  2355. cursor: window.getComputedStyle(e.target).cursor,
  2356. move: function (ev) {
  2357. var dx = (ev.clientX - sx) * 100 / W, dy = (ev.clientY - sy) * 100 / H;
  2358. crop = c0.slice();
  2359. if (h === "move") {
  2360. dx = Math.max(-c0[3], Math.min(c0[1], dx));
  2361. dy = Math.max(-c0[0], Math.min(c0[2], dy));
  2362. crop[3] = c0[3] + dx; crop[1] = c0[1] - dx;
  2363. crop[0] = c0[0] + dy; crop[2] = c0[2] - dy;
  2364. } else {
  2365. if (h.indexOf("n") >= 0) crop[0] = c0[0] + dy;
  2366. if (h.indexOf("s") >= 0) crop[2] = c0[2] - dy;
  2367. if (h.indexOf("w") >= 0) crop[3] = c0[3] + dx;
  2368. if (h.indexOf("e") >= 0) crop[1] = c0[1] - dx;
  2369. }
  2370. clampCrop();
  2371. draw();
  2372. }
  2373. });
  2374. });
  2375. if ($pic[0].complete) setTimeout(layout, 0); else $pic.on("load", layout);
  2376. OfficeApp.dialog({
  2377. title: "Crop picture",
  2378. body: $b,
  2379. buttons: [
  2380. { label: "Cancel" },
  2381. { label: "Reset", action: function () { crop = [0, 0, 0, 0]; draw(); } },
  2382. {
  2383. label: "Crop", primary: true, action: function (close) {
  2384. close();
  2385. var realign = keepPictureAlign(img);
  2386. // the frame keeps the picture's scale: it grows or
  2387. // shrinks by the share of the picture now shown
  2388. var r = img.getBoundingClientRect(), z = pictureZoom();
  2389. var w = r.width / z, hgt = r.height / z;
  2390. var oldW = (100 - start[1] - start[3]) / 100, oldH = (100 - start[0] - start[2]) / 100;
  2391. var newW = (100 - crop[1] - crop[3]) / 100, newH = (100 - crop[0] - crop[2]) / 100;
  2392. if (oldW > 0 && oldH > 0 && w > 0 && hgt > 0) {
  2393. img.style.width = Math.round(w * newW / oldW * 0.75 * 10) / 10 + "pt";
  2394. img.style.height = Math.round(hgt * newH / oldH * 0.75 * 10) / 10 + "pt";
  2395. }
  2396. setPictureCrop(img, crop);
  2397. positionImgHandle();
  2398. afterEdit(true);
  2399. realign();
  2400. }
  2401. }
  2402. ]
  2403. });
  2404. }
  2405. /* Size & properties: width / height (aspect kept unless unlocked), the
  2406. wrapping, and the alt text screen readers and the .docx carry. */
  2407. function imageSizeDialog(img) {
  2408. if (!img) return;
  2409. var r = img.getBoundingClientRect(), z = pictureZoom();
  2410. var curW = Math.round(r.width / z * 0.75 * 10) / 10, curH = Math.round(r.height / z * 0.75 * 10) / 10;
  2411. var ratio = curW > 0 ? curH / curW : 0.75;
  2412. var $b = $('<div class="doc-picprops"></div>');
  2413. var $w = $('<input type="number" min="6" max="3000" step="0.5" class="img-w">').val(curW);
  2414. var $h = $('<input type="number" min="6" max="3000" step="0.5" class="img-h">').val(curH);
  2415. var $lock = $('<input type="checkbox" class="img-lock" checked>');
  2416. var $row = $('<div class="doc-picprops-row"></div>');
  2417. $row.append($("<label>Width (pt)</label>").append($w), $("<label>Height (pt)</label>").append($h));
  2418. $b.append($row);
  2419. $b.append($('<label class="doc-picprops-check"></label>').append($lock, " Keep the proportions"));
  2420. var $wrap = $('<select class="img-wrap"></select>');
  2421. pictureWrapItems().forEach(function (it, i) {
  2422. $wrap.append($("<option></option>").val(["inline", "left", "right", "top"][i]).text(it.label));
  2423. });
  2424. $wrap.val(pictureWrap(img));
  2425. $b.append($("<label>Text wrapping</label>").append($wrap));
  2426. var $alt = $('<textarea rows="2" class="img-alt" placeholder="Describe the picture for people who cannot see it"></textarea>')
  2427. .val(img.getAttribute("alt") || "");
  2428. $b.append($("<label>Alt text</label>").append($alt));
  2429. $w.on("input", function () { if ($lock.prop("checked")) $h.val(Math.round(this.value * ratio * 10) / 10); });
  2430. $h.on("input", function () { if ($lock.prop("checked") && ratio) $w.val(Math.round(this.value / ratio * 10) / 10); });
  2431. OfficeApp.dialog({
  2432. title: "Picture size & properties",
  2433. body: $b,
  2434. buttons: [
  2435. { label: "Cancel" },
  2436. {
  2437. label: "Reset size", action: function (close) {
  2438. close();
  2439. if (img.naturalWidth > 0) {
  2440. var c = pictureCrop(img);
  2441. img.style.width = Math.round(img.naturalWidth * (100 - c[1] - c[3]) / 100 * 0.75 * 10) / 10 + "pt";
  2442. img.style.height = Math.round(img.naturalHeight * (100 - c[0] - c[2]) / 100 * 0.75 * 10) / 10 + "pt";
  2443. }
  2444. positionImgHandle();
  2445. afterEdit(true);
  2446. }
  2447. },
  2448. {
  2449. label: "Apply", primary: true, action: function (close, $body) {
  2450. var w = parseFloat($body.find(".img-w").val());
  2451. var h = parseFloat($body.find(".img-h").val());
  2452. var wrap = $body.find(".img-wrap").val();
  2453. var alt = $body.find(".img-alt").val().trim();
  2454. close();
  2455. var realign = keepPictureAlign(img);
  2456. if (w >= 6 && h >= 6) {
  2457. img.style.width = w + "pt";
  2458. img.style.height = h + "pt";
  2459. }
  2460. if (alt) img.setAttribute("alt", alt); else img.removeAttribute("alt");
  2461. if (wrap !== pictureWrap(img)) setPictureWrap(img, wrap);
  2462. else realign();
  2463. positionImgHandle();
  2464. afterEdit(true);
  2465. OfficeRibbon.refresh();
  2466. }
  2467. }
  2468. ]
  2469. });
  2470. }
  2471. function pictureMenuItems(img) {
  2472. return [
  2473. { label: "Crop...", icon: "crop", action: function () { cropPictureDialog(img); } },
  2474. { label: "Size & properties...", icon: "expand", action: function () { imageSizeDialog(img); } },
  2475. { label: "Text wrapping", icon: "align left", sub: pictureWrapItems() },
  2476. { label: "Reset picture", icon: "undo", action: function () { resetPicture(img); } },
  2477. { sep: true },
  2478. { label: "Delete picture", icon: "trash alternate outline", action: deleteSelectedPicture }
  2479. ];
  2480. }
  2481. /* ================= tables ================= */
  2482. /* Word-style drag-over grid table creator (Insert > Table) */
  2483. var TGRID_COLS = 10, TGRID_ROWS = 8;
  2484. function insertTable(rows, cols) {
  2485. var html = '<table class="of-table"><tbody>';
  2486. for (var r = 0; r < rows; r++) {
  2487. html += "<tr>";
  2488. for (var c = 0; c < cols; c++) html += "<td><br></td>";
  2489. html += "</tr>";
  2490. }
  2491. html += "</tbody></table><p><br></p>";
  2492. restoreSel();
  2493. try { document.execCommand("insertHTML", false, html); } catch (e) { }
  2494. afterEdit(true);
  2495. }
  2496. function insertTableDialog() {
  2497. if (inHeaderFooter()) return;
  2498. var $b = $("<div></div>");
  2499. var $label = $('<div class="doc-tgrid-label">1 × 1</div>');
  2500. var $grid = $('<div class="doc-tgrid"></div>');
  2501. var dlg;
  2502. var hotR = 1, hotC = 1;
  2503. function paint() {
  2504. $grid.children().each(function () {
  2505. var r = parseInt($(this).attr("data-r"), 10);
  2506. var c = parseInt($(this).attr("data-c"), 10);
  2507. $(this).toggleClass("hot", r <= hotR && c <= hotC);
  2508. });
  2509. $label.text(hotC + " × " + hotR);
  2510. }
  2511. for (var r = 1; r <= TGRID_ROWS; r++) {
  2512. for (var c = 1; c <= TGRID_COLS; c++) {
  2513. var $cell = $('<button type="button" class="doc-tgrid-cell"></button>')
  2514. .attr("data-r", r).attr("data-c", c);
  2515. $grid.append($cell);
  2516. }
  2517. }
  2518. // hover / drag over the grid selects the size, click (or release)
  2519. // inserts - matching the Word ribbon gesture
  2520. $grid.on("pointerover pointermove", ".doc-tgrid-cell", function () {
  2521. hotR = parseInt($(this).attr("data-r"), 10);
  2522. hotC = parseInt($(this).attr("data-c"), 10);
  2523. paint();
  2524. });
  2525. $grid.on("click pointerup", ".doc-tgrid-cell", function () {
  2526. var rr = parseInt($(this).attr("data-r"), 10);
  2527. var cc = parseInt($(this).attr("data-c"), 10);
  2528. dlg.close();
  2529. insertTable(rr, cc);
  2530. });
  2531. var $custom = $('<div class="dlg-two-col" style="margin-top:10px;"></div>');
  2532. $custom.append("<div><label>Rows</label><input type='number' min='1' max='50' class='tbl-rows' value='3'></div>");
  2533. $custom.append("<div><label>Columns</label><input type='number' min='1' max='20' class='tbl-cols' value='3'></div>");
  2534. $b.append($label).append($grid)
  2535. .append('<label style="margin-top:12px;">Custom size</label>')
  2536. .append($custom);
  2537. dlg = OfficeApp.dialog({
  2538. title: "Insert table",
  2539. body: $b,
  2540. buttons: [
  2541. { label: "Cancel" },
  2542. {
  2543. label: "Insert custom size", action: function (close, $body) {
  2544. var rows = Math.min(50, Math.max(1, parseInt($body.find(".tbl-rows").val(), 10) || 3));
  2545. var cols = Math.min(20, Math.max(1, parseInt($body.find(".tbl-cols").val(), 10) || 3));
  2546. close();
  2547. insertTable(rows, cols);
  2548. }
  2549. }
  2550. ]
  2551. });
  2552. paint();
  2553. }
  2554. /* ---------- table styling (themes / borders / banding) ----------
  2555. The style state lives in data attributes on the <table> so toggles
  2556. know it and re-application after row/column edits keeps banding
  2557. consistent; the rendered look is plain inline CSS (survives the
  2558. native format, HTML export and - for shading - docx). Cells with
  2559. data-cellbg carry a user-picked background that themes/banding
  2560. never overwrite. */
  2561. var TABLE_THEMES = [
  2562. { name: "Plain", bc: "#b9bec7", headbg: "#eef1f5", bandbg: "#f4f6f9", headfc: "" },
  2563. { name: "Blue", bc: "#a9c6e8", headbg: "#d9e7f8", bandbg: "#eef4fc", headfc: "" },
  2564. { name: "Green", bc: "#b2d8b4", headbg: "#d9efdb", bandbg: "#effaf0", headfc: "" },
  2565. { name: "Orange", bc: "#f0c9a4", headbg: "#fbe3c9", bandbg: "#fdf3e7", headfc: "" },
  2566. { name: "Dark header", bc: "#9aa0a6", headbg: "#3c4043", bandbg: "#f1f3f4", headfc: "#ffffff" }
  2567. ];
  2568. function applyTableStyle(table) {
  2569. var bw = parseFloat(table.getAttribute("data-th-bw")) || 1;
  2570. var bc = table.getAttribute("data-th-bc") || "#b9bec7";
  2571. var headOn = table.getAttribute("data-th-head") === "1";
  2572. var bandOn = table.getAttribute("data-th-band") === "1";
  2573. var headBg = table.getAttribute("data-th-headbg") || "#e8eaed";
  2574. var headFc = table.getAttribute("data-th-headfc") || "";
  2575. var bandBg = table.getAttribute("data-th-bandbg") || "#f4f5f7";
  2576. for (var r = 0; r < table.rows.length; r++) {
  2577. var row = table.rows[r];
  2578. for (var c = 0; c < row.cells.length; c++) {
  2579. var cell = row.cells[c];
  2580. cell.style.border = bw + "px solid " + bc;
  2581. var custom = cell.getAttribute("data-cellbg");
  2582. var isHead = headOn && r === 0;
  2583. var isBand = bandOn && ((r - (headOn ? 1 : 0)) % 2 === 1);
  2584. if (custom) cell.style.backgroundColor = custom;
  2585. else if (isHead) cell.style.backgroundColor = headBg;
  2586. else if (isBand) cell.style.backgroundColor = bandBg;
  2587. else cell.style.backgroundColor = "";
  2588. cell.style.fontWeight = isHead ? "700" : "";
  2589. cell.style.color = (isHead && headFc) ? headFc : "";
  2590. }
  2591. }
  2592. afterEdit(true);
  2593. }
  2594. function currentCell() {
  2595. if (!savedRange) return null;
  2596. var n = savedRange.startContainer;
  2597. if (n && n.nodeType === 3) n = n.parentNode;
  2598. if (!n || !n.closest || !editor.contains(n)) return null;
  2599. var cell = n.closest("td,th");
  2600. if (!cell) {
  2601. // multi-cell selections anchor at the row/tbody/table level -
  2602. // descend through the range start to the first selected cell
  2603. var host = n.closest("table, tbody, tr");
  2604. if (host) {
  2605. var child = savedRange.startContainer.childNodes ?
  2606. savedRange.startContainer.childNodes[savedRange.startOffset] : null;
  2607. if (child && child.nodeType === 1) {
  2608. if (child.matches && child.matches("td,th")) cell = child;
  2609. else if (child.querySelector) cell = child.querySelector("td,th");
  2610. }
  2611. if (!cell) cell = host.querySelector("td,th");
  2612. }
  2613. }
  2614. return cell && editor.contains(cell) ? cell : null;
  2615. }
  2616. function currentTable() {
  2617. var cell = currentCell();
  2618. return cell ? cell.closest("table") : null;
  2619. }
  2620. function tableAddRow(table, index) {
  2621. var cols = (table.rows[0] ? table.rows[0].cells.length : 1);
  2622. var tr = table.insertRow(index);
  2623. for (var i = 0; i < cols; i++) tr.insertCell(-1).innerHTML = "<br>";
  2624. applyTableStyle(table);
  2625. }
  2626. function tableAddCol(table, index) {
  2627. for (var i = 0; i < table.rows.length; i++) {
  2628. var row = table.rows[i];
  2629. var at = Math.min(index, row.cells.length);
  2630. row.insertCell(at).innerHTML = "<br>";
  2631. }
  2632. applyTableStyle(table);
  2633. }
  2634. function tableDelRow(table, ri) {
  2635. table.deleteRow(ri);
  2636. if (table.rows.length === 0 && table.parentNode) {
  2637. table.parentNode.removeChild(table);
  2638. afterEdit(true);
  2639. return;
  2640. }
  2641. applyTableStyle(table);
  2642. }
  2643. function tableDelCol(table, ci) {
  2644. var empty = true;
  2645. for (var i = 0; i < table.rows.length; i++) {
  2646. var row = table.rows[i];
  2647. if (row.cells.length > ci) row.deleteCell(ci);
  2648. if (row.cells.length > 0) empty = false;
  2649. }
  2650. if (empty && table.parentNode) {
  2651. table.parentNode.removeChild(table);
  2652. afterEdit(true);
  2653. return;
  2654. }
  2655. applyTableStyle(table);
  2656. }
  2657. /* ---------- table ops for the floating text-edit bar ----------
  2658. Rendered by OfficeTextEditBar as an extra divider-separated section
  2659. while the selection is inside a table (incl. multi-cell selections).
  2660. Empty array = section hidden. */
  2661. function withTable(fn) {
  2662. var cell = currentCell();
  2663. var table = cell ? cell.closest("table") : null;
  2664. if (!table) return;
  2665. // a row split across a page is one row again before rows or columns
  2666. // are counted
  2667. if (DocsLayout.unsplitWithin(editor, table)) {
  2668. noteEditAtCaret();
  2669. cell = currentCell() || cell;
  2670. table = cell.closest("table") || table;
  2671. }
  2672. fn(table, cell);
  2673. }
  2674. function docsTableOps() {
  2675. if (!currentCell()) return null;
  2676. return [
  2677. {
  2678. icon: "angle up", title: "Insert row above",
  2679. fn: function () { withTable(function (t, cell) { tableAddRow(t, cell.parentNode.rowIndex); }); }
  2680. },
  2681. {
  2682. icon: "angle down", title: "Insert row below",
  2683. fn: function () { withTable(function (t, cell) { tableAddRow(t, cell.parentNode.rowIndex + 1); }); }
  2684. },
  2685. {
  2686. icon: "angle left", title: "Insert column left",
  2687. fn: function () { withTable(function (t, cell) { tableAddCol(t, cell.cellIndex); }); }
  2688. },
  2689. {
  2690. icon: "angle right", title: "Insert column right",
  2691. fn: function () { withTable(function (t, cell) { tableAddCol(t, cell.cellIndex + 1); }); }
  2692. },
  2693. {
  2694. icon: "minus", title: "Delete row",
  2695. fn: function () { withTable(function (t, cell) { tableDelRow(t, cell.parentNode.rowIndex); }); }
  2696. },
  2697. {
  2698. icon: "eraser", title: "Delete column",
  2699. fn: function () { withTable(function (t, cell) { tableDelCol(t, cell.cellIndex); }); }
  2700. },
  2701. {
  2702. icon: "trash alternate outline", title: "Delete table",
  2703. fn: function () {
  2704. withTable(function (t) {
  2705. if (t.parentNode) t.parentNode.removeChild(t);
  2706. afterEdit(true);
  2707. OfficeTextEditBar.setTableOps(null);
  2708. });
  2709. }
  2710. },
  2711. {
  2712. icon: "heading", title: "Header row",
  2713. active: function () {
  2714. var c = currentCell();
  2715. var t = c ? c.closest("table") : null;
  2716. return !!(t && t.getAttribute("data-th-head") === "1");
  2717. },
  2718. fn: function () {
  2719. withTable(function (t) {
  2720. t.setAttribute("data-th-head", t.getAttribute("data-th-head") === "1" ? "" : "1");
  2721. applyTableStyle(t);
  2722. });
  2723. }
  2724. },
  2725. {
  2726. icon: "bars", title: "Banded rows",
  2727. active: function () {
  2728. var c = currentCell();
  2729. var t = c ? c.closest("table") : null;
  2730. return !!(t && t.getAttribute("data-th-band") === "1");
  2731. },
  2732. fn: function () {
  2733. withTable(function (t) {
  2734. t.setAttribute("data-th-band", t.getAttribute("data-th-band") === "1" ? "" : "1");
  2735. applyTableStyle(t);
  2736. });
  2737. }
  2738. },
  2739. {
  2740. icon: "paint brush", title: "Table theme...",
  2741. fn: function (btnEl) {
  2742. withTable(function (t) {
  2743. var r = btnEl.getBoundingClientRect();
  2744. OfficeApp.showContextMenu(r.left, r.bottom + 2, TABLE_THEMES.map(function (th) {
  2745. return {
  2746. label: th.name,
  2747. action: function () {
  2748. t.setAttribute("data-th-bc", th.bc);
  2749. t.setAttribute("data-th-headbg", th.headbg);
  2750. t.setAttribute("data-th-headfc", th.headfc);
  2751. t.setAttribute("data-th-bandbg", th.bandbg);
  2752. t.setAttribute("data-th-head", "1");
  2753. t.setAttribute("data-th-band", "1");
  2754. applyTableStyle(t);
  2755. }
  2756. };
  2757. }));
  2758. });
  2759. }
  2760. },
  2761. {
  2762. icon: "window minimize outline", title: "Border weight...",
  2763. fn: function (btnEl) {
  2764. withTable(function (t) {
  2765. var r = btnEl.getBoundingClientRect();
  2766. OfficeApp.showContextMenu(r.left, r.bottom + 2, [0.5, 1, 2, 3].map(function (w) {
  2767. return {
  2768. label: w + " px",
  2769. checked: (parseFloat(t.getAttribute("data-th-bw")) || 1) === w,
  2770. action: function () {
  2771. t.setAttribute("data-th-bw", String(w));
  2772. applyTableStyle(t);
  2773. }
  2774. };
  2775. }));
  2776. });
  2777. }
  2778. },
  2779. {
  2780. icon: "pencil alternate", title: "Border color...",
  2781. fn: function (btnEl) {
  2782. withTable(function (t) {
  2783. OfficeColorPicker.open({
  2784. anchor: btnEl,
  2785. value: t.getAttribute("data-th-bc") || "#b9bec7",
  2786. onPick: function (hex) {
  2787. if (!hex) return;
  2788. t.setAttribute("data-th-bc", hex);
  2789. applyTableStyle(t);
  2790. }
  2791. });
  2792. });
  2793. }
  2794. },
  2795. {
  2796. icon: "square full", title: "Cell background...",
  2797. fn: function (btnEl) {
  2798. withTable(function (t, cell) {
  2799. OfficeColorPicker.open({
  2800. anchor: btnEl,
  2801. value: cell.getAttribute("data-cellbg") || "#ffffff",
  2802. allowNone: true, noneLabel: "Clear (use theme)",
  2803. onPick: function (hex) {
  2804. if (hex) cell.setAttribute("data-cellbg", hex);
  2805. else cell.removeAttribute("data-cellbg");
  2806. applyTableStyle(t);
  2807. }
  2808. });
  2809. });
  2810. }
  2811. }
  2812. ];
  2813. }
  2814. /* table items reused as a submenu of the right-click context menu */
  2815. function tableMenuItems() { return tableMenuItemsFor(currentCell()); }
  2816. function tableMenuItemsFor(cell) {
  2817. var table = cell ? cell.closest("table") : null;
  2818. if (!table) {
  2819. return [{ label: "Click inside a table first", enabled: function () { return false; }, action: function () { } }];
  2820. }
  2821. function toggleAttr(attr) {
  2822. table.setAttribute(attr, table.getAttribute(attr) === "1" ? "" : "1");
  2823. applyTableStyle(table);
  2824. }
  2825. var items = [
  2826. {
  2827. label: "Header row", icon: "heading",
  2828. checked: function () { return table.getAttribute("data-th-head") === "1"; },
  2829. action: function () { toggleAttr("data-th-head"); }
  2830. },
  2831. {
  2832. label: "Banded rows", icon: "bars",
  2833. checked: function () { return table.getAttribute("data-th-band") === "1"; },
  2834. action: function () { toggleAttr("data-th-band"); }
  2835. },
  2836. {
  2837. label: "Table theme", icon: "paint brush",
  2838. sub: TABLE_THEMES.map(function (t) {
  2839. return {
  2840. label: t.name,
  2841. action: function () {
  2842. table.setAttribute("data-th-bc", t.bc);
  2843. table.setAttribute("data-th-headbg", t.headbg);
  2844. table.setAttribute("data-th-headfc", t.headfc);
  2845. table.setAttribute("data-th-bandbg", t.bandbg);
  2846. table.setAttribute("data-th-head", "1");
  2847. table.setAttribute("data-th-band", "1");
  2848. applyTableStyle(table);
  2849. }
  2850. };
  2851. })
  2852. },
  2853. {
  2854. label: "Border weight", icon: "window minimize outline",
  2855. sub: [0.5, 1, 2, 3].map(function (w) {
  2856. return {
  2857. label: w + " px",
  2858. checked: function () { return (parseFloat(table.getAttribute("data-th-bw")) || 1) === w; },
  2859. action: function () {
  2860. table.setAttribute("data-th-bw", String(w));
  2861. applyTableStyle(table);
  2862. }
  2863. };
  2864. })
  2865. },
  2866. {
  2867. label: "Border color...", icon: "pencil alternate",
  2868. action: function () {
  2869. OfficeColorPicker.open({
  2870. anchor: cell,
  2871. value: table.getAttribute("data-th-bc") || "#b9bec7",
  2872. onPick: function (hex) {
  2873. if (!hex) return;
  2874. table.setAttribute("data-th-bc", hex);
  2875. applyTableStyle(table);
  2876. }
  2877. });
  2878. }
  2879. },
  2880. {
  2881. label: "Cell background...", icon: "square full",
  2882. action: function () {
  2883. OfficeColorPicker.open({
  2884. anchor: cell,
  2885. value: cell.getAttribute("data-cellbg") || "#ffffff",
  2886. allowNone: true, noneLabel: "Clear (use theme)",
  2887. onPick: function (hex) {
  2888. if (hex) cell.setAttribute("data-cellbg", hex);
  2889. else cell.removeAttribute("data-cellbg");
  2890. applyTableStyle(table);
  2891. }
  2892. });
  2893. }
  2894. },
  2895. { sep: true }
  2896. ];
  2897. return items.concat(tableContextItems(cell));
  2898. }
  2899. function tableContextItems(cell) {
  2900. var table = cell.closest("table");
  2901. var row = cell.parentNode;
  2902. var ci = cell.cellIndex;
  2903. var ri = row.rowIndex;
  2904. return [
  2905. { label: "Insert row above", icon: "angle up", action: function () { tableAddRow(table, ri); } },
  2906. { label: "Insert row below", icon: "angle down", action: function () { tableAddRow(table, ri + 1); } },
  2907. { label: "Insert column left", icon: "angle left", action: function () { tableAddCol(table, ci); } },
  2908. { label: "Insert column right", icon: "angle right", action: function () { tableAddCol(table, ci + 1); } },
  2909. { sep: true },
  2910. { label: "Delete row", icon: "minus", action: function () { tableDelRow(table, ri); } },
  2911. { label: "Delete column", icon: "minus", action: function () { tableDelCol(table, ci); } },
  2912. { label: "Delete table", icon: "trash alternate outline", action: function () {
  2913. if (table.parentNode) table.parentNode.removeChild(table);
  2914. afterEdit(true);
  2915. } }
  2916. ];
  2917. }
  2918. /* ================= special characters ================= */
  2919. function specialCharsDialog() {
  2920. if (inHeaderFooter()) return;
  2921. var $b = $("<div></div>");
  2922. var $tabs = $('<div class="sc-tabs"></div>');
  2923. var $grid = $('<div class="sc-grid"></div>');
  2924. function showTab(i) {
  2925. $tabs.children().removeClass("active").eq(i).addClass("active");
  2926. $grid.empty();
  2927. CHAR_TABS[i].cps.forEach(function (cp) {
  2928. var ch = String.fromCodePoint(cp);
  2929. var $c = $('<button type="button" class="sc-char"></button>').text(ch)
  2930. .attr("title", "U+" + cp.toString(16).toUpperCase());
  2931. $c.on("mousedown", function (e) { e.preventDefault(); });
  2932. $c.on("click", function () {
  2933. restoreSel();
  2934. try { document.execCommand("insertText", false, ch); } catch (e) { }
  2935. afterEdit(true);
  2936. });
  2937. $grid.append($c);
  2938. });
  2939. }
  2940. CHAR_TABS.forEach(function (t, i) {
  2941. var $tb = $('<button type="button" class="sc-tab"></button>').text(t.name);
  2942. $tb.on("click", function () { showTab(i); });
  2943. $tabs.append($tb);
  2944. });
  2945. $b.append($tabs).append($grid);
  2946. showTab(0);
  2947. OfficeApp.dialog({
  2948. title: "Special characters",
  2949. body: $b,
  2950. wide: true,
  2951. buttons: [{ label: "Close" }]
  2952. });
  2953. }
  2954. /* ================= find and replace ================= */
  2955. // the panel hangs from the bottom edge of the ribbon, whose height
  2956. // changes as it is collapsed, expanded or wraps
  2957. function placeFindPanel() {
  2958. var bar = document.getElementById("toolbar");
  2959. if (!bar) return;
  2960. document.getElementById("findPanel").style.top = Math.round(bar.getBoundingClientRect().bottom) + 4 + "px";
  2961. }
  2962. if (window.ResizeObserver) new ResizeObserver(placeFindPanel).observe(document.getElementById("toolbar"));
  2963. window.addEventListener("resize", placeFindPanel);
  2964. function openFind(withReplace) {
  2965. $("#findPanel").show();
  2966. placeFindPanel();
  2967. if (withReplace) $("#replaceRow").show();
  2968. var selTxt = savedRange ? savedRange.toString() : "";
  2969. if (selTxt && selTxt.length <= 80 && selTxt.indexOf("\n") < 0) {
  2970. $("#findInput").val(selTxt);
  2971. }
  2972. $("#findInput").trigger("focus").trigger("select");
  2973. runFind(false);
  2974. }
  2975. function closeFind() {
  2976. $("#findPanel").hide();
  2977. $("#replaceRow").hide();
  2978. clearFindHits();
  2979. }
  2980. function clearFindHits() {
  2981. var hits = editor.querySelectorAll("span.of-find-hit");
  2982. for (var i = 0; i < hits.length; i++) {
  2983. var s = hits[i];
  2984. while (s.firstChild) s.parentNode.insertBefore(s.firstChild, s);
  2985. s.parentNode.removeChild(s);
  2986. }
  2987. if (hits.length) editor.normalize();
  2988. findState.hits = [];
  2989. findState.cur = -1;
  2990. updateFindCount();
  2991. }
  2992. function runFind(keepIndex) {
  2993. var oldCur = keepIndex ? Math.max(findState.cur, 0) : 0;
  2994. clearFindHits();
  2995. var term = $("#findInput").val();
  2996. if (!term) { updateFindCount(); return; }
  2997. var tl = term.toLowerCase();
  2998. var walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT, null, false);
  2999. var nodes = [];
  3000. while (walker.nextNode()) nodes.push(walker.currentNode);
  3001. nodes.forEach(function (node) {
  3002. var text = node.nodeValue;
  3003. if (!text) return;
  3004. var lower = text.toLowerCase();
  3005. var idx = lower.indexOf(tl);
  3006. if (idx < 0) return;
  3007. var frag = document.createDocumentFragment();
  3008. var pos = 0;
  3009. while (idx >= 0) {
  3010. if (idx > pos) frag.appendChild(document.createTextNode(text.slice(pos, idx)));
  3011. var sp = document.createElement("span");
  3012. sp.className = "of-find-hit";
  3013. sp.textContent = text.substr(idx, term.length);
  3014. frag.appendChild(sp);
  3015. pos = idx + term.length;
  3016. idx = lower.indexOf(tl, pos);
  3017. }
  3018. if (pos < text.length) frag.appendChild(document.createTextNode(text.slice(pos)));
  3019. node.parentNode.replaceChild(frag, node);
  3020. });
  3021. findState.hits = Array.prototype.slice.call(editor.querySelectorAll("span.of-find-hit"));
  3022. if (findState.hits.length > 0) {
  3023. findState.cur = Math.min(oldCur, findState.hits.length - 1);
  3024. setCurrentHit(findState.cur);
  3025. } else {
  3026. findState.cur = -1;
  3027. }
  3028. updateFindCount();
  3029. }
  3030. function setCurrentHit(i) {
  3031. findState.hits.forEach(function (h) { h.classList.remove("of-find-cur"); });
  3032. var h = findState.hits[i];
  3033. if (h) {
  3034. h.classList.add("of-find-cur");
  3035. try { h.scrollIntoView({ block: "center", behavior: "smooth" }); }
  3036. catch (e) { h.scrollIntoView(); }
  3037. }
  3038. }
  3039. function findStep(dir) {
  3040. var len = findState.hits.length;
  3041. if (!len) { runFind(false); return; }
  3042. findState.cur = (findState.cur + dir + len) % len;
  3043. setCurrentHit(findState.cur);
  3044. updateFindCount();
  3045. }
  3046. function updateFindCount() {
  3047. var len = findState.hits.length;
  3048. $("#findCount").text(len ? (findState.cur + 1) + "/" + len : "0/0");
  3049. }
  3050. function replaceCurrent() {
  3051. if (findState.cur < 0 || !findState.hits.length) { findStep(1); return; }
  3052. var hit = findState.hits[findState.cur];
  3053. var rep = $("#replaceInput").val();
  3054. hit.parentNode.replaceChild(document.createTextNode(rep), hit);
  3055. editor.normalize();
  3056. afterEdit(true);
  3057. runFind(true); // same index now points at the next match
  3058. }
  3059. function replaceAllMatches() {
  3060. var n = findState.hits.length;
  3061. if (!n) { runFind(false); n = findState.hits.length; }
  3062. if (!n) { OfficeApp.toast("No matches to replace"); return; }
  3063. var rep = $("#replaceInput").val();
  3064. findState.hits.forEach(function (h) {
  3065. h.parentNode.replaceChild(document.createTextNode(rep), h);
  3066. });
  3067. editor.normalize();
  3068. findState.hits = [];
  3069. findState.cur = -1;
  3070. updateFindCount();
  3071. afterEdit(true);
  3072. OfficeApp.toast(n + " occurrence" + (n === 1 ? "" : "s") + " replaced");
  3073. }
  3074. function bindFindPanel() {
  3075. $("#findInput").on("input", function () { runFind(false); });
  3076. $("#findInput, #replaceInput").on("keydown", function (e) {
  3077. if (e.key === "Enter") {
  3078. e.preventDefault();
  3079. if (this.id === "replaceInput") replaceCurrent();
  3080. else findStep(e.shiftKey ? -1 : 1);
  3081. } else if (e.key === "Escape") {
  3082. e.preventDefault();
  3083. closeFind();
  3084. editor.focus();
  3085. }
  3086. e.stopPropagation();
  3087. });
  3088. $("#findNext").on("click", function () { findStep(1); });
  3089. $("#findPrev").on("click", function () { findStep(-1); });
  3090. $("#findClose").on("click", function () { closeFind(); editor.focus(); });
  3091. $("#replaceOne").on("click", replaceCurrent);
  3092. $("#replaceAllBtn").on("click", replaceAllMatches);
  3093. }
  3094. /* ================= page setup / print css ================= */
  3095. function applyPageSetup() {
  3096. var d = PAGE_SIZES[pageConf.size] || PAGE_SIZES.A4;
  3097. var w = (pageConf.orientation === "landscape") ? d.h : d.w;
  3098. var h = (pageConf.orientation === "landscape") ? d.w : d.h;
  3099. var m = pageConf.margins;
  3100. pageEl.style.width = w + "mm";
  3101. pageEl.style.minHeight = h + "mm";
  3102. pageEl.style.padding = m.top + "mm " + m.right + "mm " + m.bottom + "mm " + m.left + "mm";
  3103. // multi-column text layout (2 = IEEE-paper style); blocks marked
  3104. // with .col-span-all (title, authors) stretch across every column
  3105. // the columns themselves are the column sections the paginator
  3106. // wraps the text in (docs_layout.js); they read these
  3107. editor.style.columnCount = "";
  3108. editor.style.columnGap = "";
  3109. editor.style.columnFill = "";
  3110. if (pageConf.columns > 1) {
  3111. editor.style.setProperty("--doc-cols", String(pageConf.columns));
  3112. editor.style.setProperty("--doc-colgap", pageConf.colGap + "mm");
  3113. } else {
  3114. editor.style.removeProperty("--doc-cols");
  3115. editor.style.removeProperty("--doc-colgap");
  3116. }
  3117. updatePrintStyle();
  3118. updatePageGuides();
  3119. }
  3120. function updatePrintStyle() {
  3121. var m = pageConf.margins;
  3122. var sizeKw = { "A4": "A4", "Letter": "letter", "Legal": "legal" }[pageConf.size] || "A4";
  3123. var css = "@page {\n";
  3124. css += " size: " + sizeKw + " " + pageConf.orientation + ";\n";
  3125. css += " margin: " + m.top + "mm " + m.right + "mm " + m.bottom + "mm " + m.left + "mm;\n";
  3126. if (pageConf.pageNumbers) {
  3127. /* best effort - @page margin boxes print the page counter in
  3128. engines that support them; ignored elsewhere */
  3129. css += " @bottom-center { content: counter(page); font-size: 10pt; color: #666; font-family: Arial, sans-serif; }\n";
  3130. }
  3131. css += "}\n";
  3132. css += "@media print {\n";
  3133. css += " #page { width: auto !important; min-height: 0 !important; padding: 0 !important; }\n";
  3134. /* the screen bands are absolutely placed per simulated page; when the
  3135. printer paginates for real, one fixed pair repeats on every sheet
  3136. (first-page suppression is a PDF-export feature - print engines
  3137. cannot skip it) */
  3138. if (pageConf.hfMode === "none") {
  3139. css += " .doc-hf { display: none !important; }\n";
  3140. } else {
  3141. css += " .doc-hf { position: fixed !important; left: 0 !important; right: 0 !important; }\n";
  3142. css += " #docHeader { top: 0 !important; }\n";
  3143. css += " #docFooter { top: auto !important; bottom: 0 !important; }\n";
  3144. css += " .doc-hf:not(#docHeader):not(#docFooter) { display: none !important; }\n";
  3145. css += " .doc-hf[hidden] { display: block !important; }\n";
  3146. }
  3147. css += "}\n";
  3148. var tag = document.getElementById("pagePrintStyle");
  3149. if (tag) tag.textContent = css;
  3150. }
  3151. /* ---------- pagination (DocsLayout) ----------
  3152. The document is one flow; docs_layout.js decides where every page
  3153. ends, splits what crosses the boundary and pushes the rest onto the
  3154. next sheet with layout-only spacers (.doc-autobreak; splits and
  3155. spacers are undone on save). This section supplies the page geometry
  3156. and draws what sits around the flow: one sheet of paper per page,
  3157. the header and footer bands, the footnote area and the automatic page
  3158. number. Everything it draws is a real
  3159. element in #page, which is what lets the PDF exporter draw the same
  3160. page the editor shows. */
  3161. var MM_PX = 96 / 25.4;
  3162. var PT_PX = 96 / 72;
  3163. var PAGE_GAP_PX = 24; // visual gap between two sheets
  3164. var HEADER_MIN_PX = 7; // Google Docs never starts a header higher
  3165. var lastPages = []; // page records of the current layout
  3166. // element top in layout px relative to #page (CSS zoom safe - unlike
  3167. // getBoundingClientRect, offsetTop is not scaled)
  3168. function offsetTopInPage(el) {
  3169. var y = 0;
  3170. while (el && el !== pageEl) {
  3171. y += el.offsetTop;
  3172. el = el.offsetParent;
  3173. }
  3174. return y;
  3175. }
  3176. function removeAutoBreaks(root) {
  3177. DocsLayout.removeSpacers(root);
  3178. }
  3179. function docLineSpacing() {
  3180. return pageConf.lineSpacing > 0 ? pageConf.lineSpacing : 1.15;
  3181. }
  3182. function pageGeometry() {
  3183. var d = PAGE_SIZES[pageConf.size] || PAGE_SIZES.A4;
  3184. var land = pageConf.orientation === "landscape";
  3185. var m = pageConf.margins;
  3186. var g = {
  3187. sheetW: (land ? d.h : d.w) * MM_PX,
  3188. sheetH: (land ? d.w : d.h) * MM_PX,
  3189. mTop: m.top * MM_PX, mBot: m.bottom * MM_PX,
  3190. mL: m.left * MM_PX, mR: m.right * MM_PX,
  3191. headerDist: (pageConf.headerDist >= 0 ? pageConf.headerDist : 12.7) * MM_PX,
  3192. footerDist: (pageConf.footerDist >= 0 ? pageConf.footerDist : 12.7) * MM_PX
  3193. };
  3194. g.contentW = g.sheetW - g.mL - g.mR;
  3195. return g;
  3196. }
  3197. /* the passes that give a rendered subtree its word-processor layout:
  3198. list markers, exact line heights, tab stops */
  3199. function runLayoutPasses(root) {
  3200. DocsLayout.applyNumbering(root);
  3201. DocsLayout.applyLineHeights(root, docLineSpacing());
  3202. DocsLayout.applyTableBorders(root);
  3203. DocsLayout.applyTabs(root);
  3204. }
  3205. /* ---------- header / footer bands ----------
  3206. The editable header/footer is repeated once per page, parked in that
  3207. sheet's margin band at the header/footer distance from the paper
  3208. edge. Every copy is editable and they mirror each other, so it can be
  3209. changed from any page. pageConf.hfMode decides which pages get one,
  3210. and the exporters read the same setting. The content is rich HTML
  3211. (hfContent); a PAGE / NUMPAGES field shows each sheet's own number. */
  3212. function hfPairs() {
  3213. return [{ header: headerEl, footer: footerEl }].concat(hfClones);
  3214. }
  3215. function hfShownOn(pageIndex) { // pageIndex is 0-based
  3216. if (pageConf.hfMode === "none") return false;
  3217. if (pageConf.hfMode === "except-first" && pageIndex === 0) return false;
  3218. return true;
  3219. }
  3220. // the stored form of a band: fields keep their placeholder, not the
  3221. // number the copy happened to show
  3222. function hfSerialize(el) {
  3223. var clone = el.cloneNode(true);
  3224. var f = clone.querySelectorAll(".doc-field");
  3225. for (var i = 0; i < f.length; i++) f[i].textContent = "1";
  3226. stripLayoutArtifacts(clone);
  3227. return clone.innerHTML;
  3228. }
  3229. // mirror one band into every other copy (never into the one being typed
  3230. // in, so the caret survives)
  3231. function syncHfFrom(el) {
  3232. var kind = el.getAttribute("data-hf");
  3233. hfContent[kind] = hfSerialize(el);
  3234. hfPairs().forEach(function (pair) {
  3235. var other = pair[kind];
  3236. if (other !== el) other.innerHTML = hfContent[kind];
  3237. });
  3238. }
  3239. function bindHfEvents(el) {
  3240. el.addEventListener("input", function () {
  3241. syncHfFrom(el);
  3242. OfficeApp.markDirty();
  3243. undo.pushDebounced(snapshot, 600);
  3244. });
  3245. el.addEventListener("paste", function (e) {
  3246. e.preventDefault();
  3247. var t = e.clipboardData ? e.clipboardData.getData("text/plain") : "";
  3248. if (t) {
  3249. try { document.execCommand("insertText", false, t); } catch (err) { }
  3250. }
  3251. });
  3252. }
  3253. function makeHfCopy(kind) {
  3254. var src = (kind === "header") ? headerEl : footerEl;
  3255. var el = document.createElement("div");
  3256. el.className = "doc-hf doc-hf-" + kind;
  3257. el.setAttribute("contenteditable", "true");
  3258. el.setAttribute("spellcheck", "false");
  3259. el.setAttribute("data-hf", kind);
  3260. el.setAttribute("data-placeholder", src.getAttribute("data-placeholder") || "");
  3261. el.innerHTML = hfContent[kind] || "";
  3262. bindHfEvents(el);
  3263. pageEl.appendChild(el);
  3264. return el;
  3265. }
  3266. function parkHeaderFooters() {
  3267. hfPairs().forEach(function (pair) {
  3268. ["header", "footer"].forEach(function (kind) {
  3269. pair[kind].style.top = "0px";
  3270. pair[kind].hidden = true;
  3271. });
  3272. });
  3273. }
  3274. function layoutHeaderFooters(pages, geo) {
  3275. // one copy per page after the first (page one uses the originals)
  3276. while (hfClones.length < pages.length - 1) {
  3277. hfClones.push({ header: makeHfCopy("header"), footer: makeHfCopy("footer") });
  3278. }
  3279. while (hfClones.length > pages.length - 1) {
  3280. var drop = hfClones.pop();
  3281. if (drop.header.parentNode) drop.header.parentNode.removeChild(drop.header);
  3282. if (drop.footer.parentNode) drop.footer.parentNode.removeChild(drop.footer);
  3283. }
  3284. var lead = true;
  3285. hfPairs().forEach(function (pair, i) {
  3286. var show = hfShownOn(i);
  3287. var sheetTop = pages[i].sheetTop;
  3288. ["header", "footer"].forEach(function (kind) {
  3289. var el = pair[kind];
  3290. el.hidden = !show;
  3291. el.classList.toggle("doc-hf-lead", show && lead);
  3292. if (!show) return;
  3293. if (el !== document.activeElement && el.innerHTML !== hfContent[kind] &&
  3294. hfSerialize(el) !== hfContent[kind]) {
  3295. el.innerHTML = hfContent[kind] || "";
  3296. }
  3297. var fields = el.querySelectorAll(".doc-field");
  3298. for (var f = 0; f < fields.length; f++) {
  3299. var v = fields[f].getAttribute("data-field") === "NUMPAGES" ? pages.length : i + 1;
  3300. if (fields[f].textContent !== String(v)) fields[f].textContent = String(v);
  3301. }
  3302. el.style.left = geo.mL + "px";
  3303. el.style.width = geo.contentW + "px";
  3304. el.style.right = "auto";
  3305. runLayoutPasses(el);
  3306. var h = el.offsetHeight;
  3307. var top;
  3308. if (kind === "header") {
  3309. top = sheetTop + Math.max(HEADER_MIN_PX, geo.headerDist);
  3310. } else {
  3311. top = sheetTop + geo.sheetH - geo.footerDist - h;
  3312. }
  3313. el.style.top = top + "px";
  3314. });
  3315. if (show) lead = false;
  3316. });
  3317. layoutPageNumbers(pages, geo);
  3318. }
  3319. /* "Page numbers" without a PAGE field in the footer: a plain number
  3320. centred in the bottom margin of every page that shows the footer */
  3321. function layoutPageNumbers(pages, geo) {
  3322. var old = pageEl.querySelectorAll(".doc-pagenum");
  3323. for (var i = 0; i < old.length; i++) old[i].parentNode.removeChild(old[i]);
  3324. if (!pageConf.pageNumbers) return;
  3325. if (/data-field="PAGE"/.test(hfContent.footer || "") || /data-field="PAGE"/.test(hfContent.header || "")) return;
  3326. pages.forEach(function (pg, idx) {
  3327. if (pageConf.hfMode === "except-first" && idx === 0) return;
  3328. var n = document.createElement("div");
  3329. n.className = "doc-pagenum";
  3330. n.textContent = String(idx + 1);
  3331. n.style.left = geo.mL + "px";
  3332. n.style.width = geo.contentW + "px";
  3333. pageEl.appendChild(n);
  3334. n.style.top = (pg.sheetTop + geo.sheetH - geo.footerDist / 2 - n.offsetHeight / 2) + "px";
  3335. });
  3336. }
  3337. /* ---------- footnotes ----------
  3338. body.footnotes holds each note's HTML; the text references them with
  3339. sup.doc-fnref[data-fn]. The notes are drawn under a short rule at the
  3340. bottom of the page that references them, numbered in reference
  3341. order, and stay editable there. */
  3342. var fnMeasureEl = null;
  3343. var fnOrder = [];
  3344. function footnoteArea(ids, geo) {
  3345. var area = document.createElement("div");
  3346. area.className = "doc-fn-area";
  3347. area.style.width = geo.contentW + "px";
  3348. area.appendChild(Object.assign(document.createElement("div"), { className: "doc-fn-sep" }));
  3349. ids.forEach(function (id) {
  3350. var fn = document.createElement("div");
  3351. fn.className = "doc-fn";
  3352. fn.setAttribute("data-fn", id);
  3353. fn.innerHTML = footnotes[id] || "<p><br></p>";
  3354. var first = fn.querySelector("p,h1,h2,h3,h4,h5,h6,li") || fn;
  3355. var mark = document.createElement("sup");
  3356. mark.className = "doc-fnnum";
  3357. mark.setAttribute("contenteditable", "false");
  3358. mark.textContent = String(fnOrder.indexOf(id) + 1);
  3359. first.insertBefore(mark, first.firstChild);
  3360. area.appendChild(fn);
  3361. });
  3362. return area;
  3363. }
  3364. function measureFootnotes(ids, geo) {
  3365. if (!fnMeasureEl) {
  3366. fnMeasureEl = document.createElement("div");
  3367. fnMeasureEl.className = "doc-fn-measure";
  3368. pageEl.appendChild(fnMeasureEl);
  3369. }
  3370. fnMeasureEl.innerHTML = "";
  3371. var area = footnoteArea(ids, geo);
  3372. fnMeasureEl.appendChild(area);
  3373. runLayoutPasses(area);
  3374. var h = area.offsetHeight;
  3375. fnMeasureEl.innerHTML = "";
  3376. return h;
  3377. }
  3378. // a note with nothing typed in it but its number
  3379. function footnoteIsEmpty(fn) {
  3380. var clone = fn.cloneNode(true);
  3381. var marks = clone.querySelectorAll(".doc-fnnum");
  3382. for (var m = 0; m < marks.length; m++) marks[m].parentNode.removeChild(marks[m]);
  3383. return !clone.textContent.replace(/[\s​]/g, "") &&
  3384. !clone.querySelector("img,svg,table,hr,video,iframe");
  3385. }
  3386. // Backspace in an empty note deletes it: its references leave the
  3387. // text and the caret goes back to where the first one was
  3388. function removeFootnote(id) {
  3389. var refs = editor.querySelectorAll('sup.doc-fnref[data-fn="' + id + '"]');
  3390. if (!refs.length) return;
  3391. var range = document.createRange();
  3392. range.setStartBefore(refs[0]);
  3393. range.collapse(true);
  3394. for (var i = 0; i < refs.length; i++) refs[i].parentNode.removeChild(refs[i]);
  3395. delete footnotes[id];
  3396. editor.focus();
  3397. var sel = window.getSelection();
  3398. sel.removeAllRanges();
  3399. sel.addRange(range);
  3400. savedRange = range.cloneRange();
  3401. afterEdit(true);
  3402. clearTimeout(countTimer);
  3403. updateCounts();
  3404. }
  3405. function renderFootnoteAreas(pages, geo) {
  3406. var old = pageEl.querySelectorAll(".doc-fn-area");
  3407. for (var i = 0; i < old.length; i++) {
  3408. if (old[i].parentNode === pageEl) old[i].parentNode.removeChild(old[i]);
  3409. }
  3410. pages.forEach(function (pg) {
  3411. if (!pg.footnotes || !pg.footnotes.length) return;
  3412. var area = footnoteArea(pg.footnotes, geo);
  3413. area.style.left = geo.mL + "px";
  3414. area.style.top = pg.footnoteTop + "px";
  3415. area.querySelectorAll(".doc-fn").forEach(function (fn) {
  3416. fn.setAttribute("contenteditable", "true");
  3417. fn.addEventListener("input", function () {
  3418. var clone = fn.cloneNode(true);
  3419. var marks = clone.querySelectorAll(".doc-fnnum");
  3420. for (var m = 0; m < marks.length; m++) marks[m].parentNode.removeChild(marks[m]);
  3421. stripLayoutArtifacts(clone);
  3422. footnotes[fn.getAttribute("data-fn")] = clone.innerHTML;
  3423. OfficeApp.markDirty();
  3424. undo.pushDebounced(snapshot, 600);
  3425. });
  3426. fn.addEventListener("keydown", function (e) {
  3427. if (e.key !== "Backspace" || e.ctrlKey || e.metaKey || e.altKey) return;
  3428. if (!footnoteIsEmpty(fn)) return;
  3429. e.preventDefault();
  3430. removeFootnote(fn.getAttribute("data-fn"));
  3431. });
  3432. });
  3433. pageEl.appendChild(area);
  3434. runLayoutPasses(area);
  3435. });
  3436. }
  3437. /* ---------- the sheets ----------
  3438. One sheet of paper per page, behind the flow. Between two sheets
  3439. there is nothing at all, which is what makes the pages really
  3440. separate: the flow has no content there (a split puts the rest of a
  3441. paragraph or a table row on the next sheet), so no border or shading
  3442. can show in the gap. */
  3443. function renderSheets(pages, geo) {
  3444. var holder = document.getElementById("pageSheets");
  3445. if (!holder) {
  3446. holder = document.createElement("div");
  3447. holder.id = "pageSheets";
  3448. holder.className = "of-noprint";
  3449. holder.setAttribute("aria-hidden", "true");
  3450. pageEl.insertBefore(holder, pageEl.firstChild);
  3451. }
  3452. var want = pages.map(function (pg) { return { top: pg.sheetTop, h: geo.sheetH }; });
  3453. while (holder.children.length > want.length) holder.removeChild(holder.lastChild);
  3454. while (holder.children.length < want.length) {
  3455. var sheet = document.createElement("div");
  3456. sheet.className = "doc-sheet";
  3457. holder.appendChild(sheet);
  3458. }
  3459. want.forEach(function (w, i) {
  3460. var el = holder.children[i];
  3461. var top = w.top + "px", h = w.h + "px";
  3462. if (el.style.top !== top) el.style.top = top;
  3463. if (el.style.height !== h) el.style.height = h;
  3464. });
  3465. }
  3466. /* ---------- deferred relayout ----------
  3467. Pictures in a document that was just opened are still decoding while
  3468. loadBody() paginates: they measure zero tall, so the page tops - and
  3469. with them the header/footer bands and the automatic breaks - come out
  3470. for a much shorter document than the one that ends up on screen.
  3471. Anything that changes the flow height without an edit (an image
  3472. finishing, a web font, a window resize) re-runs the pagination. */
  3473. var relayoutTimer = null;
  3474. var relayoutH = -1; // editor height the current layout was made for
  3475. var relayouting = false;
  3476. function scheduleRelayout() {
  3477. clearTimeout(relayoutTimer);
  3478. relayoutTimer = setTimeout(function () {
  3479. updatePageGuides();
  3480. }, 80);
  3481. }
  3482. function watchContentSize() {
  3483. // load does not bubble, but it is seen in the capture phase
  3484. var onLoad = function (e) {
  3485. if (e.target && e.target.tagName === "IMG") scheduleRelayout();
  3486. };
  3487. editor.addEventListener("load", onLoad, true);
  3488. editor.addEventListener("error", onLoad, true);
  3489. if (window.ResizeObserver) {
  3490. new ResizeObserver(function () {
  3491. if (relayouting) return;
  3492. if (Math.abs(editor.offsetHeight - relayoutH) <= 1) return;
  3493. scheduleRelayout();
  3494. }).observe(editor);
  3495. }
  3496. if (document.fonts && document.fonts.ready) {
  3497. document.fonts.ready.then(scheduleRelayout).catch(function () { });
  3498. }
  3499. }
  3500. function setHfMode(mode) {
  3501. if (HF_MODES.indexOf(mode) < 0) return;
  3502. pageConf.hfMode = mode;
  3503. updatePrintStyle();
  3504. updatePageGuides();
  3505. afterEdit(true);
  3506. OfficeApp.setStatus({
  3507. "all": "Header and footer shown on every page",
  3508. "except-first": "Header and footer shown on every page except the first",
  3509. "none": "Header and footer turned off"
  3510. }[mode]);
  3511. }
  3512. /* The earliest point an edit touched since the last layout (#page
  3513. coordinates), or null when the whole document has to be laid out
  3514. again - a newly opened document, page setup, anything that is not
  3515. typing at a caret. */
  3516. var dirtyFromY = null;
  3517. var lastGeoKey = "";
  3518. function geoKey(geo) {
  3519. return [geo.sheetW, geo.sheetH, geo.mTop, geo.mBot, geo.mL, geo.mR, docLineSpacing(),
  3520. OfficeApp.getZoom()].join(",");
  3521. }
  3522. // a viewport y as a #page layout y (the framework zooms #page)
  3523. function pageYOf(clientY) {
  3524. var pr = pageEl.getBoundingClientRect();
  3525. var scale = pageEl.offsetHeight ? pr.height / pageEl.offsetHeight : 1;
  3526. return (clientY - pr.top) / (scale || 1);
  3527. }
  3528. // where the caret is, in #page layout px; null when it is not in the text
  3529. function caretPageY() {
  3530. try {
  3531. var sel = window.getSelection();
  3532. if (!sel || !sel.rangeCount) return null;
  3533. var r = sel.getRangeAt(0);
  3534. if (!pageEl.contains(r.startContainer)) return null;
  3535. var rects = r.getClientRects();
  3536. var rect = rects.length ? rects[0] : null;
  3537. if (!rect || !rect.height) {
  3538. var n = r.startContainer.nodeType === 1 ? r.startContainer : r.startContainer.parentElement;
  3539. rect = n.getBoundingClientRect();
  3540. }
  3541. return Math.max(0, pageYOf(rect.top));
  3542. } catch (e) {
  3543. return null;
  3544. }
  3545. }
  3546. /* relayoutNow lays an edit that changes how tall its lines are (a
  3547. style, a size, a spacing) out before the browser paints again. Left
  3548. to the resize observer, the new size showed for a moment with the old
  3549. line heights - its lines stacked on top of each other - until the
  3550. layout caught up. The pages are redone from the first edited block. */
  3551. function relayoutNow(blocks) {
  3552. var y = null;
  3553. (blocks || []).forEach(function (b) {
  3554. if (!b || !b.isConnected || !editor.contains(b)) return;
  3555. var t = pageYOf(b.getBoundingClientRect().top);
  3556. y = y === null ? t : Math.min(y, t);
  3557. });
  3558. if (y === null) y = caretPageY();
  3559. if (y !== null) {
  3560. y = Math.max(0, y);
  3561. dirtyFromY = dirtyFromY === null ? y : Math.min(dirtyFromY, y);
  3562. }
  3563. clearTimeout(relayoutTimer);
  3564. updatePageGuides();
  3565. }
  3566. function noteEditAtCaret() {
  3567. var y = editor.contains((window.getSelection() || {}).anchorNode || null) ? caretPageY() : null;
  3568. if (y === null) y = 0;
  3569. dirtyFromY = dirtyFromY === null ? y : Math.min(dirtyFromY, y);
  3570. }
  3571. /* ---------- "Page 3 of 12" in the status bar ----------
  3572. The page the caret is on after a click or a keystroke, the page in
  3573. the middle of the view after a scroll - whichever happened last. */
  3574. var pageShownBy = "caret";
  3575. var pageIndicatorTimer = null;
  3576. function pageIndexAt(y) {
  3577. var n = 0;
  3578. for (var i = 0; i < lastPages.length; i++) {
  3579. if (lastPages[i].sheetTop <= y + 0.5) n = i;
  3580. }
  3581. return n;
  3582. }
  3583. function updatePageIndicator(by) {
  3584. if (by) pageShownBy = by;
  3585. var total = Math.max(1, lastPages.length);
  3586. var y = null;
  3587. if (pageShownBy === "caret") y = caretPageY();
  3588. if (y === null && workspaceEl) {
  3589. var wr = workspaceEl.getBoundingClientRect();
  3590. y = pageYOf(wr.top + wr.height / 2);
  3591. }
  3592. var n = Math.min(total, pageIndexAt(y || 0) + 1);
  3593. OfficeApp.updateStatusItem("pg", "Page " + n + " of " + total);
  3594. }
  3595. function schedulePageIndicator(by) {
  3596. if (by) pageShownBy = by;
  3597. if (pageIndicatorTimer) return;
  3598. pageIndicatorTimer = setTimeout(function () {
  3599. pageIndicatorTimer = null;
  3600. updatePageIndicator();
  3601. }, 120);
  3602. }
  3603. function updatePageGuides() {
  3604. if (relayouting) return lastPages.length || 1;
  3605. relayouting = true;
  3606. try {
  3607. return layoutPages();
  3608. } finally {
  3609. relayoutH = editor.offsetHeight;
  3610. relayouting = false;
  3611. if (tocOverlay || tocHover) scheduleTocOverlay();
  3612. }
  3613. }
  3614. function layoutPages() {
  3615. var geo = pageGeometry();
  3616. // park the bands first: a copy still sitting at the bottom of a
  3617. // longer previous layout would stretch #page and conjure a phantom
  3618. // page below
  3619. parkHeaderFooters();
  3620. pageEl.style.minHeight = geo.sheetH + "px";
  3621. // an edit only needs the pages from where it happened
  3622. var fromY = dirtyFromY;
  3623. dirtyFromY = null;
  3624. var incremental = fromY !== null && lastPages.length > 2 && pageConf.columns <= 1 &&
  3625. lastGeoKey === geoKey(geo);
  3626. lastGeoKey = geoKey(geo);
  3627. if (!incremental) removeAutoBreaks(editor);
  3628. normalizePageBreaks();
  3629. runLayoutPasses(editor);
  3630. fnOrder = DocsLayout.numberFootnotes(editor);
  3631. var refs = editor.querySelectorAll("sup.doc-fnref");
  3632. var pages = DocsLayout.paginate({
  3633. editor: editor, pageEl: pageEl,
  3634. sheetH: geo.sheetH, gap: PAGE_GAP_PX, mTop: geo.mTop, mBot: geo.mBot,
  3635. columns: pageConf.columns > 1 ? pageConf.columns : 1,
  3636. fnRefs: refs,
  3637. measureFootnotes: refs.length ? function (ids) { return measureFootnotes(ids, geo); } : null,
  3638. fromY: incremental ? fromY : undefined,
  3639. prevPages: incremental ? lastPages : null
  3640. });
  3641. lastPages = pages;
  3642. var last = pages[pages.length - 1];
  3643. pageEl.style.minHeight = (last.sheetTop + geo.sheetH + pageEl.clientTop * 2) + "px";
  3644. renderSheets(pages, geo);
  3645. renderFootnoteAreas(pages, geo);
  3646. layoutHeaderFooters(pages, geo);
  3647. updatePageIndicator();
  3648. return pages.length;
  3649. }
  3650. /* ---------- explicit page breaks ---------- */
  3651. function pageBreakHtml() {
  3652. return '<div class="doc-pagebreak" contenteditable="false"></div>';
  3653. }
  3654. // imported / restored breaks may carry old gap markup or lack the guard
  3655. function normalizePageBreaks() {
  3656. var list = editor.querySelectorAll(".doc-pagebreak");
  3657. for (var i = 0; i < list.length; i++) {
  3658. list[i].setAttribute("contenteditable", "false");
  3659. if (list[i].firstChild) list[i].innerHTML = "";
  3660. }
  3661. }
  3662. function insertPageBreak() {
  3663. if (inHeaderFooter()) return;
  3664. restoreSel();
  3665. // trailing paragraph so there is always somewhere to type on the new page
  3666. try {
  3667. document.execCommand("insertHTML", false, pageBreakHtml() + "<p><br></p>");
  3668. } catch (e) { return; }
  3669. normalizePageBreaks();
  3670. afterEdit(true);
  3671. updatePageGuides();
  3672. OfficeApp.setStatus("Page break inserted");
  3673. }
  3674. function toggleLayoutBoxes() {
  3675. var on = !document.body.classList.contains("doc-show-boxes");
  3676. document.body.classList.toggle("doc-show-boxes", on);
  3677. OfficeApp.setSetting("layoutBoxes", on);
  3678. OfficeApp.setStatus(on
  3679. ? "Layout boxes on - orange = full width (spans all columns), blue = column text"
  3680. : "Layout boxes off");
  3681. }
  3682. /* ---------- layout presets ---------- */
  3683. function setColumns(count, gap) {
  3684. pageConf.columns = Math.min(3, Math.max(1, count));
  3685. if (gap !== undefined) pageConf.colGap = gap;
  3686. applyPageSetup();
  3687. afterEdit(true);
  3688. OfficeApp.setStatus(count > 1 ? count + "-column layout applied" : "Single column layout");
  3689. }
  3690. function applyIeeePreset() {
  3691. // IEEE conference paper geometry: US Letter, 0.75in top, 1in bottom,
  3692. // 0.625in sides, two columns with a 0.17in gap
  3693. pageConf.size = "Letter";
  3694. pageConf.orientation = "portrait";
  3695. pageConf.margins = { top: 19, right: 16, bottom: 25, left: 16 };
  3696. pageConf.columns = 2;
  3697. pageConf.colGap = 5;
  3698. applyPageSetup();
  3699. afterEdit(true);
  3700. OfficeApp.setStatus("IEEE paper layout applied - mark the title block with Format > Page layout > Span all columns");
  3701. }
  3702. function toggleSpanAll() {
  3703. var blocks = getSelectedBlocks();
  3704. if (!blocks.length) {
  3705. OfficeApp.setStatus("Place the cursor in the paragraph(s) to span first", "error");
  3706. return;
  3707. }
  3708. var on = !blocks[0].classList.contains("col-span-all");
  3709. blocks.forEach(function (b) { b.classList.toggle("col-span-all", on); });
  3710. afterEdit(true);
  3711. }
  3712. function layoutMenuItems() {
  3713. return [
  3714. {
  3715. label: "Single column",
  3716. checked: function () { return pageConf.columns === 1; },
  3717. action: function () { setColumns(1); }
  3718. },
  3719. {
  3720. label: "Two columns",
  3721. checked: function () { return pageConf.columns === 2; },
  3722. action: function () { setColumns(2); }
  3723. },
  3724. {
  3725. label: "Three columns",
  3726. checked: function () { return pageConf.columns === 3; },
  3727. action: function () { setColumns(3); }
  3728. },
  3729. { sep: true },
  3730. { label: "IEEE paper preset", icon: "graduation cap", action: applyIeeePreset },
  3731. { sep: true },
  3732. {
  3733. label: "Span all columns",
  3734. checked: function () {
  3735. var b = getSelectedBlocks();
  3736. return b.length > 0 && b[0].classList.contains("col-span-all");
  3737. },
  3738. action: toggleSpanAll
  3739. }
  3740. ];
  3741. }
  3742. function pageSetupDialog() {
  3743. var $b = $("<div></div>");
  3744. var $grid = $('<div class="ps-grid"></div>');
  3745. var $size = $('<select class="ps-size"></select>');
  3746. Object.keys(PAGE_SIZES).forEach(function (k) {
  3747. var d = PAGE_SIZES[k];
  3748. $size.append($("<option></option>").attr("value", k)
  3749. .text(k + " (" + d.w + " × " + d.h + " mm)"));
  3750. });
  3751. $size.val(pageConf.size);
  3752. var $ori = $('<select class="ps-ori"></select>')
  3753. .append('<option value="portrait">Portrait</option>')
  3754. .append('<option value="landscape">Landscape</option>');
  3755. $ori.val(pageConf.orientation);
  3756. $grid.append($("<div></div>").append("<label>Paper size</label>").append($size));
  3757. $grid.append($("<div></div>").append("<label>Orientation</label>").append($ori));
  3758. var m = pageConf.margins;
  3759. [["top", "Top margin (mm)", m.top], ["bottom", "Bottom margin (mm)", m.bottom],
  3760. ["left", "Left margin (mm)", m.left], ["right", "Right margin (mm)", m.right]].forEach(function (f) {
  3761. var $in = $('<input type="number" min="0" max="80" step="1">')
  3762. .addClass("ps-m-" + f[0]).val(f[2]);
  3763. $grid.append($("<div></div>").append("<label>" + f[1] + "</label>").append($in));
  3764. });
  3765. var $cols = $('<select class="ps-cols"><option value="1">1 (single)</option><option value="2">2 (IEEE style)</option><option value="3">3</option></select>');
  3766. $cols.val(String(pageConf.columns));
  3767. $grid.append($("<div></div>").append("<label>Text columns</label>").append($cols));
  3768. var $gap = $('<input type="number" min="2" max="30" step="1" class="ps-gap">').val(pageConf.colGap);
  3769. $grid.append($("<div></div>").append("<label>Column gap (mm)</label>").append($gap));
  3770. $b.append($grid);
  3771. var $chk = $('<label class="ps-check"><input type="checkbox" class="ps-pn"> Print page numbers (bottom center, browser support permitting)</label>');
  3772. $chk.find("input").prop("checked", pageConf.pageNumbers);
  3773. $b.append($chk);
  3774. OfficeApp.dialog({
  3775. title: "Page setup",
  3776. body: $b,
  3777. buttons: [
  3778. { label: "Cancel" },
  3779. { label: "Apply", primary: true, action: function (close, $body) {
  3780. pageConf.size = $body.find(".ps-size").val();
  3781. pageConf.orientation = $body.find(".ps-ori").val();
  3782. pageConf.margins = {
  3783. top: clampMm($body.find(".ps-m-top").val()),
  3784. right: clampMm($body.find(".ps-m-right").val()),
  3785. bottom: clampMm($body.find(".ps-m-bottom").val()),
  3786. left: clampMm($body.find(".ps-m-left").val())
  3787. };
  3788. pageConf.columns = Math.min(3, Math.max(1, parseInt($body.find(".ps-cols").val(), 10) || 1));
  3789. pageConf.colGap = Math.min(30, Math.max(2, num($body.find(".ps-gap").val(), 8)));
  3790. pageConf.pageNumbers = $body.find(".ps-pn").prop("checked");
  3791. close();
  3792. applyPageSetup();
  3793. afterEdit(true);
  3794. } }
  3795. ]
  3796. });
  3797. }
  3798. function clampMm(v) {
  3799. return Math.min(80, Math.max(0, num(v, 20)));
  3800. }
  3801. /* ================= word / character count ================= */
  3802. function scheduleCounts() {
  3803. clearTimeout(countTimer);
  3804. countTimer = setTimeout(updateCounts, 300);
  3805. }
  3806. function updateCounts() {
  3807. var text = editor.innerText || "";
  3808. var words = (text.match(/\S+/g) || []).length;
  3809. var chars = text.replace(/\n/g, "").length;
  3810. var pages = updatePageGuides();
  3811. OfficeApp.updateStatusItem("wc",
  3812. words + " word" + (words === 1 ? "" : "s") + " · " +
  3813. chars + " character" + (chars === 1 ? "" : "s") + " · " +
  3814. pages + " page" + (pages === 1 ? "" : "s"));
  3815. updateSuggestStatus();
  3816. }
  3817. /* ================= review: comments ================= */
  3818. /* Comments live in body.comments [{id, text, at, resolved}] and are
  3819. anchored in the content as <span class="doc-cmt" data-cid="...">.
  3820. Resolving/deleting unwraps the anchor; anchors whose text was
  3821. edited away show as orphaned cards. */
  3822. function genCmtId() {
  3823. return "cm-" + Date.now().toString(36) + Math.random().toString(36).substring(2, 7);
  3824. }
  3825. function cmtSpan(id) {
  3826. return editor.querySelector('span.doc-cmt[data-cid="' + id + '"]');
  3827. }
  3828. function unwrapEl(el) {
  3829. while (el.firstChild) el.parentNode.insertBefore(el.firstChild, el);
  3830. el.parentNode.removeChild(el);
  3831. }
  3832. function commentDialog(existing) {
  3833. restoreSel();
  3834. var range = null;
  3835. if (!existing) {
  3836. var sel = window.getSelection();
  3837. if (savedRange && !savedRange.collapsed && editor.contains(savedRange.commonAncestorContainer)) {
  3838. range = savedRange.cloneRange();
  3839. } else if (sel && sel.rangeCount && !sel.getRangeAt(0).collapsed &&
  3840. editor.contains(sel.getRangeAt(0).commonAncestorContainer)) {
  3841. range = sel.getRangeAt(0).cloneRange();
  3842. }
  3843. if (!range) {
  3844. OfficeApp.setStatus("Select the text to comment on first", "error");
  3845. return;
  3846. }
  3847. }
  3848. var $b = $('<label>Comment</label>' +
  3849. '<textarea id="docCmtText" rows="4" style="width:100%;resize:vertical;"></textarea>');
  3850. if (existing) $b.filter("textarea").val(existing.text);
  3851. OfficeApp.dialog({
  3852. title: existing ? "Edit comment" : "Add comment",
  3853. body: $b,
  3854. buttons: [
  3855. { label: "Cancel" },
  3856. {
  3857. label: existing ? "Save" : "Comment", primary: true,
  3858. action: function (close, $bd) {
  3859. var text = String($bd.find("#docCmtText").val() || "").trim();
  3860. close();
  3861. if (!text) return;
  3862. if (existing) {
  3863. existing.text = text;
  3864. } else {
  3865. var id = genCmtId();
  3866. var span = document.createElement("span");
  3867. span.className = "doc-cmt";
  3868. span.setAttribute("data-cid", id);
  3869. try {
  3870. range.surroundContents(span);
  3871. } catch (e) {
  3872. // selection crosses element boundaries
  3873. span.appendChild(range.extractContents());
  3874. range.insertNode(span);
  3875. }
  3876. comments.push({ id: id, text: text, at: Date.now(), resolved: false });
  3877. }
  3878. afterEdit(true);
  3879. renderCommentsPanel();
  3880. showCommentsPanel(true);
  3881. }
  3882. }
  3883. ]
  3884. });
  3885. setTimeout(function () { $("#docCmtText").focus(); }, 50);
  3886. }
  3887. function commentById(id) {
  3888. for (var i = 0; i < comments.length; i++) if (comments[i].id === id) return comments[i];
  3889. return null;
  3890. }
  3891. function resolveComment(id, remove) {
  3892. var span = cmtSpan(id);
  3893. if (span) unwrapEl(span);
  3894. if (remove) {
  3895. comments = comments.filter(function (c) { return c.id !== id; });
  3896. } else {
  3897. var c = commentById(id);
  3898. if (c) c.resolved = true;
  3899. }
  3900. editor.normalize();
  3901. afterEdit(true);
  3902. renderCommentsPanel();
  3903. }
  3904. function openComments() { return comments.filter(function (c) { return !c.resolved; }); }
  3905. function showCommentsPanel(show) {
  3906. $("#docCmtPanel").toggle(show);
  3907. OfficeApp.setSetting("cmtPanel", show);
  3908. }
  3909. function commentsPanelVisible() { return $("#docCmtPanel").is(":visible"); }
  3910. function renderCommentsPanel(activeId) {
  3911. var $p = $("#docCmtPanel");
  3912. if (!$p.length) return;
  3913. var $list = $p.find(".doc-cmt-list").empty();
  3914. var open = openComments();
  3915. $p.find(".doc-cmt-count").text(open.length ? open.length : "");
  3916. if (!open.length) {
  3917. $list.append('<div class="doc-cmt-empty">No comments. Select some text and use ' +
  3918. 'Insert &gt; Comment (Ctrl+Alt+M).</div>');
  3919. return;
  3920. }
  3921. open.forEach(function (c) {
  3922. var span = cmtSpan(c.id);
  3923. var quote = span ? span.textContent : "";
  3924. if (quote.length > 60) quote = quote.substring(0, 60) + "…";
  3925. var $card = $('<div class="doc-cmt-card' + (c.id === activeId ? " active" : "") + '"></div>');
  3926. $card.append($('<div class="doc-cmt-quote"></div>')
  3927. .text(quote || "(commented text was removed)"));
  3928. $card.append($('<div class="doc-cmt-body"></div>').text(c.text));
  3929. $card.append('<div class="doc-cmt-when">' +
  3930. new Date(c.at).toLocaleString() + "</div>");
  3931. var $acts = $('<div class="doc-cmt-actions"></div>');
  3932. var act = function (icon, title, fn) {
  3933. var $a = $('<button type="button" class="of-te-btn" title="' + title + '">' +
  3934. '<i class="' + icon + ' icon"></i></button>');
  3935. $a.on("click", function (e) { e.stopPropagation(); fn(); });
  3936. return $a;
  3937. };
  3938. $acts.append(act("check", "Resolve (remove the highlight)", function () { resolveComment(c.id, false); }));
  3939. $acts.append(act("pencil alternate", "Edit comment", function () { commentDialog(c); renderCommentsPanel(c.id); }));
  3940. $acts.append(act("trash alternate outline", "Delete comment", function () { resolveComment(c.id, true); }));
  3941. $card.append($acts);
  3942. $card.on("click", function () {
  3943. var sp = cmtSpan(c.id);
  3944. if (sp) {
  3945. sp.scrollIntoView({ block: "center", behavior: "smooth" });
  3946. $(".doc-cmt.flash").removeClass("flash");
  3947. sp.classList.add("flash");
  3948. setTimeout(function () { sp.classList.remove("flash"); }, 1600);
  3949. }
  3950. renderCommentsPanel(c.id);
  3951. });
  3952. $list.append($card);
  3953. });
  3954. }
  3955. function buildCommentsPanel() {
  3956. var $p = $('<div id="docCmtPanel" class="of-noprint">' +
  3957. '<div class="doc-cmt-head"><i class="comments outline icon"></i> Comments ' +
  3958. '<span class="doc-cmt-count"></span>' +
  3959. '<button type="button" class="of-te-btn doc-cmt-close" title="Close panel">' +
  3960. '<i class="close icon"></i></button></div>' +
  3961. '<div class="doc-cmt-list"></div></div>');
  3962. $p.find(".doc-cmt-close").on("click", function () { showCommentsPanel(false); });
  3963. $("body").append($p);
  3964. $p.hide();
  3965. }
  3966. /* ================= review: track changes (suggest mode) ================= */
  3967. /* While "Suggest edits" is on, typing becomes <ins class="doc-ins"> and
  3968. deleting wraps content in <del class="doc-del"> instead of removing
  3969. it. Every suggestion can be accepted or rejected (context menu or
  3970. Edit menu); foreign exports (docx/html/md/txt) behave as if all
  3971. suggestions were accepted. Paragraph splits/merges are not tracked. */
  3972. function tagOf(node, selector) {
  3973. if (!node) return null;
  3974. if (node.nodeType === 3) node = node.parentNode;
  3975. return node && node.closest ? node.closest(selector) : null;
  3976. }
  3977. function suggestInsert(text) {
  3978. if (!text) return;
  3979. var sel = window.getSelection();
  3980. if (!sel || !sel.rangeCount) return;
  3981. var range = sel.getRangeAt(0);
  3982. if (!range.collapsed) {
  3983. suggestDeleteRange(range);
  3984. sel = window.getSelection();
  3985. range = sel.getRangeAt(0);
  3986. }
  3987. var tn = document.createTextNode(text);
  3988. var insHost = tagOf(range.startContainer, "ins.doc-ins");
  3989. var delHost = tagOf(range.startContainer, "del.doc-del");
  3990. if (insHost && !delHost) {
  3991. range.insertNode(tn); // grow the existing suggestion
  3992. } else {
  3993. var ins = document.createElement("ins");
  3994. ins.className = "doc-ins";
  3995. ins.appendChild(tn);
  3996. if (delHost) {
  3997. // typing at a suggested deletion: the insertion goes after it
  3998. delHost.parentNode.insertBefore(ins, delHost.nextSibling);
  3999. } else {
  4000. range.insertNode(ins);
  4001. }
  4002. }
  4003. var r2 = document.createRange();
  4004. r2.setStart(tn, tn.nodeValue.length);
  4005. r2.collapse(true);
  4006. sel.removeAllRanges();
  4007. sel.addRange(r2);
  4008. afterEdit(false);
  4009. }
  4010. function suggestDeleteRange(range) {
  4011. var texts = [];
  4012. if (range.commonAncestorContainer.nodeType === 3) {
  4013. texts = [range.commonAncestorContainer];
  4014. } else {
  4015. var walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT, null);
  4016. var n;
  4017. while ((n = walker.nextNode())) {
  4018. if (n.nodeValue !== "" && range.intersectsNode(n)) texts.push(n);
  4019. }
  4020. }
  4021. var caret = document.createRange();
  4022. caret.setStart(range.startContainer, range.startOffset);
  4023. caret.collapse(true);
  4024. texts.forEach(function (tn) {
  4025. var s = tn === range.startContainer ? range.startOffset : 0;
  4026. var e2 = tn === range.endContainer ? range.endOffset : tn.nodeValue.length;
  4027. if (e2 <= s) return;
  4028. if (tagOf(tn, "del.doc-del")) return; // already marked deleted
  4029. var mid = tn;
  4030. if (s > 0) mid = mid.splitText(s);
  4031. if (e2 - s < mid.nodeValue.length) mid.splitText(e2 - s);
  4032. if (tagOf(mid, "ins.doc-ins")) {
  4033. // deleting our own suggestion: really remove it
  4034. mid.parentNode.removeChild(mid);
  4035. return;
  4036. }
  4037. var del = document.createElement("del");
  4038. del.className = "doc-del";
  4039. mid.parentNode.insertBefore(del, mid);
  4040. del.appendChild(mid);
  4041. });
  4042. var sel = window.getSelection();
  4043. sel.removeAllRanges();
  4044. sel.addRange(caret);
  4045. }
  4046. function suggestDeleteCollapsed(forward) {
  4047. var sel = window.getSelection();
  4048. if (!sel || !sel.rangeCount || !sel.modify) return;
  4049. sel.modify("extend", forward ? "forward" : "backward", "character");
  4050. if (!sel.rangeCount) return;
  4051. var r = sel.getRangeAt(0);
  4052. if (r.collapsed) return;
  4053. var probe = forward ? r.endContainer : r.startContainer;
  4054. if (tagOf(probe, "ins.doc-ins") && !tagOf(probe, "del.doc-del")) {
  4055. // deleting inside our own insertion: real delete
  4056. try { document.execCommand(forward ? "forwardDelete" : "delete"); } catch (e) { }
  4057. return;
  4058. }
  4059. if (tagOf(probe, "del.doc-del")) {
  4060. // already suggested deleted: just step over it
  4061. if (forward) sel.collapse(r.endContainer, r.endOffset);
  4062. else sel.collapse(r.startContainer, r.startOffset);
  4063. return;
  4064. }
  4065. suggestDeleteRange(r);
  4066. }
  4067. function onEditorBeforeInput(e) {
  4068. if (!suggesting || inHeaderFooter()) return;
  4069. var t = e.inputType || "";
  4070. var sel = window.getSelection();
  4071. if (!sel || !sel.rangeCount) return;
  4072. if (!editor.contains(sel.getRangeAt(0).commonAncestorContainer)) return;
  4073. if (t === "insertText") {
  4074. // insertCompositionText is NOT handled: it is not cancelable, so
  4075. // intercepting it would double-insert IME (e.g. CJK) input -
  4076. // composed text stays untracked instead
  4077. if (e.data === null || e.data === undefined) return;
  4078. e.preventDefault();
  4079. suggestInsert(e.data);
  4080. } else if (t.indexOf("delete") === 0) {
  4081. e.preventDefault();
  4082. var r = sel.getRangeAt(0);
  4083. if (!r.collapsed) suggestDeleteRange(r);
  4084. else suggestDeleteCollapsed(t === "deleteContentForward" || t === "deleteWordForward");
  4085. afterEdit(false);
  4086. }
  4087. // insertParagraph / formatting / drops stay untracked (limitation)
  4088. }
  4089. function allSuggestions() {
  4090. return editor.querySelectorAll("ins.doc-ins, del.doc-del");
  4091. }
  4092. function resolveSuggestion(el, accept) {
  4093. var isIns = el.tagName === "INS";
  4094. if (isIns === accept) unwrapEl(el); // keep the content
  4095. else el.parentNode.removeChild(el); // drop it
  4096. editor.normalize();
  4097. afterEdit(true);
  4098. }
  4099. function resolveAllSuggestions(accept) {
  4100. var list = allSuggestions();
  4101. if (!list.length) return;
  4102. for (var i = 0; i < list.length; i++) {
  4103. var el = list[i];
  4104. if (el.tagName === "INS" === accept) unwrapEl(el);
  4105. else if (el.parentNode) el.parentNode.removeChild(el);
  4106. }
  4107. editor.normalize();
  4108. afterEdit(true);
  4109. OfficeApp.setStatus((accept ? "Accepted " : "Rejected ") + list.length + " suggestion(s)");
  4110. }
  4111. function setSuggesting(on) {
  4112. suggesting = !!on;
  4113. OfficeApp.markDirty();
  4114. updateSuggestStatus();
  4115. }
  4116. function updateSuggestStatus() {
  4117. var pending = allSuggestions().length;
  4118. var html = "";
  4119. if (suggesting) {
  4120. html = '<i class="pencil alternate icon"></i>Suggesting' +
  4121. (pending ? " · " + pending + " pending" : "");
  4122. } else if (pending) {
  4123. html = pending + " suggestion(s) pending";
  4124. }
  4125. OfficeApp.updateStatusItem("suggest", html);
  4126. }
  4127. /* content with every suggestion accepted and comment anchors unwrapped -
  4128. what foreign exports (docx/html/md/txt) should contain */
  4129. function resolvedHtml() {
  4130. var div = document.createElement("div");
  4131. div.innerHTML = cleanedHtml();
  4132. var list = div.querySelectorAll("ins.doc-ins, del.doc-del, span.doc-cmt");
  4133. for (var i = 0; i < list.length; i++) {
  4134. var el = list[i];
  4135. if (el.tagName === "DEL") el.parentNode.removeChild(el);
  4136. else unwrapEl(el);
  4137. }
  4138. div.normalize();
  4139. return div.innerHTML;
  4140. }
  4141. /* ================= copy / cut of a selected image =================
  4142. Image selection is app-level (selectImage), not a DOM range, so the
  4143. browser's native copy has nothing to grab. Put the image on the
  4144. system clipboard as HTML - handleEditorPaste's text/html branch
  4145. (and other apps) take it from there. */
  4146. function handleImageCopyCut(e, isCut) {
  4147. if (!selectedImg) return;
  4148. if (!e.clipboardData) return;
  4149. var clone = selectedImg.cloneNode(false);
  4150. clone.classList.remove("of-selimg");
  4151. if (!clone.getAttribute("class")) clone.removeAttribute("class");
  4152. // absolute URL so the image also resolves outside this page
  4153. try { clone.src = selectedImg.src; } catch (err) { }
  4154. canonicalCrop(clone);
  4155. e.clipboardData.setData("text/html", clone.outerHTML);
  4156. e.clipboardData.setData("text/plain", "");
  4157. e.preventDefault();
  4158. if (isCut) {
  4159. var img = selectedImg;
  4160. deselectImage();
  4161. if (img.parentNode) img.parentNode.removeChild(img);
  4162. afterEdit(true);
  4163. } else {
  4164. OfficeApp.setStatus("Image copied");
  4165. }
  4166. }
  4167. /* ================= menu-driven clipboard =================
  4168. Ctrl+X/C/V go through the native events; menu clicks have no event,
  4169. so use the async clipboard API (image > html > plain text, mirroring
  4170. handleEditorPaste, including suggest-mode wrapping). */
  4171. function menuCutCopy(isCut) {
  4172. if (selectedImg) {
  4173. // image selection is app-level - write it as HTML ourselves
  4174. var clone = selectedImg.cloneNode(false);
  4175. clone.classList.remove("of-selimg");
  4176. if (!clone.getAttribute("class")) clone.removeAttribute("class");
  4177. try { clone.src = selectedImg.src; } catch (e) { }
  4178. canonicalCrop(clone);
  4179. OfficeClipboard.writeAsync({ html: clone.outerHTML, text: "" }).catch(function () { });
  4180. if (isCut) {
  4181. var img = selectedImg;
  4182. deselectImage();
  4183. if (img.parentNode) img.parentNode.removeChild(img);
  4184. afterEdit(true);
  4185. } else {
  4186. OfficeApp.setStatus("Image copied");
  4187. }
  4188. return;
  4189. }
  4190. restoreSel();
  4191. try { document.execCommand(isCut ? "cut" : "copy"); } catch (e) { }
  4192. if (isCut) afterEdit(true);
  4193. }
  4194. // Home > Copy > Copy as plain text: the selected text without its formatting
  4195. function copyPlainText() {
  4196. restoreSel();
  4197. var s = window.getSelection ? window.getSelection().toString() : "";
  4198. if (!s) { OfficeApp.setStatus("Select some text to copy", "error"); return; }
  4199. OfficeClipboard.writeAsync({ text: s }).then(function () {
  4200. OfficeApp.setStatus("Copied as plain text");
  4201. }, function () {
  4202. OfficeApp.setStatus("Copy blocked by the browser - use Ctrl+C instead", "error");
  4203. });
  4204. }
  4205. function pasteFromMenu(plainOnly) {
  4206. var fallbackText = function () {
  4207. if (navigator.clipboard && navigator.clipboard.readText) {
  4208. navigator.clipboard.readText().then(function (t) {
  4209. if (!t) return;
  4210. restoreSel();
  4211. if (suggesting && !inHeaderFooter()) suggestInsert(t);
  4212. else { try { document.execCommand("insertText", false, t); } catch (e) { } }
  4213. afterEdit(true);
  4214. }).catch(function () {
  4215. OfficeApp.setStatus("Paste blocked by the browser - use Ctrl+V instead", "error");
  4216. });
  4217. } else {
  4218. OfficeApp.setStatus("Use Ctrl+V to paste here", "error");
  4219. }
  4220. };
  4221. if (plainOnly || !(navigator.clipboard && navigator.clipboard.read)) {
  4222. fallbackText();
  4223. return;
  4224. }
  4225. navigator.clipboard.read().then(function (cbItems) {
  4226. var img = null, htmlIt = null;
  4227. cbItems.forEach(function (it) {
  4228. it.types.forEach(function (ty) {
  4229. if (!img && ty.indexOf("image/") === 0) img = { it: it, ty: ty };
  4230. if (!htmlIt && ty === "text/html") htmlIt = it;
  4231. });
  4232. });
  4233. if (img) {
  4234. img.it.getType(img.ty).then(function (blob) {
  4235. OfficeApp.blobToSrc(blob, "pasted.png", function (src) {
  4236. restoreSel();
  4237. insertImage(src);
  4238. }, function (msg) { OfficeApp.toast(msg, "error"); });
  4239. }).catch(fallbackText);
  4240. return;
  4241. }
  4242. if (htmlIt) {
  4243. htmlIt.getType("text/html").then(function (blob) {
  4244. return blob.text();
  4245. }).then(function (html) {
  4246. var clean = sanitizeHtml(html, { keepClasses: false });
  4247. if (!clean) { fallbackText(); return; }
  4248. if (suggesting && !inHeaderFooter()) {
  4249. clean = '<ins class="doc-ins">' + clean + "</ins>";
  4250. }
  4251. restoreSel();
  4252. try { document.execCommand("insertHTML", false, clean); } catch (e) { }
  4253. afterEdit(true);
  4254. adoptPastedImages();
  4255. }).catch(fallbackText);
  4256. return;
  4257. }
  4258. fallbackText();
  4259. }).catch(fallbackText);
  4260. }
  4261. /* Pictures pasted from another window link into that window's working
  4262. copies, which go when it closes: make them this window's own. */
  4263. function adoptPastedImages() {
  4264. var imgs = editor.querySelectorAll("img");
  4265. Array.prototype.forEach.call(imgs, function (img) {
  4266. ["src", "data-export-src"].forEach(function (attr) {
  4267. var v = img.getAttribute(attr);
  4268. if (!v || !OfficePlatform.isForeignWorkingCopy(v)) return;
  4269. OfficePlatform.adoptSrc(v, function (nv) {
  4270. if (nv === v || img.getAttribute(attr) !== v) return;
  4271. img.setAttribute(attr, nv);
  4272. OfficeApp.markDirty();
  4273. });
  4274. });
  4275. });
  4276. }
  4277. /* ================= paste ================= */
  4278. function handleEditorPaste(e) {
  4279. var cd = e.clipboardData;
  4280. if (!cd) return; // let the browser do its default thing
  4281. e.preventDefault();
  4282. // 1. image from clipboard -> dataURL <img>
  4283. var items = cd.items || [];
  4284. for (var i = 0; i < items.length; i++) {
  4285. if (items[i].kind === "file" && items[i].type.indexOf("image/") === 0) {
  4286. var f = items[i].getAsFile();
  4287. if (f) {
  4288. // small images inline; big ones upload to the workdir
  4289. OfficeApp.blobToSrc(f, f.name || "pasted.png", function (src) {
  4290. insertImage(src);
  4291. }, function (msg) {
  4292. OfficeApp.toast(msg, "error");
  4293. });
  4294. return;
  4295. }
  4296. }
  4297. }
  4298. // 2. HTML clipboard -> sanitized (scripts/styles/classes/ids stripped)
  4299. var html = cd.getData("text/html");
  4300. if (html) {
  4301. var clean = sanitizeHtml(html, { keepClasses: false });
  4302. if (clean) {
  4303. if (suggesting && !inHeaderFooter()) {
  4304. // pasted content is a suggestion too
  4305. clean = '<ins class="doc-ins">' + clean + "</ins>";
  4306. }
  4307. try { document.execCommand("insertHTML", false, clean); } catch (err) { }
  4308. afterEdit(true);
  4309. adoptPastedImages();
  4310. return;
  4311. }
  4312. }
  4313. // 3. plain text (ignore another app's raw marker JSON - its rich
  4314. // text/html form was handled above)
  4315. var t = cd.getData("text/plain");
  4316. if (t && !(window.OfficeClipboard && OfficeClipboard.isMarker(t))) {
  4317. if (suggesting && !inHeaderFooter()) {
  4318. suggestInsert(t);
  4319. afterEdit(true);
  4320. return;
  4321. }
  4322. try { document.execCommand("insertText", false, t); } catch (err) { }
  4323. afterEdit(true);
  4324. }
  4325. }
  4326. /* ================= exporters ================= */
  4327. function exportBaseName() {
  4328. return OfficeApp.stripExt(OfficeApp.getFileName() || "document") || "document";
  4329. }
  4330. function downloadFile(name, mime, content) {
  4331. var blob = new Blob([content], { type: mime + ";charset=utf-8" });
  4332. var url = URL.createObjectURL(blob);
  4333. var a = document.createElement("a");
  4334. a.href = url;
  4335. a.download = name;
  4336. document.body.appendChild(a);
  4337. a.click();
  4338. document.body.removeChild(a);
  4339. setTimeout(function () { URL.revokeObjectURL(url); }, 5000);
  4340. }
  4341. /* ================= PDF =================
  4342. Drawn in the browser from the pages the editor shows (docs_pdf.js),
  4343. so the export paginates exactly like the preview, carries real
  4344. selectable text, embeds the shipped CJK faces, and needs no server -
  4345. it works in the standalone web edition too.
  4346. The page is held only while it is measured, in its export state:
  4347. 100% zoom (a zoomed layout rounds borders to different pixels), no
  4348. selection chrome, and review marks shown as resolved - suggestions
  4349. accepted, comment highlights off - which is what the other exports
  4350. write too. Everything after that (fonts, pictures, compression) runs
  4351. from the measured snapshot in a Web Worker, and the document can be
  4352. edited meanwhile without changing the file that comes out. */
  4353. function canExportPdf() {
  4354. return typeof PDFLib !== "undefined" && !!window.DocsPdf;
  4355. }
  4356. function renderPdf(onProgress) {
  4357. var prevZoom = 100;
  4358. var relaid = false;
  4359. var geo = pageGeometry();
  4360. return DocsPdf.build({
  4361. pageEl: pageEl,
  4362. pages: function () { return lastPages; },
  4363. sheetW: geo.sheetW, sheetH: geo.sheetH,
  4364. title: exportBaseName(),
  4365. onProgress: onProgress,
  4366. enter: function () {
  4367. clearFindHits();
  4368. deselectImage();
  4369. prevZoom = OfficeApp.getZoom() || 100;
  4370. if (prevZoom !== 100) OfficeApp.setZoom(100);
  4371. document.body.classList.add("doc-exporting");
  4372. // hiding pending deletions changes the text flow; everything
  4373. // else the export state does is paint only
  4374. if (prevZoom !== 100 || editor.querySelector("del.doc-del")) {
  4375. updatePageGuides();
  4376. relaid = true;
  4377. }
  4378. },
  4379. leave: function () {
  4380. document.body.classList.remove("doc-exporting");
  4381. if (prevZoom !== 100) OfficeApp.setZoom(prevZoom);
  4382. if (relaid) updatePageGuides();
  4383. }
  4384. });
  4385. }
  4386. // how far along an export is, in words and as a fraction
  4387. function pdfProgressText(done, total, stage) {
  4388. if (stage === "measure") return { f: 0.02, msg: "Reading the pages..." };
  4389. if (stage === "prepare") return { f: 0.06, msg: "Preparing fonts and pictures..." };
  4390. if (stage === "save") return { f: 0.95, msg: "Writing the file..." };
  4391. return {
  4392. f: 0.1 + 0.85 * (total ? done / total : 0),
  4393. msg: "Exporting " + done + " / " + total + (total === 1 ? " page" : " pages")
  4394. };
  4395. }
  4396. /* savePdfTo renders and writes the bytes; shared by File > Export and by
  4397. the .pdf entry in SAVE_FORMATS. prog is an optional progress panel. */
  4398. function savePdfTo(fp, done, fail, prog) {
  4399. if (!canExportPdf()) { fail("the PDF library failed to load"); return; }
  4400. renderPdf(function (n, total, stage) {
  4401. var p = pdfProgressText(n, total, stage);
  4402. if (prog) prog.set(p.f * 100, 100, p.msg);
  4403. else OfficeApp.setStatus("PDF: " + p.msg);
  4404. }).then(function (bytes) {
  4405. if (prog) prog.message("Writing " + OfficeApp.basename(fp) + "...");
  4406. OfficePlatform.writeBytes(fp, bytes, done, fail);
  4407. }).catch(function (err) {
  4408. fail(err && err.message ? err.message : "render error");
  4409. });
  4410. }
  4411. function exportPdf() {
  4412. if (!canExportPdf()) {
  4413. OfficeApp.toast("The PDF library failed to load", "error");
  4414. return;
  4415. }
  4416. OfficePlatform.pickSave({ defaultName: exportBaseName() + ".pdf", ext: ".pdf", memoryKey: "export" }, function (file) {
  4417. var fp = file.filepath;
  4418. // the export does not hold the document: a panel in the corner
  4419. // reports it while editing goes on
  4420. var prog = OfficeApp.showProgress({ title: "Exporting PDF", anchor: "#workspace" });
  4421. prog.set(0, 100, "Reading the pages...");
  4422. savePdfTo(fp, function () {
  4423. prog.close();
  4424. OfficeApp.setStatus("Exported " + OfficeApp.basename(fp));
  4425. OfficeApp.toast("Exported " + OfficeApp.basename(fp));
  4426. }, function (msg) {
  4427. prog.close();
  4428. OfficeApp.toast("Export failed: " + msg, "error");
  4429. }, prog);
  4430. });
  4431. }
  4432. var EXPORT_CSS =
  4433. "body{font-family:Arial,Helvetica,sans-serif;font-size:11pt;line-height:1.5;" +
  4434. "color:#1f2328;max-width:820px;margin:24px auto;padding:0 18px;}" +
  4435. "h1{font-size:20pt;}h2{font-size:16pt;}h3{font-size:13pt;}h4{font-size:11pt;font-style:italic;}" +
  4436. ".doc-title{font-size:26pt;font-weight:400;}" +
  4437. "a{color:#1a58c2;}" +
  4438. "table{border-collapse:collapse;width:100%;}td,th{border:1px solid #b9bec7;padding:4px 8px;vertical-align:top;}" +
  4439. "pre{background:#f1f3f4;border:1px solid #e2e5e9;border-radius:6px;padding:10px 12px;" +
  4440. "font-family:Consolas,'Courier New',monospace;font-size:10pt;overflow-x:auto;white-space:pre-wrap;}" +
  4441. "blockquote{border-left:3px solid #c3c7cc;margin-left:0;padding-left:12px;color:#5f6368;}" +
  4442. "img{max-width:100%;height:auto;}" +
  4443. "hr{border:none;border-top:1px solid #c9cdd3;}" +
  4444. "ul.of-checklist{list-style:none;padding-left:1.4em;}" +
  4445. "ul.of-checklist li::before{content:\"\\2610 \";}" +
  4446. "ul.of-checklist li.checked::before{content:\"\\2611 \";}" +
  4447. "ul.of-checklist li.checked{text-decoration:line-through;color:#888;}" +
  4448. ".hf{color:#777;font-size:9pt;margin:10px 0;}";
  4449. /* The three text renderings, built once and used twice: File > Export
  4450. downloads them, and the matching saveFormats writer stores them - which
  4451. is what a document opened from .html / .txt / .md is saved back into. */
  4452. function buildHTML() {
  4453. var body = currentBody();
  4454. var title = exportBaseName();
  4455. var out = "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n" +
  4456. "<title>" + esc(title) + "</title>\n<style>" + EXPORT_CSS + "</style>\n</head>\n<body>\n";
  4457. // a web page has no pages to repeat them on: one copy top and bottom,
  4458. // and nothing at all when the header/footer are turned off
  4459. var hf = body.hfMode !== "none";
  4460. if (hf && body.header) out += '<div class="hf">' + esc(body.header) + "</div>\n";
  4461. out += resolvedHtml() + "\n";
  4462. if (hf && body.footer) out += '<div class="hf">' + esc(body.footer) + "</div>\n";
  4463. out += "</body>\n</html>\n";
  4464. return out;
  4465. }
  4466. function buildText() {
  4467. var div = document.createElement("div");
  4468. div.innerHTML = resolvedHtml();
  4469. return div.innerText || "";
  4470. }
  4471. function buildMarkdown() {
  4472. var div = document.createElement("div");
  4473. div.innerHTML = resolvedHtml();
  4474. return htmlToMarkdown(div).replace(/\n{3,}/g, "\n\n").trim() + "\n";
  4475. }
  4476. function exportHTML() { downloadFile(exportBaseName() + ".html", "text/html", buildHTML()); }
  4477. function exportText() { downloadFile(exportBaseName() + ".txt", "text/plain", buildText()); }
  4478. function exportMarkdown() { downloadFile(exportBaseName() + ".md", "text/markdown", buildMarkdown()); }
  4479. /* --- basic HTML -> Markdown conversion (hand-written, MVP scope) --- */
  4480. function htmlToMarkdown(rootEl) {
  4481. function wrapMark(t, mark) {
  4482. var m = t.match(/^(\s*)([\s\S]*?)(\s*)$/);
  4483. if (!m || !m[2]) return "";
  4484. return m[1] + mark + m[2] + mark + m[3];
  4485. }
  4486. function inline(node) {
  4487. var out = "";
  4488. var kids = node.childNodes;
  4489. for (var i = 0; i < kids.length; i++) {
  4490. var k = kids[i];
  4491. if (k.nodeType === 3) { out += k.nodeValue.replace(/[ \t\r\n]+/g, " "); continue; }
  4492. if (k.nodeType !== 1) continue;
  4493. var tag = k.tagName;
  4494. if (tag === "BR") { out += " \n"; continue; }
  4495. if (tag === "IMG") {
  4496. out += "![" + (k.getAttribute("alt") || "") + "](" + (k.getAttribute("src") || "") + ")";
  4497. continue;
  4498. }
  4499. var inner = inline(k);
  4500. switch (tag) {
  4501. case "B": case "STRONG": out += wrapMark(inner, "**"); break;
  4502. case "I": case "EM": out += wrapMark(inner, "*"); break;
  4503. case "S": case "DEL": case "STRIKE": out += wrapMark(inner, "~~"); break;
  4504. case "CODE": out += inner.trim() ? "`" + inner.trim() + "`" : ""; break;
  4505. case "A":
  4506. out += "[" + (inner.trim() || k.getAttribute("href") || "") +
  4507. "](" + (k.getAttribute("href") || "") + ")";
  4508. break;
  4509. case "UL": case "OL": case "TABLE": case "PRE":
  4510. case "BLOCKQUOTE": case "P": case "DIV":
  4511. out += "\n" + block(k, "");
  4512. break;
  4513. default: out += inner;
  4514. }
  4515. }
  4516. return out;
  4517. }
  4518. function list(el, indent) {
  4519. var out = "";
  4520. var isOl = el.tagName === "OL";
  4521. var isCheck = el.classList.contains("of-checklist");
  4522. var n = 0;
  4523. for (var i = 0; i < el.children.length; i++) {
  4524. var li = el.children[i];
  4525. if (li.tagName !== "LI") continue;
  4526. n++;
  4527. var marker = isOl ? (n + ". ")
  4528. : (isCheck ? (li.classList.contains("checked") ? "- [x] " : "- [ ] ") : "- ");
  4529. var liClone = li.cloneNode(true);
  4530. var nested = liClone.querySelectorAll("ul,ol");
  4531. for (var j = nested.length - 1; j >= 0; j--) {
  4532. if (nested[j].parentNode) nested[j].parentNode.removeChild(nested[j]);
  4533. }
  4534. out += indent + marker + inline(liClone).trim() + "\n";
  4535. for (j = 0; j < li.children.length; j++) {
  4536. var c = li.children[j];
  4537. if (c.tagName === "UL" || c.tagName === "OL") out += list(c, indent + " ");
  4538. }
  4539. }
  4540. return out;
  4541. }
  4542. function mdTable(el) {
  4543. if (!el.rows || !el.rows.length) return "";
  4544. var out = "";
  4545. for (var i = 0; i < el.rows.length; i++) {
  4546. var cells = el.rows[i].cells;
  4547. var line = "|";
  4548. for (var j = 0; j < cells.length; j++) {
  4549. line += " " + inline(cells[j]).trim().replace(/\|/g, "\\|") + " |";
  4550. }
  4551. out += line + "\n";
  4552. if (i === 0) {
  4553. var sepLine = "|";
  4554. for (j = 0; j < cells.length; j++) sepLine += " --- |";
  4555. out += sepLine + "\n";
  4556. }
  4557. }
  4558. return out;
  4559. }
  4560. function block(node, indent) {
  4561. var out = "";
  4562. var kids = node.childNodes;
  4563. for (var i = 0; i < kids.length; i++) {
  4564. var k = kids[i];
  4565. if (k.nodeType === 3) {
  4566. var raw = k.nodeValue.trim();
  4567. if (raw) out += raw + "\n\n";
  4568. continue;
  4569. }
  4570. if (k.nodeType !== 1) continue;
  4571. var tag = k.tagName;
  4572. if (/^H[1-6]$/.test(tag)) {
  4573. var lvl = k.classList.contains("doc-title") ? 1 : parseInt(tag.substring(1), 10);
  4574. out += new Array(lvl + 1).join("#") + " " + inline(k).trim() + "\n\n";
  4575. } else if (tag === "UL" || tag === "OL") {
  4576. out += list(k, indent) + "\n";
  4577. } else if (tag === "BLOCKQUOTE") {
  4578. var q = block(k, "").trim().split("\n").map(function (l) { return "> " + l; }).join("\n");
  4579. out += q + "\n\n";
  4580. } else if (tag === "PRE") {
  4581. out += "```\n" + k.textContent.replace(/\n$/, "") + "\n```\n\n";
  4582. } else if (tag === "HR") {
  4583. out += "---\n\n";
  4584. } else if (tag === "TABLE") {
  4585. out += mdTable(k) + "\n";
  4586. } else if (tag === "P" || tag === "DIV") {
  4587. if (tag === "DIV" && k.querySelector("ul,ol,table,pre,blockquote,h1,h2,h3,h4,p,div,hr")) {
  4588. out += block(k, indent);
  4589. } else {
  4590. var t = inline(k).trim();
  4591. if (t) out += t + "\n\n";
  4592. }
  4593. } else {
  4594. var t2 = inline(k).trim();
  4595. if (t2) out += t2 + "\n\n";
  4596. }
  4597. }
  4598. return out;
  4599. }
  4600. return block(rootEl, "");
  4601. }
  4602. /* ================= importers ================= */
  4603. function setImportedContent(html) {
  4604. pageConf = defaultPageConf();
  4605. loadBody({ html: html, page: pageConf, header: "", footer: "", pageNumbers: false });
  4606. undo.reset(snapshot());
  4607. }
  4608. function importTxt(text) {
  4609. var paras = String(text).replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n{2,}/);
  4610. var html = paras.map(function (p) {
  4611. return "<p>" + (p.trim() ? esc(p).replace(/\n/g, "<br>") : "<br>") + "</p>";
  4612. }).join("");
  4613. setImportedContent(html);
  4614. }
  4615. function importMd(text) {
  4616. var html = "";
  4617. try {
  4618. if (typeof marked !== "undefined") {
  4619. html = (typeof marked.parse === "function") ? marked.parse(text) : marked(text);
  4620. }
  4621. } catch (e) { html = ""; }
  4622. if (!html) {
  4623. importTxt(text);
  4624. return;
  4625. }
  4626. setImportedContent(sanitizeHtml(html, { keepClasses: false }));
  4627. }
  4628. function importHtml(text) {
  4629. setImportedContent(sanitizeHtml(text, { keepClasses: false }));
  4630. }
  4631. /* ================= ODT import / export =================
  4632. The document's own format, .docx, is opened and saved by the framework
  4633. (OfficePlatform.documentLoad / documentSave). OpenDocument goes
  4634. through the same Go converters either way: the office AGI library in
  4635. ArozOS, the WebAssembly build of it (src/wasm/office) in the
  4636. standalone web edition. One descriptor names both, and OfficePlatform
  4637. picks. */
  4638. var CONVERT_BACKEND = "Office/docs/backend/convert.agi";
  4639. var CONVERT = {
  4640. "import-odf": { agi: CONVERT_BACKEND, action: "import-odf", wasm: "odtToDocument" },
  4641. "export-odf": { agi: CONVERT_BACKEND, action: "export-odf", wasm: "documentToOdt" }
  4642. };
  4643. function importDocFile(fp, fn, action) {
  4644. OfficeApp.showBusy("Importing " + fn + "...");
  4645. OfficePlatform.convertIn(CONVERT[action], fp, function (body) {
  4646. OfficeApp.hideBusy();
  4647. var b = body;
  4648. if (typeof b === "string") {
  4649. try { b = JSON.parse(b); } catch (e) { b = null; }
  4650. }
  4651. if (!b || typeof b.html !== "string") {
  4652. OfficeApp.toast("Import failed: unexpected response", "error");
  4653. return;
  4654. }
  4655. OfficeApp.splashStep("Laying out the pages...", function () {
  4656. loadBody(b);
  4657. undo.reset(snapshot());
  4658. // the framework kept us attached to the source file, so Save
  4659. // writes straight back to it in its own format
  4660. OfficeApp.setStatus("Opened " + fn);
  4661. OfficeApp.documentLoaded();
  4662. });
  4663. }, function (msg) {
  4664. OfficeApp.hideBusy();
  4665. OfficeApp.toast("Import failed: " + msg, "error");
  4666. });
  4667. }
  4668. function importOdt(fp, fn) { importDocFile(fp, fn, "import-odf"); }
  4669. /* ================= pictures Word cannot hold =================
  4670. Word and the OpenDocument writers embed PNG, JPEG and GIF. A picture
  4671. in anything else (an SVG chart pasted from Sheets or Slides, WebP,
  4672. BMP) is rendered to PNG at 2x its display size before saving, and the
  4673. PNG rides along in data-export-src - the writers prefer it, the
  4674. editor keeps showing the original.
  4675. Pictures are otherwise left alone: a storage picture stays a
  4676. media?file= link and the server reads it, so a save never downloads
  4677. and re-uploads them. The PNG renders are kept for the session and, in
  4678. ArozOS, uploaded once (OfficePlatform.cacheBlob), so an unchanged
  4679. chart costs nothing on the next save. */
  4680. var exportPngCache = {}; // src + "|" + width -> PNG src
  4681. function needsPngForExport(src) {
  4682. if (/^data:image\/(svg|webp|bmp)/i.test(src)) return true;
  4683. var path = String(src).split("#")[0];
  4684. try { path = decodeURIComponent(path); } catch (e) { }
  4685. return /\.(svg|webp|bmp)(\?|&|$)/i.test(path);
  4686. }
  4687. function rasterizeToPngSrc(src, w) {
  4688. var key = src + "|" + w;
  4689. if (exportPngCache[key]) return Promise.resolve(exportPngCache[key]);
  4690. return new Promise(function (resolve) {
  4691. var probe = new Image();
  4692. probe.onload = function () {
  4693. var cw = w || probe.naturalWidth || 400;
  4694. var ch = cw * (probe.naturalHeight || 300) / (probe.naturalWidth || 400);
  4695. var cv = document.createElement("canvas");
  4696. cv.width = Math.max(1, Math.round(cw * 2));
  4697. cv.height = Math.max(1, Math.round(ch * 2));
  4698. var ctx = cv.getContext("2d");
  4699. ctx.fillStyle = "#ffffff";
  4700. ctx.fillRect(0, 0, cv.width, cv.height);
  4701. try {
  4702. ctx.drawImage(probe, 0, 0, cv.width, cv.height);
  4703. } catch (e) { resolve(null); return; }
  4704. cv.toBlob(function (blob) {
  4705. if (!blob) { resolve(null); return; }
  4706. OfficePlatform.cacheBlob(blob, "picture.png", function (out) {
  4707. exportPngCache[key] = { src: out, w: cw, h: ch };
  4708. resolve(exportPngCache[key]);
  4709. }, function () { resolve(null); });
  4710. }, "image/png");
  4711. };
  4712. probe.onerror = function () { resolve(null); };
  4713. probe.src = src;
  4714. });
  4715. }
  4716. // an img's display width in CSS px, from its style or width attribute
  4717. function imgDisplayWidth(im) {
  4718. var w = parseFloat((im.getAttribute("style") || "").replace(/^(?:.*;)?\s*width:\s*([\d.]+)px.*$/, "$1"));
  4719. if (!(w > 0)) w = parseInt(im.getAttribute("width"), 10);
  4720. return w > 0 ? w : 0;
  4721. }
  4722. /* html -> Promise(html) with data-export-src on every picture that needs
  4723. one, and a stale one dropped from a picture that no longer does */
  4724. function withExportPictures(html) {
  4725. if (!html || html.indexOf("<img") < 0) return Promise.resolve(html);
  4726. var div = document.createElement("div");
  4727. div.innerHTML = html;
  4728. var jobs = Array.prototype.slice.call(div.querySelectorAll("img")).map(function (im) {
  4729. var src = im.getAttribute("src") || "";
  4730. if (!needsPngForExport(src)) {
  4731. im.removeAttribute("data-export-src");
  4732. return null;
  4733. }
  4734. var w = imgDisplayWidth(im);
  4735. var sized = w > 0 || /(^|;)\s*width\s*:/i.test(im.getAttribute("style") || "");
  4736. return rasterizeToPngSrc(src, w).then(function (png) {
  4737. if (!png) { im.removeAttribute("data-export-src"); return; }
  4738. im.setAttribute("data-export-src", png.src);
  4739. // the PNG is drawn at 2x: without a stated size the writer
  4740. // would take its pixels for the picture's size
  4741. if (!sized) {
  4742. im.setAttribute("width", String(Math.round(png.w)));
  4743. im.setAttribute("height", String(Math.round(png.h)));
  4744. }
  4745. });
  4746. });
  4747. return Promise.all(jobs).then(function () { return div.innerHTML; });
  4748. }
  4749. // the ODF writer reads src itself: swap the PNG in
  4750. function exportSrcAsSrc(html) {
  4751. if (!html || html.indexOf("data-export-src") < 0) return html;
  4752. var div = document.createElement("div");
  4753. div.innerHTML = html;
  4754. var imgs = div.querySelectorAll("img[data-export-src]");
  4755. for (var i = 0; i < imgs.length; i++) {
  4756. imgs[i].setAttribute("src", imgs[i].getAttribute("data-export-src"));
  4757. imgs[i].removeAttribute("data-export-src");
  4758. }
  4759. return div.innerHTML;
  4760. }
  4761. // what the framework calls before writing the .docx: body is its own copy
  4762. function prepareNative(body) {
  4763. var parts = ["html", "headerHtml", "footerHtml"];
  4764. var jobs = parts.map(function (k) {
  4765. if (typeof body[k] !== "string") return null;
  4766. return withExportPictures(body[k]).then(function (h) { body[k] = h; });
  4767. });
  4768. (body.footnotes || []).forEach(function (fn) {
  4769. jobs.push(withExportPictures(fn.html).then(function (h) { fn.html = h; }));
  4770. });
  4771. return Promise.all(jobs);
  4772. }
  4773. /* a body for the ODF writer: suggestions applied, comment anchors
  4774. unwrapped (ODF does not get review markup), pictures as PNG */
  4775. function odfBody() {
  4776. var b = currentBody();
  4777. b.html = resolvedHtml();
  4778. return prepareNative(b).then(function () {
  4779. ["html", "headerHtml", "footerHtml"].forEach(function (k) {
  4780. if (typeof b[k] === "string") b[k] = exportSrcAsSrc(b[k]);
  4781. });
  4782. (b.footnotes || []).forEach(function (fn) { fn.html = exportSrcAsSrc(fn.html); });
  4783. return b;
  4784. });
  4785. }
  4786. function exportOdt() {
  4787. if (!OfficePlatform.requireConvert("Exporting .odt")) return;
  4788. var defName = exportBaseName() + ".odt";
  4789. OfficePlatform.pickSave({ defaultName: defName, ext: ".odt", memoryKey: "export" }, function (file) {
  4790. var fp = file.filepath;
  4791. OfficeApp.showBusy("Exporting OpenDocument file...");
  4792. odfBody().then(function (b) {
  4793. // pictures stay links: the server reads them (office lib), and
  4794. // the web edition keeps them inline already
  4795. OfficePlatform.convertOut(CONVERT["export-odf"], fp, JSON.stringify(b), function () {
  4796. OfficeApp.hideBusy();
  4797. OfficeApp.setStatus("Exported " + OfficeApp.basename(fp));
  4798. OfficeApp.toast("Exported " + OfficeApp.basename(fp));
  4799. }, function (errmsg) {
  4800. OfficeApp.hideBusy();
  4801. OfficeApp.toast("Export failed: " + errmsg, "error");
  4802. });
  4803. });
  4804. });
  4805. }
  4806. /* ================= saving back into a foreign format =================
  4807. A document opened from .odt / .html / .md / .txt goes on living in
  4808. that file: the framework keeps filepath/filename pointing at it and
  4809. Ctrl+S comes back here instead of forcing a Save As to .docx. These
  4810. are the same renderings the Export menu produces, reporting through
  4811. the framework's save callbacks rather than a toast of their own. */
  4812. function plural(n, one, many) { return n + " " + (n === 1 ? one : many); }
  4813. function saveOdt(fp, done, fail) {
  4814. odfBody().then(function (b) {
  4815. OfficePlatform.convertOut(CONVERT["export-odf"], fp, JSON.stringify(b),
  4816. function () { done(); }, fail);
  4817. }).catch(function (err) {
  4818. fail((err && err.message) ? err.message : "could not prepare the document");
  4819. });
  4820. }
  4821. function saveTextFile(build, fp, done, fail) {
  4822. var content;
  4823. try { content = build(); }
  4824. catch (e) { fail(e.message || "could not render the document"); return; }
  4825. OfficeApp.vfsSave(fp, content, done, fail);
  4826. }
  4827. /*
  4828. Comments and pending suggestions live in the .docx as Word's own
  4829. comments and tracked changes; every other writer is fed
  4830. resolvedHtml(), which unwraps the comment anchors, keeps insertions
  4831. and drops deletions. That is a change to the text itself, so it is a
  4832. veto rather than a quiet loss. Formatting a format merely renders
  4833. differently is deliberately not listed - it would fire on nearly
  4834. every save.
  4835. */
  4836. function reviewUnsupported() {
  4837. var out = [];
  4838. var c = (comments || []).length;
  4839. if (c) out.push(plural(c, "comment", "comments"));
  4840. var s = allSuggestions().length;
  4841. if (s) {
  4842. out.push(plural(s, "pending suggestion", "pending suggestions") +
  4843. " - insertions would be accepted and deletions applied");
  4844. }
  4845. return out;
  4846. }
  4847. // .txt holds no pictures and no table structure at all
  4848. function textUnsupported() {
  4849. var out = reviewUnsupported();
  4850. var imgs = editor.querySelectorAll("img").length;
  4851. if (imgs) out.push(plural(imgs, "image", "images"));
  4852. var tables = editor.querySelectorAll("table").length;
  4853. if (tables) {
  4854. out.push(plural(tables, "table", "tables") +
  4855. " - only " + (tables === 1 ? "its" : "their") + " text would be kept");
  4856. }
  4857. return out;
  4858. }
  4859. /*
  4860. The formats File > Save as offers besides .docx, and the ones a
  4861. document opened from one of them is saved back into. needsConvert
  4862. marks the writers that go through the Office format converters and
  4863. needsBackend the ones that need a server outright (the real-text PDF
  4864. renderer); OfficeApp drops whichever the running host cannot do,
  4865. leaving the three text renderings - built right here in the browser -
  4866. always available. PDF is oneWay: it is a rendering, so writing one
  4867. leaves the document on its own file.
  4868. */
  4869. var SAVE_FORMATS = [
  4870. {
  4871. ext: ".odt", label: "OpenDocument text (.odt)", icon: "file alternate outline",
  4872. needsConvert: true, noAutosave: true,
  4873. unsupported: reviewUnsupported,
  4874. save: function (fp, fn, done, fail) { saveOdt(fp, done, fail); }
  4875. },
  4876. {
  4877. ext: ".pdf", label: "PDF document (.pdf)", icon: "file pdf outline",
  4878. oneWay: true,
  4879. save: function (fp, fn, done, fail) { savePdfTo(fp, done, fail); }
  4880. },
  4881. {
  4882. ext: ".html", label: "Web page (.html)", icon: "file code outline",
  4883. unsupported: reviewUnsupported,
  4884. save: function (fp, fn, done, fail) { saveTextFile(buildHTML, fp, done, fail); }
  4885. },
  4886. {
  4887. // the same writer under the other extension a web page may carry:
  4888. // save-back only, so Save as does not offer it twice
  4889. ext: ".htm", label: "Web page (.htm)", icon: "file code outline",
  4890. hidden: true,
  4891. unsupported: reviewUnsupported,
  4892. save: function (fp, fn, done, fail) { saveTextFile(buildHTML, fp, done, fail); }
  4893. },
  4894. {
  4895. ext: ".md", label: "Markdown (.md)", icon: "file alternate outline",
  4896. unsupported: reviewUnsupported,
  4897. save: function (fp, fn, done, fail) { saveTextFile(buildMarkdown, fp, done, fail); }
  4898. },
  4899. {
  4900. ext: ".txt", label: "Plain text (.txt)", icon: "file outline",
  4901. unsupported: textUnsupported,
  4902. save: function (fp, fn, done, fail) { saveTextFile(buildText, fp, done, fail); }
  4903. }
  4904. ];
  4905. /* ================= floating selection format bar ================= */
  4906. /* PowerPoint-style mini toolbar (shared OfficeTextEditBar) floating
  4907. above the current text selection inside the editor. */
  4908. function initSelectionBar() {
  4909. if (!window.OfficeTextEditBar) return;
  4910. var barTimer = null;
  4911. function selRect() {
  4912. var sel = window.getSelection();
  4913. if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return null;
  4914. // a selected picture is not text: right-clicking one makes the
  4915. // browser select the <img> node, which must not bring the bar up
  4916. if (selectedImg && editor.contains(selectedImg)) return null;
  4917. var range = sel.getRangeAt(0);
  4918. if (!editor.contains(range.commonAncestorContainer)) return null;
  4919. if (!/\S/.test(range.toString())) return null;
  4920. var r = range.getBoundingClientRect();
  4921. if (!r || (r.width === 0 && r.height === 0)) return null;
  4922. return r;
  4923. }
  4924. function currentSelFontPx() {
  4925. var n = window.getSelection().anchorNode;
  4926. if (n && n.nodeType === 3) n = n.parentNode;
  4927. if (!n || !editor.contains(n)) return 15;
  4928. var fs = parseFloat(getComputedStyle(n).fontSize);
  4929. return isNaN(fs) ? 15 : Math.round(fs);
  4930. }
  4931. document.addEventListener("selectionchange", function () {
  4932. clearTimeout(barTimer);
  4933. barTimer = setTimeout(function () {
  4934. if ($(".of-dialog-overlay").length) return;
  4935. var r = selRect();
  4936. if (r) {
  4937. if (!OfficeTextEditBar.isVisible()) {
  4938. OfficeTextEditBar.show({
  4939. anchor: editor,
  4940. getRect: selRect,
  4941. fontSize: currentSelFontPx(),
  4942. onFontSize: function (px) { applyFontSize(Math.round(px * 0.75)); },
  4943. tableOps: docsTableOps()
  4944. });
  4945. } else {
  4946. // the bar is reused across selection moves - keep the
  4947. // table section in step with where the caret sits
  4948. OfficeTextEditBar.setTableOps(docsTableOps());
  4949. }
  4950. } else if (OfficeTextEditBar.isVisible() &&
  4951. !OfficeTextEditBar.contains(document.activeElement)) {
  4952. OfficeTextEditBar.hide();
  4953. }
  4954. }, 180);
  4955. });
  4956. // keep the bar glued to the text when the document scrolls
  4957. workspaceEl.addEventListener("scroll", function () {
  4958. if (OfficeTextEditBar.isVisible()) OfficeTextEditBar.reposition();
  4959. });
  4960. }
  4961. /* ================= table column / row resizing ================= */
  4962. /* Drag a cell's right border to resize its column (Word-style: the
  4963. neighbour column compensates; the table's outer edge grows the
  4964. table). Drag a bottom border to change the row height. */
  4965. var tblDrag = null;
  4966. function zoomFactor() { return (OfficeApp.getZoom() || 100) / 100; }
  4967. function tableBorderHit(e) {
  4968. if (inHeaderFooter()) return null;
  4969. var cell = e.target.closest ? e.target.closest("td,th") : null;
  4970. if (!cell || !editor.contains(cell)) return null;
  4971. var r = cell.getBoundingClientRect();
  4972. var HOT = 5;
  4973. if (e.clientX >= r.right - HOT && e.clientX <= r.right + HOT) return { cell: cell, type: "col" };
  4974. if (e.clientY >= r.bottom - HOT && e.clientY <= r.bottom + HOT) return { cell: cell, type: "row" };
  4975. return null;
  4976. }
  4977. function cellColIndex(cell) {
  4978. var i = 0;
  4979. var n = cell;
  4980. while (n.previousElementSibling) { n = n.previousElementSibling; i++; }
  4981. return i;
  4982. }
  4983. /* give the table an explicit colgroup so column widths stick */
  4984. function ensureColgroup(table) {
  4985. var cg = table.querySelector("colgroup");
  4986. var firstRow = table.rows.length ? table.rows[0] : null;
  4987. if (!firstRow) return null;
  4988. var cols = firstRow.cells.length;
  4989. if (!cg || cg.children.length !== cols) {
  4990. if (cg) cg.parentNode.removeChild(cg);
  4991. cg = document.createElement("colgroup");
  4992. for (var i = 0; i < cols; i++) {
  4993. var col = document.createElement("col");
  4994. col.style.width = firstRow.cells[i].offsetWidth + "px";
  4995. cg.appendChild(col);
  4996. }
  4997. table.insertBefore(cg, table.firstChild);
  4998. table.style.tableLayout = "fixed";
  4999. table.style.width = table.offsetWidth + "px";
  5000. }
  5001. return cg;
  5002. }
  5003. function onTblPointerMove(e) {
  5004. if (tblDrag) {
  5005. var z = zoomFactor();
  5006. if (tblDrag.type === "col") {
  5007. var dx = (e.clientX - tblDrag.startX) / z;
  5008. var cols = tblDrag.cg.children;
  5009. var i = tblDrag.idx;
  5010. if (i < cols.length - 1) {
  5011. // inner border: this column grows, the neighbour shrinks
  5012. var wA = Math.max(24, tblDrag.wA + dx);
  5013. var give = wA - tblDrag.wA;
  5014. var wB = Math.max(24, tblDrag.wB - give);
  5015. cols[i].style.width = Math.round(tblDrag.wA + tblDrag.wB - wB) + "px";
  5016. cols[i + 1].style.width = Math.round(wB) + "px";
  5017. } else {
  5018. // outer border: the whole table grows/shrinks
  5019. var w = Math.max(24, tblDrag.wA + dx);
  5020. cols[i].style.width = Math.round(w) + "px";
  5021. tblDrag.table.style.width = Math.round(tblDrag.tw + (w - tblDrag.wA)) + "px";
  5022. }
  5023. } else {
  5024. var dy = (e.clientY - tblDrag.startY) / z;
  5025. tblDrag.row.style.height = Math.max(18, Math.round(tblDrag.h + dy)) + "px";
  5026. }
  5027. e.preventDefault();
  5028. return;
  5029. }
  5030. var hit = tableBorderHit(e);
  5031. editor.style.cursor = hit ? (hit.type === "col" ? "col-resize" : "row-resize") : "";
  5032. }
  5033. function onTblPointerDown(e) {
  5034. var hit = tableBorderHit(e);
  5035. if (!hit) return;
  5036. var table = hit.cell.closest("table");
  5037. if (!table) return;
  5038. e.preventDefault(); // keep the caret where it is
  5039. if (hit.type === "col") {
  5040. var cg = ensureColgroup(table);
  5041. if (!cg) return;
  5042. var idx = cellColIndex(hit.cell);
  5043. if (idx >= cg.children.length) idx = cg.children.length - 1;
  5044. tblDrag = {
  5045. type: "col", table: table, cg: cg, idx: idx,
  5046. startX: e.clientX,
  5047. wA: parseFloat(cg.children[idx].style.width) || hit.cell.offsetWidth,
  5048. wB: (idx < cg.children.length - 1)
  5049. ? (parseFloat(cg.children[idx + 1].style.width) || 0)
  5050. : 0,
  5051. tw: table.offsetWidth
  5052. };
  5053. } else {
  5054. var row = hit.cell.parentElement;
  5055. tblDrag = { type: "row", row: row, startY: e.clientY, h: row.offsetHeight };
  5056. }
  5057. document.addEventListener("pointermove", onTblPointerMove);
  5058. document.addEventListener("pointerup", onTblPointerUp);
  5059. document.body.style.userSelect = "none";
  5060. }
  5061. function onTblPointerUp() {
  5062. document.removeEventListener("pointermove", onTblPointerMove);
  5063. document.removeEventListener("pointerup", onTblPointerUp);
  5064. document.body.style.userSelect = "";
  5065. if (tblDrag) {
  5066. tblDrag = null;
  5067. afterEdit(true);
  5068. }
  5069. }
  5070. function initTableResize() {
  5071. editor.addEventListener("pointermove", onTblPointerMove);
  5072. editor.addEventListener("pointerdown", onTblPointerDown);
  5073. }
  5074. /* ================= editor events ================= */
  5075. // keys that change the text: Backspace/Delete at the caret, and anything
  5076. // typed, cut or pasted over a selection
  5077. function editsAcrossPages(e) {
  5078. if (e.key === "Backspace" || e.key === "Delete") return true;
  5079. var sel = window.getSelection();
  5080. if (!sel || !sel.rangeCount || sel.getRangeAt(0).collapsed) return false;
  5081. if (e.key === "Enter" || e.key === "Tab") return true;
  5082. if ((e.ctrlKey || e.metaKey) && !e.altKey) return /^[xv]$/i.test(e.key);
  5083. return e.key.length === 1;
  5084. }
  5085. function bindEditorEvents() {
  5086. editor.addEventListener("input", function () {
  5087. noteEditAtCaret();
  5088. OfficeApp.markDirty();
  5089. scheduleCounts();
  5090. undo.pushDebounced(snapshot, 600);
  5091. });
  5092. editor.addEventListener("paste", handleEditorPaste);
  5093. document.addEventListener("copy", function (e) { handleImageCopyCut(e, false); });
  5094. document.addEventListener("cut", function (e) { handleImageCopyCut(e, true); });
  5095. // track changes: intercept typing/deleting while suggesting
  5096. editor.addEventListener("beforeinput", onEditorBeforeInput);
  5097. editor.addEventListener("click", function (e) {
  5098. var t = e.target;
  5099. // checklist checkbox toggle (click lands in the ::before gutter)
  5100. if (t.tagName === "LI" && t.parentElement &&
  5101. t.parentElement.classList.contains("of-checklist")) {
  5102. var r = t.getBoundingClientRect();
  5103. if (e.clientX < r.left) {
  5104. t.classList.toggle("checked");
  5105. afterEdit(true);
  5106. e.preventDefault();
  5107. return;
  5108. }
  5109. }
  5110. if (t.tagName === "IMG") {
  5111. selectImage(t);
  5112. e.preventDefault();
  5113. return;
  5114. }
  5115. if (selectedImg) deselectImage();
  5116. var cmtHit = t.closest ? t.closest("span.doc-cmt") : null;
  5117. if (cmtHit && editor.contains(cmtHit)) {
  5118. showCommentsPanel(true);
  5119. renderCommentsPanel(cmtHit.getAttribute("data-cid"));
  5120. }
  5121. var tocLine = (e.ctrlKey || e.metaKey) && t.closest ? t.closest("p.doc-toc") : null;
  5122. if (tocLine && editor.contains(tocLine) && followTocEntry(tocLine)) {
  5123. e.preventDefault();
  5124. return;
  5125. }
  5126. var a = t.closest ? t.closest("a") : null;
  5127. if (a && editor.contains(a)) {
  5128. e.preventDefault();
  5129. if (e.ctrlKey || e.metaKey) {
  5130. try { window.open(a.href, "_blank", "noopener"); } catch (err) { }
  5131. } else {
  5132. OfficeApp.setStatus("Ctrl+Click to open link: " + (a.getAttribute("href") || ""), "info", 4000);
  5133. }
  5134. }
  5135. });
  5136. pageEl.addEventListener("mousemove", trackTocHover);
  5137. pageEl.addEventListener("mouseleave", function () { if (tocHover) leaveTocHover(); });
  5138. editor.addEventListener("dblclick", function (e) {
  5139. if (e.target.tagName === "IMG") {
  5140. selectImage(e.target);
  5141. imageSizeDialog(e.target);
  5142. }
  5143. });
  5144. editor.addEventListener("keydown", function (e) {
  5145. // a page boundary in the way of the edit is taken out first, so
  5146. // the key acts on the text on both sides of it
  5147. if (!selectedImg && !e.isComposing && editsAcrossPages(e)) {
  5148. if (DocsLayout.unsplitAtCaret(editor, e.key !== "Delete")) noteEditAtCaret();
  5149. }
  5150. if ((e.key === "Delete" || e.key === "Backspace") && selectedImg) {
  5151. e.preventDefault();
  5152. var img = selectedImg;
  5153. deselectImage();
  5154. if (img.parentNode) img.parentNode.removeChild(img);
  5155. afterEdit(true);
  5156. return;
  5157. }
  5158. if (e.key === "Tab") {
  5159. e.preventDefault();
  5160. try { document.execCommand(e.shiftKey ? "outdent" : "indent"); } catch (err) { }
  5161. afterEdit(false);
  5162. }
  5163. });
  5164. // editor context menu: table ops + multi-column region control
  5165. editor.addEventListener("contextmenu", function (e) {
  5166. var items = [];
  5167. if (e.target.tagName === "IMG" && editor.contains(e.target)) {
  5168. if (selectedImg !== e.target) selectImage(e.target);
  5169. items = items.concat(pictureMenuItems(e.target));
  5170. items.push({ sep: true });
  5171. }
  5172. // review: accept/reject the suggestion under the pointer
  5173. var sug = e.target.closest ? e.target.closest("ins.doc-ins, del.doc-del") : null;
  5174. if (sug && editor.contains(sug)) {
  5175. var what = sug.tagName === "INS" ? "insertion" : "deletion";
  5176. items.push({
  5177. label: "Accept " + what, icon: "check",
  5178. action: function () { resolveSuggestion(sug, true); }
  5179. });
  5180. items.push({
  5181. label: "Reject " + what, icon: "times",
  5182. action: function () { resolveSuggestion(sug, false); }
  5183. });
  5184. items.push({ sep: true });
  5185. }
  5186. // review: comment actions
  5187. var cmtEl = e.target.closest ? e.target.closest("span.doc-cmt") : null;
  5188. if (cmtEl && editor.contains(cmtEl)) {
  5189. var cm = commentById(cmtEl.getAttribute("data-cid"));
  5190. if (cm) {
  5191. items.push({
  5192. label: "View comment", icon: "comment outline",
  5193. action: function () {
  5194. showCommentsPanel(true);
  5195. renderCommentsPanel(cm.id);
  5196. }
  5197. });
  5198. items.push({
  5199. label: "Resolve comment", icon: "check",
  5200. action: function () { resolveComment(cm.id, false); }
  5201. });
  5202. items.push({ sep: true });
  5203. }
  5204. } else {
  5205. var selNow = window.getSelection();
  5206. if (selNow && selNow.rangeCount && !selNow.getRangeAt(0).collapsed &&
  5207. editor.contains(selNow.getRangeAt(0).commonAncestorContainer)) {
  5208. items.push({
  5209. label: "Comment...", icon: "comment outline", key: "Ctrl+Alt+M",
  5210. action: function () { commentDialog(null); }
  5211. });
  5212. items.push({ sep: true });
  5213. }
  5214. }
  5215. var cell = e.target.closest ? e.target.closest("td,th") : null;
  5216. if (cell && cell.closest("table.of-table") && editor.contains(cell)) {
  5217. items.push({ label: "Table", icon: "table", sub: tableMenuItemsFor(cell) });
  5218. items.push({ sep: true });
  5219. }
  5220. if (pageConf.columns > 1) {
  5221. // let the user pick which region spans the full page width
  5222. var block = e.target.closest ? e.target.closest(BLOCK_SEL) : null;
  5223. if (block && editor.contains(block)) {
  5224. items.push({
  5225. label: "Full width (span all columns)", icon: "columns",
  5226. checked: function () { return block.classList.contains("col-span-all"); },
  5227. action: function () {
  5228. block.classList.toggle("col-span-all");
  5229. afterEdit(true);
  5230. }
  5231. });
  5232. items.push({
  5233. label: "Show layout boxes",
  5234. checked: function () { return document.body.classList.contains("doc-show-boxes"); },
  5235. action: toggleLayoutBoxes
  5236. });
  5237. items.push({ sep: true });
  5238. }
  5239. }
  5240. // standard edit block (like Google Docs / Word)
  5241. var selNow2 = window.getSelection();
  5242. var canCopy = !!selectedImg || !!(selNow2 && selNow2.rangeCount &&
  5243. !selNow2.getRangeAt(0).collapsed &&
  5244. editor.contains(selNow2.getRangeAt(0).commonAncestorContainer));
  5245. var copyOk = function () { return canCopy; };
  5246. items.push({ label: "Cut", icon: "cut", key: "Ctrl+X", enabled: copyOk, action: function () { menuCutCopy(true); } });
  5247. items.push({ label: "Copy", icon: "copy", key: "Ctrl+C", enabled: copyOk, action: function () { menuCutCopy(false); } });
  5248. items.push({ label: "Paste", icon: "paste", key: "Ctrl+V", action: function () { pasteFromMenu(false); } });
  5249. items.push({ label: "Paste without formatting", icon: "clipboard outline", action: function () { pasteFromMenu(true); } });
  5250. items.push({ sep: true });
  5251. items.push({ label: "Bold", icon: "bold", key: "Ctrl+B", action: function () { exec("bold"); } });
  5252. items.push({ label: "Italic", icon: "italic", key: "Ctrl+I", action: function () { exec("italic"); } });
  5253. items.push({ label: "Underline", icon: "underline", key: "Ctrl+U", action: function () { exec("underline"); } });
  5254. items.push({ label: "Clear formatting", icon: "eraser", action: clearFormatting });
  5255. items.push({ sep: true });
  5256. // on a link the link entry takes it off instead of adding one
  5257. var linkHit = e.target.closest ? e.target.closest("a[href]") : null;
  5258. if (linkHit && editor.contains(linkHit)) {
  5259. items.push({ label: "Remove link", icon: "unlinkify", action: function () { removeLink(linkHit); } });
  5260. } else {
  5261. items.push({ label: "Insert link...", icon: "linkify", key: "Ctrl+K", action: linkDialog });
  5262. }
  5263. items.push({ label: "Insert page break", icon: "file outline", key: "Ctrl+Enter", action: insertPageBreak });
  5264. items.push({ sep: true });
  5265. items.push({ label: "Select all", icon: "i cursor", key: "Ctrl+A", action: selectAll });
  5266. e.preventDefault();
  5267. OfficeApp.showContextMenu(e.clientX, e.clientY, items);
  5268. });
  5269. // deselect image when clicking anywhere else / typing starts elsewhere;
  5270. // app chrome (ribbon, menus, dialogs, popups) keeps it selected, or
  5271. // the Picture Format tab would vanish under the click that opens it
  5272. document.addEventListener("mousedown", function (e) {
  5273. if (selectedImg && e.target !== selectedImg && e.target !== imgHandle &&
  5274. !$(e.target).closest(".of-ribbon, .of-rb-tab, .of-rb-popup, .of-rb-gpop, " +
  5275. ".of-menubar, .of-context-menu, .of-float-menu, .of-cp-panel, .of-dialog-overlay").length) {
  5276. deselectImage();
  5277. }
  5278. });
  5279. workspaceEl.addEventListener("scroll", positionImgHandle);
  5280. window.addEventListener("resize", positionImgHandle);
  5281. // header / footer: plain single-line text only, kept in sync across
  5282. // every page's copy (bindHfEvents also runs for the copies)
  5283. bindHfEvents(headerEl);
  5284. bindHfEvents(footerEl);
  5285. // re-paginate when the flow grows on its own (pictures decoding after
  5286. // a document is opened, web fonts, a resize)
  5287. watchContentSize();
  5288. }
  5289. /* ================= shortcuts ================= */
  5290. function bindShortcuts() {
  5291. OfficeApp.registerShortcut("Ctrl+B", function () { exec("bold"); }, { description: "Bold", group: "Text" });
  5292. OfficeApp.registerShortcut("Ctrl+I", function () { exec("italic"); }, { description: "Italic", group: "Text" });
  5293. OfficeApp.registerShortcut("Ctrl+U", function () { exec("underline"); }, { description: "Underline", group: "Text" });
  5294. OfficeApp.registerShortcut("Ctrl+Shift+X", function () { exec("strikeThrough"); }, { description: "Strikethrough", group: "Text" });
  5295. OfficeApp.registerShortcut("Ctrl+K", linkDialog, { description: "Insert link", group: "Text" });
  5296. OfficeApp.registerShortcut("Ctrl+Alt+M", function () { commentDialog(null); },
  5297. { description: "Add comment", group: "Review" });
  5298. OfficeApp.registerShortcut("Ctrl+Enter", insertPageBreak,
  5299. { description: "Insert page break", group: "Text" });
  5300. OfficeApp.registerShortcut("Ctrl+F", function () { openFind(false); }, { description: "Find" });
  5301. OfficeApp.registerShortcut("Ctrl+]", function () { stepFontSize(1); }, { description: "Increase font size", group: "Text" });
  5302. OfficeApp.registerShortcut("Ctrl+[", function () { stepFontSize(-1); }, { description: "Decrease font size", group: "Text" });
  5303. OfficeApp.registerShortcut("Ctrl+,", function () { exec("subscript"); }, { description: "Subscript", group: "Text" });
  5304. OfficeApp.registerShortcut("Ctrl+.", function () { exec("superscript"); }, { description: "Superscript", group: "Text" });
  5305. OfficeApp.registerShortcut("Ctrl+Alt+F", insertFootnote, { description: "Insert footnote", group: "Text" });
  5306. // Escape puts the format painter down (and falls through)
  5307. OfficeHotkeys.register("Escape", function () {
  5308. if (painter) stopPainter();
  5309. return false;
  5310. }, { id: "docs.painteresc", allowInInput: true });
  5311. OfficeApp.registerShortcut("Ctrl+H", function () { openFind(true); }, { description: "Find and replace" });
  5312. // lists - register both the digit and the shifted symbol (layout dependent)
  5313. OfficeApp.registerShortcut("Ctrl+Shift+7", function () { exec("insertOrderedList"); });
  5314. OfficeApp.registerShortcut("Ctrl+Shift+&", function () { exec("insertOrderedList"); });
  5315. OfficeApp.registerShortcut("Ctrl+Shift+8", function () { exec("insertUnorderedList"); });
  5316. OfficeApp.registerShortcut("Ctrl+Shift+*", function () { exec("insertUnorderedList"); });
  5317. }
  5318. /* ================= boot ================= */
  5319. /* the few entry points other scripts (and automated checks) use - the
  5320. counterpart of SlidesApp */
  5321. window.DocsApp = {
  5322. currentBody: function () { return currentBody(); },
  5323. loadBody: function (b) { loadBody(b); },
  5324. renderPdf: renderPdf,
  5325. pages: function () { return lastPages.slice(); }
  5326. };
  5327. $(document).ready(function () {
  5328. editor = document.getElementById("editor");
  5329. headerEl = document.getElementById("docHeader");
  5330. footerEl = document.getElementById("docFooter");
  5331. pageEl = document.getElementById("page");
  5332. workspaceEl = document.getElementById("workspace");
  5333. undo = new OfficeUndoStack({
  5334. limit: 100,
  5335. apply: function (s) { applySnapshot(s); }
  5336. });
  5337. buildToolbar();
  5338. trackSelection();
  5339. bindEditorEvents();
  5340. bindFindPanel();
  5341. try { document.execCommand("styleWithCSS", false, true); } catch (e) { }
  5342. try { document.execCommand("defaultParagraphSeparator", false, "p"); } catch (e) { }
  5343. OfficeApp.init({
  5344. appName: "Docs",
  5345. appType: "document",
  5346. appIcon: "../img/docs.svg",
  5347. extension: ".docx",
  5348. nativeLabel: "Word document (.docx)",
  5349. fileTypeName: "Document",
  5350. defaultFileName: "New Document",
  5351. // pictures Word cannot hold get a PNG beside them before a save
  5352. prepareNative: prepareNative,
  5353. serialize: function () { return currentBody(); },
  5354. deserialize: function (body) {
  5355. loadBody(body);
  5356. undo.reset(snapshot());
  5357. },
  5358. create: function () {
  5359. pageConf = defaultPageConf();
  5360. loadBody({ html: "<p><br></p>", page: pageConf, header: "", footer: "", pageNumbers: false });
  5361. undo.reset(snapshot());
  5362. },
  5363. importers: {
  5364. ".txt": function (text) { importTxt(text); },
  5365. ".md": function (text) { importMd(text); },
  5366. ".html": function (text) { importHtml(text); },
  5367. ".htm": function (text) { importHtml(text); }
  5368. },
  5369. // Word 97-2003 documents open by conversion (mod/office/doc),
  5370. // as imports: Save writes the app's own format
  5371. legacyExtensions: [".doc", ".dot"],
  5372. binaryImporters: {
  5373. ".odt": importOdt
  5374. },
  5375. saveFormats: SAVE_FORMATS,
  5376. onUndo: doUndo,
  5377. onRedo: doRedo,
  5378. canUndo: function () { return undo.canUndo(); },
  5379. canRedo: function () { return undo.canRedo(); },
  5380. // Edit menubar clipboard shares the context-menu implementations
  5381. // (image-aware copy, async rich paste)
  5382. // the ribbon (buildToolbar) carries Insert, Format and View; File
  5383. // and Edit stay menus
  5384. ribbon: true,
  5385. editMenuExtras: [
  5386. { label: "Paste without formatting", icon: "file alternate outline", key: "Ctrl+Shift+V", action: function () { pasteFromMenu(true); } },
  5387. { sep: true },
  5388. { label: "Select all", icon: "i cursor", key: "Ctrl+A", action: selectAll },
  5389. {
  5390. label: "Format painter", icon: "paint brush",
  5391. action: function () { startPainter(false); }
  5392. },
  5393. { sep: true },
  5394. { label: "Find...", icon: "search", key: "Ctrl+F", action: function () { openFind(false); } },
  5395. { label: "Find and replace...", icon: "exchange", key: "Ctrl+H", action: function () { openFind(true); } }
  5396. ],
  5397. onCut: function () { menuCutCopy(true); },
  5398. onCopy: function () { menuCutCopy(false); },
  5399. onPaste: function () { pasteFromMenu(false); },
  5400. /*
  5401. .odt needs the Office converters - the AGI backend in ArozOS,
  5402. the WebAssembly module in the web edition. .docx is the
  5403. document's own format (File > Save / Save as). .pdf, .html,
  5404. .md and .txt are rendered right here and are always
  5405. available.
  5406. */
  5407. fileMenuExtras: [
  5408. { label: "Page setup...", icon: "file alternate outline", action: pageSetupDialog },
  5409. {
  5410. label: "Export", icon: "external alternate",
  5411. sub: function () {
  5412. var items = [];
  5413. if (OfficePlatform.canConvert()) {
  5414. items.push({ label: "OpenDocument (.odt)", icon: "file alternate outline", action: exportOdt });
  5415. }
  5416. items.push({ label: "PDF document (.pdf)", icon: "file pdf outline", action: exportPdf });
  5417. items.push({ label: "Web page (.html)", icon: "file code outline", action: exportHTML });
  5418. items.push({ label: "Markdown (.md)", icon: "file alternate outline", action: exportMarkdown });
  5419. items.push({ label: "Plain text (.txt)", icon: "file outline", action: exportText });
  5420. return items;
  5421. }
  5422. }
  5423. ],
  5424. zoomTarget: "#page",
  5425. onZoomChanged: function () { positionImgHandle(); },
  5426. onBeforePrint: function () {
  5427. closeFind();
  5428. deselectImage();
  5429. OfficeApp.closeAllMenus();
  5430. },
  5431. onBeforeSave: function () {
  5432. clearFindHits();
  5433. deselectImage();
  5434. }
  5435. });
  5436. bindShortcuts();
  5437. initSelectionBar();
  5438. initTableResize();
  5439. buildCommentsPanel();
  5440. OfficeApp.addStatusItem("suggest", "");
  5441. OfficeApp.addStatusItem("pg", "Page 1 of 1");
  5442. OfficeApp.addStatusItem("wc", "0 words · 0 characters");
  5443. document.addEventListener("selectionchange", function () {
  5444. var sel = window.getSelection();
  5445. if (sel && sel.anchorNode && pageEl.contains(sel.anchorNode)) schedulePageIndicator("caret");
  5446. });
  5447. workspaceEl.addEventListener("scroll", function () { schedulePageIndicator("scroll"); }, { passive: true });
  5448. if (OfficeApp.getSetting("cmtPanel", false)) showCommentsPanel(true);
  5449. updateSuggestStatus();
  5450. if (OfficeApp.getSetting("layoutBoxes", false)) {
  5451. document.body.classList.add("doc-show-boxes");
  5452. }
  5453. if (OfficeApp.getSetting("marks", false)) document.body.classList.add("doc-show-marks");
  5454. // the format painter lays its format on the selection a drag ends
  5455. editor.addEventListener("mouseup", function () {
  5456. if (painter) setTimeout(applyPainter, 0);
  5457. });
  5458. // a phone shows the page fitted to its width (not saved as the zoom);
  5459. // a narrow desktop window (the float window opens small) keeps 100%
  5460. var onPhone = Math.min(window.screen.width || 9999, window.screen.height || 9999) < 768 &&
  5461. !!(window.matchMedia && window.matchMedia("(pointer: coarse)").matches);
  5462. var fitNarrow = function () {
  5463. if (onPhone && OfficeRibbon.isNarrow()) fitPageWidth(true);
  5464. };
  5465. setTimeout(fitNarrow, 60);
  5466. var fitTimer = null;
  5467. $(window).on("resize", function () {
  5468. clearTimeout(fitTimer);
  5469. fitTimer = setTimeout(fitNarrow, 150);
  5470. });
  5471. editor.spellcheck = OfficeApp.getSetting("spellcheck", true);
  5472. updateCounts();
  5473. editor.focus();
  5474. });
  5475. })();