12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591 |
- /*!
- * bpmn-js - bpmn-navigated-viewer v9.2.2
- *
- * Copyright (c) 2014-present, camunda Services GmbH
- *
- * Released under the bpmn.io license
- * http://bpmn.io/license
- *
- * Source Code: https://github.com/bpmn-io/bpmn-js
- *
- * Date: 2022-06-21
- */
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.BpmnJS = factory());
- }(this, (function () { 'use strict';
- function e(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}));}
- /**
- * Flatten array, one level deep.
- *
- * @param {Array<?>} arr
- *
- * @return {Array<?>}
- */
- var nativeToString$1 = Object.prototype.toString;
- var nativeHasOwnProperty$1 = Object.prototype.hasOwnProperty;
- function isUndefined$2(obj) {
- return obj === undefined;
- }
- function isDefined(obj) {
- return obj !== undefined;
- }
- function isArray$2(obj) {
- return nativeToString$1.call(obj) === '[object Array]';
- }
- function isObject(obj) {
- return nativeToString$1.call(obj) === '[object Object]';
- }
- function isNumber(obj) {
- return nativeToString$1.call(obj) === '[object Number]';
- }
- function isFunction(obj) {
- var tag = nativeToString$1.call(obj);
- return tag === '[object Function]' || tag === '[object AsyncFunction]' || tag === '[object GeneratorFunction]' || tag === '[object AsyncGeneratorFunction]' || tag === '[object Proxy]';
- }
- function isString(obj) {
- return nativeToString$1.call(obj) === '[object String]';
- }
- /**
- * Return true, if target owns a property with the given key.
- *
- * @param {Object} target
- * @param {String} key
- *
- * @return {Boolean}
- */
- function has$1(target, key) {
- return nativeHasOwnProperty$1.call(target, key);
- }
- /**
- * Find element in collection.
- *
- * @param {Array|Object} collection
- * @param {Function|Object} matcher
- *
- * @return {Object}
- */
- function find(collection, matcher) {
- matcher = toMatcher(matcher);
- var match;
- forEach$1(collection, function (val, key) {
- if (matcher(val, key)) {
- match = val;
- return false;
- }
- });
- return match;
- }
- /**
- * Find element in collection.
- *
- * @param {Array|Object} collection
- * @param {Function} matcher
- *
- * @return {Array} result
- */
- function filter(collection, matcher) {
- var result = [];
- forEach$1(collection, function (val, key) {
- if (matcher(val, key)) {
- result.push(val);
- }
- });
- return result;
- }
- /**
- * Iterate over collection; returning something
- * (non-undefined) will stop iteration.
- *
- * @param {Array|Object} collection
- * @param {Function} iterator
- *
- * @return {Object} return result that stopped the iteration
- */
- function forEach$1(collection, iterator) {
- var val, result;
- if (isUndefined$2(collection)) {
- return;
- }
- var convertKey = isArray$2(collection) ? toNum$1 : identity$1;
- for (var key in collection) {
- if (has$1(collection, key)) {
- val = collection[key];
- result = iterator(val, convertKey(key));
- if (result === false) {
- return val;
- }
- }
- }
- }
- /**
- * Reduce collection, returning a single result.
- *
- * @param {Object|Array} collection
- * @param {Function} iterator
- * @param {Any} result
- *
- * @return {Any} result returned from last iterator
- */
- function reduce(collection, iterator, result) {
- forEach$1(collection, function (value, idx) {
- result = iterator(result, value, idx);
- });
- return result;
- }
- /**
- * Return true if every element in the collection
- * matches the criteria.
- *
- * @param {Object|Array} collection
- * @param {Function} matcher
- *
- * @return {Boolean}
- */
- function every(collection, matcher) {
- return !!reduce(collection, function (matches, val, key) {
- return matches && matcher(val, key);
- }, true);
- }
- /**
- * Return true if some elements in the collection
- * match the criteria.
- *
- * @param {Object|Array} collection
- * @param {Function} matcher
- *
- * @return {Boolean}
- */
- function some(collection, matcher) {
- return !!find(collection, matcher);
- }
- /**
- * Transform a collection into another collection
- * by piping each member through the given fn.
- *
- * @param {Object|Array} collection
- * @param {Function} fn
- *
- * @return {Array} transformed collection
- */
- function map(collection, fn) {
- var result = [];
- forEach$1(collection, function (val, key) {
- result.push(fn(val, key));
- });
- return result;
- }
- /**
- * Create an object pattern matcher.
- *
- * @example
- *
- * const matcher = matchPattern({ id: 1 });
- *
- * let element = find(elements, matcher);
- *
- * @param {Object} pattern
- *
- * @return {Function} matcherFn
- */
- function matchPattern(pattern) {
- return function (el) {
- return every(pattern, function (val, key) {
- return el[key] === val;
- });
- };
- }
- function toMatcher(matcher) {
- return isFunction(matcher) ? matcher : function (e) {
- return e === matcher;
- };
- }
- function identity$1(arg) {
- return arg;
- }
- function toNum$1(arg) {
- return Number(arg);
- }
- /**
- * Debounce fn, calling it only once if the given time
- * elapsed between calls.
- *
- * Lodash-style the function exposes methods to `#clear`
- * and `#flush` to control internal behavior.
- *
- * @param {Function} fn
- * @param {Number} timeout
- *
- * @return {Function} debounced function
- */
- function debounce(fn, timeout) {
- var timer;
- var lastArgs;
- var lastThis;
- var lastNow;
- function fire(force) {
- var now = Date.now();
- var scheduledDiff = force ? 0 : lastNow + timeout - now;
- if (scheduledDiff > 0) {
- return schedule(scheduledDiff);
- }
- fn.apply(lastThis, lastArgs);
- clear();
- }
- function schedule(timeout) {
- timer = setTimeout(fire, timeout);
- }
- function clear() {
- if (timer) {
- clearTimeout(timer);
- }
- timer = lastNow = lastArgs = lastThis = undefined;
- }
- function flush() {
- if (timer) {
- fire(true);
- }
- clear();
- }
- function callback() {
- lastNow = Date.now();
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- lastArgs = args;
- lastThis = this; // ensure an execution is scheduled
- if (!timer) {
- schedule(timeout);
- }
- }
- callback.flush = flush;
- callback.cancel = clear;
- return callback;
- }
- /**
- * Bind function against target <this>.
- *
- * @param {Function} fn
- * @param {Object} target
- *
- * @return {Function} bound function
- */
- function bind(fn, target) {
- return fn.bind(target);
- }
- function _extends() {
- _extends = Object.assign || function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
- }
- /**
- * Convenience wrapper for `Object.assign`.
- *
- * @param {Object} target
- * @param {...Object} others
- *
- * @return {Object} the target
- */
- function assign(target) {
- for (var _len = arguments.length, others = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- others[_key - 1] = arguments[_key];
- }
- return _extends.apply(void 0, [target].concat(others));
- }
- /**
- * Pick given properties from the target object.
- *
- * @param {Object} target
- * @param {Array} properties
- *
- * @return {Object} target
- */
- function pick(target, properties) {
- var result = {};
- var obj = Object(target);
- forEach$1(properties, function (prop) {
- if (prop in obj) {
- result[prop] = target[prop];
- }
- });
- return result;
- }
- /**
- * Pick all target properties, excluding the given ones.
- *
- * @param {Object} target
- * @param {Array} properties
- *
- * @return {Object} target
- */
- function omit(target, properties) {
- var result = {};
- var obj = Object(target);
- forEach$1(obj, function (prop, key) {
- if (properties.indexOf(key) === -1) {
- result[key] = prop;
- }
- });
- return result;
- }
- var DEFAULT_RENDER_PRIORITY$1 = 1000;
- /**
- * The base implementation of shape and connection renderers.
- *
- * @param {EventBus} eventBus
- * @param {number} [renderPriority=1000]
- */
- function BaseRenderer(eventBus, renderPriority) {
- var self = this;
- renderPriority = renderPriority || DEFAULT_RENDER_PRIORITY$1;
- eventBus.on([ 'render.shape', 'render.connection' ], renderPriority, function(evt, context) {
- var type = evt.type,
- element = context.element,
- visuals = context.gfx,
- attrs = context.attrs;
- if (self.canRender(element)) {
- if (type === 'render.shape') {
- return self.drawShape(visuals, element, attrs);
- } else {
- return self.drawConnection(visuals, element, attrs);
- }
- }
- });
- eventBus.on([ 'render.getShapePath', 'render.getConnectionPath' ], renderPriority, function(evt, element) {
- if (self.canRender(element)) {
- if (evt.type === 'render.getShapePath') {
- return self.getShapePath(element);
- } else {
- return self.getConnectionPath(element);
- }
- }
- });
- }
- /**
- * Should check whether *this* renderer can render
- * the element/connection.
- *
- * @param {element} element
- *
- * @returns {boolean}
- */
- BaseRenderer.prototype.canRender = function() {};
- /**
- * Provides the shape's snap svg element to be drawn on the `canvas`.
- *
- * @param {djs.Graphics} visuals
- * @param {Shape} shape
- *
- * @returns {Snap.svg} [returns a Snap.svg paper element ]
- */
- BaseRenderer.prototype.drawShape = function() {};
- /**
- * Provides the shape's snap svg element to be drawn on the `canvas`.
- *
- * @param {djs.Graphics} visuals
- * @param {Connection} connection
- *
- * @returns {Snap.svg} [returns a Snap.svg paper element ]
- */
- BaseRenderer.prototype.drawConnection = function() {};
- /**
- * Gets the SVG path of a shape that represents it's visual bounds.
- *
- * @param {Shape} shape
- *
- * @return {string} svg path
- */
- BaseRenderer.prototype.getShapePath = function() {};
- /**
- * Gets the SVG path of a connection that represents it's visual bounds.
- *
- * @param {Connection} connection
- *
- * @return {string} svg path
- */
- BaseRenderer.prototype.getConnectionPath = function() {};
- /**
- * Is an element of the given BPMN type?
- *
- * @param {djs.model.Base|ModdleElement} element
- * @param {string} type
- *
- * @return {boolean}
- */
- function is$1(element, type) {
- var bo = getBusinessObject(element);
- return bo && (typeof bo.$instanceOf === 'function') && bo.$instanceOf(type);
- }
- /**
- * Return true if element has any of the given types.
- *
- * @param {djs.model.Base} element
- * @param {Array<string>} types
- *
- * @return {boolean}
- */
- function isAny(element, types) {
- return some(types, function(t) {
- return is$1(element, t);
- });
- }
- /**
- * Return the business object for a given element.
- *
- * @param {djs.model.Base|ModdleElement} element
- *
- * @return {ModdleElement}
- */
- function getBusinessObject(element) {
- return (element && element.businessObject) || element;
- }
- /**
- * Return the di object for a given element.
- *
- * @param {djs.model.Base} element
- *
- * @return {ModdleElement}
- */
- function getDi(element) {
- return element && element.di;
- }
- function isExpanded(element, di) {
- if (is$1(element, 'bpmn:CallActivity')) {
- return false;
- }
- if (is$1(element, 'bpmn:SubProcess')) {
- di = di || getDi(element);
- if (di && is$1(di, 'bpmndi:BPMNPlane')) {
- return true;
- }
- return di && !!di.isExpanded;
- }
- if (is$1(element, 'bpmn:Participant')) {
- return !!getBusinessObject(element).processRef;
- }
- return true;
- }
- function isEventSubProcess(element) {
- return element && !!getBusinessObject(element).triggeredByEvent;
- }
- function getLabelAttr(semantic) {
- if (
- is$1(semantic, 'bpmn:FlowElement') ||
- is$1(semantic, 'bpmn:Participant') ||
- is$1(semantic, 'bpmn:Lane') ||
- is$1(semantic, 'bpmn:SequenceFlow') ||
- is$1(semantic, 'bpmn:MessageFlow') ||
- is$1(semantic, 'bpmn:DataInput') ||
- is$1(semantic, 'bpmn:DataOutput')
- ) {
- return 'name';
- }
- if (is$1(semantic, 'bpmn:TextAnnotation')) {
- return 'text';
- }
- if (is$1(semantic, 'bpmn:Group')) {
- return 'categoryValueRef';
- }
- }
- function getCategoryValue(semantic) {
- var categoryValueRef = semantic['categoryValueRef'];
- if (!categoryValueRef) {
- return '';
- }
- return categoryValueRef.value || '';
- }
- function getLabel(element) {
- var semantic = element.businessObject,
- attr = getLabelAttr(semantic);
- if (attr) {
- if (attr === 'categoryValueRef') {
- return getCategoryValue(semantic);
- }
- return semantic[attr] || '';
- }
- }
- function ensureImported(element, target) {
- if (element.ownerDocument !== target.ownerDocument) {
- try {
- // may fail on webkit
- return target.ownerDocument.importNode(element, true);
- } catch (e) {
- // ignore
- }
- }
- return element;
- }
- /**
- * appendTo utility
- */
- /**
- * Append a node to a target element and return the appended node.
- *
- * @param {SVGElement} element
- * @param {SVGElement} target
- *
- * @return {SVGElement} the appended node
- */
- function appendTo(element, target) {
- return target.appendChild(ensureImported(element, target));
- }
- /**
- * append utility
- */
- /**
- * Append a node to an element
- *
- * @param {SVGElement} element
- * @param {SVGElement} node
- *
- * @return {SVGElement} the element
- */
- function append(target, node) {
- appendTo(node, target);
- return target;
- }
- /**
- * attribute accessor utility
- */
- var LENGTH_ATTR = 2;
- var CSS_PROPERTIES = {
- 'alignment-baseline': 1,
- 'baseline-shift': 1,
- 'clip': 1,
- 'clip-path': 1,
- 'clip-rule': 1,
- 'color': 1,
- 'color-interpolation': 1,
- 'color-interpolation-filters': 1,
- 'color-profile': 1,
- 'color-rendering': 1,
- 'cursor': 1,
- 'direction': 1,
- 'display': 1,
- 'dominant-baseline': 1,
- 'enable-background': 1,
- 'fill': 1,
- 'fill-opacity': 1,
- 'fill-rule': 1,
- 'filter': 1,
- 'flood-color': 1,
- 'flood-opacity': 1,
- 'font': 1,
- 'font-family': 1,
- 'font-size': LENGTH_ATTR,
- 'font-size-adjust': 1,
- 'font-stretch': 1,
- 'font-style': 1,
- 'font-variant': 1,
- 'font-weight': 1,
- 'glyph-orientation-horizontal': 1,
- 'glyph-orientation-vertical': 1,
- 'image-rendering': 1,
- 'kerning': 1,
- 'letter-spacing': 1,
- 'lighting-color': 1,
- 'marker': 1,
- 'marker-end': 1,
- 'marker-mid': 1,
- 'marker-start': 1,
- 'mask': 1,
- 'opacity': 1,
- 'overflow': 1,
- 'pointer-events': 1,
- 'shape-rendering': 1,
- 'stop-color': 1,
- 'stop-opacity': 1,
- 'stroke': 1,
- 'stroke-dasharray': 1,
- 'stroke-dashoffset': 1,
- 'stroke-linecap': 1,
- 'stroke-linejoin': 1,
- 'stroke-miterlimit': 1,
- 'stroke-opacity': 1,
- 'stroke-width': LENGTH_ATTR,
- 'text-anchor': 1,
- 'text-decoration': 1,
- 'text-rendering': 1,
- 'unicode-bidi': 1,
- 'visibility': 1,
- 'word-spacing': 1,
- 'writing-mode': 1
- };
- function getAttribute(node, name) {
- if (CSS_PROPERTIES[name]) {
- return node.style[name];
- } else {
- return node.getAttributeNS(null, name);
- }
- }
- function setAttribute(node, name, value) {
- var hyphenated = name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
- var type = CSS_PROPERTIES[hyphenated];
- if (type) {
- // append pixel unit, unless present
- if (type === LENGTH_ATTR && typeof value === 'number') {
- value = String(value) + 'px';
- }
- node.style[hyphenated] = value;
- } else {
- node.setAttributeNS(null, name, value);
- }
- }
- function setAttributes(node, attrs) {
- var names = Object.keys(attrs), i, name;
- for (i = 0, name; (name = names[i]); i++) {
- setAttribute(node, name, attrs[name]);
- }
- }
- /**
- * Gets or sets raw attributes on a node.
- *
- * @param {SVGElement} node
- * @param {Object} [attrs]
- * @param {String} [name]
- * @param {String} [value]
- *
- * @return {String}
- */
- function attr$1(node, name, value) {
- if (typeof name === 'string') {
- if (value !== undefined) {
- setAttribute(node, name, value);
- } else {
- return getAttribute(node, name);
- }
- } else {
- setAttributes(node, name);
- }
- return node;
- }
- /**
- * Clear utility
- */
- function index(arr, obj) {
- if (arr.indexOf) {
- return arr.indexOf(obj);
- }
- for (var i = 0; i < arr.length; ++i) {
- if (arr[i] === obj) {
- return i;
- }
- }
- return -1;
- }
- var re$1 = /\s+/;
- var toString$1 = Object.prototype.toString;
- function defined(o) {
- return typeof o !== 'undefined';
- }
- /**
- * Wrap `el` in a `ClassList`.
- *
- * @param {Element} el
- * @return {ClassList}
- * @api public
- */
- function classes$1(el) {
- return new ClassList$1(el);
- }
- function ClassList$1(el) {
- if (!el || !el.nodeType) {
- throw new Error('A DOM element reference is required');
- }
- this.el = el;
- this.list = el.classList;
- }
- /**
- * Add class `name` if not already present.
- *
- * @param {String} name
- * @return {ClassList}
- * @api public
- */
- ClassList$1.prototype.add = function(name) {
- // classList
- if (this.list) {
- this.list.add(name);
- return this;
- }
- // fallback
- var arr = this.array();
- var i = index(arr, name);
- if (!~i) {
- arr.push(name);
- }
- if (defined(this.el.className.baseVal)) {
- this.el.className.baseVal = arr.join(' ');
- } else {
- this.el.className = arr.join(' ');
- }
- return this;
- };
- /**
- * Remove class `name` when present, or
- * pass a regular expression to remove
- * any which match.
- *
- * @param {String|RegExp} name
- * @return {ClassList}
- * @api public
- */
- ClassList$1.prototype.remove = function(name) {
- if ('[object RegExp]' === toString$1.call(name)) {
- return this.removeMatching(name);
- }
- // classList
- if (this.list) {
- this.list.remove(name);
- return this;
- }
- // fallback
- var arr = this.array();
- var i = index(arr, name);
- if (~i) {
- arr.splice(i, 1);
- }
- this.el.className.baseVal = arr.join(' ');
- return this;
- };
- /**
- * Remove all classes matching `re`.
- *
- * @param {RegExp} re
- * @return {ClassList}
- * @api private
- */
- ClassList$1.prototype.removeMatching = function(re) {
- var arr = this.array();
- for (var i = 0; i < arr.length; i++) {
- if (re.test(arr[i])) {
- this.remove(arr[i]);
- }
- }
- return this;
- };
- /**
- * Toggle class `name`, can force state via `force`.
- *
- * For browsers that support classList, but do not support `force` yet,
- * the mistake will be detected and corrected.
- *
- * @param {String} name
- * @param {Boolean} force
- * @return {ClassList}
- * @api public
- */
- ClassList$1.prototype.toggle = function(name, force) {
- // classList
- if (this.list) {
- if (defined(force)) {
- if (force !== this.list.toggle(name, force)) {
- this.list.toggle(name); // toggle again to correct
- }
- } else {
- this.list.toggle(name);
- }
- return this;
- }
- // fallback
- if (defined(force)) {
- if (!force) {
- this.remove(name);
- } else {
- this.add(name);
- }
- } else {
- if (this.has(name)) {
- this.remove(name);
- } else {
- this.add(name);
- }
- }
- return this;
- };
- /**
- * Return an array of classes.
- *
- * @return {Array}
- * @api public
- */
- ClassList$1.prototype.array = function() {
- var className = this.el.getAttribute('class') || '';
- var str = className.replace(/^\s+|\s+$/g, '');
- var arr = str.split(re$1);
- if ('' === arr[0]) {
- arr.shift();
- }
- return arr;
- };
- /**
- * Check if class `name` is present.
- *
- * @param {String} name
- * @return {ClassList}
- * @api public
- */
- ClassList$1.prototype.has =
- ClassList$1.prototype.contains = function(name) {
- return (
- this.list ?
- this.list.contains(name) :
- !! ~index(this.array(), name)
- );
- };
- function remove$2(element) {
- var parent = element.parentNode;
- if (parent) {
- parent.removeChild(element);
- }
- return element;
- }
- /**
- * Clear utility
- */
- /**
- * Removes all children from the given element
- *
- * @param {DOMElement} element
- * @return {DOMElement} the element (for chaining)
- */
- function clear$1(element) {
- var child;
- while ((child = element.firstChild)) {
- remove$2(child);
- }
- return element;
- }
- var ns = {
- svg: 'http://www.w3.org/2000/svg'
- };
- /**
- * DOM parsing utility
- */
- var SVG_START = '<svg xmlns="' + ns.svg + '"';
- function parse$1(svg) {
- var unwrap = false;
- // ensure we import a valid svg document
- if (svg.substring(0, 4) === '<svg') {
- if (svg.indexOf(ns.svg) === -1) {
- svg = SVG_START + svg.substring(4);
- }
- } else {
- // namespace svg
- svg = SVG_START + '>' + svg + '</svg>';
- unwrap = true;
- }
- var parsed = parseDocument(svg);
- if (!unwrap) {
- return parsed;
- }
- var fragment = document.createDocumentFragment();
- var parent = parsed.firstChild;
- while (parent.firstChild) {
- fragment.appendChild(parent.firstChild);
- }
- return fragment;
- }
- function parseDocument(svg) {
- var parser;
- // parse
- parser = new DOMParser();
- parser.async = false;
- return parser.parseFromString(svg, 'text/xml');
- }
- /**
- * Create utility for SVG elements
- */
- /**
- * Create a specific type from name or SVG markup.
- *
- * @param {String} name the name or markup of the element
- * @param {Object} [attrs] attributes to set on the element
- *
- * @returns {SVGElement}
- */
- function create$1(name, attrs) {
- var element;
- if (name.charAt(0) === '<') {
- element = parse$1(name).firstChild;
- element = document.importNode(element, true);
- } else {
- element = document.createElementNS(ns.svg, name);
- }
- if (attrs) {
- attr$1(element, attrs);
- }
- return element;
- }
- /**
- * Geometry helpers
- */
- // fake node used to instantiate svg geometry elements
- var node = create$1('svg');
- function extend$1(object, props) {
- var i, k, keys = Object.keys(props);
- for (i = 0; (k = keys[i]); i++) {
- object[k] = props[k];
- }
- return object;
- }
- /**
- * Create matrix via args.
- *
- * @example
- *
- * createMatrix({ a: 1, b: 1 });
- * createMatrix();
- * createMatrix(1, 2, 0, 0, 30, 20);
- *
- * @return {SVGMatrix}
- */
- function createMatrix(a, b, c, d, e, f) {
- var matrix = node.createSVGMatrix();
- switch (arguments.length) {
- case 0:
- return matrix;
- case 1:
- return extend$1(matrix, a);
- case 6:
- return extend$1(matrix, {
- a: a,
- b: b,
- c: c,
- d: d,
- e: e,
- f: f
- });
- }
- }
- function createTransform(matrix) {
- if (matrix) {
- return node.createSVGTransformFromMatrix(matrix);
- } else {
- return node.createSVGTransform();
- }
- }
- /**
- * Serialization util
- */
- var TEXT_ENTITIES = /([&<>]{1})/g;
- var ATTR_ENTITIES = /([\n\r"]{1})/g;
- var ENTITY_REPLACEMENT = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '\''
- };
- function escape$1(str, pattern) {
- function replaceFn(match, entity) {
- return ENTITY_REPLACEMENT[entity] || entity;
- }
- return str.replace(pattern, replaceFn);
- }
- function serialize(node, output) {
- var i, len, attrMap, attrNode, childNodes;
- switch (node.nodeType) {
- // TEXT
- case 3:
- // replace special XML characters
- output.push(escape$1(node.textContent, TEXT_ENTITIES));
- break;
- // ELEMENT
- case 1:
- output.push('<', node.tagName);
- if (node.hasAttributes()) {
- attrMap = node.attributes;
- for (i = 0, len = attrMap.length; i < len; ++i) {
- attrNode = attrMap.item(i);
- output.push(' ', attrNode.name, '="', escape$1(attrNode.value, ATTR_ENTITIES), '"');
- }
- }
- if (node.hasChildNodes()) {
- output.push('>');
- childNodes = node.childNodes;
- for (i = 0, len = childNodes.length; i < len; ++i) {
- serialize(childNodes.item(i), output);
- }
- output.push('</', node.tagName, '>');
- } else {
- output.push('/>');
- }
- break;
- // COMMENT
- case 8:
- output.push('<!--', escape$1(node.nodeValue, TEXT_ENTITIES), '-->');
- break;
- // CDATA
- case 4:
- output.push('<![CDATA[', node.nodeValue, ']]>');
- break;
- default:
- throw new Error('unable to handle node ' + node.nodeType);
- }
- return output;
- }
- /**
- * innerHTML like functionality for SVG elements.
- * based on innerSVG (https://code.google.com/p/innersvg)
- */
- function set$1(element, svg) {
- var parsed = parse$1(svg);
- // clear element contents
- clear$1(element);
- if (!svg) {
- return;
- }
- if (!isFragment(parsed)) {
- // extract <svg> from parsed document
- parsed = parsed.documentElement;
- }
- var nodes = slice$1(parsed.childNodes);
- // import + append each node
- for (var i = 0; i < nodes.length; i++) {
- appendTo(nodes[i], element);
- }
- }
- function get(element) {
- var child = element.firstChild,
- output = [];
- while (child) {
- serialize(child, output);
- child = child.nextSibling;
- }
- return output.join('');
- }
- function isFragment(node) {
- return node.nodeName === '#document-fragment';
- }
- function innerSVG(element, svg) {
- if (svg !== undefined) {
- try {
- set$1(element, svg);
- } catch (e) {
- throw new Error('error parsing SVG: ' + e.message);
- }
- return element;
- } else {
- return get(element);
- }
- }
- function slice$1(arr) {
- return Array.prototype.slice.call(arr);
- }
- /**
- * transform accessor utility
- */
- function wrapMatrix(transformList, transform) {
- if (transform instanceof SVGMatrix) {
- return transformList.createSVGTransformFromMatrix(transform);
- }
- return transform;
- }
- function setTransforms(transformList, transforms) {
- var i, t;
- transformList.clear();
- for (i = 0; (t = transforms[i]); i++) {
- transformList.appendItem(wrapMatrix(transformList, t));
- }
- }
- /**
- * Get or set the transforms on the given node.
- *
- * @param {SVGElement} node
- * @param {SVGTransform|SVGMatrix|Array<SVGTransform|SVGMatrix>} [transforms]
- *
- * @return {SVGTransform} the consolidated transform
- */
- function transform$1(node, transforms) {
- var transformList = node.transform.baseVal;
- if (transforms) {
- if (!Array.isArray(transforms)) {
- transforms = [ transforms ];
- }
- setTransforms(transformList, transforms);
- }
- return transformList.consolidate();
- }
- function componentsToPath(elements) {
- return elements.join(',').replace(/,?([A-z]),?/g, '$1');
- }
- function toSVGPoints(points) {
- var result = '';
- for (var i = 0, p; (p = points[i]); i++) {
- result += p.x + ',' + p.y + ' ';
- }
- return result;
- }
- function createLine(points, attrs) {
- var line = create$1('polyline');
- attr$1(line, { points: toSVGPoints(points) });
- if (attrs) {
- attr$1(line, attrs);
- }
- return line;
- }
- function updateLine(gfx, points) {
- attr$1(gfx, { points: toSVGPoints(points) });
- return gfx;
- }
- var black = 'hsl(225, 10%, 15%)';
- // element utils //////////////////////
- /**
- * Checks if eventDefinition of the given element matches with semantic type.
- *
- * @return {boolean} true if element is of the given semantic type
- */
- function isTypedEvent(event, eventDefinitionType, filter) {
- function matches(definition, filter) {
- return every(filter, function(val, key) {
- // we want a == conversion here, to be able to catch
- // undefined == false and friends
- /* jshint -W116 */
- return definition[key] == val;
- });
- }
- return some(event.eventDefinitions, function(definition) {
- return definition.$type === eventDefinitionType && matches(event, filter);
- });
- }
- function isThrowEvent(event) {
- return (event.$type === 'bpmn:IntermediateThrowEvent') || (event.$type === 'bpmn:EndEvent');
- }
- function isCollection(element) {
- var dataObject = element.dataObjectRef;
- return element.isCollection || (dataObject && dataObject.isCollection);
- }
- function getSemantic(element) {
- return element.businessObject;
- }
- // color access //////////////////////
- function getFillColor(element, defaultColor) {
- var di = getDi(element);
- return di.get('color:background-color') || di.get('bioc:fill') || defaultColor || 'white';
- }
- function getStrokeColor(element, defaultColor) {
- var di = getDi(element);
- return di.get('color:border-color') || di.get('bioc:stroke') || defaultColor || black;
- }
- function getLabelColor(element, defaultColor, defaultStrokeColor) {
- var di = getDi(element),
- label = di.get('label');
- return label && label.get('color:color') || defaultColor ||
- getStrokeColor(element, defaultStrokeColor);
- }
- // cropping path customizations //////////////////////
- function getCirclePath(shape) {
- var cx = shape.x + shape.width / 2,
- cy = shape.y + shape.height / 2,
- radius = shape.width / 2;
- var circlePath = [
- ['M', cx, cy],
- ['m', 0, -radius],
- ['a', radius, radius, 0, 1, 1, 0, 2 * radius],
- ['a', radius, radius, 0, 1, 1, 0, -2 * radius],
- ['z']
- ];
- return componentsToPath(circlePath);
- }
- function getRoundRectPath(shape, borderRadius) {
- var x = shape.x,
- y = shape.y,
- width = shape.width,
- height = shape.height;
- var roundRectPath = [
- ['M', x + borderRadius, y],
- ['l', width - borderRadius * 2, 0],
- ['a', borderRadius, borderRadius, 0, 0, 1, borderRadius, borderRadius],
- ['l', 0, height - borderRadius * 2],
- ['a', borderRadius, borderRadius, 0, 0, 1, -borderRadius, borderRadius],
- ['l', borderRadius * 2 - width, 0],
- ['a', borderRadius, borderRadius, 0, 0, 1, -borderRadius, -borderRadius],
- ['l', 0, borderRadius * 2 - height],
- ['a', borderRadius, borderRadius, 0, 0, 1, borderRadius, -borderRadius],
- ['z']
- ];
- return componentsToPath(roundRectPath);
- }
- function getDiamondPath(shape) {
- var width = shape.width,
- height = shape.height,
- x = shape.x,
- y = shape.y,
- halfWidth = width / 2,
- halfHeight = height / 2;
- var diamondPath = [
- ['M', x + halfWidth, y],
- ['l', halfWidth, halfHeight],
- ['l', -halfWidth, halfHeight],
- ['l', -halfWidth, -halfHeight],
- ['z']
- ];
- return componentsToPath(diamondPath);
- }
- function getRectPath(shape) {
- var x = shape.x,
- y = shape.y,
- width = shape.width,
- height = shape.height;
- var rectPath = [
- ['M', x, y],
- ['l', width, 0],
- ['l', 0, height],
- ['l', -width, 0],
- ['z']
- ];
- return componentsToPath(rectPath);
- }
- /**
- * Flatten array, one level deep.
- *
- * @param {Array<?>} arr
- *
- * @return {Array<?>}
- */
- var nativeToString = Object.prototype.toString;
- var nativeHasOwnProperty = Object.prototype.hasOwnProperty;
- function isUndefined$1(obj) {
- return obj === undefined;
- }
- function isArray$1(obj) {
- return nativeToString.call(obj) === '[object Array]';
- }
- /**
- * Return true, if target owns a property with the given key.
- *
- * @param {Object} target
- * @param {String} key
- *
- * @return {Boolean}
- */
- function has(target, key) {
- return nativeHasOwnProperty.call(target, key);
- }
- /**
- * Iterate over collection; returning something
- * (non-undefined) will stop iteration.
- *
- * @param {Array|Object} collection
- * @param {Function} iterator
- *
- * @return {Object} return result that stopped the iteration
- */
- function forEach(collection, iterator) {
- var val, result;
- if (isUndefined$1(collection)) {
- return;
- }
- var convertKey = isArray$1(collection) ? toNum : identity;
- for (var key in collection) {
- if (has(collection, key)) {
- val = collection[key];
- result = iterator(val, convertKey(key));
- if (result === false) {
- return val;
- }
- }
- }
- }
- function identity(arg) {
- return arg;
- }
- function toNum(arg) {
- return Number(arg);
- }
- /**
- * Assigns style attributes in a style-src compliant way.
- *
- * @param {Element} element
- * @param {...Object} styleSources
- *
- * @return {Element} the element
- */
- function assign$1(element) {
- var target = element.style;
- for (var _len = arguments.length, styleSources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- styleSources[_key - 1] = arguments[_key];
- }
- forEach(styleSources, function (style) {
- if (!style) {
- return;
- }
- forEach(style, function (value, key) {
- target[key] = value;
- });
- });
- return element;
- }
- /**
- * Set attribute `name` to `val`, or get attr `name`.
- *
- * @param {Element} el
- * @param {String} name
- * @param {String} [val]
- * @api public
- */
- function attr(el, name, val) {
- // get
- if (arguments.length == 2) {
- return el.getAttribute(name);
- }
- // remove
- if (val === null) {
- return el.removeAttribute(name);
- }
- // set
- el.setAttribute(name, val);
- return el;
- }
- var indexOf = [].indexOf;
- var indexof = function(arr, obj){
- if (indexOf) return arr.indexOf(obj);
- for (var i = 0; i < arr.length; ++i) {
- if (arr[i] === obj) return i;
- }
- return -1;
- };
- /**
- * Taken from https://github.com/component/classes
- *
- * Without the component bits.
- */
- /**
- * Whitespace regexp.
- */
- var re = /\s+/;
- /**
- * toString reference.
- */
- var toString = Object.prototype.toString;
- /**
- * Wrap `el` in a `ClassList`.
- *
- * @param {Element} el
- * @return {ClassList}
- * @api public
- */
- function classes(el) {
- return new ClassList(el);
- }
- /**
- * Initialize a new ClassList for `el`.
- *
- * @param {Element} el
- * @api private
- */
- function ClassList(el) {
- if (!el || !el.nodeType) {
- throw new Error('A DOM element reference is required');
- }
- this.el = el;
- this.list = el.classList;
- }
- /**
- * Add class `name` if not already present.
- *
- * @param {String} name
- * @return {ClassList}
- * @api public
- */
- ClassList.prototype.add = function (name) {
- // classList
- if (this.list) {
- this.list.add(name);
- return this;
- }
- // fallback
- var arr = this.array();
- var i = indexof(arr, name);
- if (!~i) arr.push(name);
- this.el.className = arr.join(' ');
- return this;
- };
- /**
- * Remove class `name` when present, or
- * pass a regular expression to remove
- * any which match.
- *
- * @param {String|RegExp} name
- * @return {ClassList}
- * @api public
- */
- ClassList.prototype.remove = function (name) {
- if ('[object RegExp]' == toString.call(name)) {
- return this.removeMatching(name);
- }
- // classList
- if (this.list) {
- this.list.remove(name);
- return this;
- }
- // fallback
- var arr = this.array();
- var i = indexof(arr, name);
- if (~i) arr.splice(i, 1);
- this.el.className = arr.join(' ');
- return this;
- };
- /**
- * Remove all classes matching `re`.
- *
- * @param {RegExp} re
- * @return {ClassList}
- * @api private
- */
- ClassList.prototype.removeMatching = function (re) {
- var arr = this.array();
- for (var i = 0; i < arr.length; i++) {
- if (re.test(arr[i])) {
- this.remove(arr[i]);
- }
- }
- return this;
- };
- /**
- * Toggle class `name`, can force state via `force`.
- *
- * For browsers that support classList, but do not support `force` yet,
- * the mistake will be detected and corrected.
- *
- * @param {String} name
- * @param {Boolean} force
- * @return {ClassList}
- * @api public
- */
- ClassList.prototype.toggle = function (name, force) {
- // classList
- if (this.list) {
- if ('undefined' !== typeof force) {
- if (force !== this.list.toggle(name, force)) {
- this.list.toggle(name); // toggle again to correct
- }
- } else {
- this.list.toggle(name);
- }
- return this;
- }
- // fallback
- if ('undefined' !== typeof force) {
- if (!force) {
- this.remove(name);
- } else {
- this.add(name);
- }
- } else {
- if (this.has(name)) {
- this.remove(name);
- } else {
- this.add(name);
- }
- }
- return this;
- };
- /**
- * Return an array of classes.
- *
- * @return {Array}
- * @api public
- */
- ClassList.prototype.array = function () {
- var className = this.el.getAttribute('class') || '';
- var str = className.replace(/^\s+|\s+$/g, '');
- var arr = str.split(re);
- if ('' === arr[0]) arr.shift();
- return arr;
- };
- /**
- * Check if class `name` is present.
- *
- * @param {String} name
- * @return {ClassList}
- * @api public
- */
- ClassList.prototype.has = ClassList.prototype.contains = function (name) {
- return this.list ? this.list.contains(name) : !!~indexof(this.array(), name);
- };
- /**
- * Remove all children from the given element.
- */
- function clear(el) {
- var c;
- while (el.childNodes.length) {
- c = el.childNodes[0];
- el.removeChild(c);
- }
- return el;
- }
- var proto = typeof Element !== 'undefined' ? Element.prototype : {};
- var vendor = proto.matches
- || proto.matchesSelector
- || proto.webkitMatchesSelector
- || proto.mozMatchesSelector
- || proto.msMatchesSelector
- || proto.oMatchesSelector;
- var matchesSelector = match;
- /**
- * Match `el` to `selector`.
- *
- * @param {Element} el
- * @param {String} selector
- * @return {Boolean}
- * @api public
- */
- function match(el, selector) {
- if (!el || el.nodeType !== 1) return false;
- if (vendor) return vendor.call(el, selector);
- var nodes = el.parentNode.querySelectorAll(selector);
- for (var i = 0; i < nodes.length; i++) {
- if (nodes[i] == el) return true;
- }
- return false;
- }
- /**
- * Closest
- *
- * @param {Element} el
- * @param {String} selector
- * @param {Boolean} checkYourSelf (optional)
- */
- function closest (element, selector, checkYourSelf) {
- var currentElem = checkYourSelf ? element : element.parentNode;
- while (currentElem && currentElem.nodeType !== document.DOCUMENT_NODE && currentElem.nodeType !== document.DOCUMENT_FRAGMENT_NODE) {
- if (matchesSelector(currentElem, selector)) {
- return currentElem;
- }
- currentElem = currentElem.parentNode;
- }
- return matchesSelector(currentElem, selector) ? currentElem : null;
- }
- var bind$1 = window.addEventListener ? 'addEventListener' : 'attachEvent',
- unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent',
- prefix$6 = bind$1 !== 'addEventListener' ? 'on' : '';
- /**
- * Bind `el` event `type` to `fn`.
- *
- * @param {Element} el
- * @param {String} type
- * @param {Function} fn
- * @param {Boolean} capture
- * @return {Function}
- * @api public
- */
- var bind_1 = function(el, type, fn, capture){
- el[bind$1](prefix$6 + type, fn, capture || false);
- return fn;
- };
- /**
- * Unbind `el` event `type`'s callback `fn`.
- *
- * @param {Element} el
- * @param {String} type
- * @param {Function} fn
- * @param {Boolean} capture
- * @return {Function}
- * @api public
- */
- var unbind_1 = function(el, type, fn, capture){
- el[unbind](prefix$6 + type, fn, capture || false);
- return fn;
- };
- var componentEvent = {
- bind: bind_1,
- unbind: unbind_1
- };
- /**
- * Module dependencies.
- */
- /**
- * Delegate event `type` to `selector`
- * and invoke `fn(e)`. A callback function
- * is returned which may be passed to `.unbind()`.
- *
- * @param {Element} el
- * @param {String} selector
- * @param {String} type
- * @param {Function} fn
- * @param {Boolean} capture
- * @return {Function}
- * @api public
- */
- // Some events don't bubble, so we want to bind to the capture phase instead
- // when delegating.
- var forceCaptureEvents = ['focus', 'blur'];
- function bind$2(el, selector, type, fn, capture) {
- if (forceCaptureEvents.indexOf(type) !== -1) {
- capture = true;
- }
- return componentEvent.bind(el, type, function (e) {
- var target = e.target || e.srcElement;
- e.delegateTarget = closest(target, selector, true);
- if (e.delegateTarget) {
- fn.call(el, e);
- }
- }, capture);
- }
- /**
- * Unbind event `type`'s callback `fn`.
- *
- * @param {Element} el
- * @param {String} type
- * @param {Function} fn
- * @param {Boolean} capture
- * @api public
- */
- function unbind$1(el, type, fn, capture) {
- if (forceCaptureEvents.indexOf(type) !== -1) {
- capture = true;
- }
- return componentEvent.unbind(el, type, fn, capture);
- }
- var delegate = {
- bind: bind$2,
- unbind: unbind$1
- };
- /**
- * Expose `parse`.
- */
- var domify = parse;
- /**
- * Tests for browser support.
- */
- var innerHTMLBug = false;
- var bugTestDiv;
- if (typeof document !== 'undefined') {
- bugTestDiv = document.createElement('div');
- // Setup
- bugTestDiv.innerHTML = ' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';
- // Make sure that link elements get serialized correctly by innerHTML
- // This requires a wrapper element in IE
- innerHTMLBug = !bugTestDiv.getElementsByTagName('link').length;
- bugTestDiv = undefined;
- }
- /**
- * Wrap map from jquery.
- */
- var map$1 = {
- legend: [1, '<fieldset>', '</fieldset>'],
- tr: [2, '<table><tbody>', '</tbody></table>'],
- col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
- // for script/link/style tags to work in IE6-8, you have to wrap
- // in a div with a non-whitespace character in front, ha!
- _default: innerHTMLBug ? [1, 'X<div>', '</div>'] : [0, '', '']
- };
- map$1.td =
- map$1.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
- map$1.option =
- map$1.optgroup = [1, '<select multiple="multiple">', '</select>'];
- map$1.thead =
- map$1.tbody =
- map$1.colgroup =
- map$1.caption =
- map$1.tfoot = [1, '<table>', '</table>'];
- map$1.polyline =
- map$1.ellipse =
- map$1.polygon =
- map$1.circle =
- map$1.text =
- map$1.line =
- map$1.path =
- map$1.rect =
- map$1.g = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
- /**
- * Parse `html` and return a DOM Node instance, which could be a TextNode,
- * HTML DOM Node of some kind (<div> for example), or a DocumentFragment
- * instance, depending on the contents of the `html` string.
- *
- * @param {String} html - HTML string to "domify"
- * @param {Document} doc - The `document` instance to create the Node for
- * @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance
- * @api private
- */
- function parse(html, doc) {
- if ('string' != typeof html) throw new TypeError('String expected');
- // default to the global `document` object
- if (!doc) doc = document;
- // tag name
- var m = /<([\w:]+)/.exec(html);
- if (!m) return doc.createTextNode(html);
- html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
- var tag = m[1];
- // body support
- if (tag == 'body') {
- var el = doc.createElement('html');
- el.innerHTML = html;
- return el.removeChild(el.lastChild);
- }
- // wrap map
- var wrap = map$1[tag] || map$1._default;
- var depth = wrap[0];
- var prefix = wrap[1];
- var suffix = wrap[2];
- var el = doc.createElement('div');
- el.innerHTML = prefix + html + suffix;
- while (depth--) el = el.lastChild;
- // one element
- if (el.firstChild == el.lastChild) {
- return el.removeChild(el.firstChild);
- }
- // several elements
- var fragment = doc.createDocumentFragment();
- while (el.firstChild) {
- fragment.appendChild(el.removeChild(el.firstChild));
- }
- return fragment;
- }
- function query(selector, el) {
- el = el || document;
- return el.querySelector(selector);
- }
- function all(selector, el) {
- el = el || document;
- return el.querySelectorAll(selector);
- }
- function remove$1(el) {
- el.parentNode && el.parentNode.removeChild(el);
- }
- /**
- * @param {<SVGElement>} element
- * @param {number} x
- * @param {number} y
- * @param {number} angle
- * @param {number} amount
- */
- function transform(gfx, x, y, angle, amount) {
- var translate = createTransform();
- translate.setTranslate(x, y);
- var rotate = createTransform();
- rotate.setRotate(angle || 0, 0, 0);
- var scale = createTransform();
- scale.setScale(amount || 1, amount || 1);
- transform$1(gfx, [ translate, rotate, scale ]);
- }
- /**
- * @param {SVGElement} element
- * @param {number} x
- * @param {number} y
- */
- function translate$1(gfx, x, y) {
- var translate = createTransform();
- translate.setTranslate(x, y);
- transform$1(gfx, translate);
- }
- /**
- * @param {SVGElement} element
- * @param {number} angle
- */
- function rotate(gfx, angle) {
- var rotate = createTransform();
- rotate.setRotate(angle, 0, 0);
- transform$1(gfx, rotate);
- }
- function createCommonjsModule(fn, module) {
- return module = { exports: {} }, fn(module, module.exports), module.exports;
- }
- var hat_1 = createCommonjsModule(function (module) {
- var hat = module.exports = function (bits, base) {
- if (!base) base = 16;
- if (bits === undefined) bits = 128;
- if (bits <= 0) return '0';
-
- var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
- for (var i = 2; digits === Infinity; i *= 2) {
- digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
- }
-
- var rem = digits - Math.floor(digits);
-
- var res = '';
-
- for (var i = 0; i < Math.floor(digits); i++) {
- var x = Math.floor(Math.random() * base).toString(base);
- res = x + res;
- }
-
- if (rem) {
- var b = Math.pow(base, rem);
- var x = Math.floor(Math.random() * b).toString(base);
- res = x + res;
- }
-
- var parsed = parseInt(res, base);
- if (parsed !== Infinity && parsed >= Math.pow(2, bits)) {
- return hat(bits, base)
- }
- else return res;
- };
- hat.rack = function (bits, base, expandBy) {
- var fn = function (data) {
- var iters = 0;
- do {
- if (iters ++ > 10) {
- if (expandBy) bits += expandBy;
- else throw new Error('too many ID collisions, use more bits')
- }
-
- var id = hat(bits, base);
- } while (Object.hasOwnProperty.call(hats, id));
-
- hats[id] = data;
- return id;
- };
- var hats = fn.hats = {};
-
- fn.get = function (id) {
- return fn.hats[id];
- };
-
- fn.set = function (id, value) {
- fn.hats[id] = value;
- return fn;
- };
-
- fn.bits = bits || 128;
- fn.base = base || 16;
- return fn;
- };
- });
- /**
- * Create a new id generator / cache instance.
- *
- * You may optionally provide a seed that is used internally.
- *
- * @param {Seed} seed
- */
- function Ids(seed) {
- if (!(this instanceof Ids)) {
- return new Ids(seed);
- }
- seed = seed || [128, 36, 1];
- this._seed = seed.length ? hat_1.rack(seed[0], seed[1], seed[2]) : seed;
- }
- /**
- * Generate a next id.
- *
- * @param {Object} [element] element to bind the id to
- *
- * @return {String} id
- */
- Ids.prototype.next = function (element) {
- return this._seed(element || true);
- };
- /**
- * Generate a next id with a given prefix.
- *
- * @param {Object} [element] element to bind the id to
- *
- * @return {String} id
- */
- Ids.prototype.nextPrefixed = function (prefix, element) {
- var id;
- do {
- id = prefix + this.next(true);
- } while (this.assigned(id)); // claim {prefix}{random}
- this.claim(id, element); // return
- return id;
- };
- /**
- * Manually claim an existing id.
- *
- * @param {String} id
- * @param {String} [element] element the id is claimed by
- */
- Ids.prototype.claim = function (id, element) {
- this._seed.set(id, element || true);
- };
- /**
- * Returns true if the given id has already been assigned.
- *
- * @param {String} id
- * @return {Boolean}
- */
- Ids.prototype.assigned = function (id) {
- return this._seed.get(id) || false;
- };
- /**
- * Unclaim an id.
- *
- * @param {String} id the id to unclaim
- */
- Ids.prototype.unclaim = function (id) {
- delete this._seed.hats[id];
- };
- /**
- * Clear all claimed ids.
- */
- Ids.prototype.clear = function () {
- var hats = this._seed.hats,
- id;
- for (id in hats) {
- this.unclaim(id);
- }
- };
- var RENDERER_IDS = new Ids();
- var TASK_BORDER_RADIUS = 10;
- var INNER_OUTER_DIST = 3;
- var DEFAULT_FILL_OPACITY = .95,
- HIGH_FILL_OPACITY = .35;
- var ELEMENT_LABEL_DISTANCE = 10;
- function BpmnRenderer(
- config, eventBus, styles, pathMap,
- canvas, textRenderer, priority) {
- BaseRenderer.call(this, eventBus, priority);
- var defaultFillColor = config && config.defaultFillColor,
- defaultStrokeColor = config && config.defaultStrokeColor,
- defaultLabelColor = config && config.defaultLabelColor;
- var rendererId = RENDERER_IDS.next();
- var markers = {};
- var computeStyle = styles.computeStyle;
- function addMarker(id, options) {
- var attrs = assign({
- fill: black,
- strokeWidth: 1,
- strokeLinecap: 'round',
- strokeDasharray: 'none'
- }, options.attrs);
- var ref = options.ref || { x: 0, y: 0 };
- var scale = options.scale || 1;
- // fix for safari / chrome / firefox bug not correctly
- // resetting stroke dash array
- if (attrs.strokeDasharray === 'none') {
- attrs.strokeDasharray = [10000, 1];
- }
- var marker = create$1('marker');
- attr$1(options.element, attrs);
- append(marker, options.element);
- attr$1(marker, {
- id: id,
- viewBox: '0 0 20 20',
- refX: ref.x,
- refY: ref.y,
- markerWidth: 20 * scale,
- markerHeight: 20 * scale,
- orient: 'auto'
- });
- var defs = query('defs', canvas._svg);
- if (!defs) {
- defs = create$1('defs');
- append(canvas._svg, defs);
- }
- append(defs, marker);
- markers[id] = marker;
- }
- function colorEscape(str) {
- // only allow characters and numbers
- return str.replace(/[^0-9a-zA-z]+/g, '_');
- }
- function marker(type, fill, stroke) {
- var id = type + '-' + colorEscape(fill) + '-' + colorEscape(stroke) + '-' + rendererId;
- if (!markers[id]) {
- createMarker(id, type, fill, stroke);
- }
- return 'url(#' + id + ')';
- }
- function createMarker(id, type, fill, stroke) {
- if (type === 'sequenceflow-end') {
- var sequenceflowEnd = create$1('path');
- attr$1(sequenceflowEnd, { d: 'M 1 5 L 11 10 L 1 15 Z' });
- addMarker(id, {
- element: sequenceflowEnd,
- ref: { x: 11, y: 10 },
- scale: 0.5,
- attrs: {
- fill: stroke,
- stroke: stroke
- }
- });
- }
- if (type === 'messageflow-start') {
- var messageflowStart = create$1('circle');
- attr$1(messageflowStart, { cx: 6, cy: 6, r: 3.5 });
- addMarker(id, {
- element: messageflowStart,
- attrs: {
- fill: fill,
- stroke: stroke
- },
- ref: { x: 6, y: 6 }
- });
- }
- if (type === 'messageflow-end') {
- var messageflowEnd = create$1('path');
- attr$1(messageflowEnd, { d: 'm 1 5 l 0 -3 l 7 3 l -7 3 z' });
- addMarker(id, {
- element: messageflowEnd,
- attrs: {
- fill: fill,
- stroke: stroke,
- strokeLinecap: 'butt'
- },
- ref: { x: 8.5, y: 5 }
- });
- }
- if (type === 'association-start') {
- var associationStart = create$1('path');
- attr$1(associationStart, { d: 'M 11 5 L 1 10 L 11 15' });
- addMarker(id, {
- element: associationStart,
- attrs: {
- fill: 'none',
- stroke: stroke,
- strokeWidth: 1.5
- },
- ref: { x: 1, y: 10 },
- scale: 0.5
- });
- }
- if (type === 'association-end') {
- var associationEnd = create$1('path');
- attr$1(associationEnd, { d: 'M 1 5 L 11 10 L 1 15' });
- addMarker(id, {
- element: associationEnd,
- attrs: {
- fill: 'none',
- stroke: stroke,
- strokeWidth: 1.5
- },
- ref: { x: 12, y: 10 },
- scale: 0.5
- });
- }
- if (type === 'conditional-flow-marker') {
- var conditionalflowMarker = create$1('path');
- attr$1(conditionalflowMarker, { d: 'M 0 10 L 8 6 L 16 10 L 8 14 Z' });
- addMarker(id, {
- element: conditionalflowMarker,
- attrs: {
- fill: fill,
- stroke: stroke
- },
- ref: { x: -1, y: 10 },
- scale: 0.5
- });
- }
- if (type === 'conditional-default-flow-marker') {
- var conditionaldefaultflowMarker = create$1('path');
- attr$1(conditionaldefaultflowMarker, { d: 'M 6 4 L 10 16' });
- addMarker(id, {
- element: conditionaldefaultflowMarker,
- attrs: {
- stroke: stroke
- },
- ref: { x: 0, y: 10 },
- scale: 0.5
- });
- }
- }
- function drawCircle(parentGfx, width, height, offset, attrs) {
- if (isObject(offset)) {
- attrs = offset;
- offset = 0;
- }
- offset = offset || 0;
- attrs = computeStyle(attrs, {
- stroke: black,
- strokeWidth: 2,
- fill: 'white'
- });
- if (attrs.fill === 'none') {
- delete attrs.fillOpacity;
- }
- var cx = width / 2,
- cy = height / 2;
- var circle = create$1('circle');
- attr$1(circle, {
- cx: cx,
- cy: cy,
- r: Math.round((width + height) / 4 - offset)
- });
- attr$1(circle, attrs);
- append(parentGfx, circle);
- return circle;
- }
- function drawRect(parentGfx, width, height, r, offset, attrs) {
- if (isObject(offset)) {
- attrs = offset;
- offset = 0;
- }
- offset = offset || 0;
- attrs = computeStyle(attrs, {
- stroke: black,
- strokeWidth: 2,
- fill: 'white'
- });
- var rect = create$1('rect');
- attr$1(rect, {
- x: offset,
- y: offset,
- width: width - offset * 2,
- height: height - offset * 2,
- rx: r,
- ry: r
- });
- attr$1(rect, attrs);
- append(parentGfx, rect);
- return rect;
- }
- function drawDiamond(parentGfx, width, height, attrs) {
- var x_2 = width / 2;
- var y_2 = height / 2;
- var points = [{ x: x_2, y: 0 }, { x: width, y: y_2 }, { x: x_2, y: height }, { x: 0, y: y_2 }];
- var pointsString = points.map(function(point) {
- return point.x + ',' + point.y;
- }).join(' ');
- attrs = computeStyle(attrs, {
- stroke: black,
- strokeWidth: 2,
- fill: 'white'
- });
- var polygon = create$1('polygon');
- attr$1(polygon, {
- points: pointsString
- });
- attr$1(polygon, attrs);
- append(parentGfx, polygon);
- return polygon;
- }
- function drawLine(parentGfx, waypoints, attrs) {
- attrs = computeStyle(attrs, [ 'no-fill' ], {
- stroke: black,
- strokeWidth: 2,
- fill: 'none'
- });
- var line = createLine(waypoints, attrs);
- append(parentGfx, line);
- return line;
- }
- function drawPath(parentGfx, d, attrs) {
- attrs = computeStyle(attrs, [ 'no-fill' ], {
- strokeWidth: 2,
- stroke: black
- });
- var path = create$1('path');
- attr$1(path, { d: d });
- attr$1(path, attrs);
- append(parentGfx, path);
- return path;
- }
- function drawMarker(type, parentGfx, path, attrs) {
- return drawPath(parentGfx, path, assign({ 'data-marker': type }, attrs));
- }
- function renderer(type) {
- return handlers[type];
- }
- function as(type) {
- return function(parentGfx, element) {
- return renderer(type)(parentGfx, element);
- };
- }
- function renderEventContent(element, parentGfx) {
- var event = getSemantic(element);
- var isThrowing = isThrowEvent(event);
- if (event.eventDefinitions && event.eventDefinitions.length>1) {
- if (event.parallelMultiple) {
- return renderer('bpmn:ParallelMultipleEventDefinition')(parentGfx, element, isThrowing);
- }
- else {
- return renderer('bpmn:MultipleEventDefinition')(parentGfx, element, isThrowing);
- }
- }
- if (isTypedEvent(event, 'bpmn:MessageEventDefinition')) {
- return renderer('bpmn:MessageEventDefinition')(parentGfx, element, isThrowing);
- }
- if (isTypedEvent(event, 'bpmn:TimerEventDefinition')) {
- return renderer('bpmn:TimerEventDefinition')(parentGfx, element, isThrowing);
- }
- if (isTypedEvent(event, 'bpmn:ConditionalEventDefinition')) {
- return renderer('bpmn:ConditionalEventDefinition')(parentGfx, element);
- }
- if (isTypedEvent(event, 'bpmn:SignalEventDefinition')) {
- return renderer('bpmn:SignalEventDefinition')(parentGfx, element, isThrowing);
- }
- if (isTypedEvent(event, 'bpmn:EscalationEventDefinition')) {
- return renderer('bpmn:EscalationEventDefinition')(parentGfx, element, isThrowing);
- }
- if (isTypedEvent(event, 'bpmn:LinkEventDefinition')) {
- return renderer('bpmn:LinkEventDefinition')(parentGfx, element, isThrowing);
- }
- if (isTypedEvent(event, 'bpmn:ErrorEventDefinition')) {
- return renderer('bpmn:ErrorEventDefinition')(parentGfx, element, isThrowing);
- }
- if (isTypedEvent(event, 'bpmn:CancelEventDefinition')) {
- return renderer('bpmn:CancelEventDefinition')(parentGfx, element, isThrowing);
- }
- if (isTypedEvent(event, 'bpmn:CompensateEventDefinition')) {
- return renderer('bpmn:CompensateEventDefinition')(parentGfx, element, isThrowing);
- }
- if (isTypedEvent(event, 'bpmn:TerminateEventDefinition')) {
- return renderer('bpmn:TerminateEventDefinition')(parentGfx, element, isThrowing);
- }
- return null;
- }
- function renderLabel(parentGfx, label, options) {
- options = assign({
- size: {
- width: 100
- }
- }, options);
- var text = textRenderer.createText(label || '', options);
- classes$1(text).add('djs-label');
- append(parentGfx, text);
- return text;
- }
- function renderEmbeddedLabel(parentGfx, element, align) {
- var semantic = getSemantic(element);
- return renderLabel(parentGfx, semantic.name, {
- box: element,
- align: align,
- padding: 5,
- style: {
- fill: getLabelColor(element, defaultLabelColor, defaultStrokeColor)
- }
- });
- }
- function renderExternalLabel(parentGfx, element) {
- var box = {
- width: 90,
- height: 30,
- x: element.width / 2 + element.x,
- y: element.height / 2 + element.y
- };
- return renderLabel(parentGfx, getLabel(element), {
- box: box,
- fitBox: true,
- style: assign(
- {},
- textRenderer.getExternalStyle(),
- {
- fill: getLabelColor(element, defaultLabelColor, defaultStrokeColor)
- }
- )
- });
- }
- function renderLaneLabel(parentGfx, text, element) {
- var textBox = renderLabel(parentGfx, text, {
- box: {
- height: 30,
- width: element.height
- },
- align: 'center-middle',
- style: {
- fill: getLabelColor(element, defaultLabelColor, defaultStrokeColor)
- }
- });
- var top = -1 * element.height;
- transform(textBox, 0, -top, 270);
- }
- function createPathFromConnection(connection) {
- var waypoints = connection.waypoints;
- var pathData = 'm ' + waypoints[0].x + ',' + waypoints[0].y;
- for (var i = 1; i < waypoints.length; i++) {
- pathData += 'L' + waypoints[i].x + ',' + waypoints[i].y + ' ';
- }
- return pathData;
- }
- var handlers = this.handlers = {
- 'bpmn:Event': function(parentGfx, element, attrs) {
- if (!('fillOpacity' in attrs)) {
- attrs.fillOpacity = DEFAULT_FILL_OPACITY;
- }
- return drawCircle(parentGfx, element.width, element.height, attrs);
- },
- 'bpmn:StartEvent': function(parentGfx, element) {
- var attrs = {
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- var semantic = getSemantic(element);
- if (!semantic.isInterrupting) {
- attrs = {
- strokeDasharray: '6',
- strokeLinecap: 'round',
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- }
- var circle = renderer('bpmn:Event')(parentGfx, element, attrs);
- renderEventContent(element, parentGfx);
- return circle;
- },
- 'bpmn:MessageEventDefinition': function(parentGfx, element, isThrowing) {
- var pathData = pathMap.getScaledPath('EVENT_MESSAGE', {
- xScaleFactor: 0.9,
- yScaleFactor: 0.9,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.235,
- my: 0.315
- }
- });
- var fill = isThrowing ? getStrokeColor(element, defaultStrokeColor) : getFillColor(element, defaultFillColor);
- var stroke = isThrowing ? getFillColor(element, defaultFillColor) : getStrokeColor(element, defaultStrokeColor);
- var messagePath = drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: fill,
- stroke: stroke
- });
- return messagePath;
- },
- 'bpmn:TimerEventDefinition': function(parentGfx, element) {
- var circle = drawCircle(parentGfx, element.width, element.height, 0.2 * element.height, {
- strokeWidth: 2,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var pathData = pathMap.getScaledPath('EVENT_TIMER_WH', {
- xScaleFactor: 0.75,
- yScaleFactor: 0.75,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.5,
- my: 0.5
- }
- });
- drawPath(parentGfx, pathData, {
- strokeWidth: 2,
- strokeLinecap: 'square',
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- for (var i = 0;i < 12; i++) {
- var linePathData = pathMap.getScaledPath('EVENT_TIMER_LINE', {
- xScaleFactor: 0.75,
- yScaleFactor: 0.75,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.5,
- my: 0.5
- }
- });
- var width = element.width / 2;
- var height = element.height / 2;
- drawPath(parentGfx, linePathData, {
- strokeWidth: 1,
- strokeLinecap: 'square',
- transform: 'rotate(' + (i * 30) + ',' + height + ',' + width + ')',
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- }
- return circle;
- },
- 'bpmn:EscalationEventDefinition': function(parentGfx, event, isThrowing) {
- var pathData = pathMap.getScaledPath('EVENT_ESCALATION', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.5,
- my: 0.2
- }
- });
- var fill = isThrowing ? getStrokeColor(event, defaultStrokeColor) : 'none';
- return drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: fill,
- stroke: getStrokeColor(event, defaultStrokeColor)
- });
- },
- 'bpmn:ConditionalEventDefinition': function(parentGfx, event) {
- var pathData = pathMap.getScaledPath('EVENT_CONDITIONAL', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.5,
- my: 0.222
- }
- });
- return drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- stroke: getStrokeColor(event, defaultStrokeColor)
- });
- },
- 'bpmn:LinkEventDefinition': function(parentGfx, event, isThrowing) {
- var pathData = pathMap.getScaledPath('EVENT_LINK', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.57,
- my: 0.263
- }
- });
- var fill = isThrowing ? getStrokeColor(event, defaultStrokeColor) : 'none';
- return drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: fill,
- stroke: getStrokeColor(event, defaultStrokeColor)
- });
- },
- 'bpmn:ErrorEventDefinition': function(parentGfx, event, isThrowing) {
- var pathData = pathMap.getScaledPath('EVENT_ERROR', {
- xScaleFactor: 1.1,
- yScaleFactor: 1.1,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.2,
- my: 0.722
- }
- });
- var fill = isThrowing ? getStrokeColor(event, defaultStrokeColor) : 'none';
- return drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: fill,
- stroke: getStrokeColor(event, defaultStrokeColor)
- });
- },
- 'bpmn:CancelEventDefinition': function(parentGfx, event, isThrowing) {
- var pathData = pathMap.getScaledPath('EVENT_CANCEL_45', {
- xScaleFactor: 1.0,
- yScaleFactor: 1.0,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.638,
- my: -0.055
- }
- });
- var fill = isThrowing ? getStrokeColor(event, defaultStrokeColor) : 'none';
- var path = drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: fill,
- stroke: getStrokeColor(event, defaultStrokeColor)
- });
- rotate(path, 45);
- return path;
- },
- 'bpmn:CompensateEventDefinition': function(parentGfx, event, isThrowing) {
- var pathData = pathMap.getScaledPath('EVENT_COMPENSATION', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.22,
- my: 0.5
- }
- });
- var fill = isThrowing ? getStrokeColor(event, defaultStrokeColor) : 'none';
- return drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: fill,
- stroke: getStrokeColor(event, defaultStrokeColor)
- });
- },
- 'bpmn:SignalEventDefinition': function(parentGfx, event, isThrowing) {
- var pathData = pathMap.getScaledPath('EVENT_SIGNAL', {
- xScaleFactor: 0.9,
- yScaleFactor: 0.9,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.5,
- my: 0.2
- }
- });
- var fill = isThrowing ? getStrokeColor(event, defaultStrokeColor) : 'none';
- return drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: fill,
- stroke: getStrokeColor(event, defaultStrokeColor)
- });
- },
- 'bpmn:MultipleEventDefinition': function(parentGfx, event, isThrowing) {
- var pathData = pathMap.getScaledPath('EVENT_MULTIPLE', {
- xScaleFactor: 1.1,
- yScaleFactor: 1.1,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.222,
- my: 0.36
- }
- });
- var fill = isThrowing ? getStrokeColor(event, defaultStrokeColor) : 'none';
- return drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: fill
- });
- },
- 'bpmn:ParallelMultipleEventDefinition': function(parentGfx, event) {
- var pathData = pathMap.getScaledPath('EVENT_PARALLEL_MULTIPLE', {
- xScaleFactor: 1.2,
- yScaleFactor: 1.2,
- containerWidth: event.width,
- containerHeight: event.height,
- position: {
- mx: 0.458,
- my: 0.194
- }
- });
- return drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: getStrokeColor(event, defaultStrokeColor),
- stroke: getStrokeColor(event, defaultStrokeColor)
- });
- },
- 'bpmn:EndEvent': function(parentGfx, element) {
- var circle = renderer('bpmn:Event')(parentGfx, element, {
- strokeWidth: 4,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- renderEventContent(element, parentGfx);
- return circle;
- },
- 'bpmn:TerminateEventDefinition': function(parentGfx, element) {
- var circle = drawCircle(parentGfx, element.width, element.height, 8, {
- strokeWidth: 4,
- fill: getStrokeColor(element, defaultStrokeColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return circle;
- },
- 'bpmn:IntermediateEvent': function(parentGfx, element) {
- var outer = renderer('bpmn:Event')(parentGfx, element, {
- strokeWidth: 1,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- /* inner */
- drawCircle(parentGfx, element.width, element.height, INNER_OUTER_DIST, {
- strokeWidth: 1,
- fill: getFillColor(element, 'none'),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- renderEventContent(element, parentGfx);
- return outer;
- },
- 'bpmn:IntermediateCatchEvent': as('bpmn:IntermediateEvent'),
- 'bpmn:IntermediateThrowEvent': as('bpmn:IntermediateEvent'),
- 'bpmn:Activity': function(parentGfx, element, attrs) {
- attrs = attrs || {};
- if (!('fillOpacity' in attrs)) {
- attrs.fillOpacity = DEFAULT_FILL_OPACITY;
- }
- return drawRect(parentGfx, element.width, element.height, TASK_BORDER_RADIUS, attrs);
- },
- 'bpmn:Task': function(parentGfx, element) {
- var attrs = {
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- var rect = renderer('bpmn:Activity')(parentGfx, element, attrs);
- renderEmbeddedLabel(parentGfx, element, 'center-middle');
- attachTaskMarkers(parentGfx, element);
- return rect;
- },
- 'bpmn:ServiceTask': function(parentGfx, element) {
- var task = renderer('bpmn:Task')(parentGfx, element);
- var pathDataBG = pathMap.getScaledPath('TASK_TYPE_SERVICE', {
- abspos: {
- x: 12,
- y: 18
- }
- });
- /* service bg */ drawPath(parentGfx, pathDataBG, {
- strokeWidth: 1,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var fillPathData = pathMap.getScaledPath('TASK_TYPE_SERVICE_FILL', {
- abspos: {
- x: 17.2,
- y: 18
- }
- });
- /* service fill */ drawPath(parentGfx, fillPathData, {
- strokeWidth: 0,
- fill: getFillColor(element, defaultFillColor)
- });
- var pathData = pathMap.getScaledPath('TASK_TYPE_SERVICE', {
- abspos: {
- x: 17,
- y: 22
- }
- });
- /* service */ drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return task;
- },
- 'bpmn:UserTask': function(parentGfx, element) {
- var task = renderer('bpmn:Task')(parentGfx, element);
- var x = 15;
- var y = 12;
- var pathData = pathMap.getScaledPath('TASK_TYPE_USER_1', {
- abspos: {
- x: x,
- y: y
- }
- });
- /* user path */ drawPath(parentGfx, pathData, {
- strokeWidth: 0.5,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var pathData2 = pathMap.getScaledPath('TASK_TYPE_USER_2', {
- abspos: {
- x: x,
- y: y
- }
- });
- /* user2 path */ drawPath(parentGfx, pathData2, {
- strokeWidth: 0.5,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var pathData3 = pathMap.getScaledPath('TASK_TYPE_USER_3', {
- abspos: {
- x: x,
- y: y
- }
- });
- /* user3 path */ drawPath(parentGfx, pathData3, {
- strokeWidth: 0.5,
- fill: getStrokeColor(element, defaultStrokeColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return task;
- },
- 'bpmn:ManualTask': function(parentGfx, element) {
- var task = renderer('bpmn:Task')(parentGfx, element);
- var pathData = pathMap.getScaledPath('TASK_TYPE_MANUAL', {
- abspos: {
- x: 17,
- y: 15
- }
- });
- /* manual path */ drawPath(parentGfx, pathData, {
- strokeWidth: 0.5, // 0.25,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return task;
- },
- 'bpmn:SendTask': function(parentGfx, element) {
- var task = renderer('bpmn:Task')(parentGfx, element);
- var pathData = pathMap.getScaledPath('TASK_TYPE_SEND', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: 21,
- containerHeight: 14,
- position: {
- mx: 0.285,
- my: 0.357
- }
- });
- /* send path */ drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: getStrokeColor(element, defaultStrokeColor),
- stroke: getFillColor(element, defaultFillColor)
- });
- return task;
- },
- 'bpmn:ReceiveTask' : function(parentGfx, element) {
- var semantic = getSemantic(element);
- var task = renderer('bpmn:Task')(parentGfx, element);
- var pathData;
- if (semantic.instantiate) {
- drawCircle(parentGfx, 28, 28, 20 * 0.22, { strokeWidth: 1 });
- pathData = pathMap.getScaledPath('TASK_TYPE_INSTANTIATING_SEND', {
- abspos: {
- x: 7.77,
- y: 9.52
- }
- });
- } else {
- pathData = pathMap.getScaledPath('TASK_TYPE_SEND', {
- xScaleFactor: 0.9,
- yScaleFactor: 0.9,
- containerWidth: 21,
- containerHeight: 14,
- position: {
- mx: 0.3,
- my: 0.4
- }
- });
- }
- /* receive path */ drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return task;
- },
- 'bpmn:ScriptTask': function(parentGfx, element) {
- var task = renderer('bpmn:Task')(parentGfx, element);
- var pathData = pathMap.getScaledPath('TASK_TYPE_SCRIPT', {
- abspos: {
- x: 15,
- y: 20
- }
- });
- /* script path */ drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return task;
- },
- 'bpmn:BusinessRuleTask': function(parentGfx, element) {
- var task = renderer('bpmn:Task')(parentGfx, element);
- var headerPathData = pathMap.getScaledPath('TASK_TYPE_BUSINESS_RULE_HEADER', {
- abspos: {
- x: 8,
- y: 8
- }
- });
- var businessHeaderPath = drawPath(parentGfx, headerPathData);
- attr$1(businessHeaderPath, {
- strokeWidth: 1,
- fill: getFillColor(element, '#aaaaaa'),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var headerData = pathMap.getScaledPath('TASK_TYPE_BUSINESS_RULE_MAIN', {
- abspos: {
- x: 8,
- y: 8
- }
- });
- var businessPath = drawPath(parentGfx, headerData);
- attr$1(businessPath, {
- strokeWidth: 1,
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return task;
- },
- 'bpmn:SubProcess': function(parentGfx, element, attrs) {
- attrs = assign({
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- }, attrs);
- var rect = renderer('bpmn:Activity')(parentGfx, element, attrs);
- var expanded = isExpanded(element);
- if (isEventSubProcess(element)) {
- attr$1(rect, {
- strokeDasharray: '1,2'
- });
- }
- renderEmbeddedLabel(parentGfx, element, expanded ? 'center-top' : 'center-middle');
- if (expanded) {
- attachTaskMarkers(parentGfx, element);
- } else {
- attachTaskMarkers(parentGfx, element, ['SubProcessMarker']);
- }
- return rect;
- },
- 'bpmn:AdHocSubProcess': function(parentGfx, element) {
- return renderer('bpmn:SubProcess')(parentGfx, element);
- },
- 'bpmn:Transaction': function(parentGfx, element) {
- var outer = renderer('bpmn:SubProcess')(parentGfx, element);
- var innerAttrs = styles.style([ 'no-fill', 'no-events' ], {
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- /* inner path */ drawRect(parentGfx, element.width, element.height, TASK_BORDER_RADIUS - 2, INNER_OUTER_DIST, innerAttrs);
- return outer;
- },
- 'bpmn:CallActivity': function(parentGfx, element) {
- return renderer('bpmn:SubProcess')(parentGfx, element, {
- strokeWidth: 5
- });
- },
- 'bpmn:Participant': function(parentGfx, element) {
- var attrs = {
- fillOpacity: DEFAULT_FILL_OPACITY,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- var lane = renderer('bpmn:Lane')(parentGfx, element, attrs);
- var expandedPool = isExpanded(element);
- if (expandedPool) {
- drawLine(parentGfx, [
- { x: 30, y: 0 },
- { x: 30, y: element.height }
- ], {
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var text = getSemantic(element).name;
- renderLaneLabel(parentGfx, text, element);
- } else {
- // Collapsed pool draw text inline
- var text2 = getSemantic(element).name;
- renderLabel(parentGfx, text2, {
- box: element, align: 'center-middle',
- style: {
- fill: getLabelColor(element, defaultLabelColor, defaultStrokeColor)
- }
- });
- }
- var participantMultiplicity = !!(getSemantic(element).participantMultiplicity);
- if (participantMultiplicity) {
- renderer('ParticipantMultiplicityMarker')(parentGfx, element);
- }
- return lane;
- },
- 'bpmn:Lane': function(parentGfx, element, attrs) {
- var rect = drawRect(parentGfx, element.width, element.height, 0, assign({
- fill: getFillColor(element, defaultFillColor),
- fillOpacity: HIGH_FILL_OPACITY,
- stroke: getStrokeColor(element, defaultStrokeColor)
- }, attrs));
- var semantic = getSemantic(element);
- if (semantic.$type === 'bpmn:Lane') {
- var text = semantic.name;
- renderLaneLabel(parentGfx, text, element);
- }
- return rect;
- },
- 'bpmn:InclusiveGateway': function(parentGfx, element) {
- var diamond = renderer('bpmn:Gateway')(parentGfx, element);
- /* circle path */
- drawCircle(parentGfx, element.width, element.height, element.height * 0.24, {
- strokeWidth: 2.5,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return diamond;
- },
- 'bpmn:ExclusiveGateway': function(parentGfx, element) {
- var diamond = renderer('bpmn:Gateway')(parentGfx, element);
- var pathData = pathMap.getScaledPath('GATEWAY_EXCLUSIVE', {
- xScaleFactor: 0.4,
- yScaleFactor: 0.4,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.32,
- my: 0.3
- }
- });
- if ((getDi(element).isMarkerVisible)) {
- drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: getStrokeColor(element, defaultStrokeColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- }
- return diamond;
- },
- 'bpmn:ComplexGateway': function(parentGfx, element) {
- var diamond = renderer('bpmn:Gateway')(parentGfx, element);
- var pathData = pathMap.getScaledPath('GATEWAY_COMPLEX', {
- xScaleFactor: 0.5,
- yScaleFactor:0.5,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.46,
- my: 0.26
- }
- });
- /* complex path */ drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: getStrokeColor(element, defaultStrokeColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return diamond;
- },
- 'bpmn:ParallelGateway': function(parentGfx, element) {
- var diamond = renderer('bpmn:Gateway')(parentGfx, element);
- var pathData = pathMap.getScaledPath('GATEWAY_PARALLEL', {
- xScaleFactor: 0.6,
- yScaleFactor:0.6,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.46,
- my: 0.2
- }
- });
- /* parallel path */ drawPath(parentGfx, pathData, {
- strokeWidth: 1,
- fill: getStrokeColor(element, defaultStrokeColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return diamond;
- },
- 'bpmn:EventBasedGateway': function(parentGfx, element) {
- var semantic = getSemantic(element);
- var diamond = renderer('bpmn:Gateway')(parentGfx, element);
- /* outer circle path */ drawCircle(parentGfx, element.width, element.height, element.height * 0.20, {
- strokeWidth: 1,
- fill: 'none',
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var type = semantic.eventGatewayType;
- var instantiate = !!semantic.instantiate;
- function drawEvent() {
- var pathData = pathMap.getScaledPath('GATEWAY_EVENT_BASED', {
- xScaleFactor: 0.18,
- yScaleFactor: 0.18,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.36,
- my: 0.44
- }
- });
- var attrs = {
- strokeWidth: 2,
- fill: getFillColor(element, 'none'),
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- /* event path */ drawPath(parentGfx, pathData, attrs);
- }
- if (type === 'Parallel') {
- var pathData = pathMap.getScaledPath('GATEWAY_PARALLEL', {
- xScaleFactor: 0.4,
- yScaleFactor:0.4,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.474,
- my: 0.296
- }
- });
- var parallelPath = drawPath(parentGfx, pathData);
- attr$1(parallelPath, {
- strokeWidth: 1,
- fill: 'none'
- });
- } else if (type === 'Exclusive') {
- if (!instantiate) {
- var innerCircle = drawCircle(parentGfx, element.width, element.height, element.height * 0.26);
- attr$1(innerCircle, {
- strokeWidth: 1,
- fill: 'none',
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- }
- drawEvent();
- }
- return diamond;
- },
- 'bpmn:Gateway': function(parentGfx, element) {
- var attrs = {
- fill: getFillColor(element, defaultFillColor),
- fillOpacity: DEFAULT_FILL_OPACITY,
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- return drawDiamond(parentGfx, element.width, element.height, attrs);
- },
- 'bpmn:SequenceFlow': function(parentGfx, element) {
- var pathData = createPathFromConnection(element);
- var fill = getFillColor(element, defaultFillColor),
- stroke = getStrokeColor(element, defaultStrokeColor);
- var attrs = {
- strokeLinejoin: 'round',
- markerEnd: marker('sequenceflow-end', fill, stroke),
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- var path = drawPath(parentGfx, pathData, attrs);
- var sequenceFlow = getSemantic(element);
- var source;
- if (element.source) {
- source = element.source.businessObject;
- // conditional flow marker
- if (sequenceFlow.conditionExpression && source.$instanceOf('bpmn:Activity')) {
- attr$1(path, {
- markerStart: marker('conditional-flow-marker', fill, stroke)
- });
- }
- // default marker
- if (source.default && (source.$instanceOf('bpmn:Gateway') || source.$instanceOf('bpmn:Activity')) &&
- source.default === sequenceFlow) {
- attr$1(path, {
- markerStart: marker('conditional-default-flow-marker', fill, stroke)
- });
- }
- }
- return path;
- },
- 'bpmn:Association': function(parentGfx, element, attrs) {
- var semantic = getSemantic(element);
- var fill = getFillColor(element, defaultFillColor),
- stroke = getStrokeColor(element, defaultStrokeColor);
- attrs = assign({
- strokeDasharray: '0.5, 5',
- strokeLinecap: 'round',
- strokeLinejoin: 'round',
- stroke: getStrokeColor(element, defaultStrokeColor)
- }, attrs || {});
- if (semantic.associationDirection === 'One' ||
- semantic.associationDirection === 'Both') {
- attrs.markerEnd = marker('association-end', fill, stroke);
- }
- if (semantic.associationDirection === 'Both') {
- attrs.markerStart = marker('association-start', fill, stroke);
- }
- return drawLine(parentGfx, element.waypoints, attrs);
- },
- 'bpmn:DataInputAssociation': function(parentGfx, element) {
- var fill = getFillColor(element, defaultFillColor),
- stroke = getStrokeColor(element, defaultStrokeColor);
- return renderer('bpmn:Association')(parentGfx, element, {
- markerEnd: marker('association-end', fill, stroke)
- });
- },
- 'bpmn:DataOutputAssociation': function(parentGfx, element) {
- var fill = getFillColor(element, defaultFillColor),
- stroke = getStrokeColor(element, defaultStrokeColor);
- return renderer('bpmn:Association')(parentGfx, element, {
- markerEnd: marker('association-end', fill, stroke)
- });
- },
- 'bpmn:MessageFlow': function(parentGfx, element) {
- var semantic = getSemantic(element),
- di = getDi(element);
- var fill = getFillColor(element, defaultFillColor),
- stroke = getStrokeColor(element, defaultStrokeColor);
- var pathData = createPathFromConnection(element);
- var attrs = {
- markerEnd: marker('messageflow-end', fill, stroke),
- markerStart: marker('messageflow-start', fill, stroke),
- strokeDasharray: '10, 12',
- strokeLinecap: 'round',
- strokeLinejoin: 'round',
- strokeWidth: '1.5px',
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- var path = drawPath(parentGfx, pathData, attrs);
- if (semantic.messageRef) {
- var midPoint = path.getPointAtLength(path.getTotalLength() / 2);
- var markerPathData = pathMap.getScaledPath('MESSAGE_FLOW_MARKER', {
- abspos: {
- x: midPoint.x,
- y: midPoint.y
- }
- });
- var messageAttrs = { strokeWidth: 1 };
- if (di.messageVisibleKind === 'initiating') {
- messageAttrs.fill = 'white';
- messageAttrs.stroke = black;
- } else {
- messageAttrs.fill = '#888';
- messageAttrs.stroke = 'white';
- }
- var message = drawPath(parentGfx, markerPathData, messageAttrs);
- var labelText = semantic.messageRef.name;
- var label = renderLabel(parentGfx, labelText, {
- align: 'center-top',
- fitBox: true,
- style: {
- fill: getStrokeColor(element, defaultLabelColor)
- }
- });
- var messageBounds = message.getBBox(),
- labelBounds = label.getBBox();
- var translateX = midPoint.x - labelBounds.width / 2,
- translateY = midPoint.y + messageBounds.height / 2 + ELEMENT_LABEL_DISTANCE;
- transform(label, translateX, translateY, 0);
- }
- return path;
- },
- 'bpmn:DataObject': function(parentGfx, element) {
- var pathData = pathMap.getScaledPath('DATA_OBJECT_PATH', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.474,
- my: 0.296
- }
- });
- var elementObject = drawPath(parentGfx, pathData, {
- fill: getFillColor(element, defaultFillColor),
- fillOpacity: DEFAULT_FILL_OPACITY,
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var semantic = getSemantic(element);
- if (isCollection(semantic)) {
- renderDataItemCollection(parentGfx, element);
- }
- return elementObject;
- },
- 'bpmn:DataObjectReference': as('bpmn:DataObject'),
- 'bpmn:DataInput': function(parentGfx, element) {
- var arrowPathData = pathMap.getRawPath('DATA_ARROW');
- // page
- var elementObject = renderer('bpmn:DataObject')(parentGfx, element);
- /* input arrow path */ drawPath(parentGfx, arrowPathData, { strokeWidth: 1 });
- return elementObject;
- },
- 'bpmn:DataOutput': function(parentGfx, element) {
- var arrowPathData = pathMap.getRawPath('DATA_ARROW');
- // page
- var elementObject = renderer('bpmn:DataObject')(parentGfx, element);
- /* output arrow path */ drawPath(parentGfx, arrowPathData, {
- strokeWidth: 1,
- fill: black
- });
- return elementObject;
- },
- 'bpmn:DataStoreReference': function(parentGfx, element) {
- var DATA_STORE_PATH = pathMap.getScaledPath('DATA_STORE', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0,
- my: 0.133
- }
- });
- var elementStore = drawPath(parentGfx, DATA_STORE_PATH, {
- strokeWidth: 2,
- fill: getFillColor(element, defaultFillColor),
- fillOpacity: DEFAULT_FILL_OPACITY,
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- return elementStore;
- },
- 'bpmn:BoundaryEvent': function(parentGfx, element) {
- var semantic = getSemantic(element),
- cancel = semantic.cancelActivity;
- var attrs = {
- strokeWidth: 1,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- };
- if (!cancel) {
- attrs.strokeDasharray = '6';
- attrs.strokeLinecap = 'round';
- }
- // apply fillOpacity
- var outerAttrs = assign({}, attrs, {
- fillOpacity: 1
- });
- // apply no-fill
- var innerAttrs = assign({}, attrs, {
- fill: 'none'
- });
- var outer = renderer('bpmn:Event')(parentGfx, element, outerAttrs);
- /* inner path */ drawCircle(parentGfx, element.width, element.height, INNER_OUTER_DIST, innerAttrs);
- renderEventContent(element, parentGfx);
- return outer;
- },
- 'bpmn:Group': function(parentGfx, element) {
- var group = drawRect(parentGfx, element.width, element.height, TASK_BORDER_RADIUS, {
- stroke: getStrokeColor(element, defaultStrokeColor),
- strokeWidth: 1,
- strokeDasharray: '8,3,1,3',
- fill: 'none',
- pointerEvents: 'none'
- });
- return group;
- },
- 'label': function(parentGfx, element) {
- return renderExternalLabel(parentGfx, element);
- },
- 'bpmn:TextAnnotation': function(parentGfx, element) {
- var style = {
- 'fill': 'none',
- 'stroke': 'none'
- };
- var textElement = drawRect(parentGfx, element.width, element.height, 0, 0, style);
- var textPathData = pathMap.getScaledPath('TEXT_ANNOTATION', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.0,
- my: 0.0
- }
- });
- drawPath(parentGfx, textPathData, {
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- var text = getSemantic(element).text || '';
- renderLabel(parentGfx, text, {
- box: element,
- align: 'left-top',
- padding: 5,
- style: {
- fill: getLabelColor(element, defaultLabelColor, defaultStrokeColor)
- }
- });
- return textElement;
- },
- 'ParticipantMultiplicityMarker': function(parentGfx, element) {
- var markerPath = pathMap.getScaledPath('MARKER_PARALLEL', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: ((element.width / 2) / element.width),
- my: (element.height - 15) / element.height
- }
- });
- drawMarker('participant-multiplicity', parentGfx, markerPath, {
- strokeWidth: 2,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- },
- 'SubProcessMarker': function(parentGfx, element) {
- var markerRect = drawRect(parentGfx, 14, 14, 0, {
- strokeWidth: 1,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- // Process marker is placed in the middle of the box
- // therefore fixed values can be used here
- translate$1(markerRect, element.width / 2 - 7.5, element.height - 20);
- var markerPath = pathMap.getScaledPath('MARKER_SUB_PROCESS', {
- xScaleFactor: 1.5,
- yScaleFactor: 1.5,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: (element.width / 2 - 7.5) / element.width,
- my: (element.height - 20) / element.height
- }
- });
- drawMarker('sub-process', parentGfx, markerPath, {
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- },
- 'ParallelMarker': function(parentGfx, element, position) {
- var markerPath = pathMap.getScaledPath('MARKER_PARALLEL', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: ((element.width / 2 + position.parallel) / element.width),
- my: (element.height - 20) / element.height
- }
- });
- drawMarker('parallel', parentGfx, markerPath, {
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- },
- 'SequentialMarker': function(parentGfx, element, position) {
- var markerPath = pathMap.getScaledPath('MARKER_SEQUENTIAL', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: ((element.width / 2 + position.seq) / element.width),
- my: (element.height - 19) / element.height
- }
- });
- drawMarker('sequential', parentGfx, markerPath, {
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- },
- 'CompensationMarker': function(parentGfx, element, position) {
- var markerMath = pathMap.getScaledPath('MARKER_COMPENSATION', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: ((element.width / 2 + position.compensation) / element.width),
- my: (element.height - 13) / element.height
- }
- });
- drawMarker('compensation', parentGfx, markerMath, {
- strokeWidth: 1,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- },
- 'LoopMarker': function(parentGfx, element, position) {
- var markerPath = pathMap.getScaledPath('MARKER_LOOP', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: ((element.width / 2 + position.loop) / element.width),
- my: (element.height - 7) / element.height
- }
- });
- drawMarker('loop', parentGfx, markerPath, {
- strokeWidth: 1,
- fill: getFillColor(element, defaultFillColor),
- stroke: getStrokeColor(element, defaultStrokeColor),
- strokeLinecap: 'round',
- strokeMiterlimit: 0.5
- });
- },
- 'AdhocMarker': function(parentGfx, element, position) {
- var markerPath = pathMap.getScaledPath('MARKER_ADHOC', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: ((element.width / 2 + position.adhoc) / element.width),
- my: (element.height - 15) / element.height
- }
- });
- drawMarker('adhoc', parentGfx, markerPath, {
- strokeWidth: 1,
- fill: getStrokeColor(element, defaultStrokeColor),
- stroke: getStrokeColor(element, defaultStrokeColor)
- });
- }
- };
- function attachTaskMarkers(parentGfx, element, taskMarkers) {
- var obj = getSemantic(element);
- var subprocess = taskMarkers && taskMarkers.indexOf('SubProcessMarker') !== -1;
- var position;
- if (subprocess) {
- position = {
- seq: -21,
- parallel: -22,
- compensation: -42,
- loop: -18,
- adhoc: 10
- };
- } else {
- position = {
- seq: -3,
- parallel: -6,
- compensation: -27,
- loop: 0,
- adhoc: 10
- };
- }
- forEach$1(taskMarkers, function(marker) {
- renderer(marker)(parentGfx, element, position);
- });
- if (obj.isForCompensation) {
- renderer('CompensationMarker')(parentGfx, element, position);
- }
- if (obj.$type === 'bpmn:AdHocSubProcess') {
- renderer('AdhocMarker')(parentGfx, element, position);
- }
- var loopCharacteristics = obj.loopCharacteristics,
- isSequential = loopCharacteristics && loopCharacteristics.isSequential;
- if (loopCharacteristics) {
- if (isSequential === undefined) {
- renderer('LoopMarker')(parentGfx, element, position);
- }
- if (isSequential === false) {
- renderer('ParallelMarker')(parentGfx, element, position);
- }
- if (isSequential === true) {
- renderer('SequentialMarker')(parentGfx, element, position);
- }
- }
- }
- function renderDataItemCollection(parentGfx, element) {
- var yPosition = (element.height - 18) / element.height;
- var pathData = pathMap.getScaledPath('DATA_OBJECT_COLLECTION_PATH', {
- xScaleFactor: 1,
- yScaleFactor: 1,
- containerWidth: element.width,
- containerHeight: element.height,
- position: {
- mx: 0.33,
- my: yPosition
- }
- });
- /* collection path */ drawPath(parentGfx, pathData, {
- strokeWidth: 2
- });
- }
- // extension API, use at your own risk
- this._drawPath = drawPath;
- this._renderer = renderer;
- }
- e(BpmnRenderer, BaseRenderer);
- BpmnRenderer.$inject = [
- 'config.bpmnRenderer',
- 'eventBus',
- 'styles',
- 'pathMap',
- 'canvas',
- 'textRenderer'
- ];
- BpmnRenderer.prototype.canRender = function(element) {
- return is$1(element, 'bpmn:BaseElement');
- };
- BpmnRenderer.prototype.drawShape = function(parentGfx, element) {
- var type = element.type;
- var h = this._renderer(type);
- /* jshint -W040 */
- return h(parentGfx, element);
- };
- BpmnRenderer.prototype.drawConnection = function(parentGfx, element) {
- var type = element.type;
- var h = this._renderer(type);
- /* jshint -W040 */
- return h(parentGfx, element);
- };
- BpmnRenderer.prototype.getShapePath = function(element) {
- if (is$1(element, 'bpmn:Event')) {
- return getCirclePath(element);
- }
- if (is$1(element, 'bpmn:Activity')) {
- return getRoundRectPath(element, TASK_BORDER_RADIUS);
- }
- if (is$1(element, 'bpmn:Gateway')) {
- return getDiamondPath(element);
- }
- return getRectPath(element);
- };
- var DEFAULT_BOX_PADDING = 0;
- var DEFAULT_LABEL_SIZE$1 = {
- width: 150,
- height: 50
- };
- function parseAlign(align) {
- var parts = align.split('-');
- return {
- horizontal: parts[0] || 'center',
- vertical: parts[1] || 'top'
- };
- }
- function parsePadding(padding) {
- if (isObject(padding)) {
- return assign({ top: 0, left: 0, right: 0, bottom: 0 }, padding);
- } else {
- return {
- top: padding,
- left: padding,
- right: padding,
- bottom: padding
- };
- }
- }
- function getTextBBox(text, fakeText) {
- fakeText.textContent = text;
- var textBBox;
- try {
- var bbox,
- emptyLine = text === '';
- // add dummy text, when line is empty to
- // determine correct height
- fakeText.textContent = emptyLine ? 'dummy' : text;
- textBBox = fakeText.getBBox();
- // take text rendering related horizontal
- // padding into account
- bbox = {
- width: textBBox.width + textBBox.x * 2,
- height: textBBox.height
- };
- if (emptyLine) {
- // correct width
- bbox.width = 0;
- }
- return bbox;
- } catch (e) {
- return { width: 0, height: 0 };
- }
- }
- /**
- * Layout the next line and return the layouted element.
- *
- * Alters the lines passed.
- *
- * @param {Array<string>} lines
- * @return {Object} the line descriptor, an object { width, height, text }
- */
- function layoutNext(lines, maxWidth, fakeText) {
- var originalLine = lines.shift(),
- fitLine = originalLine;
- var textBBox;
- for (;;) {
- textBBox = getTextBBox(fitLine, fakeText);
- textBBox.width = fitLine ? textBBox.width : 0;
- // try to fit
- if (fitLine === ' ' || fitLine === '' || textBBox.width < Math.round(maxWidth) || fitLine.length < 2) {
- return fit(lines, fitLine, originalLine, textBBox);
- }
- fitLine = shortenLine(fitLine, textBBox.width, maxWidth);
- }
- }
- function fit(lines, fitLine, originalLine, textBBox) {
- if (fitLine.length < originalLine.length) {
- var remainder = originalLine.slice(fitLine.length).trim();
- lines.unshift(remainder);
- }
- return {
- width: textBBox.width,
- height: textBBox.height,
- text: fitLine
- };
- }
- var SOFT_BREAK = '\u00AD';
- /**
- * Shortens a line based on spacing and hyphens.
- * Returns the shortened result on success.
- *
- * @param {string} line
- * @param {number} maxLength the maximum characters of the string
- * @return {string} the shortened string
- */
- function semanticShorten(line, maxLength) {
- var parts = line.split(/(\s|-|\u00AD)/g),
- part,
- shortenedParts = [],
- length = 0;
- // try to shorten via break chars
- if (parts.length > 1) {
- while ((part = parts.shift())) {
- if (part.length + length < maxLength) {
- shortenedParts.push(part);
- length += part.length;
- } else {
- // remove previous part, too if hyphen does not fit anymore
- if (part === '-' || part === SOFT_BREAK) {
- shortenedParts.pop();
- }
- break;
- }
- }
- }
- var last = shortenedParts[shortenedParts.length - 1];
- // translate trailing soft break to actual hyphen
- if (last && last === SOFT_BREAK) {
- shortenedParts[shortenedParts.length - 1] = '-';
- }
- return shortenedParts.join('');
- }
- function shortenLine(line, width, maxWidth) {
- var length = Math.max(line.length * (maxWidth / width), 1);
- // try to shorten semantically (i.e. based on spaces and hyphens)
- var shortenedLine = semanticShorten(line, length);
- if (!shortenedLine) {
- // force shorten by cutting the long word
- shortenedLine = line.slice(0, Math.max(Math.round(length - 1), 1));
- }
- return shortenedLine;
- }
- function getHelperSvg() {
- var helperSvg = document.getElementById('helper-svg');
- if (!helperSvg) {
- helperSvg = create$1('svg');
- attr$1(helperSvg, {
- id: 'helper-svg',
- width: 0,
- height: 0,
- visibility: 'hidden',
- position: 'fixed'
- });
- document.body.appendChild(helperSvg);
- }
- return helperSvg;
- }
- /**
- * Creates a new label utility
- *
- * @param {Object} config
- * @param {Dimensions} config.size
- * @param {number} config.padding
- * @param {Object} config.style
- * @param {string} config.align
- */
- function Text(config) {
- this._config = assign({}, {
- size: DEFAULT_LABEL_SIZE$1,
- padding: DEFAULT_BOX_PADDING,
- style: {},
- align: 'center-top'
- }, config || {});
- }
- /**
- * Returns the layouted text as an SVG element.
- *
- * @param {string} text
- * @param {Object} options
- *
- * @return {SVGElement}
- */
- Text.prototype.createText = function(text, options) {
- return this.layoutText(text, options).element;
- };
- /**
- * Returns a labels layouted dimensions.
- *
- * @param {string} text to layout
- * @param {Object} options
- *
- * @return {Dimensions}
- */
- Text.prototype.getDimensions = function(text, options) {
- return this.layoutText(text, options).dimensions;
- };
- /**
- * Creates and returns a label and its bounding box.
- *
- * @method Text#createText
- *
- * @param {string} text the text to render on the label
- * @param {Object} options
- * @param {string} options.align how to align in the bounding box.
- * Any of { 'center-middle', 'center-top' },
- * defaults to 'center-top'.
- * @param {string} options.style style to be applied to the text
- * @param {boolean} options.fitBox indicates if box will be recalculated to
- * fit text
- *
- * @return {Object} { element, dimensions }
- */
- Text.prototype.layoutText = function(text, options) {
- var box = assign({}, this._config.size, options.box),
- style = assign({}, this._config.style, options.style),
- align = parseAlign(options.align || this._config.align),
- padding = parsePadding(options.padding !== undefined ? options.padding : this._config.padding),
- fitBox = options.fitBox || false;
- var lineHeight = getLineHeight(style);
- // we split text by lines and normalize
- // {soft break} + {line break} => { line break }
- var lines = text.split(/\u00AD?\r?\n/),
- layouted = [];
- var maxWidth = box.width - padding.left - padding.right;
- // ensure correct rendering by attaching helper text node to invisible SVG
- var helperText = create$1('text');
- attr$1(helperText, { x: 0, y: 0 });
- attr$1(helperText, style);
- var helperSvg = getHelperSvg();
- append(helperSvg, helperText);
- while (lines.length) {
- layouted.push(layoutNext(lines, maxWidth, helperText));
- }
- if (align.vertical === 'middle') {
- padding.top = padding.bottom = 0;
- }
- var totalHeight = reduce(layouted, function(sum, line, idx) {
- return sum + (lineHeight || line.height);
- }, 0) + padding.top + padding.bottom;
- var maxLineWidth = reduce(layouted, function(sum, line, idx) {
- return line.width > sum ? line.width : sum;
- }, 0);
- // the y position of the next line
- var y = padding.top;
- if (align.vertical === 'middle') {
- y += (box.height - totalHeight) / 2;
- }
- // magic number initial offset
- y -= (lineHeight || layouted[0].height) / 4;
- var textElement = create$1('text');
- attr$1(textElement, style);
- // layout each line taking into account that parent
- // shape might resize to fit text size
- forEach$1(layouted, function(line) {
- var x;
- y += (lineHeight || line.height);
- switch (align.horizontal) {
- case 'left':
- x = padding.left;
- break;
- case 'right':
- x = ((fitBox ? maxLineWidth : maxWidth)
- - padding.right - line.width);
- break;
- default:
- // aka center
- x = Math.max((((fitBox ? maxLineWidth : maxWidth)
- - line.width) / 2 + padding.left), 0);
- }
- var tspan = create$1('tspan');
- attr$1(tspan, { x: x, y: y });
- tspan.textContent = line.text;
- append(textElement, tspan);
- });
- remove$2(helperText);
- var dimensions = {
- width: maxLineWidth,
- height: totalHeight
- };
- return {
- dimensions: dimensions,
- element: textElement
- };
- };
- function getLineHeight(style) {
- if ('fontSize' in style && 'lineHeight' in style) {
- return style.lineHeight * parseInt(style.fontSize, 10);
- }
- }
- var DEFAULT_FONT_SIZE = 12;
- var LINE_HEIGHT_RATIO = 1.2;
- var MIN_TEXT_ANNOTATION_HEIGHT = 30;
- function TextRenderer(config) {
- var defaultStyle = assign({
- fontFamily: 'Arial, sans-serif',
- fontSize: DEFAULT_FONT_SIZE,
- fontWeight: 'normal',
- lineHeight: LINE_HEIGHT_RATIO
- }, config && config.defaultStyle || {});
- var fontSize = parseInt(defaultStyle.fontSize, 10) - 1;
- var externalStyle = assign({}, defaultStyle, {
- fontSize: fontSize
- }, config && config.externalStyle || {});
- var textUtil = new Text({
- style: defaultStyle
- });
- /**
- * Get the new bounds of an externally rendered,
- * layouted label.
- *
- * @param {Bounds} bounds
- * @param {string} text
- *
- * @return {Bounds}
- */
- this.getExternalLabelBounds = function(bounds, text) {
- var layoutedDimensions = textUtil.getDimensions(text, {
- box: {
- width: 90,
- height: 30,
- x: bounds.width / 2 + bounds.x,
- y: bounds.height / 2 + bounds.y
- },
- style: externalStyle
- });
- // resize label shape to fit label text
- return {
- x: Math.round(bounds.x + bounds.width / 2 - layoutedDimensions.width / 2),
- y: Math.round(bounds.y),
- width: Math.ceil(layoutedDimensions.width),
- height: Math.ceil(layoutedDimensions.height)
- };
- };
- /**
- * Get the new bounds of text annotation.
- *
- * @param {Bounds} bounds
- * @param {string} text
- *
- * @return {Bounds}
- */
- this.getTextAnnotationBounds = function(bounds, text) {
- var layoutedDimensions = textUtil.getDimensions(text, {
- box: bounds,
- style: defaultStyle,
- align: 'left-top',
- padding: 5
- });
- return {
- x: bounds.x,
- y: bounds.y,
- width: bounds.width,
- height: Math.max(MIN_TEXT_ANNOTATION_HEIGHT, Math.round(layoutedDimensions.height))
- };
- };
- /**
- * Create a layouted text element.
- *
- * @param {string} text
- * @param {Object} [options]
- *
- * @return {SVGElement} rendered text
- */
- this.createText = function(text, options) {
- return textUtil.createText(text, options || {});
- };
- /**
- * Get default text style.
- */
- this.getDefaultStyle = function() {
- return defaultStyle;
- };
- /**
- * Get the external text style.
- */
- this.getExternalStyle = function() {
- return externalStyle;
- };
- }
- TextRenderer.$inject = [
- 'config.textRenderer'
- ];
- /**
- * Map containing SVG paths needed by BpmnRenderer.
- */
- function PathMap() {
- /**
- * Contains a map of path elements
- *
- * <h1>Path definition</h1>
- * A parameterized path is defined like this:
- * <pre>
- * 'GATEWAY_PARALLEL': {
- * d: 'm {mx},{my} {e.x0},0 0,{e.x1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +
- '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',
- * height: 17.5,
- * width: 17.5,
- * heightElements: [2.5, 7.5],
- * widthElements: [2.5, 7.5]
- * }
- * </pre>
- * <p>It's important to specify a correct <b>height and width</b> for the path as the scaling
- * is based on the ratio between the specified height and width in this object and the
- * height and width that is set as scale target (Note x,y coordinates will be scaled with
- * individual ratios).</p>
- * <p>The '<b>heightElements</b>' and '<b>widthElements</b>' array must contain the values that will be scaled.
- * The scaling is based on the computed ratios.
- * Coordinates on the y axis should be in the <b>heightElement</b>'s array, they will be scaled using
- * the computed ratio coefficient.
- * In the parameterized path the scaled values can be accessed through the 'e' object in {} brackets.
- * <ul>
- * <li>The values for the y axis can be accessed in the path string using {e.y0}, {e.y1}, ....</li>
- * <li>The values for the x axis can be accessed in the path string using {e.x0}, {e.x1}, ....</li>
- * </ul>
- * The numbers x0, x1 respectively y0, y1, ... map to the corresponding array index.
- * </p>
- */
- this.pathMap = {
- 'EVENT_MESSAGE': {
- d: 'm {mx},{my} l 0,{e.y1} l {e.x1},0 l 0,-{e.y1} z l {e.x0},{e.y0} l {e.x0},-{e.y0}',
- height: 36,
- width: 36,
- heightElements: [6, 14],
- widthElements: [10.5, 21]
- },
- 'EVENT_SIGNAL': {
- d: 'M {mx},{my} l {e.x0},{e.y0} l -{e.x1},0 Z',
- height: 36,
- width: 36,
- heightElements: [18],
- widthElements: [10, 20]
- },
- 'EVENT_ESCALATION': {
- d: 'M {mx},{my} l {e.x0},{e.y0} l -{e.x0},-{e.y1} l -{e.x0},{e.y1} Z',
- height: 36,
- width: 36,
- heightElements: [20, 7],
- widthElements: [8]
- },
- 'EVENT_CONDITIONAL': {
- d: 'M {e.x0},{e.y0} l {e.x1},0 l 0,{e.y2} l -{e.x1},0 Z ' +
- 'M {e.x2},{e.y3} l {e.x0},0 ' +
- 'M {e.x2},{e.y4} l {e.x0},0 ' +
- 'M {e.x2},{e.y5} l {e.x0},0 ' +
- 'M {e.x2},{e.y6} l {e.x0},0 ' +
- 'M {e.x2},{e.y7} l {e.x0},0 ' +
- 'M {e.x2},{e.y8} l {e.x0},0 ',
- height: 36,
- width: 36,
- heightElements: [8.5, 14.5, 18, 11.5, 14.5, 17.5, 20.5, 23.5, 26.5],
- widthElements: [10.5, 14.5, 12.5]
- },
- 'EVENT_LINK': {
- d: 'm {mx},{my} 0,{e.y0} -{e.x1},0 0,{e.y1} {e.x1},0 0,{e.y0} {e.x0},-{e.y2} -{e.x0},-{e.y2} z',
- height: 36,
- width: 36,
- heightElements: [4.4375, 6.75, 7.8125],
- widthElements: [9.84375, 13.5]
- },
- 'EVENT_ERROR': {
- d: 'm {mx},{my} {e.x0},-{e.y0} {e.x1},-{e.y1} {e.x2},{e.y2} {e.x3},-{e.y3} -{e.x4},{e.y4} -{e.x5},-{e.y5} z',
- height: 36,
- width: 36,
- heightElements: [0.023, 8.737, 8.151, 16.564, 10.591, 8.714],
- widthElements: [0.085, 6.672, 6.97, 4.273, 5.337, 6.636]
- },
- 'EVENT_CANCEL_45': {
- d: 'm {mx},{my} -{e.x1},0 0,{e.x0} {e.x1},0 0,{e.y1} {e.x0},0 ' +
- '0,-{e.y1} {e.x1},0 0,-{e.y0} -{e.x1},0 0,-{e.y1} -{e.x0},0 z',
- height: 36,
- width: 36,
- heightElements: [4.75, 8.5],
- widthElements: [4.75, 8.5]
- },
- 'EVENT_COMPENSATION': {
- d: 'm {mx},{my} {e.x0},-{e.y0} 0,{e.y1} z m {e.x1},-{e.y2} {e.x2},-{e.y3} 0,{e.y1} -{e.x2},-{e.y3} z',
- height: 36,
- width: 36,
- heightElements: [6.5, 13, 0.4, 6.1],
- widthElements: [9, 9.3, 8.7]
- },
- 'EVENT_TIMER_WH': {
- d: 'M {mx},{my} l {e.x0},-{e.y0} m -{e.x0},{e.y0} l {e.x1},{e.y1} ',
- height: 36,
- width: 36,
- heightElements: [10, 2],
- widthElements: [3, 7]
- },
- 'EVENT_TIMER_LINE': {
- d: 'M {mx},{my} ' +
- 'm {e.x0},{e.y0} l -{e.x1},{e.y1} ',
- height: 36,
- width: 36,
- heightElements: [10, 3],
- widthElements: [0, 0]
- },
- 'EVENT_MULTIPLE': {
- d:'m {mx},{my} {e.x1},-{e.y0} {e.x1},{e.y0} -{e.x0},{e.y1} -{e.x2},0 z',
- height: 36,
- width: 36,
- heightElements: [6.28099, 12.56199],
- widthElements: [3.1405, 9.42149, 12.56198]
- },
- 'EVENT_PARALLEL_MULTIPLE': {
- d:'m {mx},{my} {e.x0},0 0,{e.y1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +
- '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',
- height: 36,
- width: 36,
- heightElements: [2.56228, 7.68683],
- widthElements: [2.56228, 7.68683]
- },
- 'GATEWAY_EXCLUSIVE': {
- d:'m {mx},{my} {e.x0},{e.y0} {e.x1},{e.y0} {e.x2},0 {e.x4},{e.y2} ' +
- '{e.x4},{e.y1} {e.x2},0 {e.x1},{e.y3} {e.x0},{e.y3} ' +
- '{e.x3},0 {e.x5},{e.y1} {e.x5},{e.y2} {e.x3},0 z',
- height: 17.5,
- width: 17.5,
- heightElements: [8.5, 6.5312, -6.5312, -8.5],
- widthElements: [6.5, -6.5, 3, -3, 5, -5]
- },
- 'GATEWAY_PARALLEL': {
- d:'m {mx},{my} 0,{e.y1} -{e.x1},0 0,{e.y0} {e.x1},0 0,{e.y1} {e.x0},0 ' +
- '0,-{e.y1} {e.x1},0 0,-{e.y0} -{e.x1},0 0,-{e.y1} -{e.x0},0 z',
- height: 30,
- width: 30,
- heightElements: [5, 12.5],
- widthElements: [5, 12.5]
- },
- 'GATEWAY_EVENT_BASED': {
- d:'m {mx},{my} {e.x0},{e.y0} {e.x0},{e.y1} {e.x1},{e.y2} {e.x2},0 z',
- height: 11,
- width: 11,
- heightElements: [-6, 6, 12, -12],
- widthElements: [9, -3, -12]
- },
- 'GATEWAY_COMPLEX': {
- d:'m {mx},{my} 0,{e.y0} -{e.x0},-{e.y1} -{e.x1},{e.y2} {e.x0},{e.y1} -{e.x2},0 0,{e.y3} ' +
- '{e.x2},0 -{e.x0},{e.y1} l {e.x1},{e.y2} {e.x0},-{e.y1} 0,{e.y0} {e.x3},0 0,-{e.y0} {e.x0},{e.y1} ' +
- '{e.x1},-{e.y2} -{e.x0},-{e.y1} {e.x2},0 0,-{e.y3} -{e.x2},0 {e.x0},-{e.y1} -{e.x1},-{e.y2} ' +
- '-{e.x0},{e.y1} 0,-{e.y0} -{e.x3},0 z',
- height: 17.125,
- width: 17.125,
- heightElements: [4.875, 3.4375, 2.125, 3],
- widthElements: [3.4375, 2.125, 4.875, 3]
- },
- 'DATA_OBJECT_PATH': {
- d:'m 0,0 {e.x1},0 {e.x0},{e.y0} 0,{e.y1} -{e.x2},0 0,-{e.y2} {e.x1},0 0,{e.y0} {e.x0},0',
- height: 61,
- width: 51,
- heightElements: [10, 50, 60],
- widthElements: [10, 40, 50, 60]
- },
- 'DATA_OBJECT_COLLECTION_PATH': {
- d: 'm{mx},{my} m 3,2 l 0,10 m 3,-10 l 0,10 m 3,-10 l 0,10',
- height: 10,
- width: 10,
- heightElements: [],
- widthElements: []
- },
- 'DATA_ARROW': {
- d:'m 5,9 9,0 0,-3 5,5 -5,5 0,-3 -9,0 z',
- height: 61,
- width: 51,
- heightElements: [],
- widthElements: []
- },
- 'DATA_STORE': {
- d:'m {mx},{my} ' +
- 'l 0,{e.y2} ' +
- 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0 ' +
- 'l 0,-{e.y2} ' +
- 'c -{e.x0},-{e.y1} -{e.x1},-{e.y1} -{e.x2},0' +
- 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0 ' +
- 'm -{e.x2},{e.y0}' +
- 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0' +
- 'm -{e.x2},{e.y0}' +
- 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0',
- height: 61,
- width: 61,
- heightElements: [7, 10, 45],
- widthElements: [2, 58, 60]
- },
- 'TEXT_ANNOTATION': {
- d: 'm {mx}, {my} m 10,0 l -10,0 l 0,{e.y0} l 10,0',
- height: 30,
- width: 10,
- heightElements: [30],
- widthElements: [10]
- },
- 'MARKER_SUB_PROCESS': {
- d: 'm{mx},{my} m 7,2 l 0,10 m -5,-5 l 10,0',
- height: 10,
- width: 10,
- heightElements: [],
- widthElements: []
- },
- 'MARKER_PARALLEL': {
- d: 'm{mx},{my} m 3,2 l 0,10 m 3,-10 l 0,10 m 3,-10 l 0,10',
- height: 10,
- width: 10,
- heightElements: [],
- widthElements: []
- },
- 'MARKER_SEQUENTIAL': {
- d: 'm{mx},{my} m 0,3 l 10,0 m -10,3 l 10,0 m -10,3 l 10,0',
- height: 10,
- width: 10,
- heightElements: [],
- widthElements: []
- },
- 'MARKER_COMPENSATION': {
- d: 'm {mx},{my} 7,-5 0,10 z m 7.1,-0.3 6.9,-4.7 0,10 -6.9,-4.7 z',
- height: 10,
- width: 21,
- heightElements: [],
- widthElements: []
- },
- 'MARKER_LOOP': {
- d: 'm {mx},{my} c 3.526979,0 6.386161,-2.829858 6.386161,-6.320661 0,-3.490806 -2.859182,-6.320661 ' +
- '-6.386161,-6.320661 -3.526978,0 -6.38616,2.829855 -6.38616,6.320661 0,1.745402 ' +
- '0.714797,3.325567 1.870463,4.469381 0.577834,0.571908 1.265885,1.034728 2.029916,1.35457 ' +
- 'l -0.718163,-3.909793 m 0.718163,3.909793 -3.885211,0.802902',
- height: 13.9,
- width: 13.7,
- heightElements: [],
- widthElements: []
- },
- 'MARKER_ADHOC': {
- d: 'm {mx},{my} m 0.84461,2.64411 c 1.05533,-1.23780996 2.64337,-2.07882 4.29653,-1.97997996 2.05163,0.0805 ' +
- '3.85579,1.15803 5.76082,1.79107 1.06385,0.34139996 2.24454,0.1438 3.18759,-0.43767 0.61743,-0.33642 ' +
- '1.2775,-0.64078 1.7542,-1.17511 0,0.56023 0,1.12046 0,1.6807 -0.98706,0.96237996 -2.29792,1.62393996 ' +
- '-3.6918,1.66181996 -1.24459,0.0927 -2.46671,-0.2491 -3.59505,-0.74812 -1.35789,-0.55965 ' +
- '-2.75133,-1.33436996 -4.27027,-1.18121996 -1.37741,0.14601 -2.41842,1.13685996 -3.44288,1.96782996 z',
- height: 4,
- width: 15,
- heightElements: [],
- widthElements: []
- },
- 'TASK_TYPE_SEND': {
- d: 'm {mx},{my} l 0,{e.y1} l {e.x1},0 l 0,-{e.y1} z l {e.x0},{e.y0} l {e.x0},-{e.y0}',
- height: 14,
- width: 21,
- heightElements: [6, 14],
- widthElements: [10.5, 21]
- },
- 'TASK_TYPE_SCRIPT': {
- d: 'm {mx},{my} c 9.966553,-6.27276 -8.000926,-7.91932 2.968968,-14.938 l -8.802728,0 ' +
- 'c -10.969894,7.01868 6.997585,8.66524 -2.968967,14.938 z ' +
- 'm -7,-12 l 5,0 ' +
- 'm -4.5,3 l 4.5,0 ' +
- 'm -3,3 l 5,0' +
- 'm -4,3 l 5,0',
- height: 15,
- width: 12.6,
- heightElements: [6, 14],
- widthElements: [10.5, 21]
- },
- 'TASK_TYPE_USER_1': {
- d: 'm {mx},{my} c 0.909,-0.845 1.594,-2.049 1.594,-3.385 0,-2.554 -1.805,-4.62199999 ' +
- '-4.357,-4.62199999 -2.55199998,0 -4.28799998,2.06799999 -4.28799998,4.62199999 0,1.348 ' +
- '0.974,2.562 1.89599998,3.405 -0.52899998,0.187 -5.669,2.097 -5.794,4.7560005 v 6.718 ' +
- 'h 17 v -6.718 c 0,-2.2980005 -5.5279996,-4.5950005 -6.0509996,-4.7760005 z' +
- 'm -8,6 l 0,5.5 m 11,0 l 0,-5'
- },
- 'TASK_TYPE_USER_2': {
- d: 'm {mx},{my} m 2.162,1.009 c 0,2.4470005 -2.158,4.4310005 -4.821,4.4310005 ' +
- '-2.66499998,0 -4.822,-1.981 -4.822,-4.4310005 '
- },
- 'TASK_TYPE_USER_3': {
- d: 'm {mx},{my} m -6.9,-3.80 c 0,0 2.25099998,-2.358 4.27399998,-1.177 2.024,1.181 4.221,1.537 ' +
- '4.124,0.965 -0.098,-0.57 -0.117,-3.79099999 -4.191,-4.13599999 -3.57499998,0.001 ' +
- '-4.20799998,3.36699999 -4.20699998,4.34799999 z'
- },
- 'TASK_TYPE_MANUAL': {
- d: 'm {mx},{my} c 0.234,-0.01 5.604,0.008 8.029,0.004 0.808,0 1.271,-0.172 1.417,-0.752 0.227,-0.898 ' +
- '-0.334,-1.314 -1.338,-1.316 -2.467,-0.01 -7.886,-0.004 -8.108,-0.004 -0.014,-0.079 0.016,-0.533 0,-0.61 ' +
- '0.195,-0.042 8.507,0.006 9.616,0.002 0.877,-0.007 1.35,-0.438 1.353,-1.208 0.003,-0.768 -0.479,-1.09 ' +
- '-1.35,-1.091 -2.968,-0.002 -9.619,-0.013 -9.619,-0.013 v -0.591 c 0,0 5.052,-0.016 7.225,-0.016 ' +
- '0.888,-0.002 1.354,-0.416 1.351,-1.193 -0.006,-0.761 -0.492,-1.196 -1.361,-1.196 -3.473,-0.005 ' +
- '-10.86,-0.003 -11.0829995,-0.003 -0.022,-0.047 -0.045,-0.094 -0.069,-0.139 0.3939995,-0.319 ' +
- '2.0409995,-1.626 2.4149995,-2.017 0.469,-0.4870005 0.519,-1.1650005 0.162,-1.6040005 -0.414,-0.511 ' +
- '-0.973,-0.5 -1.48,-0.236 -1.4609995,0.764 -6.5999995,3.6430005 -7.7329995,4.2710005 -0.9,0.499 ' +
- '-1.516,1.253 -1.882,2.19 -0.37000002,0.95 -0.17,2.01 -0.166,2.979 0.004,0.718 -0.27300002,1.345 ' +
- '-0.055,2.063 0.629,2.087 2.425,3.312 4.859,3.318 4.6179995,0.014 9.2379995,-0.139 13.8569995,-0.158 ' +
- '0.755,-0.004 1.171,-0.301 1.182,-1.033 0.012,-0.754 -0.423,-0.969 -1.183,-0.973 -1.778,-0.01 ' +
- '-5.824,-0.004 -6.04,-0.004 10e-4,-0.084 0.003,-0.586 10e-4,-0.67 z'
- },
- 'TASK_TYPE_INSTANTIATING_SEND': {
- d: 'm {mx},{my} l 0,8.4 l 12.6,0 l 0,-8.4 z l 6.3,3.6 l 6.3,-3.6'
- },
- 'TASK_TYPE_SERVICE': {
- d: 'm {mx},{my} v -1.71335 c 0.352326,-0.0705 0.703932,-0.17838 1.047628,-0.32133 ' +
- '0.344416,-0.14465 0.665822,-0.32133 0.966377,-0.52145 l 1.19431,1.18005 1.567487,-1.57688 ' +
- '-1.195028,-1.18014 c 0.403376,-0.61394 0.683079,-1.29908 0.825447,-2.01824 l 1.622133,-0.01 ' +
- 'v -2.2196 l -1.636514,0.01 c -0.07333,-0.35153 -0.178319,-0.70024 -0.323564,-1.04372 ' +
- '-0.145244,-0.34406 -0.321407,-0.6644 -0.522735,-0.96217 l 1.131035,-1.13631 -1.583305,-1.56293 ' +
- '-1.129598,1.13589 c -0.614052,-0.40108 -1.302883,-0.68093 -2.022633,-0.82247 l 0.0093,-1.61852 ' +
- 'h -2.241173 l 0.0042,1.63124 c -0.353763,0.0736 -0.705369,0.17977 -1.049785,0.32371 -0.344415,0.14437 ' +
- '-0.665102,0.32092 -0.9635006,0.52046 l -1.1698628,-1.15823 -1.5667691,1.5792 1.1684265,1.15669 ' +
- 'c -0.4026573,0.61283 -0.68308,1.29797 -0.8247287,2.01713 l -1.6588041,0.003 v 2.22174 ' +
- 'l 1.6724648,-0.006 c 0.073327,0.35077 0.1797598,0.70243 0.3242851,1.04472 0.1452428,0.34448 ' +
- '0.3214064,0.6644 0.5227339,0.96066 l -1.1993431,1.19723 1.5840256,1.56011 1.1964668,-1.19348 ' +
- 'c 0.6140517,0.40346 1.3028827,0.68232 2.0233517,0.82331 l 7.19e-4,1.69892 h 2.226848 z ' +
- 'm 0.221462,-3.9957 c -1.788948,0.7502 -3.8576,-0.0928 -4.6097055,-1.87438 -0.7521065,-1.78321 ' +
- '0.090598,-3.84627 1.8802645,-4.59604 1.78823,-0.74936 3.856881,0.0929 4.608987,1.87437 ' +
- '0.752106,1.78165 -0.0906,3.84612 -1.879546,4.59605 z'
- },
- 'TASK_TYPE_SERVICE_FILL': {
- d: 'm {mx},{my} c -1.788948,0.7502 -3.8576,-0.0928 -4.6097055,-1.87438 -0.7521065,-1.78321 ' +
- '0.090598,-3.84627 1.8802645,-4.59604 1.78823,-0.74936 3.856881,0.0929 4.608987,1.87437 ' +
- '0.752106,1.78165 -0.0906,3.84612 -1.879546,4.59605 z'
- },
- 'TASK_TYPE_BUSINESS_RULE_HEADER': {
- d: 'm {mx},{my} 0,4 20,0 0,-4 z'
- },
- 'TASK_TYPE_BUSINESS_RULE_MAIN': {
- d: 'm {mx},{my} 0,12 20,0 0,-12 z' +
- 'm 0,8 l 20,0 ' +
- 'm -13,-4 l 0,8'
- },
- 'MESSAGE_FLOW_MARKER': {
- d: 'm {mx},{my} m -10.5 ,-7 l 0,14 l 21,0 l 0,-14 z l 10.5,6 l 10.5,-6'
- }
- };
- this.getRawPath = function getRawPath(pathId) {
- return this.pathMap[pathId].d;
- };
- /**
- * Scales the path to the given height and width.
- * <h1>Use case</h1>
- * <p>Use case is to scale the content of elements (event, gateways) based
- * on the element bounding box's size.
- * </p>
- * <h1>Why not transform</h1>
- * <p>Scaling a path with transform() will also scale the stroke and IE does not support
- * the option 'non-scaling-stroke' to prevent this.
- * Also there are use cases where only some parts of a path should be
- * scaled.</p>
- *
- * @param {string} pathId The ID of the path.
- * @param {Object} param <p>
- * Example param object scales the path to 60% size of the container (data.width, data.height).
- * <pre>
- * {
- * xScaleFactor: 0.6,
- * yScaleFactor:0.6,
- * containerWidth: data.width,
- * containerHeight: data.height,
- * position: {
- * mx: 0.46,
- * my: 0.2,
- * }
- * }
- * </pre>
- * <ul>
- * <li>targetpathwidth = xScaleFactor * containerWidth</li>
- * <li>targetpathheight = yScaleFactor * containerHeight</li>
- * <li>Position is used to set the starting coordinate of the path. M is computed:
- * <ul>
- * <li>position.x * containerWidth</li>
- * <li>position.y * containerHeight</li>
- * </ul>
- * Center of the container <pre> position: {
- * mx: 0.5,
- * my: 0.5,
- * }</pre>
- * Upper left corner of the container
- * <pre> position: {
- * mx: 0.0,
- * my: 0.0,
- * }</pre>
- * </li>
- * </ul>
- * </p>
- *
- */
- this.getScaledPath = function getScaledPath(pathId, param) {
- var rawPath = this.pathMap[pathId];
- // positioning
- // compute the start point of the path
- var mx, my;
- if (param.abspos) {
- mx = param.abspos.x;
- my = param.abspos.y;
- } else {
- mx = param.containerWidth * param.position.mx;
- my = param.containerHeight * param.position.my;
- }
- var coordinates = {}; // map for the scaled coordinates
- if (param.position) {
- // path
- var heightRatio = (param.containerHeight / rawPath.height) * param.yScaleFactor;
- var widthRatio = (param.containerWidth / rawPath.width) * param.xScaleFactor;
- // Apply height ratio
- for (var heightIndex = 0; heightIndex < rawPath.heightElements.length; heightIndex++) {
- coordinates['y' + heightIndex] = rawPath.heightElements[heightIndex] * heightRatio;
- }
- // Apply width ratio
- for (var widthIndex = 0; widthIndex < rawPath.widthElements.length; widthIndex++) {
- coordinates['x' + widthIndex] = rawPath.widthElements[widthIndex] * widthRatio;
- }
- }
- // Apply value to raw path
- var path = format(
- rawPath.d, {
- mx: mx,
- my: my,
- e: coordinates
- }
- );
- return path;
- };
- }
- // helpers //////////////////////
- // copied and adjusted from https://github.com/adobe-webplatform/Snap.svg/blob/master/src/svg.js
- var tokenRegex = /\{([^{}]+)\}/g,
- objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g; // matches .xxxxx or ["xxxxx"] to run over object properties
- function replacer(all, key, obj) {
- var res = obj;
- key.replace(objNotationRegex, function(all, name, quote, quotedName, isFunc) {
- name = name || quotedName;
- if (res) {
- if (name in res) {
- res = res[name];
- }
- typeof res == 'function' && isFunc && (res = res());
- }
- });
- res = (res == null || res == obj ? all : res) + '';
- return res;
- }
- function format(str, obj) {
- return String(str).replace(tokenRegex, function(all, key) {
- return replacer(all, key, obj);
- });
- }
- var DrawModule$1 = {
- __init__: [ 'bpmnRenderer' ],
- bpmnRenderer: [ 'type', BpmnRenderer ],
- textRenderer: [ 'type', TextRenderer ],
- pathMap: [ 'type', PathMap ]
- };
- /**
- * A simple translation stub to be used for multi-language support
- * in diagrams. Can be easily replaced with a more sophisticated
- * solution.
- *
- * @example
- *
- * // use it inside any diagram component by injecting `translate`.
- *
- * function MyService(translate) {
- * alert(translate('HELLO {you}', { you: 'You!' }));
- * }
- *
- * @param {string} template to interpolate
- * @param {Object} [replacements] a map with substitutes
- *
- * @return {string} the translated string
- */
- function translate(template, replacements) {
- replacements = replacements || {};
- return template.replace(/{([^}]+)}/g, function(_, key) {
- return replacements[key] || '{' + key + '}';
- });
- }
- var TranslateModule = {
- translate: [ 'value', translate ]
- };
- var DEFAULT_LABEL_SIZE = {
- width: 90,
- height: 20
- };
- var FLOW_LABEL_INDENT = 15;
- /**
- * Returns true if the given semantic has an external label
- *
- * @param {BpmnElement} semantic
- * @return {boolean} true if has label
- */
- function isLabelExternal(semantic) {
- return is$1(semantic, 'bpmn:Event') ||
- is$1(semantic, 'bpmn:Gateway') ||
- is$1(semantic, 'bpmn:DataStoreReference') ||
- is$1(semantic, 'bpmn:DataObjectReference') ||
- is$1(semantic, 'bpmn:DataInput') ||
- is$1(semantic, 'bpmn:DataOutput') ||
- is$1(semantic, 'bpmn:SequenceFlow') ||
- is$1(semantic, 'bpmn:MessageFlow') ||
- is$1(semantic, 'bpmn:Group');
- }
- /**
- * Get the position for sequence flow labels
- *
- * @param {Array<Point>} waypoints
- * @return {Point} the label position
- */
- function getFlowLabelPosition(waypoints) {
- // get the waypoints mid
- var mid = waypoints.length / 2 - 1;
- var first = waypoints[Math.floor(mid)];
- var second = waypoints[Math.ceil(mid + 0.01)];
- // get position
- var position = getWaypointsMid(waypoints);
- // calculate angle
- var angle = Math.atan((second.y - first.y) / (second.x - first.x));
- var x = position.x,
- y = position.y;
- if (Math.abs(angle) < Math.PI / 2) {
- y -= FLOW_LABEL_INDENT;
- } else {
- x += FLOW_LABEL_INDENT;
- }
- return { x: x, y: y };
- }
- /**
- * Get the middle of a number of waypoints
- *
- * @param {Array<Point>} waypoints
- * @return {Point} the mid point
- */
- function getWaypointsMid(waypoints) {
- var mid = waypoints.length / 2 - 1;
- var first = waypoints[Math.floor(mid)];
- var second = waypoints[Math.ceil(mid + 0.01)];
- return {
- x: first.x + (second.x - first.x) / 2,
- y: first.y + (second.y - first.y) / 2
- };
- }
- function getExternalLabelMid(element) {
- if (element.waypoints) {
- return getFlowLabelPosition(element.waypoints);
- } else if (is$1(element, 'bpmn:Group')) {
- return {
- x: element.x + element.width / 2,
- y: element.y + DEFAULT_LABEL_SIZE.height / 2
- };
- } else {
- return {
- x: element.x + element.width / 2,
- y: element.y + element.height + DEFAULT_LABEL_SIZE.height / 2
- };
- }
- }
- /**
- * Returns the bounds of an elements label, parsed from the elements DI or
- * generated from its bounds.
- *
- * @param {BpmndDi} di
- * @param {djs.model.Base} element
- */
- function getExternalLabelBounds(di, element) {
- var mid,
- size,
- bounds,
- label = di.label;
- if (label && label.bounds) {
- bounds = label.bounds;
- size = {
- width: Math.max(DEFAULT_LABEL_SIZE.width, bounds.width),
- height: bounds.height
- };
- mid = {
- x: bounds.x + bounds.width / 2,
- y: bounds.y + bounds.height / 2
- };
- } else {
- mid = getExternalLabelMid(element);
- size = DEFAULT_LABEL_SIZE;
- }
- return assign({
- x: mid.x - size.width / 2,
- y: mid.y - size.height / 2
- }, size);
- }
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
- function roundPoint(point) {
- return {
- x: Math.round(point.x),
- y: Math.round(point.y)
- };
- }
- /**
- * Convert the given bounds to a { top, left, bottom, right } descriptor.
- *
- * @param {Bounds|Point} bounds
- *
- * @return {Object}
- */
- function asTRBL(bounds) {
- return {
- top: bounds.y,
- right: bounds.x + (bounds.width || 0),
- bottom: bounds.y + (bounds.height || 0),
- left: bounds.x
- };
- }
- /**
- * Convert a { top, left, bottom, right } to an objects bounds.
- *
- * @param {Object} trbl
- *
- * @return {Bounds}
- */
- function asBounds(trbl) {
- return {
- x: trbl.left,
- y: trbl.top,
- width: trbl.right - trbl.left,
- height: trbl.bottom - trbl.top
- };
- }
- /**
- * Get the mid of the given bounds or point.
- *
- * @param {Bounds|Point} bounds
- *
- * @return {Point}
- */
- function getBoundsMid(bounds) {
- return roundPoint({
- x: bounds.x + (bounds.width || 0) / 2,
- y: bounds.y + (bounds.height || 0) / 2
- });
- }
- /**
- * Get the mid of the given Connection.
- *
- * @param {djs.Base.Connection} connection
- *
- * @return {Point}
- */
- function getConnectionMid(connection) {
- var waypoints = connection.waypoints;
- // calculate total length and length of each segment
- var parts = waypoints.reduce(function(parts, point, index) {
- var lastPoint = waypoints[index - 1];
- if (lastPoint) {
- var lastPart = parts[parts.length - 1];
- var startLength = lastPart && lastPart.endLength || 0;
- var length = distance(lastPoint, point);
- parts.push({
- start: lastPoint,
- end: point,
- startLength: startLength,
- endLength: startLength + length,
- length: length
- });
- }
- return parts;
- }, []);
- var totalLength = parts.reduce(function(length, part) {
- return length + part.length;
- }, 0);
- // find which segement contains middle point
- var midLength = totalLength / 2;
- var i = 0;
- var midSegment = parts[i];
- while (midSegment.endLength < midLength) {
- midSegment = parts[++i];
- }
- // calculate relative position on mid segment
- var segmentProgress = (midLength - midSegment.startLength) / midSegment.length;
- var midPoint = {
- x: midSegment.start.x + (midSegment.end.x - midSegment.start.x) * segmentProgress,
- y: midSegment.start.y + (midSegment.end.y - midSegment.start.y) * segmentProgress
- };
- return midPoint;
- }
- /**
- * Get the mid of the given Element.
- *
- * @param {djs.Base.Connection} connection
- *
- * @return {Point}
- */
- function getMid(element) {
- if (isConnection(element)) {
- return getConnectionMid(element);
- }
- return getBoundsMid(element);
- }
- // helpers //////////////////////
- function distance(a, b) {
- return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
- }
- function isConnection(element) {
- return !!element.waypoints;
- }
- function elementToString(e) {
- if (!e) {
- return '<null>';
- }
- return '<' + e.$type + (e.id ? ' id="' + e.id : '') + '" />';
- }
- /**
- * @param {ModdleElement} semantic
- * @param {ModdleElement} di
- * @param {Object} [attrs=null]
- *
- * @return {Object}
- */
- function elementData(semantic, di, attrs) {
- return assign({
- id: semantic.id,
- type: semantic.$type,
- businessObject: semantic,
- di: di
- }, attrs);
- }
- function getWaypoints(di, source, target) {
- var waypoints = di.waypoint;
- if (!waypoints || waypoints.length < 2) {
- return [ getMid(source), getMid(target) ];
- }
- return waypoints.map(function(p) {
- return { x: p.x, y: p.y };
- });
- }
- function notYetDrawn(translate, semantic, refSemantic, property) {
- return new Error(translate('element {element} referenced by {referenced}#{property} not yet drawn', {
- element: elementToString(refSemantic),
- referenced: elementToString(semantic),
- property: property
- }));
- }
- /**
- * An importer that adds bpmn elements to the canvas
- *
- * @param {EventBus} eventBus
- * @param {Canvas} canvas
- * @param {ElementFactory} elementFactory
- * @param {ElementRegistry} elementRegistry
- * @param {Function} translate
- * @param {TextRenderer} textRenderer
- */
- function BpmnImporter(
- eventBus, canvas, elementFactory,
- elementRegistry, translate, textRenderer) {
- this._eventBus = eventBus;
- this._canvas = canvas;
- this._elementFactory = elementFactory;
- this._elementRegistry = elementRegistry;
- this._translate = translate;
- this._textRenderer = textRenderer;
- }
- BpmnImporter.$inject = [
- 'eventBus',
- 'canvas',
- 'elementFactory',
- 'elementRegistry',
- 'translate',
- 'textRenderer'
- ];
- /**
- * Add bpmn element (semantic) to the canvas onto the
- * specified parent shape.
- */
- BpmnImporter.prototype.add = function(semantic, di, parentElement) {
- var element,
- translate = this._translate,
- hidden;
- var parentIndex;
- // ROOT ELEMENT
- // handle the special case that we deal with a
- // invisible root element (process, subprocess or collaboration)
- if (is$1(di, 'bpmndi:BPMNPlane')) {
- var attrs = is$1(semantic, 'bpmn:SubProcess')
- ? { id: semantic.id + '_plane' }
- : {};
- // add a virtual element (not being drawn)
- element = this._elementFactory.createRoot(elementData(semantic, di, attrs));
- this._canvas.addRootElement(element);
- }
- // SHAPE
- else if (is$1(di, 'bpmndi:BPMNShape')) {
- var collapsed = !isExpanded(semantic, di),
- isFrame = isFrameElement$1(semantic);
- hidden = parentElement && (parentElement.hidden || parentElement.collapsed);
- var bounds = di.bounds;
- element = this._elementFactory.createShape(elementData(semantic, di, {
- collapsed: collapsed,
- hidden: hidden,
- x: Math.round(bounds.x),
- y: Math.round(bounds.y),
- width: Math.round(bounds.width),
- height: Math.round(bounds.height),
- isFrame: isFrame
- }));
- if (is$1(semantic, 'bpmn:BoundaryEvent')) {
- this._attachBoundary(semantic, element);
- }
- // insert lanes behind other flow nodes (cf. #727)
- if (is$1(semantic, 'bpmn:Lane')) {
- parentIndex = 0;
- }
- if (is$1(semantic, 'bpmn:DataStoreReference')) {
- // check whether data store is inside our outside of its semantic parent
- if (!isPointInsideBBox(parentElement, getMid(bounds))) {
- parentElement = this._canvas.findRoot(parentElement);
- }
- }
- this._canvas.addShape(element, parentElement, parentIndex);
- }
- // CONNECTION
- else if (is$1(di, 'bpmndi:BPMNEdge')) {
- var source = this._getSource(semantic),
- target = this._getTarget(semantic);
- hidden = parentElement && (parentElement.hidden || parentElement.collapsed);
- element = this._elementFactory.createConnection(elementData(semantic, di, {
- hidden: hidden,
- source: source,
- target: target,
- waypoints: getWaypoints(di, source, target)
- }));
- if (is$1(semantic, 'bpmn:DataAssociation')) {
- // render always on top; this ensures DataAssociations
- // are rendered correctly across different "hacks" people
- // love to model such as cross participant / sub process
- // associations
- parentElement = this._canvas.findRoot(parentElement);
- }
- // insert sequence flows behind other flow nodes (cf. #727)
- if (is$1(semantic, 'bpmn:SequenceFlow')) {
- parentIndex = 0;
- }
- this._canvas.addConnection(element, parentElement, parentIndex);
- } else {
- throw new Error(translate('unknown di {di} for element {semantic}', {
- di: elementToString(di),
- semantic: elementToString(semantic)
- }));
- }
- // (optional) LABEL
- if (isLabelExternal(semantic) && getLabel(element)) {
- this.addLabel(semantic, di, element);
- }
- this._eventBus.fire('bpmnElement.added', { element: element });
- return element;
- };
- /**
- * Attach the boundary element to the given host
- *
- * @param {ModdleElement} boundarySemantic
- * @param {djs.model.Base} boundaryElement
- */
- BpmnImporter.prototype._attachBoundary = function(boundarySemantic, boundaryElement) {
- var translate = this._translate;
- var hostSemantic = boundarySemantic.attachedToRef;
- if (!hostSemantic) {
- throw new Error(translate('missing {semantic}#attachedToRef', {
- semantic: elementToString(boundarySemantic)
- }));
- }
- var host = this._elementRegistry.get(hostSemantic.id),
- attachers = host && host.attachers;
- if (!host) {
- throw notYetDrawn(translate, boundarySemantic, hostSemantic, 'attachedToRef');
- }
- // wire element.host <> host.attachers
- boundaryElement.host = host;
- if (!attachers) {
- host.attachers = attachers = [];
- }
- if (attachers.indexOf(boundaryElement) === -1) {
- attachers.push(boundaryElement);
- }
- };
- /**
- * add label for an element
- */
- BpmnImporter.prototype.addLabel = function(semantic, di, element) {
- var bounds,
- text,
- label;
- bounds = getExternalLabelBounds(di, element);
- text = getLabel(element);
- if (text) {
- // get corrected bounds from actual layouted text
- bounds = this._textRenderer.getExternalLabelBounds(bounds, text);
- }
- label = this._elementFactory.createLabel(elementData(semantic, di, {
- id: semantic.id + '_label',
- labelTarget: element,
- type: 'label',
- hidden: element.hidden || !getLabel(element),
- x: Math.round(bounds.x),
- y: Math.round(bounds.y),
- width: Math.round(bounds.width),
- height: Math.round(bounds.height)
- }));
- return this._canvas.addShape(label, element.parent);
- };
- /**
- * Return the drawn connection end based on the given side.
- *
- * @throws {Error} if the end is not yet drawn
- */
- BpmnImporter.prototype._getEnd = function(semantic, side) {
- var element,
- refSemantic,
- type = semantic.$type,
- translate = this._translate;
- refSemantic = semantic[side + 'Ref'];
- // handle mysterious isMany DataAssociation#sourceRef
- if (side === 'source' && type === 'bpmn:DataInputAssociation') {
- refSemantic = refSemantic && refSemantic[0];
- }
- // fix source / target for DataInputAssociation / DataOutputAssociation
- if (side === 'source' && type === 'bpmn:DataOutputAssociation' ||
- side === 'target' && type === 'bpmn:DataInputAssociation') {
- refSemantic = semantic.$parent;
- }
- element = refSemantic && this._getElement(refSemantic);
- if (element) {
- return element;
- }
- if (refSemantic) {
- throw notYetDrawn(translate, semantic, refSemantic, side + 'Ref');
- } else {
- throw new Error(translate('{semantic}#{side} Ref not specified', {
- semantic: elementToString(semantic),
- side: side
- }));
- }
- };
- BpmnImporter.prototype._getSource = function(semantic) {
- return this._getEnd(semantic, 'source');
- };
- BpmnImporter.prototype._getTarget = function(semantic) {
- return this._getEnd(semantic, 'target');
- };
- BpmnImporter.prototype._getElement = function(semantic) {
- return this._elementRegistry.get(semantic.id);
- };
- // helpers ////////////////////
- function isPointInsideBBox(bbox, point) {
- var x = point.x,
- y = point.y;
- return x >= bbox.x &&
- x <= bbox.x + bbox.width &&
- y >= bbox.y &&
- y <= bbox.y + bbox.height;
- }
- function isFrameElement$1(semantic) {
- return is$1(semantic, 'bpmn:Group');
- }
- var ImportModule = {
- __depends__: [
- TranslateModule
- ],
- bpmnImporter: [ 'type', BpmnImporter ]
- };
- var CoreModule$1 = {
- __depends__: [
- DrawModule$1,
- ImportModule
- ]
- };
- function getOriginal(event) {
- return event.originalEvent || event.srcEvent;
- }
- function toPoint(event) {
- if (event.pointers && event.pointers.length) {
- event = event.pointers[0];
- }
- if (event.touches && event.touches.length) {
- event = event.touches[0];
- }
- return event ? {
- x: event.clientX,
- y: event.clientY
- } : null;
- }
- function isMac() {
- return (/mac/i).test(navigator.platform);
- }
- function isButton(event, button) {
- return (getOriginal(event) || event).button === button;
- }
- function isPrimaryButton(event) {
- // button === 0 -> left áka primary mouse button
- return isButton(event, 0);
- }
- function isAuxiliaryButton(event) {
- // button === 1 -> auxiliary áka wheel button
- return isButton(event, 1);
- }
- function hasPrimaryModifier(event) {
- var originalEvent = getOriginal(event) || event;
- if (!isPrimaryButton(event)) {
- return false;
- }
- // Use cmd as primary modifier key for mac OS
- if (isMac()) {
- return originalEvent.metaKey;
- } else {
- return originalEvent.ctrlKey;
- }
- }
- function hasSecondaryModifier(event) {
- var originalEvent = getOriginal(event) || event;
- return isPrimaryButton(event) && originalEvent.shiftKey;
- }
- function allowAll(event) { return true; }
- function allowPrimaryAndAuxiliary(event) {
- return isPrimaryButton(event) || isAuxiliaryButton(event);
- }
- var LOW_PRIORITY$4 = 500;
- /**
- * A plugin that provides interaction events for diagram elements.
- *
- * It emits the following events:
- *
- * * element.click
- * * element.contextmenu
- * * element.dblclick
- * * element.hover
- * * element.mousedown
- * * element.mousemove
- * * element.mouseup
- * * element.out
- *
- * Each event is a tuple { element, gfx, originalEvent }.
- *
- * Canceling the event via Event#preventDefault()
- * prevents the original DOM operation.
- *
- * @param {EventBus} eventBus
- */
- function InteractionEvents(eventBus, elementRegistry, styles) {
- var self = this;
- /**
- * Fire an interaction event.
- *
- * @param {string} type local event name, e.g. element.click.
- * @param {DOMEvent} event native event
- * @param {djs.model.Base} [element] the diagram element to emit the event on;
- * defaults to the event target
- */
- function fire(type, event, element) {
- if (isIgnored(type, event)) {
- return;
- }
- var target, gfx, returnValue;
- if (!element) {
- target = event.delegateTarget || event.target;
- if (target) {
- gfx = target;
- element = elementRegistry.get(gfx);
- }
- } else {
- gfx = elementRegistry.getGraphics(element);
- }
- if (!gfx || !element) {
- return;
- }
- returnValue = eventBus.fire(type, {
- element: element,
- gfx: gfx,
- originalEvent: event
- });
- if (returnValue === false) {
- event.stopPropagation();
- event.preventDefault();
- }
- }
- // TODO(nikku): document this
- var handlers = {};
- function mouseHandler(localEventName) {
- return handlers[localEventName];
- }
- function isIgnored(localEventName, event) {
- var filter = ignoredFilters[localEventName] || isPrimaryButton;
- // only react on left mouse button interactions
- // except for interaction events that are enabled
- // for secundary mouse button
- return !filter(event);
- }
- var bindings = {
- click: 'element.click',
- contextmenu: 'element.contextmenu',
- dblclick: 'element.dblclick',
- mousedown: 'element.mousedown',
- mousemove: 'element.mousemove',
- mouseover: 'element.hover',
- mouseout: 'element.out',
- mouseup: 'element.mouseup',
- };
- var ignoredFilters = {
- 'element.contextmenu': allowAll,
- 'element.mousedown': allowPrimaryAndAuxiliary,
- 'element.mouseup': allowPrimaryAndAuxiliary,
- 'element.click': allowPrimaryAndAuxiliary,
- 'element.dblclick': allowPrimaryAndAuxiliary
- };
- // manual event trigger //////////
- /**
- * Trigger an interaction event (based on a native dom event)
- * on the target shape or connection.
- *
- * @param {string} eventName the name of the triggered DOM event
- * @param {MouseEvent} event
- * @param {djs.model.Base} targetElement
- */
- function triggerMouseEvent(eventName, event, targetElement) {
- // i.e. element.mousedown...
- var localEventName = bindings[eventName];
- if (!localEventName) {
- throw new Error('unmapped DOM event name <' + eventName + '>');
- }
- return fire(localEventName, event, targetElement);
- }
- var ELEMENT_SELECTOR = 'svg, .djs-element';
- // event handling ///////
- function registerEvent(node, event, localEvent, ignoredFilter) {
- var handler = handlers[localEvent] = function(event) {
- fire(localEvent, event);
- };
- if (ignoredFilter) {
- ignoredFilters[localEvent] = ignoredFilter;
- }
- handler.$delegate = delegate.bind(node, ELEMENT_SELECTOR, event, handler);
- }
- function unregisterEvent(node, event, localEvent) {
- var handler = mouseHandler(localEvent);
- if (!handler) {
- return;
- }
- delegate.unbind(node, event, handler.$delegate);
- }
- function registerEvents(svg) {
- forEach$1(bindings, function(val, key) {
- registerEvent(svg, key, val);
- });
- }
- function unregisterEvents(svg) {
- forEach$1(bindings, function(val, key) {
- unregisterEvent(svg, key, val);
- });
- }
- eventBus.on('canvas.destroy', function(event) {
- unregisterEvents(event.svg);
- });
- eventBus.on('canvas.init', function(event) {
- registerEvents(event.svg);
- });
- // hit box updating ////////////////
- eventBus.on([ 'shape.added', 'connection.added' ], function(event) {
- var element = event.element,
- gfx = event.gfx;
- eventBus.fire('interactionEvents.createHit', { element: element, gfx: gfx });
- });
- // Update djs-hit on change.
- // A low priortity is necessary, because djs-hit of labels has to be updated
- // after the label bounds have been updated in the renderer.
- eventBus.on([
- 'shape.changed',
- 'connection.changed'
- ], LOW_PRIORITY$4, function(event) {
- var element = event.element,
- gfx = event.gfx;
- eventBus.fire('interactionEvents.updateHit', { element: element, gfx: gfx });
- });
- eventBus.on('interactionEvents.createHit', LOW_PRIORITY$4, function(event) {
- var element = event.element,
- gfx = event.gfx;
- self.createDefaultHit(element, gfx);
- });
- eventBus.on('interactionEvents.updateHit', function(event) {
- var element = event.element,
- gfx = event.gfx;
- self.updateDefaultHit(element, gfx);
- });
- // hit styles ////////////
- var STROKE_HIT_STYLE = createHitStyle('djs-hit djs-hit-stroke');
- var CLICK_STROKE_HIT_STYLE = createHitStyle('djs-hit djs-hit-click-stroke');
- var ALL_HIT_STYLE = createHitStyle('djs-hit djs-hit-all');
- var NO_MOVE_HIT_STYLE = createHitStyle('djs-hit djs-hit-no-move');
- var HIT_TYPES = {
- 'all': ALL_HIT_STYLE,
- 'click-stroke': CLICK_STROKE_HIT_STYLE,
- 'stroke': STROKE_HIT_STYLE,
- 'no-move': NO_MOVE_HIT_STYLE
- };
- function createHitStyle(classNames, attrs) {
- attrs = assign({
- stroke: 'white',
- strokeWidth: 15
- }, attrs || {});
- return styles.cls(classNames, [ 'no-fill', 'no-border' ], attrs);
- }
- // style helpers ///////////////
- function applyStyle(hit, type) {
- var attrs = HIT_TYPES[type];
- if (!attrs) {
- throw new Error('invalid hit type <' + type + '>');
- }
- attr$1(hit, attrs);
- return hit;
- }
- function appendHit(gfx, hit) {
- append(gfx, hit);
- }
- // API
- /**
- * Remove hints on the given graphics.
- *
- * @param {SVGElement} gfx
- */
- this.removeHits = function(gfx) {
- var hits = all('.djs-hit', gfx);
- forEach$1(hits, remove$2);
- };
- /**
- * Create default hit for the given element.
- *
- * @param {djs.model.Base} element
- * @param {SVGElement} gfx
- *
- * @return {SVGElement} created hit
- */
- this.createDefaultHit = function(element, gfx) {
- var waypoints = element.waypoints,
- isFrame = element.isFrame,
- boxType;
- if (waypoints) {
- return this.createWaypointsHit(gfx, waypoints);
- } else {
- boxType = isFrame ? 'stroke' : 'all';
- return this.createBoxHit(gfx, boxType, {
- width: element.width,
- height: element.height
- });
- }
- };
- /**
- * Create hits for the given waypoints.
- *
- * @param {SVGElement} gfx
- * @param {Array<Point>} waypoints
- *
- * @return {SVGElement}
- */
- this.createWaypointsHit = function(gfx, waypoints) {
- var hit = createLine(waypoints);
- applyStyle(hit, 'stroke');
- appendHit(gfx, hit);
- return hit;
- };
- /**
- * Create hits for a box.
- *
- * @param {SVGElement} gfx
- * @param {string} hitType
- * @param {Object} attrs
- *
- * @return {SVGElement}
- */
- this.createBoxHit = function(gfx, type, attrs) {
- attrs = assign({
- x: 0,
- y: 0
- }, attrs);
- var hit = create$1('rect');
- applyStyle(hit, type);
- attr$1(hit, attrs);
- appendHit(gfx, hit);
- return hit;
- };
- /**
- * Update default hit of the element.
- *
- * @param {djs.model.Base} element
- * @param {SVGElement} gfx
- *
- * @return {SVGElement} updated hit
- */
- this.updateDefaultHit = function(element, gfx) {
- var hit = query('.djs-hit', gfx);
- if (!hit) {
- return;
- }
- if (element.waypoints) {
- updateLine(hit, element.waypoints);
- } else {
- attr$1(hit, {
- width: element.width,
- height: element.height
- });
- }
- return hit;
- };
- this.fire = fire;
- this.triggerMouseEvent = triggerMouseEvent;
- this.mouseHandler = mouseHandler;
- this.registerEvent = registerEvent;
- this.unregisterEvent = unregisterEvent;
- }
- InteractionEvents.$inject = [
- 'eventBus',
- 'elementRegistry',
- 'styles'
- ];
- /**
- * An event indicating that the mouse hovered over an element
- *
- * @event element.hover
- *
- * @type {Object}
- * @property {djs.model.Base} element
- * @property {SVGElement} gfx
- * @property {Event} originalEvent
- */
- /**
- * An event indicating that the mouse has left an element
- *
- * @event element.out
- *
- * @type {Object}
- * @property {djs.model.Base} element
- * @property {SVGElement} gfx
- * @property {Event} originalEvent
- */
- /**
- * An event indicating that the mouse has clicked an element
- *
- * @event element.click
- *
- * @type {Object}
- * @property {djs.model.Base} element
- * @property {SVGElement} gfx
- * @property {Event} originalEvent
- */
- /**
- * An event indicating that the mouse has double clicked an element
- *
- * @event element.dblclick
- *
- * @type {Object}
- * @property {djs.model.Base} element
- * @property {SVGElement} gfx
- * @property {Event} originalEvent
- */
- /**
- * An event indicating that the mouse has gone down on an element.
- *
- * @event element.mousedown
- *
- * @type {Object}
- * @property {djs.model.Base} element
- * @property {SVGElement} gfx
- * @property {Event} originalEvent
- */
- /**
- * An event indicating that the mouse has gone up on an element.
- *
- * @event element.mouseup
- *
- * @type {Object}
- * @property {djs.model.Base} element
- * @property {SVGElement} gfx
- * @property {Event} originalEvent
- */
- /**
- * An event indicating that the context menu action is triggered
- * via mouse or touch controls.
- *
- * @event element.contextmenu
- *
- * @type {Object}
- * @property {djs.model.Base} element
- * @property {SVGElement} gfx
- * @property {Event} originalEvent
- */
- var InteractionEventsModule = {
- __init__: [ 'interactionEvents' ],
- interactionEvents: [ 'type', InteractionEvents ]
- };
- /**
- * Returns the surrounding bbox for all elements in
- * the array or the element primitive.
- *
- * @param {Array<djs.model.Shape>|djs.model.Shape} elements
- * @param {boolean} [stopRecursion=false]
- *
- * @return {Bounds}
- */
- function getBBox(elements, stopRecursion) {
- stopRecursion = !!stopRecursion;
- if (!isArray$2(elements)) {
- elements = [ elements ];
- }
- var minX,
- minY,
- maxX,
- maxY;
- forEach$1(elements, function(element) {
- // If element is a connection the bbox must be computed first
- var bbox = element;
- if (element.waypoints && !stopRecursion) {
- bbox = getBBox(element.waypoints, true);
- }
- var x = bbox.x,
- y = bbox.y,
- height = bbox.height || 0,
- width = bbox.width || 0;
- if (x < minX || minX === undefined) {
- minX = x;
- }
- if (y < minY || minY === undefined) {
- minY = y;
- }
- if ((x + width) > maxX || maxX === undefined) {
- maxX = x + width;
- }
- if ((y + height) > maxY || maxY === undefined) {
- maxY = y + height;
- }
- });
- return {
- x: minX,
- y: minY,
- height: maxY - minY,
- width: maxX - minX
- };
- }
- function getType(element) {
- if ('waypoints' in element) {
- return 'connection';
- }
- if ('x' in element) {
- return 'shape';
- }
- return 'root';
- }
- function isFrameElement(element) {
- return !!(element && element.isFrame);
- }
- var LOW_PRIORITY$3 = 500;
- /**
- * @class
- *
- * A plugin that adds an outline to shapes and connections that may be activated and styled
- * via CSS classes.
- *
- * @param {EventBus} eventBus
- * @param {Styles} styles
- * @param {ElementRegistry} elementRegistry
- */
- function Outline(eventBus, styles, elementRegistry) {
- this.offset = 6;
- var OUTLINE_STYLE = styles.cls('djs-outline', [ 'no-fill' ]);
- var self = this;
- function createOutline(gfx, bounds) {
- var outline = create$1('rect');
- attr$1(outline, assign({
- x: 10,
- y: 10,
- rx: 3,
- width: 100,
- height: 100
- }, OUTLINE_STYLE));
- append(gfx, outline);
- return outline;
- }
- // A low priortity is necessary, because outlines of labels have to be updated
- // after the label bounds have been updated in the renderer.
- eventBus.on([ 'shape.added', 'shape.changed' ], LOW_PRIORITY$3, function(event) {
- var element = event.element,
- gfx = event.gfx;
- var outline = query('.djs-outline', gfx);
- if (!outline) {
- outline = createOutline(gfx);
- }
- self.updateShapeOutline(outline, element);
- });
- eventBus.on([ 'connection.added', 'connection.changed' ], function(event) {
- var element = event.element,
- gfx = event.gfx;
- var outline = query('.djs-outline', gfx);
- if (!outline) {
- outline = createOutline(gfx);
- }
- self.updateConnectionOutline(outline, element);
- });
- }
- /**
- * Updates the outline of a shape respecting the dimension of the
- * element and an outline offset.
- *
- * @param {SVGElement} outline
- * @param {djs.model.Base} element
- */
- Outline.prototype.updateShapeOutline = function(outline, element) {
- attr$1(outline, {
- x: -this.offset,
- y: -this.offset,
- width: element.width + this.offset * 2,
- height: element.height + this.offset * 2
- });
- };
- /**
- * Updates the outline of a connection respecting the bounding box of
- * the connection and an outline offset.
- *
- * @param {SVGElement} outline
- * @param {djs.model.Base} element
- */
- Outline.prototype.updateConnectionOutline = function(outline, connection) {
- var bbox = getBBox(connection);
- attr$1(outline, {
- x: bbox.x - this.offset,
- y: bbox.y - this.offset,
- width: bbox.width + this.offset * 2,
- height: bbox.height + this.offset * 2
- });
- };
- Outline.$inject = [ 'eventBus', 'styles', 'elementRegistry' ];
- var OutlineModule = {
- __init__: [ 'outline' ],
- outline: [ 'type', Outline ]
- };
- /**
- * A service that offers the current selection in a diagram.
- * Offers the api to control the selection, too.
- *
- * @class
- *
- * @param {EventBus} eventBus the event bus
- */
- function Selection(eventBus, canvas) {
- this._eventBus = eventBus;
- this._canvas = canvas;
- this._selectedElements = [];
- var self = this;
- eventBus.on([ 'shape.remove', 'connection.remove' ], function(e) {
- var element = e.element;
- self.deselect(element);
- });
- eventBus.on([ 'diagram.clear', 'root.set' ], function(e) {
- self.select(null);
- });
- }
- Selection.$inject = [ 'eventBus', 'canvas' ];
- Selection.prototype.deselect = function(element) {
- var selectedElements = this._selectedElements;
- var idx = selectedElements.indexOf(element);
- if (idx !== -1) {
- var oldSelection = selectedElements.slice();
- selectedElements.splice(idx, 1);
- this._eventBus.fire('selection.changed', { oldSelection: oldSelection, newSelection: selectedElements });
- }
- };
- Selection.prototype.get = function() {
- return this._selectedElements;
- };
- Selection.prototype.isSelected = function(element) {
- return this._selectedElements.indexOf(element) !== -1;
- };
- /**
- * This method selects one or more elements on the diagram.
- *
- * By passing an additional add parameter you can decide whether or not the element(s)
- * should be added to the already existing selection or not.
- *
- * @method Selection#select
- *
- * @param {Object|Object[]} elements element or array of elements to be selected
- * @param {boolean} [add] whether the element(s) should be appended to the current selection, defaults to false
- */
- Selection.prototype.select = function(elements, add) {
- var selectedElements = this._selectedElements,
- oldSelection = selectedElements.slice();
- if (!isArray$2(elements)) {
- elements = elements ? [ elements ] : [];
- }
- var canvas = this._canvas;
- var rootElement = canvas.getRootElement();
- elements = elements.filter(function(element) {
- var elementRoot = canvas.findRoot(element);
- return rootElement === elementRoot;
- });
- // selection may be cleared by passing an empty array or null
- // to the method
- if (add) {
- forEach$1(elements, function(element) {
- if (selectedElements.indexOf(element) !== -1) {
- // already selected
- return;
- } else {
- selectedElements.push(element);
- }
- });
- } else {
- this._selectedElements = selectedElements = elements.slice();
- }
- this._eventBus.fire('selection.changed', { oldSelection: oldSelection, newSelection: selectedElements });
- };
- var MARKER_HOVER = 'hover',
- MARKER_SELECTED = 'selected';
- var SELECTION_OUTLINE_PADDING = 6;
- /**
- * A plugin that adds a visible selection UI to shapes and connections
- * by appending the <code>hover</code> and <code>selected</code> classes to them.
- *
- * @class
- *
- * Makes elements selectable, too.
- *
- * @param {Canvas} canvas
- * @param {EventBus} eventBus
- */
- function SelectionVisuals(canvas, eventBus, selection) {
- this._canvas = canvas;
- var self = this;
- this._multiSelectionBox = null;
- function addMarker(e, cls) {
- canvas.addMarker(e, cls);
- }
- function removeMarker(e, cls) {
- canvas.removeMarker(e, cls);
- }
- eventBus.on('element.hover', function(event) {
- addMarker(event.element, MARKER_HOVER);
- });
- eventBus.on('element.out', function(event) {
- removeMarker(event.element, MARKER_HOVER);
- });
- eventBus.on('selection.changed', function(event) {
- function deselect(s) {
- removeMarker(s, MARKER_SELECTED);
- }
- function select(s) {
- addMarker(s, MARKER_SELECTED);
- }
- var oldSelection = event.oldSelection,
- newSelection = event.newSelection;
- forEach$1(oldSelection, function(e) {
- if (newSelection.indexOf(e) === -1) {
- deselect(e);
- }
- });
- forEach$1(newSelection, function(e) {
- if (oldSelection.indexOf(e) === -1) {
- select(e);
- }
- });
- self._updateSelectionOutline(newSelection);
- });
- eventBus.on('element.changed', function(event) {
- if (selection.isSelected(event.element)) {
- self._updateSelectionOutline(selection.get());
- }
- });
- }
- SelectionVisuals.$inject = [
- 'canvas',
- 'eventBus',
- 'selection'
- ];
- SelectionVisuals.prototype._updateSelectionOutline = function(selection) {
- var layer = this._canvas.getLayer('selectionOutline');
- clear$1(layer);
- var enabled = selection.length > 1;
- var container = this._canvas.getContainer();
- classes$1(container)[enabled ? 'add' : 'remove']('djs-multi-select');
- if (!enabled) {
- return;
- }
- var bBox = addSelectionOutlinePadding(getBBox(selection));
- var rect = create$1('rect');
- attr$1(rect, assign({
- rx: 3
- }, bBox));
- classes$1(rect).add('djs-selection-outline');
- append(layer, rect);
- };
- // helpers //////////
- function addSelectionOutlinePadding(bBox) {
- return {
- x: bBox.x - SELECTION_OUTLINE_PADDING,
- y: bBox.y - SELECTION_OUTLINE_PADDING,
- width: bBox.width + SELECTION_OUTLINE_PADDING * 2,
- height: bBox.height + SELECTION_OUTLINE_PADDING * 2
- };
- }
- function SelectionBehavior(eventBus, selection, canvas, elementRegistry) {
- // Select elements on create
- eventBus.on('create.end', 500, function(event) {
- var context = event.context,
- canExecute = context.canExecute,
- elements = context.elements,
- hints = context.hints || {},
- autoSelect = hints.autoSelect;
- if (canExecute) {
- if (autoSelect === false) {
- // Select no elements
- return;
- }
- if (isArray$2(autoSelect)) {
- selection.select(autoSelect);
- } else {
- // Select all elements by default
- selection.select(elements.filter(isShown));
- }
- }
- });
- // Select connection targets on connect
- eventBus.on('connect.end', 500, function(event) {
- var context = event.context,
- connection = context.connection;
- if (connection) {
- selection.select(connection);
- }
- });
- // Select shapes on move
- eventBus.on('shape.move.end', 500, function(event) {
- var previousSelection = event.previousSelection || [];
- var shape = elementRegistry.get(event.context.shape.id);
- // Always select main shape on move
- var isSelected = find(previousSelection, function(selectedShape) {
- return shape.id === selectedShape.id;
- });
- if (!isSelected) {
- selection.select(shape);
- }
- });
- // Select elements on click
- eventBus.on('element.click', function(event) {
- if (!isPrimaryButton(event)) {
- return;
- }
- var element = event.element;
- if (element === canvas.getRootElement()) {
- element = null;
- }
- var isSelected = selection.isSelected(element),
- isMultiSelect = selection.get().length > 1;
- // Add to selection if CTRL or SHIFT pressed
- var add = hasPrimaryModifier(event) || hasSecondaryModifier(event);
- if (isSelected && isMultiSelect) {
- if (add) {
- // Deselect element
- return selection.deselect(element);
- } else {
- // Select element only
- return selection.select(element);
- }
- } else if (!isSelected) {
- // Select element
- selection.select(element, add);
- } else {
- // Deselect element
- selection.deselect(element);
- }
- });
- }
- SelectionBehavior.$inject = [
- 'eventBus',
- 'selection',
- 'canvas',
- 'elementRegistry'
- ];
- function isShown(element) {
- return !element.hidden;
- }
- var SelectionModule = {
- __init__: [ 'selectionVisuals', 'selectionBehavior' ],
- __depends__: [
- InteractionEventsModule,
- OutlineModule
- ],
- selection: [ 'type', Selection ],
- selectionVisuals: [ 'type', SelectionVisuals ],
- selectionBehavior: [ 'type', SelectionBehavior ]
- };
- /**
- * Util that provides unique IDs.
- *
- * @class djs.util.IdGenerator
- * @constructor
- * @memberOf djs.util
- *
- * The ids can be customized via a given prefix and contain a random value to avoid collisions.
- *
- * @param {string} prefix a prefix to prepend to generated ids (for better readability)
- */
- function IdGenerator(prefix) {
- this._counter = 0;
- this._prefix = (prefix ? prefix + '-' : '') + Math.floor(Math.random() * 1000000000) + '-';
- }
- /**
- * Returns a next unique ID.
- *
- * @method djs.util.IdGenerator#next
- *
- * @returns {string} the id
- */
- IdGenerator.prototype.next = function() {
- return this._prefix + (++this._counter);
- };
- // document wide unique overlay ids
- var ids = new IdGenerator('ov');
- var LOW_PRIORITY$2 = 500;
- /**
- * A service that allows users to attach overlays to diagram elements.
- *
- * The overlay service will take care of overlay positioning during updates.
- *
- * @example
- *
- * // add a pink badge on the top left of the shape
- * overlays.add(someShape, {
- * position: {
- * top: -5,
- * left: -5
- * },
- * html: '<div style="width: 10px; background: fuchsia; color: white;">0</div>'
- * });
- *
- * // or add via shape id
- *
- * overlays.add('some-element-id', {
- * position: {
- * top: -5,
- * left: -5
- * }
- * html: '<div style="width: 10px; background: fuchsia; color: white;">0</div>'
- * });
- *
- * // or add with optional type
- *
- * overlays.add(someShape, 'badge', {
- * position: {
- * top: -5,
- * left: -5
- * }
- * html: '<div style="width: 10px; background: fuchsia; color: white;">0</div>'
- * });
- *
- *
- * // remove an overlay
- *
- * var id = overlays.add(...);
- * overlays.remove(id);
- *
- *
- * You may configure overlay defaults during tool by providing a `config` module
- * with `overlays.defaults` as an entry:
- *
- * {
- * overlays: {
- * defaults: {
- * show: {
- * minZoom: 0.7,
- * maxZoom: 5.0
- * },
- * scale: {
- * min: 1
- * }
- * }
- * }
- *
- * @param {Object} config
- * @param {EventBus} eventBus
- * @param {Canvas} canvas
- * @param {ElementRegistry} elementRegistry
- */
- function Overlays(config, eventBus, canvas, elementRegistry) {
- this._eventBus = eventBus;
- this._canvas = canvas;
- this._elementRegistry = elementRegistry;
- this._ids = ids;
- this._overlayDefaults = assign({
- // no show constraints
- show: null,
- // always scale
- scale: true
- }, config && config.defaults);
- /**
- * Mapping overlayId -> overlay
- */
- this._overlays = {};
- /**
- * Mapping elementId -> overlay container
- */
- this._overlayContainers = [];
- // root html element for all overlays
- this._overlayRoot = createRoot(canvas.getContainer());
- this._init();
- }
- Overlays.$inject = [
- 'config.overlays',
- 'eventBus',
- 'canvas',
- 'elementRegistry'
- ];
- /**
- * Returns the overlay with the specified id or a list of overlays
- * for an element with a given type.
- *
- * @example
- *
- * // return the single overlay with the given id
- * overlays.get('some-id');
- *
- * // return all overlays for the shape
- * overlays.get({ element: someShape });
- *
- * // return all overlays on shape with type 'badge'
- * overlays.get({ element: someShape, type: 'badge' });
- *
- * // shape can also be specified as id
- * overlays.get({ element: 'element-id', type: 'badge' });
- *
- *
- * @param {Object} search
- * @param {string} [search.id]
- * @param {string|djs.model.Base} [search.element]
- * @param {string} [search.type]
- *
- * @return {Object|Array<Object>} the overlay(s)
- */
- Overlays.prototype.get = function(search) {
- if (isString(search)) {
- search = { id: search };
- }
- if (isString(search.element)) {
- search.element = this._elementRegistry.get(search.element);
- }
- if (search.element) {
- var container = this._getOverlayContainer(search.element, true);
- // return a list of overlays when searching by element (+type)
- if (container) {
- return search.type ? filter(container.overlays, matchPattern({ type: search.type })) : container.overlays.slice();
- } else {
- return [];
- }
- } else
- if (search.type) {
- return filter(this._overlays, matchPattern({ type: search.type }));
- } else {
- // return single element when searching by id
- return search.id ? this._overlays[search.id] : null;
- }
- };
- /**
- * Adds a HTML overlay to an element.
- *
- * @param {string|djs.model.Base} element attach overlay to this shape
- * @param {string} [type] optional type to assign to the overlay
- * @param {Object} overlay the overlay configuration
- *
- * @param {string|DOMElement} overlay.html html element to use as an overlay
- * @param {Object} [overlay.show] show configuration
- * @param {number} [overlay.show.minZoom] minimal zoom level to show the overlay
- * @param {number} [overlay.show.maxZoom] maximum zoom level to show the overlay
- * @param {Object} overlay.position where to attach the overlay
- * @param {number} [overlay.position.left] relative to element bbox left attachment
- * @param {number} [overlay.position.top] relative to element bbox top attachment
- * @param {number} [overlay.position.bottom] relative to element bbox bottom attachment
- * @param {number} [overlay.position.right] relative to element bbox right attachment
- * @param {boolean|Object} [overlay.scale=true] false to preserve the same size regardless of
- * diagram zoom
- * @param {number} [overlay.scale.min]
- * @param {number} [overlay.scale.max]
- *
- * @return {string} id that may be used to reference the overlay for update or removal
- */
- Overlays.prototype.add = function(element, type, overlay) {
- if (isObject(type)) {
- overlay = type;
- type = null;
- }
- if (!element.id) {
- element = this._elementRegistry.get(element);
- }
- if (!overlay.position) {
- throw new Error('must specifiy overlay position');
- }
- if (!overlay.html) {
- throw new Error('must specifiy overlay html');
- }
- if (!element) {
- throw new Error('invalid element specified');
- }
- var id = this._ids.next();
- overlay = assign({}, this._overlayDefaults, overlay, {
- id: id,
- type: type,
- element: element,
- html: overlay.html
- });
- this._addOverlay(overlay);
- return id;
- };
- /**
- * Remove an overlay with the given id or all overlays matching the given filter.
- *
- * @see Overlays#get for filter options.
- *
- * @param {string|object} [filter]
- */
- Overlays.prototype.remove = function(filter) {
- var overlays = this.get(filter) || [];
- if (!isArray$2(overlays)) {
- overlays = [ overlays ];
- }
- var self = this;
- forEach$1(overlays, function(overlay) {
- var container = self._getOverlayContainer(overlay.element, true);
- if (overlay) {
- remove$1(overlay.html);
- remove$1(overlay.htmlContainer);
- delete overlay.htmlContainer;
- delete overlay.element;
- delete self._overlays[overlay.id];
- }
- if (container) {
- var idx = container.overlays.indexOf(overlay);
- if (idx !== -1) {
- container.overlays.splice(idx, 1);
- }
- }
- });
- };
- Overlays.prototype.show = function() {
- setVisible(this._overlayRoot);
- };
- Overlays.prototype.hide = function() {
- setVisible(this._overlayRoot, false);
- };
- Overlays.prototype.clear = function() {
- this._overlays = {};
- this._overlayContainers = [];
- clear(this._overlayRoot);
- };
- Overlays.prototype._updateOverlayContainer = function(container) {
- var element = container.element,
- html = container.html;
- // update container left,top according to the elements x,y coordinates
- // this ensures we can attach child elements relative to this container
- var x = element.x,
- y = element.y;
- if (element.waypoints) {
- var bbox = getBBox(element);
- x = bbox.x;
- y = bbox.y;
- }
- setPosition(html, x, y);
- attr(container.html, 'data-container-id', element.id);
- };
- Overlays.prototype._updateOverlay = function(overlay) {
- var position = overlay.position,
- htmlContainer = overlay.htmlContainer,
- element = overlay.element;
- // update overlay html relative to shape because
- // it is already positioned on the element
- // update relative
- var left = position.left,
- top = position.top;
- if (position.right !== undefined) {
- var width;
- if (element.waypoints) {
- width = getBBox(element).width;
- } else {
- width = element.width;
- }
- left = position.right * -1 + width;
- }
- if (position.bottom !== undefined) {
- var height;
- if (element.waypoints) {
- height = getBBox(element).height;
- } else {
- height = element.height;
- }
- top = position.bottom * -1 + height;
- }
- setPosition(htmlContainer, left || 0, top || 0);
- this._updateOverlayVisibilty(overlay, this._canvas.viewbox());
- };
- Overlays.prototype._createOverlayContainer = function(element) {
- var html = domify('<div class="djs-overlays" />');
- assign$1(html, { position: 'absolute' });
- this._overlayRoot.appendChild(html);
- var container = {
- html: html,
- element: element,
- overlays: []
- };
- this._updateOverlayContainer(container);
- this._overlayContainers.push(container);
- return container;
- };
- Overlays.prototype._updateRoot = function(viewbox) {
- var scale = viewbox.scale || 1;
- var matrix = 'matrix(' +
- [
- scale,
- 0,
- 0,
- scale,
- -1 * viewbox.x * scale,
- -1 * viewbox.y * scale
- ].join(',') +
- ')';
- setTransform(this._overlayRoot, matrix);
- };
- Overlays.prototype._getOverlayContainer = function(element, raw) {
- var container = find(this._overlayContainers, function(c) {
- return c.element === element;
- });
- if (!container && !raw) {
- return this._createOverlayContainer(element);
- }
- return container;
- };
- Overlays.prototype._addOverlay = function(overlay) {
- var id = overlay.id,
- element = overlay.element,
- html = overlay.html,
- htmlContainer,
- overlayContainer;
- // unwrap jquery (for those who need it)
- if (html.get && html.constructor.prototype.jquery) {
- html = html.get(0);
- }
- // create proper html elements from
- // overlay HTML strings
- if (isString(html)) {
- html = domify(html);
- }
- overlayContainer = this._getOverlayContainer(element);
- htmlContainer = domify('<div class="djs-overlay" data-overlay-id="' + id + '">');
- assign$1(htmlContainer, { position: 'absolute' });
- htmlContainer.appendChild(html);
- if (overlay.type) {
- classes(htmlContainer).add('djs-overlay-' + overlay.type);
- }
- var elementRoot = this._canvas.findRoot(element);
- var activeRoot = this._canvas.getRootElement();
- setVisible(htmlContainer, elementRoot === activeRoot);
- overlay.htmlContainer = htmlContainer;
- overlayContainer.overlays.push(overlay);
- overlayContainer.html.appendChild(htmlContainer);
- this._overlays[id] = overlay;
- this._updateOverlay(overlay);
- this._updateOverlayVisibilty(overlay, this._canvas.viewbox());
- };
- Overlays.prototype._updateOverlayVisibilty = function(overlay, viewbox) {
- var show = overlay.show,
- rootElement = this._canvas.findRoot(overlay.element),
- minZoom = show && show.minZoom,
- maxZoom = show && show.maxZoom,
- htmlContainer = overlay.htmlContainer,
- activeRootElement = this._canvas.getRootElement(),
- visible = true;
- if (rootElement !== activeRootElement) {
- visible = false;
- } else if (show) {
- if (
- (isDefined(minZoom) && minZoom > viewbox.scale) ||
- (isDefined(maxZoom) && maxZoom < viewbox.scale)
- ) {
- visible = false;
- }
- }
- setVisible(htmlContainer, visible);
- this._updateOverlayScale(overlay, viewbox);
- };
- Overlays.prototype._updateOverlayScale = function(overlay, viewbox) {
- var shouldScale = overlay.scale,
- minScale,
- maxScale,
- htmlContainer = overlay.htmlContainer;
- var scale, transform = '';
- if (shouldScale !== true) {
- if (shouldScale === false) {
- minScale = 1;
- maxScale = 1;
- } else {
- minScale = shouldScale.min;
- maxScale = shouldScale.max;
- }
- if (isDefined(minScale) && viewbox.scale < minScale) {
- scale = (1 / viewbox.scale || 1) * minScale;
- }
- if (isDefined(maxScale) && viewbox.scale > maxScale) {
- scale = (1 / viewbox.scale || 1) * maxScale;
- }
- }
- if (isDefined(scale)) {
- transform = 'scale(' + scale + ',' + scale + ')';
- }
- setTransform(htmlContainer, transform);
- };
- Overlays.prototype._updateOverlaysVisibilty = function(viewbox) {
- var self = this;
- forEach$1(this._overlays, function(overlay) {
- self._updateOverlayVisibilty(overlay, viewbox);
- });
- };
- Overlays.prototype._init = function() {
- var eventBus = this._eventBus;
- var self = this;
- // scroll/zoom integration
- function updateViewbox(viewbox) {
- self._updateRoot(viewbox);
- self._updateOverlaysVisibilty(viewbox);
- self.show();
- }
- eventBus.on('canvas.viewbox.changing', function(event) {
- self.hide();
- });
- eventBus.on('canvas.viewbox.changed', function(event) {
- updateViewbox(event.viewbox);
- });
- // remove integration
- eventBus.on([ 'shape.remove', 'connection.remove' ], function(e) {
- var element = e.element;
- var overlays = self.get({ element: element });
- forEach$1(overlays, function(o) {
- self.remove(o.id);
- });
- var container = self._getOverlayContainer(element);
- if (container) {
- remove$1(container.html);
- var i = self._overlayContainers.indexOf(container);
- if (i !== -1) {
- self._overlayContainers.splice(i, 1);
- }
- }
- });
- // move integration
- eventBus.on('element.changed', LOW_PRIORITY$2, function(e) {
- var element = e.element;
- var container = self._getOverlayContainer(element, true);
- if (container) {
- forEach$1(container.overlays, function(overlay) {
- self._updateOverlay(overlay);
- });
- self._updateOverlayContainer(container);
- }
- });
- // marker integration, simply add them on the overlays as classes, too.
- eventBus.on('element.marker.update', function(e) {
- var container = self._getOverlayContainer(e.element, true);
- if (container) {
- classes(container.html)[e.add ? 'add' : 'remove'](e.marker);
- }
- });
- eventBus.on('root.set', function() {
- self._updateOverlaysVisibilty(self._canvas.viewbox());
- });
- // clear overlays with diagram
- eventBus.on('diagram.clear', this.clear, this);
- };
- // helpers /////////////////////////////
- function createRoot(parentNode) {
- var root = domify(
- '<div class="djs-overlay-container" />'
- );
- assign$1(root, {
- position: 'absolute',
- width: 0,
- height: 0
- });
- parentNode.insertBefore(root, parentNode.firstChild);
- return root;
- }
- function setPosition(el, x, y) {
- assign$1(el, { left: x + 'px', top: y + 'px' });
- }
- /**
- * Set element visible
- *
- * @param {DOMElement} el
- * @param {boolean} [visible=true]
- */
- function setVisible(el, visible) {
- el.style.display = visible === false ? 'none' : '';
- }
- function setTransform(el, transform) {
- el.style['transform-origin'] = 'top left';
- [ '', '-ms-', '-webkit-' ].forEach(function(prefix) {
- el.style[prefix + 'transform'] = transform;
- });
- }
- var OverlaysModule = {
- __init__: [ 'overlays' ],
- overlays: [ 'type', Overlays ]
- };
- /**
- * Adds change support to the diagram, including
- *
- * <ul>
- * <li>redrawing shapes and connections on change</li>
- * </ul>
- *
- * @param {EventBus} eventBus
- * @param {Canvas} canvas
- * @param {ElementRegistry} elementRegistry
- * @param {GraphicsFactory} graphicsFactory
- */
- function ChangeSupport(
- eventBus, canvas, elementRegistry,
- graphicsFactory) {
- // redraw shapes / connections on change
- eventBus.on('element.changed', function(event) {
- var element = event.element;
- // element might have been deleted and replaced by new element with same ID
- // thus check for parent of element except for root element
- if (element.parent || element === canvas.getRootElement()) {
- event.gfx = elementRegistry.getGraphics(element);
- }
- // shape + gfx may have been deleted
- if (!event.gfx) {
- return;
- }
- eventBus.fire(getType(element) + '.changed', event);
- });
- eventBus.on('elements.changed', function(event) {
- var elements = event.elements;
- elements.forEach(function(e) {
- eventBus.fire('element.changed', { element: e });
- });
- graphicsFactory.updateContainments(elements);
- });
- eventBus.on('shape.changed', function(event) {
- graphicsFactory.update('shape', event.element, event.gfx);
- });
- eventBus.on('connection.changed', function(event) {
- graphicsFactory.update('connection', event.element, event.gfx);
- });
- }
- ChangeSupport.$inject = [
- 'eventBus',
- 'canvas',
- 'elementRegistry',
- 'graphicsFactory'
- ];
- var ChangeSupportModule = {
- __init__: [ 'changeSupport' ],
- changeSupport: [ 'type', ChangeSupport ]
- };
- var DEFAULT_PRIORITY$2 = 1000;
- /**
- * A utility that can be used to plug-in into the command execution for
- * extension and/or validation.
- *
- * @param {EventBus} eventBus
- *
- * @example
- *
- * import inherits from 'inherits-browser';
- *
- * import CommandInterceptor from 'diagram-js/lib/command/CommandInterceptor';
- *
- * function CommandLogger(eventBus) {
- * CommandInterceptor.call(this, eventBus);
- *
- * this.preExecute(function(event) {
- * console.log('command pre-execute', event);
- * });
- * }
- *
- * inherits(CommandLogger, CommandInterceptor);
- *
- */
- function CommandInterceptor(eventBus) {
- this._eventBus = eventBus;
- }
- CommandInterceptor.$inject = [ 'eventBus' ];
- function unwrapEvent(fn, that) {
- return function(event) {
- return fn.call(that || null, event.context, event.command, event);
- };
- }
- /**
- * Register an interceptor for a command execution
- *
- * @param {string|Array<string>} [events] list of commands to register on
- * @param {string} [hook] command hook, i.e. preExecute, executed to listen on
- * @param {number} [priority] the priority on which to hook into the execution
- * @param {Function} handlerFn interceptor to be invoked with (event)
- * @param {boolean} unwrap if true, unwrap the event and pass (context, command, event) to the
- * listener instead
- * @param {Object} [that] Pass context (`this`) to the handler function
- */
- CommandInterceptor.prototype.on = function(events, hook, priority, handlerFn, unwrap, that) {
- if (isFunction(hook) || isNumber(hook)) {
- that = unwrap;
- unwrap = handlerFn;
- handlerFn = priority;
- priority = hook;
- hook = null;
- }
- if (isFunction(priority)) {
- that = unwrap;
- unwrap = handlerFn;
- handlerFn = priority;
- priority = DEFAULT_PRIORITY$2;
- }
- if (isObject(unwrap)) {
- that = unwrap;
- unwrap = false;
- }
- if (!isFunction(handlerFn)) {
- throw new Error('handlerFn must be a function');
- }
- if (!isArray$2(events)) {
- events = [ events ];
- }
- var eventBus = this._eventBus;
- forEach$1(events, function(event) {
- // concat commandStack(.event)?(.hook)?
- var fullEvent = [ 'commandStack', event, hook ].filter(function(e) { return e; }).join('.');
- eventBus.on(fullEvent, priority, unwrap ? unwrapEvent(handlerFn, that) : handlerFn, that);
- });
- };
- var hooks = [
- 'canExecute',
- 'preExecute',
- 'preExecuted',
- 'execute',
- 'executed',
- 'postExecute',
- 'postExecuted',
- 'revert',
- 'reverted'
- ];
- /*
- * Install hook shortcuts
- *
- * This will generate the CommandInterceptor#(preExecute|...|reverted) methods
- * which will in term forward to CommandInterceptor#on.
- */
- forEach$1(hooks, function(hook) {
- /**
- * {canExecute|preExecute|preExecuted|execute|executed|postExecute|postExecuted|revert|reverted}
- *
- * A named hook for plugging into the command execution
- *
- * @param {string|Array<string>} [events] list of commands to register on
- * @param {number} [priority] the priority on which to hook into the execution
- * @param {Function} handlerFn interceptor to be invoked with (event)
- * @param {boolean} [unwrap=false] if true, unwrap the event and pass (context, command, event) to the
- * listener instead
- * @param {Object} [that] Pass context (`this`) to the handler function
- */
- CommandInterceptor.prototype[hook] = function(events, priority, handlerFn, unwrap, that) {
- if (isFunction(events) || isNumber(events)) {
- that = unwrap;
- unwrap = handlerFn;
- handlerFn = priority;
- priority = events;
- events = null;
- }
- this.on(events, hook, priority, handlerFn, unwrap, that);
- };
- });
- /**
- * A modeling behavior that ensures we set the correct root element
- * as we undo and redo commands.
- *
- * @param {Canvas} canvas
- * @param {didi.Injector} injector
- */
- function RootElementsBehavior(canvas, injector) {
- injector.invoke(CommandInterceptor, this);
- this.executed(function(event) {
- var context = event.context;
- if (context.rootElement) {
- canvas.setRootElement(context.rootElement);
- } else {
- context.rootElement = canvas.getRootElement();
- }
- });
- this.revert(function(event) {
- var context = event.context;
- if (context.rootElement) {
- canvas.setRootElement(context.rootElement);
- }
- });
- }
- e(RootElementsBehavior, CommandInterceptor);
- RootElementsBehavior.$inject = [ 'canvas', 'injector' ];
- var RootElementsModule = {
- __init__: [ 'rootElementsBehavior' ],
- rootElementsBehavior: [ 'type', RootElementsBehavior ]
- };
- var css_escape = {exports: {}};
- /*! https://mths.be/cssescape v1.5.1 by @mathias | MIT license */
- (function (module, exports) {
- (function(root, factory) {
- // https://github.com/umdjs/umd/blob/master/returnExports.js
- {
- // For Node.js.
- module.exports = factory(root);
- }
- }(typeof commonjsGlobal != 'undefined' ? commonjsGlobal : commonjsGlobal, function(root) {
- if (root.CSS && root.CSS.escape) {
- return root.CSS.escape;
- }
- // https://drafts.csswg.org/cssom/#serialize-an-identifier
- var cssEscape = function(value) {
- if (arguments.length == 0) {
- throw new TypeError('`CSS.escape` requires an argument.');
- }
- var string = String(value);
- var length = string.length;
- var index = -1;
- var codeUnit;
- var result = '';
- var firstCodeUnit = string.charCodeAt(0);
- while (++index < length) {
- codeUnit = string.charCodeAt(index);
- // Note: there’s no need to special-case astral symbols, surrogate
- // pairs, or lone surrogates.
- // If the character is NULL (U+0000), then the REPLACEMENT CHARACTER
- // (U+FFFD).
- if (codeUnit == 0x0000) {
- result += '\uFFFD';
- continue;
- }
- if (
- // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is
- // U+007F, […]
- (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F ||
- // If the character is the first character and is in the range [0-9]
- // (U+0030 to U+0039), […]
- (index == 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) ||
- // If the character is the second character and is in the range [0-9]
- // (U+0030 to U+0039) and the first character is a `-` (U+002D), […]
- (
- index == 1 &&
- codeUnit >= 0x0030 && codeUnit <= 0x0039 &&
- firstCodeUnit == 0x002D
- )
- ) {
- // https://drafts.csswg.org/cssom/#escape-a-character-as-code-point
- result += '\\' + codeUnit.toString(16) + ' ';
- continue;
- }
- if (
- // If the character is the first character and is a `-` (U+002D), and
- // there is no second character, […]
- index == 0 &&
- length == 1 &&
- codeUnit == 0x002D
- ) {
- result += '\\' + string.charAt(index);
- continue;
- }
- // If the character is not handled by one of the above rules and is
- // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or
- // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to
- // U+005A), or [a-z] (U+0061 to U+007A), […]
- if (
- codeUnit >= 0x0080 ||
- codeUnit == 0x002D ||
- codeUnit == 0x005F ||
- codeUnit >= 0x0030 && codeUnit <= 0x0039 ||
- codeUnit >= 0x0041 && codeUnit <= 0x005A ||
- codeUnit >= 0x0061 && codeUnit <= 0x007A
- ) {
- // the character itself
- result += string.charAt(index);
- continue;
- }
- // Otherwise, the escaped character.
- // https://drafts.csswg.org/cssom/#escape-a-character
- result += '\\' + string.charAt(index);
- }
- return result;
- };
- if (!root.CSS) {
- root.CSS = {};
- }
- root.CSS.escape = cssEscape;
- return cssEscape;
- }));
- }(css_escape));
- var HTML_ESCAPE_MAP = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- '\'': '''
- };
- function escapeHTML(str) {
- str = '' + str;
- return str && str.replace(/[&<>"']/g, function(match) {
- return HTML_ESCAPE_MAP[match];
- });
- }
- var planeSuffix = '_plane';
- /**
- * Get plane ID for a primary shape.
- *
- * @param {djs.model.Base|ModdleElement} element
- *
- * @returns {String}
- */
- function getPlaneIdFromShape(element) {
- var id = element.id;
- if (is$1(element, 'bpmn:SubProcess')) {
- return addPlaneSuffix(id);
- }
- return id;
- }
- function addPlaneSuffix(id) {
- return id + planeSuffix;
- }
- var OPEN_CLASS = 'bjs-breadcrumbs-shown';
- /**
- * Adds overlays that allow switching planes on collapsed subprocesses.
- *
- * @param {eventBus} eventBus
- * @param {elementRegistry} elementRegistry
- * @param {overlays} overlays
- * @param {canvas} canvas
- */
- function DrilldownBreadcrumbs(eventBus, elementRegistry, overlays, canvas) {
- var breadcrumbs = domify('<ul class="bjs-breadcrumbs"></ul>');
- var container = canvas.getContainer();
- var containerClasses = classes(container);
- container.appendChild(breadcrumbs);
- var boParents = [];
- // update breadcrumbs if name or ID of the primary shape changes
- eventBus.on('element.changed', function(e) {
- var shape = e.element,
- bo = getBusinessObject(shape);
- var isPresent = find(boParents, function(el) {
- return el === bo;
- });
- if (!isPresent) {
- return;
- }
- updateBreadcrumbs();
- });
- /**
- * Updates the displayed breadcrumbs. If no element is provided, only the
- * labels are updated.
- *
- * @param {djs.model.Base} [element]
- */
- function updateBreadcrumbs(element) {
- if (element) {
- boParents = getBoParentChain(element);
- }
- var path = boParents.map(function(parent) {
- var title = escapeHTML(parent.name || parent.id);
- var link = domify('<li><span class="bjs-crumb"><a title="' + title + '">' + title + '</a></span></li>');
- var parentPlane = canvas.findRoot(getPlaneIdFromShape(parent)) || canvas.findRoot(parent.id);
- // when the root is a collaboration, the process does not have a corresponding
- // element in the elementRegisty. Instead, we search for the corresponding participant
- if (!parentPlane && is$1(parent, 'bpmn:Process')) {
- var participant = elementRegistry.find(function(element) {
- var bo = getBusinessObject(element);
- return bo && bo.processRef && bo.processRef === parent;
- });
- parentPlane = canvas.findRoot(participant.id);
- }
- link.addEventListener('click', function() {
- canvas.setRootElement(parentPlane);
- });
- return link;
- });
- breadcrumbs.innerHTML = '';
- // show breadcrumbs and expose state to .djs-container
- var visible = path.length > 1;
- containerClasses.toggle(OPEN_CLASS, visible);
- path.forEach(function(el) {
- breadcrumbs.appendChild(el);
- });
- }
- eventBus.on('root.set', function(event) {
- updateBreadcrumbs(event.element);
- });
- }
- DrilldownBreadcrumbs.$inject = [ 'eventBus', 'elementRegistry', 'overlays', 'canvas' ];
- // helpers //////////
- /**
- * Returns the parents for the element using the business object chain,
- * starting with the root element.
- *
- * @param {djs.model.Shape} child
- *
- * @returns {Array<djs.model.Shape>} parents
- */
- function getBoParentChain(child) {
- var bo = getBusinessObject(child);
- var parents = [];
- for (var element = bo; element; element = element.$parent) {
- if (is$1(element, 'bpmn:SubProcess') || is$1(element, 'bpmn:Process')) {
- parents.push(element);
- }
- }
- return parents.reverse();
- }
- /**
- * Move collapsed subprocesses into view when drilling down.
- *
- * Zoom and scroll are saved in a session.
- *
- * @param {eventBus} eventBus
- * @param {canvas} canvas
- */
- function DrilldownCentering(eventBus, canvas) {
- var currentRoot = null;
- var positionMap = new Map();
- eventBus.on('root.set', function(event) {
- var newRoot = event.element;
- var currentViewbox = canvas.viewbox();
- var storedViewbox = positionMap.get(newRoot);
- positionMap.set(currentRoot, {
- x: currentViewbox.x,
- y: currentViewbox.y,
- zoom: currentViewbox.scale
- });
- currentRoot = newRoot;
- // current root was replaced with a collaboration, we don't update the viewbox
- if (is$1(newRoot, 'bpmn:Collaboration') && !storedViewbox) {
- return;
- }
- storedViewbox = storedViewbox || { x: 0, y: 0, zoom: 1 };
- var dx = (currentViewbox.x - storedViewbox.x) * currentViewbox.scale,
- dy = (currentViewbox.y - storedViewbox.y) * currentViewbox.scale;
- if (dx !== 0 || dy !== 0) {
- canvas.scroll({
- dx: dx,
- dy: dy
- });
- }
- if (storedViewbox.zoom !== currentViewbox.scale) {
- canvas.zoom(storedViewbox.zoom, { x: 0, y: 0 });
- }
- });
- eventBus.on('diagram.clear', function() {
- positionMap.clear();
- currentRoot = null;
- });
- }
- DrilldownCentering.$inject = [ 'eventBus', 'canvas' ];
- /**
- * ES5 Map implementation. Works.
- */
- function Map() {
- this._entries = [];
- this.set = function(key, value) {
- var found = false;
- for (var k in this._entries) {
- if (this._entries[k][0] === key) {
- this._entries[k][1] = value;
- found = true;
- break;
- }
- }
- if (!found) {
- this._entries.push([ key, value ]);
- }
- };
- this.get = function(key) {
- for (var k in this._entries) {
- if (this._entries[k][0] === key) {
- return this._entries[k][1];
- }
- }
- return null;
- };
- this.clear = function() {
- this._entries.length = 0;
- };
- this.remove = function(key) {
- var idx = -1;
- for (var k in this._entries) {
- if (this._entries[k][0] === key) {
- idx = k;
- break;
- }
- }
- if (idx !== -1) {
- this._entries.splice(idx, 1);
- }
- };
- }
- var DEFAULT_POSITION = {
- x: 180,
- y: 160
- };
- /**
- * Hook into `import.render.start` and create new planes for diagrams with
- * collapsed subprocesses and all dis on the same plane.
- *
- * @param {eventBus} eventBus
- * @param {moddle} moddle
- */
- function SubprocessCompatibility(eventBus, moddle) {
- this._eventBus = eventBus;
- this._moddle = moddle;
- var self = this;
- eventBus.on('import.render.start', 1500, function(e, context) {
- self.handleImport(context.definitions);
- });
- }
- SubprocessCompatibility.prototype.handleImport = function(definitions) {
- if (!definitions.diagrams) {
- return;
- }
- var self = this;
- this._definitions = definitions;
- this._processToDiagramMap = {};
- definitions.diagrams.forEach(function(diagram) {
- if (!diagram.plane || !diagram.plane.bpmnElement) {
- return;
- }
- self._processToDiagramMap[diagram.plane.bpmnElement.id] = diagram;
- });
- var newDiagrams = [];
- definitions.diagrams.forEach(function(diagram) {
- var createdDiagrams = self.createNewDiagrams(diagram.plane);
- Array.prototype.push.apply(newDiagrams, createdDiagrams);
- });
- newDiagrams.forEach(function(diagram) {
- self.movePlaneElementsToOrigin(diagram.plane);
- });
- };
- /**
- * Moves all DI elements from collapsed subprocesses to a new plane.
- *
- * @param {Object} plane
- * @return {Array} new diagrams created for the collapsed subprocesses
- */
- SubprocessCompatibility.prototype.createNewDiagrams = function(plane) {
- var self = this;
- var collapsedElements = [];
- var elementsToMove = [];
- plane.get('planeElement').forEach(function(diElement) {
- var bo = diElement.bpmnElement;
- if (!bo) {
- return;
- }
- var parent = bo.$parent;
- if (is$1(bo, 'bpmn:SubProcess') && !diElement.isExpanded) {
- collapsedElements.push(bo);
- }
- if (shouldMoveToPlane(bo, plane)) {
- // don't change the array while we iterate over it
- elementsToMove.push({ diElement: diElement, parent: parent });
- }
- });
- var newDiagrams = [];
- // create new planes for all collapsed subprocesses, even when they are empty
- collapsedElements.forEach(function(element) {
- if (!self._processToDiagramMap[element.id]) {
- var diagram = self.createDiagram(element);
- self._processToDiagramMap[element.id] = diagram;
- newDiagrams.push(diagram);
- }
- });
- elementsToMove.forEach(function(element) {
- var diElement = element.diElement;
- var parent = element.parent;
- // parent is expanded, get nearest collapsed parent
- while (parent && collapsedElements.indexOf(parent) === -1) {
- parent = parent.$parent;
- }
- // false positive, all parents are expanded
- if (!parent) {
- return;
- }
- var diagram = self._processToDiagramMap[parent.id];
- self.moveToDiPlane(diElement, diagram.plane);
- });
- return newDiagrams;
- };
- SubprocessCompatibility.prototype.movePlaneElementsToOrigin = function(plane) {
- var elements = plane.get('planeElement');
- // get bounding box of all elements
- var planeBounds = getPlaneBounds(plane);
- var offset = {
- x: planeBounds.x - DEFAULT_POSITION.x,
- y: planeBounds.y - DEFAULT_POSITION.y
- };
- elements.forEach(function(diElement) {
- if (diElement.waypoint) {
- diElement.waypoint.forEach(function(waypoint) {
- waypoint.x = waypoint.x - offset.x;
- waypoint.y = waypoint.y - offset.y;
- });
- } else if (diElement.bounds) {
- diElement.bounds.x = diElement.bounds.x - offset.x;
- diElement.bounds.y = diElement.bounds.y - offset.y;
- }
- });
- };
- SubprocessCompatibility.prototype.moveToDiPlane = function(diElement, newPlane) {
- var containingDiagram = findRootDiagram(diElement);
- // remove DI from old Plane and add it to the new one
- var parentPlaneElement = containingDiagram.plane.get('planeElement');
- parentPlaneElement.splice(parentPlaneElement.indexOf(diElement), 1);
- newPlane.get('planeElement').push(diElement);
- };
- SubprocessCompatibility.prototype.createDiagram = function(bo) {
- var plane = this._moddle.create('bpmndi:BPMNPlane', { bpmnElement: bo });
- var diagram = this._moddle.create('bpmndi:BPMNDiagram', {
- plane: plane
- });
- plane.$parent = diagram;
- plane.bpmnElement = bo;
- diagram.$parent = this._definitions;
- this._definitions.diagrams.push(diagram);
- return diagram;
- };
- SubprocessCompatibility.$inject = [ 'eventBus', 'moddle' ];
- // helpers //////////////////////////
- function findRootDiagram(element) {
- if (is$1(element, 'bpmndi:BPMNDiagram')) {
- return element;
- } else {
- return findRootDiagram(element.$parent);
- }
- }
- function getPlaneBounds(plane) {
- var planeTrbl = {
- top: Infinity,
- right: -Infinity,
- bottom: -Infinity,
- left: Infinity
- };
- plane.planeElement.forEach(function(element) {
- if (!element.bounds) {
- return;
- }
- var trbl = asTRBL(element.bounds);
- planeTrbl.top = Math.min(trbl.top, planeTrbl.top);
- planeTrbl.left = Math.min(trbl.left, planeTrbl.left);
- });
- return asBounds(planeTrbl);
- }
- function shouldMoveToPlane(bo, plane) {
- var parent = bo.$parent;
- // don't move elements that are already on the plane
- if (!is$1(parent, 'bpmn:SubProcess') || parent === plane.bpmnElement) {
- return false;
- }
- // dataAssociations are children of the subprocess but rendered on process level
- // cf. https://github.com/bpmn-io/bpmn-js/issues/1619
- if (isAny(bo, ['bpmn:DataInputAssociation', 'bpmn:DataOutputAssociation'])) {
- return false;
- }
- return true;
- }
- var LOW_PRIORITY$1 = 250;
- var ARROW_DOWN_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M4.81801948,3.50735931 L10.4996894,9.1896894 L10.5,4 L12,4 L12,12 L4,12 L4,10.5 L9.6896894,10.4996894 L3.75735931,4.56801948 C3.46446609,4.27512627 3.46446609,3.80025253 3.75735931,3.50735931 C4.05025253,3.21446609 4.52512627,3.21446609 4.81801948,3.50735931 Z"/></svg>';
- var EMPTY_MARKER = 'bjs-drilldown-empty';
- function DrilldownOverlayBehavior(
- canvas, eventBus, elementRegistry, overlays
- ) {
- CommandInterceptor.call(this, eventBus);
- this._canvas = canvas;
- this._eventBus = eventBus;
- this._elementRegistry = elementRegistry;
- this._overlays = overlays;
- var self = this;
- this.executed('shape.toggleCollapse', LOW_PRIORITY$1, function(context) {
- var shape = context.shape;
- // Add overlay to the collapsed shape
- if (self.canDrillDown(shape)) {
- self.addOverlay(shape);
- } else {
- self.removeOverlay(shape);
- }
- }, true);
- this.reverted('shape.toggleCollapse', LOW_PRIORITY$1, function(context) {
- var shape = context.shape;
- // Add overlay to the collapsed shape
- if (self.canDrillDown(shape)) {
- self.addOverlay(shape);
- } else {
- self.removeOverlay(shape);
- }
- }, true);
- this.executed(['shape.create', 'shape.move', 'shape.delete'], LOW_PRIORITY$1,
- function(context) {
- var oldParent = context.oldParent,
- newParent = context.newParent || context.parent,
- shape = context.shape;
- // Add overlay to the collapsed shape
- if (self.canDrillDown(shape)) {
- self.addOverlay(shape);
- }
- self.updateDrilldownOverlay(oldParent);
- self.updateDrilldownOverlay(newParent);
- self.updateDrilldownOverlay(shape);
- }, true);
- this.reverted(['shape.create', 'shape.move', 'shape.delete'], LOW_PRIORITY$1,
- function(context) {
- var oldParent = context.oldParent,
- newParent = context.newParent || context.parent,
- shape = context.shape;
- // Add overlay to the collapsed shape
- if (self.canDrillDown(shape)) {
- self.addOverlay(shape);
- }
- self.updateDrilldownOverlay(oldParent);
- self.updateDrilldownOverlay(newParent);
- self.updateDrilldownOverlay(shape);
- }, true);
- eventBus.on('import.render.complete', function() {
- elementRegistry.filter(function(e) {
- return self.canDrillDown(e);
- }).map(function(el) {
- self.addOverlay(el);
- });
- });
- }
- e(DrilldownOverlayBehavior, CommandInterceptor);
- DrilldownOverlayBehavior.prototype.updateDrilldownOverlay = function(shape) {
- var canvas = this._canvas;
- if (!shape) {
- return;
- }
- var root = canvas.findRoot(shape);
- if (root) {
- this.updateOverlayVisibility(root);
- }
- };
- DrilldownOverlayBehavior.prototype.canDrillDown = function(element) {
- var canvas = this._canvas;
- return is$1(element, 'bpmn:SubProcess') && canvas.findRoot(getPlaneIdFromShape(element));
- };
- /**
- * Updates visibility of the drilldown overlay. If the plane has no elements,
- * the drilldown will be only shown when the element is selected.
- *
- * @param {djs.model.Shape|djs.model.Root} element collapsed shape or root element
- */
- DrilldownOverlayBehavior.prototype.updateOverlayVisibility = function(element) {
- var overlays = this._overlays;
- var bo = element.businessObject;
- var overlay = overlays.get({ element: bo.id, type: 'drilldown' })[0];
- if (!overlay) {
- return;
- }
- var hasContent = bo && bo.flowElements && bo.flowElements.length;
- classes(overlay.html).toggle(EMPTY_MARKER, !hasContent);
- };
- /**
- * Attaches a drilldown button to the given element. We assume that the plane has
- * the same id as the element.
- *
- * @param {djs.model.Shape} element collapsed shape
- */
- DrilldownOverlayBehavior.prototype.addOverlay = function(element) {
- var canvas = this._canvas;
- var overlays = this._overlays;
- var existingOverlays = overlays.get({ element: element, type: 'drilldown' });
- if (existingOverlays.length) {
- this.removeOverlay(element);
- }
- var button = domify('<button class="bjs-drilldown">' + ARROW_DOWN_SVG + '</button>');
- button.addEventListener('click', function() {
- canvas.setRootElement(canvas.findRoot(getPlaneIdFromShape(element)));
- });
- overlays.add(element, 'drilldown', {
- position: {
- bottom: -7,
- right: -8
- },
- html: button
- });
- this.updateOverlayVisibility(element);
- };
- DrilldownOverlayBehavior.prototype.removeOverlay = function(element) {
- var overlays = this._overlays;
- overlays.remove({
- element: element,
- type: 'drilldown'
- });
- };
- DrilldownOverlayBehavior.$inject = [
- 'canvas',
- 'eventBus',
- 'elementRegistry',
- 'overlays'
- ];
- var DrilldownModdule = {
- __depends__: [ OverlaysModule, ChangeSupportModule, RootElementsModule ],
- __init__: [ 'drilldownBreadcrumbs', 'drilldownOverlayBehavior', 'drilldownCentering', 'subprocessCompatibility'],
- drilldownBreadcrumbs: [ 'type', DrilldownBreadcrumbs ],
- drilldownCentering: [ 'type', DrilldownCentering ],
- drilldownOverlayBehavior: [ 'type', DrilldownOverlayBehavior ],
- subprocessCompatibility: [ 'type', SubprocessCompatibility ]
- };
- var CLASS_PATTERN = /^class /;
- /**
- * @param {function} fn
- *
- * @return {boolean}
- */
- function isClass(fn) {
- return CLASS_PATTERN.test(fn.toString());
- }
- /**
- * @param {any} obj
- *
- * @return {boolean}
- */
- function isArray(obj) {
- return Object.prototype.toString.call(obj) === '[object Array]';
- }
- /**
- * @param {any} obj
- * @param {string} prop
- *
- * @return {boolean}
- */
- function hasOwnProp(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- /**
- * @typedef {import('./index').InjectAnnotated } InjectAnnotated
- */
- /**
- * @template T
- *
- * @params {[...string[], T] | ...string[], T} args
- *
- * @return {T & InjectAnnotated}
- */
- function annotate() {
- var args = Array.prototype.slice.call(arguments);
- if (args.length === 1 && isArray(args[0])) {
- args = args[0];
- }
- var fn = args.pop();
- fn.$inject = args;
- return fn;
- }
- // Current limitations:
- // - can't put into "function arg" comments
- // function /* (no parenthesis like this) */ (){}
- // function abc( /* xx (no parenthesis like this) */ a, b) {}
- //
- // Just put the comment before function or inside:
- // /* (((this is fine))) */ function(a, b) {}
- // function abc(a) { /* (((this is fine))) */}
- //
- // - can't reliably auto-annotate constructor; we'll match the
- // first constructor(...) pattern found which may be the one
- // of a nested class, too.
- var CONSTRUCTOR_ARGS = /constructor\s*[^(]*\(\s*([^)]*)\)/m;
- var FN_ARGS = /^(?:async\s+)?(?:function\s*[^(]*)?(?:\(\s*([^)]*)\)|(\w+))/m;
- var FN_ARG = /\/\*([^*]*)\*\//m;
- /**
- * @param {unknown} fn
- *
- * @return {string[]}
- */
- function parseAnnotations(fn) {
- if (typeof fn !== 'function') {
- throw new Error('Cannot annotate "' + fn + '". Expected a function!');
- }
- var match = fn.toString().match(isClass(fn) ? CONSTRUCTOR_ARGS : FN_ARGS);
- // may parse class without constructor
- if (!match) {
- return [];
- }
- var args = match[1] || match[2];
- return args && args.split(',').map(function(arg) {
- var argMatch = arg.match(FN_ARG);
- return (argMatch && argMatch[1] || arg).trim();
- }) || [];
- }
- /**
- * @typedef { import('./index').ModuleDeclaration } ModuleDeclaration
- * @typedef { import('./index').ModuleDefinition } ModuleDefinition
- * @typedef { import('./index').InjectorContext } InjectorContext
- */
- /**
- * Create a new injector with the given modules.
- *
- * @param {ModuleDefinition[]} modules
- * @param {InjectorContext} [parent]
- */
- function Injector(modules, parent) {
- parent = parent || {
- get: function(name, strict) {
- currentlyResolving.push(name);
- if (strict === false) {
- return null;
- } else {
- throw error('No provider for "' + name + '"!');
- }
- }
- };
- var currentlyResolving = [];
- var providers = this._providers = Object.create(parent._providers || null);
- var instances = this._instances = Object.create(null);
- var self = instances.injector = this;
- var error = function(msg) {
- var stack = currentlyResolving.join(' -> ');
- currentlyResolving.length = 0;
- return new Error(stack ? msg + ' (Resolving: ' + stack + ')' : msg);
- };
- /**
- * Return a named service.
- *
- * @param {string} name
- * @param {boolean} [strict=true] if false, resolve missing services to null
- *
- * @return {any}
- */
- function get(name, strict) {
- if (!providers[name] && name.indexOf('.') !== -1) {
- var parts = name.split('.');
- var pivot = get(parts.shift());
- while (parts.length) {
- pivot = pivot[parts.shift()];
- }
- return pivot;
- }
- if (hasOwnProp(instances, name)) {
- return instances[name];
- }
- if (hasOwnProp(providers, name)) {
- if (currentlyResolving.indexOf(name) !== -1) {
- currentlyResolving.push(name);
- throw error('Cannot resolve circular dependency!');
- }
- currentlyResolving.push(name);
- instances[name] = providers[name][0](providers[name][1]);
- currentlyResolving.pop();
- return instances[name];
- }
- return parent.get(name, strict);
- }
- function fnDef(fn, locals) {
- if (typeof locals === 'undefined') {
- locals = {};
- }
- if (typeof fn !== 'function') {
- if (isArray(fn)) {
- fn = annotate(fn.slice());
- } else {
- throw new Error('Cannot invoke "' + fn + '". Expected a function!');
- }
- }
- var inject = fn.$inject || parseAnnotations(fn);
- var dependencies = inject.map(function(dep) {
- if (hasOwnProp(locals, dep)) {
- return locals[dep];
- } else {
- return get(dep);
- }
- });
- return {
- fn: fn,
- dependencies: dependencies
- };
- }
- function instantiate(Type) {
- var def = fnDef(Type);
- var fn = def.fn,
- dependencies = def.dependencies;
- // instantiate var args constructor
- var Constructor = Function.prototype.bind.apply(fn, [ null ].concat(dependencies));
- return new Constructor();
- }
- function invoke(func, context, locals) {
- var def = fnDef(func, locals);
- var fn = def.fn,
- dependencies = def.dependencies;
- return fn.apply(context, dependencies);
- }
- /**
- * @param {Injector} childInjector
- *
- * @return {Function}
- */
- function createPrivateInjectorFactory(childInjector) {
- return annotate(function(key) {
- return childInjector.get(key);
- });
- }
- /**
- * @param {ModuleDefinition[]} modules
- * @param {string[]} [forceNewInstances]
- *
- * @return {Injector}
- */
- function createChild(modules, forceNewInstances) {
- if (forceNewInstances && forceNewInstances.length) {
- var fromParentModule = Object.create(null);
- var matchedScopes = Object.create(null);
- var privateInjectorsCache = [];
- var privateChildInjectors = [];
- var privateChildFactories = [];
- var provider;
- var cacheIdx;
- var privateChildInjector;
- var privateChildInjectorFactory;
- for (var name in providers) {
- provider = providers[name];
- if (forceNewInstances.indexOf(name) !== -1) {
- if (provider[2] === 'private') {
- cacheIdx = privateInjectorsCache.indexOf(provider[3]);
- if (cacheIdx === -1) {
- privateChildInjector = provider[3].createChild([], forceNewInstances);
- privateChildInjectorFactory = createPrivateInjectorFactory(privateChildInjector);
- privateInjectorsCache.push(provider[3]);
- privateChildInjectors.push(privateChildInjector);
- privateChildFactories.push(privateChildInjectorFactory);
- fromParentModule[name] = [ privateChildInjectorFactory, name, 'private', privateChildInjector ];
- } else {
- fromParentModule[name] = [ privateChildFactories[cacheIdx], name, 'private', privateChildInjectors[cacheIdx] ];
- }
- } else {
- fromParentModule[name] = [ provider[2], provider[1] ];
- }
- matchedScopes[name] = true;
- }
- if ((provider[2] === 'factory' || provider[2] === 'type') && provider[1].$scope) {
- /* jshint -W083 */
- forceNewInstances.forEach(function(scope) {
- if (provider[1].$scope.indexOf(scope) !== -1) {
- fromParentModule[name] = [ provider[2], provider[1] ];
- matchedScopes[scope] = true;
- }
- });
- }
- }
- forceNewInstances.forEach(function(scope) {
- if (!matchedScopes[scope]) {
- throw new Error('No provider for "' + scope + '". Cannot use provider from the parent!');
- }
- });
- modules.unshift(fromParentModule);
- }
- return new Injector(modules, self);
- }
- var factoryMap = {
- factory: invoke,
- type: instantiate,
- value: function(value) {
- return value;
- }
- };
- /**
- * @param {ModuleDefinition} moduleDefinition
- * @param {Injector} injector
- */
- function createInitializer(moduleDefinition, injector) {
- var initializers = moduleDefinition.__init__ || [];
- return function() {
- initializers.forEach(function(initializer) {
- try {
- // eagerly resolve component (fn or string)
- if (typeof initializer === 'string') {
- injector.get(initializer);
- } else {
- injector.invoke(initializer);
- }
- } catch (error) {
- if (typeof AggregateError !== 'undefined') {
- throw new AggregateError([ error ], 'Failed to initialize!');
- }
- throw new Error('Failed to initialize! ' + error.message);
- }
- });
- };
- }
- /**
- * @param {ModuleDefinition} moduleDefinition
- */
- function loadModule(moduleDefinition) {
- var moduleExports = moduleDefinition.__exports__;
- // private module
- if (moduleExports) {
- var nestedModules = moduleDefinition.__modules__;
- var clonedModule = Object.keys(moduleDefinition).reduce(function(clonedModule, key) {
- if (key !== '__exports__' && key !== '__modules__' && key !== '__init__' && key !== '__depends__') {
- clonedModule[key] = moduleDefinition[key];
- }
- return clonedModule;
- }, Object.create(null));
- var childModules = (nestedModules || []).concat(clonedModule);
- var privateInjector = createChild(childModules);
- var getFromPrivateInjector = annotate(function(key) {
- return privateInjector.get(key);
- });
- moduleExports.forEach(function(key) {
- providers[key] = [ getFromPrivateInjector, key, 'private', privateInjector ];
- });
- // ensure child injector initializes
- var initializers = (moduleDefinition.__init__ || []).slice();
- initializers.unshift(function() {
- privateInjector.init();
- });
- moduleDefinition = Object.assign({}, moduleDefinition, {
- __init__: initializers
- });
- return createInitializer(moduleDefinition, privateInjector);
- }
- // normal module
- Object.keys(moduleDefinition).forEach(function(key) {
- if (key === '__init__' || key === '__depends__') {
- return;
- }
- if (moduleDefinition[key][2] === 'private') {
- providers[key] = moduleDefinition[key];
- return;
- }
- var type = moduleDefinition[key][0];
- var value = moduleDefinition[key][1];
- providers[key] = [ factoryMap[type], arrayUnwrap(type, value), type ];
- });
- return createInitializer(moduleDefinition, self);
- }
- /**
- * @param {ModuleDefinition[]} moduleDefinitions
- * @param {ModuleDefinition} moduleDefinition
- *
- * @return {ModuleDefinition[]}
- */
- function resolveDependencies(moduleDefinitions, moduleDefinition) {
- if (moduleDefinitions.indexOf(moduleDefinition) !== -1) {
- return moduleDefinitions;
- }
- moduleDefinitions = (moduleDefinition.__depends__ || []).reduce(resolveDependencies, moduleDefinitions);
- if (moduleDefinitions.indexOf(moduleDefinition) !== -1) {
- return moduleDefinitions;
- }
- return moduleDefinitions.concat(moduleDefinition);
- }
- /**
- * @param {ModuleDefinition[]} moduleDefinitions
- *
- * @return { () => void } initializerFn
- */
- function bootstrap(moduleDefinitions) {
- var initializers = moduleDefinitions
- .reduce(resolveDependencies, [])
- .map(loadModule);
- var initialized = false;
- return function() {
- if (initialized) {
- return;
- }
- initialized = true;
- initializers.forEach(function(initializer) {
- return initializer();
- });
- };
- }
- // public API
- this.get = get;
- this.invoke = invoke;
- this.instantiate = instantiate;
- this.createChild = createChild;
- // setup
- this.init = bootstrap(modules);
- }
- // helpers ///////////////
- function arrayUnwrap(type, value) {
- if (type !== 'value' && isArray(value)) {
- value = annotate(value.slice());
- }
- return value;
- }
- // apply default renderer with lowest possible priority
- // so that it only kicks in if noone else could render
- var DEFAULT_RENDER_PRIORITY = 1;
- /**
- * The default renderer used for shapes and connections.
- *
- * @param {EventBus} eventBus
- * @param {Styles} styles
- */
- function DefaultRenderer(eventBus, styles) {
- //
- BaseRenderer.call(this, eventBus, DEFAULT_RENDER_PRIORITY);
- this.CONNECTION_STYLE = styles.style([ 'no-fill' ], { strokeWidth: 5, stroke: 'fuchsia' });
- this.SHAPE_STYLE = styles.style({ fill: 'white', stroke: 'fuchsia', strokeWidth: 2 });
- this.FRAME_STYLE = styles.style([ 'no-fill' ], { stroke: 'fuchsia', strokeDasharray: 4, strokeWidth: 2 });
- }
- e(DefaultRenderer, BaseRenderer);
- DefaultRenderer.prototype.canRender = function() {
- return true;
- };
- DefaultRenderer.prototype.drawShape = function drawShape(visuals, element, attrs) {
- var rect = create$1('rect');
- attr$1(rect, {
- x: 0,
- y: 0,
- width: element.width || 0,
- height: element.height || 0
- });
- if (isFrameElement(element)) {
- attr$1(rect, assign({}, this.FRAME_STYLE, attrs || {}));
- } else {
- attr$1(rect, assign({}, this.SHAPE_STYLE, attrs || {}));
- }
- append(visuals, rect);
- return rect;
- };
- DefaultRenderer.prototype.drawConnection = function drawConnection(visuals, connection, attrs) {
- var line = createLine(connection.waypoints, assign({}, this.CONNECTION_STYLE, attrs || {}));
- append(visuals, line);
- return line;
- };
- DefaultRenderer.prototype.getShapePath = function getShapePath(shape) {
- var x = shape.x,
- y = shape.y,
- width = shape.width,
- height = shape.height;
- var shapePath = [
- [ 'M', x, y ],
- [ 'l', width, 0 ],
- [ 'l', 0, height ],
- [ 'l', -width, 0 ],
- [ 'z' ]
- ];
- return componentsToPath(shapePath);
- };
- DefaultRenderer.prototype.getConnectionPath = function getConnectionPath(connection) {
- var waypoints = connection.waypoints;
- var idx, point, connectionPath = [];
- for (idx = 0; (point = waypoints[idx]); idx++) {
- // take invisible docking into account
- // when creating the path
- point = point.original || point;
- connectionPath.push([ idx === 0 ? 'M' : 'L', point.x, point.y ]);
- }
- return componentsToPath(connectionPath);
- };
- DefaultRenderer.$inject = [ 'eventBus', 'styles' ];
- /**
- * A component that manages shape styles
- */
- function Styles() {
- var defaultTraits = {
- 'no-fill': {
- fill: 'none'
- },
- 'no-border': {
- strokeOpacity: 0.0
- },
- 'no-events': {
- pointerEvents: 'none'
- }
- };
- var self = this;
- /**
- * Builds a style definition from a className, a list of traits and an object of additional attributes.
- *
- * @param {string} className
- * @param {Array<string>} traits
- * @param {Object} additionalAttrs
- *
- * @return {Object} the style defintion
- */
- this.cls = function(className, traits, additionalAttrs) {
- var attrs = this.style(traits, additionalAttrs);
- return assign(attrs, { 'class': className });
- };
- /**
- * Builds a style definition from a list of traits and an object of additional attributes.
- *
- * @param {Array<string>} traits
- * @param {Object} additionalAttrs
- *
- * @return {Object} the style defintion
- */
- this.style = function(traits, additionalAttrs) {
- if (!isArray$2(traits) && !additionalAttrs) {
- additionalAttrs = traits;
- traits = [];
- }
- var attrs = reduce(traits, function(attrs, t) {
- return assign(attrs, defaultTraits[t] || {});
- }, {});
- return additionalAttrs ? assign(attrs, additionalAttrs) : attrs;
- };
- this.computeStyle = function(custom, traits, defaultStyles) {
- if (!isArray$2(traits)) {
- defaultStyles = traits;
- traits = [];
- }
- return self.style(traits || [], assign({}, defaultStyles, custom || {}));
- };
- }
- var DrawModule = {
- __init__: [ 'defaultRenderer' ],
- defaultRenderer: [ 'type', DefaultRenderer ],
- styles: [ 'type', Styles ]
- };
- /**
- * Failsafe remove an element from a collection
- *
- * @param {Array<Object>} [collection]
- * @param {Object} [element]
- *
- * @return {number} the previous index of the element
- */
- function remove(collection, element) {
- if (!collection || !element) {
- return -1;
- }
- var idx = collection.indexOf(element);
- if (idx !== -1) {
- collection.splice(idx, 1);
- }
- return idx;
- }
- /**
- * Fail save add an element to the given connection, ensuring
- * it does not yet exist.
- *
- * @param {Array<Object>} collection
- * @param {Object} element
- * @param {number} idx
- */
- function add(collection, element, idx) {
- if (!collection || !element) {
- return;
- }
- if (typeof idx !== 'number') {
- idx = -1;
- }
- var currentIdx = collection.indexOf(element);
- if (currentIdx !== -1) {
- if (currentIdx === idx) {
- // nothing to do, position has not changed
- return;
- } else {
- if (idx !== -1) {
- // remove from current position
- collection.splice(currentIdx, 1);
- } else {
- // already exists in collection
- return;
- }
- }
- }
- if (idx !== -1) {
- // insert at specified position
- collection.splice(idx, 0, element);
- } else {
- // push to end
- collection.push(element);
- }
- }
- function round(number, resolution) {
- return Math.round(number * resolution) / resolution;
- }
- function ensurePx(number) {
- return isNumber(number) ? number + 'px' : number;
- }
- function findRoot(element) {
- while (element.parent) {
- element = element.parent;
- }
- return element;
- }
- /**
- * Creates a HTML container element for a SVG element with
- * the given configuration
- *
- * @param {Object} options
- * @return {HTMLElement} the container element
- */
- function createContainer(options) {
- options = assign({}, { width: '100%', height: '100%' }, options);
- var container = options.container || document.body;
- // create a <div> around the svg element with the respective size
- // this way we can always get the correct container size
- // (this is impossible for <svg> elements at the moment)
- var parent = document.createElement('div');
- parent.setAttribute('class', 'djs-container');
- assign$1(parent, {
- position: 'relative',
- overflow: 'hidden',
- width: ensurePx(options.width),
- height: ensurePx(options.height)
- });
- container.appendChild(parent);
- return parent;
- }
- function createGroup(parent, cls, childIndex) {
- var group = create$1('g');
- classes$1(group).add(cls);
- var index = childIndex !== undefined ? childIndex : parent.childNodes.length - 1;
- // must ensure second argument is node or _null_
- // cf. https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
- parent.insertBefore(group, parent.childNodes[index] || null);
- return group;
- }
- var BASE_LAYER = 'base';
- // render plane contents behind utility layers
- var PLANE_LAYER_INDEX = 0;
- var UTILITY_LAYER_INDEX = 1;
- var REQUIRED_MODEL_ATTRS = {
- shape: [ 'x', 'y', 'width', 'height' ],
- connection: [ 'waypoints' ]
- };
- /**
- * The main drawing canvas.
- *
- * @class
- * @constructor
- *
- * @emits Canvas#canvas.init
- *
- * @param {Object} config
- * @param {EventBus} eventBus
- * @param {GraphicsFactory} graphicsFactory
- * @param {ElementRegistry} elementRegistry
- */
- function Canvas(config, eventBus, graphicsFactory, elementRegistry) {
- this._eventBus = eventBus;
- this._elementRegistry = elementRegistry;
- this._graphicsFactory = graphicsFactory;
- this._rootsIdx = 0;
- this._layers = {};
- this._planes = [];
- this._rootElement = null;
- this._init(config || {});
- }
- Canvas.$inject = [
- 'config.canvas',
- 'eventBus',
- 'graphicsFactory',
- 'elementRegistry'
- ];
- /**
- * Creates a <svg> element that is wrapped into a <div>.
- * This way we are always able to correctly figure out the size of the svg element
- * by querying the parent node.
- * (It is not possible to get the size of a svg element cross browser @ 2014-04-01)
- * <div class="djs-container" style="width: {desired-width}, height: {desired-height}">
- * <svg width="100%" height="100%">
- * ...
- * </svg>
- * </div>
- */
- Canvas.prototype._init = function(config) {
- var eventBus = this._eventBus;
- // html container
- var container = this._container = createContainer(config);
- var svg = this._svg = create$1('svg');
- attr$1(svg, { width: '100%', height: '100%' });
- append(container, svg);
- var viewport = this._viewport = createGroup(svg, 'viewport');
- // debounce canvas.viewbox.changed events
- // for smoother diagram interaction
- if (config.deferUpdate !== false) {
- this._viewboxChanged = debounce(bind(this._viewboxChanged, this), 300);
- }
- eventBus.on('diagram.init', function() {
- /**
- * An event indicating that the canvas is ready to be drawn on.
- *
- * @memberOf Canvas
- *
- * @event canvas.init
- *
- * @type {Object}
- * @property {SVGElement} svg the created svg element
- * @property {SVGElement} viewport the direct parent of diagram elements and shapes
- */
- eventBus.fire('canvas.init', {
- svg: svg,
- viewport: viewport
- });
- }, this);
- // reset viewbox on shape changes to
- // recompute the viewbox
- eventBus.on([
- 'shape.added',
- 'connection.added',
- 'shape.removed',
- 'connection.removed',
- 'elements.changed',
- 'root.set'
- ], function() {
- delete this._cachedViewbox;
- }, this);
- eventBus.on('diagram.destroy', 500, this._destroy, this);
- eventBus.on('diagram.clear', 500, this._clear, this);
- };
- Canvas.prototype._destroy = function(emit) {
- this._eventBus.fire('canvas.destroy', {
- svg: this._svg,
- viewport: this._viewport
- });
- var parent = this._container.parentNode;
- if (parent) {
- parent.removeChild(this._container);
- }
- delete this._svg;
- delete this._container;
- delete this._layers;
- delete this._planes;
- delete this._rootElement;
- delete this._viewport;
- };
- Canvas.prototype._clear = function() {
- var self = this;
- var allElements = this._elementRegistry.getAll();
- // remove all elements
- allElements.forEach(function(element) {
- var type = getType(element);
- if (type === 'root') {
- self.removeRootElement(element);
- } else {
- self._removeElement(element, type);
- }
- });
- // remove all planes
- this._planes = [];
- this._rootElement = null;
- // force recomputation of view box
- delete this._cachedViewbox;
- };
- /**
- * Returns the default layer on which
- * all elements are drawn.
- *
- * @returns {SVGElement}
- */
- Canvas.prototype.getDefaultLayer = function() {
- return this.getLayer(BASE_LAYER, PLANE_LAYER_INDEX);
- };
- /**
- * Returns a layer that is used to draw elements
- * or annotations on it.
- *
- * Non-existing layers retrieved through this method
- * will be created. During creation, the optional index
- * may be used to create layers below or above existing layers.
- * A layer with a certain index is always created above all
- * existing layers with the same index.
- *
- * @param {string} name
- * @param {number} index
- *
- * @returns {SVGElement}
- */
- Canvas.prototype.getLayer = function(name, index) {
- if (!name) {
- throw new Error('must specify a name');
- }
- var layer = this._layers[name];
- if (!layer) {
- layer = this._layers[name] = this._createLayer(name, index);
- }
- // throw an error if layer creation / retrival is
- // requested on different index
- if (typeof index !== 'undefined' && layer.index !== index) {
- throw new Error('layer <' + name + '> already created at index <' + index + '>');
- }
- return layer.group;
- };
- /**
- * For a given index, return the number of layers that have a higher index and
- * are visible.
- *
- * This is used to determine the node a layer should be inserted at.
- *
- * @param {Number} index
- * @returns {Number}
- */
- Canvas.prototype._getChildIndex = function(index) {
- return reduce(this._layers, function(childIndex, layer) {
- if (layer.visible && index >= layer.index) {
- childIndex++;
- }
- return childIndex;
- }, 0);
- };
- /**
- * Creates a given layer and returns it.
- *
- * @param {string} name
- * @param {number} [index=0]
- *
- * @return {Object} layer descriptor with { index, group: SVGGroup }
- */
- Canvas.prototype._createLayer = function(name, index) {
- if (typeof index === 'undefined') {
- index = UTILITY_LAYER_INDEX;
- }
- var childIndex = this._getChildIndex(index);
- return {
- group: createGroup(this._viewport, 'layer-' + name, childIndex),
- index: index,
- visible: true
- };
- };
- /**
- * Shows a given layer.
- *
- * @param {String} layer
- * @returns {SVGElement}
- */
- Canvas.prototype.showLayer = function(name) {
- if (!name) {
- throw new Error('must specify a name');
- }
- var layer = this._layers[name];
- if (!layer) {
- throw new Error('layer <' + name + '> does not exist');
- }
- var viewport = this._viewport;
- var group = layer.group;
- var index = layer.index;
- if (layer.visible) {
- return group;
- }
- var childIndex = this._getChildIndex(index);
- viewport.insertBefore(group, viewport.childNodes[childIndex] || null);
- layer.visible = true;
- return group;
- };
- /**
- * Hides a given layer.
- *
- * @param {String} layer
- * @returns {SVGElement}
- */
- Canvas.prototype.hideLayer = function(name) {
- if (!name) {
- throw new Error('must specify a name');
- }
- var layer = this._layers[name];
- if (!layer) {
- throw new Error('layer <' + name + '> does not exist');
- }
- var group = layer.group;
- if (!layer.visible) {
- return group;
- }
- remove$2(group);
- layer.visible = false;
- return group;
- };
- Canvas.prototype._removeLayer = function(name) {
- var layer = this._layers[name];
- if (layer) {
- delete this._layers[name];
- remove$2(layer.group);
- }
- };
- /**
- * Returns the currently active layer. Can be null.
- *
- * @returns {SVGElement|null}
- */
- Canvas.prototype.getActiveLayer = function() {
- var plane = this._findPlaneForRoot(this.getRootElement());
- if (!plane) {
- return null;
- }
- return plane.layer;
- };
- /**
- * Returns the plane which contains the given element.
- *
- * @param {string|djs.model.Base} element
- *
- * @return {djs.model.Base} root for element
- */
- Canvas.prototype.findRoot = function(element) {
- if (typeof element === 'string') {
- element = this._elementRegistry.get(element);
- }
- if (!element) {
- return;
- }
- var plane = this._findPlaneForRoot(
- findRoot(element)
- ) || {};
- return plane.rootElement;
- };
- /**
- * Return a list of all root elements on the diagram.
- *
- * @return {djs.model.Root[]}
- */
- Canvas.prototype.getRootElements = function() {
- return this._planes.map(function(plane) {
- return plane.rootElement;
- });
- };
- Canvas.prototype._findPlaneForRoot = function(rootElement) {
- return find(this._planes, function(plane) {
- return plane.rootElement === rootElement;
- });
- };
- /**
- * Returns the html element that encloses the
- * drawing canvas.
- *
- * @return {DOMNode}
- */
- Canvas.prototype.getContainer = function() {
- return this._container;
- };
- // markers //////////////////////
- Canvas.prototype._updateMarker = function(element, marker, add) {
- var container;
- if (!element.id) {
- element = this._elementRegistry.get(element);
- }
- // we need to access all
- container = this._elementRegistry._elements[element.id];
- if (!container) {
- return;
- }
- forEach$1([ container.gfx, container.secondaryGfx ], function(gfx) {
- if (gfx) {
- // invoke either addClass or removeClass based on mode
- if (add) {
- classes$1(gfx).add(marker);
- } else {
- classes$1(gfx).remove(marker);
- }
- }
- });
- /**
- * An event indicating that a marker has been updated for an element
- *
- * @event element.marker.update
- * @type {Object}
- * @property {djs.model.Element} element the shape
- * @property {Object} gfx the graphical representation of the shape
- * @property {string} marker
- * @property {boolean} add true if the marker was added, false if it got removed
- */
- this._eventBus.fire('element.marker.update', { element: element, gfx: container.gfx, marker: marker, add: !!add });
- };
- /**
- * Adds a marker to an element (basically a css class).
- *
- * Fires the element.marker.update event, making it possible to
- * integrate extension into the marker life-cycle, too.
- *
- * @example
- * canvas.addMarker('foo', 'some-marker');
- *
- * var fooGfx = canvas.getGraphics('foo');
- *
- * fooGfx; // <g class="... some-marker"> ... </g>
- *
- * @param {string|djs.model.Base} element
- * @param {string} marker
- */
- Canvas.prototype.addMarker = function(element, marker) {
- this._updateMarker(element, marker, true);
- };
- /**
- * Remove a marker from an element.
- *
- * Fires the element.marker.update event, making it possible to
- * integrate extension into the marker life-cycle, too.
- *
- * @param {string|djs.model.Base} element
- * @param {string} marker
- */
- Canvas.prototype.removeMarker = function(element, marker) {
- this._updateMarker(element, marker, false);
- };
- /**
- * Check the existence of a marker on element.
- *
- * @param {string|djs.model.Base} element
- * @param {string} marker
- */
- Canvas.prototype.hasMarker = function(element, marker) {
- if (!element.id) {
- element = this._elementRegistry.get(element);
- }
- var gfx = this.getGraphics(element);
- return classes$1(gfx).has(marker);
- };
- /**
- * Toggles a marker on an element.
- *
- * Fires the element.marker.update event, making it possible to
- * integrate extension into the marker life-cycle, too.
- *
- * @param {string|djs.model.Base} element
- * @param {string} marker
- */
- Canvas.prototype.toggleMarker = function(element, marker) {
- if (this.hasMarker(element, marker)) {
- this.removeMarker(element, marker);
- } else {
- this.addMarker(element, marker);
- }
- };
- /**
- * Returns the current root element.
- *
- * Supports two different modes for handling root elements:
- *
- * 1. if no root element has been added before, an implicit root will be added
- * and returned. This is used in applications that don't require explicit
- * root elements.
- *
- * 2. when root elements have been added before calling `getRootElement`,
- * root elements can be null. This is used for applications that want to manage
- * root elements themselves.
- *
- * @returns {Object|djs.model.Root|null} rootElement.
- */
- Canvas.prototype.getRootElement = function() {
- var rootElement = this._rootElement;
- // can return null if root elements are present but none was set yet
- if (rootElement || this._planes.length) {
- return rootElement;
- }
- return this.setRootElement(this.addRootElement(null));
- };
- /**
- * Adds a given root element and returns it.
- *
- * @param {Object|djs.model.Root} rootElement
- *
- * @return {Object|djs.model.Root} rootElement
- */
- Canvas.prototype.addRootElement = function(rootElement) {
- var idx = this._rootsIdx++;
- if (!rootElement) {
- rootElement = {
- id: '__implicitroot_' + idx,
- children: [],
- isImplicit: true
- };
- }
- var layerName = rootElement.layer = 'root-' + idx;
- this._ensureValid('root', rootElement);
- var layer = this.getLayer(layerName, PLANE_LAYER_INDEX);
- this.hideLayer(layerName);
- this._addRoot(rootElement, layer);
- this._planes.push({
- rootElement: rootElement,
- layer: layer
- });
- return rootElement;
- };
- /**
- * Removes a given rootElement and returns it.
- *
- * @param {djs.model.Root|String} rootElement
- *
- * @return {Object|djs.model.Root} rootElement
- */
- Canvas.prototype.removeRootElement = function(rootElement) {
- if (typeof rootElement === 'string') {
- rootElement = this._elementRegistry.get(rootElement);
- }
- var plane = this._findPlaneForRoot(rootElement);
- if (!plane) {
- return;
- }
- // hook up life-cycle events
- this._removeRoot(rootElement);
- // clean up layer
- this._removeLayer(rootElement.layer);
- // clean up plane
- this._planes = this._planes.filter(function(plane) {
- return plane.rootElement !== rootElement;
- });
- // clean up active root
- if (this._rootElement === rootElement) {
- this._rootElement = null;
- }
- return rootElement;
- };
- // root element handling //////////////////////
- /**
- * Sets a given element as the new root element for the canvas
- * and returns the new root element.
- *
- * @param {Object|djs.model.Root} rootElement
- *
- * @return {Object|djs.model.Root} new root element
- */
- Canvas.prototype.setRootElement = function(rootElement, override) {
- if (isDefined(override)) {
- throw new Error('override not supported');
- }
- if (rootElement === this._rootElement) {
- return;
- }
- var plane;
- if (!rootElement) {
- throw new Error('rootElement required');
- }
- plane = this._findPlaneForRoot(rootElement);
- // give set add semantics for backwards compatibility
- if (!plane) {
- rootElement = this.addRootElement(rootElement);
- }
- this._setRoot(rootElement);
- return rootElement;
- };
- Canvas.prototype._removeRoot = function(element) {
- var elementRegistry = this._elementRegistry,
- eventBus = this._eventBus;
- // simulate element remove event sequence
- eventBus.fire('root.remove', { element: element });
- eventBus.fire('root.removed', { element: element });
- elementRegistry.remove(element);
- };
- Canvas.prototype._addRoot = function(element, gfx) {
- var elementRegistry = this._elementRegistry,
- eventBus = this._eventBus;
- // resemble element add event sequence
- eventBus.fire('root.add', { element: element });
- elementRegistry.add(element, gfx);
- eventBus.fire('root.added', { element: element, gfx: gfx });
- };
- Canvas.prototype._setRoot = function(rootElement, layer) {
- var currentRoot = this._rootElement;
- if (currentRoot) {
- // un-associate previous root element <svg>
- this._elementRegistry.updateGraphics(currentRoot, null, true);
- // hide previous layer
- this.hideLayer(currentRoot.layer);
- }
- if (rootElement) {
- if (!layer) {
- layer = this._findPlaneForRoot(rootElement).layer;
- }
- // associate element with <svg>
- this._elementRegistry.updateGraphics(rootElement, this._svg, true);
- // show root layer
- this.showLayer(rootElement.layer);
- }
- this._rootElement = rootElement;
- this._eventBus.fire('root.set', { element: rootElement });
- };
- // add functionality //////////////////////
- Canvas.prototype._ensureValid = function(type, element) {
- if (!element.id) {
- throw new Error('element must have an id');
- }
- if (this._elementRegistry.get(element.id)) {
- throw new Error('element <' + element.id + '> already exists');
- }
- var requiredAttrs = REQUIRED_MODEL_ATTRS[type];
- var valid = every(requiredAttrs, function(attr) {
- return typeof element[attr] !== 'undefined';
- });
- if (!valid) {
- throw new Error(
- 'must supply { ' + requiredAttrs.join(', ') + ' } with ' + type);
- }
- };
- Canvas.prototype._setParent = function(element, parent, parentIndex) {
- add(parent.children, element, parentIndex);
- element.parent = parent;
- };
- /**
- * Adds an element to the canvas.
- *
- * This wires the parent <-> child relationship between the element and
- * a explicitly specified parent or an implicit root element.
- *
- * During add it emits the events
- *
- * * <{type}.add> (element, parent)
- * * <{type}.added> (element, gfx)
- *
- * Extensions may hook into these events to perform their magic.
- *
- * @param {string} type
- * @param {Object|djs.model.Base} element
- * @param {Object|djs.model.Base} [parent]
- * @param {number} [parentIndex]
- *
- * @return {Object|djs.model.Base} the added element
- */
- Canvas.prototype._addElement = function(type, element, parent, parentIndex) {
- parent = parent || this.getRootElement();
- var eventBus = this._eventBus,
- graphicsFactory = this._graphicsFactory;
- this._ensureValid(type, element);
- eventBus.fire(type + '.add', { element: element, parent: parent });
- this._setParent(element, parent, parentIndex);
- // create graphics
- var gfx = graphicsFactory.create(type, element, parentIndex);
- this._elementRegistry.add(element, gfx);
- // update its visual
- graphicsFactory.update(type, element, gfx);
- eventBus.fire(type + '.added', { element: element, gfx: gfx });
- return element;
- };
- /**
- * Adds a shape to the canvas
- *
- * @param {Object|djs.model.Shape} shape to add to the diagram
- * @param {djs.model.Base} [parent]
- * @param {number} [parentIndex]
- *
- * @return {djs.model.Shape} the added shape
- */
- Canvas.prototype.addShape = function(shape, parent, parentIndex) {
- return this._addElement('shape', shape, parent, parentIndex);
- };
- /**
- * Adds a connection to the canvas
- *
- * @param {Object|djs.model.Connection} connection to add to the diagram
- * @param {djs.model.Base} [parent]
- * @param {number} [parentIndex]
- *
- * @return {djs.model.Connection} the added connection
- */
- Canvas.prototype.addConnection = function(connection, parent, parentIndex) {
- return this._addElement('connection', connection, parent, parentIndex);
- };
- /**
- * Internal remove element
- */
- Canvas.prototype._removeElement = function(element, type) {
- var elementRegistry = this._elementRegistry,
- graphicsFactory = this._graphicsFactory,
- eventBus = this._eventBus;
- element = elementRegistry.get(element.id || element);
- if (!element) {
- // element was removed already
- return;
- }
- eventBus.fire(type + '.remove', { element: element });
- graphicsFactory.remove(element);
- // unset parent <-> child relationship
- remove(element.parent && element.parent.children, element);
- element.parent = null;
- eventBus.fire(type + '.removed', { element: element });
- elementRegistry.remove(element);
- return element;
- };
- /**
- * Removes a shape from the canvas
- *
- * @param {string|djs.model.Shape} shape or shape id to be removed
- *
- * @return {djs.model.Shape} the removed shape
- */
- Canvas.prototype.removeShape = function(shape) {
- /**
- * An event indicating that a shape is about to be removed from the canvas.
- *
- * @memberOf Canvas
- *
- * @event shape.remove
- * @type {Object}
- * @property {djs.model.Shape} element the shape descriptor
- * @property {Object} gfx the graphical representation of the shape
- */
- /**
- * An event indicating that a shape has been removed from the canvas.
- *
- * @memberOf Canvas
- *
- * @event shape.removed
- * @type {Object}
- * @property {djs.model.Shape} element the shape descriptor
- * @property {Object} gfx the graphical representation of the shape
- */
- return this._removeElement(shape, 'shape');
- };
- /**
- * Removes a connection from the canvas
- *
- * @param {string|djs.model.Connection} connection or connection id to be removed
- *
- * @return {djs.model.Connection} the removed connection
- */
- Canvas.prototype.removeConnection = function(connection) {
- /**
- * An event indicating that a connection is about to be removed from the canvas.
- *
- * @memberOf Canvas
- *
- * @event connection.remove
- * @type {Object}
- * @property {djs.model.Connection} element the connection descriptor
- * @property {Object} gfx the graphical representation of the connection
- */
- /**
- * An event indicating that a connection has been removed from the canvas.
- *
- * @memberOf Canvas
- *
- * @event connection.removed
- * @type {Object}
- * @property {djs.model.Connection} element the connection descriptor
- * @property {Object} gfx the graphical representation of the connection
- */
- return this._removeElement(connection, 'connection');
- };
- /**
- * Return the graphical object underlaying a certain diagram element
- *
- * @param {string|djs.model.Base} element descriptor of the element
- * @param {boolean} [secondary=false] whether to return the secondary connected element
- *
- * @return {SVGElement}
- */
- Canvas.prototype.getGraphics = function(element, secondary) {
- return this._elementRegistry.getGraphics(element, secondary);
- };
- /**
- * Perform a viewbox update via a given change function.
- *
- * @param {Function} changeFn
- */
- Canvas.prototype._changeViewbox = function(changeFn) {
- // notify others of the upcoming viewbox change
- this._eventBus.fire('canvas.viewbox.changing');
- // perform actual change
- changeFn.apply(this);
- // reset the cached viewbox so that
- // a new get operation on viewbox or zoom
- // triggers a viewbox re-computation
- this._cachedViewbox = null;
- // notify others of the change; this step
- // may or may not be debounced
- this._viewboxChanged();
- };
- Canvas.prototype._viewboxChanged = function() {
- this._eventBus.fire('canvas.viewbox.changed', { viewbox: this.viewbox() });
- };
- /**
- * Gets or sets the view box of the canvas, i.e. the
- * area that is currently displayed.
- *
- * The getter may return a cached viewbox (if it is currently
- * changing). To force a recomputation, pass `false` as the first argument.
- *
- * @example
- *
- * canvas.viewbox({ x: 100, y: 100, width: 500, height: 500 })
- *
- * // sets the visible area of the diagram to (100|100) -> (600|100)
- * // and and scales it according to the diagram width
- *
- * var viewbox = canvas.viewbox(); // pass `false` to force recomputing the box.
- *
- * console.log(viewbox);
- * // {
- * // inner: Dimensions,
- * // outer: Dimensions,
- * // scale,
- * // x, y,
- * // width, height
- * // }
- *
- * // if the current diagram is zoomed and scrolled, you may reset it to the
- * // default zoom via this method, too:
- *
- * var zoomedAndScrolledViewbox = canvas.viewbox();
- *
- * canvas.viewbox({
- * x: 0,
- * y: 0,
- * width: zoomedAndScrolledViewbox.outer.width,
- * height: zoomedAndScrolledViewbox.outer.height
- * });
- *
- * @param {Object} [box] the new view box to set
- * @param {number} box.x the top left X coordinate of the canvas visible in view box
- * @param {number} box.y the top left Y coordinate of the canvas visible in view box
- * @param {number} box.width the visible width
- * @param {number} box.height
- *
- * @return {Object} the current view box
- */
- Canvas.prototype.viewbox = function(box) {
- if (box === undefined && this._cachedViewbox) {
- return this._cachedViewbox;
- }
- var viewport = this._viewport,
- innerBox,
- outerBox = this.getSize(),
- matrix,
- activeLayer,
- transform,
- scale,
- x, y;
- if (!box) {
- // compute the inner box based on the
- // diagrams active layer. This allows us to exclude
- // external components, such as overlays
- activeLayer = this._rootElement ? this.getActiveLayer() : null;
- innerBox = activeLayer && activeLayer.getBBox() || {};
- transform = transform$1(viewport);
- matrix = transform ? transform.matrix : createMatrix();
- scale = round(matrix.a, 1000);
- x = round(-matrix.e || 0, 1000);
- y = round(-matrix.f || 0, 1000);
- box = this._cachedViewbox = {
- x: x ? x / scale : 0,
- y: y ? y / scale : 0,
- width: outerBox.width / scale,
- height: outerBox.height / scale,
- scale: scale,
- inner: {
- width: innerBox.width || 0,
- height: innerBox.height || 0,
- x: innerBox.x || 0,
- y: innerBox.y || 0
- },
- outer: outerBox
- };
- return box;
- } else {
- this._changeViewbox(function() {
- scale = Math.min(outerBox.width / box.width, outerBox.height / box.height);
- var matrix = this._svg.createSVGMatrix()
- .scale(scale)
- .translate(-box.x, -box.y);
- transform$1(viewport, matrix);
- });
- }
- return box;
- };
- /**
- * Gets or sets the scroll of the canvas.
- *
- * @param {Object} [delta] the new scroll to apply.
- *
- * @param {number} [delta.dx]
- * @param {number} [delta.dy]
- */
- Canvas.prototype.scroll = function(delta) {
- var node = this._viewport;
- var matrix = node.getCTM();
- if (delta) {
- this._changeViewbox(function() {
- delta = assign({ dx: 0, dy: 0 }, delta || {});
- matrix = this._svg.createSVGMatrix().translate(delta.dx, delta.dy).multiply(matrix);
- setCTM(node, matrix);
- });
- }
- return { x: matrix.e, y: matrix.f };
- };
- /**
- * Scrolls the viewbox to contain the given element.
- * Optionally specify a padding to be applied to the edges.
- *
- * @param {Object|String} [element] the element to scroll to.
- * @param {Object|Number} [padding=100] the padding to be applied. Can also specify top, bottom, left and right.
- *
- */
- Canvas.prototype.scrollToElement = function(element, padding) {
- var defaultPadding = 100;
- if (typeof element === 'string') {
- element = this._elementRegistry.get(element);
- }
- // set to correct rootElement
- var rootElement = this.findRoot(element);
- if (rootElement !== this.getRootElement()) {
- this.setRootElement(rootElement);
- }
- if (!padding) {
- padding = {};
- }
- if (typeof padding === 'number') {
- defaultPadding = padding;
- }
- padding = {
- top: padding.top || defaultPadding,
- right: padding.right || defaultPadding,
- bottom: padding.bottom || defaultPadding,
- left: padding.left || defaultPadding
- };
- var elementBounds = getBBox(element),
- elementTrbl = asTRBL(elementBounds),
- viewboxBounds = this.viewbox(),
- zoom = this.zoom(),
- dx, dy;
- // shrink viewboxBounds with padding
- viewboxBounds.y += padding.top / zoom;
- viewboxBounds.x += padding.left / zoom;
- viewboxBounds.width -= (padding.right + padding.left) / zoom;
- viewboxBounds.height -= (padding.bottom + padding.top) / zoom;
- var viewboxTrbl = asTRBL(viewboxBounds);
- var canFit = elementBounds.width < viewboxBounds.width && elementBounds.height < viewboxBounds.height;
- if (!canFit) {
- // top-left when element can't fit
- dx = elementBounds.x - viewboxBounds.x;
- dy = elementBounds.y - viewboxBounds.y;
- } else {
- var dRight = Math.max(0, elementTrbl.right - viewboxTrbl.right),
- dLeft = Math.min(0, elementTrbl.left - viewboxTrbl.left),
- dBottom = Math.max(0, elementTrbl.bottom - viewboxTrbl.bottom),
- dTop = Math.min(0, elementTrbl.top - viewboxTrbl.top);
- dx = dRight || dLeft;
- dy = dBottom || dTop;
- }
- this.scroll({ dx: -dx * zoom, dy: -dy * zoom });
- };
- /**
- * Gets or sets the current zoom of the canvas, optionally zooming
- * to the specified position.
- *
- * The getter may return a cached zoom level. Call it with `false` as
- * the first argument to force recomputation of the current level.
- *
- * @param {string|number} [newScale] the new zoom level, either a number, i.e. 0.9,
- * or `fit-viewport` to adjust the size to fit the current viewport
- * @param {string|Point} [center] the reference point { x: .., y: ..} to zoom to, 'auto' to zoom into mid or null
- *
- * @return {number} the current scale
- */
- Canvas.prototype.zoom = function(newScale, center) {
- if (!newScale) {
- return this.viewbox(newScale).scale;
- }
- if (newScale === 'fit-viewport') {
- return this._fitViewport(center);
- }
- var outer,
- matrix;
- this._changeViewbox(function() {
- if (typeof center !== 'object') {
- outer = this.viewbox().outer;
- center = {
- x: outer.width / 2,
- y: outer.height / 2
- };
- }
- matrix = this._setZoom(newScale, center);
- });
- return round(matrix.a, 1000);
- };
- function setCTM(node, m) {
- var mstr = 'matrix(' + m.a + ',' + m.b + ',' + m.c + ',' + m.d + ',' + m.e + ',' + m.f + ')';
- node.setAttribute('transform', mstr);
- }
- Canvas.prototype._fitViewport = function(center) {
- var vbox = this.viewbox(),
- outer = vbox.outer,
- inner = vbox.inner,
- newScale,
- newViewbox;
- // display the complete diagram without zooming in.
- // instead of relying on internal zoom, we perform a
- // hard reset on the canvas viewbox to realize this
- //
- // if diagram does not need to be zoomed in, we focus it around
- // the diagram origin instead
- if (inner.x >= 0 &&
- inner.y >= 0 &&
- inner.x + inner.width <= outer.width &&
- inner.y + inner.height <= outer.height &&
- !center) {
- newViewbox = {
- x: 0,
- y: 0,
- width: Math.max(inner.width + inner.x, outer.width),
- height: Math.max(inner.height + inner.y, outer.height)
- };
- } else {
- newScale = Math.min(1, outer.width / inner.width, outer.height / inner.height);
- newViewbox = {
- x: inner.x + (center ? inner.width / 2 - outer.width / newScale / 2 : 0),
- y: inner.y + (center ? inner.height / 2 - outer.height / newScale / 2 : 0),
- width: outer.width / newScale,
- height: outer.height / newScale
- };
- }
- this.viewbox(newViewbox);
- return this.viewbox(false).scale;
- };
- Canvas.prototype._setZoom = function(scale, center) {
- var svg = this._svg,
- viewport = this._viewport;
- var matrix = svg.createSVGMatrix();
- var point = svg.createSVGPoint();
- var centerPoint,
- originalPoint,
- currentMatrix,
- scaleMatrix,
- newMatrix;
- currentMatrix = viewport.getCTM();
- var currentScale = currentMatrix.a;
- if (center) {
- centerPoint = assign(point, center);
- // revert applied viewport transformations
- originalPoint = centerPoint.matrixTransform(currentMatrix.inverse());
- // create scale matrix
- scaleMatrix = matrix
- .translate(originalPoint.x, originalPoint.y)
- .scale(1 / currentScale * scale)
- .translate(-originalPoint.x, -originalPoint.y);
- newMatrix = currentMatrix.multiply(scaleMatrix);
- } else {
- newMatrix = matrix.scale(scale);
- }
- setCTM(this._viewport, newMatrix);
- return newMatrix;
- };
- /**
- * Returns the size of the canvas
- *
- * @return {Dimensions}
- */
- Canvas.prototype.getSize = function() {
- return {
- width: this._container.clientWidth,
- height: this._container.clientHeight
- };
- };
- /**
- * Return the absolute bounding box for the given element
- *
- * The absolute bounding box may be used to display overlays in the
- * callers (browser) coordinate system rather than the zoomed in/out
- * canvas coordinates.
- *
- * @param {ElementDescriptor} element
- * @return {Bounds} the absolute bounding box
- */
- Canvas.prototype.getAbsoluteBBox = function(element) {
- var vbox = this.viewbox();
- var bbox;
- // connection
- // use svg bbox
- if (element.waypoints) {
- var gfx = this.getGraphics(element);
- bbox = gfx.getBBox();
- }
- // shapes
- // use data
- else {
- bbox = element;
- }
- var x = bbox.x * vbox.scale - vbox.x * vbox.scale;
- var y = bbox.y * vbox.scale - vbox.y * vbox.scale;
- var width = bbox.width * vbox.scale;
- var height = bbox.height * vbox.scale;
- return {
- x: x,
- y: y,
- width: width,
- height: height
- };
- };
- /**
- * Fires an event in order other modules can react to the
- * canvas resizing
- */
- Canvas.prototype.resized = function() {
- // force recomputation of view box
- delete this._cachedViewbox;
- this._eventBus.fire('canvas.resized');
- };
- var ELEMENT_ID = 'data-element-id';
- /**
- * @class
- *
- * A registry that keeps track of all shapes in the diagram.
- */
- function ElementRegistry(eventBus) {
- this._elements = {};
- this._eventBus = eventBus;
- }
- ElementRegistry.$inject = [ 'eventBus' ];
- /**
- * Register a pair of (element, gfx, (secondaryGfx)).
- *
- * @param {djs.model.Base} element
- * @param {SVGElement} gfx
- * @param {SVGElement} [secondaryGfx] optional other element to register, too
- */
- ElementRegistry.prototype.add = function(element, gfx, secondaryGfx) {
- var id = element.id;
- this._validateId(id);
- // associate dom node with element
- attr$1(gfx, ELEMENT_ID, id);
- if (secondaryGfx) {
- attr$1(secondaryGfx, ELEMENT_ID, id);
- }
- this._elements[id] = { element: element, gfx: gfx, secondaryGfx: secondaryGfx };
- };
- /**
- * Removes an element from the registry.
- *
- * @param {djs.model.Base} element
- */
- ElementRegistry.prototype.remove = function(element) {
- var elements = this._elements,
- id = element.id || element,
- container = id && elements[id];
- if (container) {
- // unset element id on gfx
- attr$1(container.gfx, ELEMENT_ID, '');
- if (container.secondaryGfx) {
- attr$1(container.secondaryGfx, ELEMENT_ID, '');
- }
- delete elements[id];
- }
- };
- /**
- * Update the id of an element
- *
- * @param {djs.model.Base} element
- * @param {string} newId
- */
- ElementRegistry.prototype.updateId = function(element, newId) {
- this._validateId(newId);
- if (typeof element === 'string') {
- element = this.get(element);
- }
- this._eventBus.fire('element.updateId', {
- element: element,
- newId: newId
- });
- var gfx = this.getGraphics(element),
- secondaryGfx = this.getGraphics(element, true);
- this.remove(element);
- element.id = newId;
- this.add(element, gfx, secondaryGfx);
- };
- /**
- * Update the graphics of an element
- *
- * @param {djs.model.Base} element
- * @param {SVGElement} gfx
- * @param {boolean} [secondary=false] whether to update the secondary connected element
- */
- ElementRegistry.prototype.updateGraphics = function(filter, gfx, secondary) {
- var id = filter.id || filter;
- var container = this._elements[id];
- if (secondary) {
- container.secondaryGfx = gfx;
- } else {
- container.gfx = gfx;
- }
- if (gfx) {
- attr$1(gfx, ELEMENT_ID, id);
- }
- return gfx;
- };
- /**
- * Return the model element for a given id or graphics.
- *
- * @example
- *
- * elementRegistry.get('SomeElementId_1');
- * elementRegistry.get(gfx);
- *
- *
- * @param {string|SVGElement} filter for selecting the element
- *
- * @return {djs.model.Base}
- */
- ElementRegistry.prototype.get = function(filter) {
- var id;
- if (typeof filter === 'string') {
- id = filter;
- } else {
- id = filter && attr$1(filter, ELEMENT_ID);
- }
- var container = this._elements[id];
- return container && container.element;
- };
- /**
- * Return all elements that match a given filter function.
- *
- * @param {Function} fn
- *
- * @return {Array<djs.model.Base>}
- */
- ElementRegistry.prototype.filter = function(fn) {
- var filtered = [];
- this.forEach(function(element, gfx) {
- if (fn(element, gfx)) {
- filtered.push(element);
- }
- });
- return filtered;
- };
- /**
- * Return the first element that satisfies the provided testing function.
- *
- * @param {Function} fn
- *
- * @return {djs.model.Base}
- */
- ElementRegistry.prototype.find = function(fn) {
- var map = this._elements,
- keys = Object.keys(map);
- for (var i = 0; i < keys.length; i++) {
- var id = keys[i],
- container = map[id],
- element = container.element,
- gfx = container.gfx;
- if (fn(element, gfx)) {
- return element;
- }
- }
- };
- /**
- * Return all rendered model elements.
- *
- * @return {Array<djs.model.Base>}
- */
- ElementRegistry.prototype.getAll = function() {
- return this.filter(function(e) { return e; });
- };
- /**
- * Iterate over all diagram elements.
- *
- * @param {Function} fn
- */
- ElementRegistry.prototype.forEach = function(fn) {
- var map = this._elements;
- Object.keys(map).forEach(function(id) {
- var container = map[id],
- element = container.element,
- gfx = container.gfx;
- return fn(element, gfx);
- });
- };
- /**
- * Return the graphical representation of an element or its id.
- *
- * @example
- * elementRegistry.getGraphics('SomeElementId_1');
- * elementRegistry.getGraphics(rootElement); // <g ...>
- *
- * elementRegistry.getGraphics(rootElement, true); // <svg ...>
- *
- *
- * @param {string|djs.model.Base} filter
- * @param {boolean} [secondary=false] whether to return the secondary connected element
- *
- * @return {SVGElement}
- */
- ElementRegistry.prototype.getGraphics = function(filter, secondary) {
- var id = filter.id || filter;
- var container = this._elements[id];
- return container && (secondary ? container.secondaryGfx : container.gfx);
- };
- /**
- * Validate the suitability of the given id and signals a problem
- * with an exception.
- *
- * @param {string} id
- *
- * @throws {Error} if id is empty or already assigned
- */
- ElementRegistry.prototype._validateId = function(id) {
- if (!id) {
- throw new Error('element must have an id');
- }
- if (this._elements[id]) {
- throw new Error('element with id ' + id + ' already added');
- }
- };
- var objectRefs = {exports: {}};
- var collection = {};
- /**
- * An empty collection stub. Use {@link RefsCollection.extend} to extend a
- * collection with ref semantics.
- *
- * @class RefsCollection
- */
- /**
- * Extends a collection with {@link Refs} aware methods
- *
- * @memberof RefsCollection
- * @static
- *
- * @param {Array<Object>} collection
- * @param {Refs} refs instance
- * @param {Object} property represented by the collection
- * @param {Object} target object the collection is attached to
- *
- * @return {RefsCollection<Object>} the extended array
- */
- function extend(collection, refs, property, target) {
- var inverseProperty = property.inverse;
- /**
- * Removes the given element from the array and returns it.
- *
- * @method RefsCollection#remove
- *
- * @param {Object} element the element to remove
- */
- Object.defineProperty(collection, 'remove', {
- value: function(element) {
- var idx = this.indexOf(element);
- if (idx !== -1) {
- this.splice(idx, 1);
- // unset inverse
- refs.unset(element, inverseProperty, target);
- }
- return element;
- }
- });
- /**
- * Returns true if the collection contains the given element
- *
- * @method RefsCollection#contains
- *
- * @param {Object} element the element to check for
- */
- Object.defineProperty(collection, 'contains', {
- value: function(element) {
- return this.indexOf(element) !== -1;
- }
- });
- /**
- * Adds an element to the array, unless it exists already (set semantics).
- *
- * @method RefsCollection#add
- *
- * @param {Object} element the element to add
- * @param {Number} optional index to add element to
- * (possibly moving other elements around)
- */
- Object.defineProperty(collection, 'add', {
- value: function(element, idx) {
- var currentIdx = this.indexOf(element);
- if (typeof idx === 'undefined') {
- if (currentIdx !== -1) {
- // element already in collection (!)
- return;
- }
- // add to end of array, as no idx is specified
- idx = this.length;
- }
- // handle already in collection
- if (currentIdx !== -1) {
- // remove element from currentIdx
- this.splice(currentIdx, 1);
- }
- // add element at idx
- this.splice(idx, 0, element);
- if (currentIdx === -1) {
- // set inverse, unless element was
- // in collection already
- refs.set(element, inverseProperty, target);
- }
- }
- });
- // a simple marker, identifying this element
- // as being a refs collection
- Object.defineProperty(collection, '__refs_collection', {
- value: true
- });
- return collection;
- }
- function isExtended(collection) {
- return collection.__refs_collection === true;
- }
- collection.extend = extend;
- collection.isExtended = isExtended;
- var Collection = collection;
- function hasOwnProperty$1(e, property) {
- return Object.prototype.hasOwnProperty.call(e, property.name || property);
- }
- function defineCollectionProperty(ref, property, target) {
- var collection = Collection.extend(target[property.name] || [], ref, property, target);
- Object.defineProperty(target, property.name, {
- enumerable: property.enumerable,
- value: collection
- });
- if (collection.length) {
- collection.forEach(function(o) {
- ref.set(o, property.inverse, target);
- });
- }
- }
- function defineProperty$1(ref, property, target) {
- var inverseProperty = property.inverse;
- var _value = target[property.name];
- Object.defineProperty(target, property.name, {
- configurable: property.configurable,
- enumerable: property.enumerable,
- get: function() {
- return _value;
- },
- set: function(value) {
- // return if we already performed all changes
- if (value === _value) {
- return;
- }
- var old = _value;
- // temporary set null
- _value = null;
- if (old) {
- ref.unset(old, inverseProperty, target);
- }
- // set new value
- _value = value;
- // set inverse value
- ref.set(_value, inverseProperty, target);
- }
- });
- }
- /**
- * Creates a new references object defining two inversly related
- * attribute descriptors a and b.
- *
- * <p>
- * When bound to an object using {@link Refs#bind} the references
- * get activated and ensure that add and remove operations are applied
- * reversely, too.
- * </p>
- *
- * <p>
- * For attributes represented as collections {@link Refs} provides the
- * {@link RefsCollection#add}, {@link RefsCollection#remove} and {@link RefsCollection#contains} extensions
- * that must be used to properly hook into the inverse change mechanism.
- * </p>
- *
- * @class Refs
- *
- * @classdesc A bi-directional reference between two attributes.
- *
- * @param {Refs.AttributeDescriptor} a property descriptor
- * @param {Refs.AttributeDescriptor} b property descriptor
- *
- * @example
- *
- * var refs = Refs({ name: 'wheels', collection: true, enumerable: true }, { name: 'car' });
- *
- * var car = { name: 'toyota' };
- * var wheels = [{ pos: 'front-left' }, { pos: 'front-right' }];
- *
- * refs.bind(car, 'wheels');
- *
- * car.wheels // []
- * car.wheels.add(wheels[0]);
- * car.wheels.add(wheels[1]);
- *
- * car.wheels // [{ pos: 'front-left' }, { pos: 'front-right' }]
- *
- * wheels[0].car // { name: 'toyota' };
- * car.wheels.remove(wheels[0]);
- *
- * wheels[0].car // undefined
- */
- function Refs$1(a, b) {
- if (!(this instanceof Refs$1)) {
- return new Refs$1(a, b);
- }
- // link
- a.inverse = b;
- b.inverse = a;
- this.props = {};
- this.props[a.name] = a;
- this.props[b.name] = b;
- }
- /**
- * Binds one side of a bi-directional reference to a
- * target object.
- *
- * @memberOf Refs
- *
- * @param {Object} target
- * @param {String} property
- */
- Refs$1.prototype.bind = function(target, property) {
- if (typeof property === 'string') {
- if (!this.props[property]) {
- throw new Error('no property <' + property + '> in ref');
- }
- property = this.props[property];
- }
- if (property.collection) {
- defineCollectionProperty(this, property, target);
- } else {
- defineProperty$1(this, property, target);
- }
- };
- Refs$1.prototype.ensureRefsCollection = function(target, property) {
- var collection = target[property.name];
- if (!Collection.isExtended(collection)) {
- defineCollectionProperty(this, property, target);
- }
- return collection;
- };
- Refs$1.prototype.ensureBound = function(target, property) {
- if (!hasOwnProperty$1(target, property)) {
- this.bind(target, property);
- }
- };
- Refs$1.prototype.unset = function(target, property, value) {
- if (target) {
- this.ensureBound(target, property);
- if (property.collection) {
- this.ensureRefsCollection(target, property).remove(value);
- } else {
- target[property.name] = undefined;
- }
- }
- };
- Refs$1.prototype.set = function(target, property, value) {
- if (target) {
- this.ensureBound(target, property);
- if (property.collection) {
- this.ensureRefsCollection(target, property).add(value);
- } else {
- target[property.name] = value;
- }
- }
- };
- var refs = Refs$1;
- objectRefs.exports = refs;
- objectRefs.exports.Collection = collection;
- var Refs = objectRefs.exports;
- var parentRefs = new Refs({ name: 'children', enumerable: true, collection: true }, { name: 'parent' }),
- labelRefs = new Refs({ name: 'labels', enumerable: true, collection: true }, { name: 'labelTarget' }),
- attacherRefs = new Refs({ name: 'attachers', collection: true }, { name: 'host' }),
- outgoingRefs = new Refs({ name: 'outgoing', collection: true }, { name: 'source' }),
- incomingRefs = new Refs({ name: 'incoming', collection: true }, { name: 'target' });
- /**
- * @namespace djs.model
- */
- /**
- * @memberOf djs.model
- */
- /**
- * The basic graphical representation
- *
- * @class
- *
- * @abstract
- */
- function Base$1() {
- /**
- * The object that backs up the shape
- *
- * @name Base#businessObject
- * @type Object
- */
- Object.defineProperty(this, 'businessObject', {
- writable: true
- });
- /**
- * Single label support, will mapped to multi label array
- *
- * @name Base#label
- * @type Object
- */
- Object.defineProperty(this, 'label', {
- get: function() {
- return this.labels[0];
- },
- set: function(newLabel) {
- var label = this.label,
- labels = this.labels;
- if (!newLabel && label) {
- labels.remove(label);
- } else {
- labels.add(newLabel, 0);
- }
- }
- });
- /**
- * The parent shape
- *
- * @name Base#parent
- * @type Shape
- */
- parentRefs.bind(this, 'parent');
- /**
- * The list of labels
- *
- * @name Base#labels
- * @type Label
- */
- labelRefs.bind(this, 'labels');
- /**
- * The list of outgoing connections
- *
- * @name Base#outgoing
- * @type Array<Connection>
- */
- outgoingRefs.bind(this, 'outgoing');
- /**
- * The list of incoming connections
- *
- * @name Base#incoming
- * @type Array<Connection>
- */
- incomingRefs.bind(this, 'incoming');
- }
- /**
- * A graphical object
- *
- * @class
- * @constructor
- *
- * @extends Base
- */
- function Shape() {
- Base$1.call(this);
- /**
- * Indicates frame shapes
- *
- * @name Shape#isFrame
- * @type boolean
- */
- /**
- * The list of children
- *
- * @name Shape#children
- * @type Array<Base>
- */
- parentRefs.bind(this, 'children');
- /**
- * @name Shape#host
- * @type Shape
- */
- attacherRefs.bind(this, 'host');
- /**
- * @name Shape#attachers
- * @type Shape
- */
- attacherRefs.bind(this, 'attachers');
- }
- e(Shape, Base$1);
- /**
- * A root graphical object
- *
- * @class
- * @constructor
- *
- * @extends Shape
- */
- function Root() {
- Shape.call(this);
- }
- e(Root, Shape);
- /**
- * A label for an element
- *
- * @class
- * @constructor
- *
- * @extends Shape
- */
- function Label() {
- Shape.call(this);
- /**
- * The labeled element
- *
- * @name Label#labelTarget
- * @type Base
- */
- labelRefs.bind(this, 'labelTarget');
- }
- e(Label, Shape);
- /**
- * A connection between two elements
- *
- * @class
- * @constructor
- *
- * @extends Base
- */
- function Connection() {
- Base$1.call(this);
- /**
- * The element this connection originates from
- *
- * @name Connection#source
- * @type Base
- */
- outgoingRefs.bind(this, 'source');
- /**
- * The element this connection points to
- *
- * @name Connection#target
- * @type Base
- */
- incomingRefs.bind(this, 'target');
- }
- e(Connection, Base$1);
- var types$6 = {
- connection: Connection,
- shape: Shape,
- label: Label,
- root: Root
- };
- /**
- * Creates a new model element of the specified type
- *
- * @method create
- *
- * @example
- *
- * var shape1 = Model.create('shape', { x: 10, y: 10, width: 100, height: 100 });
- * var shape2 = Model.create('shape', { x: 210, y: 210, width: 100, height: 100 });
- *
- * var connection = Model.create('connection', { waypoints: [ { x: 110, y: 55 }, {x: 210, y: 55 } ] });
- *
- * @param {string} type lower-cased model name
- * @param {Object} attrs attributes to initialize the new model instance with
- *
- * @return {Base} the new model instance
- */
- function create(type, attrs) {
- var Type = types$6[type];
- if (!Type) {
- throw new Error('unknown type: <' + type + '>');
- }
- return assign(new Type(), attrs);
- }
- /**
- * A factory for diagram-js shapes
- */
- function ElementFactory() {
- this._uid = 12;
- }
- ElementFactory.prototype.createRoot = function(attrs) {
- return this.create('root', attrs);
- };
- ElementFactory.prototype.createLabel = function(attrs) {
- return this.create('label', attrs);
- };
- ElementFactory.prototype.createShape = function(attrs) {
- return this.create('shape', attrs);
- };
- ElementFactory.prototype.createConnection = function(attrs) {
- return this.create('connection', attrs);
- };
- /**
- * Create a model element with the given type and
- * a number of pre-set attributes.
- *
- * @param {string} type
- * @param {Object} attrs
- * @return {djs.model.Base} the newly created model instance
- */
- ElementFactory.prototype.create = function(type, attrs) {
- attrs = assign({}, attrs || {});
- if (!attrs.id) {
- attrs.id = type + '_' + (this._uid++);
- }
- return create(type, attrs);
- };
- var FN_REF = '__fn';
- var DEFAULT_PRIORITY$1 = 1000;
- var slice = Array.prototype.slice;
- /**
- * A general purpose event bus.
- *
- * This component is used to communicate across a diagram instance.
- * Other parts of a diagram can use it to listen to and broadcast events.
- *
- *
- * ## Registering for Events
- *
- * The event bus provides the {@link EventBus#on} and {@link EventBus#once}
- * methods to register for events. {@link EventBus#off} can be used to
- * remove event registrations. Listeners receive an instance of {@link Event}
- * as the first argument. It allows them to hook into the event execution.
- *
- * ```javascript
- *
- * // listen for event
- * eventBus.on('foo', function(event) {
- *
- * // access event type
- * event.type; // 'foo'
- *
- * // stop propagation to other listeners
- * event.stopPropagation();
- *
- * // prevent event default
- * event.preventDefault();
- * });
- *
- * // listen for event with custom payload
- * eventBus.on('bar', function(event, payload) {
- * console.log(payload);
- * });
- *
- * // listen for event returning value
- * eventBus.on('foobar', function(event) {
- *
- * // stop event propagation + prevent default
- * return false;
- *
- * // stop event propagation + return custom result
- * return {
- * complex: 'listening result'
- * };
- * });
- *
- *
- * // listen with custom priority (default=1000, higher is better)
- * eventBus.on('priorityfoo', 1500, function(event) {
- * console.log('invoked first!');
- * });
- *
- *
- * // listen for event and pass the context (`this`)
- * eventBus.on('foobar', function(event) {
- * this.foo();
- * }, this);
- * ```
- *
- *
- * ## Emitting Events
- *
- * Events can be emitted via the event bus using {@link EventBus#fire}.
- *
- * ```javascript
- *
- * // false indicates that the default action
- * // was prevented by listeners
- * if (eventBus.fire('foo') === false) {
- * console.log('default has been prevented!');
- * };
- *
- *
- * // custom args + return value listener
- * eventBus.on('sum', function(event, a, b) {
- * return a + b;
- * });
- *
- * // you can pass custom arguments + retrieve result values.
- * var sum = eventBus.fire('sum', 1, 2);
- * console.log(sum); // 3
- * ```
- */
- function EventBus() {
- this._listeners = {};
- // cleanup on destroy on lowest priority to allow
- // message passing until the bitter end
- this.on('diagram.destroy', 1, this._destroy, this);
- }
- /**
- * Register an event listener for events with the given name.
- *
- * The callback will be invoked with `event, ...additionalArguments`
- * that have been passed to {@link EventBus#fire}.
- *
- * Returning false from a listener will prevent the events default action
- * (if any is specified). To stop an event from being processed further in
- * other listeners execute {@link Event#stopPropagation}.
- *
- * Returning anything but `undefined` from a listener will stop the listener propagation.
- *
- * @param {string|Array<string>} events
- * @param {number} [priority=1000] the priority in which this listener is called, larger is higher
- * @param {Function} callback
- * @param {Object} [that] Pass context (`this`) to the callback
- */
- EventBus.prototype.on = function(events, priority, callback, that) {
- events = isArray$2(events) ? events : [ events ];
- if (isFunction(priority)) {
- that = callback;
- callback = priority;
- priority = DEFAULT_PRIORITY$1;
- }
- if (!isNumber(priority)) {
- throw new Error('priority must be a number');
- }
- var actualCallback = callback;
- if (that) {
- actualCallback = bind(callback, that);
- // make sure we remember and are able to remove
- // bound callbacks via {@link #off} using the original
- // callback
- actualCallback[FN_REF] = callback[FN_REF] || callback;
- }
- var self = this;
- events.forEach(function(e) {
- self._addListener(e, {
- priority: priority,
- callback: actualCallback,
- next: null
- });
- });
- };
- /**
- * Register an event listener that is executed only once.
- *
- * @param {string} event the event name to register for
- * @param {number} [priority=1000] the priority in which this listener is called, larger is higher
- * @param {Function} callback the callback to execute
- * @param {Object} [that] Pass context (`this`) to the callback
- */
- EventBus.prototype.once = function(event, priority, callback, that) {
- var self = this;
- if (isFunction(priority)) {
- that = callback;
- callback = priority;
- priority = DEFAULT_PRIORITY$1;
- }
- if (!isNumber(priority)) {
- throw new Error('priority must be a number');
- }
- function wrappedCallback() {
- wrappedCallback.__isTomb = true;
- var result = callback.apply(that, arguments);
- self.off(event, wrappedCallback);
- return result;
- }
- // make sure we remember and are able to remove
- // bound callbacks via {@link #off} using the original
- // callback
- wrappedCallback[FN_REF] = callback;
- this.on(event, priority, wrappedCallback);
- };
- /**
- * Removes event listeners by event and callback.
- *
- * If no callback is given, all listeners for a given event name are being removed.
- *
- * @param {string|Array<string>} events
- * @param {Function} [callback]
- */
- EventBus.prototype.off = function(events, callback) {
- events = isArray$2(events) ? events : [ events ];
- var self = this;
- events.forEach(function(event) {
- self._removeListener(event, callback);
- });
- };
- /**
- * Create an EventBus event.
- *
- * @param {Object} data
- *
- * @return {Object} event, recognized by the eventBus
- */
- EventBus.prototype.createEvent = function(data) {
- var event = new InternalEvent();
- event.init(data);
- return event;
- };
- /**
- * Fires a named event.
- *
- * @example
- *
- * // fire event by name
- * events.fire('foo');
- *
- * // fire event object with nested type
- * var event = { type: 'foo' };
- * events.fire(event);
- *
- * // fire event with explicit type
- * var event = { x: 10, y: 20 };
- * events.fire('element.moved', event);
- *
- * // pass additional arguments to the event
- * events.on('foo', function(event, bar) {
- * alert(bar);
- * });
- *
- * events.fire({ type: 'foo' }, 'I am bar!');
- *
- * @param {string} [name] the optional event name
- * @param {Object} [event] the event object
- * @param {...Object} additional arguments to be passed to the callback functions
- *
- * @return {boolean} the events return value, if specified or false if the
- * default action was prevented by listeners
- */
- EventBus.prototype.fire = function(type, data) {
- var event,
- firstListener,
- returnValue,
- args;
- args = slice.call(arguments);
- if (typeof type === 'object') {
- data = type;
- type = data.type;
- }
- if (!type) {
- throw new Error('no event type specified');
- }
- firstListener = this._listeners[type];
- if (!firstListener) {
- return;
- }
- // we make sure we fire instances of our home made
- // events here. We wrap them only once, though
- if (data instanceof InternalEvent) {
- // we are fine, we alread have an event
- event = data;
- } else {
- event = this.createEvent(data);
- }
- // ensure we pass the event as the first parameter
- args[0] = event;
- // original event type (in case we delegate)
- var originalType = event.type;
- // update event type before delegation
- if (type !== originalType) {
- event.type = type;
- }
- try {
- returnValue = this._invokeListeners(event, args, firstListener);
- } finally {
- // reset event type after delegation
- if (type !== originalType) {
- event.type = originalType;
- }
- }
- // set the return value to false if the event default
- // got prevented and no other return value exists
- if (returnValue === undefined && event.defaultPrevented) {
- returnValue = false;
- }
- return returnValue;
- };
- EventBus.prototype.handleError = function(error) {
- return this.fire('error', { error: error }) === false;
- };
- EventBus.prototype._destroy = function() {
- this._listeners = {};
- };
- EventBus.prototype._invokeListeners = function(event, args, listener) {
- var returnValue;
- while (listener) {
- // handle stopped propagation
- if (event.cancelBubble) {
- break;
- }
- returnValue = this._invokeListener(event, args, listener);
- listener = listener.next;
- }
- return returnValue;
- };
- EventBus.prototype._invokeListener = function(event, args, listener) {
- var returnValue;
- if (listener.callback.__isTomb) {
- return returnValue;
- }
- try {
- // returning false prevents the default action
- returnValue = invokeFunction(listener.callback, args);
- // stop propagation on return value
- if (returnValue !== undefined) {
- event.returnValue = returnValue;
- event.stopPropagation();
- }
- // prevent default on return false
- if (returnValue === false) {
- event.preventDefault();
- }
- } catch (error) {
- if (!this.handleError(error)) {
- console.error('unhandled error in event listener', error);
- throw error;
- }
- }
- return returnValue;
- };
- /*
- * Add new listener with a certain priority to the list
- * of listeners (for the given event).
- *
- * The semantics of listener registration / listener execution are
- * first register, first serve: New listeners will always be inserted
- * after existing listeners with the same priority.
- *
- * Example: Inserting two listeners with priority 1000 and 1300
- *
- * * before: [ 1500, 1500, 1000, 1000 ]
- * * after: [ 1500, 1500, (new=1300), 1000, 1000, (new=1000) ]
- *
- * @param {string} event
- * @param {Object} listener { priority, callback }
- */
- EventBus.prototype._addListener = function(event, newListener) {
- var listener = this._getListeners(event),
- previousListener;
- // no prior listeners
- if (!listener) {
- this._setListeners(event, newListener);
- return;
- }
- // ensure we order listeners by priority from
- // 0 (high) to n > 0 (low)
- while (listener) {
- if (listener.priority < newListener.priority) {
- newListener.next = listener;
- if (previousListener) {
- previousListener.next = newListener;
- } else {
- this._setListeners(event, newListener);
- }
- return;
- }
- previousListener = listener;
- listener = listener.next;
- }
- // add new listener to back
- previousListener.next = newListener;
- };
- EventBus.prototype._getListeners = function(name) {
- return this._listeners[name];
- };
- EventBus.prototype._setListeners = function(name, listener) {
- this._listeners[name] = listener;
- };
- EventBus.prototype._removeListener = function(event, callback) {
- var listener = this._getListeners(event),
- nextListener,
- previousListener,
- listenerCallback;
- if (!callback) {
- // clear listeners
- this._setListeners(event, null);
- return;
- }
- while (listener) {
- nextListener = listener.next;
- listenerCallback = listener.callback;
- if (listenerCallback === callback || listenerCallback[FN_REF] === callback) {
- if (previousListener) {
- previousListener.next = nextListener;
- } else {
- // new first listener
- this._setListeners(event, nextListener);
- }
- }
- previousListener = listener;
- listener = nextListener;
- }
- };
- /**
- * A event that is emitted via the event bus.
- */
- function InternalEvent() { }
- InternalEvent.prototype.stopPropagation = function() {
- this.cancelBubble = true;
- };
- InternalEvent.prototype.preventDefault = function() {
- this.defaultPrevented = true;
- };
- InternalEvent.prototype.init = function(data) {
- assign(this, data || {});
- };
- /**
- * Invoke function. Be fast...
- *
- * @param {Function} fn
- * @param {Array<Object>} args
- *
- * @return {Any}
- */
- function invokeFunction(fn, args) {
- return fn.apply(null, args);
- }
- /**
- * SVGs for elements are generated by the {@link GraphicsFactory}.
- *
- * This utility gives quick access to the important semantic
- * parts of an element.
- */
- /**
- * Returns the visual part of a diagram element
- *
- * @param {Snap<SVGElement>} gfx
- *
- * @return {Snap<SVGElement>}
- */
- function getVisual(gfx) {
- return gfx.childNodes[0];
- }
- /**
- * Returns the children for a given diagram element.
- *
- * @param {Snap<SVGElement>} gfx
- * @return {Snap<SVGElement>}
- */
- function getChildren(gfx) {
- return gfx.parentNode.childNodes[1];
- }
- /**
- * A factory that creates graphical elements
- *
- * @param {EventBus} eventBus
- * @param {ElementRegistry} elementRegistry
- */
- function GraphicsFactory(eventBus, elementRegistry) {
- this._eventBus = eventBus;
- this._elementRegistry = elementRegistry;
- }
- GraphicsFactory.$inject = [ 'eventBus' , 'elementRegistry' ];
- GraphicsFactory.prototype._getChildrenContainer = function(element) {
- var gfx = this._elementRegistry.getGraphics(element);
- var childrenGfx;
- // root element
- if (!element.parent) {
- childrenGfx = gfx;
- } else {
- childrenGfx = getChildren(gfx);
- if (!childrenGfx) {
- childrenGfx = create$1('g');
- classes$1(childrenGfx).add('djs-children');
- append(gfx.parentNode, childrenGfx);
- }
- }
- return childrenGfx;
- };
- /**
- * Clears the graphical representation of the element and returns the
- * cleared visual (the <g class="djs-visual" /> element).
- */
- GraphicsFactory.prototype._clear = function(gfx) {
- var visual = getVisual(gfx);
- clear(visual);
- return visual;
- };
- /**
- * Creates a gfx container for shapes and connections
- *
- * The layout is as follows:
- *
- * <g class="djs-group">
- *
- * <!-- the gfx -->
- * <g class="djs-element djs-(shape|connection|frame)">
- * <g class="djs-visual">
- * <!-- the renderer draws in here -->
- * </g>
- *
- * <!-- extensions (overlays, click box, ...) goes here
- * </g>
- *
- * <!-- the gfx child nodes -->
- * <g class="djs-children"></g>
- * </g>
- *
- * @param {string} type the type of the element, i.e. shape | connection
- * @param {SVGElement} [childrenGfx]
- * @param {number} [parentIndex] position to create container in parent
- * @param {boolean} [isFrame] is frame element
- *
- * @return {SVGElement}
- */
- GraphicsFactory.prototype._createContainer = function(
- type, childrenGfx, parentIndex, isFrame
- ) {
- var outerGfx = create$1('g');
- classes$1(outerGfx).add('djs-group');
- // insert node at position
- if (typeof parentIndex !== 'undefined') {
- prependTo(outerGfx, childrenGfx, childrenGfx.childNodes[parentIndex]);
- } else {
- append(childrenGfx, outerGfx);
- }
- var gfx = create$1('g');
- classes$1(gfx).add('djs-element');
- classes$1(gfx).add('djs-' + type);
- if (isFrame) {
- classes$1(gfx).add('djs-frame');
- }
- append(outerGfx, gfx);
- // create visual
- var visual = create$1('g');
- classes$1(visual).add('djs-visual');
- append(gfx, visual);
- return gfx;
- };
- GraphicsFactory.prototype.create = function(type, element, parentIndex) {
- var childrenGfx = this._getChildrenContainer(element.parent);
- return this._createContainer(type, childrenGfx, parentIndex, isFrameElement(element));
- };
- GraphicsFactory.prototype.updateContainments = function(elements) {
- var self = this,
- elementRegistry = this._elementRegistry,
- parents;
- parents = reduce(elements, function(map, e) {
- if (e.parent) {
- map[e.parent.id] = e.parent;
- }
- return map;
- }, {});
- // update all parents of changed and reorganized their children
- // in the correct order (as indicated in our model)
- forEach$1(parents, function(parent) {
- var children = parent.children;
- if (!children) {
- return;
- }
- var childrenGfx = self._getChildrenContainer(parent);
- forEach$1(children.slice().reverse(), function(child) {
- var childGfx = elementRegistry.getGraphics(child);
- prependTo(childGfx.parentNode, childrenGfx);
- });
- });
- };
- GraphicsFactory.prototype.drawShape = function(visual, element) {
- var eventBus = this._eventBus;
- return eventBus.fire('render.shape', { gfx: visual, element: element });
- };
- GraphicsFactory.prototype.getShapePath = function(element) {
- var eventBus = this._eventBus;
- return eventBus.fire('render.getShapePath', element);
- };
- GraphicsFactory.prototype.drawConnection = function(visual, element) {
- var eventBus = this._eventBus;
- return eventBus.fire('render.connection', { gfx: visual, element: element });
- };
- GraphicsFactory.prototype.getConnectionPath = function(waypoints) {
- var eventBus = this._eventBus;
- return eventBus.fire('render.getConnectionPath', waypoints);
- };
- GraphicsFactory.prototype.update = function(type, element, gfx) {
- // do NOT update root element
- if (!element.parent) {
- return;
- }
- var visual = this._clear(gfx);
- // redraw
- if (type === 'shape') {
- this.drawShape(visual, element);
- // update positioning
- translate$1(gfx, element.x, element.y);
- } else
- if (type === 'connection') {
- this.drawConnection(visual, element);
- } else {
- throw new Error('unknown type: ' + type);
- }
- if (element.hidden) {
- attr$1(gfx, 'display', 'none');
- } else {
- attr$1(gfx, 'display', 'block');
- }
- };
- GraphicsFactory.prototype.remove = function(element) {
- var gfx = this._elementRegistry.getGraphics(element);
- // remove
- remove$2(gfx.parentNode);
- };
- // helpers //////////
- function prependTo(newNode, parentNode, siblingNode) {
- var node = siblingNode || parentNode.firstChild;
- // do not prepend node to itself to prevent IE from crashing
- // https://github.com/bpmn-io/bpmn-js/issues/746
- if (newNode === node) {
- return;
- }
- parentNode.insertBefore(newNode, node);
- }
- var CoreModule = {
- __depends__: [ DrawModule ],
- __init__: [ 'canvas' ],
- canvas: [ 'type', Canvas ],
- elementRegistry: [ 'type', ElementRegistry ],
- elementFactory: [ 'type', ElementFactory ],
- eventBus: [ 'type', EventBus ],
- graphicsFactory: [ 'type', GraphicsFactory ]
- };
- /**
- * @typedef { import('didi').ModuleDeclaration } Module
- */
- /**
- * Bootstrap an injector from a list of modules, instantiating a number of default components
- *
- * @param {Array<Module>} modules
- *
- * @return {Injector} a injector to use to access the components
- */
- function bootstrap(modules) {
- var injector = new Injector(modules);
- injector.init();
- return injector;
- }
- /**
- * Creates an injector from passed options.
- *
- * @param {Object} options
- * @return {Injector}
- */
- function createInjector(options) {
- options = options || {};
- var configModule = {
- 'config': [ 'value', options ]
- };
- var modules = [ configModule, CoreModule ].concat(options.modules || []);
- return bootstrap(modules);
- }
- /**
- * The main diagram-js entry point that bootstraps the diagram with the given
- * configuration.
- *
- * To register extensions with the diagram, pass them as Array<Module> to the constructor.
- *
- * @class djs.Diagram
- * @memberOf djs
- * @constructor
- *
- * @example
- *
- * <caption>Creating a plug-in that logs whenever a shape is added to the canvas.</caption>
- *
- * // plug-in implemenentation
- * function MyLoggingPlugin(eventBus) {
- * eventBus.on('shape.added', function(event) {
- * console.log('shape ', event.shape, ' was added to the diagram');
- * });
- * }
- *
- * // export as module
- * export default {
- * __init__: [ 'myLoggingPlugin' ],
- * myLoggingPlugin: [ 'type', MyLoggingPlugin ]
- * };
- *
- *
- * // instantiate the diagram with the new plug-in
- *
- * import MyLoggingModule from 'path-to-my-logging-plugin';
- *
- * var diagram = new Diagram({
- * modules: [
- * MyLoggingModule
- * ]
- * });
- *
- * diagram.invoke([ 'canvas', function(canvas) {
- * // add shape to drawing canvas
- * canvas.addShape({ x: 10, y: 10 });
- * });
- *
- * // 'shape ... was added to the diagram' logged to console
- *
- * @param {Object} options
- * @param {Array<Module>} [options.modules] external modules to instantiate with the diagram
- * @param {Injector} [injector] an (optional) injector to bootstrap the diagram with
- */
- function Diagram(options, injector) {
- // create injector unless explicitly specified
- this.injector = injector = injector || createInjector(options);
- // API
- /**
- * Resolves a diagram service
- *
- * @method Diagram#get
- *
- * @param {string} name the name of the diagram service to be retrieved
- * @param {boolean} [strict=true] if false, resolve missing services to null
- */
- this.get = injector.get;
- /**
- * Executes a function into which diagram services are injected
- *
- * @method Diagram#invoke
- *
- * @param {Function|Object[]} fn the function to resolve
- * @param {Object} locals a number of locals to use to resolve certain dependencies
- */
- this.invoke = injector.invoke;
- // init
- // indicate via event
- /**
- * An event indicating that all plug-ins are loaded.
- *
- * Use this event to fire other events to interested plug-ins
- *
- * @memberOf Diagram
- *
- * @event diagram.init
- *
- * @example
- *
- * eventBus.on('diagram.init', function() {
- * eventBus.fire('my-custom-event', { foo: 'BAR' });
- * });
- *
- * @type {Object}
- */
- this.get('eventBus').fire('diagram.init');
- }
- /**
- * Destroys the diagram
- *
- * @method Diagram#destroy
- */
- Diagram.prototype.destroy = function() {
- this.get('eventBus').fire('diagram.destroy');
- };
- /**
- * Clear the diagram, removing all contents.
- */
- Diagram.prototype.clear = function() {
- this.get('eventBus').fire('diagram.clear');
- };
- /**
- * Moddle base element.
- */
- function Base() { }
- Base.prototype.get = function(name) {
- return this.$model.properties.get(this, name);
- };
- Base.prototype.set = function(name, value) {
- this.$model.properties.set(this, name, value);
- };
- /**
- * A model element factory.
- *
- * @param {Moddle} model
- * @param {Properties} properties
- */
- function Factory(model, properties) {
- this.model = model;
- this.properties = properties;
- }
- Factory.prototype.createType = function(descriptor) {
- var model = this.model;
- var props = this.properties,
- prototype = Object.create(Base.prototype);
- // initialize default values
- forEach$1(descriptor.properties, function(p) {
- if (!p.isMany && p.default !== undefined) {
- prototype[p.name] = p.default;
- }
- });
- props.defineModel(prototype, model);
- props.defineDescriptor(prototype, descriptor);
- var name = descriptor.ns.name;
- /**
- * The new type constructor
- */
- function ModdleElement(attrs) {
- props.define(this, '$type', { value: name, enumerable: true });
- props.define(this, '$attrs', { value: {} });
- props.define(this, '$parent', { writable: true });
- forEach$1(attrs, bind(function(val, key) {
- this.set(key, val);
- }, this));
- }
- ModdleElement.prototype = prototype;
- ModdleElement.hasType = prototype.$instanceOf = this.model.hasType;
- // static links
- props.defineModel(ModdleElement, model);
- props.defineDescriptor(ModdleElement, descriptor);
- return ModdleElement;
- };
- /**
- * Built-in moddle types
- */
- var BUILTINS = {
- String: true,
- Boolean: true,
- Integer: true,
- Real: true,
- Element: true
- };
- /**
- * Converters for built in types from string representations
- */
- var TYPE_CONVERTERS = {
- String: function(s) { return s; },
- Boolean: function(s) { return s === 'true'; },
- Integer: function(s) { return parseInt(s, 10); },
- Real: function(s) { return parseFloat(s); }
- };
- /**
- * Convert a type to its real representation
- */
- function coerceType(type, value) {
- var converter = TYPE_CONVERTERS[type];
- if (converter) {
- return converter(value);
- } else {
- return value;
- }
- }
- /**
- * Return whether the given type is built-in
- */
- function isBuiltIn(type) {
- return !!BUILTINS[type];
- }
- /**
- * Return whether the given type is simple
- */
- function isSimple(type) {
- return !!TYPE_CONVERTERS[type];
- }
- /**
- * Parses a namespaced attribute name of the form (ns:)localName to an object,
- * given a default prefix to assume in case no explicit namespace is given.
- *
- * @param {String} name
- * @param {String} [defaultPrefix] the default prefix to take, if none is present.
- *
- * @return {Object} the parsed name
- */
- function parseName(name, defaultPrefix) {
- var parts = name.split(/:/),
- localName, prefix;
- // no prefix (i.e. only local name)
- if (parts.length === 1) {
- localName = name;
- prefix = defaultPrefix;
- } else
- // prefix + local name
- if (parts.length === 2) {
- localName = parts[1];
- prefix = parts[0];
- } else {
- throw new Error('expected <prefix:localName> or <localName>, got ' + name);
- }
- name = (prefix ? prefix + ':' : '') + localName;
- return {
- name: name,
- prefix: prefix,
- localName: localName
- };
- }
- /**
- * A utility to build element descriptors.
- */
- function DescriptorBuilder(nameNs) {
- this.ns = nameNs;
- this.name = nameNs.name;
- this.allTypes = [];
- this.allTypesByName = {};
- this.properties = [];
- this.propertiesByName = {};
- }
- DescriptorBuilder.prototype.build = function() {
- return pick(this, [
- 'ns',
- 'name',
- 'allTypes',
- 'allTypesByName',
- 'properties',
- 'propertiesByName',
- 'bodyProperty',
- 'idProperty'
- ]);
- };
- /**
- * Add property at given index.
- *
- * @param {Object} p
- * @param {Number} [idx]
- * @param {Boolean} [validate=true]
- */
- DescriptorBuilder.prototype.addProperty = function(p, idx, validate) {
- if (typeof idx === 'boolean') {
- validate = idx;
- idx = undefined;
- }
- this.addNamedProperty(p, validate !== false);
- var properties = this.properties;
- if (idx !== undefined) {
- properties.splice(idx, 0, p);
- } else {
- properties.push(p);
- }
- };
- DescriptorBuilder.prototype.replaceProperty = function(oldProperty, newProperty, replace) {
- var oldNameNs = oldProperty.ns;
- var props = this.properties,
- propertiesByName = this.propertiesByName,
- rename = oldProperty.name !== newProperty.name;
- if (oldProperty.isId) {
- if (!newProperty.isId) {
- throw new Error(
- 'property <' + newProperty.ns.name + '> must be id property ' +
- 'to refine <' + oldProperty.ns.name + '>');
- }
- this.setIdProperty(newProperty, false);
- }
- if (oldProperty.isBody) {
- if (!newProperty.isBody) {
- throw new Error(
- 'property <' + newProperty.ns.name + '> must be body property ' +
- 'to refine <' + oldProperty.ns.name + '>');
- }
- // TODO: Check compatibility
- this.setBodyProperty(newProperty, false);
- }
- // validate existence and get location of old property
- var idx = props.indexOf(oldProperty);
- if (idx === -1) {
- throw new Error('property <' + oldNameNs.name + '> not found in property list');
- }
- // remove old property
- props.splice(idx, 1);
- // replacing the named property is intentional
- //
- // * validate only if this is a "rename" operation
- // * add at specific index unless we "replace"
- //
- this.addProperty(newProperty, replace ? undefined : idx, rename);
- // make new property available under old name
- propertiesByName[oldNameNs.name] = propertiesByName[oldNameNs.localName] = newProperty;
- };
- DescriptorBuilder.prototype.redefineProperty = function(p, targetPropertyName, replace) {
- var nsPrefix = p.ns.prefix;
- var parts = targetPropertyName.split('#');
- var name = parseName(parts[0], nsPrefix);
- var attrName = parseName(parts[1], name.prefix).name;
- var redefinedProperty = this.propertiesByName[attrName];
- if (!redefinedProperty) {
- throw new Error('refined property <' + attrName + '> not found');
- } else {
- this.replaceProperty(redefinedProperty, p, replace);
- }
- delete p.redefines;
- };
- DescriptorBuilder.prototype.addNamedProperty = function(p, validate) {
- var ns = p.ns,
- propsByName = this.propertiesByName;
- if (validate) {
- this.assertNotDefined(p, ns.name);
- this.assertNotDefined(p, ns.localName);
- }
- propsByName[ns.name] = propsByName[ns.localName] = p;
- };
- DescriptorBuilder.prototype.removeNamedProperty = function(p) {
- var ns = p.ns,
- propsByName = this.propertiesByName;
- delete propsByName[ns.name];
- delete propsByName[ns.localName];
- };
- DescriptorBuilder.prototype.setBodyProperty = function(p, validate) {
- if (validate && this.bodyProperty) {
- throw new Error(
- 'body property defined multiple times ' +
- '(<' + this.bodyProperty.ns.name + '>, <' + p.ns.name + '>)');
- }
- this.bodyProperty = p;
- };
- DescriptorBuilder.prototype.setIdProperty = function(p, validate) {
- if (validate && this.idProperty) {
- throw new Error(
- 'id property defined multiple times ' +
- '(<' + this.idProperty.ns.name + '>, <' + p.ns.name + '>)');
- }
- this.idProperty = p;
- };
- DescriptorBuilder.prototype.assertNotDefined = function(p, name) {
- var propertyName = p.name,
- definedProperty = this.propertiesByName[propertyName];
- if (definedProperty) {
- throw new Error(
- 'property <' + propertyName + '> already defined; ' +
- 'override of <' + definedProperty.definedBy.ns.name + '#' + definedProperty.ns.name + '> by ' +
- '<' + p.definedBy.ns.name + '#' + p.ns.name + '> not allowed without redefines');
- }
- };
- DescriptorBuilder.prototype.hasProperty = function(name) {
- return this.propertiesByName[name];
- };
- DescriptorBuilder.prototype.addTrait = function(t, inherited) {
- var typesByName = this.allTypesByName,
- types = this.allTypes;
- var typeName = t.name;
- if (typeName in typesByName) {
- return;
- }
- forEach$1(t.properties, bind(function(p) {
- // clone property to allow extensions
- p = assign({}, p, {
- name: p.ns.localName,
- inherited: inherited
- });
- Object.defineProperty(p, 'definedBy', {
- value: t
- });
- var replaces = p.replaces,
- redefines = p.redefines;
- // add replace/redefine support
- if (replaces || redefines) {
- this.redefineProperty(p, replaces || redefines, replaces);
- } else {
- if (p.isBody) {
- this.setBodyProperty(p);
- }
- if (p.isId) {
- this.setIdProperty(p);
- }
- this.addProperty(p);
- }
- }, this));
- types.push(t);
- typesByName[typeName] = t;
- };
- /**
- * A registry of Moddle packages.
- *
- * @param {Array<Package>} packages
- * @param {Properties} properties
- */
- function Registry(packages, properties) {
- this.packageMap = {};
- this.typeMap = {};
- this.packages = [];
- this.properties = properties;
- forEach$1(packages, bind(this.registerPackage, this));
- }
- Registry.prototype.getPackage = function(uriOrPrefix) {
- return this.packageMap[uriOrPrefix];
- };
- Registry.prototype.getPackages = function() {
- return this.packages;
- };
- Registry.prototype.registerPackage = function(pkg) {
- // copy package
- pkg = assign({}, pkg);
- var pkgMap = this.packageMap;
- ensureAvailable(pkgMap, pkg, 'prefix');
- ensureAvailable(pkgMap, pkg, 'uri');
- // register types
- forEach$1(pkg.types, bind(function(descriptor) {
- this.registerType(descriptor, pkg);
- }, this));
- pkgMap[pkg.uri] = pkgMap[pkg.prefix] = pkg;
- this.packages.push(pkg);
- };
- /**
- * Register a type from a specific package with us
- */
- Registry.prototype.registerType = function(type, pkg) {
- type = assign({}, type, {
- superClass: (type.superClass || []).slice(),
- extends: (type.extends || []).slice(),
- properties: (type.properties || []).slice(),
- meta: assign((type.meta || {}))
- });
- var ns = parseName(type.name, pkg.prefix),
- name = ns.name,
- propertiesByName = {};
- // parse properties
- forEach$1(type.properties, bind(function(p) {
- // namespace property names
- var propertyNs = parseName(p.name, ns.prefix),
- propertyName = propertyNs.name;
- // namespace property types
- if (!isBuiltIn(p.type)) {
- p.type = parseName(p.type, propertyNs.prefix).name;
- }
- assign(p, {
- ns: propertyNs,
- name: propertyName
- });
- propertiesByName[propertyName] = p;
- }, this));
- // update ns + name
- assign(type, {
- ns: ns,
- name: name,
- propertiesByName: propertiesByName
- });
- forEach$1(type.extends, bind(function(extendsName) {
- var extended = this.typeMap[extendsName];
- extended.traits = extended.traits || [];
- extended.traits.push(name);
- }, this));
- // link to package
- this.definePackage(type, pkg);
- // register
- this.typeMap[name] = type;
- };
- /**
- * Traverse the type hierarchy from bottom to top,
- * calling iterator with (type, inherited) for all elements in
- * the inheritance chain.
- *
- * @param {Object} nsName
- * @param {Function} iterator
- * @param {Boolean} [trait=false]
- */
- Registry.prototype.mapTypes = function(nsName, iterator, trait) {
- var type = isBuiltIn(nsName.name) ? { name: nsName.name } : this.typeMap[nsName.name];
- var self = this;
- /**
- * Traverse the selected trait.
- *
- * @param {String} cls
- */
- function traverseTrait(cls) {
- return traverseSuper(cls, true);
- }
- /**
- * Traverse the selected super type or trait
- *
- * @param {String} cls
- * @param {Boolean} [trait=false]
- */
- function traverseSuper(cls, trait) {
- var parentNs = parseName(cls, isBuiltIn(cls) ? '' : nsName.prefix);
- self.mapTypes(parentNs, iterator, trait);
- }
- if (!type) {
- throw new Error('unknown type <' + nsName.name + '>');
- }
- forEach$1(type.superClass, trait ? traverseTrait : traverseSuper);
- // call iterator with (type, inherited=!trait)
- iterator(type, !trait);
- forEach$1(type.traits, traverseTrait);
- };
- /**
- * Returns the effective descriptor for a type.
- *
- * @param {String} type the namespaced name (ns:localName) of the type
- *
- * @return {Descriptor} the resulting effective descriptor
- */
- Registry.prototype.getEffectiveDescriptor = function(name) {
- var nsName = parseName(name);
- var builder = new DescriptorBuilder(nsName);
- this.mapTypes(nsName, function(type, inherited) {
- builder.addTrait(type, inherited);
- });
- var descriptor = builder.build();
- // define package link
- this.definePackage(descriptor, descriptor.allTypes[descriptor.allTypes.length - 1].$pkg);
- return descriptor;
- };
- Registry.prototype.definePackage = function(target, pkg) {
- this.properties.define(target, '$pkg', { value: pkg });
- };
- ///////// helpers ////////////////////////////
- function ensureAvailable(packageMap, pkg, identifierKey) {
- var value = pkg[identifierKey];
- if (value in packageMap) {
- throw new Error('package with ' + identifierKey + ' <' + value + '> already defined');
- }
- }
- /**
- * A utility that gets and sets properties of model elements.
- *
- * @param {Model} model
- */
- function Properties(model) {
- this.model = model;
- }
- /**
- * Sets a named property on the target element.
- * If the value is undefined, the property gets deleted.
- *
- * @param {Object} target
- * @param {String} name
- * @param {Object} value
- */
- Properties.prototype.set = function(target, name, value) {
- var property = this.model.getPropertyDescriptor(target, name);
- var propertyName = property && property.name;
- if (isUndefined(value)) {
- // unset the property, if the specified value is undefined;
- // delete from $attrs (for extensions) or the target itself
- if (property) {
- delete target[propertyName];
- } else {
- delete target.$attrs[name];
- }
- } else {
- // set the property, defining well defined properties on the fly
- // or simply updating them in target.$attrs (for extensions)
- if (property) {
- if (propertyName in target) {
- target[propertyName] = value;
- } else {
- defineProperty(target, property, value);
- }
- } else {
- target.$attrs[name] = value;
- }
- }
- };
- /**
- * Returns the named property of the given element
- *
- * @param {Object} target
- * @param {String} name
- *
- * @return {Object}
- */
- Properties.prototype.get = function(target, name) {
- var property = this.model.getPropertyDescriptor(target, name);
- if (!property) {
- return target.$attrs[name];
- }
- var propertyName = property.name;
- // check if access to collection property and lazily initialize it
- if (!target[propertyName] && property.isMany) {
- defineProperty(target, property, []);
- }
- return target[propertyName];
- };
- /**
- * Define a property on the target element
- *
- * @param {Object} target
- * @param {String} name
- * @param {Object} options
- */
- Properties.prototype.define = function(target, name, options) {
- Object.defineProperty(target, name, options);
- };
- /**
- * Define the descriptor for an element
- */
- Properties.prototype.defineDescriptor = function(target, descriptor) {
- this.define(target, '$descriptor', { value: descriptor });
- };
- /**
- * Define the model for an element
- */
- Properties.prototype.defineModel = function(target, model) {
- this.define(target, '$model', { value: model });
- };
- function isUndefined(val) {
- return typeof val === 'undefined';
- }
- function defineProperty(target, property, value) {
- Object.defineProperty(target, property.name, {
- enumerable: !property.isReference,
- writable: true,
- value: value,
- configurable: true
- });
- }
- //// Moddle implementation /////////////////////////////////////////////////
- /**
- * @class Moddle
- *
- * A model that can be used to create elements of a specific type.
- *
- * @example
- *
- * var Moddle = require('moddle');
- *
- * var pkg = {
- * name: 'mypackage',
- * prefix: 'my',
- * types: [
- * { name: 'Root' }
- * ]
- * };
- *
- * var moddle = new Moddle([pkg]);
- *
- * @param {Array<Package>} packages the packages to contain
- */
- function Moddle(packages) {
- this.properties = new Properties(this);
- this.factory = new Factory(this, this.properties);
- this.registry = new Registry(packages, this.properties);
- this.typeCache = {};
- }
- /**
- * Create an instance of the specified type.
- *
- * @method Moddle#create
- *
- * @example
- *
- * var foo = moddle.create('my:Foo');
- * var bar = moddle.create('my:Bar', { id: 'BAR_1' });
- *
- * @param {String|Object} descriptor the type descriptor or name know to the model
- * @param {Object} attrs a number of attributes to initialize the model instance with
- * @return {Object} model instance
- */
- Moddle.prototype.create = function(descriptor, attrs) {
- var Type = this.getType(descriptor);
- if (!Type) {
- throw new Error('unknown type <' + descriptor + '>');
- }
- return new Type(attrs);
- };
- /**
- * Returns the type representing a given descriptor
- *
- * @method Moddle#getType
- *
- * @example
- *
- * var Foo = moddle.getType('my:Foo');
- * var foo = new Foo({ 'id' : 'FOO_1' });
- *
- * @param {String|Object} descriptor the type descriptor or name know to the model
- * @return {Object} the type representing the descriptor
- */
- Moddle.prototype.getType = function(descriptor) {
- var cache = this.typeCache;
- var name = isString(descriptor) ? descriptor : descriptor.ns.name;
- var type = cache[name];
- if (!type) {
- descriptor = this.registry.getEffectiveDescriptor(name);
- type = cache[name] = this.factory.createType(descriptor);
- }
- return type;
- };
- /**
- * Creates an any-element type to be used within model instances.
- *
- * This can be used to create custom elements that lie outside the meta-model.
- * The created element contains all the meta-data required to serialize it
- * as part of meta-model elements.
- *
- * @method Moddle#createAny
- *
- * @example
- *
- * var foo = moddle.createAny('vendor:Foo', 'http://vendor', {
- * value: 'bar'
- * });
- *
- * var container = moddle.create('my:Container', 'http://my', {
- * any: [ foo ]
- * });
- *
- * // go ahead and serialize the stuff
- *
- *
- * @param {String} name the name of the element
- * @param {String} nsUri the namespace uri of the element
- * @param {Object} [properties] a map of properties to initialize the instance with
- * @return {Object} the any type instance
- */
- Moddle.prototype.createAny = function(name, nsUri, properties) {
- var nameNs = parseName(name);
- var element = {
- $type: name,
- $instanceOf: function(type) {
- return type === this.$type;
- }
- };
- var descriptor = {
- name: name,
- isGeneric: true,
- ns: {
- prefix: nameNs.prefix,
- localName: nameNs.localName,
- uri: nsUri
- }
- };
- this.properties.defineDescriptor(element, descriptor);
- this.properties.defineModel(element, this);
- this.properties.define(element, '$parent', { enumerable: false, writable: true });
- this.properties.define(element, '$instanceOf', { enumerable: false, writable: true });
- forEach$1(properties, function(a, key) {
- if (isObject(a) && a.value !== undefined) {
- element[a.name] = a.value;
- } else {
- element[key] = a;
- }
- });
- return element;
- };
- /**
- * Returns a registered package by uri or prefix
- *
- * @return {Object} the package
- */
- Moddle.prototype.getPackage = function(uriOrPrefix) {
- return this.registry.getPackage(uriOrPrefix);
- };
- /**
- * Returns a snapshot of all known packages
- *
- * @return {Object} the package
- */
- Moddle.prototype.getPackages = function() {
- return this.registry.getPackages();
- };
- /**
- * Returns the descriptor for an element
- */
- Moddle.prototype.getElementDescriptor = function(element) {
- return element.$descriptor;
- };
- /**
- * Returns true if the given descriptor or instance
- * represents the given type.
- *
- * May be applied to this, if element is omitted.
- */
- Moddle.prototype.hasType = function(element, type) {
- if (type === undefined) {
- type = element;
- element = this;
- }
- var descriptor = element.$model.getElementDescriptor(element);
- return (type in descriptor.allTypesByName);
- };
- /**
- * Returns the descriptor of an elements named property
- */
- Moddle.prototype.getPropertyDescriptor = function(element, property) {
- return this.getElementDescriptor(element).propertiesByName[property];
- };
- /**
- * Returns a mapped type's descriptor
- */
- Moddle.prototype.getTypeDescriptor = function(type) {
- return this.registry.typeMap[type];
- };
- var fromCharCode = String.fromCharCode;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var ENTITY_PATTERN = /&#(\d+);|&#x([0-9a-f]+);|&(\w+);/ig;
- var ENTITY_MAPPING = {
- 'amp': '&',
- 'apos': '\'',
- 'gt': '>',
- 'lt': '<',
- 'quot': '"'
- };
- // map UPPERCASE variants of supported special chars
- Object.keys(ENTITY_MAPPING).forEach(function(k) {
- ENTITY_MAPPING[k.toUpperCase()] = ENTITY_MAPPING[k];
- });
- function replaceEntities(_, d, x, z) {
- // reserved names, i.e.
- if (z) {
- if (hasOwnProperty.call(ENTITY_MAPPING, z)) {
- return ENTITY_MAPPING[z];
- } else {
- // fall back to original value
- return '&' + z + ';';
- }
- }
- // decimal encoded char
- if (d) {
- return fromCharCode(d);
- }
- // hex encoded char
- return fromCharCode(parseInt(x, 16));
- }
- /**
- * A basic entity decoder that can decode a minimal
- * sub-set of reserved names (&) as well as
- * hex (ય) and decimal (ӏ) encoded characters.
- *
- * @param {string} str
- *
- * @return {string} decoded string
- */
- function decodeEntities(s) {
- if (s.length > 3 && s.indexOf('&') !== -1) {
- return s.replace(ENTITY_PATTERN, replaceEntities);
- }
- return s;
- }
- var XSI_URI = 'http://www.w3.org/2001/XMLSchema-instance';
- var XSI_PREFIX = 'xsi';
- var XSI_TYPE$1 = 'xsi:type';
- var NON_WHITESPACE_OUTSIDE_ROOT_NODE = 'non-whitespace outside of root node';
- function error$1(msg) {
- return new Error(msg);
- }
- function missingNamespaceForPrefix(prefix) {
- return 'missing namespace for prefix <' + prefix + '>';
- }
- function getter(getFn) {
- return {
- 'get': getFn,
- 'enumerable': true
- };
- }
- function cloneNsMatrix(nsMatrix) {
- var clone = {}, key;
- for (key in nsMatrix) {
- clone[key] = nsMatrix[key];
- }
- return clone;
- }
- function uriPrefix(prefix) {
- return prefix + '$uri';
- }
- function buildNsMatrix(nsUriToPrefix) {
- var nsMatrix = {},
- uri,
- prefix;
- for (uri in nsUriToPrefix) {
- prefix = nsUriToPrefix[uri];
- nsMatrix[prefix] = prefix;
- nsMatrix[uriPrefix(prefix)] = uri;
- }
- return nsMatrix;
- }
- function noopGetContext() {
- return { 'line': 0, 'column': 0 };
- }
- function throwFunc(err) {
- throw err;
- }
- /**
- * Creates a new parser with the given options.
- *
- * @constructor
- *
- * @param {!Object<string, ?>=} options
- */
- function Parser(options) {
- if (!this) {
- return new Parser(options);
- }
- var proxy = options && options['proxy'];
- var onText,
- onOpenTag,
- onCloseTag,
- onCDATA,
- onError = throwFunc,
- onWarning,
- onComment,
- onQuestion,
- onAttention;
- var getContext = noopGetContext;
- /**
- * Do we need to parse the current elements attributes for namespaces?
- *
- * @type {boolean}
- */
- var maybeNS = false;
- /**
- * Do we process namespaces at all?
- *
- * @type {boolean}
- */
- var isNamespace = false;
- /**
- * The caught error returned on parse end
- *
- * @type {Error}
- */
- var returnError = null;
- /**
- * Should we stop parsing?
- *
- * @type {boolean}
- */
- var parseStop = false;
- /**
- * A map of { uri: prefix } used by the parser.
- *
- * This map will ensure we can normalize prefixes during processing;
- * for each uri, only one prefix will be exposed to the handlers.
- *
- * @type {!Object<string, string>}}
- */
- var nsUriToPrefix;
- /**
- * Handle parse error.
- *
- * @param {string|Error} err
- */
- function handleError(err) {
- if (!(err instanceof Error)) {
- err = error$1(err);
- }
- returnError = err;
- onError(err, getContext);
- }
- /**
- * Handle parse error.
- *
- * @param {string|Error} err
- */
- function handleWarning(err) {
- if (!onWarning) {
- return;
- }
- if (!(err instanceof Error)) {
- err = error$1(err);
- }
- onWarning(err, getContext);
- }
- /**
- * Register parse listener.
- *
- * @param {string} name
- * @param {Function} cb
- *
- * @return {Parser}
- */
- this['on'] = function(name, cb) {
- if (typeof cb !== 'function') {
- throw error$1('required args <name, cb>');
- }
- switch (name) {
- case 'openTag': onOpenTag = cb; break;
- case 'text': onText = cb; break;
- case 'closeTag': onCloseTag = cb; break;
- case 'error': onError = cb; break;
- case 'warn': onWarning = cb; break;
- case 'cdata': onCDATA = cb; break;
- case 'attention': onAttention = cb; break; // <!XXXXX zzzz="eeee">
- case 'question': onQuestion = cb; break; // <? .... ?>
- case 'comment': onComment = cb; break;
- default:
- throw error$1('unsupported event: ' + name);
- }
- return this;
- };
- /**
- * Set the namespace to prefix mapping.
- *
- * @example
- *
- * parser.ns({
- * 'http://foo': 'foo',
- * 'http://bar': 'bar'
- * });
- *
- * @param {!Object<string, string>} nsMap
- *
- * @return {Parser}
- */
- this['ns'] = function(nsMap) {
- if (typeof nsMap === 'undefined') {
- nsMap = {};
- }
- if (typeof nsMap !== 'object') {
- throw error$1('required args <nsMap={}>');
- }
- var _nsUriToPrefix = {}, k;
- for (k in nsMap) {
- _nsUriToPrefix[k] = nsMap[k];
- }
- // FORCE default mapping for schema instance
- _nsUriToPrefix[XSI_URI] = XSI_PREFIX;
- isNamespace = true;
- nsUriToPrefix = _nsUriToPrefix;
- return this;
- };
- /**
- * Parse xml string.
- *
- * @param {string} xml
- *
- * @return {Error} returnError, if not thrown
- */
- this['parse'] = function(xml) {
- if (typeof xml !== 'string') {
- throw error$1('required args <xml=string>');
- }
- returnError = null;
- parse(xml);
- getContext = noopGetContext;
- parseStop = false;
- return returnError;
- };
- /**
- * Stop parsing.
- */
- this['stop'] = function() {
- parseStop = true;
- };
- /**
- * Parse string, invoking configured listeners on element.
- *
- * @param {string} xml
- */
- function parse(xml) {
- var nsMatrixStack = isNamespace ? [] : null,
- nsMatrix = isNamespace ? buildNsMatrix(nsUriToPrefix) : null,
- _nsMatrix,
- nodeStack = [],
- anonymousNsCount = 0,
- tagStart = false,
- tagEnd = false,
- i = 0, j = 0,
- x, y, q, w, v,
- xmlns,
- elementName,
- _elementName,
- elementProxy
- ;
- var attrsString = '',
- attrsStart = 0,
- cachedAttrs // false = parsed with errors, null = needs parsing
- ;
- /**
- * Parse attributes on demand and returns the parsed attributes.
- *
- * Return semantics: (1) `false` on attribute parse error,
- * (2) object hash on extracted attrs.
- *
- * @return {boolean|Object}
- */
- function getAttrs() {
- if (cachedAttrs !== null) {
- return cachedAttrs;
- }
- var nsUri,
- nsUriPrefix,
- nsName,
- defaultAlias = isNamespace && nsMatrix['xmlns'],
- attrList = isNamespace && maybeNS ? [] : null,
- i = attrsStart,
- s = attrsString,
- l = s.length,
- hasNewMatrix,
- newalias,
- value,
- alias,
- name,
- attrs = {},
- seenAttrs = {},
- skipAttr,
- w,
- j;
- parseAttr:
- for (; i < l; i++) {
- skipAttr = false;
- w = s.charCodeAt(i);
- if (w === 32 || (w < 14 && w > 8)) { // WHITESPACE={ \f\n\r\t\v}
- continue;
- }
- // wait for non whitespace character
- if (w < 65 || w > 122 || (w > 90 && w < 97)) {
- if (w !== 95 && w !== 58) { // char 95"_" 58":"
- handleWarning('illegal first char attribute name');
- skipAttr = true;
- }
- }
- // parse attribute name
- for (j = i + 1; j < l; j++) {
- w = s.charCodeAt(j);
- if (
- w > 96 && w < 123 ||
- w > 64 && w < 91 ||
- w > 47 && w < 59 ||
- w === 46 || // '.'
- w === 45 || // '-'
- w === 95 // '_'
- ) {
- continue;
- }
- // unexpected whitespace
- if (w === 32 || (w < 14 && w > 8)) { // WHITESPACE
- handleWarning('missing attribute value');
- i = j;
- continue parseAttr;
- }
- // expected "="
- if (w === 61) { // "=" == 61
- break;
- }
- handleWarning('illegal attribute name char');
- skipAttr = true;
- }
- name = s.substring(i, j);
- if (name === 'xmlns:xmlns') {
- handleWarning('illegal declaration of xmlns');
- skipAttr = true;
- }
- w = s.charCodeAt(j + 1);
- if (w === 34) { // '"'
- j = s.indexOf('"', i = j + 2);
- if (j === -1) {
- j = s.indexOf('\'', i);
- if (j !== -1) {
- handleWarning('attribute value quote missmatch');
- skipAttr = true;
- }
- }
- } else if (w === 39) { // "'"
- j = s.indexOf('\'', i = j + 2);
- if (j === -1) {
- j = s.indexOf('"', i);
- if (j !== -1) {
- handleWarning('attribute value quote missmatch');
- skipAttr = true;
- }
- }
- } else {
- handleWarning('missing attribute value quotes');
- skipAttr = true;
- // skip to next space
- for (j = j + 1; j < l; j++) {
- w = s.charCodeAt(j + 1);
- if (w === 32 || (w < 14 && w > 8)) { // WHITESPACE
- break;
- }
- }
- }
- if (j === -1) {
- handleWarning('missing closing quotes');
- j = l;
- skipAttr = true;
- }
- if (!skipAttr) {
- value = s.substring(i, j);
- }
- i = j;
- // ensure SPACE follows attribute
- // skip illegal content otherwise
- // example a="b"c
- for (; j + 1 < l; j++) {
- w = s.charCodeAt(j + 1);
- if (w === 32 || (w < 14 && w > 8)) { // WHITESPACE
- break;
- }
- // FIRST ILLEGAL CHAR
- if (i === j) {
- handleWarning('illegal character after attribute end');
- skipAttr = true;
- }
- }
- // advance cursor to next attribute
- i = j + 1;
- if (skipAttr) {
- continue parseAttr;
- }
- // check attribute re-declaration
- if (name in seenAttrs) {
- handleWarning('attribute <' + name + '> already defined');
- continue;
- }
- seenAttrs[name] = true;
- if (!isNamespace) {
- attrs[name] = value;
- continue;
- }
- // try to extract namespace information
- if (maybeNS) {
- newalias = (
- name === 'xmlns'
- ? 'xmlns'
- : (name.charCodeAt(0) === 120 && name.substr(0, 6) === 'xmlns:')
- ? name.substr(6)
- : null
- );
- // handle xmlns(:alias) assignment
- if (newalias !== null) {
- nsUri = decodeEntities(value);
- nsUriPrefix = uriPrefix(newalias);
- alias = nsUriToPrefix[nsUri];
- if (!alias) {
- // no prefix defined or prefix collision
- if (
- (newalias === 'xmlns') ||
- (nsUriPrefix in nsMatrix && nsMatrix[nsUriPrefix] !== nsUri)
- ) {
- // alocate free ns prefix
- do {
- alias = 'ns' + (anonymousNsCount++);
- } while (typeof nsMatrix[alias] !== 'undefined');
- } else {
- alias = newalias;
- }
- nsUriToPrefix[nsUri] = alias;
- }
- if (nsMatrix[newalias] !== alias) {
- if (!hasNewMatrix) {
- nsMatrix = cloneNsMatrix(nsMatrix);
- hasNewMatrix = true;
- }
- nsMatrix[newalias] = alias;
- if (newalias === 'xmlns') {
- nsMatrix[uriPrefix(alias)] = nsUri;
- defaultAlias = alias;
- }
- nsMatrix[nsUriPrefix] = nsUri;
- }
- // expose xmlns(:asd)="..." in attributes
- attrs[name] = value;
- continue;
- }
- // collect attributes until all namespace
- // declarations are processed
- attrList.push(name, value);
- continue;
- } /** end if (maybeNs) */
- // handle attributes on element without
- // namespace declarations
- w = name.indexOf(':');
- if (w === -1) {
- attrs[name] = value;
- continue;
- }
- // normalize ns attribute name
- if (!(nsName = nsMatrix[name.substring(0, w)])) {
- handleWarning(missingNamespaceForPrefix(name.substring(0, w)));
- continue;
- }
- name = defaultAlias === nsName
- ? name.substr(w + 1)
- : nsName + name.substr(w);
- // end: normalize ns attribute name
- // normalize xsi:type ns attribute value
- if (name === XSI_TYPE$1) {
- w = value.indexOf(':');
- if (w !== -1) {
- nsName = value.substring(0, w);
- // handle default prefixes, i.e. xs:String gracefully
- nsName = nsMatrix[nsName] || nsName;
- value = nsName + value.substring(w);
- } else {
- value = defaultAlias + ':' + value;
- }
- }
- // end: normalize xsi:type ns attribute value
- attrs[name] = value;
- }
- // handle deferred, possibly namespaced attributes
- if (maybeNS) {
- // normalize captured attributes
- for (i = 0, l = attrList.length; i < l; i++) {
- name = attrList[i++];
- value = attrList[i];
- w = name.indexOf(':');
- if (w !== -1) {
- // normalize ns attribute name
- if (!(nsName = nsMatrix[name.substring(0, w)])) {
- handleWarning(missingNamespaceForPrefix(name.substring(0, w)));
- continue;
- }
- name = defaultAlias === nsName
- ? name.substr(w + 1)
- : nsName + name.substr(w);
- // end: normalize ns attribute name
- // normalize xsi:type ns attribute value
- if (name === XSI_TYPE$1) {
- w = value.indexOf(':');
- if (w !== -1) {
- nsName = value.substring(0, w);
- // handle default prefixes, i.e. xs:String gracefully
- nsName = nsMatrix[nsName] || nsName;
- value = nsName + value.substring(w);
- } else {
- value = defaultAlias + ':' + value;
- }
- }
- // end: normalize xsi:type ns attribute value
- }
- attrs[name] = value;
- }
- // end: normalize captured attributes
- }
- return cachedAttrs = attrs;
- }
- /**
- * Extract the parse context { line, column, part }
- * from the current parser position.
- *
- * @return {Object} parse context
- */
- function getParseContext() {
- var splitsRe = /(\r\n|\r|\n)/g;
- var line = 0;
- var column = 0;
- var startOfLine = 0;
- var endOfLine = j;
- var match;
- var data;
- while (i >= startOfLine) {
- match = splitsRe.exec(xml);
- if (!match) {
- break;
- }
- // end of line = (break idx + break chars)
- endOfLine = match[0].length + match.index;
- if (endOfLine > i) {
- break;
- }
- // advance to next line
- line += 1;
- startOfLine = endOfLine;
- }
- // EOF errors
- if (i == -1) {
- column = endOfLine;
- data = xml.substring(j);
- } else
- // start errors
- if (j === 0) {
- data = xml.substring(j, i);
- }
- // other errors
- else {
- column = i - startOfLine;
- data = (j == -1 ? xml.substring(i) : xml.substring(i, j + 1));
- }
- return {
- 'data': data,
- 'line': line,
- 'column': column
- };
- }
- getContext = getParseContext;
- if (proxy) {
- elementProxy = Object.create({}, {
- 'name': getter(function() {
- return elementName;
- }),
- 'originalName': getter(function() {
- return _elementName;
- }),
- 'attrs': getter(getAttrs),
- 'ns': getter(function() {
- return nsMatrix;
- })
- });
- }
- // actual parse logic
- while (j !== -1) {
- if (xml.charCodeAt(j) === 60) { // "<"
- i = j;
- } else {
- i = xml.indexOf('<', j);
- }
- // parse end
- if (i === -1) {
- if (nodeStack.length) {
- return handleError('unexpected end of file');
- }
- if (j === 0) {
- return handleError('missing start tag');
- }
- if (j < xml.length) {
- if (xml.substring(j).trim()) {
- handleWarning(NON_WHITESPACE_OUTSIDE_ROOT_NODE);
- }
- }
- return;
- }
- // parse text
- if (j !== i) {
- if (nodeStack.length) {
- if (onText) {
- onText(xml.substring(j, i), decodeEntities, getContext);
- if (parseStop) {
- return;
- }
- }
- } else {
- if (xml.substring(j, i).trim()) {
- handleWarning(NON_WHITESPACE_OUTSIDE_ROOT_NODE);
- if (parseStop) {
- return;
- }
- }
- }
- }
- w = xml.charCodeAt(i+1);
- // parse comments + CDATA
- if (w === 33) { // "!"
- q = xml.charCodeAt(i+2);
- // CDATA section
- if (q === 91 && xml.substr(i + 3, 6) === 'CDATA[') { // 91 == "["
- j = xml.indexOf(']]>', i);
- if (j === -1) {
- return handleError('unclosed cdata');
- }
- if (onCDATA) {
- onCDATA(xml.substring(i + 9, j), getContext);
- if (parseStop) {
- return;
- }
- }
- j += 3;
- continue;
- }
- // comment
- if (q === 45 && xml.charCodeAt(i + 3) === 45) { // 45 == "-"
- j = xml.indexOf('-->', i);
- if (j === -1) {
- return handleError('unclosed comment');
- }
- if (onComment) {
- onComment(xml.substring(i + 4, j), decodeEntities, getContext);
- if (parseStop) {
- return;
- }
- }
- j += 3;
- continue;
- }
- }
- // parse question <? ... ?>
- if (w === 63) { // "?"
- j = xml.indexOf('?>', i);
- if (j === -1) {
- return handleError('unclosed question');
- }
- if (onQuestion) {
- onQuestion(xml.substring(i, j + 2), getContext);
- if (parseStop) {
- return;
- }
- }
- j += 2;
- continue;
- }
- // find matching closing tag for attention or standard tags
- // for that we must skip through attribute values
- // (enclosed in single or double quotes)
- for (x = i + 1; ; x++) {
- v = xml.charCodeAt(x);
- if (isNaN(v)) {
- j = -1;
- return handleError('unclosed tag');
- }
- // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'"
- // skips the quoted string
- // (double quotes) does not appear in a literal enclosed by (double quotes)
- // (single quote) does not appear in a literal enclosed by (single quote)
- if (v === 34) { // '"'
- q = xml.indexOf('"', x + 1);
- x = q !== -1 ? q : x;
- } else if (v === 39) { // "'"
- q = xml.indexOf("'", x + 1);
- x = q !== -1 ? q : x;
- } else if (v === 62) { // '>'
- j = x;
- break;
- }
- }
- // parse attention <! ...>
- // previously comment and CDATA have already been parsed
- if (w === 33) { // "!"
- if (onAttention) {
- onAttention(xml.substring(i, j + 1), decodeEntities, getContext);
- if (parseStop) {
- return;
- }
- }
- j += 1;
- continue;
- }
- // don't process attributes;
- // there are none
- cachedAttrs = {};
- // if (xml.charCodeAt(i+1) === 47) { // </...
- if (w === 47) { // </...
- tagStart = false;
- tagEnd = true;
- if (!nodeStack.length) {
- return handleError('missing open tag');
- }
- // verify open <-> close tag match
- x = elementName = nodeStack.pop();
- q = i + 2 + x.length;
- if (xml.substring(i + 2, q) !== x) {
- return handleError('closing tag mismatch');
- }
- // verify chars in close tag
- for (; q < j; q++) {
- w = xml.charCodeAt(q);
- if (w === 32 || (w > 8 && w < 14)) { // \f\n\r\t\v space
- continue;
- }
- return handleError('close tag');
- }
- } else {
- if (xml.charCodeAt(j - 1) === 47) { // .../>
- x = elementName = xml.substring(i + 1, j - 1);
- tagStart = true;
- tagEnd = true;
- } else {
- x = elementName = xml.substring(i + 1, j);
- tagStart = true;
- tagEnd = false;
- }
- if (!(w > 96 && w < 123 || w > 64 && w < 91 || w === 95 || w === 58)) { // char 95"_" 58":"
- return handleError('illegal first char nodeName');
- }
- for (q = 1, y = x.length; q < y; q++) {
- w = x.charCodeAt(q);
- if (w > 96 && w < 123 || w > 64 && w < 91 || w > 47 && w < 59 || w === 45 || w === 95 || w == 46) {
- continue;
- }
- if (w === 32 || (w < 14 && w > 8)) { // \f\n\r\t\v space
- elementName = x.substring(0, q);
- // maybe there are attributes
- cachedAttrs = null;
- break;
- }
- return handleError('invalid nodeName');
- }
- if (!tagEnd) {
- nodeStack.push(elementName);
- }
- }
- if (isNamespace) {
- _nsMatrix = nsMatrix;
- if (tagStart) {
- // remember old namespace
- // unless we're self-closing
- if (!tagEnd) {
- nsMatrixStack.push(_nsMatrix);
- }
- if (cachedAttrs === null) {
- // quick check, whether there may be namespace
- // declarations on the node; if that is the case
- // we need to eagerly parse the node attributes
- if ((maybeNS = x.indexOf('xmlns', q) !== -1)) {
- attrsStart = q;
- attrsString = x;
- getAttrs();
- maybeNS = false;
- }
- }
- }
- _elementName = elementName;
- w = elementName.indexOf(':');
- if (w !== -1) {
- xmlns = nsMatrix[elementName.substring(0, w)];
- // prefix given; namespace must exist
- if (!xmlns) {
- return handleError('missing namespace on <' + _elementName + '>');
- }
- elementName = elementName.substr(w + 1);
- } else {
- xmlns = nsMatrix['xmlns'];
- // if no default namespace is defined,
- // we'll import the element as anonymous.
- //
- // it is up to users to correct that to the document defined
- // targetNamespace, or whatever their undersanding of the
- // XML spec mandates.
- }
- // adjust namespace prefixs as configured
- if (xmlns) {
- elementName = xmlns + ':' + elementName;
- }
- }
- if (tagStart) {
- attrsStart = q;
- attrsString = x;
- if (onOpenTag) {
- if (proxy) {
- onOpenTag(elementProxy, decodeEntities, tagEnd, getContext);
- } else {
- onOpenTag(elementName, getAttrs, decodeEntities, tagEnd, getContext);
- }
- if (parseStop) {
- return;
- }
- }
- }
- if (tagEnd) {
- if (onCloseTag) {
- onCloseTag(proxy ? elementProxy : elementName, decodeEntities, tagStart, getContext);
- if (parseStop) {
- return;
- }
- }
- // restore old namespace
- if (isNamespace) {
- if (!tagStart) {
- nsMatrix = nsMatrixStack.pop();
- } else {
- nsMatrix = _nsMatrix;
- }
- }
- }
- j += 1;
- }
- } /** end parse */
- }
- function hasLowerCaseAlias(pkg) {
- return pkg.xml && pkg.xml.tagAlias === 'lowerCase';
- }
- var DEFAULT_NS_MAP = {
- 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
- 'xml': 'http://www.w3.org/XML/1998/namespace'
- };
- var XSI_TYPE = 'xsi:type';
- function serializeFormat(element) {
- return element.xml && element.xml.serialize;
- }
- function serializeAsType(element) {
- return serializeFormat(element) === XSI_TYPE;
- }
- function serializeAsProperty(element) {
- return serializeFormat(element) === 'property';
- }
- function capitalize(str) {
- return str.charAt(0).toUpperCase() + str.slice(1);
- }
- function aliasToName(aliasNs, pkg) {
- if (!hasLowerCaseAlias(pkg)) {
- return aliasNs.name;
- }
- return aliasNs.prefix + ':' + capitalize(aliasNs.localName);
- }
- function prefixedToName(nameNs, pkg) {
- var name = nameNs.name,
- localName = nameNs.localName;
- var typePrefix = pkg.xml && pkg.xml.typePrefix;
- if (typePrefix && localName.indexOf(typePrefix) === 0) {
- return nameNs.prefix + ':' + localName.slice(typePrefix.length);
- } else {
- return name;
- }
- }
- function normalizeXsiTypeName(name, model) {
- var nameNs = parseName(name);
- var pkg = model.getPackage(nameNs.prefix);
- return prefixedToName(nameNs, pkg);
- }
- function error(message) {
- return new Error(message);
- }
- /**
- * Get the moddle descriptor for a given instance or type.
- *
- * @param {ModdleElement|Function} element
- *
- * @return {Object} the moddle descriptor
- */
- function getModdleDescriptor(element) {
- return element.$descriptor;
- }
- /**
- * A parse context.
- *
- * @class
- *
- * @param {Object} options
- * @param {ElementHandler} options.rootHandler the root handler for parsing a document
- * @param {boolean} [options.lax=false] whether or not to ignore invalid elements
- */
- function Context(options) {
- /**
- * @property {ElementHandler} rootHandler
- */
- /**
- * @property {Boolean} lax
- */
- assign(this, options);
- this.elementsById = {};
- this.references = [];
- this.warnings = [];
- /**
- * Add an unresolved reference.
- *
- * @param {Object} reference
- */
- this.addReference = function(reference) {
- this.references.push(reference);
- };
- /**
- * Add a processed element.
- *
- * @param {ModdleElement} element
- */
- this.addElement = function(element) {
- if (!element) {
- throw error('expected element');
- }
- var elementsById = this.elementsById;
- var descriptor = getModdleDescriptor(element);
- var idProperty = descriptor.idProperty,
- id;
- if (idProperty) {
- id = element.get(idProperty.name);
- if (id) {
- // for QName validation as per http://www.w3.org/TR/REC-xml/#NT-NameChar
- if (!/^([a-z][\w-.]*:)?[a-z_][\w-.]*$/i.test(id)) {
- throw new Error('illegal ID <' + id + '>');
- }
- if (elementsById[id]) {
- throw error('duplicate ID <' + id + '>');
- }
- elementsById[id] = element;
- }
- }
- };
- /**
- * Add an import warning.
- *
- * @param {Object} warning
- * @param {String} warning.message
- * @param {Error} [warning.error]
- */
- this.addWarning = function(warning) {
- this.warnings.push(warning);
- };
- }
- function BaseHandler() {}
- BaseHandler.prototype.handleEnd = function() {};
- BaseHandler.prototype.handleText = function() {};
- BaseHandler.prototype.handleNode = function() {};
- /**
- * A simple pass through handler that does nothing except for
- * ignoring all input it receives.
- *
- * This is used to ignore unknown elements and
- * attributes.
- */
- function NoopHandler() { }
- NoopHandler.prototype = Object.create(BaseHandler.prototype);
- NoopHandler.prototype.handleNode = function() {
- return this;
- };
- function BodyHandler() {}
- BodyHandler.prototype = Object.create(BaseHandler.prototype);
- BodyHandler.prototype.handleText = function(text) {
- this.body = (this.body || '') + text;
- };
- function ReferenceHandler(property, context) {
- this.property = property;
- this.context = context;
- }
- ReferenceHandler.prototype = Object.create(BodyHandler.prototype);
- ReferenceHandler.prototype.handleNode = function(node) {
- if (this.element) {
- throw error('expected no sub nodes');
- } else {
- this.element = this.createReference(node);
- }
- return this;
- };
- ReferenceHandler.prototype.handleEnd = function() {
- this.element.id = this.body;
- };
- ReferenceHandler.prototype.createReference = function(node) {
- return {
- property: this.property.ns.name,
- id: ''
- };
- };
- function ValueHandler(propertyDesc, element) {
- this.element = element;
- this.propertyDesc = propertyDesc;
- }
- ValueHandler.prototype = Object.create(BodyHandler.prototype);
- ValueHandler.prototype.handleEnd = function() {
- var value = this.body || '',
- element = this.element,
- propertyDesc = this.propertyDesc;
- value = coerceType(propertyDesc.type, value);
- if (propertyDesc.isMany) {
- element.get(propertyDesc.name).push(value);
- } else {
- element.set(propertyDesc.name, value);
- }
- };
- function BaseElementHandler() {}
- BaseElementHandler.prototype = Object.create(BodyHandler.prototype);
- BaseElementHandler.prototype.handleNode = function(node) {
- var parser = this,
- element = this.element;
- if (!element) {
- element = this.element = this.createElement(node);
- this.context.addElement(element);
- } else {
- parser = this.handleChild(node);
- }
- return parser;
- };
- /**
- * @class Reader.ElementHandler
- *
- */
- function ElementHandler(model, typeName, context) {
- this.model = model;
- this.type = model.getType(typeName);
- this.context = context;
- }
- ElementHandler.prototype = Object.create(BaseElementHandler.prototype);
- ElementHandler.prototype.addReference = function(reference) {
- this.context.addReference(reference);
- };
- ElementHandler.prototype.handleText = function(text) {
- var element = this.element,
- descriptor = getModdleDescriptor(element),
- bodyProperty = descriptor.bodyProperty;
- if (!bodyProperty) {
- throw error('unexpected body text <' + text + '>');
- }
- BodyHandler.prototype.handleText.call(this, text);
- };
- ElementHandler.prototype.handleEnd = function() {
- var value = this.body,
- element = this.element,
- descriptor = getModdleDescriptor(element),
- bodyProperty = descriptor.bodyProperty;
- if (bodyProperty && value !== undefined) {
- value = coerceType(bodyProperty.type, value);
- element.set(bodyProperty.name, value);
- }
- };
- /**
- * Create an instance of the model from the given node.
- *
- * @param {Element} node the xml node
- */
- ElementHandler.prototype.createElement = function(node) {
- var attributes = node.attributes,
- Type = this.type,
- descriptor = getModdleDescriptor(Type),
- context = this.context,
- instance = new Type({}),
- model = this.model,
- propNameNs;
- forEach$1(attributes, function(value, name) {
- var prop = descriptor.propertiesByName[name],
- values;
- if (prop && prop.isReference) {
- if (!prop.isMany) {
- context.addReference({
- element: instance,
- property: prop.ns.name,
- id: value
- });
- } else {
- // IDREFS: parse references as whitespace-separated list
- values = value.split(' ');
- forEach$1(values, function(v) {
- context.addReference({
- element: instance,
- property: prop.ns.name,
- id: v
- });
- });
- }
- } else {
- if (prop) {
- value = coerceType(prop.type, value);
- } else
- if (name !== 'xmlns') {
- propNameNs = parseName(name, descriptor.ns.prefix);
- // check whether attribute is defined in a well-known namespace
- // if that is the case we emit a warning to indicate potential misuse
- if (model.getPackage(propNameNs.prefix)) {
- context.addWarning({
- message: 'unknown attribute <' + name + '>',
- element: instance,
- property: name,
- value: value
- });
- }
- }
- instance.set(name, value);
- }
- });
- return instance;
- };
- ElementHandler.prototype.getPropertyForNode = function(node) {
- var name = node.name;
- var nameNs = parseName(name);
- var type = this.type,
- model = this.model,
- descriptor = getModdleDescriptor(type);
- var propertyName = nameNs.name,
- property = descriptor.propertiesByName[propertyName],
- elementTypeName,
- elementType;
- // search for properties by name first
- if (property && !property.isAttr) {
- if (serializeAsType(property)) {
- elementTypeName = node.attributes[XSI_TYPE];
- // xsi type is optional, if it does not exists the
- // default type is assumed
- if (elementTypeName) {
- // take possible type prefixes from XML
- // into account, i.e.: xsi:type="t{ActualType}"
- elementTypeName = normalizeXsiTypeName(elementTypeName, model);
- elementType = model.getType(elementTypeName);
- return assign({}, property, {
- effectiveType: getModdleDescriptor(elementType).name
- });
- }
- }
- // search for properties by name first
- return property;
- }
- var pkg = model.getPackage(nameNs.prefix);
- if (pkg) {
- elementTypeName = aliasToName(nameNs, pkg);
- elementType = model.getType(elementTypeName);
- // search for collection members later
- property = find(descriptor.properties, function(p) {
- return !p.isVirtual && !p.isReference && !p.isAttribute && elementType.hasType(p.type);
- });
- if (property) {
- return assign({}, property, {
- effectiveType: getModdleDescriptor(elementType).name
- });
- }
- } else {
- // parse unknown element (maybe extension)
- property = find(descriptor.properties, function(p) {
- return !p.isReference && !p.isAttribute && p.type === 'Element';
- });
- if (property) {
- return property;
- }
- }
- throw error('unrecognized element <' + nameNs.name + '>');
- };
- ElementHandler.prototype.toString = function() {
- return 'ElementDescriptor[' + getModdleDescriptor(this.type).name + ']';
- };
- ElementHandler.prototype.valueHandler = function(propertyDesc, element) {
- return new ValueHandler(propertyDesc, element);
- };
- ElementHandler.prototype.referenceHandler = function(propertyDesc) {
- return new ReferenceHandler(propertyDesc, this.context);
- };
- ElementHandler.prototype.handler = function(type) {
- if (type === 'Element') {
- return new GenericElementHandler(this.model, type, this.context);
- } else {
- return new ElementHandler(this.model, type, this.context);
- }
- };
- /**
- * Handle the child element parsing
- *
- * @param {Element} node the xml node
- */
- ElementHandler.prototype.handleChild = function(node) {
- var propertyDesc, type, element, childHandler;
- propertyDesc = this.getPropertyForNode(node);
- element = this.element;
- type = propertyDesc.effectiveType || propertyDesc.type;
- if (isSimple(type)) {
- return this.valueHandler(propertyDesc, element);
- }
- if (propertyDesc.isReference) {
- childHandler = this.referenceHandler(propertyDesc).handleNode(node);
- } else {
- childHandler = this.handler(type).handleNode(node);
- }
- var newElement = childHandler.element;
- // child handles may decide to skip elements
- // by not returning anything
- if (newElement !== undefined) {
- if (propertyDesc.isMany) {
- element.get(propertyDesc.name).push(newElement);
- } else {
- element.set(propertyDesc.name, newElement);
- }
- if (propertyDesc.isReference) {
- assign(newElement, {
- element: element
- });
- this.context.addReference(newElement);
- } else {
- // establish child -> parent relationship
- newElement.$parent = element;
- }
- }
- return childHandler;
- };
- /**
- * An element handler that performs special validation
- * to ensure the node it gets initialized with matches
- * the handlers type (namespace wise).
- *
- * @param {Moddle} model
- * @param {String} typeName
- * @param {Context} context
- */
- function RootElementHandler(model, typeName, context) {
- ElementHandler.call(this, model, typeName, context);
- }
- RootElementHandler.prototype = Object.create(ElementHandler.prototype);
- RootElementHandler.prototype.createElement = function(node) {
- var name = node.name,
- nameNs = parseName(name),
- model = this.model,
- type = this.type,
- pkg = model.getPackage(nameNs.prefix),
- typeName = pkg && aliasToName(nameNs, pkg) || name;
- // verify the correct namespace if we parse
- // the first element in the handler tree
- //
- // this ensures we don't mistakenly import wrong namespace elements
- if (!type.hasType(typeName)) {
- throw error('unexpected element <' + node.originalName + '>');
- }
- return ElementHandler.prototype.createElement.call(this, node);
- };
- function GenericElementHandler(model, typeName, context) {
- this.model = model;
- this.context = context;
- }
- GenericElementHandler.prototype = Object.create(BaseElementHandler.prototype);
- GenericElementHandler.prototype.createElement = function(node) {
- var name = node.name,
- ns = parseName(name),
- prefix = ns.prefix,
- uri = node.ns[prefix + '$uri'],
- attributes = node.attributes;
- return this.model.createAny(name, uri, attributes);
- };
- GenericElementHandler.prototype.handleChild = function(node) {
- var handler = new GenericElementHandler(this.model, 'Element', this.context).handleNode(node),
- element = this.element;
- var newElement = handler.element,
- children;
- if (newElement !== undefined) {
- children = element.$children = element.$children || [];
- children.push(newElement);
- // establish child -> parent relationship
- newElement.$parent = element;
- }
- return handler;
- };
- GenericElementHandler.prototype.handleEnd = function() {
- if (this.body) {
- this.element.$body = this.body;
- }
- };
- /**
- * A reader for a meta-model
- *
- * @param {Object} options
- * @param {Model} options.model used to read xml files
- * @param {Boolean} options.lax whether to make parse errors warnings
- */
- function Reader(options) {
- if (options instanceof Moddle) {
- options = {
- model: options
- };
- }
- assign(this, { lax: false }, options);
- }
- /**
- * The fromXML result.
- *
- * @typedef {Object} ParseResult
- *
- * @property {ModdleElement} rootElement
- * @property {Array<Object>} references
- * @property {Array<Error>} warnings
- * @property {Object} elementsById - a mapping containing each ID -> ModdleElement
- */
- /**
- * The fromXML result.
- *
- * @typedef {Error} ParseError
- *
- * @property {Array<Error>} warnings
- */
- /**
- * Parse the given XML into a moddle document tree.
- *
- * @param {String} xml
- * @param {ElementHandler|Object} options or rootHandler
- *
- * @returns {Promise<ParseResult, ParseError>}
- */
- Reader.prototype.fromXML = function(xml, options, done) {
- var rootHandler = options.rootHandler;
- if (options instanceof ElementHandler) {
- // root handler passed via (xml, { rootHandler: ElementHandler }, ...)
- rootHandler = options;
- options = {};
- } else {
- if (typeof options === 'string') {
- // rootHandler passed via (xml, 'someString', ...)
- rootHandler = this.handler(options);
- options = {};
- } else if (typeof rootHandler === 'string') {
- // rootHandler passed via (xml, { rootHandler: 'someString' }, ...)
- rootHandler = this.handler(rootHandler);
- }
- }
- var model = this.model,
- lax = this.lax;
- var context = new Context(assign({}, options, { rootHandler: rootHandler })),
- parser = new Parser({ proxy: true }),
- stack = createStack();
- rootHandler.context = context;
- // push root handler
- stack.push(rootHandler);
- /**
- * Handle error.
- *
- * @param {Error} err
- * @param {Function} getContext
- * @param {boolean} lax
- *
- * @return {boolean} true if handled
- */
- function handleError(err, getContext, lax) {
- var ctx = getContext();
- var line = ctx.line,
- column = ctx.column,
- data = ctx.data;
- // we receive the full context data here,
- // for elements trim down the information
- // to the tag name, only
- if (data.charAt(0) === '<' && data.indexOf(' ') !== -1) {
- data = data.slice(0, data.indexOf(' ')) + '>';
- }
- var message =
- 'unparsable content ' + (data ? data + ' ' : '') + 'detected\n\t' +
- 'line: ' + line + '\n\t' +
- 'column: ' + column + '\n\t' +
- 'nested error: ' + err.message;
- if (lax) {
- context.addWarning({
- message: message,
- error: err
- });
- return true;
- } else {
- throw error(message);
- }
- }
- function handleWarning(err, getContext) {
- // just like handling errors in <lax=true> mode
- return handleError(err, getContext, true);
- }
- /**
- * Resolve collected references on parse end.
- */
- function resolveReferences() {
- var elementsById = context.elementsById;
- var references = context.references;
- var i, r;
- for (i = 0; (r = references[i]); i++) {
- var element = r.element;
- var reference = elementsById[r.id];
- var property = getModdleDescriptor(element).propertiesByName[r.property];
- if (!reference) {
- context.addWarning({
- message: 'unresolved reference <' + r.id + '>',
- element: r.element,
- property: r.property,
- value: r.id
- });
- }
- if (property.isMany) {
- var collection = element.get(property.name),
- idx = collection.indexOf(r);
- // we replace an existing place holder (idx != -1) or
- // append to the collection instead
- if (idx === -1) {
- idx = collection.length;
- }
- if (!reference) {
- // remove unresolvable reference
- collection.splice(idx, 1);
- } else {
- // add or update reference in collection
- collection[idx] = reference;
- }
- } else {
- element.set(property.name, reference);
- }
- }
- }
- function handleClose() {
- stack.pop().handleEnd();
- }
- var PREAMBLE_START_PATTERN = /^<\?xml /i;
- var ENCODING_PATTERN = / encoding="([^"]+)"/i;
- var UTF_8_PATTERN = /^utf-8$/i;
- function handleQuestion(question) {
- if (!PREAMBLE_START_PATTERN.test(question)) {
- return;
- }
- var match = ENCODING_PATTERN.exec(question);
- var encoding = match && match[1];
- if (!encoding || UTF_8_PATTERN.test(encoding)) {
- return;
- }
- context.addWarning({
- message:
- 'unsupported document encoding <' + encoding + '>, ' +
- 'falling back to UTF-8'
- });
- }
- function handleOpen(node, getContext) {
- var handler = stack.peek();
- try {
- stack.push(handler.handleNode(node));
- } catch (err) {
- if (handleError(err, getContext, lax)) {
- stack.push(new NoopHandler());
- }
- }
- }
- function handleCData(text, getContext) {
- try {
- stack.peek().handleText(text);
- } catch (err) {
- handleWarning(err, getContext);
- }
- }
- function handleText(text, getContext) {
- // strip whitespace only nodes, i.e. before
- // <!CDATA[ ... ]> sections and in between tags
- if (!text.trim()) {
- return;
- }
- handleCData(text, getContext);
- }
- var uriMap = model.getPackages().reduce(function(uriMap, p) {
- uriMap[p.uri] = p.prefix;
- return uriMap;
- }, {
- 'http://www.w3.org/XML/1998/namespace': 'xml' // add default xml ns
- });
- parser
- .ns(uriMap)
- .on('openTag', function(obj, decodeStr, selfClosing, getContext) {
- // gracefully handle unparsable attributes (attrs=false)
- var attrs = obj.attrs || {};
- var decodedAttrs = Object.keys(attrs).reduce(function(d, key) {
- var value = decodeStr(attrs[key]);
- d[key] = value;
- return d;
- }, {});
- var node = {
- name: obj.name,
- originalName: obj.originalName,
- attributes: decodedAttrs,
- ns: obj.ns
- };
- handleOpen(node, getContext);
- })
- .on('question', handleQuestion)
- .on('closeTag', handleClose)
- .on('cdata', handleCData)
- .on('text', function(text, decodeEntities, getContext) {
- handleText(decodeEntities(text), getContext);
- })
- .on('error', handleError)
- .on('warn', handleWarning);
- // async XML parsing to make sure the execution environment
- // (node or brower) is kept responsive and that certain optimization
- // strategies can kick in.
- return new Promise(function(resolve, reject) {
- var err;
- try {
- parser.parse(xml);
- resolveReferences();
- } catch (e) {
- err = e;
- }
- var rootElement = rootHandler.element;
- if (!err && !rootElement) {
- err = error('failed to parse document as <' + rootHandler.type.$descriptor.name + '>');
- }
- var warnings = context.warnings;
- var references = context.references;
- var elementsById = context.elementsById;
- if (err) {
- err.warnings = warnings;
- return reject(err);
- } else {
- return resolve({
- rootElement: rootElement,
- elementsById: elementsById,
- references: references,
- warnings: warnings
- });
- }
- });
- };
- Reader.prototype.handler = function(name) {
- return new RootElementHandler(this.model, name);
- };
- // helpers //////////////////////////
- function createStack() {
- var stack = [];
- Object.defineProperty(stack, 'peek', {
- value: function() {
- return this[this.length - 1];
- }
- });
- return stack;
- }
- var XML_PREAMBLE = '<?xml version="1.0" encoding="UTF-8"?>\n';
- var ESCAPE_ATTR_CHARS = /<|>|'|"|&|\n\r|\n/g;
- var ESCAPE_CHARS = /<|>|&/g;
- function Namespaces(parent) {
- var prefixMap = {};
- var uriMap = {};
- var used = {};
- var wellknown = [];
- var custom = [];
- // API
- this.byUri = function(uri) {
- return uriMap[uri] || (
- parent && parent.byUri(uri)
- );
- };
- this.add = function(ns, isWellknown) {
- uriMap[ns.uri] = ns;
- if (isWellknown) {
- wellknown.push(ns);
- } else {
- custom.push(ns);
- }
- this.mapPrefix(ns.prefix, ns.uri);
- };
- this.uriByPrefix = function(prefix) {
- return prefixMap[prefix || 'xmlns'];
- };
- this.mapPrefix = function(prefix, uri) {
- prefixMap[prefix || 'xmlns'] = uri;
- };
- this.getNSKey = function(ns) {
- return (ns.prefix !== undefined) ? (ns.uri + '|' + ns.prefix) : ns.uri;
- };
- this.logUsed = function(ns) {
- var uri = ns.uri;
- var nsKey = this.getNSKey(ns);
- used[nsKey] = this.byUri(uri);
- // Inform parent recursively about the usage of this NS
- if (parent) {
- parent.logUsed(ns);
- }
- };
- this.getUsed = function(ns) {
- function isUsed(ns) {
- var nsKey = self.getNSKey(ns);
- return used[nsKey];
- }
- var self = this;
- var allNs = [].concat(wellknown, custom);
- return allNs.filter(isUsed);
- };
- }
- function lower(string) {
- return string.charAt(0).toLowerCase() + string.slice(1);
- }
- function nameToAlias(name, pkg) {
- if (hasLowerCaseAlias(pkg)) {
- return lower(name);
- } else {
- return name;
- }
- }
- function inherits(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- }
- function nsName(ns) {
- if (isString(ns)) {
- return ns;
- } else {
- return (ns.prefix ? ns.prefix + ':' : '') + ns.localName;
- }
- }
- function getNsAttrs(namespaces) {
- return namespaces.getUsed().filter(function(ns) {
- // do not serialize built in <xml> namespace
- return ns.prefix !== 'xml';
- }).map(function(ns) {
- var name = 'xmlns' + (ns.prefix ? ':' + ns.prefix : '');
- return { name: name, value: ns.uri };
- });
- }
- function getElementNs(ns, descriptor) {
- if (descriptor.isGeneric) {
- return assign({ localName: descriptor.ns.localName }, ns);
- } else {
- return assign({ localName: nameToAlias(descriptor.ns.localName, descriptor.$pkg) }, ns);
- }
- }
- function getPropertyNs(ns, descriptor) {
- return assign({ localName: descriptor.ns.localName }, ns);
- }
- function getSerializableProperties(element) {
- var descriptor = element.$descriptor;
- return filter(descriptor.properties, function(p) {
- var name = p.name;
- if (p.isVirtual) {
- return false;
- }
- // do not serialize defaults
- if (!has$1(element, name)) {
- return false;
- }
- var value = element[name];
- // do not serialize default equals
- if (value === p.default) {
- return false;
- }
- // do not serialize null properties
- if (value === null) {
- return false;
- }
- return p.isMany ? value.length : true;
- });
- }
- var ESCAPE_ATTR_MAP = {
- '\n': '#10',
- '\n\r': '#10',
- '"': '#34',
- '\'': '#39',
- '<': '#60',
- '>': '#62',
- '&': '#38'
- };
- var ESCAPE_MAP = {
- '<': 'lt',
- '>': 'gt',
- '&': 'amp'
- };
- function escape(str, charPattern, replaceMap) {
- // ensure we are handling strings here
- str = isString(str) ? str : '' + str;
- return str.replace(charPattern, function(s) {
- return '&' + replaceMap[s] + ';';
- });
- }
- /**
- * Escape a string attribute to not contain any bad values (line breaks, '"', ...)
- *
- * @param {String} str the string to escape
- * @return {String} the escaped string
- */
- function escapeAttr(str) {
- return escape(str, ESCAPE_ATTR_CHARS, ESCAPE_ATTR_MAP);
- }
- function escapeBody(str) {
- return escape(str, ESCAPE_CHARS, ESCAPE_MAP);
- }
- function filterAttributes(props) {
- return filter(props, function(p) { return p.isAttr; });
- }
- function filterContained(props) {
- return filter(props, function(p) { return !p.isAttr; });
- }
- function ReferenceSerializer(tagName) {
- this.tagName = tagName;
- }
- ReferenceSerializer.prototype.build = function(element) {
- this.element = element;
- return this;
- };
- ReferenceSerializer.prototype.serializeTo = function(writer) {
- writer
- .appendIndent()
- .append('<' + this.tagName + '>' + this.element.id + '</' + this.tagName + '>')
- .appendNewLine();
- };
- function BodySerializer() {}
- BodySerializer.prototype.serializeValue =
- BodySerializer.prototype.serializeTo = function(writer) {
- writer.append(
- this.escape
- ? escapeBody(this.value)
- : this.value
- );
- };
- BodySerializer.prototype.build = function(prop, value) {
- this.value = value;
- if (prop.type === 'String' && value.search(ESCAPE_CHARS) !== -1) {
- this.escape = true;
- }
- return this;
- };
- function ValueSerializer(tagName) {
- this.tagName = tagName;
- }
- inherits(ValueSerializer, BodySerializer);
- ValueSerializer.prototype.serializeTo = function(writer) {
- writer
- .appendIndent()
- .append('<' + this.tagName + '>');
- this.serializeValue(writer);
- writer
- .append('</' + this.tagName + '>')
- .appendNewLine();
- };
- function ElementSerializer(parent, propertyDescriptor) {
- this.body = [];
- this.attrs = [];
- this.parent = parent;
- this.propertyDescriptor = propertyDescriptor;
- }
- ElementSerializer.prototype.build = function(element) {
- this.element = element;
- var elementDescriptor = element.$descriptor,
- propertyDescriptor = this.propertyDescriptor;
- var otherAttrs,
- properties;
- var isGeneric = elementDescriptor.isGeneric;
- if (isGeneric) {
- otherAttrs = this.parseGeneric(element);
- } else {
- otherAttrs = this.parseNsAttributes(element);
- }
- if (propertyDescriptor) {
- this.ns = this.nsPropertyTagName(propertyDescriptor);
- } else {
- this.ns = this.nsTagName(elementDescriptor);
- }
- // compute tag name
- this.tagName = this.addTagName(this.ns);
- if (!isGeneric) {
- properties = getSerializableProperties(element);
- this.parseAttributes(filterAttributes(properties));
- this.parseContainments(filterContained(properties));
- }
- this.parseGenericAttributes(element, otherAttrs);
- return this;
- };
- ElementSerializer.prototype.nsTagName = function(descriptor) {
- var effectiveNs = this.logNamespaceUsed(descriptor.ns);
- return getElementNs(effectiveNs, descriptor);
- };
- ElementSerializer.prototype.nsPropertyTagName = function(descriptor) {
- var effectiveNs = this.logNamespaceUsed(descriptor.ns);
- return getPropertyNs(effectiveNs, descriptor);
- };
- ElementSerializer.prototype.isLocalNs = function(ns) {
- return ns.uri === this.ns.uri;
- };
- /**
- * Get the actual ns attribute name for the given element.
- *
- * @param {Object} element
- * @param {Boolean} [element.inherited=false]
- *
- * @return {Object} nsName
- */
- ElementSerializer.prototype.nsAttributeName = function(element) {
- var ns;
- if (isString(element)) {
- ns = parseName(element);
- } else {
- ns = element.ns;
- }
- // return just local name for inherited attributes
- if (element.inherited) {
- return { localName: ns.localName };
- }
- // parse + log effective ns
- var effectiveNs = this.logNamespaceUsed(ns);
- // LOG ACTUAL namespace use
- this.getNamespaces().logUsed(effectiveNs);
- // strip prefix if same namespace like parent
- if (this.isLocalNs(effectiveNs)) {
- return { localName: ns.localName };
- } else {
- return assign({ localName: ns.localName }, effectiveNs);
- }
- };
- ElementSerializer.prototype.parseGeneric = function(element) {
- var self = this,
- body = this.body;
- var attributes = [];
- forEach$1(element, function(val, key) {
- var nonNsAttr;
- if (key === '$body') {
- body.push(new BodySerializer().build({ type: 'String' }, val));
- } else
- if (key === '$children') {
- forEach$1(val, function(child) {
- body.push(new ElementSerializer(self).build(child));
- });
- } else
- if (key.indexOf('$') !== 0) {
- nonNsAttr = self.parseNsAttribute(element, key, val);
- if (nonNsAttr) {
- attributes.push({ name: key, value: val });
- }
- }
- });
- return attributes;
- };
- ElementSerializer.prototype.parseNsAttribute = function(element, name, value) {
- var model = element.$model;
- var nameNs = parseName(name);
- var ns;
- // parse xmlns:foo="http://foo.bar"
- if (nameNs.prefix === 'xmlns') {
- ns = { prefix: nameNs.localName, uri: value };
- }
- // parse xmlns="http://foo.bar"
- if (!nameNs.prefix && nameNs.localName === 'xmlns') {
- ns = { uri: value };
- }
- if (!ns) {
- return {
- name: name,
- value: value
- };
- }
- if (model && model.getPackage(value)) {
- // register well known namespace
- this.logNamespace(ns, true, true);
- } else {
- // log custom namespace directly as used
- var actualNs = this.logNamespaceUsed(ns, true);
- this.getNamespaces().logUsed(actualNs);
- }
- };
- /**
- * Parse namespaces and return a list of left over generic attributes
- *
- * @param {Object} element
- * @return {Array<Object>}
- */
- ElementSerializer.prototype.parseNsAttributes = function(element, attrs) {
- var self = this;
- var genericAttrs = element.$attrs;
- var attributes = [];
- // parse namespace attributes first
- // and log them. push non namespace attributes to a list
- // and process them later
- forEach$1(genericAttrs, function(value, name) {
- var nonNsAttr = self.parseNsAttribute(element, name, value);
- if (nonNsAttr) {
- attributes.push(nonNsAttr);
- }
- });
- return attributes;
- };
- ElementSerializer.prototype.parseGenericAttributes = function(element, attributes) {
- var self = this;
- forEach$1(attributes, function(attr) {
- // do not serialize xsi:type attribute
- // it is set manually based on the actual implementation type
- if (attr.name === XSI_TYPE) {
- return;
- }
- try {
- self.addAttribute(self.nsAttributeName(attr.name), attr.value);
- } catch (e) {
- console.warn(
- 'missing namespace information for ',
- attr.name, '=', attr.value, 'on', element,
- e);
- }
- });
- };
- ElementSerializer.prototype.parseContainments = function(properties) {
- var self = this,
- body = this.body,
- element = this.element;
- forEach$1(properties, function(p) {
- var value = element.get(p.name),
- isReference = p.isReference,
- isMany = p.isMany;
- if (!isMany) {
- value = [ value ];
- }
- if (p.isBody) {
- body.push(new BodySerializer().build(p, value[0]));
- } else
- if (isSimple(p.type)) {
- forEach$1(value, function(v) {
- body.push(new ValueSerializer(self.addTagName(self.nsPropertyTagName(p))).build(p, v));
- });
- } else
- if (isReference) {
- forEach$1(value, function(v) {
- body.push(new ReferenceSerializer(self.addTagName(self.nsPropertyTagName(p))).build(v));
- });
- } else {
- // allow serialization via type
- // rather than element name
- var asType = serializeAsType(p),
- asProperty = serializeAsProperty(p);
- forEach$1(value, function(v) {
- var serializer;
- if (asType) {
- serializer = new TypeSerializer(self, p);
- } else
- if (asProperty) {
- serializer = new ElementSerializer(self, p);
- } else {
- serializer = new ElementSerializer(self);
- }
- body.push(serializer.build(v));
- });
- }
- });
- };
- ElementSerializer.prototype.getNamespaces = function(local) {
- var namespaces = this.namespaces,
- parent = this.parent,
- parentNamespaces;
- if (!namespaces) {
- parentNamespaces = parent && parent.getNamespaces();
- if (local || !parentNamespaces) {
- this.namespaces = namespaces = new Namespaces(parentNamespaces);
- } else {
- namespaces = parentNamespaces;
- }
- }
- return namespaces;
- };
- ElementSerializer.prototype.logNamespace = function(ns, wellknown, local) {
- var namespaces = this.getNamespaces(local);
- var nsUri = ns.uri,
- nsPrefix = ns.prefix;
- var existing = namespaces.byUri(nsUri);
- if (!existing || local) {
- namespaces.add(ns, wellknown);
- }
- namespaces.mapPrefix(nsPrefix, nsUri);
- return ns;
- };
- ElementSerializer.prototype.logNamespaceUsed = function(ns, local) {
- var element = this.element,
- model = element.$model,
- namespaces = this.getNamespaces(local);
- // ns may be
- //
- // * prefix only
- // * prefix:uri
- // * localName only
- var prefix = ns.prefix,
- uri = ns.uri,
- newPrefix, idx,
- wellknownUri;
- // handle anonymous namespaces (elementForm=unqualified), cf. #23
- if (!prefix && !uri) {
- return { localName: ns.localName };
- }
- wellknownUri = DEFAULT_NS_MAP[prefix] || model && (model.getPackage(prefix) || {}).uri;
- uri = uri || wellknownUri || namespaces.uriByPrefix(prefix);
- if (!uri) {
- throw new Error('no namespace uri given for prefix <' + prefix + '>');
- }
- ns = namespaces.byUri(uri);
- if (!ns) {
- newPrefix = prefix;
- idx = 1;
- // find a prefix that is not mapped yet
- while (namespaces.uriByPrefix(newPrefix)) {
- newPrefix = prefix + '_' + idx++;
- }
- ns = this.logNamespace({ prefix: newPrefix, uri: uri }, wellknownUri === uri);
- }
- if (prefix) {
- namespaces.mapPrefix(prefix, uri);
- }
- return ns;
- };
- ElementSerializer.prototype.parseAttributes = function(properties) {
- var self = this,
- element = this.element;
- forEach$1(properties, function(p) {
- var value = element.get(p.name);
- if (p.isReference) {
- if (!p.isMany) {
- value = value.id;
- }
- else {
- var values = [];
- forEach$1(value, function(v) {
- values.push(v.id);
- });
- // IDREFS is a whitespace-separated list of references.
- value = values.join(' ');
- }
- }
- self.addAttribute(self.nsAttributeName(p), value);
- });
- };
- ElementSerializer.prototype.addTagName = function(nsTagName) {
- var actualNs = this.logNamespaceUsed(nsTagName);
- this.getNamespaces().logUsed(actualNs);
- return nsName(nsTagName);
- };
- ElementSerializer.prototype.addAttribute = function(name, value) {
- var attrs = this.attrs;
- if (isString(value)) {
- value = escapeAttr(value);
- }
- attrs.push({ name: name, value: value });
- };
- ElementSerializer.prototype.serializeAttributes = function(writer) {
- var attrs = this.attrs,
- namespaces = this.namespaces;
- if (namespaces) {
- attrs = getNsAttrs(namespaces).concat(attrs);
- }
- forEach$1(attrs, function(a) {
- writer
- .append(' ')
- .append(nsName(a.name)).append('="').append(a.value).append('"');
- });
- };
- ElementSerializer.prototype.serializeTo = function(writer) {
- var firstBody = this.body[0],
- indent = firstBody && firstBody.constructor !== BodySerializer;
- writer
- .appendIndent()
- .append('<' + this.tagName);
- this.serializeAttributes(writer);
- writer.append(firstBody ? '>' : ' />');
- if (firstBody) {
- if (indent) {
- writer
- .appendNewLine()
- .indent();
- }
- forEach$1(this.body, function(b) {
- b.serializeTo(writer);
- });
- if (indent) {
- writer
- .unindent()
- .appendIndent();
- }
- writer.append('</' + this.tagName + '>');
- }
- writer.appendNewLine();
- };
- /**
- * A serializer for types that handles serialization of data types
- */
- function TypeSerializer(parent, propertyDescriptor) {
- ElementSerializer.call(this, parent, propertyDescriptor);
- }
- inherits(TypeSerializer, ElementSerializer);
- TypeSerializer.prototype.parseNsAttributes = function(element) {
- // extracted attributes
- var attributes = ElementSerializer.prototype.parseNsAttributes.call(this, element);
- var descriptor = element.$descriptor;
- // only serialize xsi:type if necessary
- if (descriptor.name === this.propertyDescriptor.type) {
- return attributes;
- }
- var typeNs = this.typeNs = this.nsTagName(descriptor);
- this.getNamespaces().logUsed(this.typeNs);
- // add xsi:type attribute to represent the elements
- // actual type
- var pkg = element.$model.getPackage(typeNs.uri),
- typePrefix = (pkg.xml && pkg.xml.typePrefix) || '';
- this.addAttribute(
- this.nsAttributeName(XSI_TYPE),
- (typeNs.prefix ? typeNs.prefix + ':' : '') + typePrefix + descriptor.ns.localName
- );
- return attributes;
- };
- TypeSerializer.prototype.isLocalNs = function(ns) {
- return ns.uri === (this.typeNs || this.ns).uri;
- };
- function SavingWriter() {
- this.value = '';
- this.write = function(str) {
- this.value += str;
- };
- }
- function FormatingWriter(out, format) {
- var indent = [''];
- this.append = function(str) {
- out.write(str);
- return this;
- };
- this.appendNewLine = function() {
- if (format) {
- out.write('\n');
- }
- return this;
- };
- this.appendIndent = function() {
- if (format) {
- out.write(indent.join(' '));
- }
- return this;
- };
- this.indent = function() {
- indent.push('');
- return this;
- };
- this.unindent = function() {
- indent.pop();
- return this;
- };
- }
- /**
- * A writer for meta-model backed document trees
- *
- * @param {Object} options output options to pass into the writer
- */
- function Writer(options) {
- options = assign({ format: false, preamble: true }, options || {});
- function toXML(tree, writer) {
- var internalWriter = writer || new SavingWriter();
- var formatingWriter = new FormatingWriter(internalWriter, options.format);
- if (options.preamble) {
- formatingWriter.append(XML_PREAMBLE);
- }
- new ElementSerializer().build(tree).serializeTo(formatingWriter);
- if (!writer) {
- return internalWriter.value;
- }
- }
- return {
- toXML: toXML
- };
- }
- /**
- * A sub class of {@link Moddle} with support for import and export of BPMN 2.0 xml files.
- *
- * @class BpmnModdle
- * @extends Moddle
- *
- * @param {Object|Array} packages to use for instantiating the model
- * @param {Object} [options] additional options to pass over
- */
- function BpmnModdle(packages, options) {
- Moddle.call(this, packages, options);
- }
- BpmnModdle.prototype = Object.create(Moddle.prototype);
- /**
- * The fromXML result.
- *
- * @typedef {Object} ParseResult
- *
- * @property {ModdleElement} rootElement
- * @property {Array<Object>} references
- * @property {Array<Error>} warnings
- * @property {Object} elementsById - a mapping containing each ID -> ModdleElement
- */
- /**
- * The fromXML error.
- *
- * @typedef {Error} ParseError
- *
- * @property {Array<Error>} warnings
- */
- /**
- * Instantiates a BPMN model tree from a given xml string.
- *
- * @param {String} xmlStr
- * @param {String} [typeName='bpmn:Definitions'] name of the root element
- * @param {Object} [options] options to pass to the underlying reader
- *
- * @returns {Promise<ParseResult, ParseError>}
- */
- BpmnModdle.prototype.fromXML = function(xmlStr, typeName, options) {
- if (!isString(typeName)) {
- options = typeName;
- typeName = 'bpmn:Definitions';
- }
- var reader = new Reader(assign({ model: this, lax: true }, options));
- var rootHandler = reader.handler(typeName);
- return reader.fromXML(xmlStr, rootHandler);
- };
- /**
- * The toXML result.
- *
- * @typedef {Object} SerializationResult
- *
- * @property {String} xml
- */
- /**
- * Serializes a BPMN 2.0 object tree to XML.
- *
- * @param {String} element the root element, typically an instance of `bpmn:Definitions`
- * @param {Object} [options] to pass to the underlying writer
- *
- * @returns {Promise<SerializationResult, Error>}
- */
- BpmnModdle.prototype.toXML = function(element, options) {
- var writer = new Writer(options);
- return new Promise(function(resolve, reject) {
- try {
- var result = writer.toXML(element);
- return resolve({
- xml: result
- });
- } catch (err) {
- return reject(err);
- }
- });
- };
- var name = "BPMN20";
- var uri = "http://www.omg.org/spec/BPMN/20100524/MODEL";
- var prefix = "bpmn";
- var associations = [
- ];
- var types = [
- {
- name: "Interface",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "operations",
- type: "Operation",
- isMany: true
- },
- {
- name: "implementationRef",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Operation",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "inMessageRef",
- type: "Message",
- isReference: true
- },
- {
- name: "outMessageRef",
- type: "Message",
- isReference: true
- },
- {
- name: "errorRef",
- type: "Error",
- isMany: true,
- isReference: true
- },
- {
- name: "implementationRef",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "EndPoint",
- superClass: [
- "RootElement"
- ]
- },
- {
- name: "Auditing",
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "GlobalTask",
- superClass: [
- "CallableElement"
- ],
- properties: [
- {
- name: "resources",
- type: "ResourceRole",
- isMany: true
- }
- ]
- },
- {
- name: "Monitoring",
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "Performer",
- superClass: [
- "ResourceRole"
- ]
- },
- {
- name: "Process",
- superClass: [
- "FlowElementsContainer",
- "CallableElement"
- ],
- properties: [
- {
- name: "processType",
- type: "ProcessType",
- isAttr: true
- },
- {
- name: "isClosed",
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "auditing",
- type: "Auditing"
- },
- {
- name: "monitoring",
- type: "Monitoring"
- },
- {
- name: "properties",
- type: "Property",
- isMany: true
- },
- {
- name: "laneSets",
- isMany: true,
- replaces: "FlowElementsContainer#laneSets",
- type: "LaneSet"
- },
- {
- name: "flowElements",
- isMany: true,
- replaces: "FlowElementsContainer#flowElements",
- type: "FlowElement"
- },
- {
- name: "artifacts",
- type: "Artifact",
- isMany: true
- },
- {
- name: "resources",
- type: "ResourceRole",
- isMany: true
- },
- {
- name: "correlationSubscriptions",
- type: "CorrelationSubscription",
- isMany: true
- },
- {
- name: "supports",
- type: "Process",
- isMany: true,
- isReference: true
- },
- {
- name: "definitionalCollaborationRef",
- type: "Collaboration",
- isAttr: true,
- isReference: true
- },
- {
- name: "isExecutable",
- isAttr: true,
- type: "Boolean"
- }
- ]
- },
- {
- name: "LaneSet",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "lanes",
- type: "Lane",
- isMany: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Lane",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "partitionElementRef",
- type: "BaseElement",
- isAttr: true,
- isReference: true
- },
- {
- name: "partitionElement",
- type: "BaseElement"
- },
- {
- name: "flowNodeRef",
- type: "FlowNode",
- isMany: true,
- isReference: true
- },
- {
- name: "childLaneSet",
- type: "LaneSet",
- xml: {
- serialize: "xsi:type"
- }
- }
- ]
- },
- {
- name: "GlobalManualTask",
- superClass: [
- "GlobalTask"
- ]
- },
- {
- name: "ManualTask",
- superClass: [
- "Task"
- ]
- },
- {
- name: "UserTask",
- superClass: [
- "Task"
- ],
- properties: [
- {
- name: "renderings",
- type: "Rendering",
- isMany: true
- },
- {
- name: "implementation",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Rendering",
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "HumanPerformer",
- superClass: [
- "Performer"
- ]
- },
- {
- name: "PotentialOwner",
- superClass: [
- "HumanPerformer"
- ]
- },
- {
- name: "GlobalUserTask",
- superClass: [
- "GlobalTask"
- ],
- properties: [
- {
- name: "implementation",
- isAttr: true,
- type: "String"
- },
- {
- name: "renderings",
- type: "Rendering",
- isMany: true
- }
- ]
- },
- {
- name: "Gateway",
- isAbstract: true,
- superClass: [
- "FlowNode"
- ],
- properties: [
- {
- name: "gatewayDirection",
- type: "GatewayDirection",
- "default": "Unspecified",
- isAttr: true
- }
- ]
- },
- {
- name: "EventBasedGateway",
- superClass: [
- "Gateway"
- ],
- properties: [
- {
- name: "instantiate",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "eventGatewayType",
- type: "EventBasedGatewayType",
- isAttr: true,
- "default": "Exclusive"
- }
- ]
- },
- {
- name: "ComplexGateway",
- superClass: [
- "Gateway"
- ],
- properties: [
- {
- name: "activationCondition",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "default",
- type: "SequenceFlow",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ExclusiveGateway",
- superClass: [
- "Gateway"
- ],
- properties: [
- {
- name: "default",
- type: "SequenceFlow",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "InclusiveGateway",
- superClass: [
- "Gateway"
- ],
- properties: [
- {
- name: "default",
- type: "SequenceFlow",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ParallelGateway",
- superClass: [
- "Gateway"
- ]
- },
- {
- name: "RootElement",
- isAbstract: true,
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "Relationship",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "type",
- isAttr: true,
- type: "String"
- },
- {
- name: "direction",
- type: "RelationshipDirection",
- isAttr: true
- },
- {
- name: "source",
- isMany: true,
- isReference: true,
- type: "Element"
- },
- {
- name: "target",
- isMany: true,
- isReference: true,
- type: "Element"
- }
- ]
- },
- {
- name: "BaseElement",
- isAbstract: true,
- properties: [
- {
- name: "id",
- isAttr: true,
- type: "String",
- isId: true
- },
- {
- name: "documentation",
- type: "Documentation",
- isMany: true
- },
- {
- name: "extensionDefinitions",
- type: "ExtensionDefinition",
- isMany: true,
- isReference: true
- },
- {
- name: "extensionElements",
- type: "ExtensionElements"
- }
- ]
- },
- {
- name: "Extension",
- properties: [
- {
- name: "mustUnderstand",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "definition",
- type: "ExtensionDefinition",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ExtensionDefinition",
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "extensionAttributeDefinitions",
- type: "ExtensionAttributeDefinition",
- isMany: true
- }
- ]
- },
- {
- name: "ExtensionAttributeDefinition",
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "type",
- isAttr: true,
- type: "String"
- },
- {
- name: "isReference",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "extensionDefinition",
- type: "ExtensionDefinition",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ExtensionElements",
- properties: [
- {
- name: "valueRef",
- isAttr: true,
- isReference: true,
- type: "Element"
- },
- {
- name: "values",
- type: "Element",
- isMany: true
- },
- {
- name: "extensionAttributeDefinition",
- type: "ExtensionAttributeDefinition",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Documentation",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "text",
- type: "String",
- isBody: true
- },
- {
- name: "textFormat",
- "default": "text/plain",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Event",
- isAbstract: true,
- superClass: [
- "FlowNode",
- "InteractionNode"
- ],
- properties: [
- {
- name: "properties",
- type: "Property",
- isMany: true
- }
- ]
- },
- {
- name: "IntermediateCatchEvent",
- superClass: [
- "CatchEvent"
- ]
- },
- {
- name: "IntermediateThrowEvent",
- superClass: [
- "ThrowEvent"
- ]
- },
- {
- name: "EndEvent",
- superClass: [
- "ThrowEvent"
- ]
- },
- {
- name: "StartEvent",
- superClass: [
- "CatchEvent"
- ],
- properties: [
- {
- name: "isInterrupting",
- "default": true,
- isAttr: true,
- type: "Boolean"
- }
- ]
- },
- {
- name: "ThrowEvent",
- isAbstract: true,
- superClass: [
- "Event"
- ],
- properties: [
- {
- name: "dataInputs",
- type: "DataInput",
- isMany: true
- },
- {
- name: "dataInputAssociations",
- type: "DataInputAssociation",
- isMany: true
- },
- {
- name: "inputSet",
- type: "InputSet"
- },
- {
- name: "eventDefinitions",
- type: "EventDefinition",
- isMany: true
- },
- {
- name: "eventDefinitionRef",
- type: "EventDefinition",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "CatchEvent",
- isAbstract: true,
- superClass: [
- "Event"
- ],
- properties: [
- {
- name: "parallelMultiple",
- isAttr: true,
- type: "Boolean",
- "default": false
- },
- {
- name: "dataOutputs",
- type: "DataOutput",
- isMany: true
- },
- {
- name: "dataOutputAssociations",
- type: "DataOutputAssociation",
- isMany: true
- },
- {
- name: "outputSet",
- type: "OutputSet"
- },
- {
- name: "eventDefinitions",
- type: "EventDefinition",
- isMany: true
- },
- {
- name: "eventDefinitionRef",
- type: "EventDefinition",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "BoundaryEvent",
- superClass: [
- "CatchEvent"
- ],
- properties: [
- {
- name: "cancelActivity",
- "default": true,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "attachedToRef",
- type: "Activity",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "EventDefinition",
- isAbstract: true,
- superClass: [
- "RootElement"
- ]
- },
- {
- name: "CancelEventDefinition",
- superClass: [
- "EventDefinition"
- ]
- },
- {
- name: "ErrorEventDefinition",
- superClass: [
- "EventDefinition"
- ],
- properties: [
- {
- name: "errorRef",
- type: "Error",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "TerminateEventDefinition",
- superClass: [
- "EventDefinition"
- ]
- },
- {
- name: "EscalationEventDefinition",
- superClass: [
- "EventDefinition"
- ],
- properties: [
- {
- name: "escalationRef",
- type: "Escalation",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Escalation",
- properties: [
- {
- name: "structureRef",
- type: "ItemDefinition",
- isAttr: true,
- isReference: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "escalationCode",
- isAttr: true,
- type: "String"
- }
- ],
- superClass: [
- "RootElement"
- ]
- },
- {
- name: "CompensateEventDefinition",
- superClass: [
- "EventDefinition"
- ],
- properties: [
- {
- name: "waitForCompletion",
- isAttr: true,
- type: "Boolean",
- "default": true
- },
- {
- name: "activityRef",
- type: "Activity",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "TimerEventDefinition",
- superClass: [
- "EventDefinition"
- ],
- properties: [
- {
- name: "timeDate",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "timeCycle",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "timeDuration",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- }
- ]
- },
- {
- name: "LinkEventDefinition",
- superClass: [
- "EventDefinition"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "target",
- type: "LinkEventDefinition",
- isAttr: true,
- isReference: true
- },
- {
- name: "source",
- type: "LinkEventDefinition",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "MessageEventDefinition",
- superClass: [
- "EventDefinition"
- ],
- properties: [
- {
- name: "messageRef",
- type: "Message",
- isAttr: true,
- isReference: true
- },
- {
- name: "operationRef",
- type: "Operation",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ConditionalEventDefinition",
- superClass: [
- "EventDefinition"
- ],
- properties: [
- {
- name: "condition",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- }
- ]
- },
- {
- name: "SignalEventDefinition",
- superClass: [
- "EventDefinition"
- ],
- properties: [
- {
- name: "signalRef",
- type: "Signal",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Signal",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "structureRef",
- type: "ItemDefinition",
- isAttr: true,
- isReference: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "ImplicitThrowEvent",
- superClass: [
- "ThrowEvent"
- ]
- },
- {
- name: "DataState",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "ItemAwareElement",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "itemSubjectRef",
- type: "ItemDefinition",
- isAttr: true,
- isReference: true
- },
- {
- name: "dataState",
- type: "DataState"
- }
- ]
- },
- {
- name: "DataAssociation",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "sourceRef",
- type: "ItemAwareElement",
- isMany: true,
- isReference: true
- },
- {
- name: "targetRef",
- type: "ItemAwareElement",
- isReference: true
- },
- {
- name: "transformation",
- type: "FormalExpression",
- xml: {
- serialize: "property"
- }
- },
- {
- name: "assignment",
- type: "Assignment",
- isMany: true
- }
- ]
- },
- {
- name: "DataInput",
- superClass: [
- "ItemAwareElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "isCollection",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "inputSetRef",
- type: "InputSet",
- isMany: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "inputSetWithOptional",
- type: "InputSet",
- isMany: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "inputSetWithWhileExecuting",
- type: "InputSet",
- isMany: true,
- isVirtual: true,
- isReference: true
- }
- ]
- },
- {
- name: "DataOutput",
- superClass: [
- "ItemAwareElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "isCollection",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "outputSetRef",
- type: "OutputSet",
- isMany: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "outputSetWithOptional",
- type: "OutputSet",
- isMany: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "outputSetWithWhileExecuting",
- type: "OutputSet",
- isMany: true,
- isVirtual: true,
- isReference: true
- }
- ]
- },
- {
- name: "InputSet",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "dataInputRefs",
- type: "DataInput",
- isMany: true,
- isReference: true
- },
- {
- name: "optionalInputRefs",
- type: "DataInput",
- isMany: true,
- isReference: true
- },
- {
- name: "whileExecutingInputRefs",
- type: "DataInput",
- isMany: true,
- isReference: true
- },
- {
- name: "outputSetRefs",
- type: "OutputSet",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "OutputSet",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "dataOutputRefs",
- type: "DataOutput",
- isMany: true,
- isReference: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "inputSetRefs",
- type: "InputSet",
- isMany: true,
- isReference: true
- },
- {
- name: "optionalOutputRefs",
- type: "DataOutput",
- isMany: true,
- isReference: true
- },
- {
- name: "whileExecutingOutputRefs",
- type: "DataOutput",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "Property",
- superClass: [
- "ItemAwareElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "DataInputAssociation",
- superClass: [
- "DataAssociation"
- ]
- },
- {
- name: "DataOutputAssociation",
- superClass: [
- "DataAssociation"
- ]
- },
- {
- name: "InputOutputSpecification",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "dataInputs",
- type: "DataInput",
- isMany: true
- },
- {
- name: "dataOutputs",
- type: "DataOutput",
- isMany: true
- },
- {
- name: "inputSets",
- type: "InputSet",
- isMany: true
- },
- {
- name: "outputSets",
- type: "OutputSet",
- isMany: true
- }
- ]
- },
- {
- name: "DataObject",
- superClass: [
- "FlowElement",
- "ItemAwareElement"
- ],
- properties: [
- {
- name: "isCollection",
- "default": false,
- isAttr: true,
- type: "Boolean"
- }
- ]
- },
- {
- name: "InputOutputBinding",
- properties: [
- {
- name: "inputDataRef",
- type: "InputSet",
- isAttr: true,
- isReference: true
- },
- {
- name: "outputDataRef",
- type: "OutputSet",
- isAttr: true,
- isReference: true
- },
- {
- name: "operationRef",
- type: "Operation",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Assignment",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "from",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "to",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- }
- ]
- },
- {
- name: "DataStore",
- superClass: [
- "RootElement",
- "ItemAwareElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "capacity",
- isAttr: true,
- type: "Integer"
- },
- {
- name: "isUnlimited",
- "default": true,
- isAttr: true,
- type: "Boolean"
- }
- ]
- },
- {
- name: "DataStoreReference",
- superClass: [
- "ItemAwareElement",
- "FlowElement"
- ],
- properties: [
- {
- name: "dataStoreRef",
- type: "DataStore",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "DataObjectReference",
- superClass: [
- "ItemAwareElement",
- "FlowElement"
- ],
- properties: [
- {
- name: "dataObjectRef",
- type: "DataObject",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ConversationLink",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "sourceRef",
- type: "InteractionNode",
- isAttr: true,
- isReference: true
- },
- {
- name: "targetRef",
- type: "InteractionNode",
- isAttr: true,
- isReference: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "ConversationAssociation",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "innerConversationNodeRef",
- type: "ConversationNode",
- isAttr: true,
- isReference: true
- },
- {
- name: "outerConversationNodeRef",
- type: "ConversationNode",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "CallConversation",
- superClass: [
- "ConversationNode"
- ],
- properties: [
- {
- name: "calledCollaborationRef",
- type: "Collaboration",
- isAttr: true,
- isReference: true
- },
- {
- name: "participantAssociations",
- type: "ParticipantAssociation",
- isMany: true
- }
- ]
- },
- {
- name: "Conversation",
- superClass: [
- "ConversationNode"
- ]
- },
- {
- name: "SubConversation",
- superClass: [
- "ConversationNode"
- ],
- properties: [
- {
- name: "conversationNodes",
- type: "ConversationNode",
- isMany: true
- }
- ]
- },
- {
- name: "ConversationNode",
- isAbstract: true,
- superClass: [
- "InteractionNode",
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "participantRef",
- type: "Participant",
- isMany: true,
- isReference: true
- },
- {
- name: "messageFlowRefs",
- type: "MessageFlow",
- isMany: true,
- isReference: true
- },
- {
- name: "correlationKeys",
- type: "CorrelationKey",
- isMany: true
- }
- ]
- },
- {
- name: "GlobalConversation",
- superClass: [
- "Collaboration"
- ]
- },
- {
- name: "PartnerEntity",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "participantRef",
- type: "Participant",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "PartnerRole",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "participantRef",
- type: "Participant",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "CorrelationProperty",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "correlationPropertyRetrievalExpression",
- type: "CorrelationPropertyRetrievalExpression",
- isMany: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "type",
- type: "ItemDefinition",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Error",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "structureRef",
- type: "ItemDefinition",
- isAttr: true,
- isReference: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "errorCode",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "CorrelationKey",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "correlationPropertyRef",
- type: "CorrelationProperty",
- isMany: true,
- isReference: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Expression",
- superClass: [
- "BaseElement"
- ],
- isAbstract: false,
- properties: [
- {
- name: "body",
- isBody: true,
- type: "String"
- }
- ]
- },
- {
- name: "FormalExpression",
- superClass: [
- "Expression"
- ],
- properties: [
- {
- name: "language",
- isAttr: true,
- type: "String"
- },
- {
- name: "evaluatesToTypeRef",
- type: "ItemDefinition",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Message",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "itemRef",
- type: "ItemDefinition",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ItemDefinition",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "itemKind",
- type: "ItemKind",
- isAttr: true
- },
- {
- name: "structureRef",
- isAttr: true,
- type: "String"
- },
- {
- name: "isCollection",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "import",
- type: "Import",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "FlowElement",
- isAbstract: true,
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "auditing",
- type: "Auditing"
- },
- {
- name: "monitoring",
- type: "Monitoring"
- },
- {
- name: "categoryValueRef",
- type: "CategoryValue",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "SequenceFlow",
- superClass: [
- "FlowElement"
- ],
- properties: [
- {
- name: "isImmediate",
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "conditionExpression",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "sourceRef",
- type: "FlowNode",
- isAttr: true,
- isReference: true
- },
- {
- name: "targetRef",
- type: "FlowNode",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "FlowElementsContainer",
- isAbstract: true,
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "laneSets",
- type: "LaneSet",
- isMany: true
- },
- {
- name: "flowElements",
- type: "FlowElement",
- isMany: true
- }
- ]
- },
- {
- name: "CallableElement",
- isAbstract: true,
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "ioSpecification",
- type: "InputOutputSpecification",
- xml: {
- serialize: "property"
- }
- },
- {
- name: "supportedInterfaceRef",
- type: "Interface",
- isMany: true,
- isReference: true
- },
- {
- name: "ioBinding",
- type: "InputOutputBinding",
- isMany: true,
- xml: {
- serialize: "property"
- }
- }
- ]
- },
- {
- name: "FlowNode",
- isAbstract: true,
- superClass: [
- "FlowElement"
- ],
- properties: [
- {
- name: "incoming",
- type: "SequenceFlow",
- isMany: true,
- isReference: true
- },
- {
- name: "outgoing",
- type: "SequenceFlow",
- isMany: true,
- isReference: true
- },
- {
- name: "lanes",
- type: "Lane",
- isMany: true,
- isVirtual: true,
- isReference: true
- }
- ]
- },
- {
- name: "CorrelationPropertyRetrievalExpression",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "messagePath",
- type: "FormalExpression"
- },
- {
- name: "messageRef",
- type: "Message",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "CorrelationPropertyBinding",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "dataPath",
- type: "FormalExpression"
- },
- {
- name: "correlationPropertyRef",
- type: "CorrelationProperty",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Resource",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "resourceParameters",
- type: "ResourceParameter",
- isMany: true
- }
- ]
- },
- {
- name: "ResourceParameter",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "isRequired",
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "type",
- type: "ItemDefinition",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "CorrelationSubscription",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "correlationKeyRef",
- type: "CorrelationKey",
- isAttr: true,
- isReference: true
- },
- {
- name: "correlationPropertyBinding",
- type: "CorrelationPropertyBinding",
- isMany: true
- }
- ]
- },
- {
- name: "MessageFlow",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "sourceRef",
- type: "InteractionNode",
- isAttr: true,
- isReference: true
- },
- {
- name: "targetRef",
- type: "InteractionNode",
- isAttr: true,
- isReference: true
- },
- {
- name: "messageRef",
- type: "Message",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "MessageFlowAssociation",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "innerMessageFlowRef",
- type: "MessageFlow",
- isAttr: true,
- isReference: true
- },
- {
- name: "outerMessageFlowRef",
- type: "MessageFlow",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "InteractionNode",
- isAbstract: true,
- properties: [
- {
- name: "incomingConversationLinks",
- type: "ConversationLink",
- isMany: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "outgoingConversationLinks",
- type: "ConversationLink",
- isMany: true,
- isVirtual: true,
- isReference: true
- }
- ]
- },
- {
- name: "Participant",
- superClass: [
- "InteractionNode",
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "interfaceRef",
- type: "Interface",
- isMany: true,
- isReference: true
- },
- {
- name: "participantMultiplicity",
- type: "ParticipantMultiplicity"
- },
- {
- name: "endPointRefs",
- type: "EndPoint",
- isMany: true,
- isReference: true
- },
- {
- name: "processRef",
- type: "Process",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ParticipantAssociation",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "innerParticipantRef",
- type: "Participant",
- isAttr: true,
- isReference: true
- },
- {
- name: "outerParticipantRef",
- type: "Participant",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ParticipantMultiplicity",
- properties: [
- {
- name: "minimum",
- "default": 0,
- isAttr: true,
- type: "Integer"
- },
- {
- name: "maximum",
- "default": 1,
- isAttr: true,
- type: "Integer"
- }
- ],
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "Collaboration",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "isClosed",
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "participants",
- type: "Participant",
- isMany: true
- },
- {
- name: "messageFlows",
- type: "MessageFlow",
- isMany: true
- },
- {
- name: "artifacts",
- type: "Artifact",
- isMany: true
- },
- {
- name: "conversations",
- type: "ConversationNode",
- isMany: true
- },
- {
- name: "conversationAssociations",
- type: "ConversationAssociation"
- },
- {
- name: "participantAssociations",
- type: "ParticipantAssociation",
- isMany: true
- },
- {
- name: "messageFlowAssociations",
- type: "MessageFlowAssociation",
- isMany: true
- },
- {
- name: "correlationKeys",
- type: "CorrelationKey",
- isMany: true
- },
- {
- name: "choreographyRef",
- type: "Choreography",
- isMany: true,
- isReference: true
- },
- {
- name: "conversationLinks",
- type: "ConversationLink",
- isMany: true
- }
- ]
- },
- {
- name: "ChoreographyActivity",
- isAbstract: true,
- superClass: [
- "FlowNode"
- ],
- properties: [
- {
- name: "participantRef",
- type: "Participant",
- isMany: true,
- isReference: true
- },
- {
- name: "initiatingParticipantRef",
- type: "Participant",
- isAttr: true,
- isReference: true
- },
- {
- name: "correlationKeys",
- type: "CorrelationKey",
- isMany: true
- },
- {
- name: "loopType",
- type: "ChoreographyLoopType",
- "default": "None",
- isAttr: true
- }
- ]
- },
- {
- name: "CallChoreography",
- superClass: [
- "ChoreographyActivity"
- ],
- properties: [
- {
- name: "calledChoreographyRef",
- type: "Choreography",
- isAttr: true,
- isReference: true
- },
- {
- name: "participantAssociations",
- type: "ParticipantAssociation",
- isMany: true
- }
- ]
- },
- {
- name: "SubChoreography",
- superClass: [
- "ChoreographyActivity",
- "FlowElementsContainer"
- ],
- properties: [
- {
- name: "artifacts",
- type: "Artifact",
- isMany: true
- }
- ]
- },
- {
- name: "ChoreographyTask",
- superClass: [
- "ChoreographyActivity"
- ],
- properties: [
- {
- name: "messageFlowRef",
- type: "MessageFlow",
- isMany: true,
- isReference: true
- }
- ]
- },
- {
- name: "Choreography",
- superClass: [
- "Collaboration",
- "FlowElementsContainer"
- ]
- },
- {
- name: "GlobalChoreographyTask",
- superClass: [
- "Choreography"
- ],
- properties: [
- {
- name: "initiatingParticipantRef",
- type: "Participant",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "TextAnnotation",
- superClass: [
- "Artifact"
- ],
- properties: [
- {
- name: "text",
- type: "String"
- },
- {
- name: "textFormat",
- "default": "text/plain",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Group",
- superClass: [
- "Artifact"
- ],
- properties: [
- {
- name: "categoryValueRef",
- type: "CategoryValue",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Association",
- superClass: [
- "Artifact"
- ],
- properties: [
- {
- name: "associationDirection",
- type: "AssociationDirection",
- isAttr: true
- },
- {
- name: "sourceRef",
- type: "BaseElement",
- isAttr: true,
- isReference: true
- },
- {
- name: "targetRef",
- type: "BaseElement",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "Category",
- superClass: [
- "RootElement"
- ],
- properties: [
- {
- name: "categoryValue",
- type: "CategoryValue",
- isMany: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Artifact",
- isAbstract: true,
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "CategoryValue",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "categorizedFlowElements",
- type: "FlowElement",
- isMany: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "value",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Activity",
- isAbstract: true,
- superClass: [
- "FlowNode"
- ],
- properties: [
- {
- name: "isForCompensation",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "default",
- type: "SequenceFlow",
- isAttr: true,
- isReference: true
- },
- {
- name: "ioSpecification",
- type: "InputOutputSpecification",
- xml: {
- serialize: "property"
- }
- },
- {
- name: "boundaryEventRefs",
- type: "BoundaryEvent",
- isMany: true,
- isReference: true
- },
- {
- name: "properties",
- type: "Property",
- isMany: true
- },
- {
- name: "dataInputAssociations",
- type: "DataInputAssociation",
- isMany: true
- },
- {
- name: "dataOutputAssociations",
- type: "DataOutputAssociation",
- isMany: true
- },
- {
- name: "startQuantity",
- "default": 1,
- isAttr: true,
- type: "Integer"
- },
- {
- name: "resources",
- type: "ResourceRole",
- isMany: true
- },
- {
- name: "completionQuantity",
- "default": 1,
- isAttr: true,
- type: "Integer"
- },
- {
- name: "loopCharacteristics",
- type: "LoopCharacteristics"
- }
- ]
- },
- {
- name: "ServiceTask",
- superClass: [
- "Task"
- ],
- properties: [
- {
- name: "implementation",
- isAttr: true,
- type: "String"
- },
- {
- name: "operationRef",
- type: "Operation",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "SubProcess",
- superClass: [
- "Activity",
- "FlowElementsContainer",
- "InteractionNode"
- ],
- properties: [
- {
- name: "triggeredByEvent",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "artifacts",
- type: "Artifact",
- isMany: true
- }
- ]
- },
- {
- name: "LoopCharacteristics",
- isAbstract: true,
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "MultiInstanceLoopCharacteristics",
- superClass: [
- "LoopCharacteristics"
- ],
- properties: [
- {
- name: "isSequential",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "behavior",
- type: "MultiInstanceBehavior",
- "default": "All",
- isAttr: true
- },
- {
- name: "loopCardinality",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "loopDataInputRef",
- type: "ItemAwareElement",
- isReference: true
- },
- {
- name: "loopDataOutputRef",
- type: "ItemAwareElement",
- isReference: true
- },
- {
- name: "inputDataItem",
- type: "DataInput",
- xml: {
- serialize: "property"
- }
- },
- {
- name: "outputDataItem",
- type: "DataOutput",
- xml: {
- serialize: "property"
- }
- },
- {
- name: "complexBehaviorDefinition",
- type: "ComplexBehaviorDefinition",
- isMany: true
- },
- {
- name: "completionCondition",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "oneBehaviorEventRef",
- type: "EventDefinition",
- isAttr: true,
- isReference: true
- },
- {
- name: "noneBehaviorEventRef",
- type: "EventDefinition",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "StandardLoopCharacteristics",
- superClass: [
- "LoopCharacteristics"
- ],
- properties: [
- {
- name: "testBefore",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "loopCondition",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "loopMaximum",
- type: "Integer",
- isAttr: true
- }
- ]
- },
- {
- name: "CallActivity",
- superClass: [
- "Activity",
- "InteractionNode"
- ],
- properties: [
- {
- name: "calledElement",
- type: "String",
- isAttr: true
- }
- ]
- },
- {
- name: "Task",
- superClass: [
- "Activity",
- "InteractionNode"
- ]
- },
- {
- name: "SendTask",
- superClass: [
- "Task"
- ],
- properties: [
- {
- name: "implementation",
- isAttr: true,
- type: "String"
- },
- {
- name: "operationRef",
- type: "Operation",
- isAttr: true,
- isReference: true
- },
- {
- name: "messageRef",
- type: "Message",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ReceiveTask",
- superClass: [
- "Task"
- ],
- properties: [
- {
- name: "implementation",
- isAttr: true,
- type: "String"
- },
- {
- name: "instantiate",
- "default": false,
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "operationRef",
- type: "Operation",
- isAttr: true,
- isReference: true
- },
- {
- name: "messageRef",
- type: "Message",
- isAttr: true,
- isReference: true
- }
- ]
- },
- {
- name: "ScriptTask",
- superClass: [
- "Task"
- ],
- properties: [
- {
- name: "scriptFormat",
- isAttr: true,
- type: "String"
- },
- {
- name: "script",
- type: "String"
- }
- ]
- },
- {
- name: "BusinessRuleTask",
- superClass: [
- "Task"
- ],
- properties: [
- {
- name: "implementation",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "AdHocSubProcess",
- superClass: [
- "SubProcess"
- ],
- properties: [
- {
- name: "completionCondition",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "ordering",
- type: "AdHocOrdering",
- isAttr: true
- },
- {
- name: "cancelRemainingInstances",
- "default": true,
- isAttr: true,
- type: "Boolean"
- }
- ]
- },
- {
- name: "Transaction",
- superClass: [
- "SubProcess"
- ],
- properties: [
- {
- name: "protocol",
- isAttr: true,
- type: "String"
- },
- {
- name: "method",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "GlobalScriptTask",
- superClass: [
- "GlobalTask"
- ],
- properties: [
- {
- name: "scriptLanguage",
- isAttr: true,
- type: "String"
- },
- {
- name: "script",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "GlobalBusinessRuleTask",
- superClass: [
- "GlobalTask"
- ],
- properties: [
- {
- name: "implementation",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "ComplexBehaviorDefinition",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "condition",
- type: "FormalExpression"
- },
- {
- name: "event",
- type: "ImplicitThrowEvent"
- }
- ]
- },
- {
- name: "ResourceRole",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "resourceRef",
- type: "Resource",
- isReference: true
- },
- {
- name: "resourceParameterBindings",
- type: "ResourceParameterBinding",
- isMany: true
- },
- {
- name: "resourceAssignmentExpression",
- type: "ResourceAssignmentExpression"
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "ResourceParameterBinding",
- properties: [
- {
- name: "expression",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- },
- {
- name: "parameterRef",
- type: "ResourceParameter",
- isAttr: true,
- isReference: true
- }
- ],
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "ResourceAssignmentExpression",
- properties: [
- {
- name: "expression",
- type: "Expression",
- xml: {
- serialize: "xsi:type"
- }
- }
- ],
- superClass: [
- "BaseElement"
- ]
- },
- {
- name: "Import",
- properties: [
- {
- name: "importType",
- isAttr: true,
- type: "String"
- },
- {
- name: "location",
- isAttr: true,
- type: "String"
- },
- {
- name: "namespace",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "Definitions",
- superClass: [
- "BaseElement"
- ],
- properties: [
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "targetNamespace",
- isAttr: true,
- type: "String"
- },
- {
- name: "expressionLanguage",
- "default": "http://www.w3.org/1999/XPath",
- isAttr: true,
- type: "String"
- },
- {
- name: "typeLanguage",
- "default": "http://www.w3.org/2001/XMLSchema",
- isAttr: true,
- type: "String"
- },
- {
- name: "imports",
- type: "Import",
- isMany: true
- },
- {
- name: "extensions",
- type: "Extension",
- isMany: true
- },
- {
- name: "rootElements",
- type: "RootElement",
- isMany: true
- },
- {
- name: "diagrams",
- isMany: true,
- type: "bpmndi:BPMNDiagram"
- },
- {
- name: "exporter",
- isAttr: true,
- type: "String"
- },
- {
- name: "relationships",
- type: "Relationship",
- isMany: true
- },
- {
- name: "exporterVersion",
- isAttr: true,
- type: "String"
- }
- ]
- }
- ];
- var enumerations = [
- {
- name: "ProcessType",
- literalValues: [
- {
- name: "None"
- },
- {
- name: "Public"
- },
- {
- name: "Private"
- }
- ]
- },
- {
- name: "GatewayDirection",
- literalValues: [
- {
- name: "Unspecified"
- },
- {
- name: "Converging"
- },
- {
- name: "Diverging"
- },
- {
- name: "Mixed"
- }
- ]
- },
- {
- name: "EventBasedGatewayType",
- literalValues: [
- {
- name: "Parallel"
- },
- {
- name: "Exclusive"
- }
- ]
- },
- {
- name: "RelationshipDirection",
- literalValues: [
- {
- name: "None"
- },
- {
- name: "Forward"
- },
- {
- name: "Backward"
- },
- {
- name: "Both"
- }
- ]
- },
- {
- name: "ItemKind",
- literalValues: [
- {
- name: "Physical"
- },
- {
- name: "Information"
- }
- ]
- },
- {
- name: "ChoreographyLoopType",
- literalValues: [
- {
- name: "None"
- },
- {
- name: "Standard"
- },
- {
- name: "MultiInstanceSequential"
- },
- {
- name: "MultiInstanceParallel"
- }
- ]
- },
- {
- name: "AssociationDirection",
- literalValues: [
- {
- name: "None"
- },
- {
- name: "One"
- },
- {
- name: "Both"
- }
- ]
- },
- {
- name: "MultiInstanceBehavior",
- literalValues: [
- {
- name: "None"
- },
- {
- name: "One"
- },
- {
- name: "All"
- },
- {
- name: "Complex"
- }
- ]
- },
- {
- name: "AdHocOrdering",
- literalValues: [
- {
- name: "Parallel"
- },
- {
- name: "Sequential"
- }
- ]
- }
- ];
- var xml = {
- tagAlias: "lowerCase",
- typePrefix: "t"
- };
- var BpmnPackage = {
- name: name,
- uri: uri,
- prefix: prefix,
- associations: associations,
- types: types,
- enumerations: enumerations,
- xml: xml
- };
- var name$1 = "BPMNDI";
- var uri$1 = "http://www.omg.org/spec/BPMN/20100524/DI";
- var prefix$1 = "bpmndi";
- var types$1 = [
- {
- name: "BPMNDiagram",
- properties: [
- {
- name: "plane",
- type: "BPMNPlane",
- redefines: "di:Diagram#rootElement"
- },
- {
- name: "labelStyle",
- type: "BPMNLabelStyle",
- isMany: true
- }
- ],
- superClass: [
- "di:Diagram"
- ]
- },
- {
- name: "BPMNPlane",
- properties: [
- {
- name: "bpmnElement",
- isAttr: true,
- isReference: true,
- type: "bpmn:BaseElement",
- redefines: "di:DiagramElement#modelElement"
- }
- ],
- superClass: [
- "di:Plane"
- ]
- },
- {
- name: "BPMNShape",
- properties: [
- {
- name: "bpmnElement",
- isAttr: true,
- isReference: true,
- type: "bpmn:BaseElement",
- redefines: "di:DiagramElement#modelElement"
- },
- {
- name: "isHorizontal",
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "isExpanded",
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "isMarkerVisible",
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "label",
- type: "BPMNLabel"
- },
- {
- name: "isMessageVisible",
- isAttr: true,
- type: "Boolean"
- },
- {
- name: "participantBandKind",
- type: "ParticipantBandKind",
- isAttr: true
- },
- {
- name: "choreographyActivityShape",
- type: "BPMNShape",
- isAttr: true,
- isReference: true
- }
- ],
- superClass: [
- "di:LabeledShape"
- ]
- },
- {
- name: "BPMNEdge",
- properties: [
- {
- name: "label",
- type: "BPMNLabel"
- },
- {
- name: "bpmnElement",
- isAttr: true,
- isReference: true,
- type: "bpmn:BaseElement",
- redefines: "di:DiagramElement#modelElement"
- },
- {
- name: "sourceElement",
- isAttr: true,
- isReference: true,
- type: "di:DiagramElement",
- redefines: "di:Edge#source"
- },
- {
- name: "targetElement",
- isAttr: true,
- isReference: true,
- type: "di:DiagramElement",
- redefines: "di:Edge#target"
- },
- {
- name: "messageVisibleKind",
- type: "MessageVisibleKind",
- isAttr: true,
- "default": "initiating"
- }
- ],
- superClass: [
- "di:LabeledEdge"
- ]
- },
- {
- name: "BPMNLabel",
- properties: [
- {
- name: "labelStyle",
- type: "BPMNLabelStyle",
- isAttr: true,
- isReference: true,
- redefines: "di:DiagramElement#style"
- }
- ],
- superClass: [
- "di:Label"
- ]
- },
- {
- name: "BPMNLabelStyle",
- properties: [
- {
- name: "font",
- type: "dc:Font"
- }
- ],
- superClass: [
- "di:Style"
- ]
- }
- ];
- var enumerations$1 = [
- {
- name: "ParticipantBandKind",
- literalValues: [
- {
- name: "top_initiating"
- },
- {
- name: "middle_initiating"
- },
- {
- name: "bottom_initiating"
- },
- {
- name: "top_non_initiating"
- },
- {
- name: "middle_non_initiating"
- },
- {
- name: "bottom_non_initiating"
- }
- ]
- },
- {
- name: "MessageVisibleKind",
- literalValues: [
- {
- name: "initiating"
- },
- {
- name: "non_initiating"
- }
- ]
- }
- ];
- var associations$1 = [
- ];
- var BpmnDiPackage = {
- name: name$1,
- uri: uri$1,
- prefix: prefix$1,
- types: types$1,
- enumerations: enumerations$1,
- associations: associations$1
- };
- var name$2 = "DC";
- var uri$2 = "http://www.omg.org/spec/DD/20100524/DC";
- var prefix$2 = "dc";
- var types$2 = [
- {
- name: "Boolean"
- },
- {
- name: "Integer"
- },
- {
- name: "Real"
- },
- {
- name: "String"
- },
- {
- name: "Font",
- properties: [
- {
- name: "name",
- type: "String",
- isAttr: true
- },
- {
- name: "size",
- type: "Real",
- isAttr: true
- },
- {
- name: "isBold",
- type: "Boolean",
- isAttr: true
- },
- {
- name: "isItalic",
- type: "Boolean",
- isAttr: true
- },
- {
- name: "isUnderline",
- type: "Boolean",
- isAttr: true
- },
- {
- name: "isStrikeThrough",
- type: "Boolean",
- isAttr: true
- }
- ]
- },
- {
- name: "Point",
- properties: [
- {
- name: "x",
- type: "Real",
- "default": "0",
- isAttr: true
- },
- {
- name: "y",
- type: "Real",
- "default": "0",
- isAttr: true
- }
- ]
- },
- {
- name: "Bounds",
- properties: [
- {
- name: "x",
- type: "Real",
- "default": "0",
- isAttr: true
- },
- {
- name: "y",
- type: "Real",
- "default": "0",
- isAttr: true
- },
- {
- name: "width",
- type: "Real",
- isAttr: true
- },
- {
- name: "height",
- type: "Real",
- isAttr: true
- }
- ]
- }
- ];
- var associations$2 = [
- ];
- var DcPackage = {
- name: name$2,
- uri: uri$2,
- prefix: prefix$2,
- types: types$2,
- associations: associations$2
- };
- var name$3 = "DI";
- var uri$3 = "http://www.omg.org/spec/DD/20100524/DI";
- var prefix$3 = "di";
- var types$3 = [
- {
- name: "DiagramElement",
- isAbstract: true,
- properties: [
- {
- name: "id",
- isAttr: true,
- isId: true,
- type: "String"
- },
- {
- name: "extension",
- type: "Extension"
- },
- {
- name: "owningDiagram",
- type: "Diagram",
- isReadOnly: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "owningElement",
- type: "DiagramElement",
- isReadOnly: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "modelElement",
- isReadOnly: true,
- isVirtual: true,
- isReference: true,
- type: "Element"
- },
- {
- name: "style",
- type: "Style",
- isReadOnly: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "ownedElement",
- type: "DiagramElement",
- isReadOnly: true,
- isMany: true,
- isVirtual: true
- }
- ]
- },
- {
- name: "Node",
- isAbstract: true,
- superClass: [
- "DiagramElement"
- ]
- },
- {
- name: "Edge",
- isAbstract: true,
- superClass: [
- "DiagramElement"
- ],
- properties: [
- {
- name: "source",
- type: "DiagramElement",
- isReadOnly: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "target",
- type: "DiagramElement",
- isReadOnly: true,
- isVirtual: true,
- isReference: true
- },
- {
- name: "waypoint",
- isUnique: false,
- isMany: true,
- type: "dc:Point",
- xml: {
- serialize: "xsi:type"
- }
- }
- ]
- },
- {
- name: "Diagram",
- isAbstract: true,
- properties: [
- {
- name: "id",
- isAttr: true,
- isId: true,
- type: "String"
- },
- {
- name: "rootElement",
- type: "DiagramElement",
- isReadOnly: true,
- isVirtual: true
- },
- {
- name: "name",
- isAttr: true,
- type: "String"
- },
- {
- name: "documentation",
- isAttr: true,
- type: "String"
- },
- {
- name: "resolution",
- isAttr: true,
- type: "Real"
- },
- {
- name: "ownedStyle",
- type: "Style",
- isReadOnly: true,
- isMany: true,
- isVirtual: true
- }
- ]
- },
- {
- name: "Shape",
- isAbstract: true,
- superClass: [
- "Node"
- ],
- properties: [
- {
- name: "bounds",
- type: "dc:Bounds"
- }
- ]
- },
- {
- name: "Plane",
- isAbstract: true,
- superClass: [
- "Node"
- ],
- properties: [
- {
- name: "planeElement",
- type: "DiagramElement",
- subsettedProperty: "DiagramElement-ownedElement",
- isMany: true
- }
- ]
- },
- {
- name: "LabeledEdge",
- isAbstract: true,
- superClass: [
- "Edge"
- ],
- properties: [
- {
- name: "ownedLabel",
- type: "Label",
- isReadOnly: true,
- subsettedProperty: "DiagramElement-ownedElement",
- isMany: true,
- isVirtual: true
- }
- ]
- },
- {
- name: "LabeledShape",
- isAbstract: true,
- superClass: [
- "Shape"
- ],
- properties: [
- {
- name: "ownedLabel",
- type: "Label",
- isReadOnly: true,
- subsettedProperty: "DiagramElement-ownedElement",
- isMany: true,
- isVirtual: true
- }
- ]
- },
- {
- name: "Label",
- isAbstract: true,
- superClass: [
- "Node"
- ],
- properties: [
- {
- name: "bounds",
- type: "dc:Bounds"
- }
- ]
- },
- {
- name: "Style",
- isAbstract: true,
- properties: [
- {
- name: "id",
- isAttr: true,
- isId: true,
- type: "String"
- }
- ]
- },
- {
- name: "Extension",
- properties: [
- {
- name: "values",
- isMany: true,
- type: "Element"
- }
- ]
- }
- ];
- var associations$3 = [
- ];
- var xml$1 = {
- tagAlias: "lowerCase"
- };
- var DiPackage = {
- name: name$3,
- uri: uri$3,
- prefix: prefix$3,
- types: types$3,
- associations: associations$3,
- xml: xml$1
- };
- var name$4 = "bpmn.io colors for BPMN";
- var uri$4 = "http://bpmn.io/schema/bpmn/biocolor/1.0";
- var prefix$4 = "bioc";
- var types$4 = [
- {
- name: "ColoredShape",
- "extends": [
- "bpmndi:BPMNShape"
- ],
- properties: [
- {
- name: "stroke",
- isAttr: true,
- type: "String"
- },
- {
- name: "fill",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "ColoredEdge",
- "extends": [
- "bpmndi:BPMNEdge"
- ],
- properties: [
- {
- name: "stroke",
- isAttr: true,
- type: "String"
- },
- {
- name: "fill",
- isAttr: true,
- type: "String"
- }
- ]
- }
- ];
- var enumerations$2 = [
- ];
- var associations$4 = [
- ];
- var BiocPackage = {
- name: name$4,
- uri: uri$4,
- prefix: prefix$4,
- types: types$4,
- enumerations: enumerations$2,
- associations: associations$4
- };
- var name$5 = "BPMN in Color";
- var uri$5 = "http://www.omg.org/spec/BPMN/non-normative/color/1.0";
- var prefix$5 = "color";
- var types$5 = [
- {
- name: "ColoredLabel",
- "extends": [
- "bpmndi:BPMNLabel"
- ],
- properties: [
- {
- name: "color",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "ColoredShape",
- "extends": [
- "bpmndi:BPMNShape"
- ],
- properties: [
- {
- name: "background-color",
- isAttr: true,
- type: "String"
- },
- {
- name: "border-color",
- isAttr: true,
- type: "String"
- }
- ]
- },
- {
- name: "ColoredEdge",
- "extends": [
- "bpmndi:BPMNEdge"
- ],
- properties: [
- {
- name: "border-color",
- isAttr: true,
- type: "String"
- }
- ]
- }
- ];
- var enumerations$3 = [
- ];
- var associations$5 = [
- ];
- var BpmnInColorPackage = {
- name: name$5,
- uri: uri$5,
- prefix: prefix$5,
- types: types$5,
- enumerations: enumerations$3,
- associations: associations$5
- };
- var packages = {
- bpmn: BpmnPackage,
- bpmndi: BpmnDiPackage,
- dc: DcPackage,
- di: DiPackage,
- bioc: BiocPackage,
- color: BpmnInColorPackage
- };
- function simple(additionalPackages, options) {
- var pks = assign({}, packages, additionalPackages);
- return new BpmnModdle(pks, options);
- }
- // TODO(nikku): remove with future bpmn-js version
- /**
- * Wraps APIs to check:
- *
- * 1) If a callback is passed -> Warn users about callback deprecation.
- * 2) If Promise class is implemented in current environment.
- *
- * @private
- */
- function wrapForCompatibility(api) {
- return function() {
- if (!window.Promise) {
- throw new Error('Promises is not supported in this environment. Please polyfill Promise.');
- }
- var argLen = arguments.length;
- if (argLen >= 1 && isFunction(arguments[argLen - 1])) {
- var callback = arguments[argLen - 1];
- console.warn(new Error(
- 'Passing callbacks to ' + api.name + ' is deprecated and will be removed in a future major release. ' +
- 'Please switch to promises: https://bpmn.io/l/moving-to-promises.html'
- ));
- var argsWithoutCallback = Array.prototype.slice.call(arguments, 0, -1);
- api.apply(this, argsWithoutCallback).then(function(result) {
- var firstKey = Object.keys(result)[0];
- // The APIs we are wrapping all resolve a single item depending on the API.
- // For instance, importXML resolves { warnings } and saveXML returns { xml }.
- // That's why we can call the callback with the first item of result.
- return callback(null, result[firstKey]);
- // Passing a second paramter instead of catch because we don't want to
- // catch errors thrown by callback().
- }, function(err) {
- return callback(err, err.warnings);
- });
- } else {
- return api.apply(this, arguments);
- }
- };
- }
- // TODO(nikku): remove with future bpmn-js version
- var DI_ERROR_MESSAGE = 'Tried to access di from the businessObject. The di is available through the diagram element only. For more information, see https://github.com/bpmn-io/bpmn-js/issues/1472';
- function ensureCompatDiRef(businessObject) {
- // bpmnElement can have multiple independent DIs
- if (!has$1(businessObject, 'di')) {
- Object.defineProperty(businessObject, 'di', {
- get: function() {
- throw new Error(DI_ERROR_MESSAGE);
- }
- });
- }
- }
- /**
- * Returns true if an element has the given meta-model type
- *
- * @param {ModdleElement} element
- * @param {string} type
- *
- * @return {boolean}
- */
- function is(element, type) {
- return element.$instanceOf(type);
- }
- /**
- * Find a suitable display candidate for definitions where the DI does not
- * correctly specify one.
- */
- function findDisplayCandidate(definitions) {
- return find(definitions.rootElements, function(e) {
- return is(e, 'bpmn:Process') || is(e, 'bpmn:Collaboration');
- });
- }
- function BpmnTreeWalker(handler, translate) {
- // list of containers already walked
- var handledElements = {};
- // list of elements to handle deferred to ensure
- // prerequisites are drawn
- var deferred = [];
- var diMap = {};
- // Helpers //////////////////////
- function contextual(fn, ctx) {
- return function(e) {
- fn(e, ctx);
- };
- }
- function handled(element) {
- handledElements[element.id] = element;
- }
- function isHandled(element) {
- return handledElements[element.id];
- }
- function visit(element, ctx) {
- var gfx = element.gfx;
- // avoid multiple rendering of elements
- if (gfx) {
- throw new Error(
- translate('already rendered {element}', { element: elementToString(element) })
- );
- }
- // call handler
- return handler.element(element, diMap[element.id], ctx);
- }
- function visitRoot(element, diagram) {
- return handler.root(element, diMap[element.id], diagram);
- }
- function visitIfDi(element, ctx) {
- try {
- var gfx = diMap[element.id] && visit(element, ctx);
- handled(element);
- return gfx;
- } catch (e) {
- logError(e.message, { element: element, error: e });
- console.error(translate('failed to import {element}', { element: elementToString(element) }));
- console.error(e);
- }
- }
- function logError(message, context) {
- handler.error(message, context);
- }
- // DI handling //////////////////////
- function registerDi(di) {
- var bpmnElement = di.bpmnElement;
- if (bpmnElement) {
- if (diMap[bpmnElement.id]) {
- logError(
- translate('multiple DI elements defined for {element}', {
- element: elementToString(bpmnElement)
- }),
- { element: bpmnElement }
- );
- } else {
- diMap[bpmnElement.id] = di;
- ensureCompatDiRef(bpmnElement);
- }
- } else {
- logError(
- translate('no bpmnElement referenced in {element}', {
- element: elementToString(di)
- }),
- { element: di }
- );
- }
- }
- function handleDiagram(diagram) {
- handlePlane(diagram.plane);
- }
- function handlePlane(plane) {
- registerDi(plane);
- forEach$1(plane.planeElement, handlePlaneElement);
- }
- function handlePlaneElement(planeElement) {
- registerDi(planeElement);
- }
- // Semantic handling //////////////////////
- /**
- * Handle definitions and return the rendered diagram (if any)
- *
- * @param {ModdleElement} definitions to walk and import
- * @param {ModdleElement} [diagram] specific diagram to import and display
- *
- * @throws {Error} if no diagram to display could be found
- */
- function handleDefinitions(definitions, diagram) {
- // make sure we walk the correct bpmnElement
- var diagrams = definitions.diagrams;
- if (diagram && diagrams.indexOf(diagram) === -1) {
- throw new Error(translate('diagram not part of bpmn:Definitions'));
- }
- if (!diagram && diagrams && diagrams.length) {
- diagram = diagrams[0];
- }
- // no diagram -> nothing to import
- if (!diagram) {
- throw new Error(translate('no diagram to display'));
- }
- // load DI from selected diagram only
- diMap = {};
- handleDiagram(diagram);
- var plane = diagram.plane;
- if (!plane) {
- throw new Error(translate(
- 'no plane for {element}',
- { element: elementToString(diagram) }
- ));
- }
- var rootElement = plane.bpmnElement;
- // ensure we default to a suitable display candidate (process or collaboration),
- // even if non is specified in DI
- if (!rootElement) {
- rootElement = findDisplayCandidate(definitions);
- if (!rootElement) {
- throw new Error(translate('no process or collaboration to display'));
- } else {
- logError(
- translate('correcting missing bpmnElement on {plane} to {rootElement}', {
- plane: elementToString(plane),
- rootElement: elementToString(rootElement)
- })
- );
- // correct DI on the fly
- plane.bpmnElement = rootElement;
- registerDi(plane);
- }
- }
- var ctx = visitRoot(rootElement, plane);
- if (is(rootElement, 'bpmn:Process') || is(rootElement, 'bpmn:SubProcess')) {
- handleProcess(rootElement, ctx);
- } else if (is(rootElement, 'bpmn:Collaboration')) {
- handleCollaboration(rootElement, ctx);
- // force drawing of everything not yet drawn that is part of the target DI
- handleUnhandledProcesses(definitions.rootElements, ctx);
- } else {
- throw new Error(
- translate('unsupported bpmnElement for {plane}: {rootElement}', {
- plane: elementToString(plane),
- rootElement: elementToString(rootElement)
- })
- );
- }
- // handle all deferred elements
- handleDeferred();
- }
- function handleDeferred() {
- var fn;
- // drain deferred until empty
- while (deferred.length) {
- fn = deferred.shift();
- fn();
- }
- }
- function handleProcess(process, context) {
- handleFlowElementsContainer(process, context);
- handleIoSpecification(process.ioSpecification, context);
- handleArtifacts(process.artifacts, context);
- // log process handled
- handled(process);
- }
- function handleUnhandledProcesses(rootElements, ctx) {
- // walk through all processes that have not yet been drawn and draw them
- // if they contain lanes with DI information.
- // we do this to pass the free-floating lane test cases in the MIWG test suite
- var processes = filter(rootElements, function(e) {
- return !isHandled(e) && is(e, 'bpmn:Process') && e.laneSets;
- });
- processes.forEach(contextual(handleProcess, ctx));
- }
- function handleMessageFlow(messageFlow, context) {
- visitIfDi(messageFlow, context);
- }
- function handleMessageFlows(messageFlows, context) {
- forEach$1(messageFlows, contextual(handleMessageFlow, context));
- }
- function handleDataAssociation(association, context) {
- visitIfDi(association, context);
- }
- function handleDataInput(dataInput, context) {
- visitIfDi(dataInput, context);
- }
- function handleDataOutput(dataOutput, context) {
- visitIfDi(dataOutput, context);
- }
- function handleArtifact(artifact, context) {
- // bpmn:TextAnnotation
- // bpmn:Group
- // bpmn:Association
- visitIfDi(artifact, context);
- }
- function handleArtifacts(artifacts, context) {
- forEach$1(artifacts, function(e) {
- if (is(e, 'bpmn:Association')) {
- deferred.push(function() {
- handleArtifact(e, context);
- });
- } else {
- handleArtifact(e, context);
- }
- });
- }
- function handleIoSpecification(ioSpecification, context) {
- if (!ioSpecification) {
- return;
- }
- forEach$1(ioSpecification.dataInputs, contextual(handleDataInput, context));
- forEach$1(ioSpecification.dataOutputs, contextual(handleDataOutput, context));
- }
- function handleSubProcess(subProcess, context) {
- handleFlowElementsContainer(subProcess, context);
- handleArtifacts(subProcess.artifacts, context);
- }
- function handleFlowNode(flowNode, context) {
- var childCtx = visitIfDi(flowNode, context);
- if (is(flowNode, 'bpmn:SubProcess')) {
- handleSubProcess(flowNode, childCtx || context);
- }
- if (is(flowNode, 'bpmn:Activity')) {
- handleIoSpecification(flowNode.ioSpecification, context);
- }
- // defer handling of associations
- // affected types:
- //
- // * bpmn:Activity
- // * bpmn:ThrowEvent
- // * bpmn:CatchEvent
- //
- deferred.push(function() {
- forEach$1(flowNode.dataInputAssociations, contextual(handleDataAssociation, context));
- forEach$1(flowNode.dataOutputAssociations, contextual(handleDataAssociation, context));
- });
- }
- function handleSequenceFlow(sequenceFlow, context) {
- visitIfDi(sequenceFlow, context);
- }
- function handleDataElement(dataObject, context) {
- visitIfDi(dataObject, context);
- }
- function handleLane(lane, context) {
- deferred.push(function() {
- var newContext = visitIfDi(lane, context);
- if (lane.childLaneSet) {
- handleLaneSet(lane.childLaneSet, newContext || context);
- }
- wireFlowNodeRefs(lane);
- });
- }
- function handleLaneSet(laneSet, context) {
- forEach$1(laneSet.lanes, contextual(handleLane, context));
- }
- function handleLaneSets(laneSets, context) {
- forEach$1(laneSets, contextual(handleLaneSet, context));
- }
- function handleFlowElementsContainer(container, context) {
- handleFlowElements(container.flowElements, context);
- if (container.laneSets) {
- handleLaneSets(container.laneSets, context);
- }
- }
- function handleFlowElements(flowElements, context) {
- forEach$1(flowElements, function(e) {
- if (is(e, 'bpmn:SequenceFlow')) {
- deferred.push(function() {
- handleSequenceFlow(e, context);
- });
- } else if (is(e, 'bpmn:BoundaryEvent')) {
- deferred.unshift(function() {
- handleFlowNode(e, context);
- });
- } else if (is(e, 'bpmn:FlowNode')) {
- handleFlowNode(e, context);
- } else if (is(e, 'bpmn:DataObject')) ; else if (is(e, 'bpmn:DataStoreReference')) {
- handleDataElement(e, context);
- } else if (is(e, 'bpmn:DataObjectReference')) {
- handleDataElement(e, context);
- } else {
- logError(
- translate('unrecognized flowElement {element} in context {context}', {
- element: elementToString(e),
- context: (context ? elementToString(context.businessObject) : 'null')
- }),
- { element: e, context: context }
- );
- }
- });
- }
- function handleParticipant(participant, context) {
- var newCtx = visitIfDi(participant, context);
- var process = participant.processRef;
- if (process) {
- handleProcess(process, newCtx || context);
- }
- }
- function handleCollaboration(collaboration, context) {
- forEach$1(collaboration.participants, contextual(handleParticipant, context));
- handleArtifacts(collaboration.artifacts, context);
- // handle message flows latest in the process
- deferred.push(function() {
- handleMessageFlows(collaboration.messageFlows, context);
- });
- }
- function wireFlowNodeRefs(lane) {
- // wire the virtual flowNodeRefs <-> relationship
- forEach$1(lane.flowNodeRef, function(flowNode) {
- var lanes = flowNode.get('lanes');
- if (lanes) {
- lanes.push(lane);
- }
- });
- }
- // API //////////////////////
- return {
- handleDeferred: handleDeferred,
- handleDefinitions: handleDefinitions,
- handleSubProcess: handleSubProcess,
- registerDi: registerDi
- };
- }
- /**
- * The importBpmnDiagram result.
- *
- * @typedef {Object} ImportBPMNDiagramResult
- *
- * @property {Array<string>} warnings
- */
- /**
- * The importBpmnDiagram error.
- *
- * @typedef {Error} ImportBPMNDiagramError
- *
- * @property {Array<string>} warnings
- */
- /**
- * Import the definitions into a diagram.
- *
- * Errors and warnings are reported through the specified callback.
- *
- * @param {djs.Diagram} diagram
- * @param {ModdleElement<Definitions>} definitions
- * @param {ModdleElement<BPMNDiagram>} [bpmnDiagram] the diagram to be rendered
- * (if not provided, the first one will be rendered)
- *
- * Returns {Promise<ImportBPMNDiagramResult, ImportBPMNDiagramError>}
- */
- function importBpmnDiagram(diagram, definitions, bpmnDiagram) {
- var importer,
- eventBus,
- translate,
- canvas;
- var error,
- warnings = [];
- /**
- * Walk the diagram semantically, importing (=drawing)
- * all elements you encounter.
- *
- * @param {ModdleElement<Definitions>} definitions
- * @param {ModdleElement<BPMNDiagram>} bpmnDiagram
- */
- function render(definitions, bpmnDiagram) {
- var visitor = {
- root: function(element, di) {
- return importer.add(element, di);
- },
- element: function(element, di, parentShape) {
- return importer.add(element, di, parentShape);
- },
- error: function(message, context) {
- warnings.push({ message: message, context: context });
- }
- };
- var walker = new BpmnTreeWalker(visitor, translate);
- bpmnDiagram = bpmnDiagram || (definitions.diagrams && definitions.diagrams[0]);
- var diagramsToImport = getDiagramsToImport(definitions, bpmnDiagram);
- if (!diagramsToImport) {
- throw new Error(translate('no diagram to display'));
- }
- // traverse BPMN 2.0 document model,
- // starting at definitions
- forEach$1(diagramsToImport, function(diagram) {
- walker.handleDefinitions(definitions, diagram);
- });
- var rootId = bpmnDiagram.plane.bpmnElement.id;
- // we do need to account for different ways we create root elements
- // each nested imported <root> do have the `_plane` suffix, while
- // the root <root> is found under the business object ID
- canvas.setRootElement(
- canvas.findRoot(rootId + '_plane') || canvas.findRoot(rootId)
- );
- }
- return new Promise(function(resolve, reject) {
- try {
- importer = diagram.get('bpmnImporter');
- eventBus = diagram.get('eventBus');
- translate = diagram.get('translate');
- canvas = diagram.get('canvas');
- eventBus.fire('import.render.start', { definitions: definitions });
- render(definitions, bpmnDiagram);
- eventBus.fire('import.render.complete', {
- error: error,
- warnings: warnings
- });
- return resolve({ warnings: warnings });
- } catch (e) {
- e.warnings = warnings;
- return reject(e);
- }
- });
- }
- /**
- * Returns all diagrams in the same hierarchy as the requested diagram.
- * Includes all parent and sub process diagrams.
- *
- * @param {Array} definitions
- * @param {Object} bpmnDiagram
- *
- * @returns {Array<Object>}
- */
- function getDiagramsToImport(definitions, bpmnDiagram) {
- if (!bpmnDiagram) {
- return;
- }
- var bpmnElement = bpmnDiagram.plane.bpmnElement,
- rootElement = bpmnElement;
- if (!is$1(bpmnElement, 'bpmn:Process') && !is$1(bpmnElement, 'bpmn:Collaboration')) {
- rootElement = findRootProcess(bpmnElement);
- }
- // in case the process is part of a collaboration, the plane references the
- // collaboration, not the process
- var collaboration;
- if (is$1(rootElement, 'bpmn:Collaboration')) {
- collaboration = rootElement;
- } else {
- collaboration = find(definitions.rootElements, function(element) {
- if (!is$1(element, 'bpmn:Collaboration')) {
- return;
- }
- return find(element.participants, function(participant) {
- return participant.processRef === rootElement;
- });
- });
- }
- var rootElements = [ rootElement ];
- // all collaboration processes can contain sub-diagrams
- if (collaboration) {
- rootElements = map(collaboration.participants, function(participant) {
- return participant.processRef;
- });
- rootElements.push(collaboration);
- }
- var allChildren = selfAndAllFlowElements(rootElements);
- // if we have multiple diagrams referencing the same element, we
- // use the first in the file
- var diagramsToImport = [ bpmnDiagram ];
- var handledElements = [ bpmnElement ];
- forEach$1(definitions.diagrams, function(diagram) {
- var businessObject = diagram.plane.bpmnElement;
- if (
- allChildren.indexOf(businessObject) !== -1 &&
- handledElements.indexOf(businessObject) === -1
- ) {
- diagramsToImport.push(diagram);
- handledElements.push(businessObject);
- }
- });
- return diagramsToImport;
- }
- function selfAndAllFlowElements(elements) {
- var result = [];
- forEach$1(elements, function(element) {
- if (!element) {
- return;
- }
- result.push(element);
- result = result.concat(selfAndAllFlowElements(element.flowElements));
- });
- return result;
- }
- function findRootProcess(element) {
- var parent = element;
- while (parent) {
- if (is$1(parent, 'bpmn:Process')) {
- return parent;
- }
- parent = parent.$parent;
- }
- }
- /**
- * This file must not be changed or exchanged.
- *
- * @see http://bpmn.io/license for more information.
- */
- // inlined ../../resources/logo.svg
- var BPMNIO_LOGO_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14.02 5.57" width="53" height="21"><path fill="currentColor" d="M1.88.92v.14c0 .41-.13.68-.4.8.33.14.46.44.46.86v.33c0 .61-.33.95-.95.95H0V0h.95c.65 0 .93.3.93.92zM.63.57v1.06h.24c.24 0 .38-.1.38-.43V.98c0-.28-.1-.4-.32-.4zm0 1.63v1.22h.36c.2 0 .32-.1.32-.39v-.35c0-.37-.12-.48-.4-.48H.63zM4.18.99v.52c0 .64-.31.98-.94.98h-.3V4h-.62V0h.92c.63 0 .94.35.94.99zM2.94.57v1.35h.3c.2 0 .3-.09.3-.37v-.6c0-.29-.1-.38-.3-.38h-.3zm2.89 2.27L6.25 0h.88v4h-.6V1.12L6.1 3.99h-.6l-.46-2.82v2.82h-.55V0h.87zM8.14 1.1V4h-.56V0h.79L9 2.4V0h.56v4h-.64zm2.49 2.29v.6h-.6v-.6zM12.12 1c0-.63.33-1 .95-1 .61 0 .95.37.95 1v2.04c0 .64-.34 1-.95 1-.62 0-.95-.37-.95-1zm.62 2.08c0 .28.13.39.33.39s.32-.1.32-.4V.98c0-.29-.12-.4-.32-.4s-.33.11-.33.4z"/><path fill="currentColor" d="M0 4.53h14.02v1.04H0zM11.08 0h.63v.62h-.63zm.63 4V1h-.63v2.98z"/></svg>';
- var BPMNIO_IMG = BPMNIO_LOGO_SVG;
- var LOGO_STYLES = {
- verticalAlign: 'middle'
- };
- var LINK_STYLES = {
- 'color': '#404040'
- };
- var LIGHTBOX_STYLES = {
- 'zIndex': '1001',
- 'position': 'fixed',
- 'top': '0',
- 'left': '0',
- 'right': '0',
- 'bottom': '0'
- };
- var BACKDROP_STYLES = {
- 'width': '100%',
- 'height': '100%',
- 'background': 'rgba(40,40,40,0.2)'
- };
- var NOTICE_STYLES = {
- 'position': 'absolute',
- 'left': '50%',
- 'top': '40%',
- 'transform': 'translate(-50%)',
- 'width': '260px',
- 'padding': '10px',
- 'background': 'white',
- 'boxShadow': '0 1px 4px rgba(0,0,0,0.3)',
- 'fontFamily': 'Helvetica, Arial, sans-serif',
- 'fontSize': '14px',
- 'display': 'flex',
- 'lineHeight': '1.3'
- };
- var LIGHTBOX_MARKUP =
- '<div class="bjs-powered-by-lightbox">' +
- '<div class="backdrop"></div>' +
- '<div class="notice">' +
- '<a href="https://bpmn.io" target="_blank" rel="noopener" class="link">' +
- BPMNIO_IMG +
- '</a>' +
- '<span>' +
- 'Web-based tooling for BPMN, DMN and CMMN diagrams ' +
- 'powered by <a href="https://bpmn.io" target="_blank" rel="noopener">bpmn.io</a>.' +
- '</span>' +
- '</div>' +
- '</div>';
- var lightbox;
- function createLightbox() {
- lightbox = domify(LIGHTBOX_MARKUP);
- assign$1(lightbox, LIGHTBOX_STYLES);
- assign$1(query('svg', lightbox), LOGO_STYLES);
- assign$1(query('.backdrop', lightbox), BACKDROP_STYLES);
- assign$1(query('.notice', lightbox), NOTICE_STYLES);
- assign$1(query('.link', lightbox), LINK_STYLES, {
- 'margin': '15px 20px 15px 10px',
- 'alignSelf': 'center'
- });
- }
- function open() {
- if (!lightbox) {
- createLightbox();
- delegate.bind(lightbox, '.backdrop', 'click', function(event) {
- document.body.removeChild(lightbox);
- });
- }
- document.body.appendChild(lightbox);
- }
- /**
- * The code in the <project-logo></project-logo> area
- * must not be changed.
- *
- * @see http://bpmn.io/license for more information.
- */
- /**
- * A base viewer for BPMN 2.0 diagrams.
- *
- * Have a look at {@link Viewer}, {@link NavigatedViewer} or {@link Modeler} for
- * bundles that include actual features.
- *
- * @param {Object} [options] configuration options to pass to the viewer
- * @param {DOMElement} [options.container] the container to render the viewer in, defaults to body.
- * @param {string|number} [options.width] the width of the viewer
- * @param {string|number} [options.height] the height of the viewer
- * @param {Object} [options.moddleExtensions] extension packages to provide
- * @param {Array<didi.Module>} [options.modules] a list of modules to override the default modules
- * @param {Array<didi.Module>} [options.additionalModules] a list of modules to use with the default modules
- */
- function BaseViewer(options) {
- options = assign({}, DEFAULT_OPTIONS, options);
- this._moddle = this._createModdle(options);
- this._container = this._createContainer(options);
- /* <project-logo> */
- addProjectLogo(this._container);
- /* </project-logo> */
- this._init(this._container, this._moddle, options);
- }
- e(BaseViewer, Diagram);
- /**
- * The importXML result.
- *
- * @typedef {Object} ImportXMLResult
- *
- * @property {Array<string>} warnings
- */
- /**
- * The importXML error.
- *
- * @typedef {Error} ImportXMLError
- *
- * @property {Array<string>} warnings
- */
- /**
- * Parse and render a BPMN 2.0 diagram.
- *
- * Once finished the viewer reports back the result to the
- * provided callback function with (err, warnings).
- *
- * ## Life-Cycle Events
- *
- * During import the viewer will fire life-cycle events:
- *
- * * import.parse.start (about to read model from xml)
- * * import.parse.complete (model read; may have worked or not)
- * * import.render.start (graphical import start)
- * * import.render.complete (graphical import finished)
- * * import.done (everything done)
- *
- * You can use these events to hook into the life-cycle.
- *
- * @param {string} xml the BPMN 2.0 xml
- * @param {ModdleElement<BPMNDiagram>|string} [bpmnDiagram] BPMN diagram or id of diagram to render (if not provided, the first one will be rendered)
- *
- * Returns {Promise<ImportXMLResult, ImportXMLError>}
- */
- BaseViewer.prototype.importXML = wrapForCompatibility(function importXML(xml, bpmnDiagram) {
- var self = this;
- function ParseCompleteEvent(data) {
- var event = self.get('eventBus').createEvent(data);
- // TODO(nikku): remove with future bpmn-js version
- Object.defineProperty(event, 'context', {
- enumerable: true,
- get: function() {
- console.warn(new Error(
- 'import.parse.complete <context> is deprecated ' +
- 'and will be removed in future library versions'
- ));
- return {
- warnings: data.warnings,
- references: data.references,
- elementsById: data.elementsById
- };
- }
- });
- return event;
- }
- return new Promise(function(resolve, reject) {
- // hook in pre-parse listeners +
- // allow xml manipulation
- xml = self._emit('import.parse.start', { xml: xml }) || xml;
- self._moddle.fromXML(xml, 'bpmn:Definitions').then(function(result) {
- var definitions = result.rootElement;
- var references = result.references;
- var parseWarnings = result.warnings;
- var elementsById = result.elementsById;
- // hook in post parse listeners +
- // allow definitions manipulation
- definitions = self._emit('import.parse.complete', ParseCompleteEvent({
- error: null,
- definitions: definitions,
- elementsById: elementsById,
- references: references,
- warnings: parseWarnings
- })) || definitions;
- self.importDefinitions(definitions, bpmnDiagram).then(function(result) {
- var allWarnings = [].concat(parseWarnings, result.warnings || []);
- self._emit('import.done', { error: null, warnings: allWarnings });
- return resolve({ warnings: allWarnings });
- }).catch(function(err) {
- var allWarnings = [].concat(parseWarnings, err.warnings || []);
- self._emit('import.done', { error: err, warnings: allWarnings });
- return reject(addWarningsToError(err, allWarnings));
- });
- }).catch(function(err) {
- self._emit('import.parse.complete', {
- error: err
- });
- err = checkValidationError(err);
- self._emit('import.done', { error: err, warnings: err.warnings });
- return reject(err);
- });
- });
- });
- /**
- * The importDefinitions result.
- *
- * @typedef {Object} ImportDefinitionsResult
- *
- * @property {Array<string>} warnings
- */
- /**
- * The importDefinitions error.
- *
- * @typedef {Error} ImportDefinitionsError
- *
- * @property {Array<string>} warnings
- */
- /**
- * Import parsed definitions and render a BPMN 2.0 diagram.
- *
- * Once finished the viewer reports back the result to the
- * provided callback function with (err, warnings).
- *
- * ## Life-Cycle Events
- *
- * During import the viewer will fire life-cycle events:
- *
- * * import.render.start (graphical import start)
- * * import.render.complete (graphical import finished)
- *
- * You can use these events to hook into the life-cycle.
- *
- * @param {ModdleElement<Definitions>} definitions parsed BPMN 2.0 definitions
- * @param {ModdleElement<BPMNDiagram>|string} [bpmnDiagram] BPMN diagram or id of diagram to render (if not provided, the first one will be rendered)
- *
- * Returns {Promise<ImportDefinitionsResult, ImportDefinitionsError>}
- */
- BaseViewer.prototype.importDefinitions = wrapForCompatibility(function importDefinitions(definitions, bpmnDiagram) {
- var self = this;
- return new Promise(function(resolve, reject) {
- self._setDefinitions(definitions);
- self.open(bpmnDiagram).then(function(result) {
- var warnings = result.warnings;
- return resolve({ warnings: warnings });
- }).catch(function(err) {
- return reject(err);
- });
- });
- });
- /**
- * The open result.
- *
- * @typedef {Object} OpenResult
- *
- * @property {Array<string>} warnings
- */
- /**
- * The open error.
- *
- * @typedef {Error} OpenError
- *
- * @property {Array<string>} warnings
- */
- /**
- * Open diagram of previously imported XML.
- *
- * Once finished the viewer reports back the result to the
- * provided callback function with (err, warnings).
- *
- * ## Life-Cycle Events
- *
- * During switch the viewer will fire life-cycle events:
- *
- * * import.render.start (graphical import start)
- * * import.render.complete (graphical import finished)
- *
- * You can use these events to hook into the life-cycle.
- *
- * @param {string|ModdleElement<BPMNDiagram>} [bpmnDiagramOrId] id or the diagram to open
- *
- * Returns {Promise<OpenResult, OpenError>}
- */
- BaseViewer.prototype.open = wrapForCompatibility(function open(bpmnDiagramOrId) {
- var definitions = this._definitions;
- var bpmnDiagram = bpmnDiagramOrId;
- var self = this;
- return new Promise(function(resolve, reject) {
- if (!definitions) {
- var err1 = new Error('no XML imported');
- return reject(addWarningsToError(err1, []));
- }
- if (typeof bpmnDiagramOrId === 'string') {
- bpmnDiagram = findBPMNDiagram(definitions, bpmnDiagramOrId);
- if (!bpmnDiagram) {
- var err2 = new Error('BPMNDiagram <' + bpmnDiagramOrId + '> not found');
- return reject(addWarningsToError(err2, []));
- }
- }
- // clear existing rendered diagram
- // catch synchronous exceptions during #clear()
- try {
- self.clear();
- } catch (error) {
- return reject(addWarningsToError(error, []));
- }
- // perform graphical import
- importBpmnDiagram(self, definitions, bpmnDiagram).then(function(result) {
- var warnings = result.warnings;
- return resolve({ warnings: warnings });
- }).catch(function(err) {
- return reject(err);
- });
- });
- });
- /**
- * The saveXML result.
- *
- * @typedef {Object} SaveXMLResult
- *
- * @property {string} xml
- */
- /**
- * Export the currently displayed BPMN 2.0 diagram as
- * a BPMN 2.0 XML document.
- *
- * ## Life-Cycle Events
- *
- * During XML saving the viewer will fire life-cycle events:
- *
- * * saveXML.start (before serialization)
- * * saveXML.serialized (after xml generation)
- * * saveXML.done (everything done)
- *
- * You can use these events to hook into the life-cycle.
- *
- * @param {Object} [options] export options
- * @param {boolean} [options.format=false] output formatted XML
- * @param {boolean} [options.preamble=true] output preamble
- *
- * Returns {Promise<SaveXMLResult, Error>}
- */
- BaseViewer.prototype.saveXML = wrapForCompatibility(function saveXML(options) {
- options = options || {};
- var self = this;
- var definitions = this._definitions;
- return new Promise(function(resolve) {
- if (!definitions) {
- return resolve({
- error: new Error('no definitions loaded')
- });
- }
- // allow to fiddle around with definitions
- definitions = self._emit('saveXML.start', {
- definitions: definitions
- }) || definitions;
- self._moddle.toXML(definitions, options).then(function(result) {
- var xml = result.xml;
- xml = self._emit('saveXML.serialized', {
- xml: xml
- }) || xml;
- return resolve({
- xml: xml
- });
- });
- }).catch(function(error) {
- return { error: error };
- }).then(function(result) {
- self._emit('saveXML.done', result);
- var error = result.error;
- if (error) {
- return Promise.reject(error);
- }
- return result;
- });
- });
- /**
- * The saveSVG result.
- *
- * @typedef {Object} SaveSVGResult
- *
- * @property {string} svg
- */
- /**
- * Export the currently displayed BPMN 2.0 diagram as
- * an SVG image.
- *
- * ## Life-Cycle Events
- *
- * During SVG saving the viewer will fire life-cycle events:
- *
- * * saveSVG.start (before serialization)
- * * saveSVG.done (everything done)
- *
- * You can use these events to hook into the life-cycle.
- *
- * @param {Object} [options]
- *
- * Returns {Promise<SaveSVGResult, Error>}
- */
- BaseViewer.prototype.saveSVG = wrapForCompatibility(function saveSVG(options) {
- var self = this;
- return new Promise(function(resolve, reject) {
- self._emit('saveSVG.start');
- var svg, err;
- try {
- var canvas = self.get('canvas');
- var contentNode = canvas.getActiveLayer(),
- defsNode = query('defs', canvas._svg);
- var contents = innerSVG(contentNode),
- defs = defsNode ? '<defs>' + innerSVG(defsNode) + '</defs>' : '';
- var bbox = contentNode.getBBox();
- svg =
- '<?xml version="1.0" encoding="utf-8"?>\n' +
- '<!-- created with bpmn-js / http://bpmn.io -->\n' +
- '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
- '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ' +
- 'width="' + bbox.width + '" height="' + bbox.height + '" ' +
- 'viewBox="' + bbox.x + ' ' + bbox.y + ' ' + bbox.width + ' ' + bbox.height + '" version="1.1">' +
- defs + contents +
- '</svg>';
- } catch (e) {
- err = e;
- }
- self._emit('saveSVG.done', {
- error: err,
- svg: svg
- });
- if (!err) {
- return resolve({ svg: svg });
- }
- return reject(err);
- });
- });
- /**
- * Get a named diagram service.
- *
- * @example
- *
- * var elementRegistry = viewer.get('elementRegistry');
- * var startEventShape = elementRegistry.get('StartEvent_1');
- *
- * @param {string} name
- *
- * @return {Object} diagram service instance
- *
- * @method BaseViewer#get
- */
- /**
- * Invoke a function in the context of this viewer.
- *
- * @example
- *
- * viewer.invoke(function(elementRegistry) {
- * var startEventShape = elementRegistry.get('StartEvent_1');
- * });
- *
- * @param {Function} fn to be invoked
- *
- * @return {Object} the functions return value
- *
- * @method BaseViewer#invoke
- */
- BaseViewer.prototype._setDefinitions = function(definitions) {
- this._definitions = definitions;
- };
- BaseViewer.prototype.getModules = function() {
- return this._modules;
- };
- /**
- * Remove all drawn elements from the viewer.
- *
- * After calling this method the viewer can still
- * be reused for opening another diagram.
- *
- * @method BaseViewer#clear
- */
- BaseViewer.prototype.clear = function() {
- if (!this.getDefinitions()) {
- // no diagram to clear
- return;
- }
- // remove drawn elements
- Diagram.prototype.clear.call(this);
- };
- /**
- * Destroy the viewer instance and remove all its
- * remainders from the document tree.
- */
- BaseViewer.prototype.destroy = function() {
- // diagram destroy
- Diagram.prototype.destroy.call(this);
- // dom detach
- remove$1(this._container);
- };
- /**
- * Register an event listener
- *
- * Remove a previously added listener via {@link #off(event, callback)}.
- *
- * @param {string} event
- * @param {number} [priority]
- * @param {Function} callback
- * @param {Object} [that]
- */
- BaseViewer.prototype.on = function(event, priority, callback, target) {
- return this.get('eventBus').on(event, priority, callback, target);
- };
- /**
- * De-register an event listener
- *
- * @param {string} event
- * @param {Function} callback
- */
- BaseViewer.prototype.off = function(event, callback) {
- this.get('eventBus').off(event, callback);
- };
- BaseViewer.prototype.attachTo = function(parentNode) {
- if (!parentNode) {
- throw new Error('parentNode required');
- }
- // ensure we detach from the
- // previous, old parent
- this.detach();
- // unwrap jQuery if provided
- if (parentNode.get && parentNode.constructor.prototype.jquery) {
- parentNode = parentNode.get(0);
- }
- if (typeof parentNode === 'string') {
- parentNode = query(parentNode);
- }
- parentNode.appendChild(this._container);
- this._emit('attach', {});
- this.get('canvas').resized();
- };
- BaseViewer.prototype.getDefinitions = function() {
- return this._definitions;
- };
- BaseViewer.prototype.detach = function() {
- var container = this._container,
- parentNode = container.parentNode;
- if (!parentNode) {
- return;
- }
- this._emit('detach', {});
- parentNode.removeChild(container);
- };
- BaseViewer.prototype._init = function(container, moddle, options) {
- var baseModules = options.modules || this.getModules(),
- additionalModules = options.additionalModules || [],
- staticModules = [
- {
- bpmnjs: [ 'value', this ],
- moddle: [ 'value', moddle ]
- }
- ];
- var diagramModules = [].concat(staticModules, baseModules, additionalModules);
- var diagramOptions = assign(omit(options, [ 'additionalModules' ]), {
- canvas: assign({}, options.canvas, { container: container }),
- modules: diagramModules
- });
- // invoke diagram constructor
- Diagram.call(this, diagramOptions);
- if (options && options.container) {
- this.attachTo(options.container);
- }
- };
- /**
- * Emit an event on the underlying {@link EventBus}
- *
- * @param {string} type
- * @param {Object} event
- *
- * @return {Object} event processing result (if any)
- */
- BaseViewer.prototype._emit = function(type, event) {
- return this.get('eventBus').fire(type, event);
- };
- BaseViewer.prototype._createContainer = function(options) {
- var container = domify('<div class="bjs-container"></div>');
- assign$1(container, {
- width: ensureUnit(options.width),
- height: ensureUnit(options.height),
- position: options.position
- });
- return container;
- };
- BaseViewer.prototype._createModdle = function(options) {
- var moddleOptions = assign({}, this._moddleExtensions, options.moddleExtensions);
- return new simple(moddleOptions);
- };
- BaseViewer.prototype._modules = [];
- // helpers ///////////////
- function addWarningsToError(err, warningsAry) {
- err.warnings = warningsAry;
- return err;
- }
- function checkValidationError(err) {
- // check if we can help the user by indicating wrong BPMN 2.0 xml
- // (in case he or the exporting tool did not get that right)
- var pattern = /unparsable content <([^>]+)> detected([\s\S]*)$/;
- var match = pattern.exec(err.message);
- if (match) {
- err.message =
- 'unparsable content <' + match[1] + '> detected; ' +
- 'this may indicate an invalid BPMN 2.0 diagram file' + match[2];
- }
- return err;
- }
- var DEFAULT_OPTIONS = {
- width: '100%',
- height: '100%',
- position: 'relative'
- };
- /**
- * Ensure the passed argument is a proper unit (defaulting to px)
- */
- function ensureUnit(val) {
- return val + (isNumber(val) ? 'px' : '');
- }
- /**
- * Find BPMNDiagram in definitions by ID
- *
- * @param {ModdleElement<Definitions>} definitions
- * @param {string} diagramId
- *
- * @return {ModdleElement<BPMNDiagram>|null}
- */
- function findBPMNDiagram(definitions, diagramId) {
- if (!diagramId) {
- return null;
- }
- return find(definitions.diagrams, function(element) {
- return element.id === diagramId;
- }) || null;
- }
- /**
- * Adds the project logo to the diagram container as
- * required by the bpmn.io license.
- *
- * @see http://bpmn.io/license
- *
- * @param {Element} container
- */
- function addProjectLogo(container) {
- var img = BPMNIO_IMG;
- var linkMarkup =
- '<a href="http://bpmn.io" ' +
- 'target="_blank" ' +
- 'class="bjs-powered-by" ' +
- 'title="Powered by bpmn.io" ' +
- '>' +
- img +
- '</a>';
- var linkElement = domify(linkMarkup);
- assign$1(query('svg', linkElement), LOGO_STYLES);
- assign$1(linkElement, LINK_STYLES, {
- position: 'absolute',
- bottom: '15px',
- right: '15px',
- zIndex: '100'
- });
- container.appendChild(linkElement);
- componentEvent.bind(linkElement, 'click', function(event) {
- open();
- event.preventDefault();
- });
- }
- /* </project-logo> */
- /**
- * A viewer for BPMN 2.0 diagrams.
- *
- * Have a look at {@link NavigatedViewer} or {@link Modeler} for bundles that include
- * additional features.
- *
- *
- * ## Extending the Viewer
- *
- * In order to extend the viewer pass extension modules to bootstrap via the
- * `additionalModules` option. An extension module is an object that exposes
- * named services.
- *
- * The following example depicts the integration of a simple
- * logging component that integrates with interaction events:
- *
- *
- * ```javascript
- *
- * // logging component
- * function InteractionLogger(eventBus) {
- * eventBus.on('element.hover', function(event) {
- * console.log()
- * })
- * }
- *
- * InteractionLogger.$inject = [ 'eventBus' ]; // minification save
- *
- * // extension module
- * var extensionModule = {
- * __init__: [ 'interactionLogger' ],
- * interactionLogger: [ 'type', InteractionLogger ]
- * };
- *
- * // extend the viewer
- * var bpmnViewer = new Viewer({ additionalModules: [ extensionModule ] });
- * bpmnViewer.importXML(...);
- * ```
- *
- * @param {Object} [options] configuration options to pass to the viewer
- * @param {DOMElement} [options.container] the container to render the viewer in, defaults to body.
- * @param {string|number} [options.width] the width of the viewer
- * @param {string|number} [options.height] the height of the viewer
- * @param {Object} [options.moddleExtensions] extension packages to provide
- * @param {Array<didi.Module>} [options.modules] a list of modules to override the default modules
- * @param {Array<didi.Module>} [options.additionalModules] a list of modules to use with the default modules
- */
- function Viewer(options) {
- BaseViewer.call(this, options);
- }
- e(Viewer, BaseViewer);
- // modules the viewer is composed of
- Viewer.prototype._modules = [
- CoreModule$1,
- TranslateModule,
- SelectionModule,
- OverlaysModule,
- DrilldownModdule
- ];
- // default moddle extensions the viewer is composed of
- Viewer.prototype._moddleExtensions = {};
- /**
- * Returns true if event was triggered with any modifier
- * @param {KeyboardEvent} event
- */
- function hasModifier(event) {
- return (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey);
- }
- /**
- * @param {KeyboardEvent} event
- */
- function isCmd(event) {
- // ensure we don't react to AltGr
- // (mapped to CTRL + ALT)
- if (event.altKey) {
- return false;
- }
- return event.ctrlKey || event.metaKey;
- }
- /**
- * Checks if key pressed is one of provided keys.
- *
- * @param {string|Array<string>} keys
- * @param {KeyboardEvent} event
- */
- function isKey(keys, event) {
- keys = isArray$2(keys) ? keys : [ keys ];
- return keys.indexOf(event.key) !== -1 || keys.indexOf(event.keyCode) !== -1;
- }
- /**
- * @param {KeyboardEvent} event
- */
- function isShift(event) {
- return event.shiftKey;
- }
- var KEYDOWN_EVENT = 'keyboard.keydown',
- KEYUP_EVENT = 'keyboard.keyup';
- var HANDLE_MODIFIER_ATTRIBUTE = 'input-handle-modified-keys';
- var DEFAULT_PRIORITY = 1000;
- /**
- * A keyboard abstraction that may be activated and
- * deactivated by users at will, consuming key events
- * and triggering diagram actions.
- *
- * For keys pressed down, keyboard fires `keyboard.keydown` event.
- * The event context contains one field which is `KeyboardEvent` event.
- *
- * The implementation fires the following key events that allow
- * other components to hook into key handling:
- *
- * - keyboard.bind
- * - keyboard.unbind
- * - keyboard.init
- * - keyboard.destroy
- *
- * All events contain one field which is node.
- *
- * A default binding for the keyboard may be specified via the
- * `keyboard.bindTo` configuration option.
- *
- * @param {Config} config
- * @param {EventBus} eventBus
- */
- function Keyboard(config, eventBus) {
- var self = this;
- this._config = config || {};
- this._eventBus = eventBus;
- this._keydownHandler = this._keydownHandler.bind(this);
- this._keyupHandler = this._keyupHandler.bind(this);
- // properly clean dom registrations
- eventBus.on('diagram.destroy', function() {
- self._fire('destroy');
- self.unbind();
- });
- eventBus.on('diagram.init', function() {
- self._fire('init');
- });
- eventBus.on('attach', function() {
- if (config && config.bindTo) {
- self.bind(config.bindTo);
- }
- });
- eventBus.on('detach', function() {
- self.unbind();
- });
- }
- Keyboard.$inject = [
- 'config.keyboard',
- 'eventBus'
- ];
- Keyboard.prototype._keydownHandler = function(event) {
- this._keyHandler(event, KEYDOWN_EVENT);
- };
- Keyboard.prototype._keyupHandler = function(event) {
- this._keyHandler(event, KEYUP_EVENT);
- };
- Keyboard.prototype._keyHandler = function(event, type) {
- var eventBusResult;
- if (this._isEventIgnored(event)) {
- return;
- }
- var context = {
- keyEvent: event
- };
- eventBusResult = this._eventBus.fire(type || KEYDOWN_EVENT, context);
- if (eventBusResult) {
- event.preventDefault();
- }
- };
- Keyboard.prototype._isEventIgnored = function(event) {
- return isInput(event.target) && this._isModifiedKeyIgnored(event);
- };
- Keyboard.prototype._isModifiedKeyIgnored = function(event) {
- if (!isCmd(event)) {
- return true;
- }
- var allowedModifiers = this._getAllowedModifiers(event.target);
- return allowedModifiers.indexOf(event.key) === -1;
- };
- Keyboard.prototype._getAllowedModifiers = function(element) {
- var modifierContainer = closest(element, '[' + HANDLE_MODIFIER_ATTRIBUTE + ']', true);
- if (!modifierContainer || (this._node && !this._node.contains(modifierContainer))) {
- return [];
- }
- return modifierContainer.getAttribute(HANDLE_MODIFIER_ATTRIBUTE).split(',');
- };
- Keyboard.prototype.bind = function(node) {
- // make sure that the keyboard is only bound once to the DOM
- this.unbind();
- this._node = node;
- // bind key events
- componentEvent.bind(node, 'keydown', this._keydownHandler, true);
- componentEvent.bind(node, 'keyup', this._keyupHandler, true);
- this._fire('bind');
- };
- Keyboard.prototype.getBinding = function() {
- return this._node;
- };
- Keyboard.prototype.unbind = function() {
- var node = this._node;
- if (node) {
- this._fire('unbind');
- // unbind key events
- componentEvent.unbind(node, 'keydown', this._keydownHandler, true);
- componentEvent.unbind(node, 'keyup', this._keyupHandler, true);
- }
- this._node = null;
- };
- Keyboard.prototype._fire = function(event) {
- this._eventBus.fire('keyboard.' + event, { node: this._node });
- };
- /**
- * Add a listener function that is notified with `KeyboardEvent` whenever
- * the keyboard is bound and the user presses a key. If no priority is
- * provided, the default value of 1000 is used.
- *
- * @param {number} [priority]
- * @param {Function} listener
- * @param {string} type
- */
- Keyboard.prototype.addListener = function(priority, listener, type) {
- if (isFunction(priority)) {
- type = listener;
- listener = priority;
- priority = DEFAULT_PRIORITY;
- }
- this._eventBus.on(type || KEYDOWN_EVENT, priority, listener);
- };
- Keyboard.prototype.removeListener = function(listener, type) {
- this._eventBus.off(type || KEYDOWN_EVENT, listener);
- };
- Keyboard.prototype.hasModifier = hasModifier;
- Keyboard.prototype.isCmd = isCmd;
- Keyboard.prototype.isShift = isShift;
- Keyboard.prototype.isKey = isKey;
- // helpers ///////
- function isInput(target) {
- return target && (matchesSelector(target, 'input, textarea') || target.contentEditable === 'true');
- }
- var LOW_PRIORITY = 500;
- var KEYCODE_C = 67;
- var KEYCODE_V = 86;
- var KEYCODE_Y = 89;
- var KEYCODE_Z = 90;
- var KEYS_COPY = [ 'c', 'C', KEYCODE_C ];
- var KEYS_PASTE = [ 'v', 'V', KEYCODE_V ];
- var KEYS_REDO = [ 'y', 'Y', KEYCODE_Y ];
- var KEYS_UNDO = [ 'z', 'Z', KEYCODE_Z ];
- /**
- * Adds default keyboard bindings.
- *
- * This does not pull in any features will bind only actions that
- * have previously been registered against the editorActions component.
- *
- * @param {EventBus} eventBus
- * @param {Keyboard} keyboard
- */
- function KeyboardBindings(eventBus, keyboard) {
- var self = this;
- eventBus.on('editorActions.init', LOW_PRIORITY, function(event) {
- var editorActions = event.editorActions;
- self.registerBindings(keyboard, editorActions);
- });
- }
- KeyboardBindings.$inject = [
- 'eventBus',
- 'keyboard'
- ];
- /**
- * Register available keyboard bindings.
- *
- * @param {Keyboard} keyboard
- * @param {EditorActions} editorActions
- */
- KeyboardBindings.prototype.registerBindings = function(keyboard, editorActions) {
- /**
- * Add keyboard binding if respective editor action
- * is registered.
- *
- * @param {string} action name
- * @param {Function} fn that implements the key binding
- */
- function addListener(action, fn) {
- if (editorActions.isRegistered(action)) {
- keyboard.addListener(fn);
- }
- }
- // undo
- // (CTRL|CMD) + Z
- addListener('undo', function(context) {
- var event = context.keyEvent;
- if (isCmd(event) && !isShift(event) && isKey(KEYS_UNDO, event)) {
- editorActions.trigger('undo');
- return true;
- }
- });
- // redo
- // CTRL + Y
- // CMD + SHIFT + Z
- addListener('redo', function(context) {
- var event = context.keyEvent;
- if (isCmd(event) && (isKey(KEYS_REDO, event) || (isKey(KEYS_UNDO, event) && isShift(event)))) {
- editorActions.trigger('redo');
- return true;
- }
- });
- // copy
- // CTRL/CMD + C
- addListener('copy', function(context) {
- var event = context.keyEvent;
- if (isCmd(event) && isKey(KEYS_COPY, event)) {
- editorActions.trigger('copy');
- return true;
- }
- });
- // paste
- // CTRL/CMD + V
- addListener('paste', function(context) {
- var event = context.keyEvent;
- if (isCmd(event) && isKey(KEYS_PASTE, event)) {
- editorActions.trigger('paste');
- return true;
- }
- });
- // zoom in one step
- // CTRL/CMD + +
- addListener('stepZoom', function(context) {
- var event = context.keyEvent;
- // quirk: it has to be triggered by `=` as well to work on international keyboard layout
- // cf: https://github.com/bpmn-io/bpmn-js/issues/1362#issuecomment-722989754
- if (isKey([ '+', 'Add', '=' ], event) && isCmd(event)) {
- editorActions.trigger('stepZoom', { value: 1 });
- return true;
- }
- });
- // zoom out one step
- // CTRL + -
- addListener('stepZoom', function(context) {
- var event = context.keyEvent;
- if (isKey([ '-', 'Subtract' ], event) && isCmd(event)) {
- editorActions.trigger('stepZoom', { value: -1 });
- return true;
- }
- });
- // zoom to the default level
- // CTRL + 0
- addListener('zoom', function(context) {
- var event = context.keyEvent;
- if (isKey('0', event) && isCmd(event)) {
- editorActions.trigger('zoom', { value: 1 });
- return true;
- }
- });
- // delete selected element
- // DEL
- addListener('removeSelection', function(context) {
- var event = context.keyEvent;
- if (isKey([ 'Backspace', 'Delete', 'Del' ], event)) {
- editorActions.trigger('removeSelection');
- return true;
- }
- });
- };
- var KeyboardModule = {
- __init__: [ 'keyboard', 'keyboardBindings' ],
- keyboard: [ 'type', Keyboard ],
- keyboardBindings: [ 'type', KeyboardBindings ]
- };
- var DEFAULT_CONFIG = {
- moveSpeed: 50,
- moveSpeedAccelerated: 200
- };
- /**
- * A feature that allows users to move the canvas using the keyboard.
- *
- * @param {Object} config
- * @param {number} [config.moveSpeed=50]
- * @param {number} [config.moveSpeedAccelerated=200]
- * @param {Keyboard} keyboard
- * @param {Canvas} canvas
- */
- function KeyboardMove(
- config,
- keyboard,
- canvas
- ) {
- var self = this;
- this._config = assign({}, DEFAULT_CONFIG, config || {});
- keyboard.addListener(arrowsListener);
- function arrowsListener(context) {
- var event = context.keyEvent,
- config = self._config;
- if (!keyboard.isCmd(event)) {
- return;
- }
- if (keyboard.isKey([
- 'ArrowLeft', 'Left',
- 'ArrowUp', 'Up',
- 'ArrowDown', 'Down',
- 'ArrowRight', 'Right'
- ], event)) {
- var speed = (
- keyboard.isShift(event) ?
- config.moveSpeedAccelerated :
- config.moveSpeed
- );
- var direction;
- switch (event.key) {
- case 'ArrowLeft':
- case 'Left':
- direction = 'left';
- break;
- case 'ArrowUp':
- case 'Up':
- direction = 'up';
- break;
- case 'ArrowRight':
- case 'Right':
- direction = 'right';
- break;
- case 'ArrowDown':
- case 'Down':
- direction = 'down';
- break;
- }
- self.moveCanvas({
- speed: speed,
- direction: direction
- });
- return true;
- }
- }
- this.moveCanvas = function(opts) {
- var dx = 0,
- dy = 0,
- speed = opts.speed;
- var actualSpeed = speed / Math.min(Math.sqrt(canvas.viewbox().scale), 1);
- switch (opts.direction) {
- case 'left': // Left
- dx = actualSpeed;
- break;
- case 'up': // Up
- dy = actualSpeed;
- break;
- case 'right': // Right
- dx = -actualSpeed;
- break;
- case 'down': // Down
- dy = -actualSpeed;
- break;
- }
- canvas.scroll({
- dx: dx,
- dy: dy
- });
- };
- }
- KeyboardMove.$inject = [
- 'config.keyboardMove',
- 'keyboard',
- 'canvas'
- ];
- var KeyboardMoveModule = {
- __depends__: [
- KeyboardModule
- ],
- __init__: [ 'keyboardMove' ],
- keyboardMove: [ 'type', KeyboardMove ]
- };
- var CURSOR_CLS_PATTERN = /^djs-cursor-.*$/;
- function set(mode) {
- var classes$1 = classes(document.body);
- classes$1.removeMatching(CURSOR_CLS_PATTERN);
- if (mode) {
- classes$1.add('djs-cursor-' + mode);
- }
- }
- function unset() {
- set(null);
- }
- var TRAP_PRIORITY = 5000;
- /**
- * Installs a click trap that prevents a ghost click following a dragging operation.
- *
- * @return {Function} a function to immediately remove the installed trap.
- */
- function install(eventBus, eventName) {
- eventName = eventName || 'element.click';
- function trap() {
- return false;
- }
- eventBus.once(eventName, TRAP_PRIORITY, trap);
- return function() {
- eventBus.off(eventName, trap);
- };
- }
- function delta(a, b) {
- return {
- x: a.x - b.x,
- y: a.y - b.y
- };
- }
- var THRESHOLD = 15;
- /**
- * Move the canvas via mouse.
- *
- * @param {EventBus} eventBus
- * @param {Canvas} canvas
- */
- function MoveCanvas(eventBus, canvas) {
- var context;
- // listen for move on element mouse down;
- // allow others to hook into the event before us though
- // (dragging / element moving will do this)
- eventBus.on('element.mousedown', 500, function(e) {
- return handleStart(e.originalEvent);
- });
- function handleMove(event) {
- var start = context.start,
- button = context.button,
- position = toPoint(event),
- delta$1 = delta(position, start);
- if (!context.dragging && length(delta$1) > THRESHOLD) {
- context.dragging = true;
- if (button === 0) {
- install(eventBus);
- }
- set('grab');
- }
- if (context.dragging) {
- var lastPosition = context.last || context.start;
- delta$1 = delta(position, lastPosition);
- canvas.scroll({
- dx: delta$1.x,
- dy: delta$1.y
- });
- context.last = position;
- }
- // prevent select
- event.preventDefault();
- }
- function handleEnd(event) {
- componentEvent.unbind(document, 'mousemove', handleMove);
- componentEvent.unbind(document, 'mouseup', handleEnd);
- context = null;
- unset();
- }
- function handleStart(event) {
- // event is already handled by '.djs-draggable'
- if (closest(event.target, '.djs-draggable')) {
- return;
- }
- var button = event.button;
- // reject right mouse button or modifier key
- if (button >= 2 || event.ctrlKey || event.shiftKey || event.altKey) {
- return;
- }
- context = {
- button: button,
- start: toPoint(event)
- };
- componentEvent.bind(document, 'mousemove', handleMove);
- componentEvent.bind(document, 'mouseup', handleEnd);
- // we've handled the event
- return true;
- }
- this.isActive = function() {
- return !!context;
- };
- }
- MoveCanvas.$inject = [
- 'eventBus',
- 'canvas'
- ];
- // helpers ///////
- function length(point) {
- return Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2));
- }
- var MoveCanvasModule = {
- __init__: [ 'moveCanvas' ],
- moveCanvas: [ 'type', MoveCanvas ]
- };
- /**
- * Get the logarithm of x with base 10
- * @param {Integer} value
- */
- function log10(x) {
- return Math.log(x) / Math.log(10);
- }
- /**
- * Get step size for given range and number of steps.
- *
- * @param {Object} range
- * @param {number} range.min
- * @param {number} range.max
- */
- function getStepSize(range, steps) {
- var minLinearRange = log10(range.min),
- maxLinearRange = log10(range.max);
- var absoluteLinearRange = Math.abs(minLinearRange) + Math.abs(maxLinearRange);
- return absoluteLinearRange / steps;
- }
- function cap(range, scale) {
- return Math.max(range.min, Math.min(range.max, scale));
- }
- var sign = Math.sign || function(n) {
- return n >= 0 ? 1 : -1;
- };
- var RANGE = { min: 0.2, max: 4 },
- NUM_STEPS = 10;
- var DELTA_THRESHOLD = 0.1;
- var DEFAULT_SCALE = 0.75;
- /**
- * An implementation of zooming and scrolling within the
- * {@link Canvas} via the mouse wheel.
- *
- * Mouse wheel zooming / scrolling may be disabled using
- * the {@link toggle(enabled)} method.
- *
- * @param {Object} [config]
- * @param {boolean} [config.enabled=true] default enabled state
- * @param {number} [config.scale=.75] scroll sensivity
- * @param {EventBus} eventBus
- * @param {Canvas} canvas
- */
- function ZoomScroll(config, eventBus, canvas) {
- config = config || {};
- this._enabled = false;
- this._canvas = canvas;
- this._container = canvas._container;
- this._handleWheel = bind(this._handleWheel, this);
- this._totalDelta = 0;
- this._scale = config.scale || DEFAULT_SCALE;
- var self = this;
- eventBus.on('canvas.init', function(e) {
- self._init(config.enabled !== false);
- });
- }
- ZoomScroll.$inject = [
- 'config.zoomScroll',
- 'eventBus',
- 'canvas'
- ];
- ZoomScroll.prototype.scroll = function scroll(delta) {
- this._canvas.scroll(delta);
- };
- ZoomScroll.prototype.reset = function reset() {
- this._canvas.zoom('fit-viewport');
- };
- /**
- * Zoom depending on delta.
- *
- * @param {number} delta
- * @param {Object} position
- */
- ZoomScroll.prototype.zoom = function zoom(delta, position) {
- // zoom with half the step size of stepZoom
- var stepSize = getStepSize(RANGE, NUM_STEPS * 2);
- // add until threshold reached
- this._totalDelta += delta;
- if (Math.abs(this._totalDelta) > DELTA_THRESHOLD) {
- this._zoom(delta, position, stepSize);
- // reset
- this._totalDelta = 0;
- }
- };
- ZoomScroll.prototype._handleWheel = function handleWheel(event) {
- // event is already handled by '.djs-scrollable'
- if (closest(event.target, '.djs-scrollable', true)) {
- return;
- }
- var element = this._container;
- event.preventDefault();
- // pinch to zoom is mapped to wheel + ctrlKey = true
- // in modern browsers (!)
- var isZoom = event.ctrlKey;
- var isHorizontalScroll = event.shiftKey;
- var factor = -1 * this._scale,
- delta;
- if (isZoom) {
- factor *= event.deltaMode === 0 ? 0.020 : 0.32;
- } else {
- factor *= event.deltaMode === 0 ? 1.0 : 16.0;
- }
- if (isZoom) {
- var elementRect = element.getBoundingClientRect();
- var offset = {
- x: event.clientX - elementRect.left,
- y: event.clientY - elementRect.top
- };
- delta = (
- Math.sqrt(
- Math.pow(event.deltaY, 2) +
- Math.pow(event.deltaX, 2)
- ) * sign(event.deltaY) * factor
- );
- // zoom in relative to diagram {x,y} coordinates
- this.zoom(delta, offset);
- } else {
- if (isHorizontalScroll) {
- delta = {
- dx: factor * event.deltaY,
- dy: 0
- };
- } else {
- delta = {
- dx: factor * event.deltaX,
- dy: factor * event.deltaY
- };
- }
- this.scroll(delta);
- }
- };
- /**
- * Zoom with fixed step size.
- *
- * @param {number} delta - Zoom delta (1 for zooming in, -1 for out).
- * @param {Object} position
- */
- ZoomScroll.prototype.stepZoom = function stepZoom(delta, position) {
- var stepSize = getStepSize(RANGE, NUM_STEPS);
- this._zoom(delta, position, stepSize);
- };
- /**
- * Zoom in/out given a step size.
- *
- * @param {number} delta
- * @param {Object} position
- * @param {number} stepSize
- */
- ZoomScroll.prototype._zoom = function(delta, position, stepSize) {
- var canvas = this._canvas;
- var direction = delta > 0 ? 1 : -1;
- var currentLinearZoomLevel = log10(canvas.zoom());
- // snap to a proximate zoom step
- var newLinearZoomLevel = Math.round(currentLinearZoomLevel / stepSize) * stepSize;
- // increase or decrease one zoom step in the given direction
- newLinearZoomLevel += stepSize * direction;
- // calculate the absolute logarithmic zoom level based on the linear zoom level
- // (e.g. 2 for an absolute x2 zoom)
- var newLogZoomLevel = Math.pow(10, newLinearZoomLevel);
- canvas.zoom(cap(RANGE, newLogZoomLevel), position);
- };
- /**
- * Toggle the zoom scroll ability via mouse wheel.
- *
- * @param {boolean} [newEnabled] new enabled state
- */
- ZoomScroll.prototype.toggle = function toggle(newEnabled) {
- var element = this._container;
- var handleWheel = this._handleWheel;
- var oldEnabled = this._enabled;
- if (typeof newEnabled === 'undefined') {
- newEnabled = !oldEnabled;
- }
- // only react on actual changes
- if (oldEnabled !== newEnabled) {
- // add or remove wheel listener based on
- // changed enabled state
- componentEvent[newEnabled ? 'bind' : 'unbind'](element, 'wheel', handleWheel, false);
- }
- this._enabled = newEnabled;
- return newEnabled;
- };
- ZoomScroll.prototype._init = function(newEnabled) {
- this.toggle(newEnabled);
- };
- var ZoomScrollModule = {
- __init__: [ 'zoomScroll' ],
- zoomScroll: [ 'type', ZoomScroll ]
- };
- /**
- * A viewer that includes mouse navigation facilities
- *
- * @param {Object} options
- */
- function NavigatedViewer(options) {
- Viewer.call(this, options);
- }
- e(NavigatedViewer, Viewer);
- NavigatedViewer.prototype._navigationModules = [
- KeyboardMoveModule,
- MoveCanvasModule,
- ZoomScrollModule
- ];
- NavigatedViewer.prototype._modules = [].concat(
- Viewer.prototype._modules,
- NavigatedViewer.prototype._navigationModules
- );
- return NavigatedViewer;
- })));
|