docs.js 244 KB

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