docs.js 281 KB

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