| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571 |
- /*
- ArozOS Office - Docs (word processor)
- =====================================
- Requires (loaded by index.html): jquery, ao_module, ../common/office.js,
- ../common/lib/marked.min.js (Markdown import).
- Envelope "body" schema (what serialize() returns / deserialize() accepts):
- {
- html: "<sanitized editor innerHTML>", // rich text content
- page: {
- size: "A4" | "Letter" | "Legal",
- orientation: "portrait" | "landscape",
- margins: { top: 20, right: 20, bottom: 20, left: 20 } // millimetres
- },
- header: "plain text repeated in every page's top margin",
- footer: "plain text repeated in every page's bottom margin",
- hfMode: "all" | "except-first" | "none", // which pages show them
- pageNumbers: false, // print page numbers (best-effort @page margin box)
- comments: [ { id, text, at, resolved } ], // review comments; anchored
- // in html as <span class="doc-cmt" data-cid>
- trackChanges: false // "suggest edits" mode; pending suggestions
- // live in html as ins.doc-ins / del.doc-del
- }
- Notes:
- - html is produced by cleanedHtml(): find/replace highlight spans and
- image-selection classes are stripped before serialisation.
- - Known allowed classes inside html: doc-title (title paragraph),
- of-checklist (on UL), checked (on LI), of-table (on TABLE),
- doc-cmt (comment anchor), doc-ins / doc-del (tracked changes),
- doc-pagebreak (explicit page break block; exports as a real
- <w:br w:type="page"/> and is sized on screen by layoutPageBreaks).
- - The .docx keeps comments and suggestions as Word comments and
- tracked changes (mod/office docx/review.go). Foreign exports
- (odt/html/md/txt) use resolvedHtml(): suggestions applied as if
- accepted, comment anchors unwrapped.
- */
- (function () {
- "use strict";
- /* ================= constants ================= */
- var PAGE_SIZES = {
- "A4": { w: 210, h: 297 },
- "Letter": { w: 215.9, h: 279.4 },
- "Legal": { w: 215.9, h: 355.6 }
- };
- // OfficeFonts (common/fonts.js) owns the list so that the families the
- // suite ships with itself are on it - see the note there
- var FONTS = OfficeFonts.MENU;
- var FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
- var LINE_SPACINGS = ["1", "1.15", "1.5", "2"];
- // which pages carry the header / footer text
- var HF_MODES = ["all", "except-first", "none"];
- var PARA_STYLES = [
- { v: "p", label: "Normal text" },
- { v: "title", label: "Title" },
- { v: "h1", label: "Heading 1" },
- { v: "h2", label: "Heading 2" },
- { v: "h3", label: "Heading 3" },
- { v: "h4", label: "Heading 4" }
- ];
- // (a column section and a page spacer are layout, not blocks of the text)
- var BLOCK_SEL = "p,h1,h2,h3,h4,h5,h6,li,blockquote,pre,div:not(.doc-colsec):not(.doc-autobreak)";
- /* Special characters palette - every glyph is generated at runtime from
- code points (never a literal emoji in this source file). */
- var CHAR_TABS = [
- { name: "Smileys", cps: [
- 0x1F600, 0x1F601, 0x1F602, 0x1F603, 0x1F604, 0x1F605, 0x1F606, 0x1F607,
- 0x1F609, 0x1F60A, 0x1F60B, 0x1F60D, 0x1F60E, 0x1F60F, 0x1F610, 0x1F612,
- 0x1F614, 0x1F618, 0x1F61C, 0x1F621, 0x1F622, 0x1F625, 0x1F62D, 0x1F631,
- 0x1F634, 0x1F637, 0x1F642, 0x1F643, 0x1F644, 0x1F914, 0x1F917, 0x1F929,
- 0x1F970, 0x1F973, 0x1F44D, 0x1F44E, 0x1F44F, 0x1F64F, 0x1F4AA, 0x1F389] },
- { name: "Objects", cps: [
- 0x1F4C1, 0x1F4C2, 0x1F4C4, 0x1F4C5, 0x1F4C8, 0x1F4C9, 0x1F4CA, 0x1F4CB,
- 0x1F4CC, 0x1F4CD, 0x1F4CE, 0x1F4DD, 0x1F4E6, 0x1F4E7, 0x1F4F1, 0x1F4BB,
- 0x1F4BE, 0x1F4BC, 0x1F50D, 0x1F511, 0x1F512, 0x1F513, 0x1F514, 0x1F4A1,
- 0x1F527, 0x1F528, 0x2699, 0x23F0, 0x1F3C6, 0x2B50, 0x2764, 0x2705,
- 0x274C, 0x26A0, 0x2B55, 0x1F6A9] },
- { name: "Arrows", cps: [
- 0x2190, 0x2191, 0x2192, 0x2193, 0x2194, 0x2195, 0x2196, 0x2197,
- 0x2198, 0x2199, 0x21A9, 0x21AA, 0x21B5, 0x21C4, 0x21C6, 0x21D0,
- 0x21D1, 0x21D2, 0x21D3, 0x21D4, 0x2794, 0x27A1, 0x2B05, 0x2B06,
- 0x2B07, 0x2B95, 0x21E7, 0x21E9] },
- { name: "Math", cps: [
- 0x00B1, 0x00D7, 0x00F7, 0x2212, 0x2260, 0x2264, 0x2265, 0x2248,
- 0x221E, 0x2211, 0x220F, 0x221A, 0x222B, 0x2202, 0x2206, 0x2207,
- 0x03C0, 0x03B1, 0x03B2, 0x03B3, 0x03B8, 0x03BB, 0x03BC, 0x03C3,
- 0x03C6, 0x03A9, 0x2208, 0x2209, 0x2229, 0x222A, 0x2282, 0x2283,
- 0x2200, 0x2203, 0x00B0, 0x00B2, 0x00B3, 0x00BD, 0x00BC, 0x00BE,
- 0x2032, 0x2033] },
- { name: "Symbols", cps: [
- 0x00A9, 0x00AE, 0x2122, 0x00A7, 0x00B6, 0x2020, 0x2021, 0x2022,
- 0x2026, 0x2030, 0x20AC, 0x00A3, 0x00A5, 0x00A2, 0x00A1, 0x00BF,
- 0x00AB, 0x00BB, 0x2018, 0x2019, 0x201C, 0x201D, 0x2013, 0x2014,
- 0x2713, 0x2717, 0x2605, 0x2606, 0x25CF, 0x25CB, 0x25A0, 0x25A1,
- 0x2660, 0x2663, 0x2665, 0x2666, 0x266A, 0x266B] }
- ];
- /* ================= state ================= */
- var editor, headerEl, footerEl, pageEl, workspaceEl;
- var savedRange = null; // last selection range inside the editor
- var selectedImg = null; // currently selected <img>
- var imgHandle = null; // floating resize handle element
- var pageConf = defaultPageConf();
- var undo = null;
- var countTimer = null;
- var stateTimer = null;
- var $fontSel, $sizeSel, $styleSel;
- var findState = { hits: [], cur: -1 };
- var hfClones = []; // header/footer copies for pages 2..n
- var hfContent = { header: "", footer: "" }; // header/footer HTML
- var footnotes = {}; // footnote id -> HTML (body.footnotes)
- var comments = []; // review comments [{id,text,at,resolved}]
- var suggesting = false; // track-changes ("suggest edits") mode
- function defaultPageConf() {
- return {
- size: "A4",
- orientation: "portrait",
- margins: { top: 20, right: 20, bottom: 20, left: 20 },
- headerDist: 12.7, // header distance from the top edge, mm
- footerDist: 12.7, // footer distance from the bottom edge, mm
- lineSpacing: 1.15, // multiple of single spacing for paragraphs
- // that do not state their own (data-ls)
- pageNumbers: false,
- hfMode: "all", // header/footer on: all | except-first | none
- columns: 1, // 1-3 text columns (2 = IEEE-style)
- colGap: 8 // gap between columns, mm
- };
- }
- function num(v, def) {
- var n = parseFloat(v);
- return isNaN(n) ? def : n;
- }
- function esc(t) { return OfficeApp.escapeHtml(t); }
- /* ================= selection helpers ================= */
- function trackSelection() {
- document.addEventListener("selectionchange", function () {
- var sel = window.getSelection();
- if (sel && sel.rangeCount > 0) {
- var r = sel.getRangeAt(0);
- if (editor.contains(r.commonAncestorContainer)) {
- savedRange = r.cloneRange();
- scheduleToolbarState();
- scheduleTocOverlay();
- } else if (tocOverlay && tocOverlay.style.display !== "none") {
- scheduleTocOverlay();
- }
- }
- });
- }
- function restoreSel() {
- editor.focus();
- if (savedRange) {
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(savedRange);
- }
- }
- function placeCaretAtEnd() {
- try {
- var r = document.createRange();
- r.selectNodeContents(editor);
- r.collapse(false);
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(r);
- savedRange = r.cloneRange();
- } catch (e) { }
- }
- function inHeaderFooter() {
- var ae = document.activeElement;
- return !!(ae && ae.classList && ae.classList.contains("doc-hf"));
- }
- function getSelectedBlocks() {
- var out = [];
- var range = null;
- var sel = window.getSelection();
- if (sel && sel.rangeCount > 0 && editor.contains(sel.getRangeAt(0).commonAncestorContainer)) {
- range = sel.getRangeAt(0);
- } else {
- range = savedRange;
- }
- if (!range) return out;
- if (range.collapsed) {
- var n = range.startContainer;
- while (n && n !== editor) {
- if (n.nodeType === 1 && n.matches && n.matches(BLOCK_SEL)) { out.push(n); break; }
- n = n.parentNode;
- }
- return out;
- }
- var cand = editor.querySelectorAll(BLOCK_SEL);
- for (var i = 0; i < cand.length; i++) {
- try { if (range.intersectsNode(cand[i])) out.push(cand[i]); } catch (e) { }
- }
- // keep only the deepest blocks (drop ancestors of other selected blocks)
- return out.filter(function (b) {
- for (var j = 0; j < out.length; j++) {
- if (out[j] !== b && b.contains(out[j])) return false;
- }
- return true;
- });
- }
- /* ================= sanitizer ================= */
- function sanitizeHtml(html, opts) {
- opts = opts || {};
- var doc;
- try {
- doc = new DOMParser().parseFromString(String(html || ""), "text/html");
- } catch (e) { return ""; }
- var root = doc.body;
- var bad = root.querySelectorAll(
- "script,style,link,meta,base,iframe,frame,frameset,object,embed,applet,form,noscript,title,svg foreignObject");
- var i;
- for (i = bad.length - 1; i >= 0; i--) {
- if (bad[i].parentNode) bad[i].parentNode.removeChild(bad[i]);
- }
- // layout-only pieces copied out of a paginated document
- var layout = root.querySelectorAll(".doc-autobreak");
- for (i = layout.length - 1; i >= 0; i--) {
- if (layout[i].parentNode) layout[i].parentNode.removeChild(layout[i]);
- }
- var all = root.querySelectorAll("*");
- for (i = 0; i < all.length; i++) {
- var el = all[i];
- el.removeAttribute("data-split");
- el.removeAttribute("data-split-of");
- el.removeAttribute("data-pair");
- // the PNG a save rendered for the writers, not part of the text
- el.removeAttribute("data-export-src");
- el.classList.remove("doc-split-head", "doc-split-tail");
- for (var a = el.attributes.length - 1; a >= 0; a--) {
- var at = el.attributes[a];
- var n = at.name.toLowerCase();
- if (n.indexOf("on") === 0) {
- el.removeAttribute(at.name);
- } else if ((n === "href" || n === "src" || n === "xlink:href" || n === "action" || n === "formaction") &&
- /^\s*(javascript|vbscript|data\s*:\s*text\/html)/i.test(at.value)) {
- el.removeAttribute(at.name);
- } else if (!opts.keepClasses && (n === "class" || n === "id")) {
- el.removeAttribute(at.name);
- }
- }
- }
- return root.innerHTML;
- }
- /* ================= serialize / deserialize ================= */
- /* Everything the layout engine computes (px line heights, tab widths,
- list markers, spacer elements) is derived from the document and made
- again on load - it is never saved. */
- function stripLayoutArtifacts(root) {
- removeAutoBreaks(root);
- DocsLayout.restoreTablePadding(root);
- DocsLayout.restorePictureLines(root);
- var styled = root.querySelectorAll("[style]");
- for (var i = 0; i < styled.length; i++) {
- var el = styled[i];
- el.style.lineHeight = "";
- if (el.classList.contains("doc-tab")) {
- el.style.width = "";
- el.style.display = "";
- }
- if (el.classList.contains("doc-pagebreak")) el.style.height = "";
- if (!el.getAttribute("style")) el.removeAttribute("style");
- }
- var marked = root.querySelectorAll("[data-marker],[data-n],[data-leader]");
- for (i = 0; i < marked.length; i++) {
- marked[i].removeAttribute("data-marker");
- marked[i].removeAttribute("data-n");
- marked[i].removeAttribute("data-leader");
- }
- }
- function cleanedHtml() {
- var clone = editor.cloneNode(true);
- // strip layout-only spacers and computed layout values
- stripLayoutArtifacts(clone);
- // strip find highlight spans
- var hits = clone.querySelectorAll("span.of-find-hit");
- for (var i = 0; i < hits.length; i++) {
- var s = hits[i];
- while (s.firstChild) s.parentNode.insertBefore(s.firstChild, s);
- s.parentNode.removeChild(s);
- }
- // strip image selection marker
- var imgs = clone.querySelectorAll("img.of-selimg");
- for (i = 0; i < imgs.length; i++) {
- imgs[i].classList.remove("of-selimg");
- if (!imgs[i].getAttribute("class")) imgs[i].removeAttribute("class");
- }
- // after every style change above: Firefox would drop it again
- imgs = clone.querySelectorAll("img[data-crop]");
- for (i = 0; i < imgs.length; i++) canonicalCrop(imgs[i]);
- clone.normalize();
- return clone.innerHTML;
- }
- function hfText(html) {
- var div = document.createElement("div");
- div.innerHTML = html || "";
- var f = div.querySelectorAll(".doc-field");
- for (var i = 0; i < f.length; i++) f[i].parentNode.removeChild(f[i]);
- return (div.textContent || "").replace(/\s+/g, " ").trim();
- }
- // header/footer HTML worth saving as rich content: anything beyond a
- // single run of plain text
- function hfIsRich(html) {
- return /<(p|div|h\d|img|span|b|i|u|table|ul|ol|br)\b/i.test(html || "");
- }
- function currentBody() {
- return {
- html: cleanedHtml(),
- page: {
- size: pageConf.size,
- orientation: pageConf.orientation,
- margins: {
- top: pageConf.margins.top, right: pageConf.margins.right,
- bottom: pageConf.margins.bottom, left: pageConf.margins.left
- },
- columns: pageConf.columns,
- colGap: pageConf.colGap,
- headerDist: pageConf.headerDist,
- footerDist: pageConf.footerDist
- },
- header: hfText(hfContent.header),
- footer: hfText(hfContent.footer),
- headerHtml: hfIsRich(hfContent.header) ? hfContent.header : undefined,
- footerHtml: hfIsRich(hfContent.footer) ? hfContent.footer : undefined,
- footnotes: currentFootnotes(),
- lineSpacing: docLineSpacing(),
- hfMode: pageConf.hfMode,
- pageNumbers: !!pageConf.pageNumbers,
- comments: JSON.parse(JSON.stringify(comments)),
- trackChanges: suggesting
- };
- }
- // the footnotes the text still references, in reference order
- function currentFootnotes() {
- var out = [];
- var seen = {};
- var refs = editor.querySelectorAll("sup.doc-fnref");
- for (var i = 0; i < refs.length; i++) {
- var id = refs[i].getAttribute("data-fn");
- if (seen[id]) continue;
- seen[id] = true;
- out.push({ id: id, html: footnotes[id] || "" });
- }
- return out.length ? out : undefined;
- }
- function loadBody(b) {
- b = b || {};
- dirtyFromY = null;
- lastPages = [];
- closeFind();
- deselectImage();
- editor.innerHTML = sanitizeHtml(b.html || "<p><br></p>", { keepClasses: true }) || "<p><br></p>";
- upgradeCrops(editor);
- normalizePageBreaks();
- hfContent.header = b.headerHtml ? sanitizeHtml(b.headerHtml, { keepClasses: true }) : esc(b.header || "");
- hfContent.footer = b.footerHtml ? sanitizeHtml(b.footerHtml, { keepClasses: true }) : esc(b.footer || "");
- headerEl.innerHTML = hfContent.header;
- footerEl.innerHTML = hfContent.footer;
- footnotes = {};
- (Array.isArray(b.footnotes) ? b.footnotes : []).forEach(function (fn) {
- if (fn && fn.id !== undefined) footnotes[String(fn.id)] = sanitizeHtml(fn.html || "", { keepClasses: true });
- });
- var p = b.page || {};
- pageConf.size = PAGE_SIZES[p.size] ? p.size : "A4";
- pageConf.orientation = (p.orientation === "landscape") ? "landscape" : "portrait";
- var m = p.margins || {};
- pageConf.margins = {
- top: num(m.top, 20), right: num(m.right, 20),
- bottom: num(m.bottom, 20), left: num(m.left, 20)
- };
- pageConf.columns = Math.min(3, Math.max(1, Math.round(num(p.columns, 1))));
- pageConf.colGap = Math.min(30, Math.max(2, num(p.colGap, 8)));
- pageConf.headerDist = Math.min(80, Math.max(0, num(p.headerDist, 12.7)));
- pageConf.footerDist = Math.min(80, Math.max(0, num(p.footerDist, 12.7)));
- pageConf.lineSpacing = Math.min(5, Math.max(0.5, num(b.lineSpacing, 1.15)));
- pageConf.pageNumbers = !!b.pageNumbers;
- pageConf.hfMode = (HF_MODES.indexOf(b.hfMode) >= 0) ? b.hfMode : "all";
- comments = Array.isArray(b.comments) ?
- JSON.parse(JSON.stringify(b.comments)) : [];
- suggesting = !!b.trackChanges;
- // fonts the document names that this machine lacks get a stand-in
- // with the original's width and line metrics, so lines and pages
- // break where they did in Word; once it is in, lay out again
- if (window.OfficeFonts && OfficeFonts.substitute) {
- OfficeFonts.substitute(OfficeFonts.familiesIn((b.html || "") + (b.headerHtml || "") +
- (b.footerHtml || "") + JSON.stringify(b.footnotes || []))).then(function (changed) {
- if (!changed) return;
- DocsLayout.clearMetrics();
- scheduleRelayout();
- });
- }
- applyPageSetup();
- updateCounts();
- renderCommentsPanel();
- updateSuggestStatus();
- }
- /* ================= undo / redo ================= */
- function snapshot() {
- return JSON.stringify(currentBody());
- }
- function applySnapshot(s) {
- try {
- loadBody(JSON.parse(s));
- } catch (e) { return; }
- OfficeApp.markDirty();
- placeCaretAtEnd();
- updateToolbarState();
- }
- function doUndo() { undo.flushDebounced(snapshot); undo.undo(); }
- function doRedo() { undo.redo(); }
- /* after any user edit: dirty flag, counters, undo bookkeeping */
- function afterEdit(immediate) {
- upgradeCrops(editor);
- OfficeApp.markDirty();
- scheduleCounts();
- scheduleToolbarState();
- if (immediate) undo.push(snapshot());
- else undo.pushDebounced(snapshot, 600);
- }
- /* ================= editing commands ================= */
- var PICTURE_ALIGN = { justifyLeft: "left", justifyCenter: "center", justifyRight: "right", justifyFull: "justify" };
- function exec(cmd, val) {
- if (inHeaderFooter()) return; // header/footer are plain text only
- // a selected picture is aligned as a picture (see alignPicture)
- if (selectedImg && PICTURE_ALIGN[cmd] && editor.contains(selectedImg)) {
- alignPicture(selectedImg, PICTURE_ALIGN[cmd]);
- return;
- }
- restoreSel();
- try {
- document.execCommand(cmd, false, val === undefined ? null : val);
- } catch (e) { }
- afterEdit(true);
- }
- /* execCommand("fontName") writes <font face="...">, naming one family and
- nothing else - a character that family has no glyph for then falls to
- whatever the machine happens to have. Tag the new nodes, then rewrite
- them to carry the full stack from OfficeFonts, so the shipped faces
- are behind every choice the user makes. */
- var FONT_MARK = "__ofdocfont__";
- function applyFontFamily(name, noCommit) {
- if (inHeaderFooter()) return;
- restoreSel();
- var stack = OfficeFonts.stack(name);
- try {
- // styleWithCSS is on for the editor, which would make this a
- // span whose font-family is the marker instead of a <font face>
- document.execCommand("styleWithCSS", false, false);
- document.execCommand("fontName", false, FONT_MARK);
- } catch (e) { }
- try { document.execCommand("styleWithCSS", false, true); } catch (e) { }
- var tagged = editor.querySelectorAll("font[face], [style*='font-family']");
- for (var i = 0; i < tagged.length; i++) {
- var el = tagged[i];
- var isMark = el.getAttribute("face") === FONT_MARK ||
- (el.style.fontFamily || "").indexOf(FONT_MARK) >= 0;
- if (!isMark) continue;
- el.removeAttribute("face");
- el.style.fontFamily = stack;
- // runs inside that name their own font (imported text) would win
- var inner = el.querySelectorAll("font[face], [style*='font-family']");
- for (var j = 0; j < inner.length; j++) {
- inner[j].removeAttribute("face");
- inner[j].style.removeProperty("font-family");
- if (!inner[j].getAttribute("style")) inner[j].removeAttribute("style");
- }
- }
- if (!noCommit) afterEdit(true);
- }
- /* wrapSelection puts the selected text in spans of its own and hands
- them back: execCommand marks it with the one size nothing else uses,
- in as many pieces as the markup needs, and the marks become spans.
- The selection is left over the new spans. */
- function wrapSelection() {
- try {
- document.execCommand("styleWithCSS", false, false);
- document.execCommand("fontSize", false, "7");
- } catch (e) { }
- try { document.execCommand("styleWithCSS", false, true); } catch (e) { }
- var out = [], i;
- var fonts = editor.querySelectorAll('font[size="7"]');
- for (i = 0; i < fonts.length; i++) {
- var f = fonts[i];
- var span = document.createElement("span");
- while (f.firstChild) span.appendChild(f.firstChild);
- f.parentNode.replaceChild(span, f);
- out.push(span);
- }
- var spans = editor.querySelectorAll("span");
- for (i = 0; i < spans.length; i++) {
- if (spans[i].style && spans[i].style.fontSize === "xxx-large") {
- spans[i].style.fontSize = "";
- out.push(spans[i]);
- }
- }
- if (out.length) {
- var r = document.createRange();
- r.setStartBefore(out[0]);
- r.setEndAfter(out[out.length - 1]);
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(r);
- savedRange = r.cloneRange();
- }
- return out;
- }
- function applyFontSize(pt, noCommit) {
- if (inHeaderFooter()) return;
- restoreSel();
- var spans = wrapSelection();
- spans.forEach(function (span) { span.style.fontSize = pt + "pt"; });
- // (a preview while the size box is typed in commits nothing; the
- // lines follow at once either way)
- relayoutNow(spans.map(function (sp) { return sp.closest(BLOCK_SEL); }));
- if (!noCommit) afterEdit(true);
- }
- /* A paragraph style applies to whole paragraphs, except when the
- selection is part of one paragraph: then it styles just those
- characters, the way Word's linked styles (Title, Heading 1-4) do. */
- function applyParagraphStyle(v) {
- if (inHeaderFooter()) return;
- restoreSel();
- var sel = window.getSelection();
- var range = sel && sel.rangeCount ? sel.getRangeAt(0) : savedRange;
- var blocks = getSelectedBlocks();
- if (range && !range.collapsed) {
- // a block the selection only touches at its very start is not in it
- blocks = blocks.filter(function (b) { return /\S/.test(partOf(range, b).toString()); });
- }
- var touched = blocks.slice();
- if (range && !range.collapsed && blocks.length === 1 &&
- partOf(range, blocks[0]).toString().trim().length < blocks[0].textContent.trim().length) {
- applyCharStyle(v, blocks[0]);
- } else if (range) {
- var start = [range.startContainer, range.startOffset], end = [range.endContainer, range.endOffset];
- touched = blocks.map(function (b) {
- var nb = restyleBlock(b, v);
- if (start[0] === b) start[0] = nb;
- if (end[0] === b) end[0] = nb;
- return nb;
- });
- // the block's children moved, which resets a live selection
- try {
- var r = document.createRange();
- r.setStart(start[0], start[1]);
- r.setEnd(end[0], end[1]);
- sel.removeAllRanges();
- sel.addRange(r);
- savedRange = r.cloneRange();
- } catch (e) { }
- }
- relayoutNow(touched);
- afterEdit(true);
- }
- // the part of a range that falls inside one block
- function partOf(range, block) {
- var r = document.createRange();
- r.selectNodeContents(block);
- if (range.compareBoundaryPoints(Range.START_TO_START, r) > 0) r.setStart(range.startContainer, range.startOffset);
- if (range.compareBoundaryPoints(Range.END_TO_END, r) < 0) r.setEnd(range.endContainer, range.endOffset);
- return r;
- }
- /* restyleBlock gives a paragraph a style. It is the same paragraph
- afterwards: its spacing (data-ls), alignment, indents and everything
- else it carries move to the new element (execCommand's formatBlock
- makes a bare one, which is how a 1.5-spaced paragraph used to come
- back single-spaced). Returns the block that holds the text now. */
- function restyleBlock(b, v) {
- var tag = v === "title" ? "H1" : v.toUpperCase();
- if (!/^(P|H[1-6])$/.test(b.tagName)) {
- // a list item, quote or cell keeps its own element
- var r = document.createRange();
- r.selectNodeContents(b);
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(r);
- try { document.execCommand("formatBlock", false, "<" + tag.toLowerCase() + ">"); } catch (e) { }
- var inner = b.querySelector(tag.toLowerCase());
- if (inner) {
- inner.classList.toggle("doc-title", v === "title");
- if (!inner.getAttribute("class")) inner.removeAttribute("class");
- }
- return b;
- }
- var nb = b;
- if (b.tagName !== tag) {
- nb = document.createElement(tag);
- for (var i = 0; i < b.attributes.length; i++) nb.setAttribute(b.attributes[i].name, b.attributes[i].value);
- while (b.firstChild) nb.appendChild(b.firstChild);
- b.parentNode.replaceChild(nb, b);
- }
- nb.classList.toggle("doc-title", v === "title");
- if (!nb.getAttribute("class")) nb.removeAttribute("class");
- return nb;
- }
- /* styleLook reads what a paragraph style looks like from the
- stylesheet: a hidden paragraph of that style, measured in place */
- function styleLook(v) {
- var probe = document.createElement(v === "title" ? "h1" : v);
- if (v === "title") probe.className = "doc-title";
- probe.style.cssText = "position:absolute;left:-10000px;top:0;visibility:hidden;margin:0;";
- probe.textContent = "x";
- editor.appendChild(probe);
- var cs = window.getComputedStyle(probe);
- var look = {
- size: Math.round(parseFloat(cs.fontSize) * 72 / 96 * 10) / 10 + "pt",
- weight: cs.fontWeight,
- style: cs.fontStyle,
- color: cssColorHex(cs.color)
- };
- editor.removeChild(probe);
- return look;
- }
- function cssColorHex(c) {
- var m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(String(c || ""));
- if (!m) return c;
- return "#" + [m[1], m[2], m[3]].map(function (x) {
- return ("0" + parseInt(x, 10).toString(16)).slice(-2);
- }).join("");
- }
- /* applyCharStyle gives the selected characters a style's look - its
- size, weight, slant and colour - as their own formatting, marked
- data-cstyle so the style list can name it again. Inside, the text
- takes the style's size throughout: an earlier style run or a run's
- own size would otherwise poke through. Normal text in a normal
- paragraph is simply the paragraph's own look, so it leaves no span. */
- function applyCharStyle(v, block) {
- var look = styleLook(v);
- var plain = v === "p" && block.tagName === "P" && !block.classList.contains("doc-title");
- wrapSelection().forEach(function (span) {
- var olds = span.querySelectorAll("span[data-cstyle]");
- for (var i = olds.length - 1; i >= 0; i--) unwrapEl(olds[i]);
- var sized = span.querySelectorAll("[style]");
- for (i = 0; i < sized.length; i++) {
- sized[i].style.removeProperty("font-size");
- if (!sized[i].getAttribute("style")) sized[i].removeAttribute("style");
- }
- var outer = span.parentNode && span.parentNode.closest ? span.parentNode.closest("span[data-cstyle]") : null;
- if (plain && !(outer && block.contains(outer))) {
- unwrapEl(span);
- return;
- }
- span.setAttribute("data-cstyle", v);
- span.style.fontSize = look.size;
- span.style.fontWeight = look.weight;
- span.style.fontStyle = look.style;
- span.style.color = look.color;
- });
- }
- function unwrapEl(el) {
- var p = el.parentNode;
- if (!p) return;
- while (el.firstChild) p.insertBefore(el.firstChild, el);
- p.removeChild(el);
- }
- function setLineSpacing(v) {
- if (inHeaderFooter()) return;
- restoreSel();
- var blocks = getSelectedBlocks();
- blocks.forEach(function (b) {
- b.setAttribute("data-ls", v);
- b.removeAttribute("data-lsexact");
- b.removeAttribute("data-lsmin");
- });
- relayoutNow(blocks);
- afterEdit(true);
- }
- function currentLineSpacing() {
- var blocks = getSelectedBlocks();
- if (!blocks.length) return "";
- var v = blocks[0].getAttribute("data-ls");
- return v ? String(parseFloat(v)) : String(docLineSpacing());
- }
- function toggleChecklist() {
- if (inHeaderFooter()) return;
- restoreSel();
- var li = null;
- getSelectedBlocks().forEach(function (b) { if (b.tagName === "LI") li = b; });
- var list = li ? li.closest("ul,ol") : null;
- try {
- if (list && list.tagName === "UL" && list.classList.contains("of-checklist")) {
- // toggle the whole list back off
- document.execCommand("insertUnorderedList");
- } else if (list && list.tagName === "UL") {
- list.classList.add("of-checklist");
- } else {
- document.execCommand("insertUnorderedList");
- var sel = window.getSelection();
- var n = sel.anchorNode;
- while (n && n !== editor) {
- if (n.nodeType === 1 && n.tagName === "UL") { n.classList.add("of-checklist"); break; }
- n = n.parentNode;
- }
- }
- } catch (e) { }
- afterEdit(true);
- }
- function clearFormatting() {
- if (inHeaderFooter()) return;
- restoreSel();
- try {
- document.execCommand("removeFormat");
- document.execCommand("formatBlock", false, "<p>");
- } catch (e) { }
- var cleared = getSelectedBlocks();
- cleared.forEach(function (b) {
- b.removeAttribute("style");
- b.classList.remove("doc-title");
- if (!b.getAttribute("class")) b.removeAttribute("class");
- });
- relayoutNow(cleared);
- afterEdit(true);
- }
- function selectAll() {
- editor.focus();
- var r = document.createRange();
- r.selectNodeContents(editor);
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(r);
- savedRange = r.cloneRange();
- }
- /* ================= ribbon ================= */
- /* The ribbon (common/ribbon.js) holds every command the editor has, in
- the tabs Word puts them in: Home, Insert, Draw, Layout, References,
- Review and View. File stays a menu (office.js). Buttons keep the
- editor's selection (mousedown is swallowed), and each command puts
- the saved range back before it runs (restoreSel). */
- var STYLE_TILES = PARA_STYLES.concat([
- { v: "blockquote", label: "Quote" },
- { v: "pre", label: "Code" }
- ]);
- var currentStyle = "p";
- function buildToolbar() {
- var R = OfficeRibbon;
- var B = R.button, D = R.dropdown;
- // hidden file input for Insert > Pictures > From this device
- $("#deviceImageInput").on("change", function () {
- var files = this.files;
- for (var i = 0; i < files.length; i++) {
- (function (f) {
- OfficeApp.blobToSrc(f, f.name || "image.png", function (src) {
- insertImage(src);
- }, function (msg) {
- OfficeApp.toast(msg, "error");
- });
- })(files[i]);
- }
- this.value = "";
- });
- // paragraph style: the styles gallery on a desktop, this select on
- // a phone (where galleries are left out)
- $styleSel = $('<select class="of-tselect tb-style" title="Paragraph style" data-desktop="hide"></select>');
- STYLE_TILES.forEach(function (s) {
- $styleSel.append($("<option></option>").attr("value", s.v).text(s.label));
- });
- $styleSel.on("change", function () { applyParagraphStyle(this.value); });
- $fontSel = $('<select class="of-tselect tb-font" title="Font"></select>');
- FONTS.forEach(function (f) {
- $fontSel.append($("<option></option>").attr("value", f).text(f).css("font-family", OfficeFonts.stack(f)));
- });
- $fontSel.on("change", function () { applyFontFamily(this.value); });
- $sizeSel = $('<select class="of-tselect tb-size" title="Font size (pt)"></select>');
- FONT_SIZES.forEach(function (s) {
- $sizeSel.append($("<option></option>").attr("value", String(s)).text(s));
- });
- $sizeSel.val("11");
- $sizeSel.on("change", function () { applyFontSize(parseInt(this.value, 10)); });
- var cmdBtn = function (icon, title, key, cmd, svg) {
- return B({
- icon: svg ? null : icon, svg: svg, title: title, key: key, cmd: cmd,
- onClick: function () { exec(cmd); }
- });
- };
- /* ---------- Home ---------- */
- var home = R.tab("home", "Home");
- R.clipboardGroup(home, {
- pasteMenu: function () {
- return [
- { label: "Keep source formatting", icon: "paste", key: "Ctrl+V", action: function () { pasteFromMenu(false); } },
- { label: "Keep text only", icon: "file alternate outline", key: "Ctrl+Shift+V", action: function () { pasteFromMenu(true); } }
- ];
- },
- copyMenu: function () {
- return [
- { label: "Copy", icon: "copy", key: "Ctrl+C", action: function () { menuCutCopy(false); } },
- { label: "Copy as plain text", icon: "file alternate outline", action: copyPlainText }
- ];
- },
- painter: {
- id: "docPainter", title: "Format Painter - click, then select the text to format (double-click to keep it on)",
- active: function () { return !!painter; },
- start: startPainter
- }
- });
- var font = home.group({ id: "font", label: "Font", icon: "font", priority: 9 });
- font.row([$fontSel, $sizeSel,
- B({ svg: "growFont", title: "Increase font size", key: "Ctrl+]", onClick: function () { stepFontSize(1); } }),
- B({ svg: "shrinkFont", title: "Decrease font size", key: "Ctrl+[", onClick: function () { stepFontSize(-1); } }),
- D({ svg: "changeCase", title: "Change case", mobile: false, menu: caseMenuItems }),
- B({ svg: "clearFormat", title: "Clear formatting", onClick: clearFormatting })
- ]);
- font.row([
- cmdBtn("bold", "Bold", "Ctrl+B", "bold"),
- cmdBtn("italic", "Italic", "Ctrl+I", "italic"),
- cmdBtn("underline", "Underline", "Ctrl+U", "underline"),
- cmdBtn("strikethrough", "Strikethrough", "Ctrl+Shift+X", "strikeThrough"),
- cmdBtn(null, "Subscript", "Ctrl+,", "subscript", "subscript"),
- cmdBtn(null, "Superscript", "Ctrl+.", "superscript", "superscript"),
- "|",
- R.colorButton({
- id: "docHilite", svg: "highlighter", title: "Text highlight color", value: "#ffff00",
- allowNone: true, noneLabel: "No highlight", onPick: applyHighlight
- }),
- R.colorButton({
- id: "docFontColor", svg: "fontColor", title: "Font color", value: "#d0342c",
- onPick: applyFontColor
- })
- ]);
- var para = home.group({ id: "paragraph", label: "Paragraph", icon: "paragraph", priority: 8 });
- para.row([
- cmdBtn("list ul", "Bulleted list", "Ctrl+Shift+8", "insertUnorderedList"),
- cmdBtn("list ol", "Numbered list", "Ctrl+Shift+7", "insertOrderedList"),
- B({ icon: "check square outline", title: "Checklist", cmd: "checklist", onClick: toggleChecklist }),
- "|",
- B({ icon: "outdent", title: "Decrease indent", onClick: function () { exec("outdent"); } }),
- B({ icon: "indent", title: "Increase indent", key: "Tab", onClick: function () { exec("indent"); } }),
- "|",
- B({ svg: "sortAZ", title: "Sort the selected paragraphs A to Z", mobile: false, onClick: sortParagraphs }),
- B({ svg: "marks", title: "Show formatting marks", mobile: false, active: marksOn, onClick: toggleMarks })
- ]);
- para.row([
- cmdBtn("align left", "Align left", null, "justifyLeft"),
- cmdBtn("align center", "Center", null, "justifyCenter"),
- cmdBtn("align right", "Align right", null, "justifyRight"),
- cmdBtn("align justify", "Justify", null, "justifyFull"),
- "|",
- D({ svg: "lineSpacing", title: "Line and paragraph spacing", menu: lineSpacingItems }),
- R.colorButton({
- id: "docShading", svg: "fill", title: "Shading", value: "#fff2cc",
- allowNone: true, noneLabel: "No colour", mobile: false, onPick: applyShading
- }),
- D({ svg: "borderBottom", title: "Borders", mobile: false, menu: borderItems })
- ]);
- home.group({ id: "styles", label: "Styles", icon: "paragraph", priority: 4 })
- .add(R.gallery({
- id: "docStyles", cls: "doc-styles", tileW: 80, visible: 6, minVisible: 2,
- moreTitle: "All styles",
- items: STYLE_TILES.map(function (s) {
- return {
- key: s.v, label: s.label,
- html: '<span class="doc-gs-prev doc-gs-' + s.v + '">AaBbCc</span>' +
- '<span class="doc-gs-name">' + esc(s.label) + "</span>",
- active: function () { return currentStyle === s.v; },
- onClick: function () { applyParagraphStyle(s.v); }
- };
- })
- }))
- .add($styleSel);
- home.group({ id: "editing", label: "Editing", icon: "search", priority: 2 }).stack([
- B({ icon: "search", label: "Find", showLabel: true, key: "Ctrl+F", onClick: function () { openFind(false); } }),
- B({ icon: "exchange", label: "Replace", showLabel: true, key: "Ctrl+H", onClick: function () { openFind(true); } }),
- B({ icon: "i cursor", label: "Select all", showLabel: true, key: "Ctrl+A", onClick: selectAll })
- ]);
- /* ---------- Insert ---------- */
- var ins = R.tab("insert", "Insert");
- ins.group({ id: "pages", label: "Pages", svg: "pageBreak" })
- .add(R.big({ svg: "pageBreak", label: "Page break", key: "Ctrl+Enter", onClick: insertPageBreak }));
- ins.group({ id: "tables", label: "Tables", svg: "table" })
- .add(R.big({ svg: "table", label: "Table", onClick: insertTableDialog }));
- ins.group({ id: "illustrations", label: "Illustrations", svg: "picture" })
- .add(R.big({ svg: "picture", label: "Pictures", menu: imageMenuItems }))
- .add(R.big({ svg: "drawing", label: "Drawing", onClick: function () { drawingDialog(); } }));
- ins.group({ id: "links", label: "Links", svg: "link" })
- .add(R.big({ svg: "link", label: "Link", key: "Ctrl+K", onClick: linkDialog }))
- .add(R.big({ svg: "newComment", label: "Comment", key: "Ctrl+Alt+M", onClick: function () { commentDialog(null); } }));
- ins.group({ id: "hf", label: "Header & Footer", svg: "headerFooter" })
- .add(R.big({ svg: "headerFooter", label: "Header & footer", menu: hfMenuItems }))
- .add(R.big({ svg: "pageNumbers", label: "Page numbers", active: function () { return !!pageConf.pageNumbers; }, onClick: togglePageNumbers }));
- ins.group({ id: "text", label: "Text", icon: "font" }).stack([
- B({ svg: "hrule", label: "Horizontal line", showLabel: true, onClick: function () { exec("insertHorizontalRule"); } }),
- B({ icon: "quote left", label: "Quote", showLabel: true, onClick: function () { applyParagraphStyle("blockquote"); } }),
- B({ icon: "code", label: "Code block", showLabel: true, onClick: function () { applyParagraphStyle("pre"); } })
- ]);
- ins.group({ id: "symbols", label: "Symbols", svg: "symbol" })
- .add(R.big({ svg: "symbol", label: "Symbol", title: "Special characters", onClick: specialCharsDialog }))
- .add(R.big({ svg: "footnote", label: "Footnote", key: "Ctrl+Alt+F", onClick: insertFootnote }));
- /* ---------- Draw ---------- */
- var draw = R.tab("draw", "Draw");
- var pens = draw.group({ id: "pens", label: "Pens", svg: "pen" });
- OfficeSketch.PENS.forEach(function (p) {
- pens.add(R.big({
- iconHtml: OfficeSketch.penIcon(p), label: p.label,
- title: "Draw with the " + p.label.toLowerCase(),
- onClick: function () { drawingDialog(p.id); }
- }));
- });
- draw.group({ id: "canvas", label: "Canvas", svg: "drawing" })
- .add(R.big({ svg: "drawing", label: "Drawing canvas", onClick: function () { drawingDialog(); } }));
- /* ---------- Layout ---------- */
- var lay = R.tab("layout", "Layout");
- lay.group({ id: "setup", label: "Page Setup", svg: "margins", priority: 5 })
- .add(R.big({ svg: "margins", label: "Margins", menu: marginItems }))
- .add(R.big({ svg: "orientation", label: "Orientation", menu: orientationItems }))
- .add(R.big({ svg: "pageSize", label: "Size", menu: sizeItems }))
- .add(R.big({ svg: "columns", label: "Columns", menu: layoutMenuItems }))
- .add(R.big({
- svg: "pageBreak", label: "Breaks", menu: function () {
- return [{ label: "Page break", icon: "file outline", key: "Ctrl+Enter", action: insertPageBreak }];
- }
- }));
- lay.group({ id: "hf", label: "Header & Footer", svg: "headerFooter" })
- .add(R.big({ svg: "headerFooter", label: "Header & footer", menu: hfMenuItems }))
- .add(R.big({ svg: "pageNumbers", label: "Page numbers", active: function () { return !!pageConf.pageNumbers; }, onClick: togglePageNumbers }));
- lay.group({ id: "paragraph", label: "Paragraph", svg: "lineSpacing" }).stack([
- D({ svg: "lineSpacing", label: "Line spacing", showLabel: true, menu: lineSpacingItems }),
- B({ icon: "indent", label: "Increase indent", showLabel: true, onClick: function () { exec("indent"); } }),
- B({ icon: "outdent", label: "Decrease indent", showLabel: true, onClick: function () { exec("outdent"); } })
- ]);
- lay.group({ id: "dialog", label: "Page setup", svg: "pageSetup" })
- .add(R.big({ svg: "pageSetup", label: "Page setup", onClick: pageSetupDialog }));
- /* ---------- References ---------- */
- var refs = R.tab("references", "References");
- refs.group({ id: "toc", label: "Table of Contents", svg: "toc" })
- .add(R.big({ svg: "toc", label: "Table of contents", title: "Insert a table of contents built from the headings", onClick: insertToc }))
- .add(R.big({ svg: "tocUpdate", label: "Update table", enabled: hasToc, onClick: updateToc }));
- refs.group({ id: "footnotes", label: "Footnotes", svg: "footnote" })
- .add(R.big({ svg: "footnote", label: "Insert footnote", key: "Ctrl+Alt+F", onClick: insertFootnote }));
- /* ---------- Review ---------- */
- var rev = R.tab("review", "Review");
- rev.group({ id: "proofing", label: "Proofing", svg: "spelling" })
- .add(R.big({ svg: "spelling", label: "Spelling", title: "Check spelling as you type", active: function () { return editor.spellcheck; }, onClick: toggleSpellcheck }))
- .add(R.big({ svg: "wordCount", label: "Word count", onClick: wordCountDialog }));
- rev.group({ id: "comments", label: "Comments", svg: "comments" })
- .add(R.big({ svg: "newComment", label: "New comment", key: "Ctrl+Alt+M", onClick: function () { commentDialog(null); } }))
- .add(R.big({
- svg: "comments", label: "Show comments", active: commentsPanelVisible,
- onClick: function () { showCommentsPanel(!commentsPanelVisible()); OfficeRibbon.refresh(); }
- }));
- rev.group({ id: "tracking", label: "Tracking", svg: "trackChanges" })
- .add(R.big({
- svg: "trackChanges", label: "Suggest edits", title: "Track changes as suggestions",
- active: function () { return suggesting; },
- onClick: function () { setSuggesting(!suggesting); OfficeRibbon.refresh(); }
- }));
- rev.group({ id: "changes", label: "Changes", svg: "accept" })
- .add(R.big({
- svg: "accept", label: "Accept all", enabled: function () { return allSuggestions().length > 0; },
- onClick: function () { resolveAllSuggestions(true); OfficeRibbon.refresh(); }
- }))
- .add(R.big({
- svg: "reject", label: "Reject all", enabled: function () { return allSuggestions().length > 0; },
- onClick: function () { resolveAllSuggestions(false); OfficeRibbon.refresh(); }
- }));
- /* ---------- View ---------- */
- var view = R.tab("view", "View");
- view.group({ id: "show", label: "Show", svg: "marks" })
- .add(R.big({ svg: "marks", label: "Formatting marks", active: marksOn, onClick: toggleMarks }))
- .add(R.big({
- svg: "layoutBoxes", label: "Layout boxes",
- active: function () { return document.body.classList.contains("doc-show-boxes"); },
- onClick: function () { toggleLayoutBoxes(); OfficeRibbon.refresh(); }
- }))
- .add(R.big({
- svg: "comments", label: "Comments", active: commentsPanelVisible,
- onClick: function () { showCommentsPanel(!commentsPanelVisible()); OfficeRibbon.refresh(); }
- }));
- view.group({ id: "zoom", label: "Zoom", svg: "zoomIn" })
- .add(R.big({ svg: "zoomOut", label: "Zoom out", key: "Ctrl+-", onClick: function () { OfficeApp.zoomOut(); } }))
- .add(R.big({ svg: "zoom100", label: "100%", key: "Ctrl+0", onClick: function () { OfficeApp.setZoom(100); } }))
- .add(R.big({ svg: "zoomIn", label: "Zoom in", key: "Ctrl+=", onClick: function () { OfficeApp.zoomIn(); } }))
- .add(R.big({ svg: "pageWidth", label: "Page width", onClick: function () { fitPageWidth(false); } }));
- view.group({ id: "appearance", label: "Appearance", svg: "darkTheme" })
- .add(R.big({
- svg: "darkTheme", label: "Dark theme", active: function () { return OfficeApp.isDark(); },
- onClick: function () { OfficeApp.toggleTheme(); OfficeRibbon.refresh(); }
- }));
- /* ---------- Picture Format (contextual) ---------- */
- var pf = R.tab("pictureformat", "Picture Format", {
- contextual: true,
- when: function () { return !!selectedImg && editor.contains(selectedImg); }
- });
- pf.group({ id: "adjust", label: "Adjust", svg: "crop" })
- .add(R.big({ svg: "crop", label: "Crop", onClick: function () { cropPictureDialog(selectedImg); } }))
- .add(R.big({ svg: "resetPicture", label: "Reset picture", title: "Remove the crop and border and restore the original size", onClick: function () { resetPicture(selectedImg); } }));
- pf.group({ id: "border", label: "Picture Border", svg: "outline" })
- .add(R.colorButton({ id: "docImgBorder", big: true, svg: "outline", label: "Border", title: "Picture border", value: "#000000", allowNone: true, noneLabel: "No border", onPick: applyPictureBorderColor }))
- .add(R.big({ svg: "lineWeight", label: "Weight", menu: pictureWeightItems }));
- pf.group({ id: "arrange", label: "Arrange", svg: "arrange" })
- .add(R.big({ svg: "wrapText", label: "Wrap text", menu: pictureWrapItems }))
- .add(R.big({ svg: "alignObjects", label: "Align", menu: pictureAlignItems }));
- pf.group({ id: "size", label: "Size", svg: "formatPane" })
- .add(R.big({ svg: "formatPane", label: "Size & properties", onClick: function () { imageSizeDialog(selectedImg); } }));
- }
- /* ---------- Home: font ---------- */
- function currentFontPt() {
- var v = parseInt($sizeSel.val(), 10);
- var n = savedRange ? savedRange.startContainer : null;
- if (n && n.nodeType === 3) n = n.parentNode;
- if (n && n.nodeType === 1 && editor.contains(n)) {
- var px = parseFloat(window.getComputedStyle(n).fontSize);
- if (px > 0) v = Math.round(px * 72 / 96);
- }
- return v || 11;
- }
- // the next size on the list up or down, as Word's grow / shrink do
- function stepFontSize(dir) {
- var cur = currentFontPt(), next = cur;
- var i;
- if (dir > 0) {
- next = cur + 10;
- for (i = 0; i < FONT_SIZES.length; i++) if (FONT_SIZES[i] > cur) { next = FONT_SIZES[i]; break; }
- next = Math.min(400, next);
- } else {
- next = Math.max(1, cur - 1);
- for (i = FONT_SIZES.length - 1; i >= 0; i--) if (FONT_SIZES[i] < cur) { next = FONT_SIZES[i]; break; }
- }
- if (next === cur) return;
- applyFontSize(next);
- if ($sizeSel.find('option[value="' + next + '"]').length) $sizeSel.val(String(next));
- }
- var CASES = [
- { key: "sentence", label: "Sentence case." },
- { key: "lower", label: "lowercase" },
- { key: "upper", label: "UPPERCASE" },
- { key: "title", label: "Capitalize Each Word" },
- { key: "toggle", label: "tOGGLE cASE" }
- ];
- function caseMenuItems() {
- return CASES.map(function (c) {
- return { label: c.label, action: function () { changeCase(c.key); } };
- });
- }
- /* Change case rewrites the characters of the selected text nodes in
- place, one for one, so the formatting runs, the selection and the
- undo snapshot all stay where they were. A character whose other
- case is longer (German sharp s) is left as it is. */
- function changeCase(mode) {
- if (inHeaderFooter()) return;
- restoreSel();
- var sel = window.getSelection();
- if (!sel || !sel.rangeCount) return;
- var range = sel.getRangeAt(0);
- if (!editor.contains(range.commonAncestorContainer)) return;
- if (range.collapsed) {
- OfficeApp.setStatus("Select the text to change first", "info", 3000);
- return;
- }
- var rootEl = range.commonAncestorContainer.nodeType === 3 ?
- range.commonAncestorContainer.parentNode : range.commonAncestorContainer;
- var walker = document.createTreeWalker(rootEl, NodeFilter.SHOW_TEXT, null);
- var nodes = [];
- while (walker.nextNode()) {
- if (range.intersectsNode(walker.currentNode)) nodes.push(walker.currentNode);
- }
- var one = function (c, f) {
- var r = f(c);
- return r.length === 1 ? r : c;
- };
- var up = function (c) { return one(c, function (x) { return x.toUpperCase(); }); };
- var low = function (c) { return one(c, function (x) { return x.toLowerCase(); }); };
- var isLetter = function (c) { return c.toUpperCase() !== c.toLowerCase(); };
- var wordStart = true, sentenceStart = true;
- nodes.forEach(function (tn) {
- var t = tn.nodeValue;
- var a = tn === range.startContainer ? range.startOffset : 0;
- var b = tn === range.endContainer ? range.endOffset : t.length;
- var out = "";
- for (var i = a; i < b; i++) {
- var c = t.charAt(i), r = c;
- if (mode === "lower") r = low(c);
- else if (mode === "upper") r = up(c);
- else if (mode === "toggle") r = (c === up(c)) ? low(c) : up(c);
- else if (mode === "title") r = wordStart ? up(c) : low(c);
- else if (mode === "sentence") r = (sentenceStart && isLetter(c)) ? up(c) : low(c);
- if (isLetter(c)) { wordStart = false; sentenceStart = false; }
- else if (/\s/.test(c)) wordStart = true;
- if (/[.!?]/.test(c)) sentenceStart = true;
- out += r;
- }
- if (out !== t.substring(a, b)) tn.nodeValue = t.substring(0, a) + out + t.substring(b);
- });
- try {
- sel.removeAllRanges();
- sel.addRange(range);
- savedRange = range.cloneRange();
- } catch (e) { }
- afterEdit(true);
- }
- function applyHighlight(v) {
- if (inHeaderFooter()) return;
- restoreSel();
- try {
- if (!document.execCommand("hiliteColor", false, v || "transparent")) {
- document.execCommand("backColor", false, v || "transparent");
- }
- } catch (e) {
- try { document.execCommand("backColor", false, v || "transparent"); } catch (e2) { }
- }
- afterEdit(true);
- }
- function applyFontColor(v) {
- if (inHeaderFooter() || !v) return;
- restoreSel();
- try { document.execCommand("foreColor", false, v); } catch (e) { }
- afterEdit(true);
- }
- /* ---------- Home: paragraph ---------- */
- function lineSpacingItems() {
- var cur = currentLineSpacing();
- return LINE_SPACINGS.map(function (v) {
- return {
- label: v === "1" ? "Single (1.0)" : v,
- checked: cur === v,
- action: function () { setLineSpacing(v); }
- };
- });
- }
- // paragraph shading: the block's background, which the .docx writer
- // turns into the paragraph's w:shd
- function applyShading(v) {
- if (inHeaderFooter()) return;
- restoreSel();
- var blocks = getSelectedBlocks();
- if (!blocks.length) return;
- blocks.forEach(function (b) {
- b.style.backgroundColor = v || "";
- if (!b.getAttribute("style")) b.removeAttribute("style");
- });
- afterEdit(true);
- updatePageGuides();
- }
- /* Paragraph borders as Word draws them: a 0.75pt rule a point away from
- the text (border-* + padding-*, which the .docx writer turns into
- w:pBdr with that w:space). */
- var BORDER_RULE = "0.75pt solid #000000";
- function setBlockBorders(sides) {
- if (inHeaderFooter()) return;
- restoreSel();
- var blocks = getSelectedBlocks();
- if (!blocks.length) return;
- var all = ["top", "right", "bottom", "left"];
- blocks.forEach(function (b, i) {
- all.forEach(function (s) {
- // a box around several paragraphs: no rules between them
- var on = sides.indexOf(s) >= 0;
- if (sides.join() === "top,right,bottom,left" && blocks.length > 1) {
- if (s === "top" && i > 0) on = false;
- if (s === "bottom" && i < blocks.length - 1) on = false;
- }
- b.style["border" + s.charAt(0).toUpperCase() + s.substring(1)] = on ? BORDER_RULE : "";
- b.style["padding" + s.charAt(0).toUpperCase() + s.substring(1)] = on ? "1pt" : "";
- });
- if (!b.getAttribute("style")) b.removeAttribute("style");
- });
- afterEdit(true);
- updatePageGuides();
- }
- function borderItems() {
- return [
- { label: "Bottom border", html: OfficeIcons.get("borderBottom") + "<span>Bottom border</span>", action: function () { setBlockBorders(["bottom"]); } },
- { label: "Top border", html: OfficeIcons.get("borderTop") + "<span>Top border</span>", action: function () { setBlockBorders(["top"]); } },
- { label: "Outside borders", html: OfficeIcons.get("borderOutside") + "<span>Outside borders</span>", action: function () { setBlockBorders(["top", "right", "bottom", "left"]); } },
- { label: "No border", html: OfficeIcons.get("borderNone") + "<span>No border</span>", action: function () { setBlockBorders([]); } }
- ];
- }
- function sortParagraphs() {
- if (inHeaderFooter()) return;
- restoreSel();
- var blocks = getSelectedBlocks().filter(function (b) {
- return !b.classList.contains("doc-pagebreak") && b.tagName !== "TABLE";
- });
- if (blocks.length < 2) {
- OfficeApp.setStatus("Select two or more paragraphs to sort", "info", 3000);
- return;
- }
- var parent = blocks[0].parentNode;
- if (!blocks.every(function (b) { return b.parentNode === parent; })) {
- OfficeApp.setStatus("Sort works on paragraphs next to each other", "error", 4000);
- return;
- }
- var anchor = blocks[blocks.length - 1].nextSibling;
- var sorted = blocks.slice().sort(function (a, b) {
- return (a.textContent || "").trim().localeCompare((b.textContent || "").trim(), undefined,
- { numeric: true, sensitivity: "base" });
- });
- sorted.forEach(function (b) { parent.insertBefore(b, anchor); });
- afterEdit(true);
- updatePageGuides();
- }
- function marksOn() { return document.body.classList.contains("doc-show-marks"); }
- function toggleMarks() {
- var on = !marksOn();
- document.body.classList.toggle("doc-show-marks", on);
- OfficeApp.setSetting("marks", on);
- OfficeRibbon.refresh();
- }
- /* ---------- Home: format painter ----------
- Picks up the look of the text at the caret (font, size, colour,
- highlight, bold / italic / underline / strike) and lays it on the
- next selection made in the document. A double-click keeps it on
- until Escape or another click on the button. */
- var painter = null;
- function readCaretFormat() {
- var n = savedRange ? savedRange.startContainer : null;
- if (n && n.nodeType === 3) n = n.parentNode;
- if (!n || n.nodeType !== 1 || !editor.contains(n)) return null;
- var cs = window.getComputedStyle(n);
- var deco = "";
- for (var e = n; e && e !== editor; e = e.parentNode) {
- if (e.nodeType === 1) deco += " " + (window.getComputedStyle(e).textDecorationLine || "");
- }
- var bg = "";
- for (var h = n; h && h !== editor; h = h.parentNode) {
- if (h.nodeType !== 1 || /^(P|H[1-6]|LI|DIV|BLOCKQUOTE|PRE|TD|TH)$/.test(h.tagName)) break;
- var c = window.getComputedStyle(h).backgroundColor;
- if (c && c !== "transparent" && !/rgba\(0, 0, 0, 0\)/.test(c)) { bg = c; break; }
- }
- var fam = String(cs.fontFamily || "").replace(/['"]/g, "").split(",")[0].trim();
- return {
- family: fam,
- pt: Math.round(parseFloat(cs.fontSize) * 72 / 96),
- bold: (parseInt(cs.fontWeight, 10) || 400) >= 600,
- italic: cs.fontStyle === "italic",
- underline: deco.indexOf("underline") >= 0,
- strike: deco.indexOf("line-through") >= 0,
- color: cs.color,
- highlight: bg
- };
- }
- function startPainter(sticky) {
- if (painter && !sticky) { stopPainter(); return; }
- var f = readCaretFormat();
- if (!f) {
- OfficeApp.setStatus("Put the cursor in the text whose format to copy", "info", 3000);
- return;
- }
- painter = { fmt: f, sticky: !!sticky };
- document.body.classList.add("doc-painting");
- OfficeApp.setStatus(sticky ? "Format painter on - select text to format, Esc to stop" :
- "Select the text to format", "info", 4000);
- OfficeRibbon.refresh();
- }
- function stopPainter() {
- painter = null;
- document.body.classList.remove("doc-painting");
- OfficeRibbon.refresh();
- }
- function applyPainter() {
- if (!painter) return;
- var sel = window.getSelection();
- if (!sel || sel.isCollapsed || !sel.rangeCount || !editor.contains(sel.getRangeAt(0).commonAncestorContainer)) return;
- savedRange = sel.getRangeAt(0).cloneRange();
- var f = painter.fmt;
- try {
- document.execCommand("removeFormat");
- if (f.bold) document.execCommand("bold");
- if (f.italic) document.execCommand("italic");
- if (f.underline) document.execCommand("underline");
- if (f.strike) document.execCommand("strikeThrough");
- if (f.color) document.execCommand("foreColor", false, f.color);
- if (f.highlight) document.execCommand("hiliteColor", false, f.highlight);
- } catch (e) { }
- savedRange = sel.rangeCount ? sel.getRangeAt(0).cloneRange() : savedRange;
- if (f.family && FONTS.indexOf(f.family) >= 0) applyFontFamily(f.family, true);
- if (f.pt) applyFontSize(f.pt, true);
- afterEdit(true);
- if (!painter.sticky) stopPainter();
- }
- /* ---------- Insert / Layout: page ---------- */
- function togglePageNumbers() {
- pageConf.pageNumbers = !pageConf.pageNumbers;
- applyPageSetup();
- afterEdit(true);
- OfficeRibbon.refresh();
- }
- function hfMenuItems() {
- return [
- { label: "Same on all pages", checked: pageConf.hfMode === "all", action: function () { setHfMode("all"); } },
- { label: "All pages except the first", checked: pageConf.hfMode === "except-first", action: function () { setHfMode("except-first"); } },
- { label: "None", checked: pageConf.hfMode === "none", action: function () { setHfMode("none"); } }
- ];
- }
- // Word's margin presets, in millimetres
- var MARGIN_PRESETS = [
- { label: "Normal", sub: "2.54 cm all round", m: { top: 25.4, right: 25.4, bottom: 25.4, left: 25.4 } },
- { label: "Narrow", sub: "1.27 cm all round", m: { top: 12.7, right: 12.7, bottom: 12.7, left: 12.7 } },
- { 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 } },
- { 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 } },
- { label: "Compact", sub: "2 cm all round", m: { top: 20, right: 20, bottom: 20, left: 20 } }
- ];
- function marginItems() {
- var m = pageConf.margins;
- var items = MARGIN_PRESETS.map(function (p) {
- var same = Math.abs(m.top - p.m.top) < 0.1 && Math.abs(m.right - p.m.right) < 0.1 &&
- Math.abs(m.bottom - p.m.bottom) < 0.1 && Math.abs(m.left - p.m.left) < 0.1;
- return {
- label: p.label + " (" + p.sub + ")", checked: same,
- action: function () {
- pageConf.margins = { top: p.m.top, right: p.m.right, bottom: p.m.bottom, left: p.m.left };
- applyPageSetup();
- afterEdit(true);
- }
- };
- });
- items.push({ sep: true });
- items.push({ label: "Custom margins...", icon: "sliders horizontal", action: pageSetupDialog });
- return items;
- }
- function orientationItems() {
- return [["portrait", "Portrait"], ["landscape", "Landscape"]].map(function (o) {
- return {
- label: o[1], checked: pageConf.orientation === o[0],
- action: function () { pageConf.orientation = o[0]; applyPageSetup(); afterEdit(true); }
- };
- });
- }
- function sizeItems() {
- return Object.keys(PAGE_SIZES).map(function (k) {
- var d = PAGE_SIZES[k];
- return {
- label: k + " (" + d.w + " x " + d.h + " mm)", checked: pageConf.size === k,
- action: function () { pageConf.size = k; applyPageSetup(); afterEdit(true); }
- };
- });
- }
- /* ---------- References ---------- */
- // a footnote: the reference in the text, its note under a rule at the
- // foot of the page (renderFootnoteAreas), where it is typed
- function insertFootnote() {
- if (inHeaderFooter()) return;
- restoreSel();
- var sel = window.getSelection();
- if (!sel || !sel.rangeCount || !editor.contains(sel.getRangeAt(0).startContainer)) return;
- var id = "fn" + Date.now().toString(36) + Math.random().toString(36).substring(2, 5);
- footnotes[id] = "<p><br></p>";
- // placed with a Range, not insertHTML: Chrome lifts a non-editable
- // element out of the paragraph it is inserted into
- var range = sel.getRangeAt(0);
- range.deleteContents();
- var ref = document.createElement("sup");
- ref.className = "doc-fnref";
- ref.setAttribute("data-fn", id);
- ref.setAttribute("contenteditable", "false");
- ref.textContent = "*";
- range.insertNode(ref);
- range.setStartAfter(ref);
- range.collapse(true);
- sel.removeAllRanges();
- sel.addRange(range);
- savedRange = range.cloneRange();
- afterEdit(true);
- // lay the pages out now rather than on the counter's timer, which
- // would redraw the note areas - and drop the caret - after it is
- // put in the new note
- clearTimeout(countTimer);
- updateCounts();
- var fn = pageEl.querySelector('.doc-fn-area .doc-fn[data-fn="' + id + '"]');
- if (!fn) return;
- fn.focus();
- try {
- var r = document.createRange();
- r.selectNodeContents(fn.querySelector("p") || fn);
- r.collapse(false);
- var s = window.getSelection();
- s.removeAllRanges();
- s.addRange(r);
- } catch (err) { }
- fn.scrollIntoView({ block: "nearest" });
- }
- /* A table of contents is ordinary paragraphs: a "Contents" title, then
- each heading's text, a right tab with a dot leader at the margin, and
- the page it is on as the layout has it now. That is what Word stores
- once a TOC field is updated, so the layout, the PDF and the writers
- treat it as plain text with real tab stops (the DOCX writer wraps it
- in a TOC field Word can update). The .doc-toc class marks the lines,
- data-toc-level the heading level of an entry and data-toc-max the
- deepest heading the table lists (3 when absent; an imported table
- keeps its own range, Google Docs lists 1-6); a run of them is one
- table, which the editor frames with an "Update table" tab on top
- while the caret or the mouse is in it (tocOverlay, not saved). */
- var ZWSP = String.fromCharCode(0x200B);
- function tocSelector(max) {
- var sel = ["h1:not(.doc-title)"];
- for (var l = 2; l <= max; l++) sel.push("h" + l);
- return sel.join(", ");
- }
- // the deepest heading level a table lists
- function tocMaxOf(lines) {
- var max = 0;
- (lines || []).forEach(function (p) {
- var v = parseInt(p.getAttribute("data-toc-max"), 10);
- if (v > max) max = v;
- });
- return max >= 1 ? Math.min(6, max) : 3;
- }
- function hasToc() { return !!editor.querySelector("p.doc-toc"); }
- // a heading's text, all of it when a page boundary divides it
- function headingText(h) {
- var parts = [];
- var el = h;
- for (var guard = 0; el && guard < 50; guard++) {
- var c = el.cloneNode(true);
- var drop = c.querySelectorAll("sup.doc-fnref, .doc-autobreak");
- for (var i = 0; i < drop.length; i++) drop[i].parentNode.removeChild(drop[i]);
- parts.push(c.textContent || "");
- var tok = el.getAttribute("data-split");
- el = tok ? editor.querySelector('[data-split-of="' + tok + '"]') : null;
- }
- return parts.join("").split(ZWSP).join("").replace(/\s+/g, " ").trim();
- }
- function tocEntries(max) {
- var heads = editor.querySelectorAll(tocSelector(max || 3));
- var out = [];
- for (var i = 0; i < heads.length; i++) {
- var h = heads[i];
- if (h.closest(".doc-fn-area, .doc-hf") || h.classList.contains("doc-split-tail")) continue;
- var text = headingText(h);
- if (!text) continue;
- out.push({
- level: parseInt(h.tagName.substring(1), 10),
- text: text,
- page: pageIndexAt(offsetTopInPage(h)) + 1
- });
- }
- return out;
- }
- function tocLinesHtml(entries, max) {
- max = max || 3;
- var geo = pageGeometry();
- var tabPt = Math.round(geo.contentW * 0.75 * 10) / 10;
- var maxAttr = max !== 3 ? ' data-toc-max="' + max + '"' : "";
- if (!entries.length) {
- return '<p class="doc-toc" data-toc-level="0"' + maxAttr + ' style="margin-bottom:3pt;color:#80868b;">' +
- esc("No headings found - use Heading 1-" + max + " for the lines this table should list") + "</p>";
- }
- // the top level present starts at the margin (a document whose
- // chapters are Heading 2 has no empty first step)
- var top = 9;
- entries.forEach(function (e) { top = Math.min(top, e.level); });
- var html = "";
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i];
- html += '<p class="doc-toc" data-toc-level="' + e.level + '"' + maxAttr + ' data-tabs="right:' + tabPt + ':dot" style="margin-left:' +
- ((e.level - top) * 14) + 'pt;margin-bottom:3pt;">' + esc(e.text) + '<span class="doc-tab"></span>' + e.page + "</p>";
- }
- return html;
- }
- function tocSignature(entries) {
- return entries.map(function (e) { return e.level + "|" + e.page + "|" + e.text; }).join("\n");
- }
- /* the tables in the document: each a run of .doc-toc paragraphs that
- follow one another (a page spacer between two of them is the layout's) */
- function tocGroups() {
- var groups = [];
- var cur = null, last = null;
- var lines = editor.querySelectorAll("p.doc-toc");
- for (var i = 0; i < lines.length; i++) {
- var p = lines[i];
- if (p.closest(".doc-hf")) continue;
- var prev = p.previousElementSibling;
- while (prev && prev.classList.contains("doc-autobreak")) prev = prev.previousElementSibling;
- if (!cur || prev !== last) {
- cur = [];
- groups.push(cur);
- }
- cur.push(p);
- last = p;
- }
- return groups;
- }
- function tocGroupOf(node) {
- var p = node && node.nodeType === 1 ? node : (node ? node.parentNode : null);
- p = p && p.closest ? p.closest("p.doc-toc") : null;
- if (!p || !editor.contains(p)) return null;
- var groups = tocGroups();
- for (var i = 0; i < groups.length; i++) {
- if (groups[i].indexOf(p) >= 0) return groups[i];
- }
- return null;
- }
- function insertToc() {
- if (inHeaderFooter()) return;
- if (hasToc()) { updateToc(); return; }
- var entries = tocEntries();
- restoreSel();
- try {
- document.execCommand("insertHTML", false,
- '<p class="doc-toc doc-toc-title" style="font-size:16pt;margin-bottom:6pt;">Contents</p>' +
- tocLinesHtml(entries) + "<p><br></p>");
- } catch (e) { return; }
- afterEdit(true);
- updatePageGuides();
- // the table itself moved the headings: number it again
- updateToc(true);
- if (!entries.length) OfficeApp.setStatus("Table of contents added - give your headings a Heading 1-3 style, then click Update table", "info", 6000);
- }
- function updateTocQuiet() { updateToc(true); }
- /* updateToc rebuilds every table (or only `only`, one group) from the
- headings. The new lines can push the headings to other pages, so the
- numbers are taken again until they stop changing. */
- function updateToc(quiet, only) {
- if (!hasToc()) return;
- var groups = tocGroups();
- if (only) {
- var first = only[0];
- groups = groups.filter(function (g) { return g.indexOf(first) >= 0; });
- }
- if (!groups.length) return;
- // the headings each table lists, from the pages as laid out now
- var maxes = groups.map(tocMaxOf);
- function entriesByMax() {
- var out = {};
- maxes.forEach(function (m) { if (!out[m]) out[m] = tocEntries(m); });
- return out;
- }
- var entries = entriesByMax();
- // then every page split is undone: the lines replaced may be cut in two
- removeAutoBreaks(editor);
- groups = tocGroups();
- if (only) groups = groups.filter(function (g) { return g.indexOf(first) >= 0; });
- if (!groups.length) return;
- // where each table goes once its lines are gone: the first old line
- var anchors = groups.map(function (g, i) {
- var lines = g.filter(function (p) { return !p.classList.contains("doc-toc-title"); });
- var title = g.filter(function (p) { return p.classList.contains("doc-toc-title"); })[0] || null;
- return { lines: lines, after: title, before: lines.length ? lines[0] : null, max: maxes[i] || 3 };
- });
- var caretInside = groups.some(function (g) {
- var sel = window.getSelection();
- return sel && sel.rangeCount && g.some(function (p) { return p.contains(sel.anchorNode); });
- });
- var sig = null;
- for (var pass = 0; pass < 4; pass++) {
- if (pass > 0) entries = entriesByMax();
- var s = Object.keys(entries).sort().map(function (m) { return m + ":" + tocSignature(entries[m]); }).join("\n");
- if (s === sig) break;
- sig = s;
- anchors.forEach(function (a) {
- var holder = document.createElement("div");
- holder.innerHTML = tocLinesHtml(entries[a.max], a.max);
- var fresh = Array.prototype.slice.call(holder.children);
- var ref = a.before || (a.after ? a.after.nextSibling : null);
- var parent = (a.before || a.after).parentNode;
- fresh.forEach(function (n) { parent.insertBefore(n, ref); });
- a.lines.forEach(function (p) { if (p.parentNode) p.parentNode.removeChild(p); });
- a.lines = fresh;
- a.before = fresh[0] || null;
- });
- dirtyFromY = null;
- updatePageGuides();
- }
- if (caretInside && anchors[0].lines[0]) {
- // the caret's line is gone: put it at the start of the new table
- try {
- var r = document.createRange();
- r.setStart(anchors[0].lines[0], 0);
- r.collapse(true);
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(r);
- savedRange = r.cloneRange();
- } catch (err) { }
- }
- afterEdit(true);
- scheduleTocOverlay();
- if (quiet !== true) OfficeApp.setStatus("Table of contents updated");
- }
- // Ctrl+click on an entry: go to the heading it lists
- function followTocEntry(p) {
- if (p.classList.contains("doc-toc-title")) return false;
- var level = parseInt(p.getAttribute("data-toc-level"), 10);
- if (level === 0) return false; // the "no headings" line
- var hit = null;
- // an imported entry links to its heading's bookmark
- var link = p.querySelector('a[href^="#"]');
- if (link) {
- try {
- var target = editor.querySelector("#" + CSS.escape(decodeURIComponent(link.getAttribute("href").substring(1))));
- if (target && /^H[1-6]$/.test(target.tagName)) hit = target;
- } catch (err) { }
- }
- var c = p.cloneNode(true);
- var tabs = c.querySelectorAll(".doc-tab");
- if (tabs.length) {
- // the text before the tab; the page number follows it
- var t = tabs[tabs.length - 1];
- var cut = document.createRange();
- cut.setStartBefore(t);
- cut.setEndAfter(c.lastChild);
- cut.deleteContents();
- }
- var want = (c.textContent || "").split(ZWSP).join("").replace(/\s+/g, " ").trim();
- var heads = editor.querySelectorAll("h1, h2, h3, h4, h5, h6");
- for (var i = 0; i < heads.length && !hit; i++) {
- var h = heads[i];
- if (h.classList.contains("doc-split-tail") || headingText(h) !== want) continue;
- if (!(level > 0) || parseInt(h.tagName.substring(1), 10) === level) hit = h;
- }
- if (!hit) {
- OfficeApp.setStatus("That heading is not in the document any more - update the table", "info", 4000);
- return true;
- }
- try {
- var r = document.createRange();
- r.setStart(hit, 0);
- r.collapse(true);
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(r);
- savedRange = r.cloneRange();
- } catch (err) { }
- hit.scrollIntoView({ block: "start" });
- return true;
- }
- /* The frame and tab of the table the caret or the mouse is in: drawn
- in #page (layout px, zoomed with it) above the text, one box per
- page the table covers, the tab above the first. Editor chrome only -
- the PDF exporter skips .doc-toc-frame and print hides it. */
- var tocOverlay = null, tocHover = null, tocHoverTimer = null, tocOverlayTimer = null;
- function scheduleTocOverlay() {
- if (tocOverlayTimer) return;
- tocOverlayTimer = setTimeout(function () {
- tocOverlayTimer = null;
- drawTocOverlay();
- }, 0);
- }
- function caretTocGroup() {
- var sel = window.getSelection();
- if (!sel || !sel.rangeCount || !editor.contains(sel.anchorNode)) return null;
- return tocGroupOf(sel.anchorNode);
- }
- function drawTocOverlay() {
- if (!pageEl) return;
- var group = caretTocGroup();
- var active = !!group;
- if (!group && tocHover && tocHover[0] && tocHover[0].isConnected) group = tocGroupOf(tocHover[0]);
- if (!group) {
- if (tocOverlay) tocOverlay.style.display = "none";
- return;
- }
- if (!tocOverlay) {
- tocOverlay = document.createElement("div");
- tocOverlay.className = "doc-toc-frame of-noprint";
- tocOverlay.addEventListener("mouseenter", function () { clearTimeout(tocHoverTimer); });
- tocOverlay.addEventListener("mouseleave", leaveTocHover);
- pageEl.appendChild(tocOverlay);
- }
- tocOverlay.style.display = "";
- tocOverlay.classList.toggle("active", active);
- // one box per page the table is on
- var boxes = [];
- group.forEach(function (p) {
- var top = offsetTopInPage(p);
- var pg = pageIndexAt(top);
- var b = boxes.length ? boxes[boxes.length - 1] : null;
- if (!b || b.page !== pg) boxes.push(b = { page: pg, top: top, bottom: top });
- b.bottom = Math.max(b.bottom, top + p.offsetHeight);
- });
- var left = editor.offsetLeft - 6;
- var width = editor.offsetWidth + 12;
- var html = "";
- boxes.forEach(function (b, i) {
- html += '<div class="doc-toc-box" style="left:' + left + "px;top:" + (b.top - 4) + "px;width:" + width +
- "px;height:" + (b.bottom - b.top + 8) + 'px;"></div>';
- if (i === 0) {
- html += '<div class="doc-toc-tab" style="left:' + left + "px;top:" + (b.top - 4) + 'px;">' +
- '<button type="button" class="doc-toc-update" title="Update the table from the headings (Ctrl+click an entry to go to its heading)">' +
- '<i class="sync alternate icon"></i>Update table</button></div>';
- }
- });
- tocOverlay.innerHTML = html;
- var btn = tocOverlay.querySelector(".doc-toc-update");
- // keep the caret where it is: the button never takes the focus
- btn.addEventListener("mousedown", function (e) { e.preventDefault(); });
- btn.addEventListener("click", function (e) {
- e.preventDefault();
- var g = caretTocGroup() || (tocHover && tocHover[0] && tocHover[0].isConnected ? tocGroupOf(tocHover[0]) : null);
- updateToc(false, g || undefined);
- });
- }
- function leaveTocHover() {
- clearTimeout(tocHoverTimer);
- // time to cross from the lines to the tab above them
- tocHoverTimer = setTimeout(function () {
- tocHover = null;
- scheduleTocOverlay();
- }, 400);
- }
- function trackTocHover(e) {
- var p = e.target && e.target.closest ? e.target.closest("p.doc-toc") : null;
- if (p && editor.contains(p)) {
- clearTimeout(tocHoverTimer);
- if (!tocHover || tocHover.indexOf(p) < 0) {
- tocHover = tocGroupOf(p);
- scheduleTocOverlay();
- }
- } else if (tocHover && !(e.target.closest && e.target.closest(".doc-toc-frame"))) {
- leaveTocHover();
- }
- }
- /* ---------- Review / View ---------- */
- function toggleSpellcheck() {
- editor.spellcheck = !editor.spellcheck;
- OfficeApp.setSetting("spellcheck", editor.spellcheck);
- editor.focus();
- OfficeRibbon.refresh();
- }
- function wordCountDialog() {
- var text = editor.innerText || "";
- var sel = window.getSelection();
- var selText = (sel && !sel.isCollapsed && sel.rangeCount && editor.contains(sel.getRangeAt(0).commonAncestorContainer)) ?
- sel.toString() : "";
- var count = function (t) {
- return {
- words: (t.match(/\S+/g) || []).length,
- chars: t.replace(/\n/g, "").length,
- charsNoSp: t.replace(/\s/g, "").length,
- paras: (t.split(/\n+/).filter(function (x) { return x.trim(); })).length
- };
- };
- var all = count(text);
- var rows = [
- ["Pages", String(lastPages.length || 1)],
- ["Words", all.words],
- ["Characters (no spaces)", all.charsNoSp],
- ["Characters (with spaces)", all.chars],
- ["Paragraphs", all.paras]
- ];
- if (selText) {
- var s = count(selText);
- rows.push(["Words in the selection", s.words]);
- }
- var html = '<table class="doc-wc">' + rows.map(function (r) {
- return "<tr><td>" + esc(r[0]) + "</td><td>" + esc(String(r[1])) + "</td></tr>";
- }).join("") + "</table>";
- OfficeApp.dialog({ title: "Word count", body: html, buttons: [{ label: "Close", primary: true }] });
- }
- // fit the page to the window's width; transient = not the person's
- // chosen zoom (a phone does this by itself)
- function fitPageWidth(transient) {
- var avail = workspaceEl.clientWidth - 28;
- var w = pageEl.offsetWidth;
- if (!(avail > 0 && w > 0)) return;
- var z = Math.floor(avail / w * 100);
- OfficeApp.setZoom(Math.max(25, Math.min(transient ? 100 : 400, z)), { transient: !!transient });
- }
- /* ---------- Insert / Draw: drawings ---------- */
- function drawingDialog(penId) {
- if (inHeaderFooter()) return;
- OfficeSketch.open({
- title: "Drawing", pen: penId,
- onInsert: function (blob, w, h) {
- OfficeApp.blobToSrc(blob, "drawing.png", function (src) {
- // shown at the size it was drawn, never wider than the text
- var geo = pageGeometry();
- var scale = Math.min(1, geo.contentW / w);
- insertImage(src, w * scale, h * scale);
- }, function (msg) { OfficeApp.toast(msg, "error"); });
- }
- });
- }
- function scheduleToolbarState() {
- clearTimeout(stateTimer);
- stateTimer = setTimeout(updateToolbarState, 90);
- }
- function updateToolbarState() {
- var states = ["bold", "italic", "underline", "strikeThrough", "subscript", "superscript",
- "justifyLeft", "justifyCenter", "justifyRight", "justifyFull",
- "insertUnorderedList", "insertOrderedList"];
- // by class rather than under #toolbar: a folded ribbon group shows
- // its buttons in a popup outside it
- var picAlign = selectedImg && editor.contains(selectedImg) ? pictureAlign(selectedImg) : null;
- states.forEach(function (c) {
- var on = false;
- if (picAlign && PICTURE_ALIGN[c]) {
- $('.of-rb-btn[data-cmd="' + c + '"]').toggleClass("active", PICTURE_ALIGN[c] === picAlign);
- return;
- }
- try { on = document.queryCommandState(c); } catch (e) { }
- $('.of-rb-btn[data-cmd="' + c + '"]').toggleClass("active", !!on);
- });
- // font family
- var fn = "";
- try { fn = document.queryCommandValue("fontName") || ""; } catch (e) { }
- fn = String(fn).replace(/['"]/g, "").split(",")[0].trim();
- if (fn && $fontSel.find('option[value="' + fn + '"]').length) $fontSel.val(fn);
- // font size + paragraph style from the caret position
- var n = savedRange ? savedRange.startContainer : null;
- // a selection that starts between nodes is about the node after it
- if (n && n.nodeType === 1 && !savedRange.collapsed && savedRange.startOffset < n.childNodes.length) {
- n = n.childNodes[savedRange.startOffset];
- }
- if (n && n.nodeType === 3) n = n.parentNode;
- if (n && n.nodeType === 1 && editor.contains(n)) {
- try {
- var px = parseFloat(window.getComputedStyle(n).fontSize);
- var pt = String(Math.round(px * 72 / 96));
- if ($sizeSel.find('option[value="' + pt + '"]').length) $sizeSel.val(pt);
- } catch (e) { }
- var b = n.closest ? n.closest("h1,h2,h3,h4,p,pre,blockquote,li,div") : null;
- var v = "p";
- if (b && editor.contains(b)) {
- if (b.classList.contains("doc-title")) v = "title";
- else if (/^H[1-4]$/.test(b.tagName)) v = b.tagName.toLowerCase();
- // characters given a style of their own (applyCharStyle)
- var cst = n.closest("span[data-cstyle]");
- if (cst && b.contains(cst)) v = cst.getAttribute("data-cstyle");
- }
- if (b && editor.contains(b)) {
- if (b.tagName === "BLOCKQUOTE" || b.closest("blockquote")) v = v === "p" ? "blockquote" : v;
- if (b.tagName === "PRE") v = "pre";
- }
- $styleSel.val(v);
- currentStyle = v;
- // checklist button state
- var li = n.closest ? n.closest("li") : null;
- var inCheck = !!(li && li.parentElement && li.parentElement.classList.contains("of-checklist"));
- $('.of-rb-btn[data-cmd="checklist"]').toggleClass("active", inCheck);
- if (inCheck) $('.of-rb-btn[data-cmd="insertUnorderedList"]').removeClass("active");
- }
- if (window.OfficeRibbon) OfficeRibbon.refresh();
- }
- /* ================= links ================= */
- // unwrap a link, keeping its text
- function removeLink(a) {
- if (!a || !a.parentNode) return;
- while (a.firstChild) a.parentNode.insertBefore(a.firstChild, a);
- a.parentNode.removeChild(a);
- afterEdit(true);
- }
- function linkDialog() {
- if (inHeaderFooter()) return;
- var existing = null;
- var n = savedRange ? savedRange.commonAncestorContainer : null;
- while (n && n !== editor) {
- if (n.nodeType === 1 && n.tagName === "A") { existing = n; break; }
- n = n.parentNode;
- }
- var initText = existing ? existing.textContent : (savedRange ? savedRange.toString() : "");
- var initUrl = existing ? (existing.getAttribute("href") || "") : "";
- var $b = $("<div></div>");
- $b.append("<label>Text to display</label>");
- var $text = $('<input type="text" class="lnk-text">').val(initText);
- $b.append($text);
- $b.append("<label>Link URL</label>");
- var $url = $('<input type="text" class="lnk-url" placeholder="https://example.com">').val(initUrl);
- $b.append($url);
- var buttons = [{ label: "Cancel" }];
- if (existing) {
- buttons.push({
- label: "Remove link", danger: true,
- action: function (close) {
- close();
- removeLink(existing);
- }
- });
- }
- buttons.push({
- label: existing ? "Apply" : "Insert", primary: true,
- action: function (close, $body) {
- var text = $body.find(".lnk-text").val().trim();
- var href = $body.find(".lnk-url").val().trim();
- close();
- if (!href) return;
- if (!/^([a-z][a-z0-9+.-]*:|\/|#)/i.test(href)) href = "https://" + href;
- if (existing) {
- existing.setAttribute("href", href);
- if (text) existing.textContent = text;
- afterEdit(true);
- } else {
- restoreSel();
- var html = '<a href="' + esc(href) + '">' + esc(text || href) + "</a>";
- try { document.execCommand("insertHTML", false, html); } catch (e) { }
- afterEdit(true);
- }
- }
- });
- var d = OfficeApp.dialog({
- title: existing ? "Edit link" : "Insert link",
- body: $b,
- buttons: buttons
- });
- d.body.find(".lnk-url").trigger("focus");
- }
- /* ================= images ================= */
- function imageMenuItems() {
- var items = [];
- // no ArozOS storage to browse in the standalone web edition
- if (OfficePlatform.hasBackend()) {
- items.push({ label: "From ArozOS storage...", icon: "hdd outline", action: insertImageFromStorage });
- }
- items.push({ label: "From this device...", icon: "upload", action: function () { $("#deviceImageInput").trigger("click"); } });
- items.push({ label: "From URL...", icon: "world", action: insertImageFromUrl });
- return items;
- }
- function insertImage(src, w, h) {
- if (!src) return;
- restoreSel();
- // the document states picture sizes in points
- var size = (w > 0 && h > 0) ?
- "width:" + Math.round(w * 0.75 * 10) / 10 + "pt;height:" + Math.round(h * 0.75 * 10) / 10 + "pt;" : "";
- try {
- document.execCommand("insertHTML", false,
- '<img src="' + esc(src) + '" style="' + size + 'max-width:100%;">');
- } catch (e) { }
- afterEdit(true);
- }
- function insertImageFromStorage() {
- try {
- OfficePlatform.pickOpen({
- filter: ["png", "jpg", "jpeg", "gif", "webp", "bmp", "svg"],
- memoryKey: "media"
- }, function (files) {
- // reference the storage file - the server reads it into the
- // saved file, keeping edits and saves lightweight
- insertImage(OfficeApp.mediaUrl(files[0].filepath));
- });
- } catch (e) {
- OfficeApp.toast("File selector unavailable outside ArozOS", "error");
- }
- }
- function insertImageFromUrl() {
- OfficeApp.prompt("Insert image from URL", "Image URL", "", function (v) {
- if (v) insertImage(v.trim());
- });
- }
- function selectImage(img) {
- deselectImage();
- selectedImg = img;
- img.classList.add("of-selimg");
- // put the caret right after the image so Delete/typing behaves naturally
- try {
- var r = document.createRange();
- r.setStartAfter(img);
- r.collapse(true);
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(r);
- savedRange = r.cloneRange();
- } catch (e) { }
- imgHandle = document.createElement("div");
- imgHandle.className = "of-img-handle of-noprint";
- imgHandle.title = "Drag to resize";
- document.body.appendChild(imgHandle);
- positionImgHandle();
- imgHandle.addEventListener("pointerdown", startImgResize);
- if (window.OfficeTextEditBar && OfficeTextEditBar.isVisible()) OfficeTextEditBar.hide();
- // the Picture Format tab comes and goes with the selection
- if (window.OfficeRibbon) OfficeRibbon.refresh();
- scheduleToolbarState();
- }
- function deselectImage() {
- if (selectedImg) {
- selectedImg.classList.remove("of-selimg");
- if (!selectedImg.getAttribute("class")) selectedImg.removeAttribute("class");
- selectedImg = null;
- }
- var had = !!imgHandle;
- if (imgHandle) {
- if (imgHandle.parentNode) imgHandle.parentNode.removeChild(imgHandle);
- imgHandle = null;
- }
- if (had && window.OfficeRibbon) OfficeRibbon.refresh();
- }
- function positionImgHandle() {
- if (!selectedImg || !imgHandle) return;
- var r = selectedImg.getBoundingClientRect();
- imgHandle.style.left = (r.right - 7) + "px";
- imgHandle.style.top = (r.bottom - 7) + "px";
- }
- function startImgResize(e) {
- if (!selectedImg) return;
- e.preventDefault();
- e.stopPropagation();
- var startX = e.clientX;
- var startW = selectedImg.getBoundingClientRect().width; // visual px
- var z = (OfficeApp.getZoom() || 100) / 100;
- // keep the frame's own shape: a cropped (or stretched) picture is
- // not the shape of its source, which height:auto would bring back
- var cs = window.getComputedStyle(selectedImg);
- var cw = parseFloat(cs.width), ch = parseFloat(cs.height);
- var ratio = cw > 0 && ch > 0 ? ch / cw : 0;
- function move(ev) {
- var w = Math.max(24, (startW + (ev.clientX - startX)) / z);
- selectedImg.style.width = Math.round(w) + "px";
- selectedImg.style.height = ratio ? Math.round(w * ratio) + "px" : "auto";
- positionImgHandle();
- }
- var realign = keepPictureAlign(selectedImg);
- function up() {
- document.removeEventListener("pointermove", move);
- document.removeEventListener("pointerup", up);
- afterEdit(true);
- realign();
- }
- document.addEventListener("pointermove", move);
- document.addEventListener("pointerup", up);
- }
- /* ================= picture format =================
- What the Picture Format tab, the picture context menu and a double
- click work with. Everything is stored the way the .docx reader and
- writer already speak it, so it saves and reopens unchanged:
- size width / height on the img
- crop object-fit:fill + object-view-box:inset(t% r% b% l%)
- (DrawingML srcRect)
- border border:<w>pt solid <color> (the picture outline)
- wrap inline (no class), or img.doc-anchor: display:block (top
- and bottom, placed by margin-left) or float:left/right
- (square) - see the docx reader's anchor import */
- function pictureZoom() { return (OfficeApp.getZoom() || 100) / 100; }
- /* object-view-box is Chromium only: Firefox and Safari drop it from the
- style, so there the crop lives in data-crop (the same inset() text)
- and is painted as the picture's background instead - the picture's
- own content is pushed out of its box. cleanedHtml turns it back into
- object-view-box, so the saved document is the same in every browser. */
- var NATIVE_CROP = !!(window.CSS && CSS.supports && CSS.supports("object-view-box", "inset(1%)"));
- var CROP_PAINT_PROPS = ["object-fit", "object-position", "background-image", "background-repeat",
- "background-origin", "background-clip", "background-size", "background-position"];
- var INSET_RE = /inset\(\s*([-\d.]+)%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*\)/;
- function rawViewBox(img) {
- var m = /object-view-box\s*:\s*(inset\([^)]*\))/i.exec(img.getAttribute("style") || "");
- return m ? m[1] : "";
- }
- function paintCropFallback(img, c) {
- var w = 100 - c[1] - c[3], h = 100 - c[0] - c[2];
- var f = function (v) { return Math.round(v * 1000) / 1000 + "%"; };
- img.style.setProperty("object-fit", "none");
- img.style.setProperty("object-position", "-100000px -100000px");
- img.style.setProperty("background-image", 'url("' + String(img.src).replace(/"/g, "%22") + '")');
- img.style.setProperty("background-repeat", "no-repeat");
- img.style.setProperty("background-origin", "content-box");
- img.style.setProperty("background-clip", "content-box");
- img.style.setProperty("background-size", f(10000 / w) + " " + f(10000 / h));
- img.style.setProperty("background-position",
- f(c[1] + c[3] > 0 ? 100 * c[3] / (c[1] + c[3]) : 0) + " " +
- f(c[0] + c[2] > 0 ? 100 * c[0] / (c[0] + c[2]) : 0));
- }
- // pictures loaded or pasted with an object-view-box crop the browser
- // cannot show get the fallback painting
- function upgradeCrops(root) {
- if (NATIVE_CROP || !root) return;
- var list = root.querySelectorAll('img[style*="object-view-box"]:not([data-crop])');
- for (var i = 0; i < list.length; i++) {
- var v = rawViewBox(list[i]);
- if (!v) continue;
- list[i].setAttribute("data-crop", v);
- paintCropFallback(list[i], pictureCrop(list[i]));
- }
- }
- // the saved form of a fallback-painted crop (on a copy of the picture)
- function canonicalCrop(img) {
- var v = img.getAttribute("data-crop");
- if (v === null) return;
- img.removeAttribute("data-crop");
- CROP_PAINT_PROPS.forEach(function (p) { img.style.removeProperty(p); });
- var st = (img.getAttribute("style") || "").replace(/\s*;?\s*$/, "");
- img.setAttribute("style", (st ? st + "; " : "") + "object-fit: fill; object-view-box: " + v + ";");
- }
- function pictureCrop(img) {
- var m = INSET_RE.exec(img.getAttribute("data-crop") ||
- img.style.getPropertyValue("object-view-box") || rawViewBox(img));
- if (!m) return [0, 0, 0, 0];
- var t = parseFloat(m[1]) || 0;
- var r = m[2] !== undefined ? parseFloat(m[2]) || 0 : t;
- var b = m[3] !== undefined ? parseFloat(m[3]) || 0 : t;
- var l = m[4] !== undefined ? parseFloat(m[4]) || 0 : r;
- return [t, r, b, l];
- }
- function setPictureCrop(img, c) {
- if (c[0] <= 0 && c[1] <= 0 && c[2] <= 0 && c[3] <= 0) {
- img.style.removeProperty("object-view-box");
- img.style.removeProperty("object-fit");
- if (img.hasAttribute("data-crop")) {
- img.removeAttribute("data-crop");
- CROP_PAINT_PROPS.forEach(function (p) { img.style.removeProperty(p); });
- }
- return;
- }
- var f = function (v) { return Math.round(v * 1000) / 1000 + "%"; };
- if (!NATIVE_CROP) {
- img.setAttribute("data-crop", "inset(" + f(c[0]) + " " + f(c[1]) + " " + f(c[2]) + " " + f(c[3]) + ")");
- paintCropFallback(img, c);
- return;
- }
- img.style.setProperty("object-fit", "fill");
- img.style.setProperty("object-view-box", "inset(" + f(c[0]) + " " + f(c[1]) + " " + f(c[2]) + " " + f(c[3]) + ")");
- }
- // the picture's wrapping: "inline", "top" (top and bottom), "left" or
- // "right" (text flows round it)
- function pictureWrap(img) {
- if (!img.classList.contains("doc-anchor")) return "inline";
- var fl = img.style.cssFloat || img.style.float;
- return fl === "left" || fl === "right" ? fl : "top";
- }
- // the width the picture lays out in (layout px, unzoomed)
- function pictureColumnWidth(img) {
- var host = img.parentElement;
- while (host && host !== editor && window.getComputedStyle(host).display.indexOf("inline") === 0) {
- host = host.parentElement;
- }
- host = host || editor;
- var cs = window.getComputedStyle(host);
- return host.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0);
- }
- function pictureAlign(img) {
- var wrap = pictureWrap(img);
- if (wrap === "left" || wrap === "right") return wrap;
- if (wrap === "top") {
- // placed by its margin: compare it with the room beside it
- var mlv = img.style.marginLeft || "";
- var ml = (parseFloat(mlv) || 0) * (/pt$/.test(mlv) ? 4 / 3 : 1);
- var free = pictureColumnWidth(img) - img.offsetWidth;
- if (free <= 3) return "left";
- if (Math.abs(ml - free / 2) < 3) return "center";
- return ml >= free - 3 ? "right" : "left";
- }
- var blk = pictureBlock(img, false);
- var ta = blk ? window.getComputedStyle(blk).textAlign : "left";
- if (ta === "center") return "center";
- if (ta === "right" || ta === "end") return "right";
- return "left";
- }
- // the paragraph an inline picture sits in (made when create is set and
- // the picture has none, e.g. one dropped straight into the body)
- function pictureBlock(img, create) {
- var n = img.parentElement;
- while (n && n !== editor) {
- if (/^(P|DIV|H[1-6]|LI|TD|TH|BLOCKQUOTE|PRE)$/.test(n.tagName)) return n;
- n = n.parentElement;
- }
- if (!create) return null;
- var p = document.createElement("p");
- img.parentNode.insertBefore(p, img);
- p.appendChild(img);
- return p;
- }
- /* Align a picture. An inline one follows its paragraph's alignment; an
- anchored one is its own box, which text-align cannot move (that was
- the bug: Center wrote text-align onto the img and nothing happened),
- so it is placed by its margin - the docx writer's horizontal offset -
- or by the side it floats to. */
- function alignPicture(img, how) {
- if (!img) return;
- var wrap = pictureWrap(img);
- if (wrap === "inline") {
- var blk = pictureBlock(img, true);
- blk.style.textAlign = how === "justify" ? "left" : how;
- } else if (wrap === "left" || wrap === "right") {
- if (how === "center") {
- setPictureWrap(img, "top");
- alignPicture(img, "center");
- return;
- }
- setPictureWrap(img, how === "right" ? "right" : "left");
- } else {
- var free = Math.max(0, pictureColumnWidth(img) - img.offsetWidth);
- var x = how === "center" ? free / 2 : how === "right" ? free : 0;
- if (x > 0) img.style.marginLeft = Math.round(x * 0.75 * 10) / 10 + "pt";
- else img.style.removeProperty("margin-left");
- }
- positionImgHandle();
- afterEdit(true);
- OfficeRibbon.refresh();
- }
- function setPictureWrap(img, wrap) {
- var s = img.style;
- ["float", "display", "margin-left", "margin-right", "margin-top", "max-width"].forEach(function (p) {
- s.removeProperty(p);
- });
- if (wrap === "inline") {
- img.classList.remove("doc-anchor");
- } else {
- img.classList.add("doc-anchor");
- s.maxWidth = "none";
- if (wrap === "left" || wrap === "right") {
- s.cssFloat = wrap;
- s.marginLeft = "9pt";
- s.marginRight = "9pt";
- } else {
- s.display = "block";
- }
- }
- }
- function applyPictureWrap(wrap) {
- var img = selectedImg;
- if (!img) return;
- setPictureWrap(img, wrap);
- positionImgHandle();
- afterEdit(true);
- OfficeRibbon.refresh();
- }
- function pictureBorder(img) {
- var w = parseFloat(img.style.borderTopWidth) || 0;
- if (!w || img.style.borderTopStyle === "none") return null;
- var unitPt = /pt$/.test(img.style.borderTopWidth) ? 1 : 0.75;
- return { w: Math.round(w * unitPt * 100) / 100, color: img.style.borderTopColor || "#000000" };
- }
- function setPictureBorder(img, w, color) {
- if (!w || color === null) {
- img.style.removeProperty("border");
- } else {
- img.style.border = w + "pt solid " + (color || "#000000");
- }
- }
- function applyPictureBorderColor(c) {
- var img = selectedImg;
- if (!img) return;
- var cur = pictureBorder(img);
- setPictureBorder(img, c ? (cur ? cur.w : 1) : 0, c || null);
- afterEdit(true);
- positionImgHandle();
- }
- function pictureWeightItems() {
- return [0.75, 1.5, 2.25, 3, 4.5, 6].map(function (w) {
- return {
- label: w + " pt", checked: function () { var b = selectedImg && pictureBorder(selectedImg); return !!b && Math.abs(b.w - w) < 0.01; },
- action: function () {
- var img = selectedImg;
- if (!img) return;
- var cur = pictureBorder(img);
- setPictureBorder(img, w, cur ? img.style.borderTopColor : "#000000");
- afterEdit(true);
- positionImgHandle();
- }
- };
- }).concat([{ sep: true }, {
- label: "No border", action: function () {
- if (!selectedImg) return;
- setPictureBorder(selectedImg, 0);
- afterEdit(true);
- }
- }]);
- }
- function pictureWrapItems() {
- var opt = function (wrap, label, icon) {
- return {
- label: label, icon: icon,
- checked: function () { return !!selectedImg && pictureWrap(selectedImg) === wrap; },
- action: function () { applyPictureWrap(wrap); }
- };
- };
- return [
- opt("inline", "In line with text", "align left"),
- opt("left", "Square, on the left", "indent"),
- opt("right", "Square, on the right", "outdent"),
- opt("top", "Top and bottom", "bars")
- ];
- }
- function pictureAlignItems() {
- var opt = function (how, label, icon) {
- return {
- label: label, icon: icon,
- checked: function () { return !!selectedImg && pictureAlign(selectedImg) === how; },
- action: function () { alignPicture(selectedImg, how); }
- };
- };
- return [opt("left", "Align left", "align left"), opt("center", "Center", "align center"),
- opt("right", "Align right", "align right")];
- }
- // Reset picture: no crop, no border, its own size (within the column)
- function resetPicture(img) {
- if (!img) return;
- var realign = keepPictureAlign(img);
- setPictureCrop(img, [0, 0, 0, 0]);
- setPictureBorder(img, 0);
- if (img.naturalWidth > 0) {
- img.style.width = Math.round(img.naturalWidth * 0.75 * 10) / 10 + "pt";
- img.style.height = Math.round(img.naturalHeight * 0.75 * 10) / 10 + "pt";
- } else {
- img.style.removeProperty("width");
- img.style.removeProperty("height");
- }
- positionImgHandle();
- afterEdit(true);
- realign();
- }
- // an anchored picture is placed by its margin, so one centred or set
- // right has to be placed again once its width changes
- function keepPictureAlign(img) {
- var al = pictureWrap(img) === "top" ? pictureAlign(img) : null;
- return function () { if (al && al !== "left") alignPicture(img, al); };
- }
- function deleteSelectedPicture() {
- var img = selectedImg;
- if (!img) return;
- deselectImage();
- if (img.parentNode) img.parentNode.removeChild(img);
- afterEdit(true);
- }
- /* Crop: the whole picture in a dialog, with the kept part as a box to
- drag (by its edges, corners or middle) or to type in. The frame on
- the page shrinks with the crop, as Word's does, so what is left keeps
- its scale. */
- function cropPictureDialog(img) {
- if (!img) return;
- var start = pictureCrop(img);
- var crop = start.slice();
- var $b = $('<div class="doc-crop"></div>');
- var $stage = $('<div class="doc-crop-stage"></div>');
- var $pic = $('<img class="doc-crop-img" alt="">').attr("src", img.src);
- var $box = $('<div class="doc-crop-box"></div>');
- ["n", "s", "e", "w", "ne", "nw", "se", "sw"].forEach(function (h) {
- $box.append($('<span class="doc-crop-h"></span>').attr("data-h", h));
- });
- $stage.append($pic, $box);
- var $fields = $('<div class="doc-crop-fields"></div>');
- var names = ["Top", "Right", "Bottom", "Left"];
- names.forEach(function (n, i) {
- $fields.append($("<label></label>").text(n + " %").append(
- $('<input type="number" min="0" max="95" step="0.5">').attr("data-i", i)));
- });
- $b.append($stage, $fields);
- var W = 0, H = 0;
- function layout() {
- var nw = $pic[0].naturalWidth || 400, nh = $pic[0].naturalHeight || 300;
- var k = Math.min(440 / nw, 320 / nh, 1.5);
- W = Math.round(nw * k); H = Math.round(nh * k);
- $stage.css({ width: W + "px", height: H + "px" });
- $pic.css({ width: W + "px", height: H + "px" });
- draw();
- }
- function draw() {
- var bl = crop[3] * W / 100, bt = crop[0] * H / 100;
- // the kept part shows at full strength: the picture as the box's
- // background, shifted back by where the box sits (and its border)
- $box.css({
- left: bl + "px", top: bt + "px",
- right: (crop[1] * W / 100) + "px", bottom: (crop[2] * H / 100) + "px",
- backgroundImage: 'url("' + String(img.src).replace(/"/g, "%22") + '")',
- backgroundSize: W + "px " + H + "px",
- backgroundPosition: (-bl - 2) + "px " + (-bt - 2) + "px"
- });
- $fields.find("input").each(function () {
- var i = +this.getAttribute("data-i");
- if (document.activeElement !== this) this.value = Math.round(crop[i] * 10) / 10;
- });
- }
- // keep at least 5% of the picture each way
- function clampCrop() {
- for (var i = 0; i < 4; i++) crop[i] = Math.max(0, Math.min(95, crop[i]));
- if (crop[0] + crop[2] > 95) crop[2] = 95 - crop[0];
- if (crop[1] + crop[3] > 95) crop[1] = 95 - crop[3];
- }
- $fields.on("input", "input", function () {
- var v = parseFloat(this.value);
- crop[+this.getAttribute("data-i")] = isNaN(v) ? 0 : v;
- clampCrop();
- draw();
- });
- $stage.on("pointerdown", function (e) {
- var h = $(e.target).attr("data-h") || (e.target === $box[0] ? "move" : null);
- if (!h) return;
- e.preventDefault();
- var sx = e.clientX, sy = e.clientY, c0 = crop.slice();
- OfficeApp.beginDrag(e, {
- cursor: window.getComputedStyle(e.target).cursor,
- move: function (ev) {
- var dx = (ev.clientX - sx) * 100 / W, dy = (ev.clientY - sy) * 100 / H;
- crop = c0.slice();
- if (h === "move") {
- dx = Math.max(-c0[3], Math.min(c0[1], dx));
- dy = Math.max(-c0[0], Math.min(c0[2], dy));
- crop[3] = c0[3] + dx; crop[1] = c0[1] - dx;
- crop[0] = c0[0] + dy; crop[2] = c0[2] - dy;
- } else {
- if (h.indexOf("n") >= 0) crop[0] = c0[0] + dy;
- if (h.indexOf("s") >= 0) crop[2] = c0[2] - dy;
- if (h.indexOf("w") >= 0) crop[3] = c0[3] + dx;
- if (h.indexOf("e") >= 0) crop[1] = c0[1] - dx;
- }
- clampCrop();
- draw();
- }
- });
- });
- if ($pic[0].complete) setTimeout(layout, 0); else $pic.on("load", layout);
- OfficeApp.dialog({
- title: "Crop picture",
- body: $b,
- buttons: [
- { label: "Cancel" },
- { label: "Reset", action: function () { crop = [0, 0, 0, 0]; draw(); } },
- {
- label: "Crop", primary: true, action: function (close) {
- close();
- var realign = keepPictureAlign(img);
- // the frame keeps the picture's scale: it grows or
- // shrinks by the share of the picture now shown
- var r = img.getBoundingClientRect(), z = pictureZoom();
- var w = r.width / z, hgt = r.height / z;
- var oldW = (100 - start[1] - start[3]) / 100, oldH = (100 - start[0] - start[2]) / 100;
- var newW = (100 - crop[1] - crop[3]) / 100, newH = (100 - crop[0] - crop[2]) / 100;
- if (oldW > 0 && oldH > 0 && w > 0 && hgt > 0) {
- img.style.width = Math.round(w * newW / oldW * 0.75 * 10) / 10 + "pt";
- img.style.height = Math.round(hgt * newH / oldH * 0.75 * 10) / 10 + "pt";
- }
- setPictureCrop(img, crop);
- positionImgHandle();
- afterEdit(true);
- realign();
- }
- }
- ]
- });
- }
- /* Size & properties: width / height (aspect kept unless unlocked), the
- wrapping, and the alt text screen readers and the .docx carry. */
- function imageSizeDialog(img) {
- if (!img) return;
- var r = img.getBoundingClientRect(), z = pictureZoom();
- var curW = Math.round(r.width / z * 0.75 * 10) / 10, curH = Math.round(r.height / z * 0.75 * 10) / 10;
- var ratio = curW > 0 ? curH / curW : 0.75;
- var $b = $('<div class="doc-picprops"></div>');
- var $w = $('<input type="number" min="6" max="3000" step="0.5" class="img-w">').val(curW);
- var $h = $('<input type="number" min="6" max="3000" step="0.5" class="img-h">').val(curH);
- var $lock = $('<input type="checkbox" class="img-lock" checked>');
- var $row = $('<div class="doc-picprops-row"></div>');
- $row.append($("<label>Width (pt)</label>").append($w), $("<label>Height (pt)</label>").append($h));
- $b.append($row);
- $b.append($('<label class="doc-picprops-check"></label>').append($lock, " Keep the proportions"));
- var $wrap = $('<select class="img-wrap"></select>');
- pictureWrapItems().forEach(function (it, i) {
- $wrap.append($("<option></option>").val(["inline", "left", "right", "top"][i]).text(it.label));
- });
- $wrap.val(pictureWrap(img));
- $b.append($("<label>Text wrapping</label>").append($wrap));
- var $alt = $('<textarea rows="2" class="img-alt" placeholder="Describe the picture for people who cannot see it"></textarea>')
- .val(img.getAttribute("alt") || "");
- $b.append($("<label>Alt text</label>").append($alt));
- $w.on("input", function () { if ($lock.prop("checked")) $h.val(Math.round(this.value * ratio * 10) / 10); });
- $h.on("input", function () { if ($lock.prop("checked") && ratio) $w.val(Math.round(this.value / ratio * 10) / 10); });
- OfficeApp.dialog({
- title: "Picture size & properties",
- body: $b,
- buttons: [
- { label: "Cancel" },
- {
- label: "Reset size", action: function (close) {
- close();
- if (img.naturalWidth > 0) {
- var c = pictureCrop(img);
- img.style.width = Math.round(img.naturalWidth * (100 - c[1] - c[3]) / 100 * 0.75 * 10) / 10 + "pt";
- img.style.height = Math.round(img.naturalHeight * (100 - c[0] - c[2]) / 100 * 0.75 * 10) / 10 + "pt";
- }
- positionImgHandle();
- afterEdit(true);
- }
- },
- {
- label: "Apply", primary: true, action: function (close, $body) {
- var w = parseFloat($body.find(".img-w").val());
- var h = parseFloat($body.find(".img-h").val());
- var wrap = $body.find(".img-wrap").val();
- var alt = $body.find(".img-alt").val().trim();
- close();
- var realign = keepPictureAlign(img);
- if (w >= 6 && h >= 6) {
- img.style.width = w + "pt";
- img.style.height = h + "pt";
- }
- if (alt) img.setAttribute("alt", alt); else img.removeAttribute("alt");
- if (wrap !== pictureWrap(img)) setPictureWrap(img, wrap);
- else realign();
- positionImgHandle();
- afterEdit(true);
- OfficeRibbon.refresh();
- }
- }
- ]
- });
- }
- function pictureMenuItems(img) {
- return [
- { label: "Crop...", icon: "crop", action: function () { cropPictureDialog(img); } },
- { label: "Size & properties...", icon: "expand", action: function () { imageSizeDialog(img); } },
- { label: "Text wrapping", icon: "align left", sub: pictureWrapItems() },
- { label: "Reset picture", icon: "undo", action: function () { resetPicture(img); } },
- { sep: true },
- { label: "Delete picture", icon: "trash alternate outline", action: deleteSelectedPicture }
- ];
- }
- /* ================= tables ================= */
- /* Word-style drag-over grid table creator (Insert > Table) */
- var TGRID_COLS = 10, TGRID_ROWS = 8;
- function insertTable(rows, cols) {
- var html = '<table class="of-table"><tbody>';
- for (var r = 0; r < rows; r++) {
- html += "<tr>";
- for (var c = 0; c < cols; c++) html += "<td><br></td>";
- html += "</tr>";
- }
- html += "</tbody></table><p><br></p>";
- restoreSel();
- try { document.execCommand("insertHTML", false, html); } catch (e) { }
- afterEdit(true);
- }
- function insertTableDialog() {
- if (inHeaderFooter()) return;
- var $b = $("<div></div>");
- var $label = $('<div class="doc-tgrid-label">1 × 1</div>');
- var $grid = $('<div class="doc-tgrid"></div>');
- var dlg;
- var hotR = 1, hotC = 1;
- function paint() {
- $grid.children().each(function () {
- var r = parseInt($(this).attr("data-r"), 10);
- var c = parseInt($(this).attr("data-c"), 10);
- $(this).toggleClass("hot", r <= hotR && c <= hotC);
- });
- $label.text(hotC + " × " + hotR);
- }
- for (var r = 1; r <= TGRID_ROWS; r++) {
- for (var c = 1; c <= TGRID_COLS; c++) {
- var $cell = $('<button type="button" class="doc-tgrid-cell"></button>')
- .attr("data-r", r).attr("data-c", c);
- $grid.append($cell);
- }
- }
- // hover / drag over the grid selects the size, click (or release)
- // inserts - matching the Word ribbon gesture
- $grid.on("pointerover pointermove", ".doc-tgrid-cell", function () {
- hotR = parseInt($(this).attr("data-r"), 10);
- hotC = parseInt($(this).attr("data-c"), 10);
- paint();
- });
- $grid.on("click pointerup", ".doc-tgrid-cell", function () {
- var rr = parseInt($(this).attr("data-r"), 10);
- var cc = parseInt($(this).attr("data-c"), 10);
- dlg.close();
- insertTable(rr, cc);
- });
- var $custom = $('<div class="dlg-two-col" style="margin-top:10px;"></div>');
- $custom.append("<div><label>Rows</label><input type='number' min='1' max='50' class='tbl-rows' value='3'></div>");
- $custom.append("<div><label>Columns</label><input type='number' min='1' max='20' class='tbl-cols' value='3'></div>");
- $b.append($label).append($grid)
- .append('<label style="margin-top:12px;">Custom size</label>')
- .append($custom);
- dlg = OfficeApp.dialog({
- title: "Insert table",
- body: $b,
- buttons: [
- { label: "Cancel" },
- {
- label: "Insert custom size", action: function (close, $body) {
- var rows = Math.min(50, Math.max(1, parseInt($body.find(".tbl-rows").val(), 10) || 3));
- var cols = Math.min(20, Math.max(1, parseInt($body.find(".tbl-cols").val(), 10) || 3));
- close();
- insertTable(rows, cols);
- }
- }
- ]
- });
- paint();
- }
- /* ---------- table styling (themes / borders / banding) ----------
- The style state lives in data attributes on the <table> so toggles
- know it and re-application after row/column edits keeps banding
- consistent; the rendered look is plain inline CSS (survives the
- native format, HTML export and - for shading - docx). Cells with
- data-cellbg carry a user-picked background that themes/banding
- never overwrite. */
- var TABLE_THEMES = [
- { name: "Plain", bc: "#b9bec7", headbg: "#eef1f5", bandbg: "#f4f6f9", headfc: "" },
- { name: "Blue", bc: "#a9c6e8", headbg: "#d9e7f8", bandbg: "#eef4fc", headfc: "" },
- { name: "Green", bc: "#b2d8b4", headbg: "#d9efdb", bandbg: "#effaf0", headfc: "" },
- { name: "Orange", bc: "#f0c9a4", headbg: "#fbe3c9", bandbg: "#fdf3e7", headfc: "" },
- { name: "Dark header", bc: "#9aa0a6", headbg: "#3c4043", bandbg: "#f1f3f4", headfc: "#ffffff" }
- ];
- function applyTableStyle(table) {
- var bw = parseFloat(table.getAttribute("data-th-bw")) || 1;
- var bc = table.getAttribute("data-th-bc") || "#b9bec7";
- var headOn = table.getAttribute("data-th-head") === "1";
- var bandOn = table.getAttribute("data-th-band") === "1";
- var headBg = table.getAttribute("data-th-headbg") || "#e8eaed";
- var headFc = table.getAttribute("data-th-headfc") || "";
- var bandBg = table.getAttribute("data-th-bandbg") || "#f4f5f7";
- for (var r = 0; r < table.rows.length; r++) {
- var row = table.rows[r];
- for (var c = 0; c < row.cells.length; c++) {
- var cell = row.cells[c];
- cell.style.border = bw + "px solid " + bc;
- var custom = cell.getAttribute("data-cellbg");
- var isHead = headOn && r === 0;
- var isBand = bandOn && ((r - (headOn ? 1 : 0)) % 2 === 1);
- if (custom) cell.style.backgroundColor = custom;
- else if (isHead) cell.style.backgroundColor = headBg;
- else if (isBand) cell.style.backgroundColor = bandBg;
- else cell.style.backgroundColor = "";
- cell.style.fontWeight = isHead ? "700" : "";
- cell.style.color = (isHead && headFc) ? headFc : "";
- }
- }
- afterEdit(true);
- }
- function currentCell() {
- if (!savedRange) return null;
- var n = savedRange.startContainer;
- if (n && n.nodeType === 3) n = n.parentNode;
- if (!n || !n.closest || !editor.contains(n)) return null;
- var cell = n.closest("td,th");
- if (!cell) {
- // multi-cell selections anchor at the row/tbody/table level -
- // descend through the range start to the first selected cell
- var host = n.closest("table, tbody, tr");
- if (host) {
- var child = savedRange.startContainer.childNodes ?
- savedRange.startContainer.childNodes[savedRange.startOffset] : null;
- if (child && child.nodeType === 1) {
- if (child.matches && child.matches("td,th")) cell = child;
- else if (child.querySelector) cell = child.querySelector("td,th");
- }
- if (!cell) cell = host.querySelector("td,th");
- }
- }
- return cell && editor.contains(cell) ? cell : null;
- }
- function currentTable() {
- var cell = currentCell();
- return cell ? cell.closest("table") : null;
- }
- function tableAddRow(table, index) {
- var cols = (table.rows[0] ? table.rows[0].cells.length : 1);
- var tr = table.insertRow(index);
- for (var i = 0; i < cols; i++) tr.insertCell(-1).innerHTML = "<br>";
- applyTableStyle(table);
- }
- function tableAddCol(table, index) {
- for (var i = 0; i < table.rows.length; i++) {
- var row = table.rows[i];
- var at = Math.min(index, row.cells.length);
- row.insertCell(at).innerHTML = "<br>";
- }
- applyTableStyle(table);
- }
- function tableDelRow(table, ri) {
- table.deleteRow(ri);
- if (table.rows.length === 0 && table.parentNode) {
- table.parentNode.removeChild(table);
- afterEdit(true);
- return;
- }
- applyTableStyle(table);
- }
- function tableDelCol(table, ci) {
- var empty = true;
- for (var i = 0; i < table.rows.length; i++) {
- var row = table.rows[i];
- if (row.cells.length > ci) row.deleteCell(ci);
- if (row.cells.length > 0) empty = false;
- }
- if (empty && table.parentNode) {
- table.parentNode.removeChild(table);
- afterEdit(true);
- return;
- }
- applyTableStyle(table);
- }
- /* ---------- table ops for the floating text-edit bar ----------
- Rendered by OfficeTextEditBar as an extra divider-separated section
- while the selection is inside a table (incl. multi-cell selections).
- Empty array = section hidden. */
- function withTable(fn) {
- var cell = currentCell();
- var table = cell ? cell.closest("table") : null;
- if (!table) return;
- // a row split across a page is one row again before rows or columns
- // are counted
- if (DocsLayout.unsplitWithin(editor, table)) {
- noteEditAtCaret();
- cell = currentCell() || cell;
- table = cell.closest("table") || table;
- }
- fn(table, cell);
- }
- function docsTableOps() {
- if (!currentCell()) return null;
- return [
- {
- icon: "angle up", title: "Insert row above",
- fn: function () { withTable(function (t, cell) { tableAddRow(t, cell.parentNode.rowIndex); }); }
- },
- {
- icon: "angle down", title: "Insert row below",
- fn: function () { withTable(function (t, cell) { tableAddRow(t, cell.parentNode.rowIndex + 1); }); }
- },
- {
- icon: "angle left", title: "Insert column left",
- fn: function () { withTable(function (t, cell) { tableAddCol(t, cell.cellIndex); }); }
- },
- {
- icon: "angle right", title: "Insert column right",
- fn: function () { withTable(function (t, cell) { tableAddCol(t, cell.cellIndex + 1); }); }
- },
- {
- icon: "minus", title: "Delete row",
- fn: function () { withTable(function (t, cell) { tableDelRow(t, cell.parentNode.rowIndex); }); }
- },
- {
- icon: "eraser", title: "Delete column",
- fn: function () { withTable(function (t, cell) { tableDelCol(t, cell.cellIndex); }); }
- },
- {
- icon: "trash alternate outline", title: "Delete table",
- fn: function () {
- withTable(function (t) {
- if (t.parentNode) t.parentNode.removeChild(t);
- afterEdit(true);
- OfficeTextEditBar.setTableOps(null);
- });
- }
- },
- {
- icon: "heading", title: "Header row",
- active: function () {
- var c = currentCell();
- var t = c ? c.closest("table") : null;
- return !!(t && t.getAttribute("data-th-head") === "1");
- },
- fn: function () {
- withTable(function (t) {
- t.setAttribute("data-th-head", t.getAttribute("data-th-head") === "1" ? "" : "1");
- applyTableStyle(t);
- });
- }
- },
- {
- icon: "bars", title: "Banded rows",
- active: function () {
- var c = currentCell();
- var t = c ? c.closest("table") : null;
- return !!(t && t.getAttribute("data-th-band") === "1");
- },
- fn: function () {
- withTable(function (t) {
- t.setAttribute("data-th-band", t.getAttribute("data-th-band") === "1" ? "" : "1");
- applyTableStyle(t);
- });
- }
- },
- {
- icon: "paint brush", title: "Table theme...",
- fn: function (btnEl) {
- withTable(function (t) {
- var r = btnEl.getBoundingClientRect();
- OfficeApp.showContextMenu(r.left, r.bottom + 2, TABLE_THEMES.map(function (th) {
- return {
- label: th.name,
- action: function () {
- t.setAttribute("data-th-bc", th.bc);
- t.setAttribute("data-th-headbg", th.headbg);
- t.setAttribute("data-th-headfc", th.headfc);
- t.setAttribute("data-th-bandbg", th.bandbg);
- t.setAttribute("data-th-head", "1");
- t.setAttribute("data-th-band", "1");
- applyTableStyle(t);
- }
- };
- }));
- });
- }
- },
- {
- icon: "window minimize outline", title: "Border weight...",
- fn: function (btnEl) {
- withTable(function (t) {
- var r = btnEl.getBoundingClientRect();
- OfficeApp.showContextMenu(r.left, r.bottom + 2, [0.5, 1, 2, 3].map(function (w) {
- return {
- label: w + " px",
- checked: (parseFloat(t.getAttribute("data-th-bw")) || 1) === w,
- action: function () {
- t.setAttribute("data-th-bw", String(w));
- applyTableStyle(t);
- }
- };
- }));
- });
- }
- },
- {
- icon: "pencil alternate", title: "Border color...",
- fn: function (btnEl) {
- withTable(function (t) {
- OfficeColorPicker.open({
- anchor: btnEl,
- value: t.getAttribute("data-th-bc") || "#b9bec7",
- onPick: function (hex) {
- if (!hex) return;
- t.setAttribute("data-th-bc", hex);
- applyTableStyle(t);
- }
- });
- });
- }
- },
- {
- icon: "square full", title: "Cell background...",
- fn: function (btnEl) {
- withTable(function (t, cell) {
- OfficeColorPicker.open({
- anchor: btnEl,
- value: cell.getAttribute("data-cellbg") || "#ffffff",
- allowNone: true, noneLabel: "Clear (use theme)",
- onPick: function (hex) {
- if (hex) cell.setAttribute("data-cellbg", hex);
- else cell.removeAttribute("data-cellbg");
- applyTableStyle(t);
- }
- });
- });
- }
- }
- ];
- }
- /* table items reused as a submenu of the right-click context menu */
- function tableMenuItems() { return tableMenuItemsFor(currentCell()); }
- function tableMenuItemsFor(cell) {
- var table = cell ? cell.closest("table") : null;
- if (!table) {
- return [{ label: "Click inside a table first", enabled: function () { return false; }, action: function () { } }];
- }
- function toggleAttr(attr) {
- table.setAttribute(attr, table.getAttribute(attr) === "1" ? "" : "1");
- applyTableStyle(table);
- }
- var items = [
- {
- label: "Header row", icon: "heading",
- checked: function () { return table.getAttribute("data-th-head") === "1"; },
- action: function () { toggleAttr("data-th-head"); }
- },
- {
- label: "Banded rows", icon: "bars",
- checked: function () { return table.getAttribute("data-th-band") === "1"; },
- action: function () { toggleAttr("data-th-band"); }
- },
- {
- label: "Table theme", icon: "paint brush",
- sub: TABLE_THEMES.map(function (t) {
- return {
- label: t.name,
- action: function () {
- table.setAttribute("data-th-bc", t.bc);
- table.setAttribute("data-th-headbg", t.headbg);
- table.setAttribute("data-th-headfc", t.headfc);
- table.setAttribute("data-th-bandbg", t.bandbg);
- table.setAttribute("data-th-head", "1");
- table.setAttribute("data-th-band", "1");
- applyTableStyle(table);
- }
- };
- })
- },
- {
- label: "Border weight", icon: "window minimize outline",
- sub: [0.5, 1, 2, 3].map(function (w) {
- return {
- label: w + " px",
- checked: function () { return (parseFloat(table.getAttribute("data-th-bw")) || 1) === w; },
- action: function () {
- table.setAttribute("data-th-bw", String(w));
- applyTableStyle(table);
- }
- };
- })
- },
- {
- label: "Border color...", icon: "pencil alternate",
- action: function () {
- OfficeColorPicker.open({
- anchor: cell,
- value: table.getAttribute("data-th-bc") || "#b9bec7",
- onPick: function (hex) {
- if (!hex) return;
- table.setAttribute("data-th-bc", hex);
- applyTableStyle(table);
- }
- });
- }
- },
- {
- label: "Cell background...", icon: "square full",
- action: function () {
- OfficeColorPicker.open({
- anchor: cell,
- value: cell.getAttribute("data-cellbg") || "#ffffff",
- allowNone: true, noneLabel: "Clear (use theme)",
- onPick: function (hex) {
- if (hex) cell.setAttribute("data-cellbg", hex);
- else cell.removeAttribute("data-cellbg");
- applyTableStyle(table);
- }
- });
- }
- },
- { sep: true }
- ];
- return items.concat(tableContextItems(cell));
- }
- function tableContextItems(cell) {
- var table = cell.closest("table");
- var row = cell.parentNode;
- var ci = cell.cellIndex;
- var ri = row.rowIndex;
- return [
- { label: "Insert row above", icon: "angle up", action: function () { tableAddRow(table, ri); } },
- { label: "Insert row below", icon: "angle down", action: function () { tableAddRow(table, ri + 1); } },
- { label: "Insert column left", icon: "angle left", action: function () { tableAddCol(table, ci); } },
- { label: "Insert column right", icon: "angle right", action: function () { tableAddCol(table, ci + 1); } },
- { sep: true },
- { label: "Delete row", icon: "minus", action: function () { tableDelRow(table, ri); } },
- { label: "Delete column", icon: "minus", action: function () { tableDelCol(table, ci); } },
- { label: "Delete table", icon: "trash alternate outline", action: function () {
- if (table.parentNode) table.parentNode.removeChild(table);
- afterEdit(true);
- } }
- ];
- }
- /* ================= special characters ================= */
- function specialCharsDialog() {
- if (inHeaderFooter()) return;
- var $b = $("<div></div>");
- var $tabs = $('<div class="sc-tabs"></div>');
- var $grid = $('<div class="sc-grid"></div>');
- function showTab(i) {
- $tabs.children().removeClass("active").eq(i).addClass("active");
- $grid.empty();
- CHAR_TABS[i].cps.forEach(function (cp) {
- var ch = String.fromCodePoint(cp);
- var $c = $('<button type="button" class="sc-char"></button>').text(ch)
- .attr("title", "U+" + cp.toString(16).toUpperCase());
- $c.on("mousedown", function (e) { e.preventDefault(); });
- $c.on("click", function () {
- restoreSel();
- try { document.execCommand("insertText", false, ch); } catch (e) { }
- afterEdit(true);
- });
- $grid.append($c);
- });
- }
- CHAR_TABS.forEach(function (t, i) {
- var $tb = $('<button type="button" class="sc-tab"></button>').text(t.name);
- $tb.on("click", function () { showTab(i); });
- $tabs.append($tb);
- });
- $b.append($tabs).append($grid);
- showTab(0);
- OfficeApp.dialog({
- title: "Special characters",
- body: $b,
- wide: true,
- buttons: [{ label: "Close" }]
- });
- }
- /* ================= find and replace ================= */
- // the panel hangs from the bottom edge of the ribbon, whose height
- // changes as it is collapsed, expanded or wraps
- function placeFindPanel() {
- var bar = document.getElementById("toolbar");
- if (!bar) return;
- document.getElementById("findPanel").style.top = Math.round(bar.getBoundingClientRect().bottom) + 4 + "px";
- }
- if (window.ResizeObserver) new ResizeObserver(placeFindPanel).observe(document.getElementById("toolbar"));
- window.addEventListener("resize", placeFindPanel);
- function openFind(withReplace) {
- $("#findPanel").show();
- placeFindPanel();
- if (withReplace) $("#replaceRow").show();
- var selTxt = savedRange ? savedRange.toString() : "";
- if (selTxt && selTxt.length <= 80 && selTxt.indexOf("\n") < 0) {
- $("#findInput").val(selTxt);
- }
- $("#findInput").trigger("focus").trigger("select");
- runFind(false);
- }
- function closeFind() {
- $("#findPanel").hide();
- $("#replaceRow").hide();
- clearFindHits();
- }
- function clearFindHits() {
- var hits = editor.querySelectorAll("span.of-find-hit");
- for (var i = 0; i < hits.length; i++) {
- var s = hits[i];
- while (s.firstChild) s.parentNode.insertBefore(s.firstChild, s);
- s.parentNode.removeChild(s);
- }
- if (hits.length) editor.normalize();
- findState.hits = [];
- findState.cur = -1;
- updateFindCount();
- }
- function runFind(keepIndex) {
- var oldCur = keepIndex ? Math.max(findState.cur, 0) : 0;
- clearFindHits();
- var term = $("#findInput").val();
- if (!term) { updateFindCount(); return; }
- var tl = term.toLowerCase();
- var walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT, null, false);
- var nodes = [];
- while (walker.nextNode()) nodes.push(walker.currentNode);
- nodes.forEach(function (node) {
- var text = node.nodeValue;
- if (!text) return;
- var lower = text.toLowerCase();
- var idx = lower.indexOf(tl);
- if (idx < 0) return;
- var frag = document.createDocumentFragment();
- var pos = 0;
- while (idx >= 0) {
- if (idx > pos) frag.appendChild(document.createTextNode(text.slice(pos, idx)));
- var sp = document.createElement("span");
- sp.className = "of-find-hit";
- sp.textContent = text.substr(idx, term.length);
- frag.appendChild(sp);
- pos = idx + term.length;
- idx = lower.indexOf(tl, pos);
- }
- if (pos < text.length) frag.appendChild(document.createTextNode(text.slice(pos)));
- node.parentNode.replaceChild(frag, node);
- });
- findState.hits = Array.prototype.slice.call(editor.querySelectorAll("span.of-find-hit"));
- if (findState.hits.length > 0) {
- findState.cur = Math.min(oldCur, findState.hits.length - 1);
- setCurrentHit(findState.cur);
- } else {
- findState.cur = -1;
- }
- updateFindCount();
- }
- function setCurrentHit(i) {
- findState.hits.forEach(function (h) { h.classList.remove("of-find-cur"); });
- var h = findState.hits[i];
- if (h) {
- h.classList.add("of-find-cur");
- try { h.scrollIntoView({ block: "center", behavior: "smooth" }); }
- catch (e) { h.scrollIntoView(); }
- }
- }
- function findStep(dir) {
- var len = findState.hits.length;
- if (!len) { runFind(false); return; }
- findState.cur = (findState.cur + dir + len) % len;
- setCurrentHit(findState.cur);
- updateFindCount();
- }
- function updateFindCount() {
- var len = findState.hits.length;
- $("#findCount").text(len ? (findState.cur + 1) + "/" + len : "0/0");
- }
- function replaceCurrent() {
- if (findState.cur < 0 || !findState.hits.length) { findStep(1); return; }
- var hit = findState.hits[findState.cur];
- var rep = $("#replaceInput").val();
- hit.parentNode.replaceChild(document.createTextNode(rep), hit);
- editor.normalize();
- afterEdit(true);
- runFind(true); // same index now points at the next match
- }
- function replaceAllMatches() {
- var n = findState.hits.length;
- if (!n) { runFind(false); n = findState.hits.length; }
- if (!n) { OfficeApp.toast("No matches to replace"); return; }
- var rep = $("#replaceInput").val();
- findState.hits.forEach(function (h) {
- h.parentNode.replaceChild(document.createTextNode(rep), h);
- });
- editor.normalize();
- findState.hits = [];
- findState.cur = -1;
- updateFindCount();
- afterEdit(true);
- OfficeApp.toast(n + " occurrence" + (n === 1 ? "" : "s") + " replaced");
- }
- function bindFindPanel() {
- $("#findInput").on("input", function () { runFind(false); });
- $("#findInput, #replaceInput").on("keydown", function (e) {
- if (e.key === "Enter") {
- e.preventDefault();
- if (this.id === "replaceInput") replaceCurrent();
- else findStep(e.shiftKey ? -1 : 1);
- } else if (e.key === "Escape") {
- e.preventDefault();
- closeFind();
- editor.focus();
- }
- e.stopPropagation();
- });
- $("#findNext").on("click", function () { findStep(1); });
- $("#findPrev").on("click", function () { findStep(-1); });
- $("#findClose").on("click", function () { closeFind(); editor.focus(); });
- $("#replaceOne").on("click", replaceCurrent);
- $("#replaceAllBtn").on("click", replaceAllMatches);
- }
- /* ================= page setup / print css ================= */
- function applyPageSetup() {
- var d = PAGE_SIZES[pageConf.size] || PAGE_SIZES.A4;
- var w = (pageConf.orientation === "landscape") ? d.h : d.w;
- var h = (pageConf.orientation === "landscape") ? d.w : d.h;
- var m = pageConf.margins;
- pageEl.style.width = w + "mm";
- pageEl.style.minHeight = h + "mm";
- pageEl.style.padding = m.top + "mm " + m.right + "mm " + m.bottom + "mm " + m.left + "mm";
- // multi-column text layout (2 = IEEE-paper style); blocks marked
- // with .col-span-all (title, authors) stretch across every column
- // the columns themselves are the column sections the paginator
- // wraps the text in (docs_layout.js); they read these
- editor.style.columnCount = "";
- editor.style.columnGap = "";
- editor.style.columnFill = "";
- if (pageConf.columns > 1) {
- editor.style.setProperty("--doc-cols", String(pageConf.columns));
- editor.style.setProperty("--doc-colgap", pageConf.colGap + "mm");
- } else {
- editor.style.removeProperty("--doc-cols");
- editor.style.removeProperty("--doc-colgap");
- }
- updatePrintStyle();
- updatePageGuides();
- }
- function updatePrintStyle() {
- var m = pageConf.margins;
- var sizeKw = { "A4": "A4", "Letter": "letter", "Legal": "legal" }[pageConf.size] || "A4";
- var css = "@page {\n";
- css += " size: " + sizeKw + " " + pageConf.orientation + ";\n";
- css += " margin: " + m.top + "mm " + m.right + "mm " + m.bottom + "mm " + m.left + "mm;\n";
- if (pageConf.pageNumbers) {
- /* best effort - @page margin boxes print the page counter in
- engines that support them; ignored elsewhere */
- css += " @bottom-center { content: counter(page); font-size: 10pt; color: #666; font-family: Arial, sans-serif; }\n";
- }
- css += "}\n";
- css += "@media print {\n";
- css += " #page { width: auto !important; min-height: 0 !important; padding: 0 !important; }\n";
- /* the screen bands are absolutely placed per simulated page; when the
- printer paginates for real, one fixed pair repeats on every sheet
- (first-page suppression is a PDF-export feature - print engines
- cannot skip it) */
- if (pageConf.hfMode === "none") {
- css += " .doc-hf { display: none !important; }\n";
- } else {
- css += " .doc-hf { position: fixed !important; left: 0 !important; right: 0 !important; }\n";
- css += " #docHeader { top: 0 !important; }\n";
- css += " #docFooter { top: auto !important; bottom: 0 !important; }\n";
- css += " .doc-hf:not(#docHeader):not(#docFooter) { display: none !important; }\n";
- css += " .doc-hf[hidden] { display: block !important; }\n";
- }
- css += "}\n";
- var tag = document.getElementById("pagePrintStyle");
- if (tag) tag.textContent = css;
- }
- /* ---------- pagination (DocsLayout) ----------
- The document is one flow; docs_layout.js decides where every page
- ends, splits what crosses the boundary and pushes the rest onto the
- next sheet with layout-only spacers (.doc-autobreak; splits and
- spacers are undone on save). This section supplies the page geometry
- and draws what sits around the flow: one sheet of paper per page,
- the header and footer bands, the footnote area and the automatic page
- number. Everything it draws is a real
- element in #page, which is what lets the PDF exporter draw the same
- page the editor shows. */
- var MM_PX = 96 / 25.4;
- var PT_PX = 96 / 72;
- var PAGE_GAP_PX = 24; // visual gap between two sheets
- var HEADER_MIN_PX = 7; // Google Docs never starts a header higher
- var lastPages = []; // page records of the current layout
- // element top in layout px relative to #page (CSS zoom safe - unlike
- // getBoundingClientRect, offsetTop is not scaled)
- function offsetTopInPage(el) {
- var y = 0;
- while (el && el !== pageEl) {
- y += el.offsetTop;
- el = el.offsetParent;
- }
- return y;
- }
- function removeAutoBreaks(root) {
- DocsLayout.removeSpacers(root);
- }
- function docLineSpacing() {
- return pageConf.lineSpacing > 0 ? pageConf.lineSpacing : 1.15;
- }
- function pageGeometry() {
- var d = PAGE_SIZES[pageConf.size] || PAGE_SIZES.A4;
- var land = pageConf.orientation === "landscape";
- var m = pageConf.margins;
- var g = {
- sheetW: (land ? d.h : d.w) * MM_PX,
- sheetH: (land ? d.w : d.h) * MM_PX,
- mTop: m.top * MM_PX, mBot: m.bottom * MM_PX,
- mL: m.left * MM_PX, mR: m.right * MM_PX,
- headerDist: (pageConf.headerDist >= 0 ? pageConf.headerDist : 12.7) * MM_PX,
- footerDist: (pageConf.footerDist >= 0 ? pageConf.footerDist : 12.7) * MM_PX
- };
- g.contentW = g.sheetW - g.mL - g.mR;
- return g;
- }
- /* the passes that give a rendered subtree its word-processor layout:
- list markers, exact line heights, tab stops */
- function runLayoutPasses(root) {
- DocsLayout.applyNumbering(root);
- DocsLayout.applyLineHeights(root, docLineSpacing());
- DocsLayout.applyTableBorders(root);
- DocsLayout.applyTabs(root);
- }
- /* ---------- header / footer bands ----------
- The editable header/footer is repeated once per page, parked in that
- sheet's margin band at the header/footer distance from the paper
- edge. Every copy is editable and they mirror each other, so it can be
- changed from any page. pageConf.hfMode decides which pages get one,
- and the exporters read the same setting. The content is rich HTML
- (hfContent); a PAGE / NUMPAGES field shows each sheet's own number. */
- function hfPairs() {
- return [{ header: headerEl, footer: footerEl }].concat(hfClones);
- }
- function hfShownOn(pageIndex) { // pageIndex is 0-based
- if (pageConf.hfMode === "none") return false;
- if (pageConf.hfMode === "except-first" && pageIndex === 0) return false;
- return true;
- }
- // the stored form of a band: fields keep their placeholder, not the
- // number the copy happened to show
- function hfSerialize(el) {
- var clone = el.cloneNode(true);
- var f = clone.querySelectorAll(".doc-field");
- for (var i = 0; i < f.length; i++) f[i].textContent = "1";
- stripLayoutArtifacts(clone);
- return clone.innerHTML;
- }
- // mirror one band into every other copy (never into the one being typed
- // in, so the caret survives)
- function syncHfFrom(el) {
- var kind = el.getAttribute("data-hf");
- hfContent[kind] = hfSerialize(el);
- hfPairs().forEach(function (pair) {
- var other = pair[kind];
- if (other !== el) other.innerHTML = hfContent[kind];
- });
- }
- function bindHfEvents(el) {
- el.addEventListener("input", function () {
- syncHfFrom(el);
- OfficeApp.markDirty();
- undo.pushDebounced(snapshot, 600);
- });
- el.addEventListener("paste", function (e) {
- e.preventDefault();
- var t = e.clipboardData ? e.clipboardData.getData("text/plain") : "";
- if (t) {
- try { document.execCommand("insertText", false, t); } catch (err) { }
- }
- });
- }
- function makeHfCopy(kind) {
- var src = (kind === "header") ? headerEl : footerEl;
- var el = document.createElement("div");
- el.className = "doc-hf doc-hf-" + kind;
- el.setAttribute("contenteditable", "true");
- el.setAttribute("spellcheck", "false");
- el.setAttribute("data-hf", kind);
- el.setAttribute("data-placeholder", src.getAttribute("data-placeholder") || "");
- el.innerHTML = hfContent[kind] || "";
- bindHfEvents(el);
- pageEl.appendChild(el);
- return el;
- }
- function parkHeaderFooters() {
- hfPairs().forEach(function (pair) {
- ["header", "footer"].forEach(function (kind) {
- pair[kind].style.top = "0px";
- pair[kind].hidden = true;
- });
- });
- }
- function layoutHeaderFooters(pages, geo) {
- // one copy per page after the first (page one uses the originals)
- while (hfClones.length < pages.length - 1) {
- hfClones.push({ header: makeHfCopy("header"), footer: makeHfCopy("footer") });
- }
- while (hfClones.length > pages.length - 1) {
- var drop = hfClones.pop();
- if (drop.header.parentNode) drop.header.parentNode.removeChild(drop.header);
- if (drop.footer.parentNode) drop.footer.parentNode.removeChild(drop.footer);
- }
- var lead = true;
- hfPairs().forEach(function (pair, i) {
- var show = hfShownOn(i);
- var sheetTop = pages[i].sheetTop;
- ["header", "footer"].forEach(function (kind) {
- var el = pair[kind];
- el.hidden = !show;
- el.classList.toggle("doc-hf-lead", show && lead);
- if (!show) return;
- if (el !== document.activeElement && el.innerHTML !== hfContent[kind] &&
- hfSerialize(el) !== hfContent[kind]) {
- el.innerHTML = hfContent[kind] || "";
- }
- var fields = el.querySelectorAll(".doc-field");
- for (var f = 0; f < fields.length; f++) {
- var v = fields[f].getAttribute("data-field") === "NUMPAGES" ? pages.length : i + 1;
- if (fields[f].textContent !== String(v)) fields[f].textContent = String(v);
- }
- el.style.left = geo.mL + "px";
- el.style.width = geo.contentW + "px";
- el.style.right = "auto";
- runLayoutPasses(el);
- var h = el.offsetHeight;
- var top;
- if (kind === "header") {
- top = sheetTop + Math.max(HEADER_MIN_PX, geo.headerDist);
- } else {
- top = sheetTop + geo.sheetH - geo.footerDist - h;
- }
- el.style.top = top + "px";
- });
- if (show) lead = false;
- });
- layoutPageNumbers(pages, geo);
- }
- /* "Page numbers" without a PAGE field in the footer: a plain number
- centred in the bottom margin of every page that shows the footer */
- function layoutPageNumbers(pages, geo) {
- var old = pageEl.querySelectorAll(".doc-pagenum");
- for (var i = 0; i < old.length; i++) old[i].parentNode.removeChild(old[i]);
- if (!pageConf.pageNumbers) return;
- if (/data-field="PAGE"/.test(hfContent.footer || "") || /data-field="PAGE"/.test(hfContent.header || "")) return;
- pages.forEach(function (pg, idx) {
- if (pageConf.hfMode === "except-first" && idx === 0) return;
- var n = document.createElement("div");
- n.className = "doc-pagenum";
- n.textContent = String(idx + 1);
- n.style.left = geo.mL + "px";
- n.style.width = geo.contentW + "px";
- pageEl.appendChild(n);
- n.style.top = (pg.sheetTop + geo.sheetH - geo.footerDist / 2 - n.offsetHeight / 2) + "px";
- });
- }
- /* ---------- footnotes ----------
- body.footnotes holds each note's HTML; the text references them with
- sup.doc-fnref[data-fn]. The notes are drawn under a short rule at the
- bottom of the page that references them, numbered in reference
- order, and stay editable there. */
- var fnMeasureEl = null;
- var fnOrder = [];
- function footnoteArea(ids, geo) {
- var area = document.createElement("div");
- area.className = "doc-fn-area";
- area.style.width = geo.contentW + "px";
- area.appendChild(Object.assign(document.createElement("div"), { className: "doc-fn-sep" }));
- ids.forEach(function (id) {
- var fn = document.createElement("div");
- fn.className = "doc-fn";
- fn.setAttribute("data-fn", id);
- fn.innerHTML = footnotes[id] || "<p><br></p>";
- var first = fn.querySelector("p,h1,h2,h3,h4,h5,h6,li") || fn;
- var mark = document.createElement("sup");
- mark.className = "doc-fnnum";
- mark.setAttribute("contenteditable", "false");
- mark.textContent = String(fnOrder.indexOf(id) + 1);
- first.insertBefore(mark, first.firstChild);
- area.appendChild(fn);
- });
- return area;
- }
- function measureFootnotes(ids, geo) {
- if (!fnMeasureEl) {
- fnMeasureEl = document.createElement("div");
- fnMeasureEl.className = "doc-fn-measure";
- pageEl.appendChild(fnMeasureEl);
- }
- fnMeasureEl.innerHTML = "";
- var area = footnoteArea(ids, geo);
- fnMeasureEl.appendChild(area);
- runLayoutPasses(area);
- var h = area.offsetHeight;
- fnMeasureEl.innerHTML = "";
- return h;
- }
- // a note with nothing typed in it but its number
- function footnoteIsEmpty(fn) {
- var clone = fn.cloneNode(true);
- var marks = clone.querySelectorAll(".doc-fnnum");
- for (var m = 0; m < marks.length; m++) marks[m].parentNode.removeChild(marks[m]);
- return !clone.textContent.replace(/[\s]/g, "") &&
- !clone.querySelector("img,svg,table,hr,video,iframe");
- }
- // Backspace in an empty note deletes it: its references leave the
- // text and the caret goes back to where the first one was
- function removeFootnote(id) {
- var refs = editor.querySelectorAll('sup.doc-fnref[data-fn="' + id + '"]');
- if (!refs.length) return;
- var range = document.createRange();
- range.setStartBefore(refs[0]);
- range.collapse(true);
- for (var i = 0; i < refs.length; i++) refs[i].parentNode.removeChild(refs[i]);
- delete footnotes[id];
- editor.focus();
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(range);
- savedRange = range.cloneRange();
- afterEdit(true);
- clearTimeout(countTimer);
- updateCounts();
- }
- function renderFootnoteAreas(pages, geo) {
- var old = pageEl.querySelectorAll(".doc-fn-area");
- for (var i = 0; i < old.length; i++) {
- if (old[i].parentNode === pageEl) old[i].parentNode.removeChild(old[i]);
- }
- pages.forEach(function (pg) {
- if (!pg.footnotes || !pg.footnotes.length) return;
- var area = footnoteArea(pg.footnotes, geo);
- area.style.left = geo.mL + "px";
- area.style.top = pg.footnoteTop + "px";
- area.querySelectorAll(".doc-fn").forEach(function (fn) {
- fn.setAttribute("contenteditable", "true");
- fn.addEventListener("input", function () {
- var clone = fn.cloneNode(true);
- var marks = clone.querySelectorAll(".doc-fnnum");
- for (var m = 0; m < marks.length; m++) marks[m].parentNode.removeChild(marks[m]);
- stripLayoutArtifacts(clone);
- footnotes[fn.getAttribute("data-fn")] = clone.innerHTML;
- OfficeApp.markDirty();
- undo.pushDebounced(snapshot, 600);
- });
- fn.addEventListener("keydown", function (e) {
- if (e.key !== "Backspace" || e.ctrlKey || e.metaKey || e.altKey) return;
- if (!footnoteIsEmpty(fn)) return;
- e.preventDefault();
- removeFootnote(fn.getAttribute("data-fn"));
- });
- });
- pageEl.appendChild(area);
- runLayoutPasses(area);
- });
- }
- /* ---------- the sheets ----------
- One sheet of paper per page, behind the flow. Between two sheets
- there is nothing at all, which is what makes the pages really
- separate: the flow has no content there (a split puts the rest of a
- paragraph or a table row on the next sheet), so no border or shading
- can show in the gap. */
- function renderSheets(pages, geo) {
- var holder = document.getElementById("pageSheets");
- if (!holder) {
- holder = document.createElement("div");
- holder.id = "pageSheets";
- holder.className = "of-noprint";
- holder.setAttribute("aria-hidden", "true");
- pageEl.insertBefore(holder, pageEl.firstChild);
- }
- var want = pages.map(function (pg) { return { top: pg.sheetTop, h: geo.sheetH }; });
- while (holder.children.length > want.length) holder.removeChild(holder.lastChild);
- while (holder.children.length < want.length) {
- var sheet = document.createElement("div");
- sheet.className = "doc-sheet";
- holder.appendChild(sheet);
- }
- want.forEach(function (w, i) {
- var el = holder.children[i];
- var top = w.top + "px", h = w.h + "px";
- if (el.style.top !== top) el.style.top = top;
- if (el.style.height !== h) el.style.height = h;
- });
- }
- /* ---------- deferred relayout ----------
- Pictures in a document that was just opened are still decoding while
- loadBody() paginates: they measure zero tall, so the page tops - and
- with them the header/footer bands and the automatic breaks - come out
- for a much shorter document than the one that ends up on screen.
- Anything that changes the flow height without an edit (an image
- finishing, a web font, a window resize) re-runs the pagination. */
- var relayoutTimer = null;
- var relayoutH = -1; // editor height the current layout was made for
- var relayouting = false;
- function scheduleRelayout() {
- clearTimeout(relayoutTimer);
- relayoutTimer = setTimeout(function () {
- updatePageGuides();
- }, 80);
- }
- function watchContentSize() {
- // load does not bubble, but it is seen in the capture phase
- var onLoad = function (e) {
- if (e.target && e.target.tagName === "IMG") scheduleRelayout();
- };
- editor.addEventListener("load", onLoad, true);
- editor.addEventListener("error", onLoad, true);
- if (window.ResizeObserver) {
- new ResizeObserver(function () {
- if (relayouting) return;
- if (Math.abs(editor.offsetHeight - relayoutH) <= 1) return;
- scheduleRelayout();
- }).observe(editor);
- }
- if (document.fonts && document.fonts.ready) {
- document.fonts.ready.then(scheduleRelayout).catch(function () { });
- }
- }
- function setHfMode(mode) {
- if (HF_MODES.indexOf(mode) < 0) return;
- pageConf.hfMode = mode;
- updatePrintStyle();
- updatePageGuides();
- afterEdit(true);
- OfficeApp.setStatus({
- "all": "Header and footer shown on every page",
- "except-first": "Header and footer shown on every page except the first",
- "none": "Header and footer turned off"
- }[mode]);
- }
- /* The earliest point an edit touched since the last layout (#page
- coordinates), or null when the whole document has to be laid out
- again - a newly opened document, page setup, anything that is not
- typing at a caret. */
- var dirtyFromY = null;
- var lastGeoKey = "";
- function geoKey(geo) {
- return [geo.sheetW, geo.sheetH, geo.mTop, geo.mBot, geo.mL, geo.mR, docLineSpacing(),
- OfficeApp.getZoom()].join(",");
- }
- // a viewport y as a #page layout y (the framework zooms #page)
- function pageYOf(clientY) {
- var pr = pageEl.getBoundingClientRect();
- var scale = pageEl.offsetHeight ? pr.height / pageEl.offsetHeight : 1;
- return (clientY - pr.top) / (scale || 1);
- }
- // where the caret is, in #page layout px; null when it is not in the text
- function caretPageY() {
- try {
- var sel = window.getSelection();
- if (!sel || !sel.rangeCount) return null;
- var r = sel.getRangeAt(0);
- if (!pageEl.contains(r.startContainer)) return null;
- var rects = r.getClientRects();
- var rect = rects.length ? rects[0] : null;
- if (!rect || !rect.height) {
- var n = r.startContainer.nodeType === 1 ? r.startContainer : r.startContainer.parentElement;
- rect = n.getBoundingClientRect();
- }
- return Math.max(0, pageYOf(rect.top));
- } catch (e) {
- return null;
- }
- }
- /* relayoutNow lays an edit that changes how tall its lines are (a
- style, a size, a spacing) out before the browser paints again. Left
- to the resize observer, the new size showed for a moment with the old
- line heights - its lines stacked on top of each other - until the
- layout caught up. The pages are redone from the first edited block. */
- function relayoutNow(blocks) {
- var y = null;
- (blocks || []).forEach(function (b) {
- if (!b || !b.isConnected || !editor.contains(b)) return;
- var t = pageYOf(b.getBoundingClientRect().top);
- y = y === null ? t : Math.min(y, t);
- });
- if (y === null) y = caretPageY();
- if (y !== null) {
- y = Math.max(0, y);
- dirtyFromY = dirtyFromY === null ? y : Math.min(dirtyFromY, y);
- }
- clearTimeout(relayoutTimer);
- updatePageGuides();
- }
- function noteEditAtCaret() {
- var y = editor.contains((window.getSelection() || {}).anchorNode || null) ? caretPageY() : null;
- if (y === null) y = 0;
- dirtyFromY = dirtyFromY === null ? y : Math.min(dirtyFromY, y);
- }
- /* ---------- "Page 3 of 12" in the status bar ----------
- The page the caret is on after a click or a keystroke, the page in
- the middle of the view after a scroll - whichever happened last. */
- var pageShownBy = "caret";
- var pageIndicatorTimer = null;
- function pageIndexAt(y) {
- var n = 0;
- for (var i = 0; i < lastPages.length; i++) {
- if (lastPages[i].sheetTop <= y + 0.5) n = i;
- }
- return n;
- }
- function updatePageIndicator(by) {
- if (by) pageShownBy = by;
- var total = Math.max(1, lastPages.length);
- var y = null;
- if (pageShownBy === "caret") y = caretPageY();
- if (y === null && workspaceEl) {
- var wr = workspaceEl.getBoundingClientRect();
- y = pageYOf(wr.top + wr.height / 2);
- }
- var n = Math.min(total, pageIndexAt(y || 0) + 1);
- OfficeApp.updateStatusItem("pg", "Page " + n + " of " + total);
- }
- function schedulePageIndicator(by) {
- if (by) pageShownBy = by;
- if (pageIndicatorTimer) return;
- pageIndicatorTimer = setTimeout(function () {
- pageIndicatorTimer = null;
- updatePageIndicator();
- }, 120);
- }
- function updatePageGuides() {
- if (relayouting) return lastPages.length || 1;
- relayouting = true;
- try {
- return layoutPages();
- } finally {
- relayoutH = editor.offsetHeight;
- relayouting = false;
- if (tocOverlay || tocHover) scheduleTocOverlay();
- }
- }
- function layoutPages() {
- var geo = pageGeometry();
- // park the bands first: a copy still sitting at the bottom of a
- // longer previous layout would stretch #page and conjure a phantom
- // page below
- parkHeaderFooters();
- pageEl.style.minHeight = geo.sheetH + "px";
- // an edit only needs the pages from where it happened
- var fromY = dirtyFromY;
- dirtyFromY = null;
- var incremental = fromY !== null && lastPages.length > 2 && pageConf.columns <= 1 &&
- lastGeoKey === geoKey(geo);
- lastGeoKey = geoKey(geo);
- if (!incremental) removeAutoBreaks(editor);
- normalizePageBreaks();
- runLayoutPasses(editor);
- fnOrder = DocsLayout.numberFootnotes(editor);
- var refs = editor.querySelectorAll("sup.doc-fnref");
- var pages = DocsLayout.paginate({
- editor: editor, pageEl: pageEl,
- sheetH: geo.sheetH, gap: PAGE_GAP_PX, mTop: geo.mTop, mBot: geo.mBot,
- columns: pageConf.columns > 1 ? pageConf.columns : 1,
- fnRefs: refs,
- measureFootnotes: refs.length ? function (ids) { return measureFootnotes(ids, geo); } : null,
- fromY: incremental ? fromY : undefined,
- prevPages: incremental ? lastPages : null
- });
- lastPages = pages;
- var last = pages[pages.length - 1];
- pageEl.style.minHeight = (last.sheetTop + geo.sheetH + pageEl.clientTop * 2) + "px";
- renderSheets(pages, geo);
- renderFootnoteAreas(pages, geo);
- layoutHeaderFooters(pages, geo);
- updatePageIndicator();
- return pages.length;
- }
- /* ---------- explicit page breaks ---------- */
- function pageBreakHtml() {
- return '<div class="doc-pagebreak" contenteditable="false"></div>';
- }
- // imported / restored breaks may carry old gap markup or lack the guard
- function normalizePageBreaks() {
- var list = editor.querySelectorAll(".doc-pagebreak");
- for (var i = 0; i < list.length; i++) {
- list[i].setAttribute("contenteditable", "false");
- if (list[i].firstChild) list[i].innerHTML = "";
- }
- }
- function insertPageBreak() {
- if (inHeaderFooter()) return;
- restoreSel();
- // trailing paragraph so there is always somewhere to type on the new page
- try {
- document.execCommand("insertHTML", false, pageBreakHtml() + "<p><br></p>");
- } catch (e) { return; }
- normalizePageBreaks();
- afterEdit(true);
- updatePageGuides();
- OfficeApp.setStatus("Page break inserted");
- }
- function toggleLayoutBoxes() {
- var on = !document.body.classList.contains("doc-show-boxes");
- document.body.classList.toggle("doc-show-boxes", on);
- OfficeApp.setSetting("layoutBoxes", on);
- OfficeApp.setStatus(on
- ? "Layout boxes on - orange = full width (spans all columns), blue = column text"
- : "Layout boxes off");
- }
- /* ---------- layout presets ---------- */
- function setColumns(count, gap) {
- pageConf.columns = Math.min(3, Math.max(1, count));
- if (gap !== undefined) pageConf.colGap = gap;
- applyPageSetup();
- afterEdit(true);
- OfficeApp.setStatus(count > 1 ? count + "-column layout applied" : "Single column layout");
- }
- function applyIeeePreset() {
- // IEEE conference paper geometry: US Letter, 0.75in top, 1in bottom,
- // 0.625in sides, two columns with a 0.17in gap
- pageConf.size = "Letter";
- pageConf.orientation = "portrait";
- pageConf.margins = { top: 19, right: 16, bottom: 25, left: 16 };
- pageConf.columns = 2;
- pageConf.colGap = 5;
- applyPageSetup();
- afterEdit(true);
- OfficeApp.setStatus("IEEE paper layout applied - mark the title block with Format > Page layout > Span all columns");
- }
- function toggleSpanAll() {
- var blocks = getSelectedBlocks();
- if (!blocks.length) {
- OfficeApp.setStatus("Place the cursor in the paragraph(s) to span first", "error");
- return;
- }
- var on = !blocks[0].classList.contains("col-span-all");
- blocks.forEach(function (b) { b.classList.toggle("col-span-all", on); });
- afterEdit(true);
- }
- function layoutMenuItems() {
- return [
- {
- label: "Single column",
- checked: function () { return pageConf.columns === 1; },
- action: function () { setColumns(1); }
- },
- {
- label: "Two columns",
- checked: function () { return pageConf.columns === 2; },
- action: function () { setColumns(2); }
- },
- {
- label: "Three columns",
- checked: function () { return pageConf.columns === 3; },
- action: function () { setColumns(3); }
- },
- { sep: true },
- { label: "IEEE paper preset", icon: "graduation cap", action: applyIeeePreset },
- { sep: true },
- {
- label: "Span all columns",
- checked: function () {
- var b = getSelectedBlocks();
- return b.length > 0 && b[0].classList.contains("col-span-all");
- },
- action: toggleSpanAll
- }
- ];
- }
- function pageSetupDialog() {
- var $b = $("<div></div>");
- var $grid = $('<div class="ps-grid"></div>');
- var $size = $('<select class="ps-size"></select>');
- Object.keys(PAGE_SIZES).forEach(function (k) {
- var d = PAGE_SIZES[k];
- $size.append($("<option></option>").attr("value", k)
- .text(k + " (" + d.w + " × " + d.h + " mm)"));
- });
- $size.val(pageConf.size);
- var $ori = $('<select class="ps-ori"></select>')
- .append('<option value="portrait">Portrait</option>')
- .append('<option value="landscape">Landscape</option>');
- $ori.val(pageConf.orientation);
- $grid.append($("<div></div>").append("<label>Paper size</label>").append($size));
- $grid.append($("<div></div>").append("<label>Orientation</label>").append($ori));
- var m = pageConf.margins;
- [["top", "Top margin (mm)", m.top], ["bottom", "Bottom margin (mm)", m.bottom],
- ["left", "Left margin (mm)", m.left], ["right", "Right margin (mm)", m.right]].forEach(function (f) {
- var $in = $('<input type="number" min="0" max="80" step="1">')
- .addClass("ps-m-" + f[0]).val(f[2]);
- $grid.append($("<div></div>").append("<label>" + f[1] + "</label>").append($in));
- });
- 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>');
- $cols.val(String(pageConf.columns));
- $grid.append($("<div></div>").append("<label>Text columns</label>").append($cols));
- var $gap = $('<input type="number" min="2" max="30" step="1" class="ps-gap">').val(pageConf.colGap);
- $grid.append($("<div></div>").append("<label>Column gap (mm)</label>").append($gap));
- $b.append($grid);
- var $chk = $('<label class="ps-check"><input type="checkbox" class="ps-pn"> Print page numbers (bottom center, browser support permitting)</label>');
- $chk.find("input").prop("checked", pageConf.pageNumbers);
- $b.append($chk);
- OfficeApp.dialog({
- title: "Page setup",
- body: $b,
- buttons: [
- { label: "Cancel" },
- { label: "Apply", primary: true, action: function (close, $body) {
- pageConf.size = $body.find(".ps-size").val();
- pageConf.orientation = $body.find(".ps-ori").val();
- pageConf.margins = {
- top: clampMm($body.find(".ps-m-top").val()),
- right: clampMm($body.find(".ps-m-right").val()),
- bottom: clampMm($body.find(".ps-m-bottom").val()),
- left: clampMm($body.find(".ps-m-left").val())
- };
- pageConf.columns = Math.min(3, Math.max(1, parseInt($body.find(".ps-cols").val(), 10) || 1));
- pageConf.colGap = Math.min(30, Math.max(2, num($body.find(".ps-gap").val(), 8)));
- pageConf.pageNumbers = $body.find(".ps-pn").prop("checked");
- close();
- applyPageSetup();
- afterEdit(true);
- } }
- ]
- });
- }
- function clampMm(v) {
- return Math.min(80, Math.max(0, num(v, 20)));
- }
- /* ================= word / character count ================= */
- function scheduleCounts() {
- clearTimeout(countTimer);
- countTimer = setTimeout(updateCounts, 300);
- }
- function updateCounts() {
- var text = editor.innerText || "";
- var words = (text.match(/\S+/g) || []).length;
- var chars = text.replace(/\n/g, "").length;
- var pages = updatePageGuides();
- OfficeApp.updateStatusItem("wc",
- words + " word" + (words === 1 ? "" : "s") + " · " +
- chars + " character" + (chars === 1 ? "" : "s") + " · " +
- pages + " page" + (pages === 1 ? "" : "s"));
- updateSuggestStatus();
- }
- /* ================= review: comments ================= */
- /* Comments live in body.comments [{id, text, at, resolved}] and are
- anchored in the content as <span class="doc-cmt" data-cid="...">.
- Resolving/deleting unwraps the anchor; anchors whose text was
- edited away show as orphaned cards. */
- function genCmtId() {
- return "cm-" + Date.now().toString(36) + Math.random().toString(36).substring(2, 7);
- }
- function cmtSpan(id) {
- return editor.querySelector('span.doc-cmt[data-cid="' + id + '"]');
- }
- function unwrapEl(el) {
- while (el.firstChild) el.parentNode.insertBefore(el.firstChild, el);
- el.parentNode.removeChild(el);
- }
- function commentDialog(existing) {
- restoreSel();
- var range = null;
- if (!existing) {
- var sel = window.getSelection();
- if (savedRange && !savedRange.collapsed && editor.contains(savedRange.commonAncestorContainer)) {
- range = savedRange.cloneRange();
- } else if (sel && sel.rangeCount && !sel.getRangeAt(0).collapsed &&
- editor.contains(sel.getRangeAt(0).commonAncestorContainer)) {
- range = sel.getRangeAt(0).cloneRange();
- }
- if (!range) {
- OfficeApp.setStatus("Select the text to comment on first", "error");
- return;
- }
- }
- var $b = $('<label>Comment</label>' +
- '<textarea id="docCmtText" rows="4" style="width:100%;resize:vertical;"></textarea>');
- if (existing) $b.filter("textarea").val(existing.text);
- OfficeApp.dialog({
- title: existing ? "Edit comment" : "Add comment",
- body: $b,
- buttons: [
- { label: "Cancel" },
- {
- label: existing ? "Save" : "Comment", primary: true,
- action: function (close, $bd) {
- var text = String($bd.find("#docCmtText").val() || "").trim();
- close();
- if (!text) return;
- if (existing) {
- existing.text = text;
- } else {
- var id = genCmtId();
- var span = document.createElement("span");
- span.className = "doc-cmt";
- span.setAttribute("data-cid", id);
- try {
- range.surroundContents(span);
- } catch (e) {
- // selection crosses element boundaries
- span.appendChild(range.extractContents());
- range.insertNode(span);
- }
- comments.push({ id: id, text: text, at: Date.now(), resolved: false });
- }
- afterEdit(true);
- renderCommentsPanel();
- showCommentsPanel(true);
- }
- }
- ]
- });
- setTimeout(function () { $("#docCmtText").focus(); }, 50);
- }
- function commentById(id) {
- for (var i = 0; i < comments.length; i++) if (comments[i].id === id) return comments[i];
- return null;
- }
- function resolveComment(id, remove) {
- var span = cmtSpan(id);
- if (span) unwrapEl(span);
- if (remove) {
- comments = comments.filter(function (c) { return c.id !== id; });
- } else {
- var c = commentById(id);
- if (c) c.resolved = true;
- }
- editor.normalize();
- afterEdit(true);
- renderCommentsPanel();
- }
- function openComments() { return comments.filter(function (c) { return !c.resolved; }); }
- function showCommentsPanel(show) {
- $("#docCmtPanel").toggle(show);
- OfficeApp.setSetting("cmtPanel", show);
- }
- function commentsPanelVisible() { return $("#docCmtPanel").is(":visible"); }
- function renderCommentsPanel(activeId) {
- var $p = $("#docCmtPanel");
- if (!$p.length) return;
- var $list = $p.find(".doc-cmt-list").empty();
- var open = openComments();
- $p.find(".doc-cmt-count").text(open.length ? open.length : "");
- if (!open.length) {
- $list.append('<div class="doc-cmt-empty">No comments. Select some text and use ' +
- 'Insert > Comment (Ctrl+Alt+M).</div>');
- return;
- }
- open.forEach(function (c) {
- var span = cmtSpan(c.id);
- var quote = span ? span.textContent : "";
- if (quote.length > 60) quote = quote.substring(0, 60) + "…";
- var $card = $('<div class="doc-cmt-card' + (c.id === activeId ? " active" : "") + '"></div>');
- $card.append($('<div class="doc-cmt-quote"></div>')
- .text(quote || "(commented text was removed)"));
- $card.append($('<div class="doc-cmt-body"></div>').text(c.text));
- $card.append('<div class="doc-cmt-when">' +
- new Date(c.at).toLocaleString() + "</div>");
- var $acts = $('<div class="doc-cmt-actions"></div>');
- var act = function (icon, title, fn) {
- var $a = $('<button type="button" class="of-te-btn" title="' + title + '">' +
- '<i class="' + icon + ' icon"></i></button>');
- $a.on("click", function (e) { e.stopPropagation(); fn(); });
- return $a;
- };
- $acts.append(act("check", "Resolve (remove the highlight)", function () { resolveComment(c.id, false); }));
- $acts.append(act("pencil alternate", "Edit comment", function () { commentDialog(c); renderCommentsPanel(c.id); }));
- $acts.append(act("trash alternate outline", "Delete comment", function () { resolveComment(c.id, true); }));
- $card.append($acts);
- $card.on("click", function () {
- var sp = cmtSpan(c.id);
- if (sp) {
- sp.scrollIntoView({ block: "center", behavior: "smooth" });
- $(".doc-cmt.flash").removeClass("flash");
- sp.classList.add("flash");
- setTimeout(function () { sp.classList.remove("flash"); }, 1600);
- }
- renderCommentsPanel(c.id);
- });
- $list.append($card);
- });
- }
- function buildCommentsPanel() {
- var $p = $('<div id="docCmtPanel" class="of-noprint">' +
- '<div class="doc-cmt-head"><i class="comments outline icon"></i> Comments ' +
- '<span class="doc-cmt-count"></span>' +
- '<button type="button" class="of-te-btn doc-cmt-close" title="Close panel">' +
- '<i class="close icon"></i></button></div>' +
- '<div class="doc-cmt-list"></div></div>');
- $p.find(".doc-cmt-close").on("click", function () { showCommentsPanel(false); });
- $("body").append($p);
- $p.hide();
- }
- /* ================= review: track changes (suggest mode) ================= */
- /* While "Suggest edits" is on, typing becomes <ins class="doc-ins"> and
- deleting wraps content in <del class="doc-del"> instead of removing
- it. Every suggestion can be accepted or rejected (context menu or
- Edit menu); foreign exports (docx/html/md/txt) behave as if all
- suggestions were accepted. Paragraph splits/merges are not tracked. */
- function tagOf(node, selector) {
- if (!node) return null;
- if (node.nodeType === 3) node = node.parentNode;
- return node && node.closest ? node.closest(selector) : null;
- }
- function suggestInsert(text) {
- if (!text) return;
- var sel = window.getSelection();
- if (!sel || !sel.rangeCount) return;
- var range = sel.getRangeAt(0);
- if (!range.collapsed) {
- suggestDeleteRange(range);
- sel = window.getSelection();
- range = sel.getRangeAt(0);
- }
- var tn = document.createTextNode(text);
- var insHost = tagOf(range.startContainer, "ins.doc-ins");
- var delHost = tagOf(range.startContainer, "del.doc-del");
- if (insHost && !delHost) {
- range.insertNode(tn); // grow the existing suggestion
- } else {
- var ins = document.createElement("ins");
- ins.className = "doc-ins";
- ins.appendChild(tn);
- if (delHost) {
- // typing at a suggested deletion: the insertion goes after it
- delHost.parentNode.insertBefore(ins, delHost.nextSibling);
- } else {
- range.insertNode(ins);
- }
- }
- var r2 = document.createRange();
- r2.setStart(tn, tn.nodeValue.length);
- r2.collapse(true);
- sel.removeAllRanges();
- sel.addRange(r2);
- afterEdit(false);
- }
- function suggestDeleteRange(range) {
- var texts = [];
- if (range.commonAncestorContainer.nodeType === 3) {
- texts = [range.commonAncestorContainer];
- } else {
- var walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT, null);
- var n;
- while ((n = walker.nextNode())) {
- if (n.nodeValue !== "" && range.intersectsNode(n)) texts.push(n);
- }
- }
- var caret = document.createRange();
- caret.setStart(range.startContainer, range.startOffset);
- caret.collapse(true);
- texts.forEach(function (tn) {
- var s = tn === range.startContainer ? range.startOffset : 0;
- var e2 = tn === range.endContainer ? range.endOffset : tn.nodeValue.length;
- if (e2 <= s) return;
- if (tagOf(tn, "del.doc-del")) return; // already marked deleted
- var mid = tn;
- if (s > 0) mid = mid.splitText(s);
- if (e2 - s < mid.nodeValue.length) mid.splitText(e2 - s);
- if (tagOf(mid, "ins.doc-ins")) {
- // deleting our own suggestion: really remove it
- mid.parentNode.removeChild(mid);
- return;
- }
- var del = document.createElement("del");
- del.className = "doc-del";
- mid.parentNode.insertBefore(del, mid);
- del.appendChild(mid);
- });
- var sel = window.getSelection();
- sel.removeAllRanges();
- sel.addRange(caret);
- }
- function suggestDeleteCollapsed(forward) {
- var sel = window.getSelection();
- if (!sel || !sel.rangeCount || !sel.modify) return;
- sel.modify("extend", forward ? "forward" : "backward", "character");
- if (!sel.rangeCount) return;
- var r = sel.getRangeAt(0);
- if (r.collapsed) return;
- var probe = forward ? r.endContainer : r.startContainer;
- if (tagOf(probe, "ins.doc-ins") && !tagOf(probe, "del.doc-del")) {
- // deleting inside our own insertion: real delete
- try { document.execCommand(forward ? "forwardDelete" : "delete"); } catch (e) { }
- return;
- }
- if (tagOf(probe, "del.doc-del")) {
- // already suggested deleted: just step over it
- if (forward) sel.collapse(r.endContainer, r.endOffset);
- else sel.collapse(r.startContainer, r.startOffset);
- return;
- }
- suggestDeleteRange(r);
- }
- function onEditorBeforeInput(e) {
- if (!suggesting || inHeaderFooter()) return;
- var t = e.inputType || "";
- var sel = window.getSelection();
- if (!sel || !sel.rangeCount) return;
- if (!editor.contains(sel.getRangeAt(0).commonAncestorContainer)) return;
- if (t === "insertText") {
- // insertCompositionText is NOT handled: it is not cancelable, so
- // intercepting it would double-insert IME (e.g. CJK) input -
- // composed text stays untracked instead
- if (e.data === null || e.data === undefined) return;
- e.preventDefault();
- suggestInsert(e.data);
- } else if (t.indexOf("delete") === 0) {
- e.preventDefault();
- var r = sel.getRangeAt(0);
- if (!r.collapsed) suggestDeleteRange(r);
- else suggestDeleteCollapsed(t === "deleteContentForward" || t === "deleteWordForward");
- afterEdit(false);
- }
- // insertParagraph / formatting / drops stay untracked (limitation)
- }
- function allSuggestions() {
- return editor.querySelectorAll("ins.doc-ins, del.doc-del");
- }
- function resolveSuggestion(el, accept) {
- var isIns = el.tagName === "INS";
- if (isIns === accept) unwrapEl(el); // keep the content
- else el.parentNode.removeChild(el); // drop it
- editor.normalize();
- afterEdit(true);
- }
- function resolveAllSuggestions(accept) {
- var list = allSuggestions();
- if (!list.length) return;
- for (var i = 0; i < list.length; i++) {
- var el = list[i];
- if (el.tagName === "INS" === accept) unwrapEl(el);
- else if (el.parentNode) el.parentNode.removeChild(el);
- }
- editor.normalize();
- afterEdit(true);
- OfficeApp.setStatus((accept ? "Accepted " : "Rejected ") + list.length + " suggestion(s)");
- }
- function setSuggesting(on) {
- suggesting = !!on;
- OfficeApp.markDirty();
- updateSuggestStatus();
- }
- function updateSuggestStatus() {
- var pending = allSuggestions().length;
- var html = "";
- if (suggesting) {
- html = '<i class="pencil alternate icon"></i>Suggesting' +
- (pending ? " · " + pending + " pending" : "");
- } else if (pending) {
- html = pending + " suggestion(s) pending";
- }
- OfficeApp.updateStatusItem("suggest", html);
- }
- /* content with every suggestion accepted and comment anchors unwrapped -
- what foreign exports (docx/html/md/txt) should contain */
- function resolvedHtml() {
- var div = document.createElement("div");
- div.innerHTML = cleanedHtml();
- var list = div.querySelectorAll("ins.doc-ins, del.doc-del, span.doc-cmt");
- for (var i = 0; i < list.length; i++) {
- var el = list[i];
- if (el.tagName === "DEL") el.parentNode.removeChild(el);
- else unwrapEl(el);
- }
- div.normalize();
- return div.innerHTML;
- }
- /* ================= copy / cut of a selected image =================
- Image selection is app-level (selectImage), not a DOM range, so the
- browser's native copy has nothing to grab. Put the image on the
- system clipboard as HTML - handleEditorPaste's text/html branch
- (and other apps) take it from there. */
- function handleImageCopyCut(e, isCut) {
- if (!selectedImg) return;
- if (!e.clipboardData) return;
- var clone = selectedImg.cloneNode(false);
- clone.classList.remove("of-selimg");
- if (!clone.getAttribute("class")) clone.removeAttribute("class");
- // absolute URL so the image also resolves outside this page
- try { clone.src = selectedImg.src; } catch (err) { }
- canonicalCrop(clone);
- e.clipboardData.setData("text/html", clone.outerHTML);
- e.clipboardData.setData("text/plain", "");
- e.preventDefault();
- if (isCut) {
- var img = selectedImg;
- deselectImage();
- if (img.parentNode) img.parentNode.removeChild(img);
- afterEdit(true);
- } else {
- OfficeApp.setStatus("Image copied");
- }
- }
- /* ================= menu-driven clipboard =================
- Ctrl+X/C/V go through the native events; menu clicks have no event,
- so use the async clipboard API (image > html > plain text, mirroring
- handleEditorPaste, including suggest-mode wrapping). */
- function menuCutCopy(isCut) {
- if (selectedImg) {
- // image selection is app-level - write it as HTML ourselves
- var clone = selectedImg.cloneNode(false);
- clone.classList.remove("of-selimg");
- if (!clone.getAttribute("class")) clone.removeAttribute("class");
- try { clone.src = selectedImg.src; } catch (e) { }
- canonicalCrop(clone);
- OfficeClipboard.writeAsync({ html: clone.outerHTML, text: "" }).catch(function () { });
- if (isCut) {
- var img = selectedImg;
- deselectImage();
- if (img.parentNode) img.parentNode.removeChild(img);
- afterEdit(true);
- } else {
- OfficeApp.setStatus("Image copied");
- }
- return;
- }
- restoreSel();
- try { document.execCommand(isCut ? "cut" : "copy"); } catch (e) { }
- if (isCut) afterEdit(true);
- }
- // Home > Copy > Copy as plain text: the selected text without its formatting
- function copyPlainText() {
- restoreSel();
- var s = window.getSelection ? window.getSelection().toString() : "";
- if (!s) { OfficeApp.setStatus("Select some text to copy", "error"); return; }
- OfficeClipboard.writeAsync({ text: s }).then(function () {
- OfficeApp.setStatus("Copied as plain text");
- }, function () {
- OfficeApp.setStatus("Copy blocked by the browser - use Ctrl+C instead", "error");
- });
- }
- function pasteFromMenu(plainOnly) {
- var fallbackText = function () {
- if (navigator.clipboard && navigator.clipboard.readText) {
- navigator.clipboard.readText().then(function (t) {
- if (!t) return;
- restoreSel();
- if (suggesting && !inHeaderFooter()) suggestInsert(t);
- else { try { document.execCommand("insertText", false, t); } catch (e) { } }
- afterEdit(true);
- }).catch(function () {
- OfficeApp.setStatus("Paste blocked by the browser - use Ctrl+V instead", "error");
- });
- } else {
- OfficeApp.setStatus("Use Ctrl+V to paste here", "error");
- }
- };
- if (plainOnly || !(navigator.clipboard && navigator.clipboard.read)) {
- fallbackText();
- return;
- }
- navigator.clipboard.read().then(function (cbItems) {
- var img = null, htmlIt = null;
- cbItems.forEach(function (it) {
- it.types.forEach(function (ty) {
- if (!img && ty.indexOf("image/") === 0) img = { it: it, ty: ty };
- if (!htmlIt && ty === "text/html") htmlIt = it;
- });
- });
- if (img) {
- img.it.getType(img.ty).then(function (blob) {
- OfficeApp.blobToSrc(blob, "pasted.png", function (src) {
- restoreSel();
- insertImage(src);
- }, function (msg) { OfficeApp.toast(msg, "error"); });
- }).catch(fallbackText);
- return;
- }
- if (htmlIt) {
- htmlIt.getType("text/html").then(function (blob) {
- return blob.text();
- }).then(function (html) {
- var clean = sanitizeHtml(html, { keepClasses: false });
- if (!clean) { fallbackText(); return; }
- if (suggesting && !inHeaderFooter()) {
- clean = '<ins class="doc-ins">' + clean + "</ins>";
- }
- restoreSel();
- try { document.execCommand("insertHTML", false, clean); } catch (e) { }
- afterEdit(true);
- adoptPastedImages();
- }).catch(fallbackText);
- return;
- }
- fallbackText();
- }).catch(fallbackText);
- }
- /* Pictures pasted from another window link into that window's working
- copies, which go when it closes: make them this window's own. */
- function adoptPastedImages() {
- var imgs = editor.querySelectorAll("img");
- Array.prototype.forEach.call(imgs, function (img) {
- ["src", "data-export-src"].forEach(function (attr) {
- var v = img.getAttribute(attr);
- if (!v || !OfficePlatform.isForeignWorkingCopy(v)) return;
- OfficePlatform.adoptSrc(v, function (nv) {
- if (nv === v || img.getAttribute(attr) !== v) return;
- img.setAttribute(attr, nv);
- OfficeApp.markDirty();
- });
- });
- });
- }
- /* ================= paste ================= */
- function handleEditorPaste(e) {
- var cd = e.clipboardData;
- if (!cd) return; // let the browser do its default thing
- e.preventDefault();
- // 1. image from clipboard -> dataURL <img>
- var items = cd.items || [];
- for (var i = 0; i < items.length; i++) {
- if (items[i].kind === "file" && items[i].type.indexOf("image/") === 0) {
- var f = items[i].getAsFile();
- if (f) {
- // small images inline; big ones upload to the workdir
- OfficeApp.blobToSrc(f, f.name || "pasted.png", function (src) {
- insertImage(src);
- }, function (msg) {
- OfficeApp.toast(msg, "error");
- });
- return;
- }
- }
- }
- // 2. HTML clipboard -> sanitized (scripts/styles/classes/ids stripped)
- var html = cd.getData("text/html");
- if (html) {
- var clean = sanitizeHtml(html, { keepClasses: false });
- if (clean) {
- if (suggesting && !inHeaderFooter()) {
- // pasted content is a suggestion too
- clean = '<ins class="doc-ins">' + clean + "</ins>";
- }
- try { document.execCommand("insertHTML", false, clean); } catch (err) { }
- afterEdit(true);
- adoptPastedImages();
- return;
- }
- }
- // 3. plain text (ignore another app's raw marker JSON - its rich
- // text/html form was handled above)
- var t = cd.getData("text/plain");
- if (t && !(window.OfficeClipboard && OfficeClipboard.isMarker(t))) {
- if (suggesting && !inHeaderFooter()) {
- suggestInsert(t);
- afterEdit(true);
- return;
- }
- try { document.execCommand("insertText", false, t); } catch (err) { }
- afterEdit(true);
- }
- }
- /* ================= exporters ================= */
- function exportBaseName() {
- return OfficeApp.stripExt(OfficeApp.getFileName() || "document") || "document";
- }
- function downloadFile(name, mime, content) {
- var blob = new Blob([content], { type: mime + ";charset=utf-8" });
- var url = URL.createObjectURL(blob);
- var a = document.createElement("a");
- a.href = url;
- a.download = name;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- setTimeout(function () { URL.revokeObjectURL(url); }, 5000);
- }
- /* ================= PDF =================
- Drawn in the browser from the pages the editor shows (docs_pdf.js),
- so the export paginates exactly like the preview, carries real
- selectable text, embeds the shipped CJK faces, and needs no server -
- it works in the standalone web edition too.
- The page is held only while it is measured, in its export state:
- 100% zoom (a zoomed layout rounds borders to different pixels), no
- selection chrome, and review marks shown as resolved - suggestions
- accepted, comment highlights off - which is what the other exports
- write too. Everything after that (fonts, pictures, compression) runs
- from the measured snapshot in a Web Worker, and the document can be
- edited meanwhile without changing the file that comes out. */
- function canExportPdf() {
- return typeof PDFLib !== "undefined" && !!window.DocsPdf;
- }
- function renderPdf(onProgress) {
- var prevZoom = 100;
- var relaid = false;
- var geo = pageGeometry();
- return DocsPdf.build({
- pageEl: pageEl,
- pages: function () { return lastPages; },
- sheetW: geo.sheetW, sheetH: geo.sheetH,
- title: exportBaseName(),
- onProgress: onProgress,
- enter: function () {
- clearFindHits();
- deselectImage();
- prevZoom = OfficeApp.getZoom() || 100;
- if (prevZoom !== 100) OfficeApp.setZoom(100);
- document.body.classList.add("doc-exporting");
- // hiding pending deletions changes the text flow; everything
- // else the export state does is paint only
- if (prevZoom !== 100 || editor.querySelector("del.doc-del")) {
- updatePageGuides();
- relaid = true;
- }
- },
- leave: function () {
- document.body.classList.remove("doc-exporting");
- if (prevZoom !== 100) OfficeApp.setZoom(prevZoom);
- if (relaid) updatePageGuides();
- }
- });
- }
- // how far along an export is, in words and as a fraction
- function pdfProgressText(done, total, stage) {
- if (stage === "measure") return { f: 0.02, msg: "Reading the pages..." };
- if (stage === "prepare") return { f: 0.06, msg: "Preparing fonts and pictures..." };
- if (stage === "save") return { f: 0.95, msg: "Writing the file..." };
- return {
- f: 0.1 + 0.85 * (total ? done / total : 0),
- msg: "Exporting " + done + " / " + total + (total === 1 ? " page" : " pages")
- };
- }
- /* savePdfTo renders and writes the bytes; shared by File > Export and by
- the .pdf entry in SAVE_FORMATS. prog is an optional progress panel. */
- function savePdfTo(fp, done, fail, prog) {
- if (!canExportPdf()) { fail("the PDF library failed to load"); return; }
- renderPdf(function (n, total, stage) {
- var p = pdfProgressText(n, total, stage);
- if (prog) prog.set(p.f * 100, 100, p.msg);
- else OfficeApp.setStatus("PDF: " + p.msg);
- }).then(function (bytes) {
- if (prog) prog.message("Writing " + OfficeApp.basename(fp) + "...");
- OfficePlatform.writeBytes(fp, bytes, done, fail);
- }).catch(function (err) {
- fail(err && err.message ? err.message : "render error");
- });
- }
- function exportPdf() {
- if (!canExportPdf()) {
- OfficeApp.toast("The PDF library failed to load", "error");
- return;
- }
- OfficePlatform.pickSave({ defaultName: exportBaseName() + ".pdf", ext: ".pdf", memoryKey: "export" }, function (file) {
- var fp = file.filepath;
- // the export does not hold the document: a panel in the corner
- // reports it while editing goes on
- var prog = OfficeApp.showProgress({ title: "Exporting PDF", anchor: "#workspace" });
- prog.set(0, 100, "Reading the pages...");
- savePdfTo(fp, function () {
- prog.close();
- OfficeApp.setStatus("Exported " + OfficeApp.basename(fp));
- OfficeApp.toast("Exported " + OfficeApp.basename(fp));
- }, function (msg) {
- prog.close();
- OfficeApp.toast("Export failed: " + msg, "error");
- }, prog);
- });
- }
- var EXPORT_CSS =
- "body{font-family:Arial,Helvetica,sans-serif;font-size:11pt;line-height:1.5;" +
- "color:#1f2328;max-width:820px;margin:24px auto;padding:0 18px;}" +
- "h1{font-size:20pt;}h2{font-size:16pt;}h3{font-size:13pt;}h4{font-size:11pt;font-style:italic;}" +
- ".doc-title{font-size:26pt;font-weight:400;}" +
- "a{color:#1a58c2;}" +
- "table{border-collapse:collapse;width:100%;}td,th{border:1px solid #b9bec7;padding:4px 8px;vertical-align:top;}" +
- "pre{background:#f1f3f4;border:1px solid #e2e5e9;border-radius:6px;padding:10px 12px;" +
- "font-family:Consolas,'Courier New',monospace;font-size:10pt;overflow-x:auto;white-space:pre-wrap;}" +
- "blockquote{border-left:3px solid #c3c7cc;margin-left:0;padding-left:12px;color:#5f6368;}" +
- "img{max-width:100%;height:auto;}" +
- "hr{border:none;border-top:1px solid #c9cdd3;}" +
- "ul.of-checklist{list-style:none;padding-left:1.4em;}" +
- "ul.of-checklist li::before{content:\"\\2610 \";}" +
- "ul.of-checklist li.checked::before{content:\"\\2611 \";}" +
- "ul.of-checklist li.checked{text-decoration:line-through;color:#888;}" +
- ".hf{color:#777;font-size:9pt;margin:10px 0;}";
- /* The three text renderings, built once and used twice: File > Export
- downloads them, and the matching saveFormats writer stores them - which
- is what a document opened from .html / .txt / .md is saved back into. */
- function buildHTML() {
- var body = currentBody();
- var title = exportBaseName();
- var out = "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n" +
- "<title>" + esc(title) + "</title>\n<style>" + EXPORT_CSS + "</style>\n</head>\n<body>\n";
- // a web page has no pages to repeat them on: one copy top and bottom,
- // and nothing at all when the header/footer are turned off
- var hf = body.hfMode !== "none";
- if (hf && body.header) out += '<div class="hf">' + esc(body.header) + "</div>\n";
- out += resolvedHtml() + "\n";
- if (hf && body.footer) out += '<div class="hf">' + esc(body.footer) + "</div>\n";
- out += "</body>\n</html>\n";
- return out;
- }
- function buildText() {
- var div = document.createElement("div");
- div.innerHTML = resolvedHtml();
- return div.innerText || "";
- }
- function buildMarkdown() {
- var div = document.createElement("div");
- div.innerHTML = resolvedHtml();
- return htmlToMarkdown(div).replace(/\n{3,}/g, "\n\n").trim() + "\n";
- }
- function exportHTML() { downloadFile(exportBaseName() + ".html", "text/html", buildHTML()); }
- function exportText() { downloadFile(exportBaseName() + ".txt", "text/plain", buildText()); }
- function exportMarkdown() { downloadFile(exportBaseName() + ".md", "text/markdown", buildMarkdown()); }
- /* --- basic HTML -> Markdown conversion (hand-written, MVP scope) --- */
- function htmlToMarkdown(rootEl) {
- function wrapMark(t, mark) {
- var m = t.match(/^(\s*)([\s\S]*?)(\s*)$/);
- if (!m || !m[2]) return "";
- return m[1] + mark + m[2] + mark + m[3];
- }
- function inline(node) {
- var out = "";
- var kids = node.childNodes;
- for (var i = 0; i < kids.length; i++) {
- var k = kids[i];
- if (k.nodeType === 3) { out += k.nodeValue.replace(/[ \t\r\n]+/g, " "); continue; }
- if (k.nodeType !== 1) continue;
- var tag = k.tagName;
- if (tag === "BR") { out += " \n"; continue; }
- if (tag === "IMG") {
- out += " || "") + ")";
- continue;
- }
- var inner = inline(k);
- switch (tag) {
- case "B": case "STRONG": out += wrapMark(inner, "**"); break;
- case "I": case "EM": out += wrapMark(inner, "*"); break;
- case "S": case "DEL": case "STRIKE": out += wrapMark(inner, "~~"); break;
- case "CODE": out += inner.trim() ? "`" + inner.trim() + "`" : ""; break;
- case "A":
- out += "[" + (inner.trim() || k.getAttribute("href") || "") +
- "](" + (k.getAttribute("href") || "") + ")";
- break;
- case "UL": case "OL": case "TABLE": case "PRE":
- case "BLOCKQUOTE": case "P": case "DIV":
- out += "\n" + block(k, "");
- break;
- default: out += inner;
- }
- }
- return out;
- }
- function list(el, indent) {
- var out = "";
- var isOl = el.tagName === "OL";
- var isCheck = el.classList.contains("of-checklist");
- var n = 0;
- for (var i = 0; i < el.children.length; i++) {
- var li = el.children[i];
- if (li.tagName !== "LI") continue;
- n++;
- var marker = isOl ? (n + ". ")
- : (isCheck ? (li.classList.contains("checked") ? "- [x] " : "- [ ] ") : "- ");
- var liClone = li.cloneNode(true);
- var nested = liClone.querySelectorAll("ul,ol");
- for (var j = nested.length - 1; j >= 0; j--) {
- if (nested[j].parentNode) nested[j].parentNode.removeChild(nested[j]);
- }
- out += indent + marker + inline(liClone).trim() + "\n";
- for (j = 0; j < li.children.length; j++) {
- var c = li.children[j];
- if (c.tagName === "UL" || c.tagName === "OL") out += list(c, indent + " ");
- }
- }
- return out;
- }
- function mdTable(el) {
- if (!el.rows || !el.rows.length) return "";
- var out = "";
- for (var i = 0; i < el.rows.length; i++) {
- var cells = el.rows[i].cells;
- var line = "|";
- for (var j = 0; j < cells.length; j++) {
- line += " " + inline(cells[j]).trim().replace(/\|/g, "\\|") + " |";
- }
- out += line + "\n";
- if (i === 0) {
- var sepLine = "|";
- for (j = 0; j < cells.length; j++) sepLine += " --- |";
- out += sepLine + "\n";
- }
- }
- return out;
- }
- function block(node, indent) {
- var out = "";
- var kids = node.childNodes;
- for (var i = 0; i < kids.length; i++) {
- var k = kids[i];
- if (k.nodeType === 3) {
- var raw = k.nodeValue.trim();
- if (raw) out += raw + "\n\n";
- continue;
- }
- if (k.nodeType !== 1) continue;
- var tag = k.tagName;
- if (/^H[1-6]$/.test(tag)) {
- var lvl = k.classList.contains("doc-title") ? 1 : parseInt(tag.substring(1), 10);
- out += new Array(lvl + 1).join("#") + " " + inline(k).trim() + "\n\n";
- } else if (tag === "UL" || tag === "OL") {
- out += list(k, indent) + "\n";
- } else if (tag === "BLOCKQUOTE") {
- var q = block(k, "").trim().split("\n").map(function (l) { return "> " + l; }).join("\n");
- out += q + "\n\n";
- } else if (tag === "PRE") {
- out += "```\n" + k.textContent.replace(/\n$/, "") + "\n```\n\n";
- } else if (tag === "HR") {
- out += "---\n\n";
- } else if (tag === "TABLE") {
- out += mdTable(k) + "\n";
- } else if (tag === "P" || tag === "DIV") {
- if (tag === "DIV" && k.querySelector("ul,ol,table,pre,blockquote,h1,h2,h3,h4,p,div,hr")) {
- out += block(k, indent);
- } else {
- var t = inline(k).trim();
- if (t) out += t + "\n\n";
- }
- } else {
- var t2 = inline(k).trim();
- if (t2) out += t2 + "\n\n";
- }
- }
- return out;
- }
- return block(rootEl, "");
- }
- /* ================= importers ================= */
- function setImportedContent(html) {
- pageConf = defaultPageConf();
- loadBody({ html: html, page: pageConf, header: "", footer: "", pageNumbers: false });
- undo.reset(snapshot());
- }
- function importTxt(text) {
- var paras = String(text).replace(/\r\n/g, "\n").replace(/\r/g, "\n").split(/\n{2,}/);
- var html = paras.map(function (p) {
- return "<p>" + (p.trim() ? esc(p).replace(/\n/g, "<br>") : "<br>") + "</p>";
- }).join("");
- setImportedContent(html);
- }
- function importMd(text) {
- var html = "";
- try {
- if (typeof marked !== "undefined") {
- html = (typeof marked.parse === "function") ? marked.parse(text) : marked(text);
- }
- } catch (e) { html = ""; }
- if (!html) {
- importTxt(text);
- return;
- }
- setImportedContent(sanitizeHtml(html, { keepClasses: false }));
- }
- function importHtml(text) {
- setImportedContent(sanitizeHtml(text, { keepClasses: false }));
- }
- /* ================= ODT import / export =================
- The document's own format, .docx, is opened and saved by the framework
- (OfficePlatform.documentLoad / documentSave). OpenDocument goes
- through the same Go converters either way: the office AGI library in
- ArozOS, the WebAssembly build of it (src/wasm/office) in the
- standalone web edition. One descriptor names both, and OfficePlatform
- picks. */
- var CONVERT_BACKEND = "Office/docs/backend/convert.agi";
- var CONVERT = {
- "import-odf": { agi: CONVERT_BACKEND, action: "import-odf", wasm: "odtToDocument" },
- "export-odf": { agi: CONVERT_BACKEND, action: "export-odf", wasm: "documentToOdt" }
- };
- function importDocFile(fp, fn, action) {
- OfficeApp.showBusy("Importing " + fn + "...");
- OfficePlatform.convertIn(CONVERT[action], fp, function (body) {
- OfficeApp.hideBusy();
- var b = body;
- if (typeof b === "string") {
- try { b = JSON.parse(b); } catch (e) { b = null; }
- }
- if (!b || typeof b.html !== "string") {
- OfficeApp.toast("Import failed: unexpected response", "error");
- return;
- }
- OfficeApp.splashStep("Laying out the pages...", function () {
- loadBody(b);
- undo.reset(snapshot());
- // the framework kept us attached to the source file, so Save
- // writes straight back to it in its own format
- OfficeApp.setStatus("Opened " + fn);
- OfficeApp.documentLoaded();
- });
- }, function (msg) {
- OfficeApp.hideBusy();
- OfficeApp.toast("Import failed: " + msg, "error");
- });
- }
- function importOdt(fp, fn) { importDocFile(fp, fn, "import-odf"); }
- /* ================= pictures Word cannot hold =================
- Word and the OpenDocument writers embed PNG, JPEG and GIF. A picture
- in anything else (an SVG chart pasted from Sheets or Slides, WebP,
- BMP) is rendered to PNG at 2x its display size before saving, and the
- PNG rides along in data-export-src - the writers prefer it, the
- editor keeps showing the original.
- Pictures are otherwise left alone: a storage picture stays a
- media?file= link and the server reads it, so a save never downloads
- and re-uploads them. The PNG renders are kept for the session and, in
- ArozOS, uploaded once (OfficePlatform.cacheBlob), so an unchanged
- chart costs nothing on the next save. */
- var exportPngCache = {}; // src + "|" + width -> PNG src
- function needsPngForExport(src) {
- if (/^data:image\/(svg|webp|bmp)/i.test(src)) return true;
- var path = String(src).split("#")[0];
- try { path = decodeURIComponent(path); } catch (e) { }
- return /\.(svg|webp|bmp)(\?|&|$)/i.test(path);
- }
- function rasterizeToPngSrc(src, w) {
- var key = src + "|" + w;
- if (exportPngCache[key]) return Promise.resolve(exportPngCache[key]);
- return new Promise(function (resolve) {
- var probe = new Image();
- probe.onload = function () {
- var cw = w || probe.naturalWidth || 400;
- var ch = cw * (probe.naturalHeight || 300) / (probe.naturalWidth || 400);
- var cv = document.createElement("canvas");
- cv.width = Math.max(1, Math.round(cw * 2));
- cv.height = Math.max(1, Math.round(ch * 2));
- var ctx = cv.getContext("2d");
- ctx.fillStyle = "#ffffff";
- ctx.fillRect(0, 0, cv.width, cv.height);
- try {
- ctx.drawImage(probe, 0, 0, cv.width, cv.height);
- } catch (e) { resolve(null); return; }
- cv.toBlob(function (blob) {
- if (!blob) { resolve(null); return; }
- OfficePlatform.cacheBlob(blob, "picture.png", function (out) {
- exportPngCache[key] = { src: out, w: cw, h: ch };
- resolve(exportPngCache[key]);
- }, function () { resolve(null); });
- }, "image/png");
- };
- probe.onerror = function () { resolve(null); };
- probe.src = src;
- });
- }
- // an img's display width in CSS px, from its style or width attribute
- function imgDisplayWidth(im) {
- var w = parseFloat((im.getAttribute("style") || "").replace(/^(?:.*;)?\s*width:\s*([\d.]+)px.*$/, "$1"));
- if (!(w > 0)) w = parseInt(im.getAttribute("width"), 10);
- return w > 0 ? w : 0;
- }
- /* html -> Promise(html) with data-export-src on every picture that needs
- one, and a stale one dropped from a picture that no longer does */
- function withExportPictures(html) {
- if (!html || html.indexOf("<img") < 0) return Promise.resolve(html);
- var div = document.createElement("div");
- div.innerHTML = html;
- var jobs = Array.prototype.slice.call(div.querySelectorAll("img")).map(function (im) {
- var src = im.getAttribute("src") || "";
- if (!needsPngForExport(src)) {
- im.removeAttribute("data-export-src");
- return null;
- }
- var w = imgDisplayWidth(im);
- var sized = w > 0 || /(^|;)\s*width\s*:/i.test(im.getAttribute("style") || "");
- return rasterizeToPngSrc(src, w).then(function (png) {
- if (!png) { im.removeAttribute("data-export-src"); return; }
- im.setAttribute("data-export-src", png.src);
- // the PNG is drawn at 2x: without a stated size the writer
- // would take its pixels for the picture's size
- if (!sized) {
- im.setAttribute("width", String(Math.round(png.w)));
- im.setAttribute("height", String(Math.round(png.h)));
- }
- });
- });
- return Promise.all(jobs).then(function () { return div.innerHTML; });
- }
- // the ODF writer reads src itself: swap the PNG in
- function exportSrcAsSrc(html) {
- if (!html || html.indexOf("data-export-src") < 0) return html;
- var div = document.createElement("div");
- div.innerHTML = html;
- var imgs = div.querySelectorAll("img[data-export-src]");
- for (var i = 0; i < imgs.length; i++) {
- imgs[i].setAttribute("src", imgs[i].getAttribute("data-export-src"));
- imgs[i].removeAttribute("data-export-src");
- }
- return div.innerHTML;
- }
- // what the framework calls before writing the .docx: body is its own copy
- function prepareNative(body) {
- var parts = ["html", "headerHtml", "footerHtml"];
- var jobs = parts.map(function (k) {
- if (typeof body[k] !== "string") return null;
- return withExportPictures(body[k]).then(function (h) { body[k] = h; });
- });
- (body.footnotes || []).forEach(function (fn) {
- jobs.push(withExportPictures(fn.html).then(function (h) { fn.html = h; }));
- });
- return Promise.all(jobs);
- }
- /* a body for the ODF writer: suggestions applied, comment anchors
- unwrapped (ODF does not get review markup), pictures as PNG */
- function odfBody() {
- var b = currentBody();
- b.html = resolvedHtml();
- return prepareNative(b).then(function () {
- ["html", "headerHtml", "footerHtml"].forEach(function (k) {
- if (typeof b[k] === "string") b[k] = exportSrcAsSrc(b[k]);
- });
- (b.footnotes || []).forEach(function (fn) { fn.html = exportSrcAsSrc(fn.html); });
- return b;
- });
- }
- function exportOdt() {
- if (!OfficePlatform.requireConvert("Exporting .odt")) return;
- var defName = exportBaseName() + ".odt";
- OfficePlatform.pickSave({ defaultName: defName, ext: ".odt", memoryKey: "export" }, function (file) {
- var fp = file.filepath;
- OfficeApp.showBusy("Exporting OpenDocument file...");
- odfBody().then(function (b) {
- // pictures stay links: the server reads them (office lib), and
- // the web edition keeps them inline already
- OfficePlatform.convertOut(CONVERT["export-odf"], fp, JSON.stringify(b), function () {
- OfficeApp.hideBusy();
- OfficeApp.setStatus("Exported " + OfficeApp.basename(fp));
- OfficeApp.toast("Exported " + OfficeApp.basename(fp));
- }, function (errmsg) {
- OfficeApp.hideBusy();
- OfficeApp.toast("Export failed: " + errmsg, "error");
- });
- });
- });
- }
- /* ================= saving back into a foreign format =================
- A document opened from .odt / .html / .md / .txt goes on living in
- that file: the framework keeps filepath/filename pointing at it and
- Ctrl+S comes back here instead of forcing a Save As to .docx. These
- are the same renderings the Export menu produces, reporting through
- the framework's save callbacks rather than a toast of their own. */
- function plural(n, one, many) { return n + " " + (n === 1 ? one : many); }
- function saveOdt(fp, done, fail) {
- odfBody().then(function (b) {
- OfficePlatform.convertOut(CONVERT["export-odf"], fp, JSON.stringify(b),
- function () { done(); }, fail);
- }).catch(function (err) {
- fail((err && err.message) ? err.message : "could not prepare the document");
- });
- }
- function saveTextFile(build, fp, done, fail) {
- var content;
- try { content = build(); }
- catch (e) { fail(e.message || "could not render the document"); return; }
- OfficeApp.vfsSave(fp, content, done, fail);
- }
- /*
- Comments and pending suggestions live in the .docx as Word's own
- comments and tracked changes; every other writer is fed
- resolvedHtml(), which unwraps the comment anchors, keeps insertions
- and drops deletions. That is a change to the text itself, so it is a
- veto rather than a quiet loss. Formatting a format merely renders
- differently is deliberately not listed - it would fire on nearly
- every save.
- */
- function reviewUnsupported() {
- var out = [];
- var c = (comments || []).length;
- if (c) out.push(plural(c, "comment", "comments"));
- var s = allSuggestions().length;
- if (s) {
- out.push(plural(s, "pending suggestion", "pending suggestions") +
- " - insertions would be accepted and deletions applied");
- }
- return out;
- }
- // .txt holds no pictures and no table structure at all
- function textUnsupported() {
- var out = reviewUnsupported();
- var imgs = editor.querySelectorAll("img").length;
- if (imgs) out.push(plural(imgs, "image", "images"));
- var tables = editor.querySelectorAll("table").length;
- if (tables) {
- out.push(plural(tables, "table", "tables") +
- " - only " + (tables === 1 ? "its" : "their") + " text would be kept");
- }
- return out;
- }
- /*
- The formats File > Save as offers besides .docx, and the ones a
- document opened from one of them is saved back into. needsConvert
- marks the writers that go through the Office format converters and
- needsBackend the ones that need a server outright (the real-text PDF
- renderer); OfficeApp drops whichever the running host cannot do,
- leaving the three text renderings - built right here in the browser -
- always available. PDF is oneWay: it is a rendering, so writing one
- leaves the document on its own file.
- */
- var SAVE_FORMATS = [
- {
- ext: ".odt", label: "OpenDocument text (.odt)", icon: "file alternate outline",
- needsConvert: true, noAutosave: true,
- unsupported: reviewUnsupported,
- save: function (fp, fn, done, fail) { saveOdt(fp, done, fail); }
- },
- {
- ext: ".pdf", label: "PDF document (.pdf)", icon: "file pdf outline",
- oneWay: true,
- save: function (fp, fn, done, fail) { savePdfTo(fp, done, fail); }
- },
- {
- ext: ".html", label: "Web page (.html)", icon: "file code outline",
- unsupported: reviewUnsupported,
- save: function (fp, fn, done, fail) { saveTextFile(buildHTML, fp, done, fail); }
- },
- {
- // the same writer under the other extension a web page may carry:
- // save-back only, so Save as does not offer it twice
- ext: ".htm", label: "Web page (.htm)", icon: "file code outline",
- hidden: true,
- unsupported: reviewUnsupported,
- save: function (fp, fn, done, fail) { saveTextFile(buildHTML, fp, done, fail); }
- },
- {
- ext: ".md", label: "Markdown (.md)", icon: "file alternate outline",
- unsupported: reviewUnsupported,
- save: function (fp, fn, done, fail) { saveTextFile(buildMarkdown, fp, done, fail); }
- },
- {
- ext: ".txt", label: "Plain text (.txt)", icon: "file outline",
- unsupported: textUnsupported,
- save: function (fp, fn, done, fail) { saveTextFile(buildText, fp, done, fail); }
- }
- ];
- /* ================= floating selection format bar ================= */
- /* PowerPoint-style mini toolbar (shared OfficeTextEditBar) floating
- above the current text selection inside the editor. */
- function initSelectionBar() {
- if (!window.OfficeTextEditBar) return;
- var barTimer = null;
- function selRect() {
- var sel = window.getSelection();
- if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return null;
- // a selected picture is not text: right-clicking one makes the
- // browser select the <img> node, which must not bring the bar up
- if (selectedImg && editor.contains(selectedImg)) return null;
- var range = sel.getRangeAt(0);
- if (!editor.contains(range.commonAncestorContainer)) return null;
- if (!/\S/.test(range.toString())) return null;
- var r = range.getBoundingClientRect();
- if (!r || (r.width === 0 && r.height === 0)) return null;
- return r;
- }
- function currentSelFontPx() {
- var n = window.getSelection().anchorNode;
- if (n && n.nodeType === 3) n = n.parentNode;
- if (!n || !editor.contains(n)) return 15;
- var fs = parseFloat(getComputedStyle(n).fontSize);
- return isNaN(fs) ? 15 : Math.round(fs);
- }
- document.addEventListener("selectionchange", function () {
- clearTimeout(barTimer);
- barTimer = setTimeout(function () {
- if ($(".of-dialog-overlay").length) return;
- var r = selRect();
- if (r) {
- if (!OfficeTextEditBar.isVisible()) {
- OfficeTextEditBar.show({
- anchor: editor,
- getRect: selRect,
- fontSize: currentSelFontPx(),
- onFontSize: function (px) { applyFontSize(Math.round(px * 0.75)); },
- tableOps: docsTableOps()
- });
- } else {
- // the bar is reused across selection moves - keep the
- // table section in step with where the caret sits
- OfficeTextEditBar.setTableOps(docsTableOps());
- }
- } else if (OfficeTextEditBar.isVisible() &&
- !OfficeTextEditBar.contains(document.activeElement)) {
- OfficeTextEditBar.hide();
- }
- }, 180);
- });
- // keep the bar glued to the text when the document scrolls
- workspaceEl.addEventListener("scroll", function () {
- if (OfficeTextEditBar.isVisible()) OfficeTextEditBar.reposition();
- });
- }
- /* ================= table column / row resizing ================= */
- /* Drag a cell's right border to resize its column (Word-style: the
- neighbour column compensates; the table's outer edge grows the
- table). Drag a bottom border to change the row height. */
- var tblDrag = null;
- function zoomFactor() { return (OfficeApp.getZoom() || 100) / 100; }
- function tableBorderHit(e) {
- if (inHeaderFooter()) return null;
- var cell = e.target.closest ? e.target.closest("td,th") : null;
- if (!cell || !editor.contains(cell)) return null;
- var r = cell.getBoundingClientRect();
- var HOT = 5;
- if (e.clientX >= r.right - HOT && e.clientX <= r.right + HOT) return { cell: cell, type: "col" };
- if (e.clientY >= r.bottom - HOT && e.clientY <= r.bottom + HOT) return { cell: cell, type: "row" };
- return null;
- }
- function cellColIndex(cell) {
- var i = 0;
- var n = cell;
- while (n.previousElementSibling) { n = n.previousElementSibling; i++; }
- return i;
- }
- /* give the table an explicit colgroup so column widths stick */
- function ensureColgroup(table) {
- var cg = table.querySelector("colgroup");
- var firstRow = table.rows.length ? table.rows[0] : null;
- if (!firstRow) return null;
- var cols = firstRow.cells.length;
- if (!cg || cg.children.length !== cols) {
- if (cg) cg.parentNode.removeChild(cg);
- cg = document.createElement("colgroup");
- for (var i = 0; i < cols; i++) {
- var col = document.createElement("col");
- col.style.width = firstRow.cells[i].offsetWidth + "px";
- cg.appendChild(col);
- }
- table.insertBefore(cg, table.firstChild);
- table.style.tableLayout = "fixed";
- table.style.width = table.offsetWidth + "px";
- }
- return cg;
- }
- function onTblPointerMove(e) {
- if (tblDrag) {
- var z = zoomFactor();
- if (tblDrag.type === "col") {
- var dx = (e.clientX - tblDrag.startX) / z;
- var cols = tblDrag.cg.children;
- var i = tblDrag.idx;
- if (i < cols.length - 1) {
- // inner border: this column grows, the neighbour shrinks
- var wA = Math.max(24, tblDrag.wA + dx);
- var give = wA - tblDrag.wA;
- var wB = Math.max(24, tblDrag.wB - give);
- cols[i].style.width = Math.round(tblDrag.wA + tblDrag.wB - wB) + "px";
- cols[i + 1].style.width = Math.round(wB) + "px";
- } else {
- // outer border: the whole table grows/shrinks
- var w = Math.max(24, tblDrag.wA + dx);
- cols[i].style.width = Math.round(w) + "px";
- tblDrag.table.style.width = Math.round(tblDrag.tw + (w - tblDrag.wA)) + "px";
- }
- } else {
- var dy = (e.clientY - tblDrag.startY) / z;
- tblDrag.row.style.height = Math.max(18, Math.round(tblDrag.h + dy)) + "px";
- }
- e.preventDefault();
- return;
- }
- var hit = tableBorderHit(e);
- editor.style.cursor = hit ? (hit.type === "col" ? "col-resize" : "row-resize") : "";
- }
- function onTblPointerDown(e) {
- var hit = tableBorderHit(e);
- if (!hit) return;
- var table = hit.cell.closest("table");
- if (!table) return;
- e.preventDefault(); // keep the caret where it is
- if (hit.type === "col") {
- var cg = ensureColgroup(table);
- if (!cg) return;
- var idx = cellColIndex(hit.cell);
- if (idx >= cg.children.length) idx = cg.children.length - 1;
- tblDrag = {
- type: "col", table: table, cg: cg, idx: idx,
- startX: e.clientX,
- wA: parseFloat(cg.children[idx].style.width) || hit.cell.offsetWidth,
- wB: (idx < cg.children.length - 1)
- ? (parseFloat(cg.children[idx + 1].style.width) || 0)
- : 0,
- tw: table.offsetWidth
- };
- } else {
- var row = hit.cell.parentElement;
- tblDrag = { type: "row", row: row, startY: e.clientY, h: row.offsetHeight };
- }
- document.addEventListener("pointermove", onTblPointerMove);
- document.addEventListener("pointerup", onTblPointerUp);
- document.body.style.userSelect = "none";
- }
- function onTblPointerUp() {
- document.removeEventListener("pointermove", onTblPointerMove);
- document.removeEventListener("pointerup", onTblPointerUp);
- document.body.style.userSelect = "";
- if (tblDrag) {
- tblDrag = null;
- afterEdit(true);
- }
- }
- function initTableResize() {
- editor.addEventListener("pointermove", onTblPointerMove);
- editor.addEventListener("pointerdown", onTblPointerDown);
- }
- /* ================= editor events ================= */
- // keys that change the text: Backspace/Delete at the caret, and anything
- // typed, cut or pasted over a selection
- function editsAcrossPages(e) {
- if (e.key === "Backspace" || e.key === "Delete") return true;
- var sel = window.getSelection();
- if (!sel || !sel.rangeCount || sel.getRangeAt(0).collapsed) return false;
- if (e.key === "Enter" || e.key === "Tab") return true;
- if ((e.ctrlKey || e.metaKey) && !e.altKey) return /^[xv]$/i.test(e.key);
- return e.key.length === 1;
- }
- function bindEditorEvents() {
- editor.addEventListener("input", function () {
- noteEditAtCaret();
- OfficeApp.markDirty();
- scheduleCounts();
- undo.pushDebounced(snapshot, 600);
- });
- editor.addEventListener("paste", handleEditorPaste);
- document.addEventListener("copy", function (e) { handleImageCopyCut(e, false); });
- document.addEventListener("cut", function (e) { handleImageCopyCut(e, true); });
- // track changes: intercept typing/deleting while suggesting
- editor.addEventListener("beforeinput", onEditorBeforeInput);
- editor.addEventListener("click", function (e) {
- var t = e.target;
- // checklist checkbox toggle (click lands in the ::before gutter)
- if (t.tagName === "LI" && t.parentElement &&
- t.parentElement.classList.contains("of-checklist")) {
- var r = t.getBoundingClientRect();
- if (e.clientX < r.left) {
- t.classList.toggle("checked");
- afterEdit(true);
- e.preventDefault();
- return;
- }
- }
- if (t.tagName === "IMG") {
- selectImage(t);
- e.preventDefault();
- return;
- }
- if (selectedImg) deselectImage();
- var cmtHit = t.closest ? t.closest("span.doc-cmt") : null;
- if (cmtHit && editor.contains(cmtHit)) {
- showCommentsPanel(true);
- renderCommentsPanel(cmtHit.getAttribute("data-cid"));
- }
- var tocLine = (e.ctrlKey || e.metaKey) && t.closest ? t.closest("p.doc-toc") : null;
- if (tocLine && editor.contains(tocLine) && followTocEntry(tocLine)) {
- e.preventDefault();
- return;
- }
- var a = t.closest ? t.closest("a") : null;
- if (a && editor.contains(a)) {
- e.preventDefault();
- if (e.ctrlKey || e.metaKey) {
- try { window.open(a.href, "_blank", "noopener"); } catch (err) { }
- } else {
- OfficeApp.setStatus("Ctrl+Click to open link: " + (a.getAttribute("href") || ""), "info", 4000);
- }
- }
- });
- pageEl.addEventListener("mousemove", trackTocHover);
- pageEl.addEventListener("mouseleave", function () { if (tocHover) leaveTocHover(); });
- editor.addEventListener("dblclick", function (e) {
- if (e.target.tagName === "IMG") {
- selectImage(e.target);
- imageSizeDialog(e.target);
- }
- });
- editor.addEventListener("keydown", function (e) {
- // a page boundary in the way of the edit is taken out first, so
- // the key acts on the text on both sides of it
- if (!selectedImg && !e.isComposing && editsAcrossPages(e)) {
- if (DocsLayout.unsplitAtCaret(editor, e.key !== "Delete")) noteEditAtCaret();
- }
- if ((e.key === "Delete" || e.key === "Backspace") && selectedImg) {
- e.preventDefault();
- var img = selectedImg;
- deselectImage();
- if (img.parentNode) img.parentNode.removeChild(img);
- afterEdit(true);
- return;
- }
- if (e.key === "Tab") {
- e.preventDefault();
- try { document.execCommand(e.shiftKey ? "outdent" : "indent"); } catch (err) { }
- afterEdit(false);
- }
- });
- // editor context menu: table ops + multi-column region control
- editor.addEventListener("contextmenu", function (e) {
- var items = [];
- if (e.target.tagName === "IMG" && editor.contains(e.target)) {
- if (selectedImg !== e.target) selectImage(e.target);
- items = items.concat(pictureMenuItems(e.target));
- items.push({ sep: true });
- }
- // review: accept/reject the suggestion under the pointer
- var sug = e.target.closest ? e.target.closest("ins.doc-ins, del.doc-del") : null;
- if (sug && editor.contains(sug)) {
- var what = sug.tagName === "INS" ? "insertion" : "deletion";
- items.push({
- label: "Accept " + what, icon: "check",
- action: function () { resolveSuggestion(sug, true); }
- });
- items.push({
- label: "Reject " + what, icon: "times",
- action: function () { resolveSuggestion(sug, false); }
- });
- items.push({ sep: true });
- }
- // review: comment actions
- var cmtEl = e.target.closest ? e.target.closest("span.doc-cmt") : null;
- if (cmtEl && editor.contains(cmtEl)) {
- var cm = commentById(cmtEl.getAttribute("data-cid"));
- if (cm) {
- items.push({
- label: "View comment", icon: "comment outline",
- action: function () {
- showCommentsPanel(true);
- renderCommentsPanel(cm.id);
- }
- });
- items.push({
- label: "Resolve comment", icon: "check",
- action: function () { resolveComment(cm.id, false); }
- });
- items.push({ sep: true });
- }
- } else {
- var selNow = window.getSelection();
- if (selNow && selNow.rangeCount && !selNow.getRangeAt(0).collapsed &&
- editor.contains(selNow.getRangeAt(0).commonAncestorContainer)) {
- items.push({
- label: "Comment...", icon: "comment outline", key: "Ctrl+Alt+M",
- action: function () { commentDialog(null); }
- });
- items.push({ sep: true });
- }
- }
- var cell = e.target.closest ? e.target.closest("td,th") : null;
- if (cell && cell.closest("table.of-table") && editor.contains(cell)) {
- items.push({ label: "Table", icon: "table", sub: tableMenuItemsFor(cell) });
- items.push({ sep: true });
- }
- if (pageConf.columns > 1) {
- // let the user pick which region spans the full page width
- var block = e.target.closest ? e.target.closest(BLOCK_SEL) : null;
- if (block && editor.contains(block)) {
- items.push({
- label: "Full width (span all columns)", icon: "columns",
- checked: function () { return block.classList.contains("col-span-all"); },
- action: function () {
- block.classList.toggle("col-span-all");
- afterEdit(true);
- }
- });
- items.push({
- label: "Show layout boxes",
- checked: function () { return document.body.classList.contains("doc-show-boxes"); },
- action: toggleLayoutBoxes
- });
- items.push({ sep: true });
- }
- }
- // standard edit block (like Google Docs / Word)
- var selNow2 = window.getSelection();
- var canCopy = !!selectedImg || !!(selNow2 && selNow2.rangeCount &&
- !selNow2.getRangeAt(0).collapsed &&
- editor.contains(selNow2.getRangeAt(0).commonAncestorContainer));
- var copyOk = function () { return canCopy; };
- items.push({ label: "Cut", icon: "cut", key: "Ctrl+X", enabled: copyOk, action: function () { menuCutCopy(true); } });
- items.push({ label: "Copy", icon: "copy", key: "Ctrl+C", enabled: copyOk, action: function () { menuCutCopy(false); } });
- items.push({ label: "Paste", icon: "paste", key: "Ctrl+V", action: function () { pasteFromMenu(false); } });
- items.push({ label: "Paste without formatting", icon: "clipboard outline", action: function () { pasteFromMenu(true); } });
- items.push({ sep: true });
- items.push({ label: "Bold", icon: "bold", key: "Ctrl+B", action: function () { exec("bold"); } });
- items.push({ label: "Italic", icon: "italic", key: "Ctrl+I", action: function () { exec("italic"); } });
- items.push({ label: "Underline", icon: "underline", key: "Ctrl+U", action: function () { exec("underline"); } });
- items.push({ label: "Clear formatting", icon: "eraser", action: clearFormatting });
- items.push({ sep: true });
- // on a link the link entry takes it off instead of adding one
- var linkHit = e.target.closest ? e.target.closest("a[href]") : null;
- if (linkHit && editor.contains(linkHit)) {
- items.push({ label: "Remove link", icon: "unlinkify", action: function () { removeLink(linkHit); } });
- } else {
- items.push({ label: "Insert link...", icon: "linkify", key: "Ctrl+K", action: linkDialog });
- }
- items.push({ label: "Insert page break", icon: "file outline", key: "Ctrl+Enter", action: insertPageBreak });
- items.push({ sep: true });
- items.push({ label: "Select all", icon: "i cursor", key: "Ctrl+A", action: selectAll });
- e.preventDefault();
- OfficeApp.showContextMenu(e.clientX, e.clientY, items);
- });
- // deselect image when clicking anywhere else / typing starts elsewhere;
- // app chrome (ribbon, menus, dialogs, popups) keeps it selected, or
- // the Picture Format tab would vanish under the click that opens it
- document.addEventListener("mousedown", function (e) {
- if (selectedImg && e.target !== selectedImg && e.target !== imgHandle &&
- !$(e.target).closest(".of-ribbon, .of-rb-tab, .of-rb-popup, .of-rb-gpop, " +
- ".of-menubar, .of-context-menu, .of-float-menu, .of-cp-panel, .of-dialog-overlay").length) {
- deselectImage();
- }
- });
- workspaceEl.addEventListener("scroll", positionImgHandle);
- window.addEventListener("resize", positionImgHandle);
- // header / footer: plain single-line text only, kept in sync across
- // every page's copy (bindHfEvents also runs for the copies)
- bindHfEvents(headerEl);
- bindHfEvents(footerEl);
- // re-paginate when the flow grows on its own (pictures decoding after
- // a document is opened, web fonts, a resize)
- watchContentSize();
- }
- /* ================= shortcuts ================= */
- function bindShortcuts() {
- OfficeApp.registerShortcut("Ctrl+B", function () { exec("bold"); }, { description: "Bold", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+I", function () { exec("italic"); }, { description: "Italic", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+U", function () { exec("underline"); }, { description: "Underline", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+Shift+X", function () { exec("strikeThrough"); }, { description: "Strikethrough", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+K", linkDialog, { description: "Insert link", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+Alt+M", function () { commentDialog(null); },
- { description: "Add comment", group: "Review" });
- OfficeApp.registerShortcut("Ctrl+Enter", insertPageBreak,
- { description: "Insert page break", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+F", function () { openFind(false); }, { description: "Find" });
- OfficeApp.registerShortcut("Ctrl+]", function () { stepFontSize(1); }, { description: "Increase font size", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+[", function () { stepFontSize(-1); }, { description: "Decrease font size", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+,", function () { exec("subscript"); }, { description: "Subscript", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+.", function () { exec("superscript"); }, { description: "Superscript", group: "Text" });
- OfficeApp.registerShortcut("Ctrl+Alt+F", insertFootnote, { description: "Insert footnote", group: "Text" });
- // Escape puts the format painter down (and falls through)
- OfficeHotkeys.register("Escape", function () {
- if (painter) stopPainter();
- return false;
- }, { id: "docs.painteresc", allowInInput: true });
- OfficeApp.registerShortcut("Ctrl+H", function () { openFind(true); }, { description: "Find and replace" });
- // lists - register both the digit and the shifted symbol (layout dependent)
- OfficeApp.registerShortcut("Ctrl+Shift+7", function () { exec("insertOrderedList"); });
- OfficeApp.registerShortcut("Ctrl+Shift+&", function () { exec("insertOrderedList"); });
- OfficeApp.registerShortcut("Ctrl+Shift+8", function () { exec("insertUnorderedList"); });
- OfficeApp.registerShortcut("Ctrl+Shift+*", function () { exec("insertUnorderedList"); });
- }
- /* ================= boot ================= */
- /* the few entry points other scripts (and automated checks) use - the
- counterpart of SlidesApp */
- window.DocsApp = {
- currentBody: function () { return currentBody(); },
- loadBody: function (b) { loadBody(b); },
- renderPdf: renderPdf,
- pages: function () { return lastPages.slice(); }
- };
- $(document).ready(function () {
- editor = document.getElementById("editor");
- headerEl = document.getElementById("docHeader");
- footerEl = document.getElementById("docFooter");
- pageEl = document.getElementById("page");
- workspaceEl = document.getElementById("workspace");
- undo = new OfficeUndoStack({
- limit: 100,
- apply: function (s) { applySnapshot(s); }
- });
- buildToolbar();
- trackSelection();
- bindEditorEvents();
- bindFindPanel();
- try { document.execCommand("styleWithCSS", false, true); } catch (e) { }
- try { document.execCommand("defaultParagraphSeparator", false, "p"); } catch (e) { }
- OfficeApp.init({
- appName: "Docs",
- appType: "document",
- appIcon: "../img/docs.svg",
- extension: ".docx",
- nativeLabel: "Word document (.docx)",
- fileTypeName: "Document",
- defaultFileName: "New Document",
- // pictures Word cannot hold get a PNG beside them before a save
- prepareNative: prepareNative,
- serialize: function () { return currentBody(); },
- deserialize: function (body) {
- loadBody(body);
- undo.reset(snapshot());
- },
- create: function () {
- pageConf = defaultPageConf();
- loadBody({ html: "<p><br></p>", page: pageConf, header: "", footer: "", pageNumbers: false });
- undo.reset(snapshot());
- },
- importers: {
- ".txt": function (text) { importTxt(text); },
- ".md": function (text) { importMd(text); },
- ".html": function (text) { importHtml(text); },
- ".htm": function (text) { importHtml(text); }
- },
- // Word 97-2003 documents open by conversion (mod/office/doc),
- // as imports: Save writes the app's own format
- legacyExtensions: [".doc", ".dot"],
- binaryImporters: {
- ".odt": importOdt
- },
- saveFormats: SAVE_FORMATS,
- onUndo: doUndo,
- onRedo: doRedo,
- canUndo: function () { return undo.canUndo(); },
- canRedo: function () { return undo.canRedo(); },
- // Edit menubar clipboard shares the context-menu implementations
- // (image-aware copy, async rich paste)
- // the ribbon (buildToolbar) carries Insert, Format and View; File
- // and Edit stay menus
- ribbon: true,
- editMenuExtras: [
- { label: "Paste without formatting", icon: "file alternate outline", key: "Ctrl+Shift+V", action: function () { pasteFromMenu(true); } },
- { sep: true },
- { label: "Select all", icon: "i cursor", key: "Ctrl+A", action: selectAll },
- {
- label: "Format painter", icon: "paint brush",
- action: function () { startPainter(false); }
- },
- { sep: true },
- { label: "Find...", icon: "search", key: "Ctrl+F", action: function () { openFind(false); } },
- { label: "Find and replace...", icon: "exchange", key: "Ctrl+H", action: function () { openFind(true); } }
- ],
- onCut: function () { menuCutCopy(true); },
- onCopy: function () { menuCutCopy(false); },
- onPaste: function () { pasteFromMenu(false); },
- /*
- .odt needs the Office converters - the AGI backend in ArozOS,
- the WebAssembly module in the web edition. .docx is the
- document's own format (File > Save / Save as). .pdf, .html,
- .md and .txt are rendered right here and are always
- available.
- */
- fileMenuExtras: [
- { label: "Page setup...", icon: "file alternate outline", action: pageSetupDialog },
- {
- label: "Export", icon: "external alternate",
- sub: function () {
- var items = [];
- if (OfficePlatform.canConvert()) {
- items.push({ label: "OpenDocument (.odt)", icon: "file alternate outline", action: exportOdt });
- }
- items.push({ label: "PDF document (.pdf)", icon: "file pdf outline", action: exportPdf });
- items.push({ label: "Web page (.html)", icon: "file code outline", action: exportHTML });
- items.push({ label: "Markdown (.md)", icon: "file alternate outline", action: exportMarkdown });
- items.push({ label: "Plain text (.txt)", icon: "file outline", action: exportText });
- return items;
- }
- }
- ],
- zoomTarget: "#page",
- onZoomChanged: function () { positionImgHandle(); },
- onBeforePrint: function () {
- closeFind();
- deselectImage();
- OfficeApp.closeAllMenus();
- },
- onBeforeSave: function () {
- clearFindHits();
- deselectImage();
- }
- });
- bindShortcuts();
- initSelectionBar();
- initTableResize();
- buildCommentsPanel();
- OfficeApp.addStatusItem("suggest", "");
- OfficeApp.addStatusItem("pg", "Page 1 of 1");
- OfficeApp.addStatusItem("wc", "0 words · 0 characters");
- document.addEventListener("selectionchange", function () {
- var sel = window.getSelection();
- if (sel && sel.anchorNode && pageEl.contains(sel.anchorNode)) schedulePageIndicator("caret");
- });
- workspaceEl.addEventListener("scroll", function () { schedulePageIndicator("scroll"); }, { passive: true });
- if (OfficeApp.getSetting("cmtPanel", false)) showCommentsPanel(true);
- updateSuggestStatus();
- if (OfficeApp.getSetting("layoutBoxes", false)) {
- document.body.classList.add("doc-show-boxes");
- }
- if (OfficeApp.getSetting("marks", false)) document.body.classList.add("doc-show-marks");
- // the format painter lays its format on the selection a drag ends
- editor.addEventListener("mouseup", function () {
- if (painter) setTimeout(applyPainter, 0);
- });
- // a phone shows the page fitted to its width (not saved as the zoom);
- // a narrow desktop window (the float window opens small) keeps 100%
- var onPhone = Math.min(window.screen.width || 9999, window.screen.height || 9999) < 768 &&
- !!(window.matchMedia && window.matchMedia("(pointer: coarse)").matches);
- var fitNarrow = function () {
- if (onPhone && OfficeRibbon.isNarrow()) fitPageWidth(true);
- };
- setTimeout(fitNarrow, 60);
- var fitTimer = null;
- $(window).on("resize", function () {
- clearTimeout(fitTimer);
- fitTimer = setTimeout(fitNarrow, 150);
- });
- editor.spellcheck = OfficeApp.getSetting("spellcheck", true);
- updateCounts();
- editor.focus();
- });
- })();
|