slides.js 260 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525
  1. /*
  2. ArozOS Office - Slides editor
  3. ==============================================================
  4. Body schema (what serialize() returns / deserialize() receives):
  5. {
  6. size: [960, 540], // slide coordinate space: 960 wide, as
  7. // tall as the deck's shape (720 = 4:3)
  8. theme: "clean", // key into THEMES
  9. slides: [
  10. {
  11. id: "s-xxxx",
  12. bg: "#rrggbb" | null, // null = use theme background
  13. bgImage: { src, x, y, w, h, tile, opacity }, // optional picture
  14. // background, placed in slide px (may
  15. // reach past the edges) or tiled
  16. bgGrad: { kind: "linear"|"radial", angle, cx, cy,
  17. stops: [{ pos, color }] }, // optional gradient
  18. // background; either one is drawn over
  19. // bg and kept until a colour is chosen
  20. notes: "speaker notes plain text",
  21. transition: "none" | "fade" | "slide" | "zoom", // entry transition
  22. objects: [
  23. {
  24. id: "o-xxxx",
  25. type: "text" | "image" | "shape" | "line" | "table" |
  26. "chart" | "video" | "audio",
  27. x, y, w, h, // slide units; for "line" w/h is the
  28. // vector to the 2nd endpoint (may be negative)
  29. rot: 0, // degrees, rotation about center (not lines)
  30. z: 1, // stacking order (mirrors array order)
  31. group: "g-xx", // optional: objects sharing a group id
  32. // select and move as one unit
  33. props: { ... } // per type:
  34. // text : { html, fontSize, color, align, bold, italic, underline }
  35. // image: { src, fit: "contain"|"cover"|"fill" }
  36. // shape: { kind: a SlidesShapes name, which is the
  37. // PresentationML preset name -
  38. // "rect"|"roundRect"|"ellipse"|"rightBrace"|...,
  39. // or "custom" with geom (an imported freeform:
  40. // { paths: [{ w, h, d, noFill, noStroke }] },
  41. // M/L/C/Z in each path's own w x h space)
  42. // fill ("#rrggbb" or "#rrggbbaa"), fillGrad (as bgGrad),
  43. // stroke, strokeW, text, textColor, fontSize, bold,
  44. // adj: { adj1, adj2, ... } - a callout's tip, and the
  45. // guides of the presets drawn to PowerPoint's
  46. // formulas (chevron, arrows, ...; SlidesShapes) }
  47. // line : { stroke, strokeW, dashStyle, startHead, endHead }
  48. // (slides_lines.js; older documents say
  49. // dash / arrowEnd / arrowStart instead)
  50. // table: { rows: [["a","b"],...], headerRow, colW?, rowH?, fontSize, color,
  51. // merges?: [[row, col, rowSpan, colSpan], ...],
  52. // cellAnchor?: [["", "middle", "bottom"], ...],
  53. // styled? (an imported table style: its own fills,
  54. // text and rules - stroke / strokeW - and no
  55. // heading look from the editor) }
  56. // chart: { spec: <OfficeCharts spec> }
  57. // video: { src (data URL), autoplay }
  58. // audio: { src (data URL), autoplay }
  59. // any type may also carry:
  60. // anim: "" | "fade" | "slide" | "zoom" entrance animation,
  61. // revealed click-by-click in present mode
  62. // link: "" | "#3" (go to slide 3) | "https://..."
  63. // followed when clicked in present mode
  64. }
  65. ]
  66. }
  67. ],
  68. fonts: [ // optional: font faces a .pptx/.odp
  69. { family, weight, style, src } // brought with it, installed as
  70. ] // @font-face (see installEmbeddedFonts)
  71. }
  72. Objects imported from a .pptx / .odp carry extra props that keep the
  73. typography and geometry of the file they came from. All are optional -
  74. an object made in the editor omits them and falls back to the
  75. stylesheet. See "Imported-deck fidelity props" in common/CONTRACT.md:
  76. text / shape : fontFamily, valign, pad[t,r,b,l], lineHeight,
  77. and on a shape, html (rich text in place of text)
  78. image : crop[l,t,r,b] fractions, radius, opacity, and fill /
  79. fillGrad on the frame (seen through transparent parts)
  80. line : points (a bent connector's polyline), arrowStart
  81. table : cellFill[][], cellPad[t,r,b,l]
  82. An image also carries what the picture tools put on it:
  83. crop[l,t,r,b] / mask / radius the crop and the shaped crop
  84. adj the shaped crop's adjustments (its
  85. handles; same guides as a shape's)
  86. orig {x,y,w,h} the frame Reset image puts back
  87. flipH / flipV mirrored horizontally / vertically
  88. recolor / bright / contrast the colour treatment (slides_image.js)
  89. opacity 1 - transparency
  90. These are the same props the pptx reader writes, because a crop or a
  91. tint made here and one made in PowerPoint mean the same thing. See the
  92. "image crop tool" section below, slides_image.js for the tools that
  93. edit them, and CONTRACT.md for the frame-vs-source identity they obey.
  94. */
  95. var SlidesApp = (function () {
  96. "use strict";
  97. /* ================= constants ================= */
  98. /* The slide is 960 px wide; its height follows the deck's shape (540
  99. for 16:9, 720 for a 4:3 deck from PowerPoint). Both are the current
  100. deck's, set from body.size by setSlideSize() whenever a document
  101. comes in, and published as --sl-w / --sl-h / --sl-ar so every slide
  102. surface in slides.css - canvas, rail, overview, present, print -
  103. takes the same shape. */
  104. var SLIDE_W = 960, SLIDE_H = 540;
  105. var GRID = 10;
  106. var GUIDE_TOL = 5;
  107. var THEMES = {
  108. clean: { label: "Clean", bg: "#ffffff", text: "#202124", accent: "#e07b1f" },
  109. midnight: { label: "Midnight", bg: "linear-gradient(135deg,#232a36 0%,#0b0e13 100%)", text: "#e8eaed", accent: "#4c9be8" },
  110. ocean: { label: "Ocean", bg: "linear-gradient(135deg,#0f4c75 0%,#3282b8 100%)", text: "#f4faff", accent: "#bbe1fa" },
  111. sunset: { label: "Sunset", bg: "linear-gradient(135deg,#c0392b 0%,#8e44ad 100%)", text: "#fdf2ec", accent: "#f8c471" },
  112. forest: { label: "Forest", bg: "linear-gradient(160deg,#0f3d33 0%,#1e6f5c 100%)", text: "#eafaf1", accent: "#7dcea0" },
  113. paper: { label: "Paper", bg: "#f6f1e5", text: "#3d3a33", accent: "#8e44ad" }
  114. };
  115. var TYPE_NAMES = {
  116. text: "Text box", image: "Image", shape: "Shape",
  117. line: "Line", table: "Table", chart: "Chart",
  118. video: "Video", audio: "Audio"
  119. };
  120. var TRANSITIONS = [
  121. { key: "none", label: "None" },
  122. { key: "fade", label: "Fade" },
  123. { key: "slide", label: "Slide in" },
  124. { key: "zoom", label: "Zoom" }
  125. ];
  126. var ANIMS = [
  127. { key: "", label: "None" },
  128. { key: "fade", label: "Fade in" },
  129. { key: "slide", label: "Slide in" },
  130. { key: "zoom", label: "Zoom in" }
  131. ];
  132. var MEDIA_MAX_BYTES = 200 * 1024 * 1024; // uploads stream to the workdir
  133. /* What a picture can be masked to. Deliberately a short list and not
  134. the whole catalogue, for two reasons. A mask reads as a silhouette,
  135. so the outlines worth offering are the ones that still say something
  136. at thumbnail size - and every one of these is a polygon, which is
  137. what lets maskClipPath() state it in percentages so the clip follows
  138. the frame while it is being dragged. A curved shape would have to be
  139. restated in pixels at every size. Every shape the editor can draw
  140. lives in SlidesShapes (slides_shapes.js) and is offered by the
  141. Insert > Shape picker. */
  142. var MASK_KINDS = [
  143. "rect", "roundRect", "ellipse", "triangle", "rtTriangle", "diamond",
  144. "pentagon", "hexagon", "heptagon", "octagon", "decagon", "dodecagon",
  145. "parallelogram", "trapezoid", "plus", "star4", "star5", "star6",
  146. "star8", "star12", "chevron", "homePlate", "rightArrow", "leftArrow",
  147. "upArrow", "downArrow", "leftRightArrow", "upDownArrow",
  148. "flowChartManualInput", "flowChartInputOutput", "irregularSeal1"
  149. ].map(function (k) {
  150. return { kind: k, label: SlidesShapes.label(k) };
  151. });
  152. /* ================= state ================= */
  153. var body = null; // document body (see schema above)
  154. var cur = 0; // current slide index
  155. var sel = []; // selected object ids on the current slide
  156. var undo = null; // OfficeUndoStack
  157. var clip = null; // internal object clipboard (array of clones)
  158. var editingId = null; // object id currently in text-edit mode
  159. var editingKind = null; // "text" | "shape" | "table"
  160. var pendingDraw = null; // "line" | "arrow" when a draw is armed
  161. var lastCell = null; // {r,c} last clicked table cell
  162. var zoomPct = 100;
  163. var fitScale = 1;
  164. var drag = null; // active pointer interaction
  165. var rafPending = false;
  166. var lastPointerEvt = null;
  167. var thumbTimer = null;
  168. var snapGrid = false;
  169. /* image crop mode: cropId is the picture being cropped, cropRect is the
  170. part of it that will be kept and cropFull is where the whole picture
  171. sits behind that (both in slide units), cropBefore is what to put
  172. back if the crop is cancelled */
  173. var cropId = null;
  174. var cropRect = null;
  175. var cropFull = null;
  176. var cropBefore = null;
  177. var canvasEl, layerEl, framesEl, guideVEl, guideHEl, marqueeEl, cropEl;
  178. /* ================= small utils ================= */
  179. function esc(t) { return OfficeApp.escapeHtml(t); }
  180. function deep(o) { return JSON.parse(JSON.stringify(o)); }
  181. function snap() { return JSON.stringify(body); }
  182. function genId(p) {
  183. return (p || "o") + "-" + Date.now().toString(36) + Math.random().toString(36).substring(2, 7);
  184. }
  185. function aoRoot() { return (typeof ao_root !== "undefined") ? ao_root : "../../"; }
  186. function clamp(v, a, b) { return Math.max(a, Math.min(b, v)); }
  187. function themeOf() { return THEMES[body && body.theme] || THEMES.clean; }
  188. function curSlide() { return body.slides[cur]; }
  189. function objById(id) {
  190. var objs = curSlide().objects;
  191. for (var i = 0; i < objs.length; i++) if (objs[i].id === id) return objs[i];
  192. return null;
  193. }
  194. function selObjs() {
  195. return sel.map(objById).filter(function (o) { return !!o; });
  196. }
  197. function curScale() { return fitScale * zoomPct / 100; }
  198. function contrastText(hex) {
  199. // an imported fill may carry alpha as #rrggbbaa
  200. var m = /^#?([0-9a-f]{6})(?:[0-9a-f]{2})?$/i.exec(String(hex || ""));
  201. if (!m) return "#ffffff";
  202. var n = parseInt(m[1], 16);
  203. var lum = 0.299 * ((n >> 16) & 255) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255);
  204. return lum > 160 ? "#202124" : "#ffffff";
  205. }
  206. /* ================= document model ================= */
  207. function newTextObj(html, x, y, w, h, fontSize, align, color) {
  208. return {
  209. id: genId(), type: "text", x: x, y: y, w: w, h: h, rot: 0, z: 1,
  210. props: { html: html, fontSize: fontSize, color: color, align: align || "left" }
  211. };
  212. }
  213. /* A layout's text boxes are placeholders: empty, with props.ph saying
  214. what they are for, so the canvas prompts "Click to add title" in them
  215. (renderObjectEl) and they vanish from the show and every export
  216. until something is typed. The .pptx writer makes them <p:ph> again. */
  217. function newPh(role, x, y, w, h, fontSize, align, color) {
  218. var o = newTextObj("", x, y, w, h, fontSize, align, color);
  219. o.props.ph = role;
  220. return o;
  221. }
  222. var PH_PROMPTS = {
  223. title: "Click to add title",
  224. subtitle: "Click to add subtitle",
  225. body: "Click to add text"
  226. };
  227. // a text object with nothing in it: no characters (the zero-width
  228. // space an imported empty line carries does not count) and no picture
  229. function isBlankText(o) {
  230. if (!o || o.type !== "text") return false;
  231. var html = String((o.props && o.props.html) || "");
  232. if (/<(img|svg|video|audio|iframe|object)\b/i.test(html)) return false;
  233. return html.replace(/<[^>]*>/g, "").replace(/&nbsp;|&#8203;|&#x200b;|&zwnj;|\u200b|\u00a0/gi, "")
  234. .trim() === "";
  235. }
  236. function newSlide(kind) {
  237. var th = themeOf ? themeOf() : THEMES.clean;
  238. var textColor = (body ? themeOf() : th).text;
  239. var s = { id: genId("s"), bg: null, notes: "", transition: "none", objects: [] };
  240. if (kind === "title") {
  241. s.objects.push(newPh("title", 80, 190, 800, 90, 44, "center", textColor));
  242. s.objects.push(newPh("subtitle", 180, 300, 600, 50, 20, "center", textColor));
  243. } else if (kind === "normal") {
  244. s.objects.push(newPh("title", 50, 34, 860, 66, 32, "left", textColor));
  245. } else if (kind === "content") {
  246. s.objects.push(newPh("title", 50, 34, 860, 66, 32, "left", textColor));
  247. s.objects.push(newPh("body", 50, 130, 860, 360, 22, "left", textColor));
  248. } else if (kind === "two") {
  249. s.objects.push(newPh("title", 50, 34, 860, 66, 32, "left", textColor));
  250. s.objects.push(newPh("body", 50, 130, 420, 360, 20, "left", textColor));
  251. s.objects.push(newPh("body", 490, 130, 420, 360, 20, "left", textColor));
  252. } else if (kind === "caption") {
  253. s.objects.push(newPh("title", 60, 60, 840, 300, 28, "left", textColor));
  254. s.objects.push(newPh("body", 60, 400, 840, 60, 16, "left", textColor));
  255. } else if (kind === "section") {
  256. s.objects.push(newPh("title", 60, 230, 840, 80, 36, "left", textColor));
  257. } else if (kind === "onecol") {
  258. s.objects.push(newPh("title", 60, 60, 840, 60, 28, "left", textColor));
  259. s.objects.push(newPh("body", 60, 140, 840, 340, 18, "left", textColor));
  260. } else if (kind === "mainpoint") {
  261. s.objects.push(newPh("title", 80, 210, 800, 120, 44, "left", textColor));
  262. } else if (kind === "sectiondesc") {
  263. s.objects.push(newPh("title", 60, 120, 380, 90, 30, "left", textColor));
  264. s.objects.push(newPh("body", 60, 230, 380, 200, 16, "left", textColor));
  265. } else if (kind === "bignumber") {
  266. s.objects.push(newPh("title", 80, 160, 800, 140, 88, "center", textColor));
  267. s.objects.push(newPh("body", 80, 320, 800, 60, 18, "center", textColor));
  268. }
  269. // the layouts are drawn for 960x540; a deck of another shape gets
  270. // them spread over its own height
  271. if (SLIDE_H !== 540) {
  272. var ky = SLIDE_H / 540;
  273. s.objects.forEach(function (o) {
  274. o.y = Math.round(o.y * ky);
  275. o.h = Math.round(o.h * ky);
  276. });
  277. }
  278. s.objects.forEach(function (o, i) { o.z = i + 1; });
  279. return s;
  280. }
  281. function defaultBody() {
  282. setSlideSize(960, 540);
  283. var b = { size: [SLIDE_W, SLIDE_H], theme: "clean", slides: [] };
  284. body = b; // themeOf() needs it while building the first slide
  285. b.slides.push(newSlide("title"));
  286. // through the same checks as an opened deck, so nothing (embedded
  287. // fonts, missing fields) carries over from the previous one
  288. return normalizeBody(b);
  289. }
  290. /* A deck states its own size: 960 wide and as tall as its shape (a
  291. 4:3 PowerPoint deck is 960x720). Anything odd falls back to 16:9. */
  292. function sizeOf(b) {
  293. var sz = b && b.size;
  294. var w = sz && Number(sz[0]), h = sz && Number(sz[1]);
  295. if (!(w >= 100 && w <= 4000 && h >= 100 && h <= 4000)) return [960, 540];
  296. return [Math.round(w), Math.round(h)];
  297. }
  298. function setSlideSize(w, h) {
  299. SLIDE_W = w;
  300. SLIDE_H = h;
  301. var root = document.documentElement.style;
  302. root.setProperty("--sl-w", w + "px");
  303. root.setProperty("--sl-h", h + "px");
  304. root.setProperty("--sl-ar", w + " / " + h);
  305. }
  306. function normalizeBody(b) {
  307. if (!b || typeof b !== "object") b = {};
  308. b.size = sizeOf(b);
  309. setSlideSize(b.size[0], b.size[1]);
  310. if (!THEMES[b.theme]) b.theme = "clean";
  311. if (!Array.isArray(b.slides) || b.slides.length === 0) {
  312. b.slides = [{ id: genId("s"), bg: null, notes: "", objects: [] }];
  313. }
  314. b.slides.forEach(function (s) {
  315. s.id = s.id || genId("s");
  316. s.bg = s.bg || null;
  317. if (!s.bgImage || typeof s.bgImage !== "object" || !s.bgImage.src) delete s.bgImage;
  318. if (!s.bgGrad || typeof s.bgGrad !== "object" || !Array.isArray(s.bgGrad.stops) ||
  319. !s.bgGrad.stops.length) delete s.bgGrad;
  320. s.notes = typeof s.notes === "string" ? s.notes : "";
  321. if (typeof s.transition !== "string") s.transition = "none";
  322. if (s.hidden !== true) delete s.hidden;
  323. if (!Array.isArray(s.objects)) s.objects = [];
  324. s.objects = s.objects.filter(function (o) { return o && TYPE_NAMES[o.type]; });
  325. s.objects.forEach(function (o, i) {
  326. o.id = o.id || genId();
  327. o.x = Number(o.x) || 0; o.y = Number(o.y) || 0;
  328. o.w = Number(o.w) || 0; o.h = Number(o.h) || 0;
  329. o.rot = Number(o.rot) || 0;
  330. o.z = i + 1;
  331. if (!o.props || typeof o.props !== "object") o.props = {};
  332. // decks written before the shape catalogue carry three
  333. // editor-invented names; rewrite them as they come in
  334. if (o.props.kind) o.props.kind = SlidesShapes.canonical(o.props.kind);
  335. if (o.props.mask) o.props.mask = SlidesShapes.canonical(o.props.mask);
  336. });
  337. });
  338. if (!Array.isArray(b.fonts)) delete b.fonts;
  339. installEmbeddedFonts(b.fonts);
  340. // fonts the deck names that this machine lacks get a stand-in
  341. // scaled to the original's width, so lines break where they did
  342. // for the author; the faces it carries itself are left alone
  343. OfficeFonts.substitute(OfficeFonts.familiesIn(JSON.stringify(b.slides)),
  344. (b.fonts || []).map(function (f) { return f && f.family; }), { lines: "powerpoint" });
  345. return b;
  346. }
  347. /* A deck imported from a file may carry the font faces it was designed
  348. in, so text renders in the right typeface on a machine that does not
  349. have them installed. They go in one stylesheet for the whole page:
  350. the editor, the thumbnails, present mode and print all share it. */
  351. function installEmbeddedFonts(fonts) {
  352. var el = document.getElementById("slEmbeddedFonts");
  353. if (!fonts || !fonts.length) {
  354. if (el) el.parentNode.removeChild(el);
  355. return;
  356. }
  357. if (!el) {
  358. el = document.createElement("style");
  359. el.id = "slEmbeddedFonts";
  360. document.head.appendChild(el);
  361. }
  362. var css = "";
  363. fonts.forEach(function (f) {
  364. if (!f || typeof f.src !== "string" || f.src.indexOf("data:") !== 0) return;
  365. if (!f.family) return;
  366. css += "@font-face{font-family:'" + String(f.family).replace(/['\\]/g, "") +
  367. "';src:url(" + f.src + ");font-weight:" + (Number(f.weight) || 400) +
  368. ";font-style:" + (f.style === "italic" ? "italic" : "normal") +
  369. ";font-display:block;}\n";
  370. });
  371. el.textContent = css;
  372. }
  373. /* ================= rendering: objects ================= */
  374. /* Imported decks (pptx / odp) carry their own typography on the text
  375. object: the CSS font stack the file asked for, the text-box insets,
  376. the paragraph line height and the vertical anchor. Documents made in
  377. the editor have none of those and fall back to the stylesheet. */
  378. var VALIGN_JUSTIFY = { top: "flex-start", middle: "center", bottom: "flex-end" };
  379. function padStyle(pad) {
  380. if (!pad || pad.length !== 4) return "";
  381. return "padding:" + pad.map(function (v) {
  382. return (Number(v) || 0) + "px";
  383. }).join(" ") + ";";
  384. }
  385. function textStyle(p) {
  386. var s = "font-size:" + (Number(p.fontSize) || 24) + "px;";
  387. if (p.color) s += "color:" + esc(p.color) + ";";
  388. s += "text-align:" + esc(p.align || "left") + ";";
  389. if (p.bold) s += "font-weight:700;";
  390. if (p.italic) s += "font-style:italic;";
  391. if (p.underline) s += "text-decoration:underline;";
  392. if (p.fontFamily) s += "font-family:" + esc(OfficeFonts.stack(p.fontFamily)) + ";";
  393. if (p.lineHeight) s += "line-height:" + (Number(p.lineHeight) || 1.3) + ";";
  394. s += padStyle(p.pad);
  395. s += "justify-content:" + (VALIGN_JUSTIFY[p.valign] || "flex-start") + ";";
  396. return s;
  397. }
  398. /* An imported picture may be cropped (pptx srcRect), have rounded
  399. corners and be partly transparent. The crop is reproduced the way
  400. PowerPoint defines it: the visible rectangle is scaled up to fill
  401. the frame and the rest is clipped by the wrapper. */
  402. function imageHtml(p, w, h) {
  403. var imgS = "object-fit:" + esc(p.fit || "contain") + ";" + cropImgStyle(p.crop);
  404. var wrapS = "";
  405. // a fill on the picture's frame, seen through its transparent parts
  406. var under = p.fillGrad ? gradientCss(p.fillGrad) : (p.fill && p.fill !== "none" ? esc(p.fill) : "");
  407. if (under) wrapS += "background:" + under + ";";
  408. if (p.radius) wrapS += "border-radius:" + (Number(p.radius) || 0) + "px;";
  409. if (p.opacity) wrapS += "opacity:" + clamp(Number(p.opacity) || 1, 0, 1) + ";";
  410. var clip = maskClipPath(p.mask, p.adj, w, h);
  411. if (clip) wrapS += "clip-path:" + clip + ";-webkit-clip-path:" + clip + ";";
  412. // a picture's outline (pptx <a:ln> on the picture) is centred on the
  413. // frame like PowerPoint draws it; a shaped crop gets it along the
  414. // shape, which a clipped wrapper cannot draw on itself
  415. var sw = Number(p.strokeW) || 0;
  416. var outline = "";
  417. if (sw > 0 && p.stroke && p.stroke !== "none") {
  418. var dash = SlidesLines.dashArray(p, sw);
  419. if (!clip && !dash) {
  420. wrapS += "outline:" + sw + "px solid " + esc(p.stroke) +
  421. ";outline-offset:" + (-sw / 2) + "px;";
  422. } else if (w > 0 && h > 0) {
  423. // CSS has no dash-dot, and a clipped wrapper cannot draw
  424. // along its own clip: an SVG does both
  425. var d = clip && window.SlidesShapes ? SlidesShapes.path(p.mask, w, h, p.adj) : "";
  426. var r = Number(p.radius) || 0;
  427. var geo = d ? '<path d="' + esc(d) + '"'
  428. : '<rect x="0" y="0" width="' + w + '" height="' + h + '" rx="' + r + '"';
  429. outline = '<svg class="sl-img-outline" width="' + w + '" height="' + h +
  430. '" style="position:absolute;left:0;top:0;overflow:visible;pointer-events:none;">' +
  431. geo + ' fill="none" stroke="' + esc(p.stroke) + '" stroke-width="' + sw + '"' +
  432. ' stroke-linecap="' + SlidesLines.capOf(p) + '"' +
  433. (dash ? ' stroke-dasharray="' + dash.join(" ") + '"' : "") + "/></svg>";
  434. }
  435. }
  436. // re-colour and the brightness / contrast adjustments are one CSS
  437. // filter, built by the picture tools so the canvas, the thumbnails,
  438. // present mode and the panel's own swatches all agree
  439. if (window.SlidesImageTools) {
  440. var f = SlidesImageTools.imageFilter(p);
  441. if (f) imgS += "filter:" + f + ";";
  442. }
  443. var flip = (p.flipH ? "scaleX(-1) " : "") + (p.flipV ? "scaleY(-1)" : "");
  444. if (flip) imgS += "transform:" + flip.trim() + ";" + flipOriginStyle(p.crop);
  445. return '<div class="sl-img-wrap" style="' + wrapS + '">' +
  446. '<img draggable="false" src="' + esc(p.src || "") +
  447. '" style="' + imgS + '" alt=""></div>' + outline;
  448. }
  449. /* The visible rectangle is scaled up to fill the frame and the rest is
  450. clipped by the wrapper - the same definition PowerPoint's srcRect
  451. uses, so an imported crop and one made here mean the same thing. */
  452. function cropImgStyle(c) {
  453. if (!c || c.length !== 4) return "";
  454. var l = Number(c[0]) || 0, t = Number(c[1]) || 0;
  455. var kw = 1 - l - (Number(c[2]) || 0);
  456. var kh = 1 - t - (Number(c[3]) || 0);
  457. if (!(kw > 0.001) || !(kh > 0.001)) return "";
  458. return "position:absolute;object-fit:fill;" +
  459. "width:" + (100 / kw) + "%;height:" + (100 / kh) + "%;" +
  460. "left:" + (-l / kw * 100) + "%;top:" + (-t / kh * 100) + "%;";
  461. }
  462. /* A flip mirrors what the frame shows, about the frame's centre: that
  463. is PowerPoint's order (crop the picture, then flip the result). A
  464. cropped <img> is bigger than its frame and offset, so mirroring it
  465. about its own centre would show the part the crop removed from the
  466. opposite side - an off-centre crop then looks cut in the wrong
  467. place. The frame's centre, in the picture's own box: */
  468. function flipOriginStyle(c) {
  469. if (!c || c.length !== 4) return "";
  470. var l = Number(c[0]) || 0, t = Number(c[1]) || 0;
  471. var kw = 1 - l - (Number(c[2]) || 0);
  472. var kh = 1 - t - (Number(c[3]) || 0);
  473. if (!(kw > 0.001) || !(kh > 0.001)) return "";
  474. return "transform-origin:" + ((l + kw / 2) * 100) + "% " + ((t + kh / 2) * 100) + "%;";
  475. }
  476. /* A shaped crop ("mask image"): the picture is clipped to one of the
  477. editor's shape outlines, with the adjustments its handles gave it
  478. (props.adj on a picture belongs to its mask). The corners are worked
  479. out at the frame's real size, because most presets measure their
  480. features from the shorter side, and stated as percentages so the
  481. clip still follows the frame while it is being dragged. */
  482. function maskClipPath(kind, adj, w, h) {
  483. if (!kind || kind === "rect") return "";
  484. if (kind === "ellipse") return "ellipse(50% 50% at 50% 50%)";
  485. if (kind === "roundRect") return ""; // border-radius draws this one
  486. var fw = w > 0 ? w : 100, fh = h > 0 ? h : 100;
  487. var pts = shapePoints(kind, fw, fh, adj);
  488. if (!pts) return "";
  489. return "polygon(" + pts.map(function (pt) {
  490. return (pt[0] / fw * 100).toFixed(2) + "% " + (pt[1] / fh * 100).toFixed(2) + "%";
  491. }).join(",") + ")";
  492. }
  493. /* shapePoints is the polygon form of a shape, for the one caller that
  494. wants corners rather than a path: the CSS clip-path of a mask, which
  495. states them as percentages so the clip follows the frame. A shape
  496. with curves in it has none, and says so - which is why MASK_KINDS is
  497. all polygons. */
  498. function shapePoints(kind, w, h, adj) {
  499. return SlidesShapes.points(kind, w, h, adj);
  500. }
  501. /* shapeSvg draws one shape. The geometry comes from SlidesShapes, so
  502. the canvas, the icon in the picker, a shaped crop and the PDF export
  503. are all working from the same outline.
  504. Two shapes are still drawn as SVG primitives rather than as a path:
  505. a rectangle and an ellipse, because a rounded rectangle's radius is
  506. a property the user sets and `rx` follows the box as it is resized. */
  507. function shapeSvg(o) {
  508. var w = Math.max(4, o.w), h = Math.max(4, o.h);
  509. var p = o.props;
  510. var kind = SlidesShapes.canonical(p.kind || "rect");
  511. var sw = Number(p.strokeW) || 0;
  512. var stroke = p.stroke || "";
  513. // an imported shape may legitimately have no fill (an outline-only
  514. // box); only an editor-made shape with nothing set gets the default
  515. var fill = p.fill || "#e07b1f";
  516. // a bracket, a brace or an arc is a line and not an area: with no
  517. // stroke there would be nothing on the slide at all
  518. var open = SlidesShapes.isOpen(kind);
  519. if (open) {
  520. if (!stroke || stroke === "none") stroke = (fill && fill !== "none") ? fill : "#333333";
  521. if (!sw) sw = 2;
  522. fill = "none";
  523. }
  524. var hasStroke = sw > 0 && stroke && stroke !== "none";
  525. // an imported gradient fill is an SVG paint server of its own
  526. var defs = "";
  527. if (!open && p.fillGrad && p.fillGrad.stops && p.fillGrad.stops.length) {
  528. var gid = "slg" + (++gradSeq);
  529. defs = "<defs>" + svgGradient(p.fillGrad, w, h, gid) + "</defs>";
  530. fill = "url(#" + gid + ")";
  531. }
  532. var attrs = 'fill="' + esc(fill) + '"' +
  533. (SlidesShapes.evenOdd(kind) ? ' fill-rule="evenodd"' : "") +
  534. (hasStroke ? ' stroke="' + esc(stroke) + '" stroke-width="' + sw + '"' +
  535. (SlidesLines.dashArray(p, sw) ? ' stroke-dasharray="' + SlidesLines.dashArray(p, sw).join(" ") +
  536. '" stroke-linecap="' + SlidesLines.capOf(p) + '"' : "") : ' stroke="none"') +
  537. ' stroke-linejoin="round" vector-effect="non-scaling-stroke"';
  538. var inner;
  539. var i = hasStroke ? Math.max(0.5, sw / 2) : 0;
  540. if (kind === "rect" || kind === "roundRect") {
  541. var rx = kind === "roundRect"
  542. ? (p.radius !== undefined ? Number(p.radius) : Math.min(w, h) * 0.15) : 0;
  543. inner = '<rect x="' + i + '" y="' + i + '" width="' + (w - 2 * i) + '" height="' + (h - 2 * i) +
  544. '" rx="' + rx + '" ' + attrs + "/>";
  545. } else if (kind === "ellipse") {
  546. inner = '<ellipse cx="' + (w / 2) + '" cy="' + (h / 2) + '" rx="' + (w / 2 - i) + '" ry="' + (h / 2 - i) + '" ' + attrs + "/>";
  547. } else if (kind === "custom" && p.geom) {
  548. // an imported freeform: the filled paths, then any drawn only
  549. // as an outline (a path the file says has no fill)
  550. var cd = SlidesShapes.customPath(p.geom, w, h, "fill");
  551. inner = cd ? '<path d="' + cd + '" ' + attrs + "/>" : "";
  552. var od = (p.geom.paths || []).some(function (gp) { return gp.noFill; })
  553. ? SlidesShapes.customPath({ paths: p.geom.paths.filter(function (gp) { return gp.noFill; }) }, w, h) : "";
  554. if (od && hasStroke) {
  555. inner += '<path d="' + od + '" fill="none" stroke="' + esc(stroke) + '" stroke-width="' + sw +
  556. '" stroke-linejoin="round" vector-effect="non-scaling-stroke"/>';
  557. }
  558. } else {
  559. var d = SlidesShapes.path(kind, w, h, p.adj);
  560. if (!d) d = SlidesShapes.path("rect", w, h);
  561. inner = '<path d="' + d + '" ' + attrs + "/>";
  562. }
  563. // markings - the divider bars of a predefined process, the fold of a
  564. // folded corner. They are drawn, never filled.
  565. var det = SlidesShapes.detail(kind, w, h, p.adj);
  566. if (det) {
  567. inner += '<path d="' + det + '" fill="none" stroke="' +
  568. esc(hasStroke ? stroke : contrastText(fill)) + '" stroke-width="' +
  569. (sw > 0 ? sw : 1) + '" vector-effect="non-scaling-stroke"/>';
  570. }
  571. // a stroke sits astride the outline, so half of it falls outside the
  572. // box - which is what PowerPoint draws too
  573. return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + w + " " + h +
  574. '" preserveAspectRatio="none" style="overflow:visible">' + defs + inner + "</svg>";
  575. }
  576. /* A gradient as an SVG paint server over a w x h box, laid out the way
  577. CSS lays out the same gradient (gradientCss): a linear one along the
  578. CSS gradient line, a radial one as "circle farthest-corner". The
  579. PDF exporter paints from the same numbers. */
  580. var gradSeq = 0;
  581. function svgGradient(g, w, h, id) {
  582. var stops = (g.stops || []).map(function (st) {
  583. var c = String(st.color || "#000000");
  584. var op = "";
  585. var m = /^#([0-9a-f]{6})([0-9a-f]{2})$/i.exec(c);
  586. if (m) { c = "#" + m[1]; op = ' stop-opacity="' + (parseInt(m[2], 16) / 255).toFixed(3) + '"'; }
  587. return '<stop offset="' + clamp(Number(st.pos) || 0, 0, 1) + '" stop-color="' + esc(c) + '"' + op + "/>";
  588. }).join("");
  589. if (g.kind === "radial") {
  590. var cx = (isFinite(Number(g.cx)) ? Number(g.cx) : 0.5) * w;
  591. var cy = (isFinite(Number(g.cy)) ? Number(g.cy) : 0.5) * h;
  592. var r = Math.max(Math.hypot(cx, cy), Math.hypot(w - cx, cy),
  593. Math.hypot(cx, h - cy), Math.hypot(w - cx, h - cy));
  594. return '<radialGradient id="' + id + '" gradientUnits="userSpaceOnUse" cx="' + cx +
  595. '" cy="' + cy + '" r="' + r + '">' + stops + "</radialGradient>";
  596. }
  597. var a = (Number(g.angle) || 0) * Math.PI / 180;
  598. var dx = Math.sin(a), dy = -Math.cos(a);
  599. var half = (Math.abs(w * dx) + Math.abs(h * dy)) / 2;
  600. return '<linearGradient id="' + id + '" gradientUnits="userSpaceOnUse" x1="' +
  601. (w / 2 - dx * half) + '" y1="' + (h / 2 - dy * half) + '" x2="' + (w / 2 + dx * half) +
  602. '" y2="' + (h / 2 + dy * half) + '">' + stops + "</linearGradient>";
  603. }
  604. function shapeTextDiv(o) {
  605. var p = o.props;
  606. var s = "font-size:" + (Number(p.fontSize) || 18) + "px;";
  607. s += "color:" + esc(p.textColor || contrastText(p.fill)) + ";";
  608. if (p.bold) s += "font-weight:700;";
  609. if (p.italic) s += "font-style:italic;";
  610. if (p.fontFamily) s += "font-family:" + esc(OfficeFonts.stack(p.fontFamily)) + ";";
  611. if (p.lineHeight) s += "line-height:" + (Number(p.lineHeight) || 1.25) + ";";
  612. // an imported shape carries the same rich paragraph HTML a text
  613. // object does, plus the alignment and insets its source stated
  614. if (p.html) {
  615. s += "text-align:" + esc(p.align || "center") + ";";
  616. s += "justify-content:" + (VALIGN_JUSTIFY[p.valign] || "center") + ";";
  617. s += padStyle(p.pad);
  618. return '<div class="sl-shape-text sl-shape-rich" style="' + s + '">' + p.html + "</div>";
  619. }
  620. return '<div class="sl-shape-text" style="' + s + '">' + esc(p.text || "") + "</div>";
  621. }
  622. /* A line is normally two points: its origin and the vector in o.w/o.h.
  623. A connector imported from a pptx may bend, and then carries the whole
  624. polyline in props.points (relative to o.x/o.y) with o.w/o.h still
  625. spanning end to end, so selection and dragging keep working. */
  626. function linePoints(o) {
  627. var p = o.props && o.props.points;
  628. if (p && p.length >= 2) {
  629. return p.map(function (pt) { return [Number(pt[0]) || 0, Number(pt[1]) || 0]; });
  630. }
  631. return [[0, 0], [o.w, o.h]];
  632. }
  633. function lineBBox(o) {
  634. var pts = linePoints(o);
  635. var x0 = pts[0][0], y0 = pts[0][1], x1 = x0, y1 = y0;
  636. pts.forEach(function (pt) {
  637. x0 = Math.min(x0, pt[0]); x1 = Math.max(x1, pt[0]);
  638. y0 = Math.min(y0, pt[1]); y1 = Math.max(y1, pt[1]);
  639. });
  640. return { x: o.x + x0, y: o.y + y0, w: x1 - x0, h: y1 - y0 };
  641. }
  642. function positionLineEl(el, o) {
  643. var bb = lineBBox(o);
  644. el.style.left = bb.x + "px";
  645. el.style.top = bb.y + "px";
  646. el.style.width = Math.max(1, bb.w) + "px";
  647. el.style.height = Math.max(1, bb.h) + "px";
  648. }
  649. function lineSvg(o) {
  650. var p = o.props;
  651. var sw = Number(p.strokeW) || 2;
  652. var stroke = p.stroke || "#202124";
  653. // draw in the element's own box: shift the polyline so its
  654. // top-left corner sits at 0,0
  655. var pts = linePoints(o);
  656. var ox = 0, oy = 0;
  657. pts.forEach(function (pt) { ox = Math.min(ox, pt[0]); oy = Math.min(oy, pt[1]); });
  658. pts = pts.map(function (pt) { return [pt[0] - ox, pt[1] - oy]; });
  659. function poly(list) {
  660. return list.map(function (pt) {
  661. return pt[0].toFixed(1) + "," + pt[1].toFixed(1);
  662. }).join(" ");
  663. }
  664. var out = '<svg xmlns="http://www.w3.org/2000/svg" style="overflow:visible;" width="100%" height="100%">';
  665. // generous transparent hit area
  666. out += '<polyline points="' + poly(pts) + '" fill="none" ' +
  667. 'stroke="rgba(0,0,0,0)" stroke-width="' + Math.max(14, sw + 10) + '"/>';
  668. // the stroke, its dash and both ends: slides_lines.js, which the PDF
  669. // exporter asks too
  670. out += SlidesLines.svgMarkup(pts, p, sw, stroke);
  671. out += "</svg>";
  672. return out;
  673. }
  674. /* Table cells store a limited HTML subset (so per-cell bold/color/font
  675. formatting survives edit mode). This sanitizer keeps only inline
  676. formatting produced by execCommand and strips everything else. */
  677. var CELL_OK_TAGS = { B: 1, I: 1, U: 1, STRONG: 1, EM: 1, S: 1, STRIKE: 1, SPAN: 1, FONT: 1, BR: 1, SUB: 1, SUP: 1, A: 1, DIV: 1 };
  678. var CELL_OK_STYLES = ["font-size", "color", "font-family", "font-weight", "font-style", "text-decoration", "background-color",
  679. "vertical-align", "line-height", "letter-spacing", "text-transform",
  680. // an imported bullet marker is a positioned span (pptx/reader.go)
  681. "position", "left", "top", "display", "width"];
  682. // a paragraph in a cell (an imported table's, or one Enter made) keeps
  683. // its alignment, spacing and indents
  684. var CELL_BLOCK_STYLES = ["text-align", "line-height", "margin-top", "margin-bottom", "padding-left",
  685. "padding-right", "text-indent", "font-size", "position", "top", "tab-size"];
  686. function sanitizeCellHtml(html) {
  687. if (html === undefined || html === null) return "";
  688. // parse in an inert DOMParser document: unlike innerHTML on a live
  689. // div, <img onerror> handlers can never fire while parsing there
  690. var doc = new DOMParser().parseFromString(
  691. "<!DOCTYPE html><body><div>" + String(html) + "</div></body>", "text/html");
  692. var tmp = doc.body.firstChild;
  693. if (!tmp) return "";
  694. (function walk(node) {
  695. var children = Array.prototype.slice.call(node.childNodes);
  696. children.forEach(function (ch) {
  697. if (ch.nodeType === 8) { node.removeChild(ch); return; } // comments
  698. if (ch.nodeType !== 1) return; // text stays
  699. if (ch.tagName === "SCRIPT" || ch.tagName === "STYLE") {
  700. node.removeChild(ch);
  701. return;
  702. }
  703. walk(ch);
  704. if (!CELL_OK_TAGS[ch.tagName]) {
  705. // unwrap unknown elements, turning block boundaries into <br>
  706. if (/^(DIV|P|LI|H[1-6]|TR|TD)$/.test(ch.tagName) && ch.previousSibling) {
  707. node.insertBefore(document.createElement("br"), ch);
  708. }
  709. while (ch.firstChild) node.insertBefore(ch.firstChild, ch);
  710. node.removeChild(ch);
  711. } else {
  712. // scrub attributes down to the formatting whitelist
  713. Array.prototype.slice.call(ch.attributes).forEach(function (a) {
  714. var an = a.name.toLowerCase();
  715. var ok = an === "style" ||
  716. (ch.tagName === "FONT" && (an === "color" || an === "face" || an === "size")) ||
  717. (ch.tagName === "A" && an === "href" &&
  718. /^(https?:\/\/|#)/i.test(a.value));
  719. if (!ok) ch.removeAttribute(a.name);
  720. });
  721. if (ch.getAttribute("style")) {
  722. var kept = [];
  723. ch.getAttribute("style").split(";").forEach(function (decl) {
  724. var ci = decl.indexOf(":");
  725. if (ci < 0) return;
  726. var prop = decl.substring(0, ci).trim().toLowerCase();
  727. var okList = ch.tagName === "DIV" ? CELL_BLOCK_STYLES : CELL_OK_STYLES;
  728. if (okList.indexOf(prop) >= 0) kept.push(decl.trim());
  729. });
  730. if (kept.length) ch.setAttribute("style", kept.join(";"));
  731. else ch.removeAttribute("style");
  732. }
  733. }
  734. });
  735. })(tmp);
  736. return tmp.innerHTML;
  737. }
  738. function tableHtml(o) {
  739. var p = o.props;
  740. var rows = p.rows || [["", ""]];
  741. var cols = rows[0] ? rows[0].length : 1;
  742. var accent = themeOf().accent;
  743. var headBg = /^#[0-9a-fA-F]{6}$/.test(accent) ? accent + "2e" : "rgba(127,127,127,0.18)";
  744. var s = "font-size:" + (Number(p.fontSize) || 16) + "px;";
  745. if (p.color) s += "color:" + esc(p.color) + ";";
  746. var out = '<table class="sl-table" style="' + s + '"><colgroup>';
  747. for (var c = 0; c < cols; c++) {
  748. var wPct = (p.colW && p.colW[c]) ? p.colW[c] : (100 / cols);
  749. out += '<col style="width:' + wPct + '%">';
  750. }
  751. out += "</colgroup>";
  752. // an imported table states its own cell shading and insets; one
  753. // that came with a table style (p.styled) states its whole look,
  754. // rules included, and gets no heading shading or weight from here
  755. var cellPad = padStyle(p.cellPad);
  756. var rule = "";
  757. if (p.styled) {
  758. var rw = Number(p.strokeW) || 0;
  759. rule = (!p.stroke || p.stroke === "none" || rw <= 0) ? "border:none;"
  760. : "border:" + rw + "px solid " + esc(p.stroke) + ";";
  761. }
  762. // merged cells span; the cells under a merge are not drawn
  763. var span = {}, covered = {};
  764. (Array.isArray(p.merges) ? p.merges : []).forEach(function (m) {
  765. var mr = Number(m[0]), mc = Number(m[1]), rs = Math.max(1, Number(m[2]) || 1), cs = Math.max(1, Number(m[3]) || 1);
  766. if (!(mr >= 0 && mc >= 0) || covered[mr + ":" + mc]) return;
  767. span[mr + ":" + mc] = [rs, cs];
  768. for (var y = mr; y < mr + rs; y++) {
  769. for (var x = mc; x < mc + cs; x++) if (y !== mr || x !== mc) covered[y + ":" + x] = true;
  770. }
  771. });
  772. rows.forEach(function (r, ri) {
  773. var isHead = p.headerRow && ri === 0;
  774. var trStyle = (p.rowH && p.rowH[ri] !== undefined) ? ' style="height:' + p.rowH[ri] + '%;"' : "";
  775. out += '<tr class="' + (isHead && !p.styled ? "sl-thead" : "") + '"' + trStyle + ">";
  776. r.forEach(function (cell, ci) {
  777. var bg = (p.cellFill && p.cellFill[ri]) ? p.cellFill[ri][ci] : "";
  778. if (!bg && isHead && !p.styled) bg = headBg;
  779. var va = (p.cellAnchor && p.cellAnchor[ri]) ? p.cellAnchor[ri][ci] : "";
  780. var tdStyle = cellPad + rule + (bg ? "background:" + esc(bg) + ";" : "") +
  781. (va === "middle" || va === "bottom" ? "vertical-align:" + va + ";" : "");
  782. if (covered[ri + ":" + ci]) return;
  783. var sp = span[ri + ":" + ci];
  784. out += '<td data-r="' + ri + '" data-c="' + ci + '"' +
  785. (sp && sp[0] > 1 ? ' rowspan="' + sp[0] + '"' : "") +
  786. (sp && sp[1] > 1 ? ' colspan="' + sp[1] + '"' : "") +
  787. (tdStyle ? ' style="' + tdStyle + '"' : "") + ">" +
  788. sanitizeCellHtml(cell) + "</td>";
  789. });
  790. out += "</tr>";
  791. });
  792. out += "</table>";
  793. return out;
  794. }
  795. function renderObjectEl(o, zIdx) {
  796. var d = document.createElement("div");
  797. d.className = "sl-obj sl-type-" + o.type;
  798. d.setAttribute("data-id", o.id);
  799. d.style.zIndex = zIdx + 1;
  800. if (o.type === "line") {
  801. positionLineEl(d, o);
  802. d.innerHTML = lineSvg(o);
  803. return d;
  804. }
  805. d.style.left = o.x + "px";
  806. d.style.top = o.y + "px";
  807. d.style.width = Math.max(1, o.w) + "px";
  808. d.style.height = Math.max(1, o.h) + "px";
  809. if (o.rot) d.style.transform = "rotate(" + o.rot + "deg)";
  810. switch (o.type) {
  811. case "text":
  812. d.innerHTML = '<div class="sl-text-in" style="' + textStyle(o.props) + '">' +
  813. (o.props.html || "") + "</div>";
  814. if (isBlankText(o)) {
  815. // the prompt is a sibling of the text, never in it: the
  816. // PDF exporter and the editor only ever read .sl-text-in,
  817. // and only a surface marked .sl-showph shows it
  818. d.className += " sl-empty";
  819. d.insertAdjacentHTML("beforeend", '<div class="sl-ph' +
  820. (o.props.ph === "title" ? " sl-ph-title" : "") + '" style="' + textStyle(o.props) +
  821. '">' + esc(PH_PROMPTS[o.props.ph] || PH_PROMPTS.body) + "</div>");
  822. }
  823. break;
  824. case "image":
  825. d.innerHTML = imageHtml(o.props, o.w, o.h);
  826. break;
  827. case "shape":
  828. d.innerHTML = shapeSvg(o) + shapeTextDiv(o);
  829. break;
  830. case "table":
  831. d.innerHTML = tableHtml(o);
  832. break;
  833. case "chart":
  834. d.innerHTML = '<div class="sl-chart-box">' +
  835. OfficeCharts.renderToString(o.props.spec || {}, Math.max(60, o.w), Math.max(60, o.h)) +
  836. "</div>";
  837. break;
  838. case "video":
  839. d.innerHTML = '<video class="sl-media" src="' + esc(o.props.src || "") +
  840. '" preload="metadata" controls' + (o.props.autoplay ? " autoplay muted" : "") + "></video>";
  841. break;
  842. case "audio":
  843. d.innerHTML = '<div class="sl-audio-box"><i class="music icon"></i>' +
  844. '<audio class="sl-media" src="' + esc(o.props.src || "") +
  845. '" preload="metadata" controls' + (o.props.autoplay ? " autoplay" : "") + "></audio></div>";
  846. break;
  847. }
  848. return d;
  849. }
  850. /* Render one slide's full content into an element (also used by
  851. thumbnails, present mode, print and export). */
  852. function renderSlideContent(el, slide) {
  853. var th = themeOf();
  854. el.innerHTML = "";
  855. el.style.background = slide.bg || th.bg;
  856. applyBgLayer(el, slide);
  857. el.style.color = th.text;
  858. (slide.objects || []).forEach(function (o, i) {
  859. el.appendChild(renderObjectEl(o, i));
  860. });
  861. }
  862. /* An imported slide may have a picture or a gradient for its
  863. background (slide.bgImage / slide.bgGrad), drawn over its plain
  864. colour. It is painted by the slide surface's ::before (slides.css,
  865. .sl-hasbg) from two custom properties rather than by a child element,
  866. so the surface's children stay exactly its objects, in order - the
  867. PDF exporter and the hit testing both count on that. */
  868. function gradientCss(g) {
  869. if (!g || !Array.isArray(g.stops) || !g.stops.length) return "";
  870. var stops = g.stops.map(function (st) {
  871. return esc(String(st.color || "#000000")) + " " +
  872. ((Number(st.pos) || 0) * 100).toFixed(2) + "%";
  873. });
  874. if (stops.length === 1) stops.push(stops[0]);
  875. if (g.kind === "radial") {
  876. var cx = Number(g.cx), cy = Number(g.cy);
  877. return "radial-gradient(circle farthest-corner at " +
  878. ((isFinite(cx) ? cx : 0.5) * 100) + "% " + ((isFinite(cy) ? cy : 0.5) * 100) + "%," +
  879. stops.join(",") + ")";
  880. }
  881. return "linear-gradient(" + (Number(g.angle) || 0) + "deg," + stops.join(",") + ")";
  882. }
  883. function bgLayerCss(slide) {
  884. var im = slide.bgImage;
  885. if (im && im.src) {
  886. var url = 'url("' + String(im.src).replace(/["\\\n]/g, "") + '")';
  887. var w = Number(im.w) || SLIDE_W, h = Number(im.h) || SLIDE_H;
  888. return url + " " + (Number(im.x) || 0) + "px " + (Number(im.y) || 0) + "px / " +
  889. w + "px " + h + "px " + (im.tile ? "repeat" : "no-repeat");
  890. }
  891. return gradientCss(slide.bgGrad);
  892. }
  893. function applyBgLayer(el, slide) {
  894. var css = bgLayerCss(slide);
  895. el.classList.toggle("sl-hasbg", !!css);
  896. if (!css) {
  897. el.style.removeProperty("--sl-bgfill");
  898. el.style.removeProperty("--sl-bgop");
  899. return;
  900. }
  901. el.style.setProperty("--sl-bgfill", css);
  902. var op = slide.bgImage && slide.bgImage.src ? Number(slide.bgImage.opacity) : 0;
  903. if (op > 0 && op < 1) el.style.setProperty("--sl-bgop", op);
  904. else el.style.removeProperty("--sl-bgop");
  905. }
  906. /* ================= rendering: editor ================= */
  907. function renderEditorSlide() {
  908. renderSlideContent(layerEl, curSlide());
  909. }
  910. function getBBox(o) {
  911. if (o.type === "line") return lineBBox(o);
  912. return { x: o.x, y: o.y, w: o.w, h: o.h };
  913. }
  914. function mkHandle(name, px, py, hs) {
  915. var h = document.createElement("div");
  916. h.className = "sl-h";
  917. h.setAttribute("data-h", name);
  918. h.style.left = (px - hs / 2) + "px";
  919. h.style.top = (py - hs / 2) + "px";
  920. h.style.width = hs + "px";
  921. h.style.height = hs + "px";
  922. h.style.borderWidth = Math.max(1, hs / 7) + "px";
  923. return h;
  924. }
  925. /* ---- shape adjustments: a callout's tip, a corner, an arrow's head ----
  926. Each yellow handle sits where its adjustment is: on the tip of a
  927. speech bubble, on the top edge where a rounded rectangle's corner
  928. ends, where an arrow's head meets its shaft. A picture's shaped crop
  929. has the handles of its shape. Positions are in the frame's own
  930. (unrotated) box; `how` says what dragging one changes ("tip",
  931. "radius", or "adj": handle i of SlidesShapes.handles). */
  932. function adjGeomKind(o) {
  933. if (!o.props) return "";
  934. if (o.type === "shape") return SlidesShapes.canonical(o.props.kind || "rect");
  935. if (o.type === "image") {
  936. if (o.props.mask) return SlidesShapes.canonical(o.props.mask);
  937. // an unmasked picture with rounded corners is a rounded rectangle
  938. return Number(o.props.radius) > 0 ? "roundRect" : "";
  939. }
  940. return "";
  941. }
  942. function adjHandles(o) {
  943. var kind = adjGeomKind(o);
  944. if (!kind) return [];
  945. var how = o.type === "shape" ? SlidesShapes.adjustable(kind) : (kind === "roundRect" ? "radius" : "");
  946. if (how === "tip") {
  947. var tp = null;
  948. if (o.props.adj) tp = SlidesShapes.tipPoint(kind, o.w, o.h, o.props.adj);
  949. else {
  950. var lt = SlidesShapes.legacyTip(kind);
  951. if (lt) tp = [lt.tip[0] * o.w, lt.tip[1] * o.h];
  952. }
  953. return tp ? [{ how: "tip", i: 0, at: tp, title: "Drag to move the tip" }] : [];
  954. }
  955. if (how === "radius") {
  956. var r = o.props.radius !== undefined ? Number(o.props.radius) : Math.min(o.w, o.h) * 0.15;
  957. return [{ how: "radius", i: 0, at: [clamp(r, 0, Math.min(o.w, o.h) / 2), 0],
  958. title: "Drag to round the corners" }];
  959. }
  960. return SlidesShapes.handles(kind, o.w, o.h, o.props.adj).map(function (pt, i) {
  961. return { how: "adj", i: i, at: pt, title: "Drag to adjust the shape" };
  962. });
  963. }
  964. /* A callout made before adjustments existed drew its body in the top of
  965. the frame and its tip at the bottom. The first drag of its handle
  966. turns it into the adjusted form without moving anything: the frame
  967. shrinks to the body and the tip is stated where it already was. */
  968. function adoptAdjustments(o) {
  969. var kind = SlidesShapes.canonical(o.props.kind || "rect");
  970. if (SlidesShapes.adjustable(kind) !== "tip" || o.props.adj) return;
  971. var lt = SlidesShapes.legacyTip(kind);
  972. if (!lt) return;
  973. var tip = [lt.tip[0] * o.w, lt.tip[1] * o.h];
  974. var bodyH = Math.max(8, o.h * lt.body);
  975. o.h = bodyH;
  976. o.props.adj = {
  977. adj1: Math.round((tip[0] - o.w / 2) / o.w * 100000),
  978. adj2: Math.round((tip[1] - bodyH / 2) / bodyH * 100000)
  979. };
  980. if (lt.round) o.props.adj.adj3 = Math.round(lt.round * 100000);
  981. }
  982. function renderOverlay() {
  983. if (!framesEl) return;
  984. framesEl.innerHTML = "";
  985. if (window.SlidesImageTools) SlidesImageTools.reposition();
  986. if (cropId) {
  987. // the crop tool replaces the selection frame while it is open
  988. renderCropOverlay();
  989. return;
  990. }
  991. if (cropEl) cropEl.innerHTML = "";
  992. var s = curScale() || 1;
  993. var hs = Math.max(7, 10 / s);
  994. var bw = Math.max(1, 1.6 / s);
  995. selObjs().forEach(function (o) {
  996. var bb = getBBox(o);
  997. var fr = document.createElement("div");
  998. fr.className = "sl-frame";
  999. fr.style.left = bb.x + "px";
  1000. fr.style.top = bb.y + "px";
  1001. fr.style.width = Math.max(1, bb.w) + "px";
  1002. fr.style.height = Math.max(1, bb.h) + "px";
  1003. fr.style.borderWidth = bw + "px";
  1004. if (o.type !== "line" && o.rot) fr.style.transform = "rotate(" + o.rot + "deg)";
  1005. if (sel.length === 1) {
  1006. if (o.type === "line") {
  1007. fr.className += " sl-frame-line";
  1008. // handles sit on the real endpoints, which for a bent
  1009. // connector are the ends of its polyline
  1010. var lp = linePoints(o);
  1011. fr.appendChild(mkHandle("p1", lp[0][0] - (bb.x - o.x), lp[0][1] - (bb.y - o.y), hs));
  1012. fr.appendChild(mkHandle("p2", lp[lp.length - 1][0] - (bb.x - o.x),
  1013. lp[lp.length - 1][1] - (bb.y - o.y), hs));
  1014. } else {
  1015. var w = bb.w, hgt = bb.h;
  1016. [["nw", 0, 0], ["n", w / 2, 0], ["ne", w, 0], ["e", w, hgt / 2],
  1017. ["se", w, hgt], ["s", w / 2, hgt], ["sw", 0, hgt], ["w", 0, hgt / 2]]
  1018. .forEach(function (hd) {
  1019. fr.appendChild(mkHandle(hd[0], hd[1], hd[2], hs));
  1020. });
  1021. var stemH = 24 / s;
  1022. var stem = document.createElement("div");
  1023. stem.className = "sl-rot-stem";
  1024. stem.style.left = (w / 2 - bw / 2) + "px";
  1025. stem.style.top = (-stemH) + "px";
  1026. stem.style.width = bw + "px";
  1027. stem.style.height = stemH + "px";
  1028. fr.appendChild(stem);
  1029. fr.appendChild(mkHandle("rot", w / 2, -stemH, hs));
  1030. adjHandles(o).forEach(function (ah) {
  1031. var knob = mkHandle("adj", ah.at[0], ah.at[1], hs * 0.95);
  1032. knob.className += " sl-h-adj";
  1033. knob.setAttribute("data-i", ah.i);
  1034. knob.title = ah.title;
  1035. fr.appendChild(knob);
  1036. });
  1037. }
  1038. }
  1039. framesEl.appendChild(fr);
  1040. });
  1041. }
  1042. /* ================= image crop tool =================
  1043. Cropping is a view onto the picture, never a change to its pixels:
  1044. the object frame states which part is visible and props.crop states
  1045. which part of the source that is. While the tool is open the whole
  1046. picture is shown ghosted, with the part that will be kept drawn at
  1047. full strength on top - so dragging a handle shrinks the visible
  1048. window and dragging the picture slides it behind that window. */
  1049. // fullImageRect returns where the whole picture sits, in slide units,
  1050. // given the frame and crop an object currently has
  1051. function fullImageRect(o) {
  1052. var c = o.props.crop;
  1053. var l = 0, t = 0, kw = 1, kh = 1;
  1054. if (c && c.length === 4) {
  1055. l = Number(c[0]) || 0;
  1056. t = Number(c[1]) || 0;
  1057. kw = 1 - l - (Number(c[2]) || 0);
  1058. kh = 1 - t - (Number(c[3]) || 0);
  1059. }
  1060. if (!(kw > 0.001) || !(kh > 0.001)) { l = 0; t = 0; kw = 1; kh = 1; }
  1061. var fw = o.w / kw, fh = o.h / kh;
  1062. return { x: o.x - l * fw, y: o.y - t * fh, w: fw, h: fh };
  1063. }
  1064. function startCrop(id) {
  1065. var o = objById(id);
  1066. if (!o || o.type !== "image") return;
  1067. if (editingId) endEdit(true);
  1068. if (cropId && cropId !== id) endCrop(true);
  1069. setSel([id]);
  1070. cropId = id;
  1071. cropBefore = { x: o.x, y: o.y, w: o.w, h: o.h,
  1072. crop: o.props.crop ? o.props.crop.slice() : null };
  1073. cropFull = fullImageRect(o);
  1074. cropRect = { x: o.x, y: o.y, w: o.w, h: o.h };
  1075. renderOverlay();
  1076. syncToolbarFromSel();
  1077. OfficeApp.setStatus(
  1078. "Crop: drag the handles to trim, drag the picture to reposition, " +
  1079. "Enter to apply, Esc to cancel", "info", 6000);
  1080. }
  1081. function endCrop(apply) {
  1082. if (!cropId) return;
  1083. var o = objById(cropId);
  1084. cropId = null;
  1085. if (o) {
  1086. if (apply) {
  1087. var l = (cropRect.x - cropFull.x) / cropFull.w;
  1088. var t = (cropRect.y - cropFull.y) / cropFull.h;
  1089. var r = 1 - (cropRect.x + cropRect.w - cropFull.x) / cropFull.w;
  1090. var b = 1 - (cropRect.y + cropRect.h - cropFull.y) / cropFull.h;
  1091. var crop = [l, t, r, b].map(function (v) {
  1092. return Math.round(clamp(v, 0, 0.99) * 10000) / 10000;
  1093. });
  1094. var cropped = crop.some(function (v) { return v > 0.0005; });
  1095. // the frame the whole picture would fill is what Reset image
  1096. // puts back, so it is stamped the first time one is trimmed
  1097. if (cropped && !o.props.orig) {
  1098. o.props.orig = {
  1099. x: Math.round(cropFull.x * 100) / 100,
  1100. y: Math.round(cropFull.y * 100) / 100,
  1101. w: Math.round(cropFull.w * 100) / 100,
  1102. h: Math.round(cropFull.h * 100) / 100
  1103. };
  1104. }
  1105. o.x = cropRect.x; o.y = cropRect.y;
  1106. o.w = cropRect.w; o.h = cropRect.h;
  1107. if (cropped) o.props.crop = crop; else delete o.props.crop;
  1108. commit();
  1109. } else {
  1110. o.x = cropBefore.x; o.y = cropBefore.y;
  1111. o.w = cropBefore.w; o.h = cropBefore.h;
  1112. if (cropBefore.crop) o.props.crop = cropBefore.crop;
  1113. else delete o.props.crop;
  1114. renderEditorSlide();
  1115. }
  1116. }
  1117. cropRect = cropFull = cropBefore = null;
  1118. renderOverlay();
  1119. syncToolbarFromSel();
  1120. }
  1121. var CROP_HANDLES = [
  1122. ["nw", 0, 0], ["n", 0.5, 0], ["ne", 1, 0], ["e", 1, 0.5],
  1123. ["se", 1, 1], ["s", 0.5, 1], ["sw", 0, 1], ["w", 0, 0.5]
  1124. ];
  1125. function renderCropOverlay() {
  1126. if (!cropEl) return;
  1127. var o = objById(cropId);
  1128. if (!o) { cropEl.innerHTML = ""; return; }
  1129. // the picture itself is hidden while the tool is open, so what is
  1130. // on screen is only the ghost and the part being kept
  1131. var srcEl = objEl(cropId);
  1132. if (srcEl) srcEl.classList.add("sl-cropping");
  1133. var s = curScale() || 1;
  1134. var src = esc(o.props.src || "");
  1135. var box = function (r) {
  1136. return "left:" + r.x + "px;top:" + r.y + "px;" +
  1137. "width:" + Math.max(1, r.w) + "px;height:" + Math.max(1, r.h) + "px;";
  1138. };
  1139. var html = '<div class="sl-crop-ghost" style="' + box(cropFull) + '">' +
  1140. '<img draggable="false" src="' + src + '" alt=""></div>';
  1141. // the kept part: the same picture, positioned so it lines up with
  1142. // the ghost behind it, clipped by the crop rectangle
  1143. html += '<div class="sl-crop-rect" style="' + box(cropRect) + '">' +
  1144. '<img draggable="false" src="' + src + '" alt="" style="' +
  1145. "left:" + (cropFull.x - cropRect.x) + "px;top:" + (cropFull.y - cropRect.y) + "px;" +
  1146. "width:" + cropFull.w + "px;height:" + cropFull.h + 'px;">';
  1147. // corner grips are drawn as an L hugging the corner, edge grips as
  1148. // a bar centred on the edge - the same language Slides/Docs use
  1149. var len = Math.min(Math.max(9, 14 / s), Math.min(cropRect.w, cropRect.h) / 2);
  1150. var th = Math.max(2.5, 4 / s);
  1151. CROP_HANDLES.forEach(function (h) {
  1152. var name = h[0];
  1153. var left, top, w, hgt, extra = "";
  1154. if (name === "n" || name === "s") {
  1155. w = len; hgt = th;
  1156. left = cropRect.w / 2 - len / 2;
  1157. top = name === "n" ? 0 : cropRect.h - th;
  1158. } else if (name === "e" || name === "w") {
  1159. w = th; hgt = len;
  1160. left = name === "w" ? 0 : cropRect.w - th;
  1161. top = cropRect.h / 2 - len / 2;
  1162. } else {
  1163. w = len; hgt = len;
  1164. left = name.indexOf("w") >= 0 ? 0 : cropRect.w - len;
  1165. top = name.indexOf("n") >= 0 ? 0 : cropRect.h - len;
  1166. extra = "background:transparent;" +
  1167. "border-" + (name.indexOf("n") >= 0 ? "top" : "bottom") +
  1168. ":" + th + "px solid #202124;" +
  1169. "border-" + (name.indexOf("w") >= 0 ? "left" : "right") +
  1170. ":" + th + "px solid #202124;";
  1171. }
  1172. html += '<div class="sl-croph" data-ch="' + name + '" style="' +
  1173. "left:" + left + "px;top:" + top + "px;" +
  1174. "width:" + w + "px;height:" + hgt + "px;" + extra + '"></div>';
  1175. });
  1176. html += "</div>";
  1177. cropEl.innerHTML = html;
  1178. }
  1179. /* Reset image: undo every crop and shaped crop and put the picture
  1180. back the way it came in. props.orig remembers the frame the whole
  1181. picture filled when it was first trimmed; without one (a picture
  1182. that was only masked) the frame stays where it is and only its
  1183. height is corrected to the source's own aspect ratio. */
  1184. function resetImage(o) {
  1185. if (!o || o.type !== "image") return;
  1186. if (cropId === o.id) endCrop(false);
  1187. var full = fullImageRect(o);
  1188. // everything the picture tools can put on a picture comes off: the
  1189. // crop, the shaped crop, the flips and the colour treatment
  1190. ["crop", "mask", "adj", "radius", "flipH", "flipV",
  1191. "recolor", "bright", "contrast", "opacity"].forEach(function (k) {
  1192. delete o.props[k];
  1193. });
  1194. if (o.props.orig) {
  1195. o.x = o.props.orig.x; o.y = o.props.orig.y;
  1196. o.w = o.props.orig.w; o.h = o.props.orig.h;
  1197. delete o.props.orig;
  1198. } else {
  1199. o.x = full.x; o.y = full.y; o.w = full.w; o.h = full.h;
  1200. }
  1201. var nat = naturalSizeOf(o);
  1202. if (nat && nat.w > 0 && nat.h > 0) {
  1203. // a picture stretched by dragging a corner is undistorted too
  1204. o.h = Math.max(8, o.w * nat.h / nat.w);
  1205. }
  1206. commit();
  1207. OfficeApp.setStatus("Image reset", "success", 2000);
  1208. }
  1209. // naturalSizeOf reads the source's own pixel size off the live <img>,
  1210. // which is already decoded because the object is on screen
  1211. function naturalSizeOf(o) {
  1212. var el = objEl(o.id);
  1213. var img = el ? el.querySelector("img") : null;
  1214. if (img && img.naturalWidth > 0) {
  1215. return { w: img.naturalWidth, h: img.naturalHeight };
  1216. }
  1217. return null;
  1218. }
  1219. function setImageMask(o, kind) {
  1220. if (!o || o.type !== "image") return;
  1221. if (cropId === o.id) endCrop(true);
  1222. // the old shape's adjustments mean nothing to the new one
  1223. delete o.props.adj;
  1224. if (!kind || kind === "rect") {
  1225. delete o.props.mask;
  1226. delete o.props.radius;
  1227. } else {
  1228. o.props.mask = kind;
  1229. if (kind === "roundRect") o.props.radius = Math.min(o.w, o.h) * 0.15;
  1230. else delete o.props.radius;
  1231. }
  1232. commit();
  1233. }
  1234. /* ================= rendering: rail / thumbnails ================= */
  1235. /* A preview is the whole slide at full size, shrunk by a transform. The
  1236. box it has to fit inside is whatever the rail can spare once the
  1237. scrollbar has taken its cut, which varies by platform - so measure it
  1238. rather than assume it. Getting this wrong does not look like a wrong
  1239. scale, it looks like the right-hand edge of every slide is missing. */
  1240. function fitThumbs() {
  1241. var view = document.querySelector("#slThumbs .sl-thumb-view");
  1242. var thumbs = document.getElementById("slThumbs");
  1243. if (!view || !thumbs) return;
  1244. var w = view.clientWidth;
  1245. if (w > 0) thumbs.style.setProperty("--sl-thumb-scale", w / SLIDE_W);
  1246. }
  1247. function renderThumb(i) {
  1248. var $mini = $("#slThumbs .sl-thumb").eq(i).find(".sl-thumb-mini");
  1249. if ($mini.length && body.slides[i]) renderSlideContent($mini[0], body.slides[i]);
  1250. if (overview) {
  1251. var $ov = $("#slOverview .sl-ov-card").eq(i).find(".sl-ov-mini");
  1252. if ($ov.length && body.slides[i]) renderSlideContent($ov[0], body.slides[i]);
  1253. }
  1254. }
  1255. function renderThumbSoon(i) {
  1256. clearTimeout(thumbTimer);
  1257. thumbTimer = setTimeout(function () { renderThumb(i); }, 220);
  1258. }
  1259. function renderAllThumbs() {
  1260. body.slides.forEach(function (s, i) { renderThumb(i); });
  1261. }
  1262. var dragSlideIdx = -1;
  1263. // railFocused answers whose Delete key it is: the rail's or the canvas's
  1264. function railFocused() {
  1265. var a = document.activeElement;
  1266. var rail = document.getElementById("slRail");
  1267. return !!(a && rail && rail.contains(a));
  1268. }
  1269. function renderRail() {
  1270. // deleting a slide rebuilds the rail, and the keyboard should not
  1271. // have to be given back by hand to delete the next one
  1272. var refocus = railFocused();
  1273. var $t = $("#slThumbs").empty();
  1274. body.slides.forEach(function (s, i) {
  1275. var $th = $('<div class="sl-thumb" draggable="true" tabindex="0"></div>');
  1276. if (i === cur) $th.addClass("active");
  1277. var $num = $('<div class="sl-thumb-num"></div>').text(i + 1);
  1278. if (s.hidden) {
  1279. $th.addClass("sl-skipped");
  1280. $num.append($('<span class="sl-skip-mark"></span>').attr("title", SKIP_TIP).html(OfficeIcons.get("skipSlide")));
  1281. }
  1282. $th.append($num);
  1283. var $view = $('<div class="sl-thumb-view"><div class="sl-thumb-mini sl-slidebase sl-showph"></div></div>');
  1284. $th.append($view);
  1285. renderSlideContent($view.find(".sl-thumb-mini")[0], s);
  1286. // Taking focus is what lets Delete mean "this slide", and
  1287. // focusing selects - so the slide the keyboard is on and the
  1288. // slide being edited can never be two different slides.
  1289. $th.on("click", function () { $th.focus(); selectSlide(i); });
  1290. $th.on("focus", function () { selectSlide(i); });
  1291. $th.on("contextmenu", function (e) {
  1292. e.preventDefault();
  1293. selectSlide(i);
  1294. showSlideContextMenu(e.clientX, e.clientY, i);
  1295. });
  1296. // drag to reorder
  1297. $th.on("dragstart", function (e) {
  1298. dragSlideIdx = i;
  1299. $th.addClass("dragging");
  1300. try {
  1301. e.originalEvent.dataTransfer.setData("text/plain", String(i));
  1302. e.originalEvent.dataTransfer.effectAllowed = "move";
  1303. } catch (err) { }
  1304. });
  1305. $th.on("dragover", function (e) {
  1306. if (dragSlideIdx < 0) return;
  1307. e.preventDefault();
  1308. var r = $th[0].getBoundingClientRect();
  1309. var before = (e.originalEvent.clientY - r.top) < r.height / 2;
  1310. $th.toggleClass("drop-before", before).toggleClass("drop-after", !before);
  1311. });
  1312. $th.on("dragleave", function () { $th.removeClass("drop-before drop-after"); });
  1313. $th.on("drop", function (e) {
  1314. e.preventDefault();
  1315. var before = $th.hasClass("drop-before");
  1316. $th.removeClass("drop-before drop-after");
  1317. if (dragSlideIdx < 0 || dragSlideIdx === i) return;
  1318. var to = i + (before ? 0 : 1);
  1319. moveSlideTo(dragSlideIdx, to);
  1320. });
  1321. $th.on("dragend", function () {
  1322. dragSlideIdx = -1;
  1323. $("#slThumbs .sl-thumb").removeClass("dragging drop-before drop-after");
  1324. });
  1325. $t.append($th);
  1326. });
  1327. fitThumbs();
  1328. if (refocus) $("#slThumbs .sl-thumb").eq(cur).focus();
  1329. if (overview) {
  1330. renderOverview();
  1331. focusOverview();
  1332. }
  1333. }
  1334. function updateRailActive() {
  1335. $("#slThumbs .sl-thumb").each(function (i) {
  1336. $(this).toggleClass("active", i === cur);
  1337. });
  1338. // walking the deck with the keys: the rail scrolls with it
  1339. var act = $("#slThumbs .sl-thumb").eq(cur)[0];
  1340. if (act) act.scrollIntoView({ block: "nearest", inline: "nearest" });
  1341. if (overview) {
  1342. $("#slOverview .sl-ov-card").each(function (i) {
  1343. $(this).toggleClass("active", i === cur);
  1344. });
  1345. }
  1346. }
  1347. /* ================= layout / zoom ================= */
  1348. function layoutCanvas() {
  1349. var area = document.getElementById("slCanvasArea");
  1350. if (!area) return;
  1351. var aw = Math.max(60, area.clientWidth - 48);
  1352. var ah = Math.max(60, area.clientHeight - 48);
  1353. fitScale = Math.max(0.05, Math.min(aw / SLIDE_W, ah / SLIDE_H));
  1354. var s = curScale();
  1355. var wrap = document.getElementById("slCanvasWrap");
  1356. wrap.style.width = (SLIDE_W * s) + "px";
  1357. wrap.style.height = (SLIDE_H * s) + "px";
  1358. canvasEl.style.transform = "scale(" + s + ")";
  1359. var gt = Math.max(1, 1.5 / s) + "px";
  1360. guideVEl.style.width = gt;
  1361. guideHEl.style.height = gt;
  1362. renderOverlay();
  1363. if (window.OfficeTextEditBar && OfficeTextEditBar.isVisible()) OfficeTextEditBar.reposition();
  1364. }
  1365. /* ================= status / notes ================= */
  1366. function updateStatus() {
  1367. OfficeApp.updateStatusItem("slide", "Slide " + (cur + 1) + " of " + body.slides.length +
  1368. (curSlide() && curSlide().hidden ? " (skipped)" : ""));
  1369. var msg = "";
  1370. var so = selObjs();
  1371. if (so.length === 1) msg = TYPE_NAMES[so[0].type] || "";
  1372. else if (so.length > 1) msg = so.length + " objects selected";
  1373. OfficeApp.updateStatusItem("sel", esc(msg));
  1374. }
  1375. function syncNotes() {
  1376. $("#slNotesText").val(curSlide().notes || "");
  1377. }
  1378. /* ================= selection / commit ================= */
  1379. function setSel(ids) {
  1380. var seen = {};
  1381. sel = (ids || []).filter(function (id) {
  1382. if (seen[id] || !objById(id)) return false;
  1383. seen[id] = true;
  1384. return true;
  1385. });
  1386. renderOverlay();
  1387. updateStatus();
  1388. syncToolbarFromSel();
  1389. }
  1390. /* While editing, fold the live DOM text back into the model WITHOUT
  1391. leaving edit mode - so toolbar changes mid-edit never clobber the
  1392. user's unsaved typing. */
  1393. function syncEditingIntoModel() {
  1394. if (!editingId) return;
  1395. var o = objById(editingId);
  1396. var el = objEl(editingId);
  1397. if (!o || !el) return;
  1398. if (editingKind === "text") {
  1399. var inner = el.querySelector(".sl-text-in");
  1400. if (inner) o.props.html = inner.innerHTML;
  1401. } else if (editingKind === "shape") {
  1402. var st = el.querySelector(".sl-shape-text");
  1403. if (st) o.props.text = st.innerText.replace(/\n$/, "");
  1404. } else if (editingKind === "table") {
  1405. var cells = el.querySelectorAll("td");
  1406. var rows = deep(o.props.rows || []);
  1407. for (var i = 0; i < cells.length; i++) {
  1408. var r = parseInt(cells[i].getAttribute("data-r"), 10);
  1409. var c = parseInt(cells[i].getAttribute("data-c"), 10);
  1410. if (rows[r] && rows[r][c] !== undefined) {
  1411. rows[r][c] = sanitizeCellHtml(cells[i].innerHTML);
  1412. }
  1413. }
  1414. o.props.rows = rows;
  1415. }
  1416. }
  1417. /* Re-enter edit mode on the freshly re-rendered element (commit()
  1418. rebuilds the DOM, which drops contenteditable state). */
  1419. function reapplyEditState() {
  1420. if (!editingId) return;
  1421. var o = objById(editingId);
  1422. var el = objEl(editingId);
  1423. if (!o || !el) {
  1424. editingId = null;
  1425. editingKind = null;
  1426. if (window.OfficeTextEditBar) OfficeTextEditBar.hide();
  1427. return;
  1428. }
  1429. el.classList.add("sl-editing");
  1430. if (editingKind === "table") {
  1431. var cells = el.querySelectorAll("td");
  1432. for (var i = 0; i < cells.length; i++) cells[i].setAttribute("contenteditable", "true");
  1433. buildTableResizers(o, el);
  1434. } else {
  1435. var inner = el.querySelector(editingKind === "text" ? ".sl-text-in" : ".sl-shape-text");
  1436. if (inner) {
  1437. inner.setAttribute("contenteditable", "true");
  1438. inner.focus();
  1439. try {
  1440. var range = document.createRange();
  1441. range.selectNodeContents(inner);
  1442. range.collapse(false);
  1443. var s = window.getSelection();
  1444. s.removeAllRanges();
  1445. s.addRange(range);
  1446. } catch (e) { }
  1447. }
  1448. }
  1449. el.addEventListener("focusout", onEditFocusOut);
  1450. // the re-render replaced the object element - re-anchor the floating
  1451. // bar to the fresh node (also refreshes its table-op section)
  1452. showTextEditBar(o, el);
  1453. syncListButtonState();
  1454. }
  1455. /* After a model mutation of the current slide: redraw, record undo,
  1456. mark the document dirty and refresh the thumbnail. Live text edits
  1457. are folded in first and edit mode survives the re-render. */
  1458. function commit() {
  1459. syncEditingIntoModel();
  1460. renderEditorSlide();
  1461. reapplyEditState();
  1462. renderOverlay();
  1463. renderThumb(cur);
  1464. updateStatus();
  1465. // the picture bar is anchored to a DOM node the re-render replaced
  1466. if (window.SlidesImageTools) SlidesImageTools.sync();
  1467. OfficeApp.markDirty();
  1468. undo.push(snap());
  1469. }
  1470. /* After structural slide-list changes (add/remove/reorder slides). */
  1471. function structCommit(newCur) {
  1472. cur = clamp(newCur, 0, body.slides.length - 1);
  1473. sel = [];
  1474. renderRail();
  1475. renderEditorSlide();
  1476. renderOverlay();
  1477. syncNotes();
  1478. updateStatus();
  1479. OfficeApp.markDirty();
  1480. undo.push(snap());
  1481. }
  1482. function renderAll() {
  1483. cur = clamp(cur, 0, body.slides.length - 1);
  1484. renderRail();
  1485. renderEditorSlide();
  1486. renderOverlay();
  1487. syncNotes();
  1488. updateStatus();
  1489. syncToolbarFromSel();
  1490. }
  1491. function selectSlide(i) {
  1492. if (i === cur && $("#slThumbs .sl-thumb").length) {
  1493. updateRailActive();
  1494. return;
  1495. }
  1496. endCrop(true);
  1497. endEdit(true);
  1498. cur = clamp(i, 0, body.slides.length - 1);
  1499. sel = [];
  1500. renderEditorSlide();
  1501. renderOverlay();
  1502. updateRailActive();
  1503. syncNotes();
  1504. updateStatus();
  1505. syncToolbarFromSel();
  1506. }
  1507. /* ================= slide operations ================= */
  1508. function addSlideAfter(i, layout) {
  1509. endEdit(true);
  1510. body.slides.splice(i + 1, 0, newSlide(layout || "normal"));
  1511. structCommit(i + 1);
  1512. }
  1513. function duplicateSlide(i) {
  1514. endEdit(true);
  1515. var copy = deep(body.slides[i]);
  1516. copy.id = genId("s");
  1517. copy.objects.forEach(function (o) { o.id = genId(); });
  1518. body.slides.splice(i + 1, 0, copy);
  1519. structCommit(i + 1);
  1520. }
  1521. function deleteSlide(i) {
  1522. endEdit(true);
  1523. if (body.slides.length <= 1) {
  1524. body.slides[0] = newSlide("");
  1525. structCommit(0);
  1526. } else {
  1527. body.slides.splice(i, 1);
  1528. structCommit(Math.min(i, body.slides.length - 1));
  1529. }
  1530. }
  1531. function moveSlide(i, dir) {
  1532. var j = i + dir;
  1533. if (j < 0 || j >= body.slides.length) return;
  1534. var s = body.slides.splice(i, 1)[0];
  1535. body.slides.splice(j, 0, s);
  1536. structCommit(j);
  1537. }
  1538. function moveSlideTo(from, to) {
  1539. var s = body.slides.splice(from, 1)[0];
  1540. if (from < to) to--;
  1541. body.slides.splice(to, 0, s);
  1542. structCommit(to);
  1543. }
  1544. /* Skip slide, Google Slides' name for PowerPoint's Hide Slide: the
  1545. slide stays in the deck, the rail, the overview and every export,
  1546. but the slide show walks past it (present.js). The model keeps it
  1547. as slide.hidden, which the .pptx writes as <p:sld show="0">. */
  1548. var SKIP_TIP = "Skipped in the slide show";
  1549. function toggleSlideSkip(i) {
  1550. var s = body.slides[i];
  1551. if (!s) return;
  1552. endEdit(true);
  1553. if (s.hidden) delete s.hidden;
  1554. else s.hidden = true;
  1555. structCommit(i);
  1556. if (window.OfficeRibbon) OfficeRibbon.refresh();
  1557. OfficeApp.setStatus(s.hidden ? "Slide " + (i + 1) + " will be skipped in the slide show"
  1558. : "Slide " + (i + 1) + " is back in the slide show", "info", 3000);
  1559. }
  1560. function showSlideContextMenu(x, y, i) {
  1561. var skipped = !!(body.slides[i] && body.slides[i].hidden);
  1562. OfficeApp.showContextMenu(x, y, [
  1563. { label: "New slide", icon: "plus", action: function () { addSlideAfter(i); } },
  1564. { label: "Duplicate slide", icon: "clone outline", action: function () { duplicateSlide(i); } },
  1565. { label: "Delete slide", icon: "trash alternate outline", action: function () { deleteSlide(i); } },
  1566. {
  1567. label: skipped ? "Unskip slide" : "Skip slide",
  1568. icon: skipped ? "eye" : "eye slash outline",
  1569. action: function () { toggleSlideSkip(i); }
  1570. },
  1571. { sep: true },
  1572. {
  1573. label: "Move up", icon: "angle up",
  1574. enabled: function () { return i > 0; },
  1575. action: function () { moveSlide(i, -1); }
  1576. },
  1577. {
  1578. label: "Move down", icon: "angle down",
  1579. enabled: function () { return i < body.slides.length - 1; },
  1580. action: function () { moveSlide(i, 1); }
  1581. },
  1582. { sep: true },
  1583. { label: "Background...", icon: "paint brush", action: function () { bgDialog(i); } }
  1584. ]);
  1585. }
  1586. /* ================= object operations ================= */
  1587. function addObj(type, props, geo) {
  1588. var slide = curSlide();
  1589. var o = {
  1590. id: genId(), type: type,
  1591. x: geo.x, y: geo.y, w: geo.w, h: geo.h,
  1592. rot: 0, z: slide.objects.length + 1, props: props
  1593. };
  1594. slide.objects.push(o);
  1595. setSel([o.id]);
  1596. commit();
  1597. return o;
  1598. }
  1599. function deleteSelection() {
  1600. if (!sel.length) return;
  1601. endCrop(false);
  1602. endEdit(false);
  1603. var slide = curSlide();
  1604. slide.objects = slide.objects.filter(function (o) { return sel.indexOf(o.id) < 0; });
  1605. slide.objects.forEach(function (o, i) { o.z = i + 1; });
  1606. sel = [];
  1607. commit();
  1608. }
  1609. /* Object copies also ride the SYSTEM clipboard as marker JSON.
  1610. Without this, Ctrl+C on an object left the system clipboard holding
  1611. whatever was copied before (e.g. an old screenshot), and the paste
  1612. handler - which rightly checks clipboard images first - pasted that
  1613. stale content instead of duplicating the object. Bonus: objects now
  1614. paste across two Slides windows. */
  1615. var OBJ_CLIP_MARKER = "arozos-slides-objects";
  1616. /* A shared text/html snapshot of the copied objects so they can be
  1617. pasted into Docs/Sheets (and external editors). Images/text/tables/
  1618. shapes carry over; video/audio/lines are same-app only. */
  1619. function objectsToHtml(objs) {
  1620. if (!objs || !objs.length) return "";
  1621. var parts = [];
  1622. objs.forEach(function (o) {
  1623. if (o.type === "image") {
  1624. parts.push(OfficeClipboard.imageHtml(absoluteMedia(o.props.src), o.w, o.h));
  1625. } else if (o.type === "text") {
  1626. parts.push('<div>' + (o.props.html || "") + "</div>");
  1627. } else if (o.type === "table") {
  1628. parts.push(tableHtml(o));
  1629. } else if (o.type === "shape") {
  1630. parts.push(OfficeClipboard.imageHtml(
  1631. OfficeClipboard.svgImageSrc(shapeSvg(o)), o.w, o.h));
  1632. } else if (o.type === "chart") {
  1633. // render the chart spec to a self-contained SVG snapshot
  1634. var csvg = OfficeCharts.renderToString(o.props.spec || {},
  1635. Math.max(60, o.w), Math.max(60, o.h));
  1636. csvg = csvg.replace("<svg ", '<svg color="#202124" ');
  1637. parts.push(OfficeClipboard.imageHtml(
  1638. OfficeClipboard.svgImageSrc(csvg), o.w, o.h));
  1639. }
  1640. });
  1641. return parts.join("\n");
  1642. }
  1643. // media?file= links are relative to Office/<app>/; Docs sits at the same
  1644. // depth so they resolve unchanged, but make device data URLs pass through
  1645. function absoluteMedia(src) { return src || ""; }
  1646. function objectClipboardText() {
  1647. return JSON.stringify({ app: OBJ_CLIP_MARKER, version: 1, objects: clip });
  1648. }
  1649. function parseObjectClipboardText(t) {
  1650. if (!t || t.indexOf(OBJ_CLIP_MARKER) < 0) return null;
  1651. try {
  1652. var o = JSON.parse(t);
  1653. if (o && o.app === OBJ_CLIP_MARKER && Array.isArray(o.objects) && o.objects.length) {
  1654. return o.objects;
  1655. }
  1656. } catch (e) { }
  1657. return null;
  1658. }
  1659. function copySelection() {
  1660. if (!sel.length) return;
  1661. clip = selObjs().map(deep);
  1662. // async system-clipboard sync for menu/toolbar copies (writes both
  1663. // the object marker and the shared text/html); real Ctrl+C goes
  1664. // through the "copy" event which sets both synchronously
  1665. OfficeClipboard.writeAsync({
  1666. text: objectClipboardText(),
  1667. html: objectsToHtml(clip)
  1668. }).catch(function () { });
  1669. OfficeApp.setStatus(clip.length + " object" + (clip.length > 1 ? "s" : "") + " copied");
  1670. }
  1671. function cutSelection() {
  1672. if (!sel.length) return;
  1673. copySelection();
  1674. deleteSelection();
  1675. }
  1676. /* Home > Paste > Keep text only: the clipboard's text, into the text
  1677. being edited or as a new text box in the slide's theme (copied
  1678. objects give up their text) */
  1679. function pasteTextOnly() {
  1680. if (!(navigator.clipboard && navigator.clipboard.readText)) {
  1681. OfficeApp.setStatus("Use Ctrl+V to paste here", "error");
  1682. return;
  1683. }
  1684. navigator.clipboard.readText().then(function (t) {
  1685. var objs = parseObjectClipboardText(t);
  1686. if (objs) {
  1687. var div = document.createElement("div");
  1688. t = objs.map(function (o) {
  1689. div.innerHTML = o.html || "";
  1690. return (div.innerText || div.textContent || "").trim();
  1691. }).filter(Boolean).join("\n");
  1692. } else if (OfficeClipboard.isMarker(t)) {
  1693. t = "";
  1694. }
  1695. if (!t) { OfficeApp.setStatus("There is no text to paste", "error"); return; }
  1696. if (editingId) {
  1697. try { document.execCommand("insertText", false, t); } catch (e) { }
  1698. return;
  1699. }
  1700. var th = themeOf();
  1701. addObj("text", { html: esc(t).replace(/\n/g, "<br>"), fontSize: 24, color: th.text, align: "left" },
  1702. { x: 280, y: 220, w: 400, h: 90 });
  1703. }).catch(function () {
  1704. OfficeApp.setStatus("Paste blocked by the browser - use Ctrl+V instead", "error");
  1705. });
  1706. }
  1707. function pasteClipboard() {
  1708. if (!clip || !clip.length) return false;
  1709. var slide = curSlide();
  1710. var ids = [];
  1711. var gidMap = {}; // pasted copies form their own new groups
  1712. clip.forEach(function (c) {
  1713. var n = deep(c);
  1714. n.id = genId();
  1715. if (n.group) {
  1716. if (!gidMap[n.group]) gidMap[n.group] = genId("g");
  1717. n.group = gidMap[n.group];
  1718. }
  1719. n.x += 15; n.y += 15;
  1720. n.z = slide.objects.length + 1;
  1721. slide.objects.push(n);
  1722. ids.push(n.id);
  1723. });
  1724. clip = clip.map(function (c) { var n = deep(c); n.x += 15; n.y += 15; return n; });
  1725. setSel(ids);
  1726. commit();
  1727. adoptPastedMedia(ids);
  1728. return true;
  1729. }
  1730. /* Pictures copied from another window link into that window's working
  1731. copies, which go when it closes: make them this window's own. */
  1732. function adoptPastedMedia(ids) {
  1733. var slide = curSlide();
  1734. slide.objects.forEach(function (o) {
  1735. if (ids.indexOf(o.id) < 0 || !o.props) return;
  1736. ["src", "png", "poster"].forEach(function (k) {
  1737. var v = o.props[k];
  1738. if (!v || !OfficePlatform.isForeignWorkingCopy(v)) return;
  1739. OfficePlatform.adoptSrc(v, function (nv) {
  1740. if (nv === v || o.props[k] !== v) return;
  1741. o.props[k] = nv;
  1742. OfficeApp.markDirty();
  1743. renderAll();
  1744. });
  1745. });
  1746. });
  1747. }
  1748. function duplicateSelection() {
  1749. if (!sel.length) return;
  1750. var saved = clip;
  1751. clip = selObjs().map(deep);
  1752. pasteClipboard();
  1753. clip = saved;
  1754. }
  1755. function nudgeSelection(dx, dy) {
  1756. var so = selObjs();
  1757. if (!so.length) return;
  1758. so.forEach(function (o) {
  1759. o.x = clamp(o.x + dx, -2000, 3000);
  1760. o.y = clamp(o.y + dy, -2000, 3000);
  1761. updateObjEl(o);
  1762. });
  1763. renderOverlay();
  1764. OfficeApp.markDirty();
  1765. undo.pushDebounced(snap, 600);
  1766. renderThumbSoon(cur);
  1767. }
  1768. function cycleSelection() {
  1769. var objs = curSlide().objects;
  1770. if (!objs.length) return;
  1771. if (!sel.length) { setSel([objs[0].id]); return; }
  1772. var i = -1;
  1773. objs.forEach(function (o, oi) { if (o.id === sel[0]) i = oi; });
  1774. setSel([objs[(i + 1) % objs.length].id]);
  1775. }
  1776. function selectAllObjects() {
  1777. setSel(curSlide().objects.map(function (o) { return o.id; }));
  1778. }
  1779. function reorderSelection(mode) {
  1780. if (!sel.length) return;
  1781. var slide = curSlide();
  1782. var objs = slide.objects;
  1783. var isSel = function (o) { return sel.indexOf(o.id) >= 0; };
  1784. var i;
  1785. if (mode === "front") {
  1786. slide.objects = objs.filter(function (o) { return !isSel(o); })
  1787. .concat(objs.filter(isSel));
  1788. } else if (mode === "back") {
  1789. slide.objects = objs.filter(isSel)
  1790. .concat(objs.filter(function (o) { return !isSel(o); }));
  1791. } else if (mode === "forward") {
  1792. for (i = objs.length - 2; i >= 0; i--) {
  1793. if (isSel(objs[i]) && !isSel(objs[i + 1])) {
  1794. var t = objs[i]; objs[i] = objs[i + 1]; objs[i + 1] = t;
  1795. }
  1796. }
  1797. } else if (mode === "backward") {
  1798. for (i = 1; i < objs.length; i++) {
  1799. if (isSel(objs[i]) && !isSel(objs[i - 1])) {
  1800. var t2 = objs[i]; objs[i] = objs[i - 1]; objs[i - 1] = t2;
  1801. }
  1802. }
  1803. }
  1804. slide.objects.forEach(function (o, oi) { o.z = oi + 1; });
  1805. commit();
  1806. }
  1807. function alignSelection(mode) {
  1808. var so = selObjs();
  1809. if (!so.length) return;
  1810. so.forEach(function (o) {
  1811. var bb = getBBox(o);
  1812. var target;
  1813. switch (mode) {
  1814. case "left": target = 0; o.x += target - bb.x; break;
  1815. case "center": target = (SLIDE_W - bb.w) / 2; o.x += target - bb.x; break;
  1816. case "right": target = SLIDE_W - bb.w; o.x += target - bb.x; break;
  1817. case "top": target = 0; o.y += target - bb.y; break;
  1818. case "middle": target = (SLIDE_H - bb.h) / 2; o.y += target - bb.y; break;
  1819. case "bottom": target = SLIDE_H - bb.h; o.y += target - bb.y; break;
  1820. }
  1821. });
  1822. commit();
  1823. }
  1824. /* ---------- grouping ---------- */
  1825. function groupSelection() {
  1826. var so = selObjs();
  1827. if (so.length < 2) {
  1828. OfficeApp.setStatus("Select two or more objects to group them", "error");
  1829. return;
  1830. }
  1831. var gid = genId("g");
  1832. so.forEach(function (o) { o.group = gid; });
  1833. commit();
  1834. OfficeApp.setStatus("Grouped " + so.length + " objects");
  1835. }
  1836. function ungroupSelection() {
  1837. var so = selObjs();
  1838. var any = false;
  1839. so.forEach(function (o) { if (o.group) { delete o.group; any = true; } });
  1840. if (any) {
  1841. commit();
  1842. OfficeApp.setStatus("Ungrouped");
  1843. }
  1844. }
  1845. function selectionHasGroup() {
  1846. return selObjs().some(function (o) { return !!o.group; });
  1847. }
  1848. /* expand an id list with every member of the touched groups */
  1849. function expandGroups(ids) {
  1850. var gids = {};
  1851. ids.forEach(function (id) {
  1852. var o = objById(id);
  1853. if (o && o.group) gids[o.group] = true;
  1854. });
  1855. if (!Object.keys(gids).length) return ids;
  1856. var out = ids.slice();
  1857. curSlide().objects.forEach(function (o) {
  1858. if (o.group && gids[o.group] && out.indexOf(o.id) < 0) out.push(o.id);
  1859. });
  1860. return out;
  1861. }
  1862. /* ---------- animation / link ---------- */
  1863. function setAnimation(key) {
  1864. applyToSel(function (o) {
  1865. if (key) o.props.anim = key;
  1866. else delete o.props.anim;
  1867. return true;
  1868. });
  1869. OfficeApp.setStatus(key
  1870. ? "Entrance animation set - objects appear click-by-click in present mode"
  1871. : "Animation removed");
  1872. }
  1873. function linkDialog() {
  1874. var so = selObjs();
  1875. if (so.length !== 1) {
  1876. OfficeApp.setStatus("Select a single object to link", "error");
  1877. return;
  1878. }
  1879. var o = so[0];
  1880. var cur = o.props.link || "";
  1881. var isSlide = /^#\d+$/.test(cur);
  1882. var $b = $(
  1883. '<div><label style="display:flex;align-items:center;gap:6px;">' +
  1884. '<input type="radio" name="slLinkKind" value="url" style="width:auto;"' + (isSlide ? "" : " checked") + "> Web address</label>" +
  1885. '<input type="text" id="slLinkUrl" placeholder="https://..." value="' + esc(isSlide ? "" : cur) + '">' +
  1886. '<label style="display:flex;align-items:center;gap:6px;margin-top:10px;">' +
  1887. '<input type="radio" name="slLinkKind" value="slide" style="width:auto;"' + (isSlide ? " checked" : "") + "> Go to slide</label>" +
  1888. '<input type="number" id="slLinkSlide" min="1" max="' + body.slides.length + '" value="' +
  1889. (isSlide ? cur.substring(1) : "1") + '"></div>'
  1890. );
  1891. OfficeApp.dialog({
  1892. title: "Object link (opens in present mode)",
  1893. body: $b,
  1894. buttons: [
  1895. {
  1896. label: "Remove link", danger: true,
  1897. action: function (close) {
  1898. close();
  1899. delete o.props.link;
  1900. commit();
  1901. }
  1902. },
  1903. { label: "Cancel" },
  1904. {
  1905. label: "Apply", primary: true,
  1906. action: function (close, $bd) {
  1907. var kind = $bd.find('input[name="slLinkKind"]:checked').val();
  1908. if (kind === "slide") {
  1909. var n = clamp(parseInt($bd.find("#slLinkSlide").val(), 10) || 1, 1, body.slides.length);
  1910. o.props.link = "#" + n;
  1911. } else {
  1912. var u = $bd.find("#slLinkUrl").val().trim();
  1913. if (!/^https?:\/\//i.test(u)) {
  1914. OfficeApp.toast("Enter a full http(s):// address", "error");
  1915. return;
  1916. }
  1917. o.props.link = u;
  1918. }
  1919. close();
  1920. commit();
  1921. }
  1922. }
  1923. ]
  1924. });
  1925. }
  1926. /* Apply a property mutation to selected objects; commit when changed. */
  1927. function applyToSel(fn) {
  1928. var so = selObjs();
  1929. if (!so.length) return false;
  1930. var changed = false;
  1931. so.forEach(function (o) { if (fn(o) !== false) changed = true; });
  1932. if (changed) commit();
  1933. return changed;
  1934. }
  1935. /* ================= object insertion ================= */
  1936. function insertText() {
  1937. var th = themeOf();
  1938. // empty, caret in it: left empty it prompts "Click to add text"
  1939. var o = addObj("text", { html: "", fontSize: 24, color: th.text, align: "left" },
  1940. { x: 330, y: 240, w: 300, h: 60 });
  1941. startEdit(o.id);
  1942. }
  1943. /* showShapePicker is the Insert > Shape control: the categories on the
  1944. left, the shapes of the one in hand as icons on the right. Icons and
  1945. not a list of names, because the outline is the thing being chosen -
  1946. and they are drawn from the catalogue, so a picker entry cannot come
  1947. to disagree with what gets inserted. */
  1948. var $shapePicker = null;
  1949. function closeShapePicker() {
  1950. if ($shapePicker) { $shapePicker.remove(); $shapePicker = null; }
  1951. $(document).off("mousedown.slshapepick");
  1952. }
  1953. function showShapePicker(x, y) {
  1954. closeShapePicker();
  1955. var $m = $('<div class="sl-shapepick of-noprint"></div>');
  1956. var $cats = $('<div class="sl-shapepick-cats"></div>');
  1957. var $grid = $('<div class="sl-shapepick-grid"></div>');
  1958. SlidesShapes.CATEGORIES.forEach(function (c, idx) {
  1959. var $b = $('<button type="button" class="sl-shapepick-cat"></button>');
  1960. $b.append($('<i class="icon"></i>').addClass(c.icon));
  1961. $b.append($("<span></span>").text(c.label));
  1962. $b.append('<i class="caret right icon sl-shapepick-more"></i>');
  1963. function open() {
  1964. $cats.find(".sl-shapepick-cat").removeClass("active");
  1965. $b.addClass("active");
  1966. $grid.empty();
  1967. c.kinds.forEach(function (k) {
  1968. var $cell = $('<button type="button" class="sl-shapepick-cell"></button>')
  1969. .attr("title", SlidesShapes.label(k))
  1970. .html(SlidesShapes.icon(k, 22));
  1971. $cell.on("click", function () { closeShapePicker(); insertShape(k); });
  1972. $grid.append($cell);
  1973. });
  1974. }
  1975. $b.on("mouseenter click", open);
  1976. if (idx === 0) open();
  1977. $cats.append($b);
  1978. });
  1979. $m.append($cats).append($grid);
  1980. $("body").append($m);
  1981. var mw = $m.outerWidth(), mh = $m.outerHeight();
  1982. $m.css({
  1983. left: Math.max(4, Math.min(x, window.innerWidth - mw - 6)) + "px",
  1984. top: Math.max(4, Math.min(y, window.innerHeight - mh - 6)) + "px"
  1985. });
  1986. $shapePicker = $m;
  1987. setTimeout(function () {
  1988. $(document).on("mousedown.slshapepick", function (e) {
  1989. if ($shapePicker && !$shapePicker[0].contains(e.target)) closeShapePicker();
  1990. });
  1991. }, 0);
  1992. }
  1993. // a brace or a bracket only reads as itself tall and narrow, so the
  1994. // catalogue gets to say what box its shapes want
  1995. function shapeDefaultSize(kind) {
  1996. return SlidesShapes.defaultSize(kind) || [200, 160];
  1997. }
  1998. function shapeProps(kind) {
  1999. var th = themeOf();
  2000. var props = {
  2001. kind: kind, fill: /^#[0-9a-fA-F]{6}$/.test(th.accent) ? th.accent : "#e07b1f",
  2002. stroke: "#333333", strokeW: 0, text: "", fontSize: 18
  2003. };
  2004. // a speech bubble starts with its tip where PowerPoint puts one,
  2005. // and a yellow handle to move it
  2006. if (SlidesShapes.adjustable(kind) === "tip") props.adj = SlidesShapes.tipDefaults(kind);
  2007. return props;
  2008. }
  2009. /* Picking a shape arms the canvas, as PowerPoint does: drag out the box
  2010. it should fill (Shift keeps the shape's own proportions), or click to
  2011. drop one at its default size there. */
  2012. var pendingShape = null;
  2013. function insertShape(kind) {
  2014. armDraw("shape");
  2015. pendingShape = kind;
  2016. OfficeApp.setStatus("Drag on the slide to draw the " + SlidesShapes.label(kind).toLowerCase() +
  2017. " (Shift keeps its proportions), or click to place it - Esc to cancel", "info", 0);
  2018. }
  2019. function armDraw(kind) {
  2020. endEdit(true);
  2021. pendingDraw = kind;
  2022. pendingShape = null;
  2023. canvasEl.classList.add("sl-drawmode");
  2024. OfficeApp.setStatus("Drag on the slide to draw a " + (kind === "arrow" ? "arrow" : "line") +
  2025. " - Esc to cancel", "info", 0);
  2026. syncDrawButtons();
  2027. }
  2028. function disarmDraw() {
  2029. pendingDraw = null;
  2030. pendingShape = null;
  2031. canvasEl.classList.remove("sl-drawmode");
  2032. OfficeApp.setStatus("");
  2033. syncDrawButtons();
  2034. }
  2035. function syncDrawButtons() {
  2036. $("#slBtnLine").toggleClass("active", pendingDraw === "line");
  2037. $("#slBtnArrow").toggleClass("active", pendingDraw === "arrow");
  2038. if (window.OfficeRibbon) OfficeRibbon.refresh();
  2039. }
  2040. function placeImage(src) {
  2041. var img = new Image();
  2042. var place = function (w, h) {
  2043. var sc = Math.min(480 / w, 320 / h, 1);
  2044. var pw = Math.max(40, Math.round(w * sc)), ph = Math.max(40, Math.round(h * sc));
  2045. addObj("image", { src: src, fit: "contain" },
  2046. { x: Math.round((SLIDE_W - pw) / 2), y: Math.round((SLIDE_H - ph) / 2), w: pw, h: ph });
  2047. };
  2048. img.onload = function () { place(img.naturalWidth || 480, img.naturalHeight || 320); };
  2049. img.onerror = function () { place(480, 320); };
  2050. img.src = src;
  2051. }
  2052. /* ArozOS storage does not exist in the standalone web edition; the menu
  2053. drops the entry there rather than offering a picker that cannot open. */
  2054. function storageSourceItem(action) {
  2055. if (!OfficePlatform.hasBackend()) return null;
  2056. return { label: "From ArozOS storage...", icon: "folder open", action: action };
  2057. }
  2058. function imageFromStorage() {
  2059. OfficePlatform.pickOpen({
  2060. filter: ["png", "jpg", "jpeg", "gif", "webp", "bmp", "svg"],
  2061. multiple: true,
  2062. memoryKey: "media"
  2063. }, function (files) {
  2064. files.forEach(function (f) {
  2065. // reference the storage file - the server reads it into the
  2066. // saved file, keeping edits and saves lightweight
  2067. placeImage(OfficeApp.mediaUrl(f.filepath));
  2068. });
  2069. });
  2070. }
  2071. function imageFromDevice() {
  2072. $("#slDeviceImage").trigger("click");
  2073. }
  2074. function imageFromUrl() {
  2075. OfficeApp.prompt("Insert image from URL", "Image URL", "https://", function (v) {
  2076. if (v) placeImage(v.trim());
  2077. });
  2078. }
  2079. /* ---------- video / audio (workdir-linked, read into the file on save) ---------- */
  2080. function placeMedia(kind, src) {
  2081. var geo = kind === "video"
  2082. ? { x: 240, y: 135, w: 480, h: 270 }
  2083. : { x: 280, y: 240, w: 400, h: 64 };
  2084. addObj(kind, { src: src, autoplay: false }, geo);
  2085. OfficeApp.setStatus(TYPE_NAMES[kind] + " inserted - it plays with its controls in present mode");
  2086. }
  2087. function mediaBlobToObject(kind, blob, name) {
  2088. if (blob.size > MEDIA_MAX_BYTES) {
  2089. OfficeApp.toast("File is too large (max " + Math.round(MEDIA_MAX_BYTES / 1048576) + " MB)", "error");
  2090. return;
  2091. }
  2092. // big files stream to user:/.appdata/Office/uploads and are linked;
  2093. // the save reads them server side without a giant POST payload
  2094. OfficeApp.showBusy("Importing " + (name || TYPE_NAMES[kind].toLowerCase()) + "...");
  2095. OfficeApp.blobToSrc(blob, name || (kind + ".bin"), function (src) {
  2096. OfficeApp.hideBusy();
  2097. placeMedia(kind, src);
  2098. }, function (msg) {
  2099. OfficeApp.hideBusy();
  2100. OfficeApp.toast(msg, "error");
  2101. });
  2102. }
  2103. function mediaFromStorage(kind) {
  2104. var filters = kind === "video"
  2105. ? ["mp4", "webm", "ogv"]
  2106. : ["mp3", "wav", "ogg", "flac", "aac"];
  2107. OfficePlatform.pickOpen({ filter: filters, memoryKey: "media" }, function (files) {
  2108. // just link it - the server reads the file in at save time
  2109. placeMedia(kind, OfficeApp.mediaUrl(files[0].filepath));
  2110. });
  2111. }
  2112. function mediaFromDevice(kind) {
  2113. var input = document.createElement("input");
  2114. input.type = "file";
  2115. input.accept = kind === "video" ? "video/*" : "audio/*";
  2116. input.onchange = function () {
  2117. if (input.files && input.files[0]) {
  2118. mediaBlobToObject(kind, input.files[0], input.files[0].name);
  2119. }
  2120. };
  2121. input.click();
  2122. }
  2123. function tableDialog() {
  2124. var $b = $(
  2125. '<div class="sl-dialog-row">' +
  2126. '<div><label>Rows</label><input type="number" id="slTblRows" min="1" max="20" value="3"></div>' +
  2127. '<div><label>Columns</label><input type="number" id="slTblCols" min="1" max="12" value="3"></div>' +
  2128. "</div>" +
  2129. '<div class="sl-swatch-row"><input type="checkbox" id="slTblHead" checked style="width:auto;">' +
  2130. '<label for="slTblHead" style="display:inline;margin:0;">First row is a header</label></div>'
  2131. );
  2132. OfficeApp.dialog({
  2133. title: "Insert table",
  2134. body: $b,
  2135. buttons: [
  2136. { label: "Cancel" },
  2137. {
  2138. label: "Insert", primary: true,
  2139. action: function (close, $bd) {
  2140. var r = clamp(parseInt($bd.find("#slTblRows").val(), 10) || 3, 1, 20);
  2141. var c = clamp(parseInt($bd.find("#slTblCols").val(), 10) || 3, 1, 12);
  2142. var head = $bd.find("#slTblHead").prop("checked");
  2143. close();
  2144. var rows = [];
  2145. for (var ri = 0; ri < r; ri++) {
  2146. var row = [];
  2147. for (var ci = 0; ci < c; ci++) row.push("");
  2148. rows.push(row);
  2149. }
  2150. var th = themeOf();
  2151. var w = Math.min(760, Math.max(240, c * 150));
  2152. var h = Math.min(440, r * 38 + 6);
  2153. addObj("table", { rows: rows, headerRow: head, fontSize: 16, color: th.text },
  2154. { x: Math.round((SLIDE_W - w) / 2), y: 120, w: w, h: h });
  2155. }
  2156. }
  2157. ]
  2158. });
  2159. }
  2160. /* ---------- chart dialog (insert + re-edit) ---------- */
  2161. function chartDialog(existing) {
  2162. var spec = existing ? deep(existing.props.spec || {}) : {
  2163. type: "bar", title: "",
  2164. labels: ["A", "B", "C", "D"],
  2165. series: [{ name: "Series 1", values: [4, 7, 5, 8] },
  2166. { name: "Series 2", values: [2, 4, 6, 3] }]
  2167. };
  2168. spec.labels = spec.labels || [];
  2169. spec.series = (spec.series && spec.series.length) ? spec.series : [{ name: "Series 1", values: [] }];
  2170. var $b = $(
  2171. '<div class="sl-dialog-row" style="margin-bottom:10px;">' +
  2172. '<div style="flex:0 0 130px;"><label>Type</label><select id="slChType">' +
  2173. '<option value="bar">Bar</option><option value="line">Line</option><option value="pie">Pie</option>' +
  2174. "</select></div>" +
  2175. '<div><label>Title</label><input type="text" id="slChTitle"></div>' +
  2176. '<div style="flex:0 0 auto;"><label>&nbsp;</label>' +
  2177. '<span class="sl-swatch-row" style="margin:0;"><input type="checkbox" id="slChStacked" style="width:auto;">' +
  2178. '<label for="slChStacked" style="display:inline;margin:0;">Stacked</label></span></div>' +
  2179. "</div>" +
  2180. '<div style="max-height:44vh;overflow:auto;"><table class="sl-grid-table" id="slChGrid"></table></div>' +
  2181. '<div class="sl-grid-tools">' +
  2182. '<button type="button" class="of-btn" data-op="addrow"><i class="plus icon"></i>Row</button>' +
  2183. '<button type="button" class="of-btn" data-op="delrow"><i class="minus icon"></i>Row</button>' +
  2184. '<button type="button" class="of-btn" data-op="addcol"><i class="plus icon"></i>Series</button>' +
  2185. '<button type="button" class="of-btn" data-op="delcol"><i class="minus icon"></i>Series</button>' +
  2186. "</div>"
  2187. );
  2188. $b.find("#slChType").val(spec.type || "bar");
  2189. $b.find("#slChTitle").val(spec.title || "");
  2190. $b.find("#slChStacked").prop("checked", !!(spec.options && spec.options.stacked));
  2191. function renderGrid() {
  2192. var $g = $b.find("#slChGrid").empty();
  2193. var $hr = $("<tr></tr>");
  2194. $hr.append('<td><input type="text" value="Category" disabled style="opacity:.55;"></td>');
  2195. spec.series.forEach(function (s, si) {
  2196. $hr.append('<td><input type="text" class="sl-ch-sname" data-s="' + si +
  2197. '" value="' + esc(s.name || ("Series " + (si + 1))) + '"></td>');
  2198. });
  2199. $g.append($hr);
  2200. spec.labels.forEach(function (l, li) {
  2201. var $r = $("<tr></tr>");
  2202. $r.append('<td><input type="text" class="sl-ch-label" data-l="' + li +
  2203. '" value="' + esc(l) + '"></td>');
  2204. spec.series.forEach(function (s, si) {
  2205. var v = (s.values && s.values[li] !== undefined) ? s.values[li] : "";
  2206. $r.append('<td><input type="text" class="sl-ch-val" data-l="' + li +
  2207. '" data-s="' + si + '" value="' + esc(v) + '"></td>');
  2208. });
  2209. $g.append($r);
  2210. });
  2211. }
  2212. function readGrid() {
  2213. $b.find(".sl-ch-sname").each(function () {
  2214. spec.series[$(this).data("s")].name = $(this).val();
  2215. });
  2216. $b.find(".sl-ch-label").each(function () {
  2217. spec.labels[$(this).data("l")] = $(this).val();
  2218. });
  2219. spec.series.forEach(function (s) { s.values = s.values || []; });
  2220. $b.find(".sl-ch-val").each(function () {
  2221. var li = $(this).data("l"), si = $(this).data("s");
  2222. spec.series[si].values[li] = parseFloat($(this).val()) || 0;
  2223. });
  2224. }
  2225. $b.on("click", ".sl-grid-tools .of-btn", function () {
  2226. readGrid();
  2227. var op = $(this).data("op");
  2228. if (op === "addrow") {
  2229. spec.labels.push("Item " + (spec.labels.length + 1));
  2230. spec.series.forEach(function (s) { s.values.push(0); });
  2231. } else if (op === "delrow" && spec.labels.length > 1) {
  2232. spec.labels.pop();
  2233. spec.series.forEach(function (s) { s.values.pop(); });
  2234. } else if (op === "addcol") {
  2235. var vals = spec.labels.map(function () { return 0; });
  2236. spec.series.push({ name: "Series " + (spec.series.length + 1), values: vals });
  2237. } else if (op === "delcol" && spec.series.length > 1) {
  2238. spec.series.pop();
  2239. }
  2240. renderGrid();
  2241. });
  2242. renderGrid();
  2243. OfficeApp.dialog({
  2244. title: existing ? "Edit chart" : "Insert chart",
  2245. body: $b,
  2246. wide: true,
  2247. buttons: [
  2248. { label: "Cancel" },
  2249. {
  2250. label: existing ? "Update" : "Insert", primary: true,
  2251. action: function (close, $bd) {
  2252. readGrid();
  2253. spec.type = $bd.find("#slChType").val();
  2254. spec.title = $bd.find("#slChTitle").val();
  2255. spec.options = spec.options || {};
  2256. spec.options.stacked = $bd.find("#slChStacked").prop("checked");
  2257. close();
  2258. if (existing) {
  2259. existing.props.spec = spec;
  2260. commit();
  2261. } else {
  2262. addObj("chart", { spec: spec }, { x: 240, y: 110, w: 480, h: 320 });
  2263. }
  2264. }
  2265. }
  2266. ]
  2267. });
  2268. }
  2269. /* ---------- slide background dialog ---------- */
  2270. function bgDialog(i) {
  2271. var slide = body.slides[i];
  2272. // a picture or gradient brought in with the deck stays until the
  2273. // slide is given a colour (or the theme's background) instead
  2274. var fancy = !!(slide.bgImage || slide.bgGrad);
  2275. var initial = (slide.bg && /^#[0-9a-f]{6}/i.test(slide.bg)) ? slide.bg.substring(0, 7) : "#ffffff";
  2276. var $b = $(
  2277. (fancy ? '<div class="sl-swatch-row"><input type="checkbox" id="slBgKeep" style="width:auto;" checked>' +
  2278. '<label for="slBgKeep" style="display:inline;margin:0;">Keep the picture / gradient background</label></div>' : "") +
  2279. '<div class="sl-swatch-row"><input type="checkbox" id="slBgTheme" style="width:auto;"' +
  2280. (slide.bg || fancy ? "" : " checked") + ">" +
  2281. '<label for="slBgTheme" style="display:inline;margin:0;">Use theme background</label></div>' +
  2282. '<div class="sl-swatch-row"><label style="display:inline;margin:0;">Custom color</label></div>'
  2283. );
  2284. $b.children().last().append(OfficeColorPicker.swatchInput({
  2285. id: "slBgColor", title: "Slide background color", value: initial
  2286. }).css({ width: "60px", height: "32px" }));
  2287. $b.find("#slBgColor").on("input", function () {
  2288. $b.find("#slBgTheme, #slBgKeep").prop("checked", false);
  2289. });
  2290. $b.find("#slBgTheme").on("change", function () {
  2291. if (this.checked) $b.find("#slBgKeep").prop("checked", false);
  2292. });
  2293. OfficeApp.dialog({
  2294. title: "Slide background",
  2295. body: $b,
  2296. buttons: [
  2297. { label: "Cancel" },
  2298. {
  2299. label: "Apply", primary: true,
  2300. action: function (close, $bd) {
  2301. var useTheme = $bd.find("#slBgTheme").prop("checked");
  2302. if (fancy && $bd.find("#slBgKeep").prop("checked")) {
  2303. close();
  2304. return;
  2305. }
  2306. delete slide.bgImage;
  2307. delete slide.bgGrad;
  2308. slide.bg = useTheme ? null : $bd.find("#slBgColor").val();
  2309. close();
  2310. if (i === cur) commit(); else { OfficeApp.markDirty(); undo.push(snap()); }
  2311. renderThumb(i);
  2312. }
  2313. }
  2314. ]
  2315. });
  2316. }
  2317. /* ---------- theme picker ---------- */
  2318. /* Objects created under the old theme keep its default text color as an
  2319. explicit value - remap those to the new theme's default so switching
  2320. e.g. dark -> light does not leave invisible white text behind. */
  2321. function remapThemeColors(oldTheme, newTheme) {
  2322. var oldText = (oldTheme.text || "").toLowerCase();
  2323. var newText = newTheme.text;
  2324. if (!oldText || oldText === (newText || "").toLowerCase()) return;
  2325. var matches = function (c) { return (c || "").toLowerCase() === oldText; };
  2326. body.slides.forEach(function (s) {
  2327. s.objects.forEach(function (o) {
  2328. var p = o.props;
  2329. if (o.type === "text" || o.type === "table") {
  2330. if (matches(p.color)) p.color = newText;
  2331. } else if (o.type === "shape") {
  2332. if (matches(p.textColor)) p.textColor = newText;
  2333. } else if (o.type === "line") {
  2334. if (matches(p.stroke)) p.stroke = newText;
  2335. }
  2336. });
  2337. });
  2338. }
  2339. function setTheme(key) {
  2340. if (!THEMES[key] || body.theme === key) return;
  2341. var oldTheme = themeOf();
  2342. body.theme = key;
  2343. remapThemeColors(oldTheme, THEMES[key]);
  2344. renderEditorSlide();
  2345. renderOverlay();
  2346. renderAllThumbs();
  2347. OfficeApp.markDirty();
  2348. undo.push(snap());
  2349. }
  2350. function themeDialog() {
  2351. var $g = $('<div class="sl-theme-grid"></div>');
  2352. Object.keys(THEMES).forEach(function (k) {
  2353. var t = THEMES[k];
  2354. var $c = $('<div class="sl-theme-card' + (body.theme === k ? " active" : "") + '"></div>');
  2355. $c.append('<div class="sl-theme-prev" style="background:' + t.bg + ";color:" + t.text + ';">Aa</div>');
  2356. $c.append('<div class="sl-theme-name">' + esc(t.label) + "</div>");
  2357. $c.on("click", function () {
  2358. setTheme(k);
  2359. $g.find(".sl-theme-card").removeClass("active");
  2360. $c.addClass("active");
  2361. });
  2362. $g.append($c);
  2363. });
  2364. OfficeApp.dialog({
  2365. title: "Presentation theme",
  2366. body: $g,
  2367. buttons: [{ label: "Done", primary: true }]
  2368. });
  2369. }
  2370. /* ================= table row/col ops ================= */
  2371. function tableCellTarget(o) {
  2372. var rows = o.props.rows || [];
  2373. var r = lastCell ? clamp(lastCell.r, 0, rows.length - 1) : rows.length - 1;
  2374. var c = lastCell ? clamp(lastCell.c, 0, (rows[0] || []).length - 1) : (rows[0] || []).length - 1;
  2375. return { r: r, c: c };
  2376. }
  2377. function tableAddRow(o, after) {
  2378. var t = tableCellTarget(o);
  2379. var cols = (o.props.rows[0] || []).length || 1;
  2380. var row = [];
  2381. for (var i = 0; i < cols; i++) row.push("");
  2382. o.props.rows.splice(t.r + (after ? 1 : 0), 0, row);
  2383. if (Array.isArray(o.props.cellFill)) o.props.cellFill.splice(t.r + (after ? 1 : 0), 0, row.slice());
  2384. if (Array.isArray(o.props.cellAnchor)) o.props.cellAnchor.splice(t.r + (after ? 1 : 0), 0, row.slice());
  2385. // a merge cannot follow the grid through a new row or column
  2386. delete o.props.merges;
  2387. delete o.props.rowH;
  2388. o.h += Math.max(24, Math.round(o.h / Math.max(1, o.props.rows.length - 1)));
  2389. commit();
  2390. }
  2391. function tableDelRow(o) {
  2392. if (o.props.rows.length <= 1) return;
  2393. var t = tableCellTarget(o);
  2394. var rowH = Math.round(o.h / o.props.rows.length);
  2395. o.props.rows.splice(t.r, 1);
  2396. if (Array.isArray(o.props.cellFill)) o.props.cellFill.splice(t.r, 1);
  2397. if (Array.isArray(o.props.cellAnchor)) o.props.cellAnchor.splice(t.r, 1);
  2398. delete o.props.merges;
  2399. delete o.props.rowH;
  2400. o.h = Math.max(30, o.h - rowH);
  2401. lastCell = null;
  2402. commit();
  2403. }
  2404. function tableAddCol(o, after) {
  2405. var t = tableCellTarget(o);
  2406. o.props.rows.forEach(function (r) { r.splice(t.c + (after ? 1 : 0), 0, ""); });
  2407. (o.props.cellFill || []).concat(o.props.cellAnchor || []).forEach(function (r) { if (Array.isArray(r)) r.splice(t.c + (after ? 1 : 0), 0, ""); });
  2408. delete o.props.merges;
  2409. delete o.props.colW;
  2410. o.w = Math.min(940, o.w + Math.max(60, Math.round(o.w / Math.max(1, o.props.rows[0].length - 1))));
  2411. commit();
  2412. }
  2413. function tableDelCol(o) {
  2414. if ((o.props.rows[0] || []).length <= 1) return;
  2415. var t = tableCellTarget(o);
  2416. var colWpx = Math.round(o.w / o.props.rows[0].length);
  2417. o.props.rows.forEach(function (r) { r.splice(t.c, 1); });
  2418. (o.props.cellFill || []).concat(o.props.cellAnchor || []).forEach(function (r) { if (Array.isArray(r)) r.splice(t.c, 1); });
  2419. delete o.props.merges;
  2420. delete o.props.colW;
  2421. o.w = Math.max(60, o.w - colWpx);
  2422. lastCell = null;
  2423. commit();
  2424. }
  2425. /* ---------- table ops for the floating text-edit bar ----------
  2426. Rendered by OfficeTextEditBar as an extra divider-separated section
  2427. while a table object is being edited. */
  2428. function currentTableObj() {
  2429. if (editingId) {
  2430. var eo = objById(editingId);
  2431. if (eo && eo.type === "table") return eo;
  2432. }
  2433. var so = selObjs();
  2434. if (so.length === 1 && so[0].type === "table") return so[0];
  2435. return null;
  2436. }
  2437. function withTableObj(fn) {
  2438. var o = currentTableObj();
  2439. if (o) fn(o);
  2440. }
  2441. function slidesTableOps() {
  2442. return [
  2443. {
  2444. icon: "angle up", title: "Insert row above",
  2445. fn: function () { withTableObj(function (o) { tableAddRow(o, false); }); }
  2446. },
  2447. {
  2448. icon: "angle down", title: "Insert row below",
  2449. fn: function () { withTableObj(function (o) { tableAddRow(o, true); }); }
  2450. },
  2451. {
  2452. icon: "angle left", title: "Insert column left",
  2453. fn: function () { withTableObj(function (o) { tableAddCol(o, false); }); }
  2454. },
  2455. {
  2456. icon: "angle right", title: "Insert column right",
  2457. fn: function () { withTableObj(function (o) { tableAddCol(o, true); }); }
  2458. },
  2459. {
  2460. icon: "minus", title: "Delete row",
  2461. fn: function () { withTableObj(function (o) { tableDelRow(o); }); }
  2462. },
  2463. {
  2464. icon: "eraser", title: "Delete column",
  2465. fn: function () { withTableObj(function (o) { tableDelCol(o); }); }
  2466. },
  2467. {
  2468. icon: "trash alternate outline", title: "Delete table",
  2469. fn: function () {
  2470. withTableObj(function (o) {
  2471. endEdit(false);
  2472. setSel([o.id]);
  2473. deleteSelection();
  2474. });
  2475. }
  2476. },
  2477. {
  2478. icon: "heading", title: "Header row",
  2479. active: function () {
  2480. var o = currentTableObj();
  2481. return !!(o && o.props.headerRow);
  2482. },
  2483. fn: function () {
  2484. withTableObj(function (o) {
  2485. o.props.headerRow = !o.props.headerRow;
  2486. commit();
  2487. });
  2488. }
  2489. }
  2490. ];
  2491. }
  2492. /* ---------- table column / row resizing (edit mode) ---------- */
  2493. function ensureTableGrid(o) {
  2494. var rows = o.props.rows || [];
  2495. var cols = rows[0] ? rows[0].length : 1;
  2496. if (!Array.isArray(o.props.colW) || o.props.colW.length !== cols) {
  2497. o.props.colW = [];
  2498. for (var c = 0; c < cols; c++) o.props.colW.push(100 / cols);
  2499. }
  2500. if (!Array.isArray(o.props.rowH) || o.props.rowH.length !== rows.length) {
  2501. o.props.rowH = [];
  2502. for (var r = 0; r < rows.length; r++) o.props.rowH.push(100 / Math.max(1, rows.length));
  2503. }
  2504. }
  2505. /* Thin drag bars on every internal column/row boundary while a table
  2506. is in edit mode. Dragging adjusts colW / rowH percentages. */
  2507. function buildTableResizers(o, el) {
  2508. $(el).find(".sl-tbl-rz").remove();
  2509. if (!o || o.type !== "table") return;
  2510. ensureTableGrid(o);
  2511. var table = el.querySelector("table.sl-table");
  2512. if (!table || !table.rows.length) return;
  2513. var c, r;
  2514. var accX = 0;
  2515. for (c = 0; c < table.rows[0].cells.length - 1; c++) {
  2516. accX += table.rows[0].cells[c].offsetWidth;
  2517. var gv = document.createElement("div");
  2518. gv.className = "sl-tbl-rz sl-tbl-rz-col";
  2519. gv.setAttribute("data-idx", c);
  2520. gv.style.left = (accX - 3) + "px";
  2521. el.appendChild(gv);
  2522. }
  2523. var accY = 0;
  2524. for (r = 0; r < table.rows.length - 1; r++) {
  2525. accY += table.rows[r].offsetHeight;
  2526. var gh = document.createElement("div");
  2527. gh.className = "sl-tbl-rz sl-tbl-rz-row";
  2528. gh.setAttribute("data-idx", r);
  2529. gh.style.top = (accY - 3) + "px";
  2530. el.appendChild(gh);
  2531. }
  2532. }
  2533. /* Live-apply colW/rowH to the rendered table during a resize drag */
  2534. function applyTableGridLive(o) {
  2535. var el = objEl(o.id);
  2536. if (!el) return;
  2537. var table = el.querySelector("table.sl-table");
  2538. if (!table) return;
  2539. var colEls = table.querySelectorAll("colgroup col");
  2540. for (var c = 0; c < colEls.length; c++) {
  2541. if (o.props.colW[c] !== undefined) colEls[c].style.width = o.props.colW[c] + "%";
  2542. }
  2543. for (var r = 0; r < table.rows.length; r++) {
  2544. if (o.props.rowH[r] !== undefined) table.rows[r].style.height = o.props.rowH[r] + "%";
  2545. }
  2546. buildTableResizers(o, el);
  2547. }
  2548. /* ================= in-place text editing ================= */
  2549. function objEl(id) {
  2550. return layerEl.querySelector('.sl-obj[data-id="' + id + '"]');
  2551. }
  2552. function startEdit(id) {
  2553. var o = objById(id);
  2554. if (!o) return;
  2555. endCrop(true);
  2556. if (editingId && editingId !== id) endEdit(true);
  2557. var el = objEl(id);
  2558. if (!el) return;
  2559. if (o.type === "text" || o.type === "shape") {
  2560. var inner = el.querySelector(o.type === "text" ? ".sl-text-in" : ".sl-shape-text");
  2561. if (!inner) return;
  2562. editingId = id;
  2563. editingKind = o.type;
  2564. setSel([id]);
  2565. el.classList.add("sl-editing");
  2566. inner.setAttribute("contenteditable", "true");
  2567. inner.focus();
  2568. try { document.execCommand("selectAll", false, null); } catch (e) { }
  2569. el.addEventListener("focusout", onEditFocusOut);
  2570. showTextEditBar(o, el);
  2571. syncListButtonState();
  2572. } else if (o.type === "table") {
  2573. editingId = id;
  2574. editingKind = "table";
  2575. setSel([id]);
  2576. el.classList.add("sl-editing");
  2577. var cells = el.querySelectorAll("td");
  2578. for (var i = 0; i < cells.length; i++) cells[i].setAttribute("contenteditable", "true");
  2579. var t = tableCellTarget(o);
  2580. var focusCell = el.querySelector('td[data-r="' + t.r + '"][data-c="' + t.c + '"]');
  2581. if (focusCell) focusCell.focus();
  2582. el.addEventListener("focusout", onEditFocusOut);
  2583. buildTableResizers(o, el);
  2584. showTextEditBar(o, el);
  2585. } else if (o.type === "chart") {
  2586. chartDialog(o);
  2587. }
  2588. }
  2589. function showTextEditBar(o, el) {
  2590. if (!window.OfficeTextEditBar) return;
  2591. OfficeTextEditBar.show({
  2592. anchor: el,
  2593. fontSize: Number(o.props.fontSize) || (o.type === "table" ? 16 : 24),
  2594. onFontSize: function (px) {
  2595. o.props.fontSize = px;
  2596. $("#slFontSize").val(px);
  2597. commit();
  2598. },
  2599. tableOps: o.type === "table" ? slidesTableOps() : null
  2600. });
  2601. }
  2602. /* Bulleted / numbered lists only make sense inside a full text box
  2603. (not a shape's single-line caption). Auto-enters edit mode when a
  2604. lone text object is selected but not yet being edited. */
  2605. function toggleList(cmd) {
  2606. if (editingId && editingKind === "text") {
  2607. try { document.execCommand(cmd); } catch (e) { }
  2608. syncListButtonState();
  2609. return;
  2610. }
  2611. var so = selObjs();
  2612. if (so.length === 1 && so[0].type === "text") {
  2613. startEdit(so[0].id);
  2614. setTimeout(function () {
  2615. try { document.execCommand(cmd); } catch (e) { }
  2616. syncListButtonState();
  2617. }, 0);
  2618. return;
  2619. }
  2620. OfficeApp.setStatus("Double-click a text box to edit it, then toggle the list", "error");
  2621. }
  2622. function syncListButtonState() {
  2623. var ul = false, ol = false;
  2624. if (editingId && editingKind === "text") {
  2625. try { ul = document.queryCommandState("insertUnorderedList"); } catch (e) { }
  2626. try { ol = document.queryCommandState("insertOrderedList"); } catch (e) { }
  2627. }
  2628. $("#slBtnUL").toggleClass("active", !!ul);
  2629. $("#slBtnOL").toggleClass("active", !!ol);
  2630. }
  2631. function onEditFocusOut() {
  2632. var id = editingId;
  2633. setTimeout(function () {
  2634. if (!id || editingId !== id) return;
  2635. var el = objEl(id);
  2636. // focus moving into the floating format bar is still "editing",
  2637. // and so is the ribbon's font list or size box
  2638. if (window.OfficeTextEditBar && OfficeTextEditBar.contains(document.activeElement)) return;
  2639. if ($(document.activeElement).closest(".of-ribbon, .of-rb-popup").length) return;
  2640. // a dialog opened over the editor (e.g. the Insert-link prompt)
  2641. // must not tear down the edit - otherwise the box re-renders and
  2642. // the command applies to a dead selection
  2643. if ($(".of-dialog-overlay").length) return;
  2644. if (el && !el.contains(document.activeElement)) endEdit(true);
  2645. }, 0);
  2646. }
  2647. function endEdit(commitChanges) {
  2648. if (!editingId) return;
  2649. var id = editingId, kind = editingKind;
  2650. var o = objById(id);
  2651. var el = objEl(id);
  2652. editingId = null;
  2653. editingKind = null;
  2654. if (window.OfficeTextEditBar) OfficeTextEditBar.hide();
  2655. syncListButtonState();
  2656. var changed = false;
  2657. if (o && el) {
  2658. if (kind === "text") {
  2659. var inner = el.querySelector(".sl-text-in");
  2660. if (inner) {
  2661. var html = inner.innerHTML;
  2662. if (commitChanges && html !== o.props.html) { o.props.html = html; changed = true; }
  2663. }
  2664. } else if (kind === "shape") {
  2665. var st = el.querySelector(".sl-shape-text");
  2666. if (st) {
  2667. var txt = st.innerText.replace(/\n$/, "");
  2668. if (commitChanges && txt !== (o.props.text || "")) { o.props.text = txt; changed = true; }
  2669. }
  2670. } else if (kind === "table") {
  2671. var cells = el.querySelectorAll("td");
  2672. var rows = deep(o.props.rows || []);
  2673. for (var i = 0; i < cells.length; i++) {
  2674. var r = parseInt(cells[i].getAttribute("data-r"), 10);
  2675. var c = parseInt(cells[i].getAttribute("data-c"), 10);
  2676. if (rows[r] && rows[r][c] !== undefined) {
  2677. rows[r][c] = sanitizeCellHtml(cells[i].innerHTML);
  2678. }
  2679. }
  2680. if (commitChanges && JSON.stringify(rows) !== JSON.stringify(o.props.rows)) {
  2681. o.props.rows = rows;
  2682. changed = true;
  2683. }
  2684. }
  2685. }
  2686. if (changed) {
  2687. commit();
  2688. } else {
  2689. renderEditorSlide();
  2690. renderOverlay();
  2691. }
  2692. }
  2693. /* ================= live element update (during drag) ================= */
  2694. /* refreshObjEl redraws an object's contents in place, for a change to
  2695. its outline (an adjustment) rather than to its frame. The rest of
  2696. the slide is left alone, so a drag stays cheap. */
  2697. function refreshObjEl(o) {
  2698. var el = objEl(o.id);
  2699. if (!el || !el.parentNode) return;
  2700. var fresh = renderObjectEl(o, (parseInt(el.style.zIndex, 10) || 1) - 1);
  2701. fresh.className = el.className;
  2702. el.parentNode.replaceChild(fresh, el);
  2703. }
  2704. function updateObjEl(o) {
  2705. var el = objEl(o.id);
  2706. if (!el) return;
  2707. if (o.type === "line") {
  2708. positionLineEl(el, o);
  2709. el.innerHTML = lineSvg(o);
  2710. return;
  2711. }
  2712. el.style.left = o.x + "px";
  2713. el.style.top = o.y + "px";
  2714. el.style.width = Math.max(1, o.w) + "px";
  2715. el.style.height = Math.max(1, o.h) + "px";
  2716. el.style.transform = o.rot ? "rotate(" + o.rot + "deg)" : "";
  2717. }
  2718. /* ================= pointer interaction ================= */
  2719. function toSlideXY(e) {
  2720. var r = canvasEl.getBoundingClientRect();
  2721. var s = curScale() || 1;
  2722. return { x: (e.clientX - r.left) / s, y: (e.clientY - r.top) / s };
  2723. }
  2724. function showGuide(which, on) {
  2725. (which === "v" ? guideVEl : guideHEl).style.display = on ? "block" : "none";
  2726. }
  2727. function hideGuides() { showGuide("v", false); showGuide("h", false); }
  2728. function onCanvasPointerDown(e) {
  2729. if (e.button === 2) return; // context menu handled separately
  2730. OfficeApp.closeAllMenus();
  2731. var pt = toSlideXY(e);
  2732. // crop mode owns every press until it is closed
  2733. if (cropId) {
  2734. if (e.target.classList && e.target.classList.contains("sl-croph")) {
  2735. drag = {
  2736. mode: "crophandle", h: e.target.getAttribute("data-ch"),
  2737. start: pt, moved: false,
  2738. g: { x: cropRect.x, y: cropRect.y, w: cropRect.w, h: cropRect.h }
  2739. };
  2740. try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
  2741. e.preventDefault();
  2742. return;
  2743. }
  2744. if (e.target.closest && e.target.closest(".sl-crop-rect, .sl-crop-ghost")) {
  2745. drag = {
  2746. mode: "croppan", start: pt, moved: false,
  2747. g: { x: cropFull.x, y: cropFull.y }
  2748. };
  2749. try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
  2750. e.preventDefault();
  2751. return;
  2752. }
  2753. // a press anywhere else closes the tool; the next click then
  2754. // does whatever it was going to do, against a settled DOM
  2755. endCrop(true);
  2756. e.preventDefault();
  2757. return;
  2758. }
  2759. // table column/row resize bars (present in table edit mode)
  2760. if (e.target.classList && e.target.classList.contains("sl-tbl-rz")) {
  2761. var rzHost = e.target.closest(".sl-obj");
  2762. var rzObj = rzHost ? objById(rzHost.getAttribute("data-id")) : null;
  2763. if (rzObj) {
  2764. ensureTableGrid(rzObj);
  2765. var isCol = e.target.classList.contains("sl-tbl-rz-col");
  2766. drag = {
  2767. mode: isCol ? "tblcol" : "tblrow",
  2768. id: rzObj.id, start: pt, moved: false,
  2769. idx: parseInt(e.target.getAttribute("data-idx"), 10),
  2770. startArr: (isCol ? rzObj.props.colW : rzObj.props.rowH).slice()
  2771. };
  2772. try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
  2773. }
  2774. e.preventDefault();
  2775. return;
  2776. }
  2777. // when editing, clicks inside the edited object keep the caret working
  2778. if (editingId) {
  2779. var edEl = objEl(editingId);
  2780. if (edEl && edEl.contains(e.target)) {
  2781. var cell = e.target.closest ? e.target.closest("td") : null;
  2782. if (cell) {
  2783. lastCell = { r: parseInt(cell.getAttribute("data-r"), 10), c: parseInt(cell.getAttribute("data-c"), 10) };
  2784. }
  2785. return;
  2786. }
  2787. endEdit(true);
  2788. }
  2789. // armed shape: drag out its box
  2790. if (pendingDraw === "shape" && pendingShape) {
  2791. var sslide = curSlide();
  2792. var sobj = {
  2793. id: genId(), type: "shape", x: pt.x, y: pt.y, w: 0, h: 0, rot: 0,
  2794. z: sslide.objects.length + 1, props: shapeProps(pendingShape)
  2795. };
  2796. sslide.objects.push(sobj);
  2797. renderEditorSlide();
  2798. drag = { mode: "drawshape", id: sobj.id, start: pt, moved: false, kind: pendingShape };
  2799. try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
  2800. return;
  2801. }
  2802. // armed line/arrow drawing
  2803. if (pendingDraw) {
  2804. var th = themeOf();
  2805. var slide = curSlide();
  2806. var lo = {
  2807. id: genId(), type: "line", x: pt.x, y: pt.y, w: 0, h: 0, rot: 0,
  2808. z: slide.objects.length + 1,
  2809. props: {
  2810. stroke: /^#/.test(th.text) ? th.text : "#202124",
  2811. strokeW: 2, dash: false, arrowEnd: pendingDraw === "arrow"
  2812. }
  2813. };
  2814. slide.objects.push(lo);
  2815. renderEditorSlide();
  2816. drag = { mode: "draw", id: lo.id, start: pt, moved: false };
  2817. try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
  2818. return;
  2819. }
  2820. // resize / rotate / line endpoint handles
  2821. if (e.target.classList && e.target.classList.contains("sl-h")) {
  2822. var hname = e.target.getAttribute("data-h");
  2823. var so = selObjs();
  2824. if (so.length !== 1) return;
  2825. var o = so[0];
  2826. drag = {
  2827. mode: hname === "rot" ? "rotate" : (hname === "p1" || hname === "p2") ? "lineend"
  2828. : hname === "adj" ? "adjust" : "resize",
  2829. h: hname, id: o.id, start: pt, moved: false,
  2830. g: { x: o.x, y: o.y, w: o.w, h: o.h, rot: o.rot || 0 }
  2831. };
  2832. if (drag.mode === "adjust") {
  2833. // where the handle starts; an old callout is converted on the
  2834. // first real move (adoptAdjustments), which leaves the tip -
  2835. // and so this point - exactly where it is
  2836. var ahi = parseInt(e.target.getAttribute("data-i"), 10) || 0;
  2837. var ah = adjHandles(o)[ahi];
  2838. drag.at = ah ? ah.at : [0, 0];
  2839. drag.how = ah ? ah.how : "";
  2840. drag.i = ahi;
  2841. drag.kind = adjGeomKind(o);
  2842. }
  2843. // the pointer leaves the knob as soon as the object turns, so
  2844. // the rotate cursor has to be put on the canvas for the drag
  2845. if (drag.mode === "rotate") canvasEl.classList.add("sl-rotating");
  2846. try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
  2847. return;
  2848. }
  2849. var hitEl = e.target.closest ? e.target.closest(".sl-obj") : null;
  2850. if (hitEl && layerEl.contains(hitEl)) {
  2851. var id = hitEl.getAttribute("data-id");
  2852. var cell2 = e.target.closest ? e.target.closest("td") : null;
  2853. if (cell2) {
  2854. lastCell = { r: parseInt(cell2.getAttribute("data-r"), 10), c: parseInt(cell2.getAttribute("data-c"), 10) };
  2855. }
  2856. var pendingToggle = null, pendingCollapse = null;
  2857. var wasSelected = sel.length === 1 && sel[0] === id && !e.shiftKey;
  2858. if (sel.indexOf(id) < 0) {
  2859. // clicking a grouped object selects its whole group
  2860. setSel(expandGroups(e.shiftKey ? sel.concat([id]) : [id]));
  2861. } else if (e.shiftKey) {
  2862. pendingToggle = id;
  2863. } else if (sel.length > 1) {
  2864. pendingCollapse = id;
  2865. }
  2866. var geos = {};
  2867. selObjs().forEach(function (o2) {
  2868. geos[o2.id] = { x: o2.x, y: o2.y };
  2869. });
  2870. drag = {
  2871. mode: "move", start: pt, geos: geos, moved: false,
  2872. pendingToggle: pendingToggle, pendingCollapse: pendingCollapse,
  2873. clickedId: id, wasSelected: wasSelected
  2874. };
  2875. // keep the move cursor for the whole drag, wherever the pointer
  2876. // gets ahead of the object
  2877. canvasEl.classList.add("sl-moving");
  2878. try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
  2879. return;
  2880. }
  2881. // empty canvas: marquee select
  2882. if (!e.shiftKey) setSel([]);
  2883. drag = { mode: "marquee", start: pt, baseSel: sel.slice(), moved: false };
  2884. try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
  2885. }
  2886. function onCanvasPointerMove(e) {
  2887. if (!drag) return;
  2888. lastPointerEvt = e;
  2889. if (!rafPending) {
  2890. rafPending = true;
  2891. requestAnimationFrame(applyDragFrame);
  2892. }
  2893. }
  2894. function applyDragFrame() {
  2895. rafPending = false;
  2896. if (!drag || !lastPointerEvt) return;
  2897. var e = lastPointerEvt;
  2898. var pt = toSlideXY(e);
  2899. var dx = pt.x - drag.start.x;
  2900. var dy = pt.y - drag.start.y;
  2901. if (!drag.moved && Math.abs(dx) < 2 && Math.abs(dy) < 2 && drag.mode !== "rotate") return;
  2902. drag.moved = true;
  2903. var o, g;
  2904. switch (drag.mode) {
  2905. case "move": {
  2906. var ox = dx, oy = dy;
  2907. var ids = Object.keys(drag.geos);
  2908. if (!ids.length) return;
  2909. if (snapGrid) {
  2910. var pg = drag.geos[ids[0]];
  2911. ox = Math.round((pg.x + dx) / GRID) * GRID - pg.x;
  2912. oy = Math.round((pg.y + dy) / GRID) * GRID - pg.y;
  2913. }
  2914. // union bbox at the tentative offset, for center smart guides
  2915. var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  2916. ids.forEach(function (id) {
  2917. var oo = objById(id);
  2918. if (!oo) return;
  2919. var saved = { x: oo.x, y: oo.y };
  2920. oo.x = drag.geos[id].x + ox; oo.y = drag.geos[id].y + oy;
  2921. var bb = getBBox(oo);
  2922. oo.x = saved.x; oo.y = saved.y;
  2923. minX = Math.min(minX, bb.x); minY = Math.min(minY, bb.y);
  2924. maxX = Math.max(maxX, bb.x + bb.w); maxY = Math.max(maxY, bb.y + bb.h);
  2925. });
  2926. var cx = (minX + maxX) / 2, cy = (minY + maxY) / 2;
  2927. var gv = false, gh = false;
  2928. if (Math.abs(cx - SLIDE_W / 2) <= GUIDE_TOL) { ox += SLIDE_W / 2 - cx; gv = true; }
  2929. if (Math.abs(cy - SLIDE_H / 2) <= GUIDE_TOL) { oy += SLIDE_H / 2 - cy; gh = true; }
  2930. showGuide("v", gv);
  2931. showGuide("h", gh);
  2932. ids.forEach(function (id) {
  2933. var oo = objById(id);
  2934. if (!oo) return;
  2935. oo.x = drag.geos[id].x + ox;
  2936. oo.y = drag.geos[id].y + oy;
  2937. updateObjEl(oo);
  2938. });
  2939. renderOverlay();
  2940. break;
  2941. }
  2942. case "resize": {
  2943. o = objById(drag.id);
  2944. if (!o) return;
  2945. g = drag.g;
  2946. var rad = -(g.rot || 0) * Math.PI / 180;
  2947. var ldx = dx * Math.cos(rad) - dy * Math.sin(rad);
  2948. var ldy = dx * Math.sin(rad) + dy * Math.cos(rad);
  2949. var dirs = {
  2950. n: [0, -1], s: [0, 1], e: [1, 0], w: [-1, 0],
  2951. ne: [1, -1], nw: [-1, -1], se: [1, 1], sw: [-1, 1]
  2952. }[drag.h] || [0, 0];
  2953. var minSz = 16;
  2954. var dW = dirs[0] === 1 ? ldx : dirs[0] === -1 ? -ldx : 0;
  2955. var dH = dirs[1] === 1 ? ldy : dirs[1] === -1 ? -ldy : 0;
  2956. var newW = Math.max(minSz, g.w + dW);
  2957. var newH = Math.max(minSz, g.h + dH);
  2958. if (e.shiftKey && dirs[0] !== 0 && dirs[1] !== 0) {
  2959. var ar = g.w / Math.max(1, g.h);
  2960. if (Math.abs(newW - g.w) >= Math.abs(newH - g.h) * ar) newH = Math.max(minSz, newW / ar);
  2961. else newW = Math.max(minSz, newH * ar);
  2962. }
  2963. if (snapGrid) {
  2964. newW = Math.max(minSz, Math.round(newW / GRID) * GRID);
  2965. newH = Math.max(minSz, Math.round(newH / GRID) * GRID);
  2966. }
  2967. o.w = newW; o.h = newH;
  2968. o.x = dirs[0] === -1 ? g.x + (g.w - newW) : g.x;
  2969. o.y = dirs[1] === -1 ? g.y + (g.h - newH) : g.y;
  2970. updateObjEl(o);
  2971. renderOverlay();
  2972. break;
  2973. }
  2974. case "adjust": {
  2975. o = objById(drag.id);
  2976. if (!o) return;
  2977. if (drag.how === "tip") adoptAdjustments(o);
  2978. // the pointer's travel, turned into the shape's own box
  2979. var arad = -(drag.g.rot || 0) * Math.PI / 180;
  2980. var lx = drag.at[0] + dx * Math.cos(arad) - dy * Math.sin(arad);
  2981. var ly = drag.at[1] + dx * Math.sin(arad) + dy * Math.cos(arad);
  2982. if (drag.how === "radius") {
  2983. o.props.radius = Math.round(clamp(lx, 0, Math.min(o.w, o.h) / 2) * 100) / 100;
  2984. } else if (drag.how === "tip") {
  2985. var adj = {};
  2986. Object.keys(o.props.adj || {}).forEach(function (k) { adj[k] = o.props.adj[k]; });
  2987. adj.adj1 = Math.round((lx - o.w / 2) / Math.max(1, o.w) * 100000);
  2988. adj.adj2 = Math.round((ly - o.h / 2) / Math.max(1, o.h) * 100000);
  2989. o.props.adj = adj;
  2990. } else if (drag.how === "adj") {
  2991. o.props.adj = SlidesShapes.dragHandle(drag.kind, drag.i, o.w, o.h, lx, ly, o.props.adj);
  2992. }
  2993. // the outline itself changes, not just the frame
  2994. refreshObjEl(o);
  2995. renderOverlay();
  2996. break;
  2997. }
  2998. case "rotate": {
  2999. o = objById(drag.id);
  3000. if (!o) return;
  3001. g = drag.g;
  3002. var ccx = g.x + g.w / 2, ccy = g.y + g.h / 2;
  3003. var ang = Math.atan2(pt.y - ccy, pt.x - ccx) * 180 / Math.PI + 90;
  3004. if (e.shiftKey) ang = Math.round(ang / 15) * 15;
  3005. else ang = Math.round(ang);
  3006. ang = ((ang + 180) % 360 + 360) % 360 - 180;
  3007. o.rot = ang;
  3008. updateObjEl(o);
  3009. renderOverlay();
  3010. break;
  3011. }
  3012. case "crophandle": {
  3013. if (!cropRect || !cropFull) return;
  3014. g = drag.g;
  3015. var MINC = 8;
  3016. var nx = g.x, ny = g.y, nw = g.w, nh = g.h;
  3017. var name = drag.h;
  3018. if (name.indexOf("w") >= 0) {
  3019. nx = clamp(g.x + dx, cropFull.x, g.x + g.w - MINC);
  3020. nw = g.x + g.w - nx;
  3021. } else if (name.indexOf("e") >= 0) {
  3022. nw = clamp(g.w + dx, MINC, cropFull.x + cropFull.w - g.x);
  3023. }
  3024. if (name.indexOf("n") >= 0) {
  3025. ny = clamp(g.y + dy, cropFull.y, g.y + g.h - MINC);
  3026. nh = g.y + g.h - ny;
  3027. } else if (name.indexOf("s") >= 0) {
  3028. nh = clamp(g.h + dy, MINC, cropFull.y + cropFull.h - g.y);
  3029. }
  3030. cropRect = { x: nx, y: ny, w: nw, h: nh };
  3031. renderCropOverlay();
  3032. break;
  3033. }
  3034. case "croppan": {
  3035. if (!cropRect || !cropFull) return;
  3036. // the picture slides behind the window, so the window must
  3037. // stay inside the picture
  3038. cropFull.x = clamp(drag.g.x + dx,
  3039. cropRect.x + cropRect.w - cropFull.w, cropRect.x);
  3040. cropFull.y = clamp(drag.g.y + dy,
  3041. cropRect.y + cropRect.h - cropFull.h, cropRect.y);
  3042. renderCropOverlay();
  3043. break;
  3044. }
  3045. case "lineend": {
  3046. o = objById(drag.id);
  3047. if (!o) return;
  3048. g = drag.g;
  3049. // dragging an endpoint straightens an imported bent
  3050. // connector - the editor only draws two-point lines
  3051. if (o.props && o.props.points) delete o.props.points;
  3052. if (drag.h === "p2") {
  3053. var e2x = g.x + g.w + dx, e2y = g.y + g.h + dy;
  3054. if (snapGrid) { e2x = Math.round(e2x / GRID) * GRID; e2y = Math.round(e2y / GRID) * GRID; }
  3055. o.w = e2x - o.x; o.h = e2y - o.y;
  3056. } else {
  3057. var n1x = g.x + dx, n1y = g.y + dy;
  3058. if (snapGrid) { n1x = Math.round(n1x / GRID) * GRID; n1y = Math.round(n1y / GRID) * GRID; }
  3059. o.x = n1x; o.y = n1y;
  3060. o.w = g.x + g.w - n1x; o.h = g.y + g.h - n1y;
  3061. }
  3062. updateObjEl(o);
  3063. renderOverlay();
  3064. break;
  3065. }
  3066. case "drawshape": {
  3067. o = objById(drag.id);
  3068. if (!o) return;
  3069. var sx0 = drag.start.x, sy0 = drag.start.y, ex = pt.x, ey = pt.y;
  3070. if (snapGrid) {
  3071. ex = Math.round(ex / GRID) * GRID;
  3072. ey = Math.round(ey / GRID) * GRID;
  3073. }
  3074. var bw = Math.abs(ex - sx0), bh = Math.abs(ey - sy0);
  3075. if (e.shiftKey && bw > 0 && bh > 0) {
  3076. var ds = shapeDefaultSize(drag.kind);
  3077. var ar = ds[0] / ds[1];
  3078. if (bw / bh > ar) bw = bh * ar; else bh = bw / ar;
  3079. }
  3080. o.x = ex < sx0 ? sx0 - bw : sx0;
  3081. o.y = ey < sy0 ? sy0 - bh : sy0;
  3082. o.w = bw;
  3083. o.h = bh;
  3084. updateObjEl(o);
  3085. break;
  3086. }
  3087. case "draw": {
  3088. o = objById(drag.id);
  3089. if (!o) return;
  3090. var vx = pt.x - o.x, vy = pt.y - o.y;
  3091. if (e.shiftKey) {
  3092. var len = Math.sqrt(vx * vx + vy * vy);
  3093. var a45 = Math.round(Math.atan2(vy, vx) / (Math.PI / 4)) * (Math.PI / 4);
  3094. vx = len * Math.cos(a45);
  3095. vy = len * Math.sin(a45);
  3096. }
  3097. if (snapGrid) {
  3098. vx = Math.round((o.x + vx) / GRID) * GRID - o.x;
  3099. vy = Math.round((o.y + vy) / GRID) * GRID - o.y;
  3100. }
  3101. o.w = vx; o.h = vy;
  3102. updateObjEl(o);
  3103. break;
  3104. }
  3105. case "tblcol": {
  3106. o = objById(drag.id);
  3107. if (!o) return;
  3108. var ci = drag.idx;
  3109. var cTotal = drag.startArr[ci] + drag.startArr[ci + 1];
  3110. var cPct = clamp(drag.startArr[ci] + (dx / Math.max(1, o.w)) * 100, 5, cTotal - 5);
  3111. o.props.colW[ci] = cPct;
  3112. o.props.colW[ci + 1] = cTotal - cPct;
  3113. applyTableGridLive(o);
  3114. break;
  3115. }
  3116. case "tblrow": {
  3117. o = objById(drag.id);
  3118. if (!o) return;
  3119. var ri = drag.idx;
  3120. var rTotal = drag.startArr[ri] + drag.startArr[ri + 1];
  3121. var rPct = clamp(drag.startArr[ri] + (dy / Math.max(1, o.h)) * 100, 5, rTotal - 5);
  3122. o.props.rowH[ri] = rPct;
  3123. o.props.rowH[ri + 1] = rTotal - rPct;
  3124. applyTableGridLive(o);
  3125. break;
  3126. }
  3127. case "marquee": {
  3128. var rx = Math.min(drag.start.x, pt.x), ry = Math.min(drag.start.y, pt.y);
  3129. var rw = Math.abs(dx), rh = Math.abs(dy);
  3130. marqueeEl.style.display = "block";
  3131. marqueeEl.style.left = rx + "px";
  3132. marqueeEl.style.top = ry + "px";
  3133. marqueeEl.style.width = rw + "px";
  3134. marqueeEl.style.height = rh + "px";
  3135. var hits = curSlide().objects.filter(function (oo) {
  3136. var bb = getBBox(oo);
  3137. return bb.x < rx + rw && bb.x + bb.w > rx && bb.y < ry + rh && bb.y + bb.h > ry;
  3138. }).map(function (oo) { return oo.id; });
  3139. setSel(expandGroups(drag.baseSel.concat(hits)));
  3140. break;
  3141. }
  3142. }
  3143. }
  3144. function onCanvasPointerUp(e) {
  3145. if (!drag) return;
  3146. var d = drag;
  3147. drag = null;
  3148. lastPointerEvt = null;
  3149. canvasEl.classList.remove("sl-rotating");
  3150. canvasEl.classList.remove("sl-moving");
  3151. hideGuides();
  3152. try { canvasEl.releasePointerCapture(e.pointerId); } catch (err) { }
  3153. if (d.mode === "marquee") {
  3154. marqueeEl.style.display = "none";
  3155. return;
  3156. }
  3157. if (d.mode === "drawshape") {
  3158. var so2 = objById(d.id);
  3159. disarmDraw();
  3160. if (!so2) return;
  3161. if (so2.w < 6 && so2.h < 6) {
  3162. // a click: the shape's own size, centred where it was clicked
  3163. var dsz = shapeDefaultSize(d.kind);
  3164. so2.w = dsz[0];
  3165. so2.h = dsz[1];
  3166. so2.x = clamp(d.start.x - dsz[0] / 2, 0, SLIDE_W - dsz[0]);
  3167. so2.y = clamp(d.start.y - dsz[1] / 2, 0, SLIDE_H - dsz[1]);
  3168. } else {
  3169. so2.w = Math.max(6, so2.w);
  3170. so2.h = Math.max(6, so2.h);
  3171. }
  3172. setSel([so2.id]);
  3173. commit();
  3174. return;
  3175. }
  3176. if (d.mode === "draw") {
  3177. var o = objById(d.id);
  3178. disarmDraw();
  3179. if (o && Math.abs(o.w) < 4 && Math.abs(o.h) < 4) {
  3180. curSlide().objects = curSlide().objects.filter(function (oo) { return oo.id !== d.id; });
  3181. renderEditorSlide();
  3182. renderOverlay();
  3183. return;
  3184. }
  3185. if (o) {
  3186. setSel([o.id]);
  3187. commit();
  3188. }
  3189. return;
  3190. }
  3191. if (d.mode === "tblcol" || d.mode === "tblrow") {
  3192. if (d.moved) commit();
  3193. return;
  3194. }
  3195. if (d.mode === "crophandle" || d.mode === "croppan") {
  3196. // the crop tool stays open until it is applied or cancelled
  3197. return;
  3198. }
  3199. if (d.mode === "move" && !d.moved) {
  3200. if (d.pendingToggle) {
  3201. setSel(sel.filter(function (id) { return id !== d.pendingToggle; }));
  3202. } else if (d.pendingCollapse) {
  3203. setSel(expandGroups([d.pendingCollapse]));
  3204. } else {
  3205. // second click on an already-selected object enters text
  3206. // edit - and the first one does on an empty text box, whose
  3207. // prompt says "Click to add"
  3208. var co = objById(d.clickedId);
  3209. if (co && (d.wasSelected || (isBlankText(co) && sel.length === 1)) &&
  3210. (co.type === "text" || co.type === "shape" || co.type === "table")) {
  3211. startEdit(co.id);
  3212. }
  3213. }
  3214. return;
  3215. }
  3216. if (d.moved) commit();
  3217. }
  3218. function onCanvasDblClick(e) {
  3219. var el = e.target.closest ? e.target.closest(".sl-obj") : null;
  3220. if (!el || !layerEl.contains(el)) return;
  3221. var id = el.getAttribute("data-id");
  3222. var o = objById(id);
  3223. if (!o) return;
  3224. if (o.type === "text" || o.type === "shape" || o.type === "table") startEdit(id);
  3225. else if (o.type === "chart") chartDialog(o);
  3226. else if (o.type === "image") startCrop(id);
  3227. }
  3228. /* ================= context menus ================= */
  3229. function orderSub() {
  3230. return [
  3231. { label: "Bring to front", action: function () { reorderSelection("front"); } },
  3232. { label: "Bring forward", action: function () { reorderSelection("forward"); } },
  3233. { label: "Send backward", action: function () { reorderSelection("backward"); } },
  3234. { label: "Send to back", action: function () { reorderSelection("back"); } }
  3235. ];
  3236. }
  3237. function alignSub() {
  3238. return [
  3239. { label: "Align left", icon: "align left", action: function () { alignSelection("left"); } },
  3240. { label: "Align center", icon: "align center", action: function () { alignSelection("center"); } },
  3241. { label: "Align right", icon: "align right", action: function () { alignSelection("right"); } },
  3242. { sep: true },
  3243. { label: "Align top", action: function () { alignSelection("top"); } },
  3244. { label: "Align middle", action: function () { alignSelection("middle"); } },
  3245. { label: "Align bottom", action: function () { alignSelection("bottom"); } }
  3246. ];
  3247. }
  3248. function onCanvasContextMenu(e) {
  3249. e.preventDefault();
  3250. var el = e.target.closest ? e.target.closest(".sl-obj") : null;
  3251. var items;
  3252. if (el && layerEl.contains(el)) {
  3253. var id = el.getAttribute("data-id");
  3254. var o = objById(id);
  3255. if (!o) return;
  3256. var cell = e.target.closest ? e.target.closest("td") : null;
  3257. if (cell) {
  3258. lastCell = { r: parseInt(cell.getAttribute("data-r"), 10), c: parseInt(cell.getAttribute("data-c"), 10) };
  3259. }
  3260. if (sel.indexOf(id) < 0) setSel([id]);
  3261. items = [
  3262. { label: "Cut", icon: "cut", key: "Ctrl+X", action: cutSelection },
  3263. { label: "Copy", icon: "copy", key: "Ctrl+C", action: copySelection },
  3264. { label: "Duplicate", icon: "clone outline", key: "Ctrl+D", action: duplicateSelection },
  3265. { label: "Delete", icon: "trash alternate outline", key: "Del", action: deleteSelection },
  3266. { sep: true },
  3267. { label: "Order", icon: "bars", sub: orderSub() },
  3268. { label: "Align to slide", icon: "align center", sub: alignSub() },
  3269. { sep: true },
  3270. {
  3271. label: "Group", icon: "object group outline", key: "Ctrl+G",
  3272. enabled: function () { return sel.length >= 2; },
  3273. action: groupSelection
  3274. },
  3275. {
  3276. label: "Ungroup", key: "Ctrl+Shift+G",
  3277. enabled: selectionHasGroup,
  3278. action: ungroupSelection
  3279. },
  3280. {
  3281. label: "Animate (entrance)", icon: "magic",
  3282. sub: ANIMS.map(function (a) {
  3283. return {
  3284. label: a.label,
  3285. checked: function () { return (o.props.anim || "") === a.key; },
  3286. action: function () { setAnimation(a.key); }
  3287. };
  3288. })
  3289. },
  3290. { label: "Link...", icon: "linkify", action: linkDialog }
  3291. ];
  3292. if (o.type === "text" || o.type === "shape") {
  3293. items.push({ sep: true });
  3294. items.push({
  3295. label: "Edit text", icon: "i cursor",
  3296. action: function () { startEdit(o.id); }
  3297. });
  3298. }
  3299. if (o.type === "table") {
  3300. items.push({ sep: true });
  3301. items.push({
  3302. label: "Table", icon: "table", sub: [
  3303. { label: "Insert row above", action: function () { tableAddRow(o, false); } },
  3304. { label: "Insert row below", action: function () { tableAddRow(o, true); } },
  3305. { label: "Delete row", action: function () { tableDelRow(o); } },
  3306. { sep: true },
  3307. { label: "Insert column left", action: function () { tableAddCol(o, false); } },
  3308. { label: "Insert column right", action: function () { tableAddCol(o, true); } },
  3309. { label: "Delete column", action: function () { tableDelCol(o); } },
  3310. { sep: true },
  3311. {
  3312. label: "Header row",
  3313. checked: function () { return !!o.props.headerRow; },
  3314. action: function () { o.props.headerRow = !o.props.headerRow; commit(); }
  3315. }
  3316. ]
  3317. });
  3318. }
  3319. if (o.type === "chart") {
  3320. items.push({ sep: true });
  3321. items.push({
  3322. label: "Edit chart data...", icon: "chart bar",
  3323. action: function () { chartDialog(o); }
  3324. });
  3325. }
  3326. if (o.type === "image") {
  3327. items.push({ sep: true });
  3328. items.push({
  3329. label: "Crop image", icon: "crop",
  3330. action: function () { startCrop(o.id); }
  3331. });
  3332. items.push({
  3333. label: "Mask image", icon: "object ungroup outline",
  3334. sub: [{
  3335. label: "None (rectangle)",
  3336. checked: function () { return !o.props.mask; },
  3337. action: function () { setImageMask(o, ""); }
  3338. }, { sep: true }].concat(MASK_KINDS.filter(function (s) {
  3339. return s.kind !== "rect";
  3340. }).map(function (s) {
  3341. return {
  3342. label: s.label,
  3343. checked: function () { return o.props.mask === s.kind; },
  3344. action: function () { setImageMask(o, s.kind); }
  3345. };
  3346. }))
  3347. });
  3348. items.push({
  3349. label: "Reset image", icon: "history",
  3350. action: function () { resetImage(o); }
  3351. });
  3352. items.push({
  3353. label: "Image fit", icon: "image outline", sub: ["contain", "cover", "fill"].map(function (f) {
  3354. return {
  3355. label: f.charAt(0).toUpperCase() + f.substring(1),
  3356. checked: function () { return (o.props.fit || "contain") === f; },
  3357. action: function () { o.props.fit = f; commit(); }
  3358. };
  3359. })
  3360. });
  3361. }
  3362. if (o.type === "line" || o.type === "shape" || o.type === "image") {
  3363. items.push({ sep: true });
  3364. items.push({ label: "Line weight", icon: "bars", sub: weightItems() });
  3365. items.push({ label: "Line dash", icon: "ellipsis horizontal", sub: dashItems() });
  3366. if (o.type === "line") {
  3367. items.push({ label: "Line start", icon: "long arrow alternate left", sub: headItems(false) });
  3368. items.push({ label: "Line end", icon: "long arrow alternate right", sub: headItems(true) });
  3369. }
  3370. }
  3371. } else {
  3372. items = [
  3373. {
  3374. label: "Paste", icon: "paste", key: "Ctrl+V",
  3375. enabled: function () { return !!(clip && clip.length); },
  3376. action: function () { pasteClipboard(); }
  3377. },
  3378. { sep: true },
  3379. { label: "New slide", icon: "plus", action: function () { addSlideAfter(cur); } },
  3380. { label: "Background...", icon: "paint brush", action: function () { bgDialog(cur); } }
  3381. ];
  3382. }
  3383. OfficeApp.showContextMenu(e.clientX, e.clientY, items);
  3384. }
  3385. /* ================= keyboard ================= */
  3386. function isTypingTarget(t) {
  3387. return t && (t.isContentEditable ||
  3388. /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName || ""));
  3389. }
  3390. function presActive() {
  3391. return !!(window.SlidesPresent && SlidesPresent.isActive());
  3392. }
  3393. /* All editor keys go through the shared OfficeHotkeys registry
  3394. (common/hotkeys.js) - `when` gates replace the old hand-rolled
  3395. onKeyDown ordering, and descriptions feed the Ctrl+/ help dialog.
  3396. Ctrl+C/X/V are NOT consumed here: the native copy/cut/paste events
  3397. (initClipboardAndDnd) own them so the system clipboard stays in
  3398. sync with the object clipboard. */
  3399. function registerHotkeys() {
  3400. var HK = OfficeHotkeys;
  3401. var GS = "Slides", GO = "Objects", GT = "Text editing";
  3402. var notPresenting = function () { return !presActive(); };
  3403. var editorIdle = function () { return !presActive() && !editingId && !cropId; };
  3404. HK.register("F5", function () { endEdit(true); startPresent(cur); },
  3405. { id: "sl.present", description: "Start presentation", group: GS, allowInInput: true, when: notPresenting });
  3406. HK.register("Shift+F5", function () { endEdit(true); startPresent(0); },
  3407. { id: "sl.present0", description: "Present from beginning", group: GS, allowInInput: true, when: notPresenting });
  3408. HK.register("Ctrl+M", function () { addSlideAfter(cur); },
  3409. { id: "sl.newslide", description: "New slide", group: GS, allowInInput: true, when: notPresenting });
  3410. HK.register("PageUp", function () { selectSlide(cur - 1); },
  3411. { id: "sl.prevslide", description: "Previous slide", group: GS, when: editorIdle });
  3412. HK.register("PageDown", function () { selectSlide(cur + 1); },
  3413. { id: "sl.nextslide", description: "Next slide", group: GS, when: editorIdle });
  3414. HK.register("Ctrl+D", function () {
  3415. if (sel.length) duplicateSelection();
  3416. else duplicateSlide(cur);
  3417. }, { id: "sl.duplicate", description: "Duplicate object / slide", group: GO, when: editorIdle });
  3418. HK.register("Ctrl+A", function () { selectAllObjects(); },
  3419. { id: "sl.selectall", description: "Select all objects", group: GO, when: editorIdle });
  3420. HK.register("Ctrl+G", function () { groupSelection(); },
  3421. { id: "sl.group", description: "Group objects", group: GO, when: editorIdle });
  3422. HK.register("Ctrl+Shift+G", function () { ungroupSelection(); },
  3423. { id: "sl.ungroup", description: "Ungroup objects", group: GO, when: editorIdle });
  3424. HK.register("Tab", function () { cycleSelection(); },
  3425. { id: "sl.cycle", description: "Cycle through objects", group: GO, when: editorIdle });
  3426. HK.register("Delete", function () { deleteSelection(); },
  3427. { id: "sl.delete", description: "Delete selection", group: GO, when: function () { return editorIdle() && sel.length > 0; } });
  3428. HK.register("Backspace", function () { deleteSelection(); },
  3429. { id: "sl.delete2", when: function () { return editorIdle() && sel.length > 0; } });
  3430. /* Delete means the slide when the rail has the keyboard and the
  3431. canvas when it does not. Registered after the object one so it
  3432. gets first look (the registry is LIFO), though the two guards are
  3433. mutually exclusive anyway - selecting a slide clears the object
  3434. selection. */
  3435. HK.register("Delete", function () { deleteSlide(cur); },
  3436. { id: "sl.deleteslide", description: "Delete slide", group: GS,
  3437. when: function () { return editorIdle() && railFocused(); } });
  3438. HK.register("Backspace", function () { deleteSlide(cur); },
  3439. { id: "sl.deleteslide2", when: function () { return editorIdle() && railFocused(); } });
  3440. HK.register("Escape", function () {
  3441. if (cropId) { endCrop(false); return; }
  3442. if (editingId) { endEdit(true); return; }
  3443. if (pendingDraw) { disarmDraw(); return; }
  3444. if (sel.length) { setSel([]); return; }
  3445. return false;
  3446. }, { id: "sl.escape", allowInInput: true, when: notPresenting });
  3447. HK.register("Enter", function () {
  3448. if (!cropId) return false;
  3449. endCrop(true);
  3450. }, { id: "sl.cropapply", description: "Apply crop", group: GO,
  3451. when: function () { return !presActive() && !!cropId; } });
  3452. // arrows: nudge the selection (Shift = 10 px) or walk the deck
  3453. ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].forEach(function (k) {
  3454. var move = function (e) {
  3455. if (sel.length) {
  3456. var step = e.shiftKey ? 10 : 1;
  3457. nudgeSelection(
  3458. k === "ArrowLeft" ? -step : k === "ArrowRight" ? step : 0,
  3459. k === "ArrowUp" ? -step : k === "ArrowDown" ? step : 0);
  3460. } else if (e.shiftKey) {
  3461. return false;
  3462. } else if (k === "ArrowUp" || k === "ArrowLeft") {
  3463. selectSlide(cur - 1);
  3464. } else {
  3465. selectSlide(cur + 1);
  3466. }
  3467. };
  3468. var desc = k === "ArrowLeft" ? "Nudge selection / change slide (Shift = 10 px)" : "";
  3469. HK.register(k, move, { id: "sl.arrow." + k, description: desc, group: GO, when: editorIdle });
  3470. HK.register("Shift+" + k, move, { id: "sl.sarrow." + k, when: editorIdle });
  3471. });
  3472. // list toggles work while typing inside a text box
  3473. HK.register("Ctrl+Shift+8", function () { toggleList("insertUnorderedList"); },
  3474. { id: "sl.ul", description: "Bulleted list", group: GT, allowInInput: true, when: notPresenting });
  3475. HK.register("Ctrl+Shift+*", function () { toggleList("insertUnorderedList"); },
  3476. { id: "sl.ul2", allowInInput: true, when: notPresenting });
  3477. HK.register("Ctrl+Shift+7", function () { toggleList("insertOrderedList"); },
  3478. { id: "sl.ol", description: "Numbered list", group: GT, allowInInput: true, when: notPresenting });
  3479. HK.register("Ctrl+Shift+&", function () { toggleList("insertOrderedList"); },
  3480. { id: "sl.ol2", allowInInput: true, when: notPresenting });
  3481. // documentation-only entries: the native clipboard events do the
  3482. // actual work, the fall-through handler just lists them in help
  3483. HK.register("Ctrl+C", function () { return false; },
  3484. { id: "sl.copy.doc", description: "Copy objects / text", group: GO, allowInInput: true });
  3485. HK.register("Ctrl+X", function () { return false; },
  3486. { id: "sl.cut.doc", description: "Cut objects / text", group: GO, allowInInput: true });
  3487. HK.register("Ctrl+V", function () { return false; },
  3488. { id: "sl.paste.doc", description: "Paste", group: GO, allowInInput: true });
  3489. }
  3490. /* ================= system clipboard & drag-drop images ================= */
  3491. function fileToImage(file) {
  3492. // small images inline; big ones upload to the Office workdir
  3493. OfficeApp.blobToSrc(file, file.name || "pasted.png", function (src) {
  3494. placeImage(src);
  3495. }, function (msg) {
  3496. OfficeApp.toast(msg, "error");
  3497. });
  3498. }
  3499. /* Native paste event: screenshots / copied images become image objects,
  3500. otherwise fall back to the internal object clipboard, then plain text. */
  3501. function onPasteEvent(e) {
  3502. if (window.SlidesPresent && SlidesPresent.isActive()) return;
  3503. // typing somewhere (text edit, notes, dialogs): keep native paste
  3504. if (editingId || isTypingTarget(e.target) || $(".of-dialog-overlay").length) return;
  3505. var cd = e.clipboardData;
  3506. if (!cd) return;
  3507. // our own object clipboard (marker JSON written by Ctrl+C on
  3508. // objects) wins over everything - it IS the newest copy
  3509. var objs = parseObjectClipboardText(cd.getData("text/plain"));
  3510. if (objs) {
  3511. e.preventDefault();
  3512. clip = objs.map(deep);
  3513. pasteClipboard();
  3514. return;
  3515. }
  3516. var i, handled = false;
  3517. var items = cd.items || [];
  3518. for (i = 0; i < items.length; i++) {
  3519. if (items[i].kind === "file" && items[i].type.indexOf("image/") === 0) {
  3520. var f = items[i].getAsFile();
  3521. if (f) { fileToImage(f); handled = true; }
  3522. }
  3523. }
  3524. if (handled) { e.preventDefault(); return; }
  3525. // cross-app: a Docs picture / Sheets chart / cells arrive as text/html
  3526. var html = cd.getData("text/html");
  3527. if (html && pasteForeignHtml(html)) { e.preventDefault(); return; }
  3528. if (clip && clip.length) { e.preventDefault(); pasteClipboard(); return; }
  3529. var t = cd.getData("text/plain");
  3530. if (t && !OfficeClipboard.isMarker(t)) {
  3531. e.preventDefault();
  3532. var th = themeOf();
  3533. addObj("text", { html: esc(t).replace(/\n/g, "<br>"), fontSize: 24, color: th.text, align: "left" },
  3534. { x: 280, y: 220, w: 400, h: 90 });
  3535. }
  3536. }
  3537. /* Build slide objects from a shared text/html payload. Returns true when
  3538. something was inserted. */
  3539. function pasteForeignHtml(html) {
  3540. var p = OfficeClipboard.parse(html);
  3541. if (!p.hasContent) return false;
  3542. if (p.images.length) {
  3543. p.images.forEach(function (im) { placeImage(im.src); });
  3544. return true;
  3545. }
  3546. if (p.tables.length) {
  3547. objectFromHtmlTable(p.tables[0]);
  3548. return true;
  3549. }
  3550. // rich text -> a text box (sanitize to the inline subset we allow)
  3551. var frag = sanitizeCellHtml(p.html);
  3552. if (frag.replace(/<[^>]*>/g, "").replace(/\s/g, "") === "") return false;
  3553. var th = themeOf();
  3554. addObj("text", { html: frag, fontSize: 24, color: th.text, align: "left" },
  3555. { x: 240, y: 200, w: 480, h: 120 });
  3556. return true;
  3557. }
  3558. function objectFromHtmlTable(rows) {
  3559. var data = rows.map(function (tr) {
  3560. return tr.map(function (cell) { return sanitizeCellHtml(cell.innerHTML); });
  3561. });
  3562. var cols = data[0] ? data[0].length : 1;
  3563. var w = Math.min(880, Math.max(240, cols * 140));
  3564. var h = Math.min(480, Math.max(80, data.length * 34));
  3565. addObj("table", { rows: data, headerRow: false, fontSize: 16 },
  3566. { x: Math.round((SLIDE_W - w) / 2), y: Math.round((SLIDE_H - h) / 2), w: w, h: h });
  3567. }
  3568. /* Drop image files (or an image URL) onto the slide canvas. */
  3569. function onCanvasDrop(e) {
  3570. var dt = e.originalEvent ? e.originalEvent.dataTransfer : e.dataTransfer;
  3571. if (!dt) return;
  3572. if (dragSlideIdx >= 0) return; // thumbnail reordering, not a file drop
  3573. var i, handled = false;
  3574. var files = dt.files || [];
  3575. for (i = 0; i < files.length; i++) {
  3576. if ((files[i].type || "").indexOf("image/") === 0) {
  3577. fileToImage(files[i]);
  3578. handled = true;
  3579. }
  3580. }
  3581. if (!handled) {
  3582. var uri = dt.getData("text/uri-list") || dt.getData("text/plain");
  3583. if (uri && /^(https?:|data:image\/)/i.test(uri.trim())) {
  3584. placeImage(uri.trim().split("\n")[0]);
  3585. handled = true;
  3586. }
  3587. }
  3588. if (handled) e.preventDefault();
  3589. }
  3590. function initClipboardAndDnd() {
  3591. document.addEventListener("paste", onPasteEvent);
  3592. // Ctrl+C / Ctrl+X in object mode: put the objects on the system
  3593. // clipboard (synchronously - no permission prompt in a user
  3594. // gesture) so the next paste deterministically duplicates them
  3595. function onCopyCutEvent(e, isCut) {
  3596. if (presActive() || editingId || isTypingTarget(e.target) ||
  3597. $(".of-dialog-overlay").length) return;
  3598. if (!sel.length) return;
  3599. copySelection();
  3600. if (e.clipboardData) {
  3601. e.clipboardData.setData("text/plain", objectClipboardText());
  3602. var html = objectsToHtml(clip);
  3603. if (html) e.clipboardData.setData("text/html", html);
  3604. e.preventDefault();
  3605. }
  3606. if (isCut) deleteSelection();
  3607. }
  3608. document.addEventListener("copy", function (e) { onCopyCutEvent(e, false); });
  3609. document.addEventListener("cut", function (e) { onCopyCutEvent(e, true); });
  3610. var area = document.getElementById("slCanvasArea");
  3611. area.addEventListener("dragover", function (e) {
  3612. if (dragSlideIdx >= 0) return;
  3613. e.preventDefault();
  3614. e.dataTransfer.dropEffect = "copy";
  3615. });
  3616. area.addEventListener("drop", onCanvasDrop);
  3617. }
  3618. /* ================= toolbar ================= */
  3619. /* ================= ribbon ================= */
  3620. /* The ribbon (common/ribbon.js), as PowerPoint lays it out: Home,
  3621. Insert, Draw, Design, Transitions, Animations, Slide Show and View,
  3622. plus Shape Format and Picture Format, which only show while such an
  3623. object is selected. File stays a menu (office.js); the Slideshow
  3624. button sits in the title bar. */
  3625. var FONT_STEPS = [8, 9, 10, 10.5, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 40, 44, 48, 54, 60, 66, 72, 80, 88, 96];
  3626. function textObjs() {
  3627. return selObjs().filter(function (o) { return o.type === "text" || o.type === "shape" || o.type === "table"; });
  3628. }
  3629. function hasShapeSel() {
  3630. return selObjs().some(function (o) { return o.type === "shape" || o.type === "line" || o.type === "text"; });
  3631. }
  3632. function buildToolbar() {
  3633. var R = OfficeRibbon;
  3634. var B = R.button, D = R.dropdown;
  3635. /* ---------- Home ---------- */
  3636. var home = R.tab("home", "Home");
  3637. R.clipboardGroup(home, {
  3638. pasteMenu: function () {
  3639. return [
  3640. { label: "Keep source formatting", icon: "paste", key: "Ctrl+V", action: function () { OfficeApp.clipboard("paste"); } },
  3641. { label: "Keep text only", icon: "file alternate outline", action: pasteTextOnly }
  3642. ];
  3643. },
  3644. copyMenu: function () {
  3645. return [
  3646. { label: "Copy", icon: "copy", key: "Ctrl+C", action: function () { OfficeApp.clipboard("copy"); } },
  3647. {
  3648. label: "Duplicate", icon: "clone outline", key: "Ctrl+D",
  3649. enabled: function () { return sel.length > 0; }, action: duplicateSelection
  3650. }
  3651. ];
  3652. },
  3653. painter: {
  3654. id: "slPainter", title: "Format Painter - click, then click the object to format (double-click to keep it on)",
  3655. active: function () { return !!painter; },
  3656. start: startPainter
  3657. }
  3658. });
  3659. home.group({ id: "slides", label: "Slides", svg: "newSlide", priority: 3 })
  3660. .add(R.big({
  3661. svg: "newSlide", label: "New slide", key: "Ctrl+M",
  3662. onClick: function () { addSlideAfter(cur); },
  3663. menuTitle: "New slide with layout",
  3664. onOpen: function (el, r) {
  3665. OfficeApp.closeAllMenus();
  3666. showLayoutPicker(r.left, r.bottom + 4);
  3667. },
  3668. menu: true
  3669. }))
  3670. .stack([
  3671. B({ icon: "clone outline", label: "Duplicate", showLabel: true, key: "Ctrl+D", onClick: function () { duplicateSlide(cur); } }),
  3672. B({ icon: "trash alternate outline", label: "Delete", showLabel: true, onClick: function () { deleteSlide(cur); } }),
  3673. B({ svg: "background", label: "Background", showLabel: true, onClick: function () { bgDialog(cur); } })
  3674. ]);
  3675. var $font = $('<select class="of-tselect sl-fontsel" id="slFontFamily" title="Font"></select>');
  3676. OfficeFonts.MENU.forEach(function (f) {
  3677. $font.append($("<option></option>").attr("value", f).text(f).css("font-family", OfficeFonts.stack(f)));
  3678. });
  3679. OfficeFonts.fillPicker($font[0]);
  3680. $font.on("change", function () { applyFontFamily($font.val()); });
  3681. var $fs = $('<input type="number" class="of-tinput sl-num" id="slFontSize" min="6" max="400" step="1" title="Font size" value="24">');
  3682. $fs.on("change", function () {
  3683. var v = clamp(parseFloat($fs.val()) || 24, 6, 400);
  3684. $fs.val(v);
  3685. applyFontSizeAll(v);
  3686. });
  3687. var font = home.group({ id: "font", label: "Font", icon: "font", priority: 9 });
  3688. font.row([$font, $fs,
  3689. B({ svg: "growFont", title: "Increase font size", key: "Ctrl+]", onClick: function () { stepFontSize(1); } }),
  3690. B({ svg: "shrinkFont", title: "Decrease font size", key: "Ctrl+[", onClick: function () { stepFontSize(-1); } }),
  3691. B({ svg: "clearFormat", title: "Clear formatting", onClick: clearTextFormatting })
  3692. ]);
  3693. var fmt = function (icon, title, key, prop, cmd, id, svg) {
  3694. return B({
  3695. icon: svg ? null : icon, svg: svg, title: title, key: key, id: id,
  3696. onClick: function () {
  3697. if (prop) toggleTextProp(prop, cmd);
  3698. else inlineCommand(cmd);
  3699. }
  3700. });
  3701. };
  3702. font.row([
  3703. fmt("bold", "Bold", "Ctrl+B", "bold", "bold", "slBtnBold"),
  3704. fmt("italic", "Italic", "Ctrl+I", "italic", "italic", "slBtnItalic"),
  3705. fmt("underline", "Underline", "Ctrl+U", "underline", "underline", "slBtnUnderline"),
  3706. fmt("strikethrough", "Strikethrough", null, null, "strikeThrough", "slBtnStrike"),
  3707. fmt(null, "Superscript", null, null, "superscript", "slBtnSup", "superscript"),
  3708. fmt(null, "Subscript", null, null, "subscript", "slBtnSub", "subscript"),
  3709. "|",
  3710. R.colorButton({ id: "slTextColor", svg: "fontColor", title: "Font color", value: "#d0342c", onPick: applyTextColor })
  3711. ]);
  3712. var para = home.group({ id: "paragraph", label: "Paragraph", icon: "paragraph", priority: 7 });
  3713. para.row([
  3714. B({ icon: "list ul", title: "Bulleted list", key: "Ctrl+Shift+8", id: "slBtnUL", onClick: function () { toggleList("insertUnorderedList"); } }),
  3715. B({ icon: "list ol", title: "Numbered list", key: "Ctrl+Shift+7", id: "slBtnOL", onClick: function () { toggleList("insertOrderedList"); } }),
  3716. "|",
  3717. D({ svg: "lineSpacing", title: "Line spacing", menu: lineSpacingItems }),
  3718. D({ svg: "alignMiddle", title: "Align text vertically", menu: valignItems })
  3719. ]);
  3720. para.row(["left", "center", "right", "justify"].map(function (a) {
  3721. return B({
  3722. icon: "align " + a, title: a === "justify" ? "Justify" : "Align " + a, id: "slAlign_" + a,
  3723. onClick: function () { setTextAlign(a); }
  3724. });
  3725. }));
  3726. home.group({ id: "drawing", label: "Drawing", svg: "shapes", priority: 5 })
  3727. .add(R.big({ svg: "shapes", label: "Shapes", onOpen: openShapePicker, menu: true }))
  3728. .add(R.big({ svg: "arrange", label: "Arrange", menu: arrangeItems }))
  3729. .stack([
  3730. R.colorButton({ id: "slFillColor", svg: "fill", title: "Shape fill", value: "#e07b1f", allowNone: true, noneLabel: "No fill", onPick: applyFill }),
  3731. R.colorButton({ id: "slStrokeColor", svg: "outline", title: "Shape outline", value: "#333333", allowNone: true, noneLabel: "No outline", onPick: applyStroke }),
  3732. D({ svg: "lineWeight", title: "Outline weight and dash", menu: function () {
  3733. return [
  3734. { label: "Weight", icon: "minus", sub: weightItems },
  3735. { label: "Dash", icon: "ellipsis horizontal", sub: dashItems }
  3736. ];
  3737. } })
  3738. ]);
  3739. home.group({ id: "pane", label: "Format pane", svg: "formatPane", priority: 2 })
  3740. .add(R.big({
  3741. svg: "formatPane", label: "Format pane", title: "Picture format options",
  3742. enabled: function () { return !!selectedImage(); },
  3743. active: function () { return !!(window.SlidesImageTools && SlidesImageTools.panelOpen()); },
  3744. onClick: function () { if (window.SlidesImageTools && selectedImage()) SlidesImageTools.togglePanel(); OfficeRibbon.refresh(); }
  3745. }))
  3746. .add(R.big({ svg: "alignObjects", label: "Align", menu: alignSub, enabled: function () { return sel.length > 0; } }))
  3747. .add(R.big({ svg: "findReplace", label: "Find / Replace", key: "Ctrl+H", onClick: findReplaceDialog }));
  3748. /* ---------- Insert ---------- */
  3749. var ins = R.tab("insert", "Insert");
  3750. ins.group({ id: "slides", label: "Slides", svg: "newSlide" })
  3751. .add(R.big({
  3752. svg: "newSlide", label: "New slide", key: "Ctrl+M", onClick: function () { addSlideAfter(cur); },
  3753. onOpen: function (el, r) { OfficeApp.closeAllMenus(); showLayoutPicker(r.left, r.bottom + 4); }, menu: true
  3754. }));
  3755. ins.group({ id: "tables", label: "Tables", svg: "table" })
  3756. .add(R.big({ svg: "table", label: "Table", onClick: tableDialog }));
  3757. ins.group({ id: "images", label: "Images", svg: "picture" })
  3758. .add(R.big({ svg: "picture", label: "Pictures", menu: imageMenu }))
  3759. .add(R.big({ svg: "drawing", label: "Drawing", onClick: function () { drawingDialog(); } }));
  3760. ins.group({ id: "illustrations", label: "Illustrations", svg: "shapes" })
  3761. .add(R.big({ svg: "shapes", label: "Shapes", onOpen: openShapePicker, menu: true }))
  3762. .add(R.big({ svg: "chart", label: "Chart", onClick: function () { chartDialog(null); } }))
  3763. .stack([
  3764. B({ icon: "minus", label: "Line", showLabel: true, id: "slBtnLine", active: function () { return pendingDraw === "line"; }, onClick: function () { if (pendingDraw === "line") disarmDraw(); else armDraw("line"); } }),
  3765. B({ icon: "long arrow alternate right", label: "Arrow", showLabel: true, id: "slBtnArrow", active: function () { return pendingDraw === "arrow"; }, onClick: function () { if (pendingDraw === "arrow") disarmDraw(); else armDraw("arrow"); } })
  3766. ]);
  3767. ins.group({ id: "text", label: "Text", svg: "textBox" })
  3768. .add(R.big({ svg: "textBox", label: "Text box", onClick: insertText }))
  3769. .add(R.big({ svg: "link", label: "Link", enabled: function () { return sel.length === 1; }, onClick: linkDialog }));
  3770. ins.group({ id: "media", label: "Media", svg: "video" })
  3771. .add(R.big({ svg: "video", label: "Video", menu: function () { return mediaMenu("video"); } }))
  3772. .add(R.big({ svg: "audio", label: "Audio", menu: function () { return mediaMenu("audio"); } }));
  3773. /* ---------- Draw ---------- */
  3774. var draw = R.tab("draw", "Draw");
  3775. draw.group({ id: "tools", label: "Tools", svg: "pen" })
  3776. .add(R.big({ icon: "mouse pointer", label: "Select", active: function () { return !pendingDraw; }, onClick: function () { if (pendingDraw) disarmDraw(); OfficeRibbon.refresh(); } }))
  3777. .add(R.big({ icon: "minus", label: "Line", active: function () { return pendingDraw === "line"; }, onClick: function () { armDraw("line"); OfficeRibbon.refresh(); } }))
  3778. .add(R.big({ icon: "long arrow alternate right", label: "Arrow", active: function () { return pendingDraw === "arrow"; }, onClick: function () { armDraw("arrow"); OfficeRibbon.refresh(); } }))
  3779. .add(R.big({ svg: "shapes", label: "Shapes", onOpen: openShapePicker, menu: true }));
  3780. var pens = draw.group({ id: "pens", label: "Pens", svg: "pen" });
  3781. OfficeSketch.PENS.forEach(function (p) {
  3782. pens.add(R.big({
  3783. iconHtml: OfficeSketch.penIcon(p), label: p.label,
  3784. title: "Draw with the " + p.label.toLowerCase(),
  3785. onClick: function () { drawingDialog(p.id); }
  3786. }));
  3787. });
  3788. draw.group({ id: "canvas", label: "Canvas", svg: "drawing" })
  3789. .add(R.big({ svg: "drawing", label: "Drawing canvas", onClick: function () { drawingDialog(); } }));
  3790. /* ---------- Design ---------- */
  3791. var design = R.tab("design", "Design");
  3792. design.group({ id: "themes", label: "Themes", svg: "theme", priority: 5 })
  3793. .add(R.gallery({
  3794. id: "slThemes", cls: "sl-themes", tileW: 96, visible: 6, moreTitle: "All themes",
  3795. items: Object.keys(THEMES).map(function (k) {
  3796. var t = THEMES[k];
  3797. return {
  3798. key: k, label: t.label,
  3799. build: function ($t) {
  3800. var $p = $('<span class="sl-themeprev"></span>').css({ background: t.bg, color: t.text });
  3801. $p.append('<span class="sl-themeprev-aa">Aa</span>')
  3802. .append($('<span class="sl-themeprev-bar"></span>').css("background", t.accent));
  3803. $t.append($p).append($('<span class="sl-themeprev-name"></span>').text(t.label));
  3804. },
  3805. active: function () { return body.theme === k; },
  3806. onClick: function () { setTheme(k); }
  3807. };
  3808. }),
  3809. extra: [{ label: "Browse themes...", icon: "paint brush", action: themeDialog }]
  3810. }));
  3811. design.group({ id: "customize", label: "Customize", svg: "background" })
  3812. .add(R.big({ svg: "background", label: "Background", title: "Format the slide background", onClick: function () { bgDialog(cur); } }))
  3813. .add(R.big({ svg: "theme", label: "Browse themes", onClick: themeDialog }));
  3814. /* ---------- Transitions ---------- */
  3815. var tr = R.tab("transitions", "Transitions");
  3816. tr.group({ id: "transition", label: "Transition to this slide", svg: "transition", priority: 5 })
  3817. .add(R.gallery({
  3818. id: "slTransitions", cls: "sl-effects", tileW: 74, visible: 6,
  3819. items: TRANSITIONS.map(function (t) {
  3820. return {
  3821. key: t.key, label: t.label,
  3822. html: effectIcon("tr-" + t.key) + '<span class="sl-effect-name">' + esc(t.label) + "</span>",
  3823. active: function () { return (curSlide().transition || "none") === t.key; },
  3824. onClick: function () { curSlide().transition = t.key; commit(); }
  3825. };
  3826. })
  3827. }));
  3828. tr.group({ id: "timing", label: "Timing", svg: "transition" })
  3829. .add(R.big({
  3830. svg: "transition", label: "Apply to all",
  3831. onClick: function () {
  3832. var t = curSlide().transition || "none";
  3833. body.slides.forEach(function (s) { s.transition = t; });
  3834. commit();
  3835. OfficeApp.setStatus("Transition applied to every slide");
  3836. }
  3837. }))
  3838. .add(R.big({ svg: "present", label: "Preview", title: "Play this slide from here", onClick: function () { startPresent(cur, { showSkipped: true }); } }));
  3839. /* ---------- Animations ---------- */
  3840. var an = R.tab("animations", "Animations");
  3841. an.group({ id: "animation", label: "Animation", svg: "animation", priority: 5 })
  3842. .add(R.gallery({
  3843. id: "slAnims", cls: "sl-effects", tileW: 74, visible: 6,
  3844. items: ANIMS.map(function (a) {
  3845. return {
  3846. key: a.key, label: a.label,
  3847. html: effectIcon("an-" + (a.key || "none")) + '<span class="sl-effect-name">' + esc(a.label) + "</span>",
  3848. active: function () {
  3849. var so = selObjs();
  3850. return so.length > 0 && (so[0].props.anim || "") === a.key;
  3851. },
  3852. onClick: function () {
  3853. if (!sel.length) { OfficeApp.setStatus("Select an object to animate first", "info", 3000); return; }
  3854. setAnimation(a.key);
  3855. }
  3856. };
  3857. })
  3858. }));
  3859. an.group({ id: "interaction", label: "Interaction", svg: "link" })
  3860. .add(R.big({ svg: "link", label: "Click link", title: "Link the object to a slide or a web page", enabled: function () { return sel.length === 1; }, onClick: linkDialog }))
  3861. .add(R.big({ svg: "present", label: "Preview", onClick: function () { startPresent(cur, { showSkipped: true }); } }));
  3862. /* ---------- Slide Show ---------- */
  3863. var show = R.tab("slideshow", "Slide Show");
  3864. show.group({ id: "start", label: "Start Slide Show", svg: "present" })
  3865. .add(R.big({ svg: "fromStart", label: "From beginning", key: "Shift+F5", onClick: function () { startPresent(0); } }))
  3866. .add(R.big({ svg: "present", label: "From current slide", key: "F5", onClick: function () { startPresent(cur); } }))
  3867. .add(R.big({ svg: "presenter", label: "Presenter view", onClick: function () { startPresent(cur, { presenter: true }); } }));
  3868. show.group({ id: "setup", label: "Set Up", svg: "notes" })
  3869. .add(R.big({
  3870. svg: "skipSlide", label: "Skip slide", title: "Leave this slide out of the slide show",
  3871. active: function () { return !!(curSlide() && curSlide().hidden); },
  3872. onClick: function () { toggleSlideSkip(cur); }
  3873. }))
  3874. .add(R.big({ svg: "notes", label: "Speaker notes", active: notesShown, onClick: function () { toggleNotes(); OfficeRibbon.refresh(); } }));
  3875. /* ---------- View ---------- */
  3876. var view = R.tab("view", "View");
  3877. view.group({ id: "views", label: "Presentation Views", svg: "normalView" })
  3878. .add(R.big({ svg: "normalView", label: "Normal", active: function () { return !overview; }, onClick: function () { setOverview(false); } }))
  3879. .add(R.big({ svg: "overview", label: "Slide overview", key: "Ctrl+Alt+1", active: function () { return overview; }, onClick: function () { setOverview(true); } }));
  3880. view.group({ id: "show", label: "Show", svg: "notes" })
  3881. .add(R.big({ svg: "notes", label: "Notes", active: notesShown, onClick: function () { toggleNotes(); OfficeRibbon.refresh(); } }))
  3882. .add(R.big({ svg: "snap", label: "Snap to grid", active: function () { return snapGrid; }, onClick: toggleSnap }));
  3883. view.group({ id: "zoom", label: "Zoom", svg: "zoomIn" })
  3884. .add(R.big({ svg: "zoomOut", label: "Zoom out", key: "Ctrl+-", onClick: function () { OfficeApp.zoomOut(); } }))
  3885. .add(R.big({ svg: "zoom100", label: "Fit", title: "Fit the slide to the window", key: "Ctrl+0", onClick: function () { OfficeApp.setZoom(100); } }))
  3886. .add(R.big({ svg: "zoomIn", label: "Zoom in", key: "Ctrl+=", onClick: function () { OfficeApp.zoomIn(); } }));
  3887. view.group({ id: "appearance", label: "Appearance", svg: "darkTheme" })
  3888. .add(R.big({ svg: "darkTheme", label: "Dark theme", active: function () { return OfficeApp.isDark(); }, onClick: function () { OfficeApp.toggleTheme(); OfficeRibbon.refresh(); } }));
  3889. /* ---------- Shape Format (contextual) ---------- */
  3890. var sf = R.tab("shapeformat", "Shape Format", { contextual: true, when: function () { return !overview && strokedObjs().some(function (o) { return o.type !== "image"; }); } });
  3891. sf.group({ id: "styles", label: "Shape Styles", svg: "fill" }).stack([
  3892. R.colorButton({ id: "slFillColor2", svg: "fill", title: "Shape fill", value: "#e07b1f", allowNone: true, noneLabel: "No fill", onPick: applyFill }),
  3893. R.colorButton({ id: "slStrokeColor2", svg: "outline", title: "Shape outline", value: "#333333", allowNone: true, noneLabel: "No outline", onPick: applyStroke })
  3894. ]);
  3895. sf.group({ id: "lines", label: "Lines", svg: "lineWeight" })
  3896. .add(R.big({ svg: "lineWeight", label: "Weight", menu: weightItems }))
  3897. .add(R.big({ svg: "lineDash", label: "Dash", menu: dashItems }))
  3898. .add(R.big({ iconHtml: SlidesLines.toolIcon("start"), label: "Line start", visible: function () { return lineObjs().length > 0; }, menu: function () { return headItems(false); } }))
  3899. .add(R.big({ iconHtml: SlidesLines.toolIcon("end"), label: "Line end", visible: function () { return lineObjs().length > 0; }, menu: function () { return headItems(true); } }));
  3900. arrangeGroup(sf);
  3901. /* ---------- Picture Format (contextual) ---------- */
  3902. var pf = R.tab("pictureformat", "Picture Format", { contextual: true, when: function () { return !overview && !!selectedImage(); } });
  3903. pf.group({ id: "adjust", label: "Adjust", svg: "resetPicture" })
  3904. .add(R.big({
  3905. svg: "crop", label: "Crop", active: function () { return !!cropId; },
  3906. onClick: function () {
  3907. var io = selectedImage();
  3908. if (io) { if (cropId === io.id) endCrop(true); else startCrop(io.id); }
  3909. OfficeRibbon.refresh();
  3910. },
  3911. onOpen: function (el) { if (selectedImage() && window.SlidesImageTools) SlidesImageTools.showShapeMenu(el); },
  3912. menu: true, menuTitle: "Crop to shape"
  3913. }))
  3914. .add(R.big({ svg: "resetPicture", label: "Reset picture", onClick: function () { var io = selectedImage(); if (io) resetImage(io); } }))
  3915. .add(R.big({
  3916. svg: "formatPane", label: "Format pane",
  3917. active: function () { return !!(window.SlidesImageTools && SlidesImageTools.panelOpen()); },
  3918. onClick: function () { if (window.SlidesImageTools) SlidesImageTools.togglePanel(); OfficeRibbon.refresh(); }
  3919. }));
  3920. pf.group({ id: "border", label: "Picture Border", svg: "outline" })
  3921. .add(R.colorButton({ id: "slImgStroke", big: true, svg: "outline", label: "Border", title: "Picture border", value: "#333333", allowNone: true, noneLabel: "No border", onPick: applyPictureBorder }))
  3922. .add(R.big({ svg: "lineWeight", label: "Weight", menu: weightItems }))
  3923. .add(R.big({ svg: "lineDash", label: "Dash", menu: dashItems }));
  3924. arrangeGroup(pf);
  3925. /* ---------- the title bar: Slideshow ---------- */
  3926. var $present = $('<button type="button" class="sl-present-btn" title="Start the slide show (F5)">' +
  3927. '<i class="play icon"></i><span>Slideshow</span></button>');
  3928. var $presentMore = $('<button type="button" class="sl-present-more" title="More ways to present"><i class="caret down icon"></i></button>');
  3929. $present.on("click", function () { startPresent(cur); });
  3930. $presentMore.on("click", function (e) {
  3931. var r = e.currentTarget.getBoundingClientRect();
  3932. OfficeApp.showContextMenu(r.right - 240, r.bottom + 4, [
  3933. { label: "Present from current slide", icon: "play", key: "F5", action: function () { startPresent(cur); } },
  3934. { label: "Present from beginning", icon: "play circle outline", key: "Shift+F5", action: function () { startPresent(0); } },
  3935. { label: "Present with presenter view", icon: "desktop", action: function () { startPresent(cur, { presenter: true }); } }
  3936. ]);
  3937. });
  3938. OfficeApp.titleBarSlot().append($('<span class="sl-present-split"></span>').append($present).append($presentMore));
  3939. /* ---------- the status bar: Normal / Overview ---------- */
  3940. OfficeApp.addStatusItem("views",
  3941. '<span class="sl-viewbtns"><button type="button" class="sl-viewbtn" data-view="normal" title="Normal">' +
  3942. OfficeIcons.get("normalView") + '</button><button type="button" class="sl-viewbtn" data-view="overview" title="Slide overview (Ctrl+Alt+1)">' +
  3943. OfficeIcons.get("overview") + "</button></span>");
  3944. $(document).on("click", ".sl-viewbtn", function () { setOverview($(this).attr("data-view") === "overview"); });
  3945. syncViewButtons();
  3946. }
  3947. function arrangeGroup(tab) {
  3948. var R = OfficeRibbon;
  3949. tab.group({ id: "arrange", label: "Arrange", svg: "arrange" })
  3950. .add(R.big({ svg: "bringFront", label: "Bring forward", onClick: function () { reorderSelection("forward"); }, menu: orderSub }))
  3951. .add(R.big({ svg: "sendBack", label: "Send backward", onClick: function () { reorderSelection("backward"); }, menu: orderSub }))
  3952. .add(R.big({ svg: "alignObjects", label: "Align", menu: alignSub }))
  3953. .add(R.big({ svg: "group", label: "Group", menu: arrangeGroupItems }));
  3954. }
  3955. function arrangeGroupItems() {
  3956. return [
  3957. { label: "Group", icon: "object group outline", key: "Ctrl+G", enabled: function () { return sel.length >= 2; }, action: groupSelection },
  3958. { label: "Ungroup", key: "Ctrl+Shift+G", enabled: selectionHasGroup, action: ungroupSelection }
  3959. ];
  3960. }
  3961. function arrangeItems() {
  3962. var items = [{ label: "Order", icon: "bars", sub: orderSub }, { label: "Align", icon: "align center", sub: alignSub }, { sep: true }];
  3963. return items.concat(arrangeGroupItems()).concat([
  3964. { sep: true },
  3965. { label: "Duplicate", icon: "clone outline", key: "Ctrl+D", enabled: function () { return sel.length > 0; }, action: duplicateSelection },
  3966. { label: "Delete", icon: "trash alternate outline", key: "Del", enabled: function () { return sel.length > 0; }, action: deleteSelection }
  3967. ]);
  3968. }
  3969. function imageMenu() {
  3970. return [
  3971. storageSourceItem(imageFromStorage),
  3972. { label: "From this device...", icon: "upload", action: imageFromDevice },
  3973. { label: "From URL...", icon: "linkify", action: imageFromUrl }
  3974. ].filter(Boolean);
  3975. }
  3976. function mediaMenu(kind) {
  3977. return [
  3978. storageSourceItem(function () { mediaFromStorage(kind); }),
  3979. { label: "From this device...", icon: "upload", action: function () { mediaFromDevice(kind); } }
  3980. ].filter(Boolean);
  3981. }
  3982. function openShapePicker(el, r) {
  3983. OfficeApp.closeAllMenus();
  3984. showShapePicker(r.left, r.bottom + 4);
  3985. }
  3986. function notesShown() { return !$("#slNotes").hasClass("collapsed"); }
  3987. function toggleSnap() {
  3988. snapGrid = !snapGrid;
  3989. OfficeApp.setSetting("snapGrid", snapGrid);
  3990. OfficeRibbon.refresh();
  3991. }
  3992. // the small pictures on the Transitions and Animations galleries
  3993. function effectIcon(kind) {
  3994. var a = '<rect x="3" y="5" width="18" height="14" rx="1.5"/>';
  3995. var body = {
  3996. "tr-none": a,
  3997. "tr-fade": '<rect x="3" y="5" width="18" height="14" rx="1.5" opacity=".35"/><rect class="accs" x="6" y="8" width="12" height="8" rx="1"/>',
  3998. "tr-slide": '<rect x="2" y="5" width="12" height="14" rx="1.5" opacity=".4"/><rect class="accs" x="10" y="5" width="12" height="14" rx="1.5"/><path d="M13 12h5M16 10l2 2-2 2"/>',
  3999. "tr-zoom": '<rect x="2" y="4" width="20" height="16" rx="1.5" opacity=".35"/><rect class="accs" x="7" y="8" width="10" height="8" rx="1"/><path d="M4 6l3 2M20 6l-3 2M4 18l3-2M20 18l-3-2"/>',
  4000. "an-none": '<circle cx="12" cy="12" r="7" opacity=".5"/><path d="M7 17 17 7"/>',
  4001. "an-fade": '<path class="acc" d="M12 4l2 4.5 5 .6-3.7 3.4 1 4.9L12 15l-4.3 2.4 1-4.9L5 9.1l5-.6z" opacity=".55"/>',
  4002. "an-slide": '<path class="acc" d="M15 5l1.6 3.6 3.9.4-2.9 2.6.8 3.9-3.4-2-3.4 2 .8-3.9-2.9-2.6 3.9-.4z"/><path d="M2 9h5M3 13h5M2 17h6"/>',
  4003. "an-zoom": '<path class="acc" d="M12 7l1.2 2.7 2.9.3-2.2 2 .6 2.9-2.5-1.5-2.5 1.5.6-2.9-2.2-2 2.9-.3z"/><path d="M4 4l3 3M20 4l-3 3M4 20l3-3M20 20l-3-3"/>'
  4004. }[kind] || a;
  4005. return '<svg class="of-ic sl-effect-ic" viewBox="0 0 24 24" aria-hidden="true">' + body + "</svg>";
  4006. }
  4007. /* ---------- Home: text formatting ----------
  4008. With a text box being edited the commands act on the selected text
  4009. (execCommand, or the floating text bar's font code); otherwise on
  4010. every selected object as a whole. */
  4011. function applyFontFamily(name) {
  4012. if (editingId && window.OfficeTextEditBar && OfficeTextEditBar.hasTextSelection && OfficeTextEditBar.hasTextSelection()) {
  4013. OfficeTextEditBar.applyFontFamily(name);
  4014. syncEditingIntoModel();
  4015. OfficeApp.markDirty();
  4016. return;
  4017. }
  4018. applyToSel(function (o) {
  4019. if (o.type !== "text" && o.type !== "shape" && o.type !== "table") return false;
  4020. o.props.fontFamily = name;
  4021. return true;
  4022. });
  4023. }
  4024. function applyFontSizeAll(v) {
  4025. if (editingId && window.OfficeTextEditBar && OfficeTextEditBar.hasTextSelection && OfficeTextEditBar.hasTextSelection()) {
  4026. OfficeTextEditBar.applyFontSizePx(v);
  4027. syncEditingIntoModel();
  4028. OfficeApp.markDirty();
  4029. return;
  4030. }
  4031. applyToSel(function (o) {
  4032. if (o.type === "text" || o.type === "shape" || o.type === "table") {
  4033. o.props.fontSize = v;
  4034. return true;
  4035. }
  4036. return false;
  4037. });
  4038. }
  4039. function stepFontSize(dir) {
  4040. var so = textObjs();
  4041. if (!so.length) return;
  4042. var curSize = Number(so[0].props.fontSize) || (so[0].type === "table" ? 16 : 24);
  4043. var next = curSize;
  4044. var i;
  4045. if (dir > 0) {
  4046. next = curSize + 8;
  4047. for (i = 0; i < FONT_STEPS.length; i++) if (FONT_STEPS[i] > curSize) { next = FONT_STEPS[i]; break; }
  4048. } else {
  4049. next = Math.max(6, curSize - 1);
  4050. for (i = FONT_STEPS.length - 1; i >= 0; i--) if (FONT_STEPS[i] < curSize) { next = FONT_STEPS[i]; break; }
  4051. }
  4052. // editing: the selected text grows; otherwise the whole object
  4053. if (editingId) { applyFontSizeAll(next); if (!OfficeTextEditBar.hasTextSelection()) return; }
  4054. applyToSel(function (o) {
  4055. if (o.type !== "text" && o.type !== "shape" && o.type !== "table") return false;
  4056. var s = Number(o.props.fontSize) || (o.type === "table" ? 16 : 24);
  4057. o.props.fontSize = dir > 0 ? Math.max(next, s) : Math.min(next, s);
  4058. if (s === curSize) o.props.fontSize = next;
  4059. return true;
  4060. });
  4061. $("#slFontSize").val(next);
  4062. }
  4063. function toggleTextProp(prop, cmd) {
  4064. if (editingId) {
  4065. try { document.execCommand(cmd); } catch (e) { }
  4066. return;
  4067. }
  4068. applyToSel(function (o) {
  4069. if (o.type === "text" || o.type === "shape") {
  4070. o.props[prop] = !o.props[prop];
  4071. return true;
  4072. }
  4073. return false;
  4074. });
  4075. }
  4076. /* strike, superscript and subscript live on the text runs: on a whole
  4077. text box they are applied as an edit over all of its text */
  4078. function inlineCommand(cmd) {
  4079. if (editingId) {
  4080. try { document.execCommand(cmd); } catch (e) { }
  4081. return;
  4082. }
  4083. var ids = selObjs().filter(function (o) { return o.type === "text"; }).map(function (o) { return o.id; });
  4084. if (!ids.length) {
  4085. OfficeApp.setStatus("Select a text box, or some text in one", "info", 3000);
  4086. return;
  4087. }
  4088. var keep = sel.slice();
  4089. ids.forEach(function (id) {
  4090. startEdit(id);
  4091. try { document.execCommand(cmd); } catch (e) { }
  4092. endEdit(true);
  4093. });
  4094. setSel(keep);
  4095. }
  4096. function clearTextFormatting() {
  4097. if (editingId) {
  4098. try { document.execCommand("removeFormat"); } catch (e) { }
  4099. return;
  4100. }
  4101. var th = themeOf();
  4102. applyToSel(function (o) {
  4103. if (o.type !== "text" && o.type !== "shape") return false;
  4104. delete o.props.bold;
  4105. delete o.props.italic;
  4106. delete o.props.underline;
  4107. delete o.props.fontFamily;
  4108. if (o.type === "text") {
  4109. o.props.color = th.text;
  4110. if (o.props.html) o.props.html = stripRunFormatting(o.props.html);
  4111. } else {
  4112. delete o.props.textColor;
  4113. }
  4114. return true;
  4115. });
  4116. }
  4117. // drop the run-level styling of stored text, keeping the paragraphs,
  4118. // lists, alignment and links
  4119. function stripRunFormatting(html) {
  4120. var d = document.createElement("div");
  4121. d.innerHTML = html;
  4122. var inl = d.querySelectorAll("b, strong, i, em, u, s, strike, del, sup, sub, font");
  4123. for (var i = inl.length - 1; i >= 0; i--) {
  4124. var el = inl[i];
  4125. while (el.firstChild) el.parentNode.insertBefore(el.firstChild, el);
  4126. el.parentNode.removeChild(el);
  4127. }
  4128. var spans = d.querySelectorAll("span[style]");
  4129. for (i = 0; i < spans.length; i++) {
  4130. ["font-family", "font-size", "font-weight", "font-style", "color", "background-color",
  4131. "text-decoration", "text-decoration-line", "vertical-align"].forEach(function (k) {
  4132. spans[i].style.removeProperty(k);
  4133. });
  4134. if (!spans[i].getAttribute("style")) spans[i].removeAttribute("style");
  4135. }
  4136. return d.innerHTML;
  4137. }
  4138. function applyTextColor(v) {
  4139. if (!v) return;
  4140. if (editingId) {
  4141. try { document.execCommand("foreColor", false, v); } catch (e) { }
  4142. return;
  4143. }
  4144. applyToSel(function (o) {
  4145. if (o.type === "text" || o.type === "table") { o.props.color = v; return true; }
  4146. if (o.type === "shape") { o.props.textColor = v; return true; }
  4147. return false;
  4148. });
  4149. }
  4150. function setTextAlign(a) {
  4151. applyToSel(function (o) {
  4152. if (o.type === "text" || o.type === "shape") {
  4153. o.props.align = a;
  4154. // the paragraphs of rich text state their own alignment
  4155. if (o.props.html) {
  4156. var d = document.createElement("div");
  4157. d.innerHTML = o.props.html;
  4158. var blocks = d.querySelectorAll("div, p, li");
  4159. for (var i = 0; i < blocks.length; i++) blocks[i].style.removeProperty("text-align");
  4160. o.props.html = d.innerHTML;
  4161. }
  4162. return true;
  4163. }
  4164. return false;
  4165. });
  4166. }
  4167. var LINE_SPACINGS = [1, 1.15, 1.3, 1.5, 2, 2.5];
  4168. function lineSpacingItems() {
  4169. var so = textObjs();
  4170. var cur0 = so.length ? (Number(so[0].props.lineHeight) || 0) : 0;
  4171. return LINE_SPACINGS.map(function (v) {
  4172. return {
  4173. label: String(v), checked: Math.abs(cur0 - v) < 0.01,
  4174. action: function () {
  4175. applyToSel(function (o) {
  4176. if (o.type !== "text" && o.type !== "shape") return false;
  4177. o.props.lineHeight = v;
  4178. return true;
  4179. });
  4180. }
  4181. };
  4182. });
  4183. }
  4184. function valignItems() {
  4185. var so = textObjs();
  4186. var curV = so.length ? (so[0].props.valign || "top") : "";
  4187. return [["top", "Top", "alignTop"], ["middle", "Middle", "alignMiddle"], ["bottom", "Bottom", "alignBottom"]].map(function (v) {
  4188. return {
  4189. label: v[1], checked: curV === v[0],
  4190. action: function () {
  4191. applyToSel(function (o) {
  4192. if (o.type !== "text" && o.type !== "shape") return false;
  4193. o.props.valign = v[0];
  4194. return true;
  4195. });
  4196. }
  4197. };
  4198. });
  4199. }
  4200. /* ---------- Home: drawing colours ---------- */
  4201. function applyFill(v) {
  4202. applyToSel(function (o) {
  4203. if (o.type !== "shape") return false;
  4204. o.props.fill = v || "none";
  4205. return true;
  4206. });
  4207. OfficeRibbon.setColor("#slFillColor", v);
  4208. OfficeRibbon.setColor("#slFillColor2", v);
  4209. }
  4210. function applyStroke(v) {
  4211. applyToSel(function (o) {
  4212. if (o.type === "shape" || o.type === "line") { o.props.stroke = v || "none"; return true; }
  4213. return false;
  4214. });
  4215. OfficeRibbon.setColor("#slStrokeColor", v);
  4216. OfficeRibbon.setColor("#slStrokeColor2", v);
  4217. }
  4218. function applyPictureBorder(v) {
  4219. applyToSel(function (o) {
  4220. if (o.type !== "image") return false;
  4221. o.props.stroke = v || "none";
  4222. if (v && !(Number(o.props.strokeW) > 0)) o.props.strokeW = 2;
  4223. if (!v) o.props.strokeW = 0;
  4224. return true;
  4225. });
  4226. }
  4227. /* ---------- Home: format painter ----------
  4228. Copies the look of the selected object - its text style, fill and
  4229. outline - onto the next object clicked. Double-click keeps it on. */
  4230. var PAINT_KEYS = {
  4231. text: ["fontSize", "color", "bold", "italic", "underline", "fontFamily", "align", "lineHeight", "valign"],
  4232. shape: ["fill", "stroke", "strokeW", "dashStyle", "dash", "textColor", "fontSize", "bold", "italic", "underline", "fontFamily", "align", "valign"],
  4233. line: ["stroke", "strokeW", "dashStyle", "dash", "startHead", "endHead", "arrowEnd", "arrowStart"],
  4234. image: ["stroke", "strokeW", "radius", "opacity", "recolor", "bright", "contrast"],
  4235. table: ["fontSize", "color", "fontFamily"]
  4236. };
  4237. var painter = null;
  4238. function startPainter(sticky) {
  4239. if (painter && !sticky) { stopPainter(); return; }
  4240. var so = selObjs();
  4241. if (so.length !== 1) {
  4242. OfficeApp.setStatus("Select the object whose format to copy", "info", 3000);
  4243. return;
  4244. }
  4245. var src = so[0];
  4246. var props = {};
  4247. (PAINT_KEYS[src.type] || []).forEach(function (k) { if (src.props[k] !== undefined) props[k] = deep(src.props[k]); });
  4248. painter = { fromId: src.id, type: src.type, props: props, sticky: !!sticky };
  4249. canvasEl.classList.add("sl-painting");
  4250. OfficeApp.setStatus(sticky ? "Format painter on - click objects to format, Esc to stop" :
  4251. "Click the object to format", "info", 4000);
  4252. OfficeRibbon.refresh();
  4253. }
  4254. function stopPainter() {
  4255. painter = null;
  4256. if (canvasEl) canvasEl.classList.remove("sl-painting");
  4257. OfficeRibbon.refresh();
  4258. }
  4259. function applyPainterToSel() {
  4260. if (!painter) return;
  4261. var targets = selObjs().filter(function (o) { return o.id !== painter.fromId; });
  4262. if (!targets.length) return;
  4263. var p = painter;
  4264. targets.forEach(function (o) {
  4265. (PAINT_KEYS[o.type] || []).forEach(function (k) {
  4266. // text style crosses between text boxes and shape labels
  4267. var srcKey = k;
  4268. if (o.type === "shape" && k === "textColor" && p.type === "text") srcKey = "color";
  4269. if (o.type === "text" && k === "color" && p.type === "shape") srcKey = "textColor";
  4270. if (p.props[srcKey] !== undefined) o.props[k] = deep(p.props[srcKey]);
  4271. });
  4272. });
  4273. commit();
  4274. if (!p.sticky) stopPainter();
  4275. }
  4276. /* ---------- Insert / Draw: drawings ---------- */
  4277. function drawingDialog(penId) {
  4278. endEdit(true);
  4279. OfficeSketch.open({
  4280. title: "Drawing", pen: penId, aspect: SLIDE_H / SLIDE_W,
  4281. onInsert: function (blob, w, h) {
  4282. OfficeApp.blobToSrc(blob, "drawing.png", function (src) {
  4283. // drawn on a slide-shaped canvas: keep its place and size
  4284. // relative to the slide it was drawn for
  4285. var sc = Math.min(1, (SLIDE_W - 40) / w, (SLIDE_H - 40) / h);
  4286. var pw = Math.max(8, Math.round(w * sc)), ph = Math.max(8, Math.round(h * sc));
  4287. addObj("image", { src: src, fit: "contain" },
  4288. { x: Math.round((SLIDE_W - pw) / 2), y: Math.round((SLIDE_H - ph) / 2), w: pw, h: ph });
  4289. }, function (msg) { OfficeApp.toast(msg, "error"); });
  4290. }
  4291. });
  4292. }
  4293. /* ---------- Home: find and replace ----------
  4294. Searches the text of every text box, shape label and table cell, in
  4295. slide order from the current slide, and replaces in the text nodes
  4296. only, so formatting runs stay as they are. */
  4297. function textHolders(o) {
  4298. // [{get, set}] for each piece of HTML the object carries
  4299. var out = [];
  4300. if (o.type === "text") {
  4301. out.push({ get: function () { return o.props.html || ""; }, set: function (h) { o.props.html = h; } });
  4302. } else if (o.type === "shape") {
  4303. if (o.props.html) out.push({ get: function () { return o.props.html; }, set: function (h) { o.props.html = h; } });
  4304. else out.push({ get: function () { return esc(o.props.text || ""); }, set: function (h) {
  4305. var d = document.createElement("div");
  4306. d.innerHTML = h;
  4307. o.props.text = d.textContent;
  4308. } });
  4309. } else if (o.type === "table") {
  4310. (o.props.rows || []).forEach(function (row, r) {
  4311. row.forEach(function (cell, c) {
  4312. out.push({ get: function () { return o.props.rows[r][c] || ""; }, set: function (h) { o.props.rows[r][c] = h; } });
  4313. });
  4314. });
  4315. }
  4316. return out;
  4317. }
  4318. function plainOf(html) {
  4319. var d = document.createElement("div");
  4320. d.innerHTML = html;
  4321. return d.textContent || "";
  4322. }
  4323. function replaceInHtml(html, needle, repl, all, matchCase) {
  4324. var d = document.createElement("div");
  4325. d.innerHTML = html;
  4326. var count = 0;
  4327. var flags = matchCase ? "g" : "gi";
  4328. var rx = new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), flags);
  4329. var walker = document.createTreeWalker(d, NodeFilter.SHOW_TEXT, null);
  4330. var nodes = [];
  4331. while (walker.nextNode()) nodes.push(walker.currentNode);
  4332. for (var i = 0; i < nodes.length; i++) {
  4333. var t = nodes[i].nodeValue;
  4334. var changed = t.replace(rx, function (m) {
  4335. if (!all && count > 0) return m;
  4336. count++;
  4337. return repl;
  4338. });
  4339. if (changed !== t) nodes[i].nodeValue = changed;
  4340. if (!all && count > 0) break;
  4341. }
  4342. return { html: d.innerHTML, count: count };
  4343. }
  4344. var findPos = { s: 0, o: -1 };
  4345. function findReplaceDialog() {
  4346. endEdit(true);
  4347. var $b = $('<div class="sl-findrep"></div>');
  4348. $b.append("<label>Find what</label>");
  4349. var $f = $('<input type="text" class="fr-find">');
  4350. $b.append($f);
  4351. $b.append("<label>Replace with</label>");
  4352. var $r = $('<input type="text" class="fr-repl">');
  4353. $b.append($r);
  4354. var $mc = $('<label class="ps-check"><input type="checkbox" class="fr-case"> Match case</label>');
  4355. $b.append($mc);
  4356. var $msg = $('<div class="of-dim fr-msg">&nbsp;</div>');
  4357. $b.append($msg);
  4358. var matches = function (o, needle, mc) {
  4359. return textHolders(o).some(function (h) {
  4360. var t = plainOf(h.get());
  4361. return mc ? t.indexOf(needle) >= 0 : t.toLowerCase().indexOf(needle.toLowerCase()) >= 0;
  4362. });
  4363. };
  4364. var findNext = function () {
  4365. var needle = $f.val();
  4366. if (!needle) return null;
  4367. var mc = $b.find(".fr-case").prop("checked");
  4368. var n = body.slides.length;
  4369. var startS = findPos.s < n ? findPos.s : cur;
  4370. for (var step = 0; step <= n; step++) {
  4371. var si = (startS + step) % n;
  4372. var objs = body.slides[si].objects;
  4373. var from = (step === 0) ? findPos.o + 1 : 0;
  4374. for (var oi = from; oi < objs.length; oi++) {
  4375. if (matches(objs[oi], needle, mc)) {
  4376. findPos = { s: si, o: oi };
  4377. if (si !== cur) selectSlide(si);
  4378. setSel([objs[oi].id]);
  4379. $msg.text("Found on slide " + (si + 1));
  4380. return objs[oi];
  4381. }
  4382. }
  4383. }
  4384. findPos = { s: cur, o: -1 };
  4385. $msg.text("No matches");
  4386. return null;
  4387. };
  4388. var replaceIn = function (o, all) {
  4389. var needle = $f.val(), mc = $b.find(".fr-case").prop("checked");
  4390. var total = 0;
  4391. textHolders(o).forEach(function (h) {
  4392. if (!all && total > 0) return;
  4393. var res = replaceInHtml(h.get(), needle, $r.val(), all, mc);
  4394. if (res.count) { h.set(res.html); total += res.count; }
  4395. });
  4396. return total;
  4397. };
  4398. findPos = { s: cur, o: -1 };
  4399. OfficeApp.dialog({
  4400. title: "Find and replace",
  4401. body: $b,
  4402. buttons: [
  4403. { label: "Close" },
  4404. {
  4405. label: "Replace all", action: function () {
  4406. var needle = $f.val();
  4407. if (!needle) return;
  4408. var total = 0;
  4409. body.slides.forEach(function (s) {
  4410. s.objects.forEach(function (o) { total += replaceIn(o, true); });
  4411. });
  4412. if (total) { renderAll(); OfficeApp.markDirty(); undo.push(snap()); }
  4413. $msg.text(total ? "Replaced " + total + " occurrence" + (total === 1 ? "" : "s") : "No matches");
  4414. }
  4415. },
  4416. {
  4417. label: "Replace", action: function () {
  4418. var o = sel.length === 1 ? objById(sel[0]) : null;
  4419. if (o && $f.val() && matches(o, $f.val(), $b.find(".fr-case").prop("checked"))) {
  4420. if (replaceIn(o, false)) commit();
  4421. }
  4422. findNext();
  4423. }
  4424. },
  4425. { label: "Find next", primary: true, action: function () { findNext(); } }
  4426. ]
  4427. });
  4428. $f.on("keydown", function (e) { if (e.key === "Enter") { e.preventDefault(); findNext(); } });
  4429. setTimeout(function () { $f.focus(); }, 30);
  4430. }
  4431. /* ================= slide overview ================= */
  4432. /* The whole deck as a grid of slides, Google Slides' grid view and
  4433. PowerPoint's Slide Sorter: click selects, double-click (or Enter)
  4434. opens the slide, drag reorders, right-click has the slide menu, and
  4435. Delete / Ctrl+D / Ctrl+M work on the slide in hand. The previews are
  4436. the same renderSlideContent() the rail uses. */
  4437. var overview = false;
  4438. var OV_SIZES = [140, 180, 220, 280, 340, 420];
  4439. function overviewSize() {
  4440. var i = OfficeApp.getSetting("overviewSize", 2);
  4441. return OV_SIZES[clamp(i, 0, OV_SIZES.length - 1)];
  4442. }
  4443. function setOverview(on) {
  4444. on = !!on;
  4445. if (on === overview) { if (on) focusOverview(); return; }
  4446. endCrop(true);
  4447. endEdit(true);
  4448. if (pendingDraw) disarmDraw();
  4449. overview = on;
  4450. document.body.classList.toggle("sl-overview-on", on);
  4451. if (on) {
  4452. setSel([]);
  4453. renderOverview();
  4454. focusOverview();
  4455. } else {
  4456. $("#slOverview").empty();
  4457. renderRail();
  4458. layoutCanvas();
  4459. fitThumbs();
  4460. }
  4461. syncViewButtons();
  4462. OfficeApp.updateMenus();
  4463. }
  4464. function syncViewButtons() {
  4465. $(".sl-viewbtn[data-view=normal]").toggleClass("active", !overview);
  4466. $(".sl-viewbtn[data-view=overview]").toggleClass("active", overview);
  4467. }
  4468. function focusOverview() {
  4469. var $c = $("#slOverview .sl-ov-card").eq(cur);
  4470. if ($c.length) {
  4471. $c[0].focus({ preventScroll: true });
  4472. $c[0].scrollIntoView({ block: "nearest" });
  4473. }
  4474. }
  4475. var ovDrag = -1;
  4476. function renderOverview() {
  4477. var $ov = $("#slOverview");
  4478. if (!$ov.length) return;
  4479. var size = overviewSize();
  4480. var keepScroll = $ov.find(".sl-ov-grid").scrollTop() || 0;
  4481. $ov.empty();
  4482. var $grid = $('<div class="sl-ov-grid"></div>').css("--sl-ov-w", size + "px")
  4483. .css("--sl-ov-scale", size / SLIDE_W);
  4484. body.slides.forEach(function (s, i) {
  4485. var $c = $('<div class="sl-ov-card" tabindex="0" draggable="true"></div>').attr("data-i", i);
  4486. if (i === cur) $c.addClass("active");
  4487. if (s.hidden) $c.addClass("sl-skipped");
  4488. var $v = $('<div class="sl-ov-view"><div class="sl-ov-mini sl-slidebase sl-showph"></div></div>');
  4489. $c.append($v);
  4490. var $meta = $('<div class="sl-ov-meta"></div>').append('<span class="sl-ov-num">' + (i + 1) + "</span>");
  4491. if (s.hidden) {
  4492. $meta.append($('<span class="sl-ov-flag sl-skip-mark"></span>').attr("title", SKIP_TIP).html(OfficeIcons.get("skipSlide")));
  4493. }
  4494. if (s.transition && s.transition !== "none") {
  4495. $meta.append('<span class="sl-ov-flag" title="Transition: ' + esc(s.transition) + '">' + OfficeIcons.get("transition") + "</span>");
  4496. }
  4497. if (s.notes) $meta.append('<span class="sl-ov-flag" title="Has speaker notes">' + OfficeIcons.get("notes") + "</span>");
  4498. $c.append($meta);
  4499. renderSlideContent($v.find(".sl-ov-mini")[0], s);
  4500. $c.on("click", function () { overviewSelect(i); });
  4501. $c.on("dblclick", function () { cur = i; setOverview(false); selectSlide(i); });
  4502. $c.on("contextmenu", function (e) {
  4503. e.preventDefault();
  4504. overviewSelect(i);
  4505. showSlideContextMenu(e.clientX, e.clientY, i);
  4506. });
  4507. $c.on("dragstart", function (e) {
  4508. ovDrag = i;
  4509. $c.addClass("dragging");
  4510. try {
  4511. e.originalEvent.dataTransfer.setData("text/plain", String(i));
  4512. e.originalEvent.dataTransfer.effectAllowed = "move";
  4513. } catch (err) { }
  4514. });
  4515. $c.on("dragover", function (e) {
  4516. if (ovDrag < 0) return;
  4517. e.preventDefault();
  4518. var r = $c[0].getBoundingClientRect();
  4519. var before = (e.originalEvent.clientX - r.left) < r.width / 2;
  4520. $c.toggleClass("drop-before", before).toggleClass("drop-after", !before);
  4521. });
  4522. $c.on("dragleave", function () { $c.removeClass("drop-before drop-after"); });
  4523. $c.on("drop", function (e) {
  4524. e.preventDefault();
  4525. var before = $c.hasClass("drop-before");
  4526. $c.removeClass("drop-before drop-after");
  4527. if (ovDrag < 0 || ovDrag === i) return;
  4528. moveSlideTo(ovDrag, i + (before ? 0 : 1));
  4529. });
  4530. $c.on("dragend", function () {
  4531. ovDrag = -1;
  4532. $("#slOverview .sl-ov-card").removeClass("dragging drop-before drop-after");
  4533. });
  4534. $grid.append($c);
  4535. });
  4536. // a new slide at the end, as the last card
  4537. var $add = $('<button type="button" class="sl-ov-add" title="New slide (Ctrl+M)"><i class="plus icon"></i></button>');
  4538. $add.on("click", function () { addSlideAfter(body.slides.length - 1); });
  4539. $grid.append($add);
  4540. $ov.append($grid);
  4541. $grid.scrollTop(keepScroll);
  4542. // the size control, Google Slides' grid view has it at the bottom
  4543. var $zoom = $('<div class="sl-ov-zoom"></div>');
  4544. var $minus = $('<button type="button" title="Smaller slides"><i class="minus icon"></i></button>');
  4545. var $mid = $('<span class="sl-ov-zoomic" title="Slide size">' + OfficeIcons.get("overview") + "</span>");
  4546. var $plus = $('<button type="button" title="Larger slides"><i class="plus icon"></i></button>');
  4547. var step = function (d) {
  4548. var i = clamp(OfficeApp.getSetting("overviewSize", 2) + d, 0, OV_SIZES.length - 1);
  4549. OfficeApp.setSetting("overviewSize", i);
  4550. renderOverview();
  4551. focusOverview();
  4552. };
  4553. $minus.on("click", function () { step(-1); });
  4554. $plus.on("click", function () { step(1); });
  4555. $zoom.append($minus).append($mid).append($plus);
  4556. $ov.append($zoom);
  4557. }
  4558. function overviewSelect(i) {
  4559. if (i < 0 || i >= body.slides.length) return;
  4560. cur = i;
  4561. $("#slOverview .sl-ov-card").each(function (k) { $(this).toggleClass("active", k === i); });
  4562. var $c = $("#slOverview .sl-ov-card").eq(i);
  4563. if ($c.length && document.activeElement !== $c[0]) {
  4564. $c[0].focus({ preventScroll: true });
  4565. }
  4566. if ($c.length) $c[0].scrollIntoView({ block: "nearest" });
  4567. // the editor behind follows, so leaving the overview lands here
  4568. renderEditorSlide();
  4569. syncNotes();
  4570. updateStatus();
  4571. if (window.OfficeRibbon) OfficeRibbon.refresh();
  4572. }
  4573. function overviewColumns() {
  4574. var cards = document.querySelectorAll("#slOverview .sl-ov-card");
  4575. if (cards.length < 2) return 1;
  4576. var top = cards[0].offsetTop, n = 0;
  4577. for (var i = 0; i < cards.length; i++) {
  4578. if (cards[i].offsetTop !== top) break;
  4579. n++;
  4580. }
  4581. return Math.max(1, n);
  4582. }
  4583. function registerOverviewKeys() {
  4584. var HK = OfficeHotkeys;
  4585. var on = function () { return overview && !presActive(); };
  4586. var G = "Slide overview";
  4587. HK.register("Ctrl+]", function () { stepFontSize(1); },
  4588. { id: "sl.grow", description: "Increase font size", group: "Text editing", allowInInput: true, when: function () { return !presActive(); } });
  4589. HK.register("Ctrl+[", function () { stepFontSize(-1); },
  4590. { id: "sl.shrink", description: "Decrease font size", group: "Text editing", allowInInput: true, when: function () { return !presActive(); } });
  4591. HK.register("Ctrl+H", function () { findReplaceDialog(); },
  4592. { id: "sl.findrep", description: "Find and replace", group: "Slides", when: function () { return !presActive(); } });
  4593. HK.register("Escape", function () { stopPainter(); },
  4594. { id: "sl.painteresc", allowInInput: true, when: function () { return !!painter; } });
  4595. HK.register("Ctrl+Alt+1", function () { setOverview(!overview); },
  4596. { id: "sl.overview", description: "Slide overview on / off", group: "Slides", allowInInput: true, when: function () { return !presActive(); } });
  4597. HK.register("Escape", function () { setOverview(false); }, { id: "sl.ov.esc", description: "Back to the slide", group: G, allowInInput: true, when: on });
  4598. HK.register("Enter", function () { var i = cur; setOverview(false); selectSlide(i); }, { id: "sl.ov.enter", description: "Open the slide", group: G, when: on });
  4599. HK.register("Delete", function () { deleteSlide(cur); }, { id: "sl.ov.del", description: "Delete slide", group: G, when: on });
  4600. HK.register("Backspace", function () { deleteSlide(cur); }, { id: "sl.ov.bs", when: on });
  4601. HK.register("Home", function () { overviewSelect(0); }, { id: "sl.ov.home", when: on });
  4602. HK.register("End", function () { overviewSelect(body.slides.length - 1); }, { id: "sl.ov.end", when: on });
  4603. HK.register("Ctrl+A", function () { }, { id: "sl.ov.ctrla", when: on });
  4604. HK.register("Tab", function () { return false; }, { id: "sl.ov.tab", when: on });
  4605. [["ArrowLeft", -1, 0], ["ArrowRight", 1, 0], ["ArrowUp", 0, -1], ["ArrowDown", 0, 1]].forEach(function (k) {
  4606. HK.register(k[0], function () {
  4607. var step = k[1] + k[2] * overviewColumns();
  4608. overviewSelect(clamp(cur + step, 0, body.slides.length - 1));
  4609. }, { id: "sl.ov." + k[0], description: k[0] === "ArrowLeft" ? "Move between slides" : "", group: G, when: on });
  4610. });
  4611. }
  4612. /* ---- line menus (weight, dash, start, end) ---- */
  4613. // what the line menus act on: shapes, lines and picture frames
  4614. function strokedObjs() {
  4615. return selObjs().filter(function (o) {
  4616. return o.type === "shape" || o.type === "line" || o.type === "image";
  4617. });
  4618. }
  4619. function lineObjs() {
  4620. return selObjs().filter(function (o) { return o.type === "line"; });
  4621. }
  4622. // a frame with no colour of its own takes the line colour on the
  4623. // toolbar, or setting its weight would show nothing
  4624. function ensureStroke(o) {
  4625. if (!o.props.stroke || o.props.stroke === "none") {
  4626. o.props.stroke = OfficeRibbon.colorOf("#slStrokeColor") || "#333333";
  4627. }
  4628. }
  4629. function weightItems() {
  4630. var first = strokedObjs()[0];
  4631. return SlidesLines.WEIGHTS.map(function (w) {
  4632. return {
  4633. label: w + "px", html: SlidesLines.weightIcon(w) + '<span class="sl-mi-text">' + w + "px</span>",
  4634. checked: function () { return !!first && (Number(first.props.strokeW) || 0) === w; },
  4635. action: function () {
  4636. applyToSel(function (o) {
  4637. if (o.type !== "shape" && o.type !== "line" && o.type !== "image") return false;
  4638. o.props.strokeW = w;
  4639. if (o.type !== "line") ensureStroke(o);
  4640. return true;
  4641. });
  4642. }
  4643. };
  4644. });
  4645. }
  4646. function dashItems() {
  4647. var first = strokedObjs()[0];
  4648. return SlidesLines.DASHES.map(function (d) {
  4649. return {
  4650. label: d.label, html: SlidesLines.dashIcon(d.id),
  4651. checked: function () {
  4652. if (!first) return false;
  4653. var cur = SlidesLines.dashOf(first.props);
  4654. return cur === d.id || (cur === "legacy" && d.id === "dash");
  4655. },
  4656. action: function () {
  4657. applyToSel(function (o) {
  4658. if (o.type !== "shape" && o.type !== "line" && o.type !== "image") return false;
  4659. SlidesLines.setDash(o.props, d.id);
  4660. return true;
  4661. });
  4662. }
  4663. };
  4664. });
  4665. }
  4666. function headItems(end) {
  4667. var first = lineObjs()[0];
  4668. return SlidesLines.HEADS.map(function (h) {
  4669. return {
  4670. label: h.label, html: SlidesLines.headIcon(h.id, end),
  4671. checked: function () { return !!first && SlidesLines.headOf(first.props, end) === h.id; },
  4672. action: function () {
  4673. applyToSel(function (o) {
  4674. if (o.type !== "line") return false;
  4675. SlidesLines.setHead(o.props, end, h.id);
  4676. return true;
  4677. });
  4678. }
  4679. };
  4680. });
  4681. }
  4682. // selectedImage returns the lone selected picture, or null
  4683. function selectedImage() {
  4684. var so = selObjs();
  4685. return (so.length === 1 && so[0].type === "image") ? so[0] : null;
  4686. }
  4687. /* The ribbon follows the selection: font and size, the toggles, and
  4688. the contextual Shape / Picture Format tabs (OfficeRibbon.refresh).
  4689. The colour buttons keep the colour last used, as in Office. */
  4690. function syncToolbarFromSel() {
  4691. var so = selObjs();
  4692. var o = so.length ? so[0] : null;
  4693. if (window.SlidesImageTools) SlidesImageTools.sync();
  4694. if (window.OfficeRibbon) OfficeRibbon.refresh();
  4695. var p = o ? o.props : {};
  4696. if (o && (o.type === "text" || o.type === "shape" || o.type === "table")) {
  4697. $("#slFontSize").val(Number(p.fontSize) || (o.type === "table" ? 16 : 24));
  4698. var fam = String(p.fontFamily || "Arial").replace(/['"]/g, "").split(",")[0].trim();
  4699. var $ff = $("#slFontFamily");
  4700. if ($ff.find('option[value="' + fam + '"]').length) $ff.val(fam);
  4701. }
  4702. $("#slBtnBold").toggleClass("active", !!p.bold);
  4703. $("#slBtnItalic").toggleClass("active", !!p.italic);
  4704. $("#slBtnUnderline").toggleClass("active", !!p.underline);
  4705. var al = o && (o.type === "text" || o.type === "shape") ? (p.align || "left") : "";
  4706. ["left", "center", "right", "justify"].forEach(function (a) {
  4707. $("#slAlign_" + a).toggleClass("active", al === a);
  4708. });
  4709. }
  4710. /* ================= notes panel ================= */
  4711. function toggleNotes() {
  4712. var collapsed = $("#slNotes").toggleClass("collapsed").hasClass("collapsed");
  4713. OfficeApp.setSetting("notesCollapsed", collapsed);
  4714. layoutCanvas();
  4715. }
  4716. function initNotes() {
  4717. // a phone starts with the notes folded away (not saved as a choice)
  4718. if (OfficeApp.getSetting("notesCollapsed", false) || OfficeRibbon.isNarrow()) $("#slNotes").addClass("collapsed");
  4719. $("#slNotesHead").on("click", toggleNotes);
  4720. $("#slNotesText").on("input", function () {
  4721. curSlide().notes = this.value;
  4722. OfficeApp.markDirty();
  4723. undo.pushDebounced(snap, 900);
  4724. renderThumbSoon(cur);
  4725. });
  4726. }
  4727. /* ================= undo / redo ================= */
  4728. function doUndo() { endEdit(true); undo.undo(); }
  4729. function doRedo() { endEdit(true); undo.redo(); }
  4730. function applyUndoState(state) {
  4731. try { body = normalizeBody(JSON.parse(state)); } catch (e) { return; }
  4732. editingId = null;
  4733. editingKind = null;
  4734. cur = clamp(cur, 0, body.slides.length - 1);
  4735. sel = sel.filter(function (id) { return !!objById(id); });
  4736. renderAll();
  4737. OfficeApp.markDirty();
  4738. }
  4739. /* ================= present / print ================= */
  4740. function startPresent(fromIndex, opts) {
  4741. endEdit(true);
  4742. if (window.SlidesPresent) SlidesPresent.start(fromIndex, opts);
  4743. }
  4744. function fillPrintArea() {
  4745. var $pa = $("#slPrintArea").empty();
  4746. body.slides.forEach(function (s) {
  4747. var $pg = $('<div class="sl-print-page"><div class="sl-slidebase"></div></div>');
  4748. renderSlideContent($pg.find(".sl-slidebase")[0], s);
  4749. $pa.append($pg);
  4750. });
  4751. }
  4752. function clearPrintArea() { $("#slPrintArea").empty(); }
  4753. /* ================= ODP import / export =================
  4754. The deck's own format, .pptx, is opened and saved by the framework
  4755. (OfficePlatform.documentLoad / documentSave). OpenDocument goes
  4756. through the same Go converters either way: the office AGI library in
  4757. ArozOS, the WebAssembly build of it (src/wasm/office) in the
  4758. standalone web edition. One descriptor names both; OfficePlatform
  4759. picks. */
  4760. var CONVERT_BACKEND = "Office/slides/backend/convert.agi";
  4761. var CONVERT = {
  4762. "import-odf": { agi: CONVERT_BACKEND, action: "import-odf", wasm: "odpToPresentation" },
  4763. "export-odf": { agi: CONVERT_BACKEND, action: "export-odf", wasm: "presentationToOdp" }
  4764. };
  4765. function importOdp(fp, fn) {
  4766. var action = "import-odf";
  4767. OfficeApp.showBusy("Importing " + fn + "...");
  4768. OfficePlatform.convertIn(CONVERT[action], fp, function (data) {
  4769. OfficeApp.hideBusy();
  4770. var b = data;
  4771. if (typeof b === "string") {
  4772. try { b = JSON.parse(b); } catch (e) { b = null; }
  4773. }
  4774. if (!b || !b.slides) {
  4775. OfficeApp.toast("Import failed: unexpected response", "error");
  4776. return;
  4777. }
  4778. OfficeApp.splashStep("Preparing the slides...", function () {
  4779. body = normalizeBody(b);
  4780. cur = 0;
  4781. sel = [];
  4782. editingId = null;
  4783. renderAll();
  4784. undo.init(snap());
  4785. // the framework kept us attached to the source file, so Save
  4786. // writes straight back to it in its own format
  4787. OfficeApp.setStatus("Opened " + fn);
  4788. OfficeApp.documentLoaded();
  4789. });
  4790. }, function (msg) {
  4791. OfficeApp.hideBusy();
  4792. OfficeApp.toast("Import failed: " + msg, "error");
  4793. });
  4794. }
  4795. /* Rasterize a chart spec to a PNG dataURL (charts export as pictures). */
  4796. function rasterizeChartToPng(spec, w, h) {
  4797. return new Promise(function (resolve) {
  4798. w = Math.max(60, Math.round(w)); h = Math.max(60, Math.round(h));
  4799. var svg = OfficeCharts.renderToString(spec, w, h)
  4800. .replace('width="100%" height="100%"', 'width="' + w + '" height="' + h + '"');
  4801. // charts inherit currentColor for text - fix it for export
  4802. svg = svg.replace("<svg ", '<svg color="#202124" ');
  4803. var img = new Image();
  4804. img.onload = function () {
  4805. try {
  4806. var cv = document.createElement("canvas");
  4807. cv.width = w * 2; cv.height = h * 2;
  4808. var ctx = cv.getContext("2d");
  4809. ctx.fillStyle = "#ffffff";
  4810. ctx.fillRect(0, 0, cv.width, cv.height);
  4811. ctx.drawImage(img, 0, 0, cv.width, cv.height);
  4812. resolve(cv.toDataURL("image/png"));
  4813. } catch (e) { resolve(null); }
  4814. };
  4815. img.onerror = function () { resolve(null); };
  4816. img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
  4817. });
  4818. }
  4819. /* Capture a poster frame of a video source as a PNG data URL - used as
  4820. the embedded media poster in pptx exports and the placeholder image
  4821. in pdf exports. Resolves null when the frame cannot be captured
  4822. (unsupported codec etc.); exports fall back to a generic poster. */
  4823. function captureVideoFrame(src) {
  4824. return new Promise(function (resolve) {
  4825. var v = document.createElement("video");
  4826. var done = false;
  4827. var timer = null;
  4828. function finish(result) {
  4829. if (done) return;
  4830. done = true;
  4831. if (timer) clearTimeout(timer);
  4832. v.removeAttribute("src");
  4833. try { v.load(); } catch (e) { /* detach only */ }
  4834. resolve(result);
  4835. }
  4836. timer = setTimeout(function () { finish(null); }, 8000);
  4837. v.muted = true;
  4838. v.preload = "auto";
  4839. v.addEventListener("error", function () { finish(null); });
  4840. v.addEventListener("loadeddata", function () {
  4841. // seek slightly in so black lead-in frames are skipped
  4842. try { v.currentTime = Math.min(0.5, (v.duration || 1) / 2); } catch (e) { finish(null); }
  4843. });
  4844. v.addEventListener("seeked", function () {
  4845. try {
  4846. var c = document.createElement("canvas");
  4847. c.width = v.videoWidth || 480;
  4848. c.height = v.videoHeight || 270;
  4849. c.getContext("2d").drawImage(v, 0, 0, c.width, c.height);
  4850. finish(c.toDataURL("image/png"));
  4851. } catch (e) { finish(null); }
  4852. });
  4853. v.src = src;
  4854. });
  4855. }
  4856. /* Deep-clone the body and inline every image / chart as a dataURL so the
  4857. server-side exporter can embed them into the .pptx. */
  4858. /* What the .pptx needs that only the browser can make: every chart as a
  4859. PNG (the writer draws charts as pictures) and a poster frame for every
  4860. video. Both are kept for the session by what they were made from, and
  4861. in ArozOS uploaded once (OfficePlatform.cacheBlob) - an unchanged chart
  4862. costs nothing on the next save, which is what lets a deck autosave.
  4863. Pictures are left alone: a storage picture stays a media?file= link,
  4864. and the server reads it. */
  4865. var renderCache = {}; // key -> Promise(src | null)
  4866. function dataUrlToBlob(durl) {
  4867. var comma = durl.indexOf(",");
  4868. var mime = (/^data:([^;,]+)/.exec(durl) || [])[1] || "image/png";
  4869. var bin = atob(durl.substring(comma + 1));
  4870. var arr = new Uint8Array(bin.length);
  4871. for (var i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
  4872. return new Blob([arr], { type: mime });
  4873. }
  4874. function cachedRender(key, make) {
  4875. if (!renderCache[key]) {
  4876. renderCache[key] = make().then(function (durl) {
  4877. if (!durl) return null;
  4878. return new Promise(function (resolve) {
  4879. OfficePlatform.cacheBlob(dataUrlToBlob(durl), "render.png",
  4880. resolve, function () { resolve(durl); });
  4881. });
  4882. });
  4883. // a failed render is tried again next time
  4884. renderCache[key].then(function (src) { if (!src) delete renderCache[key]; });
  4885. }
  4886. return renderCache[key];
  4887. }
  4888. // b is the framework's private copy of the body
  4889. function prepareNative(b) {
  4890. var jobs = [];
  4891. b.slides.forEach(function (s) {
  4892. s.objects.forEach(function (o) {
  4893. if (o.type === "chart") {
  4894. var spec = o.props.spec || {};
  4895. jobs.push(cachedRender("chart|" + JSON.stringify(spec) + "|" + Math.round(o.w) + "x" + Math.round(o.h),
  4896. function () { return rasterizeChartToPng(spec, o.w, o.h); }).then(function (png) {
  4897. if (png) o.props.png = png;
  4898. }));
  4899. } else if (o.type === "video" && o.props.src) {
  4900. // the media file itself keeps its media?file= link - the
  4901. // server reads the bytes, so they never ride this payload
  4902. var src = o.props.src;
  4903. jobs.push(cachedRender("video|" + src, function () { return captureVideoFrame(src); })
  4904. .then(function (png) { if (png) o.props.png = png; }));
  4905. }
  4906. // audio keeps its link untouched (no frame to capture)
  4907. });
  4908. });
  4909. return Promise.all(jobs);
  4910. }
  4911. function preparedCopy() {
  4912. var b = deep(body);
  4913. return prepareNative(b).then(function () { return b; });
  4914. }
  4915. /* PDF is built in the browser (slides_pdf.js), not on the server: only
  4916. the browser knows which font it actually resolved and where every
  4917. line wrapped, and that is exactly what the export has to reproduce.
  4918. Each element goes in as the real PDF object it should be - text as
  4919. text, pictures as embedded images with real clip paths, shapes and
  4920. charts as vectors - and only an element the format genuinely cannot
  4921. express falls back to a raster of itself. */
  4922. function canExportPdf() {
  4923. return typeof PDFLib !== "undefined" && !!window.SlidesPdf;
  4924. }
  4925. function exportPdf() {
  4926. if (!canExportPdf()) {
  4927. OfficeApp.toast("The PDF library failed to load", "error");
  4928. return;
  4929. }
  4930. endEdit(true);
  4931. endCrop(true);
  4932. var defName = OfficeApp.stripExt(OfficeApp.getFileName() || "New Presentation.pptx") + ".pdf";
  4933. OfficePlatform.pickSave({ defaultName: defName, ext: ".pdf", memoryKey: "export" }, function (file) {
  4934. var fp = file.filepath;
  4935. // rendering a deck takes a moment, and there is no reason for
  4936. // the editor to be unusable while it happens - savePdfTo works
  4937. // from a snapshot, so editing on does not change what comes out
  4938. var prog = OfficeApp.showProgress({
  4939. title: "Exporting PDF", anchor: "#slCanvasArea"
  4940. });
  4941. prog.set(0, 1, "Preparing...");
  4942. savePdfTo(fp, function () {
  4943. prog.close();
  4944. OfficeApp.setStatus("Exported " + OfficeApp.basename(fp));
  4945. OfficeApp.toast("Exported " + OfficeApp.basename(fp));
  4946. }, function (msg) {
  4947. prog.close();
  4948. OfficeApp.toast("Export failed: " + msg, "error");
  4949. }, prog);
  4950. });
  4951. }
  4952. /* savePdfTo renders the deck and writes the bytes; shared by File >
  4953. Export and by the .pdf entry in SAVE_FORMATS. prog is optional - a
  4954. progress panel to report pages through.
  4955. The deck is copied before rendering. The export runs without blocking
  4956. the editor, so the document underneath can change while it is going;
  4957. taking a snapshot is what makes the file that lands on disk the deck
  4958. as it was when the export was asked for. */
  4959. function savePdfTo(fp, done, fail, prog) {
  4960. if (!canExportPdf()) { fail("the PDF library failed to load"); return; }
  4961. endEdit(true);
  4962. endCrop(true);
  4963. var snapshot;
  4964. try {
  4965. snapshot = JSON.parse(JSON.stringify(body));
  4966. } catch (e) {
  4967. fail("the presentation could not be read");
  4968. return;
  4969. }
  4970. SlidesPdf.build(snapshot, {
  4971. title: OfficeApp.stripExt(OfficeApp.getFileName() || "Presentation"),
  4972. onProgress: function (n, total, stage) {
  4973. // measuring the slides is the first half, writing the file
  4974. // (in a worker) the second
  4975. var f = total > 0 ? n / total : 0;
  4976. var pct, msg;
  4977. if (stage === "save") {
  4978. pct = 97;
  4979. msg = "Writing the file...";
  4980. } else if (stage === "page") {
  4981. pct = 50 + 45 * f;
  4982. msg = "Writing " + n + " / " + total + (total === 1 ? " page" : " pages");
  4983. } else {
  4984. pct = 50 * f;
  4985. msg = "Exporting " + n + " / " + total + (total === 1 ? " page" : " pages");
  4986. }
  4987. if (prog) prog.set(pct, 100, msg);
  4988. else OfficeApp.setStatus("Exporting PDF... " + msg);
  4989. }
  4990. }).then(function (bytes) {
  4991. if (prog) prog.message("Writing " + OfficeApp.basename(fp) + "...");
  4992. OfficePlatform.writeBytes(fp, bytes, done, fail);
  4993. }).catch(function (err) {
  4994. fail(err && err.message ? err.message : "render error");
  4995. });
  4996. }
  4997. /* ================= saving back into a foreign format =================
  4998. A deck opened from .odp goes on living in that file: the framework
  4999. keeps filepath/filename pointing at it and Ctrl+S comes back here
  5000. instead of forcing a Save As to .pptx. This is the same converter the
  5001. Export menu uses, reporting through the framework's save callbacks
  5002. rather than a toast of its own. */
  5003. function plural(n, one, many) { return n + " " + (n === 1 ? one : many); }
  5004. function saveOdp(fp, done, fail) {
  5005. endEdit(true);
  5006. preparedCopy().then(function (prepared) {
  5007. OfficePlatform.convertOut(CONVERT["export-odf"], fp, JSON.stringify(prepared),
  5008. function () { done(); }, fail);
  5009. }).catch(function (err) {
  5010. fail((err && err.message) ? err.message : "could not prepare the presentation");
  5011. });
  5012. }
  5013. /* .odp: the OpenDocument presentation writer emits text, images, charts,
  5014. shapes, lines and tables (mod/office/odf/odp_writer.go) - a video or audio
  5015. object would simply vanish, so the save is refused instead. */
  5016. function odpUnsupported() {
  5017. var n = 0;
  5018. ((body && body.slides) || []).forEach(function (s) {
  5019. (s.objects || []).forEach(function (o) {
  5020. if (o.type === "video" || o.type === "audio") n++;
  5021. });
  5022. });
  5023. return n ? [plural(n, "video / audio object", "video / audio objects") +
  5024. " - the OpenDocument presentation writer cannot store them"] : [];
  5025. }
  5026. /*
  5027. The formats File > Save as offers besides .pptx, and the ones a deck
  5028. opened from .odp is saved back into. needsConvert marks the
  5029. writers that go through the Office format converters and needsBackend
  5030. the ones that need a server outright (the real-text PDF renderer);
  5031. OfficeApp drops whichever the running host cannot do. PDF is oneWay -
  5032. it is a rendering, so writing one leaves the deck on its own file.
  5033. */
  5034. var SAVE_FORMATS = [
  5035. {
  5036. ext: ".odp", label: "OpenDocument presentation (.odp)", icon: "file alternate outline",
  5037. needsConvert: true, noAutosave: true,
  5038. unsupported: odpUnsupported,
  5039. save: function (fp, fn, done, fail) { saveOdp(fp, done, fail); }
  5040. },
  5041. {
  5042. // rendered in the browser, so it needs no backend - only the
  5043. // PDF library (see exportPdf)
  5044. ext: ".pdf", label: "PDF document (.pdf)", icon: "file pdf outline",
  5045. oneWay: true,
  5046. save: function (fp, fn, done, fail) { savePdfTo(fp, done, fail); }
  5047. }
  5048. ];
  5049. /* The layouts a new slide can start from, in the order the picker
  5050. shows them. They are skeletons of real objects, not a placeholder
  5051. system - so what the preview draws is what the slide will be. */
  5052. var LAYOUTS = [
  5053. { key: "title", label: "Title slide" },
  5054. { key: "section", label: "Section header" },
  5055. { key: "content", label: "Title and body" },
  5056. { key: "two", label: "Title and two columns" },
  5057. { key: "normal", label: "Title only" },
  5058. { key: "onecol", label: "One-column text" },
  5059. { key: "mainpoint", label: "Main point" },
  5060. { key: "sectiondesc", label: "Section title and description" },
  5061. { key: "caption", label: "Caption" },
  5062. { key: "bignumber", label: "Big number" },
  5063. { key: "blank", label: "Blank" }
  5064. ];
  5065. /* showLayoutPicker is the caret beside New slide: every layout as a
  5066. preview of itself. The previews are built by the same newSlide() and
  5067. renderSlideContent() the document uses, at the scale the rail uses,
  5068. so a preview cannot come to disagree with the slide it makes. */
  5069. var $layoutPicker = null;
  5070. function closeLayoutPicker() {
  5071. if ($layoutPicker) { $layoutPicker.remove(); $layoutPicker = null; }
  5072. $(document).off("mousedown.sllayoutpick");
  5073. }
  5074. function showLayoutPicker(x, y) {
  5075. closeLayoutPicker();
  5076. var $m = $('<div class="sl-layoutpick of-noprint"></div>');
  5077. LAYOUTS.forEach(function (l) {
  5078. var $c = $('<button type="button" class="sl-layoutpick-cell"></button>');
  5079. var $v = $('<div class="sl-layoutpick-view"><div class="sl-layoutpick-mini sl-slidebase"></div></div>');
  5080. $c.append($v);
  5081. $c.append($('<div class="sl-layoutpick-label"></div>').text(l.label));
  5082. $m.append($c);
  5083. var $lmini = $v.find(".sl-layoutpick-mini").addClass("sl-showph sl-phframe");
  5084. renderSlideContent($lmini[0], newSlide(l.key));
  5085. $c.on("click", function () {
  5086. closeLayoutPicker();
  5087. addSlideAfter(cur, l.key);
  5088. });
  5089. });
  5090. $("body").append($m);
  5091. var mw = $m.outerWidth(), mh = $m.outerHeight();
  5092. $m.css({
  5093. left: Math.max(4, Math.min(x, window.innerWidth - mw - 6)) + "px",
  5094. top: Math.max(4, Math.min(y, window.innerHeight - mh - 6)) + "px"
  5095. });
  5096. $layoutPicker = $m;
  5097. setTimeout(function () {
  5098. $(document).on("mousedown.sllayoutpick", function (e) {
  5099. if ($layoutPicker && !$layoutPicker[0].contains(e.target)) closeLayoutPicker();
  5100. });
  5101. }, 0);
  5102. }
  5103. /* ================= init ================= */
  5104. function initDomRefs() {
  5105. canvasEl = document.getElementById("slCanvas");
  5106. layerEl = document.getElementById("slSlideLayer");
  5107. // the canvas shows empty text boxes' prompts and frames
  5108. layerEl.className = "sl-slidebase sl-showph sl-phframe";
  5109. var overlay = document.getElementById("slOverlay");
  5110. overlay.innerHTML = '<div id="slFrames"></div>' +
  5111. '<div id="slCrop"></div>' +
  5112. '<div id="slGuideV" class="sl-guide"></div>' +
  5113. '<div id="slGuideH" class="sl-guide"></div>' +
  5114. '<div id="slMarquee"></div>';
  5115. framesEl = document.getElementById("slFrames");
  5116. cropEl = document.getElementById("slCrop");
  5117. guideVEl = document.getElementById("slGuideV");
  5118. guideHEl = document.getElementById("slGuideH");
  5119. marqueeEl = document.getElementById("slMarquee");
  5120. canvasEl.addEventListener("pointerdown", onCanvasPointerDown);
  5121. canvasEl.addEventListener("pointermove", onCanvasPointerMove);
  5122. canvasEl.addEventListener("pointerup", onCanvasPointerUp);
  5123. canvasEl.addEventListener("pointercancel", onCanvasPointerUp);
  5124. canvasEl.addEventListener("dblclick", onCanvasDblClick);
  5125. canvasEl.addEventListener("contextmenu", onCanvasContextMenu);
  5126. // links inside text boxes must never navigate the editor itself -
  5127. // Ctrl+click follows them (like Docs/Word), a plain click only edits
  5128. canvasEl.addEventListener("click", function (e) {
  5129. var a = e.target.closest ? e.target.closest("a[href]") : null;
  5130. if (!a || !layerEl.contains(a)) return;
  5131. e.preventDefault();
  5132. var href = a.getAttribute("href") || "";
  5133. if (!(e.ctrlKey || e.metaKey)) {
  5134. OfficeApp.setStatus("Ctrl+Click to open link: " + href, "info", 4000);
  5135. return;
  5136. }
  5137. if (/^https?:\/\//i.test(href)) {
  5138. window.open(href, "_blank", "noopener");
  5139. } else if (/^#\d+$/.test(href)) {
  5140. var n = parseInt(href.substring(1), 10) - 1;
  5141. if (n >= 0 && n < body.slides.length) selectSlide(n);
  5142. }
  5143. });
  5144. // click on the gray area around the canvas deselects
  5145. document.getElementById("slCanvasArea").addEventListener("pointerdown", function (e) {
  5146. if (e.target.id === "slCanvasArea" || e.target.id === "slCanvasWrap") {
  5147. endEdit(true);
  5148. setSel([]);
  5149. }
  5150. });
  5151. $("#slDeviceImage").on("change", function () {
  5152. var files = this.files;
  5153. for (var i = 0; i < files.length; i++) fileToImage(files[i]);
  5154. this.value = "";
  5155. });
  5156. registerHotkeys();
  5157. window.addEventListener("resize", function () {
  5158. layoutCanvas();
  5159. fitThumbs();
  5160. });
  5161. // live list-button state as the caret moves through the text box
  5162. document.addEventListener("selectionchange", function () {
  5163. if (editingId && editingKind === "text") syncListButtonState();
  5164. });
  5165. }
  5166. function init() {
  5167. // the picture tools live in their own module and reach the document
  5168. // only through this host object
  5169. if (window.SlidesImageTools) {
  5170. SlidesImageTools.init({
  5171. getImage: selectedImage,
  5172. objEl: objEl,
  5173. commit: commit,
  5174. startCrop: startCrop,
  5175. endCrop: endCrop,
  5176. isCropping: function () { return !!cropId; },
  5177. resetImage: resetImage,
  5178. setMask: setImageMask,
  5179. shapeKinds: MASK_KINDS,
  5180. // read on use: the deck that is open decides the size
  5181. get slideSize() { return [SLIDE_W, SLIDE_H]; },
  5182. relayout: layoutCanvas
  5183. });
  5184. }
  5185. snapGrid = false;
  5186. undo = new OfficeUndoStack({ limit: 100, apply: applyUndoState });
  5187. initDomRefs();
  5188. OfficeApp.init({
  5189. appName: "Slides",
  5190. appType: "presentation",
  5191. appIcon: "../img/slides.svg",
  5192. extension: ".pptx",
  5193. nativeLabel: "PowerPoint presentation (.pptx)",
  5194. fileTypeName: "Presentation",
  5195. defaultFileName: "New Presentation",
  5196. // charts drawn to PNG and video poster frames, before a save
  5197. prepareNative: function (copy) {
  5198. endEdit(true);
  5199. return prepareNative(copy);
  5200. },
  5201. serialize: function () { return deep(body); },
  5202. deserialize: function (b) {
  5203. body = normalizeBody(b);
  5204. cur = 0;
  5205. sel = [];
  5206. editingId = null;
  5207. renderAll();
  5208. undo.init(snap());
  5209. },
  5210. create: function () {
  5211. body = defaultBody();
  5212. cur = 0;
  5213. sel = [];
  5214. editingId = null;
  5215. renderAll();
  5216. undo.init(snap());
  5217. },
  5218. onUndo: doUndo,
  5219. onRedo: doRedo,
  5220. canUndo: function () { return undo.canUndo(); },
  5221. canRedo: function () { return undo.canRedo(); },
  5222. onCut: function () {
  5223. if (editingId) { try { document.execCommand("cut"); } catch (e) { } return; }
  5224. cutSelection();
  5225. },
  5226. onCopy: function () {
  5227. if (editingId) { try { document.execCommand("copy"); } catch (e) { } return; }
  5228. copySelection();
  5229. },
  5230. onPaste: function () {
  5231. if (editingId) {
  5232. if (navigator.clipboard && navigator.clipboard.readText) {
  5233. navigator.clipboard.readText().then(function (t) {
  5234. try { document.execCommand("insertText", false, t); } catch (e) { }
  5235. }).catch(function () { });
  5236. }
  5237. return;
  5238. }
  5239. // menu-driven paste: async clipboard - our object marker
  5240. // wins, then images, internal object clipboard, plain text
  5241. var fallback = function () {
  5242. if (navigator.clipboard && navigator.clipboard.readText) {
  5243. navigator.clipboard.readText().then(function (t) {
  5244. var objs = parseObjectClipboardText(t);
  5245. if (objs) {
  5246. clip = objs.map(deep);
  5247. pasteClipboard();
  5248. return;
  5249. }
  5250. if (pasteClipboard()) return;
  5251. if (!t) return;
  5252. var th = themeOf();
  5253. addObj("text", { html: esc(t).replace(/\n/g, "<br>"), fontSize: 24, color: th.text, align: "left" },
  5254. { x: 280, y: 220, w: 400, h: 90 });
  5255. }).catch(function () {
  5256. if (!pasteClipboard()) OfficeApp.setStatus("Nothing to paste", "error");
  5257. });
  5258. } else if (!pasteClipboard()) {
  5259. OfficeApp.setStatus("Nothing to paste", "error");
  5260. }
  5261. };
  5262. if (navigator.clipboard && navigator.clipboard.read) {
  5263. navigator.clipboard.read().then(function (cbItems) {
  5264. var found = null;
  5265. cbItems.forEach(function (it) {
  5266. it.types.forEach(function (ty) {
  5267. if (!found && ty.indexOf("image/") === 0) found = { it: it, ty: ty };
  5268. });
  5269. });
  5270. if (found) {
  5271. found.it.getType(found.ty).then(function (blob) { fileToImage(blob); });
  5272. } else { fallback(); }
  5273. }).catch(fallback);
  5274. } else { fallback(); }
  5275. },
  5276. // the ribbon (buildToolbar) carries Insert, Slide, Format,
  5277. // Design and View; File and Edit stay menus
  5278. ribbon: true,
  5279. editMenuExtras: [
  5280. { label: "Select all", icon: "i cursor", key: "Ctrl+A", action: selectAllObjects },
  5281. { label: "Delete", icon: "trash alternate outline", key: "Del", enabled: function () { return sel.length > 0; }, action: deleteSelection },
  5282. { label: "Duplicate", icon: "clone outline", key: "Ctrl+D", enabled: function () { return sel.length > 0; }, action: duplicateSelection },
  5283. {
  5284. label: "Format painter", icon: "paint brush",
  5285. action: function () { startPainter(false); }
  5286. },
  5287. { sep: true },
  5288. { label: "Find and replace...", icon: "exchange", key: "Ctrl+H", action: findReplaceDialog }
  5289. ],
  5290. // PowerPoint 97-2003 presentations open by conversion (mod/office/ppt),
  5291. // as imports: Save writes the app's own format
  5292. legacyExtensions: [".ppt", ".pot", ".pps"],
  5293. binaryImporters: {
  5294. ".odp": importOdp
  5295. },
  5296. saveFormats: SAVE_FORMATS,
  5297. /*
  5298. File > Save as holds the formats Slides edits (.pptx, .odp);
  5299. Export the ones it only writes. The .pdf export is rendered
  5300. here in the browser (slides_pdf.js), so it needs no backend
  5301. at all; the PNG exports are rendered by html2canvas right
  5302. here and are always available.
  5303. */
  5304. fileMenuExtras: [
  5305. {
  5306. label: "Export", icon: "external alternate", sub: function () {
  5307. var items = [];
  5308. if (canExportPdf()) {
  5309. items.push({
  5310. label: "PDF document (.pdf)", icon: "file pdf outline",
  5311. action: exportPdf
  5312. });
  5313. }
  5314. items.push({
  5315. label: "Current slide as PNG", icon: "file image outline",
  5316. action: function () { SlidesExport.exportPNG(false); }
  5317. });
  5318. items.push({
  5319. label: "All slides as PNGs", icon: "images outline",
  5320. action: function () { SlidesExport.exportPNG(true); }
  5321. });
  5322. return items;
  5323. }
  5324. }
  5325. ],
  5326. onZoomChanged: function (pct) {
  5327. zoomPct = pct;
  5328. layoutCanvas();
  5329. },
  5330. onBeforePrint: fillPrintArea,
  5331. onAfterPrint: clearPrintArea
  5332. });
  5333. snapGrid = !!OfficeApp.getSetting("snapGrid", false);
  5334. buildToolbar();
  5335. $("#slFontFamily").val("Arial");
  5336. // the document was loaded before the ribbon existed
  5337. syncToolbarFromSel();
  5338. registerOverviewKeys();
  5339. // the format painter lays its look on the object the click selected
  5340. canvasEl.addEventListener("pointerup", function () {
  5341. if (painter) setTimeout(applyPainterToSel, 0);
  5342. });
  5343. initNotes();
  5344. initClipboardAndDnd();
  5345. OfficeApp.addStatusItem("slide", "");
  5346. OfficeApp.addStatusItem("sel", "");
  5347. updateStatus();
  5348. zoomPct = OfficeApp.getZoom();
  5349. layoutCanvas();
  5350. setTimeout(layoutCanvas, 120); // once chrome has settled
  5351. }
  5352. $(document).ready(init);
  5353. /* ---------- public API (used by present.js) ---------- */
  5354. return {
  5355. getBody: function () { return body; },
  5356. getCurrentIndex: function () { return cur; },
  5357. slideSize: function () { return [SLIDE_W, SLIDE_H]; },
  5358. renderSlideContent: renderSlideContent,
  5359. themeOf: themeOf,
  5360. slideCount: function () { return body ? body.slides.length : 0; }
  5361. };
  5362. })();