123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348 |
- import {
- __commonJS
- } from "./chunk-2LSFTFF7.js";
- // node_modules/.pnpm/tinymce@5.10.7/node_modules/tinymce/themes/silver/theme.js
- var require_theme = __commonJS({
- "node_modules/.pnpm/tinymce@5.10.7/node_modules/tinymce/themes/silver/theme.js"() {
- (function() {
- "use strict";
- var typeOf = function(x) {
- var t2 = typeof x;
- if (x === null) {
- return "null";
- } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === "Array")) {
- return "array";
- } else if (t2 === "object" && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === "String")) {
- return "string";
- } else {
- return t2;
- }
- };
- var isType$1 = function(type2) {
- return function(value2) {
- return typeOf(value2) === type2;
- };
- };
- var isSimpleType = function(type2) {
- return function(value2) {
- return typeof value2 === type2;
- };
- };
- var eq$1 = function(t2) {
- return function(a) {
- return t2 === a;
- };
- };
- var isString = isType$1("string");
- var isObject = isType$1("object");
- var isArray = isType$1("array");
- var isNull = eq$1(null);
- var isBoolean = isSimpleType("boolean");
- var isUndefined = eq$1(void 0);
- var isNullable = function(a) {
- return a === null || a === void 0;
- };
- var isNonNullable = function(a) {
- return !isNullable(a);
- };
- var isFunction = isSimpleType("function");
- var isNumber = isSimpleType("number");
- var isArrayOf = function(value2, pred) {
- if (isArray(value2)) {
- for (var i = 0, len = value2.length; i < len; ++i) {
- if (!pred(value2[i])) {
- return false;
- }
- }
- return true;
- }
- return false;
- };
- var noop = function() {
- };
- var noarg = function(f) {
- return function() {
- return f();
- };
- };
- var compose = function(fa, fb) {
- return function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return fa(fb.apply(null, args));
- };
- };
- var compose1 = function(fbc, fab) {
- return function(a) {
- return fbc(fab(a));
- };
- };
- var constant$1 = function(value2) {
- return function() {
- return value2;
- };
- };
- var identity$1 = function(x) {
- return x;
- };
- var tripleEquals = function(a, b2) {
- return a === b2;
- };
- function curry(fn) {
- var initialArgs = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- initialArgs[_i - 1] = arguments[_i];
- }
- return function() {
- var restArgs = [];
- for (var _i2 = 0; _i2 < arguments.length; _i2++) {
- restArgs[_i2] = arguments[_i2];
- }
- var all2 = initialArgs.concat(restArgs);
- return fn.apply(null, all2);
- };
- }
- var not = function(f) {
- return function(t2) {
- return !f(t2);
- };
- };
- var die = function(msg) {
- return function() {
- throw new Error(msg);
- };
- };
- var never = constant$1(false);
- var always = constant$1(true);
- var global$g = tinymce.util.Tools.resolve("tinymce.ThemeManager");
- var __assign = function() {
- __assign = Object.assign || function __assign2(t2) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p))
- t2[p] = s[p];
- }
- return t2;
- };
- return __assign.apply(this, arguments);
- };
- function __rest(s, e) {
- var t2 = {};
- for (var p in s)
- if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t2[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t2[p[i]] = s[p[i]];
- }
- return t2;
- }
- function __spreadArray(to2, from2, pack) {
- if (pack || arguments.length === 2)
- for (var i = 0, l2 = from2.length, ar; i < l2; i++) {
- if (ar || !(i in from2)) {
- if (!ar)
- ar = Array.prototype.slice.call(from2, 0, i);
- ar[i] = from2[i];
- }
- }
- return to2.concat(ar || Array.prototype.slice.call(from2));
- }
- var none = function() {
- return NONE;
- };
- var NONE = function() {
- var call = function(thunk2) {
- return thunk2();
- };
- var id = identity$1;
- var me = {
- fold: function(n, _s) {
- return n();
- },
- isSome: never,
- isNone: always,
- getOr: id,
- getOrThunk: call,
- getOrDie: function(msg) {
- throw new Error(msg || "error: getOrDie called on none.");
- },
- getOrNull: constant$1(null),
- getOrUndefined: constant$1(void 0),
- or: id,
- orThunk: call,
- map: none,
- each: noop,
- bind: none,
- exists: never,
- forall: always,
- filter: function() {
- return none();
- },
- toArray: function() {
- return [];
- },
- toString: constant$1("none()")
- };
- return me;
- }();
- var some = function(a) {
- var constant_a = constant$1(a);
- var self2 = function() {
- return me;
- };
- var bind2 = function(f) {
- return f(a);
- };
- var me = {
- fold: function(n, s) {
- return s(a);
- },
- isSome: always,
- isNone: never,
- getOr: constant_a,
- getOrThunk: constant_a,
- getOrDie: constant_a,
- getOrNull: constant_a,
- getOrUndefined: constant_a,
- or: self2,
- orThunk: self2,
- map: function(f) {
- return some(f(a));
- },
- each: function(f) {
- f(a);
- },
- bind: bind2,
- exists: bind2,
- forall: bind2,
- filter: function(f) {
- return f(a) ? me : NONE;
- },
- toArray: function() {
- return [a];
- },
- toString: function() {
- return "some(" + a + ")";
- }
- };
- return me;
- };
- var from$1 = function(value2) {
- return value2 === null || value2 === void 0 ? NONE : some(value2);
- };
- var Optional = {
- some,
- none,
- from: from$1
- };
- var nativeSlice = Array.prototype.slice;
- var nativeIndexOf = Array.prototype.indexOf;
- var nativePush = Array.prototype.push;
- var rawIndexOf = function(ts, t2) {
- return nativeIndexOf.call(ts, t2);
- };
- var indexOf = function(xs, x) {
- var r2 = rawIndexOf(xs, x);
- return r2 === -1 ? Optional.none() : Optional.some(r2);
- };
- var contains$2 = function(xs, x) {
- return rawIndexOf(xs, x) > -1;
- };
- var exists = function(xs, pred) {
- for (var i = 0, len = xs.length; i < len; i++) {
- var x = xs[i];
- if (pred(x, i)) {
- return true;
- }
- }
- return false;
- };
- var range$2 = function(num, f) {
- var r2 = [];
- for (var i = 0; i < num; i++) {
- r2.push(f(i));
- }
- return r2;
- };
- var chunk$1 = function(array, size) {
- var r2 = [];
- for (var i = 0; i < array.length; i += size) {
- var s = nativeSlice.call(array, i, i + size);
- r2.push(s);
- }
- return r2;
- };
- var map$2 = function(xs, f) {
- var len = xs.length;
- var r2 = new Array(len);
- for (var i = 0; i < len; i++) {
- var x = xs[i];
- r2[i] = f(x, i);
- }
- return r2;
- };
- var each$1 = function(xs, f) {
- for (var i = 0, len = xs.length; i < len; i++) {
- var x = xs[i];
- f(x, i);
- }
- };
- var eachr = function(xs, f) {
- for (var i = xs.length - 1; i >= 0; i--) {
- var x = xs[i];
- f(x, i);
- }
- };
- var partition$3 = function(xs, pred) {
- var pass = [];
- var fail = [];
- for (var i = 0, len = xs.length; i < len; i++) {
- var x = xs[i];
- var arr = pred(x, i) ? pass : fail;
- arr.push(x);
- }
- return {
- pass,
- fail
- };
- };
- var filter$2 = function(xs, pred) {
- var r2 = [];
- for (var i = 0, len = xs.length; i < len; i++) {
- var x = xs[i];
- if (pred(x, i)) {
- r2.push(x);
- }
- }
- return r2;
- };
- var foldr = function(xs, f, acc) {
- eachr(xs, function(x, i) {
- acc = f(acc, x, i);
- });
- return acc;
- };
- var foldl = function(xs, f, acc) {
- each$1(xs, function(x, i) {
- acc = f(acc, x, i);
- });
- return acc;
- };
- var findUntil = function(xs, pred, until) {
- for (var i = 0, len = xs.length; i < len; i++) {
- var x = xs[i];
- if (pred(x, i)) {
- return Optional.some(x);
- } else if (until(x, i)) {
- break;
- }
- }
- return Optional.none();
- };
- var find$5 = function(xs, pred) {
- return findUntil(xs, pred, never);
- };
- var findIndex$1 = function(xs, pred) {
- for (var i = 0, len = xs.length; i < len; i++) {
- var x = xs[i];
- if (pred(x, i)) {
- return Optional.some(i);
- }
- }
- return Optional.none();
- };
- var flatten = function(xs) {
- var r2 = [];
- for (var i = 0, len = xs.length; i < len; ++i) {
- if (!isArray(xs[i])) {
- throw new Error("Arr.flatten item " + i + " was not an array, input: " + xs);
- }
- nativePush.apply(r2, xs[i]);
- }
- return r2;
- };
- var bind$3 = function(xs, f) {
- return flatten(map$2(xs, f));
- };
- var forall = function(xs, pred) {
- for (var i = 0, len = xs.length; i < len; ++i) {
- var x = xs[i];
- if (pred(x, i) !== true) {
- return false;
- }
- }
- return true;
- };
- var reverse = function(xs) {
- var r2 = nativeSlice.call(xs, 0);
- r2.reverse();
- return r2;
- };
- var difference = function(a1, a2) {
- return filter$2(a1, function(x) {
- return !contains$2(a2, x);
- });
- };
- var mapToObject = function(xs, f) {
- var r2 = {};
- for (var i = 0, len = xs.length; i < len; i++) {
- var x = xs[i];
- r2[String(x)] = f(x, i);
- }
- return r2;
- };
- var pure$2 = function(x) {
- return [x];
- };
- var sort = function(xs, comparator) {
- var copy = nativeSlice.call(xs, 0);
- copy.sort(comparator);
- return copy;
- };
- var get$f = function(xs, i) {
- return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
- };
- var head = function(xs) {
- return get$f(xs, 0);
- };
- var last$2 = function(xs) {
- return get$f(xs, xs.length - 1);
- };
- var from = isFunction(Array.from) ? Array.from : function(x) {
- return nativeSlice.call(x);
- };
- var findMap = function(arr, f) {
- for (var i = 0; i < arr.length; i++) {
- var r2 = f(arr[i], i);
- if (r2.isSome()) {
- return r2;
- }
- }
- return Optional.none();
- };
- var keys = Object.keys;
- var hasOwnProperty$1 = Object.hasOwnProperty;
- var each = function(obj, f) {
- var props = keys(obj);
- for (var k = 0, len = props.length; k < len; k++) {
- var i = props[k];
- var x = obj[i];
- f(x, i);
- }
- };
- var map$1 = function(obj, f) {
- return tupleMap(obj, function(x, i) {
- return {
- k: i,
- v: f(x, i)
- };
- });
- };
- var tupleMap = function(obj, f) {
- var r2 = {};
- each(obj, function(x, i) {
- var tuple = f(x, i);
- r2[tuple.k] = tuple.v;
- });
- return r2;
- };
- var objAcc = function(r2) {
- return function(x, i) {
- r2[i] = x;
- };
- };
- var internalFilter = function(obj, pred, onTrue, onFalse) {
- var r2 = {};
- each(obj, function(x, i) {
- (pred(x, i) ? onTrue : onFalse)(x, i);
- });
- return r2;
- };
- var filter$1 = function(obj, pred) {
- var t2 = {};
- internalFilter(obj, pred, objAcc(t2), noop);
- return t2;
- };
- var mapToArray = function(obj, f) {
- var r2 = [];
- each(obj, function(value2, name2) {
- r2.push(f(value2, name2));
- });
- return r2;
- };
- var find$4 = function(obj, pred) {
- var props = keys(obj);
- for (var k = 0, len = props.length; k < len; k++) {
- var i = props[k];
- var x = obj[i];
- if (pred(x, i, obj)) {
- return Optional.some(x);
- }
- }
- return Optional.none();
- };
- var values = function(obj) {
- return mapToArray(obj, identity$1);
- };
- var get$e = function(obj, key) {
- return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
- };
- var has$2 = function(obj, key) {
- return hasOwnProperty$1.call(obj, key);
- };
- var hasNonNullableKey = function(obj, key) {
- return has$2(obj, key) && obj[key] !== void 0 && obj[key] !== null;
- };
- var is$1 = function(lhs, rhs, comparator) {
- if (comparator === void 0) {
- comparator = tripleEquals;
- }
- return lhs.exists(function(left2) {
- return comparator(left2, rhs);
- });
- };
- var equals = function(lhs, rhs, comparator) {
- if (comparator === void 0) {
- comparator = tripleEquals;
- }
- return lift2(lhs, rhs, comparator).getOr(lhs.isNone() && rhs.isNone());
- };
- var cat = function(arr) {
- var r2 = [];
- var push = function(x) {
- r2.push(x);
- };
- for (var i = 0; i < arr.length; i++) {
- arr[i].each(push);
- }
- return r2;
- };
- var sequence = function(arr) {
- var r2 = [];
- for (var i = 0; i < arr.length; i++) {
- var x = arr[i];
- if (x.isSome()) {
- r2.push(x.getOrDie());
- } else {
- return Optional.none();
- }
- }
- return Optional.some(r2);
- };
- var lift2 = function(oa, ob, f) {
- return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
- };
- var lift3 = function(oa, ob, oc, f) {
- return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
- };
- var mapFrom = function(a, f) {
- return a !== void 0 && a !== null ? Optional.some(f(a)) : Optional.none();
- };
- var someIf = function(b2, a) {
- return b2 ? Optional.some(a) : Optional.none();
- };
- var addToEnd = function(str, suffix2) {
- return str + suffix2;
- };
- var removeFromStart = function(str, numChars) {
- return str.substring(numChars);
- };
- var checkRange = function(str, substr, start) {
- return substr === "" || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
- };
- var removeLeading = function(str, prefix2) {
- return startsWith(str, prefix2) ? removeFromStart(str, prefix2.length) : str;
- };
- var ensureTrailing = function(str, suffix2) {
- return endsWith(str, suffix2) ? str : addToEnd(str, suffix2);
- };
- var contains$1 = function(str, substr) {
- return str.indexOf(substr) !== -1;
- };
- var startsWith = function(str, prefix2) {
- return checkRange(str, prefix2, 0);
- };
- var endsWith = function(str, suffix2) {
- return checkRange(str, suffix2, str.length - suffix2.length);
- };
- var blank = function(r2) {
- return function(s) {
- return s.replace(r2, "");
- };
- };
- var trim$1 = blank(/^\s+|\s+$/g);
- var isNotEmpty = function(s) {
- return s.length > 0;
- };
- var isEmpty = function(s) {
- return !isNotEmpty(s);
- };
- var isSupported$1 = function(dom2) {
- return dom2.style !== void 0 && isFunction(dom2.style.getPropertyValue);
- };
- var fromHtml$2 = function(html2, scope) {
- var doc = scope || document;
- var div = doc.createElement("div");
- div.innerHTML = html2;
- if (!div.hasChildNodes() || div.childNodes.length > 1) {
- console.error("HTML does not have a single root node", html2);
- throw new Error("HTML must have a single root node");
- }
- return fromDom(div.childNodes[0]);
- };
- var fromTag = function(tag, scope) {
- var doc = scope || document;
- var node = doc.createElement(tag);
- return fromDom(node);
- };
- var fromText = function(text2, scope) {
- var doc = scope || document;
- var node = doc.createTextNode(text2);
- return fromDom(node);
- };
- var fromDom = function(node) {
- if (node === null || node === void 0) {
- throw new Error("Node cannot be null or undefined");
- }
- return { dom: node };
- };
- var fromPoint = function(docElm, x, y) {
- return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
- };
- var SugarElement = {
- fromHtml: fromHtml$2,
- fromTag,
- fromText,
- fromDom,
- fromPoint
- };
- typeof window !== "undefined" ? window : Function("return this;")();
- var DOCUMENT = 9;
- var DOCUMENT_FRAGMENT = 11;
- var ELEMENT = 1;
- var TEXT = 3;
- var name$2 = function(element2) {
- var r2 = element2.dom.nodeName;
- return r2.toLowerCase();
- };
- var type = function(element2) {
- return element2.dom.nodeType;
- };
- var isType = function(t2) {
- return function(element2) {
- return type(element2) === t2;
- };
- };
- var isElement$2 = isType(ELEMENT);
- var isText$1 = isType(TEXT);
- var isDocument = isType(DOCUMENT);
- var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
- var cached = function(f) {
- var called = false;
- var r2;
- return function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- if (!called) {
- called = true;
- r2 = f.apply(null, args);
- }
- return r2;
- };
- };
- var DeviceType = function(os, browser, userAgent, mediaMatch2) {
- var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
- var isiPhone = os.isiOS() && !isiPad;
- var isMobile = os.isiOS() || os.isAndroid();
- var isTouch2 = isMobile || mediaMatch2("(pointer:coarse)");
- var isTablet = isiPad || !isiPhone && isMobile && mediaMatch2("(min-device-width:768px)");
- var isPhone = isiPhone || isMobile && !isTablet;
- var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
- var isDesktop = !isPhone && !isTablet && !iOSwebview;
- return {
- isiPad: constant$1(isiPad),
- isiPhone: constant$1(isiPhone),
- isTablet: constant$1(isTablet),
- isPhone: constant$1(isPhone),
- isTouch: constant$1(isTouch2),
- isAndroid: os.isAndroid,
- isiOS: os.isiOS,
- isWebView: constant$1(iOSwebview),
- isDesktop: constant$1(isDesktop)
- };
- };
- var firstMatch = function(regexes, s) {
- for (var i = 0; i < regexes.length; i++) {
- var x = regexes[i];
- if (x.test(s)) {
- return x;
- }
- }
- return void 0;
- };
- var find$3 = function(regexes, agent) {
- var r2 = firstMatch(regexes, agent);
- if (!r2) {
- return {
- major: 0,
- minor: 0
- };
- }
- var group2 = function(i) {
- return Number(agent.replace(r2, "$" + i));
- };
- return nu$d(group2(1), group2(2));
- };
- var detect$4 = function(versionRegexes, agent) {
- var cleanedAgent = String(agent).toLowerCase();
- if (versionRegexes.length === 0) {
- return unknown$3();
- }
- return find$3(versionRegexes, cleanedAgent);
- };
- var unknown$3 = function() {
- return nu$d(0, 0);
- };
- var nu$d = function(major, minor) {
- return {
- major,
- minor
- };
- };
- var Version = {
- nu: nu$d,
- detect: detect$4,
- unknown: unknown$3
- };
- var detectBrowser$1 = function(browsers2, userAgentData) {
- return findMap(userAgentData.brands, function(uaBrand) {
- var lcBrand = uaBrand.brand.toLowerCase();
- return find$5(browsers2, function(browser) {
- var _a2;
- return lcBrand === ((_a2 = browser.brand) === null || _a2 === void 0 ? void 0 : _a2.toLowerCase());
- }).map(function(info) {
- return {
- current: info.name,
- version: Version.nu(parseInt(uaBrand.version, 10), 0)
- };
- });
- });
- };
- var detect$3 = function(candidates, userAgent) {
- var agent = String(userAgent).toLowerCase();
- return find$5(candidates, function(candidate) {
- return candidate.search(agent);
- });
- };
- var detectBrowser = function(browsers2, userAgent) {
- return detect$3(browsers2, userAgent).map(function(browser) {
- var version = Version.detect(browser.versionRegexes, userAgent);
- return {
- current: browser.name,
- version
- };
- });
- };
- var detectOs = function(oses2, userAgent) {
- return detect$3(oses2, userAgent).map(function(os) {
- var version = Version.detect(os.versionRegexes, userAgent);
- return {
- current: os.name,
- version
- };
- });
- };
- var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
- var checkContains = function(target) {
- return function(uastring) {
- return contains$1(uastring, target);
- };
- };
- var browsers = [
- {
- name: "Edge",
- versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
- search: function(uastring) {
- return contains$1(uastring, "edge/") && contains$1(uastring, "chrome") && contains$1(uastring, "safari") && contains$1(uastring, "applewebkit");
- }
- },
- {
- name: "Chrome",
- brand: "Chromium",
- versionRegexes: [
- /.*?chrome\/([0-9]+)\.([0-9]+).*/,
- normalVersionRegex
- ],
- search: function(uastring) {
- return contains$1(uastring, "chrome") && !contains$1(uastring, "chromeframe");
- }
- },
- {
- name: "IE",
- versionRegexes: [
- /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
- /.*?rv:([0-9]+)\.([0-9]+).*/
- ],
- search: function(uastring) {
- return contains$1(uastring, "msie") || contains$1(uastring, "trident");
- }
- },
- {
- name: "Opera",
- versionRegexes: [
- normalVersionRegex,
- /.*?opera\/([0-9]+)\.([0-9]+).*/
- ],
- search: checkContains("opera")
- },
- {
- name: "Firefox",
- versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
- search: checkContains("firefox")
- },
- {
- name: "Safari",
- versionRegexes: [
- normalVersionRegex,
- /.*?cpu os ([0-9]+)_([0-9]+).*/
- ],
- search: function(uastring) {
- return (contains$1(uastring, "safari") || contains$1(uastring, "mobile/")) && contains$1(uastring, "applewebkit");
- }
- }
- ];
- var oses = [
- {
- name: "Windows",
- search: checkContains("win"),
- versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
- },
- {
- name: "iOS",
- search: function(uastring) {
- return contains$1(uastring, "iphone") || contains$1(uastring, "ipad");
- },
- versionRegexes: [
- /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
- /.*cpu os ([0-9]+)_([0-9]+).*/,
- /.*cpu iphone os ([0-9]+)_([0-9]+).*/
- ]
- },
- {
- name: "Android",
- search: checkContains("android"),
- versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
- },
- {
- name: "OSX",
- search: checkContains("mac os x"),
- versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
- },
- {
- name: "Linux",
- search: checkContains("linux"),
- versionRegexes: []
- },
- {
- name: "Solaris",
- search: checkContains("sunos"),
- versionRegexes: []
- },
- {
- name: "FreeBSD",
- search: checkContains("freebsd"),
- versionRegexes: []
- },
- {
- name: "ChromeOS",
- search: checkContains("cros"),
- versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
- }
- ];
- var PlatformInfo = {
- browsers: constant$1(browsers),
- oses: constant$1(oses)
- };
- var edge = "Edge";
- var chrome = "Chrome";
- var ie = "IE";
- var opera = "Opera";
- var firefox = "Firefox";
- var safari = "Safari";
- var unknown$2 = function() {
- return nu$c({
- current: void 0,
- version: Version.unknown()
- });
- };
- var nu$c = function(info) {
- var current = info.current;
- var version = info.version;
- var isBrowser = function(name2) {
- return function() {
- return current === name2;
- };
- };
- return {
- current,
- version,
- isEdge: isBrowser(edge),
- isChrome: isBrowser(chrome),
- isIE: isBrowser(ie),
- isOpera: isBrowser(opera),
- isFirefox: isBrowser(firefox),
- isSafari: isBrowser(safari)
- };
- };
- var Browser = {
- unknown: unknown$2,
- nu: nu$c,
- edge: constant$1(edge),
- chrome: constant$1(chrome),
- ie: constant$1(ie),
- opera: constant$1(opera),
- firefox: constant$1(firefox),
- safari: constant$1(safari)
- };
- var windows = "Windows";
- var ios = "iOS";
- var android = "Android";
- var linux = "Linux";
- var osx = "OSX";
- var solaris = "Solaris";
- var freebsd = "FreeBSD";
- var chromeos = "ChromeOS";
- var unknown$1 = function() {
- return nu$b({
- current: void 0,
- version: Version.unknown()
- });
- };
- var nu$b = function(info) {
- var current = info.current;
- var version = info.version;
- var isOS = function(name2) {
- return function() {
- return current === name2;
- };
- };
- return {
- current,
- version,
- isWindows: isOS(windows),
- isiOS: isOS(ios),
- isAndroid: isOS(android),
- isOSX: isOS(osx),
- isLinux: isOS(linux),
- isSolaris: isOS(solaris),
- isFreeBSD: isOS(freebsd),
- isChromeOS: isOS(chromeos)
- };
- };
- var OperatingSystem = {
- unknown: unknown$1,
- nu: nu$b,
- windows: constant$1(windows),
- ios: constant$1(ios),
- android: constant$1(android),
- linux: constant$1(linux),
- osx: constant$1(osx),
- solaris: constant$1(solaris),
- freebsd: constant$1(freebsd),
- chromeos: constant$1(chromeos)
- };
- var detect$2 = function(userAgent, userAgentDataOpt, mediaMatch2) {
- var browsers2 = PlatformInfo.browsers();
- var oses2 = PlatformInfo.oses();
- var browser = userAgentDataOpt.bind(function(userAgentData) {
- return detectBrowser$1(browsers2, userAgentData);
- }).orThunk(function() {
- return detectBrowser(browsers2, userAgent);
- }).fold(Browser.unknown, Browser.nu);
- var os = detectOs(oses2, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
- var deviceType = DeviceType(os, browser, userAgent, mediaMatch2);
- return {
- browser,
- os,
- deviceType
- };
- };
- var PlatformDetection = { detect: detect$2 };
- var mediaMatch = function(query2) {
- return window.matchMedia(query2).matches;
- };
- var platform = cached(function() {
- return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
- });
- var detect$1 = function() {
- return platform();
- };
- var compareDocumentPosition = function(a, b2, match) {
- return (a.compareDocumentPosition(b2) & match) !== 0;
- };
- var documentPositionContainedBy = function(a, b2) {
- return compareDocumentPosition(a, b2, Node.DOCUMENT_POSITION_CONTAINED_BY);
- };
- var is = function(element2, selector) {
- var dom2 = element2.dom;
- if (dom2.nodeType !== ELEMENT) {
- return false;
- } else {
- var elem = dom2;
- if (elem.matches !== void 0) {
- return elem.matches(selector);
- } else if (elem.msMatchesSelector !== void 0) {
- return elem.msMatchesSelector(selector);
- } else if (elem.webkitMatchesSelector !== void 0) {
- return elem.webkitMatchesSelector(selector);
- } else if (elem.mozMatchesSelector !== void 0) {
- return elem.mozMatchesSelector(selector);
- } else {
- throw new Error("Browser lacks native selectors");
- }
- }
- };
- var bypassSelector = function(dom2) {
- return dom2.nodeType !== ELEMENT && dom2.nodeType !== DOCUMENT && dom2.nodeType !== DOCUMENT_FRAGMENT || dom2.childElementCount === 0;
- };
- var all$3 = function(selector, scope) {
- var base2 = scope === void 0 ? document : scope.dom;
- return bypassSelector(base2) ? [] : map$2(base2.querySelectorAll(selector), SugarElement.fromDom);
- };
- var one = function(selector, scope) {
- var base2 = scope === void 0 ? document : scope.dom;
- return bypassSelector(base2) ? Optional.none() : Optional.from(base2.querySelector(selector)).map(SugarElement.fromDom);
- };
- var eq = function(e1, e2) {
- return e1.dom === e2.dom;
- };
- var regularContains = function(e1, e2) {
- var d1 = e1.dom;
- var d2 = e2.dom;
- return d1 === d2 ? false : d1.contains(d2);
- };
- var ieContains = function(e1, e2) {
- return documentPositionContainedBy(e1.dom, e2.dom);
- };
- var contains = function(e1, e2) {
- return detect$1().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
- };
- var owner$4 = function(element2) {
- return SugarElement.fromDom(element2.dom.ownerDocument);
- };
- var documentOrOwner = function(dos) {
- return isDocument(dos) ? dos : owner$4(dos);
- };
- var documentElement = function(element2) {
- return SugarElement.fromDom(documentOrOwner(element2).dom.documentElement);
- };
- var defaultView = function(element2) {
- return SugarElement.fromDom(documentOrOwner(element2).dom.defaultView);
- };
- var parent = function(element2) {
- return Optional.from(element2.dom.parentNode).map(SugarElement.fromDom);
- };
- var parentNode = function(element2) {
- return parent(element2);
- };
- var offsetParent = function(element2) {
- return Optional.from(element2.dom.offsetParent).map(SugarElement.fromDom);
- };
- var nextSibling = function(element2) {
- return Optional.from(element2.dom.nextSibling).map(SugarElement.fromDom);
- };
- var children = function(element2) {
- return map$2(element2.dom.childNodes, SugarElement.fromDom);
- };
- var child$2 = function(element2, index) {
- var cs = element2.dom.childNodes;
- return Optional.from(cs[index]).map(SugarElement.fromDom);
- };
- var firstChild = function(element2) {
- return child$2(element2, 0);
- };
- var spot = function(element2, offset2) {
- return {
- element: element2,
- offset: offset2
- };
- };
- var leaf = function(element2, offset2) {
- var cs = children(element2);
- return cs.length > 0 && offset2 < cs.length ? spot(cs[offset2], 0) : spot(element2, offset2);
- };
- var isShadowRoot = function(dos) {
- return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
- };
- var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
- var isSupported = constant$1(supported);
- var getRootNode = supported ? function(e) {
- return SugarElement.fromDom(e.dom.getRootNode());
- } : documentOrOwner;
- var getContentContainer = function(dos) {
- return isShadowRoot(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body);
- };
- var isInShadowRoot = function(e) {
- return getShadowRoot(e).isSome();
- };
- var getShadowRoot = function(e) {
- var r2 = getRootNode(e);
- return isShadowRoot(r2) ? Optional.some(r2) : Optional.none();
- };
- var getShadowHost = function(e) {
- return SugarElement.fromDom(e.dom.host);
- };
- var getOriginalEventTarget = function(event) {
- if (isSupported() && isNonNullable(event.target)) {
- var el = SugarElement.fromDom(event.target);
- if (isElement$2(el) && isOpenShadowHost(el)) {
- if (event.composed && event.composedPath) {
- var composedPath = event.composedPath();
- if (composedPath) {
- return head(composedPath);
- }
- }
- }
- }
- return Optional.from(event.target);
- };
- var isOpenShadowHost = function(element2) {
- return isNonNullable(element2.dom.shadowRoot);
- };
- var inBody = function(element2) {
- var dom2 = isText$1(element2) ? element2.dom.parentNode : element2.dom;
- if (dom2 === void 0 || dom2 === null || dom2.ownerDocument === null) {
- return false;
- }
- var doc = dom2.ownerDocument;
- return getShadowRoot(SugarElement.fromDom(dom2)).fold(function() {
- return doc.body.contains(dom2);
- }, compose1(inBody, getShadowHost));
- };
- var body = function() {
- return getBody(SugarElement.fromDom(document));
- };
- var getBody = function(doc) {
- var b2 = doc.dom.body;
- if (b2 === null || b2 === void 0) {
- throw new Error("Body is not available yet");
- }
- return SugarElement.fromDom(b2);
- };
- var rawSet = function(dom2, key, value2) {
- if (isString(value2) || isBoolean(value2) || isNumber(value2)) {
- dom2.setAttribute(key, value2 + "");
- } else {
- console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value2, ":: Element ", dom2);
- throw new Error("Attribute value was not simple");
- }
- };
- var set$8 = function(element2, key, value2) {
- rawSet(element2.dom, key, value2);
- };
- var setAll$1 = function(element2, attrs) {
- var dom2 = element2.dom;
- each(attrs, function(v, k) {
- rawSet(dom2, k, v);
- });
- };
- var get$d = function(element2, key) {
- var v = element2.dom.getAttribute(key);
- return v === null ? void 0 : v;
- };
- var getOpt = function(element2, key) {
- return Optional.from(get$d(element2, key));
- };
- var has$1 = function(element2, key) {
- var dom2 = element2.dom;
- return dom2 && dom2.hasAttribute ? dom2.hasAttribute(key) : false;
- };
- var remove$7 = function(element2, key) {
- element2.dom.removeAttribute(key);
- };
- var internalSet = function(dom2, property, value2) {
- if (!isString(value2)) {
- console.error("Invalid call to CSS.set. Property ", property, ":: Value ", value2, ":: Element ", dom2);
- throw new Error("CSS value must be a string: " + value2);
- }
- if (isSupported$1(dom2)) {
- dom2.style.setProperty(property, value2);
- }
- };
- var internalRemove = function(dom2, property) {
- if (isSupported$1(dom2)) {
- dom2.style.removeProperty(property);
- }
- };
- var set$7 = function(element2, property, value2) {
- var dom2 = element2.dom;
- internalSet(dom2, property, value2);
- };
- var setAll = function(element2, css) {
- var dom2 = element2.dom;
- each(css, function(v, k) {
- internalSet(dom2, k, v);
- });
- };
- var setOptions = function(element2, css) {
- var dom2 = element2.dom;
- each(css, function(v, k) {
- v.fold(function() {
- internalRemove(dom2, k);
- }, function(value2) {
- internalSet(dom2, k, value2);
- });
- });
- };
- var get$c = function(element2, property) {
- var dom2 = element2.dom;
- var styles = window.getComputedStyle(dom2);
- var r2 = styles.getPropertyValue(property);
- return r2 === "" && !inBody(element2) ? getUnsafeProperty(dom2, property) : r2;
- };
- var getUnsafeProperty = function(dom2, property) {
- return isSupported$1(dom2) ? dom2.style.getPropertyValue(property) : "";
- };
- var getRaw = function(element2, property) {
- var dom2 = element2.dom;
- var raw = getUnsafeProperty(dom2, property);
- return Optional.from(raw).filter(function(r2) {
- return r2.length > 0;
- });
- };
- var getAllRaw = function(element2) {
- var css = {};
- var dom2 = element2.dom;
- if (isSupported$1(dom2)) {
- for (var i = 0; i < dom2.style.length; i++) {
- var ruleName = dom2.style.item(i);
- css[ruleName] = dom2.style[ruleName];
- }
- }
- return css;
- };
- var isValidValue = function(tag, property, value2) {
- var element2 = SugarElement.fromTag(tag);
- set$7(element2, property, value2);
- var style = getRaw(element2, property);
- return style.isSome();
- };
- var remove$6 = function(element2, property) {
- var dom2 = element2.dom;
- internalRemove(dom2, property);
- if (is$1(getOpt(element2, "style").map(trim$1), "")) {
- remove$7(element2, "style");
- }
- };
- var reflow = function(e) {
- return e.dom.offsetWidth;
- };
- var Dimension = function(name2, getOffset2) {
- var set2 = function(element2, h) {
- if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
- throw new Error(name2 + ".set accepts only positive integer values. Value was " + h);
- }
- var dom2 = element2.dom;
- if (isSupported$1(dom2)) {
- dom2.style[name2] = h + "px";
- }
- };
- var get2 = function(element2) {
- var r2 = getOffset2(element2);
- if (r2 <= 0 || r2 === null) {
- var css = get$c(element2, name2);
- return parseFloat(css) || 0;
- }
- return r2;
- };
- var getOuter2 = get2;
- var aggregate = function(element2, properties2) {
- return foldl(properties2, function(acc, property) {
- var val = get$c(element2, property);
- var value2 = val === void 0 ? 0 : parseInt(val, 10);
- return isNaN(value2) ? acc : acc + value2;
- }, 0);
- };
- var max2 = function(element2, value2, properties2) {
- var cumulativeInclusions = aggregate(element2, properties2);
- var absoluteMax = value2 > cumulativeInclusions ? value2 - cumulativeInclusions : 0;
- return absoluteMax;
- };
- return {
- set: set2,
- get: get2,
- getOuter: getOuter2,
- aggregate,
- max: max2
- };
- };
- var api$3 = Dimension("height", function(element2) {
- var dom2 = element2.dom;
- return inBody(element2) ? dom2.getBoundingClientRect().height : dom2.offsetHeight;
- });
- var get$b = function(element2) {
- return api$3.get(element2);
- };
- var getOuter$2 = function(element2) {
- return api$3.getOuter(element2);
- };
- var setMax$1 = function(element2, value2) {
- var inclusions = [
- "margin-top",
- "border-top-width",
- "padding-top",
- "padding-bottom",
- "border-bottom-width",
- "margin-bottom"
- ];
- var absMax = api$3.max(element2, value2, inclusions);
- set$7(element2, "max-height", absMax + "px");
- };
- var r$1 = function(left2, top2) {
- var translate2 = function(x, y) {
- return r$1(left2 + x, top2 + y);
- };
- return {
- left: left2,
- top: top2,
- translate: translate2
- };
- };
- var SugarPosition = r$1;
- var boxPosition = function(dom2) {
- var box2 = dom2.getBoundingClientRect();
- return SugarPosition(box2.left, box2.top);
- };
- var firstDefinedOrZero = function(a, b2) {
- if (a !== void 0) {
- return a;
- } else {
- return b2 !== void 0 ? b2 : 0;
- }
- };
- var absolute$3 = function(element2) {
- var doc = element2.dom.ownerDocument;
- var body2 = doc.body;
- var win2 = doc.defaultView;
- var html2 = doc.documentElement;
- if (body2 === element2.dom) {
- return SugarPosition(body2.offsetLeft, body2.offsetTop);
- }
- var scrollTop = firstDefinedOrZero(win2 === null || win2 === void 0 ? void 0 : win2.pageYOffset, html2.scrollTop);
- var scrollLeft = firstDefinedOrZero(win2 === null || win2 === void 0 ? void 0 : win2.pageXOffset, html2.scrollLeft);
- var clientTop = firstDefinedOrZero(html2.clientTop, body2.clientTop);
- var clientLeft = firstDefinedOrZero(html2.clientLeft, body2.clientLeft);
- return viewport$1(element2).translate(scrollLeft - clientLeft, scrollTop - clientTop);
- };
- var viewport$1 = function(element2) {
- var dom2 = element2.dom;
- var doc = dom2.ownerDocument;
- var body2 = doc.body;
- if (body2 === dom2) {
- return SugarPosition(body2.offsetLeft, body2.offsetTop);
- }
- if (!inBody(element2)) {
- return SugarPosition(0, 0);
- }
- return boxPosition(dom2);
- };
- var api$2 = Dimension("width", function(element2) {
- return element2.dom.offsetWidth;
- });
- var set$6 = function(element2, h) {
- return api$2.set(element2, h);
- };
- var get$a = function(element2) {
- return api$2.get(element2);
- };
- var getOuter$1 = function(element2) {
- return api$2.getOuter(element2);
- };
- var setMax = function(element2, value2) {
- var inclusions = [
- "margin-left",
- "border-left-width",
- "padding-left",
- "padding-right",
- "border-right-width",
- "margin-right"
- ];
- var absMax = api$2.max(element2, value2, inclusions);
- set$7(element2, "max-width", absMax + "px");
- };
- var mkEvent = function(target, x, y, stop2, prevent, kill, raw) {
- return {
- target,
- x,
- y,
- stop: stop2,
- prevent,
- kill,
- raw
- };
- };
- var fromRawEvent$1 = function(rawEvent) {
- var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
- var stop2 = function() {
- return rawEvent.stopPropagation();
- };
- var prevent = function() {
- return rawEvent.preventDefault();
- };
- var kill = compose(prevent, stop2);
- return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop2, prevent, kill, rawEvent);
- };
- var handle = function(filter2, handler) {
- return function(rawEvent) {
- if (filter2(rawEvent)) {
- handler(fromRawEvent$1(rawEvent));
- }
- };
- };
- var binder = function(element2, event, filter2, handler, useCapture) {
- var wrapped = handle(filter2, handler);
- element2.dom.addEventListener(event, wrapped, useCapture);
- return { unbind: curry(unbind, element2, event, wrapped, useCapture) };
- };
- var bind$2 = function(element2, event, filter2, handler) {
- return binder(element2, event, filter2, handler, false);
- };
- var capture$1 = function(element2, event, filter2, handler) {
- return binder(element2, event, filter2, handler, true);
- };
- var unbind = function(element2, event, handler, useCapture) {
- element2.dom.removeEventListener(event, handler, useCapture);
- };
- var before$2 = function(marker, element2) {
- var parent$1 = parent(marker);
- parent$1.each(function(v) {
- v.dom.insertBefore(element2.dom, marker.dom);
- });
- };
- var after$2 = function(marker, element2) {
- var sibling = nextSibling(marker);
- sibling.fold(function() {
- var parent$1 = parent(marker);
- parent$1.each(function(v) {
- append$2(v, element2);
- });
- }, function(v) {
- before$2(v, element2);
- });
- };
- var prepend$1 = function(parent2, element2) {
- var firstChild$1 = firstChild(parent2);
- firstChild$1.fold(function() {
- append$2(parent2, element2);
- }, function(v) {
- parent2.dom.insertBefore(element2.dom, v.dom);
- });
- };
- var append$2 = function(parent2, element2) {
- parent2.dom.appendChild(element2.dom);
- };
- var appendAt = function(parent2, element2, index) {
- child$2(parent2, index).fold(function() {
- append$2(parent2, element2);
- }, function(v) {
- before$2(v, element2);
- });
- };
- var before$1 = function(marker, elements) {
- each$1(elements, function(x) {
- before$2(marker, x);
- });
- };
- var append$1 = function(parent2, elements) {
- each$1(elements, function(x) {
- append$2(parent2, x);
- });
- };
- var empty = function(element2) {
- element2.dom.textContent = "";
- each$1(children(element2), function(rogue) {
- remove$5(rogue);
- });
- };
- var remove$5 = function(element2) {
- var dom2 = element2.dom;
- if (dom2.parentNode !== null) {
- dom2.parentNode.removeChild(dom2);
- }
- };
- var unwrap = function(wrapper) {
- var children$1 = children(wrapper);
- if (children$1.length > 0) {
- before$1(wrapper, children$1);
- }
- remove$5(wrapper);
- };
- var get$9 = function(_DOC) {
- var doc = _DOC !== void 0 ? _DOC.dom : document;
- var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
- var y = doc.body.scrollTop || doc.documentElement.scrollTop;
- return SugarPosition(x, y);
- };
- var to = function(x, y, _DOC) {
- var doc = _DOC !== void 0 ? _DOC.dom : document;
- var win2 = doc.defaultView;
- if (win2) {
- win2.scrollTo(x, y);
- }
- };
- var get$8 = function(_win) {
- var win2 = _win === void 0 ? window : _win;
- if (detect$1().browser.isFirefox()) {
- return Optional.none();
- } else {
- return Optional.from(win2["visualViewport"]);
- }
- };
- var bounds$1 = function(x, y, width2, height2) {
- return {
- x,
- y,
- width: width2,
- height: height2,
- right: x + width2,
- bottom: y + height2
- };
- };
- var getBounds$3 = function(_win) {
- var win2 = _win === void 0 ? window : _win;
- var doc = win2.document;
- var scroll = get$9(SugarElement.fromDom(doc));
- return get$8(win2).fold(function() {
- var html2 = win2.document.documentElement;
- var width2 = html2.clientWidth;
- var height2 = html2.clientHeight;
- return bounds$1(scroll.left, scroll.top, width2, height2);
- }, function(visualViewport) {
- return bounds$1(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
- });
- };
- var walkUp = function(navigation, doc) {
- var frame = navigation.view(doc);
- return frame.fold(constant$1([]), function(f) {
- var parent2 = navigation.owner(f);
- var rest = walkUp(navigation, parent2);
- return [f].concat(rest);
- });
- };
- var pathTo = function(element2, navigation) {
- var d = navigation.owner(element2);
- var paths = walkUp(navigation, d);
- return Optional.some(paths);
- };
- var view = function(doc) {
- var _a2;
- var element2 = doc.dom === document ? Optional.none() : Optional.from((_a2 = doc.dom.defaultView) === null || _a2 === void 0 ? void 0 : _a2.frameElement);
- return element2.map(SugarElement.fromDom);
- };
- var owner$3 = function(element2) {
- return owner$4(element2);
- };
- var Navigation = Object.freeze({
- __proto__: null,
- view,
- owner: owner$3
- });
- var find$2 = function(element2) {
- var doc = SugarElement.fromDom(document);
- var scroll = get$9(doc);
- var path2 = pathTo(element2, Navigation);
- return path2.fold(curry(absolute$3, element2), function(frames) {
- var offset2 = viewport$1(element2);
- var r2 = foldr(frames, function(b2, a) {
- var loc = viewport$1(a);
- return {
- left: b2.left + loc.left,
- top: b2.top + loc.top
- };
- }, {
- left: 0,
- top: 0
- });
- return SugarPosition(r2.left + offset2.left + scroll.left, r2.top + offset2.top + scroll.top);
- });
- };
- var pointed = function(point2, width2, height2) {
- return {
- point: point2,
- width: width2,
- height: height2
- };
- };
- var rect = function(x, y, width2, height2) {
- return {
- x,
- y,
- width: width2,
- height: height2
- };
- };
- var bounds = function(x, y, width2, height2) {
- return {
- x,
- y,
- width: width2,
- height: height2,
- right: x + width2,
- bottom: y + height2
- };
- };
- var box$1 = function(element2) {
- var xy = absolute$3(element2);
- var w = getOuter$1(element2);
- var h = getOuter$2(element2);
- return bounds(xy.left, xy.top, w, h);
- };
- var absolute$2 = function(element2) {
- var position2 = find$2(element2);
- var width2 = getOuter$1(element2);
- var height2 = getOuter$2(element2);
- return bounds(position2.left, position2.top, width2, height2);
- };
- var win = function() {
- return getBounds$3(window);
- };
- var value$3 = function(o) {
- var or = function(_opt) {
- return value$3(o);
- };
- var orThunk = function(_f) {
- return value$3(o);
- };
- var map2 = function(f) {
- return value$3(f(o));
- };
- var mapError2 = function(_f) {
- return value$3(o);
- };
- var each2 = function(f) {
- f(o);
- };
- var bind2 = function(f) {
- return f(o);
- };
- var fold2 = function(_, onValue) {
- return onValue(o);
- };
- var exists2 = function(f) {
- return f(o);
- };
- var forall2 = function(f) {
- return f(o);
- };
- var toOptional = function() {
- return Optional.some(o);
- };
- return {
- isValue: always,
- isError: never,
- getOr: constant$1(o),
- getOrThunk: constant$1(o),
- getOrDie: constant$1(o),
- or,
- orThunk,
- fold: fold2,
- map: map2,
- mapError: mapError2,
- each: each2,
- bind: bind2,
- exists: exists2,
- forall: forall2,
- toOptional
- };
- };
- var error$1 = function(message) {
- var getOrThunk = function(f) {
- return f();
- };
- var getOrDie2 = function() {
- return die(String(message))();
- };
- var or = identity$1;
- var orThunk = function(f) {
- return f();
- };
- var map2 = function(_f) {
- return error$1(message);
- };
- var mapError2 = function(f) {
- return error$1(f(message));
- };
- var bind2 = function(_f) {
- return error$1(message);
- };
- var fold2 = function(onError, _) {
- return onError(message);
- };
- return {
- isValue: never,
- isError: always,
- getOr: identity$1,
- getOrThunk,
- getOrDie: getOrDie2,
- or,
- orThunk,
- fold: fold2,
- map: map2,
- mapError: mapError2,
- each: noop,
- bind: bind2,
- exists: never,
- forall: always,
- toOptional: Optional.none
- };
- };
- var fromOption = function(opt, err) {
- return opt.fold(function() {
- return error$1(err);
- }, value$3);
- };
- var Result = {
- value: value$3,
- error: error$1,
- fromOption
- };
- var SimpleResultType;
- (function(SimpleResultType2) {
- SimpleResultType2[SimpleResultType2["Error"] = 0] = "Error";
- SimpleResultType2[SimpleResultType2["Value"] = 1] = "Value";
- })(SimpleResultType || (SimpleResultType = {}));
- var fold$1 = function(res, onError, onValue) {
- return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
- };
- var partition$2 = function(results) {
- var values2 = [];
- var errors = [];
- each$1(results, function(obj) {
- fold$1(obj, function(err) {
- return errors.push(err);
- }, function(val) {
- return values2.push(val);
- });
- });
- return {
- values: values2,
- errors
- };
- };
- var mapError = function(res, f) {
- if (res.stype === SimpleResultType.Error) {
- return {
- stype: SimpleResultType.Error,
- serror: f(res.serror)
- };
- } else {
- return res;
- }
- };
- var map = function(res, f) {
- if (res.stype === SimpleResultType.Value) {
- return {
- stype: SimpleResultType.Value,
- svalue: f(res.svalue)
- };
- } else {
- return res;
- }
- };
- var bind$1 = function(res, f) {
- if (res.stype === SimpleResultType.Value) {
- return f(res.svalue);
- } else {
- return res;
- }
- };
- var bindError = function(res, f) {
- if (res.stype === SimpleResultType.Error) {
- return f(res.serror);
- } else {
- return res;
- }
- };
- var svalue = function(v) {
- return {
- stype: SimpleResultType.Value,
- svalue: v
- };
- };
- var serror = function(e) {
- return {
- stype: SimpleResultType.Error,
- serror: e
- };
- };
- var toResult$1 = function(res) {
- return fold$1(res, Result.error, Result.value);
- };
- var fromResult$1 = function(res) {
- return res.fold(serror, svalue);
- };
- var SimpleResult = {
- fromResult: fromResult$1,
- toResult: toResult$1,
- svalue,
- partition: partition$2,
- serror,
- bind: bind$1,
- bindError,
- map,
- mapError,
- fold: fold$1
- };
- var field$2 = function(key, newKey, presence, prop) {
- return {
- tag: "field",
- key,
- newKey,
- presence,
- prop
- };
- };
- var customField$1 = function(newKey, instantiator) {
- return {
- tag: "custom",
- newKey,
- instantiator
- };
- };
- var fold = function(value2, ifField, ifCustom) {
- switch (value2.tag) {
- case "field":
- return ifField(value2.key, value2.newKey, value2.presence, value2.prop);
- case "custom":
- return ifCustom(value2.newKey, value2.instantiator);
- }
- };
- var shallow$1 = function(old, nu2) {
- return nu2;
- };
- var deep = function(old, nu2) {
- var bothObjects = isObject(old) && isObject(nu2);
- return bothObjects ? deepMerge(old, nu2) : nu2;
- };
- var baseMerge = function(merger) {
- return function() {
- var objects = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- objects[_i] = arguments[_i];
- }
- if (objects.length === 0) {
- throw new Error("Can't merge zero objects");
- }
- var ret = {};
- for (var j = 0; j < objects.length; j++) {
- var curObject = objects[j];
- for (var key in curObject) {
- if (has$2(curObject, key)) {
- ret[key] = merger(ret[key], curObject[key]);
- }
- }
- }
- return ret;
- };
- };
- var deepMerge = baseMerge(deep);
- var merge$1 = baseMerge(shallow$1);
- var required$2 = function() {
- return {
- tag: "required",
- process: {}
- };
- };
- var defaultedThunk = function(fallbackThunk) {
- return {
- tag: "defaultedThunk",
- process: fallbackThunk
- };
- };
- var defaulted$1 = function(fallback2) {
- return defaultedThunk(constant$1(fallback2));
- };
- var asOption = function() {
- return {
- tag: "option",
- process: {}
- };
- };
- var mergeWithThunk = function(baseThunk) {
- return {
- tag: "mergeWithThunk",
- process: baseThunk
- };
- };
- var mergeWith = function(base2) {
- return mergeWithThunk(constant$1(base2));
- };
- var mergeValues$1 = function(values2, base2) {
- return values2.length > 0 ? SimpleResult.svalue(deepMerge(base2, merge$1.apply(void 0, values2))) : SimpleResult.svalue(base2);
- };
- var mergeErrors$1 = function(errors) {
- return compose(SimpleResult.serror, flatten)(errors);
- };
- var consolidateObj = function(objects, base2) {
- var partition2 = SimpleResult.partition(objects);
- return partition2.errors.length > 0 ? mergeErrors$1(partition2.errors) : mergeValues$1(partition2.values, base2);
- };
- var consolidateArr = function(objects) {
- var partitions = SimpleResult.partition(objects);
- return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
- };
- var ResultCombine = {
- consolidateObj,
- consolidateArr
- };
- var formatObj = function(input2) {
- return isObject(input2) && keys(input2).length > 100 ? " removed due to size" : JSON.stringify(input2, null, 2);
- };
- var formatErrors = function(errors) {
- var es = errors.length > 10 ? errors.slice(0, 10).concat([{
- path: [],
- getErrorInfo: constant$1("... (only showing first ten failures)")
- }]) : errors;
- return map$2(es, function(e) {
- return "Failed path: (" + e.path.join(" > ") + ")\n" + e.getErrorInfo();
- });
- };
- var nu$a = function(path2, getErrorInfo) {
- return SimpleResult.serror([{
- path: path2,
- getErrorInfo
- }]);
- };
- var missingRequired = function(path2, key, obj) {
- return nu$a(path2, function() {
- return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj);
- });
- };
- var missingKey = function(path2, key) {
- return nu$a(path2, function() {
- return 'Choice schema did not contain choice key: "' + key + '"';
- });
- };
- var missingBranch = function(path2, branches, branch) {
- return nu$a(path2, function() {
- return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
- });
- };
- var unsupportedFields = function(path2, unsupported) {
- return nu$a(path2, function() {
- return "There are unsupported fields: [" + unsupported.join(", ") + "] specified";
- });
- };
- var custom = function(path2, err) {
- return nu$a(path2, constant$1(err));
- };
- var value$2 = function(validator) {
- var extract2 = function(path2, val) {
- return SimpleResult.bindError(validator(val), function(err) {
- return custom(path2, err);
- });
- };
- var toString2 = constant$1("val");
- return {
- extract: extract2,
- toString: toString2
- };
- };
- var anyValue$1 = value$2(SimpleResult.svalue);
- var requiredAccess = function(path2, obj, key, bundle) {
- return get$e(obj, key).fold(function() {
- return missingRequired(path2, key, obj);
- }, bundle);
- };
- var fallbackAccess = function(obj, key, fallback2, bundle) {
- var v = get$e(obj, key).getOrThunk(function() {
- return fallback2(obj);
- });
- return bundle(v);
- };
- var optionAccess = function(obj, key, bundle) {
- return bundle(get$e(obj, key));
- };
- var optionDefaultedAccess = function(obj, key, fallback2, bundle) {
- var opt = get$e(obj, key).map(function(val) {
- return val === true ? fallback2(obj) : val;
- });
- return bundle(opt);
- };
- var extractField = function(field2, path2, obj, key, prop) {
- var bundle = function(av) {
- return prop.extract(path2.concat([key]), av);
- };
- var bundleAsOption = function(optValue) {
- return optValue.fold(function() {
- return SimpleResult.svalue(Optional.none());
- }, function(ov) {
- var result = prop.extract(path2.concat([key]), ov);
- return SimpleResult.map(result, Optional.some);
- });
- };
- switch (field2.tag) {
- case "required":
- return requiredAccess(path2, obj, key, bundle);
- case "defaultedThunk":
- return fallbackAccess(obj, key, field2.process, bundle);
- case "option":
- return optionAccess(obj, key, bundleAsOption);
- case "defaultedOptionThunk":
- return optionDefaultedAccess(obj, key, field2.process, bundleAsOption);
- case "mergeWithThunk": {
- return fallbackAccess(obj, key, constant$1({}), function(v) {
- var result = deepMerge(field2.process(obj), v);
- return bundle(result);
- });
- }
- }
- };
- var extractFields = function(path2, obj, fields) {
- var success = {};
- var errors = [];
- for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
- var field2 = fields_1[_i];
- fold(field2, function(key, newKey, presence, prop) {
- var result = extractField(presence, path2, obj, key, prop);
- SimpleResult.fold(result, function(err) {
- errors.push.apply(errors, err);
- }, function(res) {
- success[newKey] = res;
- });
- }, function(newKey, instantiator) {
- success[newKey] = instantiator(obj);
- });
- }
- return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
- };
- var valueThunk = function(getDelegate) {
- var extract2 = function(path2, val) {
- return getDelegate().extract(path2, val);
- };
- var toString2 = function() {
- return getDelegate().toString();
- };
- return {
- extract: extract2,
- toString: toString2
- };
- };
- var getSetKeys = function(obj) {
- return keys(filter$1(obj, isNonNullable));
- };
- var objOfOnly = function(fields) {
- var delegate = objOf(fields);
- var fieldNames = foldr(fields, function(acc, value2) {
- return fold(value2, function(key) {
- var _a2;
- return deepMerge(acc, (_a2 = {}, _a2[key] = true, _a2));
- }, constant$1(acc));
- }, {});
- var extract2 = function(path2, o) {
- var keys2 = isBoolean(o) ? [] : getSetKeys(o);
- var extra = filter$2(keys2, function(k) {
- return !hasNonNullableKey(fieldNames, k);
- });
- return extra.length === 0 ? delegate.extract(path2, o) : unsupportedFields(path2, extra);
- };
- return {
- extract: extract2,
- toString: delegate.toString
- };
- };
- var objOf = function(values2) {
- var extract2 = function(path2, o) {
- return extractFields(path2, o, values2);
- };
- var toString2 = function() {
- var fieldStrings = map$2(values2, function(value2) {
- return fold(value2, function(key, _okey, _presence, prop) {
- return key + " -> " + prop.toString();
- }, function(newKey, _instantiator) {
- return "state(" + newKey + ")";
- });
- });
- return "obj{\n" + fieldStrings.join("\n") + "}";
- };
- return {
- extract: extract2,
- toString: toString2
- };
- };
- var arrOf = function(prop) {
- var extract2 = function(path2, array) {
- var results = map$2(array, function(a, i) {
- return prop.extract(path2.concat(["[" + i + "]"]), a);
- });
- return ResultCombine.consolidateArr(results);
- };
- var toString2 = function() {
- return "array(" + prop.toString() + ")";
- };
- return {
- extract: extract2,
- toString: toString2
- };
- };
- var oneOf = function(props) {
- var extract2 = function(path2, val) {
- var errors = [];
- for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
- var prop = props_1[_i];
- var res = prop.extract(path2, val);
- if (res.stype === SimpleResultType.Value) {
- return res;
- }
- errors.push(res);
- }
- return ResultCombine.consolidateArr(errors);
- };
- var toString2 = function() {
- return "oneOf(" + map$2(props, function(prop) {
- return prop.toString();
- }).join(", ") + ")";
- };
- return {
- extract: extract2,
- toString: toString2
- };
- };
- var setOf$1 = function(validator, prop) {
- var validateKeys = function(path2, keys2) {
- return arrOf(value$2(validator)).extract(path2, keys2);
- };
- var extract2 = function(path2, o) {
- var keys$1 = keys(o);
- var validatedKeys = validateKeys(path2, keys$1);
- return SimpleResult.bind(validatedKeys, function(validKeys) {
- var schema2 = map$2(validKeys, function(vk) {
- return field$2(vk, vk, required$2(), prop);
- });
- return objOf(schema2).extract(path2, o);
- });
- };
- var toString2 = function() {
- return "setOf(" + prop.toString() + ")";
- };
- return {
- extract: extract2,
- toString: toString2
- };
- };
- var thunk = function(_desc, processor) {
- var getP = cached(processor);
- var extract2 = function(path2, val) {
- return getP().extract(path2, val);
- };
- var toString2 = function() {
- return getP().toString();
- };
- return {
- extract: extract2,
- toString: toString2
- };
- };
- var arrOfObj = compose(arrOf, objOf);
- var anyValue = constant$1(anyValue$1);
- var typedValue = function(validator, expectedType) {
- return value$2(function(a) {
- var actualType = typeof a;
- return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror("Expected type: " + expectedType + " but got: " + actualType);
- });
- };
- var number = typedValue(isNumber, "number");
- var string = typedValue(isString, "string");
- var boolean = typedValue(isBoolean, "boolean");
- var functionProcessor = typedValue(isFunction, "function");
- var isPostMessageable = function(val) {
- if (Object(val) !== val) {
- return true;
- }
- switch ({}.toString.call(val).slice(8, -1)) {
- case "Boolean":
- case "Number":
- case "String":
- case "Date":
- case "RegExp":
- case "Blob":
- case "FileList":
- case "ImageData":
- case "ImageBitmap":
- case "ArrayBuffer":
- return true;
- case "Array":
- case "Object":
- return Object.keys(val).every(function(prop) {
- return isPostMessageable(val[prop]);
- });
- default:
- return false;
- }
- };
- var postMessageable = value$2(function(a) {
- if (isPostMessageable(a)) {
- return SimpleResult.svalue(a);
- } else {
- return SimpleResult.serror("Expected value to be acceptable for sending via postMessage");
- }
- });
- var chooseFrom = function(path2, input2, branches, ch) {
- var fields = get$e(branches, ch);
- return fields.fold(function() {
- return missingBranch(path2, branches, ch);
- }, function(vp) {
- return vp.extract(path2.concat(["branch: " + ch]), input2);
- });
- };
- var choose$2 = function(key, branches) {
- var extract2 = function(path2, input2) {
- var choice = get$e(input2, key);
- return choice.fold(function() {
- return missingKey(path2, key);
- }, function(chosen) {
- return chooseFrom(path2, input2, branches, chosen);
- });
- };
- var toString2 = function() {
- return "chooseOn(" + key + "). Possible values: " + keys(branches);
- };
- return {
- extract: extract2,
- toString: toString2
- };
- };
- var arrOfVal = function() {
- return arrOf(anyValue$1);
- };
- var valueOf = function(validator) {
- return value$2(function(v) {
- return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
- });
- };
- var setOf = function(validator, prop) {
- return setOf$1(function(v) {
- return SimpleResult.fromResult(validator(v));
- }, prop);
- };
- var extractValue = function(label, prop, obj) {
- var res = prop.extract([label], obj);
- return SimpleResult.mapError(res, function(errs) {
- return {
- input: obj,
- errors: errs
- };
- });
- };
- var asRaw = function(label, prop, obj) {
- return SimpleResult.toResult(extractValue(label, prop, obj));
- };
- var getOrDie = function(extraction) {
- return extraction.fold(function(errInfo) {
- throw new Error(formatError(errInfo));
- }, identity$1);
- };
- var asRawOrDie$1 = function(label, prop, obj) {
- return getOrDie(asRaw(label, prop, obj));
- };
- var formatError = function(errInfo) {
- return "Errors: \n" + formatErrors(errInfo.errors).join("\n") + "\n\nInput object: " + formatObj(errInfo.input);
- };
- var choose$1 = function(key, branches) {
- return choose$2(key, map$1(branches, objOf));
- };
- var thunkOf = function(desc, schema2) {
- return thunk(desc, schema2);
- };
- var field$1 = field$2;
- var customField = customField$1;
- var validateEnum = function(values2) {
- return valueOf(function(value2) {
- return contains$2(values2, value2) ? Result.value(value2) : Result.error('Unsupported value: "' + value2 + '", choose one of "' + values2.join(", ") + '".');
- });
- };
- var required$1 = function(key) {
- return field$1(key, key, required$2(), anyValue());
- };
- var requiredOf = function(key, schema2) {
- return field$1(key, key, required$2(), schema2);
- };
- var requiredNumber = function(key) {
- return requiredOf(key, number);
- };
- var requiredString = function(key) {
- return requiredOf(key, string);
- };
- var requiredStringEnum = function(key, values2) {
- return field$1(key, key, required$2(), validateEnum(values2));
- };
- var requiredBoolean = function(key) {
- return requiredOf(key, boolean);
- };
- var requiredFunction = function(key) {
- return requiredOf(key, functionProcessor);
- };
- var forbid = function(key, message) {
- return field$1(key, key, asOption(), value$2(function(_v) {
- return SimpleResult.serror("The field: " + key + " is forbidden. " + message);
- }));
- };
- var requiredObjOf = function(key, objSchema) {
- return field$1(key, key, required$2(), objOf(objSchema));
- };
- var requiredArrayOfObj = function(key, objFields) {
- return field$1(key, key, required$2(), arrOfObj(objFields));
- };
- var requiredArrayOf = function(key, schema2) {
- return field$1(key, key, required$2(), arrOf(schema2));
- };
- var option = function(key) {
- return field$1(key, key, asOption(), anyValue());
- };
- var optionOf = function(key, schema2) {
- return field$1(key, key, asOption(), schema2);
- };
- var optionNumber = function(key) {
- return optionOf(key, number);
- };
- var optionString = function(key) {
- return optionOf(key, string);
- };
- var optionFunction = function(key) {
- return optionOf(key, functionProcessor);
- };
- var optionArrayOf = function(key, schema2) {
- return optionOf(key, arrOf(schema2));
- };
- var optionObjOf = function(key, objSchema) {
- return optionOf(key, objOf(objSchema));
- };
- var optionObjOfOnly = function(key, objSchema) {
- return optionOf(key, objOfOnly(objSchema));
- };
- var defaulted = function(key, fallback2) {
- return field$1(key, key, defaulted$1(fallback2), anyValue());
- };
- var defaultedOf = function(key, fallback2, schema2) {
- return field$1(key, key, defaulted$1(fallback2), schema2);
- };
- var defaultedNumber = function(key, fallback2) {
- return defaultedOf(key, fallback2, number);
- };
- var defaultedString = function(key, fallback2) {
- return defaultedOf(key, fallback2, string);
- };
- var defaultedStringEnum = function(key, fallback2, values2) {
- return defaultedOf(key, fallback2, validateEnum(values2));
- };
- var defaultedBoolean = function(key, fallback2) {
- return defaultedOf(key, fallback2, boolean);
- };
- var defaultedFunction = function(key, fallback2) {
- return defaultedOf(key, fallback2, functionProcessor);
- };
- var defaultedPostMsg = function(key, fallback2) {
- return defaultedOf(key, fallback2, postMessageable);
- };
- var defaultedArrayOf = function(key, fallback2, schema2) {
- return defaultedOf(key, fallback2, arrOf(schema2));
- };
- var defaultedObjOf = function(key, fallback2, objSchema) {
- return defaultedOf(key, fallback2, objOf(objSchema));
- };
- var Cell = function(initial) {
- var value2 = initial;
- var get2 = function() {
- return value2;
- };
- var set2 = function(v) {
- value2 = v;
- };
- return {
- get: get2,
- set: set2
- };
- };
- var generate$7 = function(cases) {
- if (!isArray(cases)) {
- throw new Error("cases must be an array");
- }
- if (cases.length === 0) {
- throw new Error("there must be at least one case");
- }
- var constructors = [];
- var adt2 = {};
- each$1(cases, function(acase, count2) {
- var keys$1 = keys(acase);
- if (keys$1.length !== 1) {
- throw new Error("one and only one name per case");
- }
- var key = keys$1[0];
- var value2 = acase[key];
- if (adt2[key] !== void 0) {
- throw new Error("duplicate key detected:" + key);
- } else if (key === "cata") {
- throw new Error("cannot have a case named cata (sorry)");
- } else if (!isArray(value2)) {
- throw new Error("case arguments must be an array");
- }
- constructors.push(key);
- adt2[key] = function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var argLength = args.length;
- if (argLength !== value2.length) {
- throw new Error("Wrong number of arguments to case " + key + ". Expected " + value2.length + " (" + value2 + "), got " + argLength);
- }
- var match = function(branches) {
- var branchKeys = keys(branches);
- if (constructors.length !== branchKeys.length) {
- throw new Error("Wrong number of arguments to match. Expected: " + constructors.join(",") + "\nActual: " + branchKeys.join(","));
- }
- var allReqd = forall(constructors, function(reqKey) {
- return contains$2(branchKeys, reqKey);
- });
- if (!allReqd) {
- throw new Error("Not all branches were specified when using match. Specified: " + branchKeys.join(", ") + "\nRequired: " + constructors.join(", "));
- }
- return branches[key].apply(null, args);
- };
- return {
- fold: function() {
- var foldArgs = [];
- for (var _i2 = 0; _i2 < arguments.length; _i2++) {
- foldArgs[_i2] = arguments[_i2];
- }
- if (foldArgs.length !== cases.length) {
- throw new Error("Wrong number of arguments to fold. Expected " + cases.length + ", got " + foldArgs.length);
- }
- var target = foldArgs[count2];
- return target.apply(null, args);
- },
- match,
- log: function(label) {
- console.log(label, {
- constructors,
- constructor: key,
- params: args
- });
- }
- };
- };
- });
- return adt2;
- };
- var Adt = { generate: generate$7 };
- Adt.generate([
- {
- bothErrors: [
- "error1",
- "error2"
- ]
- },
- {
- firstError: [
- "error1",
- "value2"
- ]
- },
- {
- secondError: [
- "value1",
- "error2"
- ]
- },
- {
- bothValues: [
- "value1",
- "value2"
- ]
- }
- ]);
- var partition$1 = function(results) {
- var errors = [];
- var values2 = [];
- each$1(results, function(result) {
- result.fold(function(err) {
- errors.push(err);
- }, function(value2) {
- values2.push(value2);
- });
- });
- return {
- errors,
- values: values2
- };
- };
- var exclude$1 = function(obj, fields) {
- var r2 = {};
- each(obj, function(v, k) {
- if (!contains$2(fields, k)) {
- r2[k] = v;
- }
- });
- return r2;
- };
- var wrap$2 = function(key, value2) {
- var _a2;
- return _a2 = {}, _a2[key] = value2, _a2;
- };
- var wrapAll$1 = function(keyvalues) {
- var r2 = {};
- each$1(keyvalues, function(kv) {
- r2[kv.key] = kv.value;
- });
- return r2;
- };
- var exclude = function(obj, fields) {
- return exclude$1(obj, fields);
- };
- var wrap$1 = function(key, value2) {
- return wrap$2(key, value2);
- };
- var wrapAll = function(keyvalues) {
- return wrapAll$1(keyvalues);
- };
- var mergeValues = function(values2, base2) {
- return values2.length === 0 ? Result.value(base2) : Result.value(deepMerge(base2, merge$1.apply(void 0, values2)));
- };
- var mergeErrors = function(errors) {
- return Result.error(flatten(errors));
- };
- var consolidate = function(objs, base2) {
- var partitions = partition$1(objs);
- return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base2);
- };
- var ensureIsRoot = function(isRoot) {
- return isFunction(isRoot) ? isRoot : never;
- };
- var ancestor$2 = function(scope, transform2, isRoot) {
- var element2 = scope.dom;
- var stop2 = ensureIsRoot(isRoot);
- while (element2.parentNode) {
- element2 = element2.parentNode;
- var el = SugarElement.fromDom(element2);
- var transformed = transform2(el);
- if (transformed.isSome()) {
- return transformed;
- } else if (stop2(el)) {
- break;
- }
- }
- return Optional.none();
- };
- var closest$4 = function(scope, transform2, isRoot) {
- var current = transform2(scope);
- var stop2 = ensureIsRoot(isRoot);
- return current.orThunk(function() {
- return stop2(scope) ? Optional.none() : ancestor$2(scope, transform2, stop2);
- });
- };
- var isSource = function(component, simulatedEvent) {
- return eq(component.element, simulatedEvent.event.target);
- };
- var defaultEventHandler = {
- can: always,
- abort: never,
- run: noop
- };
- var nu$9 = function(parts2) {
- if (!hasNonNullableKey(parts2, "can") && !hasNonNullableKey(parts2, "abort") && !hasNonNullableKey(parts2, "run")) {
- throw new Error("EventHandler defined by: " + JSON.stringify(parts2, null, 2) + " does not have can, abort, or run!");
- }
- return __assign(__assign({}, defaultEventHandler), parts2);
- };
- var all$2 = function(handlers2, f) {
- return function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return foldl(handlers2, function(acc, handler) {
- return acc && f(handler).apply(void 0, args);
- }, true);
- };
- };
- var any = function(handlers2, f) {
- return function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return foldl(handlers2, function(acc, handler) {
- return acc || f(handler).apply(void 0, args);
- }, false);
- };
- };
- var read$2 = function(handler) {
- return isFunction(handler) ? {
- can: always,
- abort: never,
- run: handler
- } : handler;
- };
- var fuse$1 = function(handlers2) {
- var can2 = all$2(handlers2, function(handler) {
- return handler.can;
- });
- var abort2 = any(handlers2, function(handler) {
- return handler.abort;
- });
- var run2 = function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- each$1(handlers2, function(handler) {
- handler.run.apply(void 0, args);
- });
- };
- return {
- can: can2,
- abort: abort2,
- run: run2
- };
- };
- var constant = constant$1;
- var touchstart = constant("touchstart");
- var touchmove = constant("touchmove");
- var touchend = constant("touchend");
- var touchcancel = constant("touchcancel");
- var mousedown = constant("mousedown");
- var mousemove = constant("mousemove");
- var mouseout = constant("mouseout");
- var mouseup = constant("mouseup");
- var mouseover = constant("mouseover");
- var focusin = constant("focusin");
- var focusout = constant("focusout");
- var keydown = constant("keydown");
- var keyup = constant("keyup");
- var input = constant("input");
- var change = constant("change");
- var click = constant("click");
- var transitioncancel = constant("transitioncancel");
- var transitionend = constant("transitionend");
- var transitionstart = constant("transitionstart");
- var selectstart = constant("selectstart");
- var prefixName = function(name2) {
- return constant$1("alloy." + name2);
- };
- var alloy = { tap: prefixName("tap") };
- var focus$4 = prefixName("focus");
- var postBlur = prefixName("blur.post");
- var postPaste = prefixName("paste.post");
- var receive = prefixName("receive");
- var execute$5 = prefixName("execute");
- var focusItem = prefixName("focus.item");
- var tap = alloy.tap;
- var longpress = prefixName("longpress");
- var sandboxClose = prefixName("sandbox.close");
- var typeaheadCancel = prefixName("typeahead.cancel");
- var systemInit = prefixName("system.init");
- var documentTouchmove = prefixName("system.touchmove");
- var documentTouchend = prefixName("system.touchend");
- var windowScroll = prefixName("system.scroll");
- var windowResize = prefixName("system.resize");
- var attachedToDom = prefixName("system.attached");
- var detachedFromDom = prefixName("system.detached");
- var dismissRequested = prefixName("system.dismissRequested");
- var repositionRequested = prefixName("system.repositionRequested");
- var focusShifted = prefixName("focusmanager.shifted");
- var slotVisibility = prefixName("slotcontainer.visibility");
- var changeTab = prefixName("change.tab");
- var dismissTab = prefixName("dismiss.tab");
- var highlight$1 = prefixName("highlight");
- var dehighlight$1 = prefixName("dehighlight");
- var emit = function(component, event) {
- dispatchWith(component, component.element, event, {});
- };
- var emitWith = function(component, event, properties2) {
- dispatchWith(component, component.element, event, properties2);
- };
- var emitExecute = function(component) {
- emit(component, execute$5());
- };
- var dispatch = function(component, target, event) {
- dispatchWith(component, target, event, {});
- };
- var dispatchWith = function(component, target, event, properties2) {
- var data = __assign({ target }, properties2);
- component.getSystem().triggerEvent(event, target, data);
- };
- var dispatchEvent = function(component, target, event, simulatedEvent) {
- component.getSystem().triggerEvent(event, target, simulatedEvent.event);
- };
- var derive$2 = function(configs) {
- return wrapAll(configs);
- };
- var abort = function(name2, predicate) {
- return {
- key: name2,
- value: nu$9({ abort: predicate })
- };
- };
- var can = function(name2, predicate) {
- return {
- key: name2,
- value: nu$9({ can: predicate })
- };
- };
- var preventDefault = function(name2) {
- return {
- key: name2,
- value: nu$9({
- run: function(component, simulatedEvent) {
- simulatedEvent.event.prevent();
- }
- })
- };
- };
- var run$1 = function(name2, handler) {
- return {
- key: name2,
- value: nu$9({ run: handler })
- };
- };
- var runActionExtra = function(name2, action, extra) {
- return {
- key: name2,
- value: nu$9({
- run: function(component, simulatedEvent) {
- action.apply(void 0, [
- component,
- simulatedEvent
- ].concat(extra));
- }
- })
- };
- };
- var runOnName = function(name2) {
- return function(handler) {
- return run$1(name2, handler);
- };
- };
- var runOnSourceName = function(name2) {
- return function(handler) {
- return {
- key: name2,
- value: nu$9({
- run: function(component, simulatedEvent) {
- if (isSource(component, simulatedEvent)) {
- handler(component, simulatedEvent);
- }
- }
- })
- };
- };
- };
- var redirectToUid = function(name2, uid) {
- return run$1(name2, function(component, simulatedEvent) {
- component.getSystem().getByUid(uid).each(function(redirectee) {
- dispatchEvent(redirectee, redirectee.element, name2, simulatedEvent);
- });
- });
- };
- var redirectToPart = function(name2, detail, partName) {
- var uid = detail.partUids[partName];
- return redirectToUid(name2, uid);
- };
- var runWithTarget = function(name2, f) {
- return run$1(name2, function(component, simulatedEvent) {
- var ev = simulatedEvent.event;
- var target = component.getSystem().getByDom(ev.target).getOrThunk(function() {
- var closest2 = closest$4(ev.target, function(el) {
- return component.getSystem().getByDom(el).toOptional();
- }, never);
- return closest2.getOr(component);
- });
- f(component, target, simulatedEvent);
- });
- };
- var cutter = function(name2) {
- return run$1(name2, function(component, simulatedEvent) {
- simulatedEvent.cut();
- });
- };
- var stopper = function(name2) {
- return run$1(name2, function(component, simulatedEvent) {
- simulatedEvent.stop();
- });
- };
- var runOnSource = function(name2, f) {
- return runOnSourceName(name2)(f);
- };
- var runOnAttached = runOnSourceName(attachedToDom());
- var runOnDetached = runOnSourceName(detachedFromDom());
- var runOnInit = runOnSourceName(systemInit());
- var runOnExecute$1 = runOnName(execute$5());
- var fromHtml$1 = function(html2, scope) {
- var doc = scope || document;
- var div = doc.createElement("div");
- div.innerHTML = html2;
- return children(SugarElement.fromDom(div));
- };
- var get$7 = function(element2) {
- return element2.dom.innerHTML;
- };
- var set$5 = function(element2, content) {
- var owner2 = owner$4(element2);
- var docDom = owner2.dom;
- var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
- var contentElements = fromHtml$1(content, docDom);
- append$1(fragment, contentElements);
- empty(element2);
- append$2(element2, fragment);
- };
- var getOuter = function(element2) {
- var container = SugarElement.fromTag("div");
- var clone2 = SugarElement.fromDom(element2.dom.cloneNode(true));
- append$2(container, clone2);
- return get$7(container);
- };
- var clone$2 = function(original2, isDeep) {
- return SugarElement.fromDom(original2.dom.cloneNode(isDeep));
- };
- var shallow = function(original2) {
- return clone$2(original2, false);
- };
- var getHtml = function(element2) {
- if (isShadowRoot(element2)) {
- return "#shadow-root";
- } else {
- var clone2 = shallow(element2);
- return getOuter(clone2);
- }
- };
- var element = function(elem) {
- return getHtml(elem);
- };
- var isRecursive = function(component, originator, target) {
- return eq(originator, component.element) && !eq(originator, target);
- };
- var events$i = derive$2([can(focus$4(), function(component, simulatedEvent) {
- var event = simulatedEvent.event;
- var originator = event.originator;
- var target = event.target;
- if (isRecursive(component, originator, target)) {
- console.warn(focus$4() + " did not get interpreted by the desired target. \nOriginator: " + element(originator) + "\nTarget: " + element(target) + "\nCheck the " + focus$4() + " event handlers");
- return false;
- } else {
- return true;
- }
- })]);
- var DefaultEvents = Object.freeze({
- __proto__: null,
- events: events$i
- });
- var unique = 0;
- var generate$6 = function(prefix2) {
- var date = /* @__PURE__ */ new Date();
- var time = date.getTime();
- var random = Math.floor(Math.random() * 1e9);
- unique++;
- return prefix2 + "_" + random + unique + String(time);
- };
- var prefix$1 = constant$1("alloy-id-");
- var idAttr$1 = constant$1("data-alloy-id");
- var prefix = prefix$1();
- var idAttr = idAttr$1();
- var write = function(label, elem) {
- var id = generate$6(prefix + label);
- writeOnly(elem, id);
- return id;
- };
- var writeOnly = function(elem, uid) {
- Object.defineProperty(elem.dom, idAttr, {
- value: uid,
- writable: true
- });
- };
- var read$1 = function(elem) {
- var id = isElement$2(elem) ? elem.dom[idAttr] : null;
- return Optional.from(id);
- };
- var generate$5 = function(prefix2) {
- return generate$6(prefix2);
- };
- var make$8 = identity$1;
- var NoContextApi = function(getComp) {
- var getMessage = function(event) {
- return "The component must be in a context to execute: " + event + (getComp ? "\n" + element(getComp().element) + " is not in context." : "");
- };
- var fail = function(event) {
- return function() {
- throw new Error(getMessage(event));
- };
- };
- var warn = function(event) {
- return function() {
- console.warn(getMessage(event));
- };
- };
- return {
- debugInfo: constant$1("fake"),
- triggerEvent: warn("triggerEvent"),
- triggerFocus: warn("triggerFocus"),
- triggerEscape: warn("triggerEscape"),
- broadcast: warn("broadcast"),
- broadcastOn: warn("broadcastOn"),
- broadcastEvent: warn("broadcastEvent"),
- build: fail("build"),
- addToWorld: fail("addToWorld"),
- removeFromWorld: fail("removeFromWorld"),
- addToGui: fail("addToGui"),
- removeFromGui: fail("removeFromGui"),
- getByUid: fail("getByUid"),
- getByDom: fail("getByDom"),
- isConnected: never
- };
- };
- var singleton$1 = NoContextApi();
- var markAsBehaviourApi = function(f, apiName, apiFunction) {
- var delegate = apiFunction.toString();
- var endIndex = delegate.indexOf(")") + 1;
- var openBracketIndex = delegate.indexOf("(");
- var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
- f.toFunctionAnnotation = function() {
- return {
- name: apiName,
- parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
- };
- };
- return f;
- };
- var cleanParameters = function(parameters) {
- return map$2(parameters, function(p) {
- return endsWith(p, "/*") ? p.substring(0, p.length - "/*".length) : p;
- });
- };
- var markAsExtraApi = function(f, extraName) {
- var delegate = f.toString();
- var endIndex = delegate.indexOf(")") + 1;
- var openBracketIndex = delegate.indexOf("(");
- var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
- f.toFunctionAnnotation = function() {
- return {
- name: extraName,
- parameters: cleanParameters(parameters)
- };
- };
- return f;
- };
- var markAsSketchApi = function(f, apiFunction) {
- var delegate = apiFunction.toString();
- var endIndex = delegate.indexOf(")") + 1;
- var openBracketIndex = delegate.indexOf("(");
- var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
- f.toFunctionAnnotation = function() {
- return {
- name: "OVERRIDE",
- parameters: cleanParameters(parameters.slice(1))
- };
- };
- return f;
- };
- var premadeTag = generate$6("alloy-premade");
- var premade$1 = function(comp) {
- return wrap$1(premadeTag, comp);
- };
- var getPremade = function(spec) {
- return get$e(spec, premadeTag);
- };
- var makeApi = function(f) {
- return markAsSketchApi(function(component) {
- var rest = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- rest[_i - 1] = arguments[_i];
- }
- return f.apply(void 0, __spreadArray([
- component.getApis(),
- component
- ], rest, false));
- }, f);
- };
- var NoState = {
- init: function() {
- return nu$8({ readState: constant$1("No State required") });
- }
- };
- var nu$8 = function(spec) {
- return spec;
- };
- var generateFrom$1 = function(spec, all2) {
- var schema2 = map$2(all2, function(a) {
- return optionObjOf(a.name(), [
- required$1("config"),
- defaulted("state", NoState)
- ]);
- });
- var validated = asRaw("component.behaviours", objOf(schema2), spec.behaviours).fold(function(errInfo) {
- throw new Error(formatError(errInfo) + "\nComplete spec:\n" + JSON.stringify(spec, null, 2));
- }, identity$1);
- return {
- list: all2,
- data: map$1(validated, function(optBlobThunk) {
- var output2 = optBlobThunk.map(function(blob) {
- return {
- config: blob.config,
- state: blob.state.init(blob.config)
- };
- });
- return constant$1(output2);
- })
- };
- };
- var getBehaviours$3 = function(bData) {
- return bData.list;
- };
- var getData$2 = function(bData) {
- return bData.data;
- };
- var byInnerKey = function(data, tuple) {
- var r2 = {};
- each(data, function(detail, key) {
- each(detail, function(value2, indexKey) {
- var chain = get$e(r2, indexKey).getOr([]);
- r2[indexKey] = chain.concat([tuple(key, value2)]);
- });
- });
- return r2;
- };
- var nu$7 = function(s) {
- return {
- classes: isUndefined(s.classes) ? [] : s.classes,
- attributes: isUndefined(s.attributes) ? {} : s.attributes,
- styles: isUndefined(s.styles) ? {} : s.styles
- };
- };
- var merge = function(defnA, mod) {
- return __assign(__assign({}, defnA), {
- attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
- styles: __assign(__assign({}, defnA.styles), mod.styles),
- classes: defnA.classes.concat(mod.classes)
- });
- };
- var combine$2 = function(info, baseMod, behaviours2, base2) {
- var modsByBehaviour = __assign({}, baseMod);
- each$1(behaviours2, function(behaviour) {
- modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base2);
- });
- var byAspect = byInnerKey(modsByBehaviour, function(name2, modification) {
- return {
- name: name2,
- modification
- };
- });
- var combineObjects = function(objects) {
- return foldr(objects, function(b2, a) {
- return __assign(__assign({}, a.modification), b2);
- }, {});
- };
- var combinedClasses = foldr(byAspect.classes, function(b2, a) {
- return a.modification.concat(b2);
- }, []);
- var combinedAttributes = combineObjects(byAspect.attributes);
- var combinedStyles = combineObjects(byAspect.styles);
- return nu$7({
- classes: combinedClasses,
- attributes: combinedAttributes,
- styles: combinedStyles
- });
- };
- var sortKeys = function(label, keyName, array, order) {
- try {
- var sorted = sort(array, function(a, b2) {
- var aKey = a[keyName];
- var bKey = b2[keyName];
- var aIndex = order.indexOf(aKey);
- var bIndex = order.indexOf(bKey);
- if (aIndex === -1) {
- throw new Error("The ordering for " + label + " does not have an entry for " + aKey + ".\nOrder specified: " + JSON.stringify(order, null, 2));
- }
- if (bIndex === -1) {
- throw new Error("The ordering for " + label + " does not have an entry for " + bKey + ".\nOrder specified: " + JSON.stringify(order, null, 2));
- }
- if (aIndex < bIndex) {
- return -1;
- } else if (bIndex < aIndex) {
- return 1;
- } else {
- return 0;
- }
- });
- return Result.value(sorted);
- } catch (err) {
- return Result.error([err]);
- }
- };
- var uncurried = function(handler, purpose) {
- return {
- handler,
- purpose
- };
- };
- var curried = function(handler, purpose) {
- return {
- cHandler: handler,
- purpose
- };
- };
- var curryArgs = function(descHandler, extraArgs) {
- return curried(curry.apply(void 0, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
- };
- var getCurried = function(descHandler) {
- return descHandler.cHandler;
- };
- var behaviourTuple = function(name2, handler) {
- return {
- name: name2,
- handler
- };
- };
- var nameToHandlers = function(behaviours2, info) {
- var r2 = {};
- each$1(behaviours2, function(behaviour) {
- r2[behaviour.name()] = behaviour.handlers(info);
- });
- return r2;
- };
- var groupByEvents = function(info, behaviours2, base2) {
- var behaviourEvents = __assign(__assign({}, base2), nameToHandlers(behaviours2, info));
- return byInnerKey(behaviourEvents, behaviourTuple);
- };
- var combine$1 = function(info, eventOrder, behaviours2, base2) {
- var byEventName = groupByEvents(info, behaviours2, base2);
- return combineGroups(byEventName, eventOrder);
- };
- var assemble = function(rawHandler) {
- var handler = read$2(rawHandler);
- return function(component, simulatedEvent) {
- var rest = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- rest[_i - 2] = arguments[_i];
- }
- var args = [
- component,
- simulatedEvent
- ].concat(rest);
- if (handler.abort.apply(void 0, args)) {
- simulatedEvent.stop();
- } else if (handler.can.apply(void 0, args)) {
- handler.run.apply(void 0, args);
- }
- };
- };
- var missingOrderError = function(eventName, tuples) {
- return Result.error(["The event (" + eventName + ') has more than one behaviour that listens to it.\nWhen this occurs, you must specify an event ordering for the behaviours in your spec (e.g. [ "listing", "toggling" ]).\nThe behaviours that can trigger it are: ' + JSON.stringify(map$2(tuples, function(c) {
- return c.name;
- }), null, 2)]);
- };
- var fuse = function(tuples, eventOrder, eventName) {
- var order = eventOrder[eventName];
- if (!order) {
- return missingOrderError(eventName, tuples);
- } else {
- return sortKeys("Event: " + eventName, "name", tuples, order).map(function(sortedTuples) {
- var handlers2 = map$2(sortedTuples, function(tuple) {
- return tuple.handler;
- });
- return fuse$1(handlers2);
- });
- }
- };
- var combineGroups = function(byEventName, eventOrder) {
- var r2 = mapToArray(byEventName, function(tuples, eventName) {
- var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
- return combined.map(function(handler) {
- var assembled = assemble(handler);
- var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function(o) {
- return exists(tuples, function(t2) {
- return t2.name === o;
- });
- }).join(" > ") : tuples[0].name;
- return wrap$1(eventName, uncurried(assembled, purpose));
- });
- });
- return consolidate(r2, {});
- };
- var _a$2;
- var baseBehaviour = "alloy.base.behaviour";
- var schema$z = objOf([
- field$1("dom", "dom", required$2(), objOf([
- required$1("tag"),
- defaulted("styles", {}),
- defaulted("classes", []),
- defaulted("attributes", {}),
- option("value"),
- option("innerHtml")
- ])),
- required$1("components"),
- required$1("uid"),
- defaulted("events", {}),
- defaulted("apis", {}),
- field$1("eventOrder", "eventOrder", mergeWith((_a$2 = {}, _a$2[execute$5()] = [
- "disabling",
- baseBehaviour,
- "toggling",
- "typeaheadevents"
- ], _a$2[focus$4()] = [
- baseBehaviour,
- "focusing",
- "keying"
- ], _a$2[systemInit()] = [
- baseBehaviour,
- "disabling",
- "toggling",
- "representing"
- ], _a$2[input()] = [
- baseBehaviour,
- "representing",
- "streaming",
- "invalidating"
- ], _a$2[detachedFromDom()] = [
- baseBehaviour,
- "representing",
- "item-events",
- "tooltipping"
- ], _a$2[mousedown()] = [
- "focusing",
- baseBehaviour,
- "item-type-events"
- ], _a$2[touchstart()] = [
- "focusing",
- baseBehaviour,
- "item-type-events"
- ], _a$2[mouseover()] = [
- "item-type-events",
- "tooltipping"
- ], _a$2[receive()] = [
- "receiving",
- "reflecting",
- "tooltipping"
- ], _a$2)), anyValue()),
- option("domModification")
- ]);
- var toInfo = function(spec) {
- return asRaw("custom.definition", schema$z, spec);
- };
- var toDefinition = function(detail) {
- return __assign(__assign({}, detail.dom), {
- uid: detail.uid,
- domChildren: map$2(detail.components, function(comp) {
- return comp.element;
- })
- });
- };
- var toModification = function(detail) {
- return detail.domModification.fold(function() {
- return nu$7({});
- }, nu$7);
- };
- var toEvents = function(info) {
- return info.events;
- };
- var read = function(element2, attr) {
- var value2 = get$d(element2, attr);
- return value2 === void 0 || value2 === "" ? [] : value2.split(" ");
- };
- var add$4 = function(element2, attr, id) {
- var old = read(element2, attr);
- var nu2 = old.concat([id]);
- set$8(element2, attr, nu2.join(" "));
- return true;
- };
- var remove$4 = function(element2, attr, id) {
- var nu2 = filter$2(read(element2, attr), function(v) {
- return v !== id;
- });
- if (nu2.length > 0) {
- set$8(element2, attr, nu2.join(" "));
- } else {
- remove$7(element2, attr);
- }
- return false;
- };
- var supports = function(element2) {
- return element2.dom.classList !== void 0;
- };
- var get$6 = function(element2) {
- return read(element2, "class");
- };
- var add$3 = function(element2, clazz) {
- return add$4(element2, "class", clazz);
- };
- var remove$3 = function(element2, clazz) {
- return remove$4(element2, "class", clazz);
- };
- var add$2 = function(element2, clazz) {
- if (supports(element2)) {
- element2.dom.classList.add(clazz);
- } else {
- add$3(element2, clazz);
- }
- };
- var cleanClass = function(element2) {
- var classList = supports(element2) ? element2.dom.classList : get$6(element2);
- if (classList.length === 0) {
- remove$7(element2, "class");
- }
- };
- var remove$2 = function(element2, clazz) {
- if (supports(element2)) {
- var classList = element2.dom.classList;
- classList.remove(clazz);
- } else {
- remove$3(element2, clazz);
- }
- cleanClass(element2);
- };
- var has = function(element2, clazz) {
- return supports(element2) && element2.dom.classList.contains(clazz);
- };
- var add$1 = function(element2, classes2) {
- each$1(classes2, function(x) {
- add$2(element2, x);
- });
- };
- var remove$1 = function(element2, classes2) {
- each$1(classes2, function(x) {
- remove$2(element2, x);
- });
- };
- var hasAll = function(element2, classes2) {
- return forall(classes2, function(clazz) {
- return has(element2, clazz);
- });
- };
- var get$5 = function(element2) {
- return element2.dom.value;
- };
- var set$4 = function(element2, value2) {
- if (value2 === void 0) {
- throw new Error("Value.set was undefined");
- }
- element2.dom.value = value2;
- };
- var renderToDom = function(definition) {
- var subject = SugarElement.fromTag(definition.tag);
- setAll$1(subject, definition.attributes);
- add$1(subject, definition.classes);
- setAll(subject, definition.styles);
- definition.innerHtml.each(function(html2) {
- return set$5(subject, html2);
- });
- var children2 = definition.domChildren;
- append$1(subject, children2);
- definition.value.each(function(value2) {
- set$4(subject, value2);
- });
- if (!definition.uid) {
- debugger;
- }
- writeOnly(subject, definition.uid);
- return subject;
- };
- var getBehaviours$2 = function(spec) {
- var behaviours2 = get$e(spec, "behaviours").getOr({});
- return bind$3(keys(behaviours2), function(name2) {
- var behaviour = behaviours2[name2];
- return isNonNullable(behaviour) ? [behaviour.me] : [];
- });
- };
- var generateFrom = function(spec, all2) {
- return generateFrom$1(spec, all2);
- };
- var generate$4 = function(spec) {
- var all2 = getBehaviours$2(spec);
- return generateFrom(spec, all2);
- };
- var getDomDefinition = function(info, bList, bData) {
- var definition = toDefinition(info);
- var infoModification = toModification(info);
- var baseModification = { "alloy.base.modification": infoModification };
- var modification = bList.length > 0 ? combine$2(bData, baseModification, bList, definition) : infoModification;
- return merge(definition, modification);
- };
- var getEvents = function(info, bList, bData) {
- var baseEvents = { "alloy.base.behaviour": toEvents(info) };
- return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
- };
- var build$2 = function(spec) {
- var getMe = function() {
- return me;
- };
- var systemApi = Cell(singleton$1);
- var info = getOrDie(toInfo(spec));
- var bBlob = generate$4(spec);
- var bList = getBehaviours$3(bBlob);
- var bData = getData$2(bBlob);
- var modDefinition = getDomDefinition(info, bList, bData);
- var item2 = renderToDom(modDefinition);
- var events2 = getEvents(info, bList, bData);
- var subcomponents = Cell(info.components);
- var connect = function(newApi) {
- systemApi.set(newApi);
- };
- var disconnect = function() {
- systemApi.set(NoContextApi(getMe));
- };
- var syncComponents = function() {
- var children$1 = children(item2);
- var subs2 = bind$3(children$1, function(child2) {
- return systemApi.get().getByDom(child2).fold(function() {
- return [];
- }, pure$2);
- });
- subcomponents.set(subs2);
- };
- var config2 = function(behaviour) {
- var b2 = bData;
- var f = isFunction(b2[behaviour.name()]) ? b2[behaviour.name()] : function() {
- throw new Error("Could not find " + behaviour.name() + " in " + JSON.stringify(spec, null, 2));
- };
- return f();
- };
- var hasConfigured = function(behaviour) {
- return isFunction(bData[behaviour.name()]);
- };
- var getApis = function() {
- return info.apis;
- };
- var readState = function(behaviourName) {
- return bData[behaviourName]().map(function(b2) {
- return b2.state.readState();
- }).getOr("not enabled");
- };
- var me = {
- uid: spec.uid,
- getSystem: systemApi.get,
- config: config2,
- hasConfigured,
- spec,
- readState,
- getApis,
- connect,
- disconnect,
- element: item2,
- syncComponents,
- components: subcomponents.get,
- events: events2
- };
- return me;
- };
- var buildSubcomponents = function(spec) {
- var components2 = get$e(spec, "components").getOr([]);
- return map$2(components2, build$1);
- };
- var buildFromSpec = function(userSpec) {
- var _a2 = make$8(userSpec), specEvents = _a2.events, spec = __rest(_a2, ["events"]);
- var components2 = buildSubcomponents(spec);
- var completeSpec = __assign(__assign({}, spec), {
- events: __assign(__assign({}, DefaultEvents), specEvents),
- components: components2
- });
- return Result.value(build$2(completeSpec));
- };
- var text$1 = function(textContent) {
- var element2 = SugarElement.fromText(textContent);
- return external$2({ element: element2 });
- };
- var external$2 = function(spec) {
- var extSpec = asRawOrDie$1("external.component", objOfOnly([
- required$1("element"),
- option("uid")
- ]), spec);
- var systemApi = Cell(NoContextApi());
- var connect = function(newApi) {
- systemApi.set(newApi);
- };
- var disconnect = function() {
- systemApi.set(NoContextApi(function() {
- return me;
- }));
- };
- var uid = extSpec.uid.getOrThunk(function() {
- return generate$5("external");
- });
- writeOnly(extSpec.element, uid);
- var me = {
- uid,
- getSystem: systemApi.get,
- config: Optional.none,
- hasConfigured: never,
- connect,
- disconnect,
- getApis: function() {
- return {};
- },
- element: extSpec.element,
- spec,
- readState: constant$1("No state"),
- syncComponents: noop,
- components: constant$1([]),
- events: {}
- };
- return premade$1(me);
- };
- var uids = generate$5;
- var isSketchSpec$1 = function(spec) {
- return has$2(spec, "uid");
- };
- var build$1 = function(spec) {
- return getPremade(spec).getOrThunk(function() {
- var userSpecWithUid = isSketchSpec$1(spec) ? spec : __assign({ uid: uids("") }, spec);
- return buildFromSpec(userSpecWithUid).getOrDie();
- });
- };
- var premade = premade$1;
- function ClosestOrAncestor(is2, ancestor2, scope, a, isRoot) {
- if (is2(scope, a)) {
- return Optional.some(scope);
- } else if (isFunction(isRoot) && isRoot(scope)) {
- return Optional.none();
- } else {
- return ancestor2(scope, a, isRoot);
- }
- }
- var ancestor$1 = function(scope, predicate, isRoot) {
- var element2 = scope.dom;
- var stop2 = isFunction(isRoot) ? isRoot : never;
- while (element2.parentNode) {
- element2 = element2.parentNode;
- var el = SugarElement.fromDom(element2);
- if (predicate(el)) {
- return Optional.some(el);
- } else if (stop2(el)) {
- break;
- }
- }
- return Optional.none();
- };
- var closest$3 = function(scope, predicate, isRoot) {
- var is2 = function(s, test) {
- return test(s);
- };
- return ClosestOrAncestor(is2, ancestor$1, scope, predicate, isRoot);
- };
- var child$1 = function(scope, predicate) {
- var pred = function(node) {
- return predicate(SugarElement.fromDom(node));
- };
- var result = find$5(scope.dom.childNodes, pred);
- return result.map(SugarElement.fromDom);
- };
- var descendant$1 = function(scope, predicate) {
- var descend = function(node) {
- for (var i = 0; i < node.childNodes.length; i++) {
- var child_1 = SugarElement.fromDom(node.childNodes[i]);
- if (predicate(child_1)) {
- return Optional.some(child_1);
- }
- var res = descend(node.childNodes[i]);
- if (res.isSome()) {
- return res;
- }
- }
- return Optional.none();
- };
- return descend(scope.dom);
- };
- var closest$2 = function(scope, predicate, isRoot) {
- return closest$3(scope, predicate, isRoot).isSome();
- };
- var ancestor = function(scope, selector, isRoot) {
- return ancestor$1(scope, function(e) {
- return is(e, selector);
- }, isRoot);
- };
- var child = function(scope, selector) {
- return child$1(scope, function(e) {
- return is(e, selector);
- });
- };
- var descendant = function(scope, selector) {
- return one(selector, scope);
- };
- var closest$1 = function(scope, selector, isRoot) {
- var is$12 = function(element2, selector2) {
- return is(element2, selector2);
- };
- return ClosestOrAncestor(is$12, ancestor, scope, selector, isRoot);
- };
- var find$1 = function(queryElem) {
- var dependent = closest$3(queryElem, function(elem) {
- if (!isElement$2(elem)) {
- return false;
- }
- var id = get$d(elem, "id");
- return id !== void 0 && id.indexOf("aria-owns") > -1;
- });
- return dependent.bind(function(dep) {
- var id = get$d(dep, "id");
- var dos = getRootNode(dep);
- return descendant(dos, '[aria-owns="' + id + '"]');
- });
- };
- var manager = function() {
- var ariaId = generate$6("aria-owns");
- var link = function(elem) {
- set$8(elem, "aria-owns", ariaId);
- };
- var unlink = function(elem) {
- remove$7(elem, "aria-owns");
- };
- return {
- id: ariaId,
- link,
- unlink
- };
- };
- var isAriaPartOf = function(component, queryElem) {
- return find$1(queryElem).exists(function(owner2) {
- return isPartOf$1(component, owner2);
- });
- };
- var isPartOf$1 = function(component, queryElem) {
- return closest$2(queryElem, function(el) {
- return eq(el, component.element);
- }, never) || isAriaPartOf(component, queryElem);
- };
- var unknown = "unknown";
- var EventConfiguration;
- (function(EventConfiguration2) {
- EventConfiguration2[EventConfiguration2["STOP"] = 0] = "STOP";
- EventConfiguration2[EventConfiguration2["NORMAL"] = 1] = "NORMAL";
- EventConfiguration2[EventConfiguration2["LOGGING"] = 2] = "LOGGING";
- })(EventConfiguration || (EventConfiguration = {}));
- var eventConfig = Cell({});
- var makeEventLogger = function(eventName, initialTarget) {
- var sequence2 = [];
- var startTime = (/* @__PURE__ */ new Date()).getTime();
- return {
- logEventCut: function(_name, target, purpose) {
- sequence2.push({
- outcome: "cut",
- target,
- purpose
- });
- },
- logEventStopped: function(_name, target, purpose) {
- sequence2.push({
- outcome: "stopped",
- target,
- purpose
- });
- },
- logNoParent: function(_name, target, purpose) {
- sequence2.push({
- outcome: "no-parent",
- target,
- purpose
- });
- },
- logEventNoHandlers: function(_name, target) {
- sequence2.push({
- outcome: "no-handlers-left",
- target
- });
- },
- logEventResponse: function(_name, target, purpose) {
- sequence2.push({
- outcome: "response",
- purpose,
- target
- });
- },
- write: function() {
- var finishTime = (/* @__PURE__ */ new Date()).getTime();
- if (contains$2([
- "mousemove",
- "mouseover",
- "mouseout",
- systemInit()
- ], eventName)) {
- return;
- }
- console.log(eventName, {
- event: eventName,
- time: finishTime - startTime,
- target: initialTarget.dom,
- sequence: map$2(sequence2, function(s) {
- if (!contains$2([
- "cut",
- "stopped",
- "response"
- ], s.outcome)) {
- return s.outcome;
- } else {
- return "{" + s.purpose + "} " + s.outcome + " at (" + element(s.target) + ")";
- }
- })
- });
- }
- };
- };
- var processEvent = function(eventName, initialTarget, f) {
- var status = get$e(eventConfig.get(), eventName).orThunk(function() {
- var patterns = keys(eventConfig.get());
- return findMap(patterns, function(p) {
- return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
- });
- }).getOr(EventConfiguration.NORMAL);
- switch (status) {
- case EventConfiguration.NORMAL:
- return f(noLogger());
- case EventConfiguration.LOGGING: {
- var logger = makeEventLogger(eventName, initialTarget);
- var output2 = f(logger);
- logger.write();
- return output2;
- }
- case EventConfiguration.STOP:
- return true;
- }
- };
- var path = [
- "alloy/data/Fields",
- "alloy/debugging/Debugging"
- ];
- var getTrace = function() {
- var err = new Error();
- if (err.stack !== void 0) {
- var lines = err.stack.split("\n");
- return find$5(lines, function(line) {
- return line.indexOf("alloy") > 0 && !exists(path, function(p) {
- return line.indexOf(p) > -1;
- });
- }).getOr(unknown);
- } else {
- return unknown;
- }
- };
- var ignoreEvent = {
- logEventCut: noop,
- logEventStopped: noop,
- logNoParent: noop,
- logEventNoHandlers: noop,
- logEventResponse: noop,
- write: noop
- };
- var monitorEvent = function(eventName, initialTarget, f) {
- return processEvent(eventName, initialTarget, f);
- };
- var noLogger = constant$1(ignoreEvent);
- var menuFields = constant$1([
- required$1("menu"),
- required$1("selectedMenu")
- ]);
- var itemFields = constant$1([
- required$1("item"),
- required$1("selectedItem")
- ]);
- constant$1(objOf(itemFields().concat(menuFields())));
- var itemSchema$3 = constant$1(objOf(itemFields()));
- var _initSize = requiredObjOf("initSize", [
- required$1("numColumns"),
- required$1("numRows")
- ]);
- var itemMarkers = function() {
- return requiredOf("markers", itemSchema$3());
- };
- var tieredMenuMarkers = function() {
- return requiredObjOf("markers", [required$1("backgroundMenu")].concat(menuFields()).concat(itemFields()));
- };
- var markers$1 = function(required2) {
- return requiredObjOf("markers", map$2(required2, required$1));
- };
- var onPresenceHandler = function(label, fieldName, presence) {
- getTrace();
- return field$1(fieldName, fieldName, presence, valueOf(function(f) {
- return Result.value(function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return f.apply(void 0, args);
- });
- }));
- };
- var onHandler = function(fieldName) {
- return onPresenceHandler("onHandler", fieldName, defaulted$1(noop));
- };
- var onKeyboardHandler = function(fieldName) {
- return onPresenceHandler("onKeyboardHandler", fieldName, defaulted$1(Optional.none));
- };
- var onStrictHandler = function(fieldName) {
- return onPresenceHandler("onHandler", fieldName, required$2());
- };
- var onStrictKeyboardHandler = function(fieldName) {
- return onPresenceHandler("onKeyboardHandler", fieldName, required$2());
- };
- var output$1 = function(name2, value2) {
- return customField(name2, constant$1(value2));
- };
- var snapshot = function(name2) {
- return customField(name2, identity$1);
- };
- var initSize = constant$1(_initSize);
- var nu$6 = function(x, y, bubble, direction, placement2, boundsRestriction2, labelPrefix2, alwaysFit) {
- if (alwaysFit === void 0) {
- alwaysFit = false;
- }
- return {
- x,
- y,
- bubble,
- direction,
- placement: placement2,
- restriction: boundsRestriction2,
- label: labelPrefix2 + "-" + placement2,
- alwaysFit
- };
- };
- var adt$a = Adt.generate([
- { southeast: [] },
- { southwest: [] },
- { northeast: [] },
- { northwest: [] },
- { south: [] },
- { north: [] },
- { east: [] },
- { west: [] }
- ]);
- var cata$2 = function(subject, southeast2, southwest2, northeast2, northwest2, south2, north2, east2, west2) {
- return subject.fold(southeast2, southwest2, northeast2, northwest2, south2, north2, east2, west2);
- };
- var cataVertical = function(subject, south2, middle, north2) {
- return subject.fold(south2, south2, north2, north2, south2, north2, middle, middle);
- };
- var cataHorizontal = function(subject, east2, middle, west2) {
- return subject.fold(east2, west2, east2, west2, middle, middle, east2, west2);
- };
- var southeast$3 = adt$a.southeast;
- var southwest$3 = adt$a.southwest;
- var northeast$3 = adt$a.northeast;
- var northwest$3 = adt$a.northwest;
- var south$3 = adt$a.south;
- var north$3 = adt$a.north;
- var east$3 = adt$a.east;
- var west$3 = adt$a.west;
- var cycleBy = function(value2, delta, min2, max2) {
- var r2 = value2 + delta;
- if (r2 > max2) {
- return min2;
- } else if (r2 < min2) {
- return max2;
- } else {
- return r2;
- }
- };
- var clamp$1 = function(value2, min2, max2) {
- return Math.min(Math.max(value2, min2), max2);
- };
- var getRestriction = function(anchor2, restriction) {
- switch (restriction) {
- case 1:
- return anchor2.x;
- case 0:
- return anchor2.x + anchor2.width;
- case 2:
- return anchor2.y;
- case 3:
- return anchor2.y + anchor2.height;
- }
- };
- var boundsRestriction = function(anchor2, restrictions) {
- return mapToObject([
- "left",
- "right",
- "top",
- "bottom"
- ], function(dir) {
- return get$e(restrictions, dir).map(function(restriction) {
- return getRestriction(anchor2, restriction);
- });
- });
- };
- var adjustBounds = function(bounds$12, restriction, bubbleOffset) {
- var applyRestriction = function(dir, current) {
- return restriction[dir].map(function(pos) {
- var isVerticalAxis = dir === "top" || dir === "bottom";
- var offset2 = isVerticalAxis ? bubbleOffset.top : bubbleOffset.left;
- var comparator = dir === "left" || dir === "top" ? Math.max : Math.min;
- var newPos = comparator(pos, current) + offset2;
- return isVerticalAxis ? clamp$1(newPos, bounds$12.y, bounds$12.bottom) : clamp$1(newPos, bounds$12.x, bounds$12.right);
- }).getOr(current);
- };
- var adjustedLeft = applyRestriction("left", bounds$12.x);
- var adjustedTop = applyRestriction("top", bounds$12.y);
- var adjustedRight = applyRestriction("right", bounds$12.right);
- var adjustedBottom = applyRestriction("bottom", bounds$12.bottom);
- return bounds(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop);
- };
- var labelPrefix$2 = "layout";
- var eastX$1 = function(anchor2) {
- return anchor2.x;
- };
- var middleX$1 = function(anchor2, element2) {
- return anchor2.x + anchor2.width / 2 - element2.width / 2;
- };
- var westX$1 = function(anchor2, element2) {
- return anchor2.x + anchor2.width - element2.width;
- };
- var northY$2 = function(anchor2, element2) {
- return anchor2.y - element2.height;
- };
- var southY$2 = function(anchor2) {
- return anchor2.y + anchor2.height;
- };
- var centreY$1 = function(anchor2, element2) {
- return anchor2.y + anchor2.height / 2 - element2.height / 2;
- };
- var eastEdgeX$1 = function(anchor2) {
- return anchor2.x + anchor2.width;
- };
- var westEdgeX$1 = function(anchor2, element2) {
- return anchor2.x - element2.width;
- };
- var southeast$2 = function(anchor2, element2, bubbles) {
- return nu$6(eastX$1(anchor2), southY$2(anchor2), bubbles.southeast(), southeast$3(), "southeast", boundsRestriction(anchor2, {
- left: 1,
- top: 3
- }), labelPrefix$2);
- };
- var southwest$2 = function(anchor2, element2, bubbles) {
- return nu$6(westX$1(anchor2, element2), southY$2(anchor2), bubbles.southwest(), southwest$3(), "southwest", boundsRestriction(anchor2, {
- right: 0,
- top: 3
- }), labelPrefix$2);
- };
- var northeast$2 = function(anchor2, element2, bubbles) {
- return nu$6(eastX$1(anchor2), northY$2(anchor2, element2), bubbles.northeast(), northeast$3(), "northeast", boundsRestriction(anchor2, {
- left: 1,
- bottom: 2
- }), labelPrefix$2);
- };
- var northwest$2 = function(anchor2, element2, bubbles) {
- return nu$6(westX$1(anchor2, element2), northY$2(anchor2, element2), bubbles.northwest(), northwest$3(), "northwest", boundsRestriction(anchor2, {
- right: 0,
- bottom: 2
- }), labelPrefix$2);
- };
- var north$2 = function(anchor2, element2, bubbles) {
- return nu$6(middleX$1(anchor2, element2), northY$2(anchor2, element2), bubbles.north(), north$3(), "north", boundsRestriction(anchor2, { bottom: 2 }), labelPrefix$2);
- };
- var south$2 = function(anchor2, element2, bubbles) {
- return nu$6(middleX$1(anchor2, element2), southY$2(anchor2), bubbles.south(), south$3(), "south", boundsRestriction(anchor2, { top: 3 }), labelPrefix$2);
- };
- var east$2 = function(anchor2, element2, bubbles) {
- return nu$6(eastEdgeX$1(anchor2), centreY$1(anchor2, element2), bubbles.east(), east$3(), "east", boundsRestriction(anchor2, { left: 0 }), labelPrefix$2);
- };
- var west$2 = function(anchor2, element2, bubbles) {
- return nu$6(westEdgeX$1(anchor2, element2), centreY$1(anchor2, element2), bubbles.west(), west$3(), "west", boundsRestriction(anchor2, { right: 1 }), labelPrefix$2);
- };
- var all$1 = function() {
- return [
- southeast$2,
- southwest$2,
- northeast$2,
- northwest$2,
- south$2,
- north$2,
- east$2,
- west$2
- ];
- };
- var allRtl$1 = function() {
- return [
- southwest$2,
- southeast$2,
- northwest$2,
- northeast$2,
- south$2,
- north$2,
- east$2,
- west$2
- ];
- };
- var aboveOrBelow = function() {
- return [
- northeast$2,
- northwest$2,
- southeast$2,
- southwest$2,
- north$2,
- south$2
- ];
- };
- var aboveOrBelowRtl = function() {
- return [
- northwest$2,
- northeast$2,
- southwest$2,
- southeast$2,
- north$2,
- south$2
- ];
- };
- var belowOrAbove = function() {
- return [
- southeast$2,
- southwest$2,
- northeast$2,
- northwest$2,
- south$2,
- north$2
- ];
- };
- var belowOrAboveRtl = function() {
- return [
- southwest$2,
- southeast$2,
- northwest$2,
- northeast$2,
- south$2,
- north$2
- ];
- };
- var chooseChannels = function(channels, message) {
- return message.universal ? channels : filter$2(channels, function(ch) {
- return contains$2(message.channels, ch);
- });
- };
- var events$h = function(receiveConfig) {
- return derive$2([run$1(receive(), function(component, message) {
- var channelMap = receiveConfig.channels;
- var channels = keys(channelMap);
- var receivingData = message;
- var targetChannels = chooseChannels(channels, receivingData);
- each$1(targetChannels, function(ch) {
- var channelInfo = channelMap[ch];
- var channelSchema = channelInfo.schema;
- var data = asRawOrDie$1("channel[" + ch + "] data\nReceiver: " + element(component.element), channelSchema, receivingData.data);
- channelInfo.onReceive(component, data);
- });
- })]);
- };
- var ActiveReceiving = Object.freeze({
- __proto__: null,
- events: events$h
- });
- var ReceivingSchema = [requiredOf("channels", setOf(Result.value, objOfOnly([
- onStrictHandler("onReceive"),
- defaulted("schema", anyValue())
- ])))];
- var executeEvent = function(bConfig, bState, executor) {
- return runOnExecute$1(function(component) {
- executor(component, bConfig, bState);
- });
- };
- var loadEvent = function(bConfig, bState, f) {
- return runOnInit(function(component, _simulatedEvent) {
- f(component, bConfig, bState);
- });
- };
- var create$9 = function(schema2, name2, active2, apis, extra, state) {
- var configSchema = objOfOnly(schema2);
- var schemaSchema = optionObjOf(name2, [optionObjOfOnly("config", schema2)]);
- return doCreate(configSchema, schemaSchema, name2, active2, apis, extra, state);
- };
- var createModes$1 = function(modes, name2, active2, apis, extra, state) {
- var configSchema = modes;
- var schemaSchema = optionObjOf(name2, [optionOf("config", modes)]);
- return doCreate(configSchema, schemaSchema, name2, active2, apis, extra, state);
- };
- var wrapApi = function(bName, apiFunction, apiName) {
- var f = function(component) {
- var rest = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- rest[_i - 1] = arguments[_i];
- }
- var args = [component].concat(rest);
- return component.config({ name: constant$1(bName) }).fold(function() {
- throw new Error("We could not find any behaviour configuration for: " + bName + ". Using API: " + apiName);
- }, function(info) {
- var rest2 = Array.prototype.slice.call(args, 1);
- return apiFunction.apply(void 0, [
- component,
- info.config,
- info.state
- ].concat(rest2));
- });
- };
- return markAsBehaviourApi(f, apiName, apiFunction);
- };
- var revokeBehaviour = function(name2) {
- return {
- key: name2,
- value: void 0
- };
- };
- var doCreate = function(configSchema, schemaSchema, name2, active2, apis, extra, state) {
- var getConfig = function(info) {
- return hasNonNullableKey(info, name2) ? info[name2]() : Optional.none();
- };
- var wrappedApis = map$1(apis, function(apiF, apiName) {
- return wrapApi(name2, apiF, apiName);
- });
- var wrappedExtra = map$1(extra, function(extraF, extraName) {
- return markAsExtraApi(extraF, extraName);
- });
- var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
- revoke: curry(revokeBehaviour, name2),
- config: function(spec) {
- var prepared = asRawOrDie$1(name2 + "-config", configSchema, spec);
- return {
- key: name2,
- value: {
- config: prepared,
- me,
- configAsRaw: cached(function() {
- return asRawOrDie$1(name2 + "-config", configSchema, spec);
- }),
- initialConfig: spec,
- state
- }
- };
- },
- schema: constant$1(schemaSchema),
- exhibit: function(info, base2) {
- return lift2(getConfig(info), get$e(active2, "exhibit"), function(behaviourInfo, exhibitor) {
- return exhibitor(base2, behaviourInfo.config, behaviourInfo.state);
- }).getOrThunk(function() {
- return nu$7({});
- });
- },
- name: constant$1(name2),
- handlers: function(info) {
- return getConfig(info).map(function(behaviourInfo) {
- var getEvents2 = get$e(active2, "events").getOr(function() {
- return {};
- });
- return getEvents2(behaviourInfo.config, behaviourInfo.state);
- }).getOr({});
- }
- });
- return me;
- };
- var derive$1 = function(capabilities) {
- return wrapAll(capabilities);
- };
- var simpleSchema = objOfOnly([
- required$1("fields"),
- required$1("name"),
- defaulted("active", {}),
- defaulted("apis", {}),
- defaulted("state", NoState),
- defaulted("extra", {})
- ]);
- var create$8 = function(data) {
- var value2 = asRawOrDie$1("Creating behaviour: " + data.name, simpleSchema, data);
- return create$9(value2.fields, value2.name, value2.active, value2.apis, value2.extra, value2.state);
- };
- var modeSchema = objOfOnly([
- required$1("branchKey"),
- required$1("branches"),
- required$1("name"),
- defaulted("active", {}),
- defaulted("apis", {}),
- defaulted("state", NoState),
- defaulted("extra", {})
- ]);
- var createModes = function(data) {
- var value2 = asRawOrDie$1("Creating behaviour: " + data.name, modeSchema, data);
- return createModes$1(choose$1(value2.branchKey, value2.branches), value2.name, value2.active, value2.apis, value2.extra, value2.state);
- };
- var revoke = constant$1(void 0);
- var Receiving = create$8({
- fields: ReceivingSchema,
- name: "receiving",
- active: ActiveReceiving
- });
- var exhibit$6 = function(base2, posConfig) {
- return nu$7({
- classes: [],
- styles: posConfig.useFixed() ? {} : { position: "relative" }
- });
- };
- var ActivePosition = Object.freeze({
- __proto__: null,
- exhibit: exhibit$6
- });
- var getDocument = function() {
- return SugarElement.fromDom(document);
- };
- var focus$3 = function(element2) {
- return element2.dom.focus();
- };
- var blur$1 = function(element2) {
- return element2.dom.blur();
- };
- var hasFocus = function(element2) {
- var root = getRootNode(element2).dom;
- return element2.dom === root.activeElement;
- };
- var active = function(root) {
- if (root === void 0) {
- root = getDocument();
- }
- return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
- };
- var search = function(element2) {
- return active(getRootNode(element2)).filter(function(e) {
- return element2.dom.contains(e.dom);
- });
- };
- var preserve$1 = function(f, container) {
- var dos = getRootNode(container);
- var refocus = active(dos).bind(function(focused) {
- var hasFocus2 = function(elem) {
- return eq(focused, elem);
- };
- return hasFocus2(container) ? Optional.some(container) : descendant$1(container, hasFocus2);
- });
- var result = f(container);
- refocus.each(function(oldFocus) {
- active(dos).filter(function(newFocus) {
- return eq(newFocus, oldFocus);
- }).fold(function() {
- focus$3(oldFocus);
- }, noop);
- });
- return result;
- };
- var NuPositionCss = function(position2, left2, top2, right2, bottom2) {
- var toPx = function(num) {
- return num + "px";
- };
- return {
- position: position2,
- left: left2.map(toPx),
- top: top2.map(toPx),
- right: right2.map(toPx),
- bottom: bottom2.map(toPx)
- };
- };
- var toOptions = function(position2) {
- return __assign(__assign({}, position2), { position: Optional.some(position2.position) });
- };
- var applyPositionCss = function(element2, position2) {
- setOptions(element2, toOptions(position2));
- };
- var adt$9 = Adt.generate([
- { none: [] },
- {
- relative: [
- "x",
- "y",
- "width",
- "height"
- ]
- },
- {
- fixed: [
- "x",
- "y",
- "width",
- "height"
- ]
- }
- ]);
- var positionWithDirection = function(posName, decision, x, y, width2, height2) {
- var decisionRect = decision.rect;
- var decisionX = decisionRect.x - x;
- var decisionY = decisionRect.y - y;
- var decisionWidth = decisionRect.width;
- var decisionHeight = decisionRect.height;
- var decisionRight = width2 - (decisionX + decisionWidth);
- var decisionBottom = height2 - (decisionY + decisionHeight);
- var left2 = Optional.some(decisionX);
- var top2 = Optional.some(decisionY);
- var right2 = Optional.some(decisionRight);
- var bottom2 = Optional.some(decisionBottom);
- var none2 = Optional.none();
- return cata$2(decision.direction, function() {
- return NuPositionCss(posName, left2, top2, none2, none2);
- }, function() {
- return NuPositionCss(posName, none2, top2, right2, none2);
- }, function() {
- return NuPositionCss(posName, left2, none2, none2, bottom2);
- }, function() {
- return NuPositionCss(posName, none2, none2, right2, bottom2);
- }, function() {
- return NuPositionCss(posName, left2, top2, none2, none2);
- }, function() {
- return NuPositionCss(posName, left2, none2, none2, bottom2);
- }, function() {
- return NuPositionCss(posName, left2, top2, none2, none2);
- }, function() {
- return NuPositionCss(posName, none2, top2, right2, none2);
- });
- };
- var reposition = function(origin, decision) {
- return origin.fold(function() {
- var decisionRect = decision.rect;
- return NuPositionCss("absolute", Optional.some(decisionRect.x), Optional.some(decisionRect.y), Optional.none(), Optional.none());
- }, function(x, y, width2, height2) {
- return positionWithDirection("absolute", decision, x, y, width2, height2);
- }, function(x, y, width2, height2) {
- return positionWithDirection("fixed", decision, x, y, width2, height2);
- });
- };
- var toBox = function(origin, element2) {
- var rel = curry(find$2, element2);
- var position2 = origin.fold(rel, rel, function() {
- var scroll = get$9();
- return find$2(element2).translate(-scroll.left, -scroll.top);
- });
- var width2 = getOuter$1(element2);
- var height2 = getOuter$2(element2);
- return bounds(position2.left, position2.top, width2, height2);
- };
- var viewport = function(origin, getBounds2) {
- return getBounds2.fold(function() {
- return origin.fold(win, win, bounds);
- }, function(b2) {
- return origin.fold(b2, b2, function() {
- var bounds$12 = b2();
- var pos = translate$2(origin, bounds$12.x, bounds$12.y);
- return bounds(pos.left, pos.top, bounds$12.width, bounds$12.height);
- });
- });
- };
- var translate$2 = function(origin, x, y) {
- var pos = SugarPosition(x, y);
- var removeScroll = function() {
- var outerScroll = get$9();
- return pos.translate(-outerScroll.left, -outerScroll.top);
- };
- return origin.fold(constant$1(pos), constant$1(pos), removeScroll);
- };
- var cata$1 = function(subject, onNone, onRelative, onFixed) {
- return subject.fold(onNone, onRelative, onFixed);
- };
- adt$9.none;
- var relative$1 = adt$9.relative;
- var fixed$1 = adt$9.fixed;
- var anchor = function(anchorBox, origin) {
- return {
- anchorBox,
- origin
- };
- };
- var box = function(anchorBox, origin) {
- return anchor(anchorBox, origin);
- };
- var placementAttribute = "data-alloy-placement";
- var setPlacement$1 = function(element2, placement2) {
- set$8(element2, placementAttribute, placement2);
- };
- var getPlacement = function(element2) {
- return getOpt(element2, placementAttribute);
- };
- var reset$2 = function(element2) {
- return remove$7(element2, placementAttribute);
- };
- var adt$8 = Adt.generate([
- { fit: ["reposition"] },
- {
- nofit: [
- "reposition",
- "visibleW",
- "visibleH",
- "isVisible"
- ]
- }
- ]);
- var determinePosition = function(box2, bounds2) {
- var boundsX = bounds2.x, boundsY = bounds2.y, boundsRight = bounds2.right, boundsBottom = bounds2.bottom;
- var x = box2.x, y = box2.y, right2 = box2.right, bottom2 = box2.bottom, width2 = box2.width, height2 = box2.height;
- var xInBounds = x >= boundsX && x <= boundsRight;
- var yInBounds = y >= boundsY && y <= boundsBottom;
- var originInBounds = xInBounds && yInBounds;
- var rightInBounds = right2 <= boundsRight && right2 >= boundsX;
- var bottomInBounds = bottom2 <= boundsBottom && bottom2 >= boundsY;
- var sizeInBounds = rightInBounds && bottomInBounds;
- var visibleW = Math.min(width2, x >= boundsX ? boundsRight - x : right2 - boundsX);
- var visibleH = Math.min(height2, y >= boundsY ? boundsBottom - y : bottom2 - boundsY);
- return {
- originInBounds,
- sizeInBounds,
- visibleW,
- visibleH
- };
- };
- var calcReposition = function(box2, bounds$12) {
- var boundsX = bounds$12.x, boundsY = bounds$12.y, boundsRight = bounds$12.right, boundsBottom = bounds$12.bottom;
- var x = box2.x, y = box2.y, width2 = box2.width, height2 = box2.height;
- var maxX2 = Math.max(boundsX, boundsRight - width2);
- var maxY2 = Math.max(boundsY, boundsBottom - height2);
- var restrictedX = clamp$1(x, boundsX, maxX2);
- var restrictedY = clamp$1(y, boundsY, maxY2);
- var restrictedWidth = Math.min(restrictedX + width2, boundsRight) - restrictedX;
- var restrictedHeight = Math.min(restrictedY + height2, boundsBottom) - restrictedY;
- return bounds(restrictedX, restrictedY, restrictedWidth, restrictedHeight);
- };
- var calcMaxSizes = function(direction, box2, bounds2) {
- var upAvailable = constant$1(box2.bottom - bounds2.y);
- var downAvailable = constant$1(bounds2.bottom - box2.y);
- var maxHeight = cataVertical(direction, downAvailable, downAvailable, upAvailable);
- var westAvailable = constant$1(box2.right - bounds2.x);
- var eastAvailable = constant$1(bounds2.right - box2.x);
- var maxWidth = cataHorizontal(direction, eastAvailable, eastAvailable, westAvailable);
- return {
- maxWidth,
- maxHeight
- };
- };
- var attempt = function(candidate, width2, height2, bounds$12) {
- var bubble = candidate.bubble;
- var bubbleOffset = bubble.offset;
- var adjustedBounds = adjustBounds(bounds$12, candidate.restriction, bubbleOffset);
- var newX = candidate.x + bubbleOffset.left;
- var newY = candidate.y + bubbleOffset.top;
- var box2 = bounds(newX, newY, width2, height2);
- var _a2 = determinePosition(box2, adjustedBounds), originInBounds = _a2.originInBounds, sizeInBounds = _a2.sizeInBounds, visibleW = _a2.visibleW, visibleH = _a2.visibleH;
- var fits = originInBounds && sizeInBounds;
- var fittedBox = fits ? box2 : calcReposition(box2, adjustedBounds);
- var isPartlyVisible = fittedBox.width > 0 && fittedBox.height > 0;
- var _b = calcMaxSizes(candidate.direction, fittedBox, bounds$12), maxWidth = _b.maxWidth, maxHeight = _b.maxHeight;
- var reposition2 = {
- rect: fittedBox,
- maxHeight,
- maxWidth,
- direction: candidate.direction,
- placement: candidate.placement,
- classes: {
- on: bubble.classesOn,
- off: bubble.classesOff
- },
- layout: candidate.label,
- testY: newY
- };
- return fits || candidate.alwaysFit ? adt$8.fit(reposition2) : adt$8.nofit(reposition2, visibleW, visibleH, isPartlyVisible);
- };
- var attempts = function(element2, candidates, anchorBox, elementBox, bubbles, bounds2) {
- var panelWidth = elementBox.width;
- var panelHeight = elementBox.height;
- var attemptBestFit = function(layout2, reposition2, visibleW, visibleH, isVisible2) {
- var next = layout2(anchorBox, elementBox, bubbles, element2, bounds2);
- var attemptLayout = attempt(next, panelWidth, panelHeight, bounds2);
- return attemptLayout.fold(constant$1(attemptLayout), function(newReposition, newVisibleW, newVisibleH, newIsVisible) {
- var improved = isVisible2 === newIsVisible ? newVisibleH > visibleH || newVisibleW > visibleW : !isVisible2 && newIsVisible;
- return improved ? attemptLayout : adt$8.nofit(reposition2, visibleW, visibleH, isVisible2);
- });
- };
- var abc = foldl(candidates, function(b2, a) {
- var bestNext = curry(attemptBestFit, a);
- return b2.fold(constant$1(b2), bestNext);
- }, adt$8.nofit({
- rect: anchorBox,
- maxHeight: elementBox.height,
- maxWidth: elementBox.width,
- direction: southeast$3(),
- placement: "southeast",
- classes: {
- on: [],
- off: []
- },
- layout: "none",
- testY: anchorBox.y
- }, -1, -1, false));
- return abc.fold(identity$1, identity$1);
- };
- var singleton = function(doRevoke) {
- var subject = Cell(Optional.none());
- var revoke2 = function() {
- return subject.get().each(doRevoke);
- };
- var clear2 = function() {
- revoke2();
- subject.set(Optional.none());
- };
- var isSet = function() {
- return subject.get().isSome();
- };
- var get2 = function() {
- return subject.get();
- };
- var set2 = function(s) {
- revoke2();
- subject.set(Optional.some(s));
- };
- return {
- clear: clear2,
- isSet,
- get: get2,
- set: set2
- };
- };
- var destroyable = function() {
- return singleton(function(s) {
- return s.destroy();
- });
- };
- var unbindable = function() {
- return singleton(function(s) {
- return s.unbind();
- });
- };
- var api$1 = function() {
- var subject = destroyable();
- var run2 = function(f) {
- return subject.get().each(f);
- };
- return __assign(__assign({}, subject), { run: run2 });
- };
- var value$1 = function() {
- var subject = singleton(noop);
- var on2 = function(f) {
- return subject.get().each(f);
- };
- return __assign(__assign({}, subject), { on: on2 });
- };
- var filter = always;
- var bind = function(element2, event, handler) {
- return bind$2(element2, event, filter, handler);
- };
- var capture = function(element2, event, handler) {
- return capture$1(element2, event, filter, handler);
- };
- var fromRawEvent = fromRawEvent$1;
- var properties = [
- "top",
- "bottom",
- "right",
- "left"
- ];
- var timerAttr = "data-alloy-transition-timer";
- var isTransitioning$1 = function(element2, transition) {
- return hasAll(element2, transition.classes);
- };
- var shouldApplyTransitionCss = function(transition, decision, lastPlacement) {
- return lastPlacement.exists(function(placer) {
- var mode = transition.mode;
- return mode === "all" ? true : placer[mode] !== decision[mode];
- });
- };
- var hasChanges = function(position2, intermediate) {
- var round2 = function(value2) {
- return parseFloat(value2).toFixed(3);
- };
- return find$4(intermediate, function(value2, key) {
- var newValue = position2[key].map(round2);
- var val = value2.map(round2);
- return !equals(newValue, val);
- }).isSome();
- };
- var getTransitionDuration = function(element2) {
- var get2 = function(name2) {
- var style = get$c(element2, name2);
- var times = isString(style) ? style.split(/\s*,\s*/) : [];
- return filter$2(times, isNotEmpty);
- };
- var parse2 = function(value2) {
- if (isString(value2) && /^[\d.]+/.test(value2)) {
- var num = parseFloat(value2);
- return endsWith(value2, "ms") ? num : num * 1e3;
- } else {
- return 0;
- }
- };
- var delay = get2("transition-delay");
- var duration = get2("transition-duration");
- return foldl(duration, function(acc, dur, i) {
- var time = parse2(delay[i]) + parse2(dur);
- return Math.max(acc, time);
- }, 0);
- };
- var setupTransitionListeners = function(element2, transition) {
- var transitionEnd = unbindable();
- var transitionCancel = unbindable();
- var timer;
- var isSourceTransition = function(e) {
- var _a2;
- var pseudoElement = (_a2 = e.raw.pseudoElement) !== null && _a2 !== void 0 ? _a2 : "";
- return eq(e.target, element2) && isEmpty(pseudoElement) && contains$2(properties, e.raw.propertyName);
- };
- var transitionDone = function(e) {
- if (isNullable(e) || isSourceTransition(e)) {
- transitionEnd.clear();
- transitionCancel.clear();
- var type2 = e === null || e === void 0 ? void 0 : e.raw.type;
- if (isNullable(type2) || type2 === transitionend()) {
- clearTimeout(timer);
- remove$7(element2, timerAttr);
- remove$1(element2, transition.classes);
- }
- }
- };
- var transitionStarted = function() {
- transitionEnd.set(bind(element2, transitionend(), transitionDone));
- transitionCancel.set(bind(element2, transitioncancel(), transitionDone));
- };
- if ("ontransitionstart" in element2.dom) {
- var transitionStart_1 = bind(element2, transitionstart(), function(e) {
- if (isSourceTransition(e)) {
- transitionStart_1.unbind();
- transitionStarted();
- }
- });
- } else {
- transitionStarted();
- }
- var duration = getTransitionDuration(element2);
- requestAnimationFrame(function() {
- timer = setTimeout(transitionDone, duration + 17);
- set$8(element2, timerAttr, timer);
- });
- };
- var startTransitioning = function(element2, transition) {
- add$1(element2, transition.classes);
- getOpt(element2, timerAttr).each(function(timerId) {
- clearTimeout(parseInt(timerId, 10));
- remove$7(element2, timerAttr);
- });
- setupTransitionListeners(element2, transition);
- };
- var applyTransitionCss = function(element2, origin, position2, transition, decision, lastPlacement) {
- var shouldTransition = shouldApplyTransitionCss(transition, decision, lastPlacement);
- if (shouldTransition || isTransitioning$1(element2, transition)) {
- set$7(element2, "position", position2.position);
- var rect2 = toBox(origin, element2);
- var intermediatePosition_1 = reposition(origin, __assign(__assign({}, decision), { rect: rect2 }));
- var intermediateCssOptions = mapToObject(properties, function(prop) {
- return intermediatePosition_1[prop];
- });
- if (hasChanges(position2, intermediateCssOptions)) {
- setOptions(element2, intermediateCssOptions);
- if (shouldTransition) {
- startTransitioning(element2, transition);
- }
- reflow(element2);
- }
- } else {
- remove$1(element2, transition.classes);
- }
- };
- var elementSize = function(p) {
- return {
- width: getOuter$1(p),
- height: getOuter$2(p)
- };
- };
- var layout = function(anchorBox, element2, bubbles, options) {
- remove$6(element2, "max-height");
- remove$6(element2, "max-width");
- var elementBox = elementSize(element2);
- return attempts(element2, options.preference, anchorBox, elementBox, bubbles, options.bounds);
- };
- var setClasses = function(element2, decision) {
- var classInfo = decision.classes;
- remove$1(element2, classInfo.off);
- add$1(element2, classInfo.on);
- };
- var setHeight = function(element2, decision, options) {
- var maxHeightFunction = options.maxHeightFunction;
- maxHeightFunction(element2, decision.maxHeight);
- };
- var setWidth = function(element2, decision, options) {
- var maxWidthFunction = options.maxWidthFunction;
- maxWidthFunction(element2, decision.maxWidth);
- };
- var position$2 = function(element2, decision, options) {
- var positionCss = reposition(options.origin, decision);
- options.transition.each(function(transition) {
- applyTransitionCss(element2, options.origin, positionCss, transition, decision, options.lastPlacement);
- });
- applyPositionCss(element2, positionCss);
- };
- var setPlacement = function(element2, decision) {
- setPlacement$1(element2, decision.placement);
- };
- var setMaxHeight = function(element2, maxHeight) {
- setMax$1(element2, Math.floor(maxHeight));
- };
- var anchored = constant$1(function(element2, available) {
- setMaxHeight(element2, available);
- setAll(element2, {
- "overflow-x": "hidden",
- "overflow-y": "auto"
- });
- });
- var expandable$1 = constant$1(function(element2, available) {
- setMaxHeight(element2, available);
- });
- var defaultOr = function(options, key, dephault) {
- return options[key] === void 0 ? dephault : options[key];
- };
- var simple = function(anchor2, element2, bubble, layouts2, lastPlacement, getBounds2, overrideOptions, transition) {
- var maxHeightFunction = defaultOr(overrideOptions, "maxHeightFunction", anchored());
- var maxWidthFunction = defaultOr(overrideOptions, "maxWidthFunction", noop);
- var anchorBox = anchor2.anchorBox;
- var origin = anchor2.origin;
- var options = {
- bounds: viewport(origin, getBounds2),
- origin,
- preference: layouts2,
- maxHeightFunction,
- maxWidthFunction,
- lastPlacement,
- transition
- };
- return go(anchorBox, element2, bubble, options);
- };
- var go = function(anchorBox, element2, bubble, options) {
- var decision = layout(anchorBox, element2, bubble, options);
- position$2(element2, decision, options);
- setPlacement(element2, decision);
- setClasses(element2, decision);
- setHeight(element2, decision, options);
- setWidth(element2, decision, options);
- return {
- layout: decision.layout,
- placement: decision.placement
- };
- };
- var allAlignments = [
- "valignCentre",
- "alignLeft",
- "alignRight",
- "alignCentre",
- "top",
- "bottom",
- "left",
- "right",
- "inset"
- ];
- var nu$5 = function(xOffset, yOffset, classes2, insetModifier) {
- if (insetModifier === void 0) {
- insetModifier = 1;
- }
- var insetXOffset = xOffset * insetModifier;
- var insetYOffset = yOffset * insetModifier;
- var getClasses2 = function(prop) {
- return get$e(classes2, prop).getOr([]);
- };
- var make2 = function(xDelta, yDelta, alignmentsOn) {
- var alignmentsOff = difference(allAlignments, alignmentsOn);
- return {
- offset: SugarPosition(xDelta, yDelta),
- classesOn: bind$3(alignmentsOn, getClasses2),
- classesOff: bind$3(alignmentsOff, getClasses2)
- };
- };
- return {
- southeast: function() {
- return make2(-xOffset, yOffset, [
- "top",
- "alignLeft"
- ]);
- },
- southwest: function() {
- return make2(xOffset, yOffset, [
- "top",
- "alignRight"
- ]);
- },
- south: function() {
- return make2(-xOffset / 2, yOffset, [
- "top",
- "alignCentre"
- ]);
- },
- northeast: function() {
- return make2(-xOffset, -yOffset, [
- "bottom",
- "alignLeft"
- ]);
- },
- northwest: function() {
- return make2(xOffset, -yOffset, [
- "bottom",
- "alignRight"
- ]);
- },
- north: function() {
- return make2(-xOffset / 2, -yOffset, [
- "bottom",
- "alignCentre"
- ]);
- },
- east: function() {
- return make2(xOffset, -yOffset / 2, [
- "valignCentre",
- "left"
- ]);
- },
- west: function() {
- return make2(-xOffset, -yOffset / 2, [
- "valignCentre",
- "right"
- ]);
- },
- insetNortheast: function() {
- return make2(insetXOffset, insetYOffset, [
- "top",
- "alignLeft",
- "inset"
- ]);
- },
- insetNorthwest: function() {
- return make2(-insetXOffset, insetYOffset, [
- "top",
- "alignRight",
- "inset"
- ]);
- },
- insetNorth: function() {
- return make2(-insetXOffset / 2, insetYOffset, [
- "top",
- "alignCentre",
- "inset"
- ]);
- },
- insetSoutheast: function() {
- return make2(insetXOffset, -insetYOffset, [
- "bottom",
- "alignLeft",
- "inset"
- ]);
- },
- insetSouthwest: function() {
- return make2(-insetXOffset, -insetYOffset, [
- "bottom",
- "alignRight",
- "inset"
- ]);
- },
- insetSouth: function() {
- return make2(-insetXOffset / 2, -insetYOffset, [
- "bottom",
- "alignCentre",
- "inset"
- ]);
- },
- insetEast: function() {
- return make2(-insetXOffset, -insetYOffset / 2, [
- "valignCentre",
- "right",
- "inset"
- ]);
- },
- insetWest: function() {
- return make2(insetXOffset, -insetYOffset / 2, [
- "valignCentre",
- "left",
- "inset"
- ]);
- }
- };
- };
- var fallback = function() {
- return nu$5(0, 0, {});
- };
- var nu$4 = identity$1;
- var onDirection = function(isLtr, isRtl) {
- return function(element2) {
- return getDirection(element2) === "rtl" ? isRtl : isLtr;
- };
- };
- var getDirection = function(element2) {
- return get$c(element2, "direction") === "rtl" ? "rtl" : "ltr";
- };
- var AttributeValue;
- (function(AttributeValue2) {
- AttributeValue2["TopToBottom"] = "toptobottom";
- AttributeValue2["BottomToTop"] = "bottomtotop";
- })(AttributeValue || (AttributeValue = {}));
- var Attribute = "data-alloy-vertical-dir";
- var isBottomToTopDir = function(el) {
- return closest$2(el, function(current) {
- return isElement$2(current) && get$d(current, "data-alloy-vertical-dir") === AttributeValue.BottomToTop;
- });
- };
- var schema$y = function() {
- return optionObjOf("layouts", [
- required$1("onLtr"),
- required$1("onRtl"),
- option("onBottomLtr"),
- option("onBottomRtl")
- ]);
- };
- var get$4 = function(elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) {
- var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
- var customLtr = info.layouts.map(function(ls) {
- return ls.onLtr(elem);
- });
- var customRtl = info.layouts.map(function(ls) {
- return ls.onRtl(elem);
- });
- var ltr = isBottomToTop ? info.layouts.bind(function(ls) {
- return ls.onBottomLtr.map(function(f2) {
- return f2(elem);
- });
- }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
- var rtl = isBottomToTop ? info.layouts.bind(function(ls) {
- return ls.onBottomRtl.map(function(f2) {
- return f2(elem);
- });
- }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
- var f = onDirection(ltr, rtl);
- return f(elem);
- };
- var placement$4 = function(component, anchorInfo, origin) {
- var hotspot = anchorInfo.hotspot;
- var anchorBox = toBox(origin, hotspot.element);
- var layouts2 = get$4(component.element, anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Optional.some(anchorInfo.hotspot.element));
- return Optional.some(nu$4({
- anchorBox,
- bubble: anchorInfo.bubble.getOr(fallback()),
- overrides: anchorInfo.overrides,
- layouts: layouts2,
- placer: Optional.none()
- }));
- };
- var HotspotAnchor = [
- required$1("hotspot"),
- option("bubble"),
- defaulted("overrides", {}),
- schema$y(),
- output$1("placement", placement$4)
- ];
- var placement$3 = function(component, anchorInfo, origin) {
- var pos = translate$2(origin, anchorInfo.x, anchorInfo.y);
- var anchorBox = bounds(pos.left, pos.top, anchorInfo.width, anchorInfo.height);
- var layouts2 = get$4(component.element, anchorInfo, all$1(), allRtl$1(), all$1(), allRtl$1(), Optional.none());
- return Optional.some(nu$4({
- anchorBox,
- bubble: anchorInfo.bubble,
- overrides: anchorInfo.overrides,
- layouts: layouts2,
- placer: Optional.none()
- }));
- };
- var MakeshiftAnchor = [
- required$1("x"),
- required$1("y"),
- defaulted("height", 0),
- defaulted("width", 0),
- defaulted("bubble", fallback()),
- defaulted("overrides", {}),
- schema$y(),
- output$1("placement", placement$3)
- ];
- var adt$7 = Adt.generate([
- { screen: ["point"] },
- {
- absolute: [
- "point",
- "scrollLeft",
- "scrollTop"
- ]
- }
- ]);
- var toFixed = function(pos) {
- return pos.fold(identity$1, function(point2, scrollLeft, scrollTop) {
- return point2.translate(-scrollLeft, -scrollTop);
- });
- };
- var toAbsolute = function(pos) {
- return pos.fold(identity$1, identity$1);
- };
- var sum = function(points) {
- return foldl(points, function(b2, a) {
- return b2.translate(a.left, a.top);
- }, SugarPosition(0, 0));
- };
- var sumAsFixed = function(positions) {
- var points = map$2(positions, toFixed);
- return sum(points);
- };
- var sumAsAbsolute = function(positions) {
- var points = map$2(positions, toAbsolute);
- return sum(points);
- };
- var screen = adt$7.screen;
- var absolute$1 = adt$7.absolute;
- var getOffset = function(component, origin, anchorInfo) {
- var win2 = defaultView(anchorInfo.root).dom;
- var hasSameOwner = function(frame) {
- var frameOwner = owner$4(frame);
- var compOwner = owner$4(component.element);
- return eq(frameOwner, compOwner);
- };
- return Optional.from(win2.frameElement).map(SugarElement.fromDom).filter(hasSameOwner).map(absolute$3);
- };
- var getRootPoint = function(component, origin, anchorInfo) {
- var doc = owner$4(component.element);
- var outerScroll = get$9(doc);
- var offset2 = getOffset(component, origin, anchorInfo).getOr(outerScroll);
- return absolute$1(offset2, outerScroll.left, outerScroll.top);
- };
- var getBox = function(left2, top2, width2, height2) {
- var point2 = screen(SugarPosition(left2, top2));
- return Optional.some(pointed(point2, width2, height2));
- };
- var calcNewAnchor = function(optBox, rootPoint, anchorInfo, origin, elem) {
- return optBox.map(function(box2) {
- var points = [
- rootPoint,
- box2.point
- ];
- var topLeft = cata$1(origin, function() {
- return sumAsAbsolute(points);
- }, function() {
- return sumAsAbsolute(points);
- }, function() {
- return sumAsFixed(points);
- });
- var anchorBox = rect(topLeft.left, topLeft.top, box2.width, box2.height);
- var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
- var layoutsRtl = anchorInfo.showAbove ? aboveOrBelowRtl() : belowOrAboveRtl();
- var layouts2 = get$4(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Optional.none());
- return nu$4({
- anchorBox,
- bubble: anchorInfo.bubble.getOr(fallback()),
- overrides: anchorInfo.overrides,
- layouts: layouts2,
- placer: Optional.none()
- });
- });
- };
- var placement$2 = function(component, anchorInfo, origin) {
- var rootPoint = getRootPoint(component, origin, anchorInfo);
- return anchorInfo.node.filter(inBody).bind(function(target) {
- var rect2 = target.dom.getBoundingClientRect();
- var nodeBox = getBox(rect2.left, rect2.top, rect2.width, rect2.height);
- var elem = anchorInfo.node.getOr(component.element);
- return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
- });
- };
- var NodeAnchor = [
- required$1("node"),
- required$1("root"),
- option("bubble"),
- schema$y(),
- defaulted("overrides", {}),
- defaulted("showAbove", false),
- output$1("placement", placement$2)
- ];
- var zeroWidth = "\uFEFF";
- var nbsp = " ";
- var create$7 = function(start, soffset, finish, foffset) {
- return {
- start,
- soffset,
- finish,
- foffset
- };
- };
- var SimRange = { create: create$7 };
- var adt$6 = Adt.generate([
- { before: ["element"] },
- {
- on: [
- "element",
- "offset"
- ]
- },
- { after: ["element"] }
- ]);
- var cata = function(subject, onBefore, onOn, onAfter) {
- return subject.fold(onBefore, onOn, onAfter);
- };
- var getStart$1 = function(situ) {
- return situ.fold(identity$1, identity$1, identity$1);
- };
- var before = adt$6.before;
- var on$1 = adt$6.on;
- var after$1 = adt$6.after;
- var Situ = {
- before,
- on: on$1,
- after: after$1,
- cata,
- getStart: getStart$1
- };
- var adt$5 = Adt.generate([
- { domRange: ["rng"] },
- {
- relative: [
- "startSitu",
- "finishSitu"
- ]
- },
- {
- exact: [
- "start",
- "soffset",
- "finish",
- "foffset"
- ]
- }
- ]);
- var exactFromRange = function(simRange) {
- return adt$5.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
- };
- var getStart = function(selection) {
- return selection.match({
- domRange: function(rng) {
- return SugarElement.fromDom(rng.startContainer);
- },
- relative: function(startSitu, _finishSitu) {
- return Situ.getStart(startSitu);
- },
- exact: function(start, _soffset, _finish, _foffset) {
- return start;
- }
- });
- };
- var domRange = adt$5.domRange;
- var relative = adt$5.relative;
- var exact = adt$5.exact;
- var getWin = function(selection) {
- var start = getStart(selection);
- return defaultView(start);
- };
- var range$1 = SimRange.create;
- var SimSelection = {
- domRange,
- relative,
- exact,
- exactFromRange,
- getWin,
- range: range$1
- };
- var setStart = function(rng, situ) {
- situ.fold(function(e) {
- rng.setStartBefore(e.dom);
- }, function(e, o) {
- rng.setStart(e.dom, o);
- }, function(e) {
- rng.setStartAfter(e.dom);
- });
- };
- var setFinish = function(rng, situ) {
- situ.fold(function(e) {
- rng.setEndBefore(e.dom);
- }, function(e, o) {
- rng.setEnd(e.dom, o);
- }, function(e) {
- rng.setEndAfter(e.dom);
- });
- };
- var relativeToNative = function(win2, startSitu, finishSitu) {
- var range2 = win2.document.createRange();
- setStart(range2, startSitu);
- setFinish(range2, finishSitu);
- return range2;
- };
- var exactToNative = function(win2, start, soffset, finish, foffset) {
- var rng = win2.document.createRange();
- rng.setStart(start.dom, soffset);
- rng.setEnd(finish.dom, foffset);
- return rng;
- };
- var toRect = function(rect2) {
- return {
- left: rect2.left,
- top: rect2.top,
- right: rect2.right,
- bottom: rect2.bottom,
- width: rect2.width,
- height: rect2.height
- };
- };
- var getFirstRect$1 = function(rng) {
- var rects = rng.getClientRects();
- var rect2 = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
- return rect2.width > 0 || rect2.height > 0 ? Optional.some(rect2).map(toRect) : Optional.none();
- };
- var getBounds$2 = function(rng) {
- var rect2 = rng.getBoundingClientRect();
- return rect2.width > 0 || rect2.height > 0 ? Optional.some(rect2).map(toRect) : Optional.none();
- };
- var adt$4 = Adt.generate([
- {
- ltr: [
- "start",
- "soffset",
- "finish",
- "foffset"
- ]
- },
- {
- rtl: [
- "start",
- "soffset",
- "finish",
- "foffset"
- ]
- }
- ]);
- var fromRange = function(win2, type2, range2) {
- return type2(SugarElement.fromDom(range2.startContainer), range2.startOffset, SugarElement.fromDom(range2.endContainer), range2.endOffset);
- };
- var getRanges = function(win2, selection) {
- return selection.match({
- domRange: function(rng) {
- return {
- ltr: constant$1(rng),
- rtl: Optional.none
- };
- },
- relative: function(startSitu, finishSitu) {
- return {
- ltr: cached(function() {
- return relativeToNative(win2, startSitu, finishSitu);
- }),
- rtl: cached(function() {
- return Optional.some(relativeToNative(win2, finishSitu, startSitu));
- })
- };
- },
- exact: function(start, soffset, finish, foffset) {
- return {
- ltr: cached(function() {
- return exactToNative(win2, start, soffset, finish, foffset);
- }),
- rtl: cached(function() {
- return Optional.some(exactToNative(win2, finish, foffset, start, soffset));
- })
- };
- }
- });
- };
- var doDiagnose = function(win2, ranges) {
- var rng = ranges.ltr();
- if (rng.collapsed) {
- var reversed = ranges.rtl().filter(function(rev) {
- return rev.collapsed === false;
- });
- return reversed.map(function(rev) {
- return adt$4.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
- }).getOrThunk(function() {
- return fromRange(win2, adt$4.ltr, rng);
- });
- } else {
- return fromRange(win2, adt$4.ltr, rng);
- }
- };
- var diagnose = function(win2, selection) {
- var ranges = getRanges(win2, selection);
- return doDiagnose(win2, ranges);
- };
- var asLtrRange = function(win2, selection) {
- var diagnosis = diagnose(win2, selection);
- return diagnosis.match({
- ltr: function(start, soffset, finish, foffset) {
- var rng = win2.document.createRange();
- rng.setStart(start.dom, soffset);
- rng.setEnd(finish.dom, foffset);
- return rng;
- },
- rtl: function(start, soffset, finish, foffset) {
- var rng = win2.document.createRange();
- rng.setStart(finish.dom, foffset);
- rng.setEnd(start.dom, soffset);
- return rng;
- }
- });
- };
- adt$4.ltr;
- adt$4.rtl;
- var NodeValue = function(is2, name2) {
- var get2 = function(element2) {
- if (!is2(element2)) {
- throw new Error("Can only get " + name2 + " value of a " + name2 + " node");
- }
- return getOption2(element2).getOr("");
- };
- var getOption2 = function(element2) {
- return is2(element2) ? Optional.from(element2.dom.nodeValue) : Optional.none();
- };
- var set2 = function(element2, value2) {
- if (!is2(element2)) {
- throw new Error("Can only set raw " + name2 + " value of a " + name2 + " node");
- }
- element2.dom.nodeValue = value2;
- };
- return {
- get: get2,
- getOption: getOption2,
- set: set2
- };
- };
- var api = NodeValue(isText$1, "text");
- var get$3 = function(element2) {
- return api.get(element2);
- };
- var getOption = function(element2) {
- return api.getOption(element2);
- };
- var getEnd = function(element2) {
- return name$2(element2) === "img" ? 1 : getOption(element2).fold(function() {
- return children(element2).length;
- }, function(v) {
- return v.length;
- });
- };
- var isTextNodeWithCursorPosition = function(el) {
- return getOption(el).filter(function(text2) {
- return text2.trim().length !== 0 || text2.indexOf(nbsp) > -1;
- }).isSome();
- };
- var elementsWithCursorPosition = [
- "img",
- "br"
- ];
- var isCursorPosition = function(elem) {
- var hasCursorPosition = isTextNodeWithCursorPosition(elem);
- return hasCursorPosition || contains$2(elementsWithCursorPosition, name$2(elem));
- };
- var last$1 = function(element2) {
- return descendantRtl(element2, isCursorPosition);
- };
- var descendantRtl = function(scope, predicate) {
- var descend = function(element2) {
- var children$1 = children(element2);
- for (var i = children$1.length - 1; i >= 0; i--) {
- var child2 = children$1[i];
- if (predicate(child2)) {
- return Optional.some(child2);
- }
- var res = descend(child2);
- if (res.isSome()) {
- return res;
- }
- }
- return Optional.none();
- };
- return descend(scope);
- };
- var descendants = function(scope, selector) {
- return all$3(selector, scope);
- };
- var makeRange = function(start, soffset, finish, foffset) {
- var doc = owner$4(start);
- var rng = doc.dom.createRange();
- rng.setStart(start.dom, soffset);
- rng.setEnd(finish.dom, foffset);
- return rng;
- };
- var after = function(start, soffset, finish, foffset) {
- var r2 = makeRange(start, soffset, finish, foffset);
- var same = eq(start, finish) && soffset === foffset;
- return r2.collapsed && !same;
- };
- var getNativeSelection = function(win2) {
- return Optional.from(win2.getSelection());
- };
- var readRange = function(selection) {
- if (selection.rangeCount > 0) {
- var firstRng = selection.getRangeAt(0);
- var lastRng = selection.getRangeAt(selection.rangeCount - 1);
- return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
- } else {
- return Optional.none();
- }
- };
- var doGetExact = function(selection) {
- if (selection.anchorNode === null || selection.focusNode === null) {
- return readRange(selection);
- } else {
- var anchor2 = SugarElement.fromDom(selection.anchorNode);
- var focus_1 = SugarElement.fromDom(selection.focusNode);
- return after(anchor2, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor2, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
- }
- };
- var getExact = function(win2) {
- return getNativeSelection(win2).filter(function(sel) {
- return sel.rangeCount > 0;
- }).bind(doGetExact);
- };
- var getFirstRect = function(win2, selection) {
- var rng = asLtrRange(win2, selection);
- return getFirstRect$1(rng);
- };
- var getBounds$1 = function(win2, selection) {
- var rng = asLtrRange(win2, selection);
- return getBounds$2(rng);
- };
- var point$1 = function(element2, offset2) {
- return {
- element: element2,
- offset: offset2
- };
- };
- var descendOnce$1 = function(element2, offset2) {
- var children$1 = children(element2);
- if (children$1.length === 0) {
- return point$1(element2, offset2);
- } else if (offset2 < children$1.length) {
- return point$1(children$1[offset2], 0);
- } else {
- var last2 = children$1[children$1.length - 1];
- var len = isText$1(last2) ? get$3(last2).length : children(last2).length;
- return point$1(last2, len);
- }
- };
- var descendOnce = function(element2, offset2) {
- return isText$1(element2) ? point$1(element2, offset2) : descendOnce$1(element2, offset2);
- };
- var getAnchorSelection = function(win2, anchorInfo) {
- var getSelection = anchorInfo.getSelection.getOrThunk(function() {
- return function() {
- return getExact(win2);
- };
- });
- return getSelection().map(function(sel) {
- var modStart = descendOnce(sel.start, sel.soffset);
- var modFinish = descendOnce(sel.finish, sel.foffset);
- return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
- });
- };
- var placement$1 = function(component, anchorInfo, origin) {
- var win2 = defaultView(anchorInfo.root).dom;
- var rootPoint = getRootPoint(component, origin, anchorInfo);
- var selectionBox = getAnchorSelection(win2, anchorInfo).bind(function(sel) {
- var optRect = getBounds$1(win2, SimSelection.exactFromRange(sel)).orThunk(function() {
- var x = SugarElement.fromText(zeroWidth);
- before$2(sel.start, x);
- var rect2 = getFirstRect(win2, SimSelection.exact(x, 0, x, 1));
- remove$5(x);
- return rect2;
- });
- return optRect.bind(function(rawRect) {
- return getBox(rawRect.left, rawRect.top, rawRect.width, rawRect.height);
- });
- });
- var targetElement = getAnchorSelection(win2, anchorInfo).bind(function(sel) {
- return isElement$2(sel.start) ? Optional.some(sel.start) : parentNode(sel.start);
- });
- var elem = targetElement.getOr(component.element);
- return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
- };
- var SelectionAnchor = [
- option("getSelection"),
- required$1("root"),
- option("bubble"),
- schema$y(),
- defaulted("overrides", {}),
- defaulted("showAbove", false),
- output$1("placement", placement$1)
- ];
- var labelPrefix$1 = "link-layout";
- var eastX = function(anchor2) {
- return anchor2.x + anchor2.width;
- };
- var westX = function(anchor2, element2) {
- return anchor2.x - element2.width;
- };
- var northY$1 = function(anchor2, element2) {
- return anchor2.y - element2.height + anchor2.height;
- };
- var southY$1 = function(anchor2) {
- return anchor2.y;
- };
- var southeast$1 = function(anchor2, element2, bubbles) {
- return nu$6(eastX(anchor2), southY$1(anchor2), bubbles.southeast(), southeast$3(), "southeast", boundsRestriction(anchor2, {
- left: 0,
- top: 2
- }), labelPrefix$1);
- };
- var southwest$1 = function(anchor2, element2, bubbles) {
- return nu$6(westX(anchor2, element2), southY$1(anchor2), bubbles.southwest(), southwest$3(), "southwest", boundsRestriction(anchor2, {
- right: 1,
- top: 2
- }), labelPrefix$1);
- };
- var northeast$1 = function(anchor2, element2, bubbles) {
- return nu$6(eastX(anchor2), northY$1(anchor2, element2), bubbles.northeast(), northeast$3(), "northeast", boundsRestriction(anchor2, {
- left: 0,
- bottom: 3
- }), labelPrefix$1);
- };
- var northwest$1 = function(anchor2, element2, bubbles) {
- return nu$6(westX(anchor2, element2), northY$1(anchor2, element2), bubbles.northwest(), northwest$3(), "northwest", boundsRestriction(anchor2, {
- right: 1,
- bottom: 3
- }), labelPrefix$1);
- };
- var all = function() {
- return [
- southeast$1,
- southwest$1,
- northeast$1,
- northwest$1
- ];
- };
- var allRtl = function() {
- return [
- southwest$1,
- southeast$1,
- northwest$1,
- northeast$1
- ];
- };
- var placement = function(component, submenuInfo, origin) {
- var anchorBox = toBox(origin, submenuInfo.item.element);
- var layouts2 = get$4(component.element, submenuInfo, all(), allRtl(), all(), allRtl(), Optional.none());
- return Optional.some(nu$4({
- anchorBox,
- bubble: fallback(),
- overrides: submenuInfo.overrides,
- layouts: layouts2,
- placer: Optional.none()
- }));
- };
- var SubmenuAnchor = [
- required$1("item"),
- schema$y(),
- defaulted("overrides", {}),
- output$1("placement", placement)
- ];
- var AnchorSchema = choose$1("type", {
- selection: SelectionAnchor,
- node: NodeAnchor,
- hotspot: HotspotAnchor,
- submenu: SubmenuAnchor,
- makeshift: MakeshiftAnchor
- });
- var TransitionSchema = [
- requiredArrayOf("classes", string),
- defaultedStringEnum("mode", "all", [
- "all",
- "layout",
- "placement"
- ])
- ];
- var PositionSchema = [
- defaulted("useFixed", never),
- option("getBounds")
- ];
- var PlacementSchema = [
- requiredOf("anchor", AnchorSchema),
- optionObjOf("transition", TransitionSchema)
- ];
- var getFixedOrigin = function() {
- var html2 = document.documentElement;
- return fixed$1(0, 0, html2.clientWidth, html2.clientHeight);
- };
- var getRelativeOrigin = function(component) {
- var position2 = absolute$3(component.element);
- var bounds2 = component.element.dom.getBoundingClientRect();
- return relative$1(position2.left, position2.top, bounds2.width, bounds2.height);
- };
- var place = function(component, origin, anchoring, getBounds2, placee, lastPlace, transition) {
- var anchor2 = box(anchoring.anchorBox, origin);
- return simple(anchor2, placee.element, anchoring.bubble, anchoring.layouts, lastPlace, getBounds2, anchoring.overrides, transition);
- };
- var position$1 = function(component, posConfig, posState, placee, placementSpec) {
- positionWithin(component, posConfig, posState, placee, placementSpec, Optional.none());
- };
- var positionWithin = function(component, posConfig, posState, placee, placementSpec, boxElement) {
- var boundsBox = boxElement.map(box$1);
- return positionWithinBounds(component, posConfig, posState, placee, placementSpec, boundsBox);
- };
- var positionWithinBounds = function(component, posConfig, posState, placee, placementSpec, bounds2) {
- var placeeDetail = asRawOrDie$1("placement.info", objOf(PlacementSchema), placementSpec);
- var anchorage = placeeDetail.anchor;
- var element2 = placee.element;
- var placeeState = posState.get(placee.uid);
- preserve$1(function() {
- set$7(element2, "position", "fixed");
- var oldVisibility = getRaw(element2, "visibility");
- set$7(element2, "visibility", "hidden");
- var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
- var placer = anchorage.placement;
- var getBounds2 = bounds2.map(constant$1).or(posConfig.getBounds);
- placer(component, anchorage, origin).each(function(anchoring) {
- var doPlace = anchoring.placer.getOr(place);
- var newState = doPlace(component, origin, anchoring, getBounds2, placee, placeeState, placeeDetail.transition);
- posState.set(placee.uid, newState);
- });
- oldVisibility.fold(function() {
- remove$6(element2, "visibility");
- }, function(vis) {
- set$7(element2, "visibility", vis);
- });
- if (getRaw(element2, "left").isNone() && getRaw(element2, "top").isNone() && getRaw(element2, "right").isNone() && getRaw(element2, "bottom").isNone() && is$1(getRaw(element2, "position"), "fixed")) {
- remove$6(element2, "position");
- }
- }, element2);
- };
- var getMode = function(component, pConfig, _pState) {
- return pConfig.useFixed() ? "fixed" : "absolute";
- };
- var reset$1 = function(component, pConfig, posState, placee) {
- var element2 = placee.element;
- each$1([
- "position",
- "left",
- "right",
- "top",
- "bottom"
- ], function(prop) {
- return remove$6(element2, prop);
- });
- reset$2(element2);
- posState.clear(placee.uid);
- };
- var PositionApis = Object.freeze({
- __proto__: null,
- position: position$1,
- positionWithin,
- positionWithinBounds,
- getMode,
- reset: reset$1
- });
- var init$g = function() {
- var state = {};
- var set2 = function(id, data) {
- state[id] = data;
- };
- var get2 = function(id) {
- return get$e(state, id);
- };
- var clear2 = function(id) {
- if (isNonNullable(id)) {
- delete state[id];
- } else {
- state = {};
- }
- };
- return nu$8({
- readState: function() {
- return state;
- },
- clear: clear2,
- set: set2,
- get: get2
- });
- };
- var PositioningState = Object.freeze({
- __proto__: null,
- init: init$g
- });
- var Positioning = create$8({
- fields: PositionSchema,
- name: "positioning",
- active: ActivePosition,
- apis: PositionApis,
- state: PositioningState
- });
- var fireDetaching = function(component) {
- emit(component, detachedFromDom());
- var children2 = component.components();
- each$1(children2, fireDetaching);
- };
- var fireAttaching = function(component) {
- var children2 = component.components();
- each$1(children2, fireAttaching);
- emit(component, attachedToDom());
- };
- var attach$1 = function(parent2, child2) {
- append$2(parent2.element, child2.element);
- };
- var detachChildren$1 = function(component) {
- each$1(component.components(), function(childComp) {
- return remove$5(childComp.element);
- });
- empty(component.element);
- component.syncComponents();
- };
- var replaceChildren = function(component, newChildren) {
- var subs2 = component.components();
- detachChildren$1(component);
- var deleted = difference(subs2, newChildren);
- each$1(deleted, function(comp) {
- fireDetaching(comp);
- component.getSystem().removeFromWorld(comp);
- });
- each$1(newChildren, function(childComp) {
- if (!childComp.getSystem().isConnected()) {
- component.getSystem().addToWorld(childComp);
- attach$1(component, childComp);
- if (inBody(component.element)) {
- fireAttaching(childComp);
- }
- } else {
- attach$1(component, childComp);
- }
- component.syncComponents();
- });
- };
- var attach = function(parent2, child2) {
- attachWith(parent2, child2, append$2);
- };
- var attachWith = function(parent2, child2, insertion) {
- parent2.getSystem().addToWorld(child2);
- insertion(parent2.element, child2.element);
- if (inBody(parent2.element)) {
- fireAttaching(child2);
- }
- parent2.syncComponents();
- };
- var doDetach = function(component) {
- fireDetaching(component);
- remove$5(component.element);
- component.getSystem().removeFromWorld(component);
- };
- var detach = function(component) {
- var parent$1 = parent(component.element).bind(function(p) {
- return component.getSystem().getByDom(p).toOptional();
- });
- doDetach(component);
- parent$1.each(function(p) {
- p.syncComponents();
- });
- };
- var detachChildren = function(component) {
- var subs2 = component.components();
- each$1(subs2, doDetach);
- empty(component.element);
- component.syncComponents();
- };
- var attachSystem = function(element2, guiSystem) {
- attachSystemWith(element2, guiSystem, append$2);
- };
- var attachSystemAfter = function(element2, guiSystem) {
- attachSystemWith(element2, guiSystem, after$2);
- };
- var attachSystemWith = function(element2, guiSystem, inserter) {
- inserter(element2, guiSystem.element);
- var children$1 = children(guiSystem.element);
- each$1(children$1, function(child2) {
- guiSystem.getByDom(child2).each(fireAttaching);
- });
- };
- var detachSystem = function(guiSystem) {
- var children$1 = children(guiSystem.element);
- each$1(children$1, function(child2) {
- guiSystem.getByDom(child2).each(fireDetaching);
- });
- remove$5(guiSystem.element);
- };
- var rebuild = function(sandbox, sConfig, sState, data) {
- sState.get().each(function(_data) {
- detachChildren(sandbox);
- });
- var point2 = sConfig.getAttachPoint(sandbox);
- attach(point2, sandbox);
- var built = sandbox.getSystem().build(data);
- attach(sandbox, built);
- sState.set(built);
- return built;
- };
- var open$1 = function(sandbox, sConfig, sState, data) {
- var newState = rebuild(sandbox, sConfig, sState, data);
- sConfig.onOpen(sandbox, newState);
- return newState;
- };
- var setContent = function(sandbox, sConfig, sState, data) {
- return sState.get().map(function() {
- return rebuild(sandbox, sConfig, sState, data);
- });
- };
- var openWhileCloaked = function(sandbox, sConfig, sState, data, transaction) {
- cloak(sandbox, sConfig);
- open$1(sandbox, sConfig, sState, data);
- transaction();
- decloak(sandbox, sConfig);
- };
- var close$1 = function(sandbox, sConfig, sState) {
- sState.get().each(function(data) {
- detachChildren(sandbox);
- detach(sandbox);
- sConfig.onClose(sandbox, data);
- sState.clear();
- });
- };
- var isOpen$1 = function(_sandbox, _sConfig, sState) {
- return sState.isOpen();
- };
- var isPartOf = function(sandbox, sConfig, sState, queryElem) {
- return isOpen$1(sandbox, sConfig, sState) && sState.get().exists(function(data) {
- return sConfig.isPartOf(sandbox, data, queryElem);
- });
- };
- var getState$2 = function(_sandbox, _sConfig, sState) {
- return sState.get();
- };
- var store = function(sandbox, cssKey, attr, newValue) {
- getRaw(sandbox.element, cssKey).fold(function() {
- remove$7(sandbox.element, attr);
- }, function(v) {
- set$8(sandbox.element, attr, v);
- });
- set$7(sandbox.element, cssKey, newValue);
- };
- var restore = function(sandbox, cssKey, attr) {
- getOpt(sandbox.element, attr).fold(function() {
- return remove$6(sandbox.element, cssKey);
- }, function(oldValue) {
- return set$7(sandbox.element, cssKey, oldValue);
- });
- };
- var cloak = function(sandbox, sConfig, _sState) {
- var sink = sConfig.getAttachPoint(sandbox);
- set$7(sandbox.element, "position", Positioning.getMode(sink));
- store(sandbox, "visibility", sConfig.cloakVisibilityAttr, "hidden");
- };
- var hasPosition = function(element2) {
- return exists([
- "top",
- "left",
- "right",
- "bottom"
- ], function(pos) {
- return getRaw(element2, pos).isSome();
- });
- };
- var decloak = function(sandbox, sConfig, _sState) {
- if (!hasPosition(sandbox.element)) {
- remove$6(sandbox.element, "position");
- }
- restore(sandbox, "visibility", sConfig.cloakVisibilityAttr);
- };
- var SandboxApis = Object.freeze({
- __proto__: null,
- cloak,
- decloak,
- open: open$1,
- openWhileCloaked,
- close: close$1,
- isOpen: isOpen$1,
- isPartOf,
- getState: getState$2,
- setContent
- });
- var events$g = function(sandboxConfig, sandboxState) {
- return derive$2([run$1(sandboxClose(), function(sandbox, _simulatedEvent) {
- close$1(sandbox, sandboxConfig, sandboxState);
- })]);
- };
- var ActiveSandbox = Object.freeze({
- __proto__: null,
- events: events$g
- });
- var SandboxSchema = [
- onHandler("onOpen"),
- onHandler("onClose"),
- required$1("isPartOf"),
- required$1("getAttachPoint"),
- defaulted("cloakVisibilityAttr", "data-precloak-visibility")
- ];
- var init$f = function() {
- var contents2 = value$1();
- var readState = constant$1("not-implemented");
- return nu$8({
- readState,
- isOpen: contents2.isSet,
- clear: contents2.clear,
- set: contents2.set,
- get: contents2.get
- });
- };
- var SandboxState = Object.freeze({
- __proto__: null,
- init: init$f
- });
- var Sandboxing = create$8({
- fields: SandboxSchema,
- name: "sandboxing",
- active: ActiveSandbox,
- apis: SandboxApis,
- state: SandboxState
- });
- var dismissPopups = constant$1("dismiss.popups");
- var repositionPopups = constant$1("reposition.popups");
- var mouseReleased = constant$1("mouse.released");
- var schema$x = objOfOnly([
- defaulted("isExtraPart", never),
- optionObjOf("fireEventInstead", [defaulted("event", dismissRequested())])
- ]);
- var receivingChannel$1 = function(rawSpec) {
- var _a2;
- var detail = asRawOrDie$1("Dismissal", schema$x, rawSpec);
- return _a2 = {}, _a2[dismissPopups()] = {
- schema: objOfOnly([required$1("target")]),
- onReceive: function(sandbox, data) {
- if (Sandboxing.isOpen(sandbox)) {
- var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
- if (!isPart) {
- detail.fireEventInstead.fold(function() {
- return Sandboxing.close(sandbox);
- }, function(fe) {
- return emit(sandbox, fe.event);
- });
- }
- }
- }
- }, _a2;
- };
- var schema$w = objOfOnly([
- optionObjOf("fireEventInstead", [defaulted("event", repositionRequested())]),
- requiredFunction("doReposition")
- ]);
- var receivingChannel = function(rawSpec) {
- var _a2;
- var detail = asRawOrDie$1("Reposition", schema$w, rawSpec);
- return _a2 = {}, _a2[repositionPopups()] = {
- onReceive: function(sandbox) {
- if (Sandboxing.isOpen(sandbox)) {
- detail.fireEventInstead.fold(function() {
- return detail.doReposition(sandbox);
- }, function(fe) {
- return emit(sandbox, fe.event);
- });
- }
- }
- }, _a2;
- };
- var onLoad$5 = function(component, repConfig, repState) {
- repConfig.store.manager.onLoad(component, repConfig, repState);
- };
- var onUnload$2 = function(component, repConfig, repState) {
- repConfig.store.manager.onUnload(component, repConfig, repState);
- };
- var setValue$3 = function(component, repConfig, repState, data) {
- repConfig.store.manager.setValue(component, repConfig, repState, data);
- };
- var getValue$3 = function(component, repConfig, repState) {
- return repConfig.store.manager.getValue(component, repConfig, repState);
- };
- var getState$1 = function(component, repConfig, repState) {
- return repState;
- };
- var RepresentApis = Object.freeze({
- __proto__: null,
- onLoad: onLoad$5,
- onUnload: onUnload$2,
- setValue: setValue$3,
- getValue: getValue$3,
- getState: getState$1
- });
- var events$f = function(repConfig, repState) {
- var es = repConfig.resetOnDom ? [
- runOnAttached(function(comp, _se) {
- onLoad$5(comp, repConfig, repState);
- }),
- runOnDetached(function(comp, _se) {
- onUnload$2(comp, repConfig, repState);
- })
- ] : [loadEvent(repConfig, repState, onLoad$5)];
- return derive$2(es);
- };
- var ActiveRepresenting = Object.freeze({
- __proto__: null,
- events: events$f
- });
- var memory$1 = function() {
- var data = Cell(null);
- var readState = function() {
- return {
- mode: "memory",
- value: data.get()
- };
- };
- var isNotSet = function() {
- return data.get() === null;
- };
- var clear2 = function() {
- data.set(null);
- };
- return nu$8({
- set: data.set,
- get: data.get,
- isNotSet,
- clear: clear2,
- readState
- });
- };
- var manual = function() {
- var readState = noop;
- return nu$8({ readState });
- };
- var dataset = function() {
- var dataByValue = Cell({});
- var dataByText = Cell({});
- var readState = function() {
- return {
- mode: "dataset",
- dataByValue: dataByValue.get(),
- dataByText: dataByText.get()
- };
- };
- var clear2 = function() {
- dataByValue.set({});
- dataByText.set({});
- };
- var lookup2 = function(itemString) {
- return get$e(dataByValue.get(), itemString).orThunk(function() {
- return get$e(dataByText.get(), itemString);
- });
- };
- var update = function(items) {
- var currentDataByValue = dataByValue.get();
- var currentDataByText = dataByText.get();
- var newDataByValue = {};
- var newDataByText = {};
- each$1(items, function(item2) {
- newDataByValue[item2.value] = item2;
- get$e(item2, "meta").each(function(meta) {
- get$e(meta, "text").each(function(text2) {
- newDataByText[text2] = item2;
- });
- });
- });
- dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
- dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
- };
- return nu$8({
- readState,
- lookup: lookup2,
- update,
- clear: clear2
- });
- };
- var init$e = function(spec) {
- return spec.store.manager.state(spec);
- };
- var RepresentState = Object.freeze({
- __proto__: null,
- memory: memory$1,
- dataset,
- manual,
- init: init$e
- });
- var setValue$2 = function(component, repConfig, repState, data) {
- var store2 = repConfig.store;
- repState.update([data]);
- store2.setValue(component, data);
- repConfig.onSetValue(component, data);
- };
- var getValue$2 = function(component, repConfig, repState) {
- var store2 = repConfig.store;
- var key = store2.getDataKey(component);
- return repState.lookup(key).getOrThunk(function() {
- return store2.getFallbackEntry(key);
- });
- };
- var onLoad$4 = function(component, repConfig, repState) {
- var store2 = repConfig.store;
- store2.initialValue.each(function(data) {
- setValue$2(component, repConfig, repState, data);
- });
- };
- var onUnload$1 = function(component, repConfig, repState) {
- repState.clear();
- };
- var DatasetStore = [
- option("initialValue"),
- required$1("getFallbackEntry"),
- required$1("getDataKey"),
- required$1("setValue"),
- output$1("manager", {
- setValue: setValue$2,
- getValue: getValue$2,
- onLoad: onLoad$4,
- onUnload: onUnload$1,
- state: dataset
- })
- ];
- var getValue$1 = function(component, repConfig, _repState) {
- return repConfig.store.getValue(component);
- };
- var setValue$1 = function(component, repConfig, _repState, data) {
- repConfig.store.setValue(component, data);
- repConfig.onSetValue(component, data);
- };
- var onLoad$3 = function(component, repConfig, _repState) {
- repConfig.store.initialValue.each(function(data) {
- repConfig.store.setValue(component, data);
- });
- };
- var ManualStore = [
- required$1("getValue"),
- defaulted("setValue", noop),
- option("initialValue"),
- output$1("manager", {
- setValue: setValue$1,
- getValue: getValue$1,
- onLoad: onLoad$3,
- onUnload: noop,
- state: NoState.init
- })
- ];
- var setValue = function(component, repConfig, repState, data) {
- repState.set(data);
- repConfig.onSetValue(component, data);
- };
- var getValue = function(component, repConfig, repState) {
- return repState.get();
- };
- var onLoad$2 = function(component, repConfig, repState) {
- repConfig.store.initialValue.each(function(initVal) {
- if (repState.isNotSet()) {
- repState.set(initVal);
- }
- });
- };
- var onUnload = function(component, repConfig, repState) {
- repState.clear();
- };
- var MemoryStore = [
- option("initialValue"),
- output$1("manager", {
- setValue,
- getValue,
- onLoad: onLoad$2,
- onUnload,
- state: memory$1
- })
- ];
- var RepresentSchema = [
- defaultedOf("store", { mode: "memory" }, choose$1("mode", {
- memory: MemoryStore,
- manual: ManualStore,
- dataset: DatasetStore
- })),
- onHandler("onSetValue"),
- defaulted("resetOnDom", false)
- ];
- var Representing = create$8({
- fields: RepresentSchema,
- name: "representing",
- active: ActiveRepresenting,
- apis: RepresentApis,
- extra: {
- setValueFrom: function(component, source) {
- var value2 = Representing.getValue(source);
- Representing.setValue(component, value2);
- }
- },
- state: RepresentState
- });
- var field = function(name2, forbidden) {
- return defaultedObjOf(name2, {}, map$2(forbidden, function(f) {
- return forbid(f.name(), "Cannot configure " + f.name() + " for " + name2);
- }).concat([customField("dump", identity$1)]));
- };
- var get$2 = function(data) {
- return data.dump;
- };
- var augment = function(data, original2) {
- return __assign(__assign({}, derive$1(original2)), data.dump);
- };
- var SketchBehaviours = {
- field,
- augment,
- get: get$2
- };
- var _placeholder = "placeholder";
- var adt$3 = Adt.generate([
- {
- single: [
- "required",
- "valueThunk"
- ]
- },
- {
- multiple: [
- "required",
- "valueThunks"
- ]
- }
- ]);
- var isSubstituted = function(spec) {
- return has$2(spec, "uiType");
- };
- var subPlaceholder = function(owner2, detail, compSpec, placeholders) {
- if (owner2.exists(function(o) {
- return o !== compSpec.owner;
- })) {
- return adt$3.single(true, constant$1(compSpec));
- }
- return get$e(placeholders, compSpec.name).fold(function() {
- throw new Error("Unknown placeholder component: " + compSpec.name + "\nKnown: [" + keys(placeholders) + "]\nNamespace: " + owner2.getOr("none") + "\nSpec: " + JSON.stringify(compSpec, null, 2));
- }, function(newSpec) {
- return newSpec.replace();
- });
- };
- var scan = function(owner2, detail, compSpec, placeholders) {
- if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
- return subPlaceholder(owner2, detail, compSpec, placeholders);
- } else {
- return adt$3.single(false, constant$1(compSpec));
- }
- };
- var substitute = function(owner2, detail, compSpec, placeholders) {
- var base2 = scan(owner2, detail, compSpec, placeholders);
- return base2.fold(function(req, valueThunk2) {
- var value2 = isSubstituted(compSpec) ? valueThunk2(detail, compSpec.config, compSpec.validated) : valueThunk2(detail);
- var childSpecs = get$e(value2, "components").getOr([]);
- var substituted = bind$3(childSpecs, function(c) {
- return substitute(owner2, detail, c, placeholders);
- });
- return [__assign(__assign({}, value2), { components: substituted })];
- }, function(req, valuesThunk) {
- if (isSubstituted(compSpec)) {
- var values2 = valuesThunk(detail, compSpec.config, compSpec.validated);
- var preprocessor = compSpec.validated.preprocess.getOr(identity$1);
- return preprocessor(values2);
- } else {
- return valuesThunk(detail);
- }
- });
- };
- var substituteAll = function(owner2, detail, components2, placeholders) {
- return bind$3(components2, function(c) {
- return substitute(owner2, detail, c, placeholders);
- });
- };
- var oneReplace = function(label, replacements) {
- var called = false;
- var used = function() {
- return called;
- };
- var replace = function() {
- if (called) {
- throw new Error("Trying to use the same placeholder more than once: " + label);
- }
- called = true;
- return replacements;
- };
- var required2 = function() {
- return replacements.fold(function(req, _) {
- return req;
- }, function(req, _) {
- return req;
- });
- };
- return {
- name: constant$1(label),
- required: required2,
- used,
- replace
- };
- };
- var substitutePlaces = function(owner2, detail, components2, placeholders) {
- var ps = map$1(placeholders, function(ph, name2) {
- return oneReplace(name2, ph);
- });
- var outcome = substituteAll(owner2, detail, components2, ps);
- each(ps, function(p) {
- if (p.used() === false && p.required()) {
- throw new Error("Placeholder: " + p.name() + " was not found in components list\nNamespace: " + owner2.getOr("none") + "\nComponents: " + JSON.stringify(detail.components, null, 2));
- }
- });
- return outcome;
- };
- var single$2 = adt$3.single;
- var multiple = adt$3.multiple;
- var placeholder = constant$1(_placeholder);
- var adt$2 = Adt.generate([
- { required: ["data"] },
- { external: ["data"] },
- { optional: ["data"] },
- { group: ["data"] }
- ]);
- var fFactory = defaulted("factory", { sketch: identity$1 });
- var fSchema = defaulted("schema", []);
- var fName = required$1("name");
- var fPname = field$1("pname", "pname", defaultedThunk(function(typeSpec) {
- return "<alloy." + generate$6(typeSpec.name) + ">";
- }), anyValue());
- var fGroupSchema = customField("schema", function() {
- return [option("preprocess")];
- });
- var fDefaults = defaulted("defaults", constant$1({}));
- var fOverrides = defaulted("overrides", constant$1({}));
- var requiredSpec = objOf([
- fFactory,
- fSchema,
- fName,
- fPname,
- fDefaults,
- fOverrides
- ]);
- var externalSpec = objOf([
- fFactory,
- fSchema,
- fName,
- fDefaults,
- fOverrides
- ]);
- var optionalSpec = objOf([
- fFactory,
- fSchema,
- fName,
- fPname,
- fDefaults,
- fOverrides
- ]);
- var groupSpec = objOf([
- fFactory,
- fGroupSchema,
- fName,
- required$1("unit"),
- fPname,
- fDefaults,
- fOverrides
- ]);
- var asNamedPart = function(part2) {
- return part2.fold(Optional.some, Optional.none, Optional.some, Optional.some);
- };
- var name$1 = function(part2) {
- var get2 = function(data) {
- return data.name;
- };
- return part2.fold(get2, get2, get2, get2);
- };
- var asCommon = function(part2) {
- return part2.fold(identity$1, identity$1, identity$1, identity$1);
- };
- var convert = function(adtConstructor, partSchema) {
- return function(spec) {
- var data = asRawOrDie$1("Converting part type", partSchema, spec);
- return adtConstructor(data);
- };
- };
- var required = convert(adt$2.required, requiredSpec);
- var external$1 = convert(adt$2.external, externalSpec);
- var optional = convert(adt$2.optional, optionalSpec);
- var group = convert(adt$2.group, groupSpec);
- var original = constant$1("entirety");
- var PartType = Object.freeze({
- __proto__: null,
- required,
- external: external$1,
- optional,
- group,
- asNamedPart,
- name: name$1,
- asCommon,
- original
- });
- var combine = function(detail, data, partSpec, partValidated) {
- return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
- };
- var subs = function(owner2, detail, parts2) {
- var internals = {};
- var externals = {};
- each$1(parts2, function(part2) {
- part2.fold(function(data) {
- internals[data.pname] = single$2(true, function(detail2, partSpec, partValidated) {
- return data.factory.sketch(combine(detail2, data, partSpec, partValidated));
- });
- }, function(data) {
- var partSpec = detail.parts[data.name];
- externals[data.name] = constant$1(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
- }, function(data) {
- internals[data.pname] = single$2(false, function(detail2, partSpec, partValidated) {
- return data.factory.sketch(combine(detail2, data, partSpec, partValidated));
- });
- }, function(data) {
- internals[data.pname] = multiple(true, function(detail2, _partSpec, _partValidated) {
- var units2 = detail2[data.name];
- return map$2(units2, function(u) {
- return data.factory.sketch(deepMerge(data.defaults(detail2, u, _partValidated), u, data.overrides(detail2, u)));
- });
- });
- });
- });
- return {
- internals: constant$1(internals),
- externals: constant$1(externals)
- };
- };
- var generate$3 = function(owner2, parts2) {
- var r2 = {};
- each$1(parts2, function(part2) {
- asNamedPart(part2).each(function(np) {
- var g = doGenerateOne(owner2, np.pname);
- r2[np.name] = function(config2) {
- var validated = asRawOrDie$1("Part: " + np.name + " in " + owner2, objOf(np.schema), config2);
- return __assign(__assign({}, g), {
- config: config2,
- validated
- });
- };
- });
- });
- return r2;
- };
- var doGenerateOne = function(owner2, pname) {
- return {
- uiType: placeholder(),
- owner: owner2,
- name: pname
- };
- };
- var generateOne$1 = function(owner2, pname, config2) {
- return {
- uiType: placeholder(),
- owner: owner2,
- name: pname,
- config: config2,
- validated: {}
- };
- };
- var schemas = function(parts2) {
- return bind$3(parts2, function(part2) {
- return part2.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function(data) {
- return requiredObjOf(data.name, data.schema.concat([snapshot(original())]));
- }).toArray();
- });
- };
- var names = function(parts2) {
- return map$2(parts2, name$1);
- };
- var substitutes = function(owner2, detail, parts2) {
- return subs(owner2, detail, parts2);
- };
- var components$1 = function(owner2, detail, internals) {
- return substitutePlaces(Optional.some(owner2), detail, detail.components, internals);
- };
- var getPart = function(component, detail, partKey) {
- var uid = detail.partUids[partKey];
- return component.getSystem().getByUid(uid).toOptional();
- };
- var getPartOrDie = function(component, detail, partKey) {
- return getPart(component, detail, partKey).getOrDie("Could not find part: " + partKey);
- };
- var getParts = function(component, detail, partKeys) {
- var r2 = {};
- var uids2 = detail.partUids;
- var system = component.getSystem();
- each$1(partKeys, function(pk) {
- r2[pk] = constant$1(system.getByUid(uids2[pk]));
- });
- return r2;
- };
- var getAllParts = function(component, detail) {
- var system = component.getSystem();
- return map$1(detail.partUids, function(pUid, _k) {
- return constant$1(system.getByUid(pUid));
- });
- };
- var getAllPartNames = function(detail) {
- return keys(detail.partUids);
- };
- var getPartsOrDie = function(component, detail, partKeys) {
- var r2 = {};
- var uids2 = detail.partUids;
- var system = component.getSystem();
- each$1(partKeys, function(pk) {
- r2[pk] = constant$1(system.getByUid(uids2[pk]).getOrDie());
- });
- return r2;
- };
- var defaultUids = function(baseUid, partTypes) {
- var partNames = names(partTypes);
- return wrapAll(map$2(partNames, function(pn) {
- return {
- key: pn,
- value: baseUid + "-" + pn
- };
- }));
- };
- var defaultUidsSchema = function(partTypes) {
- return field$1("partUids", "partUids", mergeWithThunk(function(spec) {
- return defaultUids(spec.uid, partTypes);
- }), anyValue());
- };
- var AlloyParts = Object.freeze({
- __proto__: null,
- generate: generate$3,
- generateOne: generateOne$1,
- schemas,
- names,
- substitutes,
- components: components$1,
- defaultUids,
- defaultUidsSchema,
- getAllParts,
- getAllPartNames,
- getPart,
- getPartOrDie,
- getParts,
- getPartsOrDie
- });
- var base = function(partSchemas, partUidsSchemas) {
- var ps = partSchemas.length > 0 ? [requiredObjOf("parts", partSchemas)] : [];
- return ps.concat([
- required$1("uid"),
- defaulted("dom", {}),
- defaulted("components", []),
- snapshot("originalSpec"),
- defaulted("debug.sketcher", {})
- ]).concat(partUidsSchemas);
- };
- var asRawOrDie = function(label, schema2, spec, partSchemas, partUidsSchemas) {
- var baseS = base(partSchemas, partUidsSchemas);
- return asRawOrDie$1(label + " [SpecSchema]", objOfOnly(baseS.concat(schema2)), spec);
- };
- var single$1 = function(owner2, schema2, factory2, spec) {
- var specWithUid = supplyUid(spec);
- var detail = asRawOrDie(owner2, schema2, specWithUid, [], []);
- return factory2(detail, specWithUid);
- };
- var composite$1 = function(owner2, schema2, partTypes, factory2, spec) {
- var specWithUid = supplyUid(spec);
- var partSchemas = schemas(partTypes);
- var partUidsSchema = defaultUidsSchema(partTypes);
- var detail = asRawOrDie(owner2, schema2, specWithUid, partSchemas, [partUidsSchema]);
- var subs2 = substitutes(owner2, detail, partTypes);
- var components2 = components$1(owner2, detail, subs2.internals());
- return factory2(detail, components2, specWithUid, subs2.externals());
- };
- var hasUid = function(spec) {
- return has$2(spec, "uid");
- };
- var supplyUid = function(spec) {
- return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$5("uid") });
- };
- var isSketchSpec = function(spec) {
- return spec.uid !== void 0;
- };
- var singleSchema = objOfOnly([
- required$1("name"),
- required$1("factory"),
- required$1("configFields"),
- defaulted("apis", {}),
- defaulted("extraApis", {})
- ]);
- var compositeSchema = objOfOnly([
- required$1("name"),
- required$1("factory"),
- required$1("configFields"),
- required$1("partFields"),
- defaulted("apis", {}),
- defaulted("extraApis", {})
- ]);
- var single = function(rawConfig) {
- var config2 = asRawOrDie$1("Sketcher for " + rawConfig.name, singleSchema, rawConfig);
- var sketch2 = function(spec) {
- return single$1(config2.name, config2.configFields, config2.factory, spec);
- };
- var apis = map$1(config2.apis, makeApi);
- var extraApis = map$1(config2.extraApis, function(f, k) {
- return markAsExtraApi(f, k);
- });
- return __assign(__assign({
- name: config2.name,
- configFields: config2.configFields,
- sketch: sketch2
- }, apis), extraApis);
- };
- var composite = function(rawConfig) {
- var config2 = asRawOrDie$1("Sketcher for " + rawConfig.name, compositeSchema, rawConfig);
- var sketch2 = function(spec) {
- return composite$1(config2.name, config2.configFields, config2.partFields, config2.factory, spec);
- };
- var parts2 = generate$3(config2.name, config2.partFields);
- var apis = map$1(config2.apis, makeApi);
- var extraApis = map$1(config2.extraApis, function(f, k) {
- return markAsExtraApi(f, k);
- });
- return __assign(__assign({
- name: config2.name,
- partFields: config2.partFields,
- configFields: config2.configFields,
- sketch: sketch2,
- parts: parts2
- }, apis), extraApis);
- };
- var inside = function(target) {
- return name$2(target) === "input" && get$d(target, "type") !== "radio" || name$2(target) === "textarea";
- };
- var getCurrent = function(component, composeConfig, _composeState) {
- return composeConfig.find(component);
- };
- var ComposeApis = Object.freeze({
- __proto__: null,
- getCurrent
- });
- var ComposeSchema = [required$1("find")];
- var Composing = create$8({
- fields: ComposeSchema,
- name: "composing",
- apis: ComposeApis
- });
- var nativeDisabled = [
- "input",
- "button",
- "textarea",
- "select"
- ];
- var onLoad$1 = function(component, disableConfig, disableState) {
- var f = disableConfig.disabled() ? disable$1 : enable$1;
- f(component, disableConfig);
- };
- var hasNative = function(component, config2) {
- return config2.useNative === true && contains$2(nativeDisabled, name$2(component.element));
- };
- var nativeIsDisabled = function(component) {
- return has$1(component.element, "disabled");
- };
- var nativeDisable = function(component) {
- set$8(component.element, "disabled", "disabled");
- };
- var nativeEnable = function(component) {
- remove$7(component.element, "disabled");
- };
- var ariaIsDisabled = function(component) {
- return get$d(component.element, "aria-disabled") === "true";
- };
- var ariaDisable = function(component) {
- set$8(component.element, "aria-disabled", "true");
- };
- var ariaEnable = function(component) {
- set$8(component.element, "aria-disabled", "false");
- };
- var disable$1 = function(component, disableConfig, _disableState) {
- disableConfig.disableClass.each(function(disableClass) {
- add$2(component.element, disableClass);
- });
- var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
- f(component);
- disableConfig.onDisabled(component);
- };
- var enable$1 = function(component, disableConfig, _disableState) {
- disableConfig.disableClass.each(function(disableClass) {
- remove$2(component.element, disableClass);
- });
- var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
- f(component);
- disableConfig.onEnabled(component);
- };
- var isDisabled = function(component, disableConfig) {
- return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
- };
- var set$3 = function(component, disableConfig, disableState, disabled) {
- var f = disabled ? disable$1 : enable$1;
- f(component, disableConfig);
- };
- var DisableApis = Object.freeze({
- __proto__: null,
- enable: enable$1,
- disable: disable$1,
- isDisabled,
- onLoad: onLoad$1,
- set: set$3
- });
- var exhibit$5 = function(base2, disableConfig) {
- return nu$7({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
- };
- var events$e = function(disableConfig, disableState) {
- return derive$2([
- abort(execute$5(), function(component, _simulatedEvent) {
- return isDisabled(component, disableConfig);
- }),
- loadEvent(disableConfig, disableState, onLoad$1)
- ]);
- };
- var ActiveDisable = Object.freeze({
- __proto__: null,
- exhibit: exhibit$5,
- events: events$e
- });
- var DisableSchema = [
- defaultedFunction("disabled", never),
- defaulted("useNative", true),
- option("disableClass"),
- onHandler("onDisabled"),
- onHandler("onEnabled")
- ];
- var Disabling = create$8({
- fields: DisableSchema,
- name: "disabling",
- active: ActiveDisable,
- apis: DisableApis
- });
- var dehighlightAllExcept = function(component, hConfig, hState, skip) {
- var highlighted = descendants(component.element, "." + hConfig.highlightClass);
- each$1(highlighted, function(h) {
- if (!exists(skip, function(skipComp) {
- return skipComp.element === h;
- })) {
- remove$2(h, hConfig.highlightClass);
- component.getSystem().getByDom(h).each(function(target) {
- hConfig.onDehighlight(component, target);
- emit(target, dehighlight$1());
- });
- }
- });
- };
- var dehighlightAll = function(component, hConfig, hState) {
- return dehighlightAllExcept(component, hConfig, hState, []);
- };
- var dehighlight = function(component, hConfig, hState, target) {
- if (isHighlighted(component, hConfig, hState, target)) {
- remove$2(target.element, hConfig.highlightClass);
- hConfig.onDehighlight(component, target);
- emit(target, dehighlight$1());
- }
- };
- var highlight = function(component, hConfig, hState, target) {
- dehighlightAllExcept(component, hConfig, hState, [target]);
- if (!isHighlighted(component, hConfig, hState, target)) {
- add$2(target.element, hConfig.highlightClass);
- hConfig.onHighlight(component, target);
- emit(target, highlight$1());
- }
- };
- var highlightFirst = function(component, hConfig, hState) {
- getFirst(component, hConfig).each(function(firstComp) {
- highlight(component, hConfig, hState, firstComp);
- });
- };
- var highlightLast = function(component, hConfig, hState) {
- getLast(component, hConfig).each(function(lastComp) {
- highlight(component, hConfig, hState, lastComp);
- });
- };
- var highlightAt = function(component, hConfig, hState, index) {
- getByIndex(component, hConfig, hState, index).fold(function(err) {
- throw err;
- }, function(firstComp) {
- highlight(component, hConfig, hState, firstComp);
- });
- };
- var highlightBy = function(component, hConfig, hState, predicate) {
- var candidates = getCandidates(component, hConfig);
- var targetComp = find$5(candidates, predicate);
- targetComp.each(function(c) {
- highlight(component, hConfig, hState, c);
- });
- };
- var isHighlighted = function(component, hConfig, hState, queryTarget) {
- return has(queryTarget.element, hConfig.highlightClass);
- };
- var getHighlighted = function(component, hConfig, _hState) {
- return descendant(component.element, "." + hConfig.highlightClass).bind(function(e) {
- return component.getSystem().getByDom(e).toOptional();
- });
- };
- var getByIndex = function(component, hConfig, hState, index) {
- var items = descendants(component.element, "." + hConfig.itemClass);
- return Optional.from(items[index]).fold(function() {
- return Result.error(new Error("No element found with index " + index));
- }, component.getSystem().getByDom);
- };
- var getFirst = function(component, hConfig, _hState) {
- return descendant(component.element, "." + hConfig.itemClass).bind(function(e) {
- return component.getSystem().getByDom(e).toOptional();
- });
- };
- var getLast = function(component, hConfig, _hState) {
- var items = descendants(component.element, "." + hConfig.itemClass);
- var last2 = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
- return last2.bind(function(c) {
- return component.getSystem().getByDom(c).toOptional();
- });
- };
- var getDelta$2 = function(component, hConfig, hState, delta) {
- var items = descendants(component.element, "." + hConfig.itemClass);
- var current = findIndex$1(items, function(item2) {
- return has(item2, hConfig.highlightClass);
- });
- return current.bind(function(selected) {
- var dest = cycleBy(selected, delta, 0, items.length - 1);
- return component.getSystem().getByDom(items[dest]).toOptional();
- });
- };
- var getPrevious = function(component, hConfig, hState) {
- return getDelta$2(component, hConfig, hState, -1);
- };
- var getNext = function(component, hConfig, hState) {
- return getDelta$2(component, hConfig, hState, 1);
- };
- var getCandidates = function(component, hConfig, _hState) {
- var items = descendants(component.element, "." + hConfig.itemClass);
- return cat(map$2(items, function(i) {
- return component.getSystem().getByDom(i).toOptional();
- }));
- };
- var HighlightApis = Object.freeze({
- __proto__: null,
- dehighlightAll,
- dehighlight,
- highlight,
- highlightFirst,
- highlightLast,
- highlightAt,
- highlightBy,
- isHighlighted,
- getHighlighted,
- getFirst,
- getLast,
- getPrevious,
- getNext,
- getCandidates
- });
- var HighlightSchema = [
- required$1("highlightClass"),
- required$1("itemClass"),
- onHandler("onHighlight"),
- onHandler("onDehighlight")
- ];
- var Highlighting = create$8({
- fields: HighlightSchema,
- name: "highlighting",
- apis: HighlightApis
- });
- var BACKSPACE = [8];
- var TAB = [9];
- var ENTER = [13];
- var ESCAPE = [27];
- var SPACE = [32];
- var LEFT = [37];
- var UP = [38];
- var RIGHT = [39];
- var DOWN = [40];
- var cyclePrev = function(values2, index, predicate) {
- var before2 = reverse(values2.slice(0, index));
- var after2 = reverse(values2.slice(index + 1));
- return find$5(before2.concat(after2), predicate);
- };
- var tryPrev = function(values2, index, predicate) {
- var before2 = reverse(values2.slice(0, index));
- return find$5(before2, predicate);
- };
- var cycleNext = function(values2, index, predicate) {
- var before2 = values2.slice(0, index);
- var after2 = values2.slice(index + 1);
- return find$5(after2.concat(before2), predicate);
- };
- var tryNext = function(values2, index, predicate) {
- var after2 = values2.slice(index + 1);
- return find$5(after2, predicate);
- };
- var inSet = function(keys2) {
- return function(event) {
- var raw = event.raw;
- return contains$2(keys2, raw.which);
- };
- };
- var and = function(preds) {
- return function(event) {
- return forall(preds, function(pred) {
- return pred(event);
- });
- };
- };
- var isShift = function(event) {
- var raw = event.raw;
- return raw.shiftKey === true;
- };
- var isControl = function(event) {
- var raw = event.raw;
- return raw.ctrlKey === true;
- };
- var isNotShift = not(isShift);
- var rule = function(matches, action) {
- return {
- matches,
- classification: action
- };
- };
- var choose = function(transitions, event) {
- var transition = find$5(transitions, function(t2) {
- return t2.matches(event);
- });
- return transition.map(function(t2) {
- return t2.classification;
- });
- };
- var reportFocusShifting = function(component, prevFocus, newFocus) {
- var noChange = prevFocus.exists(function(p) {
- return newFocus.exists(function(n) {
- return eq(n, p);
- });
- });
- if (!noChange) {
- emitWith(component, focusShifted(), {
- prevFocus,
- newFocus
- });
- }
- };
- var dom$2 = function() {
- var get2 = function(component) {
- return search(component.element);
- };
- var set2 = function(component, focusee) {
- var prevFocus = get2(component);
- component.getSystem().triggerFocus(focusee, component.element);
- var newFocus = get2(component);
- reportFocusShifting(component, prevFocus, newFocus);
- };
- return {
- get: get2,
- set: set2
- };
- };
- var highlights = function() {
- var get2 = function(component) {
- return Highlighting.getHighlighted(component).map(function(item2) {
- return item2.element;
- });
- };
- var set2 = function(component, element2) {
- var prevFocus = get2(component);
- component.getSystem().getByDom(element2).fold(noop, function(item2) {
- Highlighting.highlight(component, item2);
- });
- var newFocus = get2(component);
- reportFocusShifting(component, prevFocus, newFocus);
- };
- return {
- get: get2,
- set: set2
- };
- };
- var FocusInsideModes;
- (function(FocusInsideModes2) {
- FocusInsideModes2["OnFocusMode"] = "onFocus";
- FocusInsideModes2["OnEnterOrSpaceMode"] = "onEnterOrSpace";
- FocusInsideModes2["OnApiMode"] = "onApi";
- })(FocusInsideModes || (FocusInsideModes = {}));
- var typical = function(infoSchema, stateInit, getKeydownRules2, getKeyupRules2, optFocusIn) {
- var schema2 = function() {
- return infoSchema.concat([
- defaulted("focusManager", dom$2()),
- defaultedOf("focusInside", "onFocus", valueOf(function(val) {
- return contains$2([
- "onFocus",
- "onEnterOrSpace",
- "onApi"
- ], val) ? Result.value(val) : Result.error("Invalid value for focusInside");
- })),
- output$1("handler", me),
- output$1("state", stateInit),
- output$1("sendFocusIn", optFocusIn)
- ]);
- };
- var processKey = function(component, simulatedEvent, getRules, keyingConfig, keyingState) {
- var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
- return choose(rules, simulatedEvent.event).bind(function(rule2) {
- return rule2(component, simulatedEvent, keyingConfig, keyingState);
- });
- };
- var toEvents2 = function(keyingConfig, keyingState) {
- var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function(focusIn2) {
- return run$1(focus$4(), function(component, simulatedEvent) {
- focusIn2(component, keyingConfig, keyingState);
- simulatedEvent.stop();
- });
- });
- var tryGoInsideComponent = function(component, simulatedEvent) {
- var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
- if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
- optFocusIn(keyingConfig).each(function(focusIn2) {
- focusIn2(component, keyingConfig, keyingState);
- simulatedEvent.stop();
- });
- }
- };
- var keyboardEvents = [
- run$1(keydown(), function(component, simulatedEvent) {
- processKey(component, simulatedEvent, getKeydownRules2, keyingConfig, keyingState).fold(function() {
- tryGoInsideComponent(component, simulatedEvent);
- }, function(_) {
- simulatedEvent.stop();
- });
- }),
- run$1(keyup(), function(component, simulatedEvent) {
- processKey(component, simulatedEvent, getKeyupRules2, keyingConfig, keyingState).each(function(_) {
- simulatedEvent.stop();
- });
- })
- ];
- return derive$2(onFocusHandler.toArray().concat(keyboardEvents));
- };
- var me = {
- schema: schema2,
- processKey,
- toEvents: toEvents2
- };
- return me;
- };
- var create$6 = function(cyclicField) {
- var schema2 = [
- option("onEscape"),
- option("onEnter"),
- defaulted("selector", '[data-alloy-tabstop="true"]:not(:disabled)'),
- defaulted("firstTabstop", 0),
- defaulted("useTabstopAt", always),
- option("visibilitySelector")
- ].concat([cyclicField]);
- var isVisible2 = function(tabbingConfig, element2) {
- var target = tabbingConfig.visibilitySelector.bind(function(sel) {
- return closest$1(element2, sel);
- }).getOr(element2);
- return get$b(target) > 0;
- };
- var findInitial = function(component, tabbingConfig) {
- var tabstops = descendants(component.element, tabbingConfig.selector);
- var visibles = filter$2(tabstops, function(elem) {
- return isVisible2(tabbingConfig, elem);
- });
- return Optional.from(visibles[tabbingConfig.firstTabstop]);
- };
- var findCurrent2 = function(component, tabbingConfig) {
- return tabbingConfig.focusManager.get(component).bind(function(elem) {
- return closest$1(elem, tabbingConfig.selector);
- });
- };
- var isTabstop = function(tabbingConfig, element2) {
- return isVisible2(tabbingConfig, element2) && tabbingConfig.useTabstopAt(element2);
- };
- var focusIn2 = function(component, tabbingConfig, _tabbingState) {
- findInitial(component, tabbingConfig).each(function(target) {
- tabbingConfig.focusManager.set(component, target);
- });
- };
- var goFromTabstop = function(component, tabstops, stopIndex, tabbingConfig, cycle) {
- return cycle(tabstops, stopIndex, function(elem) {
- return isTabstop(tabbingConfig, elem);
- }).fold(function() {
- return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
- }, function(target) {
- tabbingConfig.focusManager.set(component, target);
- return Optional.some(true);
- });
- };
- var go2 = function(component, _simulatedEvent, tabbingConfig, cycle) {
- var tabstops = descendants(component.element, tabbingConfig.selector);
- return findCurrent2(component, tabbingConfig).bind(function(tabstop) {
- var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop));
- return optStopIndex.bind(function(stopIndex) {
- return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
- });
- });
- };
- var goBackwards = function(component, simulatedEvent, tabbingConfig) {
- var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
- return go2(component, simulatedEvent, tabbingConfig, navigate);
- };
- var goForwards = function(component, simulatedEvent, tabbingConfig) {
- var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
- return go2(component, simulatedEvent, tabbingConfig, navigate);
- };
- var execute2 = function(component, simulatedEvent, tabbingConfig) {
- return tabbingConfig.onEnter.bind(function(f) {
- return f(component, simulatedEvent);
- });
- };
- var exit = function(component, simulatedEvent, tabbingConfig) {
- return tabbingConfig.onEscape.bind(function(f) {
- return f(component, simulatedEvent);
- });
- };
- var getKeydownRules2 = constant$1([
- rule(and([
- isShift,
- inSet(TAB)
- ]), goBackwards),
- rule(inSet(TAB), goForwards),
- rule(inSet(ESCAPE), exit),
- rule(and([
- isNotShift,
- inSet(ENTER)
- ]), execute2)
- ]);
- var getKeyupRules2 = constant$1([]);
- return typical(schema2, NoState.init, getKeydownRules2, getKeyupRules2, function() {
- return Optional.some(focusIn2);
- });
- };
- var AcyclicType = create$6(customField("cyclic", never));
- var CyclicType = create$6(customField("cyclic", always));
- var doDefaultExecute = function(component, _simulatedEvent, focused) {
- dispatch(component, focused, execute$5());
- return Optional.some(true);
- };
- var defaultExecute = function(component, simulatedEvent, focused) {
- var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
- return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
- };
- var stopEventForFirefox = function(_component, _simulatedEvent) {
- return Optional.some(true);
- };
- var schema$v = [
- defaulted("execute", defaultExecute),
- defaulted("useSpace", false),
- defaulted("useEnter", true),
- defaulted("useControlEnter", false),
- defaulted("useDown", false)
- ];
- var execute$4 = function(component, simulatedEvent, executeConfig) {
- return executeConfig.execute(component, simulatedEvent, component.element);
- };
- var getKeydownRules$5 = function(component, _simulatedEvent, executeConfig, _executeState) {
- var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
- var enterExec = executeConfig.useEnter ? ENTER : [];
- var downExec = executeConfig.useDown ? DOWN : [];
- var execKeys = spaceExec.concat(enterExec).concat(downExec);
- return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
- isControl,
- inSet(ENTER)
- ]), execute$4)] : []);
- };
- var getKeyupRules$5 = function(component, _simulatedEvent, executeConfig, _executeState) {
- return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
- };
- var ExecutionType = typical(schema$v, NoState.init, getKeydownRules$5, getKeyupRules$5, function() {
- return Optional.none();
- });
- var flatgrid$1 = function() {
- var dimensions = value$1();
- var setGridSize = function(numRows, numColumns) {
- dimensions.set({
- numRows,
- numColumns
- });
- };
- var getNumRows = function() {
- return dimensions.get().map(function(d) {
- return d.numRows;
- });
- };
- var getNumColumns = function() {
- return dimensions.get().map(function(d) {
- return d.numColumns;
- });
- };
- return nu$8({
- readState: function() {
- return dimensions.get().map(function(d) {
- return {
- numRows: String(d.numRows),
- numColumns: String(d.numColumns)
- };
- }).getOr({
- numRows: "?",
- numColumns: "?"
- });
- },
- setGridSize,
- getNumRows,
- getNumColumns
- });
- };
- var init$d = function(spec) {
- return spec.state(spec);
- };
- var KeyingState = Object.freeze({
- __proto__: null,
- flatgrid: flatgrid$1,
- init: init$d
- });
- var useH = function(movement) {
- return function(component, simulatedEvent, config2, state) {
- var move2 = movement(component.element);
- return use(move2, component, simulatedEvent, config2, state);
- };
- };
- var west$1 = function(moveLeft2, moveRight2) {
- var movement = onDirection(moveLeft2, moveRight2);
- return useH(movement);
- };
- var east$1 = function(moveLeft2, moveRight2) {
- var movement = onDirection(moveRight2, moveLeft2);
- return useH(movement);
- };
- var useV = function(move2) {
- return function(component, simulatedEvent, config2, state) {
- return use(move2, component, simulatedEvent, config2, state);
- };
- };
- var use = function(move2, component, simulatedEvent, config2, state) {
- var outcome = config2.focusManager.get(component).bind(function(focused) {
- return move2(component.element, focused, config2, state);
- });
- return outcome.map(function(newFocus) {
- config2.focusManager.set(component, newFocus);
- return true;
- });
- };
- var north$1 = useV;
- var south$1 = useV;
- var move$1 = useV;
- var isHidden$1 = function(dom2) {
- return dom2.offsetWidth <= 0 && dom2.offsetHeight <= 0;
- };
- var isVisible = function(element2) {
- return !isHidden$1(element2.dom);
- };
- var locate = function(candidates, predicate) {
- return findIndex$1(candidates, predicate).map(function(index) {
- return {
- index,
- candidates
- };
- });
- };
- var locateVisible = function(container, current, selector) {
- var predicate = function(x) {
- return eq(x, current);
- };
- var candidates = descendants(container, selector);
- var visible = filter$2(candidates, isVisible);
- return locate(visible, predicate);
- };
- var findIndex = function(elements, target) {
- return findIndex$1(elements, function(elem) {
- return eq(target, elem);
- });
- };
- var withGrid = function(values2, index, numCols, f) {
- var oldRow = Math.floor(index / numCols);
- var oldColumn = index % numCols;
- return f(oldRow, oldColumn).bind(function(address) {
- var newIndex = address.row * numCols + address.column;
- return newIndex >= 0 && newIndex < values2.length ? Optional.some(values2[newIndex]) : Optional.none();
- });
- };
- var cycleHorizontal$1 = function(values2, index, numRows, numCols, delta) {
- return withGrid(values2, index, numCols, function(oldRow, oldColumn) {
- var onLastRow = oldRow === numRows - 1;
- var colsInRow = onLastRow ? values2.length - oldRow * numCols : numCols;
- var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
- return Optional.some({
- row: oldRow,
- column: newColumn
- });
- });
- };
- var cycleVertical$1 = function(values2, index, numRows, numCols, delta) {
- return withGrid(values2, index, numCols, function(oldRow, oldColumn) {
- var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
- var onLastRow = newRow === numRows - 1;
- var colsInRow = onLastRow ? values2.length - newRow * numCols : numCols;
- var newCol = clamp$1(oldColumn, 0, colsInRow - 1);
- return Optional.some({
- row: newRow,
- column: newCol
- });
- });
- };
- var cycleRight$1 = function(values2, index, numRows, numCols) {
- return cycleHorizontal$1(values2, index, numRows, numCols, 1);
- };
- var cycleLeft$1 = function(values2, index, numRows, numCols) {
- return cycleHorizontal$1(values2, index, numRows, numCols, -1);
- };
- var cycleUp$1 = function(values2, index, numRows, numCols) {
- return cycleVertical$1(values2, index, numRows, numCols, -1);
- };
- var cycleDown$1 = function(values2, index, numRows, numCols) {
- return cycleVertical$1(values2, index, numRows, numCols, 1);
- };
- var schema$u = [
- required$1("selector"),
- defaulted("execute", defaultExecute),
- onKeyboardHandler("onEscape"),
- defaulted("captureTab", false),
- initSize()
- ];
- var focusIn$3 = function(component, gridConfig, _gridState) {
- descendant(component.element, gridConfig.selector).each(function(first2) {
- gridConfig.focusManager.set(component, first2);
- });
- };
- var findCurrent$1 = function(component, gridConfig) {
- return gridConfig.focusManager.get(component).bind(function(elem) {
- return closest$1(elem, gridConfig.selector);
- });
- };
- var execute$3 = function(component, simulatedEvent, gridConfig, _gridState) {
- return findCurrent$1(component, gridConfig).bind(function(focused) {
- return gridConfig.execute(component, simulatedEvent, focused);
- });
- };
- var doMove$2 = function(cycle) {
- return function(element2, focused, gridConfig, gridState) {
- return locateVisible(element2, focused, gridConfig.selector).bind(function(identified) {
- return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
- });
- };
- };
- var handleTab = function(_component, _simulatedEvent, gridConfig) {
- return gridConfig.captureTab ? Optional.some(true) : Optional.none();
- };
- var doEscape$1 = function(component, simulatedEvent, gridConfig) {
- return gridConfig.onEscape(component, simulatedEvent);
- };
- var moveLeft$3 = doMove$2(cycleLeft$1);
- var moveRight$3 = doMove$2(cycleRight$1);
- var moveNorth$1 = doMove$2(cycleUp$1);
- var moveSouth$1 = doMove$2(cycleDown$1);
- var getKeydownRules$4 = constant$1([
- rule(inSet(LEFT), west$1(moveLeft$3, moveRight$3)),
- rule(inSet(RIGHT), east$1(moveLeft$3, moveRight$3)),
- rule(inSet(UP), north$1(moveNorth$1)),
- rule(inSet(DOWN), south$1(moveSouth$1)),
- rule(and([
- isShift,
- inSet(TAB)
- ]), handleTab),
- rule(and([
- isNotShift,
- inSet(TAB)
- ]), handleTab),
- rule(inSet(ESCAPE), doEscape$1),
- rule(inSet(SPACE.concat(ENTER)), execute$3)
- ]);
- var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
- var FlatgridType = typical(schema$u, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function() {
- return Optional.some(focusIn$3);
- });
- var horizontal = function(container, selector, current, delta) {
- var isDisabledButton = function(candidate) {
- return name$2(candidate) === "button" && get$d(candidate, "disabled") === "disabled";
- };
- var tryCycle = function(initial, index, candidates) {
- var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
- if (newIndex === initial) {
- return Optional.none();
- } else {
- return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
- }
- };
- return locateVisible(container, current, selector).bind(function(identified) {
- var index = identified.index;
- var candidates = identified.candidates;
- return tryCycle(index, index, candidates);
- });
- };
- var schema$t = [
- required$1("selector"),
- defaulted("getInitial", Optional.none),
- defaulted("execute", defaultExecute),
- onKeyboardHandler("onEscape"),
- defaulted("executeOnMove", false),
- defaulted("allowVertical", true)
- ];
- var findCurrent = function(component, flowConfig) {
- return flowConfig.focusManager.get(component).bind(function(elem) {
- return closest$1(elem, flowConfig.selector);
- });
- };
- var execute$2 = function(component, simulatedEvent, flowConfig) {
- return findCurrent(component, flowConfig).bind(function(focused) {
- return flowConfig.execute(component, simulatedEvent, focused);
- });
- };
- var focusIn$2 = function(component, flowConfig, _state) {
- flowConfig.getInitial(component).orThunk(function() {
- return descendant(component.element, flowConfig.selector);
- }).each(function(first2) {
- flowConfig.focusManager.set(component, first2);
- });
- };
- var moveLeft$2 = function(element2, focused, info) {
- return horizontal(element2, info.selector, focused, -1);
- };
- var moveRight$2 = function(element2, focused, info) {
- return horizontal(element2, info.selector, focused, 1);
- };
- var doMove$1 = function(movement) {
- return function(component, simulatedEvent, flowConfig, flowState) {
- return movement(component, simulatedEvent, flowConfig, flowState).bind(function() {
- return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true);
- });
- };
- };
- var doEscape = function(component, simulatedEvent, flowConfig) {
- return flowConfig.onEscape(component, simulatedEvent);
- };
- var getKeydownRules$3 = function(_component, _se, flowConfig, _flowState) {
- var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
- var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
- return [
- rule(inSet(westMovers), doMove$1(west$1(moveLeft$2, moveRight$2))),
- rule(inSet(eastMovers), doMove$1(east$1(moveLeft$2, moveRight$2))),
- rule(inSet(ENTER), execute$2),
- rule(inSet(SPACE), execute$2),
- rule(inSet(ESCAPE), doEscape)
- ];
- };
- var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
- var FlowType = typical(schema$t, NoState.init, getKeydownRules$3, getKeyupRules$3, function() {
- return Optional.some(focusIn$2);
- });
- var toCell = function(matrix2, rowIndex, columnIndex) {
- return Optional.from(matrix2[rowIndex]).bind(function(row) {
- return Optional.from(row[columnIndex]).map(function(cell) {
- return {
- rowIndex,
- columnIndex,
- cell
- };
- });
- });
- };
- var cycleHorizontal = function(matrix2, rowIndex, startCol, deltaCol) {
- var row = matrix2[rowIndex];
- var colsInRow = row.length;
- var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
- return toCell(matrix2, rowIndex, newColIndex);
- };
- var cycleVertical = function(matrix2, colIndex, startRow, deltaRow) {
- var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix2.length - 1);
- var colsInNextRow = matrix2[nextRowIndex].length;
- var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
- return toCell(matrix2, nextRowIndex, nextColIndex);
- };
- var moveHorizontal = function(matrix2, rowIndex, startCol, deltaCol) {
- var row = matrix2[rowIndex];
- var colsInRow = row.length;
- var newColIndex = clamp$1(startCol + deltaCol, 0, colsInRow - 1);
- return toCell(matrix2, rowIndex, newColIndex);
- };
- var moveVertical = function(matrix2, colIndex, startRow, deltaRow) {
- var nextRowIndex = clamp$1(startRow + deltaRow, 0, matrix2.length - 1);
- var colsInNextRow = matrix2[nextRowIndex].length;
- var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
- return toCell(matrix2, nextRowIndex, nextColIndex);
- };
- var cycleRight = function(matrix2, startRow, startCol) {
- return cycleHorizontal(matrix2, startRow, startCol, 1);
- };
- var cycleLeft = function(matrix2, startRow, startCol) {
- return cycleHorizontal(matrix2, startRow, startCol, -1);
- };
- var cycleUp = function(matrix2, startRow, startCol) {
- return cycleVertical(matrix2, startCol, startRow, -1);
- };
- var cycleDown = function(matrix2, startRow, startCol) {
- return cycleVertical(matrix2, startCol, startRow, 1);
- };
- var moveLeft$1 = function(matrix2, startRow, startCol) {
- return moveHorizontal(matrix2, startRow, startCol, -1);
- };
- var moveRight$1 = function(matrix2, startRow, startCol) {
- return moveHorizontal(matrix2, startRow, startCol, 1);
- };
- var moveUp$1 = function(matrix2, startRow, startCol) {
- return moveVertical(matrix2, startCol, startRow, -1);
- };
- var moveDown$1 = function(matrix2, startRow, startCol) {
- return moveVertical(matrix2, startCol, startRow, 1);
- };
- var schema$s = [
- requiredObjOf("selectors", [
- required$1("row"),
- required$1("cell")
- ]),
- defaulted("cycles", true),
- defaulted("previousSelector", Optional.none),
- defaulted("execute", defaultExecute)
- ];
- var focusIn$1 = function(component, matrixConfig, _state) {
- var focused = matrixConfig.previousSelector(component).orThunk(function() {
- var selectors = matrixConfig.selectors;
- return descendant(component.element, selectors.cell);
- });
- focused.each(function(cell) {
- matrixConfig.focusManager.set(component, cell);
- });
- };
- var execute$1 = function(component, simulatedEvent, matrixConfig) {
- return search(component.element).bind(function(focused) {
- return matrixConfig.execute(component, simulatedEvent, focused);
- });
- };
- var toMatrix = function(rows, matrixConfig) {
- return map$2(rows, function(row) {
- return descendants(row, matrixConfig.selectors.cell);
- });
- };
- var doMove = function(ifCycle, ifMove) {
- return function(element2, focused, matrixConfig) {
- var move2 = matrixConfig.cycles ? ifCycle : ifMove;
- return closest$1(focused, matrixConfig.selectors.row).bind(function(inRow) {
- var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
- return findIndex(cellsInRow, focused).bind(function(colIndex) {
- var allRows = descendants(element2, matrixConfig.selectors.row);
- return findIndex(allRows, inRow).bind(function(rowIndex) {
- var matrix2 = toMatrix(allRows, matrixConfig);
- return move2(matrix2, rowIndex, colIndex).map(function(next) {
- return next.cell;
- });
- });
- });
- });
- };
- };
- var moveLeft = doMove(cycleLeft, moveLeft$1);
- var moveRight = doMove(cycleRight, moveRight$1);
- var moveNorth = doMove(cycleUp, moveUp$1);
- var moveSouth = doMove(cycleDown, moveDown$1);
- var getKeydownRules$2 = constant$1([
- rule(inSet(LEFT), west$1(moveLeft, moveRight)),
- rule(inSet(RIGHT), east$1(moveLeft, moveRight)),
- rule(inSet(UP), north$1(moveNorth)),
- rule(inSet(DOWN), south$1(moveSouth)),
- rule(inSet(SPACE.concat(ENTER)), execute$1)
- ]);
- var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
- var MatrixType = typical(schema$s, NoState.init, getKeydownRules$2, getKeyupRules$2, function() {
- return Optional.some(focusIn$1);
- });
- var schema$r = [
- required$1("selector"),
- defaulted("execute", defaultExecute),
- defaulted("moveOnTab", false)
- ];
- var execute = function(component, simulatedEvent, menuConfig) {
- return menuConfig.focusManager.get(component).bind(function(focused) {
- return menuConfig.execute(component, simulatedEvent, focused);
- });
- };
- var focusIn = function(component, menuConfig, _state) {
- descendant(component.element, menuConfig.selector).each(function(first2) {
- menuConfig.focusManager.set(component, first2);
- });
- };
- var moveUp = function(element2, focused, info) {
- return horizontal(element2, info.selector, focused, -1);
- };
- var moveDown = function(element2, focused, info) {
- return horizontal(element2, info.selector, focused, 1);
- };
- var fireShiftTab = function(component, simulatedEvent, menuConfig, menuState) {
- return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
- };
- var fireTab = function(component, simulatedEvent, menuConfig, menuState) {
- return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
- };
- var getKeydownRules$1 = constant$1([
- rule(inSet(UP), move$1(moveUp)),
- rule(inSet(DOWN), move$1(moveDown)),
- rule(and([
- isShift,
- inSet(TAB)
- ]), fireShiftTab),
- rule(and([
- isNotShift,
- inSet(TAB)
- ]), fireTab),
- rule(inSet(ENTER), execute),
- rule(inSet(SPACE), execute)
- ]);
- var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
- var MenuType = typical(schema$r, NoState.init, getKeydownRules$1, getKeyupRules$1, function() {
- return Optional.some(focusIn);
- });
- var schema$q = [
- onKeyboardHandler("onSpace"),
- onKeyboardHandler("onEnter"),
- onKeyboardHandler("onShiftEnter"),
- onKeyboardHandler("onLeft"),
- onKeyboardHandler("onRight"),
- onKeyboardHandler("onTab"),
- onKeyboardHandler("onShiftTab"),
- onKeyboardHandler("onUp"),
- onKeyboardHandler("onDown"),
- onKeyboardHandler("onEscape"),
- defaulted("stopSpaceKeyup", false),
- option("focusIn")
- ];
- var getKeydownRules = function(component, simulatedEvent, specialInfo) {
- return [
- rule(inSet(SPACE), specialInfo.onSpace),
- rule(and([
- isNotShift,
- inSet(ENTER)
- ]), specialInfo.onEnter),
- rule(and([
- isShift,
- inSet(ENTER)
- ]), specialInfo.onShiftEnter),
- rule(and([
- isShift,
- inSet(TAB)
- ]), specialInfo.onShiftTab),
- rule(and([
- isNotShift,
- inSet(TAB)
- ]), specialInfo.onTab),
- rule(inSet(UP), specialInfo.onUp),
- rule(inSet(DOWN), specialInfo.onDown),
- rule(inSet(LEFT), specialInfo.onLeft),
- rule(inSet(RIGHT), specialInfo.onRight),
- rule(inSet(SPACE), specialInfo.onSpace),
- rule(inSet(ESCAPE), specialInfo.onEscape)
- ];
- };
- var getKeyupRules = function(component, simulatedEvent, specialInfo) {
- return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
- };
- var SpecialType = typical(schema$q, NoState.init, getKeydownRules, getKeyupRules, function(specialInfo) {
- return specialInfo.focusIn;
- });
- var acyclic = AcyclicType.schema();
- var cyclic = CyclicType.schema();
- var flow = FlowType.schema();
- var flatgrid = FlatgridType.schema();
- var matrix = MatrixType.schema();
- var execution = ExecutionType.schema();
- var menu = MenuType.schema();
- var special = SpecialType.schema();
- var KeyboardBranches = Object.freeze({
- __proto__: null,
- acyclic,
- cyclic,
- flow,
- flatgrid,
- matrix,
- execution,
- menu,
- special
- });
- var isFlatgridState = function(keyState) {
- return hasNonNullableKey(keyState, "setGridSize");
- };
- var Keying = createModes({
- branchKey: "mode",
- branches: KeyboardBranches,
- name: "keying",
- active: {
- events: function(keyingConfig, keyingState) {
- var handler = keyingConfig.handler;
- return handler.toEvents(keyingConfig, keyingState);
- }
- },
- apis: {
- focusIn: function(component, keyConfig, keyState) {
- keyConfig.sendFocusIn(keyConfig).fold(function() {
- component.getSystem().triggerFocus(component.element, component.element);
- }, function(sendFocusIn) {
- sendFocusIn(component, keyConfig, keyState);
- });
- },
- setGridSize: function(component, keyConfig, keyState, numRows, numColumns) {
- if (!isFlatgridState(keyState)) {
- console.error("Layout does not support setGridSize");
- } else {
- keyState.setGridSize(numRows, numColumns);
- }
- }
- },
- state: KeyingState
- });
- var set$2 = function(component, replaceConfig, replaceState, data) {
- preserve$1(function() {
- var newChildren = map$2(data, component.getSystem().build);
- replaceChildren(component, newChildren);
- }, component.element);
- };
- var insert = function(component, replaceConfig, insertion, childSpec) {
- var child2 = component.getSystem().build(childSpec);
- attachWith(component, child2, insertion);
- };
- var append = function(component, replaceConfig, replaceState, appendee) {
- insert(component, replaceConfig, append$2, appendee);
- };
- var prepend = function(component, replaceConfig, replaceState, prependee) {
- insert(component, replaceConfig, prepend$1, prependee);
- };
- var remove = function(component, replaceConfig, replaceState, removee) {
- var children2 = contents(component);
- var foundChild = find$5(children2, function(child2) {
- return eq(removee.element, child2.element);
- });
- foundChild.each(detach);
- };
- var contents = function(component, _replaceConfig) {
- return component.components();
- };
- var replaceAt = function(component, replaceConfig, replaceState, replaceeIndex, replacer) {
- var children2 = contents(component);
- return Optional.from(children2[replaceeIndex]).map(function(replacee) {
- remove(component, replaceConfig, replaceState, replacee);
- replacer.each(function(r2) {
- insert(component, replaceConfig, function(p, c) {
- appendAt(p, c, replaceeIndex);
- }, r2);
- });
- return replacee;
- });
- };
- var replaceBy = function(component, replaceConfig, replaceState, replaceePred, replacer) {
- var children2 = contents(component);
- return findIndex$1(children2, replaceePred).bind(function(replaceeIndex) {
- return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
- });
- };
- var ReplaceApis = Object.freeze({
- __proto__: null,
- append,
- prepend,
- remove,
- replaceAt,
- replaceBy,
- set: set$2,
- contents
- });
- var Replacing = create$8({
- fields: [],
- name: "replacing",
- apis: ReplaceApis
- });
- var events$d = function(name2, eventHandlers) {
- var events2 = derive$2(eventHandlers);
- return create$8({
- fields: [required$1("enabled")],
- name: name2,
- active: { events: constant$1(events2) }
- });
- };
- var config = function(name2, eventHandlers) {
- var me = events$d(name2, eventHandlers);
- return {
- key: name2,
- value: {
- config: {},
- me,
- configAsRaw: constant$1({}),
- initialConfig: {},
- state: NoState
- }
- };
- };
- var focus$2 = function(component, focusConfig) {
- if (!focusConfig.ignore) {
- focus$3(component.element);
- focusConfig.onFocus(component);
- }
- };
- var blur = function(component, focusConfig) {
- if (!focusConfig.ignore) {
- blur$1(component.element);
- }
- };
- var isFocused = function(component) {
- return hasFocus(component.element);
- };
- var FocusApis = Object.freeze({
- __proto__: null,
- focus: focus$2,
- blur,
- isFocused
- });
- var exhibit$4 = function(base2, focusConfig) {
- var mod = focusConfig.ignore ? {} : { attributes: { tabindex: "-1" } };
- return nu$7(mod);
- };
- var events$c = function(focusConfig) {
- return derive$2([run$1(focus$4(), function(component, simulatedEvent) {
- focus$2(component, focusConfig);
- simulatedEvent.stop();
- })].concat(focusConfig.stopMousedown ? [run$1(mousedown(), function(_, simulatedEvent) {
- simulatedEvent.event.prevent();
- })] : []));
- };
- var ActiveFocus = Object.freeze({
- __proto__: null,
- exhibit: exhibit$4,
- events: events$c
- });
- var FocusSchema = [
- onHandler("onFocus"),
- defaulted("stopMousedown", false),
- defaulted("ignore", false)
- ];
- var Focusing = create$8({
- fields: FocusSchema,
- name: "focusing",
- active: ActiveFocus,
- apis: FocusApis
- });
- var SetupBehaviourCellState = function(initialState) {
- var init2 = function() {
- var cell = Cell(initialState);
- var get2 = function() {
- return cell.get();
- };
- var set2 = function(newState) {
- return cell.set(newState);
- };
- var clear2 = function() {
- return cell.set(initialState);
- };
- var readState = function() {
- return cell.get();
- };
- return {
- get: get2,
- set: set2,
- clear: clear2,
- readState
- };
- };
- return { init: init2 };
- };
- var updateAriaState = function(component, toggleConfig, toggleState) {
- var ariaInfo = toggleConfig.aria;
- ariaInfo.update(component, ariaInfo, toggleState.get());
- };
- var updateClass = function(component, toggleConfig, toggleState) {
- toggleConfig.toggleClass.each(function(toggleClass) {
- if (toggleState.get()) {
- add$2(component.element, toggleClass);
- } else {
- remove$2(component.element, toggleClass);
- }
- });
- };
- var toggle$2 = function(component, toggleConfig, toggleState) {
- set$1(component, toggleConfig, toggleState, !toggleState.get());
- };
- var on = function(component, toggleConfig, toggleState) {
- toggleState.set(true);
- updateClass(component, toggleConfig, toggleState);
- updateAriaState(component, toggleConfig, toggleState);
- };
- var off = function(component, toggleConfig, toggleState) {
- toggleState.set(false);
- updateClass(component, toggleConfig, toggleState);
- updateAriaState(component, toggleConfig, toggleState);
- };
- var set$1 = function(component, toggleConfig, toggleState, state) {
- var action = state ? on : off;
- action(component, toggleConfig, toggleState);
- };
- var isOn = function(component, toggleConfig, toggleState) {
- return toggleState.get();
- };
- var onLoad = function(component, toggleConfig, toggleState) {
- set$1(component, toggleConfig, toggleState, toggleConfig.selected);
- };
- var ToggleApis = Object.freeze({
- __proto__: null,
- onLoad,
- toggle: toggle$2,
- isOn,
- on,
- off,
- set: set$1
- });
- var exhibit$3 = function() {
- return nu$7({});
- };
- var events$b = function(toggleConfig, toggleState) {
- var execute2 = executeEvent(toggleConfig, toggleState, toggle$2);
- var load = loadEvent(toggleConfig, toggleState, onLoad);
- return derive$2(flatten([
- toggleConfig.toggleOnExecute ? [execute2] : [],
- [load]
- ]));
- };
- var ActiveToggle = Object.freeze({
- __proto__: null,
- exhibit: exhibit$3,
- events: events$b
- });
- var updatePressed = function(component, ariaInfo, status) {
- set$8(component.element, "aria-pressed", status);
- if (ariaInfo.syncWithExpanded) {
- updateExpanded(component, ariaInfo, status);
- }
- };
- var updateSelected = function(component, ariaInfo, status) {
- set$8(component.element, "aria-selected", status);
- };
- var updateChecked = function(component, ariaInfo, status) {
- set$8(component.element, "aria-checked", status);
- };
- var updateExpanded = function(component, ariaInfo, status) {
- set$8(component.element, "aria-expanded", status);
- };
- var ToggleSchema = [
- defaulted("selected", false),
- option("toggleClass"),
- defaulted("toggleOnExecute", true),
- defaultedOf("aria", { mode: "none" }, choose$1("mode", {
- pressed: [
- defaulted("syncWithExpanded", false),
- output$1("update", updatePressed)
- ],
- checked: [output$1("update", updateChecked)],
- expanded: [output$1("update", updateExpanded)],
- selected: [output$1("update", updateSelected)],
- none: [output$1("update", noop)]
- }))
- ];
- var Toggling = create$8({
- fields: ToggleSchema,
- name: "toggling",
- active: ActiveToggle,
- apis: ToggleApis,
- state: SetupBehaviourCellState(false)
- });
- var pointerEvents = function() {
- var onClick = function(component, simulatedEvent) {
- simulatedEvent.stop();
- emitExecute(component);
- };
- return [
- run$1(click(), onClick),
- run$1(tap(), onClick),
- cutter(touchstart()),
- cutter(mousedown())
- ];
- };
- var events$a = function(optAction) {
- var executeHandler = function(action) {
- return runOnExecute$1(function(component, simulatedEvent) {
- action(component);
- simulatedEvent.stop();
- });
- };
- return derive$2(flatten([
- optAction.map(executeHandler).toArray(),
- pointerEvents()
- ]));
- };
- var hoverEvent = "alloy.item-hover";
- var focusEvent = "alloy.item-focus";
- var onHover = function(item2) {
- if (search(item2.element).isNone() || Focusing.isFocused(item2)) {
- if (!Focusing.isFocused(item2)) {
- Focusing.focus(item2);
- }
- emitWith(item2, hoverEvent, { item: item2 });
- }
- };
- var onFocus$1 = function(item2) {
- emitWith(item2, focusEvent, { item: item2 });
- };
- var hover = constant$1(hoverEvent);
- var focus$1 = constant$1(focusEvent);
- var builder$2 = function(detail) {
- return {
- dom: detail.dom,
- domModification: __assign(__assign({}, detail.domModification), { attributes: __assign(__assign(__assign({ "role": detail.toggling.isSome() ? "menuitemcheckbox" : "menuitem" }, detail.domModification.attributes), { "aria-haspopup": detail.hasSubmenu }), detail.hasSubmenu ? { "aria-expanded": false } : {}) }),
- behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
- detail.toggling.fold(Toggling.revoke, function(tConfig) {
- return Toggling.config(__assign({ aria: { mode: "checked" } }, tConfig));
- }),
- Focusing.config({
- ignore: detail.ignoreFocus,
- stopMousedown: detail.ignoreFocus,
- onFocus: function(component) {
- onFocus$1(component);
- }
- }),
- Keying.config({ mode: "execution" }),
- Representing.config({
- store: {
- mode: "memory",
- initialValue: detail.data
- }
- }),
- config("item-type-events", __spreadArray(__spreadArray([], pointerEvents(), true), [
- run$1(mouseover(), onHover),
- run$1(focusItem(), Focusing.focus)
- ], false))
- ]),
- components: detail.components,
- eventOrder: detail.eventOrder
- };
- };
- var schema$p = [
- required$1("data"),
- required$1("components"),
- required$1("dom"),
- defaulted("hasSubmenu", false),
- option("toggling"),
- SketchBehaviours.field("itemBehaviours", [
- Toggling,
- Focusing,
- Keying,
- Representing
- ]),
- defaulted("ignoreFocus", false),
- defaulted("domModification", {}),
- output$1("builder", builder$2),
- defaulted("eventOrder", {})
- ];
- var builder$1 = function(detail) {
- return {
- dom: detail.dom,
- components: detail.components,
- events: derive$2([stopper(focusItem())])
- };
- };
- var schema$o = [
- required$1("dom"),
- required$1("components"),
- output$1("builder", builder$1)
- ];
- var owner$2 = constant$1("item-widget");
- var parts$h = constant$1([required({
- name: "widget",
- overrides: function(detail) {
- return {
- behaviours: derive$1([Representing.config({
- store: {
- mode: "manual",
- getValue: function(_component) {
- return detail.data;
- },
- setValue: noop
- }
- })])
- };
- }
- })]);
- var builder = function(detail) {
- var subs2 = substitutes(owner$2(), detail, parts$h());
- var components2 = components$1(owner$2(), detail, subs2.internals());
- var focusWidget = function(component) {
- return getPart(component, detail, "widget").map(function(widget) {
- Keying.focusIn(widget);
- return widget;
- });
- };
- var onHorizontalArrow = function(component, simulatedEvent) {
- return inside(simulatedEvent.event.target) ? Optional.none() : function() {
- if (detail.autofocus) {
- simulatedEvent.setSource(component.element);
- return Optional.none();
- } else {
- return Optional.none();
- }
- }();
- };
- return {
- dom: detail.dom,
- components: components2,
- domModification: detail.domModification,
- events: derive$2([
- runOnExecute$1(function(component, simulatedEvent) {
- focusWidget(component).each(function(_widget) {
- simulatedEvent.stop();
- });
- }),
- run$1(mouseover(), onHover),
- run$1(focusItem(), function(component, _simulatedEvent) {
- if (detail.autofocus) {
- focusWidget(component);
- } else {
- Focusing.focus(component);
- }
- })
- ]),
- behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
- Representing.config({
- store: {
- mode: "memory",
- initialValue: detail.data
- }
- }),
- Focusing.config({
- ignore: detail.ignoreFocus,
- onFocus: function(component) {
- onFocus$1(component);
- }
- }),
- Keying.config({
- mode: "special",
- focusIn: detail.autofocus ? function(component) {
- focusWidget(component);
- } : revoke(),
- onLeft: onHorizontalArrow,
- onRight: onHorizontalArrow,
- onEscape: function(component, simulatedEvent) {
- if (!Focusing.isFocused(component) && !detail.autofocus) {
- Focusing.focus(component);
- return Optional.some(true);
- } else if (detail.autofocus) {
- simulatedEvent.setSource(component.element);
- return Optional.none();
- } else {
- return Optional.none();
- }
- }
- })
- ])
- };
- };
- var schema$n = [
- required$1("uid"),
- required$1("data"),
- required$1("components"),
- required$1("dom"),
- defaulted("autofocus", false),
- defaulted("ignoreFocus", false),
- SketchBehaviours.field("widgetBehaviours", [
- Representing,
- Focusing,
- Keying
- ]),
- defaulted("domModification", {}),
- defaultUidsSchema(parts$h()),
- output$1("builder", builder)
- ];
- var itemSchema$2 = choose$1("type", {
- widget: schema$n,
- item: schema$p,
- separator: schema$o
- });
- var configureGrid = function(detail, movementInfo) {
- return {
- mode: "flatgrid",
- selector: "." + detail.markers.item,
- initSize: {
- numColumns: movementInfo.initSize.numColumns,
- numRows: movementInfo.initSize.numRows
- },
- focusManager: detail.focusManager
- };
- };
- var configureMatrix = function(detail, movementInfo) {
- return {
- mode: "matrix",
- selectors: {
- row: movementInfo.rowSelector,
- cell: "." + detail.markers.item
- },
- focusManager: detail.focusManager
- };
- };
- var configureMenu = function(detail, movementInfo) {
- return {
- mode: "menu",
- selector: "." + detail.markers.item,
- moveOnTab: movementInfo.moveOnTab,
- focusManager: detail.focusManager
- };
- };
- var parts$g = constant$1([group({
- factory: {
- sketch: function(spec) {
- var itemInfo = asRawOrDie$1("menu.spec item", itemSchema$2, spec);
- return itemInfo.builder(itemInfo);
- }
- },
- name: "items",
- unit: "item",
- defaults: function(detail, u) {
- return has$2(u, "uid") ? u : __assign(__assign({}, u), { uid: generate$5("item") });
- },
- overrides: function(detail, u) {
- return {
- type: u.type,
- ignoreFocus: detail.fakeFocus,
- domModification: { classes: [detail.markers.item] }
- };
- }
- })]);
- var schema$m = constant$1([
- required$1("value"),
- required$1("items"),
- required$1("dom"),
- required$1("components"),
- defaulted("eventOrder", {}),
- field("menuBehaviours", [
- Highlighting,
- Representing,
- Composing,
- Keying
- ]),
- defaultedOf("movement", {
- mode: "menu",
- moveOnTab: true
- }, choose$1("mode", {
- grid: [
- initSize(),
- output$1("config", configureGrid)
- ],
- matrix: [
- output$1("config", configureMatrix),
- required$1("rowSelector")
- ],
- menu: [
- defaulted("moveOnTab", true),
- output$1("config", configureMenu)
- ]
- })),
- itemMarkers(),
- defaulted("fakeFocus", false),
- defaulted("focusManager", dom$2()),
- onHandler("onHighlight")
- ]);
- var focus = constant$1("alloy.menu-focus");
- var make$7 = function(detail, components2, _spec, _externals) {
- return {
- uid: detail.uid,
- dom: detail.dom,
- markers: detail.markers,
- behaviours: augment(detail.menuBehaviours, [
- Highlighting.config({
- highlightClass: detail.markers.selectedItem,
- itemClass: detail.markers.item,
- onHighlight: detail.onHighlight
- }),
- Representing.config({
- store: {
- mode: "memory",
- initialValue: detail.value
- }
- }),
- Composing.config({ find: Optional.some }),
- Keying.config(detail.movement.config(detail, detail.movement))
- ]),
- events: derive$2([
- run$1(focus$1(), function(menu2, simulatedEvent) {
- var event = simulatedEvent.event;
- menu2.getSystem().getByDom(event.target).each(function(item2) {
- Highlighting.highlight(menu2, item2);
- simulatedEvent.stop();
- emitWith(menu2, focus(), {
- menu: menu2,
- item: item2
- });
- });
- }),
- run$1(hover(), function(menu2, simulatedEvent) {
- var item2 = simulatedEvent.event.item;
- Highlighting.highlight(menu2, item2);
- })
- ]),
- components: components2,
- eventOrder: detail.eventOrder,
- domModification: { attributes: { role: "menu" } }
- };
- };
- var Menu = composite({
- name: "Menu",
- configFields: schema$m(),
- partFields: parts$g(),
- factory: make$7
- });
- var transpose$1 = function(obj) {
- return tupleMap(obj, function(v, k) {
- return {
- k: v,
- v: k
- };
- });
- };
- var trace = function(items, byItem, byMenu, finish) {
- return get$e(byMenu, finish).bind(function(triggerItem) {
- return get$e(items, triggerItem).bind(function(triggerMenu) {
- var rest = trace(items, byItem, byMenu, triggerMenu);
- return Optional.some([triggerMenu].concat(rest));
- });
- }).getOr([]);
- };
- var generate$2 = function(menus, expansions) {
- var items = {};
- each(menus, function(menuItems, menu2) {
- each$1(menuItems, function(item2) {
- items[item2] = menu2;
- });
- });
- var byItem = expansions;
- var byMenu = transpose$1(expansions);
- var menuPaths = map$1(byMenu, function(_triggerItem, submenu) {
- return [submenu].concat(trace(items, byItem, byMenu, submenu));
- });
- return map$1(items, function(menu2) {
- return get$e(menuPaths, menu2).getOr([menu2]);
- });
- };
- var init$c = function() {
- var expansions = Cell({});
- var menus = Cell({});
- var paths = Cell({});
- var primary = value$1();
- var directory = Cell({});
- var clear2 = function() {
- expansions.set({});
- menus.set({});
- paths.set({});
- primary.clear();
- };
- var isClear = function() {
- return primary.get().isNone();
- };
- var setMenuBuilt = function(menuName, built) {
- var _a2;
- menus.set(__assign(__assign({}, menus.get()), (_a2 = {}, _a2[menuName] = {
- type: "prepared",
- menu: built
- }, _a2)));
- };
- var setContents = function(sPrimary, sMenus, sExpansions, dir) {
- primary.set(sPrimary);
- expansions.set(sExpansions);
- menus.set(sMenus);
- directory.set(dir);
- var sPaths = generate$2(dir, sExpansions);
- paths.set(sPaths);
- };
- var getTriggeringItem = function(menuValue) {
- return find$4(expansions.get(), function(v, _k) {
- return v === menuValue;
- });
- };
- var getTriggerData = function(menuValue, getItemByValue, path2) {
- return getPreparedMenu(menuValue).bind(function(menu2) {
- return getTriggeringItem(menuValue).bind(function(triggeringItemValue) {
- return getItemByValue(triggeringItemValue).map(function(triggeredItem) {
- return {
- triggeredMenu: menu2,
- triggeringItem: triggeredItem,
- triggeringPath: path2
- };
- });
- });
- });
- };
- var getTriggeringPath = function(itemValue, getItemByValue) {
- var extraPath = filter$2(lookupItem(itemValue).toArray(), function(menuValue) {
- return getPreparedMenu(menuValue).isSome();
- });
- return get$e(paths.get(), itemValue).bind(function(path2) {
- var revPath = reverse(extraPath.concat(path2));
- var triggers = bind$3(revPath, function(menuValue, menuIndex) {
- return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function() {
- return is$1(primary.get(), menuValue) ? [] : [Optional.none()];
- }, function(data) {
- return [Optional.some(data)];
- });
- });
- return sequence(triggers);
- });
- };
- var expand2 = function(itemValue) {
- return get$e(expansions.get(), itemValue).map(function(menu2) {
- var current = get$e(paths.get(), itemValue).getOr([]);
- return [menu2].concat(current);
- });
- };
- var collapse = function(itemValue) {
- return get$e(paths.get(), itemValue).bind(function(path2) {
- return path2.length > 1 ? Optional.some(path2.slice(1)) : Optional.none();
- });
- };
- var refresh2 = function(itemValue) {
- return get$e(paths.get(), itemValue);
- };
- var getPreparedMenu = function(menuValue) {
- return lookupMenu(menuValue).bind(extractPreparedMenu);
- };
- var lookupMenu = function(menuValue) {
- return get$e(menus.get(), menuValue);
- };
- var lookupItem = function(itemValue) {
- return get$e(expansions.get(), itemValue);
- };
- var otherMenus = function(path2) {
- var menuValues = directory.get();
- return difference(keys(menuValues), path2);
- };
- var getPrimary = function() {
- return primary.get().bind(getPreparedMenu);
- };
- var getMenus2 = function() {
- return menus.get();
- };
- return {
- setMenuBuilt,
- setContents,
- expand: expand2,
- refresh: refresh2,
- collapse,
- lookupMenu,
- lookupItem,
- otherMenus,
- getPrimary,
- getMenus: getMenus2,
- clear: clear2,
- isClear,
- getTriggeringPath
- };
- };
- var extractPreparedMenu = function(prep) {
- return prep.type === "prepared" ? Optional.some(prep.menu) : Optional.none();
- };
- var LayeredState = {
- init: init$c,
- extractPreparedMenu
- };
- var make$6 = function(detail, _rawUiSpec) {
- var submenuParentItems = value$1();
- var buildMenus = function(container, primaryName, menus) {
- return map$1(menus, function(spec, name2) {
- var makeSketch = function() {
- return Menu.sketch(__assign(__assign({}, spec), {
- value: name2,
- markers: detail.markers,
- fakeFocus: detail.fakeFocus,
- onHighlight: detail.onHighlight,
- focusManager: detail.fakeFocus ? highlights() : dom$2()
- }));
- };
- return name2 === primaryName ? {
- type: "prepared",
- menu: container.getSystem().build(makeSketch())
- } : {
- type: "notbuilt",
- nbMenu: makeSketch
- };
- });
- };
- var layeredState = LayeredState.init();
- var setup2 = function(container) {
- var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
- var directory = toDirectory();
- layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
- return layeredState.getPrimary();
- };
- var getItemValue = function(item2) {
- return Representing.getValue(item2).value;
- };
- var getItemByValue = function(_container, menus, itemValue) {
- return findMap(menus, function(menu2) {
- if (!menu2.getSystem().isConnected()) {
- return Optional.none();
- }
- var candidates = Highlighting.getCandidates(menu2);
- return find$5(candidates, function(c) {
- return getItemValue(c) === itemValue;
- });
- });
- };
- var toDirectory = function(_container) {
- return map$1(detail.data.menus, function(data, _menuName) {
- return bind$3(data.items, function(item2) {
- return item2.type === "separator" ? [] : [item2.data.value];
- });
- });
- };
- var setActiveMenu = function(container, menu2) {
- Highlighting.highlight(container, menu2);
- Highlighting.getHighlighted(menu2).orThunk(function() {
- return Highlighting.getFirst(menu2);
- }).each(function(item2) {
- dispatch(container, item2.element, focusItem());
- });
- };
- var getMenus2 = function(state, menuValues) {
- return cat(map$2(menuValues, function(mv) {
- return state.lookupMenu(mv).bind(function(prep) {
- return prep.type === "prepared" ? Optional.some(prep.menu) : Optional.none();
- });
- }));
- };
- var closeOthers = function(container, state, path2) {
- var others = getMenus2(state, state.otherMenus(path2));
- each$1(others, function(o) {
- remove$1(o.element, [detail.markers.backgroundMenu]);
- if (!detail.stayInDom) {
- Replacing.remove(container, o);
- }
- });
- };
- var getSubmenuParents = function(container) {
- return submenuParentItems.get().getOrThunk(function() {
- var r2 = {};
- var items = descendants(container.element, "." + detail.markers.item);
- var parentItems = filter$2(items, function(i) {
- return get$d(i, "aria-haspopup") === "true";
- });
- each$1(parentItems, function(i) {
- container.getSystem().getByDom(i).each(function(itemComp) {
- var key = getItemValue(itemComp);
- r2[key] = itemComp;
- });
- });
- submenuParentItems.set(r2);
- return r2;
- });
- };
- var updateAriaExpansions = function(container, path2) {
- var parentItems = getSubmenuParents(container);
- each(parentItems, function(v, k) {
- var expanded = contains$2(path2, k);
- set$8(v.element, "aria-expanded", expanded);
- });
- };
- var updateMenuPath = function(container, state, path2) {
- return Optional.from(path2[0]).bind(function(latestMenuName) {
- return state.lookupMenu(latestMenuName).bind(function(menuPrep) {
- if (menuPrep.type === "notbuilt") {
- return Optional.none();
- } else {
- var activeMenu = menuPrep.menu;
- var rest = getMenus2(state, path2.slice(1));
- each$1(rest, function(r2) {
- add$2(r2.element, detail.markers.backgroundMenu);
- });
- if (!inBody(activeMenu.element)) {
- Replacing.append(container, premade(activeMenu));
- }
- remove$1(activeMenu.element, [detail.markers.backgroundMenu]);
- setActiveMenu(container, activeMenu);
- closeOthers(container, state, path2);
- return Optional.some(activeMenu);
- }
- });
- });
- };
- var ExpandHighlightDecision;
- (function(ExpandHighlightDecision2) {
- ExpandHighlightDecision2[ExpandHighlightDecision2["HighlightSubmenu"] = 0] = "HighlightSubmenu";
- ExpandHighlightDecision2[ExpandHighlightDecision2["HighlightParent"] = 1] = "HighlightParent";
- })(ExpandHighlightDecision || (ExpandHighlightDecision = {}));
- var buildIfRequired = function(container, menuName, menuPrep) {
- if (menuPrep.type === "notbuilt") {
- var menu2 = container.getSystem().build(menuPrep.nbMenu());
- layeredState.setMenuBuilt(menuName, menu2);
- return menu2;
- } else {
- return menuPrep.menu;
- }
- };
- var expandRight = function(container, item2, decision) {
- if (decision === void 0) {
- decision = ExpandHighlightDecision.HighlightSubmenu;
- }
- if (item2.hasConfigured(Disabling) && Disabling.isDisabled(item2)) {
- return Optional.some(item2);
- } else {
- var value2 = getItemValue(item2);
- return layeredState.expand(value2).bind(function(path2) {
- updateAriaExpansions(container, path2);
- return Optional.from(path2[0]).bind(function(menuName) {
- return layeredState.lookupMenu(menuName).bind(function(activeMenuPrep) {
- var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
- if (!inBody(activeMenu.element)) {
- Replacing.append(container, premade(activeMenu));
- }
- detail.onOpenSubmenu(container, item2, activeMenu, reverse(path2));
- if (decision === ExpandHighlightDecision.HighlightSubmenu) {
- Highlighting.highlightFirst(activeMenu);
- return updateMenuPath(container, layeredState, path2);
- } else {
- Highlighting.dehighlightAll(activeMenu);
- return Optional.some(item2);
- }
- });
- });
- });
- }
- };
- var collapseLeft = function(container, item2) {
- var value2 = getItemValue(item2);
- return layeredState.collapse(value2).bind(function(path2) {
- updateAriaExpansions(container, path2);
- return updateMenuPath(container, layeredState, path2).map(function(activeMenu) {
- detail.onCollapseMenu(container, item2, activeMenu);
- return activeMenu;
- });
- });
- };
- var updateView = function(container, item2) {
- var value2 = getItemValue(item2);
- return layeredState.refresh(value2).bind(function(path2) {
- updateAriaExpansions(container, path2);
- return updateMenuPath(container, layeredState, path2);
- });
- };
- var onRight2 = function(container, item2) {
- return inside(item2.element) ? Optional.none() : expandRight(container, item2, ExpandHighlightDecision.HighlightSubmenu);
- };
- var onLeft2 = function(container, item2) {
- return inside(item2.element) ? Optional.none() : collapseLeft(container, item2);
- };
- var onEscape = function(container, item2) {
- return collapseLeft(container, item2).orThunk(function() {
- return detail.onEscape(container, item2).map(function() {
- return container;
- });
- });
- };
- var keyOnItem = function(f) {
- return function(container, simulatedEvent) {
- return closest$1(simulatedEvent.getSource(), "." + detail.markers.item).bind(function(target) {
- return container.getSystem().getByDom(target).toOptional().bind(function(item2) {
- return f(container, item2).map(always);
- });
- });
- };
- };
- var events2 = derive$2([
- run$1(focus(), function(sandbox, simulatedEvent) {
- var item2 = simulatedEvent.event.item;
- layeredState.lookupItem(getItemValue(item2)).each(function() {
- var menu2 = simulatedEvent.event.menu;
- Highlighting.highlight(sandbox, menu2);
- var value2 = getItemValue(simulatedEvent.event.item);
- layeredState.refresh(value2).each(function(path2) {
- return closeOthers(sandbox, layeredState, path2);
- });
- });
- }),
- runOnExecute$1(function(component, simulatedEvent) {
- var target = simulatedEvent.event.target;
- component.getSystem().getByDom(target).each(function(item2) {
- var itemValue = getItemValue(item2);
- if (itemValue.indexOf("collapse-item") === 0) {
- collapseLeft(component, item2);
- }
- expandRight(component, item2, ExpandHighlightDecision.HighlightSubmenu).fold(function() {
- detail.onExecute(component, item2);
- }, noop);
- });
- }),
- runOnAttached(function(container, _simulatedEvent) {
- setup2(container).each(function(primary) {
- Replacing.append(container, premade(primary));
- detail.onOpenMenu(container, primary);
- if (detail.highlightImmediately) {
- setActiveMenu(container, primary);
- }
- });
- })
- ].concat(detail.navigateOnHover ? [run$1(hover(), function(sandbox, simulatedEvent) {
- var item2 = simulatedEvent.event.item;
- updateView(sandbox, item2);
- expandRight(sandbox, item2, ExpandHighlightDecision.HighlightParent);
- detail.onHover(sandbox, item2);
- })] : []));
- var getActiveItem = function(container) {
- return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
- };
- var collapseMenuApi = function(container) {
- getActiveItem(container).each(function(currentItem) {
- collapseLeft(container, currentItem);
- });
- };
- var highlightPrimary = function(container) {
- layeredState.getPrimary().each(function(primary) {
- setActiveMenu(container, primary);
- });
- };
- var extractMenuFromContainer = function(container) {
- return Optional.from(container.components()[0]).filter(function(comp) {
- return get$d(comp.element, "role") === "menu";
- });
- };
- var repositionMenus2 = function(container) {
- var maybeActivePrimary = layeredState.getPrimary().bind(function(primary) {
- return getActiveItem(container).bind(function(currentItem) {
- var itemValue = getItemValue(currentItem);
- var allMenus = values(layeredState.getMenus());
- var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
- return layeredState.getTriggeringPath(itemValue, function(v) {
- return getItemByValue(container, preparedMenus, v);
- });
- }).map(function(triggeringPath) {
- return {
- primary,
- triggeringPath
- };
- });
- });
- maybeActivePrimary.fold(function() {
- extractMenuFromContainer(container).each(function(primaryMenu) {
- detail.onRepositionMenu(container, primaryMenu, []);
- });
- }, function(_a2) {
- var primary = _a2.primary, triggeringPath = _a2.triggeringPath;
- detail.onRepositionMenu(container, primary, triggeringPath);
- });
- };
- var apis = {
- collapseMenu: collapseMenuApi,
- highlightPrimary,
- repositionMenus: repositionMenus2
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- markers: detail.markers,
- behaviours: augment(detail.tmenuBehaviours, [
- Keying.config({
- mode: "special",
- onRight: keyOnItem(onRight2),
- onLeft: keyOnItem(onLeft2),
- onEscape: keyOnItem(onEscape),
- focusIn: function(container, _keyInfo) {
- layeredState.getPrimary().each(function(primary) {
- dispatch(container, primary.element, focusItem());
- });
- }
- }),
- Highlighting.config({
- highlightClass: detail.markers.selectedMenu,
- itemClass: detail.markers.menu
- }),
- Composing.config({
- find: function(container) {
- return Highlighting.getHighlighted(container);
- }
- }),
- Replacing.config({})
- ]),
- eventOrder: detail.eventOrder,
- apis,
- events: events2
- };
- };
- var collapseItem$1 = constant$1("collapse-item");
- var tieredData = function(primary, menus, expansions) {
- return {
- primary,
- menus,
- expansions
- };
- };
- var singleData = function(name2, menu2) {
- return {
- primary: name2,
- menus: wrap$1(name2, menu2),
- expansions: {}
- };
- };
- var collapseItem = function(text2) {
- return {
- value: generate$6(collapseItem$1()),
- meta: { text: text2 }
- };
- };
- var tieredMenu = single({
- name: "TieredMenu",
- configFields: [
- onStrictKeyboardHandler("onExecute"),
- onStrictKeyboardHandler("onEscape"),
- onStrictHandler("onOpenMenu"),
- onStrictHandler("onOpenSubmenu"),
- onHandler("onRepositionMenu"),
- onHandler("onCollapseMenu"),
- defaulted("highlightImmediately", true),
- requiredObjOf("data", [
- required$1("primary"),
- required$1("menus"),
- required$1("expansions")
- ]),
- defaulted("fakeFocus", false),
- onHandler("onHighlight"),
- onHandler("onHover"),
- tieredMenuMarkers(),
- required$1("dom"),
- defaulted("navigateOnHover", true),
- defaulted("stayInDom", false),
- field("tmenuBehaviours", [
- Keying,
- Highlighting,
- Composing,
- Replacing
- ]),
- defaulted("eventOrder", {})
- ],
- apis: {
- collapseMenu: function(apis, tmenu) {
- apis.collapseMenu(tmenu);
- },
- highlightPrimary: function(apis, tmenu) {
- apis.highlightPrimary(tmenu);
- },
- repositionMenus: function(apis, tmenu) {
- apis.repositionMenus(tmenu);
- }
- },
- factory: make$6,
- extraApis: {
- tieredData,
- singleData,
- collapseItem
- }
- });
- var makeMenu = function(detail, menuSandbox, placementSpec, menuSpec, getBounds2) {
- var lazySink = function() {
- return detail.lazySink(menuSandbox);
- };
- var layouts2 = menuSpec.type === "horizontal" ? {
- layouts: {
- onLtr: function() {
- return belowOrAbove();
- },
- onRtl: function() {
- return belowOrAboveRtl();
- }
- }
- } : {};
- var isFirstTierSubmenu = function(triggeringPaths) {
- return triggeringPaths.length === 2;
- };
- var getSubmenuLayouts = function(triggeringPaths) {
- return isFirstTierSubmenu(triggeringPaths) ? layouts2 : {};
- };
- return tieredMenu.sketch({
- dom: { tag: "div" },
- data: menuSpec.data,
- markers: menuSpec.menu.markers,
- highlightImmediately: menuSpec.menu.highlightImmediately,
- onEscape: function() {
- Sandboxing.close(menuSandbox);
- detail.onEscape.map(function(handler) {
- return handler(menuSandbox);
- });
- return Optional.some(true);
- },
- onExecute: function() {
- return Optional.some(true);
- },
- onOpenMenu: function(tmenu, menu2) {
- Positioning.positionWithinBounds(lazySink().getOrDie(), menu2, placementSpec, getBounds2());
- },
- onOpenSubmenu: function(tmenu, item2, submenu, triggeringPaths) {
- var sink = lazySink().getOrDie();
- Positioning.position(sink, submenu, {
- anchor: __assign({
- type: "submenu",
- item: item2
- }, getSubmenuLayouts(triggeringPaths))
- });
- },
- onRepositionMenu: function(tmenu, primaryMenu, submenuTriggers) {
- var sink = lazySink().getOrDie();
- Positioning.positionWithinBounds(sink, primaryMenu, placementSpec, getBounds2());
- each$1(submenuTriggers, function(st) {
- var submenuLayouts = getSubmenuLayouts(st.triggeringPath);
- Positioning.position(sink, st.triggeredMenu, {
- anchor: __assign({
- type: "submenu",
- item: st.triggeringItem
- }, submenuLayouts)
- });
- });
- }
- });
- };
- var factory$m = function(detail, spec) {
- var isPartOfRelated = function(sandbox, queryElem) {
- var related = detail.getRelated(sandbox);
- return related.exists(function(rel) {
- return isPartOf$1(rel, queryElem);
- });
- };
- var setContent2 = function(sandbox, thing) {
- Sandboxing.setContent(sandbox, thing);
- };
- var showAt = function(sandbox, thing, placementSpec) {
- showWithin(sandbox, thing, placementSpec, Optional.none());
- };
- var showWithin = function(sandbox, thing, placementSpec, boxElement) {
- showWithinBounds(sandbox, thing, placementSpec, function() {
- return boxElement.map(function(elem) {
- return box$1(elem);
- });
- });
- };
- var showWithinBounds = function(sandbox, thing, placementSpec, getBounds2) {
- var sink = detail.lazySink(sandbox).getOrDie();
- Sandboxing.openWhileCloaked(sandbox, thing, function() {
- return Positioning.positionWithinBounds(sink, sandbox, placementSpec, getBounds2());
- });
- Representing.setValue(sandbox, Optional.some({
- mode: "position",
- config: placementSpec,
- getBounds: getBounds2
- }));
- };
- var showMenuAt = function(sandbox, placementSpec, menuSpec) {
- showMenuWithinBounds(sandbox, placementSpec, menuSpec, Optional.none);
- };
- var showMenuWithinBounds = function(sandbox, placementSpec, menuSpec, getBounds2) {
- var menu2 = makeMenu(detail, sandbox, placementSpec, menuSpec, getBounds2);
- Sandboxing.open(sandbox, menu2);
- Representing.setValue(sandbox, Optional.some({
- mode: "menu",
- menu: menu2
- }));
- };
- var hide = function(sandbox) {
- if (Sandboxing.isOpen(sandbox)) {
- Representing.setValue(sandbox, Optional.none());
- Sandboxing.close(sandbox);
- }
- };
- var getContent = function(sandbox) {
- return Sandboxing.getState(sandbox);
- };
- var reposition2 = function(sandbox) {
- if (Sandboxing.isOpen(sandbox)) {
- Representing.getValue(sandbox).each(function(state) {
- switch (state.mode) {
- case "menu":
- Sandboxing.getState(sandbox).each(tieredMenu.repositionMenus);
- break;
- case "position":
- var sink = detail.lazySink(sandbox).getOrDie();
- Positioning.positionWithinBounds(sink, sandbox, state.config, state.getBounds());
- break;
- }
- });
- }
- };
- var apis = {
- setContent: setContent2,
- showAt,
- showWithin,
- showWithinBounds,
- showMenuAt,
- showMenuWithinBounds,
- hide,
- getContent,
- reposition: reposition2,
- isOpen: Sandboxing.isOpen
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- behaviours: augment(detail.inlineBehaviours, [
- Sandboxing.config({
- isPartOf: function(sandbox, data, queryElem) {
- return isPartOf$1(data, queryElem) || isPartOfRelated(sandbox, queryElem);
- },
- getAttachPoint: function(sandbox) {
- return detail.lazySink(sandbox).getOrDie();
- },
- onOpen: function(sandbox) {
- detail.onShow(sandbox);
- },
- onClose: function(sandbox) {
- detail.onHide(sandbox);
- }
- }),
- Representing.config({
- store: {
- mode: "memory",
- initialValue: Optional.none()
- }
- }),
- Receiving.config({
- channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: spec.isExtraPart }, detail.fireDismissalEventInstead.map(function(fe) {
- return { fireEventInstead: { event: fe.event } };
- }).getOr({})))), receivingChannel(__assign(__assign({}, detail.fireRepositionEventInstead.map(function(fe) {
- return { fireEventInstead: { event: fe.event } };
- }).getOr({})), { doReposition: reposition2 })))
- })
- ]),
- eventOrder: detail.eventOrder,
- apis
- };
- };
- var InlineView = single({
- name: "InlineView",
- configFields: [
- required$1("lazySink"),
- onHandler("onShow"),
- onHandler("onHide"),
- optionFunction("onEscape"),
- field("inlineBehaviours", [
- Sandboxing,
- Representing,
- Receiving
- ]),
- optionObjOf("fireDismissalEventInstead", [defaulted("event", dismissRequested())]),
- optionObjOf("fireRepositionEventInstead", [defaulted("event", repositionRequested())]),
- defaulted("getRelated", Optional.none),
- defaulted("isExtraPart", never),
- defaulted("eventOrder", Optional.none)
- ],
- factory: factory$m,
- apis: {
- showAt: function(apis, component, anchor2, thing) {
- apis.showAt(component, anchor2, thing);
- },
- showWithin: function(apis, component, anchor2, thing, boxElement) {
- apis.showWithin(component, anchor2, thing, boxElement);
- },
- showWithinBounds: function(apis, component, anchor2, thing, bounds2) {
- apis.showWithinBounds(component, anchor2, thing, bounds2);
- },
- showMenuAt: function(apis, component, anchor2, menuSpec) {
- apis.showMenuAt(component, anchor2, menuSpec);
- },
- showMenuWithinBounds: function(apis, component, anchor2, menuSpec, bounds2) {
- apis.showMenuWithinBounds(component, anchor2, menuSpec, bounds2);
- },
- hide: function(apis, component) {
- apis.hide(component);
- },
- isOpen: function(apis, component) {
- return apis.isOpen(component);
- },
- getContent: function(apis, component) {
- return apis.getContent(component);
- },
- setContent: function(apis, component, thing) {
- apis.setContent(component, thing);
- },
- reposition: function(apis, component) {
- apis.reposition(component);
- }
- }
- });
- var labelPrefix = "layout-inset";
- var westEdgeX = function(anchor2) {
- return anchor2.x;
- };
- var middleX = function(anchor2, element2) {
- return anchor2.x + anchor2.width / 2 - element2.width / 2;
- };
- var eastEdgeX = function(anchor2, element2) {
- return anchor2.x + anchor2.width - element2.width;
- };
- var northY = function(anchor2) {
- return anchor2.y;
- };
- var southY = function(anchor2, element2) {
- return anchor2.y + anchor2.height - element2.height;
- };
- var centreY = function(anchor2, element2) {
- return anchor2.y + anchor2.height / 2 - element2.height / 2;
- };
- var southwest = function(anchor2, element2, bubbles) {
- return nu$6(eastEdgeX(anchor2, element2), southY(anchor2, element2), bubbles.insetSouthwest(), northwest$3(), "southwest", boundsRestriction(anchor2, {
- right: 0,
- bottom: 3
- }), labelPrefix);
- };
- var southeast = function(anchor2, element2, bubbles) {
- return nu$6(westEdgeX(anchor2), southY(anchor2, element2), bubbles.insetSoutheast(), northeast$3(), "southeast", boundsRestriction(anchor2, {
- left: 1,
- bottom: 3
- }), labelPrefix);
- };
- var northwest = function(anchor2, element2, bubbles) {
- return nu$6(eastEdgeX(anchor2, element2), northY(anchor2), bubbles.insetNorthwest(), southwest$3(), "northwest", boundsRestriction(anchor2, {
- right: 0,
- top: 2
- }), labelPrefix);
- };
- var northeast = function(anchor2, element2, bubbles) {
- return nu$6(westEdgeX(anchor2), northY(anchor2), bubbles.insetNortheast(), southeast$3(), "northeast", boundsRestriction(anchor2, {
- left: 1,
- top: 2
- }), labelPrefix);
- };
- var north = function(anchor2, element2, bubbles) {
- return nu$6(middleX(anchor2, element2), northY(anchor2), bubbles.insetNorth(), south$3(), "north", boundsRestriction(anchor2, { top: 2 }), labelPrefix);
- };
- var south = function(anchor2, element2, bubbles) {
- return nu$6(middleX(anchor2, element2), southY(anchor2, element2), bubbles.insetSouth(), north$3(), "south", boundsRestriction(anchor2, { bottom: 3 }), labelPrefix);
- };
- var east = function(anchor2, element2, bubbles) {
- return nu$6(eastEdgeX(anchor2, element2), centreY(anchor2, element2), bubbles.insetEast(), west$3(), "east", boundsRestriction(anchor2, { right: 0 }), labelPrefix);
- };
- var west = function(anchor2, element2, bubbles) {
- return nu$6(westEdgeX(anchor2), centreY(anchor2, element2), bubbles.insetWest(), east$3(), "west", boundsRestriction(anchor2, { left: 1 }), labelPrefix);
- };
- var lookupPreserveLayout = function(lastPlacement) {
- switch (lastPlacement) {
- case "north":
- return north;
- case "northeast":
- return northeast;
- case "northwest":
- return northwest;
- case "south":
- return south;
- case "southeast":
- return southeast;
- case "southwest":
- return southwest;
- case "east":
- return east;
- case "west":
- return west;
- }
- };
- var preserve = function(anchor2, element2, bubbles, placee, bounds2) {
- var layout2 = getPlacement(placee).map(lookupPreserveLayout).getOr(north);
- return layout2(anchor2, element2, bubbles, placee, bounds2);
- };
- var lookupFlippedLayout = function(lastPlacement) {
- switch (lastPlacement) {
- case "north":
- return south;
- case "northeast":
- return southeast;
- case "northwest":
- return southwest;
- case "south":
- return north;
- case "southeast":
- return northeast;
- case "southwest":
- return northwest;
- case "east":
- return west;
- case "west":
- return east;
- }
- };
- var flip$2 = function(anchor2, element2, bubbles, placee, bounds2) {
- var layout2 = getPlacement(placee).map(lookupFlippedLayout).getOr(north);
- return layout2(anchor2, element2, bubbles, placee, bounds2);
- };
- var global$f = tinymce.util.Tools.resolve("tinymce.util.Delay");
- var factory$l = function(detail) {
- var events2 = events$a(detail.action);
- var tag = detail.dom.tag;
- var lookupAttr = function(attr) {
- return get$e(detail.dom, "attributes").bind(function(attrs) {
- return get$e(attrs, attr);
- });
- };
- var getModAttributes = function() {
- if (tag === "button") {
- var type2 = lookupAttr("type").getOr("button");
- var roleAttrs = lookupAttr("role").map(function(role2) {
- return { role: role2 };
- }).getOr({});
- return __assign({ type: type2 }, roleAttrs);
- } else {
- var role = lookupAttr("role").getOr("button");
- return { role };
- }
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: detail.components,
- events: events2,
- behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
- Focusing.config({}),
- Keying.config({
- mode: "execution",
- useSpace: true,
- useEnter: true
- })
- ]),
- domModification: { attributes: getModAttributes() },
- eventOrder: detail.eventOrder
- };
- };
- var Button = single({
- name: "Button",
- factory: factory$l,
- configFields: [
- defaulted("uid", void 0),
- required$1("dom"),
- defaulted("components", []),
- SketchBehaviours.field("buttonBehaviours", [
- Focusing,
- Keying
- ]),
- option("action"),
- option("role"),
- defaulted("eventOrder", {})
- ]
- });
- var record = function(spec) {
- var uid = isSketchSpec(spec) && hasNonNullableKey(spec, "uid") ? spec.uid : generate$5("memento");
- var get2 = function(anyInSystem) {
- return anyInSystem.getSystem().getByUid(uid).getOrDie();
- };
- var getOpt2 = function(anyInSystem) {
- return anyInSystem.getSystem().getByUid(uid).toOptional();
- };
- var asSpec = function() {
- return __assign(__assign({}, spec), { uid });
- };
- return {
- get: get2,
- getOpt: getOpt2,
- asSpec
- };
- };
- var global$e = tinymce.util.Tools.resolve("tinymce.util.I18n");
- var rtlTransform = {
- "indent": true,
- "outdent": true,
- "table-insert-column-after": true,
- "table-insert-column-before": true,
- "paste-column-after": true,
- "paste-column-before": true,
- "unordered-list": true,
- "list-bull-circle": true,
- "list-bull-default": true,
- "list-bull-square": true
- };
- var defaultIconName = "temporary-placeholder";
- var defaultIcon = function(icons) {
- return function() {
- return get$e(icons, defaultIconName).getOr("!not found!");
- };
- };
- var getIconName = function(name2, icons) {
- var lcName = name2.toLowerCase();
- if (global$e.isRtl()) {
- var rtlName = ensureTrailing(lcName, "-rtl");
- return has$2(icons, rtlName) ? rtlName : lcName;
- } else {
- return lcName;
- }
- };
- var lookupIcon = function(name2, icons) {
- return get$e(icons, getIconName(name2, icons));
- };
- var get$1 = function(name2, iconProvider) {
- var icons = iconProvider();
- return lookupIcon(name2, icons).getOrThunk(defaultIcon(icons));
- };
- var getOr = function(name2, iconProvider, fallbackIcon) {
- var icons = iconProvider();
- return lookupIcon(name2, icons).or(fallbackIcon).getOrThunk(defaultIcon(icons));
- };
- var needsRtlTransform = function(iconName) {
- return global$e.isRtl() ? has$2(rtlTransform, iconName) : false;
- };
- var addFocusableBehaviour = function() {
- return config("add-focusable", [runOnAttached(function(comp) {
- child(comp.element, "svg").each(function(svg2) {
- return set$8(svg2, "focusable", "false");
- });
- })]);
- };
- var renderIcon$2 = function(spec, iconName, icons, fallbackIcon) {
- var _a2, _b;
- var rtlIconClasses = needsRtlTransform(iconName) ? ["tox-icon--flip"] : [];
- var iconHtml = get$e(icons, getIconName(iconName, icons)).or(fallbackIcon).getOrThunk(defaultIcon(icons));
- return {
- dom: {
- tag: spec.tag,
- attributes: (_a2 = spec.attributes) !== null && _a2 !== void 0 ? _a2 : {},
- classes: spec.classes.concat(rtlIconClasses),
- innerHtml: iconHtml
- },
- behaviours: derive$1(__spreadArray(__spreadArray([], (_b = spec.behaviours) !== null && _b !== void 0 ? _b : [], true), [addFocusableBehaviour()], false))
- };
- };
- var render$3 = function(iconName, spec, iconProvider, fallbackIcon) {
- if (fallbackIcon === void 0) {
- fallbackIcon = Optional.none();
- }
- return renderIcon$2(spec, iconName, iconProvider(), fallbackIcon);
- };
- var renderFirst = function(iconNames, spec, iconProvider) {
- var icons = iconProvider();
- var iconName = find$5(iconNames, function(name2) {
- return has$2(icons, getIconName(name2, icons));
- });
- return renderIcon$2(spec, iconName.getOr(defaultIconName), icons, Optional.none());
- };
- var notificationIconMap = {
- success: "checkmark",
- error: "warning",
- err: "error",
- warning: "warning",
- warn: "warning",
- info: "info"
- };
- var factory$k = function(detail) {
- var memBannerText = record({
- dom: {
- tag: "p",
- innerHtml: detail.translationProvider(detail.text)
- },
- behaviours: derive$1([Replacing.config({})])
- });
- var renderPercentBar = function(percent) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-bar"],
- attributes: { style: "width: " + percent + "%" }
- }
- };
- };
- var renderPercentText = function(percent) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-text"],
- innerHtml: percent + "%"
- }
- };
- };
- var memBannerProgress = record({
- dom: {
- tag: "div",
- classes: detail.progress ? [
- "tox-progress-bar",
- "tox-progress-indicator"
- ] : ["tox-progress-bar"]
- },
- components: [
- {
- dom: {
- tag: "div",
- classes: ["tox-bar-container"]
- },
- components: [renderPercentBar(0)]
- },
- renderPercentText(0)
- ],
- behaviours: derive$1([Replacing.config({})])
- });
- var updateProgress = function(comp, percent) {
- if (comp.getSystem().isConnected()) {
- memBannerProgress.getOpt(comp).each(function(progress) {
- Replacing.set(progress, [
- {
- dom: {
- tag: "div",
- classes: ["tox-bar-container"]
- },
- components: [renderPercentBar(percent)]
- },
- renderPercentText(percent)
- ]);
- });
- }
- };
- var updateText = function(comp, text2) {
- if (comp.getSystem().isConnected()) {
- var banner = memBannerText.get(comp);
- Replacing.set(banner, [text$1(text2)]);
- }
- };
- var apis = {
- updateProgress,
- updateText
- };
- var iconChoices = flatten([
- detail.icon.toArray(),
- detail.level.toArray(),
- detail.level.bind(function(level) {
- return Optional.from(notificationIconMap[level]);
- }).toArray()
- ]);
- var memButton = record(Button.sketch({
- dom: {
- tag: "button",
- classes: [
- "tox-notification__dismiss",
- "tox-button",
- "tox-button--naked",
- "tox-button--icon"
- ]
- },
- components: [render$3("close", {
- tag: "div",
- classes: ["tox-icon"],
- attributes: { "aria-label": detail.translationProvider("Close") }
- }, detail.iconProvider)],
- action: function(comp) {
- detail.onAction(comp);
- }
- }));
- var notificationIconSpec = renderFirst(iconChoices, {
- tag: "div",
- classes: ["tox-notification__icon"]
- }, detail.iconProvider);
- var notificationBodySpec = {
- dom: {
- tag: "div",
- classes: ["tox-notification__body"]
- },
- components: [memBannerText.asSpec()],
- behaviours: derive$1([Replacing.config({})])
- };
- var components2 = [
- notificationIconSpec,
- notificationBodySpec
- ];
- return {
- uid: detail.uid,
- dom: {
- tag: "div",
- attributes: { role: "alert" },
- classes: detail.level.map(function(level) {
- return [
- "tox-notification",
- "tox-notification--in",
- "tox-notification--" + level
- ];
- }).getOr([
- "tox-notification",
- "tox-notification--in"
- ])
- },
- behaviours: derive$1([
- Focusing.config({}),
- config("notification-events", [run$1(focusin(), function(comp) {
- memButton.getOpt(comp).each(Focusing.focus);
- })])
- ]),
- components: components2.concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [memButton.asSpec()]),
- apis
- };
- };
- var Notification = single({
- name: "Notification",
- factory: factory$k,
- configFields: [
- option("level"),
- required$1("progress"),
- required$1("icon"),
- required$1("onAction"),
- required$1("text"),
- required$1("iconProvider"),
- required$1("translationProvider"),
- defaultedBoolean("closeButton", true)
- ],
- apis: {
- updateProgress: function(apis, comp, percent) {
- apis.updateProgress(comp, percent);
- },
- updateText: function(apis, comp, text2) {
- apis.updateText(comp, text2);
- }
- }
- });
- function NotificationManagerImpl(editor, extras, uiMothership) {
- var sharedBackstage = extras.backstage.shared;
- var getLayoutDirection = function(rel) {
- switch (rel) {
- case "bc-bc":
- return south;
- case "tc-tc":
- return north;
- case "tc-bc":
- return north$2;
- case "bc-tc":
- default:
- return south$2;
- }
- };
- var reposition2 = function(notifications) {
- if (notifications.length > 0) {
- each$1(notifications, function(notification, index) {
- if (index === 0) {
- notification.moveRel(null, "banner");
- } else {
- notification.moveRel(notifications[index - 1].getEl(), "bc-tc");
- }
- });
- }
- };
- var open2 = function(settings, closeCallback) {
- var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0);
- var close3 = function() {
- closeCallback();
- InlineView.hide(notificationWrapper);
- };
- var notification = build$1(Notification.sketch({
- text: settings.text,
- level: contains$2([
- "success",
- "error",
- "warning",
- "warn",
- "info"
- ], settings.type) ? settings.type : void 0,
- progress: settings.progressBar === true,
- icon: Optional.from(settings.icon),
- closeButton: !hideCloseButton,
- onAction: close3,
- iconProvider: sharedBackstage.providers.icons,
- translationProvider: sharedBackstage.providers.translate
- }));
- var notificationWrapper = build$1(InlineView.sketch(__assign({
- dom: {
- tag: "div",
- classes: ["tox-notifications-container"]
- },
- lazySink: sharedBackstage.getSink,
- fireDismissalEventInstead: {}
- }, sharedBackstage.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} })));
- uiMothership.add(notificationWrapper);
- if (settings.timeout > 0) {
- global$f.setTimeout(function() {
- close3();
- }, settings.timeout);
- }
- var getBounds2 = function() {
- var contentArea = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
- var win$1 = win();
- var x = clamp$1(win$1.x, contentArea.x, contentArea.right);
- var y = clamp$1(win$1.y, contentArea.y, contentArea.bottom);
- var right2 = Math.max(contentArea.right, win$1.right);
- var bottom2 = Math.max(contentArea.bottom, win$1.bottom);
- return Optional.some(bounds(x, y, right2 - x, bottom2 - y));
- };
- return {
- close: close3,
- moveTo: function(x, y) {
- InlineView.showAt(notificationWrapper, premade(notification), {
- anchor: {
- type: "makeshift",
- x,
- y
- }
- });
- },
- moveRel: function(element2, rel) {
- var notificationSpec = premade(notification);
- var anchorOverrides2 = { maxHeightFunction: expandable$1() };
- if (rel !== "banner" && isNonNullable(element2)) {
- var layoutDirection_1 = getLayoutDirection(rel);
- var nodeAnchor = {
- type: "node",
- root: body(),
- node: Optional.some(SugarElement.fromDom(element2)),
- overrides: anchorOverrides2,
- layouts: {
- onRtl: function() {
- return [layoutDirection_1];
- },
- onLtr: function() {
- return [layoutDirection_1];
- }
- }
- };
- InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: nodeAnchor }, getBounds2);
- } else {
- var anchor2 = __assign(__assign({}, sharedBackstage.anchors.banner()), { overrides: anchorOverrides2 });
- InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: anchor2 }, getBounds2);
- }
- },
- text: function(nuText) {
- Notification.updateText(notification, nuText);
- },
- settings,
- getEl: function() {
- return notification.element.dom;
- },
- progressBar: {
- value: function(percent) {
- Notification.updateProgress(notification, percent);
- }
- }
- };
- };
- var close2 = function(notification) {
- notification.close();
- };
- var getArgs = function(notification) {
- return notification.settings;
- };
- return {
- open: open2,
- close: close2,
- reposition: reposition2,
- getArgs
- };
- }
- var first = function(fn, rate) {
- var timer = null;
- var cancel = function() {
- if (!isNull(timer)) {
- clearTimeout(timer);
- timer = null;
- }
- };
- var throttle2 = function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- if (isNull(timer)) {
- timer = setTimeout(function() {
- timer = null;
- fn.apply(null, args);
- }, rate);
- }
- };
- return {
- cancel,
- throttle: throttle2
- };
- };
- var last = function(fn, rate) {
- var timer = null;
- var cancel = function() {
- if (!isNull(timer)) {
- clearTimeout(timer);
- timer = null;
- }
- };
- var throttle2 = function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- cancel();
- timer = setTimeout(function() {
- timer = null;
- fn.apply(null, args);
- }, rate);
- };
- return {
- cancel,
- throttle: throttle2
- };
- };
- var global$d = tinymce.util.Tools.resolve("tinymce.dom.TextSeeker");
- var isBoundary = function(dom2, node) {
- return dom2.isBlock(node) || contains$2([
- "BR",
- "IMG",
- "HR",
- "INPUT"
- ], node.nodeName) || dom2.getContentEditable(node) === "false";
- };
- var repeatLeft = function(dom2, node, offset2, process2, rootNode) {
- var search2 = global$d(dom2, function(node2) {
- return isBoundary(dom2, node2);
- });
- return Optional.from(search2.backwards(node, offset2, process2, rootNode));
- };
- var autocompleteSelector = "[data-mce-autocompleter]";
- var create$5 = function(editor, range2) {
- return detect(SugarElement.fromDom(editor.selection.getNode())).getOrThunk(function() {
- var wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
- append$2(wrapper, SugarElement.fromDom(range2.extractContents()));
- range2.insertNode(wrapper.dom);
- parent(wrapper).each(function(elm) {
- return elm.dom.normalize();
- });
- last$1(wrapper).map(function(last2) {
- editor.selection.setCursorLocation(last2.dom, getEnd(last2));
- });
- return wrapper;
- });
- };
- var detect = function(elm) {
- return closest$1(elm, autocompleteSelector);
- };
- var isValidTextRange = function(rng) {
- return rng.collapsed && rng.startContainer.nodeType === 3;
- };
- var getText = function(rng) {
- return rng.toString().replace(/\u00A0/g, " ").replace(/\uFEFF/g, "");
- };
- var isWhitespace = function(chr) {
- return chr !== "" && " \f\n\r \v".indexOf(chr) !== -1;
- };
- var stripTriggerChar = function(text2, triggerCh) {
- return text2.substring(triggerCh.length);
- };
- var findChar = function(text2, index, ch) {
- var i;
- for (i = index - 1; i >= 0; i--) {
- var char = text2.charAt(i);
- if (isWhitespace(char)) {
- return Optional.none();
- }
- if (char === ch) {
- break;
- }
- }
- return Optional.some(i);
- };
- var findStart = function(dom2, initRange, ch, minChars) {
- if (minChars === void 0) {
- minChars = 0;
- }
- if (!isValidTextRange(initRange)) {
- return Optional.none();
- }
- var findTriggerChIndex = function(element2, offset2, text2) {
- return findChar(text2, offset2, ch).getOr(offset2);
- };
- var root = dom2.getParent(initRange.startContainer, dom2.isBlock) || dom2.getRoot();
- return repeatLeft(dom2, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function(spot2) {
- var range2 = initRange.cloneRange();
- range2.setStart(spot2.container, spot2.offset);
- range2.setEnd(initRange.endContainer, initRange.endOffset);
- if (range2.collapsed) {
- return Optional.none();
- }
- var text2 = getText(range2);
- var triggerCharIndex = text2.lastIndexOf(ch);
- if (triggerCharIndex !== 0 || stripTriggerChar(text2, ch).length < minChars) {
- return Optional.none();
- } else {
- return Optional.some({
- text: stripTriggerChar(text2, ch),
- range: range2,
- triggerChar: ch
- });
- }
- });
- };
- var getContext = function(dom2, initRange, ch, minChars) {
- if (minChars === void 0) {
- minChars = 0;
- }
- return detect(SugarElement.fromDom(initRange.startContainer)).fold(function() {
- return findStart(dom2, initRange, ch, minChars);
- }, function(elm) {
- var range2 = dom2.createRng();
- range2.selectNode(elm.dom);
- var text2 = getText(range2);
- return Optional.some({
- range: range2,
- text: stripTriggerChar(text2, ch),
- triggerChar: ch
- });
- });
- };
- var setup$e = function(api2, editor) {
- editor.on("keypress compositionend", api2.onKeypress.throttle);
- editor.on("remove", api2.onKeypress.cancel);
- var redirectKeyToItem = function(item2, e) {
- emitWith(item2, keydown(), { raw: e });
- };
- editor.on("keydown", function(e) {
- var getItem = function() {
- return api2.getView().bind(Highlighting.getHighlighted);
- };
- if (e.which === 8) {
- api2.onKeypress.throttle(e);
- }
- if (api2.isActive()) {
- if (e.which === 27) {
- api2.cancelIfNecessary();
- }
- if (api2.isMenuOpen()) {
- if (e.which === 13) {
- getItem().each(emitExecute);
- e.preventDefault();
- } else if (e.which === 40) {
- getItem().fold(function() {
- api2.getView().each(Highlighting.highlightFirst);
- }, function(item2) {
- redirectKeyToItem(item2, e);
- });
- e.preventDefault();
- e.stopImmediatePropagation();
- } else if (e.which === 37 || e.which === 38 || e.which === 39) {
- getItem().each(function(item2) {
- redirectKeyToItem(item2, e);
- e.preventDefault();
- e.stopImmediatePropagation();
- });
- }
- } else {
- if (e.which === 13 || e.which === 38 || e.which === 40) {
- api2.cancelIfNecessary();
- }
- }
- }
- });
- editor.on("NodeChange", function(e) {
- if (api2.isActive() && !api2.isProcessingAction() && detect(SugarElement.fromDom(e.element)).isNone()) {
- api2.cancelIfNecessary();
- }
- });
- };
- var AutocompleterEditorEvents = { setup: setup$e };
- var global$c = tinymce.util.Tools.resolve("tinymce.util.Promise");
- var point = function(container, offset2) {
- return {
- container,
- offset: offset2
- };
- };
- var isText = function(node) {
- return node.nodeType === TEXT;
- };
- var isElement$1 = function(node) {
- return node.nodeType === ELEMENT;
- };
- var toLast = function(node) {
- if (isText(node)) {
- return point(node, node.data.length);
- } else {
- var children2 = node.childNodes;
- return children2.length > 0 ? toLast(children2[children2.length - 1]) : point(node, children2.length);
- }
- };
- var toLeaf = function(node, offset2) {
- var children2 = node.childNodes;
- if (children2.length > 0 && offset2 < children2.length) {
- return toLeaf(children2[offset2], 0);
- } else if (children2.length > 0 && isElement$1(node) && children2.length === offset2) {
- return toLast(children2[children2.length - 1]);
- } else {
- return point(node, offset2);
- }
- };
- var isPreviousCharContent = function(dom2, leaf2) {
- return repeatLeft(dom2, leaf2.container, leaf2.offset, function(element2, offset2) {
- return offset2 === 0 ? -1 : offset2;
- }, dom2.getRoot()).filter(function(spot2) {
- var char = spot2.container.data.charAt(spot2.offset - 1);
- return !isWhitespace(char);
- }).isSome();
- };
- var isStartOfWord = function(dom2) {
- return function(rng) {
- var leaf2 = toLeaf(rng.startContainer, rng.startOffset);
- return !isPreviousCharContent(dom2, leaf2);
- };
- };
- var getTriggerContext = function(dom2, initRange, database) {
- return findMap(database.triggerChars, function(ch) {
- return getContext(dom2, initRange, ch);
- });
- };
- var lookup$2 = function(editor, getDatabase) {
- var database = getDatabase();
- var rng = editor.selection.getRng();
- return getTriggerContext(editor.dom, rng, database).bind(function(context) {
- return lookupWithContext(editor, getDatabase, context);
- });
- };
- var lookupWithContext = function(editor, getDatabase, context, fetchOptions) {
- if (fetchOptions === void 0) {
- fetchOptions = {};
- }
- var database = getDatabase();
- var rng = editor.selection.getRng();
- var startText = rng.startContainer.nodeValue;
- var autocompleters = filter$2(database.lookupByChar(context.triggerChar), function(autocompleter) {
- return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function() {
- return isStartOfWord(editor.dom);
- })(context.range, startText, context.text);
- });
- if (autocompleters.length === 0) {
- return Optional.none();
- }
- var lookupData = global$c.all(map$2(autocompleters, function(ac) {
- var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
- return fetchResult.then(function(results) {
- return {
- matchText: context.text,
- items: results,
- columns: ac.columns,
- onAction: ac.onAction,
- highlightOn: ac.highlightOn
- };
- });
- }));
- return Optional.some({
- lookupData,
- context
- });
- };
- var separatorMenuItemSchema = objOf([
- requiredString("type"),
- optionString("text")
- ]);
- var createSeparatorMenuItem = function(spec) {
- return asRaw("separatormenuitem", separatorMenuItemSchema, spec);
- };
- var autocompleterItemSchema = objOf([
- defaulted("type", "autocompleteitem"),
- defaulted("active", false),
- defaulted("disabled", false),
- defaulted("meta", {}),
- requiredString("value"),
- optionString("text"),
- optionString("icon")
- ]);
- var autocompleterSchema = objOf([
- requiredString("type"),
- requiredString("ch"),
- defaultedNumber("minChars", 1),
- defaulted("columns", 1),
- defaultedNumber("maxResults", 10),
- optionFunction("matches"),
- requiredFunction("fetch"),
- requiredFunction("onAction"),
- defaultedArrayOf("highlightOn", [], string)
- ]);
- var createSeparatorItem = function(spec) {
- return asRaw("Autocompleter.Separator", separatorMenuItemSchema, spec);
- };
- var createAutocompleterItem = function(spec) {
- return asRaw("Autocompleter.Item", autocompleterItemSchema, spec);
- };
- var createAutocompleter = function(spec) {
- return asRaw("Autocompleter", autocompleterSchema, spec);
- };
- var baseToolbarButtonFields = [
- defaultedBoolean("disabled", false),
- optionString("tooltip"),
- optionString("icon"),
- optionString("text"),
- defaultedFunction("onSetup", function() {
- return noop;
- })
- ];
- var toolbarButtonSchema = objOf([
- requiredString("type"),
- requiredFunction("onAction")
- ].concat(baseToolbarButtonFields));
- var createToolbarButton = function(spec) {
- return asRaw("toolbarbutton", toolbarButtonSchema, spec);
- };
- var baseToolbarToggleButtonFields = [defaultedBoolean("active", false)].concat(baseToolbarButtonFields);
- var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
- requiredString("type"),
- requiredFunction("onAction")
- ]));
- var createToggleButton = function(spec) {
- return asRaw("ToggleButton", toggleButtonSchema, spec);
- };
- var contextBarFields = [
- defaultedFunction("predicate", never),
- defaultedStringEnum("scope", "node", [
- "node",
- "editor"
- ]),
- defaultedStringEnum("position", "selection", [
- "node",
- "selection",
- "line"
- ])
- ];
- var contextButtonFields = baseToolbarButtonFields.concat([
- defaulted("type", "contextformbutton"),
- defaulted("primary", false),
- requiredFunction("onAction"),
- customField("original", identity$1)
- ]);
- var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
- defaulted("type", "contextformbutton"),
- defaulted("primary", false),
- requiredFunction("onAction"),
- customField("original", identity$1)
- ]);
- var launchButtonFields = baseToolbarButtonFields.concat([defaulted("type", "contextformbutton")]);
- var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted("type", "contextformtogglebutton")]);
- var toggleOrNormal = choose$1("type", {
- contextformbutton: contextButtonFields,
- contextformtogglebutton: contextToggleButtonFields
- });
- var contextFormSchema = objOf([
- defaulted("type", "contextform"),
- defaultedFunction("initValue", constant$1("")),
- optionString("label"),
- requiredArrayOf("commands", toggleOrNormal),
- optionOf("launch", choose$1("type", {
- contextformbutton: launchButtonFields,
- contextformtogglebutton: launchToggleButtonFields
- }))
- ].concat(contextBarFields));
- var createContextForm = function(spec) {
- return asRaw("ContextForm", contextFormSchema, spec);
- };
- var contextToolbarSchema = objOf([
- defaulted("type", "contexttoolbar"),
- requiredString("items")
- ].concat(contextBarFields));
- var createContextToolbar = function(spec) {
- return asRaw("ContextToolbar", contextToolbarSchema, spec);
- };
- var stringArray = function(a) {
- var all2 = {};
- each$1(a, function(key) {
- all2[key] = {};
- });
- return keys(all2);
- };
- var register$b = function(editor) {
- var popups = editor.ui.registry.getAll().popups;
- var dataset2 = map$1(popups, function(popup) {
- return createAutocompleter(popup).fold(function(err) {
- throw new Error(formatError(err));
- }, identity$1);
- });
- var triggerChars = stringArray(mapToArray(dataset2, function(v) {
- return v.ch;
- }));
- var datasetValues = values(dataset2);
- var lookupByChar = function(ch) {
- return filter$2(datasetValues, function(dv) {
- return dv.ch === ch;
- });
- };
- return {
- dataset: dataset2,
- triggerChars,
- lookupByChar
- };
- };
- var ItemResponse;
- (function(ItemResponse2) {
- ItemResponse2[ItemResponse2["CLOSE_ON_EXECUTE"] = 0] = "CLOSE_ON_EXECUTE";
- ItemResponse2[ItemResponse2["BUBBLE_TO_SANDBOX"] = 1] = "BUBBLE_TO_SANDBOX";
- })(ItemResponse || (ItemResponse = {}));
- var ItemResponse$1 = ItemResponse;
- var navClass = "tox-menu-nav__js";
- var selectableClass = "tox-collection__item";
- var colorClass = "tox-swatch";
- var presetClasses = {
- normal: navClass,
- color: colorClass
- };
- var tickedClass = "tox-collection__item--enabled";
- var groupHeadingClass = "tox-collection__group-heading";
- var iconClass = "tox-collection__item-icon";
- var textClass = "tox-collection__item-label";
- var accessoryClass = "tox-collection__item-accessory";
- var caretClass = "tox-collection__item-caret";
- var checkmarkClass = "tox-collection__item-checkmark";
- var activeClass = "tox-collection__item--active";
- var containerClass = "tox-collection__item-container";
- var containerColumnClass = "tox-collection__item-container--column";
- var containerRowClass = "tox-collection__item-container--row";
- var containerAlignRightClass = "tox-collection__item-container--align-right";
- var containerAlignLeftClass = "tox-collection__item-container--align-left";
- var containerValignTopClass = "tox-collection__item-container--valign-top";
- var containerValignMiddleClass = "tox-collection__item-container--valign-middle";
- var containerValignBottomClass = "tox-collection__item-container--valign-bottom";
- var classForPreset = function(presets) {
- return get$e(presetClasses, presets).getOr(navClass);
- };
- var forMenu = function(presets) {
- if (presets === "color") {
- return "tox-swatches";
- } else {
- return "tox-menu";
- }
- };
- var classes = function(presets) {
- return {
- backgroundMenu: "tox-background-menu",
- selectedMenu: "tox-selected-menu",
- selectedItem: "tox-collection__item--active",
- hasIcons: "tox-menu--has-icons",
- menu: forMenu(presets),
- tieredMenu: "tox-tiered-menu"
- };
- };
- var markers = function(presets) {
- var menuClasses = classes(presets);
- return {
- backgroundMenu: menuClasses.backgroundMenu,
- selectedMenu: menuClasses.selectedMenu,
- menu: menuClasses.menu,
- selectedItem: menuClasses.selectedItem,
- item: classForPreset(presets)
- };
- };
- var dom$1 = function(hasIcons, columns, presets) {
- var menuClasses = classes(presets);
- return {
- tag: "div",
- classes: flatten([
- [
- menuClasses.menu,
- "tox-menu-" + columns + "-column"
- ],
- hasIcons ? [menuClasses.hasIcons] : []
- ])
- };
- };
- var components = [Menu.parts.items({})];
- var part = function(hasIcons, columns, presets) {
- var menuClasses = classes(presets);
- var d = {
- tag: "div",
- classes: flatten([[menuClasses.tieredMenu]])
- };
- return {
- dom: d,
- markers: markers(presets)
- };
- };
- var chunk = function(rowDom, numColumns) {
- return function(items) {
- var chunks = chunk$1(items, numColumns);
- return map$2(chunks, function(c) {
- return {
- dom: rowDom,
- components: c
- };
- });
- };
- };
- var forSwatch = function(columns) {
- return {
- dom: {
- tag: "div",
- classes: [
- "tox-menu",
- "tox-swatches-menu"
- ]
- },
- components: [{
- dom: {
- tag: "div",
- classes: ["tox-swatches"]
- },
- components: [Menu.parts.items({
- preprocess: columns !== "auto" ? chunk({
- tag: "div",
- classes: ["tox-swatches__row"]
- }, columns) : identity$1
- })]
- }]
- };
- };
- var forToolbar = function(columns) {
- return {
- dom: {
- tag: "div",
- classes: [
- "tox-menu",
- "tox-collection",
- "tox-collection--toolbar",
- "tox-collection--toolbar-lg"
- ]
- },
- components: [Menu.parts.items({
- preprocess: chunk({
- tag: "div",
- classes: ["tox-collection__group"]
- }, columns)
- })]
- };
- };
- var preprocessCollection = function(items, isSeparator2) {
- var allSplits = [];
- var currentSplit = [];
- each$1(items, function(item2, i) {
- if (isSeparator2(item2, i)) {
- if (currentSplit.length > 0) {
- allSplits.push(currentSplit);
- }
- currentSplit = [];
- if (has$2(item2.dom, "innerHtml")) {
- currentSplit.push(item2);
- }
- } else {
- currentSplit.push(item2);
- }
- });
- if (currentSplit.length > 0) {
- allSplits.push(currentSplit);
- }
- return map$2(allSplits, function(s) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-collection__group"]
- },
- components: s
- };
- });
- };
- var forCollection = function(columns, initItems, _hasIcons) {
- return {
- dom: {
- tag: "div",
- classes: [
- "tox-menu",
- "tox-collection"
- ].concat(columns === 1 ? ["tox-collection--list"] : ["tox-collection--grid"])
- },
- components: [Menu.parts.items({
- preprocess: function(items) {
- if (columns !== "auto" && columns > 1) {
- return chunk({
- tag: "div",
- classes: ["tox-collection__group"]
- }, columns)(items);
- } else {
- return preprocessCollection(items, function(_item, i) {
- return initItems[i].type === "separator";
- });
- }
- }
- })]
- };
- };
- var forHorizontalCollection = function(initItems, _hasIcons) {
- return {
- dom: {
- tag: "div",
- classes: [
- "tox-collection",
- "tox-collection--horizontal"
- ]
- },
- components: [Menu.parts.items({
- preprocess: function(items) {
- return preprocessCollection(items, function(_item, i) {
- return initItems[i].type === "separator";
- });
- }
- })]
- };
- };
- var menuHasIcons = function(xs) {
- return exists(xs, function(item2) {
- return "icon" in item2 && item2.icon !== void 0;
- });
- };
- var handleError = function(error2) {
- console.error(formatError(error2));
- console.log(error2);
- return Optional.none();
- };
- var createHorizontalPartialMenuWithAlloyItems = function(value2, _hasIcons, items, _columns, _presets) {
- var structure = forHorizontalCollection(items);
- return {
- value: value2,
- dom: structure.dom,
- components: structure.components,
- items
- };
- };
- var createPartialMenuWithAlloyItems = function(value2, hasIcons, items, columns, presets) {
- if (presets === "color") {
- var structure = forSwatch(columns);
- return {
- value: value2,
- dom: structure.dom,
- components: structure.components,
- items
- };
- }
- if (presets === "normal" && columns === "auto") {
- var structure = forCollection(columns, items);
- return {
- value: value2,
- dom: structure.dom,
- components: structure.components,
- items
- };
- }
- if (presets === "normal" && columns === 1) {
- var structure = forCollection(1, items);
- return {
- value: value2,
- dom: structure.dom,
- components: structure.components,
- items
- };
- }
- if (presets === "normal") {
- var structure = forCollection(columns, items);
- return {
- value: value2,
- dom: structure.dom,
- components: structure.components,
- items
- };
- }
- if (presets === "listpreview" && columns !== "auto") {
- var structure = forToolbar(columns);
- return {
- value: value2,
- dom: structure.dom,
- components: structure.components,
- items
- };
- }
- return {
- value: value2,
- dom: dom$1(hasIcons, columns, presets),
- components,
- items
- };
- };
- var cardImageFields = [
- requiredString("type"),
- requiredString("src"),
- optionString("alt"),
- defaultedArrayOf("classes", [], string)
- ];
- var cardImageSchema = objOf(cardImageFields);
- var cardTextFields = [
- requiredString("type"),
- requiredString("text"),
- optionString("name"),
- defaultedArrayOf("classes", ["tox-collection__item-label"], string)
- ];
- var cardTextSchema = objOf(cardTextFields);
- var itemSchema$1 = valueThunk(function() {
- return choose$2("type", {
- cardimage: cardImageSchema,
- cardtext: cardTextSchema,
- cardcontainer: cardContainerSchema
- });
- });
- var cardContainerSchema = objOf([
- requiredString("type"),
- defaultedString("direction", "horizontal"),
- defaultedString("align", "left"),
- defaultedString("valign", "middle"),
- requiredArrayOf("items", itemSchema$1)
- ]);
- var commonMenuItemFields = [
- defaultedBoolean("disabled", false),
- optionString("text"),
- optionString("shortcut"),
- field$1("value", "value", defaultedThunk(function() {
- return generate$6("menuitem-value");
- }), anyValue()),
- defaulted("meta", {})
- ];
- var cardMenuItemSchema = objOf([
- requiredString("type"),
- optionString("label"),
- requiredArrayOf("items", itemSchema$1),
- defaultedFunction("onSetup", function() {
- return noop;
- }),
- defaultedFunction("onAction", noop)
- ].concat(commonMenuItemFields));
- var createCardMenuItem = function(spec) {
- return asRaw("cardmenuitem", cardMenuItemSchema, spec);
- };
- var choiceMenuItemSchema = objOf([
- requiredString("type"),
- defaultedBoolean("active", false),
- optionString("icon")
- ].concat(commonMenuItemFields));
- var createChoiceMenuItem = function(spec) {
- return asRaw("choicemenuitem", choiceMenuItemSchema, spec);
- };
- var baseFields = [
- requiredString("type"),
- requiredString("fancytype"),
- defaultedFunction("onAction", noop)
- ];
- var insertTableFields = [defaulted("initData", {})].concat(baseFields);
- var colorSwatchFields = [defaultedObjOf("initData", {}, [
- defaultedBoolean("allowCustomColors", true),
- optionArrayOf("colors", anyValue())
- ])].concat(baseFields);
- var fancyMenuItemSchema = choose$1("fancytype", {
- inserttable: insertTableFields,
- colorswatch: colorSwatchFields
- });
- var createFancyMenuItem = function(spec) {
- return asRaw("fancymenuitem", fancyMenuItemSchema, spec);
- };
- var menuItemSchema = objOf([
- requiredString("type"),
- defaultedFunction("onSetup", function() {
- return noop;
- }),
- defaultedFunction("onAction", noop),
- optionString("icon")
- ].concat(commonMenuItemFields));
- var createMenuItem = function(spec) {
- return asRaw("menuitem", menuItemSchema, spec);
- };
- var nestedMenuItemSchema = objOf([
- requiredString("type"),
- requiredFunction("getSubmenuItems"),
- defaultedFunction("onSetup", function() {
- return noop;
- }),
- optionString("icon")
- ].concat(commonMenuItemFields));
- var createNestedMenuItem = function(spec) {
- return asRaw("nestedmenuitem", nestedMenuItemSchema, spec);
- };
- var toggleMenuItemSchema = objOf([
- requiredString("type"),
- optionString("icon"),
- defaultedBoolean("active", false),
- defaultedFunction("onSetup", function() {
- return noop;
- }),
- requiredFunction("onAction")
- ].concat(commonMenuItemFields));
- var createToggleMenuItem = function(spec) {
- return asRaw("togglemenuitem", toggleMenuItemSchema, spec);
- };
- var detectSize = function(comp, margin, selectorClass) {
- var descendants$1 = descendants(comp.element, "." + selectorClass);
- if (descendants$1.length > 0) {
- var columnLength = findIndex$1(descendants$1, function(c) {
- var thisTop = c.dom.getBoundingClientRect().top;
- var cTop = descendants$1[0].dom.getBoundingClientRect().top;
- return Math.abs(thisTop - cTop) > margin;
- }).getOr(descendants$1.length);
- return Optional.some({
- numColumns: columnLength,
- numRows: Math.ceil(descendants$1.length / columnLength)
- });
- } else {
- return Optional.none();
- }
- };
- var namedEvents = function(name2, handlers2) {
- return derive$1([config(name2, handlers2)]);
- };
- var unnamedEvents = function(handlers2) {
- return namedEvents(generate$6("unnamed-events"), handlers2);
- };
- var SimpleBehaviours = {
- namedEvents,
- unnamedEvents
- };
- var ExclusivityChannel = generate$6("tooltip.exclusive");
- var ShowTooltipEvent = generate$6("tooltip.show");
- var HideTooltipEvent = generate$6("tooltip.hide");
- var hideAllExclusive = function(component, _tConfig, _tState) {
- component.getSystem().broadcastOn([ExclusivityChannel], {});
- };
- var setComponents = function(component, tConfig, tState, specs) {
- tState.getTooltip().each(function(tooltip) {
- if (tooltip.getSystem().isConnected()) {
- Replacing.set(tooltip, specs);
- }
- });
- };
- var TooltippingApis = Object.freeze({
- __proto__: null,
- hideAllExclusive,
- setComponents
- });
- var events$9 = function(tooltipConfig, state) {
- var hide = function(comp) {
- state.getTooltip().each(function(p) {
- detach(p);
- tooltipConfig.onHide(comp, p);
- state.clearTooltip();
- });
- state.clearTimer();
- };
- var show2 = function(comp) {
- if (!state.isShowing()) {
- hideAllExclusive(comp);
- var sink = tooltipConfig.lazySink(comp).getOrDie();
- var popup = comp.getSystem().build({
- dom: tooltipConfig.tooltipDom,
- components: tooltipConfig.tooltipComponents,
- events: derive$2(tooltipConfig.mode === "normal" ? [
- run$1(mouseover(), function(_) {
- emit(comp, ShowTooltipEvent);
- }),
- run$1(mouseout(), function(_) {
- emit(comp, HideTooltipEvent);
- })
- ] : []),
- behaviours: derive$1([Replacing.config({})])
- });
- state.setTooltip(popup);
- attach(sink, popup);
- tooltipConfig.onShow(comp, popup);
- Positioning.position(sink, popup, { anchor: tooltipConfig.anchor(comp) });
- }
- };
- return derive$2(flatten([
- [
- run$1(ShowTooltipEvent, function(comp) {
- state.resetTimer(function() {
- show2(comp);
- }, tooltipConfig.delay);
- }),
- run$1(HideTooltipEvent, function(comp) {
- state.resetTimer(function() {
- hide(comp);
- }, tooltipConfig.delay);
- }),
- run$1(receive(), function(comp, message) {
- var receivingData = message;
- if (!receivingData.universal) {
- if (contains$2(receivingData.channels, ExclusivityChannel)) {
- hide(comp);
- }
- }
- }),
- runOnDetached(function(comp) {
- hide(comp);
- })
- ],
- tooltipConfig.mode === "normal" ? [
- run$1(focusin(), function(comp) {
- emit(comp, ShowTooltipEvent);
- }),
- run$1(postBlur(), function(comp) {
- emit(comp, HideTooltipEvent);
- }),
- run$1(mouseover(), function(comp) {
- emit(comp, ShowTooltipEvent);
- }),
- run$1(mouseout(), function(comp) {
- emit(comp, HideTooltipEvent);
- })
- ] : [
- run$1(highlight$1(), function(comp, _se) {
- emit(comp, ShowTooltipEvent);
- }),
- run$1(dehighlight$1(), function(comp) {
- emit(comp, HideTooltipEvent);
- })
- ]
- ]));
- };
- var ActiveTooltipping = Object.freeze({
- __proto__: null,
- events: events$9
- });
- var TooltippingSchema = [
- required$1("lazySink"),
- required$1("tooltipDom"),
- defaulted("exclusive", true),
- defaulted("tooltipComponents", []),
- defaulted("delay", 300),
- defaultedStringEnum("mode", "normal", [
- "normal",
- "follow-highlight"
- ]),
- defaulted("anchor", function(comp) {
- return {
- type: "hotspot",
- hotspot: comp,
- layouts: {
- onLtr: constant$1([
- south$2,
- north$2,
- southeast$2,
- northeast$2,
- southwest$2,
- northwest$2
- ]),
- onRtl: constant$1([
- south$2,
- north$2,
- southeast$2,
- northeast$2,
- southwest$2,
- northwest$2
- ])
- }
- };
- }),
- onHandler("onHide"),
- onHandler("onShow")
- ];
- var init$b = function() {
- var timer = value$1();
- var popup = value$1();
- var clearTimer = function() {
- timer.on(clearTimeout);
- };
- var resetTimer = function(f, delay) {
- clearTimer();
- timer.set(setTimeout(f, delay));
- };
- var readState = constant$1("not-implemented");
- return nu$8({
- getTooltip: popup.get,
- isShowing: popup.isSet,
- setTooltip: popup.set,
- clearTooltip: popup.clear,
- clearTimer,
- resetTimer,
- readState
- });
- };
- var TooltippingState = Object.freeze({
- __proto__: null,
- init: init$b
- });
- var Tooltipping = create$8({
- fields: TooltippingSchema,
- name: "tooltipping",
- active: ActiveTooltipping,
- state: TooltippingState,
- apis: TooltippingApis
- });
- var escape = function(text2) {
- return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- };
- var global$b = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
- var global$a = tinymce.util.Tools.resolve("tinymce.EditorManager");
- var getSkinUrl = function(editor) {
- var skin = editor.getParam("skin");
- var skinUrl = editor.getParam("skin_url");
- if (skin !== false) {
- var skinName = skin ? skin : "oxide";
- if (skinUrl) {
- skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
- } else {
- skinUrl = global$a.baseURL + "/skins/ui/" + skinName;
- }
- }
- return skinUrl;
- };
- var isReadOnly = function(editor) {
- return editor.getParam("readonly", false, "boolean");
- };
- var isSkinDisabled = function(editor) {
- return editor.getParam("skin") === false;
- };
- var getHeightSetting = function(editor) {
- return editor.getParam("height", Math.max(editor.getElement().offsetHeight, 200));
- };
- var getWidthSetting = function(editor) {
- return editor.getParam("width", global$b.DOM.getStyle(editor.getElement(), "width"));
- };
- var getMinWidthSetting = function(editor) {
- return Optional.from(editor.getParam("min_width")).filter(isNumber);
- };
- var getMinHeightSetting = function(editor) {
- return Optional.from(editor.getParam("min_height")).filter(isNumber);
- };
- var getMaxWidthSetting = function(editor) {
- return Optional.from(editor.getParam("max_width")).filter(isNumber);
- };
- var getMaxHeightSetting = function(editor) {
- return Optional.from(editor.getParam("max_height")).filter(isNumber);
- };
- var getUserStyleFormats = function(editor) {
- return Optional.from(editor.getParam("style_formats")).filter(isArray);
- };
- var isMergeStyleFormats = function(editor) {
- return editor.getParam("style_formats_merge", false, "boolean");
- };
- var getLineHeightFormats = function(editor) {
- return editor.getParam("lineheight_formats", "1 1.1 1.2 1.3 1.4 1.5 2", "string").split(" ");
- };
- var getContentLanguages = function(editor) {
- return editor.getParam("content_langs", void 0, "array");
- };
- var getRemovedMenuItems = function(editor) {
- return editor.getParam("removed_menuitems", "");
- };
- var isMenubarEnabled = function(editor) {
- return editor.getParam("menubar", true, "boolean") !== false;
- };
- var isToolbarEnabled = function(editor) {
- var toolbar = editor.getParam("toolbar", true);
- var isToolbarTrue = toolbar === true;
- var isToolbarString = isString(toolbar);
- var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
- return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
- };
- var getMultipleToolbarsSetting = function(editor) {
- var toolbars = range$2(9, function(num) {
- return editor.getParam("toolbar" + (num + 1), false, "string");
- });
- var toolbarArray = filter$2(toolbars, function(toolbar) {
- return typeof toolbar === "string";
- });
- return toolbarArray.length > 0 ? Optional.some(toolbarArray) : Optional.none();
- };
- var isMultipleToolbars = function(editor) {
- return getMultipleToolbarsSetting(editor).fold(function() {
- var toolbar = editor.getParam("toolbar", [], "string[]");
- return toolbar.length > 0;
- }, always);
- };
- var ToolbarMode;
- (function(ToolbarMode2) {
- ToolbarMode2["default"] = "wrap";
- ToolbarMode2["floating"] = "floating";
- ToolbarMode2["sliding"] = "sliding";
- ToolbarMode2["scrolling"] = "scrolling";
- })(ToolbarMode || (ToolbarMode = {}));
- var getToolbarMode = function(editor) {
- return editor.getParam("toolbar_mode", "", "string");
- };
- var ToolbarLocation;
- (function(ToolbarLocation2) {
- ToolbarLocation2["auto"] = "auto";
- ToolbarLocation2["top"] = "top";
- ToolbarLocation2["bottom"] = "bottom";
- })(ToolbarLocation || (ToolbarLocation = {}));
- var getToolbarGroups = function(editor) {
- return editor.getParam("toolbar_groups", {}, "object");
- };
- var getToolbarLocation = function(editor) {
- return editor.getParam("toolbar_location", ToolbarLocation.auto, "string");
- };
- var isToolbarLocationBottom = function(editor) {
- return getToolbarLocation(editor) === ToolbarLocation.bottom;
- };
- var fixedContainerSelector = function(editor) {
- return editor.getParam("fixed_toolbar_container", "", "string");
- };
- var fixedToolbarContainerTarget = function(editor) {
- return editor.getParam("fixed_toolbar_container_target");
- };
- var isToolbarPersist = function(editor) {
- return editor.getParam("toolbar_persist", false, "boolean");
- };
- var fixedContainerTarget = function(editor) {
- if (!editor.inline) {
- return Optional.none();
- }
- var selector = fixedContainerSelector(editor);
- if (selector.length > 0) {
- return descendant(body(), selector);
- }
- var element2 = fixedToolbarContainerTarget(editor);
- if (isNonNullable(element2)) {
- return Optional.some(SugarElement.fromDom(element2));
- }
- return Optional.none();
- };
- var useFixedContainer = function(editor) {
- return editor.inline && fixedContainerTarget(editor).isSome();
- };
- var getUiContainer = function(editor) {
- var fixedContainer = fixedContainerTarget(editor);
- return fixedContainer.getOrThunk(function() {
- return getContentContainer(getRootNode(SugarElement.fromDom(editor.getElement())));
- });
- };
- var isDistractionFree = function(editor) {
- return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
- };
- var isStickyToolbar = function(editor) {
- var isStickyToolbar2 = editor.getParam("toolbar_sticky", false, "boolean");
- return (isStickyToolbar2 || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
- };
- var getStickyToolbarOffset = function(editor) {
- return editor.getParam("toolbar_sticky_offset", 0, "number");
- };
- var isDraggableModal$1 = function(editor) {
- return editor.getParam("draggable_modal", false, "boolean");
- };
- var getMenus = function(editor) {
- var menu2 = editor.getParam("menu");
- if (menu2) {
- return map$1(menu2, function(menu3) {
- return __assign(__assign({}, menu3), { items: menu3.items });
- });
- } else {
- return {};
- }
- };
- var getMenubar = function(editor) {
- return editor.getParam("menubar");
- };
- var getToolbar = function(editor) {
- return editor.getParam("toolbar", true);
- };
- var getFilePickerCallback = function(editor) {
- return editor.getParam("file_picker_callback");
- };
- var getFilePickerTypes = function(editor) {
- return editor.getParam("file_picker_types");
- };
- var getFileBrowserCallbackTypes = function(editor) {
- return editor.getParam("file_browser_callback_types");
- };
- var noTypeaheadUrls = function(editor) {
- return editor.getParam("typeahead_urls") === false;
- };
- var getAnchorTop = function(editor) {
- return editor.getParam("anchor_top", "#top");
- };
- var getAnchorBottom = function(editor) {
- return editor.getParam("anchor_bottom", "#bottom");
- };
- var getFilePickerValidatorHandler = function(editor) {
- var handler = editor.getParam("file_picker_validator_handler", void 0, "function");
- if (handler === void 0) {
- return editor.getParam("filepicker_validator_handler", void 0, "function");
- } else {
- return handler;
- }
- };
- var ReadOnlyChannel = "silver.readonly";
- var ReadOnlyDataSchema = objOf([requiredBoolean("readonly")]);
- var broadcastReadonly = function(uiComponents, readonly) {
- var outerContainer = uiComponents.outerContainer;
- var target = outerContainer.element;
- if (readonly) {
- uiComponents.mothership.broadcastOn([dismissPopups()], { target });
- uiComponents.uiMothership.broadcastOn([dismissPopups()], { target });
- }
- uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly });
- uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly });
- };
- var setupReadonlyModeSwitch = function(editor, uiComponents) {
- editor.on("init", function() {
- if (editor.mode.isReadOnly()) {
- broadcastReadonly(uiComponents, true);
- }
- });
- editor.on("SwitchMode", function() {
- return broadcastReadonly(uiComponents, editor.mode.isReadOnly());
- });
- if (isReadOnly(editor)) {
- editor.setMode("readonly");
- }
- };
- var receivingConfig = function() {
- var _a2;
- return Receiving.config({
- channels: (_a2 = {}, _a2[ReadOnlyChannel] = {
- schema: ReadOnlyDataSchema,
- onReceive: function(comp, data) {
- Disabling.set(comp, data.readonly);
- }
- }, _a2)
- });
- };
- var item = function(disabled) {
- return Disabling.config({
- disabled,
- disableClass: "tox-collection__item--state-disabled"
- });
- };
- var button = function(disabled) {
- return Disabling.config({ disabled });
- };
- var splitButton = function(disabled) {
- return Disabling.config({
- disabled,
- disableClass: "tox-tbtn--disabled"
- });
- };
- var toolbarButton = function(disabled) {
- return Disabling.config({
- disabled,
- disableClass: "tox-tbtn--disabled",
- useNative: false
- });
- };
- var DisablingConfigs = {
- item,
- button,
- splitButton,
- toolbarButton
- };
- var runWithApi = function(info, comp) {
- var api2 = info.getApi(comp);
- return function(f) {
- f(api2);
- };
- };
- var onControlAttached = function(info, editorOffCell) {
- return runOnAttached(function(comp) {
- var run2 = runWithApi(info, comp);
- run2(function(api2) {
- var onDestroy = info.onSetup(api2);
- if (isFunction(onDestroy)) {
- editorOffCell.set(onDestroy);
- }
- });
- });
- };
- var onControlDetached = function(getApi2, editorOffCell) {
- return runOnDetached(function(comp) {
- return runWithApi(getApi2, comp)(editorOffCell.get());
- });
- };
- var _a$1;
- var onMenuItemExecute = function(info, itemResponse) {
- return runOnExecute$1(function(comp, simulatedEvent) {
- runWithApi(info, comp)(info.onAction);
- if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
- emit(comp, sandboxClose());
- simulatedEvent.stop();
- }
- });
- };
- var menuItemEventOrder = (_a$1 = {}, _a$1[execute$5()] = [
- "disabling",
- "alloy.base.behaviour",
- "toggling",
- "item-events"
- ], _a$1);
- var componentRenderPipeline = cat;
- var renderCommonItem = function(spec, structure, itemResponse, providersbackstage) {
- var editorOffCell = Cell(noop);
- return {
- type: "item",
- dom: structure.dom,
- components: componentRenderPipeline(structure.optComponents),
- data: spec.data,
- eventOrder: menuItemEventOrder,
- hasSubmenu: spec.triggersSubmenu,
- itemBehaviours: derive$1([
- config("item-events", [
- onMenuItemExecute(spec, itemResponse),
- onControlAttached(spec, editorOffCell),
- onControlDetached(spec, editorOffCell)
- ]),
- DisablingConfigs.item(function() {
- return spec.disabled || providersbackstage.isDisabled();
- }),
- receivingConfig(),
- Replacing.config({})
- ].concat(spec.itemBehaviours))
- };
- };
- var buildData = function(source) {
- return {
- value: source.value,
- meta: __assign({ text: source.text.getOr("") }, source.meta)
- };
- };
- var global$9 = tinymce.util.Tools.resolve("tinymce.Env");
- var convertText = function(source) {
- var mac = {
- alt: "⌥",
- ctrl: "⌃",
- shift: "⇧",
- meta: "⌘",
- access: "⌃⌥"
- };
- var other = {
- meta: "Ctrl",
- access: "Shift+Alt"
- };
- var replace = global$9.mac ? mac : other;
- var shortcut = source.split("+");
- var updated = map$2(shortcut, function(segment) {
- var search2 = segment.toLowerCase().trim();
- return has$2(replace, search2) ? replace[search2] : segment;
- });
- return global$9.mac ? updated.join("") : updated.join("+");
- };
- var renderIcon$1 = function(name2, icons, classes2) {
- if (classes2 === void 0) {
- classes2 = [iconClass];
- }
- return render$3(name2, {
- tag: "div",
- classes: classes2
- }, icons);
- };
- var renderText = function(text2) {
- return {
- dom: {
- tag: "div",
- classes: [textClass]
- },
- components: [text$1(global$e.translate(text2))]
- };
- };
- var renderHtml = function(html2, classes2) {
- return {
- dom: {
- tag: "div",
- classes: classes2,
- innerHtml: html2
- }
- };
- };
- var renderStyledText = function(style, text2) {
- return {
- dom: {
- tag: "div",
- classes: [textClass]
- },
- components: [{
- dom: {
- tag: style.tag,
- styles: style.styles
- },
- components: [text$1(global$e.translate(text2))]
- }]
- };
- };
- var renderShortcut = function(shortcut) {
- return {
- dom: {
- tag: "div",
- classes: [accessoryClass],
- innerHtml: convertText(shortcut)
- }
- };
- };
- var renderCheckmark = function(icons) {
- return renderIcon$1("checkmark", icons, [checkmarkClass]);
- };
- var renderSubmenuCaret = function(icons) {
- return renderIcon$1("chevron-right", icons, [caretClass]);
- };
- var renderDownwardsCaret = function(icons) {
- return renderIcon$1("chevron-down", icons, [caretClass]);
- };
- var renderContainer = function(container, components2) {
- var directionClass = container.direction === "vertical" ? containerColumnClass : containerRowClass;
- var alignClass = container.align === "left" ? containerAlignLeftClass : containerAlignRightClass;
- var getValignClass = function() {
- switch (container.valign) {
- case "top":
- return containerValignTopClass;
- case "middle":
- return containerValignMiddleClass;
- case "bottom":
- return containerValignBottomClass;
- }
- };
- return {
- dom: {
- tag: "div",
- classes: [
- containerClass,
- directionClass,
- alignClass,
- getValignClass()
- ]
- },
- components: components2
- };
- };
- var renderImage = function(src, classes2, alt) {
- return {
- dom: {
- tag: "img",
- classes: classes2,
- attributes: {
- src,
- alt: alt.getOr("")
- }
- }
- };
- };
- var renderColorStructure = function(item2, providerBackstage, fallbackIcon) {
- var colorPickerCommand = "custom";
- var removeColorCommand = "remove";
- var itemText = item2.ariaLabel;
- var itemValue = item2.value;
- var iconSvg = item2.iconContent.map(function(name2) {
- return getOr(name2, providerBackstage.icons, fallbackIcon);
- });
- var getDom = function() {
- var common = colorClass;
- var icon = iconSvg.getOr("");
- var attributes = itemText.map(function(text2) {
- return { title: providerBackstage.translate(text2) };
- }).getOr({});
- var baseDom = {
- tag: "div",
- attributes,
- classes: [common]
- };
- if (itemValue === colorPickerCommand) {
- return __assign(__assign({}, baseDom), {
- tag: "button",
- classes: __spreadArray(__spreadArray([], baseDom.classes, true), ["tox-swatches__picker-btn"], false),
- innerHtml: icon
- });
- } else if (itemValue === removeColorCommand) {
- return __assign(__assign({}, baseDom), {
- classes: __spreadArray(__spreadArray([], baseDom.classes, true), ["tox-swatch--remove"], false),
- innerHtml: icon
- });
- } else {
- return __assign(__assign({}, baseDom), {
- attributes: __assign(__assign({}, baseDom.attributes), { "data-mce-color": itemValue }),
- styles: { "background-color": itemValue }
- });
- }
- };
- return {
- dom: getDom(),
- optComponents: []
- };
- };
- var renderItemDomStructure = function(ariaLabel) {
- var domTitle = ariaLabel.map(function(label) {
- return { attributes: { title: global$e.translate(label) } };
- }).getOr({});
- return __assign({
- tag: "div",
- classes: [
- navClass,
- selectableClass
- ]
- }, domTitle);
- };
- var renderNormalItemStructure = function(info, providersBackstage, renderIcons, fallbackIcon) {
- var iconSpec = {
- tag: "div",
- classes: [iconClass]
- };
- var renderIcon2 = function(iconName) {
- return render$3(iconName, iconSpec, providersBackstage.icons, fallbackIcon);
- };
- var renderEmptyIcon = function() {
- return Optional.some({ dom: iconSpec });
- };
- var leftIcon = renderIcons ? info.iconContent.map(renderIcon2).orThunk(renderEmptyIcon) : Optional.none();
- var checkmark = info.checkMark;
- var textRender = Optional.from(info.meta).fold(function() {
- return renderText;
- }, function(meta) {
- return has$2(meta, "style") ? curry(renderStyledText, meta.style) : renderText;
- });
- var content = info.htmlContent.fold(function() {
- return info.textContent.map(textRender);
- }, function(html2) {
- return Optional.some(renderHtml(html2, [textClass]));
- });
- var menuItem = {
- dom: renderItemDomStructure(info.ariaLabel),
- optComponents: [
- leftIcon,
- content,
- info.shortcutContent.map(renderShortcut),
- checkmark,
- info.caret
- ]
- };
- return menuItem;
- };
- var renderItemStructure = function(info, providersBackstage, renderIcons, fallbackIcon) {
- if (fallbackIcon === void 0) {
- fallbackIcon = Optional.none();
- }
- if (info.presets === "color") {
- return renderColorStructure(info, providersBackstage, fallbackIcon);
- } else {
- return renderNormalItemStructure(info, providersBackstage, renderIcons, fallbackIcon);
- }
- };
- var tooltipBehaviour = function(meta, sharedBackstage) {
- return get$e(meta, "tooltipWorker").map(function(tooltipWorker) {
- return [Tooltipping.config({
- lazySink: sharedBackstage.getSink,
- tooltipDom: {
- tag: "div",
- classes: ["tox-tooltip-worker-container"]
- },
- tooltipComponents: [],
- anchor: function(comp) {
- return {
- type: "submenu",
- item: comp,
- overrides: { maxHeightFunction: expandable$1 }
- };
- },
- mode: "follow-highlight",
- onShow: function(component, _tooltip) {
- tooltipWorker(function(elm) {
- Tooltipping.setComponents(component, [external$2({ element: SugarElement.fromDom(elm) })]);
- });
- }
- })];
- }).getOr([]);
- };
- var encodeText = function(text2) {
- return global$b.DOM.encode(text2);
- };
- var replaceText = function(text2, matchText) {
- var translated = global$e.translate(text2);
- var encoded = encodeText(translated);
- if (matchText.length > 0) {
- var escapedMatchRegex = new RegExp(escape(matchText), "gi");
- return encoded.replace(escapedMatchRegex, function(match) {
- return '<span class="tox-autocompleter-highlight">' + match + "</span>";
- });
- } else {
- return encoded;
- }
- };
- var renderAutocompleteItem = function(spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
- if (renderIcons === void 0) {
- renderIcons = true;
- }
- var structure = renderItemStructure({
- presets,
- textContent: Optional.none(),
- htmlContent: useText ? spec.text.map(function(text2) {
- return replaceText(text2, matchText);
- }) : Optional.none(),
- ariaLabel: spec.text,
- iconContent: spec.icon,
- shortcutContent: Optional.none(),
- checkMark: Optional.none(),
- caret: Optional.none(),
- value: spec.value
- }, sharedBackstage.providers, renderIcons, spec.icon);
- return renderCommonItem({
- data: buildData(spec),
- disabled: spec.disabled,
- getApi: constant$1({}),
- onAction: function(_api) {
- return onItemValueHandler(spec.value, spec.meta);
- },
- onSetup: constant$1(noop),
- triggersSubmenu: false,
- itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
- }, structure, itemResponse, sharedBackstage.providers);
- };
- var render$2 = function(items, extras) {
- return map$2(items, function(item2) {
- switch (item2.type) {
- case "cardcontainer":
- return renderContainer(item2, render$2(item2.items, extras));
- case "cardimage":
- return renderImage(item2.src, item2.classes, item2.alt);
- case "cardtext":
- var shouldHighlight = item2.name.exists(function(name2) {
- return contains$2(extras.cardText.highlightOn, name2);
- });
- var matchText = shouldHighlight ? Optional.from(extras.cardText.matchText).getOr("") : "";
- return renderHtml(replaceText(item2.text, matchText), item2.classes);
- }
- });
- };
- var renderCardMenuItem = function(spec, itemResponse, sharedBackstage, extras) {
- var getApi2 = function(component) {
- return {
- isDisabled: function() {
- return Disabling.isDisabled(component);
- },
- setDisabled: function(state) {
- Disabling.set(component, state);
- each$1(descendants(component.element, "*"), function(elm) {
- component.getSystem().getByDom(elm).each(function(comp) {
- if (comp.hasConfigured(Disabling)) {
- Disabling.set(comp, state);
- }
- });
- });
- }
- };
- };
- var structure = {
- dom: renderItemDomStructure(spec.label),
- optComponents: [Optional.some({
- dom: {
- tag: "div",
- classes: [
- containerClass,
- containerRowClass
- ]
- },
- components: render$2(spec.items, extras)
- })]
- };
- return renderCommonItem({
- data: buildData(__assign({ text: Optional.none() }, spec)),
- disabled: spec.disabled,
- getApi: getApi2,
- onAction: spec.onAction,
- onSetup: spec.onSetup,
- triggersSubmenu: false,
- itemBehaviours: Optional.from(extras.itemBehaviours).getOr([])
- }, structure, itemResponse, sharedBackstage.providers);
- };
- var renderChoiceItem = function(spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons) {
- if (renderIcons === void 0) {
- renderIcons = true;
- }
- var getApi2 = function(component) {
- return {
- setActive: function(state) {
- Toggling.set(component, state);
- },
- isActive: function() {
- return Toggling.isOn(component);
- },
- isDisabled: function() {
- return Disabling.isDisabled(component);
- },
- setDisabled: function(state) {
- return Disabling.set(component, state);
- }
- };
- };
- var structure = renderItemStructure({
- presets,
- textContent: useText ? spec.text : Optional.none(),
- htmlContent: Optional.none(),
- ariaLabel: spec.text,
- iconContent: spec.icon,
- shortcutContent: useText ? spec.shortcut : Optional.none(),
- checkMark: useText ? Optional.some(renderCheckmark(providersBackstage.icons)) : Optional.none(),
- caret: Optional.none(),
- value: spec.value
- }, providersBackstage, renderIcons);
- return deepMerge(renderCommonItem({
- data: buildData(spec),
- disabled: spec.disabled,
- getApi: getApi2,
- onAction: function(_api) {
- return onItemValueHandler(spec.value);
- },
- onSetup: function(api2) {
- api2.setActive(isSelected);
- return noop;
- },
- triggersSubmenu: false,
- itemBehaviours: []
- }, structure, itemResponse, providersBackstage), {
- toggling: {
- toggleClass: tickedClass,
- toggleOnExecute: false,
- selected: spec.active
- }
- });
- };
- var parts$f = generate$3(owner$2(), parts$h());
- var hexColour = function(value2) {
- return { value: value2 };
- };
- var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
- var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
- var isHexString = function(hex) {
- return shorthandRegex.test(hex) || longformRegex.test(hex);
- };
- var normalizeHex = function(hex) {
- return removeLeading(hex, "#").toUpperCase();
- };
- var fromString$1 = function(hex) {
- return isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
- };
- var getLongForm = function(hex) {
- var hexString = hex.value.replace(shorthandRegex, function(m, r2, g, b2) {
- return r2 + r2 + g + g + b2 + b2;
- });
- return { value: hexString };
- };
- var extractValues = function(hex) {
- var longForm = getLongForm(hex);
- var splitForm = longformRegex.exec(longForm.value);
- return splitForm === null ? [
- "FFFFFF",
- "FF",
- "FF",
- "FF"
- ] : splitForm;
- };
- var toHex = function(component) {
- var hex = component.toString(16);
- return (hex.length === 1 ? "0" + hex : hex).toUpperCase();
- };
- var fromRgba = function(rgbaColour2) {
- var value2 = toHex(rgbaColour2.red) + toHex(rgbaColour2.green) + toHex(rgbaColour2.blue);
- return hexColour(value2);
- };
- var min = Math.min;
- var max = Math.max;
- var round$1 = Math.round;
- var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
- var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
- var rgbaColour = function(red2, green, blue, alpha) {
- return {
- red: red2,
- green,
- blue,
- alpha
- };
- };
- var isRgbaComponent = function(value2) {
- var num = parseInt(value2, 10);
- return num.toString() === value2 && num >= 0 && num <= 255;
- };
- var fromHsv = function(hsv) {
- var r2;
- var g;
- var b2;
- var hue = (hsv.hue || 0) % 360;
- var saturation = hsv.saturation / 100;
- var brightness2 = hsv.value / 100;
- saturation = max(0, min(saturation, 1));
- brightness2 = max(0, min(brightness2, 1));
- if (saturation === 0) {
- r2 = g = b2 = round$1(255 * brightness2);
- return rgbaColour(r2, g, b2, 1);
- }
- var side = hue / 60;
- var chroma = brightness2 * saturation;
- var x = chroma * (1 - Math.abs(side % 2 - 1));
- var match = brightness2 - chroma;
- switch (Math.floor(side)) {
- case 0:
- r2 = chroma;
- g = x;
- b2 = 0;
- break;
- case 1:
- r2 = x;
- g = chroma;
- b2 = 0;
- break;
- case 2:
- r2 = 0;
- g = chroma;
- b2 = x;
- break;
- case 3:
- r2 = 0;
- g = x;
- b2 = chroma;
- break;
- case 4:
- r2 = x;
- g = 0;
- b2 = chroma;
- break;
- case 5:
- r2 = chroma;
- g = 0;
- b2 = x;
- break;
- default:
- r2 = g = b2 = 0;
- }
- r2 = round$1(255 * (r2 + match));
- g = round$1(255 * (g + match));
- b2 = round$1(255 * (b2 + match));
- return rgbaColour(r2, g, b2, 1);
- };
- var fromHex = function(hexColour2) {
- var result = extractValues(hexColour2);
- var red2 = parseInt(result[1], 16);
- var green = parseInt(result[2], 16);
- var blue = parseInt(result[3], 16);
- return rgbaColour(red2, green, blue, 1);
- };
- var fromStringValues = function(red2, green, blue, alpha) {
- var r2 = parseInt(red2, 10);
- var g = parseInt(green, 10);
- var b2 = parseInt(blue, 10);
- var a = parseFloat(alpha);
- return rgbaColour(r2, g, b2, a);
- };
- var fromString = function(rgbaString) {
- if (rgbaString === "transparent") {
- return Optional.some(rgbaColour(0, 0, 0, 0));
- }
- var rgbMatch = rgbRegex.exec(rgbaString);
- if (rgbMatch !== null) {
- return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], "1"));
- }
- var rgbaMatch = rgbaRegex.exec(rgbaString);
- if (rgbaMatch !== null) {
- return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
- }
- return Optional.none();
- };
- var toString = function(rgba) {
- return "rgba(" + rgba.red + "," + rgba.green + "," + rgba.blue + "," + rgba.alpha + ")";
- };
- var red = rgbaColour(255, 0, 0, 1);
- var fireSkinLoaded$1 = function(editor) {
- return editor.fire("SkinLoaded");
- };
- var fireSkinLoadError$1 = function(editor, error2) {
- return editor.fire("SkinLoadError", error2);
- };
- var fireResizeEditor = function(editor) {
- return editor.fire("ResizeEditor");
- };
- var fireResizeContent = function(editor, e) {
- return editor.fire("ResizeContent", e);
- };
- var fireScrollContent = function(editor, e) {
- return editor.fire("ScrollContent", e);
- };
- var fireTextColorChange = function(editor, data) {
- return editor.fire("TextColorChange", data);
- };
- var hsvColour = function(hue, saturation, value2) {
- return {
- hue,
- saturation,
- value: value2
- };
- };
- var fromRgb = function(rgbaColour2) {
- var h = 0;
- var s = 0;
- var v = 0;
- var r2 = rgbaColour2.red / 255;
- var g = rgbaColour2.green / 255;
- var b2 = rgbaColour2.blue / 255;
- var minRGB = Math.min(r2, Math.min(g, b2));
- var maxRGB = Math.max(r2, Math.max(g, b2));
- if (minRGB === maxRGB) {
- v = minRGB;
- return hsvColour(0, 0, v * 100);
- }
- var d = r2 === minRGB ? g - b2 : b2 === minRGB ? r2 - g : b2 - r2;
- h = r2 === minRGB ? 3 : b2 === minRGB ? 1 : 5;
- h = 60 * (h - d / (maxRGB - minRGB));
- s = (maxRGB - minRGB) / maxRGB;
- v = maxRGB;
- return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
- };
- var hexToHsv = function(hex) {
- return fromRgb(fromHex(hex));
- };
- var hsvToHex = function(hsv) {
- return fromRgba(fromHsv(hsv));
- };
- var anyToHex = function(color) {
- return fromString$1(color).orThunk(function() {
- return fromString(color).map(fromRgba);
- }).getOrThunk(function() {
- var canvas = document.createElement("canvas");
- canvas.height = 1;
- canvas.width = 1;
- var canvasContext = canvas.getContext("2d");
- canvasContext.clearRect(0, 0, canvas.width, canvas.height);
- canvasContext.fillStyle = "#FFFFFF";
- canvasContext.fillStyle = color;
- canvasContext.fillRect(0, 0, 1, 1);
- var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
- var r2 = rgba[0];
- var g = rgba[1];
- var b2 = rgba[2];
- var a = rgba[3];
- return fromRgba(rgbaColour(r2, g, b2, a));
- });
- };
- var global$8 = tinymce.util.Tools.resolve("tinymce.util.LocalStorage");
- var storageName = "tinymce-custom-colors";
- function ColorCache(max2) {
- if (max2 === void 0) {
- max2 = 10;
- }
- var storageString = global$8.getItem(storageName);
- var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
- var prune = function(list) {
- var diff = max2 - list.length;
- return diff < 0 ? list.slice(0, max2) : list;
- };
- var cache = prune(localstorage);
- var add2 = function(key) {
- indexOf(cache, key).each(remove2);
- cache.unshift(key);
- if (cache.length > max2) {
- cache.pop();
- }
- global$8.setItem(storageName, JSON.stringify(cache));
- };
- var remove2 = function(idx) {
- cache.splice(idx, 1);
- };
- var state = function() {
- return cache.slice(0);
- };
- return {
- add: add2,
- state
- };
- }
- var choiceItem = "choiceitem";
- var defaultColors = [
- {
- type: choiceItem,
- text: "Light Green",
- value: "#BFEDD2"
- },
- {
- type: choiceItem,
- text: "Light Yellow",
- value: "#FBEEB8"
- },
- {
- type: choiceItem,
- text: "Light Red",
- value: "#F8CAC6"
- },
- {
- type: choiceItem,
- text: "Light Purple",
- value: "#ECCAFA"
- },
- {
- type: choiceItem,
- text: "Light Blue",
- value: "#C2E0F4"
- },
- {
- type: choiceItem,
- text: "Green",
- value: "#2DC26B"
- },
- {
- type: choiceItem,
- text: "Yellow",
- value: "#F1C40F"
- },
- {
- type: choiceItem,
- text: "Red",
- value: "#E03E2D"
- },
- {
- type: choiceItem,
- text: "Purple",
- value: "#B96AD9"
- },
- {
- type: choiceItem,
- text: "Blue",
- value: "#3598DB"
- },
- {
- type: choiceItem,
- text: "Dark Turquoise",
- value: "#169179"
- },
- {
- type: choiceItem,
- text: "Orange",
- value: "#E67E23"
- },
- {
- type: choiceItem,
- text: "Dark Red",
- value: "#BA372A"
- },
- {
- type: choiceItem,
- text: "Dark Purple",
- value: "#843FA1"
- },
- {
- type: choiceItem,
- text: "Dark Blue",
- value: "#236FA1"
- },
- {
- type: choiceItem,
- text: "Light Gray",
- value: "#ECF0F1"
- },
- {
- type: choiceItem,
- text: "Medium Gray",
- value: "#CED4D9"
- },
- {
- type: choiceItem,
- text: "Gray",
- value: "#95A5A6"
- },
- {
- type: choiceItem,
- text: "Dark Gray",
- value: "#7E8C8D"
- },
- {
- type: choiceItem,
- text: "Navy Blue",
- value: "#34495E"
- },
- {
- type: choiceItem,
- text: "Black",
- value: "#000000"
- },
- {
- type: choiceItem,
- text: "White",
- value: "#ffffff"
- }
- ];
- var colorCache = ColorCache(10);
- var mapColors = function(colorMap) {
- var colors = [];
- for (var i = 0; i < colorMap.length; i += 2) {
- colors.push({
- text: colorMap[i + 1],
- value: "#" + anyToHex(colorMap[i]).value,
- type: "choiceitem"
- });
- }
- return colors;
- };
- var getColorCols$2 = function(editor, defaultCols) {
- return editor.getParam("color_cols", defaultCols, "number");
- };
- var hasCustomColors$1 = function(editor) {
- return editor.getParam("custom_colors") !== false;
- };
- var getColorMap = function(editor) {
- return editor.getParam("color_map");
- };
- var getColors$2 = function(editor) {
- var unmapped = getColorMap(editor);
- return unmapped !== void 0 ? mapColors(unmapped) : defaultColors;
- };
- var getCurrentColors = function() {
- return map$2(colorCache.state(), function(color) {
- return {
- type: choiceItem,
- text: color,
- value: color
- };
- });
- };
- var addColor = function(color) {
- colorCache.add(color);
- };
- var fallbackColor = "#000000";
- var getCurrentColor = function(editor, format) {
- var color;
- editor.dom.getParents(editor.selection.getStart(), function(elm) {
- var value2;
- if (value2 = elm.style[format === "forecolor" ? "color" : "background-color"]) {
- color = color ? color : value2;
- }
- });
- return Optional.from(color);
- };
- var applyFormat = function(editor, format, value2) {
- editor.undoManager.transact(function() {
- editor.focus();
- editor.formatter.apply(format, { value: value2 });
- editor.nodeChanged();
- });
- };
- var removeFormat = function(editor, format) {
- editor.undoManager.transact(function() {
- editor.focus();
- editor.formatter.remove(format, { value: null }, null, true);
- editor.nodeChanged();
- });
- };
- var registerCommands = function(editor) {
- editor.addCommand("mceApplyTextcolor", function(format, value2) {
- applyFormat(editor, format, value2);
- });
- editor.addCommand("mceRemoveTextcolor", function(format) {
- removeFormat(editor, format);
- });
- };
- var calcCols = function(colors) {
- return Math.max(5, Math.ceil(Math.sqrt(colors)));
- };
- var getColorCols$1 = function(editor) {
- var colors = getColors$2(editor);
- var defaultCols = calcCols(colors.length);
- return getColorCols$2(editor, defaultCols);
- };
- var getAdditionalColors = function(hasCustom) {
- var type2 = "choiceitem";
- var remove2 = {
- type: type2,
- text: "Remove color",
- icon: "color-swatch-remove-color",
- value: "remove"
- };
- var custom2 = {
- type: type2,
- text: "Custom color",
- icon: "color-picker",
- value: "custom"
- };
- return hasCustom ? [
- remove2,
- custom2
- ] : [remove2];
- };
- var applyColor = function(editor, format, value2, onChoice) {
- if (value2 === "custom") {
- var dialog = colorPickerDialog(editor);
- dialog(function(colorOpt) {
- colorOpt.each(function(color) {
- addColor(color);
- editor.execCommand("mceApplyTextcolor", format, color);
- onChoice(color);
- });
- }, fallbackColor);
- } else if (value2 === "remove") {
- onChoice("");
- editor.execCommand("mceRemoveTextcolor", format);
- } else {
- onChoice(value2);
- editor.execCommand("mceApplyTextcolor", format, value2);
- }
- };
- var getColors$1 = function(colors, hasCustom) {
- return colors.concat(getCurrentColors().concat(getAdditionalColors(hasCustom)));
- };
- var getFetch$1 = function(colors, hasCustom) {
- return function(callback) {
- callback(getColors$1(colors, hasCustom));
- };
- };
- var setIconColor = function(splitButtonApi, name2, newColor) {
- var id = name2 === "forecolor" ? "tox-icon-text-color__color" : "tox-icon-highlight-bg-color__color";
- splitButtonApi.setIconFill(id, newColor);
- };
- var registerTextColorButton = function(editor, name2, format, tooltip, lastColor) {
- editor.ui.registry.addSplitButton(name2, {
- tooltip,
- presets: "color",
- icon: name2 === "forecolor" ? "text-color" : "highlight-bg-color",
- select: function(value2) {
- var optCurrentRgb = getCurrentColor(editor, format);
- return optCurrentRgb.bind(function(currentRgb) {
- return fromString(currentRgb).map(function(rgba) {
- var currentHex = fromRgba(rgba).value;
- return contains$1(value2.toLowerCase(), currentHex);
- });
- }).getOr(false);
- },
- columns: getColorCols$1(editor),
- fetch: getFetch$1(getColors$2(editor), hasCustomColors$1(editor)),
- onAction: function(_splitButtonApi) {
- applyColor(editor, format, lastColor.get(), noop);
- },
- onItemAction: function(_splitButtonApi, value2) {
- applyColor(editor, format, value2, function(newColor) {
- lastColor.set(newColor);
- fireTextColorChange(editor, {
- name: name2,
- color: newColor
- });
- });
- },
- onSetup: function(splitButtonApi) {
- setIconColor(splitButtonApi, name2, lastColor.get());
- var handler = function(e) {
- if (e.name === name2) {
- setIconColor(splitButtonApi, e.name, e.color);
- }
- };
- editor.on("TextColorChange", handler);
- return function() {
- editor.off("TextColorChange", handler);
- };
- }
- });
- };
- var registerTextColorMenuItem = function(editor, name2, format, text2) {
- editor.ui.registry.addNestedMenuItem(name2, {
- text: text2,
- icon: name2 === "forecolor" ? "text-color" : "highlight-bg-color",
- getSubmenuItems: function() {
- return [{
- type: "fancymenuitem",
- fancytype: "colorswatch",
- onAction: function(data) {
- applyColor(editor, format, data.value, noop);
- }
- }];
- }
- });
- };
- var colorPickerDialog = function(editor) {
- return function(callback, value2) {
- var isValid = false;
- var onSubmit = function(api2) {
- var data = api2.getData();
- var hex = data.colorpicker;
- if (isValid) {
- callback(Optional.from(hex));
- api2.close();
- } else {
- editor.windowManager.alert(editor.translate([
- "Invalid hex color code: {0}",
- hex
- ]));
- }
- };
- var onAction = function(_api, details) {
- if (details.name === "hex-valid") {
- isValid = details.value;
- }
- };
- var initialData = { colorpicker: value2 };
- editor.windowManager.open({
- title: "Color Picker",
- size: "normal",
- body: {
- type: "panel",
- items: [{
- type: "colorpicker",
- name: "colorpicker",
- label: "Color"
- }]
- },
- buttons: [
- {
- type: "cancel",
- name: "cancel",
- text: "Cancel"
- },
- {
- type: "submit",
- name: "save",
- text: "Save",
- primary: true
- }
- ],
- initialData,
- onAction,
- onSubmit,
- onClose: noop,
- onCancel: function() {
- callback(Optional.none());
- }
- });
- };
- };
- var register$a = function(editor) {
- registerCommands(editor);
- var lastForeColor = Cell(fallbackColor);
- var lastBackColor = Cell(fallbackColor);
- registerTextColorButton(editor, "forecolor", "forecolor", "Text color", lastForeColor);
- registerTextColorButton(editor, "backcolor", "hilitecolor", "Background color", lastBackColor);
- registerTextColorMenuItem(editor, "forecolor", "forecolor", "Text color");
- registerTextColorMenuItem(editor, "backcolor", "hilitecolor", "Background color");
- };
- var createPartialChoiceMenu = function(value2, items, onItemValueHandler, columns, presets, itemResponse, select2, providersBackstage) {
- var hasIcons = menuHasIcons(items);
- var presetItemTypes = presets !== "color" ? "normal" : "color";
- var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select2, providersBackstage);
- return createPartialMenuWithAlloyItems(value2, hasIcons, alloyItems, columns, presets);
- };
- var createChoiceItems = function(items, onItemValueHandler, columns, itemPresets, itemResponse, select2, providersBackstage) {
- return cat(map$2(items, function(item2) {
- if (item2.type === "choiceitem") {
- return createChoiceMenuItem(item2).fold(handleError, function(d) {
- return Optional.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select2(item2.value), itemResponse, providersBackstage, menuHasIcons(items)));
- });
- } else {
- return Optional.none();
- }
- }));
- };
- var deriveMenuMovement = function(columns, presets) {
- var menuMarkers = markers(presets);
- if (columns === 1) {
- return {
- mode: "menu",
- moveOnTab: true
- };
- } else if (columns === "auto") {
- return {
- mode: "grid",
- selector: "." + menuMarkers.item,
- initSize: {
- numColumns: 1,
- numRows: 1
- }
- };
- } else {
- var rowClass = presets === "color" ? "tox-swatches__row" : "tox-collection__group";
- return {
- mode: "matrix",
- rowSelector: "." + rowClass
- };
- }
- };
- var deriveCollectionMovement = function(columns, presets) {
- if (columns === 1) {
- return {
- mode: "menu",
- moveOnTab: false,
- selector: ".tox-collection__item"
- };
- } else if (columns === "auto") {
- return {
- mode: "flatgrid",
- selector: ".tox-collection__item",
- initSize: {
- numColumns: 1,
- numRows: 1
- }
- };
- } else {
- return {
- mode: "matrix",
- selectors: {
- row: presets === "color" ? ".tox-swatches__row" : ".tox-collection__group",
- cell: presets === "color" ? "." + colorClass : "." + selectableClass
- }
- };
- }
- };
- var renderColorSwatchItem = function(spec, backstage) {
- var items = getColorItems(spec, backstage);
- var columns = backstage.colorinput.getColorCols();
- var presets = "color";
- var menuSpec = createPartialChoiceMenu(generate$6("menu-value"), items, function(value2) {
- spec.onAction({ value: value2 });
- }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, backstage.shared.providers);
- var widgetSpec = __assign(__assign({}, menuSpec), {
- markers: markers(presets),
- movement: deriveMenuMovement(columns, presets)
- });
- return {
- type: "widget",
- data: { value: generate$6("widget-id") },
- dom: {
- tag: "div",
- classes: ["tox-fancymenuitem"]
- },
- autofocus: true,
- components: [parts$f.widget(Menu.sketch(widgetSpec))]
- };
- };
- var getColorItems = function(spec, backstage) {
- var useCustomColors = spec.initData.allowCustomColors && backstage.colorinput.hasCustomColors();
- return spec.initData.colors.fold(function() {
- return getColors$1(backstage.colorinput.getColors(), useCustomColors);
- }, function(colors) {
- return colors.concat(getAdditionalColors(useCustomColors));
- });
- };
- var cellOverEvent = generate$6("cell-over");
- var cellExecuteEvent = generate$6("cell-execute");
- var makeCell = function(row, col, labelId) {
- var _a2;
- var emitCellOver = function(c) {
- return emitWith(c, cellOverEvent, {
- row,
- col
- });
- };
- var emitExecute2 = function(c) {
- return emitWith(c, cellExecuteEvent, {
- row,
- col
- });
- };
- var onClick = function(c, se) {
- se.stop();
- emitExecute2(c);
- };
- return build$1({
- dom: {
- tag: "div",
- attributes: (_a2 = { role: "button" }, _a2["aria-labelledby"] = labelId, _a2)
- },
- behaviours: derive$1([
- config("insert-table-picker-cell", [
- run$1(mouseover(), Focusing.focus),
- run$1(execute$5(), emitExecute2),
- run$1(click(), onClick),
- run$1(tap(), onClick)
- ]),
- Toggling.config({
- toggleClass: "tox-insert-table-picker__selected",
- toggleOnExecute: false
- }),
- Focusing.config({ onFocus: emitCellOver })
- ])
- });
- };
- var makeCells = function(labelId, numRows, numCols) {
- var cells = [];
- for (var i = 0; i < numRows; i++) {
- var row = [];
- for (var j = 0; j < numCols; j++) {
- row.push(makeCell(i, j, labelId));
- }
- cells.push(row);
- }
- return cells;
- };
- var selectCells = function(cells, selectedRow, selectedColumn, numRows, numColumns) {
- for (var i = 0; i < numRows; i++) {
- for (var j = 0; j < numColumns; j++) {
- Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
- }
- }
- };
- var makeComponents = function(cells) {
- return bind$3(cells, function(cellRow) {
- return map$2(cellRow, premade);
- });
- };
- var makeLabelText = function(row, col) {
- return text$1(col + "x" + row);
- };
- var renderInsertTableMenuItem = function(spec) {
- var numRows = 10;
- var numColumns = 10;
- var sizeLabelId = generate$6("size-label");
- var cells = makeCells(sizeLabelId, numRows, numColumns);
- var emptyLabelText = makeLabelText(0, 0);
- var memLabel = record({
- dom: {
- tag: "span",
- classes: ["tox-insert-table-picker__label"],
- attributes: { id: sizeLabelId }
- },
- components: [emptyLabelText],
- behaviours: derive$1([Replacing.config({})])
- });
- return {
- type: "widget",
- data: { value: generate$6("widget-id") },
- dom: {
- tag: "div",
- classes: ["tox-fancymenuitem"]
- },
- autofocus: true,
- components: [parts$f.widget({
- dom: {
- tag: "div",
- classes: ["tox-insert-table-picker"]
- },
- components: makeComponents(cells).concat(memLabel.asSpec()),
- behaviours: derive$1([
- config("insert-table-picker", [
- runOnAttached(function(c) {
- Replacing.set(memLabel.get(c), [emptyLabelText]);
- }),
- runWithTarget(cellOverEvent, function(c, t2, e) {
- var _a2 = e.event, row = _a2.row, col = _a2.col;
- selectCells(cells, row, col, numRows, numColumns);
- Replacing.set(memLabel.get(c), [makeLabelText(row + 1, col + 1)]);
- }),
- runWithTarget(cellExecuteEvent, function(c, _, e) {
- var _a2 = e.event, row = _a2.row, col = _a2.col;
- spec.onAction({
- numRows: row + 1,
- numColumns: col + 1
- });
- emit(c, sandboxClose());
- })
- ]),
- Keying.config({
- initSize: {
- numRows,
- numColumns
- },
- mode: "flatgrid",
- selector: '[role="button"]'
- })
- ])
- })]
- };
- };
- var fancyMenuItems = {
- inserttable: renderInsertTableMenuItem,
- colorswatch: renderColorSwatchItem
- };
- var renderFancyMenuItem = function(spec, backstage) {
- return get$e(fancyMenuItems, spec.fancytype).map(function(render2) {
- return render2(spec, backstage);
- });
- };
- var renderNestedItem = function(spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
- if (renderIcons === void 0) {
- renderIcons = true;
- }
- if (downwardsCaret === void 0) {
- downwardsCaret = false;
- }
- var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
- var getApi2 = function(component) {
- return {
- isDisabled: function() {
- return Disabling.isDisabled(component);
- },
- setDisabled: function(state) {
- return Disabling.set(component, state);
- }
- };
- };
- var structure = renderItemStructure({
- presets: "normal",
- iconContent: spec.icon,
- textContent: spec.text,
- htmlContent: Optional.none(),
- ariaLabel: spec.text,
- caret: Optional.some(caret),
- checkMark: Optional.none(),
- shortcutContent: spec.shortcut
- }, providersBackstage, renderIcons);
- return renderCommonItem({
- data: buildData(spec),
- getApi: getApi2,
- disabled: spec.disabled,
- onAction: noop,
- onSetup: spec.onSetup,
- triggersSubmenu: true,
- itemBehaviours: []
- }, structure, itemResponse, providersBackstage);
- };
- var renderNormalItem = function(spec, itemResponse, providersBackstage, renderIcons) {
- if (renderIcons === void 0) {
- renderIcons = true;
- }
- var getApi2 = function(component) {
- return {
- isDisabled: function() {
- return Disabling.isDisabled(component);
- },
- setDisabled: function(state) {
- return Disabling.set(component, state);
- }
- };
- };
- var structure = renderItemStructure({
- presets: "normal",
- iconContent: spec.icon,
- textContent: spec.text,
- htmlContent: Optional.none(),
- ariaLabel: spec.text,
- caret: Optional.none(),
- checkMark: Optional.none(),
- shortcutContent: spec.shortcut
- }, providersBackstage, renderIcons);
- return renderCommonItem({
- data: buildData(spec),
- getApi: getApi2,
- disabled: spec.disabled,
- onAction: spec.onAction,
- onSetup: spec.onSetup,
- triggersSubmenu: false,
- itemBehaviours: []
- }, structure, itemResponse, providersBackstage);
- };
- var renderSeparatorItem = function(spec) {
- var innerHtml = spec.text.fold(function() {
- return {};
- }, function(text2) {
- return { innerHtml: text2 };
- });
- return {
- type: "separator",
- dom: __assign({
- tag: "div",
- classes: [
- selectableClass,
- groupHeadingClass
- ]
- }, innerHtml),
- components: []
- };
- };
- var renderToggleMenuItem = function(spec, itemResponse, providersBackstage, renderIcons) {
- if (renderIcons === void 0) {
- renderIcons = true;
- }
- var getApi2 = function(component) {
- return {
- setActive: function(state) {
- Toggling.set(component, state);
- },
- isActive: function() {
- return Toggling.isOn(component);
- },
- isDisabled: function() {
- return Disabling.isDisabled(component);
- },
- setDisabled: function(state) {
- return Disabling.set(component, state);
- }
- };
- };
- var structure = renderItemStructure({
- iconContent: spec.icon,
- textContent: spec.text,
- htmlContent: Optional.none(),
- ariaLabel: spec.text,
- checkMark: Optional.some(renderCheckmark(providersBackstage.icons)),
- caret: Optional.none(),
- shortcutContent: spec.shortcut,
- presets: "normal",
- meta: spec.meta
- }, providersBackstage, renderIcons);
- return deepMerge(renderCommonItem({
- data: buildData(spec),
- disabled: spec.disabled,
- getApi: getApi2,
- onAction: spec.onAction,
- onSetup: spec.onSetup,
- triggersSubmenu: false,
- itemBehaviours: []
- }, structure, itemResponse, providersBackstage), {
- toggling: {
- toggleClass: tickedClass,
- toggleOnExecute: false,
- selected: spec.active
- }
- });
- };
- var autocomplete = renderAutocompleteItem;
- var separator$3 = renderSeparatorItem;
- var normal = renderNormalItem;
- var nested = renderNestedItem;
- var toggle$1 = renderToggleMenuItem;
- var fancy = renderFancyMenuItem;
- var card = renderCardMenuItem;
- var FocusMode;
- (function(FocusMode2) {
- FocusMode2[FocusMode2["ContentFocus"] = 0] = "ContentFocus";
- FocusMode2[FocusMode2["UiFocus"] = 1] = "UiFocus";
- })(FocusMode || (FocusMode = {}));
- var createMenuItemFromBridge = function(item2, itemResponse, backstage, menuHasIcons2, isHorizontalMenu) {
- var providersBackstage = backstage.shared.providers;
- var parseForHorizontalMenu = function(menuitem) {
- return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
- shortcut: Optional.none(),
- icon: menuitem.text.isSome() ? Optional.none() : menuitem.icon
- });
- };
- switch (item2.type) {
- case "menuitem":
- return createMenuItem(item2).fold(handleError, function(d) {
- return Optional.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons2));
- });
- case "nestedmenuitem":
- return createNestedMenuItem(item2).fold(handleError, function(d) {
- return Optional.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons2, isHorizontalMenu));
- });
- case "togglemenuitem":
- return createToggleMenuItem(item2).fold(handleError, function(d) {
- return Optional.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons2));
- });
- case "separator":
- return createSeparatorMenuItem(item2).fold(handleError, function(d) {
- return Optional.some(separator$3(d));
- });
- case "fancymenuitem":
- return createFancyMenuItem(item2).fold(handleError, function(d) {
- return fancy(parseForHorizontalMenu(d), backstage);
- });
- default: {
- console.error("Unknown item in general menu", item2);
- return Optional.none();
- }
- }
- };
- var createAutocompleteItems = function(items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage, highlightOn) {
- var renderText2 = columns === 1;
- var renderIcons = !renderText2 || menuHasIcons(items);
- return cat(map$2(items, function(item2) {
- switch (item2.type) {
- case "separator":
- return createSeparatorItem(item2).fold(handleError, function(d) {
- return Optional.some(separator$3(d));
- });
- case "cardmenuitem":
- return createCardMenuItem(item2).fold(handleError, function(d) {
- return Optional.some(card(__assign(__assign({}, d), {
- onAction: function(api2) {
- d.onAction(api2);
- onItemValueHandler(d.value, d.meta);
- }
- }), itemResponse, sharedBackstage, {
- itemBehaviours: tooltipBehaviour(d.meta, sharedBackstage),
- cardText: {
- matchText,
- highlightOn
- }
- }));
- });
- case "autocompleteitem":
- default:
- return createAutocompleterItem(item2).fold(handleError, function(d) {
- return Optional.some(autocomplete(d, matchText, renderText2, "normal", onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
- });
- }
- }));
- };
- var createPartialMenu = function(value2, items, itemResponse, backstage, isHorizontalMenu) {
- var hasIcons = menuHasIcons(items);
- var alloyItems = cat(map$2(items, function(item2) {
- var itemHasIcon = function(i) {
- return isHorizontalMenu ? !has$2(i, "text") : hasIcons;
- };
- var createItem = function(i) {
- return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
- };
- if (item2.type === "nestedmenuitem" && item2.getSubmenuItems().length <= 0) {
- return createItem(__assign(__assign({}, item2), { disabled: true }));
- } else {
- return createItem(item2);
- }
- }));
- var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
- return createPartial(value2, hasIcons, alloyItems, 1, "normal");
- };
- var createTieredDataFrom = function(partialMenu) {
- return tieredMenu.singleData(partialMenu.value, partialMenu);
- };
- var createMenuFrom = function(partialMenu, columns, focusMode, presets) {
- var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom$2();
- var movement = deriveMenuMovement(columns, presets);
- var menuMarkers = markers(presets);
- return {
- dom: partialMenu.dom,
- components: partialMenu.components,
- items: partialMenu.items,
- value: partialMenu.value,
- markers: {
- selectedItem: menuMarkers.selectedItem,
- item: menuMarkers.item
- },
- movement,
- fakeFocus: focusMode === FocusMode.ContentFocus,
- focusManager,
- menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== "auto" ? [] : [runOnAttached(function(comp, _se) {
- detectSize(comp, 4, menuMarkers.item).each(function(_a2) {
- var numColumns = _a2.numColumns, numRows = _a2.numRows;
- Keying.setGridSize(comp, numRows, numColumns);
- });
- })])
- };
- };
- var register$9 = function(editor, sharedBackstage) {
- var activeAutocompleter = value$1();
- var processingAction = Cell(false);
- var autocompleter = build$1(InlineView.sketch({
- dom: {
- tag: "div",
- classes: ["tox-autocompleter"]
- },
- components: [],
- fireDismissalEventInstead: {},
- inlineBehaviours: derive$1([config("dismissAutocompleter", [run$1(dismissRequested(), function() {
- return cancelIfNecessary();
- })])]),
- lazySink: sharedBackstage.getSink
- }));
- var isMenuOpen = function() {
- return InlineView.isOpen(autocompleter);
- };
- var isActive = function() {
- return activeAutocompleter.get().isSome();
- };
- var hideIfNecessary = function() {
- if (isActive()) {
- InlineView.hide(autocompleter);
- }
- };
- var cancelIfNecessary = function() {
- if (isActive()) {
- var lastElement = activeAutocompleter.get().map(function(ac) {
- return ac.element;
- });
- detect(lastElement.getOr(SugarElement.fromDom(editor.selection.getNode()))).each(unwrap);
- hideIfNecessary();
- activeAutocompleter.clear();
- processingAction.set(false);
- }
- };
- var getAutocompleters = cached(function() {
- return register$b(editor);
- });
- var getCombinedItems = function(triggerChar, matches) {
- var columns = findMap(matches, function(m) {
- return Optional.from(m.columns);
- }).getOr(1);
- return bind$3(matches, function(match) {
- var choices = match.items;
- return createAutocompleteItems(choices, match.matchText, function(itemValue, itemMeta) {
- var nr = editor.selection.getRng();
- getContext(editor.dom, nr, triggerChar).fold(function() {
- return console.error("Lost context. Cursor probably moved");
- }, function(_a2) {
- var range2 = _a2.range;
- var autocompleterApi = {
- hide: function() {
- cancelIfNecessary();
- },
- reload: function(fetchOptions) {
- hideIfNecessary();
- load(fetchOptions);
- }
- };
- processingAction.set(true);
- match.onAction(autocompleterApi, range2, itemValue, itemMeta);
- processingAction.set(false);
- });
- }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage, match.highlightOn);
- });
- };
- var commenceIfNecessary = function(context) {
- if (!isActive()) {
- var wrapper = create$5(editor, context.range);
- activeAutocompleter.set({
- triggerChar: context.triggerChar,
- element: wrapper,
- matchLength: context.text.length
- });
- processingAction.set(false);
- }
- };
- var display = function(ac, context, lookupData, items) {
- ac.matchLength = context.text.length;
- var columns = findMap(lookupData, function(ld) {
- return Optional.from(ld.columns);
- }).getOr(1);
- InlineView.showAt(autocompleter, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems("autocompleter-value", true, items, columns, "normal"), columns, FocusMode.ContentFocus, "normal")), {
- anchor: {
- type: "node",
- root: SugarElement.fromDom(editor.getBody()),
- node: Optional.from(ac.element)
- }
- });
- InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
- };
- var doLookup = function(fetchOptions) {
- return activeAutocompleter.get().map(function(ac) {
- return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function(newContext) {
- return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
- });
- }).getOrThunk(function() {
- return lookup$2(editor, getAutocompleters);
- });
- };
- var load = function(fetchOptions) {
- doLookup(fetchOptions).fold(cancelIfNecessary, function(lookupInfo) {
- commenceIfNecessary(lookupInfo.context);
- lookupInfo.lookupData.then(function(lookupData) {
- activeAutocompleter.get().map(function(ac) {
- var context = lookupInfo.context;
- if (ac.triggerChar === context.triggerChar) {
- var combinedItems = getCombinedItems(context.triggerChar, lookupData);
- if (combinedItems.length > 0) {
- display(ac, context, lookupData, combinedItems);
- } else if (context.text.length - ac.matchLength >= 10) {
- cancelIfNecessary();
- } else {
- hideIfNecessary();
- }
- }
- });
- });
- });
- };
- var onKeypress = last(function(e) {
- if (e.which === 27) {
- return;
- }
- load();
- }, 50);
- var autocompleterUiApi = {
- onKeypress,
- cancelIfNecessary,
- isMenuOpen,
- isActive,
- isProcessingAction: processingAction.get,
- getView: function() {
- return InlineView.getContent(autocompleter);
- }
- };
- if (editor.hasPlugin("rtc") === false) {
- AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
- }
- };
- var Autocompleter = { register: register$9 };
- var closest = function(scope, selector, isRoot) {
- return closest$1(scope, selector, isRoot).isSome();
- };
- var DelayedFunction = function(fun, delay) {
- var ref = null;
- var schedule = function() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- ref = setTimeout(function() {
- fun.apply(null, args);
- ref = null;
- }, delay);
- };
- var cancel = function() {
- if (ref !== null) {
- clearTimeout(ref);
- ref = null;
- }
- };
- return {
- cancel,
- schedule
- };
- };
- var SIGNIFICANT_MOVE = 5;
- var LONGPRESS_DELAY = 400;
- var getTouch = function(event) {
- var raw = event.raw;
- if (raw.touches === void 0 || raw.touches.length !== 1) {
- return Optional.none();
- }
- return Optional.some(raw.touches[0]);
- };
- var isFarEnough = function(touch2, data) {
- var distX = Math.abs(touch2.clientX - data.x);
- var distY = Math.abs(touch2.clientY - data.y);
- return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
- };
- var monitor = function(settings) {
- var startData = value$1();
- var longpressFired = Cell(false);
- var longpress$1 = DelayedFunction(function(event) {
- settings.triggerEvent(longpress(), event);
- longpressFired.set(true);
- }, LONGPRESS_DELAY);
- var handleTouchstart = function(event) {
- getTouch(event).each(function(touch2) {
- longpress$1.cancel();
- var data = {
- x: touch2.clientX,
- y: touch2.clientY,
- target: event.target
- };
- longpress$1.schedule(event);
- longpressFired.set(false);
- startData.set(data);
- });
- return Optional.none();
- };
- var handleTouchmove = function(event) {
- longpress$1.cancel();
- getTouch(event).each(function(touch2) {
- startData.on(function(data) {
- if (isFarEnough(touch2, data)) {
- startData.clear();
- }
- });
- });
- return Optional.none();
- };
- var handleTouchend = function(event) {
- longpress$1.cancel();
- var isSame = function(data) {
- return eq(data.target, event.target);
- };
- return startData.get().filter(isSame).map(function(_data) {
- if (longpressFired.get()) {
- event.prevent();
- return false;
- } else {
- return settings.triggerEvent(tap(), event);
- }
- });
- };
- var handlers2 = wrapAll([
- {
- key: touchstart(),
- value: handleTouchstart
- },
- {
- key: touchmove(),
- value: handleTouchmove
- },
- {
- key: touchend(),
- value: handleTouchend
- }
- ]);
- var fireIfReady = function(event, type2) {
- return get$e(handlers2, type2).bind(function(handler) {
- return handler(event);
- });
- };
- return { fireIfReady };
- };
- var isDangerous = function(event) {
- var keyEv = event.raw;
- return keyEv.which === BACKSPACE[0] && !contains$2([
- "input",
- "textarea"
- ], name$2(event.target)) && !closest(event.target, '[contenteditable="true"]');
- };
- var isFirefox = function() {
- return detect$1().browser.isFirefox();
- };
- var bindFocus = function(container, handler) {
- if (isFirefox()) {
- return capture(container, "focus", handler);
- } else {
- return bind(container, "focusin", handler);
- }
- };
- var bindBlur = function(container, handler) {
- if (isFirefox()) {
- return capture(container, "blur", handler);
- } else {
- return bind(container, "focusout", handler);
- }
- };
- var setup$d = function(container, rawSettings) {
- var settings = __assign({ stopBackspace: true }, rawSettings);
- var pointerEvents2 = [
- "touchstart",
- "touchmove",
- "touchend",
- "touchcancel",
- "gesturestart",
- "mousedown",
- "mouseup",
- "mouseover",
- "mousemove",
- "mouseout",
- "click"
- ];
- var tapEvent = monitor(settings);
- var simpleEvents = map$2(pointerEvents2.concat([
- "selectstart",
- "input",
- "contextmenu",
- "change",
- "transitionend",
- "transitioncancel",
- "drag",
- "dragstart",
- "dragend",
- "dragenter",
- "dragleave",
- "dragover",
- "drop",
- "keyup"
- ]), function(type2) {
- return bind(container, type2, function(event) {
- tapEvent.fireIfReady(event, type2).each(function(tapStopped) {
- if (tapStopped) {
- event.kill();
- }
- });
- var stopped = settings.triggerEvent(type2, event);
- if (stopped) {
- event.kill();
- }
- });
- });
- var pasteTimeout = value$1();
- var onPaste = bind(container, "paste", function(event) {
- tapEvent.fireIfReady(event, "paste").each(function(tapStopped) {
- if (tapStopped) {
- event.kill();
- }
- });
- var stopped = settings.triggerEvent("paste", event);
- if (stopped) {
- event.kill();
- }
- pasteTimeout.set(setTimeout(function() {
- settings.triggerEvent(postPaste(), event);
- }, 0));
- });
- var onKeydown = bind(container, "keydown", function(event) {
- var stopped = settings.triggerEvent("keydown", event);
- if (stopped) {
- event.kill();
- } else if (settings.stopBackspace && isDangerous(event)) {
- event.prevent();
- }
- });
- var onFocusIn = bindFocus(container, function(event) {
- var stopped = settings.triggerEvent("focusin", event);
- if (stopped) {
- event.kill();
- }
- });
- var focusoutTimeout = value$1();
- var onFocusOut = bindBlur(container, function(event) {
- var stopped = settings.triggerEvent("focusout", event);
- if (stopped) {
- event.kill();
- }
- focusoutTimeout.set(setTimeout(function() {
- settings.triggerEvent(postBlur(), event);
- }, 0));
- });
- var unbind2 = function() {
- each$1(simpleEvents, function(e) {
- e.unbind();
- });
- onKeydown.unbind();
- onFocusIn.unbind();
- onFocusOut.unbind();
- onPaste.unbind();
- pasteTimeout.on(clearTimeout);
- focusoutTimeout.on(clearTimeout);
- };
- return { unbind: unbind2 };
- };
- var derive = function(rawEvent, rawTarget) {
- var source = get$e(rawEvent, "target").getOr(rawTarget);
- return Cell(source);
- };
- var fromSource = function(event, source) {
- var stopper2 = Cell(false);
- var cutter2 = Cell(false);
- var stop2 = function() {
- stopper2.set(true);
- };
- var cut = function() {
- cutter2.set(true);
- };
- return {
- stop: stop2,
- cut,
- isStopped: stopper2.get,
- isCut: cutter2.get,
- event,
- setSource: source.set,
- getSource: source.get
- };
- };
- var fromExternal = function(event) {
- var stopper2 = Cell(false);
- var stop2 = function() {
- stopper2.set(true);
- };
- return {
- stop: stop2,
- cut: noop,
- isStopped: stopper2.get,
- isCut: never,
- event,
- setSource: die("Cannot set source of a broadcasted event"),
- getSource: die("Cannot get source of a broadcasted event")
- };
- };
- var adt$1 = Adt.generate([
- { stopped: [] },
- { resume: ["element"] },
- { complete: [] }
- ]);
- var doTriggerHandler = function(lookup2, eventType, rawEvent, target, source, logger) {
- var handler = lookup2(eventType, target);
- var simulatedEvent = fromSource(rawEvent, source);
- return handler.fold(function() {
- logger.logEventNoHandlers(eventType, target);
- return adt$1.complete();
- }, function(handlerInfo) {
- var descHandler = handlerInfo.descHandler;
- var eventHandler2 = getCurried(descHandler);
- eventHandler2(simulatedEvent);
- if (simulatedEvent.isStopped()) {
- logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
- return adt$1.stopped();
- } else if (simulatedEvent.isCut()) {
- logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
- return adt$1.complete();
- } else {
- return parent(handlerInfo.element).fold(function() {
- logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
- return adt$1.complete();
- }, function(parent2) {
- logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
- return adt$1.resume(parent2);
- });
- }
- });
- };
- var doTriggerOnUntilStopped = function(lookup2, eventType, rawEvent, rawTarget, source, logger) {
- return doTriggerHandler(lookup2, eventType, rawEvent, rawTarget, source, logger).fold(always, function(parent2) {
- return doTriggerOnUntilStopped(lookup2, eventType, rawEvent, parent2, source, logger);
- }, never);
- };
- var triggerHandler = function(lookup2, eventType, rawEvent, target, logger) {
- var source = derive(rawEvent, target);
- return doTriggerHandler(lookup2, eventType, rawEvent, target, source, logger);
- };
- var broadcast = function(listeners, rawEvent, _logger) {
- var simulatedEvent = fromExternal(rawEvent);
- each$1(listeners, function(listener) {
- var descHandler = listener.descHandler;
- var handler = getCurried(descHandler);
- handler(simulatedEvent);
- });
- return simulatedEvent.isStopped();
- };
- var triggerUntilStopped = function(lookup2, eventType, rawEvent, logger) {
- return triggerOnUntilStopped(lookup2, eventType, rawEvent, rawEvent.target, logger);
- };
- var triggerOnUntilStopped = function(lookup2, eventType, rawEvent, rawTarget, logger) {
- var source = derive(rawEvent, rawTarget);
- return doTriggerOnUntilStopped(lookup2, eventType, rawEvent, rawTarget, source, logger);
- };
- var eventHandler = function(element2, descHandler) {
- return {
- element: element2,
- descHandler
- };
- };
- var broadcastHandler = function(id, handler) {
- return {
- id,
- descHandler: handler
- };
- };
- var EventRegistry = function() {
- var registry = {};
- var registerId = function(extraArgs, id, events2) {
- each(events2, function(v, k) {
- var handlers2 = registry[k] !== void 0 ? registry[k] : {};
- handlers2[id] = curryArgs(v, extraArgs);
- registry[k] = handlers2;
- });
- };
- var findHandler = function(handlers2, elem) {
- return read$1(elem).bind(function(id) {
- return get$e(handlers2, id);
- }).map(function(descHandler) {
- return eventHandler(elem, descHandler);
- });
- };
- var filterByType = function(type2) {
- return get$e(registry, type2).map(function(handlers2) {
- return mapToArray(handlers2, function(f, id) {
- return broadcastHandler(id, f);
- });
- }).getOr([]);
- };
- var find2 = function(isAboveRoot, type2, target) {
- return get$e(registry, type2).bind(function(handlers2) {
- return closest$4(target, function(elem) {
- return findHandler(handlers2, elem);
- }, isAboveRoot);
- });
- };
- var unregisterId = function(id) {
- each(registry, function(handlersById, _eventName) {
- if (has$2(handlersById, id)) {
- delete handlersById[id];
- }
- });
- };
- return {
- registerId,
- unregisterId,
- filterByType,
- find: find2
- };
- };
- var Registry = function() {
- var events2 = EventRegistry();
- var components2 = {};
- var readOrTag = function(component) {
- var elem = component.element;
- return read$1(elem).getOrThunk(function() {
- return write("uid-", component.element);
- });
- };
- var failOnDuplicate = function(component, tagId) {
- var conflict = components2[tagId];
- if (conflict === component) {
- unregister(component);
- } else {
- throw new Error('The tagId "' + tagId + '" is already used by: ' + element(conflict.element) + "\nCannot use it for: " + element(component.element) + "\nThe conflicting element is" + (inBody(conflict.element) ? " " : " not ") + "already in the DOM");
- }
- };
- var register2 = function(component) {
- var tagId = readOrTag(component);
- if (hasNonNullableKey(components2, tagId)) {
- failOnDuplicate(component, tagId);
- }
- var extraArgs = [component];
- events2.registerId(extraArgs, tagId, component.events);
- components2[tagId] = component;
- };
- var unregister = function(component) {
- read$1(component.element).each(function(tagId) {
- delete components2[tagId];
- events2.unregisterId(tagId);
- });
- };
- var filter2 = function(type2) {
- return events2.filterByType(type2);
- };
- var find2 = function(isAboveRoot, type2, target) {
- return events2.find(isAboveRoot, type2, target);
- };
- var getById = function(id) {
- return get$e(components2, id);
- };
- return {
- find: find2,
- filter: filter2,
- register: register2,
- unregister,
- getById
- };
- };
- var factory$j = function(detail) {
- var _a2 = detail.dom, attributes = _a2.attributes, domWithoutAttributes = __rest(_a2, ["attributes"]);
- return {
- uid: detail.uid,
- dom: __assign({
- tag: "div",
- attributes: __assign({ role: "presentation" }, attributes)
- }, domWithoutAttributes),
- components: detail.components,
- behaviours: get$2(detail.containerBehaviours),
- events: detail.events,
- domModification: detail.domModification,
- eventOrder: detail.eventOrder
- };
- };
- var Container = single({
- name: "Container",
- factory: factory$j,
- configFields: [
- defaulted("components", []),
- field("containerBehaviours", []),
- defaulted("events", {}),
- defaulted("domModification", {}),
- defaulted("eventOrder", {})
- ]
- });
- var takeover = function(root) {
- var isAboveRoot = function(el) {
- return parent(root.element).fold(always, function(parent2) {
- return eq(el, parent2);
- });
- };
- var registry = Registry();
- var lookup2 = function(eventName, target) {
- return registry.find(isAboveRoot, eventName, target);
- };
- var domEvents = setup$d(root.element, {
- triggerEvent: function(eventName, event) {
- return monitorEvent(eventName, event.target, function(logger) {
- return triggerUntilStopped(lookup2, eventName, event, logger);
- });
- }
- });
- var systemApi = {
- debugInfo: constant$1("real"),
- triggerEvent: function(eventName, target, data) {
- monitorEvent(eventName, target, function(logger) {
- return triggerOnUntilStopped(lookup2, eventName, data, target, logger);
- });
- },
- triggerFocus: function(target, originator) {
- read$1(target).fold(function() {
- focus$3(target);
- }, function(_alloyId) {
- monitorEvent(focus$4(), target, function(logger) {
- triggerHandler(lookup2, focus$4(), {
- originator,
- kill: noop,
- prevent: noop,
- target
- }, target, logger);
- return false;
- });
- });
- },
- triggerEscape: function(comp, simulatedEvent) {
- systemApi.triggerEvent("keydown", comp.element, simulatedEvent.event);
- },
- getByUid: function(uid) {
- return getByUid(uid);
- },
- getByDom: function(elem) {
- return getByDom(elem);
- },
- build: build$1,
- addToGui: function(c) {
- add2(c);
- },
- removeFromGui: function(c) {
- remove2(c);
- },
- addToWorld: function(c) {
- addToWorld(c);
- },
- removeFromWorld: function(c) {
- removeFromWorld(c);
- },
- broadcast: function(message) {
- broadcast$1(message);
- },
- broadcastOn: function(channels, message) {
- broadcastOn(channels, message);
- },
- broadcastEvent: function(eventName, event) {
- broadcastEvent(eventName, event);
- },
- isConnected: always
- };
- var addToWorld = function(component) {
- component.connect(systemApi);
- if (!isText$1(component.element)) {
- registry.register(component);
- each$1(component.components(), addToWorld);
- systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
- }
- };
- var removeFromWorld = function(component) {
- if (!isText$1(component.element)) {
- each$1(component.components(), removeFromWorld);
- registry.unregister(component);
- }
- component.disconnect();
- };
- var add2 = function(component) {
- attach(root, component);
- };
- var remove2 = function(component) {
- detach(component);
- };
- var destroy = function() {
- domEvents.unbind();
- remove$5(root.element);
- };
- var broadcastData = function(data) {
- var receivers = registry.filter(receive());
- each$1(receivers, function(receiver) {
- var descHandler = receiver.descHandler;
- var handler = getCurried(descHandler);
- handler(data);
- });
- };
- var broadcast$1 = function(message) {
- broadcastData({
- universal: true,
- data: message
- });
- };
- var broadcastOn = function(channels, message) {
- broadcastData({
- universal: false,
- channels,
- data: message
- });
- };
- var broadcastEvent = function(eventName, event) {
- var listeners = registry.filter(eventName);
- return broadcast(listeners, event);
- };
- var getByUid = function(uid) {
- return registry.getById(uid).fold(function() {
- return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
- }, Result.value);
- };
- var getByDom = function(elem) {
- var uid = read$1(elem).getOr("not found");
- return getByUid(uid);
- };
- addToWorld(root);
- return {
- root,
- element: root.element,
- destroy,
- add: add2,
- remove: remove2,
- getByUid,
- getByDom,
- addToWorld,
- removeFromWorld,
- broadcast: broadcast$1,
- broadcastOn,
- broadcastEvent
- };
- };
- var renderBar = function(spec, backstage) {
- return {
- dom: {
- tag: "div",
- classes: [
- "tox-bar",
- "tox-form__controls-h-stack"
- ]
- },
- components: map$2(spec.items, backstage.interpreter)
- };
- };
- var schema$l = constant$1([
- defaulted("prefix", "form-field"),
- field("fieldBehaviours", [
- Composing,
- Representing
- ])
- ]);
- var parts$e = constant$1([
- optional({
- schema: [required$1("dom")],
- name: "label"
- }),
- optional({
- factory: {
- sketch: function(spec) {
- return {
- uid: spec.uid,
- dom: {
- tag: "span",
- styles: { display: "none" },
- attributes: { "aria-hidden": "true" },
- innerHtml: spec.text
- }
- };
- }
- },
- schema: [required$1("text")],
- name: "aria-descriptor"
- }),
- required({
- factory: {
- sketch: function(spec) {
- var excludeFactory = exclude(spec, ["factory"]);
- return spec.factory.sketch(excludeFactory);
- }
- },
- schema: [required$1("factory")],
- name: "field"
- })
- ]);
- var factory$i = function(detail, components2, _spec, _externals) {
- var behaviours2 = augment(detail.fieldBehaviours, [
- Composing.config({
- find: function(container) {
- return getPart(container, detail, "field");
- }
- }),
- Representing.config({
- store: {
- mode: "manual",
- getValue: function(field2) {
- return Composing.getCurrent(field2).bind(Representing.getValue);
- },
- setValue: function(field2, value2) {
- Composing.getCurrent(field2).each(function(current) {
- Representing.setValue(current, value2);
- });
- }
- }
- })
- ]);
- var events2 = derive$2([runOnAttached(function(component, _simulatedEvent) {
- var ps = getParts(component, detail, [
- "label",
- "field",
- "aria-descriptor"
- ]);
- ps.field().each(function(field2) {
- var id = generate$6(detail.prefix);
- ps.label().each(function(label) {
- set$8(label.element, "for", id);
- set$8(field2.element, "id", id);
- });
- ps["aria-descriptor"]().each(function(descriptor) {
- var descriptorId = generate$6(detail.prefix);
- set$8(descriptor.element, "id", descriptorId);
- set$8(field2.element, "aria-describedby", descriptorId);
- });
- });
- })]);
- var apis = {
- getField: function(container) {
- return getPart(container, detail, "field");
- },
- getLabel: function(container) {
- return getPart(container, detail, "label");
- }
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: behaviours2,
- events: events2,
- apis
- };
- };
- var FormField = composite({
- name: "FormField",
- configFields: schema$l(),
- partFields: parts$e(),
- factory: factory$i,
- apis: {
- getField: function(apis, comp) {
- return apis.getField(comp);
- },
- getLabel: function(apis, comp) {
- return apis.getLabel(comp);
- }
- }
- });
- var exhibit$2 = function(base2, tabConfig) {
- return nu$7({
- attributes: wrapAll([{
- key: tabConfig.tabAttr,
- value: "true"
- }])
- });
- };
- var ActiveTabstopping = Object.freeze({
- __proto__: null,
- exhibit: exhibit$2
- });
- var TabstopSchema = [defaulted("tabAttr", "data-alloy-tabstop")];
- var Tabstopping = create$8({
- fields: TabstopSchema,
- name: "tabstopping",
- active: ActiveTabstopping
- });
- var global$7 = tinymce.util.Tools.resolve("tinymce.html.Entities");
- var renderFormFieldWith = function(pLabel, pField, extraClasses, extraBehaviours) {
- var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
- return FormField.sketch(spec);
- };
- var renderFormField = function(pLabel, pField) {
- return renderFormFieldWith(pLabel, pField, [], []);
- };
- var renderFormFieldSpecWith = function(pLabel, pField, extraClasses, extraBehaviours) {
- return {
- dom: renderFormFieldDomWith(extraClasses),
- components: pLabel.toArray().concat([pField]),
- fieldBehaviours: derive$1(extraBehaviours)
- };
- };
- var renderFormFieldDom = function() {
- return renderFormFieldDomWith([]);
- };
- var renderFormFieldDomWith = function(extraClasses) {
- return {
- tag: "div",
- classes: ["tox-form__group"].concat(extraClasses)
- };
- };
- var renderLabel$2 = function(label, providersBackstage) {
- return FormField.parts.label({
- dom: {
- tag: "label",
- classes: ["tox-label"],
- innerHtml: providersBackstage.translate(label)
- }
- });
- };
- var formChangeEvent = generate$6("form-component-change");
- var formCloseEvent = generate$6("form-close");
- var formCancelEvent = generate$6("form-cancel");
- var formActionEvent = generate$6("form-action");
- var formSubmitEvent = generate$6("form-submit");
- var formBlockEvent = generate$6("form-block");
- var formUnblockEvent = generate$6("form-unblock");
- var formTabChangeEvent = generate$6("form-tabchange");
- var formResizeEvent = generate$6("form-resize");
- var renderCollection = function(spec, providersBackstage) {
- var _a2;
- var pLabel = spec.label.map(function(label) {
- return renderLabel$2(label, providersBackstage);
- });
- var runOnItem = function(f) {
- return function(comp, se) {
- closest$1(se.event.target, "[data-collection-item-value]").each(function(target) {
- f(comp, se, target, get$d(target, "data-collection-item-value"));
- });
- };
- };
- var setContents = function(comp, items) {
- var htmlLines = map$2(items, function(item2) {
- var itemText = global$e.translate(item2.text);
- var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + "</div>" : "";
- var iconContent = '<div class="tox-collection__item-icon">' + item2.icon + "</div>";
- var mapItemName = {
- "_": " ",
- " - ": " ",
- "-": " "
- };
- var ariaLabel = itemText.replace(/\_| \- |\-/g, function(match) {
- return mapItemName[match];
- });
- var disabledClass = providersBackstage.isDisabled() ? " tox-collection__item--state-disabled" : "";
- return '<div class="tox-collection__item' + disabledClass + '" tabindex="-1" data-collection-item-value="' + global$7.encodeAllRaw(item2.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + "</div>";
- });
- var chunks = spec.columns !== "auto" && spec.columns > 1 ? chunk$1(htmlLines, spec.columns) : [htmlLines];
- var html2 = map$2(chunks, function(ch) {
- return '<div class="tox-collection__group">' + ch.join("") + "</div>";
- });
- set$5(comp.element, html2.join(""));
- };
- var onClick = runOnItem(function(comp, se, tgt, itemValue) {
- se.stop();
- if (!providersBackstage.isDisabled()) {
- emitWith(comp, formActionEvent, {
- name: spec.name,
- value: itemValue
- });
- }
- });
- var collectionEvents = [
- run$1(mouseover(), runOnItem(function(comp, se, tgt) {
- focus$3(tgt);
- })),
- run$1(click(), onClick),
- run$1(tap(), onClick),
- run$1(focusin(), runOnItem(function(comp, se, tgt) {
- descendant(comp.element, "." + activeClass).each(function(currentActive) {
- remove$2(currentActive, activeClass);
- });
- add$2(tgt, activeClass);
- })),
- run$1(focusout(), runOnItem(function(comp) {
- descendant(comp.element, "." + activeClass).each(function(currentActive) {
- remove$2(currentActive, activeClass);
- });
- })),
- runOnExecute$1(runOnItem(function(comp, se, tgt, itemValue) {
- emitWith(comp, formActionEvent, {
- name: spec.name,
- value: itemValue
- });
- }))
- ];
- var iterCollectionItems = function(comp, applyAttributes) {
- return map$2(descendants(comp.element, ".tox-collection__item"), applyAttributes);
- };
- var pField = FormField.parts.field({
- dom: {
- tag: "div",
- classes: ["tox-collection"].concat(spec.columns !== 1 ? ["tox-collection--grid"] : ["tox-collection--list"])
- },
- components: [],
- factory: { sketch: identity$1 },
- behaviours: derive$1([
- Disabling.config({
- disabled: providersBackstage.isDisabled,
- onDisabled: function(comp) {
- iterCollectionItems(comp, function(childElm) {
- add$2(childElm, "tox-collection__item--state-disabled");
- set$8(childElm, "aria-disabled", true);
- });
- },
- onEnabled: function(comp) {
- iterCollectionItems(comp, function(childElm) {
- remove$2(childElm, "tox-collection__item--state-disabled");
- remove$7(childElm, "aria-disabled");
- });
- }
- }),
- receivingConfig(),
- Replacing.config({}),
- Representing.config({
- store: {
- mode: "memory",
- initialValue: []
- },
- onSetValue: function(comp, items) {
- setContents(comp, items);
- if (spec.columns === "auto") {
- detectSize(comp, 5, "tox-collection__item").each(function(_a3) {
- var numRows = _a3.numRows, numColumns = _a3.numColumns;
- Keying.setGridSize(comp, numRows, numColumns);
- });
- }
- emit(comp, formResizeEvent);
- }
- }),
- Tabstopping.config({}),
- Keying.config(deriveCollectionMovement(spec.columns, "normal")),
- config("collection-events", collectionEvents)
- ]),
- eventOrder: (_a2 = {}, _a2[execute$5()] = [
- "disabling",
- "alloy.base.behaviour",
- "collection-events"
- ], _a2)
- });
- var extraClasses = ["tox-form__group--collection"];
- return renderFormFieldWith(pLabel, pField, extraClasses, []);
- };
- var schema$k = constant$1([
- option("data"),
- defaulted("inputAttributes", {}),
- defaulted("inputStyles", {}),
- defaulted("tag", "input"),
- defaulted("inputClasses", []),
- onHandler("onSetValue"),
- defaulted("styles", {}),
- defaulted("eventOrder", {}),
- field("inputBehaviours", [
- Representing,
- Focusing
- ]),
- defaulted("selectOnFocus", true)
- ]);
- var focusBehaviours = function(detail) {
- return derive$1([Focusing.config({
- onFocus: !detail.selectOnFocus ? noop : function(component) {
- var input2 = component.element;
- var value2 = get$5(input2);
- input2.dom.setSelectionRange(0, value2.length);
- }
- })]);
- };
- var behaviours = function(detail) {
- return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
- store: __assign(__assign({ mode: "manual" }, detail.data.map(function(data) {
- return { initialValue: data };
- }).getOr({})), {
- getValue: function(input2) {
- return get$5(input2.element);
- },
- setValue: function(input2, data) {
- var current = get$5(input2.element);
- if (current !== data) {
- set$4(input2.element, data);
- }
- }
- }),
- onSetValue: detail.onSetValue
- })]));
- };
- var dom = function(detail) {
- return {
- tag: detail.tag,
- attributes: __assign({ type: "text" }, detail.inputAttributes),
- styles: detail.inputStyles,
- classes: detail.inputClasses
- };
- };
- var factory$h = function(detail, _spec) {
- return {
- uid: detail.uid,
- dom: dom(detail),
- components: [],
- behaviours: behaviours(detail),
- eventOrder: detail.eventOrder
- };
- };
- var Input = single({
- name: "Input",
- configFields: schema$k(),
- factory: factory$h
- });
- var exports$1 = {}, module2 = { exports: exports$1 };
- (function(define, exports2, module3, require2) {
- (function(global2, factory2) {
- typeof exports2 === "object" && typeof module3 !== "undefined" ? module3.exports = factory2() : typeof define === "function" && define.amd ? define(factory2) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.EphoxContactWrapper = factory2());
- })(this, function() {
- var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
- var promise = { exports: {} };
- (function(module4) {
- (function(root) {
- var setTimeoutFunc = setTimeout;
- function noop2() {
- }
- function bind2(fn, thisArg) {
- return function() {
- fn.apply(thisArg, arguments);
- };
- }
- function Promise2(fn) {
- if (typeof this !== "object")
- throw new TypeError("Promises must be constructed via new");
- if (typeof fn !== "function")
- throw new TypeError("not a function");
- this._state = 0;
- this._handled = false;
- this._value = void 0;
- this._deferreds = [];
- doResolve(fn, this);
- }
- function handle2(self2, deferred) {
- while (self2._state === 3) {
- self2 = self2._value;
- }
- if (self2._state === 0) {
- self2._deferreds.push(deferred);
- return;
- }
- self2._handled = true;
- Promise2._immediateFn(function() {
- var cb = self2._state === 1 ? deferred.onFulfilled : deferred.onRejected;
- if (cb === null) {
- (self2._state === 1 ? resolve : reject)(deferred.promise, self2._value);
- return;
- }
- var ret;
- try {
- ret = cb(self2._value);
- } catch (e) {
- reject(deferred.promise, e);
- return;
- }
- resolve(deferred.promise, ret);
- });
- }
- function resolve(self2, newValue) {
- try {
- if (newValue === self2)
- throw new TypeError("A promise cannot be resolved with itself.");
- if (newValue && (typeof newValue === "object" || typeof newValue === "function")) {
- var then = newValue.then;
- if (newValue instanceof Promise2) {
- self2._state = 3;
- self2._value = newValue;
- finale(self2);
- return;
- } else if (typeof then === "function") {
- doResolve(bind2(then, newValue), self2);
- return;
- }
- }
- self2._state = 1;
- self2._value = newValue;
- finale(self2);
- } catch (e) {
- reject(self2, e);
- }
- }
- function reject(self2, newValue) {
- self2._state = 2;
- self2._value = newValue;
- finale(self2);
- }
- function finale(self2) {
- if (self2._state === 2 && self2._deferreds.length === 0) {
- Promise2._immediateFn(function() {
- if (!self2._handled) {
- Promise2._unhandledRejectionFn(self2._value);
- }
- });
- }
- for (var i = 0, len = self2._deferreds.length; i < len; i++) {
- handle2(self2, self2._deferreds[i]);
- }
- self2._deferreds = null;
- }
- function Handler(onFulfilled, onRejected, promise2) {
- this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null;
- this.onRejected = typeof onRejected === "function" ? onRejected : null;
- this.promise = promise2;
- }
- function doResolve(fn, self2) {
- var done = false;
- try {
- fn(function(value2) {
- if (done)
- return;
- done = true;
- resolve(self2, value2);
- }, function(reason) {
- if (done)
- return;
- done = true;
- reject(self2, reason);
- });
- } catch (ex) {
- if (done)
- return;
- done = true;
- reject(self2, ex);
- }
- }
- Promise2.prototype["catch"] = function(onRejected) {
- return this.then(null, onRejected);
- };
- Promise2.prototype.then = function(onFulfilled, onRejected) {
- var prom = new this.constructor(noop2);
- handle2(this, new Handler(onFulfilled, onRejected, prom));
- return prom;
- };
- Promise2.all = function(arr) {
- var args = Array.prototype.slice.call(arr);
- return new Promise2(function(resolve2, reject2) {
- if (args.length === 0)
- return resolve2([]);
- var remaining = args.length;
- function res(i2, val) {
- try {
- if (val && (typeof val === "object" || typeof val === "function")) {
- var then = val.then;
- if (typeof then === "function") {
- then.call(val, function(val2) {
- res(i2, val2);
- }, reject2);
- return;
- }
- }
- args[i2] = val;
- if (--remaining === 0) {
- resolve2(args);
- }
- } catch (ex) {
- reject2(ex);
- }
- }
- for (var i = 0; i < args.length; i++) {
- res(i, args[i]);
- }
- });
- };
- Promise2.resolve = function(value2) {
- if (value2 && typeof value2 === "object" && value2.constructor === Promise2) {
- return value2;
- }
- return new Promise2(function(resolve2) {
- resolve2(value2);
- });
- };
- Promise2.reject = function(value2) {
- return new Promise2(function(resolve2, reject2) {
- reject2(value2);
- });
- };
- Promise2.race = function(values2) {
- return new Promise2(function(resolve2, reject2) {
- for (var i = 0, len = values2.length; i < len; i++) {
- values2[i].then(resolve2, reject2);
- }
- });
- };
- Promise2._immediateFn = typeof setImmediate === "function" ? function(fn) {
- setImmediate(fn);
- } : function(fn) {
- setTimeoutFunc(fn, 0);
- };
- Promise2._unhandledRejectionFn = function _unhandledRejectionFn(err) {
- if (typeof console !== "undefined" && console) {
- console.warn("Possible Unhandled Promise Rejection:", err);
- }
- };
- Promise2._setImmediateFn = function _setImmediateFn(fn) {
- Promise2._immediateFn = fn;
- };
- Promise2._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
- Promise2._unhandledRejectionFn = fn;
- };
- if (module4.exports) {
- module4.exports = Promise2;
- } else if (!root.Promise) {
- root.Promise = Promise2;
- }
- })(commonjsGlobal);
- })(promise);
- var promisePolyfill = promise.exports;
- var Global = function() {
- if (typeof window !== "undefined") {
- return window;
- } else {
- return Function("return this;")();
- }
- }();
- var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
- return promisePolyfill_1;
- });
- })(void 0, exports$1, module2);
- var Promise$1 = module2.exports.boltExport;
- var nu$3 = function(baseFn) {
- var data = Optional.none();
- var callbacks = [];
- var map2 = function(f) {
- return nu$3(function(nCallback) {
- get2(function(data2) {
- nCallback(f(data2));
- });
- });
- };
- var get2 = function(nCallback) {
- if (isReady()) {
- call(nCallback);
- } else {
- callbacks.push(nCallback);
- }
- };
- var set2 = function(x) {
- if (!isReady()) {
- data = Optional.some(x);
- run2(callbacks);
- callbacks = [];
- }
- };
- var isReady = function() {
- return data.isSome();
- };
- var run2 = function(cbs) {
- each$1(cbs, call);
- };
- var call = function(cb) {
- data.each(function(x) {
- setTimeout(function() {
- cb(x);
- }, 0);
- });
- };
- baseFn(set2);
- return {
- get: get2,
- map: map2,
- isReady
- };
- };
- var pure$1 = function(a) {
- return nu$3(function(callback) {
- callback(a);
- });
- };
- var LazyValue = {
- nu: nu$3,
- pure: pure$1
- };
- var errorReporter = function(err) {
- setTimeout(function() {
- throw err;
- }, 0);
- };
- var make$5 = function(run2) {
- var get2 = function(callback) {
- run2().then(callback, errorReporter);
- };
- var map2 = function(fab) {
- return make$5(function() {
- return run2().then(fab);
- });
- };
- var bind2 = function(aFutureB) {
- return make$5(function() {
- return run2().then(function(v) {
- return aFutureB(v).toPromise();
- });
- });
- };
- var anonBind = function(futureB) {
- return make$5(function() {
- return run2().then(function() {
- return futureB.toPromise();
- });
- });
- };
- var toLazy = function() {
- return LazyValue.nu(get2);
- };
- var toCached = function() {
- var cache = null;
- return make$5(function() {
- if (cache === null) {
- cache = run2();
- }
- return cache;
- });
- };
- var toPromise = run2;
- return {
- map: map2,
- bind: bind2,
- anonBind,
- toLazy,
- toCached,
- toPromise,
- get: get2
- };
- };
- var nu$2 = function(baseFn) {
- return make$5(function() {
- return new Promise$1(baseFn);
- });
- };
- var pure = function(a) {
- return make$5(function() {
- return Promise$1.resolve(a);
- });
- };
- var Future = {
- nu: nu$2,
- pure
- };
- var ariaElements = [
- "input",
- "textarea"
- ];
- var isAriaElement = function(elem) {
- var name2 = name$2(elem);
- return contains$2(ariaElements, name2);
- };
- var markValid = function(component, invalidConfig) {
- var elem = invalidConfig.getRoot(component).getOr(component.element);
- remove$2(elem, invalidConfig.invalidClass);
- invalidConfig.notify.each(function(notifyInfo) {
- if (isAriaElement(component.element)) {
- set$8(component.element, "aria-invalid", false);
- }
- notifyInfo.getContainer(component).each(function(container) {
- set$5(container, notifyInfo.validHtml);
- });
- notifyInfo.onValid(component);
- });
- };
- var markInvalid = function(component, invalidConfig, invalidState, text2) {
- var elem = invalidConfig.getRoot(component).getOr(component.element);
- add$2(elem, invalidConfig.invalidClass);
- invalidConfig.notify.each(function(notifyInfo) {
- if (isAriaElement(component.element)) {
- set$8(component.element, "aria-invalid", true);
- }
- notifyInfo.getContainer(component).each(function(container) {
- set$5(container, text2);
- });
- notifyInfo.onInvalid(component, text2);
- });
- };
- var query = function(component, invalidConfig, _invalidState) {
- return invalidConfig.validator.fold(function() {
- return Future.pure(Result.value(true));
- }, function(validatorInfo) {
- return validatorInfo.validate(component);
- });
- };
- var run = function(component, invalidConfig, invalidState) {
- invalidConfig.notify.each(function(notifyInfo) {
- notifyInfo.onValidate(component);
- });
- return query(component, invalidConfig).map(function(valid) {
- if (component.getSystem().isConnected()) {
- return valid.fold(function(err) {
- markInvalid(component, invalidConfig, invalidState, err);
- return Result.error(err);
- }, function(v) {
- markValid(component, invalidConfig);
- return Result.value(v);
- });
- } else {
- return Result.error("No longer in system");
- }
- });
- };
- var isInvalid = function(component, invalidConfig) {
- var elem = invalidConfig.getRoot(component).getOr(component.element);
- return has(elem, invalidConfig.invalidClass);
- };
- var InvalidateApis = Object.freeze({
- __proto__: null,
- markValid,
- markInvalid,
- query,
- run,
- isInvalid
- });
- var events$8 = function(invalidConfig, invalidState) {
- return invalidConfig.validator.map(function(validatorInfo) {
- return derive$2([run$1(validatorInfo.onEvent, function(component) {
- run(component, invalidConfig, invalidState).get(identity$1);
- })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function(component) {
- run(component, invalidConfig, invalidState).get(noop);
- })] : []));
- }).getOr({});
- };
- var ActiveInvalidate = Object.freeze({
- __proto__: null,
- events: events$8
- });
- var InvalidateSchema = [
- required$1("invalidClass"),
- defaulted("getRoot", Optional.none),
- optionObjOf("notify", [
- defaulted("aria", "alert"),
- defaulted("getContainer", Optional.none),
- defaulted("validHtml", ""),
- onHandler("onValid"),
- onHandler("onInvalid"),
- onHandler("onValidate")
- ]),
- optionObjOf("validator", [
- required$1("validate"),
- defaulted("onEvent", "input"),
- defaulted("validateOnLoad", true)
- ])
- ];
- var Invalidating = create$8({
- fields: InvalidateSchema,
- name: "invalidating",
- active: ActiveInvalidate,
- apis: InvalidateApis,
- extra: {
- validation: function(validator) {
- return function(component) {
- var v = Representing.getValue(component);
- return Future.pure(validator(v));
- };
- }
- }
- });
- var getCoupled = function(component, coupleConfig, coupleState, name2) {
- return coupleState.getOrCreate(component, coupleConfig, name2);
- };
- var CouplingApis = Object.freeze({
- __proto__: null,
- getCoupled
- });
- var CouplingSchema = [requiredOf("others", setOf(Result.value, anyValue()))];
- var init$a = function() {
- var coupled = {};
- var getOrCreate = function(component, coupleConfig, name2) {
- var available = keys(coupleConfig.others);
- if (!available) {
- throw new Error("Cannot find coupled component: " + name2 + ". Known coupled components: " + JSON.stringify(available, null, 2));
- } else {
- return get$e(coupled, name2).getOrThunk(function() {
- var builder2 = get$e(coupleConfig.others, name2).getOrDie("No information found for coupled component: " + name2);
- var spec = builder2(component);
- var built = component.getSystem().build(spec);
- coupled[name2] = built;
- return built;
- });
- }
- };
- var readState = constant$1({});
- return nu$8({
- readState,
- getOrCreate
- });
- };
- var CouplingState = Object.freeze({
- __proto__: null,
- init: init$a
- });
- var Coupling = create$8({
- fields: CouplingSchema,
- name: "coupling",
- apis: CouplingApis,
- state: CouplingState
- });
- var suffix = constant$1("sink");
- var partType$1 = constant$1(optional({
- name: suffix(),
- overrides: constant$1({
- dom: { tag: "div" },
- behaviours: derive$1([Positioning.config({ useFixed: always })]),
- events: derive$2([
- cutter(keydown()),
- cutter(mousedown()),
- cutter(click())
- ])
- })
- }));
- var HighlightOnOpen;
- (function(HighlightOnOpen2) {
- HighlightOnOpen2[HighlightOnOpen2["HighlightFirst"] = 0] = "HighlightFirst";
- HighlightOnOpen2[HighlightOnOpen2["HighlightNone"] = 1] = "HighlightNone";
- })(HighlightOnOpen || (HighlightOnOpen = {}));
- var getAnchor = function(detail, component) {
- var hotspot = detail.getHotspot(component).getOr(component);
- var type2 = "hotspot";
- var overrides = detail.getAnchorOverrides();
- return detail.layouts.fold(function() {
- return {
- type: type2,
- hotspot,
- overrides
- };
- }, function(layouts2) {
- return {
- type: type2,
- hotspot,
- overrides,
- layouts: layouts2
- };
- });
- };
- var fetch = function(detail, mapFetch, component) {
- var fetcher = detail.fetch;
- return fetcher(component).map(mapFetch);
- };
- var openF = function(detail, mapFetch, anchor2, component, sandbox, externals, highlightOnOpen) {
- var futureData = fetch(detail, mapFetch, component);
- var getLazySink = getSink(component, detail);
- return futureData.map(function(tdata) {
- return tdata.bind(function(data) {
- return Optional.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
- uid: generate$5(""),
- data,
- highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
- onOpenMenu: function(tmenu, menu2) {
- var sink = getLazySink().getOrDie();
- Positioning.position(sink, menu2, { anchor: anchor2 });
- Sandboxing.decloak(sandbox);
- },
- onOpenSubmenu: function(tmenu, item2, submenu) {
- var sink = getLazySink().getOrDie();
- Positioning.position(sink, submenu, {
- anchor: {
- type: "submenu",
- item: item2
- }
- });
- Sandboxing.decloak(sandbox);
- },
- onRepositionMenu: function(tmenu, primaryMenu, submenuTriggers) {
- var sink = getLazySink().getOrDie();
- Positioning.position(sink, primaryMenu, { anchor: anchor2 });
- each$1(submenuTriggers, function(st) {
- Positioning.position(sink, st.triggeredMenu, {
- anchor: {
- type: "submenu",
- item: st.triggeringItem
- }
- });
- });
- },
- onEscape: function() {
- Focusing.focus(component);
- Sandboxing.close(sandbox);
- return Optional.some(true);
- }
- })));
- });
- });
- };
- var open = function(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
- var anchor2 = getAnchor(detail, hotspot);
- var processed = openF(detail, mapFetch, anchor2, hotspot, sandbox, externals, highlightOnOpen);
- return processed.map(function(tdata) {
- tdata.fold(function() {
- if (Sandboxing.isOpen(sandbox)) {
- Sandboxing.close(sandbox);
- }
- }, function(data) {
- Sandboxing.cloak(sandbox);
- Sandboxing.open(sandbox, data);
- onOpenSync(sandbox);
- });
- return sandbox;
- });
- };
- var close = function(detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
- Sandboxing.close(sandbox);
- return Future.pure(sandbox);
- };
- var togglePopup = function(detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
- var sandbox = Coupling.getCoupled(hotspot, "sandbox");
- var showing = Sandboxing.isOpen(sandbox);
- var action = showing ? close : open;
- return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
- };
- var matchWidth = function(hotspot, container, useMinWidth) {
- var menu2 = Composing.getCurrent(container).getOr(container);
- var buttonWidth = get$a(hotspot.element);
- if (useMinWidth) {
- set$7(menu2.element, "min-width", buttonWidth + "px");
- } else {
- set$6(menu2.element, buttonWidth);
- }
- };
- var getSink = function(anyInSystem, sinkDetail) {
- return anyInSystem.getSystem().getByUid(sinkDetail.uid + "-" + suffix()).map(function(internalSink) {
- return function() {
- return Result.value(internalSink);
- };
- }).getOrThunk(function() {
- return sinkDetail.lazySink.fold(function() {
- return function() {
- return Result.error(new Error("No internal sink is specified, nor could an external sink be found"));
- };
- }, function(lazySinkFn) {
- return function() {
- return lazySinkFn(anyInSystem);
- };
- });
- });
- };
- var doRepositionMenus = function(sandbox) {
- Sandboxing.getState(sandbox).each(function(tmenu) {
- tieredMenu.repositionMenus(tmenu);
- });
- };
- var makeSandbox$1 = function(detail, hotspot, extras) {
- var ariaOwner = manager();
- var onOpen = function(component, menu2) {
- var anchor2 = getAnchor(detail, hotspot);
- ariaOwner.link(hotspot.element);
- if (detail.matchWidth) {
- matchWidth(anchor2.hotspot, menu2, detail.useMinWidth);
- }
- detail.onOpen(anchor2, component, menu2);
- if (extras !== void 0 && extras.onOpen !== void 0) {
- extras.onOpen(component, menu2);
- }
- };
- var onClose = function(component, menu2) {
- ariaOwner.unlink(hotspot.element);
- if (extras !== void 0 && extras.onClose !== void 0) {
- extras.onClose(component, menu2);
- }
- };
- var lazySink = getSink(hotspot, detail);
- return {
- dom: {
- tag: "div",
- classes: detail.sandboxClasses,
- attributes: {
- id: ariaOwner.id,
- role: "listbox"
- }
- },
- behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
- Representing.config({
- store: {
- mode: "memory",
- initialValue: hotspot
- }
- }),
- Sandboxing.config({
- onOpen,
- onClose,
- isPartOf: function(container, data, queryElem) {
- return isPartOf$1(data, queryElem) || isPartOf$1(hotspot, queryElem);
- },
- getAttachPoint: function() {
- return lazySink().getOrDie();
- }
- }),
- Composing.config({
- find: function(sandbox) {
- return Sandboxing.getState(sandbox).bind(function(menu2) {
- return Composing.getCurrent(menu2);
- });
- }
- }),
- Receiving.config({ channels: __assign(__assign({}, receivingChannel$1({ isExtraPart: never })), receivingChannel({ doReposition: doRepositionMenus })) })
- ])
- };
- };
- var repositionMenus = function(comp) {
- var sandbox = Coupling.getCoupled(comp, "sandbox");
- doRepositionMenus(sandbox);
- };
- var sandboxFields = function() {
- return [
- defaulted("sandboxClasses", []),
- SketchBehaviours.field("sandboxBehaviours", [
- Composing,
- Receiving,
- Sandboxing,
- Representing
- ])
- ];
- };
- var schema$j = constant$1([
- required$1("dom"),
- required$1("fetch"),
- onHandler("onOpen"),
- onKeyboardHandler("onExecute"),
- defaulted("getHotspot", Optional.some),
- defaulted("getAnchorOverrides", constant$1({})),
- schema$y(),
- field("dropdownBehaviours", [
- Toggling,
- Coupling,
- Keying,
- Focusing
- ]),
- required$1("toggleClass"),
- defaulted("eventOrder", {}),
- option("lazySink"),
- defaulted("matchWidth", false),
- defaulted("useMinWidth", false),
- option("role")
- ].concat(sandboxFields()));
- var parts$d = constant$1([
- external$1({
- schema: [tieredMenuMarkers()],
- name: "menu",
- defaults: function(detail) {
- return { onExecute: detail.onExecute };
- }
- }),
- partType$1()
- ]);
- var factory$g = function(detail, components2, _spec, externals) {
- var _a2;
- var lookupAttr = function(attr) {
- return get$e(detail.dom, "attributes").bind(function(attrs) {
- return get$e(attrs, attr);
- });
- };
- var switchToMenu = function(sandbox) {
- Sandboxing.getState(sandbox).each(function(tmenu) {
- tieredMenu.highlightPrimary(tmenu);
- });
- };
- var action = function(component) {
- var onOpenSync = switchToMenu;
- togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
- };
- var apis = {
- expand: function(comp) {
- if (!Toggling.isOn(comp)) {
- togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
- }
- },
- open: function(comp) {
- if (!Toggling.isOn(comp)) {
- togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
- }
- },
- isOpen: Toggling.isOn,
- close: function(comp) {
- if (Toggling.isOn(comp)) {
- togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
- }
- },
- repositionMenus: function(comp) {
- if (Toggling.isOn(comp)) {
- repositionMenus(comp);
- }
- }
- };
- var triggerExecute = function(comp, _se) {
- emitExecute(comp);
- return Optional.some(true);
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: augment(detail.dropdownBehaviours, [
- Toggling.config({
- toggleClass: detail.toggleClass,
- aria: { mode: "expanded" }
- }),
- Coupling.config({
- others: {
- sandbox: function(hotspot) {
- return makeSandbox$1(detail, hotspot, {
- onOpen: function() {
- return Toggling.on(hotspot);
- },
- onClose: function() {
- return Toggling.off(hotspot);
- }
- });
- }
- }
- }),
- Keying.config({
- mode: "special",
- onSpace: triggerExecute,
- onEnter: triggerExecute,
- onDown: function(comp, _se) {
- if (Dropdown.isOpen(comp)) {
- var sandbox = Coupling.getCoupled(comp, "sandbox");
- switchToMenu(sandbox);
- } else {
- Dropdown.open(comp);
- }
- return Optional.some(true);
- },
- onEscape: function(comp, _se) {
- if (Dropdown.isOpen(comp)) {
- Dropdown.close(comp);
- return Optional.some(true);
- } else {
- return Optional.none();
- }
- }
- }),
- Focusing.config({})
- ]),
- events: events$a(Optional.some(action)),
- eventOrder: __assign(__assign({}, detail.eventOrder), (_a2 = {}, _a2[execute$5()] = [
- "disabling",
- "toggling",
- "alloy.base.behaviour"
- ], _a2)),
- apis,
- domModification: {
- attributes: __assign(__assign({ "aria-haspopup": "true" }, detail.role.fold(function() {
- return {};
- }, function(role) {
- return { role };
- })), detail.dom.tag === "button" ? { type: lookupAttr("type").getOr("button") } : {})
- }
- };
- };
- var Dropdown = composite({
- name: "Dropdown",
- configFields: schema$j(),
- partFields: parts$d(),
- factory: factory$g,
- apis: {
- open: function(apis, comp) {
- return apis.open(comp);
- },
- expand: function(apis, comp) {
- return apis.expand(comp);
- },
- close: function(apis, comp) {
- return apis.close(comp);
- },
- isOpen: function(apis, comp) {
- return apis.isOpen(comp);
- },
- repositionMenus: function(apis, comp) {
- return apis.repositionMenus(comp);
- }
- }
- });
- var exhibit$1 = function() {
- return nu$7({
- styles: {
- "-webkit-user-select": "none",
- "user-select": "none",
- "-ms-user-select": "none",
- "-moz-user-select": "-moz-none"
- },
- attributes: { unselectable: "on" }
- });
- };
- var events$7 = function() {
- return derive$2([abort(selectstart(), always)]);
- };
- var ActiveUnselecting = Object.freeze({
- __proto__: null,
- events: events$7,
- exhibit: exhibit$1
- });
- var Unselecting = create$8({
- fields: [],
- name: "unselecting",
- active: ActiveUnselecting
- });
- var renderPanelButton = function(spec, sharedBackstage) {
- return Dropdown.sketch({
- dom: spec.dom,
- components: spec.components,
- toggleClass: "mce-active",
- dropdownBehaviours: derive$1([
- DisablingConfigs.button(sharedBackstage.providers.isDisabled),
- receivingConfig(),
- Unselecting.config({}),
- Tabstopping.config({})
- ]),
- layouts: spec.layouts,
- sandboxClasses: ["tox-dialog__popups"],
- lazySink: sharedBackstage.getSink,
- fetch: function(comp) {
- return Future.nu(function(callback) {
- return spec.fetch(callback);
- }).map(function(items) {
- return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6("menu-value"), items, function(value2) {
- spec.onItemAction(comp, value2);
- }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
- });
- },
- parts: { menu: part(false, 1, spec.presets) }
- });
- };
- var colorInputChangeEvent = generate$6("color-input-change");
- var colorSwatchChangeEvent = generate$6("color-swatch-change");
- var colorPickerCancelEvent = generate$6("color-picker-cancel");
- var renderColorInput = function(spec, sharedBackstage, colorInputBackstage) {
- var pField = FormField.parts.field({
- factory: Input,
- inputClasses: ["tox-textfield"],
- onSetValue: function(c) {
- return Invalidating.run(c).get(noop);
- },
- inputBehaviours: derive$1([
- Disabling.config({ disabled: sharedBackstage.providers.isDisabled }),
- receivingConfig(),
- Tabstopping.config({}),
- Invalidating.config({
- invalidClass: "tox-textbox-field-invalid",
- getRoot: function(comp) {
- return parent(comp.element);
- },
- notify: {
- onValid: function(comp) {
- var val = Representing.getValue(comp);
- emitWith(comp, colorInputChangeEvent, { color: val });
- }
- },
- validator: {
- validateOnLoad: false,
- validate: function(input2) {
- var inputValue = Representing.getValue(input2);
- if (inputValue.length === 0) {
- return Future.pure(Result.value(true));
- } else {
- var span = SugarElement.fromTag("span");
- set$7(span, "background-color", inputValue);
- var res = getRaw(span, "background-color").fold(function() {
- return Result.error("blah");
- }, function(_) {
- return Result.value(inputValue);
- });
- return Future.pure(res);
- }
- }
- }
- })
- ]),
- selectOnFocus: false
- });
- var pLabel = spec.label.map(function(label) {
- return renderLabel$2(label, sharedBackstage.providers);
- });
- var emitSwatchChange = function(colorBit, value2) {
- emitWith(colorBit, colorSwatchChangeEvent, { value: value2 });
- };
- var onItemAction = function(comp, value2) {
- memColorButton.getOpt(comp).each(function(colorBit) {
- if (value2 === "custom") {
- colorInputBackstage.colorPicker(function(valueOpt) {
- valueOpt.fold(function() {
- return emit(colorBit, colorPickerCancelEvent);
- }, function(value3) {
- emitSwatchChange(colorBit, value3);
- addColor(value3);
- });
- }, "#ffffff");
- } else if (value2 === "remove") {
- emitSwatchChange(colorBit, "");
- } else {
- emitSwatchChange(colorBit, value2);
- }
- });
- };
- var memColorButton = record(renderPanelButton({
- dom: {
- tag: "span",
- attributes: { "aria-label": sharedBackstage.providers.translate("Color swatch") }
- },
- layouts: {
- onRtl: function() {
- return [
- southwest$2,
- southeast$2,
- south$2
- ];
- },
- onLtr: function() {
- return [
- southeast$2,
- southwest$2,
- south$2
- ];
- }
- },
- components: [],
- fetch: getFetch$1(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
- columns: colorInputBackstage.getColorCols(),
- presets: "color",
- onItemAction
- }, sharedBackstage));
- return FormField.sketch({
- dom: {
- tag: "div",
- classes: ["tox-form__group"]
- },
- components: pLabel.toArray().concat([{
- dom: {
- tag: "div",
- classes: ["tox-color-input"]
- },
- components: [
- pField,
- memColorButton.asSpec()
- ]
- }]),
- fieldBehaviours: derive$1([config("form-field-events", [
- run$1(colorInputChangeEvent, function(comp, se) {
- memColorButton.getOpt(comp).each(function(colorButton) {
- set$7(colorButton.element, "background-color", se.event.color);
- });
- emitWith(comp, formChangeEvent, { name: spec.name });
- }),
- run$1(colorSwatchChangeEvent, function(comp, se) {
- FormField.getField(comp).each(function(field2) {
- Representing.setValue(field2, se.event.value);
- Composing.getCurrent(comp).each(Focusing.focus);
- });
- }),
- run$1(colorPickerCancelEvent, function(comp, _se) {
- FormField.getField(comp).each(function(_field) {
- Composing.getCurrent(comp).each(Focusing.focus);
- });
- })
- ])])
- });
- };
- var labelPart = optional({
- schema: [required$1("dom")],
- name: "label"
- });
- var edgePart = function(name2) {
- return optional({
- name: "" + name2 + "-edge",
- overrides: function(detail) {
- var action = detail.model.manager.edgeActions[name2];
- return action.fold(function() {
- return {};
- }, function(a) {
- return {
- events: derive$2([
- runActionExtra(touchstart(), function(comp, se, d) {
- return a(comp, d);
- }, [detail]),
- runActionExtra(mousedown(), function(comp, se, d) {
- return a(comp, d);
- }, [detail]),
- runActionExtra(mousemove(), function(comp, se, det) {
- if (det.mouseIsDown.get()) {
- a(comp, det);
- }
- }, [detail])
- ])
- };
- });
- }
- });
- };
- var tlEdgePart = edgePart("top-left");
- var tedgePart = edgePart("top");
- var trEdgePart = edgePart("top-right");
- var redgePart = edgePart("right");
- var brEdgePart = edgePart("bottom-right");
- var bedgePart = edgePart("bottom");
- var blEdgePart = edgePart("bottom-left");
- var ledgePart = edgePart("left");
- var thumbPart = required({
- name: "thumb",
- defaults: constant$1({ dom: { styles: { position: "absolute" } } }),
- overrides: function(detail) {
- return {
- events: derive$2([
- redirectToPart(touchstart(), detail, "spectrum"),
- redirectToPart(touchmove(), detail, "spectrum"),
- redirectToPart(touchend(), detail, "spectrum"),
- redirectToPart(mousedown(), detail, "spectrum"),
- redirectToPart(mousemove(), detail, "spectrum"),
- redirectToPart(mouseup(), detail, "spectrum")
- ])
- };
- }
- });
- var spectrumPart = required({
- schema: [customField("mouseIsDown", function() {
- return Cell(false);
- })],
- name: "spectrum",
- overrides: function(detail) {
- var modelDetail = detail.model;
- var model = modelDetail.manager;
- var setValueFrom2 = function(component, simulatedEvent) {
- return model.getValueFromEvent(simulatedEvent).map(function(value2) {
- return model.setValueFrom(component, detail, value2);
- });
- };
- return {
- behaviours: derive$1([
- Keying.config({
- mode: "special",
- onLeft: function(spectrum) {
- return model.onLeft(spectrum, detail);
- },
- onRight: function(spectrum) {
- return model.onRight(spectrum, detail);
- },
- onUp: function(spectrum) {
- return model.onUp(spectrum, detail);
- },
- onDown: function(spectrum) {
- return model.onDown(spectrum, detail);
- }
- }),
- Focusing.config({})
- ]),
- events: derive$2([
- run$1(touchstart(), setValueFrom2),
- run$1(touchmove(), setValueFrom2),
- run$1(mousedown(), setValueFrom2),
- run$1(mousemove(), function(spectrum, se) {
- if (detail.mouseIsDown.get()) {
- setValueFrom2(spectrum, se);
- }
- })
- ])
- };
- }
- });
- var SliderParts = [
- labelPart,
- ledgePart,
- redgePart,
- tedgePart,
- bedgePart,
- tlEdgePart,
- trEdgePart,
- blEdgePart,
- brEdgePart,
- thumbPart,
- spectrumPart
- ];
- var _sliderChangeEvent = "slider.change.value";
- var sliderChangeEvent = constant$1(_sliderChangeEvent);
- var isTouchEvent$2 = function(evt) {
- return evt.type.indexOf("touch") !== -1;
- };
- var getEventSource = function(simulatedEvent) {
- var evt = simulatedEvent.event.raw;
- if (isTouchEvent$2(evt)) {
- var touchEvent = evt;
- return touchEvent.touches !== void 0 && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function(t2) {
- return SugarPosition(t2.clientX, t2.clientY);
- }) : Optional.none();
- } else {
- var mouseEvent = evt;
- return mouseEvent.clientX !== void 0 ? Optional.some(mouseEvent).map(function(me) {
- return SugarPosition(me.clientX, me.clientY);
- }) : Optional.none();
- }
- };
- var t = "top", r = "right", b = "bottom", l = "left";
- var minX = function(detail) {
- return detail.model.minX;
- };
- var minY = function(detail) {
- return detail.model.minY;
- };
- var min1X = function(detail) {
- return detail.model.minX - 1;
- };
- var min1Y = function(detail) {
- return detail.model.minY - 1;
- };
- var maxX = function(detail) {
- return detail.model.maxX;
- };
- var maxY = function(detail) {
- return detail.model.maxY;
- };
- var max1X = function(detail) {
- return detail.model.maxX + 1;
- };
- var max1Y = function(detail) {
- return detail.model.maxY + 1;
- };
- var range = function(detail, max2, min2) {
- return max2(detail) - min2(detail);
- };
- var xRange = function(detail) {
- return range(detail, maxX, minX);
- };
- var yRange = function(detail) {
- return range(detail, maxY, minY);
- };
- var halfX = function(detail) {
- return xRange(detail) / 2;
- };
- var halfY = function(detail) {
- return yRange(detail) / 2;
- };
- var step = function(detail) {
- return detail.stepSize;
- };
- var snap = function(detail) {
- return detail.snapToGrid;
- };
- var snapStart = function(detail) {
- return detail.snapStart;
- };
- var rounded = function(detail) {
- return detail.rounded;
- };
- var hasEdge = function(detail, edgeName) {
- return detail[edgeName + "-edge"] !== void 0;
- };
- var hasLEdge = function(detail) {
- return hasEdge(detail, l);
- };
- var hasREdge = function(detail) {
- return hasEdge(detail, r);
- };
- var hasTEdge = function(detail) {
- return hasEdge(detail, t);
- };
- var hasBEdge = function(detail) {
- return hasEdge(detail, b);
- };
- var currentValue = function(detail) {
- return detail.model.value.get();
- };
- var xValue = function(x) {
- return { x };
- };
- var yValue = function(y) {
- return { y };
- };
- var xyValue = function(x, y) {
- return {
- x,
- y
- };
- };
- var fireSliderChange$3 = function(component, value2) {
- emitWith(component, sliderChangeEvent(), { value: value2 });
- };
- var setToTLEdgeXY = function(edge2, detail) {
- fireSliderChange$3(edge2, xyValue(min1X(detail), min1Y(detail)));
- };
- var setToTEdge = function(edge2, detail) {
- fireSliderChange$3(edge2, yValue(min1Y(detail)));
- };
- var setToTEdgeXY = function(edge2, detail) {
- fireSliderChange$3(edge2, xyValue(halfX(detail), min1Y(detail)));
- };
- var setToTREdgeXY = function(edge2, detail) {
- fireSliderChange$3(edge2, xyValue(max1X(detail), min1Y(detail)));
- };
- var setToREdge = function(edge2, detail) {
- fireSliderChange$3(edge2, xValue(max1X(detail)));
- };
- var setToREdgeXY = function(edge2, detail) {
- fireSliderChange$3(edge2, xyValue(max1X(detail), halfY(detail)));
- };
- var setToBREdgeXY = function(edge2, detail) {
- fireSliderChange$3(edge2, xyValue(max1X(detail), max1Y(detail)));
- };
- var setToBEdge = function(edge2, detail) {
- fireSliderChange$3(edge2, yValue(max1Y(detail)));
- };
- var setToBEdgeXY = function(edge2, detail) {
- fireSliderChange$3(edge2, xyValue(halfX(detail), max1Y(detail)));
- };
- var setToBLEdgeXY = function(edge2, detail) {
- fireSliderChange$3(edge2, xyValue(min1X(detail), max1Y(detail)));
- };
- var setToLEdge = function(edge2, detail) {
- fireSliderChange$3(edge2, xValue(min1X(detail)));
- };
- var setToLEdgeXY = function(edge2, detail) {
- fireSliderChange$3(edge2, xyValue(min1X(detail), halfY(detail)));
- };
- var reduceBy = function(value2, min2, max2, step2) {
- if (value2 < min2) {
- return value2;
- } else if (value2 > max2) {
- return max2;
- } else if (value2 === min2) {
- return min2 - 1;
- } else {
- return Math.max(min2, value2 - step2);
- }
- };
- var increaseBy = function(value2, min2, max2, step2) {
- if (value2 > max2) {
- return value2;
- } else if (value2 < min2) {
- return min2;
- } else if (value2 === max2) {
- return max2 + 1;
- } else {
- return Math.min(max2, value2 + step2);
- }
- };
- var capValue = function(value2, min2, max2) {
- return Math.max(min2, Math.min(max2, value2));
- };
- var snapValueOf = function(value2, min2, max2, step2, snapStart2) {
- return snapStart2.fold(function() {
- var initValue = value2 - min2;
- var extraValue = Math.round(initValue / step2) * step2;
- return capValue(min2 + extraValue, min2 - 1, max2 + 1);
- }, function(start) {
- var remainder = (value2 - start) % step2;
- var adjustment = Math.round(remainder / step2);
- var rawSteps = Math.floor((value2 - start) / step2);
- var maxSteps = Math.floor((max2 - start) / step2);
- var numSteps = Math.min(maxSteps, rawSteps + adjustment);
- var r2 = start + numSteps * step2;
- return Math.max(start, r2);
- });
- };
- var findOffsetOf = function(value2, min2, max2) {
- return Math.min(max2, Math.max(value2, min2)) - min2;
- };
- var findValueOf = function(args) {
- var min2 = args.min, max2 = args.max, range2 = args.range, value2 = args.value, step2 = args.step, snap2 = args.snap, snapStart2 = args.snapStart, rounded2 = args.rounded, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, minBound = args.minBound, maxBound = args.maxBound, screenRange = args.screenRange;
- var capMin = hasMinEdge ? min2 - 1 : min2;
- var capMax = hasMaxEdge ? max2 + 1 : max2;
- if (value2 < minBound) {
- return capMin;
- } else if (value2 > maxBound) {
- return capMax;
- } else {
- var offset2 = findOffsetOf(value2, minBound, maxBound);
- var newValue = capValue(offset2 / screenRange * range2 + min2, capMin, capMax);
- if (snap2 && newValue >= min2 && newValue <= max2) {
- return snapValueOf(newValue, min2, max2, step2, snapStart2);
- } else if (rounded2) {
- return Math.round(newValue);
- } else {
- return newValue;
- }
- }
- };
- var findOffsetOfValue$2 = function(args) {
- var min2 = args.min, max2 = args.max, range2 = args.range, value2 = args.value, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, maxBound = args.maxBound, maxOffset = args.maxOffset, centerMinEdge = args.centerMinEdge, centerMaxEdge = args.centerMaxEdge;
- if (value2 < min2) {
- return hasMinEdge ? 0 : centerMinEdge;
- } else if (value2 > max2) {
- return hasMaxEdge ? maxBound : centerMaxEdge;
- } else {
- return (value2 - min2) / range2 * maxOffset;
- }
- };
- var top = "top", right = "right", bottom = "bottom", left = "left", width = "width", height = "height";
- var getBounds = function(component) {
- return component.element.dom.getBoundingClientRect();
- };
- var getBoundsProperty = function(bounds2, property) {
- return bounds2[property];
- };
- var getMinXBounds = function(component) {
- var bounds2 = getBounds(component);
- return getBoundsProperty(bounds2, left);
- };
- var getMaxXBounds = function(component) {
- var bounds2 = getBounds(component);
- return getBoundsProperty(bounds2, right);
- };
- var getMinYBounds = function(component) {
- var bounds2 = getBounds(component);
- return getBoundsProperty(bounds2, top);
- };
- var getMaxYBounds = function(component) {
- var bounds2 = getBounds(component);
- return getBoundsProperty(bounds2, bottom);
- };
- var getXScreenRange = function(component) {
- var bounds2 = getBounds(component);
- return getBoundsProperty(bounds2, width);
- };
- var getYScreenRange = function(component) {
- var bounds2 = getBounds(component);
- return getBoundsProperty(bounds2, height);
- };
- var getCenterOffsetOf = function(componentMinEdge, componentMaxEdge, spectrumMinEdge) {
- return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
- };
- var getXCenterOffSetOf = function(component, spectrum) {
- var componentBounds = getBounds(component);
- var spectrumBounds = getBounds(spectrum);
- var componentMinEdge = getBoundsProperty(componentBounds, left);
- var componentMaxEdge = getBoundsProperty(componentBounds, right);
- var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
- return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
- };
- var getYCenterOffSetOf = function(component, spectrum) {
- var componentBounds = getBounds(component);
- var spectrumBounds = getBounds(spectrum);
- var componentMinEdge = getBoundsProperty(componentBounds, top);
- var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
- var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
- return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
- };
- var fireSliderChange$2 = function(spectrum, value2) {
- emitWith(spectrum, sliderChangeEvent(), { value: value2 });
- };
- var sliderValue$2 = function(x) {
- return { x };
- };
- var findValueOfOffset$1 = function(spectrum, detail, left2) {
- var args = {
- min: minX(detail),
- max: maxX(detail),
- range: xRange(detail),
- value: left2,
- step: step(detail),
- snap: snap(detail),
- snapStart: snapStart(detail),
- rounded: rounded(detail),
- hasMinEdge: hasLEdge(detail),
- hasMaxEdge: hasREdge(detail),
- minBound: getMinXBounds(spectrum),
- maxBound: getMaxXBounds(spectrum),
- screenRange: getXScreenRange(spectrum)
- };
- return findValueOf(args);
- };
- var setValueFrom$2 = function(spectrum, detail, value2) {
- var xValue2 = findValueOfOffset$1(spectrum, detail, value2);
- var sliderVal = sliderValue$2(xValue2);
- fireSliderChange$2(spectrum, sliderVal);
- return xValue2;
- };
- var setToMin$2 = function(spectrum, detail) {
- var min2 = minX(detail);
- fireSliderChange$2(spectrum, sliderValue$2(min2));
- };
- var setToMax$2 = function(spectrum, detail) {
- var max2 = maxX(detail);
- fireSliderChange$2(spectrum, sliderValue$2(max2));
- };
- var moveBy$2 = function(direction, spectrum, detail) {
- var f = direction > 0 ? increaseBy : reduceBy;
- var xValue2 = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
- fireSliderChange$2(spectrum, sliderValue$2(xValue2));
- return Optional.some(xValue2);
- };
- var handleMovement$2 = function(direction) {
- return function(spectrum, detail) {
- return moveBy$2(direction, spectrum, detail).map(always);
- };
- };
- var getValueFromEvent$2 = function(simulatedEvent) {
- var pos = getEventSource(simulatedEvent);
- return pos.map(function(p) {
- return p.left;
- });
- };
- var findOffsetOfValue$1 = function(spectrum, detail, value2, minEdge, maxEdge) {
- var minOffset = 0;
- var maxOffset = getXScreenRange(spectrum);
- var centerMinEdge = minEdge.bind(function(edge2) {
- return Optional.some(getXCenterOffSetOf(edge2, spectrum));
- }).getOr(minOffset);
- var centerMaxEdge = maxEdge.bind(function(edge2) {
- return Optional.some(getXCenterOffSetOf(edge2, spectrum));
- }).getOr(maxOffset);
- var args = {
- min: minX(detail),
- max: maxX(detail),
- range: xRange(detail),
- value: value2,
- hasMinEdge: hasLEdge(detail),
- hasMaxEdge: hasREdge(detail),
- minBound: getMinXBounds(spectrum),
- minOffset,
- maxBound: getMaxXBounds(spectrum),
- maxOffset,
- centerMinEdge,
- centerMaxEdge
- };
- return findOffsetOfValue$2(args);
- };
- var findPositionOfValue$1 = function(slider, spectrum, value2, minEdge, maxEdge, detail) {
- var offset2 = findOffsetOfValue$1(spectrum, detail, value2, minEdge, maxEdge);
- return getMinXBounds(spectrum) - getMinXBounds(slider) + offset2;
- };
- var setPositionFromValue$2 = function(slider, thumb, detail, edges) {
- var value2 = currentValue(detail);
- var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value2.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
- var thumbRadius = get$a(thumb.element) / 2;
- set$7(thumb.element, "left", pos - thumbRadius + "px");
- };
- var onLeft$2 = handleMovement$2(-1);
- var onRight$2 = handleMovement$2(1);
- var onUp$2 = Optional.none;
- var onDown$2 = Optional.none;
- var edgeActions$2 = {
- "top-left": Optional.none(),
- "top": Optional.none(),
- "top-right": Optional.none(),
- "right": Optional.some(setToREdge),
- "bottom-right": Optional.none(),
- "bottom": Optional.none(),
- "bottom-left": Optional.none(),
- "left": Optional.some(setToLEdge)
- };
- var HorizontalModel = Object.freeze({
- __proto__: null,
- setValueFrom: setValueFrom$2,
- setToMin: setToMin$2,
- setToMax: setToMax$2,
- findValueOfOffset: findValueOfOffset$1,
- getValueFromEvent: getValueFromEvent$2,
- findPositionOfValue: findPositionOfValue$1,
- setPositionFromValue: setPositionFromValue$2,
- onLeft: onLeft$2,
- onRight: onRight$2,
- onUp: onUp$2,
- onDown: onDown$2,
- edgeActions: edgeActions$2
- });
- var fireSliderChange$1 = function(spectrum, value2) {
- emitWith(spectrum, sliderChangeEvent(), { value: value2 });
- };
- var sliderValue$1 = function(y) {
- return { y };
- };
- var findValueOfOffset = function(spectrum, detail, top2) {
- var args = {
- min: minY(detail),
- max: maxY(detail),
- range: yRange(detail),
- value: top2,
- step: step(detail),
- snap: snap(detail),
- snapStart: snapStart(detail),
- rounded: rounded(detail),
- hasMinEdge: hasTEdge(detail),
- hasMaxEdge: hasBEdge(detail),
- minBound: getMinYBounds(spectrum),
- maxBound: getMaxYBounds(spectrum),
- screenRange: getYScreenRange(spectrum)
- };
- return findValueOf(args);
- };
- var setValueFrom$1 = function(spectrum, detail, value2) {
- var yValue2 = findValueOfOffset(spectrum, detail, value2);
- var sliderVal = sliderValue$1(yValue2);
- fireSliderChange$1(spectrum, sliderVal);
- return yValue2;
- };
- var setToMin$1 = function(spectrum, detail) {
- var min2 = minY(detail);
- fireSliderChange$1(spectrum, sliderValue$1(min2));
- };
- var setToMax$1 = function(spectrum, detail) {
- var max2 = maxY(detail);
- fireSliderChange$1(spectrum, sliderValue$1(max2));
- };
- var moveBy$1 = function(direction, spectrum, detail) {
- var f = direction > 0 ? increaseBy : reduceBy;
- var yValue2 = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
- fireSliderChange$1(spectrum, sliderValue$1(yValue2));
- return Optional.some(yValue2);
- };
- var handleMovement$1 = function(direction) {
- return function(spectrum, detail) {
- return moveBy$1(direction, spectrum, detail).map(always);
- };
- };
- var getValueFromEvent$1 = function(simulatedEvent) {
- var pos = getEventSource(simulatedEvent);
- return pos.map(function(p) {
- return p.top;
- });
- };
- var findOffsetOfValue = function(spectrum, detail, value2, minEdge, maxEdge) {
- var minOffset = 0;
- var maxOffset = getYScreenRange(spectrum);
- var centerMinEdge = minEdge.bind(function(edge2) {
- return Optional.some(getYCenterOffSetOf(edge2, spectrum));
- }).getOr(minOffset);
- var centerMaxEdge = maxEdge.bind(function(edge2) {
- return Optional.some(getYCenterOffSetOf(edge2, spectrum));
- }).getOr(maxOffset);
- var args = {
- min: minY(detail),
- max: maxY(detail),
- range: yRange(detail),
- value: value2,
- hasMinEdge: hasTEdge(detail),
- hasMaxEdge: hasBEdge(detail),
- minBound: getMinYBounds(spectrum),
- minOffset,
- maxBound: getMaxYBounds(spectrum),
- maxOffset,
- centerMinEdge,
- centerMaxEdge
- };
- return findOffsetOfValue$2(args);
- };
- var findPositionOfValue = function(slider, spectrum, value2, minEdge, maxEdge, detail) {
- var offset2 = findOffsetOfValue(spectrum, detail, value2, minEdge, maxEdge);
- return getMinYBounds(spectrum) - getMinYBounds(slider) + offset2;
- };
- var setPositionFromValue$1 = function(slider, thumb, detail, edges) {
- var value2 = currentValue(detail);
- var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value2.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
- var thumbRadius = get$b(thumb.element) / 2;
- set$7(thumb.element, "top", pos - thumbRadius + "px");
- };
- var onLeft$1 = Optional.none;
- var onRight$1 = Optional.none;
- var onUp$1 = handleMovement$1(-1);
- var onDown$1 = handleMovement$1(1);
- var edgeActions$1 = {
- "top-left": Optional.none(),
- "top": Optional.some(setToTEdge),
- "top-right": Optional.none(),
- "right": Optional.none(),
- "bottom-right": Optional.none(),
- "bottom": Optional.some(setToBEdge),
- "bottom-left": Optional.none(),
- "left": Optional.none()
- };
- var VerticalModel = Object.freeze({
- __proto__: null,
- setValueFrom: setValueFrom$1,
- setToMin: setToMin$1,
- setToMax: setToMax$1,
- findValueOfOffset,
- getValueFromEvent: getValueFromEvent$1,
- findPositionOfValue,
- setPositionFromValue: setPositionFromValue$1,
- onLeft: onLeft$1,
- onRight: onRight$1,
- onUp: onUp$1,
- onDown: onDown$1,
- edgeActions: edgeActions$1
- });
- var fireSliderChange = function(spectrum, value2) {
- emitWith(spectrum, sliderChangeEvent(), { value: value2 });
- };
- var sliderValue = function(x, y) {
- return {
- x,
- y
- };
- };
- var setValueFrom = function(spectrum, detail, value2) {
- var xValue2 = findValueOfOffset$1(spectrum, detail, value2.left);
- var yValue2 = findValueOfOffset(spectrum, detail, value2.top);
- var val = sliderValue(xValue2, yValue2);
- fireSliderChange(spectrum, val);
- return val;
- };
- var moveBy = function(direction, isVerticalMovement, spectrum, detail) {
- var f = direction > 0 ? increaseBy : reduceBy;
- var xValue2 = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
- var yValue2 = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
- fireSliderChange(spectrum, sliderValue(xValue2, yValue2));
- return Optional.some(xValue2);
- };
- var handleMovement = function(direction, isVerticalMovement) {
- return function(spectrum, detail) {
- return moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
- };
- };
- var setToMin = function(spectrum, detail) {
- var mX = minX(detail);
- var mY = minY(detail);
- fireSliderChange(spectrum, sliderValue(mX, mY));
- };
- var setToMax = function(spectrum, detail) {
- var mX = maxX(detail);
- var mY = maxY(detail);
- fireSliderChange(spectrum, sliderValue(mX, mY));
- };
- var getValueFromEvent = function(simulatedEvent) {
- return getEventSource(simulatedEvent);
- };
- var setPositionFromValue = function(slider, thumb, detail, edges) {
- var value2 = currentValue(detail);
- var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value2.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
- var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value2.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
- var thumbXRadius = get$a(thumb.element) / 2;
- var thumbYRadius = get$b(thumb.element) / 2;
- set$7(thumb.element, "left", xPos - thumbXRadius + "px");
- set$7(thumb.element, "top", yPos - thumbYRadius + "px");
- };
- var onLeft = handleMovement(-1, false);
- var onRight = handleMovement(1, false);
- var onUp = handleMovement(-1, true);
- var onDown = handleMovement(1, true);
- var edgeActions = {
- "top-left": Optional.some(setToTLEdgeXY),
- "top": Optional.some(setToTEdgeXY),
- "top-right": Optional.some(setToTREdgeXY),
- "right": Optional.some(setToREdgeXY),
- "bottom-right": Optional.some(setToBREdgeXY),
- "bottom": Optional.some(setToBEdgeXY),
- "bottom-left": Optional.some(setToBLEdgeXY),
- "left": Optional.some(setToLEdgeXY)
- };
- var TwoDModel = Object.freeze({
- __proto__: null,
- setValueFrom,
- setToMin,
- setToMax,
- getValueFromEvent,
- setPositionFromValue,
- onLeft,
- onRight,
- onUp,
- onDown,
- edgeActions
- });
- var SliderSchema = [
- defaulted("stepSize", 1),
- defaulted("onChange", noop),
- defaulted("onChoose", noop),
- defaulted("onInit", noop),
- defaulted("onDragStart", noop),
- defaulted("onDragEnd", noop),
- defaulted("snapToGrid", false),
- defaulted("rounded", true),
- option("snapStart"),
- requiredOf("model", choose$1("mode", {
- x: [
- defaulted("minX", 0),
- defaulted("maxX", 100),
- customField("value", function(spec) {
- return Cell(spec.mode.minX);
- }),
- required$1("getInitialValue"),
- output$1("manager", HorizontalModel)
- ],
- y: [
- defaulted("minY", 0),
- defaulted("maxY", 100),
- customField("value", function(spec) {
- return Cell(spec.mode.minY);
- }),
- required$1("getInitialValue"),
- output$1("manager", VerticalModel)
- ],
- xy: [
- defaulted("minX", 0),
- defaulted("maxX", 100),
- defaulted("minY", 0),
- defaulted("maxY", 100),
- customField("value", function(spec) {
- return Cell({
- x: spec.mode.minX,
- y: spec.mode.minY
- });
- }),
- required$1("getInitialValue"),
- output$1("manager", TwoDModel)
- ]
- })),
- field("sliderBehaviours", [
- Keying,
- Representing
- ]),
- customField("mouseIsDown", function() {
- return Cell(false);
- })
- ];
- var sketch$2 = function(detail, components2, _spec, _externals) {
- var _a2;
- var getThumb = function(component) {
- return getPartOrDie(component, detail, "thumb");
- };
- var getSpectrum = function(component) {
- return getPartOrDie(component, detail, "spectrum");
- };
- var getLeftEdge = function(component) {
- return getPart(component, detail, "left-edge");
- };
- var getRightEdge = function(component) {
- return getPart(component, detail, "right-edge");
- };
- var getTopEdge = function(component) {
- return getPart(component, detail, "top-edge");
- };
- var getBottomEdge = function(component) {
- return getPart(component, detail, "bottom-edge");
- };
- var modelDetail = detail.model;
- var model = modelDetail.manager;
- var refresh2 = function(slider, thumb) {
- model.setPositionFromValue(slider, thumb, detail, {
- getLeftEdge,
- getRightEdge,
- getTopEdge,
- getBottomEdge,
- getSpectrum
- });
- };
- var setValue2 = function(slider, newValue) {
- modelDetail.value.set(newValue);
- var thumb = getThumb(slider);
- refresh2(slider, thumb);
- };
- var changeValue = function(slider, newValue) {
- setValue2(slider, newValue);
- var thumb = getThumb(slider);
- detail.onChange(slider, thumb, newValue);
- return Optional.some(true);
- };
- var resetToMin = function(slider) {
- model.setToMin(slider, detail);
- };
- var resetToMax = function(slider) {
- model.setToMax(slider, detail);
- };
- var choose2 = function(slider) {
- var fireOnChoose = function() {
- getPart(slider, detail, "thumb").each(function(thumb) {
- var value2 = modelDetail.value.get();
- detail.onChoose(slider, thumb, value2);
- });
- };
- var wasDown = detail.mouseIsDown.get();
- detail.mouseIsDown.set(false);
- if (wasDown) {
- fireOnChoose();
- }
- };
- var onDragStart = function(slider, simulatedEvent) {
- simulatedEvent.stop();
- detail.mouseIsDown.set(true);
- detail.onDragStart(slider, getThumb(slider));
- };
- var onDragEnd = function(slider, simulatedEvent) {
- simulatedEvent.stop();
- detail.onDragEnd(slider, getThumb(slider));
- choose2(slider);
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: augment(detail.sliderBehaviours, [
- Keying.config({
- mode: "special",
- focusIn: function(slider) {
- return getPart(slider, detail, "spectrum").map(Keying.focusIn).map(always);
- }
- }),
- Representing.config({
- store: {
- mode: "manual",
- getValue: function(_) {
- return modelDetail.value.get();
- }
- }
- }),
- Receiving.config({ channels: (_a2 = {}, _a2[mouseReleased()] = { onReceive: choose2 }, _a2) })
- ]),
- events: derive$2([
- run$1(sliderChangeEvent(), function(slider, simulatedEvent) {
- changeValue(slider, simulatedEvent.event.value);
- }),
- runOnAttached(function(slider, _simulatedEvent) {
- var getInitial = modelDetail.getInitialValue();
- modelDetail.value.set(getInitial);
- var thumb = getThumb(slider);
- refresh2(slider, thumb);
- var spectrum = getSpectrum(slider);
- detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
- }),
- run$1(touchstart(), onDragStart),
- run$1(touchend(), onDragEnd),
- run$1(mousedown(), onDragStart),
- run$1(mouseup(), onDragEnd)
- ]),
- apis: {
- resetToMin,
- resetToMax,
- setValue: setValue2,
- refresh: refresh2
- },
- domModification: { styles: { position: "relative" } }
- };
- };
- var Slider = composite({
- name: "Slider",
- configFields: SliderSchema,
- partFields: SliderParts,
- factory: sketch$2,
- apis: {
- setValue: function(apis, slider, value2) {
- apis.setValue(slider, value2);
- },
- resetToMin: function(apis, slider) {
- apis.resetToMin(slider);
- },
- resetToMax: function(apis, slider) {
- apis.resetToMax(slider);
- },
- refresh: function(apis, slider) {
- apis.refresh(slider);
- }
- }
- });
- var fieldsUpdate = generate$6("rgb-hex-update");
- var sliderUpdate = generate$6("slider-update");
- var paletteUpdate = generate$6("palette-update");
- var sliderFactory = function(translate2, getClass) {
- var spectrum = Slider.parts.spectrum({
- dom: {
- tag: "div",
- classes: [getClass("hue-slider-spectrum")],
- attributes: { role: "presentation" }
- }
- });
- var thumb = Slider.parts.thumb({
- dom: {
- tag: "div",
- classes: [getClass("hue-slider-thumb")],
- attributes: { role: "presentation" }
- }
- });
- return Slider.sketch({
- dom: {
- tag: "div",
- classes: [getClass("hue-slider")],
- attributes: { role: "presentation" }
- },
- rounded: false,
- model: {
- mode: "y",
- getInitialValue: constant$1({ y: 0 })
- },
- components: [
- spectrum,
- thumb
- ],
- sliderBehaviours: derive$1([Focusing.config({})]),
- onChange: function(slider, _thumb, value2) {
- emitWith(slider, sliderUpdate, { value: value2 });
- }
- });
- };
- var owner$1 = "form";
- var schema$i = [field("formBehaviours", [Representing])];
- var getPartName$1 = function(name2) {
- return "<alloy.field." + name2 + ">";
- };
- var sketch$1 = function(fSpec) {
- var parts2 = function() {
- var record2 = [];
- var field2 = function(name2, config2) {
- record2.push(name2);
- return generateOne$1(owner$1, getPartName$1(name2), config2);
- };
- return {
- field: field2,
- record: constant$1(record2)
- };
- }();
- var spec = fSpec(parts2);
- var partNames = parts2.record();
- var fieldParts = map$2(partNames, function(n) {
- return required({
- name: n,
- pname: getPartName$1(n)
- });
- });
- return composite$1(owner$1, schema$i, fieldParts, make$4, spec);
- };
- var toResult = function(o, e) {
- return o.fold(function() {
- return Result.error(e);
- }, Result.value);
- };
- var make$4 = function(detail, components2) {
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: augment(detail.formBehaviours, [Representing.config({
- store: {
- mode: "manual",
- getValue: function(form) {
- var resPs = getAllParts(form, detail);
- return map$1(resPs, function(resPThunk, pName) {
- return resPThunk().bind(function(v) {
- var opt = Composing.getCurrent(v);
- return toResult(opt, new Error("Cannot find a current component to extract the value from for form part '" + pName + "': " + element(v.element)));
- }).map(Representing.getValue);
- });
- },
- setValue: function(form, values2) {
- each(values2, function(newValue, key) {
- getPart(form, detail, key).each(function(wrapper) {
- Composing.getCurrent(wrapper).each(function(field2) {
- Representing.setValue(field2, newValue);
- });
- });
- });
- }
- }
- })]),
- apis: {
- getField: function(form, key) {
- return getPart(form, detail, key).bind(Composing.getCurrent);
- }
- }
- };
- };
- var Form = {
- getField: makeApi(function(apis, component, key) {
- return apis.getField(component, key);
- }),
- sketch: sketch$1
- };
- var validInput = generate$6("valid-input");
- var invalidInput = generate$6("invalid-input");
- var validatingInput = generate$6("validating-input");
- var translatePrefix = "colorcustom.rgb.";
- var rgbFormFactory = function(translate2, getClass, onValidHexx, onInvalidHexx) {
- var invalidation = function(label, isValid) {
- return Invalidating.config({
- invalidClass: getClass("invalid"),
- notify: {
- onValidate: function(comp) {
- emitWith(comp, validatingInput, { type: label });
- },
- onValid: function(comp) {
- emitWith(comp, validInput, {
- type: label,
- value: Representing.getValue(comp)
- });
- },
- onInvalid: function(comp) {
- emitWith(comp, invalidInput, {
- type: label,
- value: Representing.getValue(comp)
- });
- }
- },
- validator: {
- validate: function(comp) {
- var value2 = Representing.getValue(comp);
- var res = isValid(value2) ? Result.value(true) : Result.error(translate2("aria.input.invalid"));
- return Future.pure(res);
- },
- validateOnLoad: false
- }
- });
- };
- var renderTextField2 = function(isValid, name2, label, description, data) {
- var helptext = translate2(translatePrefix + "range");
- var pLabel = FormField.parts.label({
- dom: {
- tag: "label",
- innerHtml: label,
- attributes: { "aria-label": description }
- }
- });
- var pField = FormField.parts.field({
- data,
- factory: Input,
- inputAttributes: __assign({ type: "text" }, name2 === "hex" ? { "aria-live": "polite" } : {}),
- inputClasses: [getClass("textfield")],
- inputBehaviours: derive$1([
- invalidation(name2, isValid),
- Tabstopping.config({})
- ]),
- onSetValue: function(input2) {
- if (Invalidating.isInvalid(input2)) {
- var run2 = Invalidating.run(input2);
- run2.get(noop);
- }
- }
- });
- var comps = [
- pLabel,
- pField
- ];
- var concats = name2 !== "hex" ? [FormField.parts["aria-descriptor"]({ text: helptext })] : [];
- var components2 = comps.concat(concats);
- return {
- dom: {
- tag: "div",
- attributes: { role: "presentation" }
- },
- components: components2
- };
- };
- var copyRgbToHex = function(form, rgba) {
- var hex = fromRgba(rgba);
- Form.getField(form, "hex").each(function(hexField) {
- if (!Focusing.isFocused(hexField)) {
- Representing.setValue(form, { hex: hex.value });
- }
- });
- return hex;
- };
- var copyRgbToForm = function(form, rgb) {
- var red2 = rgb.red;
- var green = rgb.green;
- var blue = rgb.blue;
- Representing.setValue(form, {
- red: red2,
- green,
- blue
- });
- };
- var memPreview = record({
- dom: {
- tag: "div",
- classes: [getClass("rgba-preview")],
- styles: { "background-color": "white" },
- attributes: { role: "presentation" }
- }
- });
- var updatePreview = function(anyInSystem, hex) {
- memPreview.getOpt(anyInSystem).each(function(preview) {
- set$7(preview.element, "background-color", "#" + hex.value);
- });
- };
- var factory2 = function() {
- var state = {
- red: Cell(Optional.some(255)),
- green: Cell(Optional.some(255)),
- blue: Cell(Optional.some(255)),
- hex: Cell(Optional.some("ffffff"))
- };
- var copyHexToRgb = function(form, hex) {
- var rgb = fromHex(hex);
- copyRgbToForm(form, rgb);
- setValueRgb(rgb);
- };
- var get2 = function(prop) {
- return state[prop].get();
- };
- var set2 = function(prop, value2) {
- state[prop].set(value2);
- };
- var getValueRgb = function() {
- return get2("red").bind(function(red2) {
- return get2("green").bind(function(green) {
- return get2("blue").map(function(blue) {
- return rgbaColour(red2, green, blue, 1);
- });
- });
- });
- };
- var setValueRgb = function(rgb) {
- var red2 = rgb.red;
- var green = rgb.green;
- var blue = rgb.blue;
- set2("red", Optional.some(red2));
- set2("green", Optional.some(green));
- set2("blue", Optional.some(blue));
- };
- var onInvalidInput = function(form, simulatedEvent) {
- var data = simulatedEvent.event;
- if (data.type !== "hex") {
- set2(data.type, Optional.none());
- } else {
- onInvalidHexx(form);
- }
- };
- var onValidHex = function(form, value2) {
- onValidHexx(form);
- var hex = hexColour(value2);
- set2("hex", Optional.some(value2));
- var rgb = fromHex(hex);
- copyRgbToForm(form, rgb);
- setValueRgb(rgb);
- emitWith(form, fieldsUpdate, { hex });
- updatePreview(form, hex);
- };
- var onValidRgb = function(form, prop, value2) {
- var val = parseInt(value2, 10);
- set2(prop, Optional.some(val));
- getValueRgb().each(function(rgb) {
- var hex = copyRgbToHex(form, rgb);
- emitWith(form, fieldsUpdate, { hex });
- updatePreview(form, hex);
- });
- };
- var isHexInputEvent = function(data) {
- return data.type === "hex";
- };
- var onValidInput = function(form, simulatedEvent) {
- var data = simulatedEvent.event;
- if (isHexInputEvent(data)) {
- onValidHex(form, data.value);
- } else {
- onValidRgb(form, data.type, data.value);
- }
- };
- var formPartStrings = function(key) {
- return {
- label: translate2(translatePrefix + key + ".label"),
- description: translate2(translatePrefix + key + ".description")
- };
- };
- var redStrings = formPartStrings("red");
- var greenStrings = formPartStrings("green");
- var blueStrings = formPartStrings("blue");
- var hexStrings = formPartStrings("hex");
- return deepMerge(Form.sketch(function(parts2) {
- return {
- dom: {
- tag: "form",
- classes: [getClass("rgb-form")],
- attributes: { "aria-label": translate2("aria.color.picker") }
- },
- components: [
- parts2.field("red", FormField.sketch(renderTextField2(isRgbaComponent, "red", redStrings.label, redStrings.description, 255))),
- parts2.field("green", FormField.sketch(renderTextField2(isRgbaComponent, "green", greenStrings.label, greenStrings.description, 255))),
- parts2.field("blue", FormField.sketch(renderTextField2(isRgbaComponent, "blue", blueStrings.label, blueStrings.description, 255))),
- parts2.field("hex", FormField.sketch(renderTextField2(isHexString, "hex", hexStrings.label, hexStrings.description, "ffffff"))),
- memPreview.asSpec()
- ],
- formBehaviours: derive$1([
- Invalidating.config({ invalidClass: getClass("form-invalid") }),
- config("rgb-form-events", [
- run$1(validInput, onValidInput),
- run$1(invalidInput, onInvalidInput),
- run$1(validatingInput, onInvalidInput)
- ])
- ])
- };
- }), {
- apis: {
- updateHex: function(form, hex) {
- Representing.setValue(form, { hex: hex.value });
- copyHexToRgb(form, hex);
- updatePreview(form, hex);
- }
- }
- });
- };
- var rgbFormSketcher = single({
- factory: factory2,
- name: "RgbForm",
- configFields: [],
- apis: {
- updateHex: function(apis, form, hex) {
- apis.updateHex(form, hex);
- }
- },
- extraApis: {}
- });
- return rgbFormSketcher;
- };
- var paletteFactory = function(_translate, getClass) {
- var spectrumPart2 = Slider.parts.spectrum({
- dom: {
- tag: "canvas",
- attributes: { role: "presentation" },
- classes: [getClass("sv-palette-spectrum")]
- }
- });
- var thumbPart2 = Slider.parts.thumb({
- dom: {
- tag: "div",
- attributes: { role: "presentation" },
- classes: [getClass("sv-palette-thumb")],
- innerHtml: "<div class=" + getClass("sv-palette-inner-thumb") + ' role="presentation"></div>'
- }
- });
- var setColour = function(canvas, rgba) {
- var width2 = canvas.width, height2 = canvas.height;
- var ctx = canvas.getContext("2d");
- if (ctx === null) {
- return;
- }
- ctx.fillStyle = rgba;
- ctx.fillRect(0, 0, width2, height2);
- var grdWhite = ctx.createLinearGradient(0, 0, width2, 0);
- grdWhite.addColorStop(0, "rgba(255,255,255,1)");
- grdWhite.addColorStop(1, "rgba(255,255,255,0)");
- ctx.fillStyle = grdWhite;
- ctx.fillRect(0, 0, width2, height2);
- var grdBlack = ctx.createLinearGradient(0, 0, 0, height2);
- grdBlack.addColorStop(0, "rgba(0,0,0,0)");
- grdBlack.addColorStop(1, "rgba(0,0,0,1)");
- ctx.fillStyle = grdBlack;
- ctx.fillRect(0, 0, width2, height2);
- };
- var setPaletteHue = function(slider, hue) {
- var canvas = slider.components()[0].element.dom;
- var hsv = hsvColour(hue, 100, 100);
- var rgba = fromHsv(hsv);
- setColour(canvas, toString(rgba));
- };
- var setPaletteThumb = function(slider, hex) {
- var hsv = fromRgb(fromHex(hex));
- Slider.setValue(slider, {
- x: hsv.saturation,
- y: 100 - hsv.value
- });
- };
- var factory2 = function(_detail) {
- var getInitialValue = constant$1({
- x: 0,
- y: 0
- });
- var onChange = function(slider, _thumb, value2) {
- emitWith(slider, paletteUpdate, { value: value2 });
- };
- var onInit = function(_slider, _thumb, spectrum, _value) {
- setColour(spectrum.element.dom, toString(red));
- };
- var sliderBehaviours = derive$1([
- Composing.config({ find: Optional.some }),
- Focusing.config({})
- ]);
- return Slider.sketch({
- dom: {
- tag: "div",
- attributes: { role: "presentation" },
- classes: [getClass("sv-palette")]
- },
- model: {
- mode: "xy",
- getInitialValue
- },
- rounded: false,
- components: [
- spectrumPart2,
- thumbPart2
- ],
- onChange,
- onInit,
- sliderBehaviours
- });
- };
- var saturationBrightnessPaletteSketcher = single({
- factory: factory2,
- name: "SaturationBrightnessPalette",
- configFields: [],
- apis: {
- setHue: function(_apis, slider, hue) {
- setPaletteHue(slider, hue);
- },
- setThumb: function(_apis, slider, hex) {
- setPaletteThumb(slider, hex);
- }
- },
- extraApis: {}
- });
- return saturationBrightnessPaletteSketcher;
- };
- var makeFactory = function(translate2, getClass) {
- var factory2 = function(detail) {
- var rgbForm = rgbFormFactory(translate2, getClass, detail.onValidHex, detail.onInvalidHex);
- var sbPalette = paletteFactory(translate2, getClass);
- var hueSliderToDegrees = function(hue) {
- return (100 - hue) / 100 * 360;
- };
- var hueDegreesToSlider = function(hue) {
- return 100 - hue / 360 * 100;
- };
- var state = {
- paletteRgba: Cell(red),
- paletteHue: Cell(0)
- };
- var memSlider = record(sliderFactory(translate2, getClass));
- var memPalette = record(sbPalette.sketch({}));
- var memRgb = record(rgbForm.sketch({}));
- var updatePalette = function(anyInSystem, _hex, hue) {
- memPalette.getOpt(anyInSystem).each(function(palette) {
- sbPalette.setHue(palette, hue);
- });
- };
- var updateFields = function(anyInSystem, hex) {
- memRgb.getOpt(anyInSystem).each(function(form) {
- rgbForm.updateHex(form, hex);
- });
- };
- var updateSlider = function(anyInSystem, _hex, hue) {
- memSlider.getOpt(anyInSystem).each(function(slider) {
- Slider.setValue(slider, { y: hueDegreesToSlider(hue) });
- });
- };
- var updatePaletteThumb = function(anyInSystem, hex) {
- memPalette.getOpt(anyInSystem).each(function(palette) {
- sbPalette.setThumb(palette, hex);
- });
- };
- var updateState = function(hex, hue) {
- var rgba = fromHex(hex);
- state.paletteRgba.set(rgba);
- state.paletteHue.set(hue);
- };
- var runUpdates = function(anyInSystem, hex, hue, updates) {
- updateState(hex, hue);
- each$1(updates, function(update) {
- update(anyInSystem, hex, hue);
- });
- };
- var onPaletteUpdate = function() {
- var updates = [updateFields];
- return function(form, simulatedEvent) {
- var value2 = simulatedEvent.event.value;
- var oldHue = state.paletteHue.get();
- var newHsv = hsvColour(oldHue, value2.x, 100 - value2.y);
- var newHex = hsvToHex(newHsv);
- runUpdates(form, newHex, oldHue, updates);
- };
- };
- var onSliderUpdate = function() {
- var updates = [
- updatePalette,
- updateFields
- ];
- return function(form, simulatedEvent) {
- var hue = hueSliderToDegrees(simulatedEvent.event.value.y);
- var oldRgb = state.paletteRgba.get();
- var oldHsv = fromRgb(oldRgb);
- var newHsv = hsvColour(hue, oldHsv.saturation, oldHsv.value);
- var newHex = hsvToHex(newHsv);
- runUpdates(form, newHex, hue, updates);
- };
- };
- var onFieldsUpdate = function() {
- var updates = [
- updatePalette,
- updateSlider,
- updatePaletteThumb
- ];
- return function(form, simulatedEvent) {
- var hex = simulatedEvent.event.hex;
- var hsv = hexToHsv(hex);
- runUpdates(form, hex, hsv.hue, updates);
- };
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: [
- memPalette.asSpec(),
- memSlider.asSpec(),
- memRgb.asSpec()
- ],
- behaviours: derive$1([
- config("colour-picker-events", [
- run$1(fieldsUpdate, onFieldsUpdate()),
- run$1(paletteUpdate, onPaletteUpdate()),
- run$1(sliderUpdate, onSliderUpdate())
- ]),
- Composing.config({
- find: function(comp) {
- return memRgb.getOpt(comp);
- }
- }),
- Keying.config({ mode: "acyclic" })
- ])
- };
- };
- var colourPickerSketcher = single({
- name: "ColourPicker",
- configFields: [
- required$1("dom"),
- defaulted("onValidHex", noop),
- defaulted("onInvalidHex", noop)
- ],
- factory: factory2
- });
- return colourPickerSketcher;
- };
- var self$1 = function() {
- return Composing.config({ find: Optional.some });
- };
- var memento$1 = function(mem) {
- return Composing.config({ find: mem.getOpt });
- };
- var childAt = function(index) {
- return Composing.config({
- find: function(comp) {
- return child$2(comp.element, index).bind(function(element2) {
- return comp.getSystem().getByDom(element2).toOptional();
- });
- }
- });
- };
- var ComposingConfigs = {
- self: self$1,
- memento: memento$1,
- childAt
- };
- var english = {
- "colorcustom.rgb.red.label": "R",
- "colorcustom.rgb.red.description": "Red component",
- "colorcustom.rgb.green.label": "G",
- "colorcustom.rgb.green.description": "Green component",
- "colorcustom.rgb.blue.label": "B",
- "colorcustom.rgb.blue.description": "Blue component",
- "colorcustom.rgb.hex.label": "#",
- "colorcustom.rgb.hex.description": "Hex color code",
- "colorcustom.rgb.range": "Range 0 to 255",
- "colorcustom.sb.saturation": "Saturation",
- "colorcustom.sb.brightness": "Brightness",
- "colorcustom.sb.picker": "Saturation and Brightness Picker",
- "colorcustom.sb.palette": "Saturation and Brightness Palette",
- "colorcustom.sb.instructions": "Use arrow keys to select saturation and brightness, on x and y axes",
- "colorcustom.hue.hue": "Hue",
- "colorcustom.hue.slider": "Hue Slider",
- "colorcustom.hue.palette": "Hue Palette",
- "colorcustom.hue.instructions": "Use arrow keys to select a hue",
- "aria.color.picker": "Color Picker",
- "aria.input.invalid": "Invalid input"
- };
- var getEnglishText = function(key) {
- return english[key];
- };
- var translate$1 = function(key) {
- return getEnglishText(key);
- };
- var renderColorPicker = function(_spec) {
- var getClass = function(key) {
- return "tox-" + key;
- };
- var colourPickerFactory = makeFactory(translate$1, getClass);
- var onValidHex = function(form) {
- emitWith(form, formActionEvent, {
- name: "hex-valid",
- value: true
- });
- };
- var onInvalidHex = function(form) {
- emitWith(form, formActionEvent, {
- name: "hex-valid",
- value: false
- });
- };
- var memPicker = record(colourPickerFactory.sketch({
- dom: {
- tag: "div",
- classes: [getClass("color-picker-container")],
- attributes: { role: "presentation" }
- },
- onValidHex,
- onInvalidHex
- }));
- return {
- dom: { tag: "div" },
- components: [memPicker.asSpec()],
- behaviours: derive$1([
- Representing.config({
- store: {
- mode: "manual",
- getValue: function(comp) {
- var picker = memPicker.get(comp);
- var optRgbForm = Composing.getCurrent(picker);
- var optHex = optRgbForm.bind(function(rgbForm) {
- var formValues = Representing.getValue(rgbForm);
- return formValues.hex;
- });
- return optHex.map(function(hex) {
- return "#" + hex;
- }).getOr("");
- },
- setValue: function(comp, newValue) {
- var pattern2 = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
- var m = pattern2.exec(newValue);
- var picker = memPicker.get(comp);
- var optRgbForm = Composing.getCurrent(picker);
- optRgbForm.fold(function() {
- console.log("Can not find form");
- }, function(rgbForm) {
- Representing.setValue(rgbForm, { hex: Optional.from(m[1]).getOr("") });
- Form.getField(rgbForm, "hex").each(function(hexField) {
- emit(hexField, input());
- });
- });
- }
- }
- }),
- ComposingConfigs.self()
- ])
- };
- };
- var global$6 = tinymce.util.Tools.resolve("tinymce.Resource");
- var isOldCustomEditor = function(spec) {
- return has$2(spec, "init");
- };
- var renderCustomEditor = function(spec) {
- var editorApi = value$1();
- var memReplaced = record({ dom: { tag: spec.tag } });
- var initialValue = value$1();
- return {
- dom: {
- tag: "div",
- classes: ["tox-custom-editor"]
- },
- behaviours: derive$1([
- config("custom-editor-events", [runOnAttached(function(component) {
- memReplaced.getOpt(component).each(function(ta) {
- (isOldCustomEditor(spec) ? spec.init(ta.element.dom) : global$6.load(spec.scriptId, spec.scriptUrl).then(function(init2) {
- return init2(ta.element.dom, spec.settings);
- })).then(function(ea) {
- initialValue.on(function(cvalue) {
- ea.setValue(cvalue);
- });
- initialValue.clear();
- editorApi.set(ea);
- });
- });
- })]),
- Representing.config({
- store: {
- mode: "manual",
- getValue: function() {
- return editorApi.get().fold(function() {
- return initialValue.get().getOr("");
- }, function(ed) {
- return ed.getValue();
- });
- },
- setValue: function(component, value2) {
- editorApi.get().fold(function() {
- initialValue.set(value2);
- }, function(ed) {
- return ed.setValue(value2);
- });
- }
- }
- }),
- ComposingConfigs.self()
- ]),
- components: [memReplaced.asSpec()]
- };
- };
- var global$5 = tinymce.util.Tools.resolve("tinymce.util.Tools");
- var processors = objOf([
- defaulted("preprocess", identity$1),
- defaulted("postprocess", identity$1)
- ]);
- var memento = function(mem, rawProcessors) {
- var ps = asRawOrDie$1("RepresentingConfigs.memento processors", processors, rawProcessors);
- return Representing.config({
- store: {
- mode: "manual",
- getValue: function(comp) {
- var other = mem.get(comp);
- var rawValue = Representing.getValue(other);
- return ps.postprocess(rawValue);
- },
- setValue: function(comp, rawValue) {
- var newValue = ps.preprocess(rawValue);
- var other = mem.get(comp);
- Representing.setValue(other, newValue);
- }
- }
- });
- };
- var withComp = function(optInitialValue, getter, setter) {
- return Representing.config(deepMerge({
- store: {
- mode: "manual",
- getValue: getter,
- setValue: setter
- }
- }, optInitialValue.map(function(initialValue) {
- return { store: { initialValue } };
- }).getOr({})));
- };
- var withElement = function(initialValue, getter, setter) {
- return withComp(initialValue, function(c) {
- return getter(c.element);
- }, function(c, v) {
- return setter(c.element, v);
- });
- };
- var domValue = function(optInitialValue) {
- return withElement(optInitialValue, get$5, set$4);
- };
- var domHtml = function(optInitialValue) {
- return withElement(optInitialValue, get$7, set$5);
- };
- var memory = function(initialValue) {
- return Representing.config({
- store: {
- mode: "memory",
- initialValue
- }
- });
- };
- var RepresentingConfigs = {
- memento,
- withElement,
- withComp,
- domValue,
- domHtml,
- memory
- };
- var defaultImageFileTypes = "jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp";
- var filterByExtension = function(files, providersBackstage) {
- var allowedImageFileTypes = global$5.explode(providersBackstage.getSetting("images_file_types", defaultImageFileTypes, "string"));
- var isFileInAllowedTypes = function(file) {
- return exists(allowedImageFileTypes, function(type2) {
- return endsWith(file.name.toLowerCase(), "." + type2.toLowerCase());
- });
- };
- return filter$2(from(files), isFileInAllowedTypes);
- };
- var renderDropZone = function(spec, providersBackstage) {
- var stopper2 = function(_, se) {
- se.stop();
- };
- var sequence2 = function(actions) {
- return function(comp, se) {
- each$1(actions, function(a) {
- a(comp, se);
- });
- };
- };
- var onDrop = function(comp, se) {
- if (!Disabling.isDisabled(comp)) {
- var transferEvent = se.event.raw;
- handleFiles(comp, transferEvent.dataTransfer.files);
- }
- };
- var onSelect = function(component, simulatedEvent) {
- var input2 = simulatedEvent.event.raw.target;
- handleFiles(component, input2.files);
- };
- var handleFiles = function(component, files) {
- Representing.setValue(component, filterByExtension(files, providersBackstage));
- emitWith(component, formChangeEvent, { name: spec.name });
- };
- var memInput = record({
- dom: {
- tag: "input",
- attributes: {
- type: "file",
- accept: "image/*"
- },
- styles: { display: "none" }
- },
- behaviours: derive$1([config("input-file-events", [
- cutter(click()),
- cutter(tap())
- ])])
- });
- var renderField = function(s) {
- return {
- uid: s.uid,
- dom: {
- tag: "div",
- classes: ["tox-dropzone-container"]
- },
- behaviours: derive$1([
- RepresentingConfigs.memory([]),
- ComposingConfigs.self(),
- Disabling.config({}),
- Toggling.config({
- toggleClass: "dragenter",
- toggleOnExecute: false
- }),
- config("dropzone-events", [
- run$1("dragenter", sequence2([
- stopper2,
- Toggling.toggle
- ])),
- run$1("dragleave", sequence2([
- stopper2,
- Toggling.toggle
- ])),
- run$1("dragover", stopper2),
- run$1("drop", sequence2([
- stopper2,
- onDrop
- ])),
- run$1(change(), onSelect)
- ])
- ]),
- components: [{
- dom: {
- tag: "div",
- classes: ["tox-dropzone"],
- styles: {}
- },
- components: [
- {
- dom: {
- tag: "p",
- innerHtml: providersBackstage.translate("Drop an image here")
- }
- },
- Button.sketch({
- dom: {
- tag: "button",
- innerHtml: providersBackstage.translate("Browse for an image"),
- styles: { position: "relative" },
- classes: [
- "tox-button",
- "tox-button--secondary"
- ]
- },
- components: [memInput.asSpec()],
- action: function(comp) {
- var inputComp = memInput.get(comp);
- inputComp.element.dom.click();
- },
- buttonBehaviours: derive$1([
- Tabstopping.config({}),
- DisablingConfigs.button(providersBackstage.isDisabled),
- receivingConfig()
- ])
- })
- ]
- }]
- };
- };
- var pLabel = spec.label.map(function(label) {
- return renderLabel$2(label, providersBackstage);
- });
- var pField = FormField.parts.field({ factory: { sketch: renderField } });
- return renderFormFieldWith(pLabel, pField, ["tox-form__group--stretched"], []);
- };
- var renderGrid = function(spec, backstage) {
- return {
- dom: {
- tag: "div",
- classes: [
- "tox-form__grid",
- "tox-form__grid--" + spec.columns + "col"
- ]
- },
- components: map$2(spec.items, backstage.interpreter)
- };
- };
- var beforeObject = generate$6("alloy-fake-before-tabstop");
- var afterObject = generate$6("alloy-fake-after-tabstop");
- var craftWithClasses = function(classes2) {
- return {
- dom: {
- tag: "div",
- styles: {
- width: "1px",
- height: "1px",
- outline: "none"
- },
- attributes: { tabindex: "0" },
- classes: classes2
- },
- behaviours: derive$1([
- Focusing.config({ ignore: true }),
- Tabstopping.config({})
- ])
- };
- };
- var craft = function(spec) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-navobj"]
- },
- components: [
- craftWithClasses([beforeObject]),
- spec,
- craftWithClasses([afterObject])
- ],
- behaviours: derive$1([ComposingConfigs.childAt(1)])
- };
- };
- var triggerTab = function(placeholder2, shiftKey) {
- emitWith(placeholder2, keydown(), {
- raw: {
- which: 9,
- shiftKey
- }
- });
- };
- var onFocus = function(container, targetComp) {
- var target = targetComp.element;
- if (has(target, beforeObject)) {
- triggerTab(container, true);
- } else if (has(target, afterObject)) {
- triggerTab(container, false);
- }
- };
- var isPseudoStop = function(element2) {
- return closest(element2, [
- "." + beforeObject,
- "." + afterObject
- ].join(","), never);
- };
- var platformNeedsSandboxing = !(detect$1().browser.isIE() || detect$1().browser.isEdge());
- var getDynamicSource = function(isSandbox) {
- var cachedValue = Cell("");
- return {
- getValue: function(_frameComponent) {
- return cachedValue.get();
- },
- setValue: function(frameComponent, html2) {
- if (!isSandbox) {
- set$8(frameComponent.element, "src", "javascript:''");
- var doc = frameComponent.element.dom.contentWindow.document;
- doc.open();
- doc.write(html2);
- doc.close();
- } else {
- set$8(frameComponent.element, "srcdoc", html2);
- }
- cachedValue.set(html2);
- }
- };
- };
- var renderIFrame = function(spec, providersBackstage) {
- var isSandbox = platformNeedsSandboxing && spec.sandboxed;
- var attributes = __assign(__assign({}, spec.label.map(function(title) {
- return { title };
- }).getOr({})), isSandbox ? { sandbox: "allow-scripts allow-same-origin" } : {});
- var sourcing = getDynamicSource(isSandbox);
- var pLabel = spec.label.map(function(label) {
- return renderLabel$2(label, providersBackstage);
- });
- var factory2 = function(newSpec) {
- return craft({
- uid: newSpec.uid,
- dom: {
- tag: "iframe",
- attributes
- },
- behaviours: derive$1([
- Tabstopping.config({}),
- Focusing.config({}),
- RepresentingConfigs.withComp(Optional.none(), sourcing.getValue, sourcing.setValue)
- ])
- });
- };
- var pField = FormField.parts.field({ factory: { sketch: factory2 } });
- return renderFormFieldWith(pLabel, pField, ["tox-form__group--stretched"], []);
- };
- var create$4 = function(width2, height2) {
- return resize$3(document.createElement("canvas"), width2, height2);
- };
- var clone$1 = function(canvas) {
- var tCanvas = create$4(canvas.width, canvas.height);
- var ctx = get2dContext(tCanvas);
- ctx.drawImage(canvas, 0, 0);
- return tCanvas;
- };
- var get2dContext = function(canvas) {
- return canvas.getContext("2d");
- };
- var resize$3 = function(canvas, width2, height2) {
- canvas.width = width2;
- canvas.height = height2;
- return canvas;
- };
- var getWidth$1 = function(image) {
- return image.naturalWidth || image.width;
- };
- var getHeight$1 = function(image) {
- return image.naturalHeight || image.height;
- };
- var blobToImage = function(blob) {
- return new Promise$1(function(resolve, reject) {
- var blobUrl = URL.createObjectURL(blob);
- var image = new Image();
- var removeListeners = function() {
- image.removeEventListener("load", loaded);
- image.removeEventListener("error", error2);
- };
- var loaded = function() {
- removeListeners();
- resolve(image);
- };
- var error2 = function() {
- removeListeners();
- reject("Unable to load data of type " + blob.type + ": " + blobUrl);
- };
- image.addEventListener("load", loaded);
- image.addEventListener("error", error2);
- image.src = blobUrl;
- if (image.complete) {
- setTimeout(loaded, 0);
- }
- });
- };
- var dataUriToBlobSync = function(uri) {
- var data = uri.split(",");
- var matches = /data:([^;]+)/.exec(data[0]);
- if (!matches) {
- return Optional.none();
- }
- var mimetype = matches[1];
- var base64 = data[1];
- var sliceSize = 1024;
- var byteCharacters = atob(base64);
- var bytesLength = byteCharacters.length;
- var slicesCount = Math.ceil(bytesLength / sliceSize);
- var byteArrays = new Array(slicesCount);
- for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
- var begin = sliceIndex * sliceSize;
- var end = Math.min(begin + sliceSize, bytesLength);
- var bytes = new Array(end - begin);
- for (var offset2 = begin, i = 0; offset2 < end; ++i, ++offset2) {
- bytes[i] = byteCharacters[offset2].charCodeAt(0);
- }
- byteArrays[sliceIndex] = new Uint8Array(bytes);
- }
- return Optional.some(new Blob(byteArrays, { type: mimetype }));
- };
- var dataUriToBlob = function(uri) {
- return new Promise$1(function(resolve, reject) {
- dataUriToBlobSync(uri).fold(function() {
- reject("uri is not base64: " + uri);
- }, resolve);
- });
- };
- var canvasToBlob = function(canvas, type2, quality) {
- type2 = type2 || "image/png";
- if (isFunction(HTMLCanvasElement.prototype.toBlob)) {
- return new Promise$1(function(resolve, reject) {
- canvas.toBlob(function(blob) {
- if (blob) {
- resolve(blob);
- } else {
- reject();
- }
- }, type2, quality);
- });
- } else {
- return dataUriToBlob(canvas.toDataURL(type2, quality));
- }
- };
- var canvasToDataURL = function(canvas, type2, quality) {
- type2 = type2 || "image/png";
- return canvas.toDataURL(type2, quality);
- };
- var blobToCanvas = function(blob) {
- return blobToImage(blob).then(function(image) {
- revokeImageUrl(image);
- var canvas = create$4(getWidth$1(image), getHeight$1(image));
- var context = get2dContext(canvas);
- context.drawImage(image, 0, 0);
- return canvas;
- });
- };
- var blobToDataUri = function(blob) {
- return new Promise$1(function(resolve) {
- var reader = new FileReader();
- reader.onloadend = function() {
- resolve(reader.result);
- };
- reader.readAsDataURL(blob);
- });
- };
- var revokeImageUrl = function(image) {
- URL.revokeObjectURL(image.src);
- };
- var create$3 = function(getCanvas, blob, uri) {
- var initialType = blob.type;
- var getType = constant$1(initialType);
- var toBlob = function() {
- return Promise$1.resolve(blob);
- };
- var toDataURL = constant$1(uri);
- var toBase64 = function() {
- return uri.split(",")[1];
- };
- var toAdjustedBlob = function(type2, quality) {
- return getCanvas.then(function(canvas) {
- return canvasToBlob(canvas, type2, quality);
- });
- };
- var toAdjustedDataURL = function(type2, quality) {
- return getCanvas.then(function(canvas) {
- return canvasToDataURL(canvas, type2, quality);
- });
- };
- var toAdjustedBase64 = function(type2, quality) {
- return toAdjustedDataURL(type2, quality).then(function(dataurl) {
- return dataurl.split(",")[1];
- });
- };
- var toCanvas = function() {
- return getCanvas.then(clone$1);
- };
- return {
- getType,
- toBlob,
- toDataURL,
- toBase64,
- toAdjustedBlob,
- toAdjustedDataURL,
- toAdjustedBase64,
- toCanvas
- };
- };
- var fromBlob = function(blob) {
- return blobToDataUri(blob).then(function(uri) {
- return create$3(blobToCanvas(blob), blob, uri);
- });
- };
- var fromCanvas = function(canvas, type2) {
- return canvasToBlob(canvas, type2).then(function(blob) {
- return create$3(Promise$1.resolve(canvas), blob, canvas.toDataURL());
- });
- };
- var blobToImageResult = function(blob) {
- return fromBlob(blob);
- };
- var clamp = function(value2, min2, max2) {
- var parsedValue = typeof value2 === "string" ? parseFloat(value2) : value2;
- if (parsedValue > max2) {
- parsedValue = max2;
- } else if (parsedValue < min2) {
- parsedValue = min2;
- }
- return parsedValue;
- };
- var identity = function() {
- return [
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1
- ];
- };
- var DELTA_INDEX = [
- 0,
- 0.01,
- 0.02,
- 0.04,
- 0.05,
- 0.06,
- 0.07,
- 0.08,
- 0.1,
- 0.11,
- 0.12,
- 0.14,
- 0.15,
- 0.16,
- 0.17,
- 0.18,
- 0.2,
- 0.21,
- 0.22,
- 0.24,
- 0.25,
- 0.27,
- 0.28,
- 0.3,
- 0.32,
- 0.34,
- 0.36,
- 0.38,
- 0.4,
- 0.42,
- 0.44,
- 0.46,
- 0.48,
- 0.5,
- 0.53,
- 0.56,
- 0.59,
- 0.62,
- 0.65,
- 0.68,
- 0.71,
- 0.74,
- 0.77,
- 0.8,
- 0.83,
- 0.86,
- 0.89,
- 0.92,
- 0.95,
- 0.98,
- 1,
- 1.06,
- 1.12,
- 1.18,
- 1.24,
- 1.3,
- 1.36,
- 1.42,
- 1.48,
- 1.54,
- 1.6,
- 1.66,
- 1.72,
- 1.78,
- 1.84,
- 1.9,
- 1.96,
- 2,
- 2.12,
- 2.25,
- 2.37,
- 2.5,
- 2.62,
- 2.75,
- 2.87,
- 3,
- 3.2,
- 3.4,
- 3.6,
- 3.8,
- 4,
- 4.3,
- 4.7,
- 4.9,
- 5,
- 5.5,
- 6,
- 6.5,
- 6.8,
- 7,
- 7.3,
- 7.5,
- 7.8,
- 8,
- 8.4,
- 8.7,
- 9,
- 9.4,
- 9.6,
- 9.8,
- 10
- ];
- var multiply = function(matrix1, matrix2) {
- var col = [];
- var out = new Array(25);
- var val;
- for (var i = 0; i < 5; i++) {
- for (var j = 0; j < 5; j++) {
- col[j] = matrix2[j + i * 5];
- }
- for (var j = 0; j < 5; j++) {
- val = 0;
- for (var k = 0; k < 5; k++) {
- val += matrix1[j + k * 5] * col[k];
- }
- out[j + i * 5] = val;
- }
- }
- return out;
- };
- var adjustContrast = function(matrix2, value2) {
- var x;
- value2 = clamp(value2, -1, 1);
- value2 *= 100;
- if (value2 < 0) {
- x = 127 + value2 / 100 * 127;
- } else {
- x = value2 % 1;
- if (x === 0) {
- x = DELTA_INDEX[value2];
- } else {
- x = DELTA_INDEX[Math.floor(value2)] * (1 - x) + DELTA_INDEX[Math.floor(value2) + 1] * x;
- }
- x = x * 127 + 127;
- }
- return multiply(matrix2, [
- x / 127,
- 0,
- 0,
- 0,
- 0.5 * (127 - x),
- 0,
- x / 127,
- 0,
- 0,
- 0.5 * (127 - x),
- 0,
- 0,
- x / 127,
- 0,
- 0.5 * (127 - x),
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1
- ]);
- };
- var adjustBrightness = function(matrix2, value2) {
- value2 = clamp(255 * value2, -255, 255);
- return multiply(matrix2, [
- 1,
- 0,
- 0,
- 0,
- value2,
- 0,
- 1,
- 0,
- 0,
- value2,
- 0,
- 0,
- 1,
- 0,
- value2,
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1
- ]);
- };
- var adjustColors = function(matrix2, adjustR, adjustG, adjustB) {
- adjustR = clamp(adjustR, 0, 2);
- adjustG = clamp(adjustG, 0, 2);
- adjustB = clamp(adjustB, 0, 2);
- return multiply(matrix2, [
- adjustR,
- 0,
- 0,
- 0,
- 0,
- 0,
- adjustG,
- 0,
- 0,
- 0,
- 0,
- 0,
- adjustB,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1
- ]);
- };
- var colorFilter = function(ir, matrix2) {
- return ir.toCanvas().then(function(canvas) {
- return applyColorFilter(canvas, ir.getType(), matrix2);
- });
- };
- var applyColorFilter = function(canvas, type2, matrix2) {
- var context = get2dContext(canvas);
- var applyMatrix = function(pixelsData, m) {
- var r2, g, b2, a;
- var data = pixelsData.data, m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5], m6 = m[6], m7 = m[7], m8 = m[8], m9 = m[9], m10 = m[10], m11 = m[11], m12 = m[12], m13 = m[13], m14 = m[14], m15 = m[15], m16 = m[16], m17 = m[17], m18 = m[18], m19 = m[19];
- for (var i = 0; i < data.length; i += 4) {
- r2 = data[i];
- g = data[i + 1];
- b2 = data[i + 2];
- a = data[i + 3];
- data[i] = r2 * m0 + g * m1 + b2 * m2 + a * m3 + m4;
- data[i + 1] = r2 * m5 + g * m6 + b2 * m7 + a * m8 + m9;
- data[i + 2] = r2 * m10 + g * m11 + b2 * m12 + a * m13 + m14;
- data[i + 3] = r2 * m15 + g * m16 + b2 * m17 + a * m18 + m19;
- }
- return pixelsData;
- };
- var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix2);
- context.putImageData(pixels, 0, 0);
- return fromCanvas(canvas, type2);
- };
- var convoluteFilter = function(ir, matrix2) {
- return ir.toCanvas().then(function(canvas) {
- return applyConvoluteFilter(canvas, ir.getType(), matrix2);
- });
- };
- var applyConvoluteFilter = function(canvas, type2, matrix2) {
- var context = get2dContext(canvas);
- var applyMatrix = function(pIn, pOut, aMatrix) {
- var clamp2 = function(value2, min2, max2) {
- if (value2 > max2) {
- value2 = max2;
- } else if (value2 < min2) {
- value2 = min2;
- }
- return value2;
- };
- var side = Math.round(Math.sqrt(aMatrix.length));
- var halfSide = Math.floor(side / 2);
- var rgba = pIn.data;
- var drgba = pOut.data;
- var w = pIn.width;
- var h = pIn.height;
- for (var y = 0; y < h; y++) {
- for (var x = 0; x < w; x++) {
- var r2 = 0;
- var g = 0;
- var b2 = 0;
- for (var cy = 0; cy < side; cy++) {
- for (var cx = 0; cx < side; cx++) {
- var scx = clamp2(x + cx - halfSide, 0, w - 1);
- var scy = clamp2(y + cy - halfSide, 0, h - 1);
- var innerOffset = (scy * w + scx) * 4;
- var wt = aMatrix[cy * side + cx];
- r2 += rgba[innerOffset] * wt;
- g += rgba[innerOffset + 1] * wt;
- b2 += rgba[innerOffset + 2] * wt;
- }
- }
- var offset2 = (y * w + x) * 4;
- drgba[offset2] = clamp2(r2, 0, 255);
- drgba[offset2 + 1] = clamp2(g, 0, 255);
- drgba[offset2 + 2] = clamp2(b2, 0, 255);
- }
- }
- return pOut;
- };
- var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
- var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
- pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix2);
- context.putImageData(pixelsOut, 0, 0);
- return fromCanvas(canvas, type2);
- };
- var functionColorFilter = function(colorFn) {
- var filterImpl = function(canvas, type2, value2) {
- var context = get2dContext(canvas);
- var lookup2 = new Array(256);
- var applyLookup = function(pixelsData, lookupData) {
- var data = pixelsData.data;
- for (var i2 = 0; i2 < data.length; i2 += 4) {
- data[i2] = lookupData[data[i2]];
- data[i2 + 1] = lookupData[data[i2 + 1]];
- data[i2 + 2] = lookupData[data[i2 + 2]];
- }
- return pixelsData;
- };
- for (var i = 0; i < lookup2.length; i++) {
- lookup2[i] = colorFn(i, value2);
- }
- var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup2);
- context.putImageData(pixels, 0, 0);
- return fromCanvas(canvas, type2);
- };
- return function(ir, value2) {
- return ir.toCanvas().then(function(canvas) {
- return filterImpl(canvas, ir.getType(), value2);
- });
- };
- };
- var complexAdjustableColorFilter = function(matrixAdjustFn) {
- return function(ir, adjust) {
- return colorFilter(ir, matrixAdjustFn(identity(), adjust));
- };
- };
- var basicColorFilter = function(matrix2) {
- return function(ir) {
- return colorFilter(ir, matrix2);
- };
- };
- var basicConvolutionFilter = function(kernel) {
- return function(ir) {
- return convoluteFilter(ir, kernel);
- };
- };
- var invert$1 = basicColorFilter([
- -1,
- 0,
- 0,
- 0,
- 255,
- 0,
- -1,
- 0,
- 0,
- 255,
- 0,
- 0,
- -1,
- 0,
- 255,
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1
- ]);
- var brightness$1 = complexAdjustableColorFilter(adjustBrightness);
- var contrast$1 = complexAdjustableColorFilter(adjustContrast);
- var colorize$1 = function(ir, adjustR, adjustG, adjustB) {
- return colorFilter(ir, adjustColors(identity(), adjustR, adjustG, adjustB));
- };
- var sharpen$1 = basicConvolutionFilter([
- 0,
- -1,
- 0,
- -1,
- 5,
- -1,
- 0,
- -1,
- 0
- ]);
- var gamma$1 = functionColorFilter(function(color, value2) {
- return Math.pow(color / 255, 1 - value2) * 255;
- });
- var scale = function(image, dW, dH) {
- var sW = getWidth$1(image);
- var sH = getHeight$1(image);
- var wRatio = dW / sW;
- var hRatio = dH / sH;
- var scaleCapped = false;
- if (wRatio < 0.5 || wRatio > 2) {
- wRatio = wRatio < 0.5 ? 0.5 : 2;
- scaleCapped = true;
- }
- if (hRatio < 0.5 || hRatio > 2) {
- hRatio = hRatio < 0.5 ? 0.5 : 2;
- scaleCapped = true;
- }
- var scaled = _scale(image, wRatio, hRatio);
- return !scaleCapped ? scaled : scaled.then(function(tCanvas) {
- return scale(tCanvas, dW, dH);
- });
- };
- var _scale = function(image, wRatio, hRatio) {
- return new Promise$1(function(resolve) {
- var sW = getWidth$1(image);
- var sH = getHeight$1(image);
- var dW = Math.floor(sW * wRatio);
- var dH = Math.floor(sH * hRatio);
- var canvas = create$4(dW, dH);
- var context = get2dContext(canvas);
- context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
- resolve(canvas);
- });
- };
- var ceilWithPrecision = function(num, precision) {
- if (precision === void 0) {
- precision = 2;
- }
- var mul = Math.pow(10, precision);
- var upper = Math.round(num * mul);
- return Math.ceil(upper / mul);
- };
- var rotate$1 = function(ir, angle) {
- return ir.toCanvas().then(function(canvas) {
- return applyRotate(canvas, ir.getType(), angle);
- });
- };
- var applyRotate = function(image, type2, angle) {
- var degrees = angle < 0 ? 360 + angle : angle;
- var rad = degrees * Math.PI / 180;
- var width2 = image.width;
- var height2 = image.height;
- var sin = Math.sin(rad);
- var cos = Math.cos(rad);
- var newWidth = ceilWithPrecision(Math.abs(width2 * cos) + Math.abs(height2 * sin));
- var newHeight = ceilWithPrecision(Math.abs(width2 * sin) + Math.abs(height2 * cos));
- var canvas = create$4(newWidth, newHeight);
- var context = get2dContext(canvas);
- context.translate(newWidth / 2, newHeight / 2);
- context.rotate(rad);
- context.drawImage(image, -width2 / 2, -height2 / 2);
- return fromCanvas(canvas, type2);
- };
- var flip$1 = function(ir, axis) {
- return ir.toCanvas().then(function(canvas) {
- return applyFlip(canvas, ir.getType(), axis);
- });
- };
- var applyFlip = function(image, type2, axis) {
- var canvas = create$4(image.width, image.height);
- var context = get2dContext(canvas);
- if (axis === "v") {
- context.scale(1, -1);
- context.drawImage(image, 0, -canvas.height);
- } else {
- context.scale(-1, 1);
- context.drawImage(image, -canvas.width, 0);
- }
- return fromCanvas(canvas, type2);
- };
- var crop$1 = function(ir, x, y, w, h) {
- return ir.toCanvas().then(function(canvas) {
- return applyCrop(canvas, ir.getType(), x, y, w, h);
- });
- };
- var applyCrop = function(image, type2, x, y, w, h) {
- var canvas = create$4(w, h);
- var context = get2dContext(canvas);
- context.drawImage(image, -x, -y);
- return fromCanvas(canvas, type2);
- };
- var resize$2 = function(ir, w, h) {
- return ir.toCanvas().then(function(canvas) {
- return scale(canvas, w, h).then(function(newCanvas) {
- return fromCanvas(newCanvas, ir.getType());
- });
- });
- };
- var invert = function(ir) {
- return invert$1(ir);
- };
- var sharpen = function(ir) {
- return sharpen$1(ir);
- };
- var gamma = function(ir, value2) {
- return gamma$1(ir, value2);
- };
- var colorize = function(ir, adjustR, adjustG, adjustB) {
- return colorize$1(ir, adjustR, adjustG, adjustB);
- };
- var brightness = function(ir, adjust) {
- return brightness$1(ir, adjust);
- };
- var contrast = function(ir, adjust) {
- return contrast$1(ir, adjust);
- };
- var flip = function(ir, axis) {
- return flip$1(ir, axis);
- };
- var crop = function(ir, x, y, w, h) {
- return crop$1(ir, x, y, w, h);
- };
- var resize$1 = function(ir, w, h) {
- return resize$2(ir, w, h);
- };
- var rotate = function(ir, angle) {
- return rotate$1(ir, angle);
- };
- var renderIcon = function(iconName, iconsProvider, behaviours2) {
- return render$3(iconName, {
- tag: "span",
- classes: [
- "tox-icon",
- "tox-tbtn__icon-wrap"
- ],
- behaviours: behaviours2
- }, iconsProvider);
- };
- var renderIconFromPack = function(iconName, iconsProvider) {
- return renderIcon(iconName, iconsProvider, []);
- };
- var renderReplacableIconFromPack = function(iconName, iconsProvider) {
- return renderIcon(iconName, iconsProvider, [Replacing.config({})]);
- };
- var renderLabel$1 = function(text2, prefix2, providersBackstage) {
- return {
- dom: {
- tag: "span",
- innerHtml: providersBackstage.translate(text2),
- classes: [prefix2 + "__select-label"]
- },
- behaviours: derive$1([Replacing.config({})])
- };
- };
- var _a;
- var internalToolbarButtonExecute = generate$6("toolbar.button.execute");
- var onToolbarButtonExecute = function(info) {
- return runOnExecute$1(function(comp, _simulatedEvent) {
- runWithApi(info, comp)(function(itemApi) {
- emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
- info.onAction(itemApi);
- });
- });
- };
- var toolbarButtonEventOrder = (_a = {}, _a[execute$5()] = [
- "disabling",
- "alloy.base.behaviour",
- "toggling",
- "toolbar-button-events"
- ], _a);
- var updateMenuText = generate$6("update-menu-text");
- var updateMenuIcon = generate$6("update-menu-icon");
- var renderCommonDropdown = function(spec, prefix2, sharedBackstage) {
- var editorOffCell = Cell(noop);
- var optMemDisplayText = spec.text.map(function(text2) {
- return record(renderLabel$1(text2, prefix2, sharedBackstage.providers));
- });
- var optMemDisplayIcon = spec.icon.map(function(iconName) {
- return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
- });
- var onLeftOrRightInMenu = function(comp, se) {
- var dropdown = Representing.getValue(comp);
- Focusing.focus(dropdown);
- emitWith(dropdown, "keydown", { raw: se.event.raw });
- Dropdown.close(dropdown);
- return Optional.some(true);
- };
- var role = spec.role.fold(function() {
- return {};
- }, function(role2) {
- return { role: role2 };
- });
- var tooltipAttributes = spec.tooltip.fold(function() {
- return {};
- }, function(tooltip) {
- var translatedTooltip = sharedBackstage.providers.translate(tooltip);
- return {
- "title": translatedTooltip,
- "aria-label": translatedTooltip
- };
- });
- var iconSpec = render$3("chevron-down", {
- tag: "div",
- classes: [prefix2 + "__select-chevron"]
- }, sharedBackstage.providers.icons);
- var memDropdown = record(Dropdown.sketch(__assign(__assign(__assign({}, spec.uid ? { uid: spec.uid } : {}), role), {
- dom: {
- tag: "button",
- classes: [
- prefix2,
- prefix2 + "--select"
- ].concat(map$2(spec.classes, function(c) {
- return prefix2 + "--" + c;
- })),
- attributes: __assign({}, tooltipAttributes)
- },
- components: componentRenderPipeline([
- optMemDisplayIcon.map(function(mem) {
- return mem.asSpec();
- }),
- optMemDisplayText.map(function(mem) {
- return mem.asSpec();
- }),
- Optional.some(iconSpec)
- ]),
- matchWidth: true,
- useMinWidth: true,
- dropdownBehaviours: derive$1(__spreadArray(__spreadArray([], spec.dropdownBehaviours, true), [
- DisablingConfigs.button(function() {
- return spec.disabled || sharedBackstage.providers.isDisabled();
- }),
- receivingConfig(),
- Unselecting.config({}),
- Replacing.config({}),
- config("dropdown-events", [
- onControlAttached(spec, editorOffCell),
- onControlDetached(spec, editorOffCell)
- ]),
- config("menubutton-update-display-text", [
- run$1(updateMenuText, function(comp, se) {
- optMemDisplayText.bind(function(mem) {
- return mem.getOpt(comp);
- }).each(function(displayText) {
- Replacing.set(displayText, [text$1(sharedBackstage.providers.translate(se.event.text))]);
- });
- }),
- run$1(updateMenuIcon, function(comp, se) {
- optMemDisplayIcon.bind(function(mem) {
- return mem.getOpt(comp);
- }).each(function(displayIcon) {
- Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event.icon, sharedBackstage.providers.icons)]);
- });
- })
- ])
- ], false)),
- eventOrder: deepMerge(toolbarButtonEventOrder, {
- mousedown: [
- "focusing",
- "alloy.base.behaviour",
- "item-type-events",
- "normal-dropdown-events"
- ]
- }),
- sandboxBehaviours: derive$1([Keying.config({
- mode: "special",
- onLeft: onLeftOrRightInMenu,
- onRight: onLeftOrRightInMenu
- })]),
- lazySink: sharedBackstage.getSink,
- toggleClass: prefix2 + "--active",
- parts: { menu: part(false, spec.columns, spec.presets) },
- fetch: function(comp) {
- return Future.nu(curry(spec.fetch, comp));
- }
- })));
- return memDropdown.asSpec();
- };
- var isMenuItemReference = function(item2) {
- return isString(item2);
- };
- var isSeparator$1 = function(item2) {
- return item2.type === "separator";
- };
- var isExpandingMenuItem = function(item2) {
- return has$2(item2, "getSubmenuItems");
- };
- var separator$2 = { type: "separator" };
- var unwrapReferences = function(items, menuItems) {
- var realItems = foldl(items, function(acc, item2) {
- if (isMenuItemReference(item2)) {
- if (item2 === "") {
- return acc;
- } else if (item2 === "|") {
- return acc.length > 0 && !isSeparator$1(acc[acc.length - 1]) ? acc.concat([separator$2]) : acc;
- } else if (has$2(menuItems, item2.toLowerCase())) {
- return acc.concat([menuItems[item2.toLowerCase()]]);
- } else {
- return acc;
- }
- } else {
- return acc.concat([item2]);
- }
- }, []);
- if (realItems.length > 0 && isSeparator$1(realItems[realItems.length - 1])) {
- realItems.pop();
- }
- return realItems;
- };
- var getFromExpandingItem = function(item2, menuItems) {
- var submenuItems = item2.getSubmenuItems();
- var rest = expand(submenuItems, menuItems);
- var newMenus = deepMerge(rest.menus, wrap$1(item2.value, rest.items));
- var newExpansions = deepMerge(rest.expansions, wrap$1(item2.value, item2.value));
- return {
- item: item2,
- menus: newMenus,
- expansions: newExpansions
- };
- };
- var getFromItem = function(item2, menuItems) {
- return isExpandingMenuItem(item2) ? getFromExpandingItem(item2, menuItems) : {
- item: item2,
- menus: {},
- expansions: {}
- };
- };
- var generateValueIfRequired = function(item2) {
- if (isSeparator$1(item2)) {
- return item2;
- } else {
- var itemValue = get$e(item2, "value").getOrThunk(function() {
- return generate$6("generated-menu-item");
- });
- return deepMerge({ value: itemValue }, item2);
- }
- };
- var expand = function(items, menuItems) {
- var realItems = unwrapReferences(isString(items) ? items.split(" ") : items, menuItems);
- return foldr(realItems, function(acc, item2) {
- var itemWithValue = generateValueIfRequired(item2);
- var newData = getFromItem(itemWithValue, menuItems);
- return {
- menus: deepMerge(acc.menus, newData.menus),
- items: [newData.item].concat(acc.items),
- expansions: deepMerge(acc.expansions, newData.expansions)
- };
- }, {
- menus: {},
- expansions: {},
- items: []
- });
- };
- var build = function(items, itemResponse, backstage, isHorizontalMenu) {
- var primary = generate$6("primary-menu");
- var data = expand(items, backstage.shared.providers.menuItems());
- if (data.items.length === 0) {
- return Optional.none();
- }
- var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
- var submenus = map$1(data.menus, function(menuItems, menuName) {
- return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
- });
- var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
- return Optional.from(tieredMenu.tieredData(primary, menus, data.expansions));
- };
- var getMenuButtonApi = function(component) {
- return {
- isDisabled: function() {
- return Disabling.isDisabled(component);
- },
- setDisabled: function(state) {
- return Disabling.set(component, state);
- },
- setActive: function(state) {
- var elm = component.element;
- if (state) {
- add$2(elm, "tox-tbtn--enabled");
- set$8(elm, "aria-pressed", true);
- } else {
- remove$2(elm, "tox-tbtn--enabled");
- remove$7(elm, "aria-pressed");
- }
- },
- isActive: function() {
- return has(component.element, "tox-tbtn--enabled");
- }
- };
- };
- var renderMenuButton = function(spec, prefix2, backstage, role) {
- return renderCommonDropdown({
- text: spec.text,
- icon: spec.icon,
- tooltip: spec.tooltip,
- role,
- fetch: function(_comp, callback) {
- spec.fetch(function(items) {
- callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
- });
- },
- onSetup: spec.onSetup,
- getApi: getMenuButtonApi,
- columns: 1,
- presets: "normal",
- classes: [],
- dropdownBehaviours: [Tabstopping.config({})]
- }, prefix2, backstage.shared);
- };
- var getFetch = function(items, getButton, backstage) {
- var getMenuItemAction = function(item2) {
- return function(api2) {
- var newValue = !api2.isActive();
- api2.setActive(newValue);
- item2.storage.set(newValue);
- backstage.shared.getSink().each(function(sink) {
- getButton().getOpt(sink).each(function(orig) {
- focus$3(orig.element);
- emitWith(orig, formActionEvent, {
- name: item2.name,
- value: item2.storage.get()
- });
- });
- });
- };
- };
- var getMenuItemSetup = function(item2) {
- return function(api2) {
- api2.setActive(item2.storage.get());
- };
- };
- return function(success) {
- success(map$2(items, function(item2) {
- var text2 = item2.text.fold(function() {
- return {};
- }, function(text3) {
- return { text: text3 };
- });
- return __assign(__assign({
- type: item2.type,
- active: false
- }, text2), {
- onAction: getMenuItemAction(item2),
- onSetup: getMenuItemSetup(item2)
- });
- }));
- };
- };
- var renderCommonSpec = function(spec, actionOpt, extraBehaviours, dom2, components2, providersBackstage) {
- if (extraBehaviours === void 0) {
- extraBehaviours = [];
- }
- var action = actionOpt.fold(function() {
- return {};
- }, function(action2) {
- return { action: action2 };
- });
- var common = __assign({
- buttonBehaviours: derive$1([
- DisablingConfigs.button(function() {
- return spec.disabled || providersBackstage.isDisabled();
- }),
- receivingConfig(),
- Tabstopping.config({}),
- config("button press", [
- preventDefault("click"),
- preventDefault("mousedown")
- ])
- ].concat(extraBehaviours)),
- eventOrder: {
- click: [
- "button press",
- "alloy.base.behaviour"
- ],
- mousedown: [
- "button press",
- "alloy.base.behaviour"
- ]
- }
- }, action);
- var domFinal = deepMerge(common, { dom: dom2 });
- return deepMerge(domFinal, { components: components2 });
- };
- var renderIconButtonSpec = function(spec, action, providersBackstage, extraBehaviours) {
- if (extraBehaviours === void 0) {
- extraBehaviours = [];
- }
- var tooltipAttributes = spec.tooltip.map(function(tooltip) {
- return {
- "aria-label": providersBackstage.translate(tooltip),
- "title": providersBackstage.translate(tooltip)
- };
- }).getOr({});
- var dom2 = {
- tag: "button",
- classes: ["tox-tbtn"],
- attributes: tooltipAttributes
- };
- var icon = spec.icon.map(function(iconName) {
- return renderIconFromPack(iconName, providersBackstage.icons);
- });
- var components2 = componentRenderPipeline([icon]);
- return renderCommonSpec(spec, action, extraBehaviours, dom2, components2, providersBackstage);
- };
- var renderIconButton = function(spec, action, providersBackstage, extraBehaviours) {
- if (extraBehaviours === void 0) {
- extraBehaviours = [];
- }
- var iconButtonSpec = renderIconButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours);
- return Button.sketch(iconButtonSpec);
- };
- var renderButtonSpec = function(spec, action, providersBackstage, extraBehaviours, extraClasses) {
- if (extraBehaviours === void 0) {
- extraBehaviours = [];
- }
- if (extraClasses === void 0) {
- extraClasses = [];
- }
- var translatedText = providersBackstage.translate(spec.text);
- var icon = spec.icon ? spec.icon.map(function(iconName) {
- return renderIconFromPack(iconName, providersBackstage.icons);
- }) : Optional.none();
- var components2 = icon.isSome() ? componentRenderPipeline([icon]) : [];
- var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
- var classes2 = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], !spec.primary && !spec.borderless ? [
- "tox-button",
- "tox-button--secondary"
- ] : ["tox-button"], true), icon.isSome() ? ["tox-button--icon"] : [], true), spec.borderless ? ["tox-button--naked"] : [], true), extraClasses, true);
- var dom2 = __assign(__assign({
- tag: "button",
- classes: classes2
- }, innerHtml), { attributes: { title: translatedText } });
- return renderCommonSpec(spec, action, extraBehaviours, dom2, components2, providersBackstage);
- };
- var renderButton = function(spec, action, providersBackstage, extraBehaviours, extraClasses) {
- if (extraBehaviours === void 0) {
- extraBehaviours = [];
- }
- if (extraClasses === void 0) {
- extraClasses = [];
- }
- var buttonSpec = renderButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours, extraClasses);
- return Button.sketch(buttonSpec);
- };
- var getAction = function(name2, buttonType) {
- return function(comp) {
- if (buttonType === "custom") {
- emitWith(comp, formActionEvent, {
- name: name2,
- value: {}
- });
- } else if (buttonType === "submit") {
- emit(comp, formSubmitEvent);
- } else if (buttonType === "cancel") {
- emit(comp, formCancelEvent);
- } else {
- console.error("Unknown button type: ", buttonType);
- }
- };
- };
- var isMenuFooterButtonSpec = function(spec, buttonType) {
- return buttonType === "menu";
- };
- var isNormalFooterButtonSpec = function(spec, buttonType) {
- return buttonType === "custom" || buttonType === "cancel" || buttonType === "submit";
- };
- var renderFooterButton = function(spec, buttonType, backstage) {
- if (isMenuFooterButtonSpec(spec, buttonType)) {
- var getButton = function() {
- return memButton_1;
- };
- var menuButtonSpec = spec;
- var fixedSpec = __assign(__assign({}, spec), {
- onSetup: function(api2) {
- api2.setDisabled(spec.disabled);
- return noop;
- },
- fetch: getFetch(menuButtonSpec.items, getButton, backstage)
- });
- var memButton_1 = record(renderMenuButton(fixedSpec, "tox-tbtn", backstage, Optional.none()));
- return memButton_1.asSpec();
- } else if (isNormalFooterButtonSpec(spec, buttonType)) {
- var action = getAction(spec.name, buttonType);
- var buttonSpec = __assign(__assign({}, spec), { borderless: false });
- return renderButton(buttonSpec, action, backstage.shared.providers, []);
- } else {
- console.error("Unknown footer button type: ", buttonType);
- }
- };
- var renderDialogButton = function(spec, providersBackstage) {
- var action = getAction(spec.name, "custom");
- return renderFormField(Optional.none(), FormField.parts.field(__assign({ factory: Button }, renderButtonSpec(spec, Optional.some(action), providersBackstage, [
- RepresentingConfigs.memory(""),
- ComposingConfigs.self()
- ]))));
- };
- var schema$h = constant$1([
- defaulted("field1Name", "field1"),
- defaulted("field2Name", "field2"),
- onStrictHandler("onLockedChange"),
- markers$1(["lockClass"]),
- defaulted("locked", false),
- SketchBehaviours.field("coupledFieldBehaviours", [
- Composing,
- Representing
- ])
- ]);
- var getField = function(comp, detail, partName) {
- return getPart(comp, detail, partName).bind(Composing.getCurrent);
- };
- var coupledPart = function(selfName, otherName) {
- return required({
- factory: FormField,
- name: selfName,
- overrides: function(detail) {
- return {
- fieldBehaviours: derive$1([config("coupled-input-behaviour", [run$1(input(), function(me) {
- getField(me, detail, otherName).each(function(other) {
- getPart(me, detail, "lock").each(function(lock) {
- if (Toggling.isOn(lock)) {
- detail.onLockedChange(me, other, lock);
- }
- });
- });
- })])])
- };
- }
- });
- };
- var parts$c = constant$1([
- coupledPart("field1", "field2"),
- coupledPart("field2", "field1"),
- required({
- factory: Button,
- schema: [required$1("dom")],
- name: "lock",
- overrides: function(detail) {
- return {
- buttonBehaviours: derive$1([Toggling.config({
- selected: detail.locked,
- toggleClass: detail.markers.lockClass,
- aria: { mode: "pressed" }
- })])
- };
- }
- })
- ]);
- var factory$f = function(detail, components2, _spec, _externals) {
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
- Composing.config({ find: Optional.some }),
- Representing.config({
- store: {
- mode: "manual",
- getValue: function(comp) {
- var _a2;
- var parts2 = getPartsOrDie(comp, detail, [
- "field1",
- "field2"
- ]);
- return _a2 = {}, _a2[detail.field1Name] = Representing.getValue(parts2.field1()), _a2[detail.field2Name] = Representing.getValue(parts2.field2()), _a2;
- },
- setValue: function(comp, value2) {
- var parts2 = getPartsOrDie(comp, detail, [
- "field1",
- "field2"
- ]);
- if (hasNonNullableKey(value2, detail.field1Name)) {
- Representing.setValue(parts2.field1(), value2[detail.field1Name]);
- }
- if (hasNonNullableKey(value2, detail.field2Name)) {
- Representing.setValue(parts2.field2(), value2[detail.field2Name]);
- }
- }
- }
- })
- ]),
- apis: {
- getField1: function(component) {
- return getPart(component, detail, "field1");
- },
- getField2: function(component) {
- return getPart(component, detail, "field2");
- },
- getLock: function(component) {
- return getPart(component, detail, "lock");
- }
- }
- };
- };
- var FormCoupledInputs = composite({
- name: "FormCoupledInputs",
- configFields: schema$h(),
- partFields: parts$c(),
- factory: factory$f,
- apis: {
- getField1: function(apis, component) {
- return apis.getField1(component);
- },
- getField2: function(apis, component) {
- return apis.getField2(component);
- },
- getLock: function(apis, component) {
- return apis.getLock(component);
- }
- }
- });
- var formatSize = function(size) {
- var unitDec = {
- "": 0,
- "px": 0,
- "pt": 1,
- "mm": 1,
- "pc": 2,
- "ex": 2,
- "em": 2,
- "ch": 2,
- "rem": 2,
- "cm": 3,
- "in": 4,
- "%": 4
- };
- var maxDecimal = function(unit) {
- return unit in unitDec ? unitDec[unit] : 1;
- };
- var numText = size.value.toFixed(maxDecimal(size.unit));
- if (numText.indexOf(".") !== -1) {
- numText = numText.replace(/\.?0*$/, "");
- }
- return numText + size.unit;
- };
- var parseSize = function(sizeText) {
- var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
- var match = numPattern.exec(sizeText);
- if (match !== null) {
- var value2 = parseFloat(match[1]);
- var unit = match[2];
- return Result.value({
- value: value2,
- unit
- });
- } else {
- return Result.error(sizeText);
- }
- };
- var convertUnit = function(size, unit) {
- var inInch = {
- "": 96,
- "px": 96,
- "pt": 72,
- "cm": 2.54,
- "pc": 12,
- "mm": 25.4,
- "in": 1
- };
- var supported2 = function(u) {
- return has$2(inInch, u);
- };
- if (size.unit === unit) {
- return Optional.some(size.value);
- } else if (supported2(size.unit) && supported2(unit)) {
- if (inInch[size.unit] === inInch[unit]) {
- return Optional.some(size.value);
- } else {
- return Optional.some(size.value / inInch[size.unit] * inInch[unit]);
- }
- } else {
- return Optional.none();
- }
- };
- var noSizeConversion = function(_input) {
- return Optional.none();
- };
- var ratioSizeConversion = function(scale2, unit) {
- return function(size) {
- return convertUnit(size, unit).map(function(value2) {
- return {
- value: value2 * scale2,
- unit
- };
- });
- };
- };
- var makeRatioConverter = function(currentFieldText, otherFieldText) {
- var cValue = parseSize(currentFieldText).toOptional();
- var oValue = parseSize(otherFieldText).toOptional();
- return lift2(cValue, oValue, function(cSize, oSize) {
- return convertUnit(cSize, oSize.unit).map(function(val) {
- return oSize.value / val;
- }).map(function(r2) {
- return ratioSizeConversion(r2, oSize.unit);
- }).getOr(noSizeConversion);
- }).getOr(noSizeConversion);
- };
- var renderSizeInput = function(spec, providersBackstage) {
- var converter = noSizeConversion;
- var ratioEvent = generate$6("ratio-event");
- var makeIcon = function(iconName) {
- return render$3(iconName, {
- tag: "span",
- classes: [
- "tox-icon",
- "tox-lock-icon__" + iconName
- ]
- }, providersBackstage.icons);
- };
- var pLock = FormCoupledInputs.parts.lock({
- dom: {
- tag: "button",
- classes: [
- "tox-lock",
- "tox-button",
- "tox-button--naked",
- "tox-button--icon"
- ],
- attributes: { title: providersBackstage.translate(spec.label.getOr("Constrain proportions")) }
- },
- components: [
- makeIcon("lock"),
- makeIcon("unlock")
- ],
- buttonBehaviours: derive$1([
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- }
- }),
- receivingConfig(),
- Tabstopping.config({})
- ])
- });
- var formGroup = function(components2) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-form__group"]
- },
- components: components2
- };
- };
- var getFieldPart = function(isField1) {
- return FormField.parts.field({
- factory: Input,
- inputClasses: ["tox-textfield"],
- inputBehaviours: derive$1([
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- }
- }),
- receivingConfig(),
- Tabstopping.config({}),
- config("size-input-events", [
- run$1(focusin(), function(component, _simulatedEvent) {
- emitWith(component, ratioEvent, { isField1 });
- }),
- run$1(change(), function(component, _simulatedEvent) {
- emitWith(component, formChangeEvent, { name: spec.name });
- })
- ])
- ]),
- selectOnFocus: false
- });
- };
- var getLabel = function(label) {
- return {
- dom: {
- tag: "label",
- classes: ["tox-label"],
- innerHtml: providersBackstage.translate(label)
- }
- };
- };
- var widthField = FormCoupledInputs.parts.field1(formGroup([
- FormField.parts.label(getLabel("Width")),
- getFieldPart(true)
- ]));
- var heightField = FormCoupledInputs.parts.field2(formGroup([
- FormField.parts.label(getLabel("Height")),
- getFieldPart(false)
- ]));
- return FormCoupledInputs.sketch({
- dom: {
- tag: "div",
- classes: ["tox-form__group"]
- },
- components: [{
- dom: {
- tag: "div",
- classes: ["tox-form__controls-h-stack"]
- },
- components: [
- widthField,
- heightField,
- formGroup([
- getLabel(" "),
- pLock
- ])
- ]
- }],
- field1Name: "width",
- field2Name: "height",
- locked: true,
- markers: { lockClass: "tox-locked" },
- onLockedChange: function(current, other, _lock) {
- parseSize(Representing.getValue(current)).each(function(size) {
- converter(size).each(function(newSize) {
- Representing.setValue(other, formatSize(newSize));
- });
- });
- },
- coupledFieldBehaviours: derive$1([
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- },
- onDisabled: function(comp) {
- FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
- FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
- FormCoupledInputs.getLock(comp).each(Disabling.disable);
- },
- onEnabled: function(comp) {
- FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
- FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
- FormCoupledInputs.getLock(comp).each(Disabling.enable);
- }
- }),
- receivingConfig(),
- config("size-input-events2", [run$1(ratioEvent, function(component, simulatedEvent) {
- var isField1 = simulatedEvent.event.isField1;
- var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
- var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
- var value1 = optCurrent.map(Representing.getValue).getOr("");
- var value2 = optOther.map(Representing.getValue).getOr("");
- converter = makeRatioConverter(value1, value2);
- })])
- ])
- });
- };
- var undo = constant$1(generate$6("undo"));
- var redo = constant$1(generate$6("redo"));
- var zoom = constant$1(generate$6("zoom"));
- var back = constant$1(generate$6("back"));
- var apply$1 = constant$1(generate$6("apply"));
- var swap = constant$1(generate$6("swap"));
- var transform$1 = constant$1(generate$6("transform"));
- var tempTransform = constant$1(generate$6("temp-transform"));
- var transformApply = constant$1(generate$6("transform-apply"));
- var internal = {
- undo,
- redo,
- zoom,
- back,
- apply: apply$1,
- swap,
- transform: transform$1,
- tempTransform,
- transformApply
- };
- var saveState = constant$1("save-state");
- var disable = constant$1("disable");
- var enable = constant$1("enable");
- var external = {
- formActionEvent,
- saveState,
- disable,
- enable
- };
- var renderEditPanel = function(imagePanel, providersBackstage) {
- var createButton2 = function(text2, action, disabled, primary) {
- return record(renderButton({
- name: text2,
- text: text2,
- disabled,
- primary,
- icon: Optional.none(),
- borderless: false
- }, action, providersBackstage));
- };
- var createIconButton = function(icon, tooltip, action, disabled) {
- return record(renderIconButton({
- name: icon,
- icon: Optional.some(icon),
- tooltip: Optional.some(tooltip),
- disabled,
- primary: false,
- borderless: false
- }, action, providersBackstage));
- };
- var disableAllComponents = function(comps, eventcomp) {
- comps.map(function(mem) {
- var component = mem.get(eventcomp);
- if (component.hasConfigured(Disabling)) {
- Disabling.disable(component);
- }
- });
- };
- var enableAllComponents = function(comps, eventcomp) {
- comps.map(function(mem) {
- var component = mem.get(eventcomp);
- if (component.hasConfigured(Disabling)) {
- Disabling.enable(component);
- }
- });
- };
- var panelDom = {
- tag: "div",
- classes: [
- "tox-image-tools__toolbar",
- "tox-image-tools-edit-panel"
- ]
- };
- var noop$1 = noop;
- var emit$1 = function(comp, event, data) {
- emitWith(comp, event, data);
- };
- var emitDisable = function(component) {
- return emit(component, external.disable());
- };
- var emitEnable = function(component) {
- return emit(component, external.enable());
- };
- var emitTransform = function(comp, transform2) {
- emitDisable(comp);
- emit$1(comp, internal.transform(), { transform: transform2 });
- emitEnable(comp);
- };
- var emitTempTransform = function(comp, transform2) {
- emitDisable(comp);
- emit$1(comp, internal.tempTransform(), { transform: transform2 });
- emitEnable(comp);
- };
- var getBackSwap = function(anyInSystem) {
- return function() {
- memContainer.getOpt(anyInSystem).each(function(container2) {
- Replacing.set(container2, [ButtonPanel]);
- });
- };
- };
- var emitTransformApply = function(comp, transform2) {
- emitDisable(comp);
- emit$1(comp, internal.transformApply(), {
- transform: transform2,
- swap: getBackSwap(comp)
- });
- emitEnable(comp);
- };
- var createBackButton = function() {
- return createButton2("Back", function(button2) {
- return emit$1(button2, internal.back(), { swap: getBackSwap(button2) });
- }, false, false);
- };
- var createSpacer = function() {
- return record({
- dom: {
- tag: "div",
- classes: ["tox-spacer"]
- },
- behaviours: derive$1([Disabling.config({})])
- });
- };
- var createApplyButton = function() {
- return createButton2("Apply", function(button2) {
- return emit$1(button2, internal.apply(), { swap: getBackSwap(button2) });
- }, true, true);
- };
- var makeCropTransform = function() {
- return function(ir) {
- var rect2 = imagePanel.getRect();
- return crop(ir, rect2.x, rect2.y, rect2.w, rect2.h);
- };
- };
- var cropPanelComponents = [
- createBackButton(),
- createSpacer(),
- createButton2("Apply", function(button2) {
- var transform2 = makeCropTransform();
- emitTransformApply(button2, transform2);
- imagePanel.hideCrop();
- }, false, true)
- ];
- var CropPanel = Container.sketch({
- dom: panelDom,
- components: cropPanelComponents.map(function(mem) {
- return mem.asSpec();
- }),
- containerBehaviours: derive$1([config("image-tools-crop-buttons-events", [
- run$1(external.disable(), function(comp, _se) {
- disableAllComponents(cropPanelComponents, comp);
- }),
- run$1(external.enable(), function(comp, _se) {
- enableAllComponents(cropPanelComponents, comp);
- })
- ])])
- });
- var memSize = record(renderSizeInput({
- name: "size",
- label: Optional.none(),
- constrain: true,
- disabled: false
- }, providersBackstage));
- var makeResizeTransform = function(width2, height2) {
- return function(ir) {
- return resize$1(ir, width2, height2);
- };
- };
- var resizePanelComponents = [
- createBackButton(),
- createSpacer(),
- memSize,
- createSpacer(),
- createButton2("Apply", function(button2) {
- memSize.getOpt(button2).each(function(sizeInput) {
- var value2 = Representing.getValue(sizeInput);
- var width2 = parseInt(value2.width, 10);
- var height2 = parseInt(value2.height, 10);
- var transform2 = makeResizeTransform(width2, height2);
- emitTransformApply(button2, transform2);
- });
- }, false, true)
- ];
- var ResizePanel = Container.sketch({
- dom: panelDom,
- components: resizePanelComponents.map(function(mem) {
- return mem.asSpec();
- }),
- containerBehaviours: derive$1([config("image-tools-resize-buttons-events", [
- run$1(external.disable(), function(comp, _se) {
- disableAllComponents(resizePanelComponents, comp);
- }),
- run$1(external.enable(), function(comp, _se) {
- enableAllComponents(resizePanelComponents, comp);
- })
- ])])
- });
- var makeValueTransform = function(transform2, value2) {
- return function(ir) {
- return transform2(ir, value2);
- };
- };
- var horizontalFlip = makeValueTransform(flip, "h");
- var verticalFlip = makeValueTransform(flip, "v");
- var counterclockwiseRotate = makeValueTransform(rotate, -90);
- var clockwiseRotate = makeValueTransform(rotate, 90);
- var flipRotateOnAction = function(comp, operation) {
- emitTempTransform(comp, operation);
- };
- var flipRotateComponents = [
- createBackButton(),
- createSpacer(),
- createIconButton("flip-horizontally", "Flip horizontally", function(button2) {
- flipRotateOnAction(button2, horizontalFlip);
- }, false),
- createIconButton("flip-vertically", "Flip vertically", function(button2) {
- flipRotateOnAction(button2, verticalFlip);
- }, false),
- createIconButton("rotate-left", "Rotate counterclockwise", function(button2) {
- flipRotateOnAction(button2, counterclockwiseRotate);
- }, false),
- createIconButton("rotate-right", "Rotate clockwise", function(button2) {
- flipRotateOnAction(button2, clockwiseRotate);
- }, false),
- createSpacer(),
- createApplyButton()
- ];
- var FlipRotatePanel = Container.sketch({
- dom: panelDom,
- components: flipRotateComponents.map(function(mem) {
- return mem.asSpec();
- }),
- containerBehaviours: derive$1([config("image-tools-fliprotate-buttons-events", [
- run$1(external.disable(), function(comp, _se) {
- disableAllComponents(flipRotateComponents, comp);
- }),
- run$1(external.enable(), function(comp, _se) {
- enableAllComponents(flipRotateComponents, comp);
- })
- ])])
- });
- var makeSlider = function(label, onChoose, min2, value2, max2) {
- var labelPart2 = Slider.parts.label({
- dom: {
- tag: "label",
- classes: ["tox-label"],
- innerHtml: providersBackstage.translate(label)
- }
- });
- var spectrum = Slider.parts.spectrum({
- dom: {
- tag: "div",
- classes: ["tox-slider__rail"],
- attributes: { role: "presentation" }
- }
- });
- var thumb = Slider.parts.thumb({
- dom: {
- tag: "div",
- classes: ["tox-slider__handle"],
- attributes: { role: "presentation" }
- }
- });
- return record(Slider.sketch({
- dom: {
- tag: "div",
- classes: ["tox-slider"],
- attributes: { role: "presentation" }
- },
- model: {
- mode: "x",
- minX: min2,
- maxX: max2,
- getInitialValue: constant$1({ x: value2 })
- },
- components: [
- labelPart2,
- spectrum,
- thumb
- ],
- sliderBehaviours: derive$1([Focusing.config({})]),
- onChoose
- }));
- };
- var makeVariableSlider = function(label, transform2, min2, value2, max2) {
- var onChoose = function(slider, _thumb, value3) {
- var valTransform = makeValueTransform(transform2, value3.x / 100);
- emitTransform(slider, valTransform);
- };
- return makeSlider(label, onChoose, min2, value2, max2);
- };
- var variableFilterPanelComponents = function(label, transform2, min2, value2, max2) {
- return [
- createBackButton(),
- makeVariableSlider(label, transform2, min2, value2, max2),
- createApplyButton()
- ];
- };
- var createVariableFilterPanel = function(label, transform2, min2, value2, max2) {
- var filterPanelComponents2 = variableFilterPanelComponents(label, transform2, min2, value2, max2);
- return Container.sketch({
- dom: panelDom,
- components: filterPanelComponents2.map(function(mem) {
- return mem.asSpec();
- }),
- containerBehaviours: derive$1([config("image-tools-filter-panel-buttons-events", [
- run$1(external.disable(), function(comp, _se) {
- disableAllComponents(filterPanelComponents2, comp);
- }),
- run$1(external.enable(), function(comp, _se) {
- enableAllComponents(filterPanelComponents2, comp);
- })
- ])])
- });
- };
- var filterPanelComponents = [
- createBackButton(),
- createSpacer(),
- createApplyButton()
- ];
- var FilterPanel = Container.sketch({
- dom: panelDom,
- components: filterPanelComponents.map(function(mem) {
- return mem.asSpec();
- })
- });
- var BrightnessPanel = createVariableFilterPanel("Brightness", brightness, -100, 0, 100);
- var ContrastPanel = createVariableFilterPanel("Contrast", contrast, -100, 0, 100);
- var GammaPanel = createVariableFilterPanel("Gamma", gamma, -100, 0, 100);
- var makeColorTransform = function(red2, green, blue) {
- return function(ir) {
- return colorize(ir, red2, green, blue);
- };
- };
- var makeColorSlider = function(label) {
- var onChoose = function(slider, _thumb, _value) {
- var redOpt = memRed.getOpt(slider);
- var blueOpt = memBlue.getOpt(slider);
- var greenOpt = memGreen.getOpt(slider);
- redOpt.each(function(red2) {
- blueOpt.each(function(blue) {
- greenOpt.each(function(green) {
- var r2 = Representing.getValue(red2).x / 100;
- var g = Representing.getValue(green).x / 100;
- var b2 = Representing.getValue(blue).x / 100;
- var transform2 = makeColorTransform(r2, g, b2);
- emitTransform(slider, transform2);
- });
- });
- });
- };
- return makeSlider(label, onChoose, 0, 100, 200);
- };
- var memRed = makeColorSlider("R");
- var memGreen = makeColorSlider("G");
- var memBlue = makeColorSlider("B");
- var colorizePanelComponents = [
- createBackButton(),
- memRed,
- memGreen,
- memBlue,
- createApplyButton()
- ];
- var ColorizePanel = Container.sketch({
- dom: panelDom,
- components: colorizePanelComponents.map(function(mem) {
- return mem.asSpec();
- })
- });
- var getTransformPanelEvent = function(panel, transform2, update) {
- return function(button2) {
- var swap2 = function() {
- memContainer.getOpt(button2).each(function(container2) {
- Replacing.set(container2, [panel]);
- update(container2);
- });
- };
- emit$1(button2, internal.swap(), {
- transform: transform2,
- swap: swap2
- });
- };
- };
- var cropPanelUpdate = function(_anyInSystem) {
- imagePanel.showCrop();
- };
- var resizePanelUpdate = function(anyInSystem) {
- memSize.getOpt(anyInSystem).each(function(sizeInput) {
- var measurements = imagePanel.getMeasurements();
- var width2 = measurements.width;
- var height2 = measurements.height;
- Representing.setValue(sizeInput, {
- width: width2,
- height: height2
- });
- });
- };
- var sharpenTransform = Optional.some(sharpen);
- var invertTransform = Optional.some(invert);
- var buttonPanelComponents = [
- createIconButton("crop", "Crop", getTransformPanelEvent(CropPanel, Optional.none(), cropPanelUpdate), false),
- createIconButton("resize", "Resize", getTransformPanelEvent(ResizePanel, Optional.none(), resizePanelUpdate), false),
- createIconButton("orientation", "Orientation", getTransformPanelEvent(FlipRotatePanel, Optional.none(), noop$1), false),
- createIconButton("brightness", "Brightness", getTransformPanelEvent(BrightnessPanel, Optional.none(), noop$1), false),
- createIconButton("sharpen", "Sharpen", getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
- createIconButton("contrast", "Contrast", getTransformPanelEvent(ContrastPanel, Optional.none(), noop$1), false),
- createIconButton("color-levels", "Color levels", getTransformPanelEvent(ColorizePanel, Optional.none(), noop$1), false),
- createIconButton("gamma", "Gamma", getTransformPanelEvent(GammaPanel, Optional.none(), noop$1), false),
- createIconButton("invert", "Invert", getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
- ];
- var ButtonPanel = Container.sketch({
- dom: panelDom,
- components: buttonPanelComponents.map(function(mem) {
- return mem.asSpec();
- })
- });
- var container = Container.sketch({
- dom: { tag: "div" },
- components: [ButtonPanel],
- containerBehaviours: derive$1([Replacing.config({})])
- });
- var memContainer = record(container);
- var getApplyButton = function(anyInSystem) {
- return memContainer.getOpt(anyInSystem).map(function(container2) {
- var panel = container2.components()[0];
- return panel.components()[panel.components().length - 1];
- });
- };
- return {
- memContainer,
- getApplyButton
- };
- };
- var global$4 = tinymce.util.Tools.resolve("tinymce.geom.Rect");
- var global$3 = tinymce.util.Tools.resolve("tinymce.util.Observable");
- var global$2 = tinymce.util.Tools.resolve("tinymce.util.VK");
- var getDocumentSize = function(doc) {
- var max2 = Math.max;
- var documentElement2 = doc.documentElement;
- var body2 = doc.body;
- var scrollWidth = max2(documentElement2.scrollWidth, body2.scrollWidth);
- var clientWidth = max2(documentElement2.clientWidth, body2.clientWidth);
- var offsetWidth = max2(documentElement2.offsetWidth, body2.offsetWidth);
- var scrollHeight = max2(documentElement2.scrollHeight, body2.scrollHeight);
- var clientHeight = max2(documentElement2.clientHeight, body2.clientHeight);
- var offsetHeight = max2(documentElement2.offsetHeight, body2.offsetHeight);
- return {
- width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
- height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
- };
- };
- var isTouchEvent$1 = function(e) {
- return isNonNullable(e.changedTouches);
- };
- var updateWithTouchData = function(e) {
- if (isTouchEvent$1(e)) {
- var keys2 = "screenX screenY pageX pageY clientX clientY".split(" ");
- for (var i = 0; i < keys2.length; i++) {
- e[keys2[i]] = e.changedTouches[0][keys2[i]];
- }
- }
- };
- function DragHelper(id, settings) {
- var _a2, _b, _c;
- var eventOverlay;
- var handleEvents = [];
- var overlayEvents = [];
- var doc = (_a2 = settings.document) !== null && _a2 !== void 0 ? _a2 : document;
- var root = (_b = settings.root) !== null && _b !== void 0 ? _b : doc;
- var sugarDoc = SugarElement.fromDom(doc);
- var downButton;
- var startX;
- var startY;
- var handleElement = SugarElement.fromDom(root.getElementById((_c = settings.handle) !== null && _c !== void 0 ? _c : id));
- var start = function(e) {
- var rawEvent = e.raw;
- var docSize = getDocumentSize(doc);
- updateWithTouchData(rawEvent);
- e.prevent();
- downButton = rawEvent.button;
- startX = rawEvent.screenX;
- startY = rawEvent.screenY;
- var cursor = get$c(handleElement, "cursor");
- eventOverlay = SugarElement.fromTag("div", doc);
- setAll(eventOverlay, {
- "position": "absolute",
- "top": "0",
- "left": "0",
- "width": docSize.width + "px",
- "height": docSize.height + "px",
- "z-index": "2147483647",
- "opacity": "0.0001",
- cursor
- });
- append$2(getBody(sugarDoc), eventOverlay);
- overlayEvents.push(bind(sugarDoc, "mousemove", drag), bind(sugarDoc, "touchmove", drag), bind(sugarDoc, "mouseup", stop2), bind(sugarDoc, "touchend", stop2));
- settings.start(rawEvent);
- };
- var drag = function(e) {
- var rawEvent = e.raw;
- updateWithTouchData(rawEvent);
- if (rawEvent.button !== downButton) {
- return stop2(e);
- }
- rawEvent.deltaX = rawEvent.screenX - startX;
- rawEvent.deltaY = rawEvent.screenY - startY;
- e.prevent();
- settings.drag(rawEvent);
- };
- var stop2 = function(e) {
- updateWithTouchData(e.raw);
- each$1(overlayEvents, function(e2) {
- return e2.unbind();
- });
- overlayEvents = [];
- remove$5(eventOverlay);
- if (settings.stop) {
- settings.stop(e.raw);
- }
- };
- var destroy = function() {
- each$1(overlayEvents.concat(handleEvents), function(e) {
- return e.unbind();
- });
- overlayEvents = [];
- handleEvents = [];
- if (isNonNullable(eventOverlay)) {
- remove$5(eventOverlay);
- }
- };
- handleEvents.push(bind(handleElement, "mousedown", start), bind(handleElement, "touchstart", start));
- return { destroy };
- }
- var count = 0;
- var create$2 = function(currentRect, viewPortRect, clampRect, containerElm, action) {
- var dragHelpers;
- var events2 = [];
- var prefix2 = "tox-";
- var id = prefix2 + "crid-" + count++;
- var container = SugarElement.fromDom(containerElm);
- var handles = [
- {
- name: "move",
- xMul: 0,
- yMul: 0,
- deltaX: 1,
- deltaY: 1,
- deltaW: 0,
- deltaH: 0,
- label: "Crop Mask"
- },
- {
- name: "nw",
- xMul: 0,
- yMul: 0,
- deltaX: 1,
- deltaY: 1,
- deltaW: -1,
- deltaH: -1,
- label: "Top Left Crop Handle"
- },
- {
- name: "ne",
- xMul: 1,
- yMul: 0,
- deltaX: 0,
- deltaY: 1,
- deltaW: 1,
- deltaH: -1,
- label: "Top Right Crop Handle"
- },
- {
- name: "sw",
- xMul: 0,
- yMul: 1,
- deltaX: 1,
- deltaY: 0,
- deltaW: -1,
- deltaH: 1,
- label: "Bottom Left Crop Handle"
- },
- {
- name: "se",
- xMul: 1,
- yMul: 1,
- deltaX: 0,
- deltaY: 0,
- deltaW: 1,
- deltaH: 1,
- label: "Bottom Right Crop Handle"
- }
- ];
- var blockers = [
- "top",
- "right",
- "bottom",
- "left"
- ];
- var getAbsoluteRect = function(outerRect, relativeRect) {
- return {
- x: relativeRect.x + outerRect.x,
- y: relativeRect.y + outerRect.y,
- w: relativeRect.w,
- h: relativeRect.h
- };
- };
- var getRelativeRect = function(outerRect, innerRect) {
- return {
- x: innerRect.x - outerRect.x,
- y: innerRect.y - outerRect.y,
- w: innerRect.w,
- h: innerRect.h
- };
- };
- var getInnerRect = function() {
- return getRelativeRect(clampRect, currentRect);
- };
- var moveRect = function(handle2, startRect, deltaX, deltaY) {
- var x = startRect.x + deltaX * handle2.deltaX;
- var y = startRect.y + deltaY * handle2.deltaY;
- var w = Math.max(20, startRect.w + deltaX * handle2.deltaW);
- var h = Math.max(20, startRect.h + deltaY * handle2.deltaH);
- var rect2 = currentRect = global$4.clamp({
- x,
- y,
- w,
- h
- }, clampRect, handle2.name === "move");
- rect2 = getRelativeRect(clampRect, rect2);
- instance.fire("updateRect", { rect: rect2 });
- setInnerRect(rect2);
- };
- var render2 = function() {
- var createDragHelper = function(handle2) {
- var startRect;
- return DragHelper(id, {
- document: containerElm.ownerDocument,
- root: getRootNode(container).dom,
- handle: id + "-" + handle2.name,
- start: function() {
- startRect = currentRect;
- },
- drag: function(e) {
- moveRect(handle2, startRect, e.deltaX, e.deltaY);
- }
- });
- };
- var cropContainer = SugarElement.fromTag("div");
- setAll$1(cropContainer, {
- id,
- "class": prefix2 + "croprect-container",
- "role": "grid",
- "aria-dropeffect": "execute"
- });
- append$2(container, cropContainer);
- each$1(blockers, function(blocker) {
- descendant(container, "#" + id).each(function(blockerElm) {
- var cropBlocker = SugarElement.fromTag("div");
- setAll$1(cropBlocker, {
- "id": id + "-" + blocker,
- "class": prefix2 + "croprect-block",
- "data-mce-bogus": "all"
- });
- set$7(cropBlocker, "display", "none");
- append$2(blockerElm, cropBlocker);
- });
- });
- each$1(handles, function(handle2) {
- descendant(container, "#" + id).each(function(handleElm) {
- var cropHandle = SugarElement.fromTag("div");
- setAll$1(cropHandle, {
- "id": id + "-" + handle2.name,
- "aria-label": handle2.label,
- "aria-grabbed": "false",
- "data-mce-bogus": "all",
- "role": "gridcell",
- "tabindex": "-1",
- "title": handle2.label
- });
- add$1(cropHandle, [
- prefix2 + "croprect-handle",
- prefix2 + "croprect-handle-" + handle2.name
- ]);
- set$7(cropHandle, "display", "none");
- append$2(handleElm, cropHandle);
- });
- });
- dragHelpers = map$2(handles, createDragHelper);
- repaint(currentRect);
- var handleFocus = function(e) {
- set$8(e.target, "aria-grabbed", e.raw.type === "focus" ? "true" : "false");
- };
- var handleKeydown = function(e) {
- var activeHandle;
- each$1(handles, function(handle2) {
- if (get$d(e.target, "id") === id + "-" + handle2.name) {
- activeHandle = handle2;
- return false;
- }
- });
- var moveAndBlock = function(evt, handle2, startRect, deltaX, deltaY) {
- evt.stopPropagation();
- evt.preventDefault();
- moveRect(activeHandle, startRect, deltaX, deltaY);
- };
- switch (e.raw.keyCode) {
- case global$2.LEFT:
- moveAndBlock(e, activeHandle, currentRect, -10, 0);
- break;
- case global$2.RIGHT:
- moveAndBlock(e, activeHandle, currentRect, 10, 0);
- break;
- case global$2.UP:
- moveAndBlock(e, activeHandle, currentRect, 0, -10);
- break;
- case global$2.DOWN:
- moveAndBlock(e, activeHandle, currentRect, 0, 10);
- break;
- case global$2.ENTER:
- case global$2.SPACEBAR:
- e.prevent();
- action();
- break;
- }
- };
- events2.push(bind(container, "focusin", handleFocus), bind(container, "focusout", handleFocus), bind(container, "keydown", handleKeydown));
- };
- var toggleVisibility = function(state) {
- var selectors = __spreadArray(__spreadArray([], map$2(handles, function(handle2) {
- return "#" + id + "-" + handle2.name;
- }), true), map$2(blockers, function(blocker) {
- return "#" + id + "-" + blocker;
- }), true).join(",");
- var elems = descendants(container, selectors);
- if (state) {
- each$1(elems, function(elm) {
- return remove$6(elm, "display");
- });
- } else {
- each$1(elems, function(elm) {
- return set$7(elm, "display", "none");
- });
- }
- };
- var repaint = function(rect2) {
- var updateElementRect = function(name2, newRect) {
- descendant(container, "#" + id + "-" + name2).each(function(elm) {
- setAll(elm, {
- left: newRect.x + "px",
- top: newRect.y + "px",
- width: Math.max(0, newRect.w) + "px",
- height: Math.max(0, newRect.h) + "px"
- });
- });
- };
- each$1(handles, function(handle2) {
- descendant(container, "#" + id + "-" + handle2.name).each(function(elm) {
- setAll(elm, {
- left: rect2.w * handle2.xMul + rect2.x + "px",
- top: rect2.h * handle2.yMul + rect2.y + "px"
- });
- });
- });
- updateElementRect("top", {
- x: viewPortRect.x,
- y: viewPortRect.y,
- w: viewPortRect.w,
- h: rect2.y - viewPortRect.y
- });
- updateElementRect("right", {
- x: rect2.x + rect2.w,
- y: rect2.y,
- w: viewPortRect.w - rect2.x - rect2.w + viewPortRect.x,
- h: rect2.h
- });
- updateElementRect("bottom", {
- x: viewPortRect.x,
- y: rect2.y + rect2.h,
- w: viewPortRect.w,
- h: viewPortRect.h - rect2.y - rect2.h + viewPortRect.y
- });
- updateElementRect("left", {
- x: viewPortRect.x,
- y: rect2.y,
- w: rect2.x - viewPortRect.x,
- h: rect2.h
- });
- updateElementRect("move", rect2);
- };
- var setRect = function(rect2) {
- currentRect = rect2;
- repaint(currentRect);
- };
- var setViewPortRect = function(rect2) {
- viewPortRect = rect2;
- repaint(currentRect);
- };
- var setInnerRect = function(rect2) {
- setRect(getAbsoluteRect(clampRect, rect2));
- };
- var setClampRect = function(rect2) {
- clampRect = rect2;
- repaint(currentRect);
- };
- var destroy = function() {
- each$1(dragHelpers, function(helper) {
- return helper.destroy();
- });
- dragHelpers = [];
- each$1(events2, function(e) {
- return e.unbind();
- });
- events2 = [];
- };
- render2();
- var instance = __assign(__assign({}, global$3), {
- toggleVisibility,
- setClampRect,
- setRect,
- getInnerRect,
- setInnerRect,
- setViewPortRect,
- destroy
- });
- return instance;
- };
- var CropRect = { create: create$2 };
- var loadImage = function(image) {
- return new global$c(function(resolve) {
- var loaded = function() {
- image.removeEventListener("load", loaded);
- resolve(image);
- };
- if (image.complete) {
- resolve(image);
- } else {
- image.addEventListener("load", loaded);
- }
- });
- };
- var renderImagePanel = function(initialUrl) {
- var memBg = record({
- dom: {
- tag: "div",
- classes: ["tox-image-tools__image-bg"],
- attributes: { role: "presentation" }
- }
- });
- var zoomState = Cell(1);
- var cropRect = api$1();
- var rectState = Cell({
- x: 0,
- y: 0,
- w: 1,
- h: 1
- });
- var viewRectState = Cell({
- x: 0,
- y: 0,
- w: 1,
- h: 1
- });
- var repaintImg = function(anyInSystem, img) {
- memContainer.getOpt(anyInSystem).each(function(panel) {
- var zoom3 = zoomState.get();
- var panelW = get$a(panel.element);
- var panelH = get$b(panel.element);
- var width2 = img.dom.naturalWidth * zoom3;
- var height2 = img.dom.naturalHeight * zoom3;
- var left2 = Math.max(0, panelW / 2 - width2 / 2);
- var top2 = Math.max(0, panelH / 2 - height2 / 2);
- var css = {
- left: left2.toString() + "px",
- top: top2.toString() + "px",
- width: width2.toString() + "px",
- height: height2.toString() + "px",
- position: "absolute"
- };
- setAll(img, css);
- memBg.getOpt(panel).each(function(bg) {
- setAll(bg.element, css);
- });
- cropRect.run(function(cRect) {
- var rect2 = rectState.get();
- cRect.setRect({
- x: rect2.x * zoom3 + left2,
- y: rect2.y * zoom3 + top2,
- w: rect2.w * zoom3,
- h: rect2.h * zoom3
- });
- cRect.setClampRect({
- x: left2,
- y: top2,
- w: width2,
- h: height2
- });
- cRect.setViewPortRect({
- x: 0,
- y: 0,
- w: panelW,
- h: panelH
- });
- });
- });
- };
- var zoomFit = function(anyInSystem, img) {
- memContainer.getOpt(anyInSystem).each(function(panel) {
- var panelW = get$a(panel.element);
- var panelH = get$b(panel.element);
- var width2 = img.dom.naturalWidth;
- var height2 = img.dom.naturalHeight;
- var zoom3 = Math.min(panelW / width2, panelH / height2);
- if (zoom3 >= 1) {
- zoomState.set(1);
- } else {
- zoomState.set(zoom3);
- }
- });
- };
- var updateSrc = function(anyInSystem, url) {
- var img = SugarElement.fromTag("img");
- set$8(img, "src", url);
- return loadImage(img.dom).then(function() {
- if (anyInSystem.getSystem().isConnected()) {
- memContainer.getOpt(anyInSystem).map(function(panel) {
- var aImg = external$2({ element: img });
- Replacing.replaceAt(panel, 1, Optional.some(aImg));
- var lastViewRect = viewRectState.get();
- var viewRect = {
- x: 0,
- y: 0,
- w: img.dom.naturalWidth,
- h: img.dom.naturalHeight
- };
- viewRectState.set(viewRect);
- var rect2 = global$4.inflate(viewRect, -20, -20);
- rectState.set(rect2);
- if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
- zoomFit(panel, img);
- }
- repaintImg(panel, img);
- });
- }
- });
- };
- var zoom2 = function(anyInSystem, direction) {
- var currentZoom = zoomState.get();
- var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
- zoomState.set(newZoom);
- memContainer.getOpt(anyInSystem).each(function(panel) {
- var img = panel.components()[1].element;
- repaintImg(panel, img);
- });
- };
- var showCrop = function() {
- cropRect.run(function(cRect) {
- cRect.toggleVisibility(true);
- });
- };
- var hideCrop = function() {
- cropRect.run(function(cRect) {
- cRect.toggleVisibility(false);
- });
- };
- var getRect = function() {
- return rectState.get();
- };
- var container = Container.sketch({
- dom: {
- tag: "div",
- classes: ["tox-image-tools__image"]
- },
- components: [
- memBg.asSpec(),
- {
- dom: {
- tag: "img",
- attributes: { src: initialUrl }
- }
- },
- {
- dom: { tag: "div" },
- behaviours: derive$1([config("image-panel-crop-events", [
- runOnAttached(function(comp) {
- memContainer.getOpt(comp).each(function(container2) {
- var el = container2.element.dom;
- var cRect = CropRect.create({
- x: 10,
- y: 10,
- w: 100,
- h: 100
- }, {
- x: 0,
- y: 0,
- w: 200,
- h: 200
- }, {
- x: 0,
- y: 0,
- w: 200,
- h: 200
- }, el, noop);
- cRect.toggleVisibility(false);
- cRect.on("updateRect", function(e) {
- var rect2 = e.rect;
- var zoom3 = zoomState.get();
- var newRect = {
- x: Math.round(rect2.x / zoom3),
- y: Math.round(rect2.y / zoom3),
- w: Math.round(rect2.w / zoom3),
- h: Math.round(rect2.h / zoom3)
- };
- rectState.set(newRect);
- });
- cropRect.set(cRect);
- });
- }),
- runOnDetached(function() {
- cropRect.clear();
- })
- ])])
- }
- ],
- containerBehaviours: derive$1([
- Replacing.config({}),
- config("image-panel-events", [runOnAttached(function(comp) {
- updateSrc(comp, initialUrl);
- })])
- ])
- });
- var memContainer = record(container);
- var getMeasurements = function() {
- var viewRect = viewRectState.get();
- return {
- width: viewRect.w,
- height: viewRect.h
- };
- };
- return {
- memContainer,
- updateSrc,
- zoom: zoom2,
- showCrop,
- hideCrop,
- getRect,
- getMeasurements
- };
- };
- var createButton = function(innerHtml, icon, disabled, action, providersBackstage) {
- return renderIconButton({
- name: innerHtml,
- icon: Optional.some(icon),
- disabled,
- tooltip: Optional.some(innerHtml),
- primary: false,
- borderless: false
- }, action, providersBackstage);
- };
- var setButtonEnabled = function(button2, enabled) {
- if (enabled) {
- Disabling.enable(button2);
- } else {
- Disabling.disable(button2);
- }
- };
- var renderSideBar = function(providersBackstage) {
- var updateButtonUndoStates = function(anyInSystem, undoEnabled, redoEnabled) {
- memUndo.getOpt(anyInSystem).each(function(undo2) {
- setButtonEnabled(undo2, undoEnabled);
- });
- memRedo.getOpt(anyInSystem).each(function(redo2) {
- setButtonEnabled(redo2, redoEnabled);
- });
- };
- var memUndo = record(createButton("Undo", "undo", true, function(button2) {
- emitWith(button2, internal.undo(), { direction: 1 });
- }, providersBackstage));
- var memRedo = record(createButton("Redo", "redo", true, function(button2) {
- emitWith(button2, internal.redo(), { direction: 1 });
- }, providersBackstage));
- var container = Container.sketch({
- dom: {
- tag: "div",
- classes: [
- "tox-image-tools__toolbar",
- "tox-image-tools__sidebar"
- ]
- },
- components: [
- memUndo.asSpec(),
- memRedo.asSpec(),
- createButton("Zoom in", "zoom-in", false, function(button2) {
- emitWith(button2, internal.zoom(), { direction: 1 });
- }, providersBackstage),
- createButton("Zoom out", "zoom-out", false, function(button2) {
- emitWith(button2, internal.zoom(), { direction: -1 });
- }, providersBackstage)
- ]
- });
- return {
- container,
- updateButtonUndoStates
- };
- };
- function UndoStack() {
- var data = [];
- var index = -1;
- var add2 = function(state) {
- var removed = data.splice(++index);
- data.push(state);
- return {
- state,
- removed
- };
- };
- var undo2 = function() {
- if (canUndo()) {
- return data[--index];
- }
- };
- var redo2 = function() {
- if (canRedo()) {
- return data[++index];
- }
- };
- var canUndo = function() {
- return index > 0;
- };
- var canRedo = function() {
- return index !== -1 && index < data.length - 1;
- };
- return {
- data,
- add: add2,
- undo: undo2,
- redo: redo2,
- canUndo,
- canRedo
- };
- }
- var makeState = function(initialState) {
- var blobState = Cell(initialState);
- var tempState = value$1();
- var undoStack = UndoStack();
- undoStack.add(initialState);
- var getBlobState = function() {
- return blobState.get();
- };
- var setBlobState = function(state) {
- blobState.set(state);
- };
- var getTempState = function() {
- return tempState.get().getOrThunk(blobState.get);
- };
- var updateTempState = function(blob) {
- var newTempState = createState(blob);
- destroyTempState();
- tempState.set(newTempState);
- return newTempState.url;
- };
- var createState = function(blob) {
- return {
- blob,
- url: URL.createObjectURL(blob)
- };
- };
- var destroyState = function(state) {
- URL.revokeObjectURL(state.url);
- };
- var destroyStates = function(states) {
- global$5.each(states, destroyState);
- };
- var destroyTempState = function() {
- tempState.on(destroyState);
- tempState.clear();
- };
- var addBlobState = function(blob) {
- var newState = createState(blob);
- setBlobState(newState);
- var removed = undoStack.add(newState).removed;
- destroyStates(removed);
- return newState.url;
- };
- var addTempState = function(blob) {
- var newState = createState(blob);
- tempState.set(newState);
- return newState.url;
- };
- var applyTempState = function(postApply) {
- return tempState.get().fold(noop, function(temp) {
- addBlobState(temp.blob);
- postApply();
- });
- };
- var undo2 = function() {
- var currentState = undoStack.undo();
- setBlobState(currentState);
- return currentState.url;
- };
- var redo2 = function() {
- var currentState = undoStack.redo();
- setBlobState(currentState);
- return currentState.url;
- };
- var getHistoryStates = function() {
- var undoEnabled = undoStack.canUndo();
- var redoEnabled = undoStack.canRedo();
- return {
- undoEnabled,
- redoEnabled
- };
- };
- return {
- getBlobState,
- setBlobState,
- addBlobState,
- getTempState,
- updateTempState,
- addTempState,
- applyTempState,
- destroyTempState,
- undo: undo2,
- redo: redo2,
- getHistoryStates
- };
- };
- var renderImageTools = function(detail, providersBackstage) {
- var state = makeState(detail.currentState);
- var zoom2 = function(anyInSystem, simulatedEvent) {
- var direction = simulatedEvent.event.direction;
- imagePanel.zoom(anyInSystem, direction);
- };
- var updateButtonUndoStates = function(anyInSystem) {
- var historyStates = state.getHistoryStates();
- sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
- emitWith(anyInSystem, external.formActionEvent, {
- name: external.saveState(),
- value: historyStates.undoEnabled
- });
- };
- var disableUndoRedo = function(anyInSystem) {
- sideBar.updateButtonUndoStates(anyInSystem, false, false);
- };
- var undo2 = function(anyInSystem, _simulatedEvent) {
- var url = state.undo();
- updateSrc(anyInSystem, url).then(function(_oImg) {
- unblock2(anyInSystem);
- updateButtonUndoStates(anyInSystem);
- });
- };
- var redo2 = function(anyInSystem, _simulatedEvent) {
- var url = state.redo();
- updateSrc(anyInSystem, url).then(function(_oImg) {
- unblock2(anyInSystem);
- updateButtonUndoStates(anyInSystem);
- });
- };
- var imageResultToBlob = function(ir) {
- return ir.toBlob();
- };
- var block2 = function(anyInSystem) {
- emitWith(anyInSystem, external.formActionEvent, {
- name: external.disable(),
- value: {}
- });
- };
- var unblock2 = function(anyInSystem) {
- editPanel.getApplyButton(anyInSystem).each(function(applyButton) {
- Disabling.enable(applyButton);
- });
- emitWith(anyInSystem, external.formActionEvent, {
- name: external.enable(),
- value: {}
- });
- };
- var updateSrc = function(anyInSystem, src) {
- block2(anyInSystem);
- return imagePanel.updateSrc(anyInSystem, src);
- };
- var blobManipulate = function(anyInSystem, blob, filter2, action, swap3) {
- block2(anyInSystem);
- blobToImageResult(blob).then(filter2).then(imageResultToBlob).then(action).then(function(url) {
- return updateSrc(anyInSystem, url);
- }).then(function() {
- updateButtonUndoStates(anyInSystem);
- swap3();
- unblock2(anyInSystem);
- }).catch(function(err) {
- console.log(err);
- if (anyInSystem.getSystem().isConnected()) {
- unblock2(anyInSystem);
- }
- });
- };
- var manipulate = function(anyInSystem, filter2, swap3) {
- var blob = state.getBlobState().blob;
- var action = function(blob2) {
- return state.updateTempState(blob2);
- };
- blobManipulate(anyInSystem, blob, filter2, action, swap3);
- };
- var tempManipulate = function(anyInSystem, filter2) {
- var blob = state.getTempState().blob;
- var action = function(blob2) {
- return state.addTempState(blob2);
- };
- blobManipulate(anyInSystem, blob, filter2, action, noop);
- };
- var manipulateApply = function(anyInSystem, filter2, swap3) {
- var blob = state.getBlobState().blob;
- var action = function(blob2) {
- var url = state.addBlobState(blob2);
- destroyTempState(anyInSystem);
- return url;
- };
- blobManipulate(anyInSystem, blob, filter2, action, swap3);
- };
- var apply2 = function(anyInSystem, simulatedEvent) {
- var postApply = function() {
- destroyTempState(anyInSystem);
- var swap3 = simulatedEvent.event.swap;
- swap3();
- };
- state.applyTempState(postApply);
- };
- var destroyTempState = function(anyInSystem) {
- var currentUrl = state.getBlobState().url;
- state.destroyTempState();
- updateButtonUndoStates(anyInSystem);
- return currentUrl;
- };
- var cancel = function(anyInSystem) {
- var currentUrl = destroyTempState(anyInSystem);
- updateSrc(anyInSystem, currentUrl).then(function(_oImg) {
- unblock2(anyInSystem);
- });
- };
- var back2 = function(anyInSystem, simulatedEvent) {
- cancel(anyInSystem);
- var swap3 = simulatedEvent.event.swap;
- swap3();
- imagePanel.hideCrop();
- };
- var transform2 = function(anyInSystem, simulatedEvent) {
- return manipulate(anyInSystem, simulatedEvent.event.transform, noop);
- };
- var tempTransform2 = function(anyInSystem, simulatedEvent) {
- return tempManipulate(anyInSystem, simulatedEvent.event.transform);
- };
- var transformApply2 = function(anyInSystem, simulatedEvent) {
- return manipulateApply(anyInSystem, simulatedEvent.event.transform, simulatedEvent.event.swap);
- };
- var imagePanel = renderImagePanel(detail.currentState.url);
- var sideBar = renderSideBar(providersBackstage);
- var editPanel = renderEditPanel(imagePanel, providersBackstage);
- var swap2 = function(anyInSystem, simulatedEvent) {
- disableUndoRedo(anyInSystem);
- var transform3 = simulatedEvent.event.transform;
- var swap3 = simulatedEvent.event.swap;
- transform3.fold(function() {
- swap3();
- }, function(transform4) {
- manipulate(anyInSystem, transform4, swap3);
- });
- };
- return {
- dom: {
- tag: "div",
- attributes: { role: "presentation" }
- },
- components: [
- editPanel.memContainer.asSpec(),
- imagePanel.memContainer.asSpec(),
- sideBar.container
- ],
- behaviours: derive$1([
- Representing.config({
- store: {
- mode: "manual",
- getValue: function() {
- return state.getBlobState();
- }
- }
- }),
- config("image-tools-events", [
- run$1(internal.undo(), undo2),
- run$1(internal.redo(), redo2),
- run$1(internal.zoom(), zoom2),
- run$1(internal.back(), back2),
- run$1(internal.apply(), apply2),
- run$1(internal.transform(), transform2),
- run$1(internal.tempTransform(), tempTransform2),
- run$1(internal.transformApply(), transformApply2),
- run$1(internal.swap(), swap2)
- ]),
- ComposingConfigs.self()
- ])
- };
- };
- var renderLabel = function(spec, backstageShared) {
- var label = {
- dom: {
- tag: "label",
- innerHtml: backstageShared.providers.translate(spec.label),
- classes: ["tox-label"]
- }
- };
- var comps = map$2(spec.items, backstageShared.interpreter);
- return {
- dom: {
- tag: "div",
- classes: ["tox-form__group"]
- },
- components: [label].concat(comps),
- behaviours: derive$1([
- ComposingConfigs.self(),
- Replacing.config({}),
- RepresentingConfigs.domHtml(Optional.none()),
- Keying.config({ mode: "acyclic" })
- ])
- };
- };
- var isSingleListItem = function(item2) {
- return !has$2(item2, "items");
- };
- var dataAttribute = "data-value";
- var fetchItems = function(dropdownComp, name2, items, selectedValue) {
- return map$2(items, function(item2) {
- if (!isSingleListItem(item2)) {
- return {
- type: "nestedmenuitem",
- text: item2.text,
- getSubmenuItems: function() {
- return fetchItems(dropdownComp, name2, item2.items, selectedValue);
- }
- };
- } else {
- return {
- type: "togglemenuitem",
- text: item2.text,
- value: item2.value,
- active: item2.value === selectedValue,
- onAction: function() {
- Representing.setValue(dropdownComp, item2.value);
- emitWith(dropdownComp, formChangeEvent, { name: name2 });
- Focusing.focus(dropdownComp);
- }
- };
- }
- });
- };
- var findItemByValue = function(items, value2) {
- return findMap(items, function(item2) {
- if (!isSingleListItem(item2)) {
- return findItemByValue(item2.items, value2);
- } else {
- return someIf(item2.value === value2, item2);
- }
- });
- };
- var renderListBox = function(spec, backstage) {
- var providersBackstage = backstage.shared.providers;
- var initialItem = head(spec.items).filter(isSingleListItem);
- var pLabel = spec.label.map(function(label) {
- return renderLabel$2(label, providersBackstage);
- });
- var pField = FormField.parts.field({
- dom: {},
- factory: {
- sketch: function(sketchSpec) {
- return renderCommonDropdown({
- uid: sketchSpec.uid,
- text: initialItem.map(function(item2) {
- return item2.text;
- }),
- icon: Optional.none(),
- tooltip: spec.label,
- role: Optional.none(),
- fetch: function(comp, callback) {
- var items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp));
- callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
- },
- onSetup: constant$1(noop),
- getApi: constant$1({}),
- columns: 1,
- presets: "normal",
- classes: [],
- dropdownBehaviours: [
- Tabstopping.config({}),
- Representing.config({
- store: {
- mode: "manual",
- initialValue: initialItem.map(function(item2) {
- return item2.value;
- }).getOr(""),
- getValue: function(comp) {
- return get$d(comp.element, dataAttribute);
- },
- setValue: function(comp, data) {
- findItemByValue(spec.items, data).each(function(item2) {
- set$8(comp.element, dataAttribute, item2.value);
- emitWith(comp, updateMenuText, { text: item2.text });
- });
- }
- }
- })
- ]
- }, "tox-listbox", backstage.shared);
- }
- }
- });
- var listBoxWrap = {
- dom: {
- tag: "div",
- classes: ["tox-listboxfield"]
- },
- components: [pField]
- };
- return FormField.sketch({
- dom: {
- tag: "div",
- classes: ["tox-form__group"]
- },
- components: flatten([
- pLabel.toArray(),
- [listBoxWrap]
- ]),
- fieldBehaviours: derive$1([Disabling.config({
- disabled: constant$1(spec.disabled),
- onDisabled: function(comp) {
- FormField.getField(comp).each(Disabling.disable);
- },
- onEnabled: function(comp) {
- FormField.getField(comp).each(Disabling.enable);
- }
- })])
- });
- };
- var renderPanel = function(spec, backstage) {
- return {
- dom: {
- tag: "div",
- classes: spec.classes
- },
- components: map$2(spec.items, backstage.shared.interpreter)
- };
- };
- var factory$e = function(detail, _spec) {
- var options = map$2(detail.options, function(option2) {
- return {
- dom: {
- tag: "option",
- value: option2.value,
- innerHtml: option2.text
- }
- };
- });
- var initialValues = detail.data.map(function(v) {
- return wrap$1("initialValue", v);
- }).getOr({});
- return {
- uid: detail.uid,
- dom: {
- tag: "select",
- classes: detail.selectClasses,
- attributes: detail.selectAttributes
- },
- components: options,
- behaviours: augment(detail.selectBehaviours, [
- Focusing.config({}),
- Representing.config({
- store: __assign({
- mode: "manual",
- getValue: function(select2) {
- return get$5(select2.element);
- },
- setValue: function(select2, newValue) {
- var found = find$5(detail.options, function(opt) {
- return opt.value === newValue;
- });
- if (found.isSome()) {
- set$4(select2.element, newValue);
- }
- }
- }, initialValues)
- })
- ])
- };
- };
- var HtmlSelect = single({
- name: "HtmlSelect",
- configFields: [
- required$1("options"),
- field("selectBehaviours", [
- Focusing,
- Representing
- ]),
- defaulted("selectClasses", []),
- defaulted("selectAttributes", {}),
- option("data")
- ],
- factory: factory$e
- });
- var renderSelectBox = function(spec, providersBackstage) {
- var translatedOptions = map$2(spec.items, function(item2) {
- return {
- text: providersBackstage.translate(item2.text),
- value: item2.value
- };
- });
- var pLabel = spec.label.map(function(label) {
- return renderLabel$2(label, providersBackstage);
- });
- var pField = FormField.parts.field({
- dom: {},
- selectAttributes: { size: spec.size },
- options: translatedOptions,
- factory: HtmlSelect,
- selectBehaviours: derive$1([
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- }
- }),
- Tabstopping.config({}),
- config("selectbox-change", [run$1(change(), function(component, _) {
- emitWith(component, formChangeEvent, { name: spec.name });
- })])
- ])
- });
- var chevron = spec.size > 1 ? Optional.none() : Optional.some(render$3("chevron-down", {
- tag: "div",
- classes: ["tox-selectfield__icon-js"]
- }, providersBackstage.icons));
- var selectWrap = {
- dom: {
- tag: "div",
- classes: ["tox-selectfield"]
- },
- components: flatten([
- [pField],
- chevron.toArray()
- ])
- };
- return FormField.sketch({
- dom: {
- tag: "div",
- classes: ["tox-form__group"]
- },
- components: flatten([
- pLabel.toArray(),
- [selectWrap]
- ]),
- fieldBehaviours: derive$1([
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- },
- onDisabled: function(comp) {
- FormField.getField(comp).each(Disabling.disable);
- },
- onEnabled: function(comp) {
- FormField.getField(comp).each(Disabling.enable);
- }
- }),
- receivingConfig()
- ])
- });
- };
- var renderTable = function(spec, providersBackstage) {
- var renderTh = function(text2) {
- return {
- dom: {
- tag: "th",
- innerHtml: providersBackstage.translate(text2)
- }
- };
- };
- var renderHeader2 = function(header) {
- return {
- dom: { tag: "thead" },
- components: [{
- dom: { tag: "tr" },
- components: map$2(header, renderTh)
- }]
- };
- };
- var renderTd = function(text2) {
- return {
- dom: {
- tag: "td",
- innerHtml: providersBackstage.translate(text2)
- }
- };
- };
- var renderTr = function(row) {
- return {
- dom: { tag: "tr" },
- components: map$2(row, renderTd)
- };
- };
- var renderRows = function(rows) {
- return {
- dom: { tag: "tbody" },
- components: map$2(rows, renderTr)
- };
- };
- return {
- dom: {
- tag: "table",
- classes: ["tox-dialog__table"]
- },
- components: [
- renderHeader2(spec.header),
- renderRows(spec.cells)
- ],
- behaviours: derive$1([
- Tabstopping.config({}),
- Focusing.config({})
- ])
- };
- };
- var renderTextField = function(spec, providersBackstage) {
- var pLabel = spec.label.map(function(label) {
- return renderLabel$2(label, providersBackstage);
- });
- var baseInputBehaviours = [
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- }
- }),
- receivingConfig(),
- Keying.config({
- mode: "execution",
- useEnter: spec.multiline !== true,
- useControlEnter: spec.multiline === true,
- execute: function(comp) {
- emit(comp, formSubmitEvent);
- return Optional.some(true);
- }
- }),
- config("textfield-change", [
- run$1(input(), function(component, _) {
- emitWith(component, formChangeEvent, { name: spec.name });
- }),
- run$1(postPaste(), function(component, _) {
- emitWith(component, formChangeEvent, { name: spec.name });
- })
- ]),
- Tabstopping.config({})
- ];
- var validatingBehaviours = spec.validation.map(function(vl) {
- return Invalidating.config({
- getRoot: function(input2) {
- return parent(input2.element);
- },
- invalidClass: "tox-invalid",
- validator: {
- validate: function(input2) {
- var v = Representing.getValue(input2);
- var result = vl.validator(v);
- return Future.pure(result === true ? Result.value(v) : Result.error(result));
- },
- validateOnLoad: vl.validateOnLoad
- }
- });
- }).toArray();
- var placeholder2 = spec.placeholder.fold(constant$1({}), function(p) {
- return { placeholder: providersBackstage.translate(p) };
- });
- var inputMode = spec.inputMode.fold(constant$1({}), function(mode) {
- return { inputmode: mode };
- });
- var inputAttributes = __assign(__assign({}, placeholder2), inputMode);
- var pField = FormField.parts.field({
- tag: spec.multiline === true ? "textarea" : "input",
- inputAttributes,
- inputClasses: [spec.classname],
- inputBehaviours: derive$1(flatten([
- baseInputBehaviours,
- validatingBehaviours
- ])),
- selectOnFocus: false,
- factory: Input
- });
- var extraClasses = spec.flex ? ["tox-form__group--stretched"] : [];
- var extraClasses2 = extraClasses.concat(spec.maximized ? ["tox-form-group--maximize"] : []);
- var extraBehaviours = [
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- },
- onDisabled: function(comp) {
- FormField.getField(comp).each(Disabling.disable);
- },
- onEnabled: function(comp) {
- FormField.getField(comp).each(Disabling.enable);
- }
- }),
- receivingConfig()
- ];
- return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
- };
- var renderInput = function(spec, providersBackstage) {
- return renderTextField({
- name: spec.name,
- multiline: false,
- label: spec.label,
- inputMode: spec.inputMode,
- placeholder: spec.placeholder,
- flex: false,
- disabled: spec.disabled,
- classname: "tox-textfield",
- validation: Optional.none(),
- maximized: spec.maximized
- }, providersBackstage);
- };
- var renderTextarea = function(spec, providersBackstage) {
- return renderTextField({
- name: spec.name,
- multiline: true,
- label: spec.label,
- inputMode: Optional.none(),
- placeholder: spec.placeholder,
- flex: true,
- disabled: spec.disabled,
- classname: "tox-textarea",
- validation: Optional.none(),
- maximized: spec.maximized
- }, providersBackstage);
- };
- var events$6 = function(streamConfig, streamState) {
- var streams = streamConfig.stream.streams;
- var processor = streams.setup(streamConfig, streamState);
- return derive$2([
- run$1(streamConfig.event, processor),
- runOnDetached(function() {
- return streamState.cancel();
- })
- ].concat(streamConfig.cancelEvent.map(function(e) {
- return [run$1(e, function() {
- return streamState.cancel();
- })];
- }).getOr([])));
- };
- var ActiveStreaming = Object.freeze({
- __proto__: null,
- events: events$6
- });
- var throttle = function(_config) {
- var state = Cell(null);
- var readState = function() {
- return { timer: state.get() !== null ? "set" : "unset" };
- };
- var setTimer = function(t2) {
- state.set(t2);
- };
- var cancel = function() {
- var t2 = state.get();
- if (t2 !== null) {
- t2.cancel();
- }
- };
- return nu$8({
- readState,
- setTimer,
- cancel
- });
- };
- var init$9 = function(spec) {
- return spec.stream.streams.state(spec);
- };
- var StreamingState = Object.freeze({
- __proto__: null,
- throttle,
- init: init$9
- });
- var setup$c = function(streamInfo, streamState) {
- var sInfo = streamInfo.stream;
- var throttler = last(streamInfo.onStream, sInfo.delay);
- streamState.setTimer(throttler);
- return function(component, simulatedEvent) {
- throttler.throttle(component, simulatedEvent);
- if (sInfo.stopEvent) {
- simulatedEvent.stop();
- }
- };
- };
- var StreamingSchema = [
- requiredOf("stream", choose$1("mode", {
- throttle: [
- required$1("delay"),
- defaulted("stopEvent", true),
- output$1("streams", {
- setup: setup$c,
- state: throttle
- })
- ]
- })),
- defaulted("event", "input"),
- option("cancelEvent"),
- onStrictHandler("onStream")
- ];
- var Streaming = create$8({
- fields: StreamingSchema,
- name: "streaming",
- active: ActiveStreaming,
- state: StreamingState
- });
- var setValueFromItem = function(model, input2, item2) {
- var itemData = Representing.getValue(item2);
- Representing.setValue(input2, itemData);
- setCursorAtEnd(input2);
- };
- var setSelectionOn = function(input2, f) {
- var el = input2.element;
- var value2 = get$5(el);
- var node = el.dom;
- if (get$d(el, "type") !== "number") {
- f(node, value2);
- }
- };
- var setCursorAtEnd = function(input2) {
- setSelectionOn(input2, function(node, value2) {
- return node.setSelectionRange(value2.length, value2.length);
- });
- };
- var setSelectionToEnd = function(input2, startOffset) {
- setSelectionOn(input2, function(node, value2) {
- return node.setSelectionRange(startOffset, value2.length);
- });
- };
- var attemptSelectOver = function(model, input2, item2) {
- if (!model.selectsOver) {
- return Optional.none();
- } else {
- var currentValue2 = Representing.getValue(input2);
- var inputDisplay_1 = model.getDisplayText(currentValue2);
- var itemValue = Representing.getValue(item2);
- var itemDisplay = model.getDisplayText(itemValue);
- return itemDisplay.indexOf(inputDisplay_1) === 0 ? Optional.some(function() {
- setValueFromItem(model, input2, item2);
- setSelectionToEnd(input2, inputDisplay_1.length);
- }) : Optional.none();
- }
- };
- var itemExecute = constant$1("alloy.typeahead.itemexecute");
- var make$3 = function(detail, components2, spec, externals) {
- var navigateList = function(comp, simulatedEvent, highlighter) {
- detail.previewing.set(false);
- var sandbox = Coupling.getCoupled(comp, "sandbox");
- if (Sandboxing.isOpen(sandbox)) {
- Composing.getCurrent(sandbox).each(function(menu2) {
- Highlighting.getHighlighted(menu2).fold(function() {
- highlighter(menu2);
- }, function() {
- dispatchEvent(sandbox, menu2.element, "keydown", simulatedEvent);
- });
- });
- } else {
- var onOpenSync = function(sandbox2) {
- Composing.getCurrent(sandbox2).each(highlighter);
- };
- open(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
- }
- };
- var focusBehaviours$1 = focusBehaviours(detail);
- var mapFetch = function(comp) {
- return function(tdata) {
- return tdata.map(function(data) {
- var menus = values(data.menus);
- var items = bind$3(menus, function(menu2) {
- return filter$2(menu2.items, function(item2) {
- return item2.type === "item";
- });
- });
- var repState = Representing.getState(comp);
- repState.update(map$2(items, function(item2) {
- return item2.data;
- }));
- return data;
- });
- };
- };
- var behaviours2 = [
- Focusing.config({}),
- Representing.config({
- onSetValue: detail.onSetValue,
- store: __assign({
- mode: "dataset",
- getDataKey: function(comp) {
- return get$5(comp.element);
- },
- getFallbackEntry: function(itemString) {
- return {
- value: itemString,
- meta: {}
- };
- },
- setValue: function(comp, data) {
- set$4(comp.element, detail.model.getDisplayText(data));
- }
- }, detail.initialData.map(function(d) {
- return wrap$1("initialValue", d);
- }).getOr({}))
- }),
- Streaming.config({
- stream: {
- mode: "throttle",
- delay: detail.responseTime,
- stopEvent: false
- },
- onStream: function(component, _simulatedEvent) {
- var sandbox = Coupling.getCoupled(component, "sandbox");
- var focusInInput = Focusing.isFocused(component);
- if (focusInInput) {
- if (get$5(component.element).length >= detail.minChars) {
- var previousValue_1 = Composing.getCurrent(sandbox).bind(function(menu2) {
- return Highlighting.getHighlighted(menu2).map(Representing.getValue);
- });
- detail.previewing.set(true);
- var onOpenSync = function(_sandbox) {
- Composing.getCurrent(sandbox).each(function(menu2) {
- previousValue_1.fold(function() {
- if (detail.model.selectsOver) {
- Highlighting.highlightFirst(menu2);
- }
- }, function(pv) {
- Highlighting.highlightBy(menu2, function(item2) {
- var itemData = Representing.getValue(item2);
- return itemData.value === pv.value;
- });
- Highlighting.getHighlighted(menu2).orThunk(function() {
- Highlighting.highlightFirst(menu2);
- return Optional.none();
- });
- });
- });
- };
- open(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
- }
- }
- },
- cancelEvent: typeaheadCancel()
- }),
- Keying.config({
- mode: "special",
- onDown: function(comp, simulatedEvent) {
- navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
- return Optional.some(true);
- },
- onEscape: function(comp) {
- var sandbox = Coupling.getCoupled(comp, "sandbox");
- if (Sandboxing.isOpen(sandbox)) {
- Sandboxing.close(sandbox);
- return Optional.some(true);
- }
- return Optional.none();
- },
- onUp: function(comp, simulatedEvent) {
- navigateList(comp, simulatedEvent, Highlighting.highlightLast);
- return Optional.some(true);
- },
- onEnter: function(comp) {
- var sandbox = Coupling.getCoupled(comp, "sandbox");
- var sandboxIsOpen = Sandboxing.isOpen(sandbox);
- if (sandboxIsOpen && !detail.previewing.get()) {
- return Composing.getCurrent(sandbox).bind(function(menu2) {
- return Highlighting.getHighlighted(menu2);
- }).map(function(item2) {
- emitWith(comp, itemExecute(), { item: item2 });
- return true;
- });
- } else {
- var currentValue2 = Representing.getValue(comp);
- emit(comp, typeaheadCancel());
- detail.onExecute(sandbox, comp, currentValue2);
- if (sandboxIsOpen) {
- Sandboxing.close(sandbox);
- }
- return Optional.some(true);
- }
- }
- }),
- Toggling.config({
- toggleClass: detail.markers.openClass,
- aria: { mode: "expanded" }
- }),
- Coupling.config({
- others: {
- sandbox: function(hotspot) {
- return makeSandbox$1(detail, hotspot, {
- onOpen: function() {
- return Toggling.on(hotspot);
- },
- onClose: function() {
- return Toggling.off(hotspot);
- }
- });
- }
- }
- }),
- config("typeaheadevents", [
- runOnExecute$1(function(comp) {
- var onOpenSync = noop;
- togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
- }),
- run$1(itemExecute(), function(comp, se) {
- var sandbox = Coupling.getCoupled(comp, "sandbox");
- setValueFromItem(detail.model, comp, se.event.item);
- emit(comp, typeaheadCancel());
- detail.onItemExecute(comp, sandbox, se.event.item, Representing.getValue(comp));
- Sandboxing.close(sandbox);
- setCursorAtEnd(comp);
- })
- ].concat(detail.dismissOnBlur ? [run$1(postBlur(), function(typeahead) {
- var sandbox = Coupling.getCoupled(typeahead, "sandbox");
- if (search(sandbox.element).isNone()) {
- Sandboxing.close(sandbox);
- }
- })] : []))
- ];
- return {
- uid: detail.uid,
- dom: dom(deepMerge(detail, {
- inputAttributes: {
- "role": "combobox",
- "aria-autocomplete": "list",
- "aria-haspopup": "true"
- }
- })),
- behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours2)),
- eventOrder: detail.eventOrder
- };
- };
- var schema$g = constant$1([
- option("lazySink"),
- required$1("fetch"),
- defaulted("minChars", 5),
- defaulted("responseTime", 1e3),
- onHandler("onOpen"),
- defaulted("getHotspot", Optional.some),
- defaulted("getAnchorOverrides", constant$1({})),
- defaulted("layouts", Optional.none()),
- defaulted("eventOrder", {}),
- defaultedObjOf("model", {}, [
- defaulted("getDisplayText", function(itemData) {
- return itemData.meta !== void 0 && itemData.meta.text !== void 0 ? itemData.meta.text : itemData.value;
- }),
- defaulted("selectsOver", true),
- defaulted("populateFromBrowse", true)
- ]),
- onHandler("onSetValue"),
- onKeyboardHandler("onExecute"),
- onHandler("onItemExecute"),
- defaulted("inputClasses", []),
- defaulted("inputAttributes", {}),
- defaulted("inputStyles", {}),
- defaulted("matchWidth", true),
- defaulted("useMinWidth", false),
- defaulted("dismissOnBlur", true),
- markers$1(["openClass"]),
- option("initialData"),
- field("typeaheadBehaviours", [
- Focusing,
- Representing,
- Streaming,
- Keying,
- Toggling,
- Coupling
- ]),
- customField("previewing", function() {
- return Cell(true);
- })
- ].concat(schema$k()).concat(sandboxFields()));
- var parts$b = constant$1([external$1({
- schema: [tieredMenuMarkers()],
- name: "menu",
- overrides: function(detail) {
- return {
- fakeFocus: true,
- onHighlight: function(menu2, item2) {
- if (!detail.previewing.get()) {
- menu2.getSystem().getByUid(detail.uid).each(function(input2) {
- if (detail.model.populateFromBrowse) {
- setValueFromItem(detail.model, input2, item2);
- }
- });
- } else {
- menu2.getSystem().getByUid(detail.uid).each(function(input2) {
- attemptSelectOver(detail.model, input2, item2).fold(function() {
- return Highlighting.dehighlight(menu2, item2);
- }, function(fn) {
- return fn();
- });
- });
- }
- detail.previewing.set(false);
- },
- onExecute: function(menu2, item2) {
- return menu2.getSystem().getByUid(detail.uid).toOptional().map(function(typeahead) {
- emitWith(typeahead, itemExecute(), { item: item2 });
- return true;
- });
- },
- onHover: function(menu2, item2) {
- detail.previewing.set(false);
- menu2.getSystem().getByUid(detail.uid).each(function(input2) {
- if (detail.model.populateFromBrowse) {
- setValueFromItem(detail.model, input2, item2);
- }
- });
- }
- };
- }
- })]);
- var Typeahead = composite({
- name: "Typeahead",
- configFields: schema$g(),
- partFields: parts$b(),
- factory: make$3
- });
- var wrap = function(delegate) {
- var toCached = function() {
- return wrap(delegate.toCached());
- };
- var bindFuture = function(f) {
- return wrap(delegate.bind(function(resA) {
- return resA.fold(function(err) {
- return Future.pure(Result.error(err));
- }, function(a) {
- return f(a);
- });
- }));
- };
- var bindResult = function(f) {
- return wrap(delegate.map(function(resA) {
- return resA.bind(f);
- }));
- };
- var mapResult = function(f) {
- return wrap(delegate.map(function(resA) {
- return resA.map(f);
- }));
- };
- var mapError2 = function(f) {
- return wrap(delegate.map(function(resA) {
- return resA.mapError(f);
- }));
- };
- var foldResult = function(whenError, whenValue) {
- return delegate.map(function(res) {
- return res.fold(whenError, whenValue);
- });
- };
- var withTimeout = function(timeout, errorThunk) {
- return wrap(Future.nu(function(callback) {
- var timedOut = false;
- var timer = setTimeout(function() {
- timedOut = true;
- callback(Result.error(errorThunk()));
- }, timeout);
- delegate.get(function(result) {
- if (!timedOut) {
- clearTimeout(timer);
- callback(result);
- }
- });
- }));
- };
- return __assign(__assign({}, delegate), {
- toCached,
- bindFuture,
- bindResult,
- mapResult,
- mapError: mapError2,
- foldResult,
- withTimeout
- });
- };
- var nu$1 = function(worker) {
- return wrap(Future.nu(worker));
- };
- var value = function(value2) {
- return wrap(Future.pure(Result.value(value2)));
- };
- var error = function(error2) {
- return wrap(Future.pure(Result.error(error2)));
- };
- var fromResult = function(result) {
- return wrap(Future.pure(result));
- };
- var fromFuture = function(future) {
- return wrap(future.map(Result.value));
- };
- var fromPromise = function(promise) {
- return nu$1(function(completer) {
- promise.then(function(value2) {
- completer(Result.value(value2));
- }, function(error2) {
- completer(Result.error(error2));
- });
- });
- };
- var FutureResult = {
- nu: nu$1,
- wrap,
- pure: value,
- value,
- error,
- fromResult,
- fromFuture,
- fromPromise
- };
- var separator$1 = { type: "separator" };
- var toMenuItem = function(target) {
- return {
- type: "menuitem",
- value: target.url,
- text: target.title,
- meta: { attach: target.attach },
- onAction: noop
- };
- };
- var staticMenuItem = function(title, url) {
- return {
- type: "menuitem",
- value: url,
- text: title,
- meta: { attach: void 0 },
- onAction: noop
- };
- };
- var toMenuItems = function(targets) {
- return map$2(targets, toMenuItem);
- };
- var filterLinkTargets = function(type2, targets) {
- return filter$2(targets, function(target) {
- return target.type === type2;
- });
- };
- var filteredTargets = function(type2, targets) {
- return toMenuItems(filterLinkTargets(type2, targets));
- };
- var headerTargets = function(linkInfo) {
- return filteredTargets("header", linkInfo.targets);
- };
- var anchorTargets = function(linkInfo) {
- return filteredTargets("anchor", linkInfo.targets);
- };
- var anchorTargetTop = function(linkInfo) {
- return Optional.from(linkInfo.anchorTop).map(function(url) {
- return staticMenuItem("<top>", url);
- }).toArray();
- };
- var anchorTargetBottom = function(linkInfo) {
- return Optional.from(linkInfo.anchorBottom).map(function(url) {
- return staticMenuItem("<bottom>", url);
- }).toArray();
- };
- var historyTargets = function(history) {
- return map$2(history, function(url) {
- return staticMenuItem(url, url);
- });
- };
- var joinMenuLists = function(items) {
- return foldl(items, function(a, b2) {
- var bothEmpty = a.length === 0 || b2.length === 0;
- return bothEmpty ? a.concat(b2) : a.concat(separator$1, b2);
- }, []);
- };
- var filterByQuery = function(term, menuItems) {
- var lowerCaseTerm = term.toLowerCase();
- return filter$2(menuItems, function(item2) {
- var text2 = item2.meta !== void 0 && item2.meta.text !== void 0 ? item2.meta.text : item2.text;
- return contains$1(text2.toLowerCase(), lowerCaseTerm) || contains$1(item2.value.toLowerCase(), lowerCaseTerm);
- });
- };
- var getItems = function(fileType, input2, urlBackstage) {
- var urlInputValue = Representing.getValue(input2);
- var term = urlInputValue.meta.text !== void 0 ? urlInputValue.meta.text : urlInputValue.value;
- var info = urlBackstage.getLinkInformation();
- return info.fold(function() {
- return [];
- }, function(linkInfo) {
- var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
- return fileType === "file" ? joinMenuLists([
- history,
- filterByQuery(term, headerTargets(linkInfo)),
- filterByQuery(term, flatten([
- anchorTargetTop(linkInfo),
- anchorTargets(linkInfo),
- anchorTargetBottom(linkInfo)
- ]))
- ]) : history;
- });
- };
- var errorId = generate$6("aria-invalid");
- var renderUrlInput = function(spec, backstage, urlBackstage) {
- var _a2;
- var providersBackstage = backstage.shared.providers;
- var updateHistory = function(component) {
- var urlEntry = Representing.getValue(component);
- urlBackstage.addToHistory(urlEntry.value, spec.filetype);
- };
- var pField = FormField.parts.field({
- factory: Typeahead,
- dismissOnBlur: true,
- inputClasses: ["tox-textfield"],
- sandboxClasses: ["tox-dialog__popups"],
- inputAttributes: {
- "aria-errormessage": errorId,
- "type": "url"
- },
- minChars: 0,
- responseTime: 0,
- fetch: function(input2) {
- var items = getItems(spec.filetype, input2, urlBackstage);
- var tdata = build(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
- return Future.pure(tdata);
- },
- getHotspot: function(comp) {
- return memUrlBox.getOpt(comp);
- },
- onSetValue: function(comp, _newValue) {
- if (comp.hasConfigured(Invalidating)) {
- Invalidating.run(comp).get(noop);
- }
- },
- typeaheadBehaviours: derive$1(flatten([
- urlBackstage.getValidationHandler().map(function(handler) {
- return Invalidating.config({
- getRoot: function(comp) {
- return parent(comp.element);
- },
- invalidClass: "tox-control-wrap--status-invalid",
- notify: {
- onInvalid: function(comp, err) {
- memInvalidIcon.getOpt(comp).each(function(invalidComp) {
- set$8(invalidComp.element, "title", providersBackstage.translate(err));
- });
- }
- },
- validator: {
- validate: function(input2) {
- var urlEntry = Representing.getValue(input2);
- return FutureResult.nu(function(completer) {
- handler({
- type: spec.filetype,
- url: urlEntry.value
- }, function(validation) {
- if (validation.status === "invalid") {
- var err = Result.error(validation.message);
- completer(err);
- } else {
- var val = Result.value(validation.message);
- completer(val);
- }
- });
- });
- },
- validateOnLoad: false
- }
- });
- }).toArray(),
- [
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- }
- }),
- Tabstopping.config({}),
- config("urlinput-events", flatten([
- spec.filetype === "file" ? [run$1(input(), function(comp) {
- emitWith(comp, formChangeEvent, { name: spec.name });
- })] : [],
- [
- run$1(change(), function(comp) {
- emitWith(comp, formChangeEvent, { name: spec.name });
- updateHistory(comp);
- }),
- run$1(postPaste(), function(comp) {
- emitWith(comp, formChangeEvent, { name: spec.name });
- updateHistory(comp);
- })
- ]
- ]))
- ]
- ])),
- eventOrder: (_a2 = {}, _a2[input()] = [
- "streaming",
- "urlinput-events",
- "invalidating"
- ], _a2),
- model: {
- getDisplayText: function(itemData) {
- return itemData.value;
- },
- selectsOver: false,
- populateFromBrowse: false
- },
- markers: { openClass: "tox-textfield--popup-open" },
- lazySink: backstage.shared.getSink,
- parts: { menu: part(false, 1, "normal") },
- onExecute: function(_menu, component, _entry) {
- emitWith(component, formSubmitEvent, {});
- },
- onItemExecute: function(typeahead, _sandbox, _item, _value) {
- updateHistory(typeahead);
- emitWith(typeahead, formChangeEvent, { name: spec.name });
- }
- });
- var pLabel = spec.label.map(function(label) {
- return renderLabel$2(label, providersBackstage);
- });
- var makeIcon = function(name2, errId, icon, label) {
- if (icon === void 0) {
- icon = name2;
- }
- if (label === void 0) {
- label = name2;
- }
- return render$3(icon, {
- tag: "div",
- classes: [
- "tox-icon",
- "tox-control-wrap__status-icon-" + name2
- ],
- attributes: __assign({
- "title": providersBackstage.translate(label),
- "aria-live": "polite"
- }, errId.fold(function() {
- return {};
- }, function(id) {
- return { id };
- }))
- }, providersBackstage.icons);
- };
- var memInvalidIcon = record(makeIcon("invalid", Optional.some(errorId), "warning"));
- var memStatus = record({
- dom: {
- tag: "div",
- classes: ["tox-control-wrap__status-icon-wrap"]
- },
- components: [memInvalidIcon.asSpec()]
- });
- var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
- var browseUrlEvent = generate$6("browser.url.event");
- var memUrlBox = record({
- dom: {
- tag: "div",
- classes: ["tox-control-wrap"]
- },
- components: [
- pField,
- memStatus.asSpec()
- ],
- behaviours: derive$1([Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- }
- })])
- });
- var memUrlPickerButton = record(renderButton({
- name: spec.name,
- icon: Optional.some("browse"),
- text: spec.label.getOr(""),
- disabled: spec.disabled,
- primary: false,
- borderless: true
- }, function(component) {
- return emit(component, browseUrlEvent);
- }, providersBackstage, [], ["tox-browse-url"]));
- var controlHWrapper = function() {
- return {
- dom: {
- tag: "div",
- classes: ["tox-form__controls-h-stack"]
- },
- components: flatten([
- [memUrlBox.asSpec()],
- optUrlPicker.map(function() {
- return memUrlPickerButton.asSpec();
- }).toArray()
- ])
- };
- };
- var openUrlPicker = function(comp) {
- Composing.getCurrent(comp).each(function(field2) {
- var componentData = Representing.getValue(field2);
- var urlData = __assign({ fieldname: spec.name }, componentData);
- optUrlPicker.each(function(picker) {
- picker(urlData).get(function(chosenData) {
- Representing.setValue(field2, chosenData);
- emitWith(comp, formChangeEvent, { name: spec.name });
- });
- });
- });
- };
- return FormField.sketch({
- dom: renderFormFieldDom(),
- components: pLabel.toArray().concat([controlHWrapper()]),
- fieldBehaviours: derive$1([
- Disabling.config({
- disabled: function() {
- return spec.disabled || providersBackstage.isDisabled();
- },
- onDisabled: function(comp) {
- FormField.getField(comp).each(Disabling.disable);
- memUrlPickerButton.getOpt(comp).each(Disabling.disable);
- },
- onEnabled: function(comp) {
- FormField.getField(comp).each(Disabling.enable);
- memUrlPickerButton.getOpt(comp).each(Disabling.enable);
- }
- }),
- receivingConfig(),
- config("url-input-events", [run$1(browseUrlEvent, openUrlPicker)])
- ])
- });
- };
- var renderAlertBanner = function(spec, providersBackstage) {
- return Container.sketch({
- dom: {
- tag: "div",
- attributes: { role: "alert" },
- classes: [
- "tox-notification",
- "tox-notification--in",
- "tox-notification--" + spec.level
- ]
- },
- components: [
- {
- dom: {
- tag: "div",
- classes: ["tox-notification__icon"]
- },
- components: [Button.sketch({
- dom: {
- tag: "button",
- classes: [
- "tox-button",
- "tox-button--naked",
- "tox-button--icon"
- ],
- innerHtml: get$1(spec.icon, providersBackstage.icons),
- attributes: { title: providersBackstage.translate(spec.iconTooltip) }
- },
- action: function(comp) {
- emitWith(comp, formActionEvent, {
- name: "alert-banner",
- value: spec.url
- });
- },
- buttonBehaviours: derive$1([addFocusableBehaviour()])
- })]
- },
- {
- dom: {
- tag: "div",
- classes: ["tox-notification__body"],
- innerHtml: providersBackstage.translate(spec.text)
- }
- }
- ]
- });
- };
- var renderCheckbox = function(spec, providerBackstage) {
- var repBehaviour = Representing.config({
- store: {
- mode: "manual",
- getValue: function(comp) {
- var el = comp.element.dom;
- return el.checked;
- },
- setValue: function(comp, value2) {
- var el = comp.element.dom;
- el.checked = value2;
- }
- }
- });
- var toggleCheckboxHandler = function(comp) {
- comp.element.dom.click();
- return Optional.some(true);
- };
- var pField = FormField.parts.field({
- factory: { sketch: identity$1 },
- dom: {
- tag: "input",
- classes: ["tox-checkbox__input"],
- attributes: { type: "checkbox" }
- },
- behaviours: derive$1([
- ComposingConfigs.self(),
- Disabling.config({
- disabled: function() {
- return spec.disabled || providerBackstage.isDisabled();
- }
- }),
- Tabstopping.config({}),
- Focusing.config({}),
- repBehaviour,
- Keying.config({
- mode: "special",
- onEnter: toggleCheckboxHandler,
- onSpace: toggleCheckboxHandler,
- stopSpaceKeyup: true
- }),
- config("checkbox-events", [run$1(change(), function(component, _) {
- emitWith(component, formChangeEvent, { name: spec.name });
- })])
- ])
- });
- var pLabel = FormField.parts.label({
- dom: {
- tag: "span",
- classes: ["tox-checkbox__label"],
- innerHtml: providerBackstage.translate(spec.label)
- },
- behaviours: derive$1([Unselecting.config({})])
- });
- var makeIcon = function(className) {
- var iconName = className === "checked" ? "selected" : "unselected";
- return render$3(iconName, {
- tag: "span",
- classes: [
- "tox-icon",
- "tox-checkbox-icon__" + className
- ]
- }, providerBackstage.icons);
- };
- var memIcons = record({
- dom: {
- tag: "div",
- classes: ["tox-checkbox__icons"]
- },
- components: [
- makeIcon("checked"),
- makeIcon("unchecked")
- ]
- });
- return FormField.sketch({
- dom: {
- tag: "label",
- classes: ["tox-checkbox"]
- },
- components: [
- pField,
- memIcons.asSpec(),
- pLabel
- ],
- fieldBehaviours: derive$1([
- Disabling.config({
- disabled: function() {
- return spec.disabled || providerBackstage.isDisabled();
- },
- disableClass: "tox-checkbox--disabled",
- onDisabled: function(comp) {
- FormField.getField(comp).each(Disabling.disable);
- },
- onEnabled: function(comp) {
- FormField.getField(comp).each(Disabling.enable);
- }
- }),
- receivingConfig()
- ])
- });
- };
- var renderHtmlPanel = function(spec) {
- if (spec.presets === "presentation") {
- return Container.sketch({
- dom: {
- tag: "div",
- classes: ["tox-form__group"],
- innerHtml: spec.html
- }
- });
- } else {
- return Container.sketch({
- dom: {
- tag: "div",
- classes: ["tox-form__group"],
- innerHtml: spec.html,
- attributes: { role: "document" }
- },
- containerBehaviours: derive$1([
- Tabstopping.config({}),
- Focusing.config({})
- ])
- });
- }
- };
- var make$2 = function(render2) {
- return function(parts2, spec, backstage) {
- return get$e(spec, "name").fold(function() {
- return render2(spec, backstage);
- }, function(fieldName) {
- return parts2.field(fieldName, render2(spec, backstage));
- });
- };
- };
- var makeIframe = function(render2) {
- return function(parts2, spec, backstage) {
- var iframeSpec = deepMerge(spec, { source: "dynamic" });
- return make$2(render2)(parts2, iframeSpec, backstage);
- };
- };
- var factories = {
- bar: make$2(function(spec, backstage) {
- return renderBar(spec, backstage.shared);
- }),
- collection: make$2(function(spec, backstage) {
- return renderCollection(spec, backstage.shared.providers);
- }),
- alertbanner: make$2(function(spec, backstage) {
- return renderAlertBanner(spec, backstage.shared.providers);
- }),
- input: make$2(function(spec, backstage) {
- return renderInput(spec, backstage.shared.providers);
- }),
- textarea: make$2(function(spec, backstage) {
- return renderTextarea(spec, backstage.shared.providers);
- }),
- label: make$2(function(spec, backstage) {
- return renderLabel(spec, backstage.shared);
- }),
- iframe: makeIframe(function(spec, backstage) {
- return renderIFrame(spec, backstage.shared.providers);
- }),
- button: make$2(function(spec, backstage) {
- return renderDialogButton(spec, backstage.shared.providers);
- }),
- checkbox: make$2(function(spec, backstage) {
- return renderCheckbox(spec, backstage.shared.providers);
- }),
- colorinput: make$2(function(spec, backstage) {
- return renderColorInput(spec, backstage.shared, backstage.colorinput);
- }),
- colorpicker: make$2(renderColorPicker),
- dropzone: make$2(function(spec, backstage) {
- return renderDropZone(spec, backstage.shared.providers);
- }),
- grid: make$2(function(spec, backstage) {
- return renderGrid(spec, backstage.shared);
- }),
- listbox: make$2(function(spec, backstage) {
- return renderListBox(spec, backstage);
- }),
- selectbox: make$2(function(spec, backstage) {
- return renderSelectBox(spec, backstage.shared.providers);
- }),
- sizeinput: make$2(function(spec, backstage) {
- return renderSizeInput(spec, backstage.shared.providers);
- }),
- urlinput: make$2(function(spec, backstage) {
- return renderUrlInput(spec, backstage, backstage.urlinput);
- }),
- customeditor: make$2(renderCustomEditor),
- htmlpanel: make$2(renderHtmlPanel),
- imagetools: make$2(function(spec, backstage) {
- return renderImageTools(spec, backstage.shared.providers);
- }),
- table: make$2(function(spec, backstage) {
- return renderTable(spec, backstage.shared.providers);
- }),
- panel: make$2(function(spec, backstage) {
- return renderPanel(spec, backstage);
- })
- };
- var noFormParts = {
- field: function(_name, spec) {
- return spec;
- }
- };
- var interpretInForm = function(parts2, spec, oldBackstage) {
- var newBackstage = deepMerge(oldBackstage, {
- shared: {
- interpreter: function(childSpec) {
- return interpretParts(parts2, childSpec, newBackstage);
- }
- }
- });
- return interpretParts(parts2, spec, newBackstage);
- };
- var interpretParts = function(parts2, spec, backstage) {
- return get$e(factories, spec.type).fold(function() {
- console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
- return spec;
- }, function(factory2) {
- return factory2(parts2, spec, backstage);
- });
- };
- var interpretWithoutForm = function(spec, backstage) {
- var parts2 = noFormParts;
- return interpretParts(parts2, spec, backstage);
- };
- var bubbleAlignments$2 = {
- valignCentre: [],
- alignCentre: [],
- alignLeft: [],
- alignRight: [],
- right: [],
- left: [],
- bottom: [],
- top: []
- };
- var getInlineDialogAnchor = function(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
- var bubbleSize2 = 12;
- var overrides = { maxHeightFunction: expandable$1() };
- var editableAreaAnchor = function() {
- return {
- type: "node",
- root: getContentContainer(contentAreaElement()),
- node: Optional.from(contentAreaElement()),
- bubble: nu$5(bubbleSize2, bubbleSize2, bubbleAlignments$2),
- layouts: {
- onRtl: function() {
- return [northeast];
- },
- onLtr: function() {
- return [northwest];
- }
- },
- overrides
- };
- };
- var standardAnchor = function() {
- return {
- type: "hotspot",
- hotspot: lazyAnchorbar(),
- bubble: nu$5(-bubbleSize2, bubbleSize2, bubbleAlignments$2),
- layouts: {
- onRtl: function() {
- return [southeast$2];
- },
- onLtr: function() {
- return [southwest$2];
- }
- },
- overrides
- };
- };
- return function() {
- return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
- };
- };
- var getBannerAnchor = function(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
- var editableAreaAnchor = function() {
- return {
- type: "node",
- root: getContentContainer(contentAreaElement()),
- node: Optional.from(contentAreaElement()),
- layouts: {
- onRtl: function() {
- return [north];
- },
- onLtr: function() {
- return [north];
- }
- }
- };
- };
- var standardAnchor = function() {
- return {
- type: "hotspot",
- hotspot: lazyAnchorbar(),
- layouts: {
- onRtl: function() {
- return [south$2];
- },
- onLtr: function() {
- return [south$2];
- }
- }
- };
- };
- return function() {
- return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
- };
- };
- var getCursorAnchor = function(editor, bodyElement) {
- return function() {
- return {
- type: "selection",
- root: bodyElement(),
- getSelection: function() {
- var rng = editor.selection.getRng();
- return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
- }
- };
- };
- };
- var getNodeAnchor$1 = function(bodyElement) {
- return function(element2) {
- return {
- type: "node",
- root: bodyElement(),
- node: element2
- };
- };
- };
- var getAnchors = function(editor, lazyAnchorbar, isToolbarTop) {
- var useFixedToolbarContainer = useFixedContainer(editor);
- var bodyElement = function() {
- return SugarElement.fromDom(editor.getBody());
- };
- var contentAreaElement = function() {
- return SugarElement.fromDom(editor.getContentAreaContainer());
- };
- var lazyUseEditableAreaAnchor = function() {
- return useFixedToolbarContainer || !isToolbarTop();
- };
- return {
- inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
- banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
- cursor: getCursorAnchor(editor, bodyElement),
- node: getNodeAnchor$1(bodyElement)
- };
- };
- var colorPicker = function(editor) {
- return function(callback, value2) {
- var dialog = colorPickerDialog(editor);
- dialog(callback, value2);
- };
- };
- var hasCustomColors = function(editor) {
- return function() {
- return hasCustomColors$1(editor);
- };
- };
- var getColors = function(editor) {
- return function() {
- return getColors$2(editor);
- };
- };
- var getColorCols = function(editor) {
- return function() {
- return getColorCols$1(editor);
- };
- };
- var ColorInputBackstage = function(editor) {
- return {
- colorPicker: colorPicker(editor),
- hasCustomColors: hasCustomColors(editor),
- getColors: getColors(editor),
- getColorCols: getColorCols(editor)
- };
- };
- var isDraggableModal = function(editor) {
- return function() {
- return isDraggableModal$1(editor);
- };
- };
- var DialogBackstage = function(editor) {
- return { isDraggableModal: isDraggableModal(editor) };
- };
- var HeaderBackstage = function(editor) {
- var mode = Cell(isToolbarLocationBottom(editor) ? "bottom" : "top");
- return {
- isPositionedAtTop: function() {
- return mode.get() === "top";
- },
- getDockingMode: mode.get,
- setDockingMode: mode.set
- };
- };
- var defaultStyleFormats = [
- {
- title: "Headings",
- items: [
- {
- title: "Heading 1",
- format: "h1"
- },
- {
- title: "Heading 2",
- format: "h2"
- },
- {
- title: "Heading 3",
- format: "h3"
- },
- {
- title: "Heading 4",
- format: "h4"
- },
- {
- title: "Heading 5",
- format: "h5"
- },
- {
- title: "Heading 6",
- format: "h6"
- }
- ]
- },
- {
- title: "Inline",
- items: [
- {
- title: "Bold",
- format: "bold"
- },
- {
- title: "Italic",
- format: "italic"
- },
- {
- title: "Underline",
- format: "underline"
- },
- {
- title: "Strikethrough",
- format: "strikethrough"
- },
- {
- title: "Superscript",
- format: "superscript"
- },
- {
- title: "Subscript",
- format: "subscript"
- },
- {
- title: "Code",
- format: "code"
- }
- ]
- },
- {
- title: "Blocks",
- items: [
- {
- title: "Paragraph",
- format: "p"
- },
- {
- title: "Blockquote",
- format: "blockquote"
- },
- {
- title: "Div",
- format: "div"
- },
- {
- title: "Pre",
- format: "pre"
- }
- ]
- },
- {
- title: "Align",
- items: [
- {
- title: "Left",
- format: "alignleft"
- },
- {
- title: "Center",
- format: "aligncenter"
- },
- {
- title: "Right",
- format: "alignright"
- },
- {
- title: "Justify",
- format: "alignjustify"
- }
- ]
- }
- ];
- var isNestedFormat = function(format) {
- return has$2(format, "items");
- };
- var isBlockFormat = function(format) {
- return has$2(format, "block");
- };
- var isInlineFormat = function(format) {
- return has$2(format, "inline");
- };
- var isSelectorFormat = function(format) {
- return has$2(format, "selector");
- };
- var mapFormats = function(userFormats) {
- return foldl(userFormats, function(acc, fmt) {
- if (isNestedFormat(fmt)) {
- var result = mapFormats(fmt.items);
- return {
- customFormats: acc.customFormats.concat(result.customFormats),
- formats: acc.formats.concat([{
- title: fmt.title,
- items: result.formats
- }])
- };
- } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
- var formatName = isString(fmt.name) ? fmt.name : fmt.title.toLowerCase();
- var formatNameWithPrefix = "custom-" + formatName;
- return {
- customFormats: acc.customFormats.concat([{
- name: formatNameWithPrefix,
- format: fmt
- }]),
- formats: acc.formats.concat([{
- title: fmt.title,
- format: formatNameWithPrefix,
- icon: fmt.icon
- }])
- };
- } else {
- return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
- }
- }, {
- customFormats: [],
- formats: []
- });
- };
- var registerCustomFormats = function(editor, userFormats) {
- var result = mapFormats(userFormats);
- var registerFormats = function(customFormats) {
- each$1(customFormats, function(fmt) {
- if (!editor.formatter.has(fmt.name)) {
- editor.formatter.register(fmt.name, fmt.format);
- }
- });
- };
- if (editor.formatter) {
- registerFormats(result.customFormats);
- } else {
- editor.on("init", function() {
- registerFormats(result.customFormats);
- });
- }
- return result.formats;
- };
- var getStyleFormats = function(editor) {
- return getUserStyleFormats(editor).map(function(userFormats) {
- var registeredUserFormats = registerCustomFormats(editor, userFormats);
- return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
- }).getOr(defaultStyleFormats);
- };
- var processBasic = function(item2, isSelectedFor, getPreviewFor) {
- var formatterSpec = {
- type: "formatter",
- isSelected: isSelectedFor(item2.format),
- getStylePreview: getPreviewFor(item2.format)
- };
- return deepMerge(item2, formatterSpec);
- };
- var register$8 = function(editor, formats, isSelectedFor, getPreviewFor) {
- var enrichSupported = function(item2) {
- return processBasic(item2, isSelectedFor, getPreviewFor);
- };
- var enrichMenu = function(item2) {
- var submenuSpec = { type: "submenu" };
- return deepMerge(item2, submenuSpec);
- };
- var enrichCustom = function(item2) {
- var formatName = isString(item2.name) ? item2.name : generate$6(item2.title);
- var formatNameWithPrefix = "custom-" + formatName;
- var customSpec = {
- type: "formatter",
- format: formatNameWithPrefix,
- isSelected: isSelectedFor(formatNameWithPrefix),
- getStylePreview: getPreviewFor(formatNameWithPrefix)
- };
- var newItem = deepMerge(item2, customSpec);
- editor.formatter.register(formatName, newItem);
- return newItem;
- };
- var doEnrich = function(items) {
- return map$2(items, function(item2) {
- var keys$1 = keys(item2);
- if (hasNonNullableKey(item2, "items")) {
- var newItems = doEnrich(item2.items);
- return deepMerge(enrichMenu(item2), { getStyleItems: constant$1(newItems) });
- } else if (hasNonNullableKey(item2, "format")) {
- return enrichSupported(item2);
- } else if (keys$1.length === 1 && contains$2(keys$1, "title")) {
- return deepMerge(item2, { type: "separator" });
- } else {
- return enrichCustom(item2);
- }
- });
- };
- return doEnrich(formats);
- };
- var init$8 = function(editor) {
- var isSelectedFor = function(format) {
- return function() {
- return editor.formatter.match(format);
- };
- };
- var getPreviewFor = function(format) {
- return function() {
- var fmt = editor.formatter.get(format);
- return fmt !== void 0 ? Optional.some({
- tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || "div" : "div",
- styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
- }) : Optional.none();
- };
- };
- var flatten2 = function(fmt) {
- var subs2 = fmt.items;
- return subs2 !== void 0 && subs2.length > 0 ? bind$3(subs2, flatten2) : [fmt.format];
- };
- var settingsFormats = Cell([]);
- var settingsFlattenedFormats = Cell([]);
- var eventsFormats = Cell([]);
- var eventsFlattenedFormats = Cell([]);
- var replaceSettings = Cell(false);
- editor.on("PreInit", function(_e) {
- var formats = getStyleFormats(editor);
- var enriched = register$8(editor, formats, isSelectedFor, getPreviewFor);
- settingsFormats.set(enriched);
- settingsFlattenedFormats.set(bind$3(enriched, flatten2));
- });
- editor.on("addStyleModifications", function(e) {
- var modifications = register$8(editor, e.items, isSelectedFor, getPreviewFor);
- eventsFormats.set(modifications);
- replaceSettings.set(e.replace);
- eventsFlattenedFormats.set(bind$3(modifications, flatten2));
- });
- var getData2 = function() {
- var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
- var fromEvents = eventsFormats.get();
- return fromSettings.concat(fromEvents);
- };
- var getFlattenedKeys = function() {
- var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
- var fromEvents = eventsFlattenedFormats.get();
- return fromSettings.concat(fromEvents);
- };
- return {
- getData: getData2,
- getFlattenedKeys
- };
- };
- var isElement = function(node) {
- return isNonNullable(node) && node.nodeType === 1;
- };
- var trim = global$5.trim;
- var hasContentEditableState = function(value2) {
- return function(node) {
- if (isElement(node)) {
- if (node.contentEditable === value2) {
- return true;
- }
- if (node.getAttribute("data-mce-contenteditable") === value2) {
- return true;
- }
- }
- return false;
- };
- };
- var isContentEditableTrue = hasContentEditableState("true");
- var isContentEditableFalse = hasContentEditableState("false");
- var create$1 = function(type2, title, url, level, attach2) {
- return {
- type: type2,
- title,
- url,
- level,
- attach: attach2
- };
- };
- var isChildOfContentEditableTrue = function(node) {
- while (node = node.parentNode) {
- var value2 = node.contentEditable;
- if (value2 && value2 !== "inherit") {
- return isContentEditableTrue(node);
- }
- }
- return false;
- };
- var select = function(selector, root) {
- return map$2(descendants(SugarElement.fromDom(root), selector), function(element2) {
- return element2.dom;
- });
- };
- var getElementText = function(elm) {
- return elm.innerText || elm.textContent;
- };
- var getOrGenerateId = function(elm) {
- return elm.id ? elm.id : generate$6("h");
- };
- var isAnchor = function(elm) {
- return elm && elm.nodeName === "A" && (elm.id || elm.name) !== void 0;
- };
- var isValidAnchor = function(elm) {
- return isAnchor(elm) && isEditable(elm);
- };
- var isHeader = function(elm) {
- return elm && /^(H[1-6])$/.test(elm.nodeName);
- };
- var isEditable = function(elm) {
- return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
- };
- var isValidHeader = function(elm) {
- return isHeader(elm) && isEditable(elm);
- };
- var getLevel = function(elm) {
- return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
- };
- var headerTarget = function(elm) {
- var headerId = getOrGenerateId(elm);
- var attach2 = function() {
- elm.id = headerId;
- };
- return create$1("header", getElementText(elm), "#" + headerId, getLevel(elm), attach2);
- };
- var anchorTarget = function(elm) {
- var anchorId = elm.id || elm.name;
- var anchorText = getElementText(elm);
- return create$1("anchor", anchorText ? anchorText : "#" + anchorId, "#" + anchorId, 0, noop);
- };
- var getHeaderTargets = function(elms) {
- return map$2(filter$2(elms, isValidHeader), headerTarget);
- };
- var getAnchorTargets = function(elms) {
- return map$2(filter$2(elms, isValidAnchor), anchorTarget);
- };
- var getTargetElements = function(elm) {
- var elms = select("h1,h2,h3,h4,h5,h6,a:not([href])", elm);
- return elms;
- };
- var hasTitle = function(target) {
- return trim(target.title).length > 0;
- };
- var find = function(elm) {
- var elms = getTargetElements(elm);
- return filter$2(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
- };
- var LinkTargets = { find };
- var STORAGE_KEY = "tinymce-url-history";
- var HISTORY_LENGTH = 5;
- var isHttpUrl = function(url) {
- return isString(url) && /^https?/.test(url);
- };
- var isArrayOfUrl = function(a) {
- return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
- };
- var isRecordOfUrlArray = function(r2) {
- return isObject(r2) && find$4(r2, function(value2) {
- return !isArrayOfUrl(value2);
- }).isNone();
- };
- var getAllHistory = function() {
- var unparsedHistory = global$8.getItem(STORAGE_KEY);
- if (unparsedHistory === null) {
- return {};
- }
- var history;
- try {
- history = JSON.parse(unparsedHistory);
- } catch (e) {
- if (e instanceof SyntaxError) {
- console.log("Local storage " + STORAGE_KEY + " was not valid JSON", e);
- return {};
- }
- throw e;
- }
- if (!isRecordOfUrlArray(history)) {
- console.log("Local storage " + STORAGE_KEY + " was not valid format", history);
- return {};
- }
- return history;
- };
- var setAllHistory = function(history) {
- if (!isRecordOfUrlArray(history)) {
- throw new Error("Bad format for history:\n" + JSON.stringify(history));
- }
- global$8.setItem(STORAGE_KEY, JSON.stringify(history));
- };
- var getHistory = function(fileType) {
- var history = getAllHistory();
- return get$e(history, fileType).getOr([]);
- };
- var addToHistory = function(url, fileType) {
- if (!isHttpUrl(url)) {
- return;
- }
- var history = getAllHistory();
- var items = get$e(history, fileType).getOr([]);
- var itemsWithoutUrl = filter$2(items, function(item2) {
- return item2 !== url;
- });
- history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
- setAllHistory(history);
- };
- var isTruthy = function(value2) {
- return !!value2;
- };
- var makeMap = function(value2) {
- return map$1(global$5.makeMap(value2, /[, ]/), isTruthy);
- };
- var getPicker = function(editor) {
- return Optional.from(getFilePickerCallback(editor)).filter(isFunction);
- };
- var getPickerTypes = function(editor) {
- var optFileTypes = Optional.some(getFilePickerTypes(editor)).filter(isTruthy);
- var optLegacyTypes = Optional.some(getFileBrowserCallbackTypes(editor)).filter(isTruthy);
- var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
- return getPicker(editor).fold(never, function(_picker) {
- return optTypes.fold(always, function(types2) {
- return keys(types2).length > 0 ? types2 : false;
- });
- });
- };
- var getPickerSetting = function(editor, filetype) {
- var pickerTypes = getPickerTypes(editor);
- if (isBoolean(pickerTypes)) {
- return pickerTypes ? getPicker(editor) : Optional.none();
- } else {
- return pickerTypes[filetype] ? getPicker(editor) : Optional.none();
- }
- };
- var getUrlPicker = function(editor, filetype) {
- return getPickerSetting(editor, filetype).map(function(picker) {
- return function(entry) {
- return Future.nu(function(completer) {
- var handler = function(value2, meta2) {
- if (!isString(value2)) {
- throw new Error("Expected value to be string");
- }
- if (meta2 !== void 0 && !isObject(meta2)) {
- throw new Error("Expected meta to be a object");
- }
- var r2 = {
- value: value2,
- meta: meta2
- };
- completer(r2);
- };
- var meta = __assign({
- filetype,
- fieldname: entry.fieldname
- }, Optional.from(entry.meta).getOr({}));
- picker.call(editor, handler, entry.value, meta);
- });
- };
- });
- };
- var getTextSetting = function(value2) {
- return Optional.from(value2).filter(isString).getOrUndefined();
- };
- var getLinkInformation = function(editor) {
- if (noTypeaheadUrls(editor)) {
- return Optional.none();
- }
- return Optional.some({
- targets: LinkTargets.find(editor.getBody()),
- anchorTop: getTextSetting(getAnchorTop(editor)),
- anchorBottom: getTextSetting(getAnchorBottom(editor))
- });
- };
- var getValidationHandler = function(editor) {
- return Optional.from(getFilePickerValidatorHandler(editor));
- };
- var UrlInputBackstage = function(editor) {
- return {
- getHistory,
- addToHistory,
- getLinkInformation: function() {
- return getLinkInformation(editor);
- },
- getValidationHandler: function() {
- return getValidationHandler(editor);
- },
- getUrlPicker: function(filetype) {
- return getUrlPicker(editor, filetype);
- }
- };
- };
- var init$7 = function(sink, editor, lazyAnchorbar) {
- var contextMenuState = Cell(false);
- var toolbar = HeaderBackstage(editor);
- var backstage = {
- shared: {
- providers: {
- icons: function() {
- return editor.ui.registry.getAll().icons;
- },
- menuItems: function() {
- return editor.ui.registry.getAll().menuItems;
- },
- translate: global$e.translate,
- isDisabled: function() {
- return editor.mode.isReadOnly() || editor.ui.isDisabled();
- },
- getSetting: editor.getParam.bind(editor)
- },
- interpreter: function(s) {
- return interpretWithoutForm(s, backstage);
- },
- anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
- header: toolbar,
- getSink: function() {
- return Result.value(sink);
- }
- },
- urlinput: UrlInputBackstage(editor),
- styleselect: init$8(editor),
- colorinput: ColorInputBackstage(editor),
- dialog: DialogBackstage(editor),
- isContextMenuOpen: function() {
- return contextMenuState.get();
- },
- setContextMenuState: function(state) {
- return contextMenuState.set(state);
- }
- };
- return backstage;
- };
- var setup$b = function(editor, mothership, uiMothership) {
- var broadcastEvent = function(name2, evt) {
- each$1([
- mothership,
- uiMothership
- ], function(ship) {
- ship.broadcastEvent(name2, evt);
- });
- };
- var broadcastOn = function(channel, message) {
- each$1([
- mothership,
- uiMothership
- ], function(ship) {
- ship.broadcastOn([channel], message);
- });
- };
- var fireDismissPopups = function(evt) {
- return broadcastOn(dismissPopups(), { target: evt.target });
- };
- var doc = getDocument();
- var onTouchstart = bind(doc, "touchstart", fireDismissPopups);
- var onTouchmove = bind(doc, "touchmove", function(evt) {
- return broadcastEvent(documentTouchmove(), evt);
- });
- var onTouchend = bind(doc, "touchend", function(evt) {
- return broadcastEvent(documentTouchend(), evt);
- });
- var onMousedown = bind(doc, "mousedown", fireDismissPopups);
- var onMouseup = bind(doc, "mouseup", function(evt) {
- if (evt.raw.button === 0) {
- broadcastOn(mouseReleased(), { target: evt.target });
- }
- });
- var onContentClick = function(raw) {
- return broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) });
- };
- var onContentMouseup = function(raw) {
- if (raw.button === 0) {
- broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) });
- }
- };
- var onContentMousedown = function() {
- each$1(editor.editorManager.get(), function(loopEditor) {
- if (editor !== loopEditor) {
- loopEditor.fire("DismissPopups", { relatedTarget: editor });
- }
- });
- };
- var onWindowScroll = function(evt) {
- return broadcastEvent(windowScroll(), fromRawEvent(evt));
- };
- var onWindowResize = function(evt) {
- broadcastOn(repositionPopups(), {});
- broadcastEvent(windowResize(), fromRawEvent(evt));
- };
- var onEditorResize = function() {
- return broadcastOn(repositionPopups(), {});
- };
- var onEditorProgress = function(evt) {
- if (evt.state) {
- broadcastOn(dismissPopups(), { target: SugarElement.fromDom(editor.getContainer()) });
- }
- };
- var onDismissPopups = function(event) {
- broadcastOn(dismissPopups(), { target: SugarElement.fromDom(event.relatedTarget.getContainer()) });
- };
- editor.on("PostRender", function() {
- editor.on("click", onContentClick);
- editor.on("tap", onContentClick);
- editor.on("mouseup", onContentMouseup);
- editor.on("mousedown", onContentMousedown);
- editor.on("ScrollWindow", onWindowScroll);
- editor.on("ResizeWindow", onWindowResize);
- editor.on("ResizeEditor", onEditorResize);
- editor.on("AfterProgressState", onEditorProgress);
- editor.on("DismissPopups", onDismissPopups);
- });
- editor.on("remove", function() {
- editor.off("click", onContentClick);
- editor.off("tap", onContentClick);
- editor.off("mouseup", onContentMouseup);
- editor.off("mousedown", onContentMousedown);
- editor.off("ScrollWindow", onWindowScroll);
- editor.off("ResizeWindow", onWindowResize);
- editor.off("ResizeEditor", onEditorResize);
- editor.off("AfterProgressState", onEditorProgress);
- editor.off("DismissPopups", onDismissPopups);
- onMousedown.unbind();
- onTouchstart.unbind();
- onTouchmove.unbind();
- onTouchend.unbind();
- onMouseup.unbind();
- });
- editor.on("detach", function() {
- detachSystem(mothership);
- detachSystem(uiMothership);
- mothership.destroy();
- uiMothership.destroy();
- });
- };
- var parts$a = AlloyParts;
- var partType = PartType;
- var schema$f = constant$1([
- defaulted("shell", false),
- required$1("makeItem"),
- defaulted("setupItem", noop),
- SketchBehaviours.field("listBehaviours", [Replacing])
- ]);
- var customListDetail = function() {
- return { behaviours: derive$1([Replacing.config({})]) };
- };
- var itemsPart = optional({
- name: "items",
- overrides: customListDetail
- });
- var parts$9 = constant$1([itemsPart]);
- var name = constant$1("CustomList");
- var factory$d = function(detail, components2, _spec, _external) {
- var setItems = function(list, items) {
- getListContainer(list).fold(function() {
- console.error("Custom List was defined to not be a shell, but no item container was specified in components");
- throw new Error("Custom List was defined to not be a shell, but no item container was specified in components");
- }, function(container) {
- var itemComps = Replacing.contents(container);
- var numListsRequired = items.length;
- var numListsToAdd = numListsRequired - itemComps.length;
- var itemsToAdd = numListsToAdd > 0 ? range$2(numListsToAdd, function() {
- return detail.makeItem();
- }) : [];
- var itemsToRemove = itemComps.slice(numListsRequired);
- each$1(itemsToRemove, function(item2) {
- return Replacing.remove(container, item2);
- });
- each$1(itemsToAdd, function(item2) {
- return Replacing.append(container, item2);
- });
- var builtLists = Replacing.contents(container);
- each$1(builtLists, function(item2, i) {
- detail.setupItem(list, item2, items[i], i);
- });
- });
- };
- var extra = detail.shell ? {
- behaviours: [Replacing.config({})],
- components: []
- } : {
- behaviours: [],
- components: components2
- };
- var getListContainer = function(component) {
- return detail.shell ? Optional.some(component) : getPart(component, detail, "items");
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: extra.components,
- behaviours: augment(detail.listBehaviours, extra.behaviours),
- apis: { setItems }
- };
- };
- var CustomList = composite({
- name: name(),
- configFields: schema$f(),
- partFields: parts$9(),
- factory: factory$d,
- apis: {
- setItems: function(apis, list, items) {
- apis.setItems(list, items);
- }
- }
- });
- var schema$e = constant$1([
- required$1("dom"),
- defaulted("shell", true),
- field("toolbarBehaviours", [Replacing])
- ]);
- var enhanceGroups = function() {
- return { behaviours: derive$1([Replacing.config({})]) };
- };
- var parts$8 = constant$1([optional({
- name: "groups",
- overrides: enhanceGroups
- })]);
- var factory$c = function(detail, components2, _spec, _externals) {
- var setGroups2 = function(toolbar, groups) {
- getGroupContainer(toolbar).fold(function() {
- console.error("Toolbar was defined to not be a shell, but no groups container was specified in components");
- throw new Error("Toolbar was defined to not be a shell, but no groups container was specified in components");
- }, function(container) {
- Replacing.set(container, groups);
- });
- };
- var getGroupContainer = function(component) {
- return detail.shell ? Optional.some(component) : getPart(component, detail, "groups");
- };
- var extra = detail.shell ? {
- behaviours: [Replacing.config({})],
- components: []
- } : {
- behaviours: [],
- components: components2
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: extra.components,
- behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
- apis: { setGroups: setGroups2 },
- domModification: { attributes: { role: "group" } }
- };
- };
- var Toolbar = composite({
- name: "Toolbar",
- configFields: schema$e(),
- partFields: parts$8(),
- factory: factory$c,
- apis: {
- setGroups: function(apis, toolbar, groups) {
- apis.setGroups(toolbar, groups);
- }
- }
- });
- var setup$a = noop;
- var isDocked$2 = never;
- var getBehaviours$1 = constant$1([]);
- var StaticHeader = Object.freeze({
- __proto__: null,
- setup: setup$a,
- isDocked: isDocked$2,
- getBehaviours: getBehaviours$1
- });
- var getOffsetParent = function(element2) {
- var isFixed = is$1(getRaw(element2, "position"), "fixed");
- var offsetParent$1 = isFixed ? Optional.none() : offsetParent(element2);
- return offsetParent$1.orThunk(function() {
- var marker = SugarElement.fromTag("span");
- return parent(element2).bind(function(parent2) {
- append$2(parent2, marker);
- var offsetParent$12 = offsetParent(marker);
- remove$5(marker);
- return offsetParent$12;
- });
- });
- };
- var getOrigin = function(element2) {
- return getOffsetParent(element2).map(absolute$3).getOrThunk(function() {
- return SugarPosition(0, 0);
- });
- };
- var morphAdt = Adt.generate([
- { static: [] },
- { absolute: ["positionCss"] },
- { fixed: ["positionCss"] }
- ]);
- var appear = function(component, contextualInfo) {
- var elem = component.element;
- add$2(elem, contextualInfo.transitionClass);
- remove$2(elem, contextualInfo.fadeOutClass);
- add$2(elem, contextualInfo.fadeInClass);
- contextualInfo.onShow(component);
- };
- var disappear = function(component, contextualInfo) {
- var elem = component.element;
- add$2(elem, contextualInfo.transitionClass);
- remove$2(elem, contextualInfo.fadeInClass);
- add$2(elem, contextualInfo.fadeOutClass);
- contextualInfo.onHide(component);
- };
- var isPartiallyVisible = function(box2, viewport2) {
- return box2.y < viewport2.bottom && box2.bottom > viewport2.y;
- };
- var isTopCompletelyVisible = function(box2, viewport2) {
- return box2.y >= viewport2.y;
- };
- var isBottomCompletelyVisible = function(box2, viewport2) {
- return box2.bottom <= viewport2.bottom;
- };
- var isVisibleForModes = function(modes, box2, viewport2) {
- return forall(modes, function(mode) {
- switch (mode) {
- case "bottom":
- return isBottomCompletelyVisible(box2, viewport2);
- case "top":
- return isTopCompletelyVisible(box2, viewport2);
- }
- });
- };
- var getPrior = function(elem, state) {
- return state.getInitialPos().map(function(pos) {
- return bounds(pos.bounds.x, pos.bounds.y, get$a(elem), get$b(elem));
- });
- };
- var storePrior = function(elem, box2, state) {
- state.setInitialPos({
- style: getAllRaw(elem),
- position: get$c(elem, "position") || "static",
- bounds: box2
- });
- };
- var revertToOriginal = function(elem, box2, state) {
- return state.getInitialPos().bind(function(position2) {
- state.clearInitialPos();
- switch (position2.position) {
- case "static":
- return Optional.some(morphAdt.static());
- case "absolute":
- var offsetBox_1 = getOffsetParent(elem).map(box$1).getOrThunk(function() {
- return box$1(body());
- });
- return Optional.some(morphAdt.absolute(NuPositionCss("absolute", get$e(position2.style, "left").map(function(_left) {
- return box2.x - offsetBox_1.x;
- }), get$e(position2.style, "top").map(function(_top) {
- return box2.y - offsetBox_1.y;
- }), get$e(position2.style, "right").map(function(_right) {
- return offsetBox_1.right - box2.right;
- }), get$e(position2.style, "bottom").map(function(_bottom) {
- return offsetBox_1.bottom - box2.bottom;
- }))));
- default:
- return Optional.none();
- }
- });
- };
- var morphToOriginal = function(elem, viewport2, state) {
- return getPrior(elem, state).filter(function(box2) {
- return isVisibleForModes(state.getModes(), box2, viewport2);
- }).bind(function(box2) {
- return revertToOriginal(elem, box2, state);
- });
- };
- var morphToFixed = function(elem, viewport2, state) {
- var box2 = box$1(elem);
- if (!isVisibleForModes(state.getModes(), box2, viewport2)) {
- storePrior(elem, box2, state);
- var winBox = win();
- var left2 = box2.x - winBox.x;
- var top_1 = viewport2.y - winBox.y;
- var bottom2 = winBox.bottom - viewport2.bottom;
- var isTop = box2.y <= viewport2.y;
- return Optional.some(morphAdt.fixed(NuPositionCss("fixed", Optional.some(left2), isTop ? Optional.some(top_1) : Optional.none(), Optional.none(), !isTop ? Optional.some(bottom2) : Optional.none())));
- } else {
- return Optional.none();
- }
- };
- var getMorph = function(component, viewport2, state) {
- var elem = component.element;
- var isDocked2 = is$1(getRaw(elem, "position"), "fixed");
- return isDocked2 ? morphToOriginal(elem, viewport2, state) : morphToFixed(elem, viewport2, state);
- };
- var getMorphToOriginal = function(component, state) {
- var elem = component.element;
- return getPrior(elem, state).bind(function(box2) {
- return revertToOriginal(elem, box2, state);
- });
- };
- var morphToStatic = function(component, config2, state) {
- state.setDocked(false);
- each$1([
- "left",
- "right",
- "top",
- "bottom",
- "position"
- ], function(prop) {
- return remove$6(component.element, prop);
- });
- config2.onUndocked(component);
- };
- var morphToCoord = function(component, config2, state, position2) {
- var isDocked2 = position2.position === "fixed";
- state.setDocked(isDocked2);
- applyPositionCss(component.element, position2);
- var method = isDocked2 ? config2.onDocked : config2.onUndocked;
- method(component);
- };
- var updateVisibility = function(component, config2, state, viewport2, morphToDocked) {
- if (morphToDocked === void 0) {
- morphToDocked = false;
- }
- config2.contextual.each(function(contextInfo) {
- contextInfo.lazyContext(component).each(function(box2) {
- var isVisible2 = isPartiallyVisible(box2, viewport2);
- if (isVisible2 !== state.isVisible()) {
- state.setVisible(isVisible2);
- if (morphToDocked && !isVisible2) {
- add$1(component.element, [contextInfo.fadeOutClass]);
- contextInfo.onHide(component);
- } else {
- var method = isVisible2 ? appear : disappear;
- method(component, contextInfo);
- }
- }
- });
- });
- };
- var refreshInternal = function(component, config2, state) {
- var viewport2 = config2.lazyViewport(component);
- var isDocked2 = state.isDocked();
- if (isDocked2) {
- updateVisibility(component, config2, state, viewport2);
- }
- getMorph(component, viewport2, state).each(function(morph) {
- morph.fold(function() {
- return morphToStatic(component, config2, state);
- }, function(position2) {
- return morphToCoord(component, config2, state, position2);
- }, function(position2) {
- updateVisibility(component, config2, state, viewport2, true);
- morphToCoord(component, config2, state, position2);
- });
- });
- };
- var resetInternal = function(component, config2, state) {
- var elem = component.element;
- state.setDocked(false);
- getMorphToOriginal(component, state).each(function(morph) {
- morph.fold(function() {
- return morphToStatic(component, config2, state);
- }, function(position2) {
- return morphToCoord(component, config2, state, position2);
- }, noop);
- });
- state.setVisible(true);
- config2.contextual.each(function(contextInfo) {
- remove$1(elem, [
- contextInfo.fadeInClass,
- contextInfo.fadeOutClass,
- contextInfo.transitionClass
- ]);
- contextInfo.onShow(component);
- });
- refresh$4(component, config2, state);
- };
- var refresh$4 = function(component, config2, state) {
- if (component.getSystem().isConnected()) {
- refreshInternal(component, config2, state);
- }
- };
- var reset = function(component, config2, state) {
- if (state.isDocked()) {
- resetInternal(component, config2, state);
- }
- };
- var isDocked$1 = function(component, config2, state) {
- return state.isDocked();
- };
- var setModes = function(component, config2, state, modes) {
- return state.setModes(modes);
- };
- var getModes = function(component, config2, state) {
- return state.getModes();
- };
- var DockingApis = Object.freeze({
- __proto__: null,
- refresh: refresh$4,
- reset,
- isDocked: isDocked$1,
- getModes,
- setModes
- });
- var events$5 = function(dockInfo, dockState) {
- return derive$2([
- runOnSource(transitionend(), function(component, simulatedEvent) {
- dockInfo.contextual.each(function(contextInfo) {
- if (has(component.element, contextInfo.transitionClass)) {
- remove$1(component.element, [
- contextInfo.transitionClass,
- contextInfo.fadeInClass
- ]);
- var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
- notify(component);
- }
- simulatedEvent.stop();
- });
- }),
- run$1(windowScroll(), function(component, _) {
- refresh$4(component, dockInfo, dockState);
- }),
- run$1(windowResize(), function(component, _) {
- reset(component, dockInfo, dockState);
- })
- ]);
- };
- var ActiveDocking = Object.freeze({
- __proto__: null,
- events: events$5
- });
- var DockingSchema = [
- optionObjOf("contextual", [
- requiredString("fadeInClass"),
- requiredString("fadeOutClass"),
- requiredString("transitionClass"),
- requiredFunction("lazyContext"),
- onHandler("onShow"),
- onHandler("onShown"),
- onHandler("onHide"),
- onHandler("onHidden")
- ]),
- defaultedFunction("lazyViewport", win),
- defaultedArrayOf("modes", [
- "top",
- "bottom"
- ], string),
- onHandler("onDocked"),
- onHandler("onUndocked")
- ];
- var init$6 = function(spec) {
- var docked = Cell(false);
- var visible = Cell(true);
- var initialBounds = value$1();
- var modes = Cell(spec.modes);
- var readState = function() {
- return "docked: " + docked.get() + ", visible: " + visible.get() + ", modes: " + modes.get().join(",");
- };
- return nu$8({
- isDocked: docked.get,
- setDocked: docked.set,
- getInitialPos: initialBounds.get,
- setInitialPos: initialBounds.set,
- clearInitialPos: initialBounds.clear,
- isVisible: visible.get,
- setVisible: visible.set,
- getModes: modes.get,
- setModes: modes.set,
- readState
- });
- };
- var DockingState = Object.freeze({
- __proto__: null,
- init: init$6
- });
- var Docking = create$8({
- fields: DockingSchema,
- name: "docking",
- active: ActiveDocking,
- apis: DockingApis,
- state: DockingState
- });
- var toolbarHeightChange = constant$1(generate$6("toolbar-height-change"));
- var visibility = {
- fadeInClass: "tox-editor-dock-fadein",
- fadeOutClass: "tox-editor-dock-fadeout",
- transitionClass: "tox-editor-dock-transition"
- };
- var editorStickyOnClass = "tox-tinymce--toolbar-sticky-on";
- var editorStickyOffClass = "tox-tinymce--toolbar-sticky-off";
- var scrollFromBehindHeader = function(e, containerHeader) {
- var doc = owner$4(containerHeader);
- var viewHeight = doc.dom.defaultView.innerHeight;
- var scrollPos = get$9(doc);
- var markerElement = SugarElement.fromDom(e.elm);
- var markerPos = absolute$2(markerElement);
- var markerHeight = get$b(markerElement);
- var markerTop = markerPos.y;
- var markerBottom = markerTop + markerHeight;
- var editorHeaderPos = absolute$3(containerHeader);
- var editorHeaderHeight = get$b(containerHeader);
- var editorHeaderTop = editorHeaderPos.top;
- var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
- var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2;
- var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2;
- if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
- to(scrollPos.left, markerTop - editorHeaderHeight, doc);
- } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
- var y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
- to(scrollPos.left, y, doc);
- }
- };
- var isDockedMode = function(header, mode) {
- return contains$2(Docking.getModes(header), mode);
- };
- var updateIframeContentFlow = function(header) {
- var getOccupiedHeight = function(elm2) {
- return getOuter$2(elm2) + (parseInt(get$c(elm2, "margin-top"), 10) || 0) + (parseInt(get$c(elm2, "margin-bottom"), 10) || 0);
- };
- var elm = header.element;
- parent(elm).each(function(parentElem) {
- var padding = "padding-" + Docking.getModes(header)[0];
- if (Docking.isDocked(header)) {
- var parentWidth = get$a(parentElem);
- set$7(elm, "width", parentWidth + "px");
- set$7(parentElem, padding, getOccupiedHeight(elm) + "px");
- } else {
- remove$6(elm, "width");
- remove$6(parentElem, padding);
- }
- });
- };
- var updateSinkVisibility = function(sinkElem, visible) {
- if (visible) {
- remove$2(sinkElem, visibility.fadeOutClass);
- add$1(sinkElem, [
- visibility.transitionClass,
- visibility.fadeInClass
- ]);
- } else {
- remove$2(sinkElem, visibility.fadeInClass);
- add$1(sinkElem, [
- visibility.fadeOutClass,
- visibility.transitionClass
- ]);
- }
- };
- var updateEditorClasses = function(editor, docked) {
- var editorContainer = SugarElement.fromDom(editor.getContainer());
- if (docked) {
- add$2(editorContainer, editorStickyOnClass);
- remove$2(editorContainer, editorStickyOffClass);
- } else {
- add$2(editorContainer, editorStickyOffClass);
- remove$2(editorContainer, editorStickyOnClass);
- }
- };
- var restoreFocus = function(headerElem, focusedElem) {
- var ownerDoc = owner$4(focusedElem);
- active(ownerDoc).filter(function(activeElm) {
- return !eq(focusedElem, activeElm);
- }).filter(function(activeElm) {
- return eq(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains(headerElem, activeElm);
- }).each(function() {
- return focus$3(focusedElem);
- });
- };
- var findFocusedElem = function(rootElm, lazySink) {
- return search(rootElm).orThunk(function() {
- return lazySink().toOptional().bind(function(sink) {
- return search(sink.element);
- });
- });
- };
- var setup$9 = function(editor, sharedBackstage, lazyHeader) {
- if (!editor.inline) {
- if (!sharedBackstage.header.isPositionedAtTop()) {
- editor.on("ResizeEditor", function() {
- lazyHeader().each(Docking.reset);
- });
- }
- editor.on("ResizeWindow ResizeEditor", function() {
- lazyHeader().each(updateIframeContentFlow);
- });
- editor.on("SkinLoaded", function() {
- lazyHeader().each(function(comp) {
- Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
- });
- });
- editor.on("FullscreenStateChanged", function() {
- lazyHeader().each(Docking.reset);
- });
- }
- editor.on("AfterScrollIntoView", function(e) {
- lazyHeader().each(function(header) {
- Docking.refresh(header);
- var headerElem = header.element;
- if (isVisible(headerElem)) {
- scrollFromBehindHeader(e, headerElem);
- }
- });
- });
- editor.on("PostRender", function() {
- updateEditorClasses(editor, false);
- });
- };
- var isDocked = function(lazyHeader) {
- return lazyHeader().map(Docking.isDocked).getOr(false);
- };
- var getIframeBehaviours = function() {
- var _a2;
- return [Receiving.config({ channels: (_a2 = {}, _a2[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a2) })];
- };
- var getBehaviours = function(editor, sharedBackstage) {
- var focusedElm = value$1();
- var lazySink = sharedBackstage.getSink;
- var runOnSinkElement = function(f) {
- lazySink().each(function(sink) {
- return f(sink.element);
- });
- };
- var onDockingSwitch = function(comp) {
- if (!editor.inline) {
- updateIframeContentFlow(comp);
- }
- updateEditorClasses(editor, Docking.isDocked(comp));
- comp.getSystem().broadcastOn([repositionPopups()], {});
- lazySink().each(function(sink) {
- return sink.getSystem().broadcastOn([repositionPopups()], {});
- });
- };
- var additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
- return __spreadArray([
- Focusing.config({}),
- Docking.config({
- contextual: __assign({
- lazyContext: function(comp) {
- var headerHeight = getOuter$2(comp.element);
- var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
- var box2 = box$1(SugarElement.fromDom(container));
- var boxHeight = box2.height - headerHeight;
- var topBound = box2.y + (isDockedMode(comp, "top") ? 0 : headerHeight);
- return Optional.some(bounds(box2.x, topBound, box2.width, boxHeight));
- },
- onShow: function() {
- runOnSinkElement(function(elem) {
- return updateSinkVisibility(elem, true);
- });
- },
- onShown: function(comp) {
- runOnSinkElement(function(elem) {
- return remove$1(elem, [
- visibility.transitionClass,
- visibility.fadeInClass
- ]);
- });
- focusedElm.get().each(function(elem) {
- restoreFocus(comp.element, elem);
- focusedElm.clear();
- });
- },
- onHide: function(comp) {
- findFocusedElem(comp.element, lazySink).fold(focusedElm.clear, focusedElm.set);
- runOnSinkElement(function(elem) {
- return updateSinkVisibility(elem, false);
- });
- },
- onHidden: function() {
- runOnSinkElement(function(elem) {
- return remove$1(elem, [visibility.transitionClass]);
- });
- }
- }, visibility),
- lazyViewport: function(comp) {
- var win$1 = win();
- var offset2 = getStickyToolbarOffset(editor);
- var top2 = win$1.y + (isDockedMode(comp, "top") ? offset2 : 0);
- var height2 = win$1.height - (isDockedMode(comp, "bottom") ? offset2 : 0);
- return bounds(win$1.x, top2, win$1.width, height2);
- },
- modes: [sharedBackstage.header.getDockingMode()],
- onDocked: onDockingSwitch,
- onUndocked: onDockingSwitch
- })
- ], additionalBehaviours, true);
- };
- var StickyHeader = Object.freeze({
- __proto__: null,
- setup: setup$9,
- isDocked,
- getBehaviours
- });
- var renderHeader = function(spec) {
- var editor = spec.editor;
- var getBehaviours$22 = spec.sticky ? getBehaviours : getBehaviours$1;
- return {
- uid: spec.uid,
- dom: spec.dom,
- components: spec.components,
- behaviours: derive$1(getBehaviours$22(editor, spec.sharedBackstage))
- };
- };
- var groupToolbarButtonSchema = objOf([
- requiredString("type"),
- requiredOf("items", oneOf([
- arrOfObj([
- requiredString("name"),
- requiredArrayOf("items", string)
- ]),
- string
- ]))
- ].concat(baseToolbarButtonFields));
- var createGroupToolbarButton = function(spec) {
- return asRaw("GroupToolbarButton", groupToolbarButtonSchema, spec);
- };
- var baseMenuButtonFields = [
- optionString("text"),
- optionString("tooltip"),
- optionString("icon"),
- requiredFunction("fetch"),
- defaultedFunction("onSetup", function() {
- return noop;
- })
- ];
- var MenuButtonSchema = objOf(__spreadArray([requiredString("type")], baseMenuButtonFields, true));
- var createMenuButton = function(spec) {
- return asRaw("menubutton", MenuButtonSchema, spec);
- };
- var splitButtonSchema = objOf([
- requiredString("type"),
- optionString("tooltip"),
- optionString("icon"),
- optionString("text"),
- optionFunction("select"),
- requiredFunction("fetch"),
- defaultedFunction("onSetup", function() {
- return noop;
- }),
- defaultedStringEnum("presets", "normal", [
- "normal",
- "color",
- "listpreview"
- ]),
- defaulted("columns", 1),
- requiredFunction("onAction"),
- requiredFunction("onItemAction")
- ]);
- var createSplitButton = function(spec) {
- return asRaw("SplitButton", splitButtonSchema, spec);
- };
- var factory$b = function(detail, spec) {
- var setMenus = function(comp, menus) {
- var newMenus = map$2(menus, function(m) {
- var buttonSpec = {
- type: "menubutton",
- text: m.text,
- fetch: function(callback) {
- callback(m.getItems());
- }
- };
- var internal2 = createMenuButton(buttonSpec).mapError(function(errInfo) {
- return formatError(errInfo);
- }).getOrDie();
- return renderMenuButton(internal2, "tox-mbtn", spec.backstage, Optional.some("menuitem"));
- });
- Replacing.set(comp, newMenus);
- };
- var apis = {
- focus: Keying.focusIn,
- setMenus
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: [],
- behaviours: derive$1([
- Replacing.config({}),
- config("menubar-events", [
- runOnAttached(function(component) {
- detail.onSetup(component);
- }),
- run$1(mouseover(), function(comp, se) {
- descendant(comp.element, ".tox-mbtn--active").each(function(activeButton) {
- closest$1(se.event.target, ".tox-mbtn").each(function(hoveredButton) {
- if (!eq(activeButton, hoveredButton)) {
- comp.getSystem().getByDom(activeButton).each(function(activeComp) {
- comp.getSystem().getByDom(hoveredButton).each(function(hoveredComp) {
- Dropdown.expand(hoveredComp);
- Dropdown.close(activeComp);
- Focusing.focus(hoveredComp);
- });
- });
- }
- });
- });
- }),
- run$1(focusShifted(), function(comp, se) {
- se.event.prevFocus.bind(function(prev) {
- return comp.getSystem().getByDom(prev).toOptional();
- }).each(function(prev) {
- se.event.newFocus.bind(function(nu2) {
- return comp.getSystem().getByDom(nu2).toOptional();
- }).each(function(nu2) {
- if (Dropdown.isOpen(prev)) {
- Dropdown.expand(nu2);
- Dropdown.close(prev);
- }
- });
- });
- })
- ]),
- Keying.config({
- mode: "flow",
- selector: ".tox-mbtn",
- onEscape: function(comp) {
- detail.onEscape(comp);
- return Optional.some(true);
- }
- }),
- Tabstopping.config({})
- ]),
- apis,
- domModification: { attributes: { role: "menubar" } }
- };
- };
- var SilverMenubar = single({
- factory: factory$b,
- name: "silver.Menubar",
- configFields: [
- required$1("dom"),
- required$1("uid"),
- required$1("onEscape"),
- required$1("backstage"),
- defaulted("onSetup", noop)
- ],
- apis: {
- focus: function(apis, comp) {
- apis.focus(comp);
- },
- setMenus: function(apis, comp, menus) {
- apis.setMenus(comp, menus);
- }
- }
- });
- var getAnimationRoot = function(component, slideConfig) {
- return slideConfig.getAnimationRoot.fold(function() {
- return component.element;
- }, function(get2) {
- return get2(component);
- });
- };
- var getDimensionProperty = function(slideConfig) {
- return slideConfig.dimension.property;
- };
- var getDimension = function(slideConfig, elem) {
- return slideConfig.dimension.getDimension(elem);
- };
- var disableTransitions = function(component, slideConfig) {
- var root = getAnimationRoot(component, slideConfig);
- remove$1(root, [
- slideConfig.shrinkingClass,
- slideConfig.growingClass
- ]);
- };
- var setShrunk = function(component, slideConfig) {
- remove$2(component.element, slideConfig.openClass);
- add$2(component.element, slideConfig.closedClass);
- set$7(component.element, getDimensionProperty(slideConfig), "0px");
- reflow(component.element);
- };
- var setGrown = function(component, slideConfig) {
- remove$2(component.element, slideConfig.closedClass);
- add$2(component.element, slideConfig.openClass);
- remove$6(component.element, getDimensionProperty(slideConfig));
- };
- var doImmediateShrink = function(component, slideConfig, slideState, _calculatedSize) {
- slideState.setCollapsed();
- set$7(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
- reflow(component.element);
- disableTransitions(component, slideConfig);
- setShrunk(component, slideConfig);
- slideConfig.onStartShrink(component);
- slideConfig.onShrunk(component);
- };
- var doStartShrink = function(component, slideConfig, slideState, calculatedSize) {
- var size = calculatedSize.getOrThunk(function() {
- return getDimension(slideConfig, component.element);
- });
- slideState.setCollapsed();
- set$7(component.element, getDimensionProperty(slideConfig), size);
- reflow(component.element);
- var root = getAnimationRoot(component, slideConfig);
- remove$2(root, slideConfig.growingClass);
- add$2(root, slideConfig.shrinkingClass);
- setShrunk(component, slideConfig);
- slideConfig.onStartShrink(component);
- };
- var doStartSmartShrink = function(component, slideConfig, slideState) {
- var size = getDimension(slideConfig, component.element);
- var shrinker = size === "0px" ? doImmediateShrink : doStartShrink;
- shrinker(component, slideConfig, slideState, Optional.some(size));
- };
- var doStartGrow = function(component, slideConfig, slideState) {
- var root = getAnimationRoot(component, slideConfig);
- var wasShrinking = has(root, slideConfig.shrinkingClass);
- var beforeSize = getDimension(slideConfig, component.element);
- setGrown(component, slideConfig);
- var fullSize = getDimension(slideConfig, component.element);
- var startPartialGrow = function() {
- set$7(component.element, getDimensionProperty(slideConfig), beforeSize);
- reflow(component.element);
- };
- var startCompleteGrow = function() {
- setShrunk(component, slideConfig);
- };
- var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
- setStartSize();
- remove$2(root, slideConfig.shrinkingClass);
- add$2(root, slideConfig.growingClass);
- setGrown(component, slideConfig);
- set$7(component.element, getDimensionProperty(slideConfig), fullSize);
- slideState.setExpanded();
- slideConfig.onStartGrow(component);
- };
- var refresh$3 = function(component, slideConfig, slideState) {
- if (slideState.isExpanded()) {
- remove$6(component.element, getDimensionProperty(slideConfig));
- var fullSize = getDimension(slideConfig, component.element);
- set$7(component.element, getDimensionProperty(slideConfig), fullSize);
- }
- };
- var grow = function(component, slideConfig, slideState) {
- if (!slideState.isExpanded()) {
- doStartGrow(component, slideConfig, slideState);
- }
- };
- var shrink = function(component, slideConfig, slideState) {
- if (slideState.isExpanded()) {
- doStartSmartShrink(component, slideConfig, slideState);
- }
- };
- var immediateShrink = function(component, slideConfig, slideState) {
- if (slideState.isExpanded()) {
- doImmediateShrink(component, slideConfig, slideState);
- }
- };
- var hasGrown = function(component, slideConfig, slideState) {
- return slideState.isExpanded();
- };
- var hasShrunk = function(component, slideConfig, slideState) {
- return slideState.isCollapsed();
- };
- var isGrowing = function(component, slideConfig, _slideState) {
- var root = getAnimationRoot(component, slideConfig);
- return has(root, slideConfig.growingClass) === true;
- };
- var isShrinking = function(component, slideConfig, _slideState) {
- var root = getAnimationRoot(component, slideConfig);
- return has(root, slideConfig.shrinkingClass) === true;
- };
- var isTransitioning = function(component, slideConfig, slideState) {
- return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
- };
- var toggleGrow = function(component, slideConfig, slideState) {
- var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
- f(component, slideConfig, slideState);
- };
- var SlidingApis = Object.freeze({
- __proto__: null,
- refresh: refresh$3,
- grow,
- shrink,
- immediateShrink,
- hasGrown,
- hasShrunk,
- isGrowing,
- isShrinking,
- isTransitioning,
- toggleGrow,
- disableTransitions
- });
- var exhibit = function(base2, slideConfig, _slideState) {
- var expanded = slideConfig.expanded;
- return expanded ? nu$7({
- classes: [slideConfig.openClass],
- styles: {}
- }) : nu$7({
- classes: [slideConfig.closedClass],
- styles: wrap$1(slideConfig.dimension.property, "0px")
- });
- };
- var events$4 = function(slideConfig, slideState) {
- return derive$2([runOnSource(transitionend(), function(component, simulatedEvent) {
- var raw = simulatedEvent.event.raw;
- if (raw.propertyName === slideConfig.dimension.property) {
- disableTransitions(component, slideConfig);
- if (slideState.isExpanded()) {
- remove$6(component.element, slideConfig.dimension.property);
- }
- var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
- notify(component);
- }
- })]);
- };
- var ActiveSliding = Object.freeze({
- __proto__: null,
- exhibit,
- events: events$4
- });
- var SlidingSchema = [
- required$1("closedClass"),
- required$1("openClass"),
- required$1("shrinkingClass"),
- required$1("growingClass"),
- option("getAnimationRoot"),
- onHandler("onShrunk"),
- onHandler("onStartShrink"),
- onHandler("onGrown"),
- onHandler("onStartGrow"),
- defaulted("expanded", false),
- requiredOf("dimension", choose$1("property", {
- width: [
- output$1("property", "width"),
- output$1("getDimension", function(elem) {
- return get$a(elem) + "px";
- })
- ],
- height: [
- output$1("property", "height"),
- output$1("getDimension", function(elem) {
- return get$b(elem) + "px";
- })
- ]
- }))
- ];
- var init$5 = function(spec) {
- var state = Cell(spec.expanded);
- var readState = function() {
- return "expanded: " + state.get();
- };
- return nu$8({
- isExpanded: function() {
- return state.get() === true;
- },
- isCollapsed: function() {
- return state.get() === false;
- },
- setCollapsed: curry(state.set, false),
- setExpanded: curry(state.set, true),
- readState
- });
- };
- var SlidingState = Object.freeze({
- __proto__: null,
- init: init$5
- });
- var Sliding = create$8({
- fields: SlidingSchema,
- name: "sliding",
- active: ActiveSliding,
- apis: SlidingApis,
- state: SlidingState
- });
- var owner = "container";
- var schema$d = [field("slotBehaviours", [])];
- var getPartName = function(name2) {
- return "<alloy.field." + name2 + ">";
- };
- var sketch = function(sSpec) {
- var parts2 = function() {
- var record2 = [];
- var slot = function(name2, config2) {
- record2.push(name2);
- return generateOne$1(owner, getPartName(name2), config2);
- };
- return {
- slot,
- record: constant$1(record2)
- };
- }();
- var spec = sSpec(parts2);
- var partNames = parts2.record();
- var fieldParts = map$2(partNames, function(n) {
- return required({
- name: n,
- pname: getPartName(n)
- });
- });
- return composite$1(owner, schema$d, fieldParts, make$1, spec);
- };
- var make$1 = function(detail, components2) {
- var getSlotNames = function(_) {
- return getAllPartNames(detail);
- };
- var getSlot = function(container, key) {
- return getPart(container, detail, key);
- };
- var onSlot = function(f, def) {
- return function(container, key) {
- return getPart(container, detail, key).map(function(slot) {
- return f(slot, key);
- }).getOr(def);
- };
- };
- var onSlots = function(f) {
- return function(container, keys2) {
- each$1(keys2, function(key) {
- return f(container, key);
- });
- };
- };
- var doShowing = function(comp, _key) {
- return get$d(comp.element, "aria-hidden") !== "true";
- };
- var doShow = function(comp, key) {
- if (!doShowing(comp)) {
- var element2 = comp.element;
- remove$6(element2, "display");
- remove$7(element2, "aria-hidden");
- emitWith(comp, slotVisibility(), {
- name: key,
- visible: true
- });
- }
- };
- var doHide = function(comp, key) {
- if (doShowing(comp)) {
- var element2 = comp.element;
- set$7(element2, "display", "none");
- set$8(element2, "aria-hidden", "true");
- emitWith(comp, slotVisibility(), {
- name: key,
- visible: false
- });
- }
- };
- var isShowing = onSlot(doShowing, false);
- var hideSlot = onSlot(doHide);
- var hideSlots = onSlots(hideSlot);
- var hideAllSlots = function(container) {
- return hideSlots(container, getSlotNames());
- };
- var showSlot = onSlot(doShow);
- var apis = {
- getSlotNames,
- getSlot,
- isShowing,
- hideSlot,
- hideAllSlots,
- showSlot
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: get$2(detail.slotBehaviours),
- apis
- };
- };
- var slotApis = map$1({
- getSlotNames: function(apis, c) {
- return apis.getSlotNames(c);
- },
- getSlot: function(apis, c, key) {
- return apis.getSlot(c, key);
- },
- isShowing: function(apis, c, key) {
- return apis.isShowing(c, key);
- },
- hideSlot: function(apis, c, key) {
- return apis.hideSlot(c, key);
- },
- hideAllSlots: function(apis, c) {
- return apis.hideAllSlots(c);
- },
- showSlot: function(apis, c, key) {
- return apis.showSlot(c, key);
- }
- }, function(value2) {
- return makeApi(value2);
- });
- var SlotContainer = __assign(__assign({}, slotApis), { sketch });
- var sidebarSchema = objOf([
- optionString("icon"),
- optionString("tooltip"),
- defaultedFunction("onShow", noop),
- defaultedFunction("onHide", noop),
- defaultedFunction("onSetup", function() {
- return noop;
- })
- ]);
- var createSidebar = function(spec) {
- return asRaw("sidebar", sidebarSchema, spec);
- };
- var setup$8 = function(editor) {
- var sidebars = editor.ui.registry.getAll().sidebars;
- each$1(keys(sidebars), function(name2) {
- var spec = sidebars[name2];
- var isActive = function() {
- return is$1(Optional.from(editor.queryCommandValue("ToggleSidebar")), name2);
- };
- editor.ui.registry.addToggleButton(name2, {
- icon: spec.icon,
- tooltip: spec.tooltip,
- onAction: function(buttonApi) {
- editor.execCommand("ToggleSidebar", false, name2);
- buttonApi.setActive(isActive());
- },
- onSetup: function(buttonApi) {
- var handleToggle = function() {
- return buttonApi.setActive(isActive());
- };
- editor.on("ToggleSidebar", handleToggle);
- return function() {
- editor.off("ToggleSidebar", handleToggle);
- };
- }
- });
- });
- };
- var getApi = function(comp) {
- return {
- element: function() {
- return comp.element.dom;
- }
- };
- };
- var makePanels = function(parts2, panelConfigs) {
- var specs = map$2(keys(panelConfigs), function(name2) {
- var spec = panelConfigs[name2];
- var bridged = getOrDie(createSidebar(spec));
- return {
- name: name2,
- getApi,
- onSetup: bridged.onSetup,
- onShow: bridged.onShow,
- onHide: bridged.onHide
- };
- });
- return map$2(specs, function(spec) {
- var editorOffCell = Cell(noop);
- return parts2.slot(spec.name, {
- dom: {
- tag: "div",
- classes: ["tox-sidebar__pane"]
- },
- behaviours: SimpleBehaviours.unnamedEvents([
- onControlAttached(spec, editorOffCell),
- onControlDetached(spec, editorOffCell),
- run$1(slotVisibility(), function(sidepanel, se) {
- var data = se.event;
- var optSidePanelSpec = find$5(specs, function(config2) {
- return config2.name === data.name;
- });
- optSidePanelSpec.each(function(sidePanelSpec) {
- var handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide;
- handler(sidePanelSpec.getApi(sidepanel));
- });
- })
- ])
- });
- });
- };
- var makeSidebar = function(panelConfigs) {
- return SlotContainer.sketch(function(parts2) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-sidebar__pane-container"]
- },
- components: makePanels(parts2, panelConfigs),
- slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function(slotContainer) {
- return SlotContainer.hideAllSlots(slotContainer);
- })])
- };
- });
- };
- var setSidebar = function(sidebar, panelConfigs) {
- var optSlider = Composing.getCurrent(sidebar);
- optSlider.each(function(slider) {
- return Replacing.set(slider, [makeSidebar(panelConfigs)]);
- });
- };
- var toggleSidebar = function(sidebar, name2) {
- var optSlider = Composing.getCurrent(sidebar);
- optSlider.each(function(slider) {
- var optSlotContainer = Composing.getCurrent(slider);
- optSlotContainer.each(function(slotContainer) {
- if (Sliding.hasGrown(slider)) {
- if (SlotContainer.isShowing(slotContainer, name2)) {
- Sliding.shrink(slider);
- } else {
- SlotContainer.hideAllSlots(slotContainer);
- SlotContainer.showSlot(slotContainer, name2);
- }
- } else {
- SlotContainer.hideAllSlots(slotContainer);
- SlotContainer.showSlot(slotContainer, name2);
- Sliding.grow(slider);
- }
- });
- });
- };
- var whichSidebar = function(sidebar) {
- var optSlider = Composing.getCurrent(sidebar);
- return optSlider.bind(function(slider) {
- var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
- if (sidebarOpen) {
- var optSlotContainer = Composing.getCurrent(slider);
- return optSlotContainer.bind(function(slotContainer) {
- return find$5(SlotContainer.getSlotNames(slotContainer), function(name2) {
- return SlotContainer.isShowing(slotContainer, name2);
- });
- });
- } else {
- return Optional.none();
- }
- });
- };
- var fixSize = generate$6("FixSizeEvent");
- var autoSize = generate$6("AutoSizeEvent");
- var renderSidebar = function(spec) {
- return {
- uid: spec.uid,
- dom: {
- tag: "div",
- classes: ["tox-sidebar"],
- attributes: { role: "complementary" }
- },
- components: [{
- dom: {
- tag: "div",
- classes: ["tox-sidebar__slider"]
- },
- components: [],
- behaviours: derive$1([
- Tabstopping.config({}),
- Focusing.config({}),
- Sliding.config({
- dimension: { property: "width" },
- closedClass: "tox-sidebar--sliding-closed",
- openClass: "tox-sidebar--sliding-open",
- shrinkingClass: "tox-sidebar--sliding-shrinking",
- growingClass: "tox-sidebar--sliding-growing",
- onShrunk: function(slider) {
- var optSlotContainer = Composing.getCurrent(slider);
- optSlotContainer.each(SlotContainer.hideAllSlots);
- emit(slider, autoSize);
- },
- onGrown: function(slider) {
- emit(slider, autoSize);
- },
- onStartGrow: function(slider) {
- emitWith(slider, fixSize, { width: getRaw(slider.element, "width").getOr("") });
- },
- onStartShrink: function(slider) {
- emitWith(slider, fixSize, { width: get$a(slider.element) + "px" });
- }
- }),
- Replacing.config({}),
- Composing.config({
- find: function(comp) {
- var children2 = Replacing.contents(comp);
- return head(children2);
- }
- })
- ])
- }],
- behaviours: derive$1([
- ComposingConfigs.childAt(0),
- config("sidebar-sliding-events", [
- run$1(fixSize, function(comp, se) {
- set$7(comp.element, "width", se.event.width);
- }),
- run$1(autoSize, function(comp, _se) {
- remove$6(comp.element, "width");
- })
- ])
- ])
- };
- };
- var block = function(component, config2, state, getBusySpec2) {
- set$8(component.element, "aria-busy", true);
- var root = config2.getRoot(component).getOr(component);
- var blockerBehaviours = derive$1([
- Keying.config({
- mode: "special",
- onTab: function() {
- return Optional.some(true);
- },
- onShiftTab: function() {
- return Optional.some(true);
- }
- }),
- Focusing.config({})
- ]);
- var blockSpec = getBusySpec2(root, blockerBehaviours);
- var blocker = root.getSystem().build(blockSpec);
- Replacing.append(root, premade(blocker));
- if (blocker.hasConfigured(Keying) && config2.focus) {
- Keying.focusIn(blocker);
- }
- if (!state.isBlocked()) {
- config2.onBlock(component);
- }
- state.blockWith(function() {
- return Replacing.remove(root, blocker);
- });
- };
- var unblock = function(component, config2, state) {
- remove$7(component.element, "aria-busy");
- if (state.isBlocked()) {
- config2.onUnblock(component);
- }
- state.clear();
- };
- var BlockingApis = Object.freeze({
- __proto__: null,
- block,
- unblock
- });
- var BlockingSchema = [
- defaultedFunction("getRoot", Optional.none),
- defaultedBoolean("focus", true),
- onHandler("onBlock"),
- onHandler("onUnblock")
- ];
- var init$4 = function() {
- var blocker = destroyable();
- var blockWith = function(destroy) {
- blocker.set({ destroy });
- };
- return nu$8({
- readState: blocker.isSet,
- blockWith,
- clear: blocker.clear,
- isBlocked: blocker.isSet
- });
- };
- var BlockingState = Object.freeze({
- __proto__: null,
- init: init$4
- });
- var Blocking = create$8({
- fields: BlockingSchema,
- name: "blocking",
- apis: BlockingApis,
- state: BlockingState
- });
- var getAttrs = function(elem) {
- var attributes = elem.dom.attributes !== void 0 ? elem.dom.attributes : [];
- return foldl(attributes, function(b2, attr) {
- var _a2;
- if (attr.name === "class") {
- return b2;
- } else {
- return __assign(__assign({}, b2), (_a2 = {}, _a2[attr.name] = attr.value, _a2));
- }
- }, {});
- };
- var getClasses = function(elem) {
- return Array.prototype.slice.call(elem.dom.classList, 0);
- };
- var fromHtml = function(html2) {
- var elem = SugarElement.fromHtml(html2);
- var children$1 = children(elem);
- var attrs = getAttrs(elem);
- var classes2 = getClasses(elem);
- var contents2 = children$1.length === 0 ? {} : { innerHtml: get$7(elem) };
- return __assign({
- tag: name$2(elem),
- classes: classes2,
- attributes: attrs
- }, contents2);
- };
- var getBusySpec$1 = function(providerBackstage) {
- return function(_root, _behaviours) {
- return {
- dom: {
- tag: "div",
- attributes: {
- "aria-label": providerBackstage.translate("Loading..."),
- "tabindex": "0"
- },
- classes: ["tox-throbber__busy-spinner"]
- },
- components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
- };
- };
- };
- var focusBusyComponent = function(throbber) {
- return Composing.getCurrent(throbber).each(function(comp) {
- return focus$3(comp.element);
- });
- };
- var toggleEditorTabIndex = function(editor, state) {
- var tabIndexAttr = "tabindex";
- var dataTabIndexAttr = "data-mce-" + tabIndexAttr;
- Optional.from(editor.iframeElement).map(SugarElement.fromDom).each(function(iframe2) {
- if (state) {
- getOpt(iframe2, tabIndexAttr).each(function(tabIndex) {
- return set$8(iframe2, dataTabIndexAttr, tabIndex);
- });
- set$8(iframe2, tabIndexAttr, -1);
- } else {
- remove$7(iframe2, tabIndexAttr);
- getOpt(iframe2, dataTabIndexAttr).each(function(tabIndex) {
- set$8(iframe2, tabIndexAttr, tabIndex);
- remove$7(iframe2, dataTabIndexAttr);
- });
- }
- });
- };
- var toggleThrobber = function(editor, comp, state, providerBackstage) {
- var element2 = comp.element;
- toggleEditorTabIndex(editor, state);
- if (state) {
- Blocking.block(comp, getBusySpec$1(providerBackstage));
- remove$6(element2, "display");
- remove$7(element2, "aria-hidden");
- if (editor.hasFocus()) {
- focusBusyComponent(comp);
- }
- } else {
- var throbberFocus = Composing.getCurrent(comp).exists(function(busyComp) {
- return hasFocus(busyComp.element);
- });
- Blocking.unblock(comp);
- set$7(element2, "display", "none");
- set$8(element2, "aria-hidden", "true");
- if (throbberFocus) {
- editor.focus();
- }
- }
- };
- var renderThrobber = function(spec) {
- return {
- uid: spec.uid,
- dom: {
- tag: "div",
- attributes: { "aria-hidden": "true" },
- classes: ["tox-throbber"],
- styles: { display: "none" }
- },
- behaviours: derive$1([
- Replacing.config({}),
- Blocking.config({ focus: false }),
- Composing.config({
- find: function(comp) {
- return head(comp.components());
- }
- })
- ]),
- components: []
- };
- };
- var isFocusEvent = function(event) {
- return event.type === "focusin";
- };
- var isPasteBinTarget = function(event) {
- if (isFocusEvent(event)) {
- var node = event.composed ? head(event.composedPath()) : Optional.from(event.target);
- return node.map(SugarElement.fromDom).filter(isElement$2).exists(function(targetElm) {
- return has(targetElm, "mce-pastebin");
- });
- } else {
- return false;
- }
- };
- var setup$7 = function(editor, lazyThrobber, sharedBackstage) {
- var throbberState = Cell(false);
- var timer = value$1();
- var stealFocus = function(e) {
- if (throbberState.get() && !isPasteBinTarget(e)) {
- e.preventDefault();
- focusBusyComponent(lazyThrobber());
- editor.editorManager.setActive(editor);
- }
- };
- if (!editor.inline) {
- editor.on("PreInit", function() {
- editor.dom.bind(editor.getWin(), "focusin", stealFocus);
- editor.on("BeforeExecCommand", function(e) {
- if (e.command.toLowerCase() === "mcefocus" && e.value !== true) {
- stealFocus(e);
- }
- });
- });
- }
- var toggle2 = function(state) {
- if (state !== throbberState.get()) {
- throbberState.set(state);
- toggleThrobber(editor, lazyThrobber(), state, sharedBackstage.providers);
- editor.fire("AfterProgressState", { state });
- }
- };
- editor.on("ProgressState", function(e) {
- timer.on(global$f.clearTimeout);
- if (isNumber(e.time)) {
- var timerId = global$f.setEditorTimeout(editor, function() {
- return toggle2(e.state);
- }, e.time);
- timer.set(timerId);
- } else {
- toggle2(e.state);
- timer.clear();
- }
- });
- };
- var generate$1 = function(xs, f) {
- var init2 = {
- len: 0,
- list: []
- };
- var r2 = foldl(xs, function(b2, a) {
- var value2 = f(a, b2.len);
- return value2.fold(constant$1(b2), function(v) {
- return {
- len: v.finish,
- list: b2.list.concat([v])
- };
- });
- }, init2);
- return r2.list;
- };
- var output = function(within, extra, withinWidth) {
- return {
- within,
- extra,
- withinWidth
- };
- };
- var apportion = function(units2, total, len) {
- var parray = generate$1(units2, function(unit, current) {
- var width2 = len(unit);
- return Optional.some({
- element: unit,
- start: current,
- finish: current + width2,
- width: width2
- });
- });
- var within = filter$2(parray, function(unit) {
- return unit.finish <= total;
- });
- var withinWidth = foldr(within, function(acc, el) {
- return acc + el.width;
- }, 0);
- var extra = parray.slice(within.length);
- return {
- within,
- extra,
- withinWidth
- };
- };
- var toUnit = function(parray) {
- return map$2(parray, function(unit) {
- return unit.element;
- });
- };
- var fitLast = function(within, extra, withinWidth) {
- var fits = toUnit(within.concat(extra));
- return output(fits, [], withinWidth);
- };
- var overflow = function(within, extra, overflower, withinWidth) {
- var fits = toUnit(within).concat([overflower]);
- return output(fits, toUnit(extra), withinWidth);
- };
- var fitAll = function(within, extra, withinWidth) {
- return output(toUnit(within), [], withinWidth);
- };
- var tryFit = function(total, units2, len) {
- var divide = apportion(units2, total, len);
- return divide.extra.length === 0 ? Optional.some(divide) : Optional.none();
- };
- var partition = function(total, units2, len, overflower) {
- var divide = tryFit(total, units2, len).getOrThunk(function() {
- return apportion(units2, total - len(overflower), len);
- });
- var within = divide.within;
- var extra = divide.extra;
- var withinWidth = divide.withinWidth;
- if (extra.length === 1 && extra[0].width <= len(overflower)) {
- return fitLast(within, extra, withinWidth);
- } else if (extra.length >= 1) {
- return overflow(within, extra, overflower, withinWidth);
- } else {
- return fitAll(within, extra, withinWidth);
- }
- };
- var setGroups$1 = function(toolbar, storedGroups) {
- var bGroups = map$2(storedGroups, function(g) {
- return premade(g);
- });
- Toolbar.setGroups(toolbar, bGroups);
- };
- var findFocusedComp = function(comps) {
- return findMap(comps, function(comp) {
- return search(comp.element).bind(function(focusedElm) {
- return comp.getSystem().getByDom(focusedElm).toOptional();
- });
- });
- };
- var refresh$2 = function(toolbar, detail, setOverflow) {
- var builtGroups = detail.builtGroups.get();
- if (builtGroups.length === 0) {
- return;
- }
- var primary = getPartOrDie(toolbar, detail, "primary");
- var overflowGroup = Coupling.getCoupled(toolbar, "overflowGroup");
- set$7(primary.element, "visibility", "hidden");
- var groups = builtGroups.concat([overflowGroup]);
- var focusedComp = findFocusedComp(groups);
- setOverflow([]);
- setGroups$1(primary, groups);
- var availableWidth = get$a(primary.element);
- var overflows = partition(availableWidth, detail.builtGroups.get(), function(comp) {
- return get$a(comp.element);
- }, overflowGroup);
- if (overflows.extra.length === 0) {
- Replacing.remove(primary, overflowGroup);
- setOverflow([]);
- } else {
- setGroups$1(primary, overflows.within);
- setOverflow(overflows.extra);
- }
- remove$6(primary.element, "visibility");
- reflow(primary.element);
- focusedComp.each(Focusing.focus);
- };
- var schema$c = constant$1([
- field("splitToolbarBehaviours", [Coupling]),
- customField("builtGroups", function() {
- return Cell([]);
- })
- ]);
- var schema$b = constant$1([
- markers$1(["overflowToggledClass"]),
- optionFunction("getOverflowBounds"),
- required$1("lazySink"),
- customField("overflowGroups", function() {
- return Cell([]);
- })
- ].concat(schema$c()));
- var parts$7 = constant$1([
- required({
- factory: Toolbar,
- schema: schema$e(),
- name: "primary"
- }),
- external$1({
- schema: schema$e(),
- name: "overflow"
- }),
- external$1({ name: "overflow-button" }),
- external$1({ name: "overflow-group" })
- ]);
- var expandable = constant$1(function(element2, available) {
- setMax(element2, Math.floor(available));
- });
- var schema$a = constant$1([
- markers$1(["toggledClass"]),
- required$1("lazySink"),
- requiredFunction("fetch"),
- optionFunction("getBounds"),
- optionObjOf("fireDismissalEventInstead", [defaulted("event", dismissRequested())]),
- schema$y()
- ]);
- var parts$6 = constant$1([
- external$1({
- name: "button",
- overrides: function(detail) {
- return {
- dom: { attributes: { "aria-haspopup": "true" } },
- buttonBehaviours: derive$1([Toggling.config({
- toggleClass: detail.markers.toggledClass,
- aria: { mode: "expanded" },
- toggleOnExecute: false
- })])
- };
- }
- }),
- external$1({
- factory: Toolbar,
- schema: schema$e(),
- name: "toolbar",
- overrides: function(detail) {
- return {
- toolbarBehaviours: derive$1([Keying.config({
- mode: "cyclic",
- onEscape: function(comp) {
- getPart(comp, detail, "button").each(Focusing.focus);
- return Optional.none();
- }
- })])
- };
- }
- })
- ]);
- var toggle = function(button2, externals) {
- var toolbarSandbox = Coupling.getCoupled(button2, "toolbarSandbox");
- if (Sandboxing.isOpen(toolbarSandbox)) {
- Sandboxing.close(toolbarSandbox);
- } else {
- Sandboxing.open(toolbarSandbox, externals.toolbar());
- }
- };
- var position = function(button2, toolbar, detail, layouts2) {
- var bounds2 = detail.getBounds.map(function(bounder) {
- return bounder();
- });
- var sink = detail.lazySink(button2).getOrDie();
- Positioning.positionWithinBounds(sink, toolbar, {
- anchor: {
- type: "hotspot",
- hotspot: button2,
- layouts: layouts2,
- overrides: { maxWidthFunction: expandable() }
- }
- }, bounds2);
- };
- var setGroups = function(button2, toolbar, detail, layouts2, groups) {
- Toolbar.setGroups(toolbar, groups);
- position(button2, toolbar, detail, layouts2);
- Toggling.on(button2);
- };
- var makeSandbox = function(button2, spec, detail) {
- var ariaOwner = manager();
- var onOpen = function(sandbox, toolbar) {
- detail.fetch().get(function(groups) {
- setGroups(button2, toolbar, detail, spec.layouts, groups);
- ariaOwner.link(button2.element);
- Keying.focusIn(toolbar);
- });
- };
- var onClose = function() {
- Toggling.off(button2);
- Focusing.focus(button2);
- ariaOwner.unlink(button2.element);
- };
- return {
- dom: {
- tag: "div",
- attributes: { id: ariaOwner.id }
- },
- behaviours: derive$1([
- Keying.config({
- mode: "special",
- onEscape: function(comp) {
- Sandboxing.close(comp);
- return Optional.some(true);
- }
- }),
- Sandboxing.config({
- onOpen,
- onClose,
- isPartOf: function(container, data, queryElem) {
- return isPartOf$1(data, queryElem) || isPartOf$1(button2, queryElem);
- },
- getAttachPoint: function() {
- return detail.lazySink(button2).getOrDie();
- }
- }),
- Receiving.config({
- channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function(fe) {
- return { fireEventInstead: { event: fe.event } };
- }).getOr({})))), receivingChannel({
- doReposition: function() {
- Sandboxing.getState(Coupling.getCoupled(button2, "toolbarSandbox")).each(function(toolbar) {
- position(button2, toolbar, detail, spec.layouts);
- });
- }
- }))
- })
- ])
- };
- };
- var factory$a = function(detail, components2, spec, externals) {
- return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), {
- action: function(button2) {
- toggle(button2, externals);
- },
- buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
- others: {
- toolbarSandbox: function(button2) {
- return makeSandbox(button2, spec, detail);
- }
- }
- })])
- }))), {
- apis: {
- setGroups: function(button2, groups) {
- Sandboxing.getState(Coupling.getCoupled(button2, "toolbarSandbox")).each(function(toolbar) {
- setGroups(button2, toolbar, detail, spec.layouts, groups);
- });
- },
- reposition: function(button2) {
- Sandboxing.getState(Coupling.getCoupled(button2, "toolbarSandbox")).each(function(toolbar) {
- position(button2, toolbar, detail, spec.layouts);
- });
- },
- toggle: function(button2) {
- toggle(button2, externals);
- },
- getToolbar: function(button2) {
- return Sandboxing.getState(Coupling.getCoupled(button2, "toolbarSandbox"));
- },
- isOpen: function(button2) {
- return Sandboxing.isOpen(Coupling.getCoupled(button2, "toolbarSandbox"));
- }
- }
- });
- };
- var FloatingToolbarButton = composite({
- name: "FloatingToolbarButton",
- factory: factory$a,
- configFields: schema$a(),
- partFields: parts$6(),
- apis: {
- setGroups: function(apis, button2, groups) {
- apis.setGroups(button2, groups);
- },
- reposition: function(apis, button2) {
- apis.reposition(button2);
- },
- toggle: function(apis, button2) {
- apis.toggle(button2);
- },
- getToolbar: function(apis, button2) {
- return apis.getToolbar(button2);
- },
- isOpen: function(apis, button2) {
- return apis.isOpen(button2);
- }
- }
- });
- var schema$9 = constant$1([
- required$1("items"),
- markers$1(["itemSelector"]),
- field("tgroupBehaviours", [Keying])
- ]);
- var parts$5 = constant$1([group({
- name: "items",
- unit: "item"
- })]);
- var factory$9 = function(detail, components2, _spec, _externals) {
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: augment(detail.tgroupBehaviours, [Keying.config({
- mode: "flow",
- selector: detail.markers.itemSelector
- })]),
- domModification: { attributes: { role: "toolbar" } }
- };
- };
- var ToolbarGroup = composite({
- name: "ToolbarGroup",
- configFields: schema$9(),
- partFields: parts$5(),
- factory: factory$9
- });
- var buildGroups = function(comps) {
- return map$2(comps, function(g) {
- return premade(g);
- });
- };
- var refresh$1 = function(toolbar, memFloatingToolbarButton, detail) {
- refresh$2(toolbar, detail, function(overflowGroups) {
- detail.overflowGroups.set(overflowGroups);
- memFloatingToolbarButton.getOpt(toolbar).each(function(floatingToolbarButton) {
- FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
- });
- });
- };
- var factory$8 = function(detail, components2, spec, externals) {
- var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
- fetch: function() {
- return Future.nu(function(resolve) {
- resolve(buildGroups(detail.overflowGroups.get()));
- });
- },
- layouts: {
- onLtr: function() {
- return [
- southwest$2,
- southeast$2
- ];
- },
- onRtl: function() {
- return [
- southeast$2,
- southwest$2
- ];
- },
- onBottomLtr: function() {
- return [
- northwest$2,
- northeast$2
- ];
- },
- onBottomRtl: function() {
- return [
- northeast$2,
- northwest$2
- ];
- }
- },
- getBounds: spec.getOverflowBounds,
- lazySink: detail.lazySink,
- fireDismissalEventInstead: {},
- markers: { toggledClass: detail.markers.overflowToggledClass },
- parts: {
- button: externals["overflow-button"](),
- toolbar: externals.overflow()
- }
- }));
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
- others: {
- overflowGroup: function() {
- return ToolbarGroup.sketch(__assign(__assign({}, externals["overflow-group"]()), { items: [memFloatingToolbarButton.asSpec()] }));
- }
- }
- })]),
- apis: {
- setGroups: function(toolbar, groups) {
- detail.builtGroups.set(map$2(groups, toolbar.getSystem().build));
- refresh$1(toolbar, memFloatingToolbarButton, detail);
- },
- refresh: function(toolbar) {
- return refresh$1(toolbar, memFloatingToolbarButton, detail);
- },
- toggle: function(toolbar) {
- memFloatingToolbarButton.getOpt(toolbar).each(function(floatingToolbarButton) {
- FloatingToolbarButton.toggle(floatingToolbarButton);
- });
- },
- isOpen: function(toolbar) {
- return memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false);
- },
- reposition: function(toolbar) {
- memFloatingToolbarButton.getOpt(toolbar).each(function(floatingToolbarButton) {
- FloatingToolbarButton.reposition(floatingToolbarButton);
- });
- },
- getOverflow: function(toolbar) {
- return memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar);
- }
- },
- domModification: { attributes: { role: "group" } }
- };
- };
- var SplitFloatingToolbar = composite({
- name: "SplitFloatingToolbar",
- configFields: schema$b(),
- partFields: parts$7(),
- factory: factory$8,
- apis: {
- setGroups: function(apis, toolbar, groups) {
- apis.setGroups(toolbar, groups);
- },
- refresh: function(apis, toolbar) {
- apis.refresh(toolbar);
- },
- reposition: function(apis, toolbar) {
- apis.reposition(toolbar);
- },
- toggle: function(apis, toolbar) {
- apis.toggle(toolbar);
- },
- isOpen: function(apis, toolbar) {
- return apis.isOpen(toolbar);
- },
- getOverflow: function(apis, toolbar) {
- return apis.getOverflow(toolbar);
- }
- }
- });
- var schema$8 = constant$1([
- markers$1([
- "closedClass",
- "openClass",
- "shrinkingClass",
- "growingClass",
- "overflowToggledClass"
- ]),
- onHandler("onOpened"),
- onHandler("onClosed")
- ].concat(schema$c()));
- var parts$4 = constant$1([
- required({
- factory: Toolbar,
- schema: schema$e(),
- name: "primary"
- }),
- required({
- factory: Toolbar,
- schema: schema$e(),
- name: "overflow",
- overrides: function(detail) {
- return {
- toolbarBehaviours: derive$1([
- Sliding.config({
- dimension: { property: "height" },
- closedClass: detail.markers.closedClass,
- openClass: detail.markers.openClass,
- shrinkingClass: detail.markers.shrinkingClass,
- growingClass: detail.markers.growingClass,
- onShrunk: function(comp) {
- getPart(comp, detail, "overflow-button").each(function(button2) {
- Toggling.off(button2);
- Focusing.focus(button2);
- });
- detail.onClosed(comp);
- },
- onGrown: function(comp) {
- Keying.focusIn(comp);
- detail.onOpened(comp);
- },
- onStartGrow: function(comp) {
- getPart(comp, detail, "overflow-button").each(Toggling.on);
- }
- }),
- Keying.config({
- mode: "acyclic",
- onEscape: function(comp) {
- getPart(comp, detail, "overflow-button").each(Focusing.focus);
- return Optional.some(true);
- }
- })
- ])
- };
- }
- }),
- external$1({
- name: "overflow-button",
- overrides: function(detail) {
- return {
- buttonBehaviours: derive$1([Toggling.config({
- toggleClass: detail.markers.overflowToggledClass,
- aria: { mode: "pressed" },
- toggleOnExecute: false
- })])
- };
- }
- }),
- external$1({ name: "overflow-group" })
- ]);
- var isOpen = function(toolbar, detail) {
- return getPart(toolbar, detail, "overflow").map(Sliding.hasGrown).getOr(false);
- };
- var toggleToolbar = function(toolbar, detail) {
- getPart(toolbar, detail, "overflow-button").bind(function() {
- return getPart(toolbar, detail, "overflow");
- }).each(function(overf) {
- refresh(toolbar, detail);
- Sliding.toggleGrow(overf);
- });
- };
- var refresh = function(toolbar, detail) {
- getPart(toolbar, detail, "overflow").each(function(overflow2) {
- refresh$2(toolbar, detail, function(groups) {
- var builtGroups = map$2(groups, function(g) {
- return premade(g);
- });
- Toolbar.setGroups(overflow2, builtGroups);
- });
- getPart(toolbar, detail, "overflow-button").each(function(button2) {
- if (Sliding.hasGrown(overflow2)) {
- Toggling.on(button2);
- }
- });
- Sliding.refresh(overflow2);
- });
- };
- var factory$7 = function(detail, components2, spec, externals) {
- var toolbarToggleEvent = "alloy.toolbar.toggle";
- var doSetGroups = function(toolbar, groups) {
- var built = map$2(groups, toolbar.getSystem().build);
- detail.builtGroups.set(built);
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: augment(detail.splitToolbarBehaviours, [
- Coupling.config({
- others: {
- overflowGroup: function(toolbar) {
- return ToolbarGroup.sketch(__assign(__assign({}, externals["overflow-group"]()), {
- items: [Button.sketch(__assign(__assign({}, externals["overflow-button"]()), {
- action: function(_button) {
- emit(toolbar, toolbarToggleEvent);
- }
- }))]
- }));
- }
- }
- }),
- config("toolbar-toggle-events", [run$1(toolbarToggleEvent, function(toolbar) {
- toggleToolbar(toolbar, detail);
- })])
- ]),
- apis: {
- setGroups: function(toolbar, groups) {
- doSetGroups(toolbar, groups);
- refresh(toolbar, detail);
- },
- refresh: function(toolbar) {
- return refresh(toolbar, detail);
- },
- toggle: function(toolbar) {
- return toggleToolbar(toolbar, detail);
- },
- isOpen: function(toolbar) {
- return isOpen(toolbar, detail);
- }
- },
- domModification: { attributes: { role: "group" } }
- };
- };
- var SplitSlidingToolbar = composite({
- name: "SplitSlidingToolbar",
- configFields: schema$8(),
- partFields: parts$4(),
- factory: factory$7,
- apis: {
- setGroups: function(apis, toolbar, groups) {
- apis.setGroups(toolbar, groups);
- },
- refresh: function(apis, toolbar) {
- apis.refresh(toolbar);
- },
- toggle: function(apis, toolbar) {
- apis.toggle(toolbar);
- },
- isOpen: function(apis, toolbar) {
- return apis.isOpen(toolbar);
- }
- }
- });
- var renderToolbarGroupCommon = function(toolbarGroup) {
- var attributes = toolbarGroup.title.fold(function() {
- return {};
- }, function(title) {
- return { attributes: { title } };
- });
- return {
- dom: __assign({
- tag: "div",
- classes: ["tox-toolbar__group"]
- }, attributes),
- components: [ToolbarGroup.parts.items({})],
- items: toolbarGroup.items,
- markers: { itemSelector: "*:not(.tox-split-button) > .tox-tbtn:not([disabled]), .tox-split-button:not([disabled]), .tox-toolbar-nav-js:not([disabled])" },
- tgroupBehaviours: derive$1([
- Tabstopping.config({}),
- Focusing.config({})
- ])
- };
- };
- var renderToolbarGroup = function(toolbarGroup) {
- return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
- };
- var getToolbarbehaviours = function(toolbarSpec, modeName) {
- var onAttached = runOnAttached(function(component) {
- var groups = map$2(toolbarSpec.initGroups, renderToolbarGroup);
- Toolbar.setGroups(component, groups);
- });
- return derive$1([
- DisablingConfigs.toolbarButton(toolbarSpec.providers.isDisabled),
- receivingConfig(),
- Keying.config({
- mode: modeName,
- onEscape: toolbarSpec.onEscape,
- selector: ".tox-toolbar__group"
- }),
- config("toolbar-events", [onAttached])
- ]);
- };
- var renderMoreToolbarCommon = function(toolbarSpec) {
- var modeName = toolbarSpec.cyclicKeying ? "cyclic" : "acyclic";
- return {
- uid: toolbarSpec.uid,
- dom: {
- tag: "div",
- classes: ["tox-toolbar-overlord"]
- },
- parts: {
- "overflow-group": renderToolbarGroupCommon({
- title: Optional.none(),
- items: []
- }),
- "overflow-button": renderIconButtonSpec({
- name: "more",
- icon: Optional.some("more-drawer"),
- disabled: false,
- tooltip: Optional.some("More..."),
- primary: false,
- borderless: false
- }, Optional.none(), toolbarSpec.providers)
- },
- splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
- };
- };
- var renderFloatingMoreToolbar = function(toolbarSpec) {
- var baseSpec = renderMoreToolbarCommon(toolbarSpec);
- var overflowXOffset = 4;
- var primary = SplitFloatingToolbar.parts.primary({
- dom: {
- tag: "div",
- classes: ["tox-toolbar__primary"]
- }
- });
- return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
- lazySink: toolbarSpec.getSink,
- getOverflowBounds: function() {
- var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element;
- var headerBounds = absolute$2(headerElem);
- var docElem = documentElement(headerElem);
- var docBounds = absolute$2(docElem);
- var height2 = Math.max(docElem.dom.scrollHeight, docBounds.height);
- return bounds(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height2);
- },
- parts: __assign(__assign({}, baseSpec.parts), {
- overflow: {
- dom: {
- tag: "div",
- classes: ["tox-toolbar__overflow"],
- attributes: toolbarSpec.attributes
- }
- }
- }),
- components: [primary],
- markers: { overflowToggledClass: "tox-tbtn--enabled" }
- }));
- };
- var renderSlidingMoreToolbar = function(toolbarSpec) {
- var primary = SplitSlidingToolbar.parts.primary({
- dom: {
- tag: "div",
- classes: ["tox-toolbar__primary"]
- }
- });
- var overflow2 = SplitSlidingToolbar.parts.overflow({
- dom: {
- tag: "div",
- classes: ["tox-toolbar__overflow"]
- }
- });
- var baseSpec = renderMoreToolbarCommon(toolbarSpec);
- return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
- components: [
- primary,
- overflow2
- ],
- markers: {
- openClass: "tox-toolbar__overflow--open",
- closedClass: "tox-toolbar__overflow--closed",
- growingClass: "tox-toolbar__overflow--growing",
- shrinkingClass: "tox-toolbar__overflow--shrinking",
- overflowToggledClass: "tox-tbtn--enabled"
- },
- onOpened: function(comp) {
- comp.getSystem().broadcastOn([toolbarHeightChange()], { type: "opened" });
- },
- onClosed: function(comp) {
- comp.getSystem().broadcastOn([toolbarHeightChange()], { type: "closed" });
- }
- }));
- };
- var renderToolbar = function(toolbarSpec) {
- var modeName = toolbarSpec.cyclicKeying ? "cyclic" : "acyclic";
- return Toolbar.sketch({
- uid: toolbarSpec.uid,
- dom: {
- tag: "div",
- classes: ["tox-toolbar"].concat(toolbarSpec.type === ToolbarMode.scrolling ? ["tox-toolbar--scrolling"] : [])
- },
- components: [Toolbar.parts.groups({})],
- toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
- });
- };
- var factory$6 = function(detail, components2, _spec) {
- var apis = {
- getSocket: function(comp) {
- return parts$a.getPart(comp, detail, "socket");
- },
- setSidebar: function(comp, panelConfigs) {
- parts$a.getPart(comp, detail, "sidebar").each(function(sidebar) {
- return setSidebar(sidebar, panelConfigs);
- });
- },
- toggleSidebar: function(comp, name2) {
- parts$a.getPart(comp, detail, "sidebar").each(function(sidebar) {
- return toggleSidebar(sidebar, name2);
- });
- },
- whichSidebar: function(comp) {
- return parts$a.getPart(comp, detail, "sidebar").bind(whichSidebar).getOrNull();
- },
- getHeader: function(comp) {
- return parts$a.getPart(comp, detail, "header");
- },
- getToolbar: function(comp) {
- return parts$a.getPart(comp, detail, "toolbar");
- },
- setToolbar: function(comp, groups) {
- parts$a.getPart(comp, detail, "toolbar").each(function(toolbar) {
- toolbar.getApis().setGroups(toolbar, groups);
- });
- },
- setToolbars: function(comp, toolbars) {
- parts$a.getPart(comp, detail, "multiple-toolbar").each(function(mToolbar) {
- CustomList.setItems(mToolbar, toolbars);
- });
- },
- refreshToolbar: function(comp) {
- var toolbar = parts$a.getPart(comp, detail, "toolbar");
- toolbar.each(function(toolbar2) {
- return toolbar2.getApis().refresh(toolbar2);
- });
- },
- toggleToolbarDrawer: function(comp) {
- parts$a.getPart(comp, detail, "toolbar").each(function(toolbar) {
- mapFrom(toolbar.getApis().toggle, function(toggle2) {
- return toggle2(toolbar);
- });
- });
- },
- isToolbarDrawerToggled: function(comp) {
- return parts$a.getPart(comp, detail, "toolbar").bind(function(toolbar) {
- return Optional.from(toolbar.getApis().isOpen).map(function(isOpen2) {
- return isOpen2(toolbar);
- });
- }).getOr(false);
- },
- getThrobber: function(comp) {
- return parts$a.getPart(comp, detail, "throbber");
- },
- focusToolbar: function(comp) {
- var optToolbar = parts$a.getPart(comp, detail, "toolbar").orThunk(function() {
- return parts$a.getPart(comp, detail, "multiple-toolbar");
- });
- optToolbar.each(function(toolbar) {
- Keying.focusIn(toolbar);
- });
- },
- setMenubar: function(comp, menus) {
- parts$a.getPart(comp, detail, "menubar").each(function(menubar) {
- SilverMenubar.setMenus(menubar, menus);
- });
- },
- focusMenubar: function(comp) {
- parts$a.getPart(comp, detail, "menubar").each(function(menubar) {
- SilverMenubar.focus(menubar);
- });
- }
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- apis,
- behaviours: detail.behaviours
- };
- };
- var partMenubar = partType.optional({
- factory: SilverMenubar,
- name: "menubar",
- schema: [required$1("backstage")]
- });
- var toolbarFactory = function(spec) {
- if (spec.type === ToolbarMode.sliding) {
- return renderSlidingMoreToolbar;
- } else if (spec.type === ToolbarMode.floating) {
- return renderFloatingMoreToolbar;
- } else {
- return renderToolbar;
- }
- };
- var partMultipleToolbar = partType.optional({
- factory: {
- sketch: function(spec) {
- return CustomList.sketch({
- uid: spec.uid,
- dom: spec.dom,
- listBehaviours: derive$1([Keying.config({
- mode: "acyclic",
- selector: ".tox-toolbar"
- })]),
- makeItem: function() {
- return renderToolbar({
- type: spec.type,
- uid: generate$6("multiple-toolbar-item"),
- cyclicKeying: false,
- initGroups: [],
- providers: spec.providers,
- onEscape: function() {
- spec.onEscape();
- return Optional.some(true);
- }
- });
- },
- setupItem: function(_mToolbar, tc, data, _index) {
- Toolbar.setGroups(tc, data);
- },
- shell: true
- });
- }
- },
- name: "multiple-toolbar",
- schema: [
- required$1("dom"),
- required$1("onEscape")
- ]
- });
- var partToolbar = partType.optional({
- factory: {
- sketch: function(spec) {
- var renderer = toolbarFactory(spec);
- var toolbarSpec = {
- type: spec.type,
- uid: spec.uid,
- onEscape: function() {
- spec.onEscape();
- return Optional.some(true);
- },
- cyclicKeying: false,
- initGroups: [],
- getSink: spec.getSink,
- providers: spec.providers,
- moreDrawerData: {
- lazyToolbar: spec.lazyToolbar,
- lazyMoreButton: spec.lazyMoreButton,
- lazyHeader: spec.lazyHeader
- },
- attributes: spec.attributes
- };
- return renderer(toolbarSpec);
- }
- },
- name: "toolbar",
- schema: [
- required$1("dom"),
- required$1("onEscape"),
- required$1("getSink")
- ]
- });
- var partHeader = partType.optional({
- factory: { sketch: renderHeader },
- name: "header",
- schema: [required$1("dom")]
- });
- var partSocket = partType.optional({
- name: "socket",
- schema: [required$1("dom")]
- });
- var partSidebar = partType.optional({
- factory: { sketch: renderSidebar },
- name: "sidebar",
- schema: [required$1("dom")]
- });
- var partThrobber = partType.optional({
- factory: { sketch: renderThrobber },
- name: "throbber",
- schema: [required$1("dom")]
- });
- var OuterContainer = composite({
- name: "OuterContainer",
- factory: factory$6,
- configFields: [
- required$1("dom"),
- required$1("behaviours")
- ],
- partFields: [
- partHeader,
- partMenubar,
- partToolbar,
- partMultipleToolbar,
- partSocket,
- partSidebar,
- partThrobber
- ],
- apis: {
- getSocket: function(apis, comp) {
- return apis.getSocket(comp);
- },
- setSidebar: function(apis, comp, panelConfigs) {
- apis.setSidebar(comp, panelConfigs);
- },
- toggleSidebar: function(apis, comp, name2) {
- apis.toggleSidebar(comp, name2);
- },
- whichSidebar: function(apis, comp) {
- return apis.whichSidebar(comp);
- },
- getHeader: function(apis, comp) {
- return apis.getHeader(comp);
- },
- getToolbar: function(apis, comp) {
- return apis.getToolbar(comp);
- },
- setToolbar: function(apis, comp, grps) {
- var groups = map$2(grps, function(grp) {
- return renderToolbarGroup(grp);
- });
- apis.setToolbar(comp, groups);
- },
- setToolbars: function(apis, comp, ts) {
- var renderedToolbars = map$2(ts, function(g) {
- return map$2(g, renderToolbarGroup);
- });
- apis.setToolbars(comp, renderedToolbars);
- },
- refreshToolbar: function(apis, comp) {
- return apis.refreshToolbar(comp);
- },
- toggleToolbarDrawer: function(apis, comp) {
- apis.toggleToolbarDrawer(comp);
- },
- isToolbarDrawerToggled: function(apis, comp) {
- return apis.isToolbarDrawerToggled(comp);
- },
- getThrobber: function(apis, comp) {
- return apis.getThrobber(comp);
- },
- setMenubar: function(apis, comp, menus) {
- apis.setMenubar(comp, menus);
- },
- focusMenubar: function(apis, comp) {
- apis.focusMenubar(comp);
- },
- focusToolbar: function(apis, comp) {
- apis.focusToolbar(comp);
- }
- }
- });
- var defaultMenubar = "file edit view insert format tools table help";
- var defaultMenus = {
- file: {
- title: "File",
- items: "newdocument restoredraft | preview | export print | deleteallconversations"
- },
- edit: {
- title: "Edit",
- items: "undo redo | cut copy paste pastetext | selectall | searchreplace"
- },
- view: {
- title: "View",
- items: "code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments"
- },
- insert: {
- title: "Insert",
- items: "image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime"
- },
- format: {
- title: "Format",
- items: "bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | language | removeformat"
- },
- tools: {
- title: "Tools",
- items: "spellchecker spellcheckerlanguage | a11ycheck code wordcount"
- },
- table: {
- title: "Table",
- items: "inserttable | cell row column | advtablesort | tableprops deletetable"
- },
- help: {
- title: "Help",
- items: "help"
- }
- };
- var make = function(menu2, registry, editor) {
- var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
- return {
- text: menu2.title,
- getItems: function() {
- return bind$3(menu2.items, function(i) {
- var itemName = i.toLowerCase();
- if (itemName.trim().length === 0) {
- return [];
- } else if (exists(removedMenuItems, function(removedMenuItem) {
- return removedMenuItem === itemName;
- })) {
- return [];
- } else if (itemName === "separator" || itemName === "|") {
- return [{ type: "separator" }];
- } else if (registry.menuItems[itemName]) {
- return [registry.menuItems[itemName]];
- } else {
- return [];
- }
- });
- }
- };
- };
- var parseItemsString = function(items) {
- if (typeof items === "string") {
- return items.split(" ");
- }
- return items;
- };
- var identifyMenus = function(editor, registry) {
- var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus);
- var userDefinedMenus = keys(registry.menus).length > 0;
- var menubar = registry.menubar === void 0 || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? "" : registry.menubar);
- var validMenus = filter$2(menubar, function(menuName) {
- var isDefaultMenu = has$2(defaultMenus, menuName);
- if (userDefinedMenus) {
- return isDefaultMenu || get$e(registry.menus, menuName).exists(function(menu2) {
- return has$2(menu2, "items");
- });
- } else {
- return isDefaultMenu;
- }
- });
- var menus = map$2(validMenus, function(menuName) {
- var menuData = rawMenuData[menuName];
- return make({
- title: menuData.title,
- items: parseItemsString(menuData.items)
- }, registry, editor);
- });
- return filter$2(menus, function(menu2) {
- var isNotSeparator = function(item2) {
- return item2.type !== "separator";
- };
- return menu2.getItems().length > 0 && exists(menu2.getItems(), isNotSeparator);
- });
- };
- var fireSkinLoaded = function(editor) {
- var done = function() {
- editor._skinLoaded = true;
- fireSkinLoaded$1(editor);
- };
- return function() {
- if (editor.initialized) {
- done();
- } else {
- editor.on("init", done);
- }
- };
- };
- var fireSkinLoadError = function(editor, err) {
- return function() {
- return fireSkinLoadError$1(editor, { message: err });
- };
- };
- var loadStylesheet = function(editor, stylesheetUrl, styleSheetLoader) {
- return new global$c(function(resolve, reject) {
- styleSheetLoader.load(stylesheetUrl, resolve, reject);
- editor.on("remove", function() {
- return styleSheetLoader.unload(stylesheetUrl);
- });
- });
- };
- var loadUiSkins = function(editor, skinUrl) {
- var skinUiCss = skinUrl + "/skin.min.css";
- return loadStylesheet(editor, skinUiCss, editor.ui.styleSheetLoader);
- };
- var loadShadowDomUiSkins = function(editor, skinUrl) {
- var isInShadowRoot$1 = isInShadowRoot(SugarElement.fromDom(editor.getElement()));
- if (isInShadowRoot$1) {
- var shadowDomSkinCss = skinUrl + "/skin.shadowdom.min.css";
- return loadStylesheet(editor, shadowDomSkinCss, global$b.DOM.styleSheetLoader);
- } else {
- return global$c.resolve();
- }
- };
- var loadSkin = function(isInline, editor) {
- var skinUrl = getSkinUrl(editor);
- if (skinUrl) {
- editor.contentCSS.push(skinUrl + (isInline ? "/content.inline" : "/content") + ".min.css");
- }
- if (isSkinDisabled(editor) === false && isString(skinUrl)) {
- global$c.all([
- loadUiSkins(editor, skinUrl),
- loadShadowDomUiSkins(editor, skinUrl)
- ]).then(fireSkinLoaded(editor), fireSkinLoadError(editor, "Skin could not be loaded"));
- } else {
- fireSkinLoaded(editor)();
- }
- };
- var iframe = curry(loadSkin, false);
- var inline = curry(loadSkin, true);
- var onSetupFormatToggle = function(editor, name2) {
- return function(api2) {
- var boundCallback = unbindable();
- var init2 = function() {
- api2.setActive(editor.formatter.match(name2));
- var binding = editor.formatter.formatChanged(name2, api2.setActive);
- boundCallback.set(binding);
- };
- editor.initialized ? init2() : editor.once("init", init2);
- return function() {
- editor.off("init", init2);
- boundCallback.clear();
- };
- };
- };
- var onSetupEvent = function(editor, event, f) {
- return function(api2) {
- var handleEvent = function() {
- return f(api2);
- };
- var init2 = function() {
- f(api2);
- editor.on(event, handleEvent);
- };
- editor.initialized ? init2() : editor.once("init", init2);
- return function() {
- editor.off("init", init2);
- editor.off(event, handleEvent);
- };
- };
- };
- var onActionToggleFormat$1 = function(editor) {
- return function(rawItem) {
- return function() {
- editor.undoManager.transact(function() {
- editor.focus();
- editor.execCommand("mceToggleFormat", false, rawItem.format);
- });
- };
- };
- };
- var onActionExecCommand = function(editor, command) {
- return function() {
- return editor.execCommand(command);
- };
- };
- var generateSelectItems = function(_editor, backstage, spec) {
- var generateItem = function(rawItem, response, disabled, value2) {
- var translatedText = backstage.shared.providers.translate(rawItem.title);
- if (rawItem.type === "separator") {
- return Optional.some({
- type: "separator",
- text: translatedText
- });
- } else if (rawItem.type === "submenu") {
- var items = bind$3(rawItem.getStyleItems(), function(si) {
- return validate(si, response, value2);
- });
- if (response === 0 && items.length <= 0) {
- return Optional.none();
- } else {
- return Optional.some({
- type: "nestedmenuitem",
- text: translatedText,
- disabled: items.length <= 0,
- getSubmenuItems: function() {
- return bind$3(rawItem.getStyleItems(), function(si) {
- return validate(si, response, value2);
- });
- }
- });
- }
- } else {
- return Optional.some(__assign({
- type: "togglemenuitem",
- text: translatedText,
- icon: rawItem.icon,
- active: rawItem.isSelected(value2),
- disabled,
- onAction: spec.onAction(rawItem)
- }, rawItem.getStylePreview().fold(function() {
- return {};
- }, function(preview) {
- return { meta: { style: preview } };
- })));
- }
- };
- var validate = function(item2, response, value2) {
- var invalid = item2.type === "formatter" && spec.isInvalid(item2);
- if (response === 0) {
- return invalid ? [] : generateItem(item2, response, false, value2).toArray();
- } else {
- return generateItem(item2, response, invalid, value2).toArray();
- }
- };
- var validateItems = function(preItems) {
- var value2 = spec.getCurrentValue();
- var response = spec.shouldHide ? 0 : 1;
- return bind$3(preItems, function(item2) {
- return validate(item2, response, value2);
- });
- };
- var getFetch2 = function(backstage2, getStyleItems) {
- return function(comp, callback) {
- var preItems = getStyleItems();
- var items = validateItems(preItems);
- var menu2 = build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage2, false);
- callback(menu2);
- };
- };
- return {
- validateItems,
- getFetch: getFetch2
- };
- };
- var createMenuItems = function(editor, backstage, spec) {
- var dataset2 = spec.dataset;
- var getStyleItems = dataset2.type === "basic" ? function() {
- return map$2(dataset2.data, function(d) {
- return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
- });
- } : dataset2.getData;
- return {
- items: generateSelectItems(editor, backstage, spec),
- getStyleItems
- };
- };
- var createSelectButton = function(editor, backstage, spec) {
- var _a2 = createMenuItems(editor, backstage, spec), items = _a2.items, getStyleItems = _a2.getStyleItems;
- var getApi2 = function(comp) {
- return { getComponent: constant$1(comp) };
- };
- var onSetup = onSetupEvent(editor, "NodeChange", function(api2) {
- var comp = api2.getComponent();
- spec.updateText(comp);
- });
- return renderCommonDropdown({
- text: spec.icon.isSome() ? Optional.none() : spec.text,
- icon: spec.icon,
- tooltip: Optional.from(spec.tooltip),
- role: Optional.none(),
- fetch: items.getFetch(backstage, getStyleItems),
- onSetup,
- getApi: getApi2,
- columns: 1,
- presets: "normal",
- classes: spec.icon.isSome() ? [] : ["bespoke"],
- dropdownBehaviours: []
- }, "tox-tbtn", backstage.shared);
- };
- var process = function(rawFormats) {
- return map$2(rawFormats, function(item2) {
- var title = item2, format = item2;
- var values2 = item2.split("=");
- if (values2.length > 1) {
- title = values2[0];
- format = values2[1];
- }
- return {
- title,
- format
- };
- });
- };
- var buildBasicStaticDataset = function(data) {
- return {
- type: "basic",
- data
- };
- };
- var Delimiter;
- (function(Delimiter2) {
- Delimiter2[Delimiter2["SemiColon"] = 0] = "SemiColon";
- Delimiter2[Delimiter2["Space"] = 1] = "Space";
- })(Delimiter || (Delimiter = {}));
- var split = function(rawFormats, delimiter) {
- if (delimiter === Delimiter.SemiColon) {
- return rawFormats.replace(/;$/, "").split(";");
- } else {
- return rawFormats.split(" ");
- }
- };
- var buildBasicSettingsDataset = function(editor, settingName, defaults, delimiter) {
- var rawFormats = editor.getParam(settingName, defaults, "string");
- var data = process(split(rawFormats, delimiter));
- return {
- type: "basic",
- data
- };
- };
- var alignMenuItems = [
- {
- title: "Left",
- icon: "align-left",
- format: "alignleft",
- command: "JustifyLeft"
- },
- {
- title: "Center",
- icon: "align-center",
- format: "aligncenter",
- command: "JustifyCenter"
- },
- {
- title: "Right",
- icon: "align-right",
- format: "alignright",
- command: "JustifyRight"
- },
- {
- title: "Justify",
- icon: "align-justify",
- format: "alignjustify",
- command: "JustifyFull"
- }
- ];
- var getSpec$4 = function(editor) {
- var getMatchingValue = function() {
- return find$5(alignMenuItems, function(item2) {
- return editor.formatter.match(item2.format);
- });
- };
- var isSelectedFor = function(format) {
- return function() {
- return editor.formatter.match(format);
- };
- };
- var getPreviewFor = function(_format) {
- return Optional.none;
- };
- var updateSelectMenuIcon = function(comp) {
- var match = getMatchingValue();
- var alignment = match.fold(constant$1("left"), function(item2) {
- return item2.title.toLowerCase();
- });
- emitWith(comp, updateMenuIcon, { icon: "align-" + alignment });
- };
- var dataset2 = buildBasicStaticDataset(alignMenuItems);
- var onAction = function(rawItem) {
- return function() {
- return find$5(alignMenuItems, function(item2) {
- return item2.format === rawItem.format;
- }).each(function(item2) {
- return editor.execCommand(item2.command);
- });
- };
- };
- return {
- tooltip: "Align",
- text: Optional.none(),
- icon: Optional.some("align-left"),
- isSelectedFor,
- getCurrentValue: Optional.none,
- getPreviewFor,
- onAction,
- updateText: updateSelectMenuIcon,
- dataset: dataset2,
- shouldHide: false,
- isInvalid: function(item2) {
- return !editor.formatter.canApply(item2.format);
- }
- };
- };
- var createAlignSelect = function(editor, backstage) {
- return createSelectButton(editor, backstage, getSpec$4(editor));
- };
- var alignSelectMenu = function(editor, backstage) {
- var menuItems = createMenuItems(editor, backstage, getSpec$4(editor));
- editor.ui.registry.addNestedMenuItem("align", {
- text: backstage.shared.providers.translate("Align"),
- getSubmenuItems: function() {
- return menuItems.items.validateItems(menuItems.getStyleItems());
- }
- });
- };
- var defaultFontsFormats = "Andale Mono=andale mono,monospace;Arial=arial,helvetica,sans-serif;Arial Black=arial black,sans-serif;Book Antiqua=book antiqua,palatino,serif;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,palatino,serif;Helvetica=helvetica,arial,sans-serif;Impact=impact,sans-serif;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco,monospace;Times New Roman=times new roman,times,serif;Trebuchet MS=trebuchet ms,geneva,sans-serif;Verdana=verdana,geneva,sans-serif;Webdings=webdings;Wingdings=wingdings,zapf dingbats";
- var systemStackFonts = [
- "-apple-system",
- "Segoe UI",
- "Roboto",
- "Helvetica Neue",
- "sans-serif"
- ];
- var splitFonts = function(fontFamily) {
- var fonts = fontFamily.split(/\s*,\s*/);
- return map$2(fonts, function(font) {
- return font.replace(/^['"]+|['"]+$/g, "");
- });
- };
- var isSystemFontStack = function(fontFamily) {
- var matchesSystemStack = function() {
- var fonts = splitFonts(fontFamily.toLowerCase());
- return forall(systemStackFonts, function(font) {
- return fonts.indexOf(font.toLowerCase()) > -1;
- });
- };
- return fontFamily.indexOf("-apple-system") === 0 && matchesSystemStack();
- };
- var getSpec$3 = function(editor) {
- var systemFont = "System Font";
- var getMatchingValue = function() {
- var getFirstFont = function(fontFamily2) {
- return fontFamily2 ? splitFonts(fontFamily2)[0] : "";
- };
- var fontFamily = editor.queryCommandValue("FontName");
- var items = dataset2.data;
- var font = fontFamily ? fontFamily.toLowerCase() : "";
- var matchOpt = find$5(items, function(item2) {
- var format = item2.format;
- return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
- }).orThunk(function() {
- return someIf(isSystemFontStack(font), {
- title: systemFont,
- format: font
- });
- });
- return {
- matchOpt,
- font: fontFamily
- };
- };
- var isSelectedFor = function(item2) {
- return function(valueOpt) {
- return valueOpt.exists(function(value2) {
- return value2.format === item2;
- });
- };
- };
- var getCurrentValue = function() {
- var matchOpt = getMatchingValue().matchOpt;
- return matchOpt;
- };
- var getPreviewFor = function(item2) {
- return function() {
- return Optional.some({
- tag: "div",
- styles: item2.indexOf("dings") === -1 ? { "font-family": item2 } : {}
- });
- };
- };
- var onAction = function(rawItem) {
- return function() {
- editor.undoManager.transact(function() {
- editor.focus();
- editor.execCommand("FontName", false, rawItem.format);
- });
- };
- };
- var updateSelectMenuText = function(comp) {
- var _a2 = getMatchingValue(), matchOpt = _a2.matchOpt, font = _a2.font;
- var text2 = matchOpt.fold(constant$1(font), function(item2) {
- return item2.title;
- });
- emitWith(comp, updateMenuText, { text: text2 });
- };
- var dataset2 = buildBasicSettingsDataset(editor, "font_formats", defaultFontsFormats, Delimiter.SemiColon);
- return {
- tooltip: "Fonts",
- text: Optional.some(systemFont),
- icon: Optional.none(),
- isSelectedFor,
- getCurrentValue,
- getPreviewFor,
- onAction,
- updateText: updateSelectMenuText,
- dataset: dataset2,
- shouldHide: false,
- isInvalid: never
- };
- };
- var createFontSelect = function(editor, backstage) {
- return createSelectButton(editor, backstage, getSpec$3(editor));
- };
- var fontSelectMenu = function(editor, backstage) {
- var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
- editor.ui.registry.addNestedMenuItem("fontformats", {
- text: backstage.shared.providers.translate("Fonts"),
- getSubmenuItems: function() {
- return menuItems.items.validateItems(menuItems.getStyleItems());
- }
- });
- };
- var defaultFontsizeFormats = "8pt 10pt 12pt 14pt 18pt 24pt 36pt";
- var legacyFontSizes = {
- "8pt": "1",
- "10pt": "2",
- "12pt": "3",
- "14pt": "4",
- "18pt": "5",
- "24pt": "6",
- "36pt": "7"
- };
- var keywordFontSizes = {
- "xx-small": "7pt",
- "x-small": "8pt",
- "small": "10pt",
- "medium": "12pt",
- "large": "14pt",
- "x-large": "18pt",
- "xx-large": "24pt"
- };
- var round = function(number2, precision) {
- var factor = Math.pow(10, precision);
- return Math.round(number2 * factor) / factor;
- };
- var toPt = function(fontSize, precision) {
- if (/[0-9.]+px$/.test(fontSize)) {
- return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + "pt";
- } else {
- return get$e(keywordFontSizes, fontSize).getOr(fontSize);
- }
- };
- var toLegacy = function(fontSize) {
- return get$e(legacyFontSizes, fontSize).getOr("");
- };
- var getSpec$2 = function(editor) {
- var getMatchingValue = function() {
- var matchOpt = Optional.none();
- var items = dataset2.data;
- var fontSize = editor.queryCommandValue("FontSize");
- if (fontSize) {
- var _loop_1 = function(precision2) {
- var pt = toPt(fontSize, precision2);
- var legacy = toLegacy(pt);
- matchOpt = find$5(items, function(item2) {
- return item2.format === fontSize || item2.format === pt || item2.format === legacy;
- });
- };
- for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
- _loop_1(precision);
- }
- }
- return {
- matchOpt,
- size: fontSize
- };
- };
- var isSelectedFor = function(item2) {
- return function(valueOpt) {
- return valueOpt.exists(function(value2) {
- return value2.format === item2;
- });
- };
- };
- var getCurrentValue = function() {
- var matchOpt = getMatchingValue().matchOpt;
- return matchOpt;
- };
- var getPreviewFor = constant$1(Optional.none);
- var onAction = function(rawItem) {
- return function() {
- editor.undoManager.transact(function() {
- editor.focus();
- editor.execCommand("FontSize", false, rawItem.format);
- });
- };
- };
- var updateSelectMenuText = function(comp) {
- var _a2 = getMatchingValue(), matchOpt = _a2.matchOpt, size = _a2.size;
- var text2 = matchOpt.fold(constant$1(size), function(match) {
- return match.title;
- });
- emitWith(comp, updateMenuText, { text: text2 });
- };
- var dataset2 = buildBasicSettingsDataset(editor, "fontsize_formats", defaultFontsizeFormats, Delimiter.Space);
- return {
- tooltip: "Font sizes",
- text: Optional.some("12pt"),
- icon: Optional.none(),
- isSelectedFor,
- getPreviewFor,
- getCurrentValue,
- onAction,
- updateText: updateSelectMenuText,
- dataset: dataset2,
- shouldHide: false,
- isInvalid: never
- };
- };
- var createFontsizeSelect = function(editor, backstage) {
- return createSelectButton(editor, backstage, getSpec$2(editor));
- };
- var fontsizeSelectMenu = function(editor, backstage) {
- var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
- editor.ui.registry.addNestedMenuItem("fontsizes", {
- text: "Font sizes",
- getSubmenuItems: function() {
- return menuItems.items.validateItems(menuItems.getStyleItems());
- }
- });
- };
- var findNearest = function(editor, getStyles) {
- var styles = getStyles();
- var formats = map$2(styles, function(style) {
- return style.format;
- });
- return Optional.from(editor.formatter.closest(formats)).bind(function(fmt) {
- return find$5(styles, function(data) {
- return data.format === fmt;
- });
- }).orThunk(function() {
- return someIf(editor.formatter.match("p"), {
- title: "Paragraph",
- format: "p"
- });
- });
- };
- var defaultBlocks = "Paragraph=p;Heading 1=h1;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Preformatted=pre";
- var getSpec$1 = function(editor) {
- var fallbackFormat = "Paragraph";
- var isSelectedFor = function(format) {
- return function() {
- return editor.formatter.match(format);
- };
- };
- var getPreviewFor = function(format) {
- return function() {
- var fmt = editor.formatter.get(format);
- return Optional.some({
- tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || "div" : "div",
- styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
- });
- };
- };
- var updateSelectMenuText = function(comp) {
- var detectedFormat = findNearest(editor, function() {
- return dataset2.data;
- });
- var text2 = detectedFormat.fold(constant$1(fallbackFormat), function(fmt) {
- return fmt.title;
- });
- emitWith(comp, updateMenuText, { text: text2 });
- };
- var dataset2 = buildBasicSettingsDataset(editor, "block_formats", defaultBlocks, Delimiter.SemiColon);
- return {
- tooltip: "Blocks",
- text: Optional.some(fallbackFormat),
- icon: Optional.none(),
- isSelectedFor,
- getCurrentValue: Optional.none,
- getPreviewFor,
- onAction: onActionToggleFormat$1(editor),
- updateText: updateSelectMenuText,
- dataset: dataset2,
- shouldHide: false,
- isInvalid: function(item2) {
- return !editor.formatter.canApply(item2.format);
- }
- };
- };
- var createFormatSelect = function(editor, backstage) {
- return createSelectButton(editor, backstage, getSpec$1(editor));
- };
- var formatSelectMenu = function(editor, backstage) {
- var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
- editor.ui.registry.addNestedMenuItem("blockformats", {
- text: "Blocks",
- getSubmenuItems: function() {
- return menuItems.items.validateItems(menuItems.getStyleItems());
- }
- });
- };
- var getSpec = function(editor, dataset2) {
- var fallbackFormat = "Paragraph";
- var isSelectedFor = function(format) {
- return function() {
- return editor.formatter.match(format);
- };
- };
- var getPreviewFor = function(format) {
- return function() {
- var fmt = editor.formatter.get(format);
- return fmt !== void 0 ? Optional.some({
- tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || "div" : "div",
- styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
- }) : Optional.none();
- };
- };
- var updateSelectMenuText = function(comp) {
- var getFormatItems = function(fmt) {
- var subs2 = fmt.items;
- return subs2 !== void 0 && subs2.length > 0 ? bind$3(subs2, getFormatItems) : [{
- title: fmt.title,
- format: fmt.format
- }];
- };
- var flattenedItems = bind$3(getStyleFormats(editor), getFormatItems);
- var detectedFormat = findNearest(editor, constant$1(flattenedItems));
- var text2 = detectedFormat.fold(constant$1(fallbackFormat), function(fmt) {
- return fmt.title;
- });
- emitWith(comp, updateMenuText, { text: text2 });
- };
- return {
- tooltip: "Formats",
- text: Optional.some(fallbackFormat),
- icon: Optional.none(),
- isSelectedFor,
- getCurrentValue: Optional.none,
- getPreviewFor,
- onAction: onActionToggleFormat$1(editor),
- updateText: updateSelectMenuText,
- shouldHide: editor.getParam("style_formats_autohide", false, "boolean"),
- isInvalid: function(item2) {
- return !editor.formatter.canApply(item2.format);
- },
- dataset: dataset2
- };
- };
- var createStyleSelect = function(editor, backstage) {
- var dataset2 = __assign({ type: "advanced" }, backstage.styleselect);
- return createSelectButton(editor, backstage, getSpec(editor, dataset2));
- };
- var styleSelectMenu = function(editor, backstage) {
- var dataset2 = __assign({ type: "advanced" }, backstage.styleselect);
- var menuItems = createMenuItems(editor, backstage, getSpec(editor, dataset2));
- editor.ui.registry.addNestedMenuItem("formats", {
- text: "Formats",
- getSubmenuItems: function() {
- return menuItems.items.validateItems(menuItems.getStyleItems());
- }
- });
- };
- var events$3 = function(reflectingConfig, reflectingState) {
- var update = function(component, data) {
- reflectingConfig.updateState.each(function(updateState) {
- var newState = updateState(component, data);
- reflectingState.set(newState);
- });
- reflectingConfig.renderComponents.each(function(renderComponents2) {
- var newComponents = renderComponents2(data, reflectingState.get());
- var newChildren = map$2(newComponents, component.getSystem().build);
- replaceChildren(component, newChildren);
- });
- };
- return derive$2([
- run$1(receive(), function(component, message) {
- var receivingData = message;
- if (!receivingData.universal) {
- var channel = reflectingConfig.channel;
- if (contains$2(receivingData.channels, channel)) {
- update(component, receivingData.data);
- }
- }
- }),
- runOnAttached(function(comp, _se) {
- reflectingConfig.initialData.each(function(rawData) {
- update(comp, rawData);
- });
- })
- ]);
- };
- var ActiveReflecting = Object.freeze({
- __proto__: null,
- events: events$3
- });
- var getState = function(component, replaceConfig, reflectState) {
- return reflectState;
- };
- var ReflectingApis = Object.freeze({
- __proto__: null,
- getState
- });
- var ReflectingSchema = [
- required$1("channel"),
- option("renderComponents"),
- option("updateState"),
- option("initialData")
- ];
- var init$3 = function() {
- var cell = Cell(Optional.none());
- var clear2 = function() {
- return cell.set(Optional.none());
- };
- var readState = function() {
- return cell.get().getOr("none");
- };
- return {
- readState,
- get: cell.get,
- set: cell.set,
- clear: clear2
- };
- };
- var ReflectingState = Object.freeze({
- __proto__: null,
- init: init$3
- });
- var Reflecting = create$8({
- fields: ReflectingSchema,
- name: "reflecting",
- active: ActiveReflecting,
- apis: ReflectingApis,
- state: ReflectingState
- });
- var schema$7 = constant$1([
- required$1("toggleClass"),
- required$1("fetch"),
- onStrictHandler("onExecute"),
- defaulted("getHotspot", Optional.some),
- defaulted("getAnchorOverrides", constant$1({})),
- schema$y(),
- onStrictHandler("onItemExecute"),
- option("lazySink"),
- required$1("dom"),
- onHandler("onOpen"),
- field("splitDropdownBehaviours", [
- Coupling,
- Keying,
- Focusing
- ]),
- defaulted("matchWidth", false),
- defaulted("useMinWidth", false),
- defaulted("eventOrder", {}),
- option("role")
- ].concat(sandboxFields()));
- var arrowPart = required({
- factory: Button,
- schema: [required$1("dom")],
- name: "arrow",
- defaults: function() {
- return { buttonBehaviours: derive$1([Focusing.revoke()]) };
- },
- overrides: function(detail) {
- return {
- dom: {
- tag: "span",
- attributes: { role: "presentation" }
- },
- action: function(arrow) {
- arrow.getSystem().getByUid(detail.uid).each(emitExecute);
- },
- buttonBehaviours: derive$1([Toggling.config({
- toggleOnExecute: false,
- toggleClass: detail.toggleClass
- })])
- };
- }
- });
- var buttonPart = required({
- factory: Button,
- schema: [required$1("dom")],
- name: "button",
- defaults: function() {
- return { buttonBehaviours: derive$1([Focusing.revoke()]) };
- },
- overrides: function(detail) {
- return {
- dom: {
- tag: "span",
- attributes: { role: "presentation" }
- },
- action: function(btn) {
- btn.getSystem().getByUid(detail.uid).each(function(splitDropdown) {
- detail.onExecute(splitDropdown, btn);
- });
- }
- };
- }
- });
- var parts$3 = constant$1([
- arrowPart,
- buttonPart,
- optional({
- factory: {
- sketch: function(spec) {
- return {
- uid: spec.uid,
- dom: {
- tag: "span",
- styles: { display: "none" },
- attributes: { "aria-hidden": "true" },
- innerHtml: spec.text
- }
- };
- }
- },
- schema: [required$1("text")],
- name: "aria-descriptor"
- }),
- external$1({
- schema: [tieredMenuMarkers()],
- name: "menu",
- defaults: function(detail) {
- return {
- onExecute: function(tmenu, item2) {
- tmenu.getSystem().getByUid(detail.uid).each(function(splitDropdown) {
- detail.onItemExecute(splitDropdown, tmenu, item2);
- });
- }
- };
- }
- }),
- partType$1()
- ]);
- var factory$5 = function(detail, components2, spec, externals) {
- var _a2;
- var switchToMenu = function(sandbox) {
- Composing.getCurrent(sandbox).each(function(current) {
- Highlighting.highlightFirst(current);
- Keying.focusIn(current);
- });
- };
- var action = function(component) {
- var onOpenSync = switchToMenu;
- togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
- };
- var openMenu = function(comp) {
- action(comp);
- return Optional.some(true);
- };
- var executeOnButton = function(comp) {
- var button2 = getPartOrDie(comp, detail, "button");
- emitExecute(button2);
- return Optional.some(true);
- };
- var buttonEvents = __assign(__assign({}, derive$2([runOnAttached(function(component, _simulatedEvent) {
- var ariaDescriptor = getPart(component, detail, "aria-descriptor");
- ariaDescriptor.each(function(descriptor) {
- var descriptorId = generate$6("aria");
- set$8(descriptor.element, "id", descriptorId);
- set$8(component.element, "aria-describedby", descriptorId);
- });
- })])), events$a(Optional.some(action)));
- var apis = {
- repositionMenus: function(comp) {
- if (Toggling.isOn(comp)) {
- repositionMenus(comp);
- }
- }
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- apis,
- eventOrder: __assign(__assign({}, detail.eventOrder), (_a2 = {}, _a2[execute$5()] = [
- "disabling",
- "toggling",
- "alloy.base.behaviour"
- ], _a2)),
- events: buttonEvents,
- behaviours: augment(detail.splitDropdownBehaviours, [
- Coupling.config({
- others: {
- sandbox: function(hotspot) {
- var arrow = getPartOrDie(hotspot, detail, "arrow");
- var extras = {
- onOpen: function() {
- Toggling.on(arrow);
- Toggling.on(hotspot);
- },
- onClose: function() {
- Toggling.off(arrow);
- Toggling.off(hotspot);
- }
- };
- return makeSandbox$1(detail, hotspot, extras);
- }
- }
- }),
- Keying.config({
- mode: "special",
- onSpace: executeOnButton,
- onEnter: executeOnButton,
- onDown: openMenu
- }),
- Focusing.config({}),
- Toggling.config({
- toggleOnExecute: false,
- aria: { mode: "expanded" }
- })
- ]),
- domModification: {
- attributes: {
- "role": detail.role.getOr("button"),
- "aria-haspopup": true
- }
- }
- };
- };
- var SplitDropdown = composite({
- name: "SplitDropdown",
- configFields: schema$7(),
- partFields: parts$3(),
- factory: factory$5,
- apis: {
- repositionMenus: function(apis, comp) {
- return apis.repositionMenus(comp);
- }
- }
- });
- var getButtonApi = function(component) {
- return {
- isDisabled: function() {
- return Disabling.isDisabled(component);
- },
- setDisabled: function(state) {
- return Disabling.set(component, state);
- }
- };
- };
- var getToggleApi = function(component) {
- return {
- setActive: function(state) {
- Toggling.set(component, state);
- },
- isActive: function() {
- return Toggling.isOn(component);
- },
- isDisabled: function() {
- return Disabling.isDisabled(component);
- },
- setDisabled: function(state) {
- return Disabling.set(component, state);
- }
- };
- };
- var getTooltipAttributes = function(tooltip, providersBackstage) {
- return tooltip.map(function(tooltip2) {
- return {
- "aria-label": providersBackstage.translate(tooltip2),
- "title": providersBackstage.translate(tooltip2)
- };
- }).getOr({});
- };
- var focusButtonEvent = generate$6("focus-button");
- var renderCommonStructure = function(icon, text2, tooltip, receiver, behaviours2, providersBackstage) {
- var _d;
- return {
- dom: {
- tag: "button",
- classes: ["tox-tbtn"].concat(text2.isSome() ? ["tox-tbtn--select"] : []),
- attributes: getTooltipAttributes(tooltip, providersBackstage)
- },
- components: componentRenderPipeline([
- icon.map(function(iconName) {
- return renderIconFromPack(iconName, providersBackstage.icons);
- }),
- text2.map(function(text3) {
- return renderLabel$1(text3, "tox-tbtn", providersBackstage);
- })
- ]),
- eventOrder: (_d = {}, _d[mousedown()] = [
- "focusing",
- "alloy.base.behaviour",
- "common-button-display-events"
- ], _d),
- buttonBehaviours: derive$1([
- DisablingConfigs.toolbarButton(providersBackstage.isDisabled),
- receivingConfig(),
- config("common-button-display-events", [run$1(mousedown(), function(button2, se) {
- se.event.prevent();
- emit(button2, focusButtonEvent);
- })])
- ].concat(receiver.map(function(r2) {
- return Reflecting.config({
- channel: r2,
- initialData: {
- icon,
- text: text2
- },
- renderComponents: function(data, _state) {
- return componentRenderPipeline([
- data.icon.map(function(iconName) {
- return renderIconFromPack(iconName, providersBackstage.icons);
- }),
- data.text.map(function(text3) {
- return renderLabel$1(text3, "tox-tbtn", providersBackstage);
- })
- ]);
- }
- });
- }).toArray()).concat(behaviours2.getOr([])))
- };
- };
- var renderFloatingToolbarButton = function(spec, backstage, identifyButtons2, attributes) {
- var sharedBackstage = backstage.shared;
- return FloatingToolbarButton.sketch({
- lazySink: sharedBackstage.getSink,
- fetch: function() {
- return Future.nu(function(resolve) {
- resolve(map$2(identifyButtons2(spec.items), renderToolbarGroup));
- });
- },
- markers: { toggledClass: "tox-tbtn--enabled" },
- parts: {
- button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers),
- toolbar: {
- dom: {
- tag: "div",
- classes: ["tox-toolbar__overflow"],
- attributes
- }
- }
- }
- });
- };
- var renderCommonToolbarButton = function(spec, specialisation, providersBackstage) {
- var editorOffCell = Cell(noop);
- var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage);
- return Button.sketch({
- dom: structure.dom,
- components: structure.components,
- eventOrder: toolbarButtonEventOrder,
- buttonBehaviours: derive$1([
- config("toolbar-button-events", [
- onToolbarButtonExecute({
- onAction: spec.onAction,
- getApi: specialisation.getApi
- }),
- onControlAttached(specialisation, editorOffCell),
- onControlDetached(specialisation, editorOffCell)
- ]),
- DisablingConfigs.toolbarButton(function() {
- return spec.disabled || providersBackstage.isDisabled();
- }),
- receivingConfig()
- ].concat(specialisation.toolbarButtonBehaviours))
- });
- };
- var renderToolbarButton = function(spec, providersBackstage) {
- return renderToolbarButtonWith(spec, providersBackstage, []);
- };
- var renderToolbarButtonWith = function(spec, providersBackstage, bonusEvents) {
- return renderCommonToolbarButton(spec, {
- toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config("toolbarButtonWith", bonusEvents)] : []),
- getApi: getButtonApi,
- onSetup: spec.onSetup
- }, providersBackstage);
- };
- var renderToolbarToggleButton = function(spec, providersBackstage) {
- return renderToolbarToggleButtonWith(spec, providersBackstage, []);
- };
- var renderToolbarToggleButtonWith = function(spec, providersBackstage, bonusEvents) {
- return deepMerge(renderCommonToolbarButton(spec, {
- toolbarButtonBehaviours: [
- Replacing.config({}),
- Toggling.config({
- toggleClass: "tox-tbtn--enabled",
- aria: { mode: "pressed" },
- toggleOnExecute: false
- })
- ].concat(bonusEvents.length > 0 ? [config("toolbarToggleButtonWith", bonusEvents)] : []),
- getApi: getToggleApi,
- onSetup: spec.onSetup
- }, providersBackstage));
- };
- var fetchChoices = function(getApi2, spec, providersBackstage) {
- return function(comp) {
- return Future.nu(function(callback) {
- return spec.fetch(callback);
- }).map(function(items) {
- return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6("menu-value"), items, function(value2) {
- spec.onItemAction(getApi2(comp), value2);
- }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(never), providersBackstage), {
- movement: deriveMenuMovement(spec.columns, spec.presets),
- menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== "auto" ? [] : [runOnAttached(function(comp2, _se) {
- detectSize(comp2, 4, classForPreset(spec.presets)).each(function(_d) {
- var numRows = _d.numRows, numColumns = _d.numColumns;
- Keying.setGridSize(comp2, numRows, numColumns);
- });
- })])
- })));
- });
- };
- };
- var renderSplitButton = function(spec, sharedBackstage) {
- var _d;
- var displayChannel = generate$6("channel-update-split-dropdown-display");
- var getApi2 = function(comp) {
- return {
- isDisabled: function() {
- return Disabling.isDisabled(comp);
- },
- setDisabled: function(state) {
- return Disabling.set(comp, state);
- },
- setIconFill: function(id, value2) {
- descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function(underlinePath) {
- set$8(underlinePath, "fill", value2);
- });
- },
- setIconStroke: function(id, value2) {
- descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function(underlinePath) {
- set$8(underlinePath, "stroke", value2);
- });
- },
- setActive: function(state) {
- set$8(comp.element, "aria-pressed", state);
- descendant(comp.element, "span").each(function(button2) {
- comp.getSystem().getByDom(button2).each(function(buttonComp) {
- return Toggling.set(buttonComp, state);
- });
- });
- },
- isActive: function() {
- return descendant(comp.element, "span").exists(function(button2) {
- return comp.getSystem().getByDom(button2).exists(Toggling.isOn);
- });
- }
- };
- };
- var editorOffCell = Cell(noop);
- var specialisation = {
- getApi: getApi2,
- onSetup: spec.onSetup
- };
- return SplitDropdown.sketch({
- dom: {
- tag: "div",
- classes: ["tox-split-button"],
- attributes: __assign({ "aria-pressed": false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
- },
- onExecute: function(button2) {
- spec.onAction(getApi2(button2));
- },
- onItemExecute: function(_a2, _b, _c) {
- },
- splitDropdownBehaviours: derive$1([
- DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
- receivingConfig(),
- config("split-dropdown-events", [
- run$1(focusButtonEvent, Focusing.focus),
- onControlAttached(specialisation, editorOffCell),
- onControlDetached(specialisation, editorOffCell)
- ]),
- Unselecting.config({})
- ]),
- eventOrder: (_d = {}, _d[attachedToDom()] = [
- "alloy.base.behaviour",
- "split-dropdown-events"
- ], _d),
- toggleClass: "tox-tbtn--enabled",
- lazySink: sharedBackstage.getSink,
- fetch: fetchChoices(getApi2, spec, sharedBackstage.providers),
- parts: { menu: part(false, spec.columns, spec.presets) },
- components: [
- SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({
- toggleClass: "tox-tbtn--enabled",
- toggleOnExecute: false
- })]), sharedBackstage.providers)),
- SplitDropdown.parts.arrow({
- dom: {
- tag: "button",
- classes: [
- "tox-tbtn",
- "tox-split-button__chevron"
- ],
- innerHtml: get$1("chevron-down", sharedBackstage.providers.icons)
- },
- buttonBehaviours: derive$1([
- DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
- receivingConfig(),
- addFocusableBehaviour()
- ])
- }),
- SplitDropdown.parts["aria-descriptor"]({ text: sharedBackstage.providers.translate("To open the popup, press Shift+Enter") })
- ]
- });
- };
- var defaultToolbar = [
- {
- name: "history",
- items: [
- "undo",
- "redo"
- ]
- },
- {
- name: "styles",
- items: ["styleselect"]
- },
- {
- name: "formatting",
- items: [
- "bold",
- "italic"
- ]
- },
- {
- name: "alignment",
- items: [
- "alignleft",
- "aligncenter",
- "alignright",
- "alignjustify"
- ]
- },
- {
- name: "indentation",
- items: [
- "outdent",
- "indent"
- ]
- },
- {
- name: "permanent pen",
- items: ["permanentpen"]
- },
- {
- name: "comments",
- items: ["addcomment"]
- }
- ];
- var renderFromBridge = function(bridgeBuilder, render2) {
- return function(spec, extras, editor) {
- var internal2 = bridgeBuilder(spec).mapError(function(errInfo) {
- return formatError(errInfo);
- }).getOrDie();
- return render2(internal2, extras, editor);
- };
- };
- var types = {
- button: renderFromBridge(createToolbarButton, function(s, extras) {
- return renderToolbarButton(s, extras.backstage.shared.providers);
- }),
- togglebutton: renderFromBridge(createToggleButton, function(s, extras) {
- return renderToolbarToggleButton(s, extras.backstage.shared.providers);
- }),
- menubutton: renderFromBridge(createMenuButton, function(s, extras) {
- return renderMenuButton(s, "tox-tbtn", extras.backstage, Optional.none());
- }),
- splitbutton: renderFromBridge(createSplitButton, function(s, extras) {
- return renderSplitButton(s, extras.backstage.shared);
- }),
- grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function(s, extras, editor) {
- var _a2;
- var buttons = editor.ui.registry.getAll().buttons;
- var identify = function(toolbar) {
- return identifyButtons(editor, {
- buttons,
- toolbar,
- allowToolbarGroups: false
- }, extras, Optional.none());
- };
- var attributes = (_a2 = {}, _a2[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a2);
- switch (getToolbarMode(editor)) {
- case ToolbarMode.floating:
- return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
- default:
- throw new Error("Toolbar groups are only supported when using floating toolbar mode");
- }
- }),
- styleSelectButton: function(editor, extras) {
- return createStyleSelect(editor, extras.backstage);
- },
- fontsizeSelectButton: function(editor, extras) {
- return createFontsizeSelect(editor, extras.backstage);
- },
- fontSelectButton: function(editor, extras) {
- return createFontSelect(editor, extras.backstage);
- },
- formatButton: function(editor, extras) {
- return createFormatSelect(editor, extras.backstage);
- },
- alignMenuButton: function(editor, extras) {
- return createAlignSelect(editor, extras.backstage);
- }
- };
- var extractFrom = function(spec, extras, editor) {
- return get$e(types, spec.type).fold(function() {
- console.error("skipping button defined by", spec);
- return Optional.none();
- }, function(render2) {
- return Optional.some(render2(spec, extras, editor));
- });
- };
- var bespokeButtons = {
- styleselect: types.styleSelectButton,
- fontsizeselect: types.fontsizeSelectButton,
- fontselect: types.fontSelectButton,
- formatselect: types.formatButton,
- align: types.alignMenuButton
- };
- var removeUnusedDefaults = function(buttons) {
- var filteredItemGroups = map$2(defaultToolbar, function(group2) {
- var items = filter$2(group2.items, function(subItem) {
- return has$2(buttons, subItem) || has$2(bespokeButtons, subItem);
- });
- return {
- name: group2.name,
- items
- };
- });
- return filter$2(filteredItemGroups, function(group2) {
- return group2.items.length > 0;
- });
- };
- var convertStringToolbar = function(strToolbar) {
- var groupsStrings = strToolbar.split("|");
- return map$2(groupsStrings, function(g) {
- return { items: g.trim().split(" ") };
- });
- };
- var isToolbarGroupSettingArray = function(toolbar) {
- return isArrayOf(toolbar, function(t2) {
- return has$2(t2, "name") && has$2(t2, "items");
- });
- };
- var createToolbar = function(toolbarConfig) {
- var toolbar = toolbarConfig.toolbar;
- var buttons = toolbarConfig.buttons;
- if (toolbar === false) {
- return [];
- } else if (toolbar === void 0 || toolbar === true) {
- return removeUnusedDefaults(buttons);
- } else if (isString(toolbar)) {
- return convertStringToolbar(toolbar);
- } else if (isToolbarGroupSettingArray(toolbar)) {
- return toolbar;
- } else {
- console.error("Toolbar type should be string, string[], boolean or ToolbarGroup[]");
- return [];
- }
- };
- var lookupButton = function(editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
- return get$e(buttons, toolbarItem.toLowerCase()).orThunk(function() {
- return prefixes.bind(function(ps) {
- return findMap(ps, function(prefix2) {
- return get$e(buttons, prefix2 + toolbarItem.toLowerCase());
- });
- });
- }).fold(function() {
- return get$e(bespokeButtons, toolbarItem.toLowerCase()).map(function(r2) {
- return r2(editor, extras);
- }).orThunk(function() {
- return Optional.none();
- });
- }, function(spec) {
- if (spec.type === "grouptoolbarbutton" && !allowToolbarGroups) {
- console.warn("Ignoring the '" + toolbarItem + "' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.");
- return Optional.none();
- } else {
- return extractFrom(spec, extras, editor);
- }
- });
- };
- var identifyButtons = function(editor, toolbarConfig, extras, prefixes) {
- var toolbarGroups = createToolbar(toolbarConfig);
- var groups = map$2(toolbarGroups, function(group2) {
- var items = bind$3(group2.items, function(toolbarItem) {
- return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
- });
- return {
- title: Optional.from(editor.translate(group2.name)),
- items
- };
- });
- return filter$2(groups, function(group2) {
- return group2.items.length > 0;
- });
- };
- var setToolbar = function(editor, uiComponents, rawUiConfig, backstage) {
- var comp = uiComponents.outerContainer;
- var toolbarConfig = rawUiConfig.toolbar;
- var toolbarButtonsConfig = rawUiConfig.buttons;
- if (isArrayOf(toolbarConfig, isString)) {
- var toolbars = toolbarConfig.map(function(t2) {
- var config2 = {
- toolbar: t2,
- buttons: toolbarButtonsConfig,
- allowToolbarGroups: rawUiConfig.allowToolbarGroups
- };
- return identifyButtons(editor, config2, { backstage }, Optional.none());
- });
- OuterContainer.setToolbars(comp, toolbars);
- } else {
- OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage }, Optional.none()));
- }
- };
- var detection = detect$1();
- var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
- var setupEvents$1 = function(editor, uiComponents) {
- var dom2 = editor.dom;
- var contentWindow = editor.getWin();
- var initialDocEle = editor.getDoc().documentElement;
- var lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
- var lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
- var resizeWindow = function() {
- var outer = lastWindowDimensions.get();
- if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) {
- lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
- fireResizeContent(editor);
- }
- };
- var resizeDocument = function() {
- var docEle = editor.getDoc().documentElement;
- var inner = lastDocumentDimensions.get();
- if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) {
- lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight));
- fireResizeContent(editor);
- }
- };
- var scroll = function(e) {
- return fireScrollContent(editor, e);
- };
- dom2.bind(contentWindow, "resize", resizeWindow);
- dom2.bind(contentWindow, "scroll", scroll);
- var elementLoad = capture(SugarElement.fromDom(editor.getBody()), "load", resizeDocument);
- var mothership = uiComponents.uiMothership.element;
- editor.on("hide", function() {
- set$7(mothership, "display", "none");
- });
- editor.on("show", function() {
- remove$6(mothership, "display");
- });
- editor.on("NodeChange", resizeDocument);
- editor.on("remove", function() {
- elementLoad.unbind();
- dom2.unbind(contentWindow, "resize", resizeWindow);
- dom2.unbind(contentWindow, "scroll", scroll);
- contentWindow = null;
- });
- };
- var render$1 = function(editor, uiComponents, rawUiConfig, backstage, args) {
- var lastToolbarWidth = Cell(0);
- var outerContainer = uiComponents.outerContainer;
- iframe(editor);
- var eTargetNode = SugarElement.fromDom(args.targetNode);
- var uiRoot = getContentContainer(getRootNode(eTargetNode));
- attachSystemAfter(eTargetNode, uiComponents.mothership);
- attachSystem(uiRoot, uiComponents.uiMothership);
- editor.on("PostRender", function() {
- setToolbar(editor, uiComponents, rawUiConfig, backstage);
- lastToolbarWidth.set(editor.getWin().innerWidth);
- OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
- OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar);
- setupEvents$1(editor, uiComponents);
- });
- var socket = OuterContainer.getSocket(outerContainer).getOrDie("Could not find expected socket element");
- if (isiOS12) {
- setAll(socket.element, {
- "overflow": "scroll",
- "-webkit-overflow-scrolling": "touch"
- });
- var limit = first(function() {
- editor.fire("ScrollContent");
- }, 20);
- var unbinder = bind(socket.element, "scroll", limit.throttle);
- editor.on("remove", unbinder.unbind);
- }
- setupReadonlyModeSwitch(editor, uiComponents);
- editor.addCommand("ToggleSidebar", function(_ui, value2) {
- OuterContainer.toggleSidebar(outerContainer, value2);
- editor.fire("ToggleSidebar");
- });
- editor.addQueryValueHandler("ToggleSidebar", function() {
- return OuterContainer.whichSidebar(outerContainer);
- });
- var toolbarMode = getToolbarMode(editor);
- var refreshDrawer = function() {
- OuterContainer.refreshToolbar(uiComponents.outerContainer);
- };
- if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
- editor.on("ResizeWindow ResizeEditor ResizeContent", function() {
- var width2 = editor.getWin().innerWidth;
- if (width2 !== lastToolbarWidth.get()) {
- refreshDrawer();
- lastToolbarWidth.set(width2);
- }
- });
- }
- var api2 = {
- enable: function() {
- broadcastReadonly(uiComponents, false);
- },
- disable: function() {
- broadcastReadonly(uiComponents, true);
- },
- isDisabled: function() {
- return Disabling.isDisabled(outerContainer);
- }
- };
- return {
- iframeContainer: socket.element.dom,
- editorContainer: outerContainer.element.dom,
- api: api2
- };
- };
- var Iframe = Object.freeze({
- __proto__: null,
- render: render$1
- });
- var parseToInt = function(val) {
- var re = /^[0-9\.]+(|px)$/i;
- if (re.test("" + val)) {
- return Optional.some(parseInt("" + val, 10));
- }
- return Optional.none();
- };
- var numToPx = function(val) {
- return isNumber(val) ? val + "px" : val;
- };
- var calcCappedSize = function(size, minSize, maxSize) {
- var minOverride = minSize.filter(function(min2) {
- return size < min2;
- });
- var maxOverride = maxSize.filter(function(max2) {
- return size > max2;
- });
- return minOverride.or(maxOverride).getOr(size);
- };
- var getHeight = function(editor) {
- var baseHeight = getHeightSetting(editor);
- var minHeight = getMinHeightSetting(editor);
- var maxHeight = getMaxHeightSetting(editor);
- return parseToInt(baseHeight).map(function(height2) {
- return calcCappedSize(height2, minHeight, maxHeight);
- });
- };
- var getHeightWithFallback = function(editor) {
- var height2 = getHeight(editor);
- return height2.getOr(getHeightSetting(editor));
- };
- var getWidth = function(editor) {
- var baseWidth = getWidthSetting(editor);
- var minWidth = getMinWidthSetting(editor);
- var maxWidth = getMaxWidthSetting(editor);
- return parseToInt(baseWidth).map(function(width2) {
- return calcCappedSize(width2, minWidth, maxWidth);
- });
- };
- var getWidthWithFallback = function(editor) {
- var width2 = getWidth(editor);
- return width2.getOr(getWidthSetting(editor));
- };
- var InlineHeader = function(editor, targetElm, uiComponents, backstage, floatContainer) {
- var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
- var DOM = global$b.DOM;
- var useFixedToolbarContainer = useFixedContainer(editor);
- var isSticky = isStickyToolbar(editor);
- var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth(editor));
- var headerBackstage = backstage.shared.header;
- var isPositionedAtTop = headerBackstage.isPositionedAtTop;
- var toolbarMode = getToolbarMode(editor);
- var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
- var visible = Cell(false);
- var isVisible2 = function() {
- return visible.get() && !editor.removed;
- };
- var calcToolbarOffset = function(toolbar) {
- return isSplitToolbar ? toolbar.fold(constant$1(0), function(tbar) {
- return tbar.components().length > 1 ? get$b(tbar.components()[1].element) : 0;
- }) : 0;
- };
- var calcMode = function(container) {
- switch (getToolbarLocation(editor)) {
- case ToolbarLocation.auto:
- var toolbar_1 = OuterContainer.getToolbar(outerContainer);
- var offset2 = calcToolbarOffset(toolbar_1);
- var toolbarHeight = get$b(container.element) - offset2;
- var targetBounds = box$1(targetElm);
- var roomAtTop = targetBounds.y > toolbarHeight;
- if (roomAtTop) {
- return "top";
- } else {
- var doc = documentElement(targetElm);
- var docHeight = Math.max(doc.dom.scrollHeight, get$b(doc));
- var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
- if (roomAtBottom) {
- return "bottom";
- } else {
- var winBounds = win();
- var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
- return isRoomAtBottomViewport ? "bottom" : "top";
- }
- }
- case ToolbarLocation.bottom:
- return "bottom";
- case ToolbarLocation.top:
- default:
- return "top";
- }
- };
- var setupMode = function(mode) {
- var container = floatContainer.get();
- Docking.setModes(container, [mode]);
- headerBackstage.setDockingMode(mode);
- var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
- set$8(container.element, Attribute, verticalDir);
- };
- var updateChromeWidth = function() {
- var maxWidth = editorMaxWidthOpt.getOrThunk(function() {
- var bodyMargin = parseToInt(get$c(body(), "margin-left")).getOr(0);
- return get$a(body()) - absolute$3(targetElm).left + bodyMargin;
- });
- set$7(floatContainer.get().element, "max-width", maxWidth + "px");
- };
- var updateChromePosition = function() {
- var toolbar = OuterContainer.getToolbar(outerContainer);
- var offset2 = calcToolbarOffset(toolbar);
- var targetBounds = box$1(targetElm);
- var top2 = isPositionedAtTop() ? Math.max(targetBounds.y - get$b(floatContainer.get().element) + offset2, 0) : targetBounds.bottom;
- setAll(outerContainer.element, {
- position: "absolute",
- top: Math.round(top2) + "px",
- left: Math.round(targetBounds.x) + "px"
- });
- };
- var repositionPopups$1 = function() {
- uiMothership.broadcastOn([repositionPopups()], {});
- };
- var updateChromeUi = function(resetDocking) {
- if (resetDocking === void 0) {
- resetDocking = false;
- }
- if (!isVisible2()) {
- return;
- }
- if (!useFixedToolbarContainer) {
- updateChromeWidth();
- }
- if (isSplitToolbar) {
- OuterContainer.refreshToolbar(outerContainer);
- }
- if (!useFixedToolbarContainer) {
- updateChromePosition();
- }
- if (isSticky) {
- var floatContainerComp = floatContainer.get();
- resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
- }
- repositionPopups$1();
- };
- var updateMode = function(updateUi) {
- if (updateUi === void 0) {
- updateUi = true;
- }
- if (useFixedToolbarContainer || !isSticky || !isVisible2()) {
- return;
- }
- var currentMode = headerBackstage.getDockingMode();
- var newMode = calcMode(floatContainer.get());
- if (newMode !== currentMode) {
- setupMode(newMode);
- if (updateUi) {
- updateChromeUi(true);
- }
- }
- };
- var show2 = function() {
- visible.set(true);
- set$7(outerContainer.element, "display", "flex");
- DOM.addClass(editor.getBody(), "mce-edit-focus");
- remove$6(uiMothership.element, "display");
- updateMode(false);
- updateChromeUi();
- };
- var hide = function() {
- visible.set(false);
- if (uiComponents.outerContainer) {
- set$7(outerContainer.element, "display", "none");
- DOM.removeClass(editor.getBody(), "mce-edit-focus");
- }
- set$7(uiMothership.element, "display", "none");
- };
- return {
- isVisible: isVisible2,
- isPositionedAtTop,
- show: show2,
- hide,
- update: updateChromeUi,
- updateMode,
- repositionPopups: repositionPopups$1
- };
- };
- var getTargetPosAndBounds = function(targetElm, isToolbarTop) {
- var bounds2 = box$1(targetElm);
- return {
- pos: isToolbarTop ? bounds2.y : bounds2.bottom,
- bounds: bounds2
- };
- };
- var setupEvents = function(editor, targetElm, ui, toolbarPersist) {
- var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()));
- var resizeContent = function(e) {
- var _a2 = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()), pos = _a2.pos, bounds2 = _a2.bounds;
- var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds;
- var hasResized = bounds2.height !== prevBounds.height || bounds2.width !== prevBounds.width;
- prevPosAndBounds.set({
- pos,
- bounds: bounds2
- });
- if (hasResized) {
- fireResizeContent(editor, e);
- }
- if (ui.isVisible()) {
- if (prevPos !== pos) {
- ui.update(true);
- } else if (hasResized) {
- ui.updateMode();
- ui.repositionPopups();
- }
- }
- };
- if (!toolbarPersist) {
- editor.on("activate", ui.show);
- editor.on("deactivate", ui.hide);
- }
- editor.on("SkinLoaded ResizeWindow", function() {
- return ui.update(true);
- });
- editor.on("NodeChange keydown", function(e) {
- global$f.requestAnimationFrame(function() {
- return resizeContent(e);
- });
- });
- editor.on("ScrollWindow", function() {
- return ui.updateMode();
- });
- var elementLoad = unbindable();
- elementLoad.set(capture(SugarElement.fromDom(editor.getBody()), "load", resizeContent));
- editor.on("remove", function() {
- elementLoad.clear();
- });
- };
- var render = function(editor, uiComponents, rawUiConfig, backstage, args) {
- var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
- var floatContainer = Cell(null);
- var targetElm = SugarElement.fromDom(args.targetNode);
- var ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
- var toolbarPersist = isToolbarPersist(editor);
- inline(editor);
- var render2 = function() {
- if (floatContainer.get()) {
- ui.show();
- return;
- }
- floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
- var uiContainer = getUiContainer(editor);
- attachSystem(uiContainer, mothership);
- attachSystem(uiContainer, uiMothership);
- setToolbar(editor, uiComponents, rawUiConfig, backstage);
- OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
- ui.show();
- setupEvents(editor, targetElm, ui, toolbarPersist);
- editor.nodeChanged();
- };
- editor.on("show", render2);
- editor.on("hide", ui.hide);
- if (!toolbarPersist) {
- editor.on("focus", render2);
- editor.on("blur", ui.hide);
- }
- editor.on("init", function() {
- if (editor.hasFocus() || toolbarPersist) {
- render2();
- }
- });
- setupReadonlyModeSwitch(editor, uiComponents);
- var api2 = {
- show: function() {
- ui.show();
- },
- hide: function() {
- ui.hide();
- },
- enable: function() {
- broadcastReadonly(uiComponents, false);
- },
- disable: function() {
- broadcastReadonly(uiComponents, true);
- },
- isDisabled: function() {
- return Disabling.isDisabled(outerContainer);
- }
- };
- return {
- editorContainer: outerContainer.element.dom,
- api: api2
- };
- };
- var Inline = Object.freeze({
- __proto__: null,
- render
- });
- var showContextToolbarEvent = "contexttoolbar-show";
- var hideContextToolbarEvent = "contexttoolbar-hide";
- var getFormApi = function(input2) {
- return {
- hide: function() {
- return emit(input2, sandboxClose());
- },
- getValue: function() {
- return Representing.getValue(input2);
- }
- };
- };
- var runOnExecute = function(memInput, original2) {
- return run$1(internalToolbarButtonExecute, function(comp, se) {
- var input2 = memInput.get(comp);
- var formApi = getFormApi(input2);
- original2.onAction(formApi, se.event.buttonApi);
- });
- };
- var renderContextButton = function(memInput, button2, extras) {
- var _a2 = button2.original;
- _a2.primary;
- var rest = __rest(_a2, ["primary"]);
- var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
- type: "button",
- onAction: noop
- })));
- return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button2)]);
- };
- var renderContextToggleButton = function(memInput, button2, extras) {
- var _a2 = button2.original;
- _a2.primary;
- var rest = __rest(_a2, ["primary"]);
- var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
- type: "togglebutton",
- onAction: noop
- })));
- return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button2)]);
- };
- var generateOne = function(memInput, button2, providersBackstage) {
- var extras = { backstage: { shared: { providers: providersBackstage } } };
- if (button2.type === "contextformtogglebutton") {
- return renderContextToggleButton(memInput, button2, extras);
- } else {
- return renderContextButton(memInput, button2, extras);
- }
- };
- var generate = function(memInput, buttons, providersBackstage) {
- var mementos = map$2(buttons, function(button2) {
- return record(generateOne(memInput, button2, providersBackstage));
- });
- var asSpecs = function() {
- return map$2(mementos, function(mem) {
- return mem.asSpec();
- });
- };
- var findPrimary = function(compInSystem) {
- return findMap(buttons, function(button2, i) {
- if (button2.primary) {
- return Optional.from(mementos[i]).bind(function(mem) {
- return mem.getOpt(compInSystem);
- }).filter(not(Disabling.isDisabled));
- } else {
- return Optional.none();
- }
- });
- };
- return {
- asSpecs,
- findPrimary
- };
- };
- var buildInitGroups = function(ctx, providers) {
- var inputAttributes = ctx.label.fold(function() {
- return {};
- }, function(label) {
- return { "aria-label": label };
- });
- var memInput = record(Input.sketch({
- inputClasses: [
- "tox-toolbar-textfield",
- "tox-toolbar-nav-js"
- ],
- data: ctx.initValue(),
- inputAttributes,
- selectOnFocus: true,
- inputBehaviours: derive$1([Keying.config({
- mode: "special",
- onEnter: function(input2) {
- return commands.findPrimary(input2).map(function(primary) {
- emitExecute(primary);
- return true;
- });
- },
- onLeft: function(comp, se) {
- se.cut();
- return Optional.none();
- },
- onRight: function(comp, se) {
- se.cut();
- return Optional.none();
- }
- })])
- }));
- var commands = generate(memInput, ctx.commands, providers);
- return [
- {
- title: Optional.none(),
- items: [memInput.asSpec()]
- },
- {
- title: Optional.none(),
- items: commands.asSpecs()
- }
- ];
- };
- var renderContextForm = function(toolbarType, ctx, providers) {
- return renderToolbar({
- type: toolbarType,
- uid: generate$6("context-toolbar"),
- initGroups: buildInitGroups(ctx, providers),
- onEscape: Optional.none,
- cyclicKeying: true,
- providers
- });
- };
- var ContextForm = {
- renderContextForm,
- buildInitGroups
- };
- var isVerticalOverlap = function(a, b2, threshold) {
- if (threshold === void 0) {
- threshold = 0.01;
- }
- return b2.bottom - a.y >= threshold && a.bottom - b2.y >= threshold;
- };
- var getRangeRect = function(rng) {
- var rect2 = rng.getBoundingClientRect();
- if (rect2.height <= 0 && rect2.width <= 0) {
- var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset).element;
- var elm = isText$1(leaf$1) ? parent(leaf$1) : Optional.some(leaf$1);
- return elm.filter(isElement$2).map(function(e) {
- return e.dom.getBoundingClientRect();
- }).getOr(rect2);
- } else {
- return rect2;
- }
- };
- var getSelectionBounds = function(editor) {
- var rng = editor.selection.getRng();
- var rect2 = getRangeRect(rng);
- if (editor.inline) {
- var scroll_1 = get$9();
- return bounds(scroll_1.left + rect2.left, scroll_1.top + rect2.top, rect2.width, rect2.height);
- } else {
- var bodyPos = absolute$2(SugarElement.fromDom(editor.getBody()));
- return bounds(bodyPos.x + rect2.left, bodyPos.y + rect2.top, rect2.width, rect2.height);
- }
- };
- var getAnchorElementBounds = function(editor, lastElement) {
- return lastElement.filter(inBody).map(absolute$2).getOrThunk(function() {
- return getSelectionBounds(editor);
- });
- };
- var getHorizontalBounds = function(contentAreaBox, viewportBounds, margin) {
- var x = Math.max(contentAreaBox.x + margin, viewportBounds.x);
- var right2 = Math.min(contentAreaBox.right - margin, viewportBounds.right);
- return {
- x,
- width: right2 - x
- };
- };
- var getVerticalBounds = function(editor, contentAreaBox, viewportBounds, isToolbarLocationTop, toolbarType, margin) {
- var container = SugarElement.fromDom(editor.getContainer());
- var header = descendant(container, ".tox-editor-header").getOr(container);
- var headerBox = box$1(header);
- var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
- var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
- if (editor.inline && isToolbarAbove) {
- return {
- y: Math.max(headerBox.bottom + margin, viewportBounds.y),
- bottom: viewportBounds.bottom
- };
- }
- if (editor.inline && !isToolbarAbove) {
- return {
- y: viewportBounds.y,
- bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
- };
- }
- var containerBounds = toolbarType === "line" ? box$1(container) : contentAreaBox;
- if (isToolbarAbove) {
- return {
- y: Math.max(headerBox.bottom + margin, viewportBounds.y),
- bottom: Math.min(containerBounds.bottom - margin, viewportBounds.bottom)
- };
- }
- return {
- y: Math.max(containerBounds.y + margin, viewportBounds.y),
- bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
- };
- };
- var getContextToolbarBounds = function(editor, sharedBackstage, toolbarType, margin) {
- if (margin === void 0) {
- margin = 0;
- }
- var viewportBounds = getBounds$3(window);
- var contentAreaBox = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
- var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
- var _a2 = getHorizontalBounds(contentAreaBox, viewportBounds, margin), x = _a2.x, width2 = _a2.width;
- if (editor.inline && !toolbarOrMenubarEnabled) {
- return bounds(x, viewportBounds.y, width2, viewportBounds.height);
- } else {
- var isToolbarTop = sharedBackstage.header.isPositionedAtTop();
- var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop, toolbarType, margin), y = _b.y, bottom2 = _b.bottom;
- return bounds(x, y, width2, bottom2 - y);
- }
- };
- var bubbleSize$1 = 12;
- var bubbleAlignments$1 = {
- valignCentre: [],
- alignCentre: [],
- alignLeft: ["tox-pop--align-left"],
- alignRight: ["tox-pop--align-right"],
- right: ["tox-pop--right"],
- left: ["tox-pop--left"],
- bottom: ["tox-pop--bottom"],
- top: ["tox-pop--top"],
- inset: ["tox-pop--inset"]
- };
- var anchorOverrides = {
- maxHeightFunction: expandable$1(),
- maxWidthFunction: expandable()
- };
- var isEntireElementSelected = function(editor, elem) {
- var rng = editor.selection.getRng();
- var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset);
- return rng.startContainer === rng.endContainer && rng.startOffset === rng.endOffset - 1 && eq(leaf$1.element, elem);
- };
- var preservePosition = function(elem, position2, f) {
- var currentPosition = getRaw(elem, "position");
- set$7(elem, "position", position2);
- var result = f(elem);
- currentPosition.each(function(pos) {
- return set$7(elem, "position", pos);
- });
- return result;
- };
- var shouldUseInsetLayouts = function(position2) {
- return position2 === "node";
- };
- var determineInsetLayout = function(editor, contextbar, elem, data, bounds2) {
- var selectionBounds = getSelectionBounds(editor);
- var isSameAnchorElement = data.lastElement().exists(function(prev) {
- return eq(elem, prev);
- });
- if (isEntireElementSelected(editor, elem)) {
- return isSameAnchorElement ? preserve : north;
- } else if (isSameAnchorElement) {
- return preservePosition(contextbar, data.getMode(), function() {
- var isOverlapping = isVerticalOverlap(selectionBounds, box$1(contextbar));
- return isOverlapping && !data.isReposition() ? flip$2 : preserve;
- });
- } else {
- var yBounds = data.getMode() === "fixed" ? bounds2.y + get$9().top : bounds2.y;
- var contextbarHeight = get$b(contextbar) + bubbleSize$1;
- return yBounds + contextbarHeight <= selectionBounds.y ? north : south;
- }
- };
- var getAnchorSpec$2 = function(editor, mobile, data, position2) {
- var smartInsetLayout = function(elem) {
- return function(anchor2, element2, bubbles, placee, bounds2) {
- var layout2 = determineInsetLayout(editor, placee, elem, data, bounds2);
- var newAnchor = __assign(__assign({}, anchor2), {
- y: bounds2.y,
- height: bounds2.height
- });
- return __assign(__assign({}, layout2(newAnchor, element2, bubbles, placee, bounds2)), { alwaysFit: true });
- };
- };
- var getInsetLayouts = function(elem) {
- return shouldUseInsetLayouts(position2) ? [smartInsetLayout(elem)] : [];
- };
- var desktopAnchorSpecLayouts = {
- onLtr: function(elem) {
- return [
- north$2,
- south$2,
- northeast$2,
- southeast$2,
- northwest$2,
- southwest$2
- ].concat(getInsetLayouts(elem));
- },
- onRtl: function(elem) {
- return [
- north$2,
- south$2,
- northwest$2,
- southwest$2,
- northeast$2,
- southeast$2
- ].concat(getInsetLayouts(elem));
- }
- };
- var mobileAnchorSpecLayouts = {
- onLtr: function(elem) {
- return [
- south$2,
- southeast$2,
- southwest$2,
- northeast$2,
- northwest$2,
- north$2
- ].concat(getInsetLayouts(elem));
- },
- onRtl: function(elem) {
- return [
- south$2,
- southwest$2,
- southeast$2,
- northwest$2,
- northeast$2,
- north$2
- ].concat(getInsetLayouts(elem));
- }
- };
- return mobile ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts;
- };
- var getAnchorLayout = function(editor, position2, isTouch2, data) {
- if (position2 === "line") {
- return {
- bubble: nu$5(bubbleSize$1, 0, bubbleAlignments$1),
- layouts: {
- onLtr: function() {
- return [east$2];
- },
- onRtl: function() {
- return [west$2];
- }
- },
- overrides: anchorOverrides
- };
- } else {
- return {
- bubble: nu$5(0, bubbleSize$1, bubbleAlignments$1, 1 / bubbleSize$1),
- layouts: getAnchorSpec$2(editor, isTouch2, data, position2),
- overrides: anchorOverrides
- };
- }
- };
- var matchTargetWith = function(elem, candidates) {
- var ctxs = filter$2(candidates, function(toolbarApi) {
- return toolbarApi.predicate(elem.dom);
- });
- var _a2 = partition$3(ctxs, function(t2) {
- return t2.type === "contexttoolbar";
- }), pass = _a2.pass, fail = _a2.fail;
- return {
- contextToolbars: pass,
- contextForms: fail
- };
- };
- var filterByPositionForStartNode = function(toolbars) {
- if (toolbars.length <= 1) {
- return toolbars;
- } else {
- var doesPositionExist = function(value2) {
- return exists(toolbars, function(t2) {
- return t2.position === value2;
- });
- };
- var filterToolbarsByPosition = function(value2) {
- return filter$2(toolbars, function(t2) {
- return t2.position === value2;
- });
- };
- var hasSelectionToolbars = doesPositionExist("selection");
- var hasNodeToolbars = doesPositionExist("node");
- if (hasSelectionToolbars || hasNodeToolbars) {
- if (hasNodeToolbars && hasSelectionToolbars) {
- var nodeToolbars = filterToolbarsByPosition("node");
- var selectionToolbars = map$2(filterToolbarsByPosition("selection"), function(t2) {
- return __assign(__assign({}, t2), { position: "node" });
- });
- return nodeToolbars.concat(selectionToolbars);
- } else {
- return hasSelectionToolbars ? filterToolbarsByPosition("selection") : filterToolbarsByPosition("node");
- }
- } else {
- return filterToolbarsByPosition("line");
- }
- }
- };
- var filterByPositionForAncestorNode = function(toolbars) {
- if (toolbars.length <= 1) {
- return toolbars;
- } else {
- var findPosition_1 = function(value2) {
- return find$5(toolbars, function(t2) {
- return t2.position === value2;
- });
- };
- var basePosition = findPosition_1("selection").orThunk(function() {
- return findPosition_1("node");
- }).orThunk(function() {
- return findPosition_1("line");
- }).map(function(t2) {
- return t2.position;
- });
- return basePosition.fold(function() {
- return [];
- }, function(pos) {
- return filter$2(toolbars, function(t2) {
- return t2.position === pos;
- });
- });
- }
- };
- var matchStartNode = function(elem, nodeCandidates, editorCandidates) {
- var nodeMatches = matchTargetWith(elem, nodeCandidates);
- if (nodeMatches.contextForms.length > 0) {
- return Optional.some({
- elem,
- toolbars: [nodeMatches.contextForms[0]]
- });
- } else {
- var editorMatches = matchTargetWith(elem, editorCandidates);
- if (editorMatches.contextForms.length > 0) {
- return Optional.some({
- elem,
- toolbars: [editorMatches.contextForms[0]]
- });
- } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
- var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
- return Optional.some({
- elem,
- toolbars
- });
- } else {
- return Optional.none();
- }
- }
- };
- var matchAncestor = function(isRoot, startNode, scopes) {
- if (isRoot(startNode)) {
- return Optional.none();
- } else {
- return ancestor$2(startNode, function(ancestorElem) {
- if (isElement$2(ancestorElem)) {
- var _a2 = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a2.contextToolbars, contextForms = _a2.contextForms;
- var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
- return toolbars.length > 0 ? Optional.some({
- elem: ancestorElem,
- toolbars
- }) : Optional.none();
- } else {
- return Optional.none();
- }
- }, isRoot);
- }
- };
- var lookup$1 = function(scopes, editor) {
- var rootElem = SugarElement.fromDom(editor.getBody());
- var isRoot = function(elem) {
- return eq(elem, rootElem);
- };
- var isOutsideRoot = function(startNode2) {
- return !isRoot(startNode2) && !contains(rootElem, startNode2);
- };
- var startNode = SugarElement.fromDom(editor.selection.getNode());
- if (isOutsideRoot(startNode)) {
- return Optional.none();
- }
- return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function() {
- return matchAncestor(isRoot, startNode, scopes);
- });
- };
- var categorise = function(contextToolbars, navigate) {
- var forms = {};
- var inNodeScope = [];
- var inEditorScope = [];
- var formNavigators = {};
- var lookupTable = {};
- var registerForm = function(key, toolbarSpec) {
- var contextForm = getOrDie(createContextForm(toolbarSpec));
- forms[key] = contextForm;
- contextForm.launch.map(function(launch) {
- formNavigators["form:" + key] = __assign(__assign({}, toolbarSpec.launch), {
- type: launch.type === "contextformtogglebutton" ? "togglebutton" : "button",
- onAction: function() {
- navigate(contextForm);
- }
- });
- });
- if (contextForm.scope === "editor") {
- inEditorScope.push(contextForm);
- } else {
- inNodeScope.push(contextForm);
- }
- lookupTable[key] = contextForm;
- };
- var registerToolbar = function(key, toolbarSpec) {
- createContextToolbar(toolbarSpec).each(function(contextToolbar) {
- if (toolbarSpec.scope === "editor") {
- inEditorScope.push(contextToolbar);
- } else {
- inNodeScope.push(contextToolbar);
- }
- lookupTable[key] = contextToolbar;
- });
- };
- var keys$1 = keys(contextToolbars);
- each$1(keys$1, function(key) {
- var toolbarApi = contextToolbars[key];
- if (toolbarApi.type === "contextform") {
- registerForm(key, toolbarApi);
- } else if (toolbarApi.type === "contexttoolbar") {
- registerToolbar(key, toolbarApi);
- }
- });
- return {
- forms,
- inNodeScope,
- inEditorScope,
- lookupTable,
- formNavigators
- };
- };
- var forwardSlideEvent = generate$6("forward-slide");
- var backSlideEvent = generate$6("backward-slide");
- var changeSlideEvent = generate$6("change-slide-event");
- var resizingClass = "tox-pop--resizing";
- var renderContextToolbar = function(spec) {
- var stack = Cell([]);
- return InlineView.sketch({
- dom: {
- tag: "div",
- classes: ["tox-pop"]
- },
- fireDismissalEventInstead: { event: "doNotDismissYet" },
- onShow: function(comp) {
- stack.set([]);
- InlineView.getContent(comp).each(function(c) {
- remove$6(c.element, "visibility");
- });
- remove$2(comp.element, resizingClass);
- remove$6(comp.element, "width");
- },
- inlineBehaviours: derive$1([
- config("context-toolbar-events", [
- runOnSource(transitionend(), function(comp, se) {
- if (se.event.raw.propertyName === "width") {
- remove$2(comp.element, resizingClass);
- remove$6(comp.element, "width");
- }
- }),
- run$1(changeSlideEvent, function(comp, se) {
- var elem = comp.element;
- remove$6(elem, "width");
- var currentWidth = get$a(elem);
- InlineView.setContent(comp, se.event.contents);
- add$2(elem, resizingClass);
- var newWidth = get$a(elem);
- set$7(elem, "width", currentWidth + "px");
- InlineView.getContent(comp).each(function(newContents) {
- se.event.focus.bind(function(f) {
- focus$3(f);
- return search(elem);
- }).orThunk(function() {
- Keying.focusIn(newContents);
- return active(getRootNode(elem));
- });
- });
- global$f.setTimeout(function() {
- set$7(comp.element, "width", newWidth + "px");
- }, 0);
- }),
- run$1(forwardSlideEvent, function(comp, se) {
- InlineView.getContent(comp).each(function(oldContents) {
- stack.set(stack.get().concat([{
- bar: oldContents,
- focus: active(getRootNode(comp.element))
- }]));
- });
- emitWith(comp, changeSlideEvent, {
- contents: se.event.forwardContents,
- focus: Optional.none()
- });
- }),
- run$1(backSlideEvent, function(comp, _se) {
- last$2(stack.get()).each(function(last2) {
- stack.set(stack.get().slice(0, stack.get().length - 1));
- emitWith(comp, changeSlideEvent, {
- contents: premade(last2.bar),
- focus: last2.focus
- });
- });
- })
- ]),
- Keying.config({
- mode: "special",
- onEscape: function(comp) {
- return last$2(stack.get()).fold(function() {
- return spec.onEscape();
- }, function(_) {
- emit(comp, backSlideEvent);
- return Optional.some(true);
- });
- }
- })
- ]),
- lazySink: function() {
- return Result.value(spec.sink);
- }
- });
- };
- var transitionClass = "tox-pop--transition";
- var register$7 = function(editor, registryContextToolbars, sink, extras) {
- var backstage = extras.backstage;
- var sharedBackstage = backstage.shared;
- var isTouch2 = detect$1().deviceType.isTouch;
- var lastElement = value$1();
- var lastTrigger = value$1();
- var lastContextPosition = value$1();
- var contextbar = build$1(renderContextToolbar({
- sink,
- onEscape: function() {
- editor.focus();
- return Optional.some(true);
- }
- }));
- var getBounds2 = function() {
- var position2 = lastContextPosition.get().getOr("node");
- var margin = shouldUseInsetLayouts(position2) ? 1 : 0;
- return getContextToolbarBounds(editor, sharedBackstage, position2, margin);
- };
- var canLaunchToolbar = function() {
- return !editor.removed && !(isTouch2() && backstage.isContextMenuOpen());
- };
- var isSameLaunchElement = function(elem) {
- return is$1(lift2(elem, lastElement.get(), eq), true);
- };
- var shouldContextToolbarHide = function() {
- if (!canLaunchToolbar()) {
- return true;
- } else {
- var contextToolbarBounds = getBounds2();
- var anchorBounds = is$1(lastContextPosition.get(), "node") ? getAnchorElementBounds(editor, lastElement.get()) : getSelectionBounds(editor);
- return contextToolbarBounds.height <= 0 || !isVerticalOverlap(anchorBounds, contextToolbarBounds);
- }
- };
- var close2 = function() {
- lastElement.clear();
- lastTrigger.clear();
- lastContextPosition.clear();
- InlineView.hide(contextbar);
- };
- var hideOrRepositionIfNecessary = function() {
- if (InlineView.isOpen(contextbar)) {
- var contextBarEle = contextbar.element;
- remove$6(contextBarEle, "display");
- if (shouldContextToolbarHide()) {
- set$7(contextBarEle, "display", "none");
- } else {
- lastTrigger.set(0);
- InlineView.reposition(contextbar);
- }
- }
- };
- var wrapInPopDialog = function(toolbarSpec) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-pop__dialog"]
- },
- components: [toolbarSpec],
- behaviours: derive$1([
- Keying.config({ mode: "acyclic" }),
- config("pop-dialog-wrap-events", [
- runOnAttached(function(comp) {
- editor.shortcuts.add("ctrl+F9", "focus statusbar", function() {
- return Keying.focusIn(comp);
- });
- }),
- runOnDetached(function(_comp) {
- editor.shortcuts.remove("ctrl+F9");
- })
- ])
- ])
- };
- };
- var getScopes = cached(function() {
- return categorise(registryContextToolbars, function(toolbarApi) {
- var alloySpec = buildToolbar([toolbarApi]);
- emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
- });
- });
- var buildContextToolbarGroups = function(allButtons, ctx) {
- return identifyButtons(editor, {
- buttons: allButtons,
- toolbar: ctx.items,
- allowToolbarGroups: false
- }, extras, Optional.some(["form:"]));
- };
- var buildContextFormGroups = function(ctx, providers) {
- return ContextForm.buildInitGroups(ctx, providers);
- };
- var buildToolbar = function(toolbars) {
- var buttons = editor.ui.registry.getAll().buttons;
- var scopes = getScopes();
- var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
- var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
- var initGroups = flatten(map$2(toolbars, function(ctx) {
- return ctx.type === "contexttoolbar" ? buildContextToolbarGroups(allButtons, ctx) : buildContextFormGroups(ctx, sharedBackstage.providers);
- }));
- return renderToolbar({
- type: toolbarType,
- uid: generate$6("context-toolbar"),
- initGroups,
- onEscape: Optional.none,
- cyclicKeying: true,
- providers: sharedBackstage.providers
- });
- };
- var getAnchor2 = function(position2, element2) {
- var anchorage = position2 === "node" ? sharedBackstage.anchors.node(element2) : sharedBackstage.anchors.cursor();
- var anchorLayout = getAnchorLayout(editor, position2, isTouch2(), {
- lastElement: lastElement.get,
- isReposition: function() {
- return is$1(lastTrigger.get(), 0);
- },
- getMode: function() {
- return Positioning.getMode(sink);
- }
- });
- return deepMerge(anchorage, anchorLayout);
- };
- var launchContext = function(toolbarApi, elem) {
- launchContextToolbar.cancel();
- if (!canLaunchToolbar()) {
- return;
- }
- var toolbarSpec = buildToolbar(toolbarApi);
- var position2 = toolbarApi[0].position;
- var anchor2 = getAnchor2(position2, elem);
- lastContextPosition.set(position2);
- lastTrigger.set(1);
- var contextBarEle = contextbar.element;
- remove$6(contextBarEle, "display");
- if (!isSameLaunchElement(elem)) {
- remove$2(contextBarEle, transitionClass);
- Positioning.reset(sink, contextbar);
- }
- InlineView.showWithinBounds(contextbar, wrapInPopDialog(toolbarSpec), {
- anchor: anchor2,
- transition: {
- classes: [transitionClass],
- mode: "placement"
- }
- }, function() {
- return Optional.some(getBounds2());
- });
- elem.fold(lastElement.clear, lastElement.set);
- if (shouldContextToolbarHide()) {
- set$7(contextBarEle, "display", "none");
- }
- };
- var launchContextToolbar = last(function() {
- if (!editor.hasFocus() || editor.removed) {
- return;
- }
- if (has(contextbar.element, transitionClass)) {
- launchContextToolbar.throttle();
- } else {
- var scopes = getScopes();
- lookup$1(scopes, editor).fold(close2, function(info) {
- launchContext(info.toolbars, Optional.some(info.elem));
- });
- }
- }, 17);
- editor.on("init", function() {
- editor.on("remove", close2);
- editor.on("ScrollContent ScrollWindow ObjectResized ResizeEditor longpress", hideOrRepositionIfNecessary);
- editor.on("click keyup focus SetContent", launchContextToolbar.throttle);
- editor.on(hideContextToolbarEvent, close2);
- editor.on(showContextToolbarEvent, function(e) {
- var scopes = getScopes();
- get$e(scopes.lookupTable, e.toolbarKey).each(function(ctx) {
- launchContext([ctx], someIf(e.target !== editor, e.target));
- InlineView.getContent(contextbar).each(Keying.focusIn);
- });
- });
- editor.on("focusout", function(_e) {
- global$f.setEditorTimeout(editor, function() {
- if (search(sink.element).isNone() && search(contextbar.element).isNone()) {
- close2();
- }
- }, 0);
- });
- editor.on("SwitchMode", function() {
- if (editor.mode.isReadOnly()) {
- close2();
- }
- });
- editor.on("AfterProgressState", function(event) {
- if (event.state) {
- close2();
- } else if (editor.hasFocus()) {
- launchContextToolbar.throttle();
- }
- });
- editor.on("NodeChange", function(_e) {
- search(contextbar.element).fold(launchContextToolbar.throttle, noop);
- });
- });
- };
- var register$6 = function(editor) {
- var alignToolbarButtons = [
- {
- name: "alignleft",
- text: "Align left",
- cmd: "JustifyLeft",
- icon: "align-left"
- },
- {
- name: "aligncenter",
- text: "Align center",
- cmd: "JustifyCenter",
- icon: "align-center"
- },
- {
- name: "alignright",
- text: "Align right",
- cmd: "JustifyRight",
- icon: "align-right"
- },
- {
- name: "alignjustify",
- text: "Justify",
- cmd: "JustifyFull",
- icon: "align-justify"
- }
- ];
- each$1(alignToolbarButtons, function(item2) {
- editor.ui.registry.addToggleButton(item2.name, {
- tooltip: item2.text,
- icon: item2.icon,
- onAction: onActionExecCommand(editor, item2.cmd),
- onSetup: onSetupFormatToggle(editor, item2.name)
- });
- });
- editor.ui.registry.addButton("alignnone", {
- tooltip: "No alignment",
- icon: "align-none",
- onAction: onActionExecCommand(editor, "JustifyNone")
- });
- };
- var units = {
- unsupportedLength: [
- "em",
- "ex",
- "cap",
- "ch",
- "ic",
- "rem",
- "lh",
- "rlh",
- "vw",
- "vh",
- "vi",
- "vb",
- "vmin",
- "vmax",
- "cm",
- "mm",
- "Q",
- "in",
- "pc",
- "pt",
- "px"
- ],
- fixed: [
- "px",
- "pt"
- ],
- relative: ["%"],
- empty: [""]
- };
- var pattern = function() {
- var decimalDigits = "[0-9]+";
- var signedInteger = "[+-]?" + decimalDigits;
- var exponentPart = "[eE]" + signedInteger;
- var dot = "\\.";
- var opt = function(input2) {
- return "(?:" + input2 + ")?";
- };
- var unsignedDecimalLiteral = [
- "Infinity",
- decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
- dot + decimalDigits + opt(exponentPart),
- decimalDigits + opt(exponentPart)
- ].join("|");
- var float = "[+-]?(?:" + unsignedDecimalLiteral + ")";
- return new RegExp("^(" + float + ")(.*)$");
- }();
- var isUnit = function(unit, accepted) {
- return exists(accepted, function(acc) {
- return exists(units[acc], function(check) {
- return unit === check;
- });
- });
- };
- var parse = function(input2, accepted) {
- var match = Optional.from(pattern.exec(input2));
- return match.bind(function(array) {
- var value2 = Number(array[1]);
- var unitRaw = array[2];
- if (isUnit(unitRaw, accepted)) {
- return Optional.some({
- value: value2,
- unit: unitRaw
- });
- } else {
- return Optional.none();
- }
- });
- };
- var normalise = function(input2, accepted) {
- return parse(input2, accepted).map(function(_a2) {
- var value2 = _a2.value, unit = _a2.unit;
- return value2 + unit;
- });
- };
- var registerController = function(editor, spec) {
- var getMenuItems2 = function() {
- var options = spec.getOptions(editor);
- var initial = spec.getCurrent(editor).map(spec.hash);
- var current = value$1();
- return map$2(options, function(value2) {
- return {
- type: "togglemenuitem",
- text: spec.display(value2),
- onSetup: function(api2) {
- var setActive = function(active2) {
- if (active2) {
- current.on(function(oldApi) {
- return oldApi.setActive(false);
- });
- current.set(api2);
- }
- api2.setActive(active2);
- };
- setActive(is$1(initial, spec.hash(value2)));
- var unbindWatcher = spec.watcher(editor, value2, setActive);
- return function() {
- current.clear();
- unbindWatcher();
- };
- },
- onAction: function() {
- return spec.setCurrent(editor, value2);
- }
- };
- });
- };
- editor.ui.registry.addMenuButton(spec.name, {
- tooltip: spec.text,
- icon: spec.icon,
- fetch: function(callback) {
- return callback(getMenuItems2());
- },
- onSetup: spec.onToolbarSetup
- });
- editor.ui.registry.addNestedMenuItem(spec.name, {
- type: "nestedmenuitem",
- text: spec.text,
- getSubmenuItems: getMenuItems2,
- onSetup: spec.onMenuSetup
- });
- };
- var lineHeightSpec = {
- name: "lineheight",
- text: "Line height",
- icon: "line-height",
- getOptions: getLineHeightFormats,
- hash: function(input2) {
- return normalise(input2, [
- "fixed",
- "relative",
- "empty"
- ]).getOr(input2);
- },
- display: identity$1,
- watcher: function(editor, value2, callback) {
- return editor.formatter.formatChanged("lineheight", callback, false, { value: value2 }).unbind;
- },
- getCurrent: function(editor) {
- return Optional.from(editor.queryCommandValue("LineHeight"));
- },
- setCurrent: function(editor, value2) {
- return editor.execCommand("LineHeight", false, value2);
- }
- };
- var languageSpec = function(editor) {
- var settingsOpt = Optional.from(getContentLanguages(editor));
- return settingsOpt.map(function(settings) {
- return {
- name: "language",
- text: "Language",
- icon: "language",
- getOptions: constant$1(settings),
- hash: function(input2) {
- return isUndefined(input2.customCode) ? input2.code : input2.code + "/" + input2.customCode;
- },
- display: function(input2) {
- return input2.title;
- },
- watcher: function(editor2, value2, callback) {
- return editor2.formatter.formatChanged("lang", callback, false, {
- value: value2.code,
- customValue: value2.customCode
- }).unbind;
- },
- getCurrent: function(editor2) {
- var node = SugarElement.fromDom(editor2.selection.getNode());
- return closest$4(node, function(n) {
- return Optional.some(n).filter(isElement$2).bind(function(ele) {
- var codeOpt = getOpt(ele, "lang");
- return codeOpt.map(function(code) {
- var customCode = getOpt(ele, "data-mce-lang").getOrUndefined();
- return {
- code,
- customCode,
- title: ""
- };
- });
- });
- });
- },
- setCurrent: function(editor2, lang) {
- return editor2.execCommand("Lang", false, lang);
- },
- onToolbarSetup: function(api2) {
- var unbinder = unbindable();
- api2.setActive(editor.formatter.match("lang", {}, void 0, true));
- unbinder.set(editor.formatter.formatChanged("lang", api2.setActive, true));
- return unbinder.clear;
- }
- };
- });
- };
- var register$5 = function(editor) {
- registerController(editor, lineHeightSpec);
- languageSpec(editor).each(function(spec) {
- return registerController(editor, spec);
- });
- };
- var register$4 = function(editor, backstage) {
- alignSelectMenu(editor, backstage);
- fontSelectMenu(editor, backstage);
- styleSelectMenu(editor, backstage);
- formatSelectMenu(editor, backstage);
- fontsizeSelectMenu(editor, backstage);
- };
- var onSetupOutdentState = function(editor) {
- return onSetupEvent(editor, "NodeChange", function(api2) {
- api2.setDisabled(!editor.queryCommandState("outdent"));
- });
- };
- var registerButtons$2 = function(editor) {
- editor.ui.registry.addButton("outdent", {
- tooltip: "Decrease indent",
- icon: "outdent",
- onSetup: onSetupOutdentState(editor),
- onAction: onActionExecCommand(editor, "outdent")
- });
- editor.ui.registry.addButton("indent", {
- tooltip: "Increase indent",
- icon: "indent",
- onAction: onActionExecCommand(editor, "indent")
- });
- };
- var register$3 = function(editor) {
- registerButtons$2(editor);
- };
- var onActionToggleFormat = function(editor, fmt) {
- return function() {
- editor.execCommand("mceToggleFormat", false, fmt);
- };
- };
- var registerFormatButtons = function(editor) {
- global$5.each([
- {
- name: "bold",
- text: "Bold",
- icon: "bold"
- },
- {
- name: "italic",
- text: "Italic",
- icon: "italic"
- },
- {
- name: "underline",
- text: "Underline",
- icon: "underline"
- },
- {
- name: "strikethrough",
- text: "Strikethrough",
- icon: "strike-through"
- },
- {
- name: "subscript",
- text: "Subscript",
- icon: "subscript"
- },
- {
- name: "superscript",
- text: "Superscript",
- icon: "superscript"
- }
- ], function(btn, _idx) {
- editor.ui.registry.addToggleButton(btn.name, {
- tooltip: btn.text,
- icon: btn.icon,
- onSetup: onSetupFormatToggle(editor, btn.name),
- onAction: onActionToggleFormat(editor, btn.name)
- });
- });
- for (var i = 1; i <= 6; i++) {
- var name_1 = "h" + i;
- editor.ui.registry.addToggleButton(name_1, {
- text: name_1.toUpperCase(),
- tooltip: "Heading " + i,
- onSetup: onSetupFormatToggle(editor, name_1),
- onAction: onActionToggleFormat(editor, name_1)
- });
- }
- };
- var registerCommandButtons = function(editor) {
- global$5.each([
- {
- name: "cut",
- text: "Cut",
- action: "Cut",
- icon: "cut"
- },
- {
- name: "copy",
- text: "Copy",
- action: "Copy",
- icon: "copy"
- },
- {
- name: "paste",
- text: "Paste",
- action: "Paste",
- icon: "paste"
- },
- {
- name: "help",
- text: "Help",
- action: "mceHelp",
- icon: "help"
- },
- {
- name: "selectall",
- text: "Select all",
- action: "SelectAll",
- icon: "select-all"
- },
- {
- name: "newdocument",
- text: "New document",
- action: "mceNewDocument",
- icon: "new-document"
- },
- {
- name: "removeformat",
- text: "Clear formatting",
- action: "RemoveFormat",
- icon: "remove-formatting"
- },
- {
- name: "remove",
- text: "Remove",
- action: "Delete",
- icon: "remove"
- }
- ], function(btn) {
- editor.ui.registry.addButton(btn.name, {
- tooltip: btn.text,
- icon: btn.icon,
- onAction: onActionExecCommand(editor, btn.action)
- });
- });
- };
- var registerCommandToggleButtons = function(editor) {
- global$5.each([{
- name: "blockquote",
- text: "Blockquote",
- action: "mceBlockQuote",
- icon: "quote"
- }], function(btn) {
- editor.ui.registry.addToggleButton(btn.name, {
- tooltip: btn.text,
- icon: btn.icon,
- onAction: onActionExecCommand(editor, btn.action),
- onSetup: onSetupFormatToggle(editor, btn.name)
- });
- });
- };
- var registerButtons$1 = function(editor) {
- registerFormatButtons(editor);
- registerCommandButtons(editor);
- registerCommandToggleButtons(editor);
- };
- var registerMenuItems$2 = function(editor) {
- global$5.each([
- {
- name: "bold",
- text: "Bold",
- action: "Bold",
- icon: "bold",
- shortcut: "Meta+B"
- },
- {
- name: "italic",
- text: "Italic",
- action: "Italic",
- icon: "italic",
- shortcut: "Meta+I"
- },
- {
- name: "underline",
- text: "Underline",
- action: "Underline",
- icon: "underline",
- shortcut: "Meta+U"
- },
- {
- name: "strikethrough",
- text: "Strikethrough",
- action: "Strikethrough",
- icon: "strike-through",
- shortcut: ""
- },
- {
- name: "subscript",
- text: "Subscript",
- action: "Subscript",
- icon: "subscript",
- shortcut: ""
- },
- {
- name: "superscript",
- text: "Superscript",
- action: "Superscript",
- icon: "superscript",
- shortcut: ""
- },
- {
- name: "removeformat",
- text: "Clear formatting",
- action: "RemoveFormat",
- icon: "remove-formatting",
- shortcut: ""
- },
- {
- name: "newdocument",
- text: "New document",
- action: "mceNewDocument",
- icon: "new-document",
- shortcut: ""
- },
- {
- name: "cut",
- text: "Cut",
- action: "Cut",
- icon: "cut",
- shortcut: "Meta+X"
- },
- {
- name: "copy",
- text: "Copy",
- action: "Copy",
- icon: "copy",
- shortcut: "Meta+C"
- },
- {
- name: "paste",
- text: "Paste",
- action: "Paste",
- icon: "paste",
- shortcut: "Meta+V"
- },
- {
- name: "selectall",
- text: "Select all",
- action: "SelectAll",
- icon: "select-all",
- shortcut: "Meta+A"
- }
- ], function(btn) {
- editor.ui.registry.addMenuItem(btn.name, {
- text: btn.text,
- icon: btn.icon,
- shortcut: btn.shortcut,
- onAction: onActionExecCommand(editor, btn.action)
- });
- });
- editor.ui.registry.addMenuItem("codeformat", {
- text: "Code",
- icon: "sourcecode",
- onAction: onActionToggleFormat(editor, "code")
- });
- };
- var register$2 = function(editor) {
- registerButtons$1(editor);
- registerMenuItems$2(editor);
- };
- var onSetupUndoRedoState = function(editor, type2) {
- return onSetupEvent(editor, "Undo Redo AddUndo TypingUndo ClearUndos SwitchMode", function(api2) {
- api2.setDisabled(editor.mode.isReadOnly() || !editor.undoManager[type2]());
- });
- };
- var registerMenuItems$1 = function(editor) {
- editor.ui.registry.addMenuItem("undo", {
- text: "Undo",
- icon: "undo",
- shortcut: "Meta+Z",
- onSetup: onSetupUndoRedoState(editor, "hasUndo"),
- onAction: onActionExecCommand(editor, "undo")
- });
- editor.ui.registry.addMenuItem("redo", {
- text: "Redo",
- icon: "redo",
- shortcut: "Meta+Y",
- onSetup: onSetupUndoRedoState(editor, "hasRedo"),
- onAction: onActionExecCommand(editor, "redo")
- });
- };
- var registerButtons = function(editor) {
- editor.ui.registry.addButton("undo", {
- tooltip: "Undo",
- icon: "undo",
- disabled: true,
- onSetup: onSetupUndoRedoState(editor, "hasUndo"),
- onAction: onActionExecCommand(editor, "undo")
- });
- editor.ui.registry.addButton("redo", {
- tooltip: "Redo",
- icon: "redo",
- disabled: true,
- onSetup: onSetupUndoRedoState(editor, "hasRedo"),
- onAction: onActionExecCommand(editor, "redo")
- });
- };
- var register$1 = function(editor) {
- registerMenuItems$1(editor);
- registerButtons(editor);
- };
- var onSetupVisualAidState = function(editor) {
- return onSetupEvent(editor, "VisualAid", function(api2) {
- api2.setActive(editor.hasVisual);
- });
- };
- var registerMenuItems = function(editor) {
- editor.ui.registry.addToggleMenuItem("visualaid", {
- text: "Visual aids",
- onSetup: onSetupVisualAidState(editor),
- onAction: onActionExecCommand(editor, "mceToggleVisualAid")
- });
- };
- var registerToolbarButton = function(editor) {
- editor.ui.registry.addButton("visualaid", {
- tooltip: "Visual aids",
- text: "Visual aids",
- onAction: onActionExecCommand(editor, "mceToggleVisualAid")
- });
- };
- var register = function(editor) {
- registerToolbarButton(editor);
- registerMenuItems(editor);
- };
- var setup$6 = function(editor, backstage) {
- register$6(editor);
- register$2(editor);
- register$4(editor, backstage);
- register$1(editor);
- register$a(editor);
- register(editor);
- register$3(editor);
- register$5(editor);
- };
- var nu = function(x, y) {
- return {
- type: "makeshift",
- x,
- y
- };
- };
- var transpose = function(pos, dx, dy) {
- return nu(pos.x + dx, pos.y + dy);
- };
- var isTouchEvent = function(e) {
- return e.type === "longpress" || e.type.indexOf("touch") === 0;
- };
- var fromPageXY = function(e) {
- if (isTouchEvent(e)) {
- var touch2 = e.touches[0];
- return nu(touch2.pageX, touch2.pageY);
- } else {
- return nu(e.pageX, e.pageY);
- }
- };
- var fromClientXY = function(e) {
- if (isTouchEvent(e)) {
- var touch2 = e.touches[0];
- return nu(touch2.clientX, touch2.clientY);
- } else {
- return nu(e.clientX, e.clientY);
- }
- };
- var transposeContentAreaContainer = function(element2, pos) {
- var containerPos = global$b.DOM.getPos(element2);
- return transpose(pos, containerPos.x, containerPos.y);
- };
- var getPointAnchor = function(editor, e) {
- if (e.type === "contextmenu" || e.type === "longpress") {
- if (editor.inline) {
- return fromPageXY(e);
- } else {
- return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
- }
- } else {
- return getSelectionAnchor(editor);
- }
- };
- var getSelectionAnchor = function(editor) {
- return {
- type: "selection",
- root: SugarElement.fromDom(editor.selection.getNode())
- };
- };
- var getNodeAnchor = function(editor) {
- return {
- type: "node",
- node: Optional.some(SugarElement.fromDom(editor.selection.getNode())),
- root: SugarElement.fromDom(editor.getBody())
- };
- };
- var getAnchorSpec$1 = function(editor, e, anchorType) {
- switch (anchorType) {
- case "node":
- return getNodeAnchor(editor);
- case "point":
- return getPointAnchor(editor, e);
- case "selection":
- return getSelectionAnchor(editor);
- }
- };
- var initAndShow$1 = function(editor, e, buildMenu, backstage, contextmenu, anchorType) {
- var items = buildMenu();
- var anchorSpec = getAnchorSpec$1(editor, e, anchorType);
- build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function(menuData) {
- e.preventDefault();
- InlineView.showMenuAt(contextmenu, { anchor: anchorSpec }, {
- menu: { markers: markers("normal") },
- data: menuData
- });
- });
- };
- var layouts = {
- onLtr: function() {
- return [
- south$2,
- southeast$2,
- southwest$2,
- northeast$2,
- northwest$2,
- north$2,
- north,
- south,
- northeast,
- southeast,
- northwest,
- southwest
- ];
- },
- onRtl: function() {
- return [
- south$2,
- southwest$2,
- southeast$2,
- northwest$2,
- northeast$2,
- north$2,
- north,
- south,
- northwest,
- southwest,
- northeast,
- southeast
- ];
- }
- };
- var bubbleSize = 12;
- var bubbleAlignments = {
- valignCentre: [],
- alignCentre: [],
- alignLeft: ["tox-pop--align-left"],
- alignRight: ["tox-pop--align-right"],
- right: ["tox-pop--right"],
- left: ["tox-pop--left"],
- bottom: ["tox-pop--bottom"],
- top: ["tox-pop--top"]
- };
- var isTouchWithinSelection = function(editor, e) {
- var selection = editor.selection;
- if (selection.isCollapsed() || e.touches.length < 1) {
- return false;
- } else {
- var touch_1 = e.touches[0];
- var rng = selection.getRng();
- var rngRectOpt = getFirstRect(editor.getWin(), SimSelection.domRange(rng));
- return rngRectOpt.exists(function(rngRect) {
- return rngRect.left <= touch_1.clientX && rngRect.right >= touch_1.clientX && rngRect.top <= touch_1.clientY && rngRect.bottom >= touch_1.clientY;
- });
- }
- };
- var setupiOSOverrides = function(editor) {
- var originalSelection = editor.selection.getRng();
- var selectionReset = function() {
- global$f.setEditorTimeout(editor, function() {
- editor.selection.setRng(originalSelection);
- }, 10);
- unbindEventListeners();
- };
- editor.once("touchend", selectionReset);
- var preventMousedown = function(e) {
- e.preventDefault();
- e.stopImmediatePropagation();
- };
- editor.on("mousedown", preventMousedown, true);
- var clearSelectionReset = function() {
- return unbindEventListeners();
- };
- editor.once("longpresscancel", clearSelectionReset);
- var unbindEventListeners = function() {
- editor.off("touchend", selectionReset);
- editor.off("longpresscancel", clearSelectionReset);
- editor.off("mousedown", preventMousedown);
- };
- };
- var getAnchorSpec = function(editor, e, anchorType) {
- var anchorSpec = getAnchorSpec$1(editor, e, anchorType);
- var bubbleYOffset = anchorType === "point" ? bubbleSize : 0;
- return __assign({
- bubble: nu$5(0, bubbleYOffset, bubbleAlignments),
- layouts,
- overrides: {
- maxWidthFunction: expandable(),
- maxHeightFunction: expandable$1()
- }
- }, anchorSpec);
- };
- var show = function(editor, e, items, backstage, contextmenu, anchorType, highlightImmediately) {
- var anchorSpec = getAnchorSpec(editor, e, anchorType);
- build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function(menuData) {
- e.preventDefault();
- InlineView.showMenuWithinBounds(contextmenu, { anchor: anchorSpec }, {
- menu: {
- markers: markers("normal"),
- highlightImmediately
- },
- data: menuData,
- type: "horizontal"
- }, function() {
- return Optional.some(getContextToolbarBounds(editor, backstage.shared, anchorType === "node" ? "node" : "selection"));
- });
- editor.fire(hideContextToolbarEvent);
- });
- };
- var initAndShow = function(editor, e, buildMenu, backstage, contextmenu, anchorType) {
- var detection2 = detect$1();
- var isiOS = detection2.os.isiOS();
- var isOSX = detection2.os.isOSX();
- var isAndroid = detection2.os.isAndroid();
- var isTouch2 = detection2.deviceType.isTouch();
- var shouldHighlightImmediately = function() {
- return !(isAndroid || isiOS || isOSX && isTouch2);
- };
- var open2 = function() {
- var items = buildMenu();
- show(editor, e, items, backstage, contextmenu, anchorType, shouldHighlightImmediately());
- };
- if ((isOSX || isiOS) && anchorType !== "node") {
- var openiOS_1 = function() {
- setupiOSOverrides(editor);
- open2();
- };
- if (isTouchWithinSelection(editor, e)) {
- openiOS_1();
- } else {
- editor.once("selectionchange", openiOS_1);
- editor.once("touchend", function() {
- return editor.off("selectionchange", openiOS_1);
- });
- }
- } else {
- open2();
- }
- };
- var patchPipeConfig = function(config2) {
- return typeof config2 === "string" ? config2.split(/[ ,]/) : config2;
- };
- var shouldNeverUseNative = function(editor) {
- return editor.getParam("contextmenu_never_use_native", false, "boolean");
- };
- var getMenuItems = function(editor, name2, defaultItems) {
- var contextMenus = editor.ui.registry.getAll().contextMenus;
- return Optional.from(editor.getParam(name2)).map(patchPipeConfig).getOrThunk(function() {
- return filter$2(patchPipeConfig(defaultItems), function(item2) {
- return has$2(contextMenus, item2);
- });
- });
- };
- var isContextMenuDisabled = function(editor) {
- return editor.getParam("contextmenu") === false;
- };
- var getContextMenu = function(editor) {
- return getMenuItems(editor, "contextmenu", "link linkchecker image imagetools table spellchecker configurepermanentpen");
- };
- var getAvoidOverlapSelector = function(editor) {
- return editor.getParam("contextmenu_avoid_overlap", "", "string");
- };
- var isSeparator = function(item2) {
- return isString(item2) ? item2 === "|" : item2.type === "separator";
- };
- var separator = { type: "separator" };
- var makeContextItem = function(item2) {
- var commonMenuItem = function(item3) {
- return {
- text: item3.text,
- icon: item3.icon,
- disabled: item3.disabled,
- shortcut: item3.shortcut
- };
- };
- if (isString(item2)) {
- return item2;
- } else {
- switch (item2.type) {
- case "separator":
- return separator;
- case "submenu":
- return __assign(__assign({ type: "nestedmenuitem" }, commonMenuItem(item2)), {
- getSubmenuItems: function() {
- var items = item2.getSubmenuItems();
- if (isString(items)) {
- return items;
- } else {
- return map$2(items, makeContextItem);
- }
- }
- });
- default:
- return __assign(__assign({ type: "menuitem" }, commonMenuItem(item2)), { onAction: noarg(item2.onAction) });
- }
- }
- };
- var addContextMenuGroup = function(xs, groupItems) {
- if (groupItems.length === 0) {
- return xs;
- }
- var lastMenuItem = last$2(xs).filter(function(item2) {
- return !isSeparator(item2);
- });
- var before2 = lastMenuItem.fold(function() {
- return [];
- }, function(_) {
- return [separator];
- });
- return xs.concat(before2).concat(groupItems).concat([separator]);
- };
- var generateContextMenu = function(contextMenus, menuConfig, selectedElement) {
- var sections = foldl(menuConfig, function(acc, name2) {
- return get$e(contextMenus, name2.toLowerCase()).map(function(menu2) {
- var items = menu2.update(selectedElement);
- if (isString(items)) {
- return addContextMenuGroup(acc, items.split(" "));
- } else if (items.length > 0) {
- var allItems = map$2(items, makeContextItem);
- return addContextMenuGroup(acc, allItems);
- } else {
- return acc;
- }
- }).getOrThunk(function() {
- return acc.concat([name2]);
- });
- }, []);
- if (sections.length > 0 && isSeparator(sections[sections.length - 1])) {
- sections.pop();
- }
- return sections;
- };
- var isNativeOverrideKeyEvent = function(editor, e) {
- return e.ctrlKey && !shouldNeverUseNative(editor);
- };
- var isTriggeredByKeyboard = function(editor, e) {
- return e.type !== "longpress" && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === "");
- };
- var getSelectedElement = function(editor, e) {
- return isTriggeredByKeyboard(editor, e) ? editor.selection.getStart(true) : e.target;
- };
- var getAnchorType = function(editor, e) {
- var selector = getAvoidOverlapSelector(editor);
- var anchorType = isTriggeredByKeyboard(editor, e) ? "selection" : "point";
- if (isNotEmpty(selector)) {
- var target = getSelectedElement(editor, e);
- var selectorExists = closest(SugarElement.fromDom(target), selector);
- return selectorExists ? "node" : anchorType;
- } else {
- return anchorType;
- }
- };
- var setup$5 = function(editor, lazySink, backstage) {
- var detection2 = detect$1();
- var isTouch2 = detection2.deviceType.isTouch;
- var contextmenu = build$1(InlineView.sketch({
- dom: { tag: "div" },
- lazySink,
- onEscape: function() {
- return editor.focus();
- },
- onShow: function() {
- return backstage.setContextMenuState(true);
- },
- onHide: function() {
- return backstage.setContextMenuState(false);
- },
- fireDismissalEventInstead: {},
- inlineBehaviours: derive$1([config("dismissContextMenu", [run$1(dismissRequested(), function(comp, _se) {
- Sandboxing.close(comp);
- editor.focus();
- })])])
- }));
- var hideContextMenu = function(_e) {
- return InlineView.hide(contextmenu);
- };
- var showContextMenu = function(e) {
- if (shouldNeverUseNative(editor)) {
- e.preventDefault();
- }
- if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) {
- return;
- }
- var anchorType = getAnchorType(editor, e);
- var buildMenu = function() {
- var selectedElement = getSelectedElement(editor, e);
- var registry = editor.ui.registry.getAll();
- var menuConfig = getContextMenu(editor);
- return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
- };
- var initAndShow$2 = isTouch2() ? initAndShow : initAndShow$1;
- initAndShow$2(editor, e, buildMenu, backstage, contextmenu, anchorType);
- };
- editor.on("init", function() {
- var hideEvents = "ResizeEditor ScrollContent ScrollWindow longpresscancel" + (isTouch2() ? "" : " ResizeWindow");
- editor.on(hideEvents, hideContextMenu);
- editor.on("longpress contextmenu", showContextMenu);
- });
- };
- var adt = Adt.generate([
- {
- offset: [
- "x",
- "y"
- ]
- },
- {
- absolute: [
- "x",
- "y"
- ]
- },
- {
- fixed: [
- "x",
- "y"
- ]
- }
- ]);
- var subtract = function(change2) {
- return function(point2) {
- return point2.translate(-change2.left, -change2.top);
- };
- };
- var add = function(change2) {
- return function(point2) {
- return point2.translate(change2.left, change2.top);
- };
- };
- var transform = function(changes) {
- return function(x, y) {
- return foldl(changes, function(rest, f) {
- return f(rest);
- }, SugarPosition(x, y));
- };
- };
- var asFixed = function(coord, scroll, origin) {
- return coord.fold(transform([
- add(origin),
- subtract(scroll)
- ]), transform([subtract(scroll)]), transform([]));
- };
- var asAbsolute = function(coord, scroll, origin) {
- return coord.fold(transform([add(origin)]), transform([]), transform([add(scroll)]));
- };
- var asOffset = function(coord, scroll, origin) {
- return coord.fold(transform([]), transform([subtract(origin)]), transform([
- add(scroll),
- subtract(origin)
- ]));
- };
- var withinRange = function(coord1, coord2, xRange2, yRange2, scroll, origin) {
- var a1 = asAbsolute(coord1, scroll, origin);
- var a2 = asAbsolute(coord2, scroll, origin);
- return Math.abs(a1.left - a2.left) <= xRange2 && Math.abs(a1.top - a2.top) <= yRange2;
- };
- var getDeltas = function(coord1, coord2, xRange2, yRange2, scroll, origin) {
- var a1 = asAbsolute(coord1, scroll, origin);
- var a2 = asAbsolute(coord2, scroll, origin);
- var left2 = Math.abs(a1.left - a2.left);
- var top2 = Math.abs(a1.top - a2.top);
- return SugarPosition(left2, top2);
- };
- var toStyles = function(coord, scroll, origin) {
- var stylesOpt = coord.fold(function(x, y) {
- return {
- position: Optional.some("absolute"),
- left: Optional.some(x + "px"),
- top: Optional.some(y + "px")
- };
- }, function(x, y) {
- return {
- position: Optional.some("absolute"),
- left: Optional.some(x - origin.left + "px"),
- top: Optional.some(y - origin.top + "px")
- };
- }, function(x, y) {
- return {
- position: Optional.some("fixed"),
- left: Optional.some(x + "px"),
- top: Optional.some(y + "px")
- };
- });
- return __assign({
- right: Optional.none(),
- bottom: Optional.none()
- }, stylesOpt);
- };
- var translate = function(coord, deltaX, deltaY) {
- return coord.fold(function(x, y) {
- return offset(x + deltaX, y + deltaY);
- }, function(x, y) {
- return absolute(x + deltaX, y + deltaY);
- }, function(x, y) {
- return fixed(x + deltaX, y + deltaY);
- });
- };
- var absorb = function(partialCoord, originalCoord, scroll, origin) {
- var absorbOne = function(stencil, nu2) {
- return function(optX, optY) {
- var original2 = stencil(originalCoord, scroll, origin);
- return nu2(optX.getOr(original2.left), optY.getOr(original2.top));
- };
- };
- return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute), absorbOne(asFixed, fixed));
- };
- var offset = adt.offset;
- var absolute = adt.absolute;
- var fixed = adt.fixed;
- var parseAttrToInt = function(element2, name2) {
- var value2 = get$d(element2, name2);
- return isUndefined(value2) ? NaN : parseInt(value2, 10);
- };
- var get = function(component, snapsInfo) {
- var element2 = component.element;
- var x = parseAttrToInt(element2, snapsInfo.leftAttr);
- var y = parseAttrToInt(element2, snapsInfo.topAttr);
- return isNaN(x) || isNaN(y) ? Optional.none() : Optional.some(SugarPosition(x, y));
- };
- var set = function(component, snapsInfo, pt) {
- var element2 = component.element;
- set$8(element2, snapsInfo.leftAttr, pt.left + "px");
- set$8(element2, snapsInfo.topAttr, pt.top + "px");
- };
- var clear = function(component, snapsInfo) {
- var element2 = component.element;
- remove$7(element2, snapsInfo.leftAttr);
- remove$7(element2, snapsInfo.topAttr);
- };
- var getCoords = function(component, snapInfo, coord, delta) {
- return get(component, snapInfo).fold(function() {
- return coord;
- }, function(fixed$12) {
- return fixed(fixed$12.left + delta.left, fixed$12.top + delta.top);
- });
- };
- var moveOrSnap = function(component, snapInfo, coord, delta, scroll, origin) {
- var newCoord = getCoords(component, snapInfo, coord, delta);
- var snap2 = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
- var fixedCoord = asFixed(newCoord, scroll, origin);
- set(component, snapInfo, fixedCoord);
- return snap2.fold(function() {
- return {
- coord: fixed(fixedCoord.left, fixedCoord.top),
- extra: Optional.none()
- };
- }, function(spanned) {
- return {
- coord: spanned.output,
- extra: spanned.extra
- };
- });
- };
- var stopDrag = function(component, snapInfo) {
- clear(component, snapInfo);
- };
- var findMatchingSnap = function(snaps, newCoord, scroll, origin) {
- return findMap(snaps, function(snap2) {
- var sensor = snap2.sensor;
- var inRange = withinRange(newCoord, sensor, snap2.range.left, snap2.range.top, scroll, origin);
- return inRange ? Optional.some({
- output: absorb(snap2.output, newCoord, scroll, origin),
- extra: snap2.extra
- }) : Optional.none();
- });
- };
- var findClosestSnap = function(component, snapInfo, newCoord, scroll, origin) {
- var snaps = snapInfo.getSnapPoints(component);
- var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
- return matchSnap.orThunk(function() {
- var bestSnap = foldl(snaps, function(acc, snap2) {
- var sensor = snap2.sensor;
- var deltas = getDeltas(newCoord, sensor, snap2.range.left, snap2.range.top, scroll, origin);
- return acc.deltas.fold(function() {
- return {
- deltas: Optional.some(deltas),
- snap: Optional.some(snap2)
- };
- }, function(bestDeltas) {
- var currAvg = (deltas.left + deltas.top) / 2;
- var bestAvg = (bestDeltas.left + bestDeltas.top) / 2;
- if (currAvg <= bestAvg) {
- return {
- deltas: Optional.some(deltas),
- snap: Optional.some(snap2)
- };
- } else {
- return acc;
- }
- });
- }, {
- deltas: Optional.none(),
- snap: Optional.none()
- });
- return bestSnap.snap.map(function(snap2) {
- return {
- output: absorb(snap2.output, newCoord, scroll, origin),
- extra: snap2.extra
- };
- });
- });
- };
- var findSnap = function(component, snapInfo, newCoord, scroll, origin) {
- var snaps = snapInfo.getSnapPoints(component);
- return findMatchingSnap(snaps, newCoord, scroll, origin);
- };
- var snapTo$1 = function(snap2, scroll, origin) {
- return {
- coord: absorb(snap2.output, snap2.output, scroll, origin),
- extra: snap2.extra
- };
- };
- var snapTo = function(component, dragConfig, _state, snap2) {
- var target = dragConfig.getTarget(component.element);
- if (dragConfig.repositionTarget) {
- var doc = owner$4(component.element);
- var scroll_1 = get$9(doc);
- var origin_1 = getOrigin(target);
- var snapPin = snapTo$1(snap2, scroll_1, origin_1);
- var styles = toStyles(snapPin.coord, scroll_1, origin_1);
- setOptions(target, styles);
- }
- };
- var DraggingApis = Object.freeze({
- __proto__: null,
- snapTo
- });
- var initialAttribute = "data-initial-z-index";
- var resetZIndex = function(blocker) {
- parent(blocker.element).filter(isElement$2).each(function(root) {
- getOpt(root, initialAttribute).fold(function() {
- return remove$6(root, "z-index");
- }, function(zIndex) {
- return set$7(root, "z-index", zIndex);
- });
- remove$7(root, initialAttribute);
- });
- };
- var changeZIndex = function(blocker) {
- parent(blocker.element).filter(isElement$2).each(function(root) {
- getRaw(root, "z-index").each(function(zindex) {
- set$8(root, initialAttribute, zindex);
- });
- set$7(root, "z-index", get$c(blocker.element, "z-index"));
- });
- };
- var instigate = function(anyComponent, blocker) {
- anyComponent.getSystem().addToGui(blocker);
- changeZIndex(blocker);
- };
- var discard = function(blocker) {
- resetZIndex(blocker);
- blocker.getSystem().removeFromGui(blocker);
- };
- var createComponent = function(component, blockerClass, blockerEvents) {
- return component.getSystem().build(Container.sketch({
- dom: {
- styles: {
- "left": "0px",
- "top": "0px",
- "width": "100%",
- "height": "100%",
- "position": "fixed",
- "z-index": "1000000000000000"
- },
- classes: [blockerClass]
- },
- events: blockerEvents
- }));
- };
- var SnapSchema = optionObjOf("snaps", [
- required$1("getSnapPoints"),
- onHandler("onSensor"),
- required$1("leftAttr"),
- required$1("topAttr"),
- defaulted("lazyViewport", win),
- defaulted("mustSnap", false)
- ]);
- var schema$6 = [
- defaulted("useFixed", never),
- required$1("blockerClass"),
- defaulted("getTarget", identity$1),
- defaulted("onDrag", noop),
- defaulted("repositionTarget", true),
- defaulted("onDrop", noop),
- defaultedFunction("getBounds", win),
- SnapSchema
- ];
- var getCurrentCoord = function(target) {
- return lift3(getRaw(target, "left"), getRaw(target, "top"), getRaw(target, "position"), function(left2, top2, position2) {
- var nu2 = position2 === "fixed" ? fixed : offset;
- return nu2(parseInt(left2, 10), parseInt(top2, 10));
- }).getOrThunk(function() {
- var location = absolute$3(target);
- return absolute(location.left, location.top);
- });
- };
- var clampCoords = function(component, coords, scroll, origin, startData) {
- var bounds2 = startData.bounds;
- var absoluteCoord = asAbsolute(coords, scroll, origin);
- var newX = clamp$1(absoluteCoord.left, bounds2.x, bounds2.x + bounds2.width - startData.width);
- var newY = clamp$1(absoluteCoord.top, bounds2.y, bounds2.y + bounds2.height - startData.height);
- var newCoords = absolute(newX, newY);
- return coords.fold(function() {
- var offset$1 = asOffset(newCoords, scroll, origin);
- return offset(offset$1.left, offset$1.top);
- }, constant$1(newCoords), function() {
- var fixed$12 = asFixed(newCoords, scroll, origin);
- return fixed(fixed$12.left, fixed$12.top);
- });
- };
- var calcNewCoord = function(component, optSnaps, currentCoord, scroll, origin, delta, startData) {
- var newCoord = optSnaps.fold(function() {
- var translated = translate(currentCoord, delta.left, delta.top);
- var fixedCoord = asFixed(translated, scroll, origin);
- return fixed(fixedCoord.left, fixedCoord.top);
- }, function(snapInfo) {
- var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
- snapping.extra.each(function(extra) {
- snapInfo.onSensor(component, extra);
- });
- return snapping.coord;
- });
- return clampCoords(component, newCoord, scroll, origin, startData);
- };
- var dragBy = function(component, dragConfig, startData, delta) {
- var target = dragConfig.getTarget(component.element);
- if (dragConfig.repositionTarget) {
- var doc = owner$4(component.element);
- var scroll_1 = get$9(doc);
- var origin_1 = getOrigin(target);
- var currentCoord = getCurrentCoord(target);
- var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll_1, origin_1, delta, startData);
- var styles = toStyles(newCoord, scroll_1, origin_1);
- setOptions(target, styles);
- }
- dragConfig.onDrag(component, target, delta);
- };
- var calcStartData = function(dragConfig, comp) {
- return {
- bounds: dragConfig.getBounds(),
- height: getOuter$2(comp.element),
- width: getOuter$1(comp.element)
- };
- };
- var move = function(component, dragConfig, dragState, dragMode, event) {
- var delta = dragState.update(dragMode, event);
- var dragStartData = dragState.getStartData().getOrThunk(function() {
- return calcStartData(dragConfig, component);
- });
- delta.each(function(dlt) {
- dragBy(component, dragConfig, dragStartData, dlt);
- });
- };
- var stop = function(component, blocker, dragConfig, dragState) {
- blocker.each(discard);
- dragConfig.snaps.each(function(snapInfo) {
- stopDrag(component, snapInfo);
- });
- var target = dragConfig.getTarget(component.element);
- dragState.reset();
- dragConfig.onDrop(component, target);
- };
- var handlers = function(events2) {
- return function(dragConfig, dragState) {
- var updateStartState = function(comp) {
- dragState.setStartData(calcStartData(dragConfig, comp));
- };
- return derive$2(__spreadArray([run$1(windowScroll(), function(comp) {
- dragState.getStartData().each(function() {
- return updateStartState(comp);
- });
- })], events2(dragConfig, dragState, updateStartState), true));
- };
- };
- var init$2 = function(dragApi) {
- return derive$2([
- run$1(mousedown(), dragApi.forceDrop),
- run$1(mouseup(), dragApi.drop),
- run$1(mousemove(), function(comp, simulatedEvent) {
- dragApi.move(simulatedEvent.event);
- }),
- run$1(mouseout(), dragApi.delayDrop)
- ]);
- };
- var getData$1 = function(event) {
- return Optional.from(SugarPosition(event.x, event.y));
- };
- var getDelta$1 = function(old, nu2) {
- return SugarPosition(nu2.left - old.left, nu2.top - old.top);
- };
- var MouseData = Object.freeze({
- __proto__: null,
- getData: getData$1,
- getDelta: getDelta$1
- });
- var events$2 = function(dragConfig, dragState, updateStartState) {
- return [run$1(mousedown(), function(component, simulatedEvent) {
- var raw = simulatedEvent.event.raw;
- if (raw.button !== 0) {
- return;
- }
- simulatedEvent.stop();
- var stop$1 = function() {
- return stop(component, Optional.some(blocker), dragConfig, dragState);
- };
- var delayDrop = DelayedFunction(stop$1, 200);
- var dragApi = {
- drop: stop$1,
- delayDrop: delayDrop.schedule,
- forceDrop: stop$1,
- move: function(event) {
- delayDrop.cancel();
- move(component, dragConfig, dragState, MouseData, event);
- }
- };
- var blocker = createComponent(component, dragConfig.blockerClass, init$2(dragApi));
- var start = function() {
- updateStartState(component);
- instigate(component, blocker);
- };
- start();
- })];
- };
- var schema$5 = __spreadArray(__spreadArray([], schema$6, true), [output$1("dragger", { handlers: handlers(events$2) })], false);
- var init$1 = function(dragApi) {
- return derive$2([
- run$1(touchstart(), dragApi.forceDrop),
- run$1(touchend(), dragApi.drop),
- run$1(touchcancel(), dragApi.drop),
- run$1(touchmove(), function(comp, simulatedEvent) {
- dragApi.move(simulatedEvent.event);
- })
- ]);
- };
- var getDataFrom = function(touches) {
- var touch2 = touches[0];
- return Optional.some(SugarPosition(touch2.clientX, touch2.clientY));
- };
- var getData = function(event) {
- var raw = event.raw;
- var touches = raw.touches;
- return touches.length === 1 ? getDataFrom(touches) : Optional.none();
- };
- var getDelta = function(old, nu2) {
- return SugarPosition(nu2.left - old.left, nu2.top - old.top);
- };
- var TouchData = Object.freeze({
- __proto__: null,
- getData,
- getDelta
- });
- var events$1 = function(dragConfig, dragState, updateStartState) {
- var blockerSingleton = value$1();
- var stopBlocking = function(component) {
- stop(component, blockerSingleton.get(), dragConfig, dragState);
- blockerSingleton.clear();
- };
- return [
- run$1(touchstart(), function(component, simulatedEvent) {
- simulatedEvent.stop();
- var stop2 = function() {
- return stopBlocking(component);
- };
- var dragApi = {
- drop: stop2,
- delayDrop: noop,
- forceDrop: stop2,
- move: function(event) {
- move(component, dragConfig, dragState, TouchData, event);
- }
- };
- var blocker = createComponent(component, dragConfig.blockerClass, init$1(dragApi));
- blockerSingleton.set(blocker);
- var start = function() {
- updateStartState(component);
- instigate(component, blocker);
- };
- start();
- }),
- run$1(touchmove(), function(component, simulatedEvent) {
- simulatedEvent.stop();
- move(component, dragConfig, dragState, TouchData, simulatedEvent.event);
- }),
- run$1(touchend(), function(component, simulatedEvent) {
- simulatedEvent.stop();
- stopBlocking(component);
- }),
- run$1(touchcancel(), stopBlocking)
- ];
- };
- var schema$4 = __spreadArray(__spreadArray([], schema$6, true), [output$1("dragger", { handlers: handlers(events$1) })], false);
- var events = function(dragConfig, dragState, updateStartState) {
- return __spreadArray(__spreadArray([], events$2(dragConfig, dragState, updateStartState), true), events$1(dragConfig, dragState, updateStartState), true);
- };
- var schema$3 = __spreadArray(__spreadArray([], schema$6, true), [output$1("dragger", { handlers: handlers(events) })], false);
- var mouse = schema$5;
- var touch = schema$4;
- var mouseOrTouch = schema$3;
- var DraggingBranches = Object.freeze({
- __proto__: null,
- mouse,
- touch,
- mouseOrTouch
- });
- var init = function() {
- var previous = Optional.none();
- var startData = Optional.none();
- var reset2 = function() {
- previous = Optional.none();
- startData = Optional.none();
- };
- var calculateDelta = function(mode, nu2) {
- var result = previous.map(function(old) {
- return mode.getDelta(old, nu2);
- });
- previous = Optional.some(nu2);
- return result;
- };
- var update = function(mode, dragEvent) {
- return mode.getData(dragEvent).bind(function(nuData) {
- return calculateDelta(mode, nuData);
- });
- };
- var setStartData = function(data) {
- startData = Optional.some(data);
- };
- var getStartData = function() {
- return startData;
- };
- var readState = constant$1({});
- return nu$8({
- readState,
- reset: reset2,
- update,
- getStartData,
- setStartData
- });
- };
- var DragState = Object.freeze({
- __proto__: null,
- init
- });
- var Dragging = createModes({
- branchKey: "mode",
- branches: DraggingBranches,
- name: "dragging",
- active: {
- events: function(dragConfig, dragState) {
- var dragger = dragConfig.dragger;
- return dragger.handlers(dragConfig, dragState);
- }
- },
- extra: {
- snap: function(sConfig) {
- return {
- sensor: sConfig.sensor,
- range: sConfig.range,
- output: sConfig.output,
- extra: Optional.from(sConfig.extra)
- };
- }
- },
- state: DragState,
- apis: DraggingApis
- });
- var snapWidth = 40;
- var snapOffset = snapWidth / 2;
- var calcSnap = function(selectorOpt, td, x, y, width2, height2) {
- return selectorOpt.fold(function() {
- return Dragging.snap({
- sensor: absolute(x - snapOffset, y - snapOffset),
- range: SugarPosition(width2, height2),
- output: absolute(Optional.some(x), Optional.some(y)),
- extra: { td }
- });
- }, function(selectorHandle) {
- var sensorLeft = x - snapOffset;
- var sensorTop = y - snapOffset;
- var sensorWidth = snapWidth;
- var sensorHeight = snapWidth;
- var rect2 = selectorHandle.element.dom.getBoundingClientRect();
- return Dragging.snap({
- sensor: absolute(sensorLeft, sensorTop),
- range: SugarPosition(sensorWidth, sensorHeight),
- output: absolute(Optional.some(x - rect2.width / 2), Optional.some(y - rect2.height / 2)),
- extra: { td }
- });
- });
- };
- var getSnapsConfig = function(getSnapPoints, cell, onChange) {
- var isSameCell = function(cellOpt, td) {
- return cellOpt.exists(function(currentTd) {
- return eq(currentTd, td);
- });
- };
- return {
- getSnapPoints,
- leftAttr: "data-drag-left",
- topAttr: "data-drag-top",
- onSensor: function(component, extra) {
- var td = extra.td;
- if (!isSameCell(cell.get(), td)) {
- cell.set(td);
- onChange(td);
- }
- },
- mustSnap: true
- };
- };
- var createSelector = function(snaps) {
- return record(Button.sketch({
- dom: {
- tag: "div",
- classes: ["tox-selector"]
- },
- buttonBehaviours: derive$1([
- Dragging.config({
- mode: "mouseOrTouch",
- blockerClass: "blocker",
- snaps
- }),
- Unselecting.config({})
- ]),
- eventOrder: {
- mousedown: [
- "dragging",
- "alloy.base.behaviour"
- ],
- touchstart: [
- "dragging",
- "alloy.base.behaviour"
- ]
- }
- }));
- };
- var setup$4 = function(editor, sink) {
- var tlTds = Cell([]);
- var brTds = Cell([]);
- var isVisible2 = Cell(false);
- var startCell = value$1();
- var finishCell = value$1();
- var getTopLeftSnap = function(td) {
- var box2 = absolute$2(td);
- return calcSnap(memTopLeft.getOpt(sink), td, box2.x, box2.y, box2.width, box2.height);
- };
- var getTopLeftSnaps = function() {
- return map$2(tlTds.get(), function(td) {
- return getTopLeftSnap(td);
- });
- };
- var getBottomRightSnap = function(td) {
- var box2 = absolute$2(td);
- return calcSnap(memBottomRight.getOpt(sink), td, box2.right, box2.bottom, box2.width, box2.height);
- };
- var getBottomRightSnaps = function() {
- return map$2(brTds.get(), function(td) {
- return getBottomRightSnap(td);
- });
- };
- var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function(start) {
- finishCell.get().each(function(finish) {
- editor.fire("TableSelectorChange", {
- start,
- finish
- });
- });
- });
- var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function(finish) {
- startCell.get().each(function(start) {
- editor.fire("TableSelectorChange", {
- start,
- finish
- });
- });
- });
- var memTopLeft = createSelector(topLeftSnaps);
- var memBottomRight = createSelector(bottomRightSnaps);
- var topLeft = build$1(memTopLeft.asSpec());
- var bottomRight = build$1(memBottomRight.asSpec());
- var showOrHideHandle = function(selector, cell, isAbove, isBelow) {
- var cellRect = cell.dom.getBoundingClientRect();
- remove$6(selector.element, "display");
- var viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight;
- var aboveViewport = isAbove(cellRect);
- var belowViewport = isBelow(cellRect, viewportHeight);
- if (aboveViewport || belowViewport) {
- set$7(selector.element, "display", "none");
- }
- };
- var snapTo2 = function(selector, cell, getSnapConfig, pos) {
- var snap2 = getSnapConfig(cell);
- Dragging.snapTo(selector, snap2);
- var isAbove = function(rect2) {
- return rect2[pos] < 0;
- };
- var isBelow = function(rect2, viewportHeight) {
- return rect2[pos] > viewportHeight;
- };
- showOrHideHandle(selector, cell, isAbove, isBelow);
- };
- var snapTopLeft = function(cell) {
- return snapTo2(topLeft, cell, getTopLeftSnap, "top");
- };
- var snapLastTopLeft = function() {
- return startCell.get().each(snapTopLeft);
- };
- var snapBottomRight = function(cell) {
- return snapTo2(bottomRight, cell, getBottomRightSnap, "bottom");
- };
- var snapLastBottomRight = function() {
- return finishCell.get().each(snapBottomRight);
- };
- if (detect$1().deviceType.isTouch()) {
- editor.on("TableSelectionChange", function(e) {
- if (!isVisible2.get()) {
- attach(sink, topLeft);
- attach(sink, bottomRight);
- isVisible2.set(true);
- }
- startCell.set(e.start);
- finishCell.set(e.finish);
- e.otherCells.each(function(otherCells) {
- tlTds.set(otherCells.upOrLeftCells);
- brTds.set(otherCells.downOrRightCells);
- snapTopLeft(e.start);
- snapBottomRight(e.finish);
- });
- });
- editor.on("ResizeEditor ResizeWindow ScrollContent", function() {
- snapLastTopLeft();
- snapLastBottomRight();
- });
- editor.on("TableSelectionClear", function() {
- if (isVisible2.get()) {
- detach(topLeft);
- detach(bottomRight);
- isVisible2.set(false);
- }
- startCell.clear();
- finishCell.clear();
- });
- }
- };
- var isHidden = function(elm) {
- if (elm.nodeType === 1) {
- if (elm.nodeName === "BR" || !!elm.getAttribute("data-mce-bogus")) {
- return true;
- }
- if (elm.getAttribute("data-mce-type") === "bookmark") {
- return true;
- }
- }
- return false;
- };
- var renderElementPath = function(editor, settings, providersBackstage) {
- if (!settings.delimiter) {
- settings.delimiter = "»";
- }
- var getDataPath = function(data) {
- var parts2 = data || [];
- var newPathElements = map$2(parts2, function(part2, index) {
- return Button.sketch({
- dom: {
- tag: "div",
- classes: ["tox-statusbar__path-item"],
- attributes: {
- "role": "button",
- "data-index": index,
- "tab-index": -1,
- "aria-level": index + 1
- },
- innerHtml: part2.name
- },
- action: function(_btn) {
- editor.focus();
- editor.selection.select(part2.element);
- editor.nodeChanged();
- },
- buttonBehaviours: derive$1([
- DisablingConfigs.button(providersBackstage.isDisabled),
- receivingConfig()
- ])
- });
- });
- var divider = {
- dom: {
- tag: "div",
- classes: ["tox-statusbar__path-divider"],
- attributes: { "aria-hidden": true },
- innerHtml: " " + settings.delimiter + " "
- }
- };
- return foldl(newPathElements.slice(1), function(acc, element2) {
- var newAcc = acc;
- newAcc.push(divider);
- newAcc.push(element2);
- return newAcc;
- }, [newPathElements[0]]);
- };
- var updatePath = function(parents) {
- var newPath = [];
- var i = parents.length;
- while (i-- > 0) {
- var parent_1 = parents[i];
- if (parent_1.nodeType === 1 && !isHidden(parent_1)) {
- var args = editor.fire("ResolveName", {
- name: parent_1.nodeName.toLowerCase(),
- target: parent_1
- });
- if (!args.isDefaultPrevented()) {
- newPath.push({
- name: args.name,
- element: parent_1
- });
- }
- if (args.isPropagationStopped()) {
- break;
- }
- }
- }
- return newPath;
- };
- return {
- dom: {
- tag: "div",
- classes: ["tox-statusbar__path"],
- attributes: { role: "navigation" }
- },
- behaviours: derive$1([
- Keying.config({
- mode: "flow",
- selector: "div[role=button]"
- }),
- Disabling.config({ disabled: providersBackstage.isDisabled }),
- receivingConfig(),
- Tabstopping.config({}),
- Replacing.config({}),
- config("elementPathEvents", [runOnAttached(function(comp, _e) {
- editor.shortcuts.add("alt+F11", "focus statusbar elementpath", function() {
- return Keying.focusIn(comp);
- });
- editor.on("NodeChange", function(e) {
- var newPath = updatePath(e.parents);
- if (newPath.length > 0) {
- Replacing.set(comp, getDataPath(newPath));
- } else {
- Replacing.set(comp, []);
- }
- });
- })])
- ]),
- components: []
- };
- };
- var ResizeTypes;
- (function(ResizeTypes2) {
- ResizeTypes2[ResizeTypes2["None"] = 0] = "None";
- ResizeTypes2[ResizeTypes2["Both"] = 1] = "Both";
- ResizeTypes2[ResizeTypes2["Vertical"] = 2] = "Vertical";
- })(ResizeTypes || (ResizeTypes = {}));
- var getDimensions = function(editor, deltas, resizeType, originalHeight, originalWidth) {
- var dimensions = {};
- dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightSetting(editor), getMaxHeightSetting(editor));
- if (resizeType === ResizeTypes.Both) {
- dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthSetting(editor), getMaxWidthSetting(editor));
- }
- return dimensions;
- };
- var resize = function(editor, deltas, resizeType) {
- var container = SugarElement.fromDom(editor.getContainer());
- var dimensions = getDimensions(editor, deltas, resizeType, get$b(container), get$a(container));
- each(dimensions, function(val, dim) {
- return set$7(container, dim, numToPx(val));
- });
- fireResizeEditor(editor);
- };
- var getResizeType = function(editor) {
- var fallback2 = !editor.hasPlugin("autoresize");
- var resize2 = editor.getParam("resize", fallback2);
- if (resize2 === false) {
- return ResizeTypes.None;
- } else if (resize2 === "both") {
- return ResizeTypes.Both;
- } else {
- return ResizeTypes.Vertical;
- }
- };
- var keyboardHandler = function(editor, resizeType, x, y) {
- var scale2 = 20;
- var delta = SugarPosition(x * scale2, y * scale2);
- resize(editor, delta, resizeType);
- return Optional.some(true);
- };
- var renderResizeHandler = function(editor, providersBackstage) {
- var resizeType = getResizeType(editor);
- if (resizeType === ResizeTypes.None) {
- return Optional.none();
- }
- return Optional.some(render$3("resize-handle", {
- tag: "div",
- classes: ["tox-statusbar__resize-handle"],
- attributes: { title: providersBackstage.translate("Resize") },
- behaviours: [
- Dragging.config({
- mode: "mouse",
- repositionTarget: false,
- onDrag: function(_comp, _target, delta) {
- return resize(editor, delta, resizeType);
- },
- blockerClass: "tox-blocker"
- }),
- Keying.config({
- mode: "special",
- onLeft: function() {
- return keyboardHandler(editor, resizeType, -1, 0);
- },
- onRight: function() {
- return keyboardHandler(editor, resizeType, 1, 0);
- },
- onUp: function() {
- return keyboardHandler(editor, resizeType, 0, -1);
- },
- onDown: function() {
- return keyboardHandler(editor, resizeType, 0, 1);
- }
- }),
- Tabstopping.config({}),
- Focusing.config({})
- ]
- }, providersBackstage.icons));
- };
- var renderWordCount = function(editor, providersBackstage) {
- var _a2;
- var replaceCountText = function(comp, count2, mode) {
- return Replacing.set(comp, [text$1(providersBackstage.translate([
- "{0} " + mode,
- count2[mode]
- ]))]);
- };
- return Button.sketch({
- dom: {
- tag: "button",
- classes: ["tox-statusbar__wordcount"]
- },
- components: [],
- buttonBehaviours: derive$1([
- DisablingConfigs.button(providersBackstage.isDisabled),
- receivingConfig(),
- Tabstopping.config({}),
- Replacing.config({}),
- Representing.config({
- store: {
- mode: "memory",
- initialValue: {
- mode: "words",
- count: {
- words: 0,
- characters: 0
- }
- }
- }
- }),
- config("wordcount-events", [
- runOnExecute$1(function(comp) {
- var currentVal = Representing.getValue(comp);
- var newMode = currentVal.mode === "words" ? "characters" : "words";
- Representing.setValue(comp, {
- mode: newMode,
- count: currentVal.count
- });
- replaceCountText(comp, currentVal.count, newMode);
- }),
- runOnAttached(function(comp) {
- editor.on("wordCountUpdate", function(e) {
- var mode = Representing.getValue(comp).mode;
- Representing.setValue(comp, {
- mode,
- count: e.wordCount
- });
- replaceCountText(comp, e.wordCount, mode);
- });
- })
- ])
- ]),
- eventOrder: (_a2 = {}, _a2[execute$5()] = [
- "disabling",
- "alloy.base.behaviour",
- "wordcount-events"
- ], _a2)
- });
- };
- var renderStatusbar = function(editor, providersBackstage) {
- var renderBranding = function() {
- var label = global$e.translate([
- "Powered by {0}",
- "Tiny"
- ]);
- var linkHtml = '<a href="https://www.tiny.cloud/?utm_campaign=editor_referral&utm_medium=poweredby&utm_source=tinymce&utm_content=v5" rel="noopener" target="_blank" tabindex="-1" aria-label="' + label + '">' + label + "</a>";
- return {
- dom: {
- tag: "span",
- classes: ["tox-statusbar__branding"],
- innerHtml: linkHtml
- }
- };
- };
- var getTextComponents = function() {
- var components2 = [];
- if (editor.getParam("elementpath", true, "boolean")) {
- components2.push(renderElementPath(editor, {}, providersBackstage));
- }
- if (editor.hasPlugin("wordcount")) {
- components2.push(renderWordCount(editor, providersBackstage));
- }
- if (editor.getParam("branding", true, "boolean")) {
- components2.push(renderBranding());
- }
- if (components2.length > 0) {
- return [{
- dom: {
- tag: "div",
- classes: ["tox-statusbar__text-container"]
- },
- components: components2
- }];
- }
- return [];
- };
- var getComponents = function() {
- var components2 = getTextComponents();
- var resizeHandler = renderResizeHandler(editor, providersBackstage);
- return components2.concat(resizeHandler.toArray());
- };
- return {
- dom: {
- tag: "div",
- classes: ["tox-statusbar"]
- },
- components: getComponents()
- };
- };
- var setup$3 = function(editor) {
- var _a2;
- var isInline = editor.inline;
- var mode = isInline ? Inline : Iframe;
- var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
- var lazyOuterContainer = Optional.none();
- var platform2 = detect$1();
- var isIE = platform2.browser.isIE();
- var platformClasses = isIE ? ["tox-platform-ie"] : [];
- var isTouch2 = platform2.deviceType.isTouch();
- var touchPlatformClass = "tox-platform-touch";
- var deviceClasses = isTouch2 ? [touchPlatformClass] : [];
- var isToolbarBottom = isToolbarLocationBottom(editor);
- var uiContainer = getUiContainer(editor);
- var dirAttributes = global$e.isRtl() ? { attributes: { dir: "rtl" } } : {};
- var verticalDirAttributes = { attributes: (_a2 = {}, _a2[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a2) };
- var lazyHeader = function() {
- return lazyOuterContainer.bind(OuterContainer.getHeader);
- };
- var isHeaderDocked = function() {
- return header.isDocked(lazyHeader);
- };
- var resizeUiMothership = function() {
- set$7(uiMothership.element, "width", document.body.clientWidth + "px");
- };
- var makeSinkDefinition = function() {
- var isGridUiContainer = eq(body(), uiContainer) && get$c(uiContainer, "display") === "grid";
- var sinkSpec = {
- dom: __assign({
- tag: "div",
- classes: [
- "tox",
- "tox-silver-sink",
- "tox-tinymce-aux"
- ].concat(platformClasses).concat(deviceClasses)
- }, dirAttributes),
- behaviours: derive$1([Positioning.config({
- useFixed: function() {
- return isHeaderDocked();
- }
- })])
- };
- var reactiveWidthSpec = {
- dom: { styles: { width: document.body.clientWidth + "px" } },
- events: derive$2([run$1(windowResize(), resizeUiMothership)])
- };
- return deepMerge(sinkSpec, isGridUiContainer ? reactiveWidthSpec : {});
- };
- var sink = build$1(makeSinkDefinition());
- var lazySink = function() {
- return Result.value(sink);
- };
- var memAnchorBar = record({
- dom: {
- tag: "div",
- classes: ["tox-anchorbar"]
- }
- });
- var lazyAnchorBar = function() {
- return lazyOuterContainer.bind(function(container) {
- return memAnchorBar.getOpt(container);
- }).getOrDie("Could not find a anchor bar element");
- };
- var lazyToolbar = function() {
- return lazyOuterContainer.bind(function(container) {
- return OuterContainer.getToolbar(container);
- }).getOrDie("Could not find more toolbar element");
- };
- var lazyThrobber = function() {
- return lazyOuterContainer.bind(function(container) {
- return OuterContainer.getThrobber(container);
- }).getOrDie("Could not find throbber element");
- };
- var backstage = init$7(sink, editor, lazyAnchorBar);
- var partMenubar2 = OuterContainer.parts.menubar({
- dom: {
- tag: "div",
- classes: ["tox-menubar"]
- },
- backstage,
- onEscape: function() {
- editor.focus();
- }
- });
- var toolbarMode = getToolbarMode(editor);
- var partToolbar2 = OuterContainer.parts.toolbar(__assign({
- dom: {
- tag: "div",
- classes: ["tox-toolbar"]
- },
- getSink: lazySink,
- providers: backstage.shared.providers,
- onEscape: function() {
- editor.focus();
- },
- type: toolbarMode,
- lazyToolbar,
- lazyHeader: function() {
- return lazyHeader().getOrDie("Could not find header element");
- }
- }, verticalDirAttributes));
- var partMultipleToolbar2 = OuterContainer.parts["multiple-toolbar"]({
- dom: {
- tag: "div",
- classes: ["tox-toolbar-overlord"]
- },
- providers: backstage.shared.providers,
- onEscape: function() {
- editor.focus();
- },
- type: toolbarMode
- });
- var partSocket2 = OuterContainer.parts.socket({
- dom: {
- tag: "div",
- classes: ["tox-edit-area"]
- }
- });
- var partSidebar2 = OuterContainer.parts.sidebar({
- dom: {
- tag: "div",
- classes: ["tox-sidebar"]
- }
- });
- var partThrobber2 = OuterContainer.parts.throbber({
- dom: {
- tag: "div",
- classes: ["tox-throbber"]
- },
- backstage
- });
- var sb = editor.getParam("statusbar", true, "boolean");
- var statusbar = sb && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none();
- var socketSidebarContainer = {
- dom: {
- tag: "div",
- classes: ["tox-sidebar-wrap"]
- },
- components: [
- partSocket2,
- partSidebar2
- ]
- };
- var hasMultipleToolbar = isMultipleToolbars(editor);
- var hasToolbar = isToolbarEnabled(editor);
- var hasMenubar = isMenubarEnabled(editor);
- var getPartToolbar = function() {
- if (hasMultipleToolbar) {
- return [partMultipleToolbar2];
- } else if (hasToolbar) {
- return [partToolbar2];
- } else {
- return [];
- }
- };
- var partHeader2 = OuterContainer.parts.header({
- dom: __assign({
- tag: "div",
- classes: ["tox-editor-header"]
- }, verticalDirAttributes),
- components: flatten([
- hasMenubar ? [partMenubar2] : [],
- getPartToolbar(),
- useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
- ]),
- sticky: isStickyToolbar(editor),
- editor,
- sharedBackstage: backstage.shared
- });
- var editorComponents = flatten([
- isToolbarBottom ? [] : [partHeader2],
- isInline ? [] : [socketSidebarContainer],
- isToolbarBottom ? [partHeader2] : []
- ]);
- var editorContainer = {
- dom: {
- tag: "div",
- classes: ["tox-editor-container"]
- },
- components: editorComponents
- };
- var containerComponents = flatten([
- [editorContainer],
- isInline ? [] : statusbar.toArray(),
- [partThrobber2]
- ]);
- var isHidden2 = isDistractionFree(editor);
- var attributes = __assign(__assign({ role: "application" }, global$e.isRtl() ? { dir: "rtl" } : {}), isHidden2 ? { "aria-hidden": "true" } : {});
- var outerContainer = build$1(OuterContainer.sketch({
- dom: {
- tag: "div",
- classes: [
- "tox",
- "tox-tinymce"
- ].concat(isInline ? ["tox-tinymce-inline"] : []).concat(isToolbarBottom ? ["tox-tinymce--toolbar-bottom"] : []).concat(deviceClasses).concat(platformClasses),
- styles: __assign({ visibility: "hidden" }, isHidden2 ? {
- opacity: "0",
- border: "0"
- } : {}),
- attributes
- },
- components: containerComponents,
- behaviours: derive$1([
- receivingConfig(),
- Disabling.config({ disableClass: "tox-tinymce--disabled" }),
- Keying.config({
- mode: "cyclic",
- selector: ".tox-menubar, .tox-toolbar, .tox-toolbar__primary, .tox-toolbar__overflow--open, .tox-sidebar__overflow--open, .tox-statusbar__path, .tox-statusbar__wordcount, .tox-statusbar__branding a, .tox-statusbar__resize-handle"
- })
- ])
- }));
- lazyOuterContainer = Optional.some(outerContainer);
- editor.shortcuts.add("alt+F9", "focus menubar", function() {
- OuterContainer.focusMenubar(outerContainer);
- });
- editor.shortcuts.add("alt+F10", "focus toolbar", function() {
- OuterContainer.focusToolbar(outerContainer);
- });
- editor.addCommand("ToggleToolbarDrawer", function() {
- OuterContainer.toggleToolbarDrawer(outerContainer);
- });
- editor.addQueryStateHandler("ToggleToolbarDrawer", function() {
- return OuterContainer.isToolbarDrawerToggled(outerContainer);
- });
- var mothership = takeover(outerContainer);
- var uiMothership = takeover(sink);
- setup$b(editor, mothership, uiMothership);
- var getUi = function() {
- var channels = {
- broadcastAll: uiMothership.broadcast,
- broadcastOn: uiMothership.broadcastOn,
- register: noop
- };
- return { channels };
- };
- var setEditorSize = function() {
- var parsedHeight = numToPx(getHeightWithFallback(editor));
- var parsedWidth = numToPx(getWidthWithFallback(editor));
- if (!editor.inline) {
- if (isValidValue("div", "width", parsedWidth)) {
- set$7(outerContainer.element, "width", parsedWidth);
- }
- if (isValidValue("div", "height", parsedHeight)) {
- set$7(outerContainer.element, "height", parsedHeight);
- } else {
- set$7(outerContainer.element, "height", "200px");
- }
- }
- return parsedHeight;
- };
- var renderUI = function() {
- header.setup(editor, backstage.shared, lazyHeader);
- setup$6(editor, backstage);
- setup$5(editor, lazySink, backstage);
- setup$8(editor);
- setup$7(editor, lazyThrobber, backstage.shared);
- map$1(getToolbarGroups(editor), function(toolbarGroupButtonConfig, name2) {
- editor.ui.registry.addGroupToolbarButton(name2, toolbarGroupButtonConfig);
- });
- var _a3 = editor.ui.registry.getAll(), buttons = _a3.buttons, menuItems = _a3.menuItems, contextToolbars = _a3.contextToolbars, sidebars = _a3.sidebars;
- var toolbarOpt = getMultipleToolbarsSetting(editor);
- var rawUiConfig = {
- menuItems,
- menus: getMenus(editor),
- menubar: getMenubar(editor),
- toolbar: toolbarOpt.getOrThunk(function() {
- return getToolbar(editor);
- }),
- allowToolbarGroups: toolbarMode === ToolbarMode.floating,
- buttons,
- sidebar: sidebars
- };
- register$7(editor, contextToolbars, sink, { backstage });
- setup$4(editor, sink);
- var elm = editor.getElement();
- var height2 = setEditorSize();
- var uiComponents = {
- mothership,
- uiMothership,
- outerContainer
- };
- var args = {
- targetNode: elm,
- height: height2
- };
- return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
- };
- return {
- mothership,
- uiMothership,
- backstage,
- renderUI,
- getUi
- };
- };
- var describedBy = function(describedElement, describeElement) {
- var describeId = Optional.from(get$d(describedElement, "id")).fold(function() {
- var id = generate$6("dialog-describe");
- set$8(describeElement, "id", id);
- return id;
- }, identity$1);
- set$8(describedElement, "aria-describedby", describeId);
- };
- var labelledBy = function(labelledElement, labelElement) {
- var labelId = getOpt(labelledElement, "id").fold(function() {
- var id = generate$6("dialog-label");
- set$8(labelElement, "id", id);
- return id;
- }, identity$1);
- set$8(labelledElement, "aria-labelledby", labelId);
- };
- var schema$2 = constant$1([
- required$1("lazySink"),
- option("dragBlockClass"),
- defaultedFunction("getBounds", win),
- defaulted("useTabstopAt", always),
- defaulted("eventOrder", {}),
- field("modalBehaviours", [Keying]),
- onKeyboardHandler("onExecute"),
- onStrictKeyboardHandler("onEscape")
- ]);
- var basic = { sketch: identity$1 };
- var parts$2 = constant$1([
- optional({
- name: "draghandle",
- overrides: function(detail, spec) {
- return {
- behaviours: derive$1([Dragging.config({
- mode: "mouse",
- getTarget: function(handle2) {
- return ancestor(handle2, '[role="dialog"]').getOr(handle2);
- },
- blockerClass: detail.dragBlockClass.getOrDie(new Error("The drag blocker class was not specified for a dialog with a drag handle: \n" + JSON.stringify(spec, null, 2)).message),
- getBounds: detail.getDragBounds
- })])
- };
- }
- }),
- required({
- schema: [required$1("dom")],
- name: "title"
- }),
- required({
- factory: basic,
- schema: [required$1("dom")],
- name: "close"
- }),
- required({
- factory: basic,
- schema: [required$1("dom")],
- name: "body"
- }),
- optional({
- factory: basic,
- schema: [required$1("dom")],
- name: "footer"
- }),
- external$1({
- factory: {
- sketch: function(spec, detail) {
- return __assign(__assign({}, spec), {
- dom: detail.dom,
- components: detail.components
- });
- }
- },
- schema: [
- defaulted("dom", {
- tag: "div",
- styles: {
- position: "fixed",
- left: "0px",
- top: "0px",
- right: "0px",
- bottom: "0px"
- }
- }),
- defaulted("components", [])
- ],
- name: "blocker"
- })
- ]);
- var factory$4 = function(detail, components2, spec, externals) {
- var _a2;
- var dialogComp = value$1();
- var showDialog = function(dialog) {
- dialogComp.set(dialog);
- var sink = detail.lazySink(dialog).getOrDie();
- var externalBlocker = externals.blocker();
- var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
- components: externalBlocker.components.concat([premade(dialog)]),
- behaviours: derive$1([
- Focusing.config({}),
- config("dialog-blocker-events", [runOnSource(focusin(), function() {
- Keying.focusIn(dialog);
- })])
- ])
- }));
- attach(sink, blocker);
- Keying.focusIn(dialog);
- };
- var hideDialog = function(dialog) {
- dialogComp.clear();
- parent(dialog.element).each(function(blockerDom) {
- dialog.getSystem().getByDom(blockerDom).each(function(blocker) {
- detach(blocker);
- });
- });
- };
- var getDialogBody = function(dialog) {
- return getPartOrDie(dialog, detail, "body");
- };
- var getDialogFooter = function(dialog) {
- return getPartOrDie(dialog, detail, "footer");
- };
- var setBusy = function(dialog, getBusySpec2) {
- Blocking.block(dialog, getBusySpec2);
- };
- var setIdle = function(dialog) {
- Blocking.unblock(dialog);
- };
- var modalEventsId = generate$6("modal-events");
- var eventOrder = __assign(__assign({}, detail.eventOrder), (_a2 = {}, _a2[attachedToDom()] = [modalEventsId].concat(detail.eventOrder["alloy.system.attached"] || []), _a2));
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- apis: {
- show: showDialog,
- hide: hideDialog,
- getBody: getDialogBody,
- getFooter: getDialogFooter,
- setIdle,
- setBusy
- },
- eventOrder,
- domModification: {
- attributes: {
- "role": "dialog",
- "aria-modal": "true"
- }
- },
- behaviours: augment(detail.modalBehaviours, [
- Replacing.config({}),
- Keying.config({
- mode: "cyclic",
- onEnter: detail.onExecute,
- onEscape: detail.onEscape,
- useTabstopAt: detail.useTabstopAt
- }),
- Blocking.config({ getRoot: dialogComp.get }),
- config(modalEventsId, [runOnAttached(function(c) {
- labelledBy(c.element, getPartOrDie(c, detail, "title").element);
- describedBy(c.element, getPartOrDie(c, detail, "body").element);
- })])
- ])
- };
- };
- var ModalDialog = composite({
- name: "ModalDialog",
- configFields: schema$2(),
- partFields: parts$2(),
- factory: factory$4,
- apis: {
- show: function(apis, dialog) {
- apis.show(dialog);
- },
- hide: function(apis, dialog) {
- apis.hide(dialog);
- },
- getBody: function(apis, dialog) {
- return apis.getBody(dialog);
- },
- getFooter: function(apis, dialog) {
- return apis.getFooter(dialog);
- },
- setBusy: function(apis, dialog, getBusySpec2) {
- apis.setBusy(dialog, getBusySpec2);
- },
- setIdle: function(apis, dialog) {
- apis.setIdle(dialog);
- }
- }
- });
- var dialogToggleMenuItemSchema = objOf([
- requiredString("type"),
- requiredString("name")
- ].concat(commonMenuItemFields));
- var dialogToggleMenuItemDataProcessor = boolean;
- var baseFooterButtonFields = [
- field$1("name", "name", defaultedThunk(function() {
- return generate$6("button-name");
- }), string),
- optionString("icon"),
- defaultedStringEnum("align", "end", [
- "start",
- "end"
- ]),
- defaultedBoolean("primary", false),
- defaultedBoolean("disabled", false)
- ];
- var dialogFooterButtonFields = __spreadArray(__spreadArray([], baseFooterButtonFields, true), [requiredString("text")], false);
- var normalFooterButtonFields = __spreadArray([requiredStringEnum("type", [
- "submit",
- "cancel",
- "custom"
- ])], dialogFooterButtonFields, true);
- var menuFooterButtonFields = __spreadArray([
- requiredStringEnum("type", ["menu"]),
- optionString("text"),
- optionString("tooltip"),
- optionString("icon"),
- requiredArrayOf("items", dialogToggleMenuItemSchema)
- ], baseFooterButtonFields, true);
- var dialogFooterButtonSchema = choose$1("type", {
- submit: normalFooterButtonFields,
- cancel: normalFooterButtonFields,
- custom: normalFooterButtonFields,
- menu: menuFooterButtonFields
- });
- var alertBannerFields = [
- requiredString("type"),
- requiredString("text"),
- requiredStringEnum("level", [
- "info",
- "warn",
- "error",
- "success"
- ]),
- requiredString("icon"),
- defaulted("url", "")
- ];
- var alertBannerSchema = objOf(alertBannerFields);
- var createBarFields = function(itemsField) {
- return [
- requiredString("type"),
- itemsField
- ];
- };
- var buttonFields = [
- requiredString("type"),
- requiredString("text"),
- defaultedBoolean("disabled", false),
- defaultedBoolean("primary", false),
- field$1("name", "name", defaultedThunk(function() {
- return generate$6("button-name");
- }), string),
- optionString("icon"),
- defaultedBoolean("borderless", false)
- ];
- var buttonSchema = objOf(buttonFields);
- var checkboxFields = [
- requiredString("type"),
- requiredString("name"),
- requiredString("label"),
- defaultedBoolean("disabled", false)
- ];
- var checkboxSchema = objOf(checkboxFields);
- var checkboxDataProcessor = boolean;
- var formComponentFields = [
- requiredString("type"),
- requiredString("name")
- ];
- var formComponentWithLabelFields = formComponentFields.concat([optionString("label")]);
- var collectionFields = formComponentWithLabelFields.concat([defaulted("columns", "auto")]);
- var collectionSchema = objOf(collectionFields);
- var collectionDataProcessor = arrOfObj([
- requiredString("value"),
- requiredString("text"),
- requiredString("icon")
- ]);
- var colorInputFields = formComponentWithLabelFields;
- var colorInputSchema = objOf(colorInputFields);
- var colorInputDataProcessor = string;
- var colorPickerFields = formComponentWithLabelFields;
- var colorPickerSchema = objOf(colorPickerFields);
- var colorPickerDataProcessor = string;
- var customEditorFields = formComponentFields.concat([
- defaultedString("tag", "textarea"),
- requiredString("scriptId"),
- requiredString("scriptUrl"),
- defaultedPostMsg("settings", void 0)
- ]);
- var customEditorFieldsOld = formComponentFields.concat([
- defaultedString("tag", "textarea"),
- requiredFunction("init")
- ]);
- var customEditorSchema = valueOf(function(v) {
- return asRaw("customeditor.old", objOfOnly(customEditorFieldsOld), v).orThunk(function() {
- return asRaw("customeditor.new", objOfOnly(customEditorFields), v);
- });
- });
- var customEditorDataProcessor = string;
- var dropZoneFields = formComponentWithLabelFields;
- var dropZoneSchema = objOf(dropZoneFields);
- var dropZoneDataProcessor = arrOfVal();
- var createGridFields = function(itemsField) {
- return [
- requiredString("type"),
- requiredNumber("columns"),
- itemsField
- ];
- };
- var htmlPanelFields = [
- requiredString("type"),
- requiredString("html"),
- defaultedStringEnum("presets", "presentation", [
- "presentation",
- "document"
- ])
- ];
- var htmlPanelSchema = objOf(htmlPanelFields);
- var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean("sandboxed", true)]);
- var iframeSchema = objOf(iframeFields);
- var iframeDataProcessor = string;
- var imageToolsFields = formComponentWithLabelFields.concat([requiredOf("currentState", objOf([
- required$1("blob"),
- requiredString("url")
- ]))]);
- var imageToolsSchema = objOf(imageToolsFields);
- var inputFields = formComponentWithLabelFields.concat([
- optionString("inputMode"),
- optionString("placeholder"),
- defaultedBoolean("maximized", false),
- defaultedBoolean("disabled", false)
- ]);
- var inputSchema = objOf(inputFields);
- var inputDataProcessor = string;
- var createLabelFields = function(itemsField) {
- return [
- requiredString("type"),
- requiredString("label"),
- itemsField
- ];
- };
- var listBoxSingleItemFields = [
- requiredString("text"),
- requiredString("value")
- ];
- var listBoxNestedItemFields = [
- requiredString("text"),
- requiredArrayOf("items", thunkOf("items", function() {
- return listBoxItemSchema;
- }))
- ];
- var listBoxItemSchema = oneOf([
- objOf(listBoxSingleItemFields),
- objOf(listBoxNestedItemFields)
- ]);
- var listBoxFields = formComponentWithLabelFields.concat([
- requiredArrayOf("items", listBoxItemSchema),
- defaultedBoolean("disabled", false)
- ]);
- var listBoxSchema = objOf(listBoxFields);
- var listBoxDataProcessor = string;
- var selectBoxFields = formComponentWithLabelFields.concat([
- requiredArrayOfObj("items", [
- requiredString("text"),
- requiredString("value")
- ]),
- defaultedNumber("size", 1),
- defaultedBoolean("disabled", false)
- ]);
- var selectBoxSchema = objOf(selectBoxFields);
- var selectBoxDataProcessor = string;
- var sizeInputFields = formComponentWithLabelFields.concat([
- defaultedBoolean("constrain", true),
- defaultedBoolean("disabled", false)
- ]);
- var sizeInputSchema = objOf(sizeInputFields);
- var sizeInputDataProcessor = objOf([
- requiredString("width"),
- requiredString("height")
- ]);
- var tableFields = [
- requiredString("type"),
- requiredArrayOf("header", string),
- requiredArrayOf("cells", arrOf(string))
- ];
- var tableSchema = objOf(tableFields);
- var textAreaFields = formComponentWithLabelFields.concat([
- optionString("placeholder"),
- defaultedBoolean("maximized", false),
- defaultedBoolean("disabled", false)
- ]);
- var textAreaSchema = objOf(textAreaFields);
- var textAreaDataProcessor = string;
- var urlInputFields = formComponentWithLabelFields.concat([
- defaultedStringEnum("filetype", "file", [
- "image",
- "media",
- "file"
- ]),
- defaulted("disabled", false)
- ]);
- var urlInputSchema = objOf(urlInputFields);
- var urlInputDataProcessor = objOf([
- requiredString("value"),
- defaulted("meta", {})
- ]);
- var createItemsField = function(name2) {
- return field$1("items", "items", required$2(), arrOf(valueOf(function(v) {
- return asRaw("Checking item of " + name2, itemSchema, v).fold(function(sErr) {
- return Result.error(formatError(sErr));
- }, function(passValue) {
- return Result.value(passValue);
- });
- })));
- };
- var itemSchema = valueThunk(function() {
- return choose$2("type", {
- alertbanner: alertBannerSchema,
- bar: objOf(createBarFields(createItemsField("bar"))),
- button: buttonSchema,
- checkbox: checkboxSchema,
- colorinput: colorInputSchema,
- colorpicker: colorPickerSchema,
- dropzone: dropZoneSchema,
- grid: objOf(createGridFields(createItemsField("grid"))),
- iframe: iframeSchema,
- input: inputSchema,
- listbox: listBoxSchema,
- selectbox: selectBoxSchema,
- sizeinput: sizeInputSchema,
- textarea: textAreaSchema,
- urlinput: urlInputSchema,
- customeditor: customEditorSchema,
- htmlpanel: htmlPanelSchema,
- imagetools: imageToolsSchema,
- collection: collectionSchema,
- label: objOf(createLabelFields(createItemsField("label"))),
- table: tableSchema,
- panel: panelSchema
- });
- });
- var panelFields = [
- requiredString("type"),
- defaulted("classes", []),
- requiredArrayOf("items", itemSchema)
- ];
- var panelSchema = objOf(panelFields);
- var tabFields = [
- field$1("name", "name", defaultedThunk(function() {
- return generate$6("tab-name");
- }), string),
- requiredString("title"),
- requiredArrayOf("items", itemSchema)
- ];
- var tabPanelFields = [
- requiredString("type"),
- requiredArrayOfObj("tabs", tabFields)
- ];
- var tabPanelSchema = objOf(tabPanelFields);
- var dialogButtonFields = dialogFooterButtonFields;
- var dialogButtonSchema = dialogFooterButtonSchema;
- var dialogSchema = objOf([
- requiredString("title"),
- requiredOf("body", choose$2("type", {
- panel: panelSchema,
- tabpanel: tabPanelSchema
- })),
- defaultedString("size", "normal"),
- requiredArrayOf("buttons", dialogButtonSchema),
- defaulted("initialData", {}),
- defaultedFunction("onAction", noop),
- defaultedFunction("onChange", noop),
- defaultedFunction("onSubmit", noop),
- defaultedFunction("onClose", noop),
- defaultedFunction("onCancel", noop),
- defaulted("onTabChange", noop)
- ]);
- var createDialog = function(spec) {
- return asRaw("dialog", dialogSchema, spec);
- };
- var urlDialogButtonSchema = objOf(__spreadArray([requiredStringEnum("type", [
- "cancel",
- "custom"
- ])], dialogButtonFields, true));
- var urlDialogSchema = objOf([
- requiredString("title"),
- requiredString("url"),
- optionNumber("height"),
- optionNumber("width"),
- optionArrayOf("buttons", urlDialogButtonSchema),
- defaultedFunction("onAction", noop),
- defaultedFunction("onCancel", noop),
- defaultedFunction("onClose", noop),
- defaultedFunction("onMessage", noop)
- ]);
- var createUrlDialog = function(spec) {
- return asRaw("dialog", urlDialogSchema, spec);
- };
- var getAllObjects = function(obj) {
- if (isObject(obj)) {
- return [obj].concat(bind$3(values(obj), getAllObjects));
- } else if (isArray(obj)) {
- return bind$3(obj, getAllObjects);
- } else {
- return [];
- }
- };
- var isNamedItem = function(obj) {
- return isString(obj.type) && isString(obj.name);
- };
- var dataProcessors = {
- checkbox: checkboxDataProcessor,
- colorinput: colorInputDataProcessor,
- colorpicker: colorPickerDataProcessor,
- dropzone: dropZoneDataProcessor,
- input: inputDataProcessor,
- iframe: iframeDataProcessor,
- sizeinput: sizeInputDataProcessor,
- selectbox: selectBoxDataProcessor,
- listbox: listBoxDataProcessor,
- size: sizeInputDataProcessor,
- textarea: textAreaDataProcessor,
- urlinput: urlInputDataProcessor,
- customeditor: customEditorDataProcessor,
- collection: collectionDataProcessor,
- togglemenuitem: dialogToggleMenuItemDataProcessor
- };
- var getDataProcessor = function(item2) {
- return Optional.from(dataProcessors[item2.type]);
- };
- var getNamedItems = function(structure) {
- return filter$2(getAllObjects(structure), isNamedItem);
- };
- var createDataValidator = function(structure) {
- var namedItems = getNamedItems(structure);
- var fields = bind$3(namedItems, function(item2) {
- return getDataProcessor(item2).fold(function() {
- return [];
- }, function(schema2) {
- return [requiredOf(item2.name, schema2)];
- });
- });
- return objOf(fields);
- };
- var extract = function(structure) {
- var internalDialog = getOrDie(createDialog(structure));
- var dataValidator = createDataValidator(structure);
- var initialData = structure.initialData;
- return {
- internalDialog,
- dataValidator,
- initialData
- };
- };
- var DialogManager = {
- open: function(factory2, structure) {
- var extraction = extract(structure);
- return factory2(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
- },
- openUrl: function(factory2, structure) {
- var internalDialog = getOrDie(createUrlDialog(structure));
- return factory2(internalDialog);
- },
- redial: function(structure) {
- return extract(structure);
- }
- };
- var toValidValues = function(values2) {
- var errors = [];
- var result = {};
- each(values2, function(value2, name2) {
- value2.fold(function() {
- errors.push(name2);
- }, function(v) {
- result[name2] = v;
- });
- });
- return errors.length > 0 ? Result.error(errors) : Result.value(result);
- };
- var renderBodyPanel = function(spec, backstage) {
- var memForm = record(Form.sketch(function(parts2) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-form"].concat(spec.classes)
- },
- components: map$2(spec.items, function(item2) {
- return interpretInForm(parts2, item2, backstage);
- })
- };
- }));
- return {
- dom: {
- tag: "div",
- classes: ["tox-dialog__body"]
- },
- components: [{
- dom: {
- tag: "div",
- classes: ["tox-dialog__body-content"]
- },
- components: [memForm.asSpec()]
- }],
- behaviours: derive$1([
- Keying.config({
- mode: "acyclic",
- useTabstopAt: not(isPseudoStop)
- }),
- ComposingConfigs.memento(memForm),
- RepresentingConfigs.memento(memForm, {
- postprocess: function(formValue) {
- return toValidValues(formValue).fold(function(err) {
- console.error(err);
- return {};
- }, identity$1);
- }
- })
- ])
- };
- };
- var factory$3 = function(detail, _spec) {
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: detail.components,
- events: events$a(detail.action),
- behaviours: augment(detail.tabButtonBehaviours, [
- Focusing.config({}),
- Keying.config({
- mode: "execution",
- useSpace: true,
- useEnter: true
- }),
- Representing.config({
- store: {
- mode: "memory",
- initialValue: detail.value
- }
- })
- ]),
- domModification: detail.domModification
- };
- };
- var TabButton = single({
- name: "TabButton",
- configFields: [
- defaulted("uid", void 0),
- required$1("value"),
- field$1("dom", "dom", mergeWithThunk(function() {
- return {
- attributes: {
- "role": "tab",
- "id": generate$6("aria"),
- "aria-selected": "false"
- }
- };
- }), anyValue()),
- option("action"),
- defaulted("domModification", {}),
- field("tabButtonBehaviours", [
- Focusing,
- Keying,
- Representing
- ]),
- required$1("view")
- ],
- factory: factory$3
- });
- var schema$1 = constant$1([
- required$1("tabs"),
- required$1("dom"),
- defaulted("clickToDismiss", false),
- field("tabbarBehaviours", [
- Highlighting,
- Keying
- ]),
- markers$1([
- "tabClass",
- "selectedClass"
- ])
- ]);
- var tabsPart = group({
- factory: TabButton,
- name: "tabs",
- unit: "tab",
- overrides: function(barDetail) {
- var dismissTab$1 = function(tabbar, button2) {
- Highlighting.dehighlight(tabbar, button2);
- emitWith(tabbar, dismissTab(), {
- tabbar,
- button: button2
- });
- };
- var changeTab$1 = function(tabbar, button2) {
- Highlighting.highlight(tabbar, button2);
- emitWith(tabbar, changeTab(), {
- tabbar,
- button: button2
- });
- };
- return {
- action: function(button2) {
- var tabbar = button2.getSystem().getByUid(barDetail.uid).getOrDie();
- var activeButton = Highlighting.isHighlighted(tabbar, button2);
- var response = function() {
- if (activeButton && barDetail.clickToDismiss) {
- return dismissTab$1;
- } else if (!activeButton) {
- return changeTab$1;
- } else {
- return noop;
- }
- }();
- response(tabbar, button2);
- },
- domModification: { classes: [barDetail.markers.tabClass] }
- };
- }
- });
- var parts$1 = constant$1([tabsPart]);
- var factory$2 = function(detail, components2, _spec, _externals) {
- return {
- "uid": detail.uid,
- "dom": detail.dom,
- components: components2,
- "debug.sketcher": "Tabbar",
- "domModification": { attributes: { role: "tablist" } },
- "behaviours": augment(detail.tabbarBehaviours, [
- Highlighting.config({
- highlightClass: detail.markers.selectedClass,
- itemClass: detail.markers.tabClass,
- onHighlight: function(tabbar, tab) {
- set$8(tab.element, "aria-selected", "true");
- },
- onDehighlight: function(tabbar, tab) {
- set$8(tab.element, "aria-selected", "false");
- }
- }),
- Keying.config({
- mode: "flow",
- getInitial: function(tabbar) {
- return Highlighting.getHighlighted(tabbar).map(function(tab) {
- return tab.element;
- });
- },
- selector: "." + detail.markers.tabClass,
- executeOnMove: true
- })
- ])
- };
- };
- var Tabbar = composite({
- name: "Tabbar",
- configFields: schema$1(),
- partFields: parts$1(),
- factory: factory$2
- });
- var factory$1 = function(detail, _spec) {
- return {
- uid: detail.uid,
- dom: detail.dom,
- behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
- domModification: { attributes: { role: "tabpanel" } }
- };
- };
- var Tabview = single({
- name: "Tabview",
- configFields: [field("tabviewBehaviours", [Replacing])],
- factory: factory$1
- });
- var schema = constant$1([
- defaulted("selectFirst", true),
- onHandler("onChangeTab"),
- onHandler("onDismissTab"),
- defaulted("tabs", []),
- field("tabSectionBehaviours", [])
- ]);
- var barPart = required({
- factory: Tabbar,
- schema: [
- required$1("dom"),
- requiredObjOf("markers", [
- required$1("tabClass"),
- required$1("selectedClass")
- ])
- ],
- name: "tabbar",
- defaults: function(detail) {
- return { tabs: detail.tabs };
- }
- });
- var viewPart = required({
- factory: Tabview,
- name: "tabview"
- });
- var parts = constant$1([
- barPart,
- viewPart
- ]);
- var factory = function(detail, components2, _spec, _externals) {
- var changeTab$1 = function(button2) {
- var tabValue = Representing.getValue(button2);
- getPart(button2, detail, "tabview").each(function(tabview) {
- var tabWithValue = find$5(detail.tabs, function(t2) {
- return t2.value === tabValue;
- });
- tabWithValue.each(function(tabData) {
- var panel = tabData.view();
- getOpt(button2.element, "id").each(function(id) {
- set$8(tabview.element, "aria-labelledby", id);
- });
- Replacing.set(tabview, panel);
- detail.onChangeTab(tabview, button2, panel);
- });
- });
- };
- var changeTabBy = function(section, byPred) {
- getPart(section, detail, "tabbar").each(function(tabbar) {
- byPred(tabbar).each(emitExecute);
- });
- };
- return {
- uid: detail.uid,
- dom: detail.dom,
- components: components2,
- behaviours: get$2(detail.tabSectionBehaviours),
- events: derive$2(flatten([
- detail.selectFirst ? [runOnAttached(function(section, _simulatedEvent) {
- changeTabBy(section, Highlighting.getFirst);
- })] : [],
- [
- run$1(changeTab(), function(section, simulatedEvent) {
- var button2 = simulatedEvent.event.button;
- changeTab$1(button2);
- }),
- run$1(dismissTab(), function(section, simulatedEvent) {
- var button2 = simulatedEvent.event.button;
- detail.onDismissTab(section, button2);
- })
- ]
- ])),
- apis: {
- getViewItems: function(section) {
- return getPart(section, detail, "tabview").map(function(tabview) {
- return Replacing.contents(tabview);
- }).getOr([]);
- },
- showTab: function(section, tabKey) {
- var getTabIfNotActive = function(tabbar) {
- var candidates = Highlighting.getCandidates(tabbar);
- var optTab = find$5(candidates, function(c) {
- return Representing.getValue(c) === tabKey;
- });
- return optTab.filter(function(tab) {
- return !Highlighting.isHighlighted(tabbar, tab);
- });
- };
- changeTabBy(section, getTabIfNotActive);
- }
- }
- };
- };
- var TabSection = composite({
- name: "TabSection",
- configFields: schema(),
- partFields: parts(),
- factory,
- apis: {
- getViewItems: function(apis, component) {
- return apis.getViewItems(component);
- },
- showTab: function(apis, component, tabKey) {
- apis.showTab(component, tabKey);
- }
- }
- });
- var measureHeights = function(allTabs, tabview, tabviewComp) {
- return map$2(allTabs, function(_tab, i) {
- Replacing.set(tabviewComp, allTabs[i].view());
- var rect2 = tabview.dom.getBoundingClientRect();
- Replacing.set(tabviewComp, []);
- return rect2.height;
- });
- };
- var getMaxHeight = function(heights) {
- return head(sort(heights, function(a, b2) {
- if (a > b2) {
- return -1;
- } else if (a < b2) {
- return 1;
- } else {
- return 0;
- }
- }));
- };
- var getMaxTabviewHeight = function(dialog, tabview, tablist) {
- var documentElement$1 = documentElement(dialog).dom;
- var rootElm = ancestor(dialog, ".tox-dialog-wrap").getOr(dialog);
- var isFixed = get$c(rootElm, "position") === "fixed";
- var maxHeight;
- if (isFixed) {
- maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight);
- } else {
- maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
- }
- var tabviewHeight = get$b(tabview);
- var isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$a(tablist);
- var currentTabHeight = isTabListBeside ? Math.max(get$b(tablist), tabviewHeight) : tabviewHeight;
- var dialogTopMargin = parseInt(get$c(dialog, "margin-top"), 10) || 0;
- var dialogBottomMargin = parseInt(get$c(dialog, "margin-bottom"), 10) || 0;
- var dialogHeight = get$b(dialog) + dialogTopMargin + dialogBottomMargin;
- var chromeHeight = dialogHeight - currentTabHeight;
- return maxHeight - chromeHeight;
- };
- var showTab = function(allTabs, comp) {
- head(allTabs).each(function(tab) {
- return TabSection.showTab(comp, tab.value);
- });
- };
- var setTabviewHeight = function(tabview, height2) {
- set$7(tabview, "height", height2 + "px");
- if (!detect$1().browser.isIE()) {
- set$7(tabview, "flex-basis", height2 + "px");
- } else {
- remove$6(tabview, "flex-basis");
- }
- };
- var updateTabviewHeight = function(dialogBody, tabview, maxTabHeight) {
- ancestor(dialogBody, '[role="dialog"]').each(function(dialog) {
- descendant(dialog, '[role="tablist"]').each(function(tablist) {
- maxTabHeight.get().map(function(height2) {
- set$7(tabview, "height", "0");
- set$7(tabview, "flex-basis", "0");
- return Math.min(height2, getMaxTabviewHeight(dialog, tabview, tablist));
- }).each(function(height2) {
- setTabviewHeight(tabview, height2);
- });
- });
- });
- };
- var getTabview = function(dialog) {
- return descendant(dialog, '[role="tabpanel"]');
- };
- var setMode = function(allTabs) {
- var smartTabHeight = function() {
- var maxTabHeight = value$1();
- var extraEvents = [
- runOnAttached(function(comp) {
- var dialog = comp.element;
- getTabview(dialog).each(function(tabview) {
- set$7(tabview, "visibility", "hidden");
- comp.getSystem().getByDom(tabview).toOptional().each(function(tabviewComp) {
- var heights = measureHeights(allTabs, tabview, tabviewComp);
- var maxTabHeightOpt = getMaxHeight(heights);
- maxTabHeightOpt.fold(maxTabHeight.clear, maxTabHeight.set);
- });
- updateTabviewHeight(dialog, tabview, maxTabHeight);
- remove$6(tabview, "visibility");
- showTab(allTabs, comp);
- global$f.requestAnimationFrame(function() {
- updateTabviewHeight(dialog, tabview, maxTabHeight);
- });
- });
- }),
- run$1(windowResize(), function(comp) {
- var dialog = comp.element;
- getTabview(dialog).each(function(tabview) {
- updateTabviewHeight(dialog, tabview, maxTabHeight);
- });
- }),
- run$1(formResizeEvent, function(comp, _se) {
- var dialog = comp.element;
- getTabview(dialog).each(function(tabview) {
- var oldFocus = active(getRootNode(tabview));
- set$7(tabview, "visibility", "hidden");
- var oldHeight = getRaw(tabview, "height").map(function(h) {
- return parseInt(h, 10);
- });
- remove$6(tabview, "height");
- remove$6(tabview, "flex-basis");
- var newHeight = tabview.dom.getBoundingClientRect().height;
- var hasGrown2 = oldHeight.forall(function(h) {
- return newHeight > h;
- });
- if (hasGrown2) {
- maxTabHeight.set(newHeight);
- updateTabviewHeight(dialog, tabview, maxTabHeight);
- } else {
- oldHeight.each(function(h) {
- setTabviewHeight(tabview, h);
- });
- }
- remove$6(tabview, "visibility");
- oldFocus.each(focus$3);
- });
- })
- ];
- var selectFirst = false;
- return {
- extraEvents,
- selectFirst
- };
- }();
- var naiveTabHeight = function() {
- var extraEvents = [];
- var selectFirst = true;
- return {
- extraEvents,
- selectFirst
- };
- }();
- return {
- smartTabHeight,
- naiveTabHeight
- };
- };
- var SendDataToSectionChannel = "send-data-to-section";
- var SendDataToViewChannel = "send-data-to-view";
- var renderTabPanel = function(spec, backstage) {
- var storedValue = Cell({});
- var updateDataWithForm = function(form) {
- var formData = Representing.getValue(form);
- var validData = toValidValues(formData).getOr({});
- var currentData = storedValue.get();
- var newData = deepMerge(currentData, validData);
- storedValue.set(newData);
- };
- var setDataOnForm = function(form) {
- var tabData = storedValue.get();
- Representing.setValue(form, tabData);
- };
- var oldTab = Cell(null);
- var allTabs = map$2(spec.tabs, function(tab) {
- return {
- value: tab.name,
- dom: {
- tag: "div",
- classes: ["tox-dialog__body-nav-item"],
- innerHtml: backstage.shared.providers.translate(tab.title)
- },
- view: function() {
- return [Form.sketch(function(parts2) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-form"]
- },
- components: map$2(tab.items, function(item2) {
- return interpretInForm(parts2, item2, backstage);
- }),
- formBehaviours: derive$1([
- Keying.config({
- mode: "acyclic",
- useTabstopAt: not(isPseudoStop)
- }),
- config("TabView.form.events", [
- runOnAttached(setDataOnForm),
- runOnDetached(updateDataWithForm)
- ]),
- Receiving.config({
- channels: wrapAll([
- {
- key: SendDataToSectionChannel,
- value: { onReceive: updateDataWithForm }
- },
- {
- key: SendDataToViewChannel,
- value: { onReceive: setDataOnForm }
- }
- ])
- })
- ])
- };
- })];
- }
- };
- });
- var tabMode = setMode(allTabs).smartTabHeight;
- return TabSection.sketch({
- dom: {
- tag: "div",
- classes: ["tox-dialog__body"]
- },
- onChangeTab: function(section, button2, _viewItems) {
- var name2 = Representing.getValue(button2);
- emitWith(section, formTabChangeEvent, {
- name: name2,
- oldName: oldTab.get()
- });
- oldTab.set(name2);
- },
- tabs: allTabs,
- components: [
- TabSection.parts.tabbar({
- dom: {
- tag: "div",
- classes: ["tox-dialog__body-nav"]
- },
- components: [Tabbar.parts.tabs({})],
- markers: {
- tabClass: "tox-tab",
- selectedClass: "tox-dialog__body-nav-item--active"
- },
- tabbarBehaviours: derive$1([Tabstopping.config({})])
- }),
- TabSection.parts.tabview({
- dom: {
- tag: "div",
- classes: ["tox-dialog__body-content"]
- }
- })
- ],
- selectFirst: tabMode.selectFirst,
- tabSectionBehaviours: derive$1([
- config("tabpanel", tabMode.extraEvents),
- Keying.config({ mode: "acyclic" }),
- Composing.config({
- find: function(comp) {
- return head(TabSection.getViewItems(comp));
- }
- }),
- Representing.config({
- store: {
- mode: "manual",
- getValue: function(tsection) {
- tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
- return storedValue.get();
- },
- setValue: function(tsection, value2) {
- storedValue.set(value2);
- tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
- }
- }
- })
- ])
- });
- };
- var dialogChannel = generate$6("update-dialog");
- var titleChannel = generate$6("update-title");
- var bodyChannel = generate$6("update-body");
- var footerChannel = generate$6("update-footer");
- var bodySendMessageChannel = generate$6("body-send-message");
- var renderBody = function(spec, id, backstage, ariaAttrs) {
- var renderComponents2 = function(incoming) {
- switch (incoming.body.type) {
- case "tabpanel": {
- return [renderTabPanel(incoming.body, backstage)];
- }
- default: {
- return [renderBodyPanel(incoming.body, backstage)];
- }
- }
- };
- var updateState = function(_comp, incoming) {
- return Optional.some({
- isTabPanel: function() {
- return incoming.body.type === "tabpanel";
- }
- });
- };
- var ariaAttributes = { "aria-live": "polite" };
- return {
- dom: {
- tag: "div",
- classes: ["tox-dialog__content-js"],
- attributes: __assign(__assign({}, id.map(function(x) {
- return { id: x };
- }).getOr({})), ariaAttrs ? ariaAttributes : {})
- },
- components: [],
- behaviours: derive$1([
- ComposingConfigs.childAt(0),
- Reflecting.config({
- channel: bodyChannel,
- updateState,
- renderComponents: renderComponents2,
- initialData: spec
- })
- ])
- };
- };
- var renderInlineBody = function(spec, contentId, backstage, ariaAttrs) {
- return renderBody(spec, Optional.some(contentId), backstage, ariaAttrs);
- };
- var renderModalBody = function(spec, backstage) {
- var bodySpec = renderBody(spec, Optional.none(), backstage, false);
- return ModalDialog.parts.body(bodySpec);
- };
- var renderIframeBody = function(spec) {
- var bodySpec = {
- dom: {
- tag: "div",
- classes: ["tox-dialog__content-js"]
- },
- components: [{
- dom: {
- tag: "div",
- classes: ["tox-dialog__body-iframe"]
- },
- components: [craft({
- dom: {
- tag: "iframe",
- attributes: { src: spec.url }
- },
- behaviours: derive$1([
- Tabstopping.config({}),
- Focusing.config({})
- ])
- })]
- }],
- behaviours: derive$1([Keying.config({
- mode: "acyclic",
- useTabstopAt: not(isPseudoStop)
- })])
- };
- return ModalDialog.parts.body(bodySpec);
- };
- function _typeof(obj) {
- "@babel/helpers - typeof";
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) {
- return typeof obj2;
- } : function(obj2) {
- return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
- }, _typeof(obj);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) {
- o2.__proto__ = p2;
- return o2;
- };
- return _setPrototypeOf(o, p);
- }
- function _isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct)
- return false;
- if (Reflect.construct.sham)
- return false;
- if (typeof Proxy === "function")
- return true;
- try {
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
- }));
- return true;
- } catch (e) {
- return false;
- }
- }
- function _construct(Parent, args, Class) {
- if (_isNativeReflectConstruct()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct2(Parent2, args2, Class2) {
- var a = [null];
- a.push.apply(a, args2);
- var Constructor = Function.bind.apply(Parent2, a);
- var instance = new Constructor();
- if (Class2)
- _setPrototypeOf(instance, Class2.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
- }
- function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
- }
- function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr))
- return _arrayLikeToArray(arr);
- }
- function _iterableToArray(iter) {
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null)
- return Array.from(iter);
- }
- function _unsupportedIterableToArray(o, minLen) {
- if (!o)
- return;
- if (typeof o === "string")
- return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor)
- n = o.constructor.name;
- if (n === "Map" || n === "Set")
- return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
- return _arrayLikeToArray(o, minLen);
- }
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length)
- len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++)
- arr2[i] = arr[i];
- return arr2;
- }
- function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
- var hasOwnProperty = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
- var freeze = Object.freeze, seal = Object.seal, create = Object.create;
- var _ref = typeof Reflect !== "undefined" && Reflect, apply = _ref.apply, construct = _ref.construct;
- if (!apply) {
- apply = function apply2(fun, thisValue, args) {
- return fun.apply(thisValue, args);
- };
- }
- if (!freeze) {
- freeze = function freeze2(x) {
- return x;
- };
- }
- if (!seal) {
- seal = function seal2(x) {
- return x;
- };
- }
- if (!construct) {
- construct = function construct2(Func, args) {
- return _construct(Func, _toConsumableArray(args));
- };
- }
- var arrayForEach = unapply(Array.prototype.forEach);
- var arrayPop = unapply(Array.prototype.pop);
- var arrayPush = unapply(Array.prototype.push);
- var stringToLowerCase = unapply(String.prototype.toLowerCase);
- var stringMatch = unapply(String.prototype.match);
- var stringReplace = unapply(String.prototype.replace);
- var stringIndexOf = unapply(String.prototype.indexOf);
- var stringTrim = unapply(String.prototype.trim);
- var regExpTest = unapply(RegExp.prototype.test);
- var typeErrorCreate = unconstruct(TypeError);
- function unapply(func) {
- return function(thisArg) {
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
- return apply(func, thisArg, args);
- };
- }
- function unconstruct(func) {
- return function() {
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- args[_key2] = arguments[_key2];
- }
- return construct(func, args);
- };
- }
- function addToSet(set2, array) {
- if (setPrototypeOf) {
- setPrototypeOf(set2, null);
- }
- var l2 = array.length;
- while (l2--) {
- var element2 = array[l2];
- if (typeof element2 === "string") {
- var lcElement = stringToLowerCase(element2);
- if (lcElement !== element2) {
- if (!isFrozen(array)) {
- array[l2] = lcElement;
- }
- element2 = lcElement;
- }
- }
- set2[element2] = true;
- }
- return set2;
- }
- function clone(object) {
- var newObject = create(null);
- var property;
- for (property in object) {
- if (apply(hasOwnProperty, object, [property])) {
- newObject[property] = object[property];
- }
- }
- return newObject;
- }
- function lookupGetter(object, prop) {
- while (object !== null) {
- var desc = getOwnPropertyDescriptor(object, prop);
- if (desc) {
- if (desc.get) {
- return unapply(desc.get);
- }
- if (typeof desc.value === "function") {
- return unapply(desc.value);
- }
- }
- object = getPrototypeOf(object);
- }
- function fallbackValue(element2) {
- console.warn("fallback value for", element2);
- return null;
- }
- return fallbackValue;
- }
- var html$1 = freeze([
- "a",
- "abbr",
- "acronym",
- "address",
- "area",
- "article",
- "aside",
- "audio",
- "b",
- "bdi",
- "bdo",
- "big",
- "blink",
- "blockquote",
- "body",
- "br",
- "button",
- "canvas",
- "caption",
- "center",
- "cite",
- "code",
- "col",
- "colgroup",
- "content",
- "data",
- "datalist",
- "dd",
- "decorator",
- "del",
- "details",
- "dfn",
- "dialog",
- "dir",
- "div",
- "dl",
- "dt",
- "element",
- "em",
- "fieldset",
- "figcaption",
- "figure",
- "font",
- "footer",
- "form",
- "h1",
- "h2",
- "h3",
- "h4",
- "h5",
- "h6",
- "head",
- "header",
- "hgroup",
- "hr",
- "html",
- "i",
- "img",
- "input",
- "ins",
- "kbd",
- "label",
- "legend",
- "li",
- "main",
- "map",
- "mark",
- "marquee",
- "menu",
- "menuitem",
- "meter",
- "nav",
- "nobr",
- "ol",
- "optgroup",
- "option",
- "output",
- "p",
- "picture",
- "pre",
- "progress",
- "q",
- "rp",
- "rt",
- "ruby",
- "s",
- "samp",
- "section",
- "select",
- "shadow",
- "small",
- "source",
- "spacer",
- "span",
- "strike",
- "strong",
- "style",
- "sub",
- "summary",
- "sup",
- "table",
- "tbody",
- "td",
- "template",
- "textarea",
- "tfoot",
- "th",
- "thead",
- "time",
- "tr",
- "track",
- "tt",
- "u",
- "ul",
- "var",
- "video",
- "wbr"
- ]);
- var svg$1 = freeze([
- "svg",
- "a",
- "altglyph",
- "altglyphdef",
- "altglyphitem",
- "animatecolor",
- "animatemotion",
- "animatetransform",
- "circle",
- "clippath",
- "defs",
- "desc",
- "ellipse",
- "filter",
- "font",
- "g",
- "glyph",
- "glyphref",
- "hkern",
- "image",
- "line",
- "lineargradient",
- "marker",
- "mask",
- "metadata",
- "mpath",
- "path",
- "pattern",
- "polygon",
- "polyline",
- "radialgradient",
- "rect",
- "stop",
- "style",
- "switch",
- "symbol",
- "text",
- "textpath",
- "title",
- "tref",
- "tspan",
- "view",
- "vkern"
- ]);
- var svgFilters = freeze([
- "feBlend",
- "feColorMatrix",
- "feComponentTransfer",
- "feComposite",
- "feConvolveMatrix",
- "feDiffuseLighting",
- "feDisplacementMap",
- "feDistantLight",
- "feFlood",
- "feFuncA",
- "feFuncB",
- "feFuncG",
- "feFuncR",
- "feGaussianBlur",
- "feImage",
- "feMerge",
- "feMergeNode",
- "feMorphology",
- "feOffset",
- "fePointLight",
- "feSpecularLighting",
- "feSpotLight",
- "feTile",
- "feTurbulence"
- ]);
- var svgDisallowed = freeze([
- "animate",
- "color-profile",
- "cursor",
- "discard",
- "fedropshadow",
- "font-face",
- "font-face-format",
- "font-face-name",
- "font-face-src",
- "font-face-uri",
- "foreignobject",
- "hatch",
- "hatchpath",
- "mesh",
- "meshgradient",
- "meshpatch",
- "meshrow",
- "missing-glyph",
- "script",
- "set",
- "solidcolor",
- "unknown",
- "use"
- ]);
- var mathMl$1 = freeze([
- "math",
- "menclose",
- "merror",
- "mfenced",
- "mfrac",
- "mglyph",
- "mi",
- "mlabeledtr",
- "mmultiscripts",
- "mn",
- "mo",
- "mover",
- "mpadded",
- "mphantom",
- "mroot",
- "mrow",
- "ms",
- "mspace",
- "msqrt",
- "mstyle",
- "msub",
- "msup",
- "msubsup",
- "mtable",
- "mtd",
- "mtext",
- "mtr",
- "munder",
- "munderover"
- ]);
- var mathMlDisallowed = freeze([
- "maction",
- "maligngroup",
- "malignmark",
- "mlongdiv",
- "mscarries",
- "mscarry",
- "msgroup",
- "mstack",
- "msline",
- "msrow",
- "semantics",
- "annotation",
- "annotation-xml",
- "mprescripts",
- "none"
- ]);
- var text = freeze(["#text"]);
- var html = freeze([
- "accept",
- "action",
- "align",
- "alt",
- "autocapitalize",
- "autocomplete",
- "autopictureinpicture",
- "autoplay",
- "background",
- "bgcolor",
- "border",
- "capture",
- "cellpadding",
- "cellspacing",
- "checked",
- "cite",
- "class",
- "clear",
- "color",
- "cols",
- "colspan",
- "controls",
- "controlslist",
- "coords",
- "crossorigin",
- "datetime",
- "decoding",
- "default",
- "dir",
- "disabled",
- "disablepictureinpicture",
- "disableremoteplayback",
- "download",
- "draggable",
- "enctype",
- "enterkeyhint",
- "face",
- "for",
- "headers",
- "height",
- "hidden",
- "high",
- "href",
- "hreflang",
- "id",
- "inputmode",
- "integrity",
- "ismap",
- "kind",
- "label",
- "lang",
- "list",
- "loading",
- "loop",
- "low",
- "max",
- "maxlength",
- "media",
- "method",
- "min",
- "minlength",
- "multiple",
- "muted",
- "name",
- "nonce",
- "noshade",
- "novalidate",
- "nowrap",
- "open",
- "optimum",
- "pattern",
- "placeholder",
- "playsinline",
- "poster",
- "preload",
- "pubdate",
- "radiogroup",
- "readonly",
- "rel",
- "required",
- "rev",
- "reversed",
- "role",
- "rows",
- "rowspan",
- "spellcheck",
- "scope",
- "selected",
- "shape",
- "size",
- "sizes",
- "span",
- "srclang",
- "start",
- "src",
- "srcset",
- "step",
- "style",
- "summary",
- "tabindex",
- "title",
- "translate",
- "type",
- "usemap",
- "valign",
- "value",
- "width",
- "xmlns",
- "slot"
- ]);
- var svg = freeze([
- "accent-height",
- "accumulate",
- "additive",
- "alignment-baseline",
- "ascent",
- "attributename",
- "attributetype",
- "azimuth",
- "basefrequency",
- "baseline-shift",
- "begin",
- "bias",
- "by",
- "class",
- "clip",
- "clippathunits",
- "clip-path",
- "clip-rule",
- "color",
- "color-interpolation",
- "color-interpolation-filters",
- "color-profile",
- "color-rendering",
- "cx",
- "cy",
- "d",
- "dx",
- "dy",
- "diffuseconstant",
- "direction",
- "display",
- "divisor",
- "dur",
- "edgemode",
- "elevation",
- "end",
- "fill",
- "fill-opacity",
- "fill-rule",
- "filter",
- "filterunits",
- "flood-color",
- "flood-opacity",
- "font-family",
- "font-size",
- "font-size-adjust",
- "font-stretch",
- "font-style",
- "font-variant",
- "font-weight",
- "fx",
- "fy",
- "g1",
- "g2",
- "glyph-name",
- "glyphref",
- "gradientunits",
- "gradienttransform",
- "height",
- "href",
- "id",
- "image-rendering",
- "in",
- "in2",
- "k",
- "k1",
- "k2",
- "k3",
- "k4",
- "kerning",
- "keypoints",
- "keysplines",
- "keytimes",
- "lang",
- "lengthadjust",
- "letter-spacing",
- "kernelmatrix",
- "kernelunitlength",
- "lighting-color",
- "local",
- "marker-end",
- "marker-mid",
- "marker-start",
- "markerheight",
- "markerunits",
- "markerwidth",
- "maskcontentunits",
- "maskunits",
- "max",
- "mask",
- "media",
- "method",
- "mode",
- "min",
- "name",
- "numoctaves",
- "offset",
- "operator",
- "opacity",
- "order",
- "orient",
- "orientation",
- "origin",
- "overflow",
- "paint-order",
- "path",
- "pathlength",
- "patterncontentunits",
- "patterntransform",
- "patternunits",
- "points",
- "preservealpha",
- "preserveaspectratio",
- "primitiveunits",
- "r",
- "rx",
- "ry",
- "radius",
- "refx",
- "refy",
- "repeatcount",
- "repeatdur",
- "restart",
- "result",
- "rotate",
- "scale",
- "seed",
- "shape-rendering",
- "specularconstant",
- "specularexponent",
- "spreadmethod",
- "startoffset",
- "stddeviation",
- "stitchtiles",
- "stop-color",
- "stop-opacity",
- "stroke-dasharray",
- "stroke-dashoffset",
- "stroke-linecap",
- "stroke-linejoin",
- "stroke-miterlimit",
- "stroke-opacity",
- "stroke",
- "stroke-width",
- "style",
- "surfacescale",
- "systemlanguage",
- "tabindex",
- "targetx",
- "targety",
- "transform",
- "transform-origin",
- "text-anchor",
- "text-decoration",
- "text-rendering",
- "textlength",
- "type",
- "u1",
- "u2",
- "unicode",
- "values",
- "viewbox",
- "visibility",
- "version",
- "vert-adv-y",
- "vert-origin-x",
- "vert-origin-y",
- "width",
- "word-spacing",
- "wrap",
- "writing-mode",
- "xchannelselector",
- "ychannelselector",
- "x",
- "x1",
- "x2",
- "xmlns",
- "y",
- "y1",
- "y2",
- "z",
- "zoomandpan"
- ]);
- var mathMl = freeze([
- "accent",
- "accentunder",
- "align",
- "bevelled",
- "close",
- "columnsalign",
- "columnlines",
- "columnspan",
- "denomalign",
- "depth",
- "dir",
- "display",
- "displaystyle",
- "encoding",
- "fence",
- "frame",
- "height",
- "href",
- "id",
- "largeop",
- "length",
- "linethickness",
- "lspace",
- "lquote",
- "mathbackground",
- "mathcolor",
- "mathsize",
- "mathvariant",
- "maxsize",
- "minsize",
- "movablelimits",
- "notation",
- "numalign",
- "open",
- "rowalign",
- "rowlines",
- "rowspacing",
- "rowspan",
- "rspace",
- "rquote",
- "scriptlevel",
- "scriptminsize",
- "scriptsizemultiplier",
- "selection",
- "separator",
- "separators",
- "stretchy",
- "subscriptshift",
- "supscriptshift",
- "symmetric",
- "voffset",
- "width",
- "xmlns"
- ]);
- var xml = freeze([
- "xlink:href",
- "xml:id",
- "xlink:title",
- "xml:space",
- "xmlns:xlink"
- ]);
- var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm);
- var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
- var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
- var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
- var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i);
- var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
- var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g);
- var DOCTYPE_NAME = seal(/^html$/i);
- var getGlobal = function getGlobal2() {
- return typeof window === "undefined" ? null : window;
- };
- var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, document2) {
- if (_typeof(trustedTypes) !== "object" || typeof trustedTypes.createPolicy !== "function") {
- return null;
- }
- var suffix2 = null;
- var ATTR_NAME = "data-tt-policy-suffix";
- if (document2.currentScript && document2.currentScript.hasAttribute(ATTR_NAME)) {
- suffix2 = document2.currentScript.getAttribute(ATTR_NAME);
- }
- var policyName = "dompurify" + (suffix2 ? "#" + suffix2 : "");
- try {
- return trustedTypes.createPolicy(policyName, {
- createHTML: function createHTML(html2) {
- return html2;
- }
- });
- } catch (_) {
- console.warn("TrustedTypes policy " + policyName + " could not be created.");
- return null;
- }
- };
- function createDOMPurify() {
- var window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
- var DOMPurify = function DOMPurify2(root) {
- return createDOMPurify(root);
- };
- DOMPurify.version = "2.3.8";
- DOMPurify.removed = [];
- if (!window2 || !window2.document || window2.document.nodeType !== 9) {
- DOMPurify.isSupported = false;
- return DOMPurify;
- }
- var originalDocument = window2.document;
- var document2 = window2.document;
- var DocumentFragment = window2.DocumentFragment, HTMLTemplateElement = window2.HTMLTemplateElement, Node2 = window2.Node, Element2 = window2.Element, NodeFilter = window2.NodeFilter, _window$NamedNodeMap = window2.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === void 0 ? window2.NamedNodeMap || window2.MozNamedAttrMap : _window$NamedNodeMap, HTMLFormElement = window2.HTMLFormElement, DOMParser = window2.DOMParser, trustedTypes = window2.trustedTypes;
- var ElementPrototype = Element2.prototype;
- var cloneNode = lookupGetter(ElementPrototype, "cloneNode");
- var getNextSibling = lookupGetter(ElementPrototype, "nextSibling");
- var getChildNodes = lookupGetter(ElementPrototype, "childNodes");
- var getParentNode = lookupGetter(ElementPrototype, "parentNode");
- if (typeof HTMLTemplateElement === "function") {
- var template = document2.createElement("template");
- if (template.content && template.content.ownerDocument) {
- document2 = template.content.ownerDocument;
- }
- }
- var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
- var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML("") : "";
- var _document = document2, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;
- var importNode = originalDocument.importNode;
- var documentMode = {};
- try {
- documentMode = clone(document2).documentMode ? document2.documentMode : {};
- } catch (_) {
- }
- var hooks = {};
- DOMPurify.isSupported = typeof getParentNode === "function" && implementation && typeof implementation.createHTMLDocument !== "undefined" && documentMode !== 9;
- var MUSTACHE_EXPR$1 = MUSTACHE_EXPR, ERB_EXPR$1 = ERB_EXPR, DATA_ATTR$1 = DATA_ATTR, ARIA_ATTR$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$1 = ATTR_WHITESPACE;
- var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
- var ALLOWED_TAGS = null;
- var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
- var ALLOWED_ATTR = null;
- var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
- var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
- tagNameCheck: {
- writable: true,
- configurable: false,
- enumerable: true,
- value: null
- },
- attributeNameCheck: {
- writable: true,
- configurable: false,
- enumerable: true,
- value: null
- },
- allowCustomizedBuiltInElements: {
- writable: true,
- configurable: false,
- enumerable: true,
- value: false
- }
- }));
- var FORBID_TAGS = null;
- var FORBID_ATTR = null;
- var ALLOW_ARIA_ATTR = true;
- var ALLOW_DATA_ATTR = true;
- var ALLOW_UNKNOWN_PROTOCOLS = false;
- var SAFE_FOR_TEMPLATES = false;
- var WHOLE_DOCUMENT = false;
- var SET_CONFIG = false;
- var FORCE_BODY = false;
- var RETURN_DOM = false;
- var RETURN_DOM_FRAGMENT = false;
- var RETURN_TRUSTED_TYPE = false;
- var SANITIZE_DOM = true;
- var KEEP_CONTENT = true;
- var IN_PLACE = false;
- var USE_PROFILES = {};
- var FORBID_CONTENTS = null;
- var DEFAULT_FORBID_CONTENTS = addToSet({}, [
- "annotation-xml",
- "audio",
- "colgroup",
- "desc",
- "foreignobject",
- "head",
- "iframe",
- "math",
- "mi",
- "mn",
- "mo",
- "ms",
- "mtext",
- "noembed",
- "noframes",
- "noscript",
- "plaintext",
- "script",
- "style",
- "svg",
- "template",
- "thead",
- "title",
- "video",
- "xmp"
- ]);
- var DATA_URI_TAGS = null;
- var DEFAULT_DATA_URI_TAGS = addToSet({}, [
- "audio",
- "video",
- "img",
- "source",
- "image",
- "track"
- ]);
- var URI_SAFE_ATTRIBUTES = null;
- var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [
- "alt",
- "class",
- "for",
- "id",
- "label",
- "name",
- "pattern",
- "placeholder",
- "role",
- "summary",
- "title",
- "value",
- "style",
- "xmlns"
- ]);
- var MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
- var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
- var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
- var NAMESPACE = HTML_NAMESPACE;
- var IS_EMPTY_INPUT = false;
- var PARSER_MEDIA_TYPE;
- var SUPPORTED_PARSER_MEDIA_TYPES = [
- "application/xhtml+xml",
- "text/html"
- ];
- var DEFAULT_PARSER_MEDIA_TYPE = "text/html";
- var transformCaseFunc;
- var CONFIG = null;
- var formElement = document2.createElement("form");
- var isRegexOrFunction = function isRegexOrFunction2(testValue) {
- return testValue instanceof RegExp || testValue instanceof Function;
- };
- var _parseConfig = function _parseConfig2(cfg) {
- if (CONFIG && CONFIG === cfg) {
- return;
- }
- if (!cfg || _typeof(cfg) !== "object") {
- cfg = {};
- }
- cfg = clone(cfg);
- ALLOWED_TAGS = "ALLOWED_TAGS" in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
- ALLOWED_ATTR = "ALLOWED_ATTR" in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
- URI_SAFE_ATTRIBUTES = "ADD_URI_SAFE_ATTR" in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
- DATA_URI_TAGS = "ADD_DATA_URI_TAGS" in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
- FORBID_CONTENTS = "FORBID_CONTENTS" in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
- FORBID_TAGS = "FORBID_TAGS" in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
- FORBID_ATTR = "FORBID_ATTR" in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
- USE_PROFILES = "USE_PROFILES" in cfg ? cfg.USE_PROFILES : false;
- ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
- ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
- ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
- SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
- WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
- RETURN_DOM = cfg.RETURN_DOM || false;
- RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
- RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
- FORCE_BODY = cfg.FORCE_BODY || false;
- SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
- KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
- IN_PLACE = cfg.IN_PLACE || false;
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
- }
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
- }
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") {
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
- }
- PARSER_MEDIA_TYPE = SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE;
- transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? function(x) {
- return x;
- } : stringToLowerCase;
- if (SAFE_FOR_TEMPLATES) {
- ALLOW_DATA_ATTR = false;
- }
- if (RETURN_DOM_FRAGMENT) {
- RETURN_DOM = true;
- }
- if (USE_PROFILES) {
- ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
- ALLOWED_ATTR = [];
- if (USE_PROFILES.html === true) {
- addToSet(ALLOWED_TAGS, html$1);
- addToSet(ALLOWED_ATTR, html);
- }
- if (USE_PROFILES.svg === true) {
- addToSet(ALLOWED_TAGS, svg$1);
- addToSet(ALLOWED_ATTR, svg);
- addToSet(ALLOWED_ATTR, xml);
- }
- if (USE_PROFILES.svgFilters === true) {
- addToSet(ALLOWED_TAGS, svgFilters);
- addToSet(ALLOWED_ATTR, svg);
- addToSet(ALLOWED_ATTR, xml);
- }
- if (USE_PROFILES.mathMl === true) {
- addToSet(ALLOWED_TAGS, mathMl$1);
- addToSet(ALLOWED_ATTR, mathMl);
- addToSet(ALLOWED_ATTR, xml);
- }
- }
- if (cfg.ADD_TAGS) {
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
- }
- addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
- }
- if (cfg.ADD_ATTR) {
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
- }
- addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
- }
- if (cfg.ADD_URI_SAFE_ATTR) {
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
- }
- if (cfg.FORBID_CONTENTS) {
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
- }
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
- }
- if (KEEP_CONTENT) {
- ALLOWED_TAGS["#text"] = true;
- }
- if (WHOLE_DOCUMENT) {
- addToSet(ALLOWED_TAGS, [
- "html",
- "head",
- "body"
- ]);
- }
- if (ALLOWED_TAGS.table) {
- addToSet(ALLOWED_TAGS, ["tbody"]);
- delete FORBID_TAGS.tbody;
- }
- if (freeze) {
- freeze(cfg);
- }
- CONFIG = cfg;
- };
- var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [
- "mi",
- "mo",
- "mn",
- "ms",
- "mtext"
- ]);
- var HTML_INTEGRATION_POINTS = addToSet({}, [
- "foreignobject",
- "desc",
- "title",
- "annotation-xml"
- ]);
- var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [
- "title",
- "style",
- "font",
- "a",
- "script"
- ]);
- var ALL_SVG_TAGS = addToSet({}, svg$1);
- addToSet(ALL_SVG_TAGS, svgFilters);
- addToSet(ALL_SVG_TAGS, svgDisallowed);
- var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
- addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
- var _checkValidNamespace = function _checkValidNamespace2(element2) {
- var parent2 = getParentNode(element2);
- if (!parent2 || !parent2.tagName) {
- parent2 = {
- namespaceURI: HTML_NAMESPACE,
- tagName: "template"
- };
- }
- var tagName = stringToLowerCase(element2.tagName);
- var parentTagName = stringToLowerCase(parent2.tagName);
- if (element2.namespaceURI === SVG_NAMESPACE) {
- if (parent2.namespaceURI === HTML_NAMESPACE) {
- return tagName === "svg";
- }
- if (parent2.namespaceURI === MATHML_NAMESPACE) {
- return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
- }
- return Boolean(ALL_SVG_TAGS[tagName]);
- }
- if (element2.namespaceURI === MATHML_NAMESPACE) {
- if (parent2.namespaceURI === HTML_NAMESPACE) {
- return tagName === "math";
- }
- if (parent2.namespaceURI === SVG_NAMESPACE) {
- return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
- }
- return Boolean(ALL_MATHML_TAGS[tagName]);
- }
- if (element2.namespaceURI === HTML_NAMESPACE) {
- if (parent2.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
- return false;
- }
- if (parent2.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
- return false;
- }
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
- }
- return false;
- };
- var _forceRemove = function _forceRemove2(node) {
- arrayPush(DOMPurify.removed, { element: node });
- try {
- node.parentNode.removeChild(node);
- } catch (_) {
- try {
- node.outerHTML = emptyHTML;
- } catch (_2) {
- node.remove();
- }
- }
- };
- var _removeAttribute = function _removeAttribute2(name2, node) {
- try {
- arrayPush(DOMPurify.removed, {
- attribute: node.getAttributeNode(name2),
- from: node
- });
- } catch (_) {
- arrayPush(DOMPurify.removed, {
- attribute: null,
- from: node
- });
- }
- node.removeAttribute(name2);
- if (name2 === "is" && !ALLOWED_ATTR[name2]) {
- if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
- try {
- _forceRemove(node);
- } catch (_) {
- }
- } else {
- try {
- node.setAttribute(name2, "");
- } catch (_) {
- }
- }
- }
- };
- var _initDocument = function _initDocument2(dirty) {
- var doc;
- var leadingWhitespace;
- if (FORCE_BODY) {
- dirty = "<remove></remove>" + dirty;
- } else {
- var matches = stringMatch(dirty, /^[\r\n\t ]+/);
- leadingWhitespace = matches && matches[0];
- }
- if (PARSER_MEDIA_TYPE === "application/xhtml+xml") {
- dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + "</body></html>";
- }
- var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
- if (NAMESPACE === HTML_NAMESPACE) {
- try {
- doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
- } catch (_) {
- }
- }
- if (!doc || !doc.documentElement) {
- doc = implementation.createDocument(NAMESPACE, "template", null);
- try {
- doc.documentElement.innerHTML = IS_EMPTY_INPUT ? "" : dirtyPayload;
- } catch (_) {
- }
- }
- var body2 = doc.body || doc.documentElement;
- if (dirty && leadingWhitespace) {
- body2.insertBefore(document2.createTextNode(leadingWhitespace), body2.childNodes[0] || null);
- }
- if (NAMESPACE === HTML_NAMESPACE) {
- return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? "html" : "body")[0];
- }
- return WHOLE_DOCUMENT ? doc.documentElement : body2;
- };
- var _createIterator = function _createIterator2(root) {
- return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
- };
- var _isClobbered = function _isClobbered2(elm) {
- return elm instanceof HTMLFormElement && (typeof elm.nodeName !== "string" || typeof elm.textContent !== "string" || typeof elm.removeChild !== "function" || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== "function" || typeof elm.setAttribute !== "function" || typeof elm.namespaceURI !== "string" || typeof elm.insertBefore !== "function");
- };
- var _isNode = function _isNode2(object) {
- return _typeof(Node2) === "object" ? object instanceof Node2 : object && _typeof(object) === "object" && typeof object.nodeType === "number" && typeof object.nodeName === "string";
- };
- var _executeHook = function _executeHook2(entryPoint, currentNode, data) {
- if (!hooks[entryPoint]) {
- return;
- }
- arrayForEach(hooks[entryPoint], function(hook) {
- hook.call(DOMPurify, currentNode, data, CONFIG);
- });
- };
- var _sanitizeElements = function _sanitizeElements2(currentNode) {
- var content;
- _executeHook("beforeSanitizeElements", currentNode, null);
- if (_isClobbered(currentNode)) {
- _forceRemove(currentNode);
- return true;
- }
- if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
- _forceRemove(currentNode);
- return true;
- }
- var tagName = transformCaseFunc(currentNode.nodeName);
- _executeHook("uponSanitizeElement", currentNode, {
- tagName,
- allowedTags: ALLOWED_TAGS
- });
- if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
- _forceRemove(currentNode);
- return true;
- }
- if (tagName === "select" && regExpTest(/<template/i, currentNode.innerHTML)) {
- _forceRemove(currentNode);
- return true;
- }
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
- if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName))
- return false;
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName))
- return false;
- }
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
- var parentNode2 = getParentNode(currentNode) || currentNode.parentNode;
- var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
- if (childNodes && parentNode2) {
- var childCount = childNodes.length;
- for (var i = childCount - 1; i >= 0; --i) {
- parentNode2.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
- }
- }
- }
- _forceRemove(currentNode);
- return true;
- }
- if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) {
- _forceRemove(currentNode);
- return true;
- }
- if ((tagName === "noscript" || tagName === "noembed") && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
- _forceRemove(currentNode);
- return true;
- }
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
- content = currentNode.textContent;
- content = stringReplace(content, MUSTACHE_EXPR$1, " ");
- content = stringReplace(content, ERB_EXPR$1, " ");
- if (currentNode.textContent !== content) {
- arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
- currentNode.textContent = content;
- }
- }
- _executeHook("afterSanitizeElements", currentNode, null);
- return false;
- };
- var _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value2) {
- if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value2 in document2 || value2 in formElement)) {
- return false;
- }
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName))
- ;
- else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName))
- ;
- else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
- if (_basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value2) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value2)))
- ;
- else {
- return false;
- }
- } else if (URI_SAFE_ATTRIBUTES[lcName])
- ;
- else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value2, ATTR_WHITESPACE$1, "")))
- ;
- else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value2, "data:") === 0 && DATA_URI_TAGS[lcTag])
- ;
- else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value2, ATTR_WHITESPACE$1, "")))
- ;
- else if (!value2)
- ;
- else {
- return false;
- }
- return true;
- };
- var _basicCustomElementTest = function _basicCustomElementTest2(tagName) {
- return tagName.indexOf("-") > 0;
- };
- var _sanitizeAttributes = function _sanitizeAttributes2(currentNode) {
- var attr;
- var value2;
- var lcName;
- var l2;
- _executeHook("beforeSanitizeAttributes", currentNode, null);
- var attributes = currentNode.attributes;
- if (!attributes) {
- return;
- }
- var hookEvent = {
- attrName: "",
- attrValue: "",
- keepAttr: true,
- allowedAttributes: ALLOWED_ATTR
- };
- l2 = attributes.length;
- while (l2--) {
- attr = attributes[l2];
- var _attr = attr, name2 = _attr.name, namespaceURI = _attr.namespaceURI;
- value2 = name2 === "value" ? attr.value : stringTrim(attr.value);
- lcName = transformCaseFunc(name2);
- hookEvent.attrName = lcName;
- hookEvent.attrValue = value2;
- hookEvent.keepAttr = true;
- hookEvent.forceKeepAttr = void 0;
- _executeHook("uponSanitizeAttribute", currentNode, hookEvent);
- value2 = hookEvent.attrValue;
- if (hookEvent.forceKeepAttr) {
- continue;
- }
- _removeAttribute(name2, currentNode);
- if (!hookEvent.keepAttr) {
- continue;
- }
- if (regExpTest(/\/>/i, value2)) {
- _removeAttribute(name2, currentNode);
- continue;
- }
- if (SAFE_FOR_TEMPLATES) {
- value2 = stringReplace(value2, MUSTACHE_EXPR$1, " ");
- value2 = stringReplace(value2, ERB_EXPR$1, " ");
- }
- var lcTag = transformCaseFunc(currentNode.nodeName);
- if (!_isValidAttribute(lcTag, lcName, value2)) {
- continue;
- }
- try {
- if (namespaceURI) {
- currentNode.setAttributeNS(namespaceURI, name2, value2);
- } else {
- currentNode.setAttribute(name2, value2);
- }
- arrayPop(DOMPurify.removed);
- } catch (_) {
- }
- }
- _executeHook("afterSanitizeAttributes", currentNode, null);
- };
- var _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) {
- var shadowNode;
- var shadowIterator = _createIterator(fragment);
- _executeHook("beforeSanitizeShadowDOM", fragment, null);
- while (shadowNode = shadowIterator.nextNode()) {
- _executeHook("uponSanitizeShadowNode", shadowNode, null);
- if (_sanitizeElements(shadowNode)) {
- continue;
- }
- if (shadowNode.content instanceof DocumentFragment) {
- _sanitizeShadowDOM2(shadowNode.content);
- }
- _sanitizeAttributes(shadowNode);
- }
- _executeHook("afterSanitizeShadowDOM", fragment, null);
- };
- DOMPurify.sanitize = function(dirty, cfg) {
- var body2;
- var importedNode;
- var currentNode;
- var oldNode;
- var returnNode;
- IS_EMPTY_INPUT = !dirty;
- if (IS_EMPTY_INPUT) {
- dirty = "<!-->";
- }
- if (typeof dirty !== "string" && !_isNode(dirty)) {
- if (typeof dirty.toString !== "function") {
- throw typeErrorCreate("toString is not a function");
- } else {
- dirty = dirty.toString();
- if (typeof dirty !== "string") {
- throw typeErrorCreate("dirty is not a string, aborting");
- }
- }
- }
- if (!DOMPurify.isSupported) {
- if (_typeof(window2.toStaticHTML) === "object" || typeof window2.toStaticHTML === "function") {
- if (typeof dirty === "string") {
- return window2.toStaticHTML(dirty);
- }
- if (_isNode(dirty)) {
- return window2.toStaticHTML(dirty.outerHTML);
- }
- }
- return dirty;
- }
- if (!SET_CONFIG) {
- _parseConfig(cfg);
- }
- DOMPurify.removed = [];
- if (typeof dirty === "string") {
- IN_PLACE = false;
- }
- if (IN_PLACE) {
- if (dirty.nodeName) {
- var tagName = transformCaseFunc(dirty.nodeName);
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
- throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place");
- }
- }
- } else if (dirty instanceof Node2) {
- body2 = _initDocument("<!---->");
- importedNode = body2.ownerDocument.importNode(dirty, true);
- if (importedNode.nodeType === 1 && importedNode.nodeName === "BODY") {
- body2 = importedNode;
- } else if (importedNode.nodeName === "HTML") {
- body2 = importedNode;
- } else {
- body2.appendChild(importedNode);
- }
- } else {
- if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf("<") === -1) {
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
- }
- body2 = _initDocument(dirty);
- if (!body2) {
- return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : "";
- }
- }
- if (body2 && FORCE_BODY) {
- _forceRemove(body2.firstChild);
- }
- var nodeIterator = _createIterator(IN_PLACE ? dirty : body2);
- while (currentNode = nodeIterator.nextNode()) {
- if (currentNode.nodeType === 3 && currentNode === oldNode) {
- continue;
- }
- if (_sanitizeElements(currentNode)) {
- continue;
- }
- if (currentNode.content instanceof DocumentFragment) {
- _sanitizeShadowDOM(currentNode.content);
- }
- _sanitizeAttributes(currentNode);
- oldNode = currentNode;
- }
- oldNode = null;
- if (IN_PLACE) {
- return dirty;
- }
- if (RETURN_DOM) {
- if (RETURN_DOM_FRAGMENT) {
- returnNode = createDocumentFragment.call(body2.ownerDocument);
- while (body2.firstChild) {
- returnNode.appendChild(body2.firstChild);
- }
- } else {
- returnNode = body2;
- }
- if (ALLOWED_ATTR.shadowroot) {
- returnNode = importNode.call(originalDocument, returnNode, true);
- }
- return returnNode;
- }
- var serializedHTML = WHOLE_DOCUMENT ? body2.outerHTML : body2.innerHTML;
- if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body2.ownerDocument && body2.ownerDocument.doctype && body2.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body2.ownerDocument.doctype.name)) {
- serializedHTML = "<!DOCTYPE " + body2.ownerDocument.doctype.name + ">\n" + serializedHTML;
- }
- if (SAFE_FOR_TEMPLATES) {
- serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, " ");
- serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, " ");
- }
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
- };
- DOMPurify.setConfig = function(cfg) {
- _parseConfig(cfg);
- SET_CONFIG = true;
- };
- DOMPurify.clearConfig = function() {
- CONFIG = null;
- SET_CONFIG = false;
- };
- DOMPurify.isValidAttribute = function(tag, attr, value2) {
- if (!CONFIG) {
- _parseConfig({});
- }
- var lcTag = transformCaseFunc(tag);
- var lcName = transformCaseFunc(attr);
- return _isValidAttribute(lcTag, lcName, value2);
- };
- DOMPurify.addHook = function(entryPoint, hookFunction) {
- if (typeof hookFunction !== "function") {
- return;
- }
- hooks[entryPoint] = hooks[entryPoint] || [];
- arrayPush(hooks[entryPoint], hookFunction);
- };
- DOMPurify.removeHook = function(entryPoint) {
- if (hooks[entryPoint]) {
- return arrayPop(hooks[entryPoint]);
- }
- };
- DOMPurify.removeHooks = function(entryPoint) {
- if (hooks[entryPoint]) {
- hooks[entryPoint] = [];
- }
- };
- DOMPurify.removeAllHooks = function() {
- hooks = {};
- };
- return DOMPurify;
- }
- var purify = createDOMPurify();
- var sanitizeHtmlString = function(html2) {
- return purify().sanitize(html2);
- };
- var isTouch = global$9.deviceType.isTouch();
- var hiddenHeader = function(title, close2) {
- return {
- dom: {
- tag: "div",
- styles: { display: "none" },
- classes: ["tox-dialog__header"]
- },
- components: [
- title,
- close2
- ]
- };
- };
- var pClose = function(onClose, providersBackstage) {
- return ModalDialog.parts.close(Button.sketch({
- dom: {
- tag: "button",
- classes: [
- "tox-button",
- "tox-button--icon",
- "tox-button--naked"
- ],
- attributes: {
- "type": "button",
- "aria-label": providersBackstage.translate("Close")
- }
- },
- action: onClose,
- buttonBehaviours: derive$1([Tabstopping.config({})])
- }));
- };
- var pUntitled = function() {
- return ModalDialog.parts.title({
- dom: {
- tag: "div",
- classes: ["tox-dialog__title"],
- innerHtml: "",
- styles: { display: "none" }
- }
- });
- };
- var pBodyMessage = function(message, providersBackstage) {
- return ModalDialog.parts.body({
- dom: {
- tag: "div",
- classes: ["tox-dialog__body"]
- },
- components: [{
- dom: {
- tag: "div",
- classes: ["tox-dialog__body-content"]
- },
- components: [{ dom: fromHtml("<p>" + sanitizeHtmlString(providersBackstage.translate(message)) + "</p>") }]
- }]
- });
- };
- var pFooter = function(buttons) {
- return ModalDialog.parts.footer({
- dom: {
- tag: "div",
- classes: ["tox-dialog__footer"]
- },
- components: buttons
- });
- };
- var pFooterGroup = function(startButtons, endButtons) {
- return [
- Container.sketch({
- dom: {
- tag: "div",
- classes: ["tox-dialog__footer-start"]
- },
- components: startButtons
- }),
- Container.sketch({
- dom: {
- tag: "div",
- classes: ["tox-dialog__footer-end"]
- },
- components: endButtons
- })
- ];
- };
- var renderDialog$1 = function(spec) {
- var _a2;
- var dialogClass = "tox-dialog";
- var blockerClass = dialogClass + "-wrap";
- var blockerBackdropClass = blockerClass + "__backdrop";
- var scrollLockClass = dialogClass + "__disable-scroll";
- return ModalDialog.sketch({
- lazySink: spec.lazySink,
- onEscape: function(comp) {
- spec.onEscape(comp);
- return Optional.some(true);
- },
- useTabstopAt: function(elem) {
- return !isPseudoStop(elem);
- },
- dom: {
- tag: "div",
- classes: [dialogClass].concat(spec.extraClasses),
- styles: __assign({ position: "relative" }, spec.extraStyles)
- },
- components: __spreadArray([
- spec.header,
- spec.body
- ], spec.footer.toArray(), true),
- parts: {
- blocker: {
- dom: fromHtml('<div class="' + blockerClass + '"></div>'),
- components: [{
- dom: {
- tag: "div",
- classes: isTouch ? [
- blockerBackdropClass,
- blockerBackdropClass + "--opaque"
- ] : [blockerBackdropClass]
- }
- }]
- }
- },
- dragBlockClass: blockerClass,
- modalBehaviours: derive$1(__spreadArray([
- Focusing.config({}),
- config("dialog-events", spec.dialogEvents.concat([runOnSource(focusin(), function(comp, _se) {
- Keying.focusIn(comp);
- })])),
- config("scroll-lock", [
- runOnAttached(function() {
- add$2(body(), scrollLockClass);
- }),
- runOnDetached(function() {
- remove$2(body(), scrollLockClass);
- })
- ])
- ], spec.extraBehaviours, true)),
- eventOrder: __assign((_a2 = {}, _a2[execute$5()] = ["dialog-events"], _a2[attachedToDom()] = [
- "scroll-lock",
- "dialog-events",
- "alloy.base.behaviour"
- ], _a2[detachedFromDom()] = [
- "alloy.base.behaviour",
- "dialog-events",
- "scroll-lock"
- ], _a2), spec.eventOrder)
- });
- };
- var renderClose = function(providersBackstage) {
- return Button.sketch({
- dom: {
- tag: "button",
- classes: [
- "tox-button",
- "tox-button--icon",
- "tox-button--naked"
- ],
- attributes: {
- "type": "button",
- "aria-label": providersBackstage.translate("Close"),
- "title": providersBackstage.translate("Close")
- }
- },
- components: [render$3("close", {
- tag: "div",
- classes: ["tox-icon"]
- }, providersBackstage.icons)],
- action: function(comp) {
- emit(comp, formCancelEvent);
- }
- });
- };
- var renderTitle = function(spec, id, providersBackstage) {
- var renderComponents2 = function(data) {
- return [text$1(providersBackstage.translate(data.title))];
- };
- return {
- dom: {
- tag: "div",
- classes: ["tox-dialog__title"],
- attributes: __assign({}, id.map(function(x) {
- return { id: x };
- }).getOr({}))
- },
- components: renderComponents2(spec),
- behaviours: derive$1([Reflecting.config({
- channel: titleChannel,
- renderComponents: renderComponents2
- })])
- };
- };
- var renderDragHandle = function() {
- return { dom: fromHtml('<div class="tox-dialog__draghandle"></div>') };
- };
- var renderInlineHeader = function(spec, titleId, providersBackstage) {
- return Container.sketch({
- dom: fromHtml('<div class="tox-dialog__header"></div>'),
- components: [
- renderTitle(spec, Optional.some(titleId), providersBackstage),
- renderDragHandle(),
- renderClose(providersBackstage)
- ],
- containerBehaviours: derive$1([Dragging.config({
- mode: "mouse",
- blockerClass: "blocker",
- getTarget: function(handle2) {
- return closest$1(handle2, '[role="dialog"]').getOrDie();
- },
- snaps: {
- getSnapPoints: function() {
- return [];
- },
- leftAttr: "data-drag-left",
- topAttr: "data-drag-top"
- }
- })])
- });
- };
- var renderModalHeader = function(spec, providersBackstage) {
- var pTitle = ModalDialog.parts.title(renderTitle(spec, Optional.none(), providersBackstage));
- var pHandle = ModalDialog.parts.draghandle(renderDragHandle());
- var pClose2 = ModalDialog.parts.close(renderClose(providersBackstage));
- var components2 = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose2]);
- return Container.sketch({
- dom: fromHtml('<div class="tox-dialog__header"></div>'),
- components: components2
- });
- };
- var getHeader = function(title, backstage) {
- return renderModalHeader({
- title: backstage.shared.providers.translate(title),
- draggable: backstage.dialog.isDraggableModal()
- }, backstage.shared.providers);
- };
- var getBusySpec = function(message, bs, providers) {
- return {
- dom: {
- tag: "div",
- classes: ["tox-dialog__busy-spinner"],
- attributes: { "aria-label": providers.translate(message) },
- styles: {
- left: "0px",
- right: "0px",
- bottom: "0px",
- top: "0px",
- position: "absolute"
- }
- },
- behaviours: bs,
- components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
- };
- };
- var getEventExtras = function(lazyDialog, providers, extra) {
- return {
- onClose: function() {
- return extra.closeWindow();
- },
- onBlock: function(blockEvent) {
- ModalDialog.setBusy(lazyDialog(), function(_comp, bs) {
- return getBusySpec(blockEvent.message, bs, providers);
- });
- },
- onUnblock: function() {
- ModalDialog.setIdle(lazyDialog());
- }
- };
- };
- var renderModalDialog = function(spec, initialData, dialogEvents, backstage) {
- var _a2;
- var updateState = function(_comp, incoming) {
- return Optional.some(incoming);
- };
- return build$1(renderDialog$1(__assign(__assign({}, spec), {
- lazySink: backstage.shared.getSink,
- extraBehaviours: __spreadArray([
- Reflecting.config({
- channel: dialogChannel,
- updateState,
- initialData
- }),
- RepresentingConfigs.memory({})
- ], spec.extraBehaviours, true),
- onEscape: function(comp) {
- emit(comp, formCancelEvent);
- },
- dialogEvents,
- eventOrder: (_a2 = {}, _a2[receive()] = [
- Reflecting.name(),
- Receiving.name()
- ], _a2[attachedToDom()] = [
- "scroll-lock",
- Reflecting.name(),
- "messages",
- "dialog-events",
- "alloy.base.behaviour"
- ], _a2[detachedFromDom()] = [
- "alloy.base.behaviour",
- "dialog-events",
- "messages",
- Reflecting.name(),
- "scroll-lock"
- ], _a2)
- })));
- };
- var mapMenuButtons = function(buttons) {
- var mapItems = function(button2) {
- var items = map$2(button2.items, function(item2) {
- var cell = Cell(false);
- return __assign(__assign({}, item2), { storage: cell });
- });
- return __assign(__assign({}, button2), { items });
- };
- return map$2(buttons, function(button2) {
- if (button2.type === "menu") {
- return mapItems(button2);
- }
- return button2;
- });
- };
- var extractCellsToObject = function(buttons) {
- return foldl(buttons, function(acc, button2) {
- if (button2.type === "menu") {
- var menuButton = button2;
- return foldl(menuButton.items, function(innerAcc, item2) {
- innerAcc[item2.name] = item2.storage;
- return innerAcc;
- }, acc);
- }
- return acc;
- }, {});
- };
- var initCommonEvents = function(fireApiEvent, extras) {
- return [
- runWithTarget(focusin(), onFocus),
- fireApiEvent(formCloseEvent, function(_api, spec) {
- extras.onClose();
- spec.onClose();
- }),
- fireApiEvent(formCancelEvent, function(api2, spec, _event, self2) {
- spec.onCancel(api2);
- emit(self2, formCloseEvent);
- }),
- run$1(formUnblockEvent, function(_c, _se) {
- return extras.onUnblock();
- }),
- run$1(formBlockEvent, function(_c, se) {
- return extras.onBlock(se.event);
- })
- ];
- };
- var initUrlDialog = function(getInstanceApi, extras) {
- var fireApiEvent = function(eventName, f) {
- return run$1(eventName, function(c, se) {
- withSpec(c, function(spec, _c) {
- f(getInstanceApi(), spec, se.event, c);
- });
- });
- };
- var withSpec = function(c, f) {
- Reflecting.getState(c).get().each(function(currentDialog) {
- f(currentDialog, c);
- });
- };
- return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [fireApiEvent(formActionEvent, function(api2, spec, event) {
- spec.onAction(api2, { name: event.name });
- })], false);
- };
- var initDialog = function(getInstanceApi, extras, getSink2) {
- var fireApiEvent = function(eventName, f) {
- return run$1(eventName, function(c, se) {
- withSpec(c, function(spec, _c) {
- f(getInstanceApi(), spec, se.event, c);
- });
- });
- };
- var withSpec = function(c, f) {
- Reflecting.getState(c).get().each(function(currentDialogInit) {
- f(currentDialogInit.internalDialog, c);
- });
- };
- return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [
- fireApiEvent(formSubmitEvent, function(api2, spec) {
- return spec.onSubmit(api2);
- }),
- fireApiEvent(formChangeEvent, function(api2, spec, event) {
- spec.onChange(api2, { name: event.name });
- }),
- fireApiEvent(formActionEvent, function(api2, spec, event, component) {
- var focusIn2 = function() {
- return Keying.focusIn(component);
- };
- var isDisabled2 = function(focused) {
- return has$1(focused, "disabled") || getOpt(focused, "aria-disabled").exists(function(val) {
- return val === "true";
- });
- };
- var rootNode = getRootNode(component.element);
- var current = active(rootNode);
- spec.onAction(api2, {
- name: event.name,
- value: event.value
- });
- active(rootNode).fold(focusIn2, function(focused) {
- if (isDisabled2(focused)) {
- focusIn2();
- } else if (current.exists(function(cur) {
- return contains(focused, cur) && isDisabled2(cur);
- })) {
- focusIn2();
- } else {
- getSink2().toOptional().filter(function(sink) {
- return !contains(sink.element, focused);
- }).each(focusIn2);
- }
- });
- }),
- fireApiEvent(formTabChangeEvent, function(api2, spec, event) {
- spec.onTabChange(api2, {
- newTabName: event.name,
- oldTabName: event.oldName
- });
- }),
- runOnDetached(function(component) {
- var api2 = getInstanceApi();
- Representing.setValue(component, api2.getData());
- })
- ], false);
- };
- var SilverDialogEvents = {
- initUrlDialog,
- initDialog
- };
- var makeButton = function(button2, backstage) {
- return renderFooterButton(button2, button2.type, backstage);
- };
- var lookup = function(compInSystem, footerButtons, buttonName) {
- return find$5(footerButtons, function(button2) {
- return button2.name === buttonName;
- }).bind(function(memButton) {
- return memButton.memento.getOpt(compInSystem);
- });
- };
- var renderComponents = function(_data, state) {
- var footerButtons = state.map(function(s) {
- return s.footerButtons;
- }).getOr([]);
- var buttonGroups = partition$3(footerButtons, function(button2) {
- return button2.align === "start";
- });
- var makeGroup = function(edge2, buttons) {
- return Container.sketch({
- dom: {
- tag: "div",
- classes: ["tox-dialog__footer-" + edge2]
- },
- components: map$2(buttons, function(button2) {
- return button2.memento.asSpec();
- })
- });
- };
- var startButtons = makeGroup("start", buttonGroups.pass);
- var endButtons = makeGroup("end", buttonGroups.fail);
- return [
- startButtons,
- endButtons
- ];
- };
- var renderFooter = function(initSpec, backstage) {
- var updateState = function(_comp, data) {
- var footerButtons = map$2(data.buttons, function(button2) {
- var memButton = record(makeButton(button2, backstage));
- return {
- name: button2.name,
- align: button2.align,
- memento: memButton
- };
- });
- var lookupByName = function(compInSystem, buttonName) {
- return lookup(compInSystem, footerButtons, buttonName);
- };
- return Optional.some({
- lookupByName,
- footerButtons
- });
- };
- return {
- dom: fromHtml('<div class="tox-dialog__footer"></div>'),
- components: [],
- behaviours: derive$1([Reflecting.config({
- channel: footerChannel,
- initialData: initSpec,
- updateState,
- renderComponents
- })])
- };
- };
- var renderInlineFooter = function(initSpec, backstage) {
- return renderFooter(initSpec, backstage);
- };
- var renderModalFooter = function(initSpec, backstage) {
- return ModalDialog.parts.footer(renderFooter(initSpec, backstage));
- };
- var getCompByName = function(access, name2) {
- var root = access.getRoot();
- if (root.getSystem().isConnected()) {
- var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
- return Form.getField(form_1, name2).fold(function() {
- var footer = access.getFooter();
- var footerState = Reflecting.getState(footer);
- return footerState.get().bind(function(f) {
- return f.lookupByName(form_1, name2);
- });
- }, function(comp) {
- return Optional.some(comp);
- });
- } else {
- return Optional.none();
- }
- };
- var validateData$1 = function(access, data) {
- var root = access.getRoot();
- return Reflecting.getState(root).get().map(function(dialogState) {
- return getOrDie(asRaw("data", dialogState.dataValidator, data));
- }).getOr(data);
- };
- var getDialogApi = function(access, doRedial, menuItemStates) {
- var withRoot = function(f) {
- var root = access.getRoot();
- if (root.getSystem().isConnected()) {
- f(root);
- }
- };
- var getData2 = function() {
- var root = access.getRoot();
- var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
- var representedValues = Representing.getValue(valueComp);
- var menuItemCurrentState = map$1(menuItemStates, function(cell) {
- return cell.get();
- });
- return __assign(__assign({}, representedValues), menuItemCurrentState);
- };
- var setData = function(newData) {
- withRoot(function(_) {
- var prevData = instanceApi.getData();
- var mergedData = __assign(__assign({}, prevData), newData);
- var newInternalData = validateData$1(access, mergedData);
- var form = access.getFormWrapper();
- Representing.setValue(form, newInternalData);
- each(menuItemStates, function(v, k) {
- if (has$2(mergedData, k)) {
- v.set(mergedData[k]);
- }
- });
- });
- };
- var disable2 = function(name2) {
- getCompByName(access, name2).each(Disabling.disable);
- };
- var enable2 = function(name2) {
- getCompByName(access, name2).each(Disabling.enable);
- };
- var focus2 = function(name2) {
- getCompByName(access, name2).each(Focusing.focus);
- };
- var block2 = function(message) {
- if (!isString(message)) {
- throw new Error("The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument");
- }
- withRoot(function(root) {
- emitWith(root, formBlockEvent, { message });
- });
- };
- var unblock2 = function() {
- withRoot(function(root) {
- emit(root, formUnblockEvent);
- });
- };
- var showTab2 = function(name2) {
- withRoot(function(_) {
- var body2 = access.getBody();
- var bodyState = Reflecting.getState(body2);
- if (bodyState.get().exists(function(b2) {
- return b2.isTabPanel();
- })) {
- Composing.getCurrent(body2).each(function(tabSection) {
- TabSection.showTab(tabSection, name2);
- });
- }
- });
- };
- var redial = function(d) {
- withRoot(function(root) {
- var dialogInit = doRedial(d);
- root.getSystem().broadcastOn([dialogChannel], dialogInit);
- root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
- root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
- root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
- instanceApi.setData(dialogInit.initialData);
- });
- };
- var close2 = function() {
- withRoot(function(root) {
- emit(root, formCloseEvent);
- });
- };
- var instanceApi = {
- getData: getData2,
- setData,
- disable: disable2,
- enable: enable2,
- focus: focus2,
- block: block2,
- unblock: unblock2,
- showTab: showTab2,
- redial,
- close: close2
- };
- return instanceApi;
- };
- var getDialogSizeClasses = function(size) {
- switch (size) {
- case "large":
- return ["tox-dialog--width-lg"];
- case "medium":
- return ["tox-dialog--width-md"];
- default:
- return [];
- }
- };
- var renderDialog = function(dialogInit, extra, backstage) {
- var header = getHeader(dialogInit.internalDialog.title, backstage);
- var body2 = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
- var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
- var objOfCells = extractCellsToObject(storagedMenuButtons);
- var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
- var dialogEvents = SilverDialogEvents.initDialog(function() {
- return instanceApi;
- }, getEventExtras(function() {
- return dialog;
- }, backstage.shared.providers, extra), backstage.shared.getSink);
- var dialogSize = getDialogSizeClasses(dialogInit.internalDialog.size);
- var spec = {
- header,
- body: body2,
- footer: Optional.some(footer),
- extraClasses: dialogSize,
- extraBehaviours: [],
- extraStyles: {}
- };
- var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
- var modalAccess = function() {
- var getForm = function() {
- var outerForm = ModalDialog.getBody(dialog);
- return Composing.getCurrent(outerForm).getOr(outerForm);
- };
- return {
- getRoot: constant$1(dialog),
- getBody: function() {
- return ModalDialog.getBody(dialog);
- },
- getFooter: function() {
- return ModalDialog.getFooter(dialog);
- },
- getFormWrapper: getForm
- };
- }();
- var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
- return {
- dialog,
- instanceApi
- };
- };
- var renderInlineDialog = function(dialogInit, extra, backstage, ariaAttrs) {
- var _a2, _b;
- var dialogLabelId = generate$6("dialog-label");
- var dialogContentId = generate$6("dialog-content");
- var updateState = function(_comp, incoming) {
- return Optional.some(incoming);
- };
- var memHeader = record(renderInlineHeader({
- title: dialogInit.internalDialog.title,
- draggable: true
- }, dialogLabelId, backstage.shared.providers));
- var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
- var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
- var objOfCells = extractCellsToObject(storagedMenuButtons);
- var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
- var dialogEvents = SilverDialogEvents.initDialog(function() {
- return instanceApi;
- }, {
- onBlock: function(event) {
- Blocking.block(dialog, function(_comp, bs) {
- return getBusySpec(event.message, bs, backstage.shared.providers);
- });
- },
- onUnblock: function() {
- Blocking.unblock(dialog);
- },
- onClose: function() {
- return extra.closeWindow();
- }
- }, backstage.shared.getSink);
- var dialog = build$1({
- dom: {
- tag: "div",
- classes: [
- "tox-dialog",
- "tox-dialog-inline"
- ],
- attributes: (_a2 = { role: "dialog" }, _a2["aria-labelledby"] = dialogLabelId, _a2["aria-describedby"] = dialogContentId, _a2)
- },
- eventOrder: (_b = {}, _b[receive()] = [
- Reflecting.name(),
- Receiving.name()
- ], _b[execute$5()] = ["execute-on-form"], _b[attachedToDom()] = [
- "reflecting",
- "execute-on-form"
- ], _b),
- behaviours: derive$1([
- Keying.config({
- mode: "cyclic",
- onEscape: function(c) {
- emit(c, formCloseEvent);
- return Optional.some(true);
- },
- useTabstopAt: function(elem) {
- return !isPseudoStop(elem) && (name$2(elem) !== "button" || get$d(elem, "disabled") !== "disabled");
- }
- }),
- Reflecting.config({
- channel: dialogChannel,
- updateState,
- initialData: dialogInit
- }),
- Focusing.config({}),
- config("execute-on-form", dialogEvents.concat([runOnSource(focusin(), function(comp, _se) {
- Keying.focusIn(comp);
- })])),
- Blocking.config({
- getRoot: function() {
- return Optional.some(dialog);
- }
- }),
- Replacing.config({}),
- RepresentingConfigs.memory({})
- ]),
- components: [
- memHeader.asSpec(),
- memBody.asSpec(),
- memFooter.asSpec()
- ]
- });
- var instanceApi = getDialogApi({
- getRoot: constant$1(dialog),
- getFooter: function() {
- return memFooter.get(dialog);
- },
- getBody: function() {
- return memBody.get(dialog);
- },
- getFormWrapper: function() {
- var body2 = memBody.get(dialog);
- return Composing.getCurrent(body2).getOr(body2);
- }
- }, extra.redial, objOfCells);
- return {
- dialog,
- instanceApi
- };
- };
- var global$1 = tinymce.util.Tools.resolve("tinymce.util.URI");
- var getUrlDialogApi = function(root) {
- var withRoot = function(f) {
- if (root.getSystem().isConnected()) {
- f(root);
- }
- };
- var block2 = function(message) {
- if (!isString(message)) {
- throw new Error("The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument");
- }
- withRoot(function(root2) {
- emitWith(root2, formBlockEvent, { message });
- });
- };
- var unblock2 = function() {
- withRoot(function(root2) {
- emit(root2, formUnblockEvent);
- });
- };
- var close2 = function() {
- withRoot(function(root2) {
- emit(root2, formCloseEvent);
- });
- };
- var sendMessage = function(data) {
- withRoot(function(root2) {
- root2.getSystem().broadcastOn([bodySendMessageChannel], data);
- });
- };
- return {
- block: block2,
- unblock: unblock2,
- close: close2,
- sendMessage
- };
- };
- var SUPPORTED_MESSAGE_ACTIONS = [
- "insertContent",
- "setContent",
- "execCommand",
- "close",
- "block",
- "unblock"
- ];
- var isSupportedMessage = function(data) {
- return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
- };
- var isCustomMessage = function(data) {
- return !isSupportedMessage(data) && isObject(data) && has$2(data, "mceAction");
- };
- var handleMessage = function(editor, api2, data) {
- switch (data.mceAction) {
- case "insertContent":
- editor.insertContent(data.content);
- break;
- case "setContent":
- editor.setContent(data.content);
- break;
- case "execCommand":
- var ui = isBoolean(data.ui) ? data.ui : false;
- editor.execCommand(data.cmd, ui, data.value);
- break;
- case "close":
- api2.close();
- break;
- case "block":
- api2.block(data.message);
- break;
- case "unblock":
- api2.unblock();
- break;
- }
- };
- var renderUrlDialog = function(internalDialog, extra, editor, backstage) {
- var _a2;
- var header = getHeader(internalDialog.title, backstage);
- var body2 = renderIframeBody(internalDialog);
- var footer = internalDialog.buttons.bind(function(buttons) {
- if (buttons.length === 0) {
- return Optional.none();
- } else {
- return Optional.some(renderModalFooter({ buttons }, backstage));
- }
- });
- var dialogEvents = SilverDialogEvents.initUrlDialog(function() {
- return instanceApi;
- }, getEventExtras(function() {
- return dialog;
- }, backstage.shared.providers, extra));
- var styles = __assign(__assign({}, internalDialog.height.fold(function() {
- return {};
- }, function(height2) {
- return {
- "height": height2 + "px",
- "max-height": height2 + "px"
- };
- })), internalDialog.width.fold(function() {
- return {};
- }, function(width2) {
- return {
- "width": width2 + "px",
- "max-width": width2 + "px"
- };
- }));
- var classes2 = internalDialog.width.isNone() && internalDialog.height.isNone() ? ["tox-dialog--width-lg"] : [];
- var iframeUri = new global$1(internalDialog.url, { base_uri: new global$1(window.location.href) });
- var iframeDomain = iframeUri.protocol + "://" + iframeUri.host + (iframeUri.port ? ":" + iframeUri.port : "");
- var messageHandlerUnbinder = unbindable();
- var extraBehaviours = [
- config("messages", [
- runOnAttached(function() {
- var unbind2 = bind(SugarElement.fromDom(window), "message", function(e) {
- if (iframeUri.isSameOrigin(new global$1(e.raw.origin))) {
- var data = e.raw.data;
- if (isSupportedMessage(data)) {
- handleMessage(editor, instanceApi, data);
- } else if (isCustomMessage(data)) {
- internalDialog.onMessage(instanceApi, data);
- }
- }
- });
- messageHandlerUnbinder.set(unbind2);
- }),
- runOnDetached(messageHandlerUnbinder.clear)
- ]),
- Receiving.config({
- channels: (_a2 = {}, _a2[bodySendMessageChannel] = {
- onReceive: function(comp, data) {
- descendant(comp.element, "iframe").each(function(iframeEle) {
- var iframeWin = iframeEle.dom.contentWindow;
- iframeWin.postMessage(data, iframeDomain);
- });
- }
- }, _a2)
- })
- ];
- var spec = {
- header,
- body: body2,
- footer,
- extraClasses: classes2,
- extraBehaviours,
- extraStyles: styles
- };
- var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
- var instanceApi = getUrlDialogApi(dialog);
- return {
- dialog,
- instanceApi
- };
- };
- var setup$2 = function(extras) {
- var sharedBackstage = extras.backstage.shared;
- var open2 = function(message, callback) {
- var closeDialog = function() {
- ModalDialog.hide(alertDialog);
- callback();
- };
- var memFooterClose = record(renderFooterButton({
- name: "close-alert",
- text: "OK",
- primary: true,
- align: "end",
- disabled: false,
- icon: Optional.none()
- }, "cancel", extras.backstage));
- var titleSpec = pUntitled();
- var closeSpec = pClose(closeDialog, sharedBackstage.providers);
- var alertDialog = build$1(renderDialog$1({
- lazySink: function() {
- return sharedBackstage.getSink();
- },
- header: hiddenHeader(titleSpec, closeSpec),
- body: pBodyMessage(message, sharedBackstage.providers),
- footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
- onEscape: closeDialog,
- extraClasses: ["tox-alert-dialog"],
- extraBehaviours: [],
- extraStyles: {},
- dialogEvents: [run$1(formCancelEvent, closeDialog)],
- eventOrder: {}
- }));
- ModalDialog.show(alertDialog);
- var footerCloseButton = memFooterClose.get(alertDialog);
- Focusing.focus(footerCloseButton);
- };
- return { open: open2 };
- };
- var setup$1 = function(extras) {
- var sharedBackstage = extras.backstage.shared;
- var open2 = function(message, callback) {
- var closeDialog = function(state) {
- ModalDialog.hide(confirmDialog);
- callback(state);
- };
- var memFooterYes = record(renderFooterButton({
- name: "yes",
- text: "Yes",
- primary: true,
- align: "end",
- disabled: false,
- icon: Optional.none()
- }, "submit", extras.backstage));
- var footerNo = renderFooterButton({
- name: "no",
- text: "No",
- primary: false,
- align: "end",
- disabled: false,
- icon: Optional.none()
- }, "cancel", extras.backstage);
- var titleSpec = pUntitled();
- var closeSpec = pClose(function() {
- return closeDialog(false);
- }, sharedBackstage.providers);
- var confirmDialog = build$1(renderDialog$1({
- lazySink: function() {
- return sharedBackstage.getSink();
- },
- header: hiddenHeader(titleSpec, closeSpec),
- body: pBodyMessage(message, sharedBackstage.providers),
- footer: Optional.some(pFooter(pFooterGroup([], [
- footerNo,
- memFooterYes.asSpec()
- ]))),
- onEscape: function() {
- return closeDialog(false);
- },
- extraClasses: ["tox-confirm-dialog"],
- extraBehaviours: [],
- extraStyles: {},
- dialogEvents: [
- run$1(formCancelEvent, function() {
- return closeDialog(false);
- }),
- run$1(formSubmitEvent, function() {
- return closeDialog(true);
- })
- ],
- eventOrder: {}
- }));
- ModalDialog.show(confirmDialog);
- var footerYesButton = memFooterYes.get(confirmDialog);
- Focusing.focus(footerYesButton);
- };
- return { open: open2 };
- };
- var validateData = function(data, validator) {
- return getOrDie(asRaw("data", validator, data));
- };
- var isAlertOrConfirmDialog = function(target) {
- return closest(target, ".tox-alert-dialog") || closest(target, ".tox-confirm-dialog");
- };
- var inlineAdditionalBehaviours = function(editor, isStickyToolbar2, isToolbarLocationTop) {
- if (isStickyToolbar2 && isToolbarLocationTop) {
- return [];
- } else {
- return [Docking.config({
- contextual: {
- lazyContext: function() {
- return Optional.some(box$1(SugarElement.fromDom(editor.getContentAreaContainer())));
- },
- fadeInClass: "tox-dialog-dock-fadein",
- fadeOutClass: "tox-dialog-dock-fadeout",
- transitionClass: "tox-dialog-dock-transition"
- },
- modes: ["top"]
- })];
- }
- };
- var setup = function(extras) {
- var backstage = extras.backstage;
- var editor = extras.editor;
- var isStickyToolbar$1 = isStickyToolbar(editor);
- var alertDialog = setup$2(extras);
- var confirmDialog = setup$1(extras);
- var open2 = function(config2, params, closeWindow) {
- if (params !== void 0 && params.inline === "toolbar") {
- return openInlineDialog(config2, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
- } else if (params !== void 0 && params.inline === "cursor") {
- return openInlineDialog(config2, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
- } else {
- return openModalDialog(config2, closeWindow);
- }
- };
- var openUrl = function(config2, closeWindow) {
- return openModalUrlDialog(config2, closeWindow);
- };
- var openModalUrlDialog = function(config2, closeWindow) {
- var factory2 = function(contents2) {
- var dialog = renderUrlDialog(contents2, {
- closeWindow: function() {
- ModalDialog.hide(dialog.dialog);
- closeWindow(dialog.instanceApi);
- }
- }, editor, backstage);
- ModalDialog.show(dialog.dialog);
- return dialog.instanceApi;
- };
- return DialogManager.openUrl(factory2, config2);
- };
- var openModalDialog = function(config2, closeWindow) {
- var factory2 = function(contents2, internalInitialData, dataValidator) {
- var initialData = internalInitialData;
- var dialogInit = {
- dataValidator,
- initialData,
- internalDialog: contents2
- };
- var dialog = renderDialog(dialogInit, {
- redial: DialogManager.redial,
- closeWindow: function() {
- ModalDialog.hide(dialog.dialog);
- closeWindow(dialog.instanceApi);
- }
- }, backstage);
- ModalDialog.show(dialog.dialog);
- dialog.instanceApi.setData(initialData);
- return dialog.instanceApi;
- };
- return DialogManager.open(factory2, config2);
- };
- var openInlineDialog = function(config$1, anchor2, closeWindow, ariaAttrs) {
- var factory2 = function(contents2, internalInitialData, dataValidator) {
- var initialData = validateData(internalInitialData, dataValidator);
- var inlineDialog = value$1();
- var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
- var dialogInit = {
- dataValidator,
- initialData,
- internalDialog: contents2
- };
- var refreshDocking = function() {
- return inlineDialog.on(function(dialog) {
- InlineView.reposition(dialog);
- Docking.refresh(dialog);
- });
- };
- var dialogUi = renderInlineDialog(dialogInit, {
- redial: DialogManager.redial,
- closeWindow: function() {
- inlineDialog.on(InlineView.hide);
- editor.off("ResizeEditor", refreshDocking);
- inlineDialog.clear();
- closeWindow(dialogUi.instanceApi);
- }
- }, backstage, ariaAttrs);
- var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
- lazySink: backstage.shared.getSink,
- dom: {
- tag: "div",
- classes: []
- },
- fireDismissalEventInstead: {}
- }, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), {
- inlineBehaviours: derive$1(__spreadArray([config("window-manager-inline-events", [run$1(dismissRequested(), function(_comp, _se) {
- emit(dialogUi.dialog, formCancelEvent);
- })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop), true)),
- isExtraPart: function(_comp, target) {
- return isAlertOrConfirmDialog(target);
- }
- })));
- inlineDialog.set(inlineDialogComp);
- InlineView.showWithin(inlineDialogComp, premade(dialogUi.dialog), { anchor: anchor2 }, Optional.some(body()));
- if (!isStickyToolbar$1 || !isToolbarLocationTop) {
- Docking.refresh(inlineDialogComp);
- editor.on("ResizeEditor", refreshDocking);
- }
- dialogUi.instanceApi.setData(initialData);
- Keying.focusIn(dialogUi.dialog);
- return dialogUi.instanceApi;
- };
- return DialogManager.open(factory2, config$1);
- };
- var confirm = function(message, callback) {
- confirmDialog.open(message, function(state) {
- callback(state);
- });
- };
- var alert = function(message, callback) {
- alertDialog.open(message, function() {
- callback();
- });
- };
- var close2 = function(instanceApi) {
- instanceApi.close();
- };
- return {
- open: open2,
- openUrl,
- alert,
- close: close2,
- confirm
- };
- };
- function Theme() {
- global$g.add("silver", function(editor) {
- var _a2 = setup$3(editor), uiMothership = _a2.uiMothership, backstage = _a2.backstage, renderUI = _a2.renderUI, getUi = _a2.getUi;
- Autocompleter.register(editor, backstage.shared);
- var windowMgr = setup({
- editor,
- backstage
- });
- return {
- renderUI,
- getWindowManagerImpl: constant$1(windowMgr),
- getNotificationManagerImpl: function() {
- return NotificationManagerImpl(editor, { backstage }, uiMothership);
- },
- ui: getUi()
- };
- });
- }
- Theme();
- })();
- }
- });
- // node_modules/.pnpm/tinymce@5.10.7/node_modules/tinymce/themes/silver/index.js
- require_theme();
- //# sourceMappingURL=tinymce_themes_silver.js.map
|