epub.js 499 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory(require("xmldom"), (function webpackLoadOptionalExternalModule() { try { return require("jszip"); } catch(e) {} }()));
  4. else if(typeof define === 'function' && define.amd)
  5. define(["xmldom", "jszip"], factory);
  6. else if(typeof exports === 'object')
  7. exports["ePub"] = factory(require("xmldom"), (function webpackLoadOptionalExternalModule() { try { return require("jszip"); } catch(e) {} }()));
  8. else
  9. root["ePub"] = factory(root["xmldom"], root["jszip"]);
  10. })(this, function(__WEBPACK_EXTERNAL_MODULE_42__, __WEBPACK_EXTERNAL_MODULE_71__) {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, {
  50. /******/ configurable: false,
  51. /******/ enumerable: true,
  52. /******/ get: getter
  53. /******/ });
  54. /******/ }
  55. /******/ };
  56. /******/
  57. /******/ // getDefaultExport function for compatibility with non-harmony modules
  58. /******/ __webpack_require__.n = function(module) {
  59. /******/ var getter = module && module.__esModule ?
  60. /******/ function getDefault() { return module['default']; } :
  61. /******/ function getModuleExports() { return module; };
  62. /******/ __webpack_require__.d(getter, 'a', getter);
  63. /******/ return getter;
  64. /******/ };
  65. /******/
  66. /******/ // Object.prototype.hasOwnProperty.call
  67. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  68. /******/
  69. /******/ // __webpack_public_path__
  70. /******/ __webpack_require__.p = "/dist/";
  71. /******/
  72. /******/ // Load entry module and return exports
  73. /******/ return __webpack_require__(__webpack_require__.s = 25);
  74. /******/ })
  75. /************************************************************************/
  76. /******/ ([
  77. /* 0 */
  78. /***/ (function(module, exports, __webpack_require__) {
  79. "use strict";
  80. Object.defineProperty(exports, "__esModule", {
  81. value: true
  82. });
  83. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  84. exports.uuid = uuid;
  85. exports.documentHeight = documentHeight;
  86. exports.isElement = isElement;
  87. exports.isNumber = isNumber;
  88. exports.isFloat = isFloat;
  89. exports.prefixed = prefixed;
  90. exports.defaults = defaults;
  91. exports.extend = extend;
  92. exports.insert = insert;
  93. exports.locationOf = locationOf;
  94. exports.indexOfSorted = indexOfSorted;
  95. exports.bounds = bounds;
  96. exports.borders = borders;
  97. exports.nodeBounds = nodeBounds;
  98. exports.windowBounds = windowBounds;
  99. exports.indexOfNode = indexOfNode;
  100. exports.indexOfTextNode = indexOfTextNode;
  101. exports.indexOfElementNode = indexOfElementNode;
  102. exports.isXml = isXml;
  103. exports.createBlob = createBlob;
  104. exports.createBlobUrl = createBlobUrl;
  105. exports.revokeBlobUrl = revokeBlobUrl;
  106. exports.createBase64Url = createBase64Url;
  107. exports.type = type;
  108. exports.parse = parse;
  109. exports.qs = qs;
  110. exports.qsa = qsa;
  111. exports.qsp = qsp;
  112. exports.sprint = sprint;
  113. exports.treeWalker = treeWalker;
  114. exports.walk = walk;
  115. exports.blob2base64 = blob2base64;
  116. exports.defer = defer;
  117. exports.querySelectorByType = querySelectorByType;
  118. exports.findChildren = findChildren;
  119. exports.parents = parents;
  120. exports.filterChildren = filterChildren;
  121. exports.getParentByTagName = getParentByTagName;
  122. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  123. /**
  124. * Core Utilities and Helpers
  125. * @module Core
  126. */
  127. /**
  128. * Vendor prefixed requestAnimationFrame
  129. * @returns {function} requestAnimationFrame
  130. * @memberof Core
  131. */
  132. var requestAnimationFrame = exports.requestAnimationFrame = typeof window != "undefined" ? window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame : false;
  133. var ELEMENT_NODE = 1;
  134. var TEXT_NODE = 3;
  135. var COMMENT_NODE = 8;
  136. var DOCUMENT_NODE = 9;
  137. var _URL = typeof URL != "undefined" ? URL : typeof window != "undefined" ? window.URL || window.webkitURL || window.mozURL : undefined;
  138. /**
  139. * Generates a UUID
  140. * based on: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
  141. * @returns {string} uuid
  142. * @memberof Core
  143. */
  144. function uuid() {
  145. var d = new Date().getTime();
  146. var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
  147. var r = (d + Math.random() * 16) % 16 | 0;
  148. d = Math.floor(d / 16);
  149. return (c == "x" ? r : r & 0x7 | 0x8).toString(16);
  150. });
  151. return uuid;
  152. }
  153. /**
  154. * Gets the height of a document
  155. * @returns {number} height
  156. * @memberof Core
  157. */
  158. function documentHeight() {
  159. return Math.max(document.documentElement.clientHeight, document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight);
  160. }
  161. /**
  162. * Checks if a node is an element
  163. * @param {object} obj
  164. * @returns {boolean}
  165. * @memberof Core
  166. */
  167. function isElement(obj) {
  168. return !!(obj && obj.nodeType == 1);
  169. }
  170. /**
  171. * @param {any} n
  172. * @returns {boolean}
  173. * @memberof Core
  174. */
  175. function isNumber(n) {
  176. return !isNaN(parseFloat(n)) && isFinite(n);
  177. }
  178. /**
  179. * @param {any} n
  180. * @returns {boolean}
  181. * @memberof Core
  182. */
  183. function isFloat(n) {
  184. var f = parseFloat(n);
  185. if (isNumber(n) === false) {
  186. return false;
  187. }
  188. if (typeof n === "string" && n.indexOf(".") > -1) {
  189. return true;
  190. }
  191. return Math.floor(f) !== f;
  192. }
  193. /**
  194. * Get a prefixed css property
  195. * @param {string} unprefixed
  196. * @returns {string}
  197. * @memberof Core
  198. */
  199. function prefixed(unprefixed) {
  200. var vendors = ["Webkit", "webkit", "Moz", "O", "ms"];
  201. var prefixes = ["-webkit-", "-webkit-", "-moz-", "-o-", "-ms-"];
  202. var upper = unprefixed[0].toUpperCase() + unprefixed.slice(1);
  203. var length = vendors.length;
  204. if (typeof document === "undefined" || typeof document.body.style[unprefixed] != "undefined") {
  205. return unprefixed;
  206. }
  207. for (var i = 0; i < length; i++) {
  208. if (typeof document.body.style[vendors[i] + upper] != "undefined") {
  209. return prefixes[i] + unprefixed;
  210. }
  211. }
  212. return unprefixed;
  213. }
  214. /**
  215. * Apply defaults to an object
  216. * @param {object} obj
  217. * @returns {object}
  218. * @memberof Core
  219. */
  220. function defaults(obj) {
  221. for (var i = 1, length = arguments.length; i < length; i++) {
  222. var source = arguments[i];
  223. for (var prop in source) {
  224. if (obj[prop] === void 0) obj[prop] = source[prop];
  225. }
  226. }
  227. return obj;
  228. }
  229. /**
  230. * Extend properties of an object
  231. * @param {object} target
  232. * @returns {object}
  233. * @memberof Core
  234. */
  235. function extend(target) {
  236. var sources = [].slice.call(arguments, 1);
  237. sources.forEach(function (source) {
  238. if (!source) return;
  239. Object.getOwnPropertyNames(source).forEach(function (propName) {
  240. Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName));
  241. });
  242. });
  243. return target;
  244. }
  245. /**
  246. * Fast quicksort insert for sorted array -- based on:
  247. * http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers
  248. * @param {any} item
  249. * @param {array} array
  250. * @param {function} [compareFunction]
  251. * @returns {number} location (in array)
  252. * @memberof Core
  253. */
  254. function insert(item, array, compareFunction) {
  255. var location = locationOf(item, array, compareFunction);
  256. array.splice(location, 0, item);
  257. return location;
  258. }
  259. /**
  260. * Finds where something would fit into a sorted array
  261. * @param {any} item
  262. * @param {array} array
  263. * @param {function} [compareFunction]
  264. * @param {function} [_start]
  265. * @param {function} [_end]
  266. * @returns {number} location (in array)
  267. * @memberof Core
  268. */
  269. function locationOf(item, array, compareFunction, _start, _end) {
  270. var start = _start || 0;
  271. var end = _end || array.length;
  272. var pivot = parseInt(start + (end - start) / 2);
  273. var compared;
  274. if (!compareFunction) {
  275. compareFunction = function compareFunction(a, b) {
  276. if (a > b) return 1;
  277. if (a < b) return -1;
  278. if (a == b) return 0;
  279. };
  280. }
  281. if (end - start <= 0) {
  282. return pivot;
  283. }
  284. compared = compareFunction(array[pivot], item);
  285. if (end - start === 1) {
  286. return compared >= 0 ? pivot : pivot + 1;
  287. }
  288. if (compared === 0) {
  289. return pivot;
  290. }
  291. if (compared === -1) {
  292. return locationOf(item, array, compareFunction, pivot, end);
  293. } else {
  294. return locationOf(item, array, compareFunction, start, pivot);
  295. }
  296. }
  297. /**
  298. * Finds index of something in a sorted array
  299. * Returns -1 if not found
  300. * @param {any} item
  301. * @param {array} array
  302. * @param {function} [compareFunction]
  303. * @param {function} [_start]
  304. * @param {function} [_end]
  305. * @returns {number} index (in array) or -1
  306. * @memberof Core
  307. */
  308. function indexOfSorted(item, array, compareFunction, _start, _end) {
  309. var start = _start || 0;
  310. var end = _end || array.length;
  311. var pivot = parseInt(start + (end - start) / 2);
  312. var compared;
  313. if (!compareFunction) {
  314. compareFunction = function compareFunction(a, b) {
  315. if (a > b) return 1;
  316. if (a < b) return -1;
  317. if (a == b) return 0;
  318. };
  319. }
  320. if (end - start <= 0) {
  321. return -1; // Not found
  322. }
  323. compared = compareFunction(array[pivot], item);
  324. if (end - start === 1) {
  325. return compared === 0 ? pivot : -1;
  326. }
  327. if (compared === 0) {
  328. return pivot; // Found
  329. }
  330. if (compared === -1) {
  331. return indexOfSorted(item, array, compareFunction, pivot, end);
  332. } else {
  333. return indexOfSorted(item, array, compareFunction, start, pivot);
  334. }
  335. }
  336. /**
  337. * Find the bounds of an element
  338. * taking padding and margin into account
  339. * @param {element} el
  340. * @returns {{ width: Number, height: Number}}
  341. * @memberof Core
  342. */
  343. function bounds(el) {
  344. var style = window.getComputedStyle(el);
  345. var widthProps = ["width", "paddingRight", "paddingLeft", "marginRight", "marginLeft", "borderRightWidth", "borderLeftWidth"];
  346. var heightProps = ["height", "paddingTop", "paddingBottom", "marginTop", "marginBottom", "borderTopWidth", "borderBottomWidth"];
  347. var width = 0;
  348. var height = 0;
  349. widthProps.forEach(function (prop) {
  350. width += parseFloat(style[prop]) || 0;
  351. });
  352. heightProps.forEach(function (prop) {
  353. height += parseFloat(style[prop]) || 0;
  354. });
  355. return {
  356. height: height,
  357. width: width
  358. };
  359. }
  360. /**
  361. * Find the bounds of an element
  362. * taking padding, margin and borders into account
  363. * @param {element} el
  364. * @returns {{ width: Number, height: Number}}
  365. * @memberof Core
  366. */
  367. function borders(el) {
  368. var style = window.getComputedStyle(el);
  369. var widthProps = ["paddingRight", "paddingLeft", "marginRight", "marginLeft", "borderRightWidth", "borderLeftWidth"];
  370. var heightProps = ["paddingTop", "paddingBottom", "marginTop", "marginBottom", "borderTopWidth", "borderBottomWidth"];
  371. var width = 0;
  372. var height = 0;
  373. widthProps.forEach(function (prop) {
  374. width += parseFloat(style[prop]) || 0;
  375. });
  376. heightProps.forEach(function (prop) {
  377. height += parseFloat(style[prop]) || 0;
  378. });
  379. return {
  380. height: height,
  381. width: width
  382. };
  383. }
  384. /**
  385. * Find the bounds of any node
  386. * allows for getting bounds of text nodes by wrapping them in a range
  387. * @param {node} node
  388. * @returns {BoundingClientRect}
  389. * @memberof Core
  390. */
  391. function nodeBounds(node) {
  392. var elPos = void 0;
  393. var doc = node.ownerDocument;
  394. if (node.nodeType == Node.TEXT_NODE) {
  395. var elRange = doc.createRange();
  396. elRange.selectNodeContents(node);
  397. elPos = elRange.getBoundingClientRect();
  398. } else {
  399. elPos = node.getBoundingClientRect();
  400. }
  401. return elPos;
  402. }
  403. /**
  404. * Find the equivelent of getBoundingClientRect of a browser window
  405. * @returns {{ width: Number, height: Number, top: Number, left: Number, right: Number, bottom: Number }}
  406. * @memberof Core
  407. */
  408. function windowBounds() {
  409. var width = window.innerWidth;
  410. var height = window.innerHeight;
  411. return {
  412. top: 0,
  413. left: 0,
  414. right: width,
  415. bottom: height,
  416. width: width,
  417. height: height
  418. };
  419. }
  420. /**
  421. * Gets the index of a node in its parent
  422. * @param {Node} node
  423. * @param {string} typeId
  424. * @return {number} index
  425. * @memberof Core
  426. */
  427. function indexOfNode(node, typeId) {
  428. var parent = node.parentNode;
  429. var children = parent.childNodes;
  430. var sib;
  431. var index = -1;
  432. for (var i = 0; i < children.length; i++) {
  433. sib = children[i];
  434. if (sib.nodeType === typeId) {
  435. index++;
  436. }
  437. if (sib == node) break;
  438. }
  439. return index;
  440. }
  441. /**
  442. * Gets the index of a text node in its parent
  443. * @param {node} textNode
  444. * @returns {number} index
  445. * @memberof Core
  446. */
  447. function indexOfTextNode(textNode) {
  448. return indexOfNode(textNode, TEXT_NODE);
  449. }
  450. /**
  451. * Gets the index of an element node in its parent
  452. * @param {element} elementNode
  453. * @returns {number} index
  454. * @memberof Core
  455. */
  456. function indexOfElementNode(elementNode) {
  457. return indexOfNode(elementNode, ELEMENT_NODE);
  458. }
  459. /**
  460. * Check if extension is xml
  461. * @param {string} ext
  462. * @returns {boolean}
  463. * @memberof Core
  464. */
  465. function isXml(ext) {
  466. return ["xml", "opf", "ncx"].indexOf(ext) > -1;
  467. }
  468. /**
  469. * Create a new blob
  470. * @param {any} content
  471. * @param {string} mime
  472. * @returns {Blob}
  473. * @memberof Core
  474. */
  475. function createBlob(content, mime) {
  476. return new Blob([content], { type: mime });
  477. }
  478. /**
  479. * Create a new blob url
  480. * @param {any} content
  481. * @param {string} mime
  482. * @returns {string} url
  483. * @memberof Core
  484. */
  485. function createBlobUrl(content, mime) {
  486. var tempUrl;
  487. var blob = createBlob(content, mime);
  488. tempUrl = _URL.createObjectURL(blob);
  489. return tempUrl;
  490. }
  491. /**
  492. * Remove a blob url
  493. * @param {string} url
  494. * @memberof Core
  495. */
  496. function revokeBlobUrl(url) {
  497. return _URL.revokeObjectURL(url);
  498. }
  499. /**
  500. * Create a new base64 encoded url
  501. * @param {any} content
  502. * @param {string} mime
  503. * @returns {string} url
  504. * @memberof Core
  505. */
  506. function createBase64Url(content, mime) {
  507. var data;
  508. var datauri;
  509. if (typeof content !== "string") {
  510. // Only handles strings
  511. return;
  512. }
  513. data = btoa(encodeURIComponent(content));
  514. datauri = "data:" + mime + ";base64," + data;
  515. return datauri;
  516. }
  517. /**
  518. * Get type of an object
  519. * @param {object} obj
  520. * @returns {string} type
  521. * @memberof Core
  522. */
  523. function type(obj) {
  524. return Object.prototype.toString.call(obj).slice(8, -1);
  525. }
  526. /**
  527. * Parse xml (or html) markup
  528. * @param {string} markup
  529. * @param {string} mime
  530. * @param {boolean} forceXMLDom force using xmlDom to parse instead of native parser
  531. * @returns {document} document
  532. * @memberof Core
  533. */
  534. function parse(markup, mime, forceXMLDom) {
  535. var doc;
  536. var Parser;
  537. if (typeof DOMParser === "undefined" || forceXMLDom) {
  538. Parser = __webpack_require__(42).DOMParser;
  539. } else {
  540. Parser = DOMParser;
  541. }
  542. // Remove byte order mark before parsing
  543. // https://www.w3.org/International/questions/qa-byte-order-mark
  544. if (markup.charCodeAt(0) === 0xFEFF) {
  545. markup = markup.slice(1);
  546. }
  547. doc = new Parser().parseFromString(markup, mime);
  548. return doc;
  549. }
  550. /**
  551. * querySelector polyfill
  552. * @param {element} el
  553. * @param {string} sel selector string
  554. * @returns {element} element
  555. * @memberof Core
  556. */
  557. function qs(el, sel) {
  558. var elements;
  559. if (!el) {
  560. throw new Error("No Element Provided");
  561. }
  562. if (typeof el.querySelector != "undefined") {
  563. return el.querySelector(sel);
  564. } else {
  565. elements = el.getElementsByTagName(sel);
  566. if (elements.length) {
  567. return elements[0];
  568. }
  569. }
  570. }
  571. /**
  572. * querySelectorAll polyfill
  573. * @param {element} el
  574. * @param {string} sel selector string
  575. * @returns {element[]} elements
  576. * @memberof Core
  577. */
  578. function qsa(el, sel) {
  579. if (typeof el.querySelector != "undefined") {
  580. return el.querySelectorAll(sel);
  581. } else {
  582. return el.getElementsByTagName(sel);
  583. }
  584. }
  585. /**
  586. * querySelector by property
  587. * @param {element} el
  588. * @param {string} sel selector string
  589. * @param {object[]} props
  590. * @returns {element[]} elements
  591. * @memberof Core
  592. */
  593. function qsp(el, sel, props) {
  594. var q, filtered;
  595. if (typeof el.querySelector != "undefined") {
  596. sel += "[";
  597. for (var prop in props) {
  598. sel += prop + "~='" + props[prop] + "'";
  599. }
  600. sel += "]";
  601. return el.querySelector(sel);
  602. } else {
  603. q = el.getElementsByTagName(sel);
  604. filtered = Array.prototype.slice.call(q, 0).filter(function (el) {
  605. for (var prop in props) {
  606. if (el.getAttribute(prop) === props[prop]) {
  607. return true;
  608. }
  609. }
  610. return false;
  611. });
  612. if (filtered) {
  613. return filtered[0];
  614. }
  615. }
  616. }
  617. /**
  618. * Sprint through all text nodes in a document
  619. * @memberof Core
  620. * @param {element} root element to start with
  621. * @param {function} func function to run on each element
  622. */
  623. function sprint(root, func) {
  624. var doc = root.ownerDocument || root;
  625. if (typeof doc.createTreeWalker !== "undefined") {
  626. treeWalker(root, func, NodeFilter.SHOW_TEXT);
  627. } else {
  628. walk(root, function (node) {
  629. if (node && node.nodeType === 3) {
  630. // Node.TEXT_NODE
  631. func(node);
  632. }
  633. }, true);
  634. }
  635. }
  636. /**
  637. * Create a treeWalker
  638. * @memberof Core
  639. * @param {element} root element to start with
  640. * @param {function} func function to run on each element
  641. * @param {function | object} filter funtion or object to filter with
  642. */
  643. function treeWalker(root, func, filter) {
  644. var treeWalker = document.createTreeWalker(root, filter, null, false);
  645. var node = void 0;
  646. while (node = treeWalker.nextNode()) {
  647. func(node);
  648. }
  649. }
  650. /**
  651. * @memberof Core
  652. * @param {node} node
  653. * @param {callback} return false for continue,true for break inside callback
  654. */
  655. function walk(node, callback) {
  656. if (callback(node)) {
  657. return true;
  658. }
  659. node = node.firstChild;
  660. if (node) {
  661. do {
  662. var walked = walk(node, callback);
  663. if (walked) {
  664. return true;
  665. }
  666. node = node.nextSibling;
  667. } while (node);
  668. }
  669. }
  670. /**
  671. * Convert a blob to a base64 encoded string
  672. * @param {Blog} blob
  673. * @returns {string}
  674. * @memberof Core
  675. */
  676. function blob2base64(blob) {
  677. return new Promise(function (resolve, reject) {
  678. var reader = new FileReader();
  679. reader.readAsDataURL(blob);
  680. reader.onloadend = function () {
  681. resolve(reader.result);
  682. };
  683. });
  684. }
  685. /**
  686. * Creates a new pending promise and provides methods to resolve or reject it.
  687. * From: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred#backwards_forwards_compatible
  688. * @memberof Core
  689. */
  690. function defer() {
  691. var _this = this;
  692. /* A method to resolve the associated Promise with the value passed.
  693. * If the promise is already settled it does nothing.
  694. *
  695. * @param {anything} value : This value is used to resolve the promise
  696. * If the value is a Promise then the associated promise assumes the state
  697. * of Promise passed as value.
  698. */
  699. this.resolve = null;
  700. /* A method to reject the assocaited Promise with the value passed.
  701. * If the promise is already settled it does nothing.
  702. *
  703. * @param {anything} reason: The reason for the rejection of the Promise.
  704. * Generally its an Error object. If however a Promise is passed, then the Promise
  705. * itself will be the reason for rejection no matter the state of the Promise.
  706. */
  707. this.reject = null;
  708. this.id = uuid();
  709. /* A newly created Pomise object.
  710. * Initially in pending state.
  711. */
  712. this.promise = new Promise(function (resolve, reject) {
  713. _this.resolve = resolve;
  714. _this.reject = reject;
  715. });
  716. Object.freeze(this);
  717. }
  718. /**
  719. * querySelector with filter by epub type
  720. * @param {element} html
  721. * @param {string} element element type to find
  722. * @param {string} type epub type to find
  723. * @returns {element[]} elements
  724. * @memberof Core
  725. */
  726. function querySelectorByType(html, element, type) {
  727. var query;
  728. if (typeof html.querySelector != "undefined") {
  729. query = html.querySelector(element + "[*|type=\"" + type + "\"]");
  730. }
  731. // Handle IE not supporting namespaced epub:type in querySelector
  732. if (!query || query.length === 0) {
  733. query = qsa(html, element);
  734. for (var i = 0; i < query.length; i++) {
  735. if (query[i].getAttributeNS("http://www.idpf.org/2007/ops", "type") === type || query[i].getAttribute("epub:type") === type) {
  736. return query[i];
  737. }
  738. }
  739. } else {
  740. return query;
  741. }
  742. }
  743. /**
  744. * Find direct decendents of an element
  745. * @param {element} el
  746. * @returns {element[]} children
  747. * @memberof Core
  748. */
  749. function findChildren(el) {
  750. var result = [];
  751. var childNodes = el.childNodes;
  752. for (var i = 0; i < childNodes.length; i++) {
  753. var node = childNodes[i];
  754. if (node.nodeType === 1) {
  755. result.push(node);
  756. }
  757. }
  758. return result;
  759. }
  760. /**
  761. * Find all parents (ancestors) of an element
  762. * @param {element} node
  763. * @returns {element[]} parents
  764. * @memberof Core
  765. */
  766. function parents(node) {
  767. var nodes = [node];
  768. for (; node; node = node.parentNode) {
  769. nodes.unshift(node);
  770. }
  771. return nodes;
  772. }
  773. /**
  774. * Find all direct decendents of a specific type
  775. * @param {element} el
  776. * @param {string} nodeName
  777. * @param {boolean} [single]
  778. * @returns {element[]} children
  779. * @memberof Core
  780. */
  781. function filterChildren(el, nodeName, single) {
  782. var result = [];
  783. var childNodes = el.childNodes;
  784. for (var i = 0; i < childNodes.length; i++) {
  785. var node = childNodes[i];
  786. if (node.nodeType === 1 && node.nodeName.toLowerCase() === nodeName) {
  787. if (single) {
  788. return node;
  789. } else {
  790. result.push(node);
  791. }
  792. }
  793. }
  794. if (!single) {
  795. return result;
  796. }
  797. }
  798. /**
  799. * Filter all parents (ancestors) with tag name
  800. * @param {element} node
  801. * @param {string} tagname
  802. * @returns {element[]} parents
  803. * @memberof Core
  804. */
  805. function getParentByTagName(node, tagname) {
  806. var parent = void 0;
  807. if (node === null || tagname === '') return;
  808. parent = node.parentNode;
  809. while (parent.nodeType === 1) {
  810. if (parent.tagName.toLowerCase() === tagname) {
  811. return parent;
  812. }
  813. parent = parent.parentNode;
  814. }
  815. }
  816. /**
  817. * Lightweight Polyfill for DOM Range
  818. * @class
  819. * @memberof Core
  820. */
  821. var RangeObject = exports.RangeObject = function () {
  822. function RangeObject() {
  823. _classCallCheck(this, RangeObject);
  824. this.collapsed = false;
  825. this.commonAncestorContainer = undefined;
  826. this.endContainer = undefined;
  827. this.endOffset = undefined;
  828. this.startContainer = undefined;
  829. this.startOffset = undefined;
  830. }
  831. _createClass(RangeObject, [{
  832. key: "setStart",
  833. value: function setStart(startNode, startOffset) {
  834. this.startContainer = startNode;
  835. this.startOffset = startOffset;
  836. if (!this.endContainer) {
  837. this.collapse(true);
  838. } else {
  839. this.commonAncestorContainer = this._commonAncestorContainer();
  840. }
  841. this._checkCollapsed();
  842. }
  843. }, {
  844. key: "setEnd",
  845. value: function setEnd(endNode, endOffset) {
  846. this.endContainer = endNode;
  847. this.endOffset = endOffset;
  848. if (!this.startContainer) {
  849. this.collapse(false);
  850. } else {
  851. this.collapsed = false;
  852. this.commonAncestorContainer = this._commonAncestorContainer();
  853. }
  854. this._checkCollapsed();
  855. }
  856. }, {
  857. key: "collapse",
  858. value: function collapse(toStart) {
  859. this.collapsed = true;
  860. if (toStart) {
  861. this.endContainer = this.startContainer;
  862. this.endOffset = this.startOffset;
  863. this.commonAncestorContainer = this.startContainer.parentNode;
  864. } else {
  865. this.startContainer = this.endContainer;
  866. this.startOffset = this.endOffset;
  867. this.commonAncestorContainer = this.endOffset.parentNode;
  868. }
  869. }
  870. }, {
  871. key: "selectNode",
  872. value: function selectNode(referenceNode) {
  873. var parent = referenceNode.parentNode;
  874. var index = Array.prototype.indexOf.call(parent.childNodes, referenceNode);
  875. this.setStart(parent, index);
  876. this.setEnd(parent, index + 1);
  877. }
  878. }, {
  879. key: "selectNodeContents",
  880. value: function selectNodeContents(referenceNode) {
  881. var end = referenceNode.childNodes[referenceNode.childNodes - 1];
  882. var endIndex = referenceNode.nodeType === 3 ? referenceNode.textContent.length : parent.childNodes.length;
  883. this.setStart(referenceNode, 0);
  884. this.setEnd(referenceNode, endIndex);
  885. }
  886. }, {
  887. key: "_commonAncestorContainer",
  888. value: function _commonAncestorContainer(startContainer, endContainer) {
  889. var startParents = parents(startContainer || this.startContainer);
  890. var endParents = parents(endContainer || this.endContainer);
  891. if (startParents[0] != endParents[0]) return undefined;
  892. for (var i = 0; i < startParents.length; i++) {
  893. if (startParents[i] != endParents[i]) {
  894. return startParents[i - 1];
  895. }
  896. }
  897. }
  898. }, {
  899. key: "_checkCollapsed",
  900. value: function _checkCollapsed() {
  901. if (this.startContainer === this.endContainer && this.startOffset === this.endOffset) {
  902. this.collapsed = true;
  903. } else {
  904. this.collapsed = false;
  905. }
  906. }
  907. }, {
  908. key: "toString",
  909. value: function toString() {
  910. // TODO: implement walking between start and end to find text
  911. }
  912. }]);
  913. return RangeObject;
  914. }();
  915. /***/ }),
  916. /* 1 */
  917. /***/ (function(module, exports, __webpack_require__) {
  918. "use strict";
  919. Object.defineProperty(exports, "__esModule", {
  920. value: true
  921. });
  922. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  923. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  924. var _core = __webpack_require__(0);
  925. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  926. var ELEMENT_NODE = 1;
  927. var TEXT_NODE = 3;
  928. var COMMENT_NODE = 8;
  929. var DOCUMENT_NODE = 9;
  930. /**
  931. * Parsing and creation of EpubCFIs: http://www.idpf.org/epub/linking/cfi/epub-cfi.html
  932. * Implements:
  933. * - Character Offset: epubcfi(/6/4[chap01ref]!/4[body01]/10[para05]/2/1:3)
  934. * - Simple Ranges : epubcfi(/6/4[chap01ref]!/4[body01]/10[para05],/2/1:1,/3:4)
  935. * Does Not Implement:
  936. * - Temporal Offset (~)
  937. * - Spatial Offset (@)
  938. * - Temporal-Spatial Offset (~ + @)
  939. * - Text Location Assertion ([)
  940. * @class
  941. @param {string | Range | Node } [cfiFrom]
  942. @param {string | object} [base]
  943. @param {string} [ignoreClass] class to ignore when parsing DOM
  944. */
  945. var EpubCFI = function () {
  946. function EpubCFI(cfiFrom, base, ignoreClass) {
  947. _classCallCheck(this, EpubCFI);
  948. var type;
  949. this.str = "";
  950. this.base = {};
  951. this.spinePos = 0; // For compatibility
  952. this.range = false; // true || false;
  953. this.path = {};
  954. this.start = null;
  955. this.end = null;
  956. // Allow instantiation without the "new" keyword
  957. if (!(this instanceof EpubCFI)) {
  958. return new EpubCFI(cfiFrom, base, ignoreClass);
  959. }
  960. if (typeof base === "string") {
  961. this.base = this.parseComponent(base);
  962. } else if ((typeof base === "undefined" ? "undefined" : _typeof(base)) === "object" && base.steps) {
  963. this.base = base;
  964. }
  965. type = this.checkType(cfiFrom);
  966. if (type === "string") {
  967. this.str = cfiFrom;
  968. return (0, _core.extend)(this, this.parse(cfiFrom));
  969. } else if (type === "range") {
  970. return (0, _core.extend)(this, this.fromRange(cfiFrom, this.base, ignoreClass));
  971. } else if (type === "node") {
  972. return (0, _core.extend)(this, this.fromNode(cfiFrom, this.base, ignoreClass));
  973. } else if (type === "EpubCFI" && cfiFrom.path) {
  974. return cfiFrom;
  975. } else if (!cfiFrom) {
  976. return this;
  977. } else {
  978. throw new TypeError("not a valid argument for EpubCFI");
  979. }
  980. }
  981. /**
  982. * Check the type of constructor input
  983. * @private
  984. */
  985. _createClass(EpubCFI, [{
  986. key: "checkType",
  987. value: function checkType(cfi) {
  988. if (this.isCfiString(cfi)) {
  989. return "string";
  990. // Is a range object
  991. } else if (cfi && (typeof cfi === "undefined" ? "undefined" : _typeof(cfi)) === "object" && ((0, _core.type)(cfi) === "Range" || typeof cfi.startContainer != "undefined")) {
  992. return "range";
  993. } else if (cfi && (typeof cfi === "undefined" ? "undefined" : _typeof(cfi)) === "object" && typeof cfi.nodeType != "undefined") {
  994. // || typeof cfi === "function"
  995. return "node";
  996. } else if (cfi && (typeof cfi === "undefined" ? "undefined" : _typeof(cfi)) === "object" && cfi instanceof EpubCFI) {
  997. return "EpubCFI";
  998. } else {
  999. return false;
  1000. }
  1001. }
  1002. /**
  1003. * Parse a cfi string to a CFI object representation
  1004. * @param {string} cfiStr
  1005. * @returns {object} cfi
  1006. */
  1007. }, {
  1008. key: "parse",
  1009. value: function parse(cfiStr) {
  1010. var cfi = {
  1011. spinePos: -1,
  1012. range: false,
  1013. base: {},
  1014. path: {},
  1015. start: null,
  1016. end: null
  1017. };
  1018. var baseComponent, pathComponent, range;
  1019. if (typeof cfiStr !== "string") {
  1020. return { spinePos: -1 };
  1021. }
  1022. if (cfiStr.indexOf("epubcfi(") === 0 && cfiStr[cfiStr.length - 1] === ")") {
  1023. // Remove intial epubcfi( and ending )
  1024. cfiStr = cfiStr.slice(8, cfiStr.length - 1);
  1025. }
  1026. baseComponent = this.getChapterComponent(cfiStr);
  1027. // Make sure this is a valid cfi or return
  1028. if (!baseComponent) {
  1029. return { spinePos: -1 };
  1030. }
  1031. cfi.base = this.parseComponent(baseComponent);
  1032. pathComponent = this.getPathComponent(cfiStr);
  1033. cfi.path = this.parseComponent(pathComponent);
  1034. range = this.getRange(cfiStr);
  1035. if (range) {
  1036. cfi.range = true;
  1037. cfi.start = this.parseComponent(range[0]);
  1038. cfi.end = this.parseComponent(range[1]);
  1039. }
  1040. // Get spine node position
  1041. // cfi.spineSegment = cfi.base.steps[1];
  1042. // Chapter segment is always the second step
  1043. cfi.spinePos = cfi.base.steps[1].index;
  1044. return cfi;
  1045. }
  1046. }, {
  1047. key: "parseComponent",
  1048. value: function parseComponent(componentStr) {
  1049. var component = {
  1050. steps: [],
  1051. terminal: {
  1052. offset: null,
  1053. assertion: null
  1054. }
  1055. };
  1056. var parts = componentStr.split(":");
  1057. var steps = parts[0].split("/");
  1058. var terminal;
  1059. if (parts.length > 1) {
  1060. terminal = parts[1];
  1061. component.terminal = this.parseTerminal(terminal);
  1062. }
  1063. if (steps[0] === "") {
  1064. steps.shift(); // Ignore the first slash
  1065. }
  1066. component.steps = steps.map(function (step) {
  1067. return this.parseStep(step);
  1068. }.bind(this));
  1069. return component;
  1070. }
  1071. }, {
  1072. key: "parseStep",
  1073. value: function parseStep(stepStr) {
  1074. var type, num, index, has_brackets, id;
  1075. has_brackets = stepStr.match(/\[(.*)\]/);
  1076. if (has_brackets && has_brackets[1]) {
  1077. id = has_brackets[1];
  1078. }
  1079. //-- Check if step is a text node or element
  1080. num = parseInt(stepStr);
  1081. if (isNaN(num)) {
  1082. return;
  1083. }
  1084. if (num % 2 === 0) {
  1085. // Even = is an element
  1086. type = "element";
  1087. index = num / 2 - 1;
  1088. } else {
  1089. type = "text";
  1090. index = (num - 1) / 2;
  1091. }
  1092. return {
  1093. "type": type,
  1094. "index": index,
  1095. "id": id || null
  1096. };
  1097. }
  1098. }, {
  1099. key: "parseTerminal",
  1100. value: function parseTerminal(termialStr) {
  1101. var characterOffset, textLocationAssertion;
  1102. var assertion = termialStr.match(/\[(.*)\]/);
  1103. if (assertion && assertion[1]) {
  1104. characterOffset = parseInt(termialStr.split("[")[0]);
  1105. textLocationAssertion = assertion[1];
  1106. } else {
  1107. characterOffset = parseInt(termialStr);
  1108. }
  1109. if (!(0, _core.isNumber)(characterOffset)) {
  1110. characterOffset = null;
  1111. }
  1112. return {
  1113. "offset": characterOffset,
  1114. "assertion": textLocationAssertion
  1115. };
  1116. }
  1117. }, {
  1118. key: "getChapterComponent",
  1119. value: function getChapterComponent(cfiStr) {
  1120. var indirection = cfiStr.split("!");
  1121. return indirection[0];
  1122. }
  1123. }, {
  1124. key: "getPathComponent",
  1125. value: function getPathComponent(cfiStr) {
  1126. var indirection = cfiStr.split("!");
  1127. if (indirection[1]) {
  1128. var ranges = indirection[1].split(",");
  1129. return ranges[0];
  1130. }
  1131. }
  1132. }, {
  1133. key: "getRange",
  1134. value: function getRange(cfiStr) {
  1135. var ranges = cfiStr.split(",");
  1136. if (ranges.length === 3) {
  1137. return [ranges[1], ranges[2]];
  1138. }
  1139. return false;
  1140. }
  1141. }, {
  1142. key: "getCharecterOffsetComponent",
  1143. value: function getCharecterOffsetComponent(cfiStr) {
  1144. var splitStr = cfiStr.split(":");
  1145. return splitStr[1] || "";
  1146. }
  1147. }, {
  1148. key: "joinSteps",
  1149. value: function joinSteps(steps) {
  1150. if (!steps) {
  1151. return "";
  1152. }
  1153. return steps.map(function (part) {
  1154. var segment = "";
  1155. if (part.type === "element") {
  1156. segment += (part.index + 1) * 2;
  1157. }
  1158. if (part.type === "text") {
  1159. segment += 1 + 2 * part.index; // TODO: double check that this is odd
  1160. }
  1161. if (part.id) {
  1162. segment += "[" + part.id + "]";
  1163. }
  1164. return segment;
  1165. }).join("/");
  1166. }
  1167. }, {
  1168. key: "segmentString",
  1169. value: function segmentString(segment) {
  1170. var segmentString = "/";
  1171. segmentString += this.joinSteps(segment.steps);
  1172. if (segment.terminal && segment.terminal.offset != null) {
  1173. segmentString += ":" + segment.terminal.offset;
  1174. }
  1175. if (segment.terminal && segment.terminal.assertion != null) {
  1176. segmentString += "[" + segment.terminal.assertion + "]";
  1177. }
  1178. return segmentString;
  1179. }
  1180. /**
  1181. * Convert CFI to a epubcfi(...) string
  1182. * @returns {string} epubcfi
  1183. */
  1184. }, {
  1185. key: "toString",
  1186. value: function toString() {
  1187. var cfiString = "epubcfi(";
  1188. cfiString += this.segmentString(this.base);
  1189. cfiString += "!";
  1190. cfiString += this.segmentString(this.path);
  1191. // Add Range, if present
  1192. if (this.range && this.start) {
  1193. cfiString += ",";
  1194. cfiString += this.segmentString(this.start);
  1195. }
  1196. if (this.range && this.end) {
  1197. cfiString += ",";
  1198. cfiString += this.segmentString(this.end);
  1199. }
  1200. cfiString += ")";
  1201. return cfiString;
  1202. }
  1203. /**
  1204. * Compare which of two CFIs is earlier in the text
  1205. * @returns {number} First is earlier = -1, Second is earlier = 1, They are equal = 0
  1206. */
  1207. }, {
  1208. key: "compare",
  1209. value: function compare(cfiOne, cfiTwo) {
  1210. var stepsA, stepsB;
  1211. var terminalA, terminalB;
  1212. var rangeAStartSteps, rangeAEndSteps;
  1213. var rangeBEndSteps, rangeBEndSteps;
  1214. var rangeAStartTerminal, rangeAEndTerminal;
  1215. var rangeBStartTerminal, rangeBEndTerminal;
  1216. if (typeof cfiOne === "string") {
  1217. cfiOne = new EpubCFI(cfiOne);
  1218. }
  1219. if (typeof cfiTwo === "string") {
  1220. cfiTwo = new EpubCFI(cfiTwo);
  1221. }
  1222. // Compare Spine Positions
  1223. if (cfiOne.spinePos > cfiTwo.spinePos) {
  1224. return 1;
  1225. }
  1226. if (cfiOne.spinePos < cfiTwo.spinePos) {
  1227. return -1;
  1228. }
  1229. if (cfiOne.range) {
  1230. stepsA = cfiOne.path.steps.concat(cfiOne.start.steps);
  1231. terminalA = cfiOne.start.terminal;
  1232. } else {
  1233. stepsA = cfiOne.path.steps;
  1234. terminalA = cfiOne.path.terminal;
  1235. }
  1236. if (cfiTwo.range) {
  1237. stepsB = cfiTwo.path.steps.concat(cfiTwo.start.steps);
  1238. terminalB = cfiTwo.start.terminal;
  1239. } else {
  1240. stepsB = cfiTwo.path.steps;
  1241. terminalB = cfiTwo.path.terminal;
  1242. }
  1243. // Compare Each Step in the First item
  1244. for (var i = 0; i < stepsA.length; i++) {
  1245. if (!stepsA[i]) {
  1246. return -1;
  1247. }
  1248. if (!stepsB[i]) {
  1249. return 1;
  1250. }
  1251. if (stepsA[i].index > stepsB[i].index) {
  1252. return 1;
  1253. }
  1254. if (stepsA[i].index < stepsB[i].index) {
  1255. return -1;
  1256. }
  1257. // Otherwise continue checking
  1258. }
  1259. // All steps in First equal to Second and First is Less Specific
  1260. if (stepsA.length < stepsB.length) {
  1261. return 1;
  1262. }
  1263. // Compare the charecter offset of the text node
  1264. if (terminalA.offset > terminalB.offset) {
  1265. return 1;
  1266. }
  1267. if (terminalA.offset < terminalB.offset) {
  1268. return -1;
  1269. }
  1270. // CFI's are equal
  1271. return 0;
  1272. }
  1273. }, {
  1274. key: "step",
  1275. value: function step(node) {
  1276. var nodeType = node.nodeType === TEXT_NODE ? "text" : "element";
  1277. return {
  1278. "id": node.id,
  1279. "tagName": node.tagName,
  1280. "type": nodeType,
  1281. "index": this.position(node)
  1282. };
  1283. }
  1284. }, {
  1285. key: "filteredStep",
  1286. value: function filteredStep(node, ignoreClass) {
  1287. var filteredNode = this.filter(node, ignoreClass);
  1288. var nodeType;
  1289. // Node filtered, so ignore
  1290. if (!filteredNode) {
  1291. return;
  1292. }
  1293. // Otherwise add the filter node in
  1294. nodeType = filteredNode.nodeType === TEXT_NODE ? "text" : "element";
  1295. return {
  1296. "id": filteredNode.id,
  1297. "tagName": filteredNode.tagName,
  1298. "type": nodeType,
  1299. "index": this.filteredPosition(filteredNode, ignoreClass)
  1300. };
  1301. }
  1302. }, {
  1303. key: "pathTo",
  1304. value: function pathTo(node, offset, ignoreClass) {
  1305. var segment = {
  1306. steps: [],
  1307. terminal: {
  1308. offset: null,
  1309. assertion: null
  1310. }
  1311. };
  1312. var currentNode = node;
  1313. var step;
  1314. while (currentNode && currentNode.parentNode && currentNode.parentNode.nodeType != DOCUMENT_NODE) {
  1315. if (ignoreClass) {
  1316. step = this.filteredStep(currentNode, ignoreClass);
  1317. } else {
  1318. step = this.step(currentNode);
  1319. }
  1320. if (step) {
  1321. segment.steps.unshift(step);
  1322. }
  1323. currentNode = currentNode.parentNode;
  1324. }
  1325. if (offset != null && offset >= 0) {
  1326. segment.terminal.offset = offset;
  1327. // Make sure we are getting to a textNode if there is an offset
  1328. if (segment.steps[segment.steps.length - 1].type != "text") {
  1329. segment.steps.push({
  1330. "type": "text",
  1331. "index": 0
  1332. });
  1333. }
  1334. }
  1335. return segment;
  1336. }
  1337. }, {
  1338. key: "equalStep",
  1339. value: function equalStep(stepA, stepB) {
  1340. if (!stepA || !stepB) {
  1341. return false;
  1342. }
  1343. if (stepA.index === stepB.index && stepA.id === stepB.id && stepA.type === stepB.type) {
  1344. return true;
  1345. }
  1346. return false;
  1347. }
  1348. /**
  1349. * Create a CFI object from a Range
  1350. * @param {Range} range
  1351. * @param {string | object} base
  1352. * @param {string} [ignoreClass]
  1353. * @returns {object} cfi
  1354. */
  1355. }, {
  1356. key: "fromRange",
  1357. value: function fromRange(range, base, ignoreClass) {
  1358. var cfi = {
  1359. range: false,
  1360. base: {},
  1361. path: {},
  1362. start: null,
  1363. end: null
  1364. };
  1365. var start = range.startContainer;
  1366. var end = range.endContainer;
  1367. var startOffset = range.startOffset;
  1368. var endOffset = range.endOffset;
  1369. var needsIgnoring = false;
  1370. if (ignoreClass) {
  1371. // Tell pathTo if / what to ignore
  1372. needsIgnoring = start.ownerDocument.querySelector("." + ignoreClass) != null;
  1373. }
  1374. if (typeof base === "string") {
  1375. cfi.base = this.parseComponent(base);
  1376. cfi.spinePos = cfi.base.steps[1].index;
  1377. } else if ((typeof base === "undefined" ? "undefined" : _typeof(base)) === "object") {
  1378. cfi.base = base;
  1379. }
  1380. if (range.collapsed) {
  1381. if (needsIgnoring) {
  1382. startOffset = this.patchOffset(start, startOffset, ignoreClass);
  1383. }
  1384. cfi.path = this.pathTo(start, startOffset, ignoreClass);
  1385. } else {
  1386. cfi.range = true;
  1387. if (needsIgnoring) {
  1388. startOffset = this.patchOffset(start, startOffset, ignoreClass);
  1389. }
  1390. cfi.start = this.pathTo(start, startOffset, ignoreClass);
  1391. if (needsIgnoring) {
  1392. endOffset = this.patchOffset(end, endOffset, ignoreClass);
  1393. }
  1394. cfi.end = this.pathTo(end, endOffset, ignoreClass);
  1395. // Create a new empty path
  1396. cfi.path = {
  1397. steps: [],
  1398. terminal: null
  1399. };
  1400. // Push steps that are shared between start and end to the common path
  1401. var len = cfi.start.steps.length;
  1402. var i;
  1403. for (i = 0; i < len; i++) {
  1404. if (this.equalStep(cfi.start.steps[i], cfi.end.steps[i])) {
  1405. if (i === len - 1) {
  1406. // Last step is equal, check terminals
  1407. if (cfi.start.terminal === cfi.end.terminal) {
  1408. // CFI's are equal
  1409. cfi.path.steps.push(cfi.start.steps[i]);
  1410. // Not a range
  1411. cfi.range = false;
  1412. }
  1413. } else {
  1414. cfi.path.steps.push(cfi.start.steps[i]);
  1415. }
  1416. } else {
  1417. break;
  1418. }
  1419. }
  1420. cfi.start.steps = cfi.start.steps.slice(cfi.path.steps.length);
  1421. cfi.end.steps = cfi.end.steps.slice(cfi.path.steps.length);
  1422. // TODO: Add Sanity check to make sure that the end if greater than the start
  1423. }
  1424. return cfi;
  1425. }
  1426. /**
  1427. * Create a CFI object from a Node
  1428. * @param {Node} anchor
  1429. * @param {string | object} base
  1430. * @param {string} [ignoreClass]
  1431. * @returns {object} cfi
  1432. */
  1433. }, {
  1434. key: "fromNode",
  1435. value: function fromNode(anchor, base, ignoreClass) {
  1436. var cfi = {
  1437. range: false,
  1438. base: {},
  1439. path: {},
  1440. start: null,
  1441. end: null
  1442. };
  1443. if (typeof base === "string") {
  1444. cfi.base = this.parseComponent(base);
  1445. cfi.spinePos = cfi.base.steps[1].index;
  1446. } else if ((typeof base === "undefined" ? "undefined" : _typeof(base)) === "object") {
  1447. cfi.base = base;
  1448. }
  1449. cfi.path = this.pathTo(anchor, null, ignoreClass);
  1450. return cfi;
  1451. }
  1452. }, {
  1453. key: "filter",
  1454. value: function filter(anchor, ignoreClass) {
  1455. var needsIgnoring;
  1456. var sibling; // to join with
  1457. var parent, previousSibling, nextSibling;
  1458. var isText = false;
  1459. if (anchor.nodeType === TEXT_NODE) {
  1460. isText = true;
  1461. parent = anchor.parentNode;
  1462. needsIgnoring = anchor.parentNode.classList.contains(ignoreClass);
  1463. } else {
  1464. isText = false;
  1465. needsIgnoring = anchor.classList.contains(ignoreClass);
  1466. }
  1467. if (needsIgnoring && isText) {
  1468. previousSibling = parent.previousSibling;
  1469. nextSibling = parent.nextSibling;
  1470. // If the sibling is a text node, join the nodes
  1471. if (previousSibling && previousSibling.nodeType === TEXT_NODE) {
  1472. sibling = previousSibling;
  1473. } else if (nextSibling && nextSibling.nodeType === TEXT_NODE) {
  1474. sibling = nextSibling;
  1475. }
  1476. if (sibling) {
  1477. return sibling;
  1478. } else {
  1479. // Parent will be ignored on next step
  1480. return anchor;
  1481. }
  1482. } else if (needsIgnoring && !isText) {
  1483. // Otherwise just skip the element node
  1484. return false;
  1485. } else {
  1486. // No need to filter
  1487. return anchor;
  1488. }
  1489. }
  1490. }, {
  1491. key: "patchOffset",
  1492. value: function patchOffset(anchor, offset, ignoreClass) {
  1493. if (anchor.nodeType != TEXT_NODE) {
  1494. throw new Error("Anchor must be a text node");
  1495. }
  1496. var curr = anchor;
  1497. var totalOffset = offset;
  1498. // If the parent is a ignored node, get offset from it's start
  1499. if (anchor.parentNode.classList.contains(ignoreClass)) {
  1500. curr = anchor.parentNode;
  1501. }
  1502. while (curr.previousSibling) {
  1503. if (curr.previousSibling.nodeType === ELEMENT_NODE) {
  1504. // Originally a text node, so join
  1505. if (curr.previousSibling.classList.contains(ignoreClass)) {
  1506. totalOffset += curr.previousSibling.textContent.length;
  1507. } else {
  1508. break; // Normal node, dont join
  1509. }
  1510. } else {
  1511. // If the previous sibling is a text node, join the nodes
  1512. totalOffset += curr.previousSibling.textContent.length;
  1513. }
  1514. curr = curr.previousSibling;
  1515. }
  1516. return totalOffset;
  1517. }
  1518. }, {
  1519. key: "normalizedMap",
  1520. value: function normalizedMap(children, nodeType, ignoreClass) {
  1521. var output = {};
  1522. var prevIndex = -1;
  1523. var i,
  1524. len = children.length;
  1525. var currNodeType;
  1526. var prevNodeType;
  1527. for (i = 0; i < len; i++) {
  1528. currNodeType = children[i].nodeType;
  1529. // Check if needs ignoring
  1530. if (currNodeType === ELEMENT_NODE && children[i].classList.contains(ignoreClass)) {
  1531. currNodeType = TEXT_NODE;
  1532. }
  1533. if (i > 0 && currNodeType === TEXT_NODE && prevNodeType === TEXT_NODE) {
  1534. // join text nodes
  1535. output[i] = prevIndex;
  1536. } else if (nodeType === currNodeType) {
  1537. prevIndex = prevIndex + 1;
  1538. output[i] = prevIndex;
  1539. }
  1540. prevNodeType = currNodeType;
  1541. }
  1542. return output;
  1543. }
  1544. }, {
  1545. key: "position",
  1546. value: function position(anchor) {
  1547. var children, index;
  1548. if (anchor.nodeType === ELEMENT_NODE) {
  1549. children = anchor.parentNode.children;
  1550. if (!children) {
  1551. children = (0, _core.findChildren)(anchor.parentNode);
  1552. }
  1553. index = Array.prototype.indexOf.call(children, anchor);
  1554. } else {
  1555. children = this.textNodes(anchor.parentNode);
  1556. index = children.indexOf(anchor);
  1557. }
  1558. return index;
  1559. }
  1560. }, {
  1561. key: "filteredPosition",
  1562. value: function filteredPosition(anchor, ignoreClass) {
  1563. var children, index, map;
  1564. if (anchor.nodeType === ELEMENT_NODE) {
  1565. children = anchor.parentNode.children;
  1566. map = this.normalizedMap(children, ELEMENT_NODE, ignoreClass);
  1567. } else {
  1568. children = anchor.parentNode.childNodes;
  1569. // Inside an ignored node
  1570. if (anchor.parentNode.classList.contains(ignoreClass)) {
  1571. anchor = anchor.parentNode;
  1572. children = anchor.parentNode.childNodes;
  1573. }
  1574. map = this.normalizedMap(children, TEXT_NODE, ignoreClass);
  1575. }
  1576. index = Array.prototype.indexOf.call(children, anchor);
  1577. return map[index];
  1578. }
  1579. }, {
  1580. key: "stepsToXpath",
  1581. value: function stepsToXpath(steps) {
  1582. var xpath = [".", "*"];
  1583. steps.forEach(function (step) {
  1584. var position = step.index + 1;
  1585. if (step.id) {
  1586. xpath.push("*[position()=" + position + " and @id='" + step.id + "']");
  1587. } else if (step.type === "text") {
  1588. xpath.push("text()[" + position + "]");
  1589. } else {
  1590. xpath.push("*[" + position + "]");
  1591. }
  1592. });
  1593. return xpath.join("/");
  1594. }
  1595. /*
  1596. To get the last step if needed:
  1597. // Get the terminal step
  1598. lastStep = steps[steps.length-1];
  1599. // Get the query string
  1600. query = this.stepsToQuery(steps);
  1601. // Find the containing element
  1602. startContainerParent = doc.querySelector(query);
  1603. // Find the text node within that element
  1604. if(startContainerParent && lastStep.type == "text") {
  1605. container = startContainerParent.childNodes[lastStep.index];
  1606. }
  1607. */
  1608. }, {
  1609. key: "stepsToQuerySelector",
  1610. value: function stepsToQuerySelector(steps) {
  1611. var query = ["html"];
  1612. steps.forEach(function (step) {
  1613. var position = step.index + 1;
  1614. if (step.id) {
  1615. query.push("#" + step.id);
  1616. } else if (step.type === "text") {
  1617. // unsupported in querySelector
  1618. // query.push("text()[" + position + "]");
  1619. } else {
  1620. query.push("*:nth-child(" + position + ")");
  1621. }
  1622. });
  1623. return query.join(">");
  1624. }
  1625. }, {
  1626. key: "textNodes",
  1627. value: function textNodes(container, ignoreClass) {
  1628. return Array.prototype.slice.call(container.childNodes).filter(function (node) {
  1629. if (node.nodeType === TEXT_NODE) {
  1630. return true;
  1631. } else if (ignoreClass && node.classList.contains(ignoreClass)) {
  1632. return true;
  1633. }
  1634. return false;
  1635. });
  1636. }
  1637. }, {
  1638. key: "walkToNode",
  1639. value: function walkToNode(steps, _doc, ignoreClass) {
  1640. var doc = _doc || document;
  1641. var container = doc.documentElement;
  1642. var children;
  1643. var step;
  1644. var len = steps.length;
  1645. var i;
  1646. for (i = 0; i < len; i++) {
  1647. step = steps[i];
  1648. if (step.type === "element") {
  1649. //better to get a container using id as some times step.index may not be correct
  1650. //For ex.https://github.com/futurepress/epub.js/issues/561
  1651. if (step.id) {
  1652. container = doc.getElementById(step.id);
  1653. } else {
  1654. children = container.children || (0, _core.findChildren)(container);
  1655. container = children[step.index];
  1656. }
  1657. } else if (step.type === "text") {
  1658. container = this.textNodes(container, ignoreClass)[step.index];
  1659. }
  1660. if (!container) {
  1661. //Break the for loop as due to incorrect index we can get error if
  1662. //container is undefined so that other functionailties works fine
  1663. //like navigation
  1664. break;
  1665. }
  1666. }
  1667. return container;
  1668. }
  1669. }, {
  1670. key: "findNode",
  1671. value: function findNode(steps, _doc, ignoreClass) {
  1672. var doc = _doc || document;
  1673. var container;
  1674. var xpath;
  1675. if (!ignoreClass && typeof doc.evaluate != "undefined") {
  1676. xpath = this.stepsToXpath(steps);
  1677. container = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  1678. } else if (ignoreClass) {
  1679. container = this.walkToNode(steps, doc, ignoreClass);
  1680. } else {
  1681. container = this.walkToNode(steps, doc);
  1682. }
  1683. return container;
  1684. }
  1685. }, {
  1686. key: "fixMiss",
  1687. value: function fixMiss(steps, offset, _doc, ignoreClass) {
  1688. var container = this.findNode(steps.slice(0, -1), _doc, ignoreClass);
  1689. var children = container.childNodes;
  1690. var map = this.normalizedMap(children, TEXT_NODE, ignoreClass);
  1691. var child;
  1692. var len;
  1693. var lastStepIndex = steps[steps.length - 1].index;
  1694. for (var childIndex in map) {
  1695. if (!map.hasOwnProperty(childIndex)) return;
  1696. if (map[childIndex] === lastStepIndex) {
  1697. child = children[childIndex];
  1698. len = child.textContent.length;
  1699. if (offset > len) {
  1700. offset = offset - len;
  1701. } else {
  1702. if (child.nodeType === ELEMENT_NODE) {
  1703. container = child.childNodes[0];
  1704. } else {
  1705. container = child;
  1706. }
  1707. break;
  1708. }
  1709. }
  1710. }
  1711. return {
  1712. container: container,
  1713. offset: offset
  1714. };
  1715. }
  1716. /**
  1717. * Creates a DOM range representing a CFI
  1718. * @param {document} _doc document referenced in the base
  1719. * @param {string} [ignoreClass]
  1720. * @return {Range}
  1721. */
  1722. }, {
  1723. key: "toRange",
  1724. value: function toRange(_doc, ignoreClass) {
  1725. var doc = _doc || document;
  1726. var range;
  1727. var start, end, startContainer, endContainer;
  1728. var cfi = this;
  1729. var startSteps, endSteps;
  1730. var needsIgnoring = ignoreClass ? doc.querySelector("." + ignoreClass) != null : false;
  1731. var missed;
  1732. if (typeof doc.createRange !== "undefined") {
  1733. range = doc.createRange();
  1734. } else {
  1735. range = new _core.RangeObject();
  1736. }
  1737. if (cfi.range) {
  1738. start = cfi.start;
  1739. startSteps = cfi.path.steps.concat(start.steps);
  1740. startContainer = this.findNode(startSteps, doc, needsIgnoring ? ignoreClass : null);
  1741. end = cfi.end;
  1742. endSteps = cfi.path.steps.concat(end.steps);
  1743. endContainer = this.findNode(endSteps, doc, needsIgnoring ? ignoreClass : null);
  1744. } else {
  1745. start = cfi.path;
  1746. startSteps = cfi.path.steps;
  1747. startContainer = this.findNode(cfi.path.steps, doc, needsIgnoring ? ignoreClass : null);
  1748. }
  1749. if (startContainer) {
  1750. try {
  1751. if (start.terminal.offset != null) {
  1752. range.setStart(startContainer, start.terminal.offset);
  1753. } else {
  1754. range.setStart(startContainer, 0);
  1755. }
  1756. } catch (e) {
  1757. missed = this.fixMiss(startSteps, start.terminal.offset, doc, needsIgnoring ? ignoreClass : null);
  1758. range.setStart(missed.container, missed.offset);
  1759. }
  1760. } else {
  1761. console.log("No startContainer found for", this.toString());
  1762. // No start found
  1763. return null;
  1764. }
  1765. if (endContainer) {
  1766. try {
  1767. if (end.terminal.offset != null) {
  1768. range.setEnd(endContainer, end.terminal.offset);
  1769. } else {
  1770. range.setEnd(endContainer, 0);
  1771. }
  1772. } catch (e) {
  1773. missed = this.fixMiss(endSteps, cfi.end.terminal.offset, doc, needsIgnoring ? ignoreClass : null);
  1774. range.setEnd(missed.container, missed.offset);
  1775. }
  1776. }
  1777. // doc.defaultView.getSelection().addRange(range);
  1778. return range;
  1779. }
  1780. /**
  1781. * Check if a string is wrapped with "epubcfi()"
  1782. * @param {string} str
  1783. * @returns {boolean}
  1784. */
  1785. }, {
  1786. key: "isCfiString",
  1787. value: function isCfiString(str) {
  1788. if (typeof str === "string" && str.indexOf("epubcfi(") === 0 && str[str.length - 1] === ")") {
  1789. return true;
  1790. }
  1791. return false;
  1792. }
  1793. }, {
  1794. key: "generateChapterComponent",
  1795. value: function generateChapterComponent(_spineNodeIndex, _pos, id) {
  1796. var pos = parseInt(_pos),
  1797. spineNodeIndex = (_spineNodeIndex + 1) * 2,
  1798. cfi = "/" + spineNodeIndex + "/";
  1799. cfi += (pos + 1) * 2;
  1800. if (id) {
  1801. cfi += "[" + id + "]";
  1802. }
  1803. return cfi;
  1804. }
  1805. /**
  1806. * Collapse a CFI Range to a single CFI Position
  1807. * @param {boolean} [toStart=false]
  1808. */
  1809. }, {
  1810. key: "collapse",
  1811. value: function collapse(toStart) {
  1812. if (!this.range) {
  1813. return;
  1814. }
  1815. this.range = false;
  1816. if (toStart) {
  1817. this.path.steps = this.path.steps.concat(this.start.steps);
  1818. this.path.terminal = this.start.terminal;
  1819. } else {
  1820. this.path.steps = this.path.steps.concat(this.end.steps);
  1821. this.path.terminal = this.end.terminal;
  1822. }
  1823. }
  1824. }]);
  1825. return EpubCFI;
  1826. }();
  1827. exports.default = EpubCFI;
  1828. module.exports = exports["default"];
  1829. /***/ }),
  1830. /* 2 */
  1831. /***/ (function(module, exports, __webpack_require__) {
  1832. "use strict";
  1833. Object.defineProperty(exports, "__esModule", {
  1834. value: true
  1835. });
  1836. var EPUBJS_VERSION = exports.EPUBJS_VERSION = "0.3";
  1837. // Dom events to listen for
  1838. var DOM_EVENTS = exports.DOM_EVENTS = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click", "touchend", "touchstart"];
  1839. var EVENTS = exports.EVENTS = {
  1840. BOOK: {
  1841. OPEN_FAILED: "openFailed"
  1842. },
  1843. CONTENTS: {
  1844. EXPAND: "expand",
  1845. RESIZE: "resize",
  1846. SELECTED: "selected",
  1847. SELECTED_RANGE: "selectedRange",
  1848. LINK_CLICKED: "linkClicked"
  1849. },
  1850. LOCATIONS: {
  1851. CHANGED: "changed"
  1852. },
  1853. MANAGERS: {
  1854. RESIZE: "resize",
  1855. RESIZED: "resized",
  1856. ORIENTATION_CHANGE: "orientationchange",
  1857. ADDED: "added",
  1858. SCROLL: "scroll",
  1859. SCROLLED: "scrolled",
  1860. REMOVED: "removed"
  1861. },
  1862. VIEWS: {
  1863. AXIS: "axis",
  1864. LOAD_ERROR: "loaderror",
  1865. RENDERED: "rendered",
  1866. RESIZED: "resized",
  1867. DISPLAYED: "displayed",
  1868. SHOWN: "shown",
  1869. HIDDEN: "hidden",
  1870. MARK_CLICKED: "markClicked"
  1871. },
  1872. RENDITION: {
  1873. STARTED: "started",
  1874. ATTACHED: "attached",
  1875. DISPLAYED: "displayed",
  1876. DISPLAY_ERROR: "displayerror",
  1877. RENDERED: "rendered",
  1878. REMOVED: "removed",
  1879. RESIZED: "resized",
  1880. ORIENTATION_CHANGE: "orientationchange",
  1881. LOCATION_CHANGED: "locationChanged",
  1882. RELOCATED: "relocated",
  1883. MARK_CLICKED: "markClicked",
  1884. SELECTED: "selected",
  1885. LAYOUT: "layout"
  1886. },
  1887. LAYOUT: {
  1888. UPDATED: "updated"
  1889. }
  1890. };
  1891. /***/ }),
  1892. /* 3 */
  1893. /***/ (function(module, exports, __webpack_require__) {
  1894. "use strict";
  1895. var d = __webpack_require__(27)
  1896. , callable = __webpack_require__(41)
  1897. , apply = Function.prototype.apply, call = Function.prototype.call
  1898. , create = Object.create, defineProperty = Object.defineProperty
  1899. , defineProperties = Object.defineProperties
  1900. , hasOwnProperty = Object.prototype.hasOwnProperty
  1901. , descriptor = { configurable: true, enumerable: false, writable: true }
  1902. , on, once, off, emit, methods, descriptors, base;
  1903. on = function (type, listener) {
  1904. var data;
  1905. callable(listener);
  1906. if (!hasOwnProperty.call(this, '__ee__')) {
  1907. data = descriptor.value = create(null);
  1908. defineProperty(this, '__ee__', descriptor);
  1909. descriptor.value = null;
  1910. } else {
  1911. data = this.__ee__;
  1912. }
  1913. if (!data[type]) data[type] = listener;
  1914. else if (typeof data[type] === 'object') data[type].push(listener);
  1915. else data[type] = [data[type], listener];
  1916. return this;
  1917. };
  1918. once = function (type, listener) {
  1919. var once, self;
  1920. callable(listener);
  1921. self = this;
  1922. on.call(this, type, once = function () {
  1923. off.call(self, type, once);
  1924. apply.call(listener, this, arguments);
  1925. });
  1926. once.__eeOnceListener__ = listener;
  1927. return this;
  1928. };
  1929. off = function (type, listener) {
  1930. var data, listeners, candidate, i;
  1931. callable(listener);
  1932. if (!hasOwnProperty.call(this, '__ee__')) return this;
  1933. data = this.__ee__;
  1934. if (!data[type]) return this;
  1935. listeners = data[type];
  1936. if (typeof listeners === 'object') {
  1937. for (i = 0; (candidate = listeners[i]); ++i) {
  1938. if ((candidate === listener) ||
  1939. (candidate.__eeOnceListener__ === listener)) {
  1940. if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
  1941. else listeners.splice(i, 1);
  1942. }
  1943. }
  1944. } else {
  1945. if ((listeners === listener) ||
  1946. (listeners.__eeOnceListener__ === listener)) {
  1947. delete data[type];
  1948. }
  1949. }
  1950. return this;
  1951. };
  1952. emit = function (type) {
  1953. var i, l, listener, listeners, args;
  1954. if (!hasOwnProperty.call(this, '__ee__')) return;
  1955. listeners = this.__ee__[type];
  1956. if (!listeners) return;
  1957. if (typeof listeners === 'object') {
  1958. l = arguments.length;
  1959. args = new Array(l - 1);
  1960. for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
  1961. listeners = listeners.slice();
  1962. for (i = 0; (listener = listeners[i]); ++i) {
  1963. apply.call(listener, this, args);
  1964. }
  1965. } else {
  1966. switch (arguments.length) {
  1967. case 1:
  1968. call.call(listeners, this);
  1969. break;
  1970. case 2:
  1971. call.call(listeners, this, arguments[1]);
  1972. break;
  1973. case 3:
  1974. call.call(listeners, this, arguments[1], arguments[2]);
  1975. break;
  1976. default:
  1977. l = arguments.length;
  1978. args = new Array(l - 1);
  1979. for (i = 1; i < l; ++i) {
  1980. args[i - 1] = arguments[i];
  1981. }
  1982. apply.call(listeners, this, args);
  1983. }
  1984. }
  1985. };
  1986. methods = {
  1987. on: on,
  1988. once: once,
  1989. off: off,
  1990. emit: emit
  1991. };
  1992. descriptors = {
  1993. on: d(on),
  1994. once: d(once),
  1995. off: d(off),
  1996. emit: d(emit)
  1997. };
  1998. base = defineProperties({}, descriptors);
  1999. module.exports = exports = function (o) {
  2000. return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
  2001. };
  2002. exports.methods = methods;
  2003. /***/ }),
  2004. /* 4 */
  2005. /***/ (function(module, exports, __webpack_require__) {
  2006. "use strict";
  2007. Object.defineProperty(exports, "__esModule", {
  2008. value: true
  2009. });
  2010. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  2011. var _pathWebpack = __webpack_require__(6);
  2012. var _pathWebpack2 = _interopRequireDefault(_pathWebpack);
  2013. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2014. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2015. /**
  2016. * Creates a Path object for parsing and manipulation of a path strings
  2017. *
  2018. * Uses a polyfill for Nodejs path: https://nodejs.org/api/path.html
  2019. * @param {string} pathString a url string (relative or absolute)
  2020. * @class
  2021. */
  2022. var Path = function () {
  2023. function Path(pathString) {
  2024. _classCallCheck(this, Path);
  2025. var protocol;
  2026. var parsed;
  2027. protocol = pathString.indexOf("://");
  2028. if (protocol > -1) {
  2029. pathString = new URL(pathString).pathname;
  2030. }
  2031. parsed = this.parse(pathString);
  2032. this.path = pathString;
  2033. if (this.isDirectory(pathString)) {
  2034. this.directory = pathString;
  2035. } else {
  2036. this.directory = parsed.dir + "/";
  2037. }
  2038. this.filename = parsed.base;
  2039. this.extension = parsed.ext.slice(1);
  2040. }
  2041. /**
  2042. * Parse the path: https://nodejs.org/api/path.html#path_path_parse_path
  2043. * @param {string} what
  2044. * @returns {object}
  2045. */
  2046. _createClass(Path, [{
  2047. key: "parse",
  2048. value: function parse(what) {
  2049. return _pathWebpack2.default.parse(what);
  2050. }
  2051. /**
  2052. * @param {string} what
  2053. * @returns {boolean}
  2054. */
  2055. }, {
  2056. key: "isAbsolute",
  2057. value: function isAbsolute(what) {
  2058. return _pathWebpack2.default.isAbsolute(what || this.path);
  2059. }
  2060. /**
  2061. * Check if path ends with a directory
  2062. * @param {string} what
  2063. * @returns {boolean}
  2064. */
  2065. }, {
  2066. key: "isDirectory",
  2067. value: function isDirectory(what) {
  2068. return what.charAt(what.length - 1) === "/";
  2069. }
  2070. /**
  2071. * Resolve a path against the directory of the Path
  2072. *
  2073. * https://nodejs.org/api/path.html#path_path_resolve_paths
  2074. * @param {string} what
  2075. * @returns {string} resolved
  2076. */
  2077. }, {
  2078. key: "resolve",
  2079. value: function resolve(what) {
  2080. return _pathWebpack2.default.resolve(this.directory, what);
  2081. }
  2082. /**
  2083. * Resolve a path relative to the directory of the Path
  2084. *
  2085. * https://nodejs.org/api/path.html#path_path_relative_from_to
  2086. * @param {string} what
  2087. * @returns {string} relative
  2088. */
  2089. }, {
  2090. key: "relative",
  2091. value: function relative(what) {
  2092. return _pathWebpack2.default.relative(this.directory, what);
  2093. }
  2094. }, {
  2095. key: "splitPath",
  2096. value: function splitPath(filename) {
  2097. return this.splitPathRe.exec(filename).slice(1);
  2098. }
  2099. /**
  2100. * Return the path string
  2101. * @returns {string} path
  2102. */
  2103. }, {
  2104. key: "toString",
  2105. value: function toString() {
  2106. return this.path;
  2107. }
  2108. }]);
  2109. return Path;
  2110. }();
  2111. exports.default = Path;
  2112. module.exports = exports["default"];
  2113. /***/ }),
  2114. /* 5 */
  2115. /***/ (function(module, exports, __webpack_require__) {
  2116. "use strict";
  2117. Object.defineProperty(exports, "__esModule", {
  2118. value: true
  2119. });
  2120. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  2121. var _path = __webpack_require__(4);
  2122. var _path2 = _interopRequireDefault(_path);
  2123. var _pathWebpack = __webpack_require__(6);
  2124. var _pathWebpack2 = _interopRequireDefault(_pathWebpack);
  2125. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2126. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2127. /**
  2128. * creates a Url object for parsing and manipulation of a url string
  2129. * @param {string} urlString a url string (relative or absolute)
  2130. * @param {string} [baseString] optional base for the url,
  2131. * default to window.location.href
  2132. */
  2133. var Url = function () {
  2134. function Url(urlString, baseString) {
  2135. _classCallCheck(this, Url);
  2136. var absolute = urlString.indexOf("://") > -1;
  2137. var pathname = urlString;
  2138. var basePath;
  2139. this.Url = undefined;
  2140. this.href = urlString;
  2141. this.protocol = "";
  2142. this.origin = "";
  2143. this.hash = "";
  2144. this.hash = "";
  2145. this.search = "";
  2146. this.base = baseString;
  2147. if (!absolute && baseString !== false && typeof baseString !== "string" && window && window.location) {
  2148. this.base = window.location.href;
  2149. }
  2150. // URL Polyfill doesn't throw an error if base is empty
  2151. if (absolute || this.base) {
  2152. try {
  2153. if (this.base) {
  2154. // Safari doesn't like an undefined base
  2155. this.Url = new URL(urlString, this.base);
  2156. } else {
  2157. this.Url = new URL(urlString);
  2158. }
  2159. this.href = this.Url.href;
  2160. this.protocol = this.Url.protocol;
  2161. this.origin = this.Url.origin;
  2162. this.hash = this.Url.hash;
  2163. this.search = this.Url.search;
  2164. pathname = this.Url.pathname;
  2165. } catch (e) {
  2166. // Skip URL parsing
  2167. this.Url = undefined;
  2168. // resolve the pathname from the base
  2169. if (this.base) {
  2170. basePath = new _path2.default(this.base);
  2171. pathname = basePath.resolve(pathname);
  2172. }
  2173. }
  2174. }
  2175. this.Path = new _path2.default(pathname);
  2176. this.directory = this.Path.directory;
  2177. this.filename = this.Path.filename;
  2178. this.extension = this.Path.extension;
  2179. }
  2180. /**
  2181. * @returns {Path}
  2182. */
  2183. _createClass(Url, [{
  2184. key: "path",
  2185. value: function path() {
  2186. return this.Path;
  2187. }
  2188. /**
  2189. * Resolves a relative path to a absolute url
  2190. * @param {string} what
  2191. * @returns {string} url
  2192. */
  2193. }, {
  2194. key: "resolve",
  2195. value: function resolve(what) {
  2196. var isAbsolute = what.indexOf("://") > -1;
  2197. var fullpath;
  2198. if (isAbsolute) {
  2199. return what;
  2200. }
  2201. fullpath = _pathWebpack2.default.resolve(this.directory, what);
  2202. return this.origin + fullpath;
  2203. }
  2204. /**
  2205. * Resolve a path relative to the url
  2206. * @param {string} what
  2207. * @returns {string} path
  2208. */
  2209. }, {
  2210. key: "relative",
  2211. value: function relative(what) {
  2212. return _pathWebpack2.default.relative(what, this.directory);
  2213. }
  2214. /**
  2215. * @returns {string}
  2216. */
  2217. }, {
  2218. key: "toString",
  2219. value: function toString() {
  2220. return this.href;
  2221. }
  2222. }]);
  2223. return Url;
  2224. }();
  2225. exports.default = Url;
  2226. module.exports = exports["default"];
  2227. /***/ }),
  2228. /* 6 */
  2229. /***/ (function(module, exports, __webpack_require__) {
  2230. "use strict";
  2231. if (!process) {
  2232. var process = {
  2233. "cwd" : function () { return '/' }
  2234. };
  2235. }
  2236. function assertPath(path) {
  2237. if (typeof path !== 'string') {
  2238. throw new TypeError('Path must be a string. Received ' + path);
  2239. }
  2240. }
  2241. // Resolves . and .. elements in a path with directory names
  2242. function normalizeStringPosix(path, allowAboveRoot) {
  2243. var res = '';
  2244. var lastSlash = -1;
  2245. var dots = 0;
  2246. var code;
  2247. for (var i = 0; i <= path.length; ++i) {
  2248. if (i < path.length)
  2249. code = path.charCodeAt(i);
  2250. else if (code === 47/*/*/)
  2251. break;
  2252. else
  2253. code = 47/*/*/;
  2254. if (code === 47/*/*/) {
  2255. if (lastSlash === i - 1 || dots === 1) {
  2256. // NOOP
  2257. } else if (lastSlash !== i - 1 && dots === 2) {
  2258. if (res.length < 2 ||
  2259. res.charCodeAt(res.length - 1) !== 46/*.*/ ||
  2260. res.charCodeAt(res.length - 2) !== 46/*.*/) {
  2261. if (res.length > 2) {
  2262. var start = res.length - 1;
  2263. var j = start;
  2264. for (; j >= 0; --j) {
  2265. if (res.charCodeAt(j) === 47/*/*/)
  2266. break;
  2267. }
  2268. if (j !== start) {
  2269. if (j === -1)
  2270. res = '';
  2271. else
  2272. res = res.slice(0, j);
  2273. lastSlash = i;
  2274. dots = 0;
  2275. continue;
  2276. }
  2277. } else if (res.length === 2 || res.length === 1) {
  2278. res = '';
  2279. lastSlash = i;
  2280. dots = 0;
  2281. continue;
  2282. }
  2283. }
  2284. if (allowAboveRoot) {
  2285. if (res.length > 0)
  2286. res += '/..';
  2287. else
  2288. res = '..';
  2289. }
  2290. } else {
  2291. if (res.length > 0)
  2292. res += '/' + path.slice(lastSlash + 1, i);
  2293. else
  2294. res = path.slice(lastSlash + 1, i);
  2295. }
  2296. lastSlash = i;
  2297. dots = 0;
  2298. } else if (code === 46/*.*/ && dots !== -1) {
  2299. ++dots;
  2300. } else {
  2301. dots = -1;
  2302. }
  2303. }
  2304. return res;
  2305. }
  2306. function _format(sep, pathObject) {
  2307. var dir = pathObject.dir || pathObject.root;
  2308. var base = pathObject.base ||
  2309. ((pathObject.name || '') + (pathObject.ext || ''));
  2310. if (!dir) {
  2311. return base;
  2312. }
  2313. if (dir === pathObject.root) {
  2314. return dir + base;
  2315. }
  2316. return dir + sep + base;
  2317. }
  2318. var posix = {
  2319. // path.resolve([from ...], to)
  2320. resolve: function resolve() {
  2321. var resolvedPath = '';
  2322. var resolvedAbsolute = false;
  2323. var cwd;
  2324. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  2325. var path;
  2326. if (i >= 0)
  2327. path = arguments[i];
  2328. else {
  2329. if (cwd === undefined)
  2330. cwd = process.cwd();
  2331. path = cwd;
  2332. }
  2333. assertPath(path);
  2334. // Skip empty entries
  2335. if (path.length === 0) {
  2336. continue;
  2337. }
  2338. resolvedPath = path + '/' + resolvedPath;
  2339. resolvedAbsolute = path.charCodeAt(0) === 47/*/*/;
  2340. }
  2341. // At this point the path should be resolved to a full absolute path, but
  2342. // handle relative paths to be safe (might happen when process.cwd() fails)
  2343. // Normalize the path
  2344. resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
  2345. if (resolvedAbsolute) {
  2346. if (resolvedPath.length > 0)
  2347. return '/' + resolvedPath;
  2348. else
  2349. return '/';
  2350. } else if (resolvedPath.length > 0) {
  2351. return resolvedPath;
  2352. } else {
  2353. return '.';
  2354. }
  2355. },
  2356. normalize: function normalize(path) {
  2357. assertPath(path);
  2358. if (path.length === 0)
  2359. return '.';
  2360. var isAbsolute = path.charCodeAt(0) === 47/*/*/;
  2361. var trailingSeparator = path.charCodeAt(path.length - 1) === 47/*/*/;
  2362. // Normalize the path
  2363. path = normalizeStringPosix(path, !isAbsolute);
  2364. if (path.length === 0 && !isAbsolute)
  2365. path = '.';
  2366. if (path.length > 0 && trailingSeparator)
  2367. path += '/';
  2368. if (isAbsolute)
  2369. return '/' + path;
  2370. return path;
  2371. },
  2372. isAbsolute: function isAbsolute(path) {
  2373. assertPath(path);
  2374. return path.length > 0 && path.charCodeAt(0) === 47/*/*/;
  2375. },
  2376. join: function join() {
  2377. if (arguments.length === 0)
  2378. return '.';
  2379. var joined;
  2380. for (var i = 0; i < arguments.length; ++i) {
  2381. var arg = arguments[i];
  2382. assertPath(arg);
  2383. if (arg.length > 0) {
  2384. if (joined === undefined)
  2385. joined = arg;
  2386. else
  2387. joined += '/' + arg;
  2388. }
  2389. }
  2390. if (joined === undefined)
  2391. return '.';
  2392. return posix.normalize(joined);
  2393. },
  2394. relative: function relative(from, to) {
  2395. assertPath(from);
  2396. assertPath(to);
  2397. if (from === to)
  2398. return '';
  2399. from = posix.resolve(from);
  2400. to = posix.resolve(to);
  2401. if (from === to)
  2402. return '';
  2403. // Trim any leading backslashes
  2404. var fromStart = 1;
  2405. for (; fromStart < from.length; ++fromStart) {
  2406. if (from.charCodeAt(fromStart) !== 47/*/*/)
  2407. break;
  2408. }
  2409. var fromEnd = from.length;
  2410. var fromLen = (fromEnd - fromStart);
  2411. // Trim any leading backslashes
  2412. var toStart = 1;
  2413. for (; toStart < to.length; ++toStart) {
  2414. if (to.charCodeAt(toStart) !== 47/*/*/)
  2415. break;
  2416. }
  2417. var toEnd = to.length;
  2418. var toLen = (toEnd - toStart);
  2419. // Compare paths to find the longest common path from root
  2420. var length = (fromLen < toLen ? fromLen : toLen);
  2421. var lastCommonSep = -1;
  2422. var i = 0;
  2423. for (; i <= length; ++i) {
  2424. if (i === length) {
  2425. if (toLen > length) {
  2426. if (to.charCodeAt(toStart + i) === 47/*/*/) {
  2427. // We get here if `from` is the exact base path for `to`.
  2428. // For example: from='/foo/bar'; to='/foo/bar/baz'
  2429. return to.slice(toStart + i + 1);
  2430. } else if (i === 0) {
  2431. // We get here if `from` is the root
  2432. // For example: from='/'; to='/foo'
  2433. return to.slice(toStart + i);
  2434. }
  2435. } else if (fromLen > length) {
  2436. if (from.charCodeAt(fromStart + i) === 47/*/*/) {
  2437. // We get here if `to` is the exact base path for `from`.
  2438. // For example: from='/foo/bar/baz'; to='/foo/bar'
  2439. lastCommonSep = i;
  2440. } else if (i === 0) {
  2441. // We get here if `to` is the root.
  2442. // For example: from='/foo'; to='/'
  2443. lastCommonSep = 0;
  2444. }
  2445. }
  2446. break;
  2447. }
  2448. var fromCode = from.charCodeAt(fromStart + i);
  2449. var toCode = to.charCodeAt(toStart + i);
  2450. if (fromCode !== toCode)
  2451. break;
  2452. else if (fromCode === 47/*/*/)
  2453. lastCommonSep = i;
  2454. }
  2455. var out = '';
  2456. // Generate the relative path based on the path difference between `to`
  2457. // and `from`
  2458. for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
  2459. if (i === fromEnd || from.charCodeAt(i) === 47/*/*/) {
  2460. if (out.length === 0)
  2461. out += '..';
  2462. else
  2463. out += '/..';
  2464. }
  2465. }
  2466. // Lastly, append the rest of the destination (`to`) path that comes after
  2467. // the common path parts
  2468. if (out.length > 0)
  2469. return out + to.slice(toStart + lastCommonSep);
  2470. else {
  2471. toStart += lastCommonSep;
  2472. if (to.charCodeAt(toStart) === 47/*/*/)
  2473. ++toStart;
  2474. return to.slice(toStart);
  2475. }
  2476. },
  2477. _makeLong: function _makeLong(path) {
  2478. return path;
  2479. },
  2480. dirname: function dirname(path) {
  2481. assertPath(path);
  2482. if (path.length === 0)
  2483. return '.';
  2484. var code = path.charCodeAt(0);
  2485. var hasRoot = (code === 47/*/*/);
  2486. var end = -1;
  2487. var matchedSlash = true;
  2488. for (var i = path.length - 1; i >= 1; --i) {
  2489. code = path.charCodeAt(i);
  2490. if (code === 47/*/*/) {
  2491. if (!matchedSlash) {
  2492. end = i;
  2493. break;
  2494. }
  2495. } else {
  2496. // We saw the first non-path separator
  2497. matchedSlash = false;
  2498. }
  2499. }
  2500. if (end === -1)
  2501. return hasRoot ? '/' : '.';
  2502. if (hasRoot && end === 1)
  2503. return '//';
  2504. return path.slice(0, end);
  2505. },
  2506. basename: function basename(path, ext) {
  2507. if (ext !== undefined && typeof ext !== 'string')
  2508. throw new TypeError('"ext" argument must be a string');
  2509. assertPath(path);
  2510. var start = 0;
  2511. var end = -1;
  2512. var matchedSlash = true;
  2513. var i;
  2514. if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
  2515. if (ext.length === path.length && ext === path)
  2516. return '';
  2517. var extIdx = ext.length - 1;
  2518. var firstNonSlashEnd = -1;
  2519. for (i = path.length - 1; i >= 0; --i) {
  2520. var code = path.charCodeAt(i);
  2521. if (code === 47/*/*/) {
  2522. // If we reached a path separator that was not part of a set of path
  2523. // separators at the end of the string, stop now
  2524. if (!matchedSlash) {
  2525. start = i + 1;
  2526. break;
  2527. }
  2528. } else {
  2529. if (firstNonSlashEnd === -1) {
  2530. // We saw the first non-path separator, remember this index in case
  2531. // we need it if the extension ends up not matching
  2532. matchedSlash = false;
  2533. firstNonSlashEnd = i + 1;
  2534. }
  2535. if (extIdx >= 0) {
  2536. // Try to match the explicit extension
  2537. if (code === ext.charCodeAt(extIdx)) {
  2538. if (--extIdx === -1) {
  2539. // We matched the extension, so mark this as the end of our path
  2540. // component
  2541. end = i;
  2542. }
  2543. } else {
  2544. // Extension does not match, so our result is the entire path
  2545. // component
  2546. extIdx = -1;
  2547. end = firstNonSlashEnd;
  2548. }
  2549. }
  2550. }
  2551. }
  2552. if (start === end)
  2553. end = firstNonSlashEnd;
  2554. else if (end === -1)
  2555. end = path.length;
  2556. return path.slice(start, end);
  2557. } else {
  2558. for (i = path.length - 1; i >= 0; --i) {
  2559. if (path.charCodeAt(i) === 47/*/*/) {
  2560. // If we reached a path separator that was not part of a set of path
  2561. // separators at the end of the string, stop now
  2562. if (!matchedSlash) {
  2563. start = i + 1;
  2564. break;
  2565. }
  2566. } else if (end === -1) {
  2567. // We saw the first non-path separator, mark this as the end of our
  2568. // path component
  2569. matchedSlash = false;
  2570. end = i + 1;
  2571. }
  2572. }
  2573. if (end === -1)
  2574. return '';
  2575. return path.slice(start, end);
  2576. }
  2577. },
  2578. extname: function extname(path) {
  2579. assertPath(path);
  2580. var startDot = -1;
  2581. var startPart = 0;
  2582. var end = -1;
  2583. var matchedSlash = true;
  2584. // Track the state of characters (if any) we see before our first dot and
  2585. // after any path separator we find
  2586. var preDotState = 0;
  2587. for (var i = path.length - 1; i >= 0; --i) {
  2588. var code = path.charCodeAt(i);
  2589. if (code === 47/*/*/) {
  2590. // If we reached a path separator that was not part of a set of path
  2591. // separators at the end of the string, stop now
  2592. if (!matchedSlash) {
  2593. startPart = i + 1;
  2594. break;
  2595. }
  2596. continue;
  2597. }
  2598. if (end === -1) {
  2599. // We saw the first non-path separator, mark this as the end of our
  2600. // extension
  2601. matchedSlash = false;
  2602. end = i + 1;
  2603. }
  2604. if (code === 46/*.*/) {
  2605. // If this is our first dot, mark it as the start of our extension
  2606. if (startDot === -1)
  2607. startDot = i;
  2608. else if (preDotState !== 1)
  2609. preDotState = 1;
  2610. } else if (startDot !== -1) {
  2611. // We saw a non-dot and non-path separator before our dot, so we should
  2612. // have a good chance at having a non-empty extension
  2613. preDotState = -1;
  2614. }
  2615. }
  2616. if (startDot === -1 ||
  2617. end === -1 ||
  2618. // We saw a non-dot character immediately before the dot
  2619. preDotState === 0 ||
  2620. // The (right-most) trimmed path component is exactly '..'
  2621. (preDotState === 1 &&
  2622. startDot === end - 1 &&
  2623. startDot === startPart + 1)) {
  2624. return '';
  2625. }
  2626. return path.slice(startDot, end);
  2627. },
  2628. format: function format(pathObject) {
  2629. if (pathObject === null || typeof pathObject !== 'object') {
  2630. throw new TypeError(
  2631. 'Parameter "pathObject" must be an object, not ' + typeof(pathObject)
  2632. );
  2633. }
  2634. return _format('/', pathObject);
  2635. },
  2636. parse: function parse(path) {
  2637. assertPath(path);
  2638. var ret = { root: '', dir: '', base: '', ext: '', name: '' };
  2639. if (path.length === 0)
  2640. return ret;
  2641. var code = path.charCodeAt(0);
  2642. var isAbsolute = (code === 47/*/*/);
  2643. var start;
  2644. if (isAbsolute) {
  2645. ret.root = '/';
  2646. start = 1;
  2647. } else {
  2648. start = 0;
  2649. }
  2650. var startDot = -1;
  2651. var startPart = 0;
  2652. var end = -1;
  2653. var matchedSlash = true;
  2654. var i = path.length - 1;
  2655. // Track the state of characters (if any) we see before our first dot and
  2656. // after any path separator we find
  2657. var preDotState = 0;
  2658. // Get non-dir info
  2659. for (; i >= start; --i) {
  2660. code = path.charCodeAt(i);
  2661. if (code === 47/*/*/) {
  2662. // If we reached a path separator that was not part of a set of path
  2663. // separators at the end of the string, stop now
  2664. if (!matchedSlash) {
  2665. startPart = i + 1;
  2666. break;
  2667. }
  2668. continue;
  2669. }
  2670. if (end === -1) {
  2671. // We saw the first non-path separator, mark this as the end of our
  2672. // extension
  2673. matchedSlash = false;
  2674. end = i + 1;
  2675. }
  2676. if (code === 46/*.*/) {
  2677. // If this is our first dot, mark it as the start of our extension
  2678. if (startDot === -1)
  2679. startDot = i;
  2680. else if (preDotState !== 1)
  2681. preDotState = 1;
  2682. } else if (startDot !== -1) {
  2683. // We saw a non-dot and non-path separator before our dot, so we should
  2684. // have a good chance at having a non-empty extension
  2685. preDotState = -1;
  2686. }
  2687. }
  2688. if (startDot === -1 ||
  2689. end === -1 ||
  2690. // We saw a non-dot character immediately before the dot
  2691. preDotState === 0 ||
  2692. // The (right-most) trimmed path component is exactly '..'
  2693. (preDotState === 1 &&
  2694. startDot === end - 1 &&
  2695. startDot === startPart + 1)) {
  2696. if (end !== -1) {
  2697. if (startPart === 0 && isAbsolute)
  2698. ret.base = ret.name = path.slice(1, end);
  2699. else
  2700. ret.base = ret.name = path.slice(startPart, end);
  2701. }
  2702. } else {
  2703. if (startPart === 0 && isAbsolute) {
  2704. ret.name = path.slice(1, startDot);
  2705. ret.base = path.slice(1, end);
  2706. } else {
  2707. ret.name = path.slice(startPart, startDot);
  2708. ret.base = path.slice(startPart, end);
  2709. }
  2710. ret.ext = path.slice(startDot, end);
  2711. }
  2712. if (startPart > 0)
  2713. ret.dir = path.slice(0, startPart - 1);
  2714. else if (isAbsolute)
  2715. ret.dir = '/';
  2716. return ret;
  2717. },
  2718. sep: '/',
  2719. delimiter: ':',
  2720. posix: null
  2721. };
  2722. module.exports = posix;
  2723. /***/ }),
  2724. /* 7 */
  2725. /***/ (function(module, exports, __webpack_require__) {
  2726. "use strict";
  2727. Object.defineProperty(exports, "__esModule", {
  2728. value: true
  2729. });
  2730. exports.replaceBase = replaceBase;
  2731. exports.replaceCanonical = replaceCanonical;
  2732. exports.replaceMeta = replaceMeta;
  2733. exports.replaceLinks = replaceLinks;
  2734. exports.substitute = substitute;
  2735. var _core = __webpack_require__(0);
  2736. var _url = __webpack_require__(5);
  2737. var _url2 = _interopRequireDefault(_url);
  2738. var _path = __webpack_require__(4);
  2739. var _path2 = _interopRequireDefault(_path);
  2740. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2741. function replaceBase(doc, section) {
  2742. var base;
  2743. var head;
  2744. var url = section.url;
  2745. var absolute = url.indexOf("://") > -1;
  2746. if (!doc) {
  2747. return;
  2748. }
  2749. head = (0, _core.qs)(doc, "head");
  2750. base = (0, _core.qs)(head, "base");
  2751. if (!base) {
  2752. base = doc.createElement("base");
  2753. head.insertBefore(base, head.firstChild);
  2754. }
  2755. // Fix for Safari crashing if the url doesn't have an origin
  2756. if (!absolute && window && window.location) {
  2757. url = window.location.origin + url;
  2758. }
  2759. base.setAttribute("href", url);
  2760. }
  2761. function replaceCanonical(doc, section) {
  2762. var head;
  2763. var link;
  2764. var url = section.canonical;
  2765. if (!doc) {
  2766. return;
  2767. }
  2768. head = (0, _core.qs)(doc, "head");
  2769. link = (0, _core.qs)(head, "link[rel='canonical']");
  2770. if (link) {
  2771. link.setAttribute("href", url);
  2772. } else {
  2773. link = doc.createElement("link");
  2774. link.setAttribute("rel", "canonical");
  2775. link.setAttribute("href", url);
  2776. head.appendChild(link);
  2777. }
  2778. }
  2779. function replaceMeta(doc, section) {
  2780. var head;
  2781. var meta;
  2782. var id = section.idref;
  2783. if (!doc) {
  2784. return;
  2785. }
  2786. head = (0, _core.qs)(doc, "head");
  2787. meta = (0, _core.qs)(head, "link[property='dc.identifier']");
  2788. if (meta) {
  2789. meta.setAttribute("content", id);
  2790. } else {
  2791. meta = doc.createElement("meta");
  2792. meta.setAttribute("name", "dc.identifier");
  2793. meta.setAttribute("content", id);
  2794. head.appendChild(meta);
  2795. }
  2796. }
  2797. // TODO: move me to Contents
  2798. function replaceLinks(contents, fn) {
  2799. var links = contents.querySelectorAll("a[href]");
  2800. if (!links.length) {
  2801. return;
  2802. }
  2803. var base = (0, _core.qs)(contents.ownerDocument, "base");
  2804. var location = base ? base.getAttribute("href") : undefined;
  2805. var replaceLink = function (link) {
  2806. var href = link.getAttribute("href");
  2807. if (href.indexOf("mailto:") === 0) {
  2808. return;
  2809. }
  2810. var absolute = href.indexOf("://") > -1;
  2811. var linkUrl = new _url2.default(href, location);
  2812. if (absolute) {
  2813. link.setAttribute("target", "_blank");
  2814. } else {
  2815. link.onclick = function () {
  2816. if (linkUrl && linkUrl.hash) {
  2817. fn(linkUrl.Path.path + linkUrl.hash);
  2818. } else if (linkUrl) {
  2819. fn(linkUrl.Path.path);
  2820. } else {
  2821. fn(href);
  2822. }
  2823. return false;
  2824. };
  2825. }
  2826. }.bind(this);
  2827. for (var i = 0; i < links.length; i++) {
  2828. replaceLink(links[i]);
  2829. }
  2830. }
  2831. function substitute(content, urls, replacements) {
  2832. urls.forEach(function (url, i) {
  2833. if (url && replacements[i]) {
  2834. content = content.replace(new RegExp(url, "g"), replacements[i]);
  2835. }
  2836. });
  2837. return content;
  2838. }
  2839. /***/ }),
  2840. /* 8 */
  2841. /***/ (function(module, exports) {
  2842. var g;
  2843. // This works in non-strict mode
  2844. g = (function() {
  2845. return this;
  2846. })();
  2847. try {
  2848. // This works if eval is allowed (see CSP)
  2849. g = g || Function("return this")() || (1,eval)("this");
  2850. } catch(e) {
  2851. // This works if the window reference is available
  2852. if(typeof window === "object")
  2853. g = window;
  2854. }
  2855. // g can still be undefined, but nothing to do about it...
  2856. // We return undefined, instead of nothing here, so it's
  2857. // easier to handle this case. if(!global) { ...}
  2858. module.exports = g;
  2859. /***/ }),
  2860. /* 9 */
  2861. /***/ (function(module, exports, __webpack_require__) {
  2862. "use strict";
  2863. var _undefined = __webpack_require__(34)(); // Support ES3 engines
  2864. module.exports = function (val) {
  2865. return (val !== _undefined) && (val !== null);
  2866. };
  2867. /***/ }),
  2868. /* 10 */
  2869. /***/ (function(module, exports, __webpack_require__) {
  2870. "use strict";
  2871. Object.defineProperty(exports, "__esModule", {
  2872. value: true
  2873. });
  2874. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  2875. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2876. /**
  2877. * Hooks allow for injecting functions that must all complete in order before finishing
  2878. * They will execute in parallel but all must finish before continuing
  2879. * Functions may return a promise if they are asycn.
  2880. * @param {any} context scope of this
  2881. * @example this.content = new EPUBJS.Hook(this);
  2882. */
  2883. var Hook = function () {
  2884. function Hook(context) {
  2885. _classCallCheck(this, Hook);
  2886. this.context = context || this;
  2887. this.hooks = [];
  2888. }
  2889. /**
  2890. * Adds a function to be run before a hook completes
  2891. * @example this.content.register(function(){...});
  2892. */
  2893. _createClass(Hook, [{
  2894. key: "register",
  2895. value: function register() {
  2896. for (var i = 0; i < arguments.length; ++i) {
  2897. if (typeof arguments[i] === "function") {
  2898. this.hooks.push(arguments[i]);
  2899. } else {
  2900. // unpack array
  2901. for (var j = 0; j < arguments[i].length; ++j) {
  2902. this.hooks.push(arguments[i][j]);
  2903. }
  2904. }
  2905. }
  2906. }
  2907. /**
  2908. * Triggers a hook to run all functions
  2909. * @example this.content.trigger(args).then(function(){...});
  2910. */
  2911. }, {
  2912. key: "trigger",
  2913. value: function trigger() {
  2914. var args = arguments;
  2915. var context = this.context;
  2916. var promises = [];
  2917. this.hooks.forEach(function (task) {
  2918. var executing = task.apply(context, args);
  2919. if (executing && typeof executing["then"] === "function") {
  2920. // Task is a function that returns a promise
  2921. promises.push(executing);
  2922. }
  2923. // Otherwise Task resolves immediately, continue
  2924. });
  2925. return Promise.all(promises);
  2926. }
  2927. // Adds a function to be run before a hook completes
  2928. }, {
  2929. key: "list",
  2930. value: function list() {
  2931. return this.hooks;
  2932. }
  2933. }, {
  2934. key: "clear",
  2935. value: function clear() {
  2936. return this.hooks = [];
  2937. }
  2938. }]);
  2939. return Hook;
  2940. }();
  2941. exports.default = Hook;
  2942. module.exports = exports["default"];
  2943. /***/ }),
  2944. /* 11 */
  2945. /***/ (function(module, exports, __webpack_require__) {
  2946. "use strict";
  2947. Object.defineProperty(exports, "__esModule", {
  2948. value: true
  2949. });
  2950. var _core = __webpack_require__(0);
  2951. var _path = __webpack_require__(4);
  2952. var _path2 = _interopRequireDefault(_path);
  2953. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2954. function request(url, type, withCredentials, headers) {
  2955. var supportsURL = typeof window != "undefined" ? window.URL : false; // TODO: fallback for url if window isn't defined
  2956. var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer";
  2957. var deferred = new _core.defer();
  2958. var xhr = new XMLHttpRequest();
  2959. //-- Check from PDF.js:
  2960. // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js
  2961. var xhrPrototype = XMLHttpRequest.prototype;
  2962. var header;
  2963. if (!("overrideMimeType" in xhrPrototype)) {
  2964. // IE10 might have response, but not overrideMimeType
  2965. Object.defineProperty(xhrPrototype, "overrideMimeType", {
  2966. value: function xmlHttpRequestOverrideMimeType() {}
  2967. });
  2968. }
  2969. if (withCredentials) {
  2970. xhr.withCredentials = true;
  2971. }
  2972. xhr.onreadystatechange = handler;
  2973. xhr.onerror = err;
  2974. xhr.open("GET", url, true);
  2975. for (header in headers) {
  2976. xhr.setRequestHeader(header, headers[header]);
  2977. }
  2978. if (type == "json") {
  2979. xhr.setRequestHeader("Accept", "application/json");
  2980. }
  2981. // If type isn"t set, determine it from the file extension
  2982. if (!type) {
  2983. type = new _path2.default(url).extension;
  2984. }
  2985. if (type == "blob") {
  2986. xhr.responseType = BLOB_RESPONSE;
  2987. }
  2988. if ((0, _core.isXml)(type)) {
  2989. // xhr.responseType = "document";
  2990. xhr.overrideMimeType("text/xml"); // for OPF parsing
  2991. }
  2992. if (type == "xhtml") {
  2993. // xhr.responseType = "document";
  2994. }
  2995. if (type == "html" || type == "htm") {
  2996. // xhr.responseType = "document";
  2997. }
  2998. if (type == "binary") {
  2999. xhr.responseType = "arraybuffer";
  3000. }
  3001. xhr.send();
  3002. function err(e) {
  3003. deferred.reject(e);
  3004. }
  3005. function handler() {
  3006. if (this.readyState === XMLHttpRequest.DONE) {
  3007. var responseXML = false;
  3008. if (this.responseType === "" || this.responseType === "document") {
  3009. responseXML = this.responseXML;
  3010. }
  3011. if (this.status === 200 || this.status === 0 || responseXML) {
  3012. //-- Firefox is reporting 0 for blob urls
  3013. var r;
  3014. if (!this.response && !responseXML) {
  3015. deferred.reject({
  3016. status: this.status,
  3017. message: "Empty Response",
  3018. stack: new Error().stack
  3019. });
  3020. return deferred.promise;
  3021. }
  3022. if (this.status === 403) {
  3023. deferred.reject({
  3024. status: this.status,
  3025. response: this.response,
  3026. message: "Forbidden",
  3027. stack: new Error().stack
  3028. });
  3029. return deferred.promise;
  3030. }
  3031. if (responseXML) {
  3032. r = this.responseXML;
  3033. } else if ((0, _core.isXml)(type)) {
  3034. // xhr.overrideMimeType("text/xml"); // for OPF parsing
  3035. // If this.responseXML wasn't set, try to parse using a DOMParser from text
  3036. r = (0, _core.parse)(this.response, "text/xml");
  3037. } else if (type == "xhtml") {
  3038. r = (0, _core.parse)(this.response, "application/xhtml+xml");
  3039. } else if (type == "html" || type == "htm") {
  3040. r = (0, _core.parse)(this.response, "text/html");
  3041. } else if (type == "json") {
  3042. r = JSON.parse(this.response);
  3043. } else if (type == "blob") {
  3044. if (supportsURL) {
  3045. r = this.response;
  3046. } else {
  3047. //-- Safari doesn't support responseType blob, so create a blob from arraybuffer
  3048. r = new Blob([this.response]);
  3049. }
  3050. } else {
  3051. r = this.response;
  3052. }
  3053. deferred.resolve(r);
  3054. } else {
  3055. deferred.reject({
  3056. status: this.status,
  3057. message: this.response,
  3058. stack: new Error().stack
  3059. });
  3060. }
  3061. }
  3062. }
  3063. return deferred.promise;
  3064. }
  3065. exports.default = request;
  3066. module.exports = exports["default"];
  3067. /***/ }),
  3068. /* 12 */
  3069. /***/ (function(module, exports, __webpack_require__) {
  3070. "use strict";
  3071. Object.defineProperty(exports, "__esModule", {
  3072. value: true
  3073. });
  3074. exports.Task = undefined;
  3075. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  3076. var _core = __webpack_require__(0);
  3077. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3078. /**
  3079. * Queue for handling tasks one at a time
  3080. * @class
  3081. * @param {scope} context what this will resolve to in the tasks
  3082. */
  3083. var Queue = function () {
  3084. function Queue(context) {
  3085. _classCallCheck(this, Queue);
  3086. this._q = [];
  3087. this.context = context;
  3088. this.tick = _core.requestAnimationFrame;
  3089. this.running = false;
  3090. this.paused = false;
  3091. }
  3092. /**
  3093. * Add an item to the queue
  3094. * @return {Promise}
  3095. */
  3096. _createClass(Queue, [{
  3097. key: "enqueue",
  3098. value: function enqueue() {
  3099. var deferred, promise;
  3100. var queued;
  3101. var task = [].shift.call(arguments);
  3102. var args = arguments;
  3103. // Handle single args without context
  3104. // if(args && !Array.isArray(args)) {
  3105. // args = [args];
  3106. // }
  3107. if (!task) {
  3108. throw new Error("No Task Provided");
  3109. }
  3110. if (typeof task === "function") {
  3111. deferred = new _core.defer();
  3112. promise = deferred.promise;
  3113. queued = {
  3114. "task": task,
  3115. "args": args,
  3116. //"context" : context,
  3117. "deferred": deferred,
  3118. "promise": promise
  3119. };
  3120. } else {
  3121. // Task is a promise
  3122. queued = {
  3123. "promise": task
  3124. };
  3125. }
  3126. this._q.push(queued);
  3127. // Wait to start queue flush
  3128. if (this.paused == false && !this.running) {
  3129. // setTimeout(this.flush.bind(this), 0);
  3130. // this.tick.call(window, this.run.bind(this));
  3131. this.run();
  3132. }
  3133. return queued.promise;
  3134. }
  3135. /**
  3136. * Run one item
  3137. * @return {Promise}
  3138. */
  3139. }, {
  3140. key: "dequeue",
  3141. value: function dequeue() {
  3142. var inwait, task, result;
  3143. if (this._q.length && !this.paused) {
  3144. inwait = this._q.shift();
  3145. task = inwait.task;
  3146. if (task) {
  3147. // console.log(task)
  3148. result = task.apply(this.context, inwait.args);
  3149. if (result && typeof result["then"] === "function") {
  3150. // Task is a function that returns a promise
  3151. return result.then(function () {
  3152. inwait.deferred.resolve.apply(this.context, arguments);
  3153. }.bind(this), function () {
  3154. inwait.deferred.reject.apply(this.context, arguments);
  3155. }.bind(this));
  3156. } else {
  3157. // Task resolves immediately
  3158. inwait.deferred.resolve.apply(this.context, result);
  3159. return inwait.promise;
  3160. }
  3161. } else if (inwait.promise) {
  3162. // Task is a promise
  3163. return inwait.promise;
  3164. }
  3165. } else {
  3166. inwait = new _core.defer();
  3167. inwait.deferred.resolve();
  3168. return inwait.promise;
  3169. }
  3170. }
  3171. // Run All Immediately
  3172. }, {
  3173. key: "dump",
  3174. value: function dump() {
  3175. while (this._q.length) {
  3176. this.dequeue();
  3177. }
  3178. }
  3179. /**
  3180. * Run all tasks sequentially, at convince
  3181. * @return {Promise}
  3182. */
  3183. }, {
  3184. key: "run",
  3185. value: function run() {
  3186. var _this = this;
  3187. if (!this.running) {
  3188. this.running = true;
  3189. this.defered = new _core.defer();
  3190. }
  3191. this.tick.call(window, function () {
  3192. if (_this._q.length) {
  3193. _this.dequeue().then(function () {
  3194. this.run();
  3195. }.bind(_this));
  3196. } else {
  3197. _this.defered.resolve();
  3198. _this.running = undefined;
  3199. }
  3200. });
  3201. // Unpause
  3202. if (this.paused == true) {
  3203. this.paused = false;
  3204. }
  3205. return this.defered.promise;
  3206. }
  3207. /**
  3208. * Flush all, as quickly as possible
  3209. * @return {Promise}
  3210. */
  3211. }, {
  3212. key: "flush",
  3213. value: function flush() {
  3214. if (this.running) {
  3215. return this.running;
  3216. }
  3217. if (this._q.length) {
  3218. this.running = this.dequeue().then(function () {
  3219. this.running = undefined;
  3220. return this.flush();
  3221. }.bind(this));
  3222. return this.running;
  3223. }
  3224. }
  3225. /**
  3226. * Clear all items in wait
  3227. */
  3228. }, {
  3229. key: "clear",
  3230. value: function clear() {
  3231. this._q = [];
  3232. }
  3233. /**
  3234. * Get the number of tasks in the queue
  3235. * @return {number} tasks
  3236. */
  3237. }, {
  3238. key: "length",
  3239. value: function length() {
  3240. return this._q.length;
  3241. }
  3242. /**
  3243. * Pause a running queue
  3244. */
  3245. }, {
  3246. key: "pause",
  3247. value: function pause() {
  3248. this.paused = true;
  3249. }
  3250. /**
  3251. * End the queue
  3252. */
  3253. }, {
  3254. key: "stop",
  3255. value: function stop() {
  3256. this._q = [];
  3257. this.running = false;
  3258. this.paused = true;
  3259. }
  3260. }]);
  3261. return Queue;
  3262. }();
  3263. /**
  3264. * Create a new task from a callback
  3265. * @class
  3266. * @private
  3267. * @param {function} task
  3268. * @param {array} args
  3269. * @param {scope} context
  3270. * @return {function} task
  3271. */
  3272. var Task = function Task(task, args, context) {
  3273. _classCallCheck(this, Task);
  3274. return function () {
  3275. var _this2 = this;
  3276. var toApply = arguments || [];
  3277. return new Promise(function (resolve, reject) {
  3278. var callback = function callback(value, err) {
  3279. if (!value && err) {
  3280. reject(err);
  3281. } else {
  3282. resolve(value);
  3283. }
  3284. };
  3285. // Add the callback to the arguments list
  3286. toApply.push(callback);
  3287. // Apply all arguments to the functions
  3288. task.apply(context || _this2, toApply);
  3289. });
  3290. };
  3291. };
  3292. exports.default = Queue;
  3293. exports.Task = Task;
  3294. /***/ }),
  3295. /* 13 */
  3296. /***/ (function(module, exports, __webpack_require__) {
  3297. "use strict";
  3298. Object.defineProperty(exports, "__esModule", {
  3299. value: true
  3300. });
  3301. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  3302. var _eventEmitter = __webpack_require__(3);
  3303. var _eventEmitter2 = _interopRequireDefault(_eventEmitter);
  3304. var _core = __webpack_require__(0);
  3305. var _epubcfi = __webpack_require__(1);
  3306. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  3307. var _mapping = __webpack_require__(19);
  3308. var _mapping2 = _interopRequireDefault(_mapping);
  3309. var _replacements = __webpack_require__(7);
  3310. var _constants = __webpack_require__(2);
  3311. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3312. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3313. var hasNavigator = typeof navigator !== "undefined";
  3314. var isChrome = hasNavigator && /Chrome/.test(navigator.userAgent);
  3315. var isWebkit = hasNavigator && !isChrome && /AppleWebKit/.test(navigator.userAgent);
  3316. var ELEMENT_NODE = 1;
  3317. var TEXT_NODE = 3;
  3318. /**
  3319. * Handles DOM manipulation, queries and events for View contents
  3320. * @class
  3321. * @param {document} doc Document
  3322. * @param {element} content Parent Element (typically Body)
  3323. * @param {string} cfiBase Section component of CFIs
  3324. * @param {number} sectionIndex Index in Spine of Conntent's Section
  3325. */
  3326. var Contents = function () {
  3327. function Contents(doc, content, cfiBase, sectionIndex) {
  3328. _classCallCheck(this, Contents);
  3329. // Blank Cfi for Parsing
  3330. this.epubcfi = new _epubcfi2.default();
  3331. this.document = doc;
  3332. this.documentElement = this.document.documentElement;
  3333. this.content = content || this.document.body;
  3334. this.window = this.document.defaultView;
  3335. this._size = {
  3336. width: 0,
  3337. height: 0
  3338. };
  3339. this.sectionIndex = sectionIndex || 0;
  3340. this.cfiBase = cfiBase || "";
  3341. this.epubReadingSystem("epub.js", _constants.EPUBJS_VERSION);
  3342. this.listeners();
  3343. }
  3344. /**
  3345. * Get DOM events that are listened for and passed along
  3346. */
  3347. _createClass(Contents, [{
  3348. key: "width",
  3349. /**
  3350. * Get or Set width
  3351. * @param {number} [w]
  3352. * @returns {number} width
  3353. */
  3354. value: function width(w) {
  3355. // var frame = this.documentElement;
  3356. var frame = this.content;
  3357. if (w && (0, _core.isNumber)(w)) {
  3358. w = w + "px";
  3359. }
  3360. if (w) {
  3361. frame.style.width = w;
  3362. // this.content.style.width = w;
  3363. }
  3364. return this.window.getComputedStyle(frame)["width"];
  3365. }
  3366. /**
  3367. * Get or Set height
  3368. * @param {number} [h]
  3369. * @returns {number} height
  3370. */
  3371. }, {
  3372. key: "height",
  3373. value: function height(h) {
  3374. // var frame = this.documentElement;
  3375. var frame = this.content;
  3376. if (h && (0, _core.isNumber)(h)) {
  3377. h = h + "px";
  3378. }
  3379. if (h) {
  3380. frame.style.height = h;
  3381. // this.content.style.height = h;
  3382. }
  3383. return this.window.getComputedStyle(frame)["height"];
  3384. }
  3385. /**
  3386. * Get or Set width of the contents
  3387. * @param {number} [w]
  3388. * @returns {number} width
  3389. */
  3390. }, {
  3391. key: "contentWidth",
  3392. value: function contentWidth(w) {
  3393. var content = this.content || this.document.body;
  3394. if (w && (0, _core.isNumber)(w)) {
  3395. w = w + "px";
  3396. }
  3397. if (w) {
  3398. content.style.width = w;
  3399. }
  3400. return this.window.getComputedStyle(content)["width"];
  3401. }
  3402. /**
  3403. * Get or Set height of the contents
  3404. * @param {number} [h]
  3405. * @returns {number} height
  3406. */
  3407. }, {
  3408. key: "contentHeight",
  3409. value: function contentHeight(h) {
  3410. var content = this.content || this.document.body;
  3411. if (h && (0, _core.isNumber)(h)) {
  3412. h = h + "px";
  3413. }
  3414. if (h) {
  3415. content.style.height = h;
  3416. }
  3417. return this.window.getComputedStyle(content)["height"];
  3418. }
  3419. /**
  3420. * Get the width of the text using Range
  3421. * @returns {number} width
  3422. */
  3423. }, {
  3424. key: "textWidth",
  3425. value: function textWidth() {
  3426. var rect = void 0;
  3427. var width = void 0;
  3428. var range = this.document.createRange();
  3429. var content = this.content || this.document.body;
  3430. var border = (0, _core.borders)(content);
  3431. // Select the contents of frame
  3432. range.selectNodeContents(content);
  3433. // get the width of the text content
  3434. rect = range.getBoundingClientRect();
  3435. width = rect.width;
  3436. if (border && border.width) {
  3437. width += border.width;
  3438. }
  3439. return Math.round(width);
  3440. }
  3441. /**
  3442. * Get the height of the text using Range
  3443. * @returns {number} height
  3444. */
  3445. }, {
  3446. key: "textHeight",
  3447. value: function textHeight() {
  3448. var rect = void 0;
  3449. var height = void 0;
  3450. var range = this.document.createRange();
  3451. var content = this.content || this.document.body;
  3452. var border = (0, _core.borders)(content);
  3453. range.selectNodeContents(content);
  3454. rect = range.getBoundingClientRect();
  3455. height = rect.height;
  3456. if (height && border.height) {
  3457. height += border.height;
  3458. }
  3459. return Math.round(height);
  3460. }
  3461. /**
  3462. * Get documentElement scrollWidth
  3463. * @returns {number} width
  3464. */
  3465. }, {
  3466. key: "scrollWidth",
  3467. value: function scrollWidth() {
  3468. var width = this.documentElement.scrollWidth;
  3469. return width;
  3470. }
  3471. /**
  3472. * Get documentElement scrollHeight
  3473. * @returns {number} height
  3474. */
  3475. }, {
  3476. key: "scrollHeight",
  3477. value: function scrollHeight() {
  3478. var height = this.documentElement.scrollHeight;
  3479. return height;
  3480. }
  3481. /**
  3482. * Set overflow css style of the contents
  3483. * @param {string} [overflow]
  3484. */
  3485. }, {
  3486. key: "overflow",
  3487. value: function overflow(_overflow) {
  3488. if (_overflow) {
  3489. this.documentElement.style.overflow = _overflow;
  3490. }
  3491. return this.window.getComputedStyle(this.documentElement)["overflow"];
  3492. }
  3493. /**
  3494. * Set overflowX css style of the documentElement
  3495. * @param {string} [overflow]
  3496. */
  3497. }, {
  3498. key: "overflowX",
  3499. value: function overflowX(overflow) {
  3500. if (overflow) {
  3501. this.documentElement.style.overflowX = overflow;
  3502. }
  3503. return this.window.getComputedStyle(this.documentElement)["overflowX"];
  3504. }
  3505. /**
  3506. * Set overflowY css style of the documentElement
  3507. * @param {string} [overflow]
  3508. */
  3509. }, {
  3510. key: "overflowY",
  3511. value: function overflowY(overflow) {
  3512. if (overflow) {
  3513. this.documentElement.style.overflowY = overflow;
  3514. }
  3515. return this.window.getComputedStyle(this.documentElement)["overflowY"];
  3516. }
  3517. /**
  3518. * Set Css styles on the contents element (typically Body)
  3519. * @param {string} property
  3520. * @param {string} value
  3521. * @param {boolean} [priority] set as "important"
  3522. */
  3523. }, {
  3524. key: "css",
  3525. value: function css(property, value, priority) {
  3526. var content = this.content || this.document.body;
  3527. if (value) {
  3528. content.style.setProperty(property, value, priority ? "important" : "");
  3529. }
  3530. return this.window.getComputedStyle(content)[property];
  3531. }
  3532. /**
  3533. * Get or Set the viewport element
  3534. * @param {object} [options]
  3535. * @param {string} [options.width]
  3536. * @param {string} [options.height]
  3537. * @param {string} [options.scale]
  3538. * @param {string} [options.minimum]
  3539. * @param {string} [options.maximum]
  3540. * @param {string} [options.scalable]
  3541. */
  3542. }, {
  3543. key: "viewport",
  3544. value: function viewport(options) {
  3545. var _width, _height, _scale, _minimum, _maximum, _scalable;
  3546. // var width, height, scale, minimum, maximum, scalable;
  3547. var $viewport = this.document.querySelector("meta[name='viewport']");
  3548. var parsed = {
  3549. "width": undefined,
  3550. "height": undefined,
  3551. "scale": undefined,
  3552. "minimum": undefined,
  3553. "maximum": undefined,
  3554. "scalable": undefined
  3555. };
  3556. var newContent = [];
  3557. var settings = {};
  3558. /*
  3559. * check for the viewport size
  3560. * <meta name="viewport" content="width=1024,height=697" />
  3561. */
  3562. if ($viewport && $viewport.hasAttribute("content")) {
  3563. var content = $viewport.getAttribute("content");
  3564. var _width2 = content.match(/width\s*=\s*([^,]*)/);
  3565. var _height2 = content.match(/height\s*=\s*([^,]*)/);
  3566. var _scale2 = content.match(/initial-scale\s*=\s*([^,]*)/);
  3567. var _minimum2 = content.match(/minimum-scale\s*=\s*([^,]*)/);
  3568. var _maximum2 = content.match(/maximum-scale\s*=\s*([^,]*)/);
  3569. var _scalable2 = content.match(/user-scalable\s*=\s*([^,]*)/);
  3570. if (_width2 && _width2.length && typeof _width2[1] !== "undefined") {
  3571. parsed.width = _width2[1];
  3572. }
  3573. if (_height2 && _height2.length && typeof _height2[1] !== "undefined") {
  3574. parsed.height = _height2[1];
  3575. }
  3576. if (_scale2 && _scale2.length && typeof _scale2[1] !== "undefined") {
  3577. parsed.scale = _scale2[1];
  3578. }
  3579. if (_minimum2 && _minimum2.length && typeof _minimum2[1] !== "undefined") {
  3580. parsed.minimum = _minimum2[1];
  3581. }
  3582. if (_maximum2 && _maximum2.length && typeof _maximum2[1] !== "undefined") {
  3583. parsed.maximum = _maximum2[1];
  3584. }
  3585. if (_scalable2 && _scalable2.length && typeof _scalable2[1] !== "undefined") {
  3586. parsed.scalable = _scalable2[1];
  3587. }
  3588. }
  3589. settings = (0, _core.defaults)(options || {}, parsed);
  3590. if (options) {
  3591. if (settings.width) {
  3592. newContent.push("width=" + settings.width);
  3593. }
  3594. if (settings.height) {
  3595. newContent.push("height=" + settings.height);
  3596. }
  3597. if (settings.scale) {
  3598. newContent.push("initial-scale=" + settings.scale);
  3599. }
  3600. if (settings.scalable === "no") {
  3601. newContent.push("minimum-scale=" + settings.scale);
  3602. newContent.push("maximum-scale=" + settings.scale);
  3603. newContent.push("user-scalable=" + settings.scalable);
  3604. } else {
  3605. if (settings.scalable) {
  3606. newContent.push("user-scalable=" + settings.scalable);
  3607. }
  3608. if (settings.minimum) {
  3609. newContent.push("minimum-scale=" + settings.minimum);
  3610. }
  3611. if (settings.maximum) {
  3612. newContent.push("minimum-scale=" + settings.maximum);
  3613. }
  3614. }
  3615. if (!$viewport) {
  3616. $viewport = this.document.createElement("meta");
  3617. $viewport.setAttribute("name", "viewport");
  3618. this.document.querySelector("head").appendChild($viewport);
  3619. }
  3620. $viewport.setAttribute("content", newContent.join(", "));
  3621. this.window.scrollTo(0, 0);
  3622. }
  3623. return settings;
  3624. }
  3625. /**
  3626. * Event emitter for when the contents has expanded
  3627. * @private
  3628. */
  3629. }, {
  3630. key: "expand",
  3631. value: function expand() {
  3632. this.emit(_constants.EVENTS.CONTENTS.EXPAND);
  3633. }
  3634. /**
  3635. * Add DOM listeners
  3636. * @private
  3637. */
  3638. }, {
  3639. key: "listeners",
  3640. value: function listeners() {
  3641. this.imageLoadListeners();
  3642. this.mediaQueryListeners();
  3643. // this.fontLoadListeners();
  3644. this.addEventListeners();
  3645. this.addSelectionListeners();
  3646. // this.transitionListeners();
  3647. this.resizeListeners();
  3648. // this.resizeObservers();
  3649. this.linksHandler();
  3650. }
  3651. /**
  3652. * Remove DOM listeners
  3653. * @private
  3654. */
  3655. }, {
  3656. key: "removeListeners",
  3657. value: function removeListeners() {
  3658. this.removeEventListeners();
  3659. this.removeSelectionListeners();
  3660. clearTimeout(this.expanding);
  3661. }
  3662. /**
  3663. * Check if size of contents has changed and
  3664. * emit 'resize' event if it has.
  3665. * @private
  3666. */
  3667. }, {
  3668. key: "resizeCheck",
  3669. value: function resizeCheck() {
  3670. var width = this.textWidth();
  3671. var height = this.textHeight();
  3672. if (width != this._size.width || height != this._size.height) {
  3673. this._size = {
  3674. width: width,
  3675. height: height
  3676. };
  3677. this.onResize && this.onResize(this._size);
  3678. this.emit(_constants.EVENTS.CONTENTS.RESIZE, this._size);
  3679. }
  3680. }
  3681. /**
  3682. * Poll for resize detection
  3683. * @private
  3684. */
  3685. }, {
  3686. key: "resizeListeners",
  3687. value: function resizeListeners() {
  3688. var width, height;
  3689. // Test size again
  3690. clearTimeout(this.expanding);
  3691. requestAnimationFrame(this.resizeCheck.bind(this));
  3692. this.expanding = setTimeout(this.resizeListeners.bind(this), 350);
  3693. }
  3694. /**
  3695. * Use css transitions to detect resize
  3696. * @private
  3697. */
  3698. }, {
  3699. key: "transitionListeners",
  3700. value: function transitionListeners() {
  3701. var body = this.content;
  3702. body.style['transitionProperty'] = "font, font-size, font-size-adjust, font-stretch, font-variation-settings, font-weight, width, height";
  3703. body.style['transitionDuration'] = "0.001ms";
  3704. body.style['transitionTimingFunction'] = "linear";
  3705. body.style['transitionDelay'] = "0";
  3706. this.document.addEventListener('transitionend', this.resizeCheck.bind(this));
  3707. }
  3708. /**
  3709. * Listen for media query changes and emit 'expand' event
  3710. * Adapted from: https://github.com/tylergaw/media-query-events/blob/master/js/mq-events.js
  3711. * @private
  3712. */
  3713. }, {
  3714. key: "mediaQueryListeners",
  3715. value: function mediaQueryListeners() {
  3716. var sheets = this.document.styleSheets;
  3717. var mediaChangeHandler = function (m) {
  3718. if (m.matches && !this._expanding) {
  3719. setTimeout(this.expand.bind(this), 1);
  3720. }
  3721. }.bind(this);
  3722. for (var i = 0; i < sheets.length; i += 1) {
  3723. var rules;
  3724. // Firefox errors if we access cssRules cross-domain
  3725. try {
  3726. rules = sheets[i].cssRules;
  3727. } catch (e) {
  3728. return;
  3729. }
  3730. if (!rules) return; // Stylesheets changed
  3731. for (var j = 0; j < rules.length; j += 1) {
  3732. //if (rules[j].constructor === CSSMediaRule) {
  3733. if (rules[j].media) {
  3734. var mql = this.window.matchMedia(rules[j].media.mediaText);
  3735. mql.addListener(mediaChangeHandler);
  3736. //mql.onchange = mediaChangeHandler;
  3737. }
  3738. }
  3739. }
  3740. }
  3741. /**
  3742. * Use MutationObserver to listen for changes in the DOM and check for resize
  3743. * @private
  3744. */
  3745. }, {
  3746. key: "resizeObservers",
  3747. value: function resizeObservers() {
  3748. var _this = this;
  3749. // create an observer instance
  3750. this.observer = new MutationObserver(function (mutations) {
  3751. _this.resizeCheck();
  3752. });
  3753. // configuration of the observer:
  3754. var config = { attributes: true, childList: true, characterData: true, subtree: true };
  3755. // pass in the target node, as well as the observer options
  3756. this.observer.observe(this.document, config);
  3757. }
  3758. /**
  3759. * Test if images are loaded or add listener for when they load
  3760. * @private
  3761. */
  3762. }, {
  3763. key: "imageLoadListeners",
  3764. value: function imageLoadListeners() {
  3765. var images = this.document.querySelectorAll("img");
  3766. var img;
  3767. for (var i = 0; i < images.length; i++) {
  3768. img = images[i];
  3769. if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
  3770. img.onload = this.expand.bind(this);
  3771. }
  3772. }
  3773. }
  3774. /**
  3775. * Listen for font load and check for resize when loaded
  3776. * @private
  3777. */
  3778. }, {
  3779. key: "fontLoadListeners",
  3780. value: function fontLoadListeners() {
  3781. if (!this.document || !this.document.fonts) {
  3782. return;
  3783. }
  3784. this.document.fonts.ready.then(function () {
  3785. this.resizeCheck();
  3786. }.bind(this));
  3787. }
  3788. /**
  3789. * Get the documentElement
  3790. * @returns {element} documentElement
  3791. */
  3792. }, {
  3793. key: "root",
  3794. value: function root() {
  3795. if (!this.document) return null;
  3796. return this.document.documentElement;
  3797. }
  3798. /**
  3799. * Get the location offset of a EpubCFI or an #id
  3800. * @param {string | EpubCFI} target
  3801. * @param {string} [ignoreClass] for the cfi
  3802. * @returns { {left: Number, top: Number }
  3803. */
  3804. }, {
  3805. key: "locationOf",
  3806. value: function locationOf(target, ignoreClass) {
  3807. var position;
  3808. var targetPos = { "left": 0, "top": 0 };
  3809. if (!this.document) return targetPos;
  3810. if (this.epubcfi.isCfiString(target)) {
  3811. var range = new _epubcfi2.default(target).toRange(this.document, ignoreClass);
  3812. if (range) {
  3813. if (range.startContainer.nodeType === Node.ELEMENT_NODE) {
  3814. position = range.startContainer.getBoundingClientRect();
  3815. targetPos.left = position.left;
  3816. targetPos.top = position.top;
  3817. } else {
  3818. // Webkit does not handle collapsed range bounds correctly
  3819. // https://bugs.webkit.org/show_bug.cgi?id=138949
  3820. // Construct a new non-collapsed range
  3821. if (isWebkit) {
  3822. var container = range.startContainer;
  3823. var newRange = new Range();
  3824. try {
  3825. if (container.nodeType === ELEMENT_NODE) {
  3826. position = container.getBoundingClientRect();
  3827. } else if (range.startOffset + 2 < container.length) {
  3828. newRange.setStart(container, range.startOffset);
  3829. newRange.setEnd(container, range.startOffset + 2);
  3830. position = newRange.getBoundingClientRect();
  3831. } else if (range.startOffset - 2 > 0) {
  3832. newRange.setStart(container, range.startOffset - 2);
  3833. newRange.setEnd(container, range.startOffset);
  3834. position = newRange.getBoundingClientRect();
  3835. } else {
  3836. // empty, return the parent element
  3837. position = container.parentNode.getBoundingClientRect();
  3838. }
  3839. } catch (e) {
  3840. console.error(e, e.stack);
  3841. }
  3842. } else {
  3843. position = range.getBoundingClientRect();
  3844. }
  3845. }
  3846. }
  3847. } else if (typeof target === "string" && target.indexOf("#") > -1) {
  3848. var id = target.substring(target.indexOf("#") + 1);
  3849. var el = this.document.getElementById(id);
  3850. if (el) {
  3851. position = el.getBoundingClientRect();
  3852. }
  3853. }
  3854. if (position) {
  3855. targetPos.left = position.left;
  3856. targetPos.top = position.top;
  3857. }
  3858. return targetPos;
  3859. }
  3860. /**
  3861. * Append a stylesheet link to the document head
  3862. * @param {string} src url
  3863. */
  3864. }, {
  3865. key: "addStylesheet",
  3866. value: function addStylesheet(src) {
  3867. return new Promise(function (resolve, reject) {
  3868. var $stylesheet;
  3869. var ready = false;
  3870. if (!this.document) {
  3871. resolve(false);
  3872. return;
  3873. }
  3874. // Check if link already exists
  3875. $stylesheet = this.document.querySelector("link[href='" + src + "']");
  3876. if ($stylesheet) {
  3877. resolve(true);
  3878. return; // already present
  3879. }
  3880. $stylesheet = this.document.createElement("link");
  3881. $stylesheet.type = "text/css";
  3882. $stylesheet.rel = "stylesheet";
  3883. $stylesheet.href = src;
  3884. $stylesheet.onload = $stylesheet.onreadystatechange = function () {
  3885. if (!ready && (!this.readyState || this.readyState == "complete")) {
  3886. ready = true;
  3887. // Let apply
  3888. setTimeout(function () {
  3889. resolve(true);
  3890. }, 1);
  3891. }
  3892. };
  3893. this.document.head.appendChild($stylesheet);
  3894. }.bind(this));
  3895. }
  3896. /**
  3897. * Append stylesheet rules to a generate stylesheet
  3898. * Array: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule
  3899. * Object: https://github.com/desirable-objects/json-to-css
  3900. * @param {array | object} rules
  3901. */
  3902. }, {
  3903. key: "addStylesheetRules",
  3904. value: function addStylesheetRules(rules) {
  3905. var styleEl;
  3906. var styleSheet;
  3907. var key = "epubjs-inserted-css";
  3908. if (!this.document || !rules || rules.length === 0) return;
  3909. // Check if link already exists
  3910. styleEl = this.document.getElementById("#" + key);
  3911. if (!styleEl) {
  3912. styleEl = this.document.createElement("style");
  3913. styleEl.id = key;
  3914. }
  3915. // Append style element to head
  3916. this.document.head.appendChild(styleEl);
  3917. // Grab style sheet
  3918. styleSheet = styleEl.sheet;
  3919. if (Object.prototype.toString.call(rules) === "[object Array]") {
  3920. for (var i = 0, rl = rules.length; i < rl; i++) {
  3921. var j = 1,
  3922. rule = rules[i],
  3923. selector = rules[i][0],
  3924. propStr = "";
  3925. // If the second argument of a rule is an array of arrays, correct our variables.
  3926. if (Object.prototype.toString.call(rule[1][0]) === "[object Array]") {
  3927. rule = rule[1];
  3928. j = 0;
  3929. }
  3930. for (var pl = rule.length; j < pl; j++) {
  3931. var prop = rule[j];
  3932. propStr += prop[0] + ":" + prop[1] + (prop[2] ? " !important" : "") + ";\n";
  3933. }
  3934. // Insert CSS Rule
  3935. styleSheet.insertRule(selector + "{" + propStr + "}", styleSheet.cssRules.length);
  3936. }
  3937. } else {
  3938. var selectors = Object.keys(rules);
  3939. selectors.forEach(function (selector) {
  3940. var definition = rules[selector];
  3941. if (Array.isArray(definition)) {
  3942. definition.forEach(function (item) {
  3943. var _rules = Object.keys(item);
  3944. var result = _rules.map(function (rule) {
  3945. return rule + ":" + item[rule];
  3946. }).join(';');
  3947. styleSheet.insertRule(selector + "{" + result + "}", styleSheet.cssRules.length);
  3948. });
  3949. } else {
  3950. var _rules = Object.keys(definition);
  3951. var result = _rules.map(function (rule) {
  3952. return rule + ":" + definition[rule];
  3953. }).join(';');
  3954. styleSheet.insertRule(selector + "{" + result + "}", styleSheet.cssRules.length);
  3955. }
  3956. });
  3957. }
  3958. }
  3959. /**
  3960. * Append a script tag to the document head
  3961. * @param {string} src url
  3962. * @returns {Promise} loaded
  3963. */
  3964. }, {
  3965. key: "addScript",
  3966. value: function addScript(src) {
  3967. return new Promise(function (resolve, reject) {
  3968. var $script;
  3969. var ready = false;
  3970. if (!this.document) {
  3971. resolve(false);
  3972. return;
  3973. }
  3974. $script = this.document.createElement("script");
  3975. $script.type = "text/javascript";
  3976. $script.async = true;
  3977. $script.src = src;
  3978. $script.onload = $script.onreadystatechange = function () {
  3979. if (!ready && (!this.readyState || this.readyState == "complete")) {
  3980. ready = true;
  3981. setTimeout(function () {
  3982. resolve(true);
  3983. }, 1);
  3984. }
  3985. };
  3986. this.document.head.appendChild($script);
  3987. }.bind(this));
  3988. }
  3989. /**
  3990. * Add a class to the contents container
  3991. * @param {string} className
  3992. */
  3993. }, {
  3994. key: "addClass",
  3995. value: function addClass(className) {
  3996. var content;
  3997. if (!this.document) return;
  3998. content = this.content || this.document.body;
  3999. if (content) {
  4000. content.classList.add(className);
  4001. }
  4002. }
  4003. /**
  4004. * Remove a class from the contents container
  4005. * @param {string} removeClass
  4006. */
  4007. }, {
  4008. key: "removeClass",
  4009. value: function removeClass(className) {
  4010. var content;
  4011. if (!this.document) return;
  4012. content = this.content || this.document.body;
  4013. if (content) {
  4014. content.classList.remove(className);
  4015. }
  4016. }
  4017. /**
  4018. * Add DOM event listeners
  4019. * @private
  4020. */
  4021. }, {
  4022. key: "addEventListeners",
  4023. value: function addEventListeners() {
  4024. if (!this.document) {
  4025. return;
  4026. }
  4027. _constants.DOM_EVENTS.forEach(function (eventName) {
  4028. this.document.addEventListener(eventName, this.triggerEvent.bind(this), false);
  4029. }, this);
  4030. }
  4031. /**
  4032. * Remove DOM event listeners
  4033. * @private
  4034. */
  4035. }, {
  4036. key: "removeEventListeners",
  4037. value: function removeEventListeners() {
  4038. if (!this.document) {
  4039. return;
  4040. }
  4041. _constants.DOM_EVENTS.forEach(function (eventName) {
  4042. this.document.removeEventListener(eventName, this.triggerEvent, false);
  4043. }, this);
  4044. }
  4045. /**
  4046. * Emit passed browser events
  4047. * @private
  4048. */
  4049. }, {
  4050. key: "triggerEvent",
  4051. value: function triggerEvent(e) {
  4052. this.emit(e.type, e);
  4053. }
  4054. /**
  4055. * Add listener for text selection
  4056. * @private
  4057. */
  4058. }, {
  4059. key: "addSelectionListeners",
  4060. value: function addSelectionListeners() {
  4061. if (!this.document) {
  4062. return;
  4063. }
  4064. this.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false);
  4065. }
  4066. /**
  4067. * Remove listener for text selection
  4068. * @private
  4069. */
  4070. }, {
  4071. key: "removeSelectionListeners",
  4072. value: function removeSelectionListeners() {
  4073. if (!this.document) {
  4074. return;
  4075. }
  4076. this.document.removeEventListener("selectionchange", this.onSelectionChange, false);
  4077. }
  4078. /**
  4079. * Handle getting text on selection
  4080. * @private
  4081. */
  4082. }, {
  4083. key: "onSelectionChange",
  4084. value: function onSelectionChange(e) {
  4085. if (this.selectionEndTimeout) {
  4086. clearTimeout(this.selectionEndTimeout);
  4087. }
  4088. this.selectionEndTimeout = setTimeout(function () {
  4089. var selection = this.window.getSelection();
  4090. this.triggerSelectedEvent(selection);
  4091. }.bind(this), 250);
  4092. }
  4093. /**
  4094. * Emit event on text selection
  4095. * @private
  4096. */
  4097. }, {
  4098. key: "triggerSelectedEvent",
  4099. value: function triggerSelectedEvent(selection) {
  4100. var range, cfirange;
  4101. if (selection && selection.rangeCount > 0) {
  4102. range = selection.getRangeAt(0);
  4103. if (!range.collapsed) {
  4104. // cfirange = this.section.cfiFromRange(range);
  4105. cfirange = new _epubcfi2.default(range, this.cfiBase).toString();
  4106. this.emit(_constants.EVENTS.CONTENTS.SELECTED, cfirange);
  4107. this.emit(_constants.EVENTS.CONTENTS.SELECTED_RANGE, range);
  4108. }
  4109. }
  4110. }
  4111. /**
  4112. * Get a Dom Range from EpubCFI
  4113. * @param {EpubCFI} _cfi
  4114. * @param {string} [ignoreClass]
  4115. * @returns {Range} range
  4116. */
  4117. }, {
  4118. key: "range",
  4119. value: function range(_cfi, ignoreClass) {
  4120. var cfi = new _epubcfi2.default(_cfi);
  4121. return cfi.toRange(this.document, ignoreClass);
  4122. }
  4123. /**
  4124. * Get an EpubCFI from a Dom Range
  4125. * @param {Range} range
  4126. * @param {string} [ignoreClass]
  4127. * @returns {EpubCFI} cfi
  4128. */
  4129. }, {
  4130. key: "cfiFromRange",
  4131. value: function cfiFromRange(range, ignoreClass) {
  4132. return new _epubcfi2.default(range, this.cfiBase, ignoreClass).toString();
  4133. }
  4134. /**
  4135. * Get an EpubCFI from a Dom node
  4136. * @param {node} node
  4137. * @param {string} [ignoreClass]
  4138. * @returns {EpubCFI} cfi
  4139. */
  4140. }, {
  4141. key: "cfiFromNode",
  4142. value: function cfiFromNode(node, ignoreClass) {
  4143. return new _epubcfi2.default(node, this.cfiBase, ignoreClass).toString();
  4144. }
  4145. // TODO: find where this is used - remove?
  4146. }, {
  4147. key: "map",
  4148. value: function map(layout) {
  4149. var map = new _mapping2.default(layout);
  4150. return map.section();
  4151. }
  4152. /**
  4153. * Size the contents to a given width and height
  4154. * @param {number} [width]
  4155. * @param {number} [height]
  4156. */
  4157. }, {
  4158. key: "size",
  4159. value: function size(width, height) {
  4160. var viewport = { scale: 1.0, scalable: "no" };
  4161. this.layoutStyle("scrolling");
  4162. if (width >= 0) {
  4163. this.width(width);
  4164. viewport.width = width;
  4165. this.css("padding", "0 " + width / 12 + "px");
  4166. }
  4167. if (height >= 0) {
  4168. this.height(height);
  4169. viewport.height = height;
  4170. }
  4171. this.css("margin", "0");
  4172. this.css("box-sizing", "border-box");
  4173. this.viewport(viewport);
  4174. }
  4175. /**
  4176. * Apply columns to the contents for pagination
  4177. * @param {number} width
  4178. * @param {number} height
  4179. * @param {number} columnWidth
  4180. * @param {number} gap
  4181. */
  4182. }, {
  4183. key: "columns",
  4184. value: function columns(width, height, columnWidth, gap) {
  4185. var COLUMN_AXIS = (0, _core.prefixed)("column-axis");
  4186. var COLUMN_GAP = (0, _core.prefixed)("column-gap");
  4187. var COLUMN_WIDTH = (0, _core.prefixed)("column-width");
  4188. var COLUMN_FILL = (0, _core.prefixed)("column-fill");
  4189. var writingMode = this.writingMode();
  4190. var axis = writingMode.indexOf("vertical") === 0 ? "vertical" : "horizontal";
  4191. this.layoutStyle("paginated");
  4192. // Fix body width issues if rtl is only set on body element
  4193. if (this.content.dir === "rtl") {
  4194. this.direction("rtl");
  4195. }
  4196. this.width(width);
  4197. this.height(height);
  4198. // Deal with Mobile trying to scale to viewport
  4199. this.viewport({ width: width, height: height, scale: 1.0, scalable: "no" });
  4200. // TODO: inline-block needs more testing
  4201. // Fixes Safari column cut offs, but causes RTL issues
  4202. // this.css("display", "inline-block");
  4203. this.css("overflow-y", "hidden");
  4204. this.css("margin", "0", true);
  4205. if (axis === "vertical") {
  4206. this.css("padding-top", gap / 2 + "px", true);
  4207. this.css("padding-bottom", gap / 2 + "px", true);
  4208. this.css("padding-left", "20px");
  4209. this.css("padding-right", "20px");
  4210. } else {
  4211. this.css("padding-top", "20px");
  4212. this.css("padding-bottom", "20px");
  4213. this.css("padding-left", gap / 2 + "px", true);
  4214. this.css("padding-right", gap / 2 + "px", true);
  4215. }
  4216. this.css("box-sizing", "border-box");
  4217. this.css("max-width", "inherit");
  4218. this.css(COLUMN_AXIS, "horizontal");
  4219. this.css(COLUMN_FILL, "auto");
  4220. this.css(COLUMN_GAP, gap + "px");
  4221. this.css(COLUMN_WIDTH, columnWidth + "px");
  4222. }
  4223. /**
  4224. * Scale contents from center
  4225. * @param {number} scale
  4226. * @param {number} offsetX
  4227. * @param {number} offsetY
  4228. */
  4229. }, {
  4230. key: "scaler",
  4231. value: function scaler(scale, offsetX, offsetY) {
  4232. var scaleStr = "scale(" + scale + ")";
  4233. var translateStr = "";
  4234. // this.css("position", "absolute"));
  4235. this.css("transform-origin", "top left");
  4236. if (offsetX >= 0 || offsetY >= 0) {
  4237. translateStr = " translate(" + (offsetX || 0) + "px, " + (offsetY || 0) + "px )";
  4238. }
  4239. this.css("transform", scaleStr + translateStr);
  4240. }
  4241. /**
  4242. * Fit contents into a fixed width and height
  4243. * @param {number} width
  4244. * @param {number} height
  4245. */
  4246. }, {
  4247. key: "fit",
  4248. value: function fit(width, height) {
  4249. var viewport = this.viewport();
  4250. var widthScale = width / parseInt(viewport.width);
  4251. var heightScale = height / parseInt(viewport.height);
  4252. var scale = widthScale < heightScale ? widthScale : heightScale;
  4253. var offsetY = (height - viewport.height * scale) / 2;
  4254. this.layoutStyle("paginated");
  4255. this.width(width);
  4256. this.height(height);
  4257. this.overflow("hidden");
  4258. // Scale to the correct size
  4259. this.scaler(scale, 0, offsetY);
  4260. this.css("background-color", "transparent");
  4261. }
  4262. /**
  4263. * Set the direction of the text
  4264. * @param {string} [dir="ltr"] "rtl" | "ltr"
  4265. */
  4266. }, {
  4267. key: "direction",
  4268. value: function direction(dir) {
  4269. if (this.documentElement) {
  4270. this.documentElement.style["direction"] = dir;
  4271. }
  4272. }
  4273. }, {
  4274. key: "mapPage",
  4275. value: function mapPage(cfiBase, layout, start, end, dev) {
  4276. var mapping = new _mapping2.default(layout, dev);
  4277. return mapping.page(this, cfiBase, start, end);
  4278. }
  4279. /**
  4280. * Emit event when link in content is clicked
  4281. * @private
  4282. */
  4283. }, {
  4284. key: "linksHandler",
  4285. value: function linksHandler() {
  4286. var _this2 = this;
  4287. (0, _replacements.replaceLinks)(this.content, function (href) {
  4288. _this2.emit(_constants.EVENTS.CONTENTS.LINK_CLICKED, href);
  4289. });
  4290. }
  4291. /**
  4292. * Set the writingMode of the text
  4293. * @param {string} [mode="horizontal-tb"] "horizontal-tb" | "vertical-rl" | "vertical-lr"
  4294. */
  4295. }, {
  4296. key: "writingMode",
  4297. value: function writingMode(mode) {
  4298. var WRITING_MODE = (0, _core.prefixed)("writing-mode");
  4299. if (mode && this.documentElement) {
  4300. this.documentElement.style[WRITING_MODE] = mode;
  4301. }
  4302. return this.window.getComputedStyle(this.documentElement)[WRITING_MODE] || '';
  4303. }
  4304. /**
  4305. * Set the layoutStyle of the content
  4306. * @param {string} [style="paginated"] "scrolling" | "paginated"
  4307. * @private
  4308. */
  4309. }, {
  4310. key: "layoutStyle",
  4311. value: function layoutStyle(style) {
  4312. if (style) {
  4313. this._layoutStyle = style;
  4314. navigator.epubReadingSystem.layoutStyle = this._layoutStyle;
  4315. }
  4316. return this._layoutStyle || "paginated";
  4317. }
  4318. /**
  4319. * Add the epubReadingSystem object to the navigator
  4320. * @param {string} name
  4321. * @param {string} version
  4322. * @private
  4323. */
  4324. }, {
  4325. key: "epubReadingSystem",
  4326. value: function epubReadingSystem(name, version) {
  4327. navigator.epubReadingSystem = {
  4328. name: name,
  4329. version: version,
  4330. layoutStyle: this.layoutStyle(),
  4331. hasFeature: function hasFeature(feature) {
  4332. switch (feature) {
  4333. case "dom-manipulation":
  4334. return true;
  4335. case "layout-changes":
  4336. return true;
  4337. case "touch-events":
  4338. return true;
  4339. case "mouse-events":
  4340. return true;
  4341. case "keyboard-events":
  4342. return true;
  4343. case "spine-scripting":
  4344. return false;
  4345. default:
  4346. return false;
  4347. }
  4348. }
  4349. };
  4350. return navigator.epubReadingSystem;
  4351. }
  4352. }, {
  4353. key: "destroy",
  4354. value: function destroy() {
  4355. // Stop observing
  4356. if (this.observer) {
  4357. this.observer.disconnect();
  4358. }
  4359. this.document.removeEventListener('transitionend', this.resizeCheck);
  4360. this.removeListeners();
  4361. }
  4362. }], [{
  4363. key: "listenedEvents",
  4364. get: function get() {
  4365. return _constants.DOM_EVENTS;
  4366. }
  4367. }]);
  4368. return Contents;
  4369. }();
  4370. (0, _eventEmitter2.default)(Contents.prototype);
  4371. exports.default = Contents;
  4372. module.exports = exports["default"];
  4373. /***/ }),
  4374. /* 14 */
  4375. /***/ (function(module, exports, __webpack_require__) {
  4376. "use strict";
  4377. Object.defineProperty(exports, "__esModule", {
  4378. value: true
  4379. });
  4380. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  4381. var _eventEmitter = __webpack_require__(3);
  4382. var _eventEmitter2 = _interopRequireDefault(_eventEmitter);
  4383. var _core = __webpack_require__(0);
  4384. var _mapping = __webpack_require__(19);
  4385. var _mapping2 = _interopRequireDefault(_mapping);
  4386. var _queue = __webpack_require__(12);
  4387. var _queue2 = _interopRequireDefault(_queue);
  4388. var _stage = __webpack_require__(59);
  4389. var _stage2 = _interopRequireDefault(_stage);
  4390. var _views = __webpack_require__(69);
  4391. var _views2 = _interopRequireDefault(_views);
  4392. var _constants = __webpack_require__(2);
  4393. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4394. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4395. var DefaultViewManager = function () {
  4396. function DefaultViewManager(options) {
  4397. _classCallCheck(this, DefaultViewManager);
  4398. this.name = "default";
  4399. this.optsSettings = options.settings;
  4400. this.View = options.view;
  4401. this.request = options.request;
  4402. this.renditionQueue = options.queue;
  4403. this.q = new _queue2.default(this);
  4404. this.settings = (0, _core.extend)(this.settings || {}, {
  4405. infinite: true,
  4406. hidden: false,
  4407. width: undefined,
  4408. height: undefined,
  4409. axis: undefined,
  4410. flow: "scrolled",
  4411. ignoreClass: "",
  4412. fullsize: undefined
  4413. });
  4414. (0, _core.extend)(this.settings, options.settings || {});
  4415. this.viewSettings = {
  4416. ignoreClass: this.settings.ignoreClass,
  4417. axis: this.settings.axis,
  4418. flow: this.settings.flow,
  4419. layout: this.layout,
  4420. method: this.settings.method, // srcdoc, blobUrl, write
  4421. width: 0,
  4422. height: 0,
  4423. forceEvenPages: true
  4424. };
  4425. this.rendered = false;
  4426. }
  4427. _createClass(DefaultViewManager, [{
  4428. key: "render",
  4429. value: function render(element, size) {
  4430. var tag = element.tagName;
  4431. if (typeof this.settings.fullsize === "undefined" && tag && (tag.toLowerCase() == "body" || tag.toLowerCase() == "html")) {
  4432. this.settings.fullsize = true;
  4433. }
  4434. if (this.settings.fullsize) {
  4435. this.settings.overflow = "visible";
  4436. this.overflow = this.settings.overflow;
  4437. }
  4438. this.settings.size = size;
  4439. // Save the stage
  4440. this.stage = new _stage2.default({
  4441. width: size.width,
  4442. height: size.height,
  4443. overflow: this.overflow,
  4444. hidden: this.settings.hidden,
  4445. axis: this.settings.axis,
  4446. fullsize: this.settings.fullsize,
  4447. direction: this.settings.direction
  4448. });
  4449. this.stage.attachTo(element);
  4450. // Get this stage container div
  4451. this.container = this.stage.getContainer();
  4452. // Views array methods
  4453. this.views = new _views2.default(this.container);
  4454. // Calculate Stage Size
  4455. this._bounds = this.bounds();
  4456. this._stageSize = this.stage.size();
  4457. // Set the dimensions for views
  4458. this.viewSettings.width = this._stageSize.width;
  4459. this.viewSettings.height = this._stageSize.height;
  4460. // Function to handle a resize event.
  4461. // Will only attach if width and height are both fixed.
  4462. this.stage.onResize(this.onResized.bind(this));
  4463. this.stage.onOrientationChange(this.onOrientationChange.bind(this));
  4464. // Add Event Listeners
  4465. this.addEventListeners();
  4466. // Add Layout method
  4467. // this.applyLayoutMethod();
  4468. if (this.layout) {
  4469. this.updateLayout();
  4470. }
  4471. this.rendered = true;
  4472. }
  4473. }, {
  4474. key: "addEventListeners",
  4475. value: function addEventListeners() {
  4476. var scroller;
  4477. window.addEventListener("unload", function (e) {
  4478. this.destroy();
  4479. }.bind(this));
  4480. if (!this.settings.fullsize) {
  4481. scroller = this.container;
  4482. } else {
  4483. scroller = window;
  4484. }
  4485. scroller.addEventListener("scroll", this.onScroll.bind(this));
  4486. }
  4487. }, {
  4488. key: "removeEventListeners",
  4489. value: function removeEventListeners() {
  4490. var scroller;
  4491. if (!this.settings.fullsize) {
  4492. scroller = this.container;
  4493. } else {
  4494. scroller = window;
  4495. }
  4496. scroller.removeEventListener("scroll", this.onScroll.bind(this));
  4497. }
  4498. }, {
  4499. key: "destroy",
  4500. value: function destroy() {
  4501. clearTimeout(this.orientationTimeout);
  4502. clearTimeout(this.resizeTimeout);
  4503. clearTimeout(this.afterScrolled);
  4504. this.clear();
  4505. this.removeEventListeners();
  4506. this.stage.destroy();
  4507. this.rendered = false;
  4508. /*
  4509. clearTimeout(this.trimTimeout);
  4510. if(this.settings.hidden) {
  4511. this.element.removeChild(this.wrapper);
  4512. } else {
  4513. this.element.removeChild(this.container);
  4514. }
  4515. */
  4516. }
  4517. }, {
  4518. key: "onOrientationChange",
  4519. value: function onOrientationChange(e) {
  4520. var _window = window,
  4521. orientation = _window.orientation;
  4522. if (this.optsSettings.resizeOnOrientationChange) {
  4523. this.resize();
  4524. }
  4525. // Per ampproject:
  4526. // In IOS 10.3, the measured size of an element is incorrect if the
  4527. // element size depends on window size directly and the measurement
  4528. // happens in window.resize event. Adding a timeout for correct
  4529. // measurement. See https://github.com/ampproject/amphtml/issues/8479
  4530. clearTimeout(this.orientationTimeout);
  4531. this.orientationTimeout = setTimeout(function () {
  4532. this.orientationTimeout = undefined;
  4533. if (this.optsSettings.resizeOnOrientationChange) {
  4534. this.resize();
  4535. }
  4536. this.emit(_constants.EVENTS.MANAGERS.ORIENTATION_CHANGE, orientation);
  4537. }.bind(this), 500);
  4538. }
  4539. }, {
  4540. key: "onResized",
  4541. value: function onResized(e) {
  4542. this.resize();
  4543. }
  4544. }, {
  4545. key: "resize",
  4546. value: function resize(width, height) {
  4547. var stageSize = this.stage.size(width, height);
  4548. // For Safari, wait for orientation to catch up
  4549. // if the window is a square
  4550. this.winBounds = (0, _core.windowBounds)();
  4551. if (this.orientationTimeout && this.winBounds.width === this.winBounds.height) {
  4552. // reset the stage size for next resize
  4553. this._stageSize = undefined;
  4554. return;
  4555. }
  4556. if (this._stageSize && this._stageSize.width === stageSize.width && this._stageSize.height === stageSize.height) {
  4557. // Size is the same, no need to resize
  4558. return;
  4559. }
  4560. this._stageSize = stageSize;
  4561. this._bounds = this.bounds();
  4562. // Clear current views
  4563. this.clear();
  4564. // Update for new views
  4565. this.viewSettings.width = this._stageSize.width;
  4566. this.viewSettings.height = this._stageSize.height;
  4567. this.updateLayout();
  4568. this.emit(_constants.EVENTS.MANAGERS.RESIZED, {
  4569. width: this._stageSize.width,
  4570. height: this._stageSize.height
  4571. });
  4572. }
  4573. }, {
  4574. key: "createView",
  4575. value: function createView(section) {
  4576. return new this.View(section, this.viewSettings);
  4577. }
  4578. }, {
  4579. key: "display",
  4580. value: function display(section, target) {
  4581. var displaying = new _core.defer();
  4582. var displayed = displaying.promise;
  4583. // Check if moving to target is needed
  4584. if (target === section.href || (0, _core.isNumber)(target)) {
  4585. target = undefined;
  4586. }
  4587. // Check to make sure the section we want isn't already shown
  4588. var visible = this.views.find(section);
  4589. // View is already shown, just move to correct location in view
  4590. if (visible && section) {
  4591. var offset = visible.offset();
  4592. if (this.settings.direction === "ltr") {
  4593. this.scrollTo(offset.left, offset.top, true);
  4594. } else {
  4595. var width = visible.width();
  4596. this.scrollTo(offset.left + width, offset.top, true);
  4597. }
  4598. if (target) {
  4599. var _offset = visible.locationOf(target);
  4600. this.moveTo(_offset);
  4601. }
  4602. displaying.resolve();
  4603. return displayed;
  4604. }
  4605. // Hide all current views
  4606. this.clear();
  4607. this.add(section).then(function (view) {
  4608. // Move to correct place within the section, if needed
  4609. if (target) {
  4610. var _offset2 = view.locationOf(target);
  4611. this.moveTo(_offset2);
  4612. }
  4613. }.bind(this), function (err) {
  4614. displaying.reject(err);
  4615. }).then(function () {
  4616. var next;
  4617. if (this.layout.name === "pre-paginated" && this.layout.divisor > 1) {
  4618. next = section.next();
  4619. if (next) {
  4620. return this.add(next);
  4621. }
  4622. }
  4623. }.bind(this)).then(function () {
  4624. this.views.show();
  4625. displaying.resolve();
  4626. }.bind(this));
  4627. // .then(function(){
  4628. // return this.hooks.display.trigger(view);
  4629. // }.bind(this))
  4630. // .then(function(){
  4631. // this.views.show();
  4632. // }.bind(this));
  4633. return displayed;
  4634. }
  4635. }, {
  4636. key: "afterDisplayed",
  4637. value: function afterDisplayed(view) {
  4638. this.emit(_constants.EVENTS.MANAGERS.ADDED, view);
  4639. }
  4640. }, {
  4641. key: "afterResized",
  4642. value: function afterResized(view) {
  4643. this.emit(_constants.EVENTS.MANAGERS.RESIZE, view.section);
  4644. }
  4645. }, {
  4646. key: "moveTo",
  4647. value: function moveTo(offset) {
  4648. var distX = 0,
  4649. distY = 0;
  4650. if (!this.isPaginated) {
  4651. distY = offset.top;
  4652. } else {
  4653. distX = Math.floor(offset.left / this.layout.delta) * this.layout.delta;
  4654. if (distX + this.layout.delta > this.container.scrollWidth) {
  4655. distX = this.container.scrollWidth - this.layout.delta;
  4656. }
  4657. }
  4658. this.scrollTo(distX, distY, true);
  4659. }
  4660. }, {
  4661. key: "add",
  4662. value: function add(section) {
  4663. var _this = this;
  4664. var view = this.createView(section);
  4665. this.views.append(view);
  4666. // view.on(EVENTS.VIEWS.SHOWN, this.afterDisplayed.bind(this));
  4667. view.onDisplayed = this.afterDisplayed.bind(this);
  4668. view.onResize = this.afterResized.bind(this);
  4669. view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) {
  4670. _this.updateAxis(axis);
  4671. });
  4672. return view.display(this.request);
  4673. }
  4674. }, {
  4675. key: "append",
  4676. value: function append(section) {
  4677. var _this2 = this;
  4678. var view = this.createView(section);
  4679. this.views.append(view);
  4680. view.onDisplayed = this.afterDisplayed.bind(this);
  4681. view.onResize = this.afterResized.bind(this);
  4682. view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) {
  4683. _this2.updateAxis(axis);
  4684. });
  4685. return view.display(this.request);
  4686. }
  4687. }, {
  4688. key: "prepend",
  4689. value: function prepend(section) {
  4690. var _this3 = this;
  4691. var view = this.createView(section);
  4692. view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) {
  4693. _this3.counter(bounds);
  4694. });
  4695. this.views.prepend(view);
  4696. view.onDisplayed = this.afterDisplayed.bind(this);
  4697. view.onResize = this.afterResized.bind(this);
  4698. view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) {
  4699. _this3.updateAxis(axis);
  4700. });
  4701. return view.display(this.request);
  4702. }
  4703. }, {
  4704. key: "counter",
  4705. value: function counter(bounds) {
  4706. if (this.settings.axis === "vertical") {
  4707. this.scrollBy(0, bounds.heightDelta, true);
  4708. } else {
  4709. this.scrollBy(bounds.widthDelta, 0, true);
  4710. }
  4711. }
  4712. // resizeView(view) {
  4713. //
  4714. // if(this.settings.globalLayoutProperties.layout === "pre-paginated") {
  4715. // view.lock("both", this.bounds.width, this.bounds.height);
  4716. // } else {
  4717. // view.lock("width", this.bounds.width, this.bounds.height);
  4718. // }
  4719. //
  4720. // };
  4721. }, {
  4722. key: "next",
  4723. value: function next() {
  4724. var next;
  4725. var left;
  4726. var dir = this.settings.direction;
  4727. if (!this.views.length) return;
  4728. if (this.isPaginated && this.settings.axis === "horizontal" && (!dir || dir === "ltr")) {
  4729. this.scrollLeft = this.container.scrollLeft;
  4730. left = this.container.scrollLeft + this.container.offsetWidth + this.layout.delta;
  4731. if (left <= this.container.scrollWidth) {
  4732. this.scrollBy(this.layout.delta, 0, true);
  4733. } else {
  4734. next = this.views.last().section.next();
  4735. }
  4736. } else if (this.isPaginated && this.settings.axis === "horizontal" && dir === "rtl") {
  4737. this.scrollLeft = this.container.scrollLeft;
  4738. left = this.container.scrollLeft;
  4739. if (left > 0) {
  4740. this.scrollBy(this.layout.delta, 0, true);
  4741. } else {
  4742. next = this.views.last().section.next();
  4743. }
  4744. } else if (this.isPaginated && this.settings.axis === "vertical") {
  4745. this.scrollTop = this.container.scrollTop;
  4746. var top = this.container.scrollTop + this.container.offsetHeight;
  4747. if (top < this.container.scrollHeight) {
  4748. this.scrollBy(0, this.layout.height, true);
  4749. } else {
  4750. next = this.views.last().section.next();
  4751. }
  4752. } else {
  4753. next = this.views.last().section.next();
  4754. }
  4755. if (next) {
  4756. this.clear();
  4757. return this.append(next).then(function () {
  4758. var right;
  4759. if (this.layout.name === "pre-paginated" && this.layout.divisor > 1) {
  4760. right = next.next();
  4761. if (right) {
  4762. return this.append(right);
  4763. }
  4764. }
  4765. }.bind(this), function (err) {
  4766. displaying.reject(err);
  4767. }).then(function () {
  4768. this.views.show();
  4769. }.bind(this));
  4770. }
  4771. }
  4772. }, {
  4773. key: "prev",
  4774. value: function prev() {
  4775. var prev;
  4776. var left;
  4777. var dir = this.settings.direction;
  4778. if (!this.views.length) return;
  4779. if (this.isPaginated && this.settings.axis === "horizontal" && (!dir || dir === "ltr")) {
  4780. this.scrollLeft = this.container.scrollLeft;
  4781. left = this.container.scrollLeft;
  4782. if (left > 0) {
  4783. this.scrollBy(-this.layout.delta, 0, true);
  4784. } else {
  4785. prev = this.views.first().section.prev();
  4786. }
  4787. } else if (this.isPaginated && this.settings.axis === "horizontal" && dir === "rtl") {
  4788. this.scrollLeft = this.container.scrollLeft;
  4789. left = this.container.scrollLeft + this.container.offsetWidth + this.layout.delta;
  4790. if (left <= this.container.scrollWidth) {
  4791. this.scrollBy(-this.layout.delta, 0, true);
  4792. } else {
  4793. prev = this.views.first().section.prev();
  4794. }
  4795. } else if (this.isPaginated && this.settings.axis === "vertical") {
  4796. this.scrollTop = this.container.scrollTop;
  4797. var top = this.container.scrollTop;
  4798. if (top > 0) {
  4799. this.scrollBy(0, -this.layout.height, true);
  4800. } else {
  4801. prev = this.views.first().section.prev();
  4802. }
  4803. } else {
  4804. prev = this.views.first().section.prev();
  4805. }
  4806. if (prev) {
  4807. this.clear();
  4808. return this.prepend(prev).then(function () {
  4809. var left;
  4810. if (this.layout.name === "pre-paginated" && this.layout.divisor > 1) {
  4811. left = prev.prev();
  4812. if (left) {
  4813. return this.prepend(left);
  4814. }
  4815. }
  4816. }.bind(this), function (err) {
  4817. displaying.reject(err);
  4818. }).then(function () {
  4819. if (this.isPaginated && this.settings.axis === "horizontal") {
  4820. if (this.settings.direction === "rtl") {
  4821. this.scrollTo(0, 0, true);
  4822. } else {
  4823. this.scrollTo(this.container.scrollWidth - this.layout.delta, 0, true);
  4824. }
  4825. }
  4826. this.views.show();
  4827. }.bind(this));
  4828. }
  4829. }
  4830. }, {
  4831. key: "current",
  4832. value: function current() {
  4833. var visible = this.visible();
  4834. if (visible.length) {
  4835. // Current is the last visible view
  4836. return visible[visible.length - 1];
  4837. }
  4838. return null;
  4839. }
  4840. }, {
  4841. key: "clear",
  4842. value: function clear() {
  4843. // this.q.clear();
  4844. if (this.views) {
  4845. this.views.hide();
  4846. this.scrollTo(0, 0, true);
  4847. this.views.clear();
  4848. }
  4849. }
  4850. }, {
  4851. key: "currentLocation",
  4852. value: function currentLocation() {
  4853. if (this.settings.axis === "vertical") {
  4854. this.location = this.scrolledLocation();
  4855. } else {
  4856. this.location = this.paginatedLocation();
  4857. }
  4858. return this.location;
  4859. }
  4860. }, {
  4861. key: "scrolledLocation",
  4862. value: function scrolledLocation() {
  4863. var _this4 = this;
  4864. var visible = this.visible();
  4865. var container = this.container.getBoundingClientRect();
  4866. var pageHeight = container.height < window.innerHeight ? container.height : window.innerHeight;
  4867. var offset = 0;
  4868. var used = 0;
  4869. if (this.settings.fullsize) {
  4870. offset = window.scrollY;
  4871. }
  4872. var sections = visible.map(function (view) {
  4873. var _view$section = view.section,
  4874. index = _view$section.index,
  4875. href = _view$section.href;
  4876. var position = view.position();
  4877. var height = view.height();
  4878. var startPos = offset + container.top - position.top + used;
  4879. var endPos = startPos + pageHeight - used;
  4880. if (endPos > height) {
  4881. endPos = height;
  4882. used = endPos - startPos;
  4883. }
  4884. var totalPages = _this4.layout.count(height, pageHeight).pages;
  4885. var currPage = Math.ceil(startPos / pageHeight);
  4886. var pages = [];
  4887. var endPage = Math.ceil(endPos / pageHeight);
  4888. pages = [];
  4889. for (var i = currPage; i <= endPage; i++) {
  4890. var pg = i + 1;
  4891. pages.push(pg);
  4892. }
  4893. var mapping = _this4.mapping.page(view.contents, view.section.cfiBase, startPos, endPos);
  4894. return {
  4895. index: index,
  4896. href: href,
  4897. pages: pages,
  4898. totalPages: totalPages,
  4899. mapping: mapping
  4900. };
  4901. });
  4902. return sections;
  4903. }
  4904. }, {
  4905. key: "paginatedLocation",
  4906. value: function paginatedLocation() {
  4907. var _this5 = this;
  4908. var visible = this.visible();
  4909. var container = this.container.getBoundingClientRect();
  4910. var left = 0;
  4911. var used = 0;
  4912. if (this.settings.fullsize) {
  4913. left = window.scrollX;
  4914. }
  4915. var sections = visible.map(function (view) {
  4916. var _view$section2 = view.section,
  4917. index = _view$section2.index,
  4918. href = _view$section2.href;
  4919. var offset = view.offset().left;
  4920. var position = view.position().left;
  4921. var width = view.width();
  4922. // Find mapping
  4923. var start = left + container.left - position + used;
  4924. var end = start + _this5.layout.width - used;
  4925. var mapping = _this5.mapping.page(view.contents, view.section.cfiBase, start, end);
  4926. // Find displayed pages
  4927. //console.log("pre", end, offset + width);
  4928. // if (end > offset + width) {
  4929. // end = offset + width;
  4930. // used = this.layout.pageWidth;
  4931. // }
  4932. // console.log("post", end);
  4933. var totalPages = _this5.layout.count(width).pages;
  4934. var startPage = Math.floor(start / _this5.layout.pageWidth);
  4935. var pages = [];
  4936. var endPage = Math.floor(end / _this5.layout.pageWidth);
  4937. // start page should not be negative
  4938. if (startPage < 0) {
  4939. startPage = 0;
  4940. endPage = endPage + 1;
  4941. }
  4942. // Reverse page counts for rtl
  4943. if (_this5.settings.direction === "rtl") {
  4944. var tempStartPage = startPage;
  4945. startPage = totalPages - endPage;
  4946. endPage = totalPages - tempStartPage;
  4947. }
  4948. for (var i = startPage + 1; i <= endPage; i++) {
  4949. var pg = i;
  4950. pages.push(pg);
  4951. }
  4952. return {
  4953. index: index,
  4954. href: href,
  4955. pages: pages,
  4956. totalPages: totalPages,
  4957. mapping: mapping
  4958. };
  4959. });
  4960. return sections;
  4961. }
  4962. }, {
  4963. key: "isVisible",
  4964. value: function isVisible(view, offsetPrev, offsetNext, _container) {
  4965. var position = view.position();
  4966. var container = _container || this.bounds();
  4967. if (this.settings.axis === "horizontal" && position.right > container.left - offsetPrev && position.left < container.right + offsetNext) {
  4968. return true;
  4969. } else if (this.settings.axis === "vertical" && position.bottom > container.top - offsetPrev && position.top < container.bottom + offsetNext) {
  4970. return true;
  4971. }
  4972. return false;
  4973. }
  4974. }, {
  4975. key: "visible",
  4976. value: function visible() {
  4977. var container = this.bounds();
  4978. var views = this.views.displayed();
  4979. var viewsLength = views.length;
  4980. var visible = [];
  4981. var isVisible;
  4982. var view;
  4983. for (var i = 0; i < viewsLength; i++) {
  4984. view = views[i];
  4985. isVisible = this.isVisible(view, 0, 0, container);
  4986. if (isVisible === true) {
  4987. visible.push(view);
  4988. }
  4989. }
  4990. return visible;
  4991. }
  4992. }, {
  4993. key: "scrollBy",
  4994. value: function scrollBy(x, y, silent) {
  4995. var dir = this.settings.direction === "rtl" ? -1 : 1;
  4996. if (silent) {
  4997. this.ignore = true;
  4998. }
  4999. if (!this.settings.fullsize) {
  5000. if (x) this.container.scrollLeft += x * dir;
  5001. if (y) this.container.scrollTop += y;
  5002. } else {
  5003. window.scrollBy(x * dir, y * dir);
  5004. }
  5005. this.scrolled = true;
  5006. }
  5007. }, {
  5008. key: "scrollTo",
  5009. value: function scrollTo(x, y, silent) {
  5010. if (silent) {
  5011. this.ignore = true;
  5012. }
  5013. if (!this.settings.fullsize) {
  5014. this.container.scrollLeft = x;
  5015. this.container.scrollTop = y;
  5016. } else {
  5017. window.scrollTo(x, y);
  5018. }
  5019. this.scrolled = true;
  5020. }
  5021. }, {
  5022. key: "onScroll",
  5023. value: function onScroll() {
  5024. var scrollTop = void 0;
  5025. var scrollLeft = void 0;
  5026. if (!this.settings.fullsize) {
  5027. scrollTop = this.container.scrollTop;
  5028. scrollLeft = this.container.scrollLeft;
  5029. } else {
  5030. scrollTop = window.scrollY;
  5031. scrollLeft = window.scrollX;
  5032. }
  5033. this.scrollTop = scrollTop;
  5034. this.scrollLeft = scrollLeft;
  5035. if (!this.ignore) {
  5036. this.emit(_constants.EVENTS.MANAGERS.SCROLL, {
  5037. top: scrollTop,
  5038. left: scrollLeft
  5039. });
  5040. clearTimeout(this.afterScrolled);
  5041. this.afterScrolled = setTimeout(function () {
  5042. this.emit(_constants.EVENTS.MANAGERS.SCROLLED, {
  5043. top: this.scrollTop,
  5044. left: this.scrollLeft
  5045. });
  5046. }.bind(this), 20);
  5047. } else {
  5048. this.ignore = false;
  5049. }
  5050. }
  5051. }, {
  5052. key: "bounds",
  5053. value: function bounds() {
  5054. var bounds;
  5055. bounds = this.stage.bounds();
  5056. return bounds;
  5057. }
  5058. }, {
  5059. key: "applyLayout",
  5060. value: function applyLayout(layout) {
  5061. this.layout = layout;
  5062. this.updateLayout();
  5063. // this.manager.layout(this.layout.format);
  5064. }
  5065. }, {
  5066. key: "updateLayout",
  5067. value: function updateLayout() {
  5068. if (!this.stage) {
  5069. return;
  5070. }
  5071. this._stageSize = this.stage.size();
  5072. if (!this.isPaginated) {
  5073. this.layout.calculate(this._stageSize.width, this._stageSize.height);
  5074. } else {
  5075. this.layout.calculate(this._stageSize.width, this._stageSize.height, this.settings.gap);
  5076. // Set the look ahead offset for what is visible
  5077. this.settings.offset = this.layout.delta;
  5078. // this.stage.addStyleRules("iframe", [{"margin-right" : this.layout.gap + "px"}]);
  5079. }
  5080. // Set the dimensions for views
  5081. this.viewSettings.width = this.layout.width;
  5082. this.viewSettings.height = this.layout.height;
  5083. this.setLayout(this.layout);
  5084. }
  5085. }, {
  5086. key: "setLayout",
  5087. value: function setLayout(layout) {
  5088. this.viewSettings.layout = layout;
  5089. this.mapping = new _mapping2.default(layout.props, this.settings.direction, this.settings.axis);
  5090. if (this.views) {
  5091. this.views.forEach(function (view) {
  5092. if (view) {
  5093. view.setLayout(layout);
  5094. }
  5095. });
  5096. }
  5097. }
  5098. }, {
  5099. key: "updateAxis",
  5100. value: function updateAxis(axis, forceUpdate) {
  5101. if (!this.isPaginated) {
  5102. axis = "vertical";
  5103. }
  5104. if (!forceUpdate && axis === this.settings.axis) {
  5105. return;
  5106. }
  5107. this.settings.axis = axis;
  5108. this.stage && this.stage.axis(axis);
  5109. this.viewSettings.axis = axis;
  5110. if (this.mapping) {
  5111. this.mapping = new _mapping2.default(this.layout.props, this.settings.direction, this.settings.axis);
  5112. }
  5113. if (this.layout) {
  5114. if (axis === "vertical") {
  5115. this.layout.spread("none");
  5116. } else {
  5117. this.layout.spread(this.layout.settings.spread);
  5118. }
  5119. }
  5120. }
  5121. }, {
  5122. key: "updateFlow",
  5123. value: function updateFlow(flow) {
  5124. var isPaginated = flow === "paginated" || flow === "auto";
  5125. this.isPaginated = isPaginated;
  5126. if (flow === "scrolled-doc" || flow === "scrolled-continuous" || flow === "scrolled") {
  5127. this.updateAxis("vertical");
  5128. }
  5129. this.viewSettings.flow = flow;
  5130. if (!this.settings.overflow) {
  5131. this.overflow = isPaginated ? "hidden" : "auto";
  5132. } else {
  5133. this.overflow = this.settings.overflow;
  5134. }
  5135. // this.views.forEach(function(view){
  5136. // view.setAxis(axis);
  5137. // });
  5138. this.updateLayout();
  5139. }
  5140. }, {
  5141. key: "getContents",
  5142. value: function getContents() {
  5143. var contents = [];
  5144. if (!this.views) {
  5145. return contents;
  5146. }
  5147. this.views.forEach(function (view) {
  5148. var viewContents = view && view.contents;
  5149. if (viewContents) {
  5150. contents.push(viewContents);
  5151. }
  5152. });
  5153. return contents;
  5154. }
  5155. }, {
  5156. key: "direction",
  5157. value: function direction() {
  5158. var dir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "ltr";
  5159. this.settings.direction = dir;
  5160. this.stage && this.stage.direction(dir);
  5161. this.viewSettings.direction = dir;
  5162. this.updateLayout();
  5163. }
  5164. }, {
  5165. key: "isRendered",
  5166. value: function isRendered() {
  5167. return this.rendered;
  5168. }
  5169. }]);
  5170. return DefaultViewManager;
  5171. }();
  5172. //-- Enable binding events to Manager
  5173. (0, _eventEmitter2.default)(DefaultViewManager.prototype);
  5174. exports.default = DefaultViewManager;
  5175. module.exports = exports["default"];
  5176. /***/ }),
  5177. /* 15 */
  5178. /***/ (function(module, exports) {
  5179. /**
  5180. * Checks if `value` is the
  5181. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  5182. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  5183. *
  5184. * @static
  5185. * @memberOf _
  5186. * @since 0.1.0
  5187. * @category Lang
  5188. * @param {*} value The value to check.
  5189. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  5190. * @example
  5191. *
  5192. * _.isObject({});
  5193. * // => true
  5194. *
  5195. * _.isObject([1, 2, 3]);
  5196. * // => true
  5197. *
  5198. * _.isObject(_.noop);
  5199. * // => true
  5200. *
  5201. * _.isObject(null);
  5202. * // => false
  5203. */
  5204. function isObject(value) {
  5205. var type = typeof value;
  5206. return value != null && (type == 'object' || type == 'function');
  5207. }
  5208. module.exports = isObject;
  5209. /***/ }),
  5210. /* 16 */
  5211. /***/ (function(module, exports) {
  5212. /*
  5213. * DOM Level 2
  5214. * Object DOMException
  5215. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  5216. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  5217. */
  5218. function copy(src,dest){
  5219. for(var p in src){
  5220. dest[p] = src[p];
  5221. }
  5222. }
  5223. /**
  5224. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  5225. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  5226. */
  5227. function _extends(Class,Super){
  5228. var pt = Class.prototype;
  5229. if(Object.create){
  5230. var ppt = Object.create(Super.prototype)
  5231. pt.__proto__ = ppt;
  5232. }
  5233. if(!(pt instanceof Super)){
  5234. function t(){};
  5235. t.prototype = Super.prototype;
  5236. t = new t();
  5237. copy(pt,t);
  5238. Class.prototype = pt = t;
  5239. }
  5240. if(pt.constructor != Class){
  5241. if(typeof Class != 'function'){
  5242. console.error("unknow Class:"+Class)
  5243. }
  5244. pt.constructor = Class
  5245. }
  5246. }
  5247. var htmlns = 'http://www.w3.org/1999/xhtml' ;
  5248. // Node Types
  5249. var NodeType = {}
  5250. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  5251. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  5252. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  5253. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  5254. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  5255. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  5256. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  5257. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  5258. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  5259. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  5260. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  5261. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  5262. // ExceptionCode
  5263. var ExceptionCode = {}
  5264. var ExceptionMessage = {};
  5265. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
  5266. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
  5267. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
  5268. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
  5269. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
  5270. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
  5271. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
  5272. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
  5273. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
  5274. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
  5275. //level2
  5276. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
  5277. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
  5278. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
  5279. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
  5280. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
  5281. function DOMException(code, message) {
  5282. if(message instanceof Error){
  5283. var error = message;
  5284. }else{
  5285. error = this;
  5286. Error.call(this, ExceptionMessage[code]);
  5287. this.message = ExceptionMessage[code];
  5288. if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  5289. }
  5290. error.code = code;
  5291. if(message) this.message = this.message + ": " + message;
  5292. return error;
  5293. };
  5294. DOMException.prototype = Error.prototype;
  5295. copy(ExceptionCode,DOMException)
  5296. /**
  5297. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  5298. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  5299. * The items in the NodeList are accessible via an integral index, starting from 0.
  5300. */
  5301. function NodeList() {
  5302. };
  5303. NodeList.prototype = {
  5304. /**
  5305. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  5306. * @standard level1
  5307. */
  5308. length:0,
  5309. /**
  5310. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  5311. * @standard level1
  5312. * @param index unsigned long
  5313. * Index into the collection.
  5314. * @return Node
  5315. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  5316. */
  5317. item: function(index) {
  5318. return this[index] || null;
  5319. },
  5320. toString:function(isHTML,nodeFilter){
  5321. for(var buf = [], i = 0;i<this.length;i++){
  5322. serializeToString(this[i],buf,isHTML,nodeFilter);
  5323. }
  5324. return buf.join('');
  5325. }
  5326. };
  5327. function LiveNodeList(node,refresh){
  5328. this._node = node;
  5329. this._refresh = refresh
  5330. _updateLiveList(this);
  5331. }
  5332. function _updateLiveList(list){
  5333. var inc = list._node._inc || list._node.ownerDocument._inc;
  5334. if(list._inc != inc){
  5335. var ls = list._refresh(list._node);
  5336. //console.log(ls.length)
  5337. __set__(list,'length',ls.length);
  5338. copy(ls,list);
  5339. list._inc = inc;
  5340. }
  5341. }
  5342. LiveNodeList.prototype.item = function(i){
  5343. _updateLiveList(this);
  5344. return this[i];
  5345. }
  5346. _extends(LiveNodeList,NodeList);
  5347. /**
  5348. *
  5349. * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
  5350. * NamedNodeMap objects in the DOM are live.
  5351. * used for attributes or DocumentType entities
  5352. */
  5353. function NamedNodeMap() {
  5354. };
  5355. function _findNodeIndex(list,node){
  5356. var i = list.length;
  5357. while(i--){
  5358. if(list[i] === node){return i}
  5359. }
  5360. }
  5361. function _addNamedNode(el,list,newAttr,oldAttr){
  5362. if(oldAttr){
  5363. list[_findNodeIndex(list,oldAttr)] = newAttr;
  5364. }else{
  5365. list[list.length++] = newAttr;
  5366. }
  5367. if(el){
  5368. newAttr.ownerElement = el;
  5369. var doc = el.ownerDocument;
  5370. if(doc){
  5371. oldAttr && _onRemoveAttribute(doc,el,oldAttr);
  5372. _onAddAttribute(doc,el,newAttr);
  5373. }
  5374. }
  5375. }
  5376. function _removeNamedNode(el,list,attr){
  5377. //console.log('remove attr:'+attr)
  5378. var i = _findNodeIndex(list,attr);
  5379. if(i>=0){
  5380. var lastIndex = list.length-1
  5381. while(i<lastIndex){
  5382. list[i] = list[++i]
  5383. }
  5384. list.length = lastIndex;
  5385. if(el){
  5386. var doc = el.ownerDocument;
  5387. if(doc){
  5388. _onRemoveAttribute(doc,el,attr);
  5389. attr.ownerElement = null;
  5390. }
  5391. }
  5392. }else{
  5393. throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
  5394. }
  5395. }
  5396. NamedNodeMap.prototype = {
  5397. length:0,
  5398. item:NodeList.prototype.item,
  5399. getNamedItem: function(key) {
  5400. // if(key.indexOf(':')>0 || key == 'xmlns'){
  5401. // return null;
  5402. // }
  5403. //console.log()
  5404. var i = this.length;
  5405. while(i--){
  5406. var attr = this[i];
  5407. //console.log(attr.nodeName,key)
  5408. if(attr.nodeName == key){
  5409. return attr;
  5410. }
  5411. }
  5412. },
  5413. setNamedItem: function(attr) {
  5414. var el = attr.ownerElement;
  5415. if(el && el!=this._ownerElement){
  5416. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  5417. }
  5418. var oldAttr = this.getNamedItem(attr.nodeName);
  5419. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  5420. return oldAttr;
  5421. },
  5422. /* returns Node */
  5423. setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  5424. var el = attr.ownerElement, oldAttr;
  5425. if(el && el!=this._ownerElement){
  5426. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  5427. }
  5428. oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
  5429. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  5430. return oldAttr;
  5431. },
  5432. /* returns Node */
  5433. removeNamedItem: function(key) {
  5434. var attr = this.getNamedItem(key);
  5435. _removeNamedNode(this._ownerElement,this,attr);
  5436. return attr;
  5437. },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  5438. //for level2
  5439. removeNamedItemNS:function(namespaceURI,localName){
  5440. var attr = this.getNamedItemNS(namespaceURI,localName);
  5441. _removeNamedNode(this._ownerElement,this,attr);
  5442. return attr;
  5443. },
  5444. getNamedItemNS: function(namespaceURI, localName) {
  5445. var i = this.length;
  5446. while(i--){
  5447. var node = this[i];
  5448. if(node.localName == localName && node.namespaceURI == namespaceURI){
  5449. return node;
  5450. }
  5451. }
  5452. return null;
  5453. }
  5454. };
  5455. /**
  5456. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
  5457. */
  5458. function DOMImplementation(/* Object */ features) {
  5459. this._features = {};
  5460. if (features) {
  5461. for (var feature in features) {
  5462. this._features = features[feature];
  5463. }
  5464. }
  5465. };
  5466. DOMImplementation.prototype = {
  5467. hasFeature: function(/* string */ feature, /* string */ version) {
  5468. var versions = this._features[feature.toLowerCase()];
  5469. if (versions && (!version || version in versions)) {
  5470. return true;
  5471. } else {
  5472. return false;
  5473. }
  5474. },
  5475. // Introduced in DOM Level 2:
  5476. createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
  5477. var doc = new Document();
  5478. doc.implementation = this;
  5479. doc.childNodes = new NodeList();
  5480. doc.doctype = doctype;
  5481. if(doctype){
  5482. doc.appendChild(doctype);
  5483. }
  5484. if(qualifiedName){
  5485. var root = doc.createElementNS(namespaceURI,qualifiedName);
  5486. doc.appendChild(root);
  5487. }
  5488. return doc;
  5489. },
  5490. // Introduced in DOM Level 2:
  5491. createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
  5492. var node = new DocumentType();
  5493. node.name = qualifiedName;
  5494. node.nodeName = qualifiedName;
  5495. node.publicId = publicId;
  5496. node.systemId = systemId;
  5497. // Introduced in DOM Level 2:
  5498. //readonly attribute DOMString internalSubset;
  5499. //TODO:..
  5500. // readonly attribute NamedNodeMap entities;
  5501. // readonly attribute NamedNodeMap notations;
  5502. return node;
  5503. }
  5504. };
  5505. /**
  5506. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  5507. */
  5508. function Node() {
  5509. };
  5510. Node.prototype = {
  5511. firstChild : null,
  5512. lastChild : null,
  5513. previousSibling : null,
  5514. nextSibling : null,
  5515. attributes : null,
  5516. parentNode : null,
  5517. childNodes : null,
  5518. ownerDocument : null,
  5519. nodeValue : null,
  5520. namespaceURI : null,
  5521. prefix : null,
  5522. localName : null,
  5523. // Modified in DOM Level 2:
  5524. insertBefore:function(newChild, refChild){//raises
  5525. return _insertBefore(this,newChild,refChild);
  5526. },
  5527. replaceChild:function(newChild, oldChild){//raises
  5528. this.insertBefore(newChild,oldChild);
  5529. if(oldChild){
  5530. this.removeChild(oldChild);
  5531. }
  5532. },
  5533. removeChild:function(oldChild){
  5534. return _removeChild(this,oldChild);
  5535. },
  5536. appendChild:function(newChild){
  5537. return this.insertBefore(newChild,null);
  5538. },
  5539. hasChildNodes:function(){
  5540. return this.firstChild != null;
  5541. },
  5542. cloneNode:function(deep){
  5543. return cloneNode(this.ownerDocument||this,this,deep);
  5544. },
  5545. // Modified in DOM Level 2:
  5546. normalize:function(){
  5547. var child = this.firstChild;
  5548. while(child){
  5549. var next = child.nextSibling;
  5550. if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
  5551. this.removeChild(next);
  5552. child.appendData(next.data);
  5553. }else{
  5554. child.normalize();
  5555. child = next;
  5556. }
  5557. }
  5558. },
  5559. // Introduced in DOM Level 2:
  5560. isSupported:function(feature, version){
  5561. return this.ownerDocument.implementation.hasFeature(feature,version);
  5562. },
  5563. // Introduced in DOM Level 2:
  5564. hasAttributes:function(){
  5565. return this.attributes.length>0;
  5566. },
  5567. lookupPrefix:function(namespaceURI){
  5568. var el = this;
  5569. while(el){
  5570. var map = el._nsMap;
  5571. //console.dir(map)
  5572. if(map){
  5573. for(var n in map){
  5574. if(map[n] == namespaceURI){
  5575. return n;
  5576. }
  5577. }
  5578. }
  5579. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  5580. }
  5581. return null;
  5582. },
  5583. // Introduced in DOM Level 3:
  5584. lookupNamespaceURI:function(prefix){
  5585. var el = this;
  5586. while(el){
  5587. var map = el._nsMap;
  5588. //console.dir(map)
  5589. if(map){
  5590. if(prefix in map){
  5591. return map[prefix] ;
  5592. }
  5593. }
  5594. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  5595. }
  5596. return null;
  5597. },
  5598. // Introduced in DOM Level 3:
  5599. isDefaultNamespace:function(namespaceURI){
  5600. var prefix = this.lookupPrefix(namespaceURI);
  5601. return prefix == null;
  5602. }
  5603. };
  5604. function _xmlEncoder(c){
  5605. return c == '<' && '&lt;' ||
  5606. c == '>' && '&gt;' ||
  5607. c == '&' && '&amp;' ||
  5608. c == '"' && '&quot;' ||
  5609. '&#'+c.charCodeAt()+';'
  5610. }
  5611. copy(NodeType,Node);
  5612. copy(NodeType,Node.prototype);
  5613. /**
  5614. * @param callback return true for continue,false for break
  5615. * @return boolean true: break visit;
  5616. */
  5617. function _visitNode(node,callback){
  5618. if(callback(node)){
  5619. return true;
  5620. }
  5621. if(node = node.firstChild){
  5622. do{
  5623. if(_visitNode(node,callback)){return true}
  5624. }while(node=node.nextSibling)
  5625. }
  5626. }
  5627. function Document(){
  5628. }
  5629. function _onAddAttribute(doc,el,newAttr){
  5630. doc && doc._inc++;
  5631. var ns = newAttr.namespaceURI ;
  5632. if(ns == 'http://www.w3.org/2000/xmlns/'){
  5633. //update namespace
  5634. el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
  5635. }
  5636. }
  5637. function _onRemoveAttribute(doc,el,newAttr,remove){
  5638. doc && doc._inc++;
  5639. var ns = newAttr.namespaceURI ;
  5640. if(ns == 'http://www.w3.org/2000/xmlns/'){
  5641. //update namespace
  5642. delete el._nsMap[newAttr.prefix?newAttr.localName:'']
  5643. }
  5644. }
  5645. function _onUpdateChild(doc,el,newChild){
  5646. if(doc && doc._inc){
  5647. doc._inc++;
  5648. //update childNodes
  5649. var cs = el.childNodes;
  5650. if(newChild){
  5651. cs[cs.length++] = newChild;
  5652. }else{
  5653. //console.log(1)
  5654. var child = el.firstChild;
  5655. var i = 0;
  5656. while(child){
  5657. cs[i++] = child;
  5658. child =child.nextSibling;
  5659. }
  5660. cs.length = i;
  5661. }
  5662. }
  5663. }
  5664. /**
  5665. * attributes;
  5666. * children;
  5667. *
  5668. * writeable properties:
  5669. * nodeValue,Attr:value,CharacterData:data
  5670. * prefix
  5671. */
  5672. function _removeChild(parentNode,child){
  5673. var previous = child.previousSibling;
  5674. var next = child.nextSibling;
  5675. if(previous){
  5676. previous.nextSibling = next;
  5677. }else{
  5678. parentNode.firstChild = next
  5679. }
  5680. if(next){
  5681. next.previousSibling = previous;
  5682. }else{
  5683. parentNode.lastChild = previous;
  5684. }
  5685. _onUpdateChild(parentNode.ownerDocument,parentNode);
  5686. return child;
  5687. }
  5688. /**
  5689. * preformance key(refChild == null)
  5690. */
  5691. function _insertBefore(parentNode,newChild,nextChild){
  5692. var cp = newChild.parentNode;
  5693. if(cp){
  5694. cp.removeChild(newChild);//remove and update
  5695. }
  5696. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  5697. var newFirst = newChild.firstChild;
  5698. if (newFirst == null) {
  5699. return newChild;
  5700. }
  5701. var newLast = newChild.lastChild;
  5702. }else{
  5703. newFirst = newLast = newChild;
  5704. }
  5705. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  5706. newFirst.previousSibling = pre;
  5707. newLast.nextSibling = nextChild;
  5708. if(pre){
  5709. pre.nextSibling = newFirst;
  5710. }else{
  5711. parentNode.firstChild = newFirst;
  5712. }
  5713. if(nextChild == null){
  5714. parentNode.lastChild = newLast;
  5715. }else{
  5716. nextChild.previousSibling = newLast;
  5717. }
  5718. do{
  5719. newFirst.parentNode = parentNode;
  5720. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  5721. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  5722. //console.log(parentNode.lastChild.nextSibling == null)
  5723. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  5724. newChild.firstChild = newChild.lastChild = null;
  5725. }
  5726. return newChild;
  5727. }
  5728. function _appendSingleChild(parentNode,newChild){
  5729. var cp = newChild.parentNode;
  5730. if(cp){
  5731. var pre = parentNode.lastChild;
  5732. cp.removeChild(newChild);//remove and update
  5733. var pre = parentNode.lastChild;
  5734. }
  5735. var pre = parentNode.lastChild;
  5736. newChild.parentNode = parentNode;
  5737. newChild.previousSibling = pre;
  5738. newChild.nextSibling = null;
  5739. if(pre){
  5740. pre.nextSibling = newChild;
  5741. }else{
  5742. parentNode.firstChild = newChild;
  5743. }
  5744. parentNode.lastChild = newChild;
  5745. _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
  5746. return newChild;
  5747. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  5748. }
  5749. Document.prototype = {
  5750. //implementation : null,
  5751. nodeName : '#document',
  5752. nodeType : DOCUMENT_NODE,
  5753. doctype : null,
  5754. documentElement : null,
  5755. _inc : 1,
  5756. insertBefore : function(newChild, refChild){//raises
  5757. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  5758. var child = newChild.firstChild;
  5759. while(child){
  5760. var next = child.nextSibling;
  5761. this.insertBefore(child,refChild);
  5762. child = next;
  5763. }
  5764. return newChild;
  5765. }
  5766. if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
  5767. this.documentElement = newChild;
  5768. }
  5769. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  5770. },
  5771. removeChild : function(oldChild){
  5772. if(this.documentElement == oldChild){
  5773. this.documentElement = null;
  5774. }
  5775. return _removeChild(this,oldChild);
  5776. },
  5777. // Introduced in DOM Level 2:
  5778. importNode : function(importedNode,deep){
  5779. return importNode(this,importedNode,deep);
  5780. },
  5781. // Introduced in DOM Level 2:
  5782. getElementById : function(id){
  5783. var rtv = null;
  5784. _visitNode(this.documentElement,function(node){
  5785. if(node.nodeType == ELEMENT_NODE){
  5786. if(node.getAttribute('id') == id){
  5787. rtv = node;
  5788. return true;
  5789. }
  5790. }
  5791. })
  5792. return rtv;
  5793. },
  5794. //document factory method:
  5795. createElement : function(tagName){
  5796. var node = new Element();
  5797. node.ownerDocument = this;
  5798. node.nodeName = tagName;
  5799. node.tagName = tagName;
  5800. node.childNodes = new NodeList();
  5801. var attrs = node.attributes = new NamedNodeMap();
  5802. attrs._ownerElement = node;
  5803. return node;
  5804. },
  5805. createDocumentFragment : function(){
  5806. var node = new DocumentFragment();
  5807. node.ownerDocument = this;
  5808. node.childNodes = new NodeList();
  5809. return node;
  5810. },
  5811. createTextNode : function(data){
  5812. var node = new Text();
  5813. node.ownerDocument = this;
  5814. node.appendData(data)
  5815. return node;
  5816. },
  5817. createComment : function(data){
  5818. var node = new Comment();
  5819. node.ownerDocument = this;
  5820. node.appendData(data)
  5821. return node;
  5822. },
  5823. createCDATASection : function(data){
  5824. var node = new CDATASection();
  5825. node.ownerDocument = this;
  5826. node.appendData(data)
  5827. return node;
  5828. },
  5829. createProcessingInstruction : function(target,data){
  5830. var node = new ProcessingInstruction();
  5831. node.ownerDocument = this;
  5832. node.tagName = node.target = target;
  5833. node.nodeValue= node.data = data;
  5834. return node;
  5835. },
  5836. createAttribute : function(name){
  5837. var node = new Attr();
  5838. node.ownerDocument = this;
  5839. node.name = name;
  5840. node.nodeName = name;
  5841. node.localName = name;
  5842. node.specified = true;
  5843. return node;
  5844. },
  5845. createEntityReference : function(name){
  5846. var node = new EntityReference();
  5847. node.ownerDocument = this;
  5848. node.nodeName = name;
  5849. return node;
  5850. },
  5851. // Introduced in DOM Level 2:
  5852. createElementNS : function(namespaceURI,qualifiedName){
  5853. var node = new Element();
  5854. var pl = qualifiedName.split(':');
  5855. var attrs = node.attributes = new NamedNodeMap();
  5856. node.childNodes = new NodeList();
  5857. node.ownerDocument = this;
  5858. node.nodeName = qualifiedName;
  5859. node.tagName = qualifiedName;
  5860. node.namespaceURI = namespaceURI;
  5861. if(pl.length == 2){
  5862. node.prefix = pl[0];
  5863. node.localName = pl[1];
  5864. }else{
  5865. //el.prefix = null;
  5866. node.localName = qualifiedName;
  5867. }
  5868. attrs._ownerElement = node;
  5869. return node;
  5870. },
  5871. // Introduced in DOM Level 2:
  5872. createAttributeNS : function(namespaceURI,qualifiedName){
  5873. var node = new Attr();
  5874. var pl = qualifiedName.split(':');
  5875. node.ownerDocument = this;
  5876. node.nodeName = qualifiedName;
  5877. node.name = qualifiedName;
  5878. node.namespaceURI = namespaceURI;
  5879. node.specified = true;
  5880. if(pl.length == 2){
  5881. node.prefix = pl[0];
  5882. node.localName = pl[1];
  5883. }else{
  5884. //el.prefix = null;
  5885. node.localName = qualifiedName;
  5886. }
  5887. return node;
  5888. }
  5889. };
  5890. _extends(Document,Node);
  5891. function Element() {
  5892. this._nsMap = {};
  5893. };
  5894. Element.prototype = {
  5895. nodeType : ELEMENT_NODE,
  5896. hasAttribute : function(name){
  5897. return this.getAttributeNode(name)!=null;
  5898. },
  5899. getAttribute : function(name){
  5900. var attr = this.getAttributeNode(name);
  5901. return attr && attr.value || '';
  5902. },
  5903. getAttributeNode : function(name){
  5904. return this.attributes.getNamedItem(name);
  5905. },
  5906. setAttribute : function(name, value){
  5907. var attr = this.ownerDocument.createAttribute(name);
  5908. attr.value = attr.nodeValue = "" + value;
  5909. this.setAttributeNode(attr)
  5910. },
  5911. removeAttribute : function(name){
  5912. var attr = this.getAttributeNode(name)
  5913. attr && this.removeAttributeNode(attr);
  5914. },
  5915. //four real opeartion method
  5916. appendChild:function(newChild){
  5917. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  5918. return this.insertBefore(newChild,null);
  5919. }else{
  5920. return _appendSingleChild(this,newChild);
  5921. }
  5922. },
  5923. setAttributeNode : function(newAttr){
  5924. return this.attributes.setNamedItem(newAttr);
  5925. },
  5926. setAttributeNodeNS : function(newAttr){
  5927. return this.attributes.setNamedItemNS(newAttr);
  5928. },
  5929. removeAttributeNode : function(oldAttr){
  5930. //console.log(this == oldAttr.ownerElement)
  5931. return this.attributes.removeNamedItem(oldAttr.nodeName);
  5932. },
  5933. //get real attribute name,and remove it by removeAttributeNode
  5934. removeAttributeNS : function(namespaceURI, localName){
  5935. var old = this.getAttributeNodeNS(namespaceURI, localName);
  5936. old && this.removeAttributeNode(old);
  5937. },
  5938. hasAttributeNS : function(namespaceURI, localName){
  5939. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  5940. },
  5941. getAttributeNS : function(namespaceURI, localName){
  5942. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  5943. return attr && attr.value || '';
  5944. },
  5945. setAttributeNS : function(namespaceURI, qualifiedName, value){
  5946. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  5947. attr.value = attr.nodeValue = "" + value;
  5948. this.setAttributeNode(attr)
  5949. },
  5950. getAttributeNodeNS : function(namespaceURI, localName){
  5951. return this.attributes.getNamedItemNS(namespaceURI, localName);
  5952. },
  5953. getElementsByTagName : function(tagName){
  5954. return new LiveNodeList(this,function(base){
  5955. var ls = [];
  5956. _visitNode(base,function(node){
  5957. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  5958. ls.push(node);
  5959. }
  5960. });
  5961. return ls;
  5962. });
  5963. },
  5964. getElementsByTagNameNS : function(namespaceURI, localName){
  5965. return new LiveNodeList(this,function(base){
  5966. var ls = [];
  5967. _visitNode(base,function(node){
  5968. if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
  5969. ls.push(node);
  5970. }
  5971. });
  5972. return ls;
  5973. });
  5974. }
  5975. };
  5976. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  5977. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  5978. _extends(Element,Node);
  5979. function Attr() {
  5980. };
  5981. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  5982. _extends(Attr,Node);
  5983. function CharacterData() {
  5984. };
  5985. CharacterData.prototype = {
  5986. data : '',
  5987. substringData : function(offset, count) {
  5988. return this.data.substring(offset, offset+count);
  5989. },
  5990. appendData: function(text) {
  5991. text = this.data+text;
  5992. this.nodeValue = this.data = text;
  5993. this.length = text.length;
  5994. },
  5995. insertData: function(offset,text) {
  5996. this.replaceData(offset,0,text);
  5997. },
  5998. appendChild:function(newChild){
  5999. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
  6000. },
  6001. deleteData: function(offset, count) {
  6002. this.replaceData(offset,count,"");
  6003. },
  6004. replaceData: function(offset, count, text) {
  6005. var start = this.data.substring(0,offset);
  6006. var end = this.data.substring(offset+count);
  6007. text = start + text + end;
  6008. this.nodeValue = this.data = text;
  6009. this.length = text.length;
  6010. }
  6011. }
  6012. _extends(CharacterData,Node);
  6013. function Text() {
  6014. };
  6015. Text.prototype = {
  6016. nodeName : "#text",
  6017. nodeType : TEXT_NODE,
  6018. splitText : function(offset) {
  6019. var text = this.data;
  6020. var newText = text.substring(offset);
  6021. text = text.substring(0, offset);
  6022. this.data = this.nodeValue = text;
  6023. this.length = text.length;
  6024. var newNode = this.ownerDocument.createTextNode(newText);
  6025. if(this.parentNode){
  6026. this.parentNode.insertBefore(newNode, this.nextSibling);
  6027. }
  6028. return newNode;
  6029. }
  6030. }
  6031. _extends(Text,CharacterData);
  6032. function Comment() {
  6033. };
  6034. Comment.prototype = {
  6035. nodeName : "#comment",
  6036. nodeType : COMMENT_NODE
  6037. }
  6038. _extends(Comment,CharacterData);
  6039. function CDATASection() {
  6040. };
  6041. CDATASection.prototype = {
  6042. nodeName : "#cdata-section",
  6043. nodeType : CDATA_SECTION_NODE
  6044. }
  6045. _extends(CDATASection,CharacterData);
  6046. function DocumentType() {
  6047. };
  6048. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  6049. _extends(DocumentType,Node);
  6050. function Notation() {
  6051. };
  6052. Notation.prototype.nodeType = NOTATION_NODE;
  6053. _extends(Notation,Node);
  6054. function Entity() {
  6055. };
  6056. Entity.prototype.nodeType = ENTITY_NODE;
  6057. _extends(Entity,Node);
  6058. function EntityReference() {
  6059. };
  6060. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  6061. _extends(EntityReference,Node);
  6062. function DocumentFragment() {
  6063. };
  6064. DocumentFragment.prototype.nodeName = "#document-fragment";
  6065. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  6066. _extends(DocumentFragment,Node);
  6067. function ProcessingInstruction() {
  6068. }
  6069. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  6070. _extends(ProcessingInstruction,Node);
  6071. function XMLSerializer(){}
  6072. XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
  6073. return nodeSerializeToString.call(node,isHtml,nodeFilter);
  6074. }
  6075. Node.prototype.toString = nodeSerializeToString;
  6076. function nodeSerializeToString(isHtml,nodeFilter){
  6077. var buf = [];
  6078. var refNode = this.nodeType == 9?this.documentElement:this;
  6079. var prefix = refNode.prefix;
  6080. var uri = refNode.namespaceURI;
  6081. if(uri && prefix == null){
  6082. //console.log(prefix)
  6083. var prefix = refNode.lookupPrefix(uri);
  6084. if(prefix == null){
  6085. //isHTML = true;
  6086. var visibleNamespaces=[
  6087. {namespace:uri,prefix:null}
  6088. //{namespace:uri,prefix:''}
  6089. ]
  6090. }
  6091. }
  6092. serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
  6093. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  6094. return buf.join('');
  6095. }
  6096. function needNamespaceDefine(node,isHTML, visibleNamespaces) {
  6097. var prefix = node.prefix||'';
  6098. var uri = node.namespaceURI;
  6099. if (!prefix && !uri){
  6100. return false;
  6101. }
  6102. if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
  6103. || uri == 'http://www.w3.org/2000/xmlns/'){
  6104. return false;
  6105. }
  6106. var i = visibleNamespaces.length
  6107. //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
  6108. while (i--) {
  6109. var ns = visibleNamespaces[i];
  6110. // get namespace prefix
  6111. //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
  6112. if (ns.prefix == prefix){
  6113. return ns.namespace != uri;
  6114. }
  6115. }
  6116. //console.log(isHTML,uri,prefix=='')
  6117. //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
  6118. // return false;
  6119. //}
  6120. //node.flag = '11111'
  6121. //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
  6122. return true;
  6123. }
  6124. function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
  6125. if(nodeFilter){
  6126. node = nodeFilter(node);
  6127. if(node){
  6128. if(typeof node == 'string'){
  6129. buf.push(node);
  6130. return;
  6131. }
  6132. }else{
  6133. return;
  6134. }
  6135. //buf.sort.apply(attrs, attributeSorter);
  6136. }
  6137. switch(node.nodeType){
  6138. case ELEMENT_NODE:
  6139. if (!visibleNamespaces) visibleNamespaces = [];
  6140. var startVisibleNamespaces = visibleNamespaces.length;
  6141. var attrs = node.attributes;
  6142. var len = attrs.length;
  6143. var child = node.firstChild;
  6144. var nodeName = node.tagName;
  6145. isHTML = (htmlns === node.namespaceURI) ||isHTML
  6146. buf.push('<',nodeName);
  6147. for(var i=0;i<len;i++){
  6148. // add namespaces for attributes
  6149. var attr = attrs.item(i);
  6150. if (attr.prefix == 'xmlns') {
  6151. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  6152. }else if(attr.nodeName == 'xmlns'){
  6153. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  6154. }
  6155. }
  6156. for(var i=0;i<len;i++){
  6157. var attr = attrs.item(i);
  6158. if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
  6159. var prefix = attr.prefix||'';
  6160. var uri = attr.namespaceURI;
  6161. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  6162. buf.push(ns, '="' , uri , '"');
  6163. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  6164. }
  6165. serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
  6166. }
  6167. // add namespace for current node
  6168. if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
  6169. var prefix = node.prefix||'';
  6170. var uri = node.namespaceURI;
  6171. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  6172. buf.push(ns, '="' , uri , '"');
  6173. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  6174. }
  6175. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  6176. buf.push('>');
  6177. //if is cdata child node
  6178. if(isHTML && /^script$/i.test(nodeName)){
  6179. while(child){
  6180. if(child.data){
  6181. buf.push(child.data);
  6182. }else{
  6183. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  6184. }
  6185. child = child.nextSibling;
  6186. }
  6187. }else
  6188. {
  6189. while(child){
  6190. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  6191. child = child.nextSibling;
  6192. }
  6193. }
  6194. buf.push('</',nodeName,'>');
  6195. }else{
  6196. buf.push('/>');
  6197. }
  6198. // remove added visible namespaces
  6199. //visibleNamespaces.length = startVisibleNamespaces;
  6200. return;
  6201. case DOCUMENT_NODE:
  6202. case DOCUMENT_FRAGMENT_NODE:
  6203. var child = node.firstChild;
  6204. while(child){
  6205. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  6206. child = child.nextSibling;
  6207. }
  6208. return;
  6209. case ATTRIBUTE_NODE:
  6210. return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
  6211. case TEXT_NODE:
  6212. return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
  6213. case CDATA_SECTION_NODE:
  6214. return buf.push( '<![CDATA[',node.data,']]>');
  6215. case COMMENT_NODE:
  6216. return buf.push( "<!--",node.data,"-->");
  6217. case DOCUMENT_TYPE_NODE:
  6218. var pubid = node.publicId;
  6219. var sysid = node.systemId;
  6220. buf.push('<!DOCTYPE ',node.name);
  6221. if(pubid){
  6222. buf.push(' PUBLIC "',pubid);
  6223. if (sysid && sysid!='.') {
  6224. buf.push( '" "',sysid);
  6225. }
  6226. buf.push('">');
  6227. }else if(sysid && sysid!='.'){
  6228. buf.push(' SYSTEM "',sysid,'">');
  6229. }else{
  6230. var sub = node.internalSubset;
  6231. if(sub){
  6232. buf.push(" [",sub,"]");
  6233. }
  6234. buf.push(">");
  6235. }
  6236. return;
  6237. case PROCESSING_INSTRUCTION_NODE:
  6238. return buf.push( "<?",node.target," ",node.data,"?>");
  6239. case ENTITY_REFERENCE_NODE:
  6240. return buf.push( '&',node.nodeName,';');
  6241. //case ENTITY_NODE:
  6242. //case NOTATION_NODE:
  6243. default:
  6244. buf.push('??',node.nodeName);
  6245. }
  6246. }
  6247. function importNode(doc,node,deep){
  6248. var node2;
  6249. switch (node.nodeType) {
  6250. case ELEMENT_NODE:
  6251. node2 = node.cloneNode(false);
  6252. node2.ownerDocument = doc;
  6253. //var attrs = node2.attributes;
  6254. //var len = attrs.length;
  6255. //for(var i=0;i<len;i++){
  6256. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  6257. //}
  6258. case DOCUMENT_FRAGMENT_NODE:
  6259. break;
  6260. case ATTRIBUTE_NODE:
  6261. deep = true;
  6262. break;
  6263. //case ENTITY_REFERENCE_NODE:
  6264. //case PROCESSING_INSTRUCTION_NODE:
  6265. ////case TEXT_NODE:
  6266. //case CDATA_SECTION_NODE:
  6267. //case COMMENT_NODE:
  6268. // deep = false;
  6269. // break;
  6270. //case DOCUMENT_NODE:
  6271. //case DOCUMENT_TYPE_NODE:
  6272. //cannot be imported.
  6273. //case ENTITY_NODE:
  6274. //case NOTATION_NODE:
  6275. //can not hit in level3
  6276. //default:throw e;
  6277. }
  6278. if(!node2){
  6279. node2 = node.cloneNode(false);//false
  6280. }
  6281. node2.ownerDocument = doc;
  6282. node2.parentNode = null;
  6283. if(deep){
  6284. var child = node.firstChild;
  6285. while(child){
  6286. node2.appendChild(importNode(doc,child,deep));
  6287. child = child.nextSibling;
  6288. }
  6289. }
  6290. return node2;
  6291. }
  6292. //
  6293. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  6294. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  6295. function cloneNode(doc,node,deep){
  6296. var node2 = new node.constructor();
  6297. for(var n in node){
  6298. var v = node[n];
  6299. if(typeof v != 'object' ){
  6300. if(v != node2[n]){
  6301. node2[n] = v;
  6302. }
  6303. }
  6304. }
  6305. if(node.childNodes){
  6306. node2.childNodes = new NodeList();
  6307. }
  6308. node2.ownerDocument = doc;
  6309. switch (node2.nodeType) {
  6310. case ELEMENT_NODE:
  6311. var attrs = node.attributes;
  6312. var attrs2 = node2.attributes = new NamedNodeMap();
  6313. var len = attrs.length
  6314. attrs2._ownerElement = node2;
  6315. for(var i=0;i<len;i++){
  6316. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  6317. }
  6318. break;;
  6319. case ATTRIBUTE_NODE:
  6320. deep = true;
  6321. }
  6322. if(deep){
  6323. var child = node.firstChild;
  6324. while(child){
  6325. node2.appendChild(cloneNode(doc,child,deep));
  6326. child = child.nextSibling;
  6327. }
  6328. }
  6329. return node2;
  6330. }
  6331. function __set__(object,key,value){
  6332. object[key] = value
  6333. }
  6334. //do dynamic
  6335. try{
  6336. if(Object.defineProperty){
  6337. Object.defineProperty(LiveNodeList.prototype,'length',{
  6338. get:function(){
  6339. _updateLiveList(this);
  6340. return this.$$length;
  6341. }
  6342. });
  6343. Object.defineProperty(Node.prototype,'textContent',{
  6344. get:function(){
  6345. return getTextContent(this);
  6346. },
  6347. set:function(data){
  6348. switch(this.nodeType){
  6349. case ELEMENT_NODE:
  6350. case DOCUMENT_FRAGMENT_NODE:
  6351. while(this.firstChild){
  6352. this.removeChild(this.firstChild);
  6353. }
  6354. if(data || String(data)){
  6355. this.appendChild(this.ownerDocument.createTextNode(data));
  6356. }
  6357. break;
  6358. default:
  6359. //TODO:
  6360. this.data = data;
  6361. this.value = data;
  6362. this.nodeValue = data;
  6363. }
  6364. }
  6365. })
  6366. function getTextContent(node){
  6367. switch(node.nodeType){
  6368. case ELEMENT_NODE:
  6369. case DOCUMENT_FRAGMENT_NODE:
  6370. var buf = [];
  6371. node = node.firstChild;
  6372. while(node){
  6373. if(node.nodeType!==7 && node.nodeType !==8){
  6374. buf.push(getTextContent(node));
  6375. }
  6376. node = node.nextSibling;
  6377. }
  6378. return buf.join('');
  6379. default:
  6380. return node.nodeValue;
  6381. }
  6382. }
  6383. __set__ = function(object,key,value){
  6384. //console.log(value)
  6385. object['$$'+key] = value
  6386. }
  6387. }
  6388. }catch(e){//ie8
  6389. }
  6390. //if(typeof require == 'function'){
  6391. exports.DOMImplementation = DOMImplementation;
  6392. exports.XMLSerializer = XMLSerializer;
  6393. //}
  6394. /***/ }),
  6395. /* 17 */
  6396. /***/ (function(module, exports, __webpack_require__) {
  6397. "use strict";
  6398. /*
  6399. From Zip.js, by Gildas Lormeau
  6400. edited down
  6401. */
  6402. var table = {
  6403. "application": {
  6404. "ecmascript": ["es", "ecma"],
  6405. "javascript": "js",
  6406. "ogg": "ogx",
  6407. "pdf": "pdf",
  6408. "postscript": ["ps", "ai", "eps", "epsi", "epsf", "eps2", "eps3"],
  6409. "rdf+xml": "rdf",
  6410. "smil": ["smi", "smil"],
  6411. "xhtml+xml": ["xhtml", "xht"],
  6412. "xml": ["xml", "xsl", "xsd", "opf", "ncx"],
  6413. "zip": "zip",
  6414. "x-httpd-eruby": "rhtml",
  6415. "x-latex": "latex",
  6416. "x-maker": ["frm", "maker", "frame", "fm", "fb", "book", "fbdoc"],
  6417. "x-object": "o",
  6418. "x-shockwave-flash": ["swf", "swfl"],
  6419. "x-silverlight": "scr",
  6420. "epub+zip": "epub",
  6421. "font-tdpfr": "pfr",
  6422. "inkml+xml": ["ink", "inkml"],
  6423. "json": "json",
  6424. "jsonml+json": "jsonml",
  6425. "mathml+xml": "mathml",
  6426. "metalink+xml": "metalink",
  6427. "mp4": "mp4s",
  6428. // "oebps-package+xml" : "opf",
  6429. "omdoc+xml": "omdoc",
  6430. "oxps": "oxps",
  6431. "vnd.amazon.ebook": "azw",
  6432. "widget": "wgt",
  6433. // "x-dtbncx+xml" : "ncx",
  6434. "x-dtbook+xml": "dtb",
  6435. "x-dtbresource+xml": "res",
  6436. "x-font-bdf": "bdf",
  6437. "x-font-ghostscript": "gsf",
  6438. "x-font-linux-psf": "psf",
  6439. "x-font-otf": "otf",
  6440. "x-font-pcf": "pcf",
  6441. "x-font-snf": "snf",
  6442. "x-font-ttf": ["ttf", "ttc"],
  6443. "x-font-type1": ["pfa", "pfb", "pfm", "afm"],
  6444. "x-font-woff": "woff",
  6445. "x-mobipocket-ebook": ["prc", "mobi"],
  6446. "x-mspublisher": "pub",
  6447. "x-nzb": "nzb",
  6448. "x-tgif": "obj",
  6449. "xaml+xml": "xaml",
  6450. "xml-dtd": "dtd",
  6451. "xproc+xml": "xpl",
  6452. "xslt+xml": "xslt",
  6453. "internet-property-stream": "acx",
  6454. "x-compress": "z",
  6455. "x-compressed": "tgz",
  6456. "x-gzip": "gz"
  6457. },
  6458. "audio": {
  6459. "flac": "flac",
  6460. "midi": ["mid", "midi", "kar", "rmi"],
  6461. "mpeg": ["mpga", "mpega", "mp2", "mp3", "m4a", "mp2a", "m2a", "m3a"],
  6462. "mpegurl": "m3u",
  6463. "ogg": ["oga", "ogg", "spx"],
  6464. "x-aiff": ["aif", "aiff", "aifc"],
  6465. "x-ms-wma": "wma",
  6466. "x-wav": "wav",
  6467. "adpcm": "adp",
  6468. "mp4": "mp4a",
  6469. "webm": "weba",
  6470. "x-aac": "aac",
  6471. "x-caf": "caf",
  6472. "x-matroska": "mka",
  6473. "x-pn-realaudio-plugin": "rmp",
  6474. "xm": "xm",
  6475. "mid": ["mid", "rmi"]
  6476. },
  6477. "image": {
  6478. "gif": "gif",
  6479. "ief": "ief",
  6480. "jpeg": ["jpeg", "jpg", "jpe"],
  6481. "pcx": "pcx",
  6482. "png": "png",
  6483. "svg+xml": ["svg", "svgz"],
  6484. "tiff": ["tiff", "tif"],
  6485. "x-icon": "ico",
  6486. "bmp": "bmp",
  6487. "webp": "webp",
  6488. "x-pict": ["pic", "pct"],
  6489. "x-tga": "tga",
  6490. "cis-cod": "cod"
  6491. },
  6492. "text": {
  6493. "cache-manifest": ["manifest", "appcache"],
  6494. "css": "css",
  6495. "csv": "csv",
  6496. "html": ["html", "htm", "shtml", "stm"],
  6497. "mathml": "mml",
  6498. "plain": ["txt", "text", "brf", "conf", "def", "list", "log", "in", "bas"],
  6499. "richtext": "rtx",
  6500. "tab-separated-values": "tsv",
  6501. "x-bibtex": "bib"
  6502. },
  6503. "video": {
  6504. "mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v", "mp2", "mpa", "mpv2"],
  6505. "mp4": ["mp4", "mp4v", "mpg4"],
  6506. "quicktime": ["qt", "mov"],
  6507. "ogg": "ogv",
  6508. "vnd.mpegurl": ["mxu", "m4u"],
  6509. "x-flv": "flv",
  6510. "x-la-asf": ["lsf", "lsx"],
  6511. "x-mng": "mng",
  6512. "x-ms-asf": ["asf", "asx", "asr"],
  6513. "x-ms-wm": "wm",
  6514. "x-ms-wmv": "wmv",
  6515. "x-ms-wmx": "wmx",
  6516. "x-ms-wvx": "wvx",
  6517. "x-msvideo": "avi",
  6518. "x-sgi-movie": "movie",
  6519. "x-matroska": ["mpv", "mkv", "mk3d", "mks"],
  6520. "3gpp2": "3g2",
  6521. "h261": "h261",
  6522. "h263": "h263",
  6523. "h264": "h264",
  6524. "jpeg": "jpgv",
  6525. "jpm": ["jpm", "jpgm"],
  6526. "mj2": ["mj2", "mjp2"],
  6527. "vnd.ms-playready.media.pyv": "pyv",
  6528. "vnd.uvvu.mp4": ["uvu", "uvvu"],
  6529. "vnd.vivo": "viv",
  6530. "webm": "webm",
  6531. "x-f4v": "f4v",
  6532. "x-m4v": "m4v",
  6533. "x-ms-vob": "vob",
  6534. "x-smv": "smv"
  6535. }
  6536. };
  6537. var mimeTypes = function () {
  6538. var type,
  6539. subtype,
  6540. val,
  6541. index,
  6542. mimeTypes = {};
  6543. for (type in table) {
  6544. if (table.hasOwnProperty(type)) {
  6545. for (subtype in table[type]) {
  6546. if (table[type].hasOwnProperty(subtype)) {
  6547. val = table[type][subtype];
  6548. if (typeof val == "string") {
  6549. mimeTypes[val] = type + "/" + subtype;
  6550. } else {
  6551. for (index = 0; index < val.length; index++) {
  6552. mimeTypes[val[index]] = type + "/" + subtype;
  6553. }
  6554. }
  6555. }
  6556. }
  6557. }
  6558. }
  6559. return mimeTypes;
  6560. }();
  6561. var defaultValue = "text/plain"; //"application/octet-stream";
  6562. function lookup(filename) {
  6563. return filename && mimeTypes[filename.split(".").pop().toLowerCase()] || defaultValue;
  6564. };
  6565. module.exports = {
  6566. 'lookup': lookup
  6567. };
  6568. /***/ }),
  6569. /* 18 */
  6570. /***/ (function(module, exports, __webpack_require__) {
  6571. "use strict";
  6572. Object.defineProperty(exports, "__esModule", {
  6573. value: true
  6574. });
  6575. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  6576. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6577. // import Mapping from "./mapping";
  6578. // Default Views
  6579. // Default View Managers
  6580. var _eventEmitter = __webpack_require__(3);
  6581. var _eventEmitter2 = _interopRequireDefault(_eventEmitter);
  6582. var _core = __webpack_require__(0);
  6583. var _hook = __webpack_require__(10);
  6584. var _hook2 = _interopRequireDefault(_hook);
  6585. var _epubcfi = __webpack_require__(1);
  6586. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  6587. var _queue = __webpack_require__(12);
  6588. var _queue2 = _interopRequireDefault(_queue);
  6589. var _layout = __webpack_require__(53);
  6590. var _layout2 = _interopRequireDefault(_layout);
  6591. var _themes = __webpack_require__(54);
  6592. var _themes2 = _interopRequireDefault(_themes);
  6593. var _contents = __webpack_require__(13);
  6594. var _contents2 = _interopRequireDefault(_contents);
  6595. var _annotations = __webpack_require__(55);
  6596. var _annotations2 = _interopRequireDefault(_annotations);
  6597. var _constants = __webpack_require__(2);
  6598. var _iframe = __webpack_require__(20);
  6599. var _iframe2 = _interopRequireDefault(_iframe);
  6600. var _index = __webpack_require__(14);
  6601. var _index2 = _interopRequireDefault(_index);
  6602. var _index3 = __webpack_require__(24);
  6603. var _index4 = _interopRequireDefault(_index3);
  6604. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6605. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6606. /**
  6607. * Displays an Epub as a series of Views for each Section.
  6608. * Requires Manager and View class to handle specifics of rendering
  6609. * the section contetn.
  6610. * @class
  6611. * @param {Book} book
  6612. * @param {object} [options]
  6613. * @param {number} [options.width]
  6614. * @param {number} [options.height]
  6615. * @param {string} [options.ignoreClass] class for the cfi parser to ignore
  6616. * @param {string | function | object} [options.manager='default']
  6617. * @param {string | function} [options.view='iframe']
  6618. * @param {string} [options.layout] layout to force
  6619. * @param {string} [options.spread] force spread value
  6620. * @param {number} [options.minSpreadWidth] overridden by spread: none (never) / both (always)
  6621. * @param {string} [options.stylesheet] url of stylesheet to be injected
  6622. * @param {boolean} [options.resizeOnOrientationChange] false to disable orientation events
  6623. * @param {string} [options.script] url of script to be injected
  6624. */
  6625. var Rendition = function () {
  6626. function Rendition(book, options) {
  6627. _classCallCheck(this, Rendition);
  6628. this.settings = (0, _core.extend)(this.settings || {}, {
  6629. width: null,
  6630. height: null,
  6631. ignoreClass: "",
  6632. manager: "default",
  6633. view: "iframe",
  6634. flow: null,
  6635. layout: null,
  6636. spread: null,
  6637. minSpreadWidth: 800,
  6638. stylesheet: null,
  6639. resizeOnOrientationChange: true,
  6640. script: null
  6641. });
  6642. (0, _core.extend)(this.settings, options);
  6643. if (_typeof(this.settings.manager) === "object") {
  6644. this.manager = this.settings.manager;
  6645. }
  6646. this.book = book;
  6647. /**
  6648. * Adds Hook methods to the Rendition prototype
  6649. * @member {object} hooks
  6650. * @property {Hook} hooks.content
  6651. * @memberof Rendition
  6652. */
  6653. this.hooks = {};
  6654. this.hooks.display = new _hook2.default(this);
  6655. this.hooks.serialize = new _hook2.default(this);
  6656. this.hooks.content = new _hook2.default(this);
  6657. this.hooks.unloaded = new _hook2.default(this);
  6658. this.hooks.layout = new _hook2.default(this);
  6659. this.hooks.render = new _hook2.default(this);
  6660. this.hooks.show = new _hook2.default(this);
  6661. this.hooks.content.register(this.handleLinks.bind(this));
  6662. this.hooks.content.register(this.passEvents.bind(this));
  6663. this.hooks.content.register(this.adjustImages.bind(this));
  6664. this.book.spine.hooks.content.register(this.injectIdentifier.bind(this));
  6665. if (this.settings.stylesheet) {
  6666. this.book.spine.hooks.content.register(this.injectStylesheet.bind(this));
  6667. }
  6668. if (this.settings.script) {
  6669. this.book.spine.hooks.content.register(this.injectScript.bind(this));
  6670. }
  6671. /**
  6672. * @member {Themes} themes
  6673. * @memberof Rendition
  6674. */
  6675. this.themes = new _themes2.default(this);
  6676. /**
  6677. * @member {Annotations} annotations
  6678. * @memberof Rendition
  6679. */
  6680. this.annotations = new _annotations2.default(this);
  6681. this.epubcfi = new _epubcfi2.default();
  6682. this.q = new _queue2.default(this);
  6683. /**
  6684. * A Rendered Location Range
  6685. * @typedef location
  6686. * @type {Object}
  6687. * @property {object} start
  6688. * @property {string} start.index
  6689. * @property {string} start.href
  6690. * @property {object} start.displayed
  6691. * @property {EpubCFI} start.cfi
  6692. * @property {number} start.location
  6693. * @property {number} start.percentage
  6694. * @property {number} start.displayed.page
  6695. * @property {number} start.displayed.total
  6696. * @property {object} end
  6697. * @property {string} end.index
  6698. * @property {string} end.href
  6699. * @property {object} end.displayed
  6700. * @property {EpubCFI} end.cfi
  6701. * @property {number} end.location
  6702. * @property {number} end.percentage
  6703. * @property {number} end.displayed.page
  6704. * @property {number} end.displayed.total
  6705. * @property {boolean} atStart
  6706. * @property {boolean} atEnd
  6707. * @memberof Rendition
  6708. */
  6709. this.location = undefined;
  6710. // Hold queue until book is opened
  6711. this.q.enqueue(this.book.opened);
  6712. this.starting = new _core.defer();
  6713. /**
  6714. * @member {promise} started returns after the rendition has started
  6715. * @memberof Rendition
  6716. */
  6717. this.started = this.starting.promise;
  6718. // Block the queue until rendering is started
  6719. this.q.enqueue(this.start);
  6720. }
  6721. /**
  6722. * Set the manager function
  6723. * @param {function} manager
  6724. */
  6725. _createClass(Rendition, [{
  6726. key: "setManager",
  6727. value: function setManager(manager) {
  6728. this.manager = manager;
  6729. }
  6730. /**
  6731. * Require the manager from passed string, or as a class function
  6732. * @param {string|object} manager [description]
  6733. * @return {method}
  6734. */
  6735. }, {
  6736. key: "requireManager",
  6737. value: function requireManager(manager) {
  6738. var viewManager;
  6739. // If manager is a string, try to load from imported managers
  6740. if (typeof manager === "string" && manager === "default") {
  6741. viewManager = _index2.default;
  6742. } else if (typeof manager === "string" && manager === "continuous") {
  6743. viewManager = _index4.default;
  6744. } else {
  6745. // otherwise, assume we were passed a class function
  6746. viewManager = manager;
  6747. }
  6748. return viewManager;
  6749. }
  6750. /**
  6751. * Require the view from passed string, or as a class function
  6752. * @param {string|object} view
  6753. * @return {view}
  6754. */
  6755. }, {
  6756. key: "requireView",
  6757. value: function requireView(view) {
  6758. var View;
  6759. // If view is a string, try to load from imported views,
  6760. if (typeof view == "string" && view === "iframe") {
  6761. View = _iframe2.default;
  6762. } else {
  6763. // otherwise, assume we were passed a class function
  6764. View = view;
  6765. }
  6766. return View;
  6767. }
  6768. /**
  6769. * Start the rendering
  6770. * @return {Promise} rendering has started
  6771. */
  6772. }, {
  6773. key: "start",
  6774. value: function start() {
  6775. if (!this.manager) {
  6776. this.ViewManager = this.requireManager(this.settings.manager);
  6777. this.View = this.requireView(this.settings.view);
  6778. this.manager = new this.ViewManager({
  6779. view: this.View,
  6780. queue: this.q,
  6781. request: this.book.load.bind(this.book),
  6782. settings: this.settings
  6783. });
  6784. }
  6785. this.direction(this.book.package.metadata.direction);
  6786. // Parse metadata to get layout props
  6787. this.settings.globalLayoutProperties = this.determineLayoutProperties(this.book.package.metadata);
  6788. this.flow(this.settings.globalLayoutProperties.flow);
  6789. this.layout(this.settings.globalLayoutProperties);
  6790. // Listen for displayed views
  6791. this.manager.on(_constants.EVENTS.MANAGERS.ADDED, this.afterDisplayed.bind(this));
  6792. this.manager.on(_constants.EVENTS.MANAGERS.REMOVED, this.afterRemoved.bind(this));
  6793. // Listen for resizing
  6794. this.manager.on(_constants.EVENTS.MANAGERS.RESIZED, this.onResized.bind(this));
  6795. // Listen for rotation
  6796. this.manager.on(_constants.EVENTS.MANAGERS.ORIENTATION_CHANGE, this.onOrientationChange.bind(this));
  6797. // Listen for scroll changes
  6798. this.manager.on(_constants.EVENTS.MANAGERS.SCROLLED, this.reportLocation.bind(this));
  6799. /**
  6800. * Emit that rendering has started
  6801. * @event started
  6802. * @memberof Rendition
  6803. */
  6804. this.emit(_constants.EVENTS.RENDITION.STARTED);
  6805. // Start processing queue
  6806. this.starting.resolve();
  6807. }
  6808. /**
  6809. * Call to attach the container to an element in the dom
  6810. * Container must be attached before rendering can begin
  6811. * @param {element} element to attach to
  6812. * @return {Promise}
  6813. */
  6814. }, {
  6815. key: "attachTo",
  6816. value: function attachTo(element) {
  6817. return this.q.enqueue(function () {
  6818. // Start rendering
  6819. this.manager.render(element, {
  6820. "width": this.settings.width,
  6821. "height": this.settings.height
  6822. });
  6823. /**
  6824. * Emit that rendering has attached to an element
  6825. * @event attached
  6826. * @memberof Rendition
  6827. */
  6828. this.emit(_constants.EVENTS.RENDITION.ATTACHED);
  6829. }.bind(this));
  6830. }
  6831. /**
  6832. * Display a point in the book
  6833. * The request will be added to the rendering Queue,
  6834. * so it will wait until book is opened, rendering started
  6835. * and all other rendering tasks have finished to be called.
  6836. * @param {string} target Url or EpubCFI
  6837. * @return {Promise}
  6838. */
  6839. }, {
  6840. key: "display",
  6841. value: function display(target) {
  6842. if (this.displaying) {
  6843. this.displaying.resolve();
  6844. }
  6845. return this.q.enqueue(this._display, target);
  6846. }
  6847. /**
  6848. * Tells the manager what to display immediately
  6849. * @private
  6850. * @param {string} target Url or EpubCFI
  6851. * @return {Promise}
  6852. */
  6853. }, {
  6854. key: "_display",
  6855. value: function _display(target) {
  6856. var _this = this;
  6857. if (!this.book) {
  6858. return;
  6859. }
  6860. var isCfiString = this.epubcfi.isCfiString(target);
  6861. var displaying = new _core.defer();
  6862. var displayed = displaying.promise;
  6863. var section;
  6864. var moveTo;
  6865. this.displaying = displaying;
  6866. // Check if this is a book percentage
  6867. if (this.book.locations.length() && (0, _core.isFloat)(target)) {
  6868. target = this.book.locations.cfiFromPercentage(parseFloat(target));
  6869. }
  6870. section = this.book.spine.get(target);
  6871. if (!section) {
  6872. displaying.reject(new Error("No Section Found"));
  6873. return displayed;
  6874. }
  6875. this.manager.display(section, target).then(function () {
  6876. displaying.resolve(section);
  6877. _this.displaying = undefined;
  6878. /**
  6879. * Emit that a section has been displayed
  6880. * @event displayed
  6881. * @param {Section} section
  6882. * @memberof Rendition
  6883. */
  6884. _this.emit(_constants.EVENTS.RENDITION.DISPLAYED, section);
  6885. _this.reportLocation();
  6886. }, function (err) {
  6887. /**
  6888. * Emit that has been an error displaying
  6889. * @event displayError
  6890. * @param {Section} section
  6891. * @memberof Rendition
  6892. */
  6893. _this.emit(_constants.EVENTS.RENDITION.DISPLAY_ERROR, err);
  6894. });
  6895. return displayed;
  6896. }
  6897. /*
  6898. render(view, show) {
  6899. // view.onLayout = this.layout.format.bind(this.layout);
  6900. view.create();
  6901. // Fit to size of the container, apply padding
  6902. this.manager.resizeView(view);
  6903. // Render Chain
  6904. return view.section.render(this.book.request)
  6905. .then(function(contents){
  6906. return view.load(contents);
  6907. }.bind(this))
  6908. .then(function(doc){
  6909. return this.hooks.content.trigger(view, this);
  6910. }.bind(this))
  6911. .then(function(){
  6912. this.layout.format(view.contents);
  6913. return this.hooks.layout.trigger(view, this);
  6914. }.bind(this))
  6915. .then(function(){
  6916. return view.display();
  6917. }.bind(this))
  6918. .then(function(){
  6919. return this.hooks.render.trigger(view, this);
  6920. }.bind(this))
  6921. .then(function(){
  6922. if(show !== false) {
  6923. this.q.enqueue(function(view){
  6924. view.show();
  6925. }, view);
  6926. }
  6927. // this.map = new Map(view, this.layout);
  6928. this.hooks.show.trigger(view, this);
  6929. this.trigger("rendered", view.section);
  6930. }.bind(this))
  6931. .catch(function(e){
  6932. this.trigger("loaderror", e);
  6933. }.bind(this));
  6934. }
  6935. */
  6936. /**
  6937. * Report what section has been displayed
  6938. * @private
  6939. * @param {*} view
  6940. */
  6941. }, {
  6942. key: "afterDisplayed",
  6943. value: function afterDisplayed(view) {
  6944. var _this2 = this;
  6945. view.on(_constants.EVENTS.VIEWS.MARK_CLICKED, function (cfiRange, data) {
  6946. return _this2.triggerMarkEvent(cfiRange, data, view);
  6947. });
  6948. this.hooks.render.trigger(view, this).then(function () {
  6949. if (view.contents) {
  6950. _this2.hooks.content.trigger(view.contents, _this2).then(function () {
  6951. /**
  6952. * Emit that a section has been rendered
  6953. * @event rendered
  6954. * @param {Section} section
  6955. * @param {View} view
  6956. * @memberof Rendition
  6957. */
  6958. _this2.emit(_constants.EVENTS.RENDITION.RENDERED, view.section, view);
  6959. });
  6960. } else {
  6961. _this2.emit(_constants.EVENTS.RENDITION.RENDERED, view.section, view);
  6962. }
  6963. });
  6964. }
  6965. /**
  6966. * Report what has been removed
  6967. * @private
  6968. * @param {*} view
  6969. */
  6970. }, {
  6971. key: "afterRemoved",
  6972. value: function afterRemoved(view) {
  6973. var _this3 = this;
  6974. this.hooks.unloaded.trigger(view, this).then(function () {
  6975. /**
  6976. * Emit that a section has been removed
  6977. * @event removed
  6978. * @param {Section} section
  6979. * @param {View} view
  6980. * @memberof Rendition
  6981. */
  6982. _this3.emit(_constants.EVENTS.RENDITION.REMOVED, view.section, view);
  6983. });
  6984. }
  6985. /**
  6986. * Report resize events and display the last seen location
  6987. * @private
  6988. */
  6989. }, {
  6990. key: "onResized",
  6991. value: function onResized(size) {
  6992. /**
  6993. * Emit that the rendition has been resized
  6994. * @event resized
  6995. * @param {number} width
  6996. * @param {height} height
  6997. * @memberof Rendition
  6998. */
  6999. this.emit(_constants.EVENTS.RENDITION.RESIZED, {
  7000. width: size.width,
  7001. height: size.height
  7002. });
  7003. if (this.location && this.location.start) {
  7004. this.display(this.location.start.cfi);
  7005. }
  7006. }
  7007. /**
  7008. * Report orientation events and display the last seen location
  7009. * @private
  7010. */
  7011. }, {
  7012. key: "onOrientationChange",
  7013. value: function onOrientationChange(orientation) {
  7014. /**
  7015. * Emit that the rendition has been rotated
  7016. * @event orientationchange
  7017. * @param {string} orientation
  7018. * @memberof Rendition
  7019. */
  7020. this.emit(_constants.EVENTS.RENDITION.ORIENTATION_CHANGE, orientation);
  7021. }
  7022. /**
  7023. * Move the Rendition to a specific offset
  7024. * Usually you would be better off calling display()
  7025. * @param {object} offset
  7026. */
  7027. }, {
  7028. key: "moveTo",
  7029. value: function moveTo(offset) {
  7030. this.manager.moveTo(offset);
  7031. }
  7032. /**
  7033. * Trigger a resize of the views
  7034. * @param {number} [width]
  7035. * @param {number} [height]
  7036. */
  7037. }, {
  7038. key: "resize",
  7039. value: function resize(width, height) {
  7040. if (width) {
  7041. this.settings.width = width;
  7042. }
  7043. if (height) {
  7044. this.settings.height = height;
  7045. }
  7046. this.manager.resize(width, height);
  7047. }
  7048. /**
  7049. * Clear all rendered views
  7050. */
  7051. }, {
  7052. key: "clear",
  7053. value: function clear() {
  7054. this.manager.clear();
  7055. }
  7056. /**
  7057. * Go to the next "page" in the rendition
  7058. * @return {Promise}
  7059. */
  7060. }, {
  7061. key: "next",
  7062. value: function next() {
  7063. return this.q.enqueue(this.manager.next.bind(this.manager)).then(this.reportLocation.bind(this));
  7064. }
  7065. /**
  7066. * Go to the previous "page" in the rendition
  7067. * @return {Promise}
  7068. */
  7069. }, {
  7070. key: "prev",
  7071. value: function prev() {
  7072. return this.q.enqueue(this.manager.prev.bind(this.manager)).then(this.reportLocation.bind(this));
  7073. }
  7074. //-- http://www.idpf.org/epub/301/spec/epub-publications.html#meta-properties-rendering
  7075. /**
  7076. * Determine the Layout properties from metadata and settings
  7077. * @private
  7078. * @param {object} metadata
  7079. * @return {object} properties
  7080. */
  7081. }, {
  7082. key: "determineLayoutProperties",
  7083. value: function determineLayoutProperties(metadata) {
  7084. var properties;
  7085. var layout = this.settings.layout || metadata.layout || "reflowable";
  7086. var spread = this.settings.spread || metadata.spread || "auto";
  7087. var orientation = this.settings.orientation || metadata.orientation || "auto";
  7088. var flow = this.settings.flow || metadata.flow || "auto";
  7089. var viewport = metadata.viewport || "";
  7090. var minSpreadWidth = this.settings.minSpreadWidth || metadata.minSpreadWidth || 800;
  7091. var direction = this.settings.direction || metadata.direction || "ltr";
  7092. if ((this.settings.width === 0 || this.settings.width > 0) && (this.settings.height === 0 || this.settings.height > 0)) {
  7093. // viewport = "width="+this.settings.width+", height="+this.settings.height+"";
  7094. }
  7095. properties = {
  7096. layout: layout,
  7097. spread: spread,
  7098. orientation: orientation,
  7099. flow: flow,
  7100. viewport: viewport,
  7101. minSpreadWidth: minSpreadWidth,
  7102. direction: direction
  7103. };
  7104. return properties;
  7105. }
  7106. /**
  7107. * Adjust the flow of the rendition to paginated or scrolled
  7108. * (scrolled-continuous vs scrolled-doc are handled by different view managers)
  7109. * @param {string} flow
  7110. */
  7111. }, {
  7112. key: "flow",
  7113. value: function flow(_flow2) {
  7114. var _flow = _flow2;
  7115. if (_flow2 === "scrolled" || _flow2 === "scrolled-doc" || _flow2 === "scrolled-continuous") {
  7116. _flow = "scrolled";
  7117. }
  7118. if (_flow2 === "auto" || _flow2 === "paginated") {
  7119. _flow = "paginated";
  7120. }
  7121. this.settings.flow = _flow2;
  7122. if (this._layout) {
  7123. this._layout.flow(_flow);
  7124. }
  7125. if (this.manager && this._layout) {
  7126. this.manager.applyLayout(this._layout);
  7127. }
  7128. if (this.manager) {
  7129. this.manager.updateFlow(_flow);
  7130. }
  7131. if (this.manager && this.manager.isRendered() && this.location) {
  7132. this.manager.clear();
  7133. this.display(this.location.start.cfi);
  7134. }
  7135. }
  7136. /**
  7137. * Adjust the layout of the rendition to reflowable or pre-paginated
  7138. * @param {object} settings
  7139. */
  7140. }, {
  7141. key: "layout",
  7142. value: function layout(settings) {
  7143. var _this4 = this;
  7144. if (settings) {
  7145. this._layout = new _layout2.default(settings);
  7146. this._layout.spread(settings.spread, this.settings.minSpreadWidth);
  7147. // this.mapping = new Mapping(this._layout.props);
  7148. this._layout.on(_constants.EVENTS.LAYOUT.UPDATED, function (props, changed) {
  7149. _this4.emit(_constants.EVENTS.RENDITION.LAYOUT, props, changed);
  7150. });
  7151. }
  7152. if (this.manager && this._layout) {
  7153. this.manager.applyLayout(this._layout);
  7154. }
  7155. return this._layout;
  7156. }
  7157. /**
  7158. * Adjust if the rendition uses spreads
  7159. * @param {string} spread none | auto (TODO: implement landscape, portrait, both)
  7160. * @param {int} min min width to use spreads at
  7161. */
  7162. }, {
  7163. key: "spread",
  7164. value: function spread(_spread, min) {
  7165. this._layout.spread(_spread, min);
  7166. if (this.manager.isRendered()) {
  7167. this.manager.updateLayout();
  7168. }
  7169. }
  7170. /**
  7171. * Adjust the direction of the rendition
  7172. * @param {string} dir
  7173. */
  7174. }, {
  7175. key: "direction",
  7176. value: function direction(dir) {
  7177. this.settings.direction = dir || "ltr";
  7178. if (this.manager) {
  7179. this.manager.direction(this.settings.direction);
  7180. }
  7181. if (this.manager && this.manager.isRendered() && this.location) {
  7182. this.manager.clear();
  7183. this.display(this.location.start.cfi);
  7184. }
  7185. }
  7186. /**
  7187. * Report the current location
  7188. * @fires relocated
  7189. * @fires locationChanged
  7190. */
  7191. }, {
  7192. key: "reportLocation",
  7193. value: function reportLocation() {
  7194. return this.q.enqueue(function reportedLocation() {
  7195. requestAnimationFrame(function reportedLocationAfterRAF() {
  7196. var location = this.manager.currentLocation();
  7197. if (location && location.then && typeof location.then === "function") {
  7198. location.then(function (result) {
  7199. var located = this.located(result);
  7200. if (!located || !located.start || !located.end) {
  7201. return;
  7202. }
  7203. this.location = located;
  7204. this.emit(_constants.EVENTS.RENDITION.LOCATION_CHANGED, {
  7205. index: this.location.start.index,
  7206. href: this.location.start.href,
  7207. start: this.location.start.cfi,
  7208. end: this.location.end.cfi,
  7209. percentage: this.location.start.percentage
  7210. });
  7211. this.emit(_constants.EVENTS.RENDITION.RELOCATED, this.location);
  7212. }.bind(this));
  7213. } else if (location) {
  7214. var located = this.located(location);
  7215. if (!located || !located.start || !located.end) {
  7216. return;
  7217. }
  7218. this.location = located;
  7219. /**
  7220. * @event locationChanged
  7221. * @deprecated
  7222. * @type {object}
  7223. * @property {number} index
  7224. * @property {string} href
  7225. * @property {EpubCFI} start
  7226. * @property {EpubCFI} end
  7227. * @property {number} percentage
  7228. * @memberof Rendition
  7229. */
  7230. this.emit(_constants.EVENTS.RENDITION.LOCATION_CHANGED, {
  7231. index: this.location.start.index,
  7232. href: this.location.start.href,
  7233. start: this.location.start.cfi,
  7234. end: this.location.end.cfi,
  7235. percentage: this.location.start.percentage
  7236. });
  7237. /**
  7238. * @event relocated
  7239. * @type {displayedLocation}
  7240. * @memberof Rendition
  7241. */
  7242. this.emit(_constants.EVENTS.RENDITION.RELOCATED, this.location);
  7243. }
  7244. }.bind(this));
  7245. }.bind(this));
  7246. }
  7247. /**
  7248. * Get the Current Location object
  7249. * @return {displayedLocation | promise} location (may be a promise)
  7250. */
  7251. }, {
  7252. key: "currentLocation",
  7253. value: function currentLocation() {
  7254. var location = this.manager.currentLocation();
  7255. if (location && location.then && typeof location.then === "function") {
  7256. location.then(function (result) {
  7257. var located = this.located(result);
  7258. return located;
  7259. }.bind(this));
  7260. } else if (location) {
  7261. var located = this.located(location);
  7262. return located;
  7263. }
  7264. }
  7265. /**
  7266. * Creates a Rendition#locationRange from location
  7267. * passed by the Manager
  7268. * @returns {displayedLocation}
  7269. * @private
  7270. */
  7271. }, {
  7272. key: "located",
  7273. value: function located(location) {
  7274. if (!location.length) {
  7275. return {};
  7276. }
  7277. var start = location[0];
  7278. var end = location[location.length - 1];
  7279. var located = {
  7280. start: {
  7281. index: start.index,
  7282. href: start.href,
  7283. cfi: start.mapping.start,
  7284. displayed: {
  7285. page: start.pages[0] || 1,
  7286. total: start.totalPages
  7287. }
  7288. },
  7289. end: {
  7290. index: end.index,
  7291. href: end.href,
  7292. cfi: end.mapping.end,
  7293. displayed: {
  7294. page: end.pages[end.pages.length - 1] || 1,
  7295. total: end.totalPages
  7296. }
  7297. }
  7298. };
  7299. var locationStart = this.book.locations.locationFromCfi(start.mapping.start);
  7300. var locationEnd = this.book.locations.locationFromCfi(end.mapping.end);
  7301. if (locationStart != null) {
  7302. located.start.location = locationStart;
  7303. located.start.percentage = this.book.locations.percentageFromLocation(locationStart);
  7304. }
  7305. if (locationEnd != null) {
  7306. located.end.location = locationEnd;
  7307. located.end.percentage = this.book.locations.percentageFromLocation(locationEnd);
  7308. }
  7309. var pageStart = this.book.pageList.pageFromCfi(start.mapping.start);
  7310. var pageEnd = this.book.pageList.pageFromCfi(end.mapping.end);
  7311. if (pageStart != -1) {
  7312. located.start.page = pageStart;
  7313. }
  7314. if (pageEnd != -1) {
  7315. located.end.page = pageEnd;
  7316. }
  7317. if (end.index === this.book.spine.last().index && located.end.displayed.page >= located.end.displayed.total) {
  7318. located.atEnd = true;
  7319. }
  7320. if (start.index === this.book.spine.first().index && located.start.displayed.page === 1) {
  7321. located.atStart = true;
  7322. }
  7323. return located;
  7324. }
  7325. /**
  7326. * Remove and Clean Up the Rendition
  7327. */
  7328. }, {
  7329. key: "destroy",
  7330. value: function destroy() {
  7331. // Clear the queue
  7332. // this.q.clear();
  7333. // this.q = undefined;
  7334. this.manager && this.manager.destroy();
  7335. this.book = undefined;
  7336. // this.views = null;
  7337. // this.hooks.display.clear();
  7338. // this.hooks.serialize.clear();
  7339. // this.hooks.content.clear();
  7340. // this.hooks.layout.clear();
  7341. // this.hooks.render.clear();
  7342. // this.hooks.show.clear();
  7343. // this.hooks = {};
  7344. // this.themes.destroy();
  7345. // this.themes = undefined;
  7346. // this.epubcfi = undefined;
  7347. // this.starting = undefined;
  7348. // this.started = undefined;
  7349. }
  7350. /**
  7351. * Pass the events from a view's Contents
  7352. * @private
  7353. * @param {Contents} view contents
  7354. */
  7355. }, {
  7356. key: "passEvents",
  7357. value: function passEvents(contents) {
  7358. var _this5 = this;
  7359. var listenedEvents = _contents2.default.listenedEvents;
  7360. listenedEvents.forEach(function (e) {
  7361. contents.on(e, function (ev) {
  7362. return _this5.triggerViewEvent(ev, contents);
  7363. });
  7364. });
  7365. contents.on(_constants.EVENTS.CONTENTS.SELECTED, function (e) {
  7366. return _this5.triggerSelectedEvent(e, contents);
  7367. });
  7368. }
  7369. /**
  7370. * Emit events passed by a view
  7371. * @private
  7372. * @param {event} e
  7373. */
  7374. }, {
  7375. key: "triggerViewEvent",
  7376. value: function triggerViewEvent(e, contents) {
  7377. this.emit(e.type, e, contents);
  7378. }
  7379. /**
  7380. * Emit a selection event's CFI Range passed from a a view
  7381. * @private
  7382. * @param {EpubCFI} cfirange
  7383. */
  7384. }, {
  7385. key: "triggerSelectedEvent",
  7386. value: function triggerSelectedEvent(cfirange, contents) {
  7387. /**
  7388. * Emit that a text selection has occured
  7389. * @event selected
  7390. * @param {EpubCFI} cfirange
  7391. * @param {Contents} contents
  7392. * @memberof Rendition
  7393. */
  7394. this.emit(_constants.EVENTS.RENDITION.SELECTED, cfirange, contents);
  7395. }
  7396. /**
  7397. * Emit a markClicked event with the cfiRange and data from a mark
  7398. * @private
  7399. * @param {EpubCFI} cfirange
  7400. */
  7401. }, {
  7402. key: "triggerMarkEvent",
  7403. value: function triggerMarkEvent(cfiRange, data, contents) {
  7404. /**
  7405. * Emit that a mark was clicked
  7406. * @event markClicked
  7407. * @param {EpubCFI} cfirange
  7408. * @param {object} data
  7409. * @param {Contents} contents
  7410. * @memberof Rendition
  7411. */
  7412. this.emit(_constants.EVENTS.RENDITION.MARK_CLICKED, cfiRange, data, contents);
  7413. }
  7414. /**
  7415. * Get a Range from a Visible CFI
  7416. * @param {string} cfi EpubCfi String
  7417. * @param {string} ignoreClass
  7418. * @return {range}
  7419. */
  7420. }, {
  7421. key: "getRange",
  7422. value: function getRange(cfi, ignoreClass) {
  7423. var _cfi = new _epubcfi2.default(cfi);
  7424. var found = this.manager.visible().filter(function (view) {
  7425. if (_cfi.spinePos === view.index) return true;
  7426. });
  7427. // Should only every return 1 item
  7428. if (found.length) {
  7429. return found[0].contents.range(_cfi, ignoreClass);
  7430. }
  7431. }
  7432. /**
  7433. * Hook to adjust images to fit in columns
  7434. * @param {Contents} contents
  7435. * @private
  7436. */
  7437. }, {
  7438. key: "adjustImages",
  7439. value: function adjustImages(contents) {
  7440. if (this._layout.name === "pre-paginated") {
  7441. return new Promise(function (resolve) {
  7442. resolve();
  7443. });
  7444. }
  7445. var computed = contents.window.getComputedStyle(contents.content, null);
  7446. var height = contents.content.offsetHeight - (parseFloat(computed.paddingTop) + parseFloat(computed.paddingBottom));
  7447. contents.addStylesheetRules({
  7448. "img": {
  7449. "max-width": (this._layout.columnWidth ? this._layout.columnWidth + "px" : "100%") + "!important",
  7450. "max-height": height + "px" + "!important",
  7451. "object-fit": "contain",
  7452. "page-break-inside": "avoid",
  7453. "break-inside": "avoid"
  7454. },
  7455. "svg": {
  7456. "max-width": (this._layout.columnWidth ? this._layout.columnWidth + "px" : "100%") + "!important",
  7457. "max-height": height + "px" + "!important",
  7458. "page-break-inside": "avoid",
  7459. "break-inside": "avoid"
  7460. }
  7461. });
  7462. return new Promise(function (resolve, reject) {
  7463. // Wait to apply
  7464. setTimeout(function () {
  7465. resolve();
  7466. }, 1);
  7467. });
  7468. }
  7469. /**
  7470. * Get the Contents object of each rendered view
  7471. * @returns {Contents[]}
  7472. */
  7473. }, {
  7474. key: "getContents",
  7475. value: function getContents() {
  7476. return this.manager ? this.manager.getContents() : [];
  7477. }
  7478. /**
  7479. * Get the views member from the manager
  7480. * @returns {Views}
  7481. */
  7482. }, {
  7483. key: "views",
  7484. value: function views() {
  7485. var views = this.manager ? this.manager.views : undefined;
  7486. return views || [];
  7487. }
  7488. /**
  7489. * Hook to handle link clicks in rendered content
  7490. * @param {Contents} contents
  7491. * @private
  7492. */
  7493. }, {
  7494. key: "handleLinks",
  7495. value: function handleLinks(contents) {
  7496. var _this6 = this;
  7497. if (contents) {
  7498. contents.on(_constants.EVENTS.CONTENTS.LINK_CLICKED, function (href) {
  7499. var relative = _this6.book.path.relative(href);
  7500. _this6.display(relative);
  7501. });
  7502. }
  7503. }
  7504. /**
  7505. * Hook to handle injecting stylesheet before
  7506. * a Section is serialized
  7507. * @param {document} doc
  7508. * @param {Section} section
  7509. * @private
  7510. */
  7511. }, {
  7512. key: "injectStylesheet",
  7513. value: function injectStylesheet(doc, section) {
  7514. var style = doc.createElement("link");
  7515. style.setAttribute("type", "text/css");
  7516. style.setAttribute("rel", "stylesheet");
  7517. style.setAttribute("href", this.settings.stylesheet);
  7518. doc.getElementsByTagName("head")[0].appendChild(style);
  7519. }
  7520. /**
  7521. * Hook to handle injecting scripts before
  7522. * a Section is serialized
  7523. * @param {document} doc
  7524. * @param {Section} section
  7525. * @private
  7526. */
  7527. }, {
  7528. key: "injectScript",
  7529. value: function injectScript(doc, section) {
  7530. var script = doc.createElement("script");
  7531. script.setAttribute("type", "text/javascript");
  7532. script.setAttribute("src", this.settings.script);
  7533. script.textContent = " "; // Needed to prevent self closing tag
  7534. doc.getElementsByTagName("head")[0].appendChild(script);
  7535. }
  7536. /**
  7537. * Hook to handle the document identifier before
  7538. * a Section is serialized
  7539. * @param {document} doc
  7540. * @param {Section} section
  7541. * @private
  7542. */
  7543. }, {
  7544. key: "injectIdentifier",
  7545. value: function injectIdentifier(doc, section) {
  7546. var ident = this.book.package.metadata.identifier;
  7547. var meta = doc.createElement("meta");
  7548. meta.setAttribute("name", "dc.relation.ispartof");
  7549. if (ident) {
  7550. meta.setAttribute("content", ident);
  7551. }
  7552. doc.getElementsByTagName("head")[0].appendChild(meta);
  7553. }
  7554. }]);
  7555. return Rendition;
  7556. }();
  7557. //-- Enable binding events to Renderer
  7558. (0, _eventEmitter2.default)(Rendition.prototype);
  7559. exports.default = Rendition;
  7560. module.exports = exports["default"];
  7561. /***/ }),
  7562. /* 19 */
  7563. /***/ (function(module, exports, __webpack_require__) {
  7564. "use strict";
  7565. Object.defineProperty(exports, "__esModule", {
  7566. value: true
  7567. });
  7568. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  7569. var _epubcfi = __webpack_require__(1);
  7570. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  7571. var _core = __webpack_require__(0);
  7572. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7573. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7574. /**
  7575. * Map text locations to CFI ranges
  7576. * @class
  7577. * @param {Layout} layout Layout to apply
  7578. * @param {string} [direction="ltr"] Text direction
  7579. * @param {string} [axis="horizontal"] vertical or horizontal axis
  7580. * @param {boolean} [dev] toggle developer highlighting
  7581. */
  7582. var Mapping = function () {
  7583. function Mapping(layout, direction, axis, dev) {
  7584. _classCallCheck(this, Mapping);
  7585. this.layout = layout;
  7586. this.horizontal = axis === "horizontal" ? true : false;
  7587. this.direction = direction || "ltr";
  7588. this._dev = dev;
  7589. }
  7590. /**
  7591. * Find CFI pairs for entire section at once
  7592. */
  7593. _createClass(Mapping, [{
  7594. key: "section",
  7595. value: function section(view) {
  7596. var ranges = this.findRanges(view);
  7597. var map = this.rangeListToCfiList(view.section.cfiBase, ranges);
  7598. return map;
  7599. }
  7600. /**
  7601. * Find CFI pairs for a page
  7602. * @param {Contents} contents Contents from view
  7603. * @param {string} cfiBase string of the base for a cfi
  7604. * @param {number} start position to start at
  7605. * @param {number} end position to end at
  7606. */
  7607. }, {
  7608. key: "page",
  7609. value: function page(contents, cfiBase, start, end) {
  7610. var root = contents && contents.document ? contents.document.body : false;
  7611. var result;
  7612. if (!root) {
  7613. return;
  7614. }
  7615. result = this.rangePairToCfiPair(cfiBase, {
  7616. start: this.findStart(root, start, end),
  7617. end: this.findEnd(root, start, end)
  7618. });
  7619. if (this._dev === true) {
  7620. var doc = contents.document;
  7621. var startRange = new _epubcfi2.default(result.start).toRange(doc);
  7622. var endRange = new _epubcfi2.default(result.end).toRange(doc);
  7623. var selection = doc.defaultView.getSelection();
  7624. var r = doc.createRange();
  7625. selection.removeAllRanges();
  7626. r.setStart(startRange.startContainer, startRange.startOffset);
  7627. r.setEnd(endRange.endContainer, endRange.endOffset);
  7628. selection.addRange(r);
  7629. }
  7630. return result;
  7631. }
  7632. /**
  7633. * Walk a node, preforming a function on each node it finds
  7634. * @private
  7635. * @param {Node} root Node to walkToNode
  7636. * @param {function} func walk function
  7637. * @return {*} returns the result of the walk function
  7638. */
  7639. }, {
  7640. key: "walk",
  7641. value: function walk(root, func) {
  7642. // IE11 has strange issue, if root is text node IE throws exception on
  7643. // calling treeWalker.nextNode(), saying
  7644. // Unexpected call to method or property access instead of returing null value
  7645. if (root && root.nodeType === Node.TEXT_NODE) {
  7646. return;
  7647. }
  7648. // safeFilter is required so that it can work in IE as filter is a function for IE
  7649. // and for other browser filter is an object.
  7650. var filter = {
  7651. acceptNode: function acceptNode(node) {
  7652. if (node.data.trim().length > 0) {
  7653. return NodeFilter.FILTER_ACCEPT;
  7654. } else {
  7655. return NodeFilter.FILTER_REJECT;
  7656. }
  7657. }
  7658. };
  7659. var safeFilter = filter.acceptNode;
  7660. safeFilter.acceptNode = filter.acceptNode;
  7661. var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, safeFilter, false);
  7662. var node;
  7663. var result;
  7664. while (node = treeWalker.nextNode()) {
  7665. result = func(node);
  7666. if (result) break;
  7667. }
  7668. return result;
  7669. }
  7670. }, {
  7671. key: "findRanges",
  7672. value: function findRanges(view) {
  7673. var columns = [];
  7674. var scrollWidth = view.contents.scrollWidth();
  7675. var spreads = Math.ceil(scrollWidth / this.layout.spreadWidth);
  7676. var count = spreads * this.layout.divisor;
  7677. var columnWidth = this.layout.columnWidth;
  7678. var gap = this.layout.gap;
  7679. var start, end;
  7680. for (var i = 0; i < count.pages; i++) {
  7681. start = (columnWidth + gap) * i;
  7682. end = columnWidth * (i + 1) + gap * i;
  7683. columns.push({
  7684. start: this.findStart(view.document.body, start, end),
  7685. end: this.findEnd(view.document.body, start, end)
  7686. });
  7687. }
  7688. return columns;
  7689. }
  7690. /**
  7691. * Find Start Range
  7692. * @private
  7693. * @param {Node} root root node
  7694. * @param {number} start position to start at
  7695. * @param {number} end position to end at
  7696. * @return {Range}
  7697. */
  7698. }, {
  7699. key: "findStart",
  7700. value: function findStart(root, start, end) {
  7701. var _this = this;
  7702. var stack = [root];
  7703. var $el;
  7704. var found;
  7705. var $prev = root;
  7706. while (stack.length) {
  7707. $el = stack.shift();
  7708. found = this.walk($el, function (node) {
  7709. var left, right, top, bottom;
  7710. var elPos;
  7711. var elRange;
  7712. elPos = (0, _core.nodeBounds)(node);
  7713. if (_this.horizontal && _this.direction === "ltr") {
  7714. left = _this.horizontal ? elPos.left : elPos.top;
  7715. right = _this.horizontal ? elPos.right : elPos.bottom;
  7716. if (left >= start && left <= end) {
  7717. return node;
  7718. } else if (right > start) {
  7719. return node;
  7720. } else {
  7721. $prev = node;
  7722. stack.push(node);
  7723. }
  7724. } else if (_this.horizontal && _this.direction === "rtl") {
  7725. left = elPos.left;
  7726. right = elPos.right;
  7727. if (right <= end && right >= start) {
  7728. return node;
  7729. } else if (left < end) {
  7730. return node;
  7731. } else {
  7732. $prev = node;
  7733. stack.push(node);
  7734. }
  7735. } else {
  7736. top = elPos.top;
  7737. bottom = elPos.bottom;
  7738. if (top >= start && top <= end) {
  7739. return node;
  7740. } else if (bottom > start) {
  7741. return node;
  7742. } else {
  7743. $prev = node;
  7744. stack.push(node);
  7745. }
  7746. }
  7747. });
  7748. if (found) {
  7749. return this.findTextStartRange(found, start, end);
  7750. }
  7751. }
  7752. // Return last element
  7753. return this.findTextStartRange($prev, start, end);
  7754. }
  7755. /**
  7756. * Find End Range
  7757. * @private
  7758. * @param {Node} root root node
  7759. * @param {number} start position to start at
  7760. * @param {number} end position to end at
  7761. * @return {Range}
  7762. */
  7763. }, {
  7764. key: "findEnd",
  7765. value: function findEnd(root, start, end) {
  7766. var _this2 = this;
  7767. var stack = [root];
  7768. var $el;
  7769. var $prev = root;
  7770. var found;
  7771. while (stack.length) {
  7772. $el = stack.shift();
  7773. found = this.walk($el, function (node) {
  7774. var left, right, top, bottom;
  7775. var elPos;
  7776. var elRange;
  7777. elPos = (0, _core.nodeBounds)(node);
  7778. if (_this2.horizontal && _this2.direction === "ltr") {
  7779. left = Math.round(elPos.left);
  7780. right = Math.round(elPos.right);
  7781. if (left > end && $prev) {
  7782. return $prev;
  7783. } else if (right > end) {
  7784. return node;
  7785. } else {
  7786. $prev = node;
  7787. stack.push(node);
  7788. }
  7789. } else if (_this2.horizontal && _this2.direction === "rtl") {
  7790. left = Math.round(_this2.horizontal ? elPos.left : elPos.top);
  7791. right = Math.round(_this2.horizontal ? elPos.right : elPos.bottom);
  7792. if (right < start && $prev) {
  7793. return $prev;
  7794. } else if (left < start) {
  7795. return node;
  7796. } else {
  7797. $prev = node;
  7798. stack.push(node);
  7799. }
  7800. } else {
  7801. top = Math.round(elPos.top);
  7802. bottom = Math.round(elPos.bottom);
  7803. if (top > end && $prev) {
  7804. return $prev;
  7805. } else if (bottom > end) {
  7806. return node;
  7807. } else {
  7808. $prev = node;
  7809. stack.push(node);
  7810. }
  7811. }
  7812. });
  7813. if (found) {
  7814. return this.findTextEndRange(found, start, end);
  7815. }
  7816. }
  7817. // end of chapter
  7818. return this.findTextEndRange($prev, start, end);
  7819. }
  7820. /**
  7821. * Find Text Start Range
  7822. * @private
  7823. * @param {Node} root root node
  7824. * @param {number} start position to start at
  7825. * @param {number} end position to end at
  7826. * @return {Range}
  7827. */
  7828. }, {
  7829. key: "findTextStartRange",
  7830. value: function findTextStartRange(node, start, end) {
  7831. var ranges = this.splitTextNodeIntoRanges(node);
  7832. var range;
  7833. var pos;
  7834. var left, top, right;
  7835. for (var i = 0; i < ranges.length; i++) {
  7836. range = ranges[i];
  7837. pos = range.getBoundingClientRect();
  7838. if (this.horizontal && this.direction === "ltr") {
  7839. left = pos.left;
  7840. if (left >= start) {
  7841. return range;
  7842. }
  7843. } else if (this.horizontal && this.direction === "rtl") {
  7844. right = pos.right;
  7845. if (right <= end) {
  7846. return range;
  7847. }
  7848. } else {
  7849. top = pos.top;
  7850. if (top >= start) {
  7851. return range;
  7852. }
  7853. }
  7854. // prev = range;
  7855. }
  7856. return ranges[0];
  7857. }
  7858. /**
  7859. * Find Text End Range
  7860. * @private
  7861. * @param {Node} root root node
  7862. * @param {number} start position to start at
  7863. * @param {number} end position to end at
  7864. * @return {Range}
  7865. */
  7866. }, {
  7867. key: "findTextEndRange",
  7868. value: function findTextEndRange(node, start, end) {
  7869. var ranges = this.splitTextNodeIntoRanges(node);
  7870. var prev;
  7871. var range;
  7872. var pos;
  7873. var left, right, top, bottom;
  7874. for (var i = 0; i < ranges.length; i++) {
  7875. range = ranges[i];
  7876. pos = range.getBoundingClientRect();
  7877. if (this.horizontal && this.direction === "ltr") {
  7878. left = pos.left;
  7879. right = pos.right;
  7880. if (left > end && prev) {
  7881. return prev;
  7882. } else if (right > end) {
  7883. return range;
  7884. }
  7885. } else if (this.horizontal && this.direction === "rtl") {
  7886. left = pos.left;
  7887. right = pos.right;
  7888. if (right < start && prev) {
  7889. return prev;
  7890. } else if (left < start) {
  7891. return range;
  7892. }
  7893. } else {
  7894. top = pos.top;
  7895. bottom = pos.bottom;
  7896. if (top > end && prev) {
  7897. return prev;
  7898. } else if (bottom > end) {
  7899. return range;
  7900. }
  7901. }
  7902. prev = range;
  7903. }
  7904. // Ends before limit
  7905. return ranges[ranges.length - 1];
  7906. }
  7907. /**
  7908. * Split up a text node into ranges for each word
  7909. * @private
  7910. * @param {Node} root root node
  7911. * @param {string} [_splitter] what to split on
  7912. * @return {Range[]}
  7913. */
  7914. }, {
  7915. key: "splitTextNodeIntoRanges",
  7916. value: function splitTextNodeIntoRanges(node, _splitter) {
  7917. var ranges = [];
  7918. var textContent = node.textContent || "";
  7919. var text = textContent.trim();
  7920. var range;
  7921. var doc = node.ownerDocument;
  7922. var splitter = _splitter || " ";
  7923. var pos = text.indexOf(splitter);
  7924. if (pos === -1 || node.nodeType != Node.TEXT_NODE) {
  7925. range = doc.createRange();
  7926. range.selectNodeContents(node);
  7927. return [range];
  7928. }
  7929. range = doc.createRange();
  7930. range.setStart(node, 0);
  7931. range.setEnd(node, pos);
  7932. ranges.push(range);
  7933. range = false;
  7934. while (pos != -1) {
  7935. pos = text.indexOf(splitter, pos + 1);
  7936. if (pos > 0) {
  7937. if (range) {
  7938. range.setEnd(node, pos);
  7939. ranges.push(range);
  7940. }
  7941. range = doc.createRange();
  7942. range.setStart(node, pos + 1);
  7943. }
  7944. }
  7945. if (range) {
  7946. range.setEnd(node, text.length);
  7947. ranges.push(range);
  7948. }
  7949. return ranges;
  7950. }
  7951. /**
  7952. * Turn a pair of ranges into a pair of CFIs
  7953. * @private
  7954. * @param {string} cfiBase base string for an EpubCFI
  7955. * @param {object} rangePair { start: Range, end: Range }
  7956. * @return {object} { start: "epubcfi(...)", end: "epubcfi(...)" }
  7957. */
  7958. }, {
  7959. key: "rangePairToCfiPair",
  7960. value: function rangePairToCfiPair(cfiBase, rangePair) {
  7961. var startRange = rangePair.start;
  7962. var endRange = rangePair.end;
  7963. startRange.collapse(true);
  7964. endRange.collapse(false);
  7965. var startCfi = new _epubcfi2.default(startRange, cfiBase).toString();
  7966. var endCfi = new _epubcfi2.default(endRange, cfiBase).toString();
  7967. return {
  7968. start: startCfi,
  7969. end: endCfi
  7970. };
  7971. }
  7972. }, {
  7973. key: "rangeListToCfiList",
  7974. value: function rangeListToCfiList(cfiBase, columns) {
  7975. var map = [];
  7976. var cifPair;
  7977. for (var i = 0; i < columns.length; i++) {
  7978. cifPair = this.rangePairToCfiPair(cfiBase, columns[i]);
  7979. map.push(cifPair);
  7980. }
  7981. return map;
  7982. }
  7983. /**
  7984. * Set the axis for mapping
  7985. * @param {string} axis horizontal | vertical
  7986. * @return {boolean} is it horizontal?
  7987. */
  7988. }, {
  7989. key: "axis",
  7990. value: function axis(_axis) {
  7991. if (_axis) {
  7992. this.horizontal = _axis === "horizontal" ? true : false;
  7993. }
  7994. return this.horizontal;
  7995. }
  7996. }]);
  7997. return Mapping;
  7998. }();
  7999. exports.default = Mapping;
  8000. module.exports = exports["default"];
  8001. /***/ }),
  8002. /* 20 */
  8003. /***/ (function(module, exports, __webpack_require__) {
  8004. "use strict";
  8005. Object.defineProperty(exports, "__esModule", {
  8006. value: true
  8007. });
  8008. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8009. var _eventEmitter = __webpack_require__(3);
  8010. var _eventEmitter2 = _interopRequireDefault(_eventEmitter);
  8011. var _core = __webpack_require__(0);
  8012. var _epubcfi = __webpack_require__(1);
  8013. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  8014. var _contents = __webpack_require__(13);
  8015. var _contents2 = _interopRequireDefault(_contents);
  8016. var _constants = __webpack_require__(2);
  8017. var _marksPane = __webpack_require__(56);
  8018. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8019. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8020. var IframeView = function () {
  8021. function IframeView(section, options) {
  8022. _classCallCheck(this, IframeView);
  8023. this.settings = (0, _core.extend)({
  8024. ignoreClass: "",
  8025. axis: options.layout && options.layout.props.flow === "scrolled" ? "vertical" : "horizontal",
  8026. direction: undefined,
  8027. width: 0,
  8028. height: 0,
  8029. layout: undefined,
  8030. globalLayoutProperties: {},
  8031. method: undefined
  8032. }, options || {});
  8033. this.id = "epubjs-view-" + (0, _core.uuid)();
  8034. this.section = section;
  8035. this.index = section.index;
  8036. this.element = this.container(this.settings.axis);
  8037. this.added = false;
  8038. this.displayed = false;
  8039. this.rendered = false;
  8040. // this.width = this.settings.width;
  8041. // this.height = this.settings.height;
  8042. this.fixedWidth = 0;
  8043. this.fixedHeight = 0;
  8044. // Blank Cfi for Parsing
  8045. this.epubcfi = new _epubcfi2.default();
  8046. this.layout = this.settings.layout;
  8047. // Dom events to listen for
  8048. // this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click", "touchend", "touchstart"];
  8049. this.pane = undefined;
  8050. this.highlights = {};
  8051. this.underlines = {};
  8052. this.marks = {};
  8053. }
  8054. _createClass(IframeView, [{
  8055. key: "container",
  8056. value: function container(axis) {
  8057. var element = document.createElement("div");
  8058. element.classList.add("epub-view");
  8059. // this.element.style.minHeight = "100px";
  8060. element.style.height = "0px";
  8061. element.style.width = "0px";
  8062. element.style.overflow = "hidden";
  8063. element.style.position = "relative";
  8064. element.style.display = "block";
  8065. if (axis && axis == "horizontal") {
  8066. element.style.flex = "none";
  8067. } else {
  8068. element.style.flex = "initial";
  8069. }
  8070. return element;
  8071. }
  8072. }, {
  8073. key: "create",
  8074. value: function create() {
  8075. if (this.iframe) {
  8076. return this.iframe;
  8077. }
  8078. if (!this.element) {
  8079. this.element = this.createContainer();
  8080. }
  8081. this.iframe = document.createElement("iframe");
  8082. this.iframe.id = this.id;
  8083. this.iframe.scrolling = "no"; // Might need to be removed: breaks ios width calculations
  8084. this.iframe.style.overflow = "hidden";
  8085. this.iframe.seamless = "seamless";
  8086. // Back up if seamless isn't supported
  8087. this.iframe.style.border = "none";
  8088. this.iframe.setAttribute("enable-annotation", "true");
  8089. this.resizing = true;
  8090. // this.iframe.style.display = "none";
  8091. this.element.style.visibility = "hidden";
  8092. this.iframe.style.visibility = "hidden";
  8093. this.iframe.style.width = "0";
  8094. this.iframe.style.height = "0";
  8095. this._width = 0;
  8096. this._height = 0;
  8097. this.element.setAttribute("ref", this.index);
  8098. this.element.appendChild(this.iframe);
  8099. this.added = true;
  8100. this.elementBounds = (0, _core.bounds)(this.element);
  8101. // if(width || height){
  8102. // this.resize(width, height);
  8103. // } else if(this.width && this.height){
  8104. // this.resize(this.width, this.height);
  8105. // } else {
  8106. // this.iframeBounds = bounds(this.iframe);
  8107. // }
  8108. // if ("srcdoc" in this.iframe) {
  8109. // this.supportsSrcdoc = true;
  8110. // } else {
  8111. // this.supportsSrcdoc = false;
  8112. // }
  8113. this.supportsSrcdoc = false;
  8114. if (!this.settings.method) {
  8115. this.settings.method = this.supportsSrcdoc ? "srcdoc" : "write";
  8116. }
  8117. return this.iframe;
  8118. }
  8119. }, {
  8120. key: "render",
  8121. value: function render(request, show) {
  8122. // view.onLayout = this.layout.format.bind(this.layout);
  8123. this.create();
  8124. // Fit to size of the container, apply padding
  8125. this.size();
  8126. if (!this.sectionRender) {
  8127. this.sectionRender = this.section.render(request);
  8128. }
  8129. // Render Chain
  8130. return this.sectionRender.then(function (contents) {
  8131. return this.load(contents);
  8132. }.bind(this)).then(function () {
  8133. var _this = this;
  8134. // apply the layout function to the contents
  8135. this.layout.format(this.contents);
  8136. // find and report the writingMode axis
  8137. var writingMode = this.contents.writingMode();
  8138. var axis = writingMode.indexOf("vertical") === 0 ? "vertical" : "horizontal";
  8139. this.setAxis(axis);
  8140. this.emit(_constants.EVENTS.VIEWS.AXIS, axis);
  8141. // Listen for events that require an expansion of the iframe
  8142. this.addListeners();
  8143. return new Promise(function (resolve, reject) {
  8144. // Expand the iframe to the full size of the content
  8145. _this.expand();
  8146. resolve();
  8147. });
  8148. }.bind(this), function (e) {
  8149. this.emit(_constants.EVENTS.VIEWS.LOAD_ERROR, e);
  8150. return new Promise(function (resolve, reject) {
  8151. reject(e);
  8152. });
  8153. }.bind(this)).then(function () {
  8154. this.emit(_constants.EVENTS.VIEWS.RENDERED, this.section);
  8155. }.bind(this));
  8156. }
  8157. }, {
  8158. key: "reset",
  8159. value: function reset() {
  8160. if (this.iframe) {
  8161. this.iframe.style.width = "0";
  8162. this.iframe.style.height = "0";
  8163. this._width = 0;
  8164. this._height = 0;
  8165. this._textWidth = undefined;
  8166. this._contentWidth = undefined;
  8167. this._textHeight = undefined;
  8168. this._contentHeight = undefined;
  8169. }
  8170. this._needsReframe = true;
  8171. }
  8172. // Determine locks base on settings
  8173. }, {
  8174. key: "size",
  8175. value: function size(_width, _height) {
  8176. var width = _width || this.settings.width;
  8177. var height = _height || this.settings.height;
  8178. if (this.layout.name === "pre-paginated") {
  8179. this.lock("both", width, height);
  8180. } else if (this.settings.axis === "horizontal") {
  8181. this.lock("height", width, height);
  8182. } else {
  8183. this.lock("width", width, height);
  8184. }
  8185. this.settings.width = width;
  8186. this.settings.height = height;
  8187. }
  8188. // Lock an axis to element dimensions, taking borders into account
  8189. }, {
  8190. key: "lock",
  8191. value: function lock(what, width, height) {
  8192. var elBorders = (0, _core.borders)(this.element);
  8193. var iframeBorders;
  8194. if (this.iframe) {
  8195. iframeBorders = (0, _core.borders)(this.iframe);
  8196. } else {
  8197. iframeBorders = { width: 0, height: 0 };
  8198. }
  8199. if (what == "width" && (0, _core.isNumber)(width)) {
  8200. this.lockedWidth = width - elBorders.width - iframeBorders.width;
  8201. // this.resize(this.lockedWidth, width); // width keeps ratio correct
  8202. }
  8203. if (what == "height" && (0, _core.isNumber)(height)) {
  8204. this.lockedHeight = height - elBorders.height - iframeBorders.height;
  8205. // this.resize(width, this.lockedHeight);
  8206. }
  8207. if (what === "both" && (0, _core.isNumber)(width) && (0, _core.isNumber)(height)) {
  8208. this.lockedWidth = width - elBorders.width - iframeBorders.width;
  8209. this.lockedHeight = height - elBorders.height - iframeBorders.height;
  8210. // this.resize(this.lockedWidth, this.lockedHeight);
  8211. }
  8212. if (this.displayed && this.iframe) {
  8213. // this.contents.layout();
  8214. this.expand();
  8215. }
  8216. }
  8217. // Resize a single axis based on content dimensions
  8218. }, {
  8219. key: "expand",
  8220. value: function expand(force) {
  8221. var width = this.lockedWidth;
  8222. var height = this.lockedHeight;
  8223. var columns;
  8224. var textWidth, textHeight;
  8225. if (!this.iframe || this._expanding) return;
  8226. this._expanding = true;
  8227. if (this.layout.name === "pre-paginated") {
  8228. width = this.layout.columnWidth;
  8229. height = this.layout.height;
  8230. }
  8231. // Expand Horizontally
  8232. else if (this.settings.axis === "horizontal") {
  8233. // Get the width of the text
  8234. width = this.contents.textWidth();
  8235. if (width % this.layout.pageWidth > 0) {
  8236. width = Math.ceil(width / this.layout.pageWidth) * this.layout.pageWidth;
  8237. }
  8238. if (this.settings.forceEvenPages) {
  8239. columns = width / this.layout.pageWidth;
  8240. if (this.layout.divisor > 1 && this.layout.name === "reflowable" && columns % 2 > 0) {
  8241. // add a blank page
  8242. width += this.layout.pageWidth;
  8243. }
  8244. }
  8245. } // Expand Vertically
  8246. else if (this.settings.axis === "vertical") {
  8247. height = this.contents.textHeight();
  8248. }
  8249. // Only Resize if dimensions have changed or
  8250. // if Frame is still hidden, so needs reframing
  8251. if (this._needsReframe || width != this._width || height != this._height) {
  8252. this.reframe(width, height);
  8253. }
  8254. this._expanding = false;
  8255. }
  8256. }, {
  8257. key: "reframe",
  8258. value: function reframe(width, height) {
  8259. var _this2 = this;
  8260. var size;
  8261. if ((0, _core.isNumber)(width)) {
  8262. this.element.style.width = width + "px";
  8263. this.iframe.style.width = width + "px";
  8264. this._width = width;
  8265. }
  8266. if ((0, _core.isNumber)(height)) {
  8267. this.element.style.height = height + "px";
  8268. this.iframe.style.height = height + "px";
  8269. this._height = height;
  8270. }
  8271. var widthDelta = this.prevBounds ? width - this.prevBounds.width : width;
  8272. var heightDelta = this.prevBounds ? height - this.prevBounds.height : height;
  8273. size = {
  8274. width: width,
  8275. height: height,
  8276. widthDelta: widthDelta,
  8277. heightDelta: heightDelta
  8278. };
  8279. this.pane && this.pane.render();
  8280. requestAnimationFrame(function () {
  8281. var mark = void 0;
  8282. for (var m in _this2.marks) {
  8283. if (_this2.marks.hasOwnProperty(m)) {
  8284. mark = _this2.marks[m];
  8285. _this2.placeMark(mark.element, mark.range);
  8286. }
  8287. }
  8288. });
  8289. this.onResize(this, size);
  8290. this.emit(_constants.EVENTS.VIEWS.RESIZED, size);
  8291. this.prevBounds = size;
  8292. this.elementBounds = (0, _core.bounds)(this.element);
  8293. }
  8294. }, {
  8295. key: "load",
  8296. value: function load(contents) {
  8297. var loading = new _core.defer();
  8298. var loaded = loading.promise;
  8299. if (!this.iframe) {
  8300. loading.reject(new Error("No Iframe Available"));
  8301. return loaded;
  8302. }
  8303. this.iframe.onload = function (event) {
  8304. this.onLoad(event, loading);
  8305. }.bind(this);
  8306. if (this.settings.method === "blobUrl") {
  8307. this.blobUrl = (0, _core.createBlobUrl)(contents, "application/xhtml+xml");
  8308. this.iframe.src = this.blobUrl;
  8309. } else if (this.settings.method === "srcdoc") {
  8310. this.iframe.srcdoc = contents;
  8311. } else {
  8312. this.document = this.iframe.contentDocument;
  8313. if (!this.document) {
  8314. loading.reject(new Error("No Document Available"));
  8315. return loaded;
  8316. }
  8317. this.iframe.contentDocument.open();
  8318. this.iframe.contentDocument.write(contents);
  8319. this.iframe.contentDocument.close();
  8320. }
  8321. return loaded;
  8322. }
  8323. }, {
  8324. key: "onLoad",
  8325. value: function onLoad(event, promise) {
  8326. var _this3 = this;
  8327. this.window = this.iframe.contentWindow;
  8328. this.document = this.iframe.contentDocument;
  8329. this.contents = new _contents2.default(this.document, this.document.body, this.section.cfiBase, this.section.index);
  8330. this.rendering = false;
  8331. var link = this.document.querySelector("link[rel='canonical']");
  8332. if (link) {
  8333. link.setAttribute("href", this.section.canonical);
  8334. } else {
  8335. link = this.document.createElement("link");
  8336. link.setAttribute("rel", "canonical");
  8337. link.setAttribute("href", this.section.canonical);
  8338. this.document.querySelector("head").appendChild(link);
  8339. }
  8340. this.contents.on(_constants.EVENTS.CONTENTS.EXPAND, function () {
  8341. if (_this3.displayed && _this3.iframe) {
  8342. _this3.expand();
  8343. if (_this3.contents) {
  8344. _this3.layout.format(_this3.contents);
  8345. }
  8346. }
  8347. });
  8348. this.contents.on(_constants.EVENTS.CONTENTS.RESIZE, function (e) {
  8349. if (_this3.displayed && _this3.iframe) {
  8350. _this3.expand();
  8351. if (_this3.contents) {
  8352. _this3.layout.format(_this3.contents);
  8353. }
  8354. }
  8355. });
  8356. promise.resolve(this.contents);
  8357. }
  8358. }, {
  8359. key: "setLayout",
  8360. value: function setLayout(layout) {
  8361. this.layout = layout;
  8362. if (this.contents) {
  8363. this.layout.format(this.contents);
  8364. this.expand();
  8365. }
  8366. }
  8367. }, {
  8368. key: "setAxis",
  8369. value: function setAxis(axis) {
  8370. // Force vertical for scrolled
  8371. if (this.layout.props.flow === "scrolled") {
  8372. axis = "vertical";
  8373. }
  8374. this.settings.axis = axis;
  8375. if (axis == "horizontal") {
  8376. this.element.style.flex = "none";
  8377. } else {
  8378. this.element.style.flex = "initial";
  8379. }
  8380. this.size();
  8381. }
  8382. }, {
  8383. key: "addListeners",
  8384. value: function addListeners() {
  8385. //TODO: Add content listeners for expanding
  8386. }
  8387. }, {
  8388. key: "removeListeners",
  8389. value: function removeListeners(layoutFunc) {
  8390. //TODO: remove content listeners for expanding
  8391. }
  8392. }, {
  8393. key: "display",
  8394. value: function display(request) {
  8395. var displayed = new _core.defer();
  8396. if (!this.displayed) {
  8397. this.render(request).then(function () {
  8398. this.emit(_constants.EVENTS.VIEWS.DISPLAYED, this);
  8399. this.onDisplayed(this);
  8400. this.displayed = true;
  8401. displayed.resolve(this);
  8402. }.bind(this), function (err) {
  8403. displayed.reject(err, this);
  8404. });
  8405. } else {
  8406. displayed.resolve(this);
  8407. }
  8408. return displayed.promise;
  8409. }
  8410. }, {
  8411. key: "show",
  8412. value: function show() {
  8413. this.element.style.visibility = "visible";
  8414. if (this.iframe) {
  8415. this.iframe.style.visibility = "visible";
  8416. // Remind Safari to redraw the iframe
  8417. this.iframe.style.transform = "translateZ(0)";
  8418. this.iframe.offsetWidth;
  8419. this.iframe.style.transform = null;
  8420. }
  8421. this.emit(_constants.EVENTS.VIEWS.SHOWN, this);
  8422. }
  8423. }, {
  8424. key: "hide",
  8425. value: function hide() {
  8426. // this.iframe.style.display = "none";
  8427. this.element.style.visibility = "hidden";
  8428. this.iframe.style.visibility = "hidden";
  8429. this.stopExpanding = true;
  8430. this.emit(_constants.EVENTS.VIEWS.HIDDEN, this);
  8431. }
  8432. }, {
  8433. key: "offset",
  8434. value: function offset() {
  8435. return {
  8436. top: this.element.offsetTop,
  8437. left: this.element.offsetLeft
  8438. };
  8439. }
  8440. }, {
  8441. key: "width",
  8442. value: function width() {
  8443. return this._width;
  8444. }
  8445. }, {
  8446. key: "height",
  8447. value: function height() {
  8448. return this._height;
  8449. }
  8450. }, {
  8451. key: "position",
  8452. value: function position() {
  8453. return this.element.getBoundingClientRect();
  8454. }
  8455. }, {
  8456. key: "locationOf",
  8457. value: function locationOf(target) {
  8458. var parentPos = this.iframe.getBoundingClientRect();
  8459. var targetPos = this.contents.locationOf(target, this.settings.ignoreClass);
  8460. return {
  8461. "left": targetPos.left,
  8462. "top": targetPos.top
  8463. };
  8464. }
  8465. }, {
  8466. key: "onDisplayed",
  8467. value: function onDisplayed(view) {
  8468. // Stub, override with a custom functions
  8469. }
  8470. }, {
  8471. key: "onResize",
  8472. value: function onResize(view, e) {
  8473. // Stub, override with a custom functions
  8474. }
  8475. }, {
  8476. key: "bounds",
  8477. value: function bounds(force) {
  8478. if (force || !this.elementBounds) {
  8479. this.elementBounds = (0, _core.bounds)(this.element);
  8480. }
  8481. return this.elementBounds;
  8482. }
  8483. }, {
  8484. key: "highlight",
  8485. value: function highlight(cfiRange) {
  8486. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  8487. var cb = arguments[2];
  8488. var _this4 = this;
  8489. var className = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "epubjs-hl";
  8490. var styles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  8491. if (!this.contents) {
  8492. return;
  8493. }
  8494. var attributes = Object.assign({ "fill": "yellow", "fill-opacity": "0.3", "mix-blend-mode": "multiply" }, styles);
  8495. var range = this.contents.range(cfiRange);
  8496. var emitter = function emitter() {
  8497. _this4.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data);
  8498. };
  8499. data["epubcfi"] = cfiRange;
  8500. if (!this.pane) {
  8501. this.pane = new _marksPane.Pane(this.iframe, this.element);
  8502. }
  8503. var m = new _marksPane.Highlight(range, className, data, attributes);
  8504. var h = this.pane.addMark(m);
  8505. this.highlights[cfiRange] = { "mark": h, "element": h.element, "listeners": [emitter, cb] };
  8506. h.element.setAttribute("ref", className);
  8507. h.element.addEventListener("click", emitter);
  8508. h.element.addEventListener("touchstart", emitter);
  8509. if (cb) {
  8510. h.element.addEventListener("click", cb);
  8511. h.element.addEventListener("touchstart", cb);
  8512. }
  8513. return h;
  8514. }
  8515. }, {
  8516. key: "underline",
  8517. value: function underline(cfiRange) {
  8518. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  8519. var cb = arguments[2];
  8520. var _this5 = this;
  8521. var className = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "epubjs-ul";
  8522. var styles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  8523. if (!this.contents) {
  8524. return;
  8525. }
  8526. var attributes = Object.assign({ "stroke": "black", "stroke-opacity": "0.3", "mix-blend-mode": "multiply" }, styles);
  8527. var range = this.contents.range(cfiRange);
  8528. var emitter = function emitter() {
  8529. _this5.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data);
  8530. };
  8531. data["epubcfi"] = cfiRange;
  8532. if (!this.pane) {
  8533. this.pane = new _marksPane.Pane(this.iframe, this.element);
  8534. }
  8535. var m = new _marksPane.Underline(range, className, data, attributes);
  8536. var h = this.pane.addMark(m);
  8537. this.underlines[cfiRange] = { "mark": h, "element": h.element, "listeners": [emitter, cb] };
  8538. h.element.setAttribute("ref", className);
  8539. h.element.addEventListener("click", emitter);
  8540. h.element.addEventListener("touchstart", emitter);
  8541. if (cb) {
  8542. h.element.addEventListener("click", cb);
  8543. h.element.addEventListener("touchstart", cb);
  8544. }
  8545. return h;
  8546. }
  8547. }, {
  8548. key: "mark",
  8549. value: function mark(cfiRange) {
  8550. var _this6 = this;
  8551. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  8552. var cb = arguments[2];
  8553. if (!this.contents) {
  8554. return;
  8555. }
  8556. if (cfiRange in this.marks) {
  8557. var item = this.marks[cfiRange];
  8558. return item;
  8559. }
  8560. var range = this.contents.range(cfiRange);
  8561. if (!range) {
  8562. return;
  8563. }
  8564. var container = range.commonAncestorContainer;
  8565. var parent = container.nodeType === 1 ? container : container.parentNode;
  8566. var emitter = function emitter(e) {
  8567. _this6.emit(_constants.EVENTS.VIEWS.MARK_CLICKED, cfiRange, data);
  8568. };
  8569. if (range.collapsed && container.nodeType === 1) {
  8570. range = new Range();
  8571. range.selectNodeContents(container);
  8572. } else if (range.collapsed) {
  8573. // Webkit doesn't like collapsed ranges
  8574. range = new Range();
  8575. range.selectNodeContents(parent);
  8576. }
  8577. var mark = this.document.createElement("a");
  8578. mark.setAttribute("ref", "epubjs-mk");
  8579. mark.style.position = "absolute";
  8580. mark.dataset["epubcfi"] = cfiRange;
  8581. if (data) {
  8582. Object.keys(data).forEach(function (key) {
  8583. mark.dataset[key] = data[key];
  8584. });
  8585. }
  8586. if (cb) {
  8587. mark.addEventListener("click", cb);
  8588. mark.addEventListener("touchstart", cb);
  8589. }
  8590. mark.addEventListener("click", emitter);
  8591. mark.addEventListener("touchstart", emitter);
  8592. this.placeMark(mark, range);
  8593. this.element.appendChild(mark);
  8594. this.marks[cfiRange] = { "element": mark, "range": range, "listeners": [emitter, cb] };
  8595. return parent;
  8596. }
  8597. }, {
  8598. key: "placeMark",
  8599. value: function placeMark(element, range) {
  8600. var top = void 0,
  8601. right = void 0,
  8602. left = void 0;
  8603. if (this.layout.name === "pre-paginated" || this.settings.axis !== "horizontal") {
  8604. var pos = range.getBoundingClientRect();
  8605. top = pos.top;
  8606. right = pos.right;
  8607. } else {
  8608. // Element might break columns, so find the left most element
  8609. var rects = range.getClientRects();
  8610. var rect = void 0;
  8611. for (var i = 0; i != rects.length; i++) {
  8612. rect = rects[i];
  8613. if (!left || rect.left < left) {
  8614. left = rect.left;
  8615. right = left + this.layout.columnWidth - this.layout.gap;
  8616. top = rect.top;
  8617. }
  8618. }
  8619. }
  8620. element.style.top = top + "px";
  8621. element.style.left = right + "px";
  8622. }
  8623. }, {
  8624. key: "unhighlight",
  8625. value: function unhighlight(cfiRange) {
  8626. var item = void 0;
  8627. if (cfiRange in this.highlights) {
  8628. item = this.highlights[cfiRange];
  8629. this.pane.removeMark(item.mark);
  8630. item.listeners.forEach(function (l) {
  8631. if (l) {
  8632. item.element.removeEventListener("click", l);
  8633. };
  8634. });
  8635. delete this.highlights[cfiRange];
  8636. }
  8637. }
  8638. }, {
  8639. key: "ununderline",
  8640. value: function ununderline(cfiRange) {
  8641. var item = void 0;
  8642. if (cfiRange in this.underlines) {
  8643. item = this.underlines[cfiRange];
  8644. this.pane.removeMark(item.mark);
  8645. item.listeners.forEach(function (l) {
  8646. if (l) {
  8647. item.element.removeEventListener("click", l);
  8648. };
  8649. });
  8650. delete this.underlines[cfiRange];
  8651. }
  8652. }
  8653. }, {
  8654. key: "unmark",
  8655. value: function unmark(cfiRange) {
  8656. var item = void 0;
  8657. if (cfiRange in this.marks) {
  8658. item = this.marks[cfiRange];
  8659. this.element.removeChild(item.element);
  8660. item.listeners.forEach(function (l) {
  8661. if (l) {
  8662. item.element.removeEventListener("click", l);
  8663. };
  8664. });
  8665. delete this.marks[cfiRange];
  8666. }
  8667. }
  8668. }, {
  8669. key: "destroy",
  8670. value: function destroy() {
  8671. for (var cfiRange in this.highlights) {
  8672. this.unhighlight(cfiRange);
  8673. }
  8674. for (var _cfiRange in this.underlines) {
  8675. this.ununderline(_cfiRange);
  8676. }
  8677. for (var _cfiRange2 in this.marks) {
  8678. this.unmark(_cfiRange2);
  8679. }
  8680. if (this.blobUrl) {
  8681. (0, _core.revokeBlobUrl)(this.blobUrl);
  8682. }
  8683. if (this.displayed) {
  8684. this.displayed = false;
  8685. this.removeListeners();
  8686. this.stopExpanding = true;
  8687. this.element.removeChild(this.iframe);
  8688. this.iframe = undefined;
  8689. this.contents = undefined;
  8690. this._textWidth = null;
  8691. this._textHeight = null;
  8692. this._width = null;
  8693. this._height = null;
  8694. }
  8695. // this.element.style.height = "0px";
  8696. // this.element.style.width = "0px";
  8697. }
  8698. }]);
  8699. return IframeView;
  8700. }();
  8701. (0, _eventEmitter2.default)(IframeView.prototype);
  8702. exports.default = IframeView;
  8703. module.exports = exports["default"];
  8704. /***/ }),
  8705. /* 21 */
  8706. /***/ (function(module, exports, __webpack_require__) {
  8707. var isObject = __webpack_require__(15),
  8708. now = __webpack_require__(61),
  8709. toNumber = __webpack_require__(63);
  8710. /** Error message constants. */
  8711. var FUNC_ERROR_TEXT = 'Expected a function';
  8712. /* Built-in method references for those with the same name as other `lodash` methods. */
  8713. var nativeMax = Math.max,
  8714. nativeMin = Math.min;
  8715. /**
  8716. * Creates a debounced function that delays invoking `func` until after `wait`
  8717. * milliseconds have elapsed since the last time the debounced function was
  8718. * invoked. The debounced function comes with a `cancel` method to cancel
  8719. * delayed `func` invocations and a `flush` method to immediately invoke them.
  8720. * Provide `options` to indicate whether `func` should be invoked on the
  8721. * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
  8722. * with the last arguments provided to the debounced function. Subsequent
  8723. * calls to the debounced function return the result of the last `func`
  8724. * invocation.
  8725. *
  8726. * **Note:** If `leading` and `trailing` options are `true`, `func` is
  8727. * invoked on the trailing edge of the timeout only if the debounced function
  8728. * is invoked more than once during the `wait` timeout.
  8729. *
  8730. * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
  8731. * until to the next tick, similar to `setTimeout` with a timeout of `0`.
  8732. *
  8733. * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
  8734. * for details over the differences between `_.debounce` and `_.throttle`.
  8735. *
  8736. * @static
  8737. * @memberOf _
  8738. * @since 0.1.0
  8739. * @category Function
  8740. * @param {Function} func The function to debounce.
  8741. * @param {number} [wait=0] The number of milliseconds to delay.
  8742. * @param {Object} [options={}] The options object.
  8743. * @param {boolean} [options.leading=false]
  8744. * Specify invoking on the leading edge of the timeout.
  8745. * @param {number} [options.maxWait]
  8746. * The maximum time `func` is allowed to be delayed before it's invoked.
  8747. * @param {boolean} [options.trailing=true]
  8748. * Specify invoking on the trailing edge of the timeout.
  8749. * @returns {Function} Returns the new debounced function.
  8750. * @example
  8751. *
  8752. * // Avoid costly calculations while the window size is in flux.
  8753. * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
  8754. *
  8755. * // Invoke `sendMail` when clicked, debouncing subsequent calls.
  8756. * jQuery(element).on('click', _.debounce(sendMail, 300, {
  8757. * 'leading': true,
  8758. * 'trailing': false
  8759. * }));
  8760. *
  8761. * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
  8762. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
  8763. * var source = new EventSource('/stream');
  8764. * jQuery(source).on('message', debounced);
  8765. *
  8766. * // Cancel the trailing debounced invocation.
  8767. * jQuery(window).on('popstate', debounced.cancel);
  8768. */
  8769. function debounce(func, wait, options) {
  8770. var lastArgs,
  8771. lastThis,
  8772. maxWait,
  8773. result,
  8774. timerId,
  8775. lastCallTime,
  8776. lastInvokeTime = 0,
  8777. leading = false,
  8778. maxing = false,
  8779. trailing = true;
  8780. if (typeof func != 'function') {
  8781. throw new TypeError(FUNC_ERROR_TEXT);
  8782. }
  8783. wait = toNumber(wait) || 0;
  8784. if (isObject(options)) {
  8785. leading = !!options.leading;
  8786. maxing = 'maxWait' in options;
  8787. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  8788. trailing = 'trailing' in options ? !!options.trailing : trailing;
  8789. }
  8790. function invokeFunc(time) {
  8791. var args = lastArgs,
  8792. thisArg = lastThis;
  8793. lastArgs = lastThis = undefined;
  8794. lastInvokeTime = time;
  8795. result = func.apply(thisArg, args);
  8796. return result;
  8797. }
  8798. function leadingEdge(time) {
  8799. // Reset any `maxWait` timer.
  8800. lastInvokeTime = time;
  8801. // Start the timer for the trailing edge.
  8802. timerId = setTimeout(timerExpired, wait);
  8803. // Invoke the leading edge.
  8804. return leading ? invokeFunc(time) : result;
  8805. }
  8806. function remainingWait(time) {
  8807. var timeSinceLastCall = time - lastCallTime,
  8808. timeSinceLastInvoke = time - lastInvokeTime,
  8809. result = wait - timeSinceLastCall;
  8810. return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
  8811. }
  8812. function shouldInvoke(time) {
  8813. var timeSinceLastCall = time - lastCallTime,
  8814. timeSinceLastInvoke = time - lastInvokeTime;
  8815. // Either this is the first call, activity has stopped and we're at the
  8816. // trailing edge, the system time has gone backwards and we're treating
  8817. // it as the trailing edge, or we've hit the `maxWait` limit.
  8818. return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
  8819. (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  8820. }
  8821. function timerExpired() {
  8822. var time = now();
  8823. if (shouldInvoke(time)) {
  8824. return trailingEdge(time);
  8825. }
  8826. // Restart the timer.
  8827. timerId = setTimeout(timerExpired, remainingWait(time));
  8828. }
  8829. function trailingEdge(time) {
  8830. timerId = undefined;
  8831. // Only invoke if we have `lastArgs` which means `func` has been
  8832. // debounced at least once.
  8833. if (trailing && lastArgs) {
  8834. return invokeFunc(time);
  8835. }
  8836. lastArgs = lastThis = undefined;
  8837. return result;
  8838. }
  8839. function cancel() {
  8840. if (timerId !== undefined) {
  8841. clearTimeout(timerId);
  8842. }
  8843. lastInvokeTime = 0;
  8844. lastArgs = lastCallTime = lastThis = timerId = undefined;
  8845. }
  8846. function flush() {
  8847. return timerId === undefined ? result : trailingEdge(now());
  8848. }
  8849. function debounced() {
  8850. var time = now(),
  8851. isInvoking = shouldInvoke(time);
  8852. lastArgs = arguments;
  8853. lastThis = this;
  8854. lastCallTime = time;
  8855. if (isInvoking) {
  8856. if (timerId === undefined) {
  8857. return leadingEdge(lastCallTime);
  8858. }
  8859. if (maxing) {
  8860. // Handle invocations in a tight loop.
  8861. timerId = setTimeout(timerExpired, wait);
  8862. return invokeFunc(lastCallTime);
  8863. }
  8864. }
  8865. if (timerId === undefined) {
  8866. timerId = setTimeout(timerExpired, wait);
  8867. }
  8868. return result;
  8869. }
  8870. debounced.cancel = cancel;
  8871. debounced.flush = flush;
  8872. return debounced;
  8873. }
  8874. module.exports = debounce;
  8875. /***/ }),
  8876. /* 22 */
  8877. /***/ (function(module, exports, __webpack_require__) {
  8878. var freeGlobal = __webpack_require__(62);
  8879. /** Detect free variable `self`. */
  8880. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  8881. /** Used as a reference to the global object. */
  8882. var root = freeGlobal || freeSelf || Function('return this')();
  8883. module.exports = root;
  8884. /***/ }),
  8885. /* 23 */
  8886. /***/ (function(module, exports, __webpack_require__) {
  8887. var root = __webpack_require__(22);
  8888. /** Built-in value references. */
  8889. var Symbol = root.Symbol;
  8890. module.exports = Symbol;
  8891. /***/ }),
  8892. /* 24 */
  8893. /***/ (function(module, exports, __webpack_require__) {
  8894. "use strict";
  8895. Object.defineProperty(exports, "__esModule", {
  8896. value: true
  8897. });
  8898. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8899. var _core = __webpack_require__(0);
  8900. var _default = __webpack_require__(14);
  8901. var _default2 = _interopRequireDefault(_default);
  8902. var _constants = __webpack_require__(2);
  8903. var _debounce = __webpack_require__(21);
  8904. var _debounce2 = _interopRequireDefault(_debounce);
  8905. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8906. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8907. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  8908. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  8909. var ContinuousViewManager = function (_DefaultViewManager) {
  8910. _inherits(ContinuousViewManager, _DefaultViewManager);
  8911. function ContinuousViewManager(options) {
  8912. _classCallCheck(this, ContinuousViewManager);
  8913. var _this = _possibleConstructorReturn(this, (ContinuousViewManager.__proto__ || Object.getPrototypeOf(ContinuousViewManager)).call(this, options));
  8914. _this.name = "continuous";
  8915. _this.settings = (0, _core.extend)(_this.settings || {}, {
  8916. infinite: true,
  8917. overflow: undefined,
  8918. axis: undefined,
  8919. flow: "scrolled",
  8920. offset: 500,
  8921. offsetDelta: 250,
  8922. width: undefined,
  8923. height: undefined
  8924. });
  8925. (0, _core.extend)(_this.settings, options.settings || {});
  8926. // Gap can be 0, but defaults doesn't handle that
  8927. if (options.settings.gap != "undefined" && options.settings.gap === 0) {
  8928. _this.settings.gap = options.settings.gap;
  8929. }
  8930. _this.viewSettings = {
  8931. ignoreClass: _this.settings.ignoreClass,
  8932. axis: _this.settings.axis,
  8933. flow: _this.settings.flow,
  8934. layout: _this.layout,
  8935. width: 0,
  8936. height: 0,
  8937. forceEvenPages: false
  8938. };
  8939. _this.scrollTop = 0;
  8940. _this.scrollLeft = 0;
  8941. return _this;
  8942. }
  8943. _createClass(ContinuousViewManager, [{
  8944. key: "display",
  8945. value: function display(section, target) {
  8946. return _default2.default.prototype.display.call(this, section, target).then(function () {
  8947. return this.fill();
  8948. }.bind(this));
  8949. }
  8950. }, {
  8951. key: "fill",
  8952. value: function fill(_full) {
  8953. var _this2 = this;
  8954. var full = _full || new _core.defer();
  8955. this.q.enqueue(function () {
  8956. return _this2.check();
  8957. }).then(function (result) {
  8958. if (result) {
  8959. _this2.fill(full);
  8960. } else {
  8961. full.resolve();
  8962. }
  8963. });
  8964. return full.promise;
  8965. }
  8966. }, {
  8967. key: "moveTo",
  8968. value: function moveTo(offset) {
  8969. // var bounds = this.stage.bounds();
  8970. // var dist = Math.floor(offset.top / bounds.height) * bounds.height;
  8971. var distX = 0,
  8972. distY = 0;
  8973. var offsetX = 0,
  8974. offsetY = 0;
  8975. if (!this.isPaginated) {
  8976. distY = offset.top;
  8977. offsetY = offset.top + this.settings.offset;
  8978. } else {
  8979. distX = Math.floor(offset.left / this.layout.delta) * this.layout.delta;
  8980. offsetX = distX + this.settings.offset;
  8981. }
  8982. if (distX > 0 || distY > 0) {
  8983. this.scrollBy(distX, distY, true);
  8984. }
  8985. }
  8986. }, {
  8987. key: "afterResized",
  8988. value: function afterResized(view) {
  8989. this.emit(_constants.EVENTS.MANAGERS.RESIZE, view.section);
  8990. }
  8991. // Remove Previous Listeners if present
  8992. }, {
  8993. key: "removeShownListeners",
  8994. value: function removeShownListeners(view) {
  8995. // view.off("shown", this.afterDisplayed);
  8996. // view.off("shown", this.afterDisplayedAbove);
  8997. view.onDisplayed = function () {};
  8998. }
  8999. }, {
  9000. key: "add",
  9001. value: function add(section) {
  9002. var _this3 = this;
  9003. var view = this.createView(section);
  9004. this.views.append(view);
  9005. view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) {
  9006. view.expanded = true;
  9007. });
  9008. view.on(_constants.EVENTS.VIEWS.AXIS, function (axis) {
  9009. _this3.updateAxis(axis);
  9010. });
  9011. // view.on(EVENTS.VIEWS.SHOWN, this.afterDisplayed.bind(this));
  9012. view.onDisplayed = this.afterDisplayed.bind(this);
  9013. view.onResize = this.afterResized.bind(this);
  9014. return view.display(this.request);
  9015. }
  9016. }, {
  9017. key: "append",
  9018. value: function append(section) {
  9019. var view = this.createView(section);
  9020. view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) {
  9021. view.expanded = true;
  9022. });
  9023. /*
  9024. view.on(EVENTS.VIEWS.AXIS, (axis) => {
  9025. this.updateAxis(axis);
  9026. });
  9027. */
  9028. this.views.append(view);
  9029. view.onDisplayed = this.afterDisplayed.bind(this);
  9030. return view;
  9031. }
  9032. }, {
  9033. key: "prepend",
  9034. value: function prepend(section) {
  9035. var _this4 = this;
  9036. var view = this.createView(section);
  9037. view.on(_constants.EVENTS.VIEWS.RESIZED, function (bounds) {
  9038. _this4.counter(bounds);
  9039. view.expanded = true;
  9040. });
  9041. /*
  9042. view.on(EVENTS.VIEWS.AXIS, (axis) => {
  9043. this.updateAxis(axis);
  9044. });
  9045. */
  9046. this.views.prepend(view);
  9047. view.onDisplayed = this.afterDisplayed.bind(this);
  9048. return view;
  9049. }
  9050. }, {
  9051. key: "counter",
  9052. value: function counter(bounds) {
  9053. if (this.settings.axis === "vertical") {
  9054. this.scrollBy(0, bounds.heightDelta, true);
  9055. } else {
  9056. this.scrollBy(bounds.widthDelta, 0, true);
  9057. }
  9058. }
  9059. }, {
  9060. key: "update",
  9061. value: function update(_offset) {
  9062. var container = this.bounds();
  9063. var views = this.views.all();
  9064. var viewsLength = views.length;
  9065. var visible = [];
  9066. var offset = typeof _offset != "undefined" ? _offset : this.settings.offset || 0;
  9067. var isVisible;
  9068. var view;
  9069. var updating = new _core.defer();
  9070. var promises = [];
  9071. for (var i = 0; i < viewsLength; i++) {
  9072. view = views[i];
  9073. isVisible = this.isVisible(view, offset, offset, container);
  9074. if (isVisible === true) {
  9075. // console.log("visible " + view.index);
  9076. if (!view.displayed) {
  9077. var displayed = view.display(this.request).then(function (view) {
  9078. view.show();
  9079. }, function (err) {
  9080. view.hide();
  9081. });
  9082. promises.push(displayed);
  9083. } else {
  9084. view.show();
  9085. }
  9086. visible.push(view);
  9087. } else {
  9088. this.q.enqueue(view.destroy.bind(view));
  9089. // console.log("hidden " + view.index);
  9090. clearTimeout(this.trimTimeout);
  9091. this.trimTimeout = setTimeout(function () {
  9092. this.q.enqueue(this.trim.bind(this));
  9093. }.bind(this), 250);
  9094. }
  9095. }
  9096. if (promises.length) {
  9097. return Promise.all(promises).catch(function (err) {
  9098. updating.reject(err);
  9099. });
  9100. } else {
  9101. updating.resolve();
  9102. return updating.promise;
  9103. }
  9104. }
  9105. }, {
  9106. key: "check",
  9107. value: function check(_offsetLeft, _offsetTop) {
  9108. var _this5 = this;
  9109. var checking = new _core.defer();
  9110. var newViews = [];
  9111. var horizontal = this.settings.axis === "horizontal";
  9112. var delta = this.settings.offset || 0;
  9113. if (_offsetLeft && horizontal) {
  9114. delta = _offsetLeft;
  9115. }
  9116. if (_offsetTop && !horizontal) {
  9117. delta = _offsetTop;
  9118. }
  9119. var bounds = this._bounds; // bounds saved this until resize
  9120. var rtl = this.settings.direction === "rtl";
  9121. var dir = horizontal && rtl ? -1 : 1; //RTL reverses scrollTop
  9122. var offset = horizontal ? this.scrollLeft : this.scrollTop * dir;
  9123. var visibleLength = horizontal ? Math.floor(bounds.width) : bounds.height;
  9124. var contentLength = horizontal ? this.container.scrollWidth : this.container.scrollHeight;
  9125. var prepend = function prepend() {
  9126. var first = _this5.views.first();
  9127. var prev = first && first.section.prev();
  9128. if (prev) {
  9129. newViews.push(_this5.prepend(prev));
  9130. }
  9131. };
  9132. var append = function append() {
  9133. var last = _this5.views.last();
  9134. var next = last && last.section.next();
  9135. if (next) {
  9136. newViews.push(_this5.append(next));
  9137. }
  9138. };
  9139. if (offset + visibleLength + delta >= contentLength) {
  9140. if (horizontal && rtl) {
  9141. prepend();
  9142. } else {
  9143. append();
  9144. }
  9145. }
  9146. if (offset - delta < 0) {
  9147. if (horizontal && rtl) {
  9148. append();
  9149. } else {
  9150. prepend();
  9151. }
  9152. }
  9153. var promises = newViews.map(function (view) {
  9154. return view.displayed;
  9155. });
  9156. if (newViews.length) {
  9157. return Promise.all(promises).then(function () {
  9158. if (_this5.layout.name === "pre-paginated" && _this5.layout.props.spread) {
  9159. return _this5.check();
  9160. }
  9161. }).then(function () {
  9162. // Check to see if anything new is on screen after rendering
  9163. return _this5.update(delta);
  9164. }, function (err) {
  9165. return err;
  9166. });
  9167. } else {
  9168. this.q.enqueue(function () {
  9169. this.update();
  9170. }.bind(this));
  9171. checking.resolve(false);
  9172. return checking.promise;
  9173. }
  9174. }
  9175. }, {
  9176. key: "trim",
  9177. value: function trim() {
  9178. var task = new _core.defer();
  9179. var displayed = this.views.displayed();
  9180. var first = displayed[0];
  9181. var last = displayed[displayed.length - 1];
  9182. var firstIndex = this.views.indexOf(first);
  9183. var lastIndex = this.views.indexOf(last);
  9184. var above = this.views.slice(0, firstIndex);
  9185. var below = this.views.slice(lastIndex + 1);
  9186. // Erase all but last above
  9187. for (var i = 0; i < above.length - 1; i++) {
  9188. this.erase(above[i], above);
  9189. }
  9190. // Erase all except first below
  9191. for (var j = 1; j < below.length; j++) {
  9192. this.erase(below[j]);
  9193. }
  9194. task.resolve();
  9195. return task.promise;
  9196. }
  9197. }, {
  9198. key: "erase",
  9199. value: function erase(view, above) {
  9200. //Trim
  9201. var prevTop;
  9202. var prevLeft;
  9203. if (!this.settings.fullsize) {
  9204. prevTop = this.container.scrollTop;
  9205. prevLeft = this.container.scrollLeft;
  9206. } else {
  9207. prevTop = window.scrollY;
  9208. prevLeft = window.scrollX;
  9209. }
  9210. var bounds = view.bounds();
  9211. this.views.remove(view);
  9212. if (above) {
  9213. if (this.settings.axis === "vertical") {
  9214. this.scrollTo(0, prevTop - bounds.height, true);
  9215. } else {
  9216. this.scrollTo(prevLeft - Math.floor(bounds.width), 0, true);
  9217. }
  9218. }
  9219. }
  9220. }, {
  9221. key: "addEventListeners",
  9222. value: function addEventListeners(stage) {
  9223. window.addEventListener("unload", function (e) {
  9224. this.ignore = true;
  9225. // this.scrollTo(0,0);
  9226. this.destroy();
  9227. }.bind(this));
  9228. this.addScrollListeners();
  9229. }
  9230. }, {
  9231. key: "addScrollListeners",
  9232. value: function addScrollListeners() {
  9233. var scroller;
  9234. this.tick = _core.requestAnimationFrame;
  9235. if (!this.settings.fullsize) {
  9236. this.prevScrollTop = this.container.scrollTop;
  9237. this.prevScrollLeft = this.container.scrollLeft;
  9238. } else {
  9239. this.prevScrollTop = window.scrollY;
  9240. this.prevScrollLeft = window.scrollX;
  9241. }
  9242. this.scrollDeltaVert = 0;
  9243. this.scrollDeltaHorz = 0;
  9244. if (!this.settings.fullsize) {
  9245. scroller = this.container;
  9246. this.scrollTop = this.container.scrollTop;
  9247. this.scrollLeft = this.container.scrollLeft;
  9248. } else {
  9249. scroller = window;
  9250. this.scrollTop = window.scrollY;
  9251. this.scrollLeft = window.scrollX;
  9252. }
  9253. scroller.addEventListener("scroll", this.onScroll.bind(this));
  9254. this._scrolled = (0, _debounce2.default)(this.scrolled.bind(this), 30);
  9255. // this.tick.call(window, this.onScroll.bind(this));
  9256. this.didScroll = false;
  9257. }
  9258. }, {
  9259. key: "removeEventListeners",
  9260. value: function removeEventListeners() {
  9261. var scroller;
  9262. if (!this.settings.fullsize) {
  9263. scroller = this.container;
  9264. } else {
  9265. scroller = window;
  9266. }
  9267. scroller.removeEventListener("scroll", this.onScroll.bind(this));
  9268. }
  9269. }, {
  9270. key: "onScroll",
  9271. value: function onScroll() {
  9272. var scrollTop = void 0;
  9273. var scrollLeft = void 0;
  9274. var dir = this.settings.direction === "rtl" ? -1 : 1;
  9275. if (!this.settings.fullsize) {
  9276. scrollTop = this.container.scrollTop;
  9277. scrollLeft = this.container.scrollLeft;
  9278. } else {
  9279. scrollTop = window.scrollY * dir;
  9280. scrollLeft = window.scrollX * dir;
  9281. }
  9282. this.scrollTop = scrollTop;
  9283. this.scrollLeft = scrollLeft;
  9284. if (!this.ignore) {
  9285. this._scrolled();
  9286. } else {
  9287. this.ignore = false;
  9288. }
  9289. this.scrollDeltaVert += Math.abs(scrollTop - this.prevScrollTop);
  9290. this.scrollDeltaHorz += Math.abs(scrollLeft - this.prevScrollLeft);
  9291. this.prevScrollTop = scrollTop;
  9292. this.prevScrollLeft = scrollLeft;
  9293. clearTimeout(this.scrollTimeout);
  9294. this.scrollTimeout = setTimeout(function () {
  9295. this.scrollDeltaVert = 0;
  9296. this.scrollDeltaHorz = 0;
  9297. }.bind(this), 150);
  9298. this.didScroll = false;
  9299. }
  9300. }, {
  9301. key: "scrolled",
  9302. value: function scrolled() {
  9303. this.q.enqueue(function () {
  9304. this.check();
  9305. }.bind(this));
  9306. this.emit(_constants.EVENTS.MANAGERS.SCROLL, {
  9307. top: this.scrollTop,
  9308. left: this.scrollLeft
  9309. });
  9310. clearTimeout(this.afterScrolled);
  9311. this.afterScrolled = setTimeout(function () {
  9312. this.emit(_constants.EVENTS.MANAGERS.SCROLLED, {
  9313. top: this.scrollTop,
  9314. left: this.scrollLeft
  9315. });
  9316. }.bind(this));
  9317. }
  9318. }, {
  9319. key: "next",
  9320. value: function next() {
  9321. var dir = this.settings.direction;
  9322. var delta = this.layout.props.name === "pre-paginated" && this.layout.props.spread ? this.layout.props.delta * 2 : this.layout.props.delta;
  9323. if (!this.views.length) return;
  9324. if (this.isPaginated && this.settings.axis === "horizontal") {
  9325. this.scrollBy(delta, 0, true);
  9326. } else {
  9327. this.scrollBy(0, this.layout.height, true);
  9328. }
  9329. this.q.enqueue(function () {
  9330. this.check();
  9331. }.bind(this));
  9332. }
  9333. }, {
  9334. key: "prev",
  9335. value: function prev() {
  9336. var dir = this.settings.direction;
  9337. var delta = this.layout.props.name === "pre-paginated" && this.layout.props.spread ? this.layout.props.delta * 2 : this.layout.props.delta;
  9338. if (!this.views.length) return;
  9339. if (this.isPaginated && this.settings.axis === "horizontal") {
  9340. this.scrollBy(-delta, 0, true);
  9341. } else {
  9342. this.scrollBy(0, -this.layout.height, true);
  9343. }
  9344. this.q.enqueue(function () {
  9345. this.check();
  9346. }.bind(this));
  9347. }
  9348. }, {
  9349. key: "updateAxis",
  9350. value: function updateAxis(axis, forceUpdate) {
  9351. if (!this.isPaginated) {
  9352. axis = "vertical";
  9353. }
  9354. if (!forceUpdate && axis === this.settings.axis) {
  9355. return;
  9356. }
  9357. this.settings.axis = axis;
  9358. this.stage && this.stage.axis(axis);
  9359. this.viewSettings.axis = axis;
  9360. if (this.mapping) {
  9361. this.mapping.axis(axis);
  9362. }
  9363. if (this.layout) {
  9364. if (axis === "vertical") {
  9365. this.layout.spread("none");
  9366. } else {
  9367. this.layout.spread(this.layout.settings.spread);
  9368. }
  9369. }
  9370. if (axis === "vertical") {
  9371. this.settings.infinite = true;
  9372. } else {
  9373. this.settings.infinite = false;
  9374. }
  9375. }
  9376. }]);
  9377. return ContinuousViewManager;
  9378. }(_default2.default);
  9379. exports.default = ContinuousViewManager;
  9380. module.exports = exports["default"];
  9381. /***/ }),
  9382. /* 25 */
  9383. /***/ (function(module, exports, __webpack_require__) {
  9384. "use strict";
  9385. /* WEBPACK VAR INJECTION */(function(global) {
  9386. Object.defineProperty(exports, "__esModule", {
  9387. value: true
  9388. });
  9389. var _book = __webpack_require__(26);
  9390. var _book2 = _interopRequireDefault(_book);
  9391. var _rendition = __webpack_require__(18);
  9392. var _rendition2 = _interopRequireDefault(_rendition);
  9393. var _epubcfi = __webpack_require__(1);
  9394. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  9395. var _contents = __webpack_require__(13);
  9396. var _contents2 = _interopRequireDefault(_contents);
  9397. var _core = __webpack_require__(0);
  9398. var utils = _interopRequireWildcard(_core);
  9399. var _constants = __webpack_require__(2);
  9400. __webpack_require__(72);
  9401. var _iframe = __webpack_require__(20);
  9402. var _iframe2 = _interopRequireDefault(_iframe);
  9403. var _default = __webpack_require__(14);
  9404. var _default2 = _interopRequireDefault(_default);
  9405. var _continuous = __webpack_require__(24);
  9406. var _continuous2 = _interopRequireDefault(_continuous);
  9407. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  9408. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9409. /**
  9410. * Creates a new Book
  9411. * @param {string|ArrayBuffer} url URL, Path or ArrayBuffer
  9412. * @param {object} options to pass to the book
  9413. * @returns {Book} a new Book object
  9414. * @example ePub("/path/to/book.epub", {})
  9415. */
  9416. function ePub(url, options) {
  9417. return new _book2.default(url, options);
  9418. }
  9419. ePub.VERSION = _constants.EPUBJS_VERSION;
  9420. if (typeof global !== "undefined") {
  9421. global.EPUBJS_VERSION = _constants.EPUBJS_VERSION;
  9422. }
  9423. ePub.Book = _book2.default;
  9424. ePub.Rendition = _rendition2.default;
  9425. ePub.Contents = _contents2.default;
  9426. ePub.CFI = _epubcfi2.default;
  9427. ePub.utils = utils;
  9428. exports.default = ePub;
  9429. module.exports = exports["default"];
  9430. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8)))
  9431. /***/ }),
  9432. /* 26 */
  9433. /***/ (function(module, exports, __webpack_require__) {
  9434. "use strict";
  9435. Object.defineProperty(exports, "__esModule", {
  9436. value: true
  9437. });
  9438. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  9439. var _eventEmitter = __webpack_require__(3);
  9440. var _eventEmitter2 = _interopRequireDefault(_eventEmitter);
  9441. var _core = __webpack_require__(0);
  9442. var _url = __webpack_require__(5);
  9443. var _url2 = _interopRequireDefault(_url);
  9444. var _path = __webpack_require__(4);
  9445. var _path2 = _interopRequireDefault(_path);
  9446. var _spine = __webpack_require__(43);
  9447. var _spine2 = _interopRequireDefault(_spine);
  9448. var _locations = __webpack_require__(47);
  9449. var _locations2 = _interopRequireDefault(_locations);
  9450. var _container = __webpack_require__(48);
  9451. var _container2 = _interopRequireDefault(_container);
  9452. var _packaging = __webpack_require__(49);
  9453. var _packaging2 = _interopRequireDefault(_packaging);
  9454. var _navigation = __webpack_require__(50);
  9455. var _navigation2 = _interopRequireDefault(_navigation);
  9456. var _resources = __webpack_require__(51);
  9457. var _resources2 = _interopRequireDefault(_resources);
  9458. var _pagelist = __webpack_require__(52);
  9459. var _pagelist2 = _interopRequireDefault(_pagelist);
  9460. var _rendition = __webpack_require__(18);
  9461. var _rendition2 = _interopRequireDefault(_rendition);
  9462. var _archive = __webpack_require__(70);
  9463. var _archive2 = _interopRequireDefault(_archive);
  9464. var _request2 = __webpack_require__(11);
  9465. var _request3 = _interopRequireDefault(_request2);
  9466. var _epubcfi = __webpack_require__(1);
  9467. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  9468. var _constants = __webpack_require__(2);
  9469. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9470. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9471. var CONTAINER_PATH = "META-INF/container.xml";
  9472. var INPUT_TYPE = {
  9473. BINARY: "binary",
  9474. BASE64: "base64",
  9475. EPUB: "epub",
  9476. OPF: "opf",
  9477. MANIFEST: "json",
  9478. DIRECTORY: "directory"
  9479. };
  9480. /**
  9481. * An Epub representation with methods for the loading, parsing and manipulation
  9482. * of its contents.
  9483. * @class
  9484. * @param {string} [url]
  9485. * @param {object} [options]
  9486. * @param {method} [options.requestMethod] a request function to use instead of the default
  9487. * @param {boolean} [options.requestCredentials=undefined] send the xhr request withCredentials
  9488. * @param {object} [options.requestHeaders=undefined] send the xhr request headers
  9489. * @param {string} [options.encoding=binary] optional to pass 'binary' or base64' for archived Epubs
  9490. * @param {string} [options.replacements=none] use base64, blobUrl, or none for replacing assets in archived Epubs
  9491. * @param {method} [options.canonical] optional function to determine canonical urls for a path
  9492. * @param {string} [options.openAs] optional string to determine the input type
  9493. * @returns {Book}
  9494. * @example new Book("/path/to/book.epub", {})
  9495. * @example new Book({ replacements: "blobUrl" })
  9496. */
  9497. var Book = function () {
  9498. function Book(url, options) {
  9499. var _this = this;
  9500. _classCallCheck(this, Book);
  9501. // Allow passing just options to the Book
  9502. if (typeof options === "undefined" && typeof url !== "string" && url instanceof Blob === false) {
  9503. options = url;
  9504. url = undefined;
  9505. }
  9506. this.settings = (0, _core.extend)(this.settings || {}, {
  9507. requestMethod: undefined,
  9508. requestCredentials: undefined,
  9509. requestHeaders: undefined,
  9510. encoding: undefined,
  9511. replacements: undefined,
  9512. canonical: undefined,
  9513. openAs: undefined
  9514. });
  9515. (0, _core.extend)(this.settings, options);
  9516. // Promises
  9517. this.opening = new _core.defer();
  9518. /**
  9519. * @member {promise} opened returns after the book is loaded
  9520. * @memberof Book
  9521. */
  9522. this.opened = this.opening.promise;
  9523. this.isOpen = false;
  9524. this.loading = {
  9525. manifest: new _core.defer(),
  9526. spine: new _core.defer(),
  9527. metadata: new _core.defer(),
  9528. cover: new _core.defer(),
  9529. navigation: new _core.defer(),
  9530. pageList: new _core.defer(),
  9531. resources: new _core.defer()
  9532. };
  9533. this.loaded = {
  9534. manifest: this.loading.manifest.promise,
  9535. spine: this.loading.spine.promise,
  9536. metadata: this.loading.metadata.promise,
  9537. cover: this.loading.cover.promise,
  9538. navigation: this.loading.navigation.promise,
  9539. pageList: this.loading.pageList.promise,
  9540. resources: this.loading.resources.promise
  9541. };
  9542. /**
  9543. * @member {promise} ready returns after the book is loaded and parsed
  9544. * @memberof Book
  9545. * @private
  9546. */
  9547. this.ready = Promise.all([this.loaded.manifest, this.loaded.spine, this.loaded.metadata, this.loaded.cover, this.loaded.navigation, this.loaded.resources]);
  9548. // Queue for methods used before opening
  9549. this.isRendered = false;
  9550. // this._q = queue(this);
  9551. /**
  9552. * @member {method} request
  9553. * @memberof Book
  9554. * @private
  9555. */
  9556. this.request = this.settings.requestMethod || _request3.default;
  9557. /**
  9558. * @member {Spine} spine
  9559. * @memberof Book
  9560. */
  9561. this.spine = new _spine2.default();
  9562. /**
  9563. * @member {Locations} locations
  9564. * @memberof Book
  9565. */
  9566. this.locations = new _locations2.default(this.spine, this.load.bind(this));
  9567. /**
  9568. * @member {Navigation} navigation
  9569. * @memberof Book
  9570. */
  9571. this.navigation = undefined;
  9572. /**
  9573. * @member {PageList} pagelist
  9574. * @memberof Book
  9575. */
  9576. this.pageList = undefined;
  9577. /**
  9578. * @member {Url} url
  9579. * @memberof Book
  9580. * @private
  9581. */
  9582. this.url = undefined;
  9583. /**
  9584. * @member {Path} path
  9585. * @memberof Book
  9586. * @private
  9587. */
  9588. this.path = undefined;
  9589. /**
  9590. * @member {boolean} archived
  9591. * @memberof Book
  9592. * @private
  9593. */
  9594. this.archived = false;
  9595. /**
  9596. * @member {Archive} archive
  9597. * @memberof Book
  9598. * @private
  9599. */
  9600. this.archive = undefined;
  9601. /**
  9602. * @member {Resources} resources
  9603. * @memberof Book
  9604. * @private
  9605. */
  9606. this.resources = undefined;
  9607. /**
  9608. * @member {Rendition} rendition
  9609. * @memberof Book
  9610. * @private
  9611. */
  9612. this.rendition = undefined;
  9613. /**
  9614. * @member {Container} container
  9615. * @memberof Book
  9616. * @private
  9617. */
  9618. this.container = undefined;
  9619. /**
  9620. * @member {Packaging} packaging
  9621. * @memberof Book
  9622. * @private
  9623. */
  9624. this.packaging = undefined;
  9625. // this.toc = undefined;
  9626. if (url) {
  9627. this.open(url, this.settings.openAs).catch(function (error) {
  9628. var err = new Error("Cannot load book at " + url);
  9629. _this.emit(_constants.EVENTS.BOOK.OPEN_FAILED, err);
  9630. });
  9631. }
  9632. }
  9633. /**
  9634. * Open a epub or url
  9635. * @param {string | ArrayBuffer} input Url, Path or ArrayBuffer
  9636. * @param {string} [what="binary", "base64", "epub", "opf", "json", "directory"] force opening as a certain type
  9637. * @returns {Promise} of when the book has been loaded
  9638. * @example book.open("/path/to/book.epub")
  9639. */
  9640. _createClass(Book, [{
  9641. key: "open",
  9642. value: function open(input, what) {
  9643. var opening;
  9644. var type = what || this.determineType(input);
  9645. if (type === INPUT_TYPE.BINARY) {
  9646. this.archived = true;
  9647. this.url = new _url2.default("/", "");
  9648. opening = this.openEpub(input);
  9649. } else if (type === INPUT_TYPE.BASE64) {
  9650. this.archived = true;
  9651. this.url = new _url2.default("/", "");
  9652. opening = this.openEpub(input, type);
  9653. } else if (type === INPUT_TYPE.EPUB) {
  9654. this.archived = true;
  9655. this.url = new _url2.default("/", "");
  9656. opening = this.request(input, "binary", this.settings.requestCredentials).then(this.openEpub.bind(this));
  9657. } else if (type == INPUT_TYPE.OPF) {
  9658. this.url = new _url2.default(input);
  9659. opening = this.openPackaging(this.url.Path.toString());
  9660. } else if (type == INPUT_TYPE.MANIFEST) {
  9661. this.url = new _url2.default(input);
  9662. opening = this.openManifest(this.url.Path.toString());
  9663. } else {
  9664. this.url = new _url2.default(input);
  9665. opening = this.openContainer(CONTAINER_PATH).then(this.openPackaging.bind(this));
  9666. }
  9667. return opening;
  9668. }
  9669. /**
  9670. * Open an archived epub
  9671. * @private
  9672. * @param {binary} data
  9673. * @param {string} [encoding]
  9674. * @return {Promise}
  9675. */
  9676. }, {
  9677. key: "openEpub",
  9678. value: function openEpub(data, encoding) {
  9679. var _this2 = this;
  9680. return this.unarchive(data, encoding || this.settings.encoding).then(function () {
  9681. return _this2.openContainer(CONTAINER_PATH);
  9682. }).then(function (packagePath) {
  9683. return _this2.openPackaging(packagePath);
  9684. });
  9685. }
  9686. /**
  9687. * Open the epub container
  9688. * @private
  9689. * @param {string} url
  9690. * @return {string} packagePath
  9691. */
  9692. }, {
  9693. key: "openContainer",
  9694. value: function openContainer(url) {
  9695. var _this3 = this;
  9696. return this.load(url).then(function (xml) {
  9697. _this3.container = new _container2.default(xml);
  9698. return _this3.resolve(_this3.container.packagePath);
  9699. });
  9700. }
  9701. /**
  9702. * Open the Open Packaging Format Xml
  9703. * @private
  9704. * @param {string} url
  9705. * @return {Promise}
  9706. */
  9707. }, {
  9708. key: "openPackaging",
  9709. value: function openPackaging(url) {
  9710. var _this4 = this;
  9711. this.path = new _path2.default(url);
  9712. return this.load(url).then(function (xml) {
  9713. _this4.packaging = new _packaging2.default(xml);
  9714. return _this4.unpack(_this4.packaging);
  9715. });
  9716. }
  9717. /**
  9718. * Open the manifest JSON
  9719. * @private
  9720. * @param {string} url
  9721. * @return {Promise}
  9722. */
  9723. }, {
  9724. key: "openManifest",
  9725. value: function openManifest(url) {
  9726. var _this5 = this;
  9727. this.path = new _path2.default(url);
  9728. return this.load(url).then(function (json) {
  9729. _this5.packaging = new _packaging2.default();
  9730. _this5.packaging.load(json);
  9731. return _this5.unpack(_this5.packaging);
  9732. });
  9733. }
  9734. /**
  9735. * Load a resource from the Book
  9736. * @param {string} path path to the resource to load
  9737. * @return {Promise} returns a promise with the requested resource
  9738. */
  9739. }, {
  9740. key: "load",
  9741. value: function load(path) {
  9742. var resolved;
  9743. if (this.archived) {
  9744. resolved = this.resolve(path);
  9745. return this.archive.request(resolved);
  9746. } else {
  9747. resolved = this.resolve(path);
  9748. return this.request(resolved, null, this.settings.requestCredentials, this.settings.requestHeaders);
  9749. }
  9750. }
  9751. /**
  9752. * Resolve a path to it's absolute position in the Book
  9753. * @param {string} path
  9754. * @param {boolean} [absolute] force resolving the full URL
  9755. * @return {string} the resolved path string
  9756. */
  9757. }, {
  9758. key: "resolve",
  9759. value: function resolve(path, absolute) {
  9760. if (!path) {
  9761. return;
  9762. }
  9763. var resolved = path;
  9764. var isAbsolute = path.indexOf("://") > -1;
  9765. if (isAbsolute) {
  9766. return path;
  9767. }
  9768. if (this.path) {
  9769. resolved = this.path.resolve(path);
  9770. }
  9771. if (absolute != false && this.url) {
  9772. resolved = this.url.resolve(resolved);
  9773. }
  9774. return resolved;
  9775. }
  9776. /**
  9777. * Get a canonical link to a path
  9778. * @param {string} path
  9779. * @return {string} the canonical path string
  9780. */
  9781. }, {
  9782. key: "canonical",
  9783. value: function canonical(path) {
  9784. var url = path;
  9785. if (!path) {
  9786. return "";
  9787. }
  9788. if (this.settings.canonical) {
  9789. url = this.settings.canonical(path);
  9790. } else {
  9791. url = this.resolve(path, true);
  9792. }
  9793. return url;
  9794. }
  9795. /**
  9796. * Determine the type of they input passed to open
  9797. * @private
  9798. * @param {string} input
  9799. * @return {string} binary | directory | epub | opf
  9800. */
  9801. }, {
  9802. key: "determineType",
  9803. value: function determineType(input) {
  9804. var url;
  9805. var path;
  9806. var extension;
  9807. if (this.settings.encoding === "base64") {
  9808. return INPUT_TYPE.BASE64;
  9809. }
  9810. if (typeof input != "string") {
  9811. return INPUT_TYPE.BINARY;
  9812. }
  9813. url = new _url2.default(input);
  9814. path = url.path();
  9815. extension = path.extension;
  9816. if (!extension) {
  9817. return INPUT_TYPE.DIRECTORY;
  9818. }
  9819. if (extension === "epub") {
  9820. return INPUT_TYPE.EPUB;
  9821. }
  9822. if (extension === "opf") {
  9823. return INPUT_TYPE.OPF;
  9824. }
  9825. if (extension === "json") {
  9826. return INPUT_TYPE.MANIFEST;
  9827. }
  9828. }
  9829. /**
  9830. * unpack the contents of the Books packageXml
  9831. * @private
  9832. * @param {document} packageXml XML Document
  9833. */
  9834. }, {
  9835. key: "unpack",
  9836. value: function unpack(opf) {
  9837. var _this6 = this;
  9838. this.package = opf;
  9839. this.spine.unpack(this.package, this.resolve.bind(this), this.canonical.bind(this));
  9840. this.resources = new _resources2.default(this.package.manifest, {
  9841. archive: this.archive,
  9842. resolver: this.resolve.bind(this),
  9843. request: this.request.bind(this),
  9844. replacements: this.settings.replacements || (this.archived ? "blobUrl" : "base64")
  9845. });
  9846. this.loadNavigation(this.package).then(function () {
  9847. // this.toc = this.navigation.toc;
  9848. _this6.loading.navigation.resolve(_this6.navigation);
  9849. });
  9850. if (this.package.coverPath) {
  9851. this.cover = this.resolve(this.package.coverPath);
  9852. }
  9853. // Resolve promises
  9854. this.loading.manifest.resolve(this.package.manifest);
  9855. this.loading.metadata.resolve(this.package.metadata);
  9856. this.loading.spine.resolve(this.spine);
  9857. this.loading.cover.resolve(this.cover);
  9858. this.loading.resources.resolve(this.resources);
  9859. this.loading.pageList.resolve(this.pageList);
  9860. this.isOpen = true;
  9861. if (this.archived || this.settings.replacements && this.settings.replacements != "none") {
  9862. this.replacements().then(function () {
  9863. _this6.opening.resolve(_this6);
  9864. }).catch(function (err) {
  9865. console.error(err);
  9866. });
  9867. } else {
  9868. // Resolve book opened promise
  9869. this.opening.resolve(this);
  9870. }
  9871. }
  9872. /**
  9873. * Load Navigation and PageList from package
  9874. * @private
  9875. * @param {document} opf XML Document
  9876. */
  9877. }, {
  9878. key: "loadNavigation",
  9879. value: function loadNavigation(opf) {
  9880. var _this7 = this;
  9881. var navPath = opf.navPath || opf.ncxPath;
  9882. var toc = opf.toc;
  9883. // From json manifest
  9884. if (toc) {
  9885. return new Promise(function (resolve, reject) {
  9886. _this7.navigation = new _navigation2.default(toc);
  9887. if (opf.pageList) {
  9888. _this7.pageList = new _pagelist2.default(opf.pageList); // TODO: handle page lists from Manifest
  9889. }
  9890. resolve(_this7.navigation);
  9891. });
  9892. }
  9893. if (!navPath) {
  9894. return new Promise(function (resolve, reject) {
  9895. _this7.navigation = new _navigation2.default();
  9896. _this7.pageList = new _pagelist2.default();
  9897. resolve(_this7.navigation);
  9898. });
  9899. }
  9900. return this.load(navPath, "xml").then(function (xml) {
  9901. _this7.navigation = new _navigation2.default(xml);
  9902. _this7.pageList = new _pagelist2.default(xml);
  9903. return _this7.navigation;
  9904. });
  9905. }
  9906. /**
  9907. * Gets a Section of the Book from the Spine
  9908. * Alias for `book.spine.get`
  9909. * @param {string} target
  9910. * @return {Section}
  9911. */
  9912. }, {
  9913. key: "section",
  9914. value: function section(target) {
  9915. return this.spine.get(target);
  9916. }
  9917. /**
  9918. * Sugar to render a book to an element
  9919. * @param {element | string} element element or string to add a rendition to
  9920. * @param {object} [options]
  9921. * @return {Rendition}
  9922. */
  9923. }, {
  9924. key: "renderTo",
  9925. value: function renderTo(element, options) {
  9926. this.rendition = new _rendition2.default(this, options);
  9927. this.rendition.attachTo(element);
  9928. return this.rendition;
  9929. }
  9930. /**
  9931. * Set if request should use withCredentials
  9932. * @param {boolean} credentials
  9933. */
  9934. }, {
  9935. key: "setRequestCredentials",
  9936. value: function setRequestCredentials(credentials) {
  9937. this.settings.requestCredentials = credentials;
  9938. }
  9939. /**
  9940. * Set headers request should use
  9941. * @param {object} headers
  9942. */
  9943. }, {
  9944. key: "setRequestHeaders",
  9945. value: function setRequestHeaders(headers) {
  9946. this.settings.requestHeaders = headers;
  9947. }
  9948. /**
  9949. * Unarchive a zipped epub
  9950. * @private
  9951. * @param {binary} input epub data
  9952. * @param {string} [encoding]
  9953. * @return {Archive}
  9954. */
  9955. }, {
  9956. key: "unarchive",
  9957. value: function unarchive(input, encoding) {
  9958. this.archive = new _archive2.default();
  9959. return this.archive.open(input, encoding);
  9960. }
  9961. /**
  9962. * Get the cover url
  9963. * @return {string} coverUrl
  9964. */
  9965. }, {
  9966. key: "coverUrl",
  9967. value: function coverUrl() {
  9968. var _this8 = this;
  9969. var retrieved = this.loaded.cover.then(function (url) {
  9970. if (_this8.archived) {
  9971. // return this.archive.createUrl(this.cover);
  9972. return _this8.resources.get(_this8.cover);
  9973. } else {
  9974. return _this8.cover;
  9975. }
  9976. });
  9977. return retrieved;
  9978. }
  9979. /**
  9980. * Load replacement urls
  9981. * @private
  9982. * @return {Promise} completed loading urls
  9983. */
  9984. }, {
  9985. key: "replacements",
  9986. value: function replacements() {
  9987. var _this9 = this;
  9988. this.spine.hooks.serialize.register(function (output, section) {
  9989. section.output = _this9.resources.substitute(output, section.url);
  9990. });
  9991. return this.resources.replacements().then(function () {
  9992. return _this9.resources.replaceCss();
  9993. });
  9994. }
  9995. /**
  9996. * Find a DOM Range for a given CFI Range
  9997. * @param {EpubCFI} cfiRange a epub cfi range
  9998. * @return {Range}
  9999. */
  10000. }, {
  10001. key: "getRange",
  10002. value: function getRange(cfiRange) {
  10003. var cfi = new _epubcfi2.default(cfiRange);
  10004. var item = this.spine.get(cfi.spinePos);
  10005. var _request = this.load.bind(this);
  10006. if (!item) {
  10007. return new Promise(function (resolve, reject) {
  10008. reject("CFI could not be found");
  10009. });
  10010. }
  10011. return item.load(_request).then(function (contents) {
  10012. var range = cfi.toRange(item.document);
  10013. return range;
  10014. });
  10015. }
  10016. /**
  10017. * Generates the Book Key using the identifer in the manifest or other string provided
  10018. * @param {string} [identifier] to use instead of metadata identifier
  10019. * @return {string} key
  10020. */
  10021. }, {
  10022. key: "key",
  10023. value: function key(identifier) {
  10024. var ident = identifier || this.package.metadata.identifier || this.url.filename;
  10025. return "epubjs:" + _constants.EPUBJS_VERSION + ":" + ident;
  10026. }
  10027. /**
  10028. * Destroy the Book and all associated objects
  10029. */
  10030. }, {
  10031. key: "destroy",
  10032. value: function destroy() {
  10033. this.opened = undefined;
  10034. this.loading = undefined;
  10035. this.loaded = undefined;
  10036. this.ready = undefined;
  10037. this.isOpen = false;
  10038. this.isRendered = false;
  10039. this.spine && this.spine.destroy();
  10040. this.locations && this.locations.destroy();
  10041. this.pageList && this.pageList.destroy();
  10042. this.archive && this.archive.destroy();
  10043. this.resources && this.resources.destroy();
  10044. this.container && this.container.destroy();
  10045. this.packaging && this.packaging.destroy();
  10046. this.rendition && this.rendition.destroy();
  10047. this.spine = undefined;
  10048. this.locations = undefined;
  10049. this.pageList = undefined;
  10050. this.archive = undefined;
  10051. this.resources = undefined;
  10052. this.container = undefined;
  10053. this.packaging = undefined;
  10054. this.rendition = undefined;
  10055. this.navigation = undefined;
  10056. this.url = undefined;
  10057. this.path = undefined;
  10058. this.archived = false;
  10059. }
  10060. }]);
  10061. return Book;
  10062. }();
  10063. //-- Enable binding events to book
  10064. (0, _eventEmitter2.default)(Book.prototype);
  10065. exports.default = Book;
  10066. module.exports = exports["default"];
  10067. /***/ }),
  10068. /* 27 */
  10069. /***/ (function(module, exports, __webpack_require__) {
  10070. "use strict";
  10071. var assign = __webpack_require__(28)
  10072. , normalizeOpts = __webpack_require__(36)
  10073. , isCallable = __webpack_require__(37)
  10074. , contains = __webpack_require__(38)
  10075. , d;
  10076. d = module.exports = function (dscr, value/*, options*/) {
  10077. var c, e, w, options, desc;
  10078. if ((arguments.length < 2) || (typeof dscr !== 'string')) {
  10079. options = value;
  10080. value = dscr;
  10081. dscr = null;
  10082. } else {
  10083. options = arguments[2];
  10084. }
  10085. if (dscr == null) {
  10086. c = w = true;
  10087. e = false;
  10088. } else {
  10089. c = contains.call(dscr, 'c');
  10090. e = contains.call(dscr, 'e');
  10091. w = contains.call(dscr, 'w');
  10092. }
  10093. desc = { value: value, configurable: c, enumerable: e, writable: w };
  10094. return !options ? desc : assign(normalizeOpts(options), desc);
  10095. };
  10096. d.gs = function (dscr, get, set/*, options*/) {
  10097. var c, e, options, desc;
  10098. if (typeof dscr !== 'string') {
  10099. options = set;
  10100. set = get;
  10101. get = dscr;
  10102. dscr = null;
  10103. } else {
  10104. options = arguments[3];
  10105. }
  10106. if (get == null) {
  10107. get = undefined;
  10108. } else if (!isCallable(get)) {
  10109. options = get;
  10110. get = set = undefined;
  10111. } else if (set == null) {
  10112. set = undefined;
  10113. } else if (!isCallable(set)) {
  10114. options = set;
  10115. set = undefined;
  10116. }
  10117. if (dscr == null) {
  10118. c = true;
  10119. e = false;
  10120. } else {
  10121. c = contains.call(dscr, 'c');
  10122. e = contains.call(dscr, 'e');
  10123. }
  10124. desc = { get: get, set: set, configurable: c, enumerable: e };
  10125. return !options ? desc : assign(normalizeOpts(options), desc);
  10126. };
  10127. /***/ }),
  10128. /* 28 */
  10129. /***/ (function(module, exports, __webpack_require__) {
  10130. "use strict";
  10131. module.exports = __webpack_require__(29)()
  10132. ? Object.assign
  10133. : __webpack_require__(30);
  10134. /***/ }),
  10135. /* 29 */
  10136. /***/ (function(module, exports, __webpack_require__) {
  10137. "use strict";
  10138. module.exports = function () {
  10139. var assign = Object.assign, obj;
  10140. if (typeof assign !== "function") return false;
  10141. obj = { foo: "raz" };
  10142. assign(obj, { bar: "dwa" }, { trzy: "trzy" });
  10143. return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
  10144. };
  10145. /***/ }),
  10146. /* 30 */
  10147. /***/ (function(module, exports, __webpack_require__) {
  10148. "use strict";
  10149. var keys = __webpack_require__(31)
  10150. , value = __webpack_require__(35)
  10151. , max = Math.max;
  10152. module.exports = function (dest, src /*, …srcn*/) {
  10153. var error, i, length = max(arguments.length, 2), assign;
  10154. dest = Object(value(dest));
  10155. assign = function (key) {
  10156. try {
  10157. dest[key] = src[key];
  10158. } catch (e) {
  10159. if (!error) error = e;
  10160. }
  10161. };
  10162. for (i = 1; i < length; ++i) {
  10163. src = arguments[i];
  10164. keys(src).forEach(assign);
  10165. }
  10166. if (error !== undefined) throw error;
  10167. return dest;
  10168. };
  10169. /***/ }),
  10170. /* 31 */
  10171. /***/ (function(module, exports, __webpack_require__) {
  10172. "use strict";
  10173. module.exports = __webpack_require__(32)()
  10174. ? Object.keys
  10175. : __webpack_require__(33);
  10176. /***/ }),
  10177. /* 32 */
  10178. /***/ (function(module, exports, __webpack_require__) {
  10179. "use strict";
  10180. module.exports = function () {
  10181. try {
  10182. Object.keys("primitive");
  10183. return true;
  10184. } catch (e) {
  10185. return false;
  10186. }
  10187. };
  10188. /***/ }),
  10189. /* 33 */
  10190. /***/ (function(module, exports, __webpack_require__) {
  10191. "use strict";
  10192. var isValue = __webpack_require__(9);
  10193. var keys = Object.keys;
  10194. module.exports = function (object) {
  10195. return keys(isValue(object) ? Object(object) : object);
  10196. };
  10197. /***/ }),
  10198. /* 34 */
  10199. /***/ (function(module, exports, __webpack_require__) {
  10200. "use strict";
  10201. // eslint-disable-next-line no-empty-function
  10202. module.exports = function () {};
  10203. /***/ }),
  10204. /* 35 */
  10205. /***/ (function(module, exports, __webpack_require__) {
  10206. "use strict";
  10207. var isValue = __webpack_require__(9);
  10208. module.exports = function (value) {
  10209. if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
  10210. return value;
  10211. };
  10212. /***/ }),
  10213. /* 36 */
  10214. /***/ (function(module, exports, __webpack_require__) {
  10215. "use strict";
  10216. var isValue = __webpack_require__(9);
  10217. var forEach = Array.prototype.forEach, create = Object.create;
  10218. var process = function (src, obj) {
  10219. var key;
  10220. for (key in src) obj[key] = src[key];
  10221. };
  10222. // eslint-disable-next-line no-unused-vars
  10223. module.exports = function (opts1 /*, …options*/) {
  10224. var result = create(null);
  10225. forEach.call(arguments, function (options) {
  10226. if (!isValue(options)) return;
  10227. process(Object(options), result);
  10228. });
  10229. return result;
  10230. };
  10231. /***/ }),
  10232. /* 37 */
  10233. /***/ (function(module, exports, __webpack_require__) {
  10234. "use strict";
  10235. // Deprecated
  10236. module.exports = function (obj) {
  10237. return typeof obj === "function";
  10238. };
  10239. /***/ }),
  10240. /* 38 */
  10241. /***/ (function(module, exports, __webpack_require__) {
  10242. "use strict";
  10243. module.exports = __webpack_require__(39)()
  10244. ? String.prototype.contains
  10245. : __webpack_require__(40);
  10246. /***/ }),
  10247. /* 39 */
  10248. /***/ (function(module, exports, __webpack_require__) {
  10249. "use strict";
  10250. var str = "razdwatrzy";
  10251. module.exports = function () {
  10252. if (typeof str.contains !== "function") return false;
  10253. return (str.contains("dwa") === true) && (str.contains("foo") === false);
  10254. };
  10255. /***/ }),
  10256. /* 40 */
  10257. /***/ (function(module, exports, __webpack_require__) {
  10258. "use strict";
  10259. var indexOf = String.prototype.indexOf;
  10260. module.exports = function (searchString/*, position*/) {
  10261. return indexOf.call(this, searchString, arguments[1]) > -1;
  10262. };
  10263. /***/ }),
  10264. /* 41 */
  10265. /***/ (function(module, exports, __webpack_require__) {
  10266. "use strict";
  10267. module.exports = function (fn) {
  10268. if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
  10269. return fn;
  10270. };
  10271. /***/ }),
  10272. /* 42 */
  10273. /***/ (function(module, exports) {
  10274. module.exports = __WEBPACK_EXTERNAL_MODULE_42__;
  10275. /***/ }),
  10276. /* 43 */
  10277. /***/ (function(module, exports, __webpack_require__) {
  10278. "use strict";
  10279. Object.defineProperty(exports, "__esModule", {
  10280. value: true
  10281. });
  10282. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  10283. var _epubcfi = __webpack_require__(1);
  10284. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  10285. var _hook = __webpack_require__(10);
  10286. var _hook2 = _interopRequireDefault(_hook);
  10287. var _section = __webpack_require__(44);
  10288. var _section2 = _interopRequireDefault(_section);
  10289. var _replacements = __webpack_require__(7);
  10290. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10291. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10292. /**
  10293. * A collection of Spine Items
  10294. */
  10295. var Spine = function () {
  10296. function Spine() {
  10297. _classCallCheck(this, Spine);
  10298. this.spineItems = [];
  10299. this.spineByHref = {};
  10300. this.spineById = {};
  10301. this.hooks = {};
  10302. this.hooks.serialize = new _hook2.default();
  10303. this.hooks.content = new _hook2.default();
  10304. // Register replacements
  10305. this.hooks.content.register(_replacements.replaceBase);
  10306. this.hooks.content.register(_replacements.replaceCanonical);
  10307. this.hooks.content.register(_replacements.replaceMeta);
  10308. this.epubcfi = new _epubcfi2.default();
  10309. this.loaded = false;
  10310. this.items = undefined;
  10311. this.manifest = undefined;
  10312. this.spineNodeIndex = undefined;
  10313. this.baseUrl = undefined;
  10314. this.length = undefined;
  10315. }
  10316. /**
  10317. * Unpack items from a opf into spine items
  10318. * @param {Packaging} _package
  10319. * @param {method} resolver URL resolver
  10320. * @param {method} canonical Resolve canonical url
  10321. */
  10322. _createClass(Spine, [{
  10323. key: "unpack",
  10324. value: function unpack(_package, resolver, canonical) {
  10325. var _this = this;
  10326. this.items = _package.spine;
  10327. this.manifest = _package.manifest;
  10328. this.spineNodeIndex = _package.spineNodeIndex;
  10329. this.baseUrl = _package.baseUrl || _package.basePath || "";
  10330. this.length = this.items.length;
  10331. this.items.forEach(function (item, index) {
  10332. var manifestItem = _this.manifest[item.idref];
  10333. var spineItem;
  10334. item.index = index;
  10335. item.cfiBase = _this.epubcfi.generateChapterComponent(_this.spineNodeIndex, item.index, item.idref);
  10336. if (item.href) {
  10337. item.url = resolver(item.href, true);
  10338. item.canonical = canonical(item.href);
  10339. }
  10340. if (manifestItem) {
  10341. item.href = manifestItem.href;
  10342. item.url = resolver(item.href, true);
  10343. item.canonical = canonical(item.href);
  10344. if (manifestItem.properties.length) {
  10345. item.properties.push.apply(item.properties, manifestItem.properties);
  10346. }
  10347. }
  10348. if (item.linear === "yes") {
  10349. item.prev = function () {
  10350. var prevIndex = item.index;
  10351. while (prevIndex > 0) {
  10352. var prev = this.get(prevIndex - 1);
  10353. if (prev && prev.linear) {
  10354. return prev;
  10355. }
  10356. prevIndex -= 1;
  10357. }
  10358. return;
  10359. }.bind(_this);
  10360. item.next = function () {
  10361. var nextIndex = item.index;
  10362. while (nextIndex < this.spineItems.length - 1) {
  10363. var next = this.get(nextIndex + 1);
  10364. if (next && next.linear) {
  10365. return next;
  10366. }
  10367. nextIndex += 1;
  10368. }
  10369. return;
  10370. }.bind(_this);
  10371. } else {
  10372. item.prev = function () {
  10373. return;
  10374. };
  10375. item.next = function () {
  10376. return;
  10377. };
  10378. }
  10379. spineItem = new _section2.default(item, _this.hooks);
  10380. _this.append(spineItem);
  10381. });
  10382. this.loaded = true;
  10383. }
  10384. /**
  10385. * Get an item from the spine
  10386. * @param {string|number} [target]
  10387. * @return {Section} section
  10388. * @example spine.get();
  10389. * @example spine.get(1);
  10390. * @example spine.get("chap1.html");
  10391. * @example spine.get("#id1234");
  10392. */
  10393. }, {
  10394. key: "get",
  10395. value: function get(target) {
  10396. var index = 0;
  10397. if (typeof target === "undefined") {
  10398. while (index < this.spineItems.length) {
  10399. var next = this.spineItems[index];
  10400. if (next && next.linear) {
  10401. break;
  10402. }
  10403. index += 1;
  10404. }
  10405. } else if (this.epubcfi.isCfiString(target)) {
  10406. var cfi = new _epubcfi2.default(target);
  10407. index = cfi.spinePos;
  10408. } else if (typeof target === "number" || isNaN(target) === false) {
  10409. index = target;
  10410. } else if (typeof target === "string" && target.indexOf("#") === 0) {
  10411. index = this.spineById[target.substring(1)];
  10412. } else if (typeof target === "string") {
  10413. // Remove fragments
  10414. target = target.split("#")[0];
  10415. index = this.spineByHref[target] || this.spineByHref[encodeURI(target)];
  10416. }
  10417. return this.spineItems[index] || null;
  10418. }
  10419. /**
  10420. * Append a Section to the Spine
  10421. * @private
  10422. * @param {Section} section
  10423. */
  10424. }, {
  10425. key: "append",
  10426. value: function append(section) {
  10427. var index = this.spineItems.length;
  10428. section.index = index;
  10429. this.spineItems.push(section);
  10430. // Encode and Decode href lookups
  10431. // see pr for details: https://github.com/futurepress/epub.js/pull/358
  10432. this.spineByHref[decodeURI(section.href)] = index;
  10433. this.spineByHref[encodeURI(section.href)] = index;
  10434. this.spineByHref[section.href] = index;
  10435. this.spineById[section.idref] = index;
  10436. return index;
  10437. }
  10438. /**
  10439. * Prepend a Section to the Spine
  10440. * @private
  10441. * @param {Section} section
  10442. */
  10443. }, {
  10444. key: "prepend",
  10445. value: function prepend(section) {
  10446. // var index = this.spineItems.unshift(section);
  10447. this.spineByHref[section.href] = 0;
  10448. this.spineById[section.idref] = 0;
  10449. // Re-index
  10450. this.spineItems.forEach(function (item, index) {
  10451. item.index = index;
  10452. });
  10453. return 0;
  10454. }
  10455. // insert(section, index) {
  10456. //
  10457. // };
  10458. /**
  10459. * Remove a Section from the Spine
  10460. * @private
  10461. * @param {Section} section
  10462. */
  10463. }, {
  10464. key: "remove",
  10465. value: function remove(section) {
  10466. var index = this.spineItems.indexOf(section);
  10467. if (index > -1) {
  10468. delete this.spineByHref[section.href];
  10469. delete this.spineById[section.idref];
  10470. return this.spineItems.splice(index, 1);
  10471. }
  10472. }
  10473. /**
  10474. * Loop over the Sections in the Spine
  10475. * @return {method} forEach
  10476. */
  10477. }, {
  10478. key: "each",
  10479. value: function each() {
  10480. return this.spineItems.forEach.apply(this.spineItems, arguments);
  10481. }
  10482. /**
  10483. * Find the first Section in the Spine
  10484. * @return {Section} first section
  10485. */
  10486. }, {
  10487. key: "first",
  10488. value: function first() {
  10489. var index = 0;
  10490. do {
  10491. var next = this.get(index);
  10492. if (next && next.linear) {
  10493. return next;
  10494. }
  10495. index += 1;
  10496. } while (index < this.spineItems.length);
  10497. }
  10498. /**
  10499. * Find the last Section in the Spine
  10500. * @return {Section} last section
  10501. */
  10502. }, {
  10503. key: "last",
  10504. value: function last() {
  10505. var index = this.spineItems.length - 1;
  10506. do {
  10507. var prev = this.get(index);
  10508. if (prev && prev.linear) {
  10509. return prev;
  10510. }
  10511. index -= 1;
  10512. } while (index >= 0);
  10513. }
  10514. }, {
  10515. key: "destroy",
  10516. value: function destroy() {
  10517. this.each(function (section) {
  10518. return section.destroy();
  10519. });
  10520. this.spineItems = undefined;
  10521. this.spineByHref = undefined;
  10522. this.spineById = undefined;
  10523. this.hooks.serialize.clear();
  10524. this.hooks.content.clear();
  10525. this.hooks = undefined;
  10526. this.epubcfi = undefined;
  10527. this.loaded = false;
  10528. this.items = undefined;
  10529. this.manifest = undefined;
  10530. this.spineNodeIndex = undefined;
  10531. this.baseUrl = undefined;
  10532. this.length = undefined;
  10533. }
  10534. }]);
  10535. return Spine;
  10536. }();
  10537. exports.default = Spine;
  10538. module.exports = exports["default"];
  10539. /***/ }),
  10540. /* 44 */
  10541. /***/ (function(module, exports, __webpack_require__) {
  10542. "use strict";
  10543. Object.defineProperty(exports, "__esModule", {
  10544. value: true
  10545. });
  10546. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  10547. var _core = __webpack_require__(0);
  10548. var _epubcfi = __webpack_require__(1);
  10549. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  10550. var _hook = __webpack_require__(10);
  10551. var _hook2 = _interopRequireDefault(_hook);
  10552. var _replacements = __webpack_require__(7);
  10553. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10554. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10555. /**
  10556. * Represents a Section of the Book
  10557. *
  10558. * In most books this is equivelent to a Chapter
  10559. * @param {object} item The spine item representing the section
  10560. * @param {object} hooks hooks for serialize and content
  10561. */
  10562. var Section = function () {
  10563. function Section(item, hooks) {
  10564. _classCallCheck(this, Section);
  10565. this.idref = item.idref;
  10566. this.linear = item.linear === "yes";
  10567. this.properties = item.properties;
  10568. this.index = item.index;
  10569. this.href = item.href;
  10570. this.url = item.url;
  10571. this.canonical = item.canonical;
  10572. this.next = item.next;
  10573. this.prev = item.prev;
  10574. this.cfiBase = item.cfiBase;
  10575. if (hooks) {
  10576. this.hooks = hooks;
  10577. } else {
  10578. this.hooks = {};
  10579. this.hooks.serialize = new _hook2.default(this);
  10580. this.hooks.content = new _hook2.default(this);
  10581. }
  10582. this.document = undefined;
  10583. this.contents = undefined;
  10584. this.output = undefined;
  10585. }
  10586. /**
  10587. * Load the section from its url
  10588. * @param {method} [_request] a request method to use for loading
  10589. * @return {document} a promise with the xml document
  10590. */
  10591. _createClass(Section, [{
  10592. key: "load",
  10593. value: function load(_request) {
  10594. var request = _request || this.request || __webpack_require__(11);
  10595. var loading = new _core.defer();
  10596. var loaded = loading.promise;
  10597. if (this.contents) {
  10598. loading.resolve(this.contents);
  10599. } else {
  10600. request(this.url).then(function (xml) {
  10601. // var directory = new Url(this.url).directory;
  10602. this.document = xml;
  10603. this.contents = xml.documentElement;
  10604. return this.hooks.content.trigger(this.document, this);
  10605. }.bind(this)).then(function () {
  10606. loading.resolve(this.contents);
  10607. }.bind(this)).catch(function (error) {
  10608. loading.reject(error);
  10609. });
  10610. }
  10611. return loaded;
  10612. }
  10613. /**
  10614. * Adds a base tag for resolving urls in the section
  10615. * @private
  10616. */
  10617. }, {
  10618. key: "base",
  10619. value: function base() {
  10620. return (0, _replacements.replaceBase)(this.document, this);
  10621. }
  10622. /**
  10623. * Render the contents of a section
  10624. * @param {method} [_request] a request method to use for loading
  10625. * @return {string} output a serialized XML Document
  10626. */
  10627. }, {
  10628. key: "render",
  10629. value: function render(_request) {
  10630. var rendering = new _core.defer();
  10631. var rendered = rendering.promise;
  10632. this.output; // TODO: better way to return this from hooks?
  10633. this.load(_request).then(function (contents) {
  10634. var userAgent = typeof navigator !== 'undefined' && navigator.userAgent || '';
  10635. var isIE = userAgent.indexOf('Trident') >= 0;
  10636. var Serializer;
  10637. if (typeof XMLSerializer === "undefined" || isIE) {
  10638. Serializer = __webpack_require__(45).XMLSerializer;
  10639. } else {
  10640. Serializer = XMLSerializer;
  10641. }
  10642. var serializer = new Serializer();
  10643. this.output = serializer.serializeToString(contents);
  10644. return this.output;
  10645. }.bind(this)).then(function () {
  10646. return this.hooks.serialize.trigger(this.output, this);
  10647. }.bind(this)).then(function () {
  10648. rendering.resolve(this.output);
  10649. }.bind(this)).catch(function (error) {
  10650. rendering.reject(error);
  10651. });
  10652. return rendered;
  10653. }
  10654. /**
  10655. * Find a string in a section
  10656. * @param {string} _query The query string to find
  10657. * @return {object[]} A list of matches, with form {cfi, excerpt}
  10658. */
  10659. }, {
  10660. key: "find",
  10661. value: function find(_query) {
  10662. var section = this;
  10663. var matches = [];
  10664. var query = _query.toLowerCase();
  10665. var find = function find(node) {
  10666. var text = node.textContent.toLowerCase();
  10667. var range = section.document.createRange();
  10668. var cfi;
  10669. var pos;
  10670. var last = -1;
  10671. var excerpt;
  10672. var limit = 150;
  10673. while (pos != -1) {
  10674. // Search for the query
  10675. pos = text.indexOf(query, last + 1);
  10676. if (pos != -1) {
  10677. // We found it! Generate a CFI
  10678. range = section.document.createRange();
  10679. range.setStart(node, pos);
  10680. range.setEnd(node, pos + query.length);
  10681. cfi = section.cfiFromRange(range);
  10682. // Generate the excerpt
  10683. if (node.textContent.length < limit) {
  10684. excerpt = node.textContent;
  10685. } else {
  10686. excerpt = node.textContent.substring(pos - limit / 2, pos + limit / 2);
  10687. excerpt = "..." + excerpt + "...";
  10688. }
  10689. // Add the CFI to the matches list
  10690. matches.push({
  10691. cfi: cfi,
  10692. excerpt: excerpt
  10693. });
  10694. }
  10695. last = pos;
  10696. }
  10697. };
  10698. (0, _core.sprint)(section.document, function (node) {
  10699. find(node);
  10700. });
  10701. return matches;
  10702. }
  10703. }, {
  10704. key: "reconcileLayoutSettings",
  10705. /**
  10706. * Reconciles the current chapters layout properies with
  10707. * the global layout properities.
  10708. * @param {object} globalLayout The global layout settings object, chapter properties string
  10709. * @return {object} layoutProperties Object with layout properties
  10710. */
  10711. value: function reconcileLayoutSettings(globalLayout) {
  10712. //-- Get the global defaults
  10713. var settings = {
  10714. layout: globalLayout.layout,
  10715. spread: globalLayout.spread,
  10716. orientation: globalLayout.orientation
  10717. };
  10718. //-- Get the chapter's display type
  10719. this.properties.forEach(function (prop) {
  10720. var rendition = prop.replace("rendition:", "");
  10721. var split = rendition.indexOf("-");
  10722. var property, value;
  10723. if (split != -1) {
  10724. property = rendition.slice(0, split);
  10725. value = rendition.slice(split + 1);
  10726. settings[property] = value;
  10727. }
  10728. });
  10729. return settings;
  10730. }
  10731. /**
  10732. * Get a CFI from a Range in the Section
  10733. * @param {range} _range
  10734. * @return {string} cfi an EpubCFI string
  10735. */
  10736. }, {
  10737. key: "cfiFromRange",
  10738. value: function cfiFromRange(_range) {
  10739. return new _epubcfi2.default(_range, this.cfiBase).toString();
  10740. }
  10741. /**
  10742. * Get a CFI from an Element in the Section
  10743. * @param {element} el
  10744. * @return {string} cfi an EpubCFI string
  10745. */
  10746. }, {
  10747. key: "cfiFromElement",
  10748. value: function cfiFromElement(el) {
  10749. return new _epubcfi2.default(el, this.cfiBase).toString();
  10750. }
  10751. /**
  10752. * Unload the section document
  10753. */
  10754. }, {
  10755. key: "unload",
  10756. value: function unload() {
  10757. this.document = undefined;
  10758. this.contents = undefined;
  10759. this.output = undefined;
  10760. }
  10761. }, {
  10762. key: "destroy",
  10763. value: function destroy() {
  10764. this.unload();
  10765. this.hooks.serialize.clear();
  10766. this.hooks.content.clear();
  10767. this.hooks = undefined;
  10768. this.idref = undefined;
  10769. this.linear = undefined;
  10770. this.properties = undefined;
  10771. this.index = undefined;
  10772. this.href = undefined;
  10773. this.url = undefined;
  10774. this.next = undefined;
  10775. this.prev = undefined;
  10776. this.cfiBase = undefined;
  10777. }
  10778. }]);
  10779. return Section;
  10780. }();
  10781. exports.default = Section;
  10782. module.exports = exports["default"];
  10783. /***/ }),
  10784. /* 45 */
  10785. /***/ (function(module, exports, __webpack_require__) {
  10786. function DOMParser(options){
  10787. this.options = options ||{locator:{}};
  10788. }
  10789. DOMParser.prototype.parseFromString = function(source,mimeType){
  10790. var options = this.options;
  10791. var sax = new XMLReader();
  10792. var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
  10793. var errorHandler = options.errorHandler;
  10794. var locator = options.locator;
  10795. var defaultNSMap = options.xmlns||{};
  10796. var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}
  10797. if(locator){
  10798. domBuilder.setDocumentLocator(locator)
  10799. }
  10800. sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
  10801. sax.domBuilder = options.domBuilder || domBuilder;
  10802. if(/\/x?html?$/.test(mimeType)){
  10803. entityMap.nbsp = '\xa0';
  10804. entityMap.copy = '\xa9';
  10805. defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
  10806. }
  10807. defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
  10808. if(source){
  10809. sax.parse(source,defaultNSMap,entityMap);
  10810. }else{
  10811. sax.errorHandler.error("invalid doc source");
  10812. }
  10813. return domBuilder.doc;
  10814. }
  10815. function buildErrorHandler(errorImpl,domBuilder,locator){
  10816. if(!errorImpl){
  10817. if(domBuilder instanceof DOMHandler){
  10818. return domBuilder;
  10819. }
  10820. errorImpl = domBuilder ;
  10821. }
  10822. var errorHandler = {}
  10823. var isCallback = errorImpl instanceof Function;
  10824. locator = locator||{}
  10825. function build(key){
  10826. var fn = errorImpl[key];
  10827. if(!fn && isCallback){
  10828. fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
  10829. }
  10830. errorHandler[key] = fn && function(msg){
  10831. fn('[xmldom '+key+']\t'+msg+_locator(locator));
  10832. }||function(){};
  10833. }
  10834. build('warning');
  10835. build('error');
  10836. build('fatalError');
  10837. return errorHandler;
  10838. }
  10839. //console.log('#\n\n\n\n\n\n\n####')
  10840. /**
  10841. * +ContentHandler+ErrorHandler
  10842. * +LexicalHandler+EntityResolver2
  10843. * -DeclHandler-DTDHandler
  10844. *
  10845. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  10846. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  10847. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  10848. */
  10849. function DOMHandler() {
  10850. this.cdata = false;
  10851. }
  10852. function position(locator,node){
  10853. node.lineNumber = locator.lineNumber;
  10854. node.columnNumber = locator.columnNumber;
  10855. }
  10856. /**
  10857. * @see org.xml.sax.ContentHandler#startDocument
  10858. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  10859. */
  10860. DOMHandler.prototype = {
  10861. startDocument : function() {
  10862. this.doc = new DOMImplementation().createDocument(null, null, null);
  10863. if (this.locator) {
  10864. this.doc.documentURI = this.locator.systemId;
  10865. }
  10866. },
  10867. startElement:function(namespaceURI, localName, qName, attrs) {
  10868. var doc = this.doc;
  10869. var el = doc.createElementNS(namespaceURI, qName||localName);
  10870. var len = attrs.length;
  10871. appendElement(this, el);
  10872. this.currentElement = el;
  10873. this.locator && position(this.locator,el)
  10874. for (var i = 0 ; i < len; i++) {
  10875. var namespaceURI = attrs.getURI(i);
  10876. var value = attrs.getValue(i);
  10877. var qName = attrs.getQName(i);
  10878. var attr = doc.createAttributeNS(namespaceURI, qName);
  10879. this.locator &&position(attrs.getLocator(i),attr);
  10880. attr.value = attr.nodeValue = value;
  10881. el.setAttributeNode(attr)
  10882. }
  10883. },
  10884. endElement:function(namespaceURI, localName, qName) {
  10885. var current = this.currentElement
  10886. var tagName = current.tagName;
  10887. this.currentElement = current.parentNode;
  10888. },
  10889. startPrefixMapping:function(prefix, uri) {
  10890. },
  10891. endPrefixMapping:function(prefix) {
  10892. },
  10893. processingInstruction:function(target, data) {
  10894. var ins = this.doc.createProcessingInstruction(target, data);
  10895. this.locator && position(this.locator,ins)
  10896. appendElement(this, ins);
  10897. },
  10898. ignorableWhitespace:function(ch, start, length) {
  10899. },
  10900. characters:function(chars, start, length) {
  10901. chars = _toString.apply(this,arguments)
  10902. //console.log(chars)
  10903. if(chars){
  10904. if (this.cdata) {
  10905. var charNode = this.doc.createCDATASection(chars);
  10906. } else {
  10907. var charNode = this.doc.createTextNode(chars);
  10908. }
  10909. if(this.currentElement){
  10910. this.currentElement.appendChild(charNode);
  10911. }else if(/^\s*$/.test(chars)){
  10912. this.doc.appendChild(charNode);
  10913. //process xml
  10914. }
  10915. this.locator && position(this.locator,charNode)
  10916. }
  10917. },
  10918. skippedEntity:function(name) {
  10919. },
  10920. endDocument:function() {
  10921. this.doc.normalize();
  10922. },
  10923. setDocumentLocator:function (locator) {
  10924. if(this.locator = locator){// && !('lineNumber' in locator)){
  10925. locator.lineNumber = 0;
  10926. }
  10927. },
  10928. //LexicalHandler
  10929. comment:function(chars, start, length) {
  10930. chars = _toString.apply(this,arguments)
  10931. var comm = this.doc.createComment(chars);
  10932. this.locator && position(this.locator,comm)
  10933. appendElement(this, comm);
  10934. },
  10935. startCDATA:function() {
  10936. //used in characters() methods
  10937. this.cdata = true;
  10938. },
  10939. endCDATA:function() {
  10940. this.cdata = false;
  10941. },
  10942. startDTD:function(name, publicId, systemId) {
  10943. var impl = this.doc.implementation;
  10944. if (impl && impl.createDocumentType) {
  10945. var dt = impl.createDocumentType(name, publicId, systemId);
  10946. this.locator && position(this.locator,dt)
  10947. appendElement(this, dt);
  10948. }
  10949. },
  10950. /**
  10951. * @see org.xml.sax.ErrorHandler
  10952. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  10953. */
  10954. warning:function(error) {
  10955. console.warn('[xmldom warning]\t'+error,_locator(this.locator));
  10956. },
  10957. error:function(error) {
  10958. console.error('[xmldom error]\t'+error,_locator(this.locator));
  10959. },
  10960. fatalError:function(error) {
  10961. console.error('[xmldom fatalError]\t'+error,_locator(this.locator));
  10962. throw error;
  10963. }
  10964. }
  10965. function _locator(l){
  10966. if(l){
  10967. return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
  10968. }
  10969. }
  10970. function _toString(chars,start,length){
  10971. if(typeof chars == 'string'){
  10972. return chars.substr(start,length)
  10973. }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  10974. if(chars.length >= start+length || start){
  10975. return new java.lang.String(chars,start,length)+'';
  10976. }
  10977. return chars;
  10978. }
  10979. }
  10980. /*
  10981. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  10982. * used method of org.xml.sax.ext.LexicalHandler:
  10983. * #comment(chars, start, length)
  10984. * #startCDATA()
  10985. * #endCDATA()
  10986. * #startDTD(name, publicId, systemId)
  10987. *
  10988. *
  10989. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  10990. * #endDTD()
  10991. * #startEntity(name)
  10992. * #endEntity(name)
  10993. *
  10994. *
  10995. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  10996. * IGNORED method of org.xml.sax.ext.DeclHandler
  10997. * #attributeDecl(eName, aName, type, mode, value)
  10998. * #elementDecl(name, model)
  10999. * #externalEntityDecl(name, publicId, systemId)
  11000. * #internalEntityDecl(name, value)
  11001. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  11002. * IGNORED method of org.xml.sax.EntityResolver2
  11003. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  11004. * #resolveEntity(publicId, systemId)
  11005. * #getExternalSubset(name, baseURI)
  11006. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  11007. * IGNORED method of org.xml.sax.DTDHandler
  11008. * #notationDecl(name, publicId, systemId) {};
  11009. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  11010. */
  11011. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
  11012. DOMHandler.prototype[key] = function(){return null}
  11013. })
  11014. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  11015. function appendElement (hander,node) {
  11016. if (!hander.currentElement) {
  11017. hander.doc.appendChild(node);
  11018. } else {
  11019. hander.currentElement.appendChild(node);
  11020. }
  11021. }//appendChild and setAttributeNS are preformance key
  11022. //if(typeof require == 'function'){
  11023. var XMLReader = __webpack_require__(46).XMLReader;
  11024. var DOMImplementation = exports.DOMImplementation = __webpack_require__(16).DOMImplementation;
  11025. exports.XMLSerializer = __webpack_require__(16).XMLSerializer ;
  11026. exports.DOMParser = DOMParser;
  11027. //}
  11028. /***/ }),
  11029. /* 46 */
  11030. /***/ (function(module, exports) {
  11031. //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  11032. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  11033. //[5] Name ::= NameStartChar (NameChar)*
  11034. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
  11035. var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  11036. var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
  11037. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  11038. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  11039. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  11040. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  11041. var S_TAG = 0;//tag name offerring
  11042. var S_ATTR = 1;//attr name offerring
  11043. var S_ATTR_SPACE=2;//attr name end and space offer
  11044. var S_EQ = 3;//=space?
  11045. var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
  11046. var S_ATTR_END = 5;//attr value end and no space(quot end)
  11047. var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
  11048. var S_TAG_CLOSE = 7;//closed el<el />
  11049. function XMLReader(){
  11050. }
  11051. XMLReader.prototype = {
  11052. parse:function(source,defaultNSMap,entityMap){
  11053. var domBuilder = this.domBuilder;
  11054. domBuilder.startDocument();
  11055. _copy(defaultNSMap ,defaultNSMap = {})
  11056. parse(source,defaultNSMap,entityMap,
  11057. domBuilder,this.errorHandler);
  11058. domBuilder.endDocument();
  11059. }
  11060. }
  11061. function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
  11062. function fixedFromCharCode(code) {
  11063. // String.prototype.fromCharCode does not supports
  11064. // > 2 bytes unicode chars directly
  11065. if (code > 0xffff) {
  11066. code -= 0x10000;
  11067. var surrogate1 = 0xd800 + (code >> 10)
  11068. , surrogate2 = 0xdc00 + (code & 0x3ff);
  11069. return String.fromCharCode(surrogate1, surrogate2);
  11070. } else {
  11071. return String.fromCharCode(code);
  11072. }
  11073. }
  11074. function entityReplacer(a){
  11075. var k = a.slice(1,-1);
  11076. if(k in entityMap){
  11077. return entityMap[k];
  11078. }else if(k.charAt(0) === '#'){
  11079. return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
  11080. }else{
  11081. errorHandler.error('entity not found:'+a);
  11082. return a;
  11083. }
  11084. }
  11085. function appendText(end){//has some bugs
  11086. if(end>start){
  11087. var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
  11088. locator&&position(start);
  11089. domBuilder.characters(xt,0,end-start);
  11090. start = end
  11091. }
  11092. }
  11093. function position(p,m){
  11094. while(p>=lineEnd && (m = linePattern.exec(source))){
  11095. lineStart = m.index;
  11096. lineEnd = lineStart + m[0].length;
  11097. locator.lineNumber++;
  11098. //console.log('line++:',locator,startPos,endPos)
  11099. }
  11100. locator.columnNumber = p-lineStart+1;
  11101. }
  11102. var lineStart = 0;
  11103. var lineEnd = 0;
  11104. var linePattern = /.*(?:\r\n?|\n)|.*$/g
  11105. var locator = domBuilder.locator;
  11106. var parseStack = [{currentNSMap:defaultNSMapCopy}]
  11107. var closeMap = {};
  11108. var start = 0;
  11109. while(true){
  11110. try{
  11111. var tagStart = source.indexOf('<',start);
  11112. if(tagStart<0){
  11113. if(!source.substr(start).match(/^\s*$/)){
  11114. var doc = domBuilder.doc;
  11115. var text = doc.createTextNode(source.substr(start));
  11116. doc.appendChild(text);
  11117. domBuilder.currentElement = text;
  11118. }
  11119. return;
  11120. }
  11121. if(tagStart>start){
  11122. appendText(tagStart);
  11123. }
  11124. switch(source.charAt(tagStart+1)){
  11125. case '/':
  11126. var end = source.indexOf('>',tagStart+3);
  11127. var tagName = source.substring(tagStart+2,end);
  11128. var config = parseStack.pop();
  11129. if(end<0){
  11130. tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
  11131. //console.error('#@@@@@@'+tagName)
  11132. errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
  11133. end = tagStart+1+tagName.length;
  11134. }else if(tagName.match(/\s</)){
  11135. tagName = tagName.replace(/[\s<].*/,'');
  11136. errorHandler.error("end tag name: "+tagName+' maybe not complete');
  11137. end = tagStart+1+tagName.length;
  11138. }
  11139. //console.error(parseStack.length,parseStack)
  11140. //console.error(config);
  11141. var localNSMap = config.localNSMap;
  11142. var endMatch = config.tagName == tagName;
  11143. var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
  11144. if(endIgnoreCaseMach){
  11145. domBuilder.endElement(config.uri,config.localName,tagName);
  11146. if(localNSMap){
  11147. for(var prefix in localNSMap){
  11148. domBuilder.endPrefixMapping(prefix) ;
  11149. }
  11150. }
  11151. if(!endMatch){
  11152. errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
  11153. }
  11154. }else{
  11155. parseStack.push(config)
  11156. }
  11157. end++;
  11158. break;
  11159. // end elment
  11160. case '?':// <?...?>
  11161. locator&&position(tagStart);
  11162. end = parseInstruction(source,tagStart,domBuilder);
  11163. break;
  11164. case '!':// <!doctype,<![CDATA,<!--
  11165. locator&&position(tagStart);
  11166. end = parseDCC(source,tagStart,domBuilder,errorHandler);
  11167. break;
  11168. default:
  11169. locator&&position(tagStart);
  11170. var el = new ElementAttributes();
  11171. var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  11172. //elStartEnd
  11173. var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
  11174. var len = el.length;
  11175. if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
  11176. el.closed = true;
  11177. if(!entityMap.nbsp){
  11178. errorHandler.warning('unclosed xml attribute');
  11179. }
  11180. }
  11181. if(locator && len){
  11182. var locator2 = copyLocator(locator,{});
  11183. //try{//attribute position fixed
  11184. for(var i = 0;i<len;i++){
  11185. var a = el[i];
  11186. position(a.offset);
  11187. a.locator = copyLocator(locator,{});
  11188. }
  11189. //}catch(e){console.error('@@@@@'+e)}
  11190. domBuilder.locator = locator2
  11191. if(appendElement(el,domBuilder,currentNSMap)){
  11192. parseStack.push(el)
  11193. }
  11194. domBuilder.locator = locator;
  11195. }else{
  11196. if(appendElement(el,domBuilder,currentNSMap)){
  11197. parseStack.push(el)
  11198. }
  11199. }
  11200. if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
  11201. end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
  11202. }else{
  11203. end++;
  11204. }
  11205. }
  11206. }catch(e){
  11207. errorHandler.error('element parse error: '+e)
  11208. //errorHandler.error('element parse error: '+e);
  11209. end = -1;
  11210. //throw e;
  11211. }
  11212. if(end>start){
  11213. start = end;
  11214. }else{
  11215. //TODO: 这里有可能sax回退,有位置错误风险
  11216. appendText(Math.max(tagStart,start)+1);
  11217. }
  11218. }
  11219. }
  11220. function copyLocator(f,t){
  11221. t.lineNumber = f.lineNumber;
  11222. t.columnNumber = f.columnNumber;
  11223. return t;
  11224. }
  11225. /**
  11226. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  11227. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  11228. */
  11229. function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
  11230. var attrName;
  11231. var value;
  11232. var p = ++start;
  11233. var s = S_TAG;//status
  11234. while(true){
  11235. var c = source.charAt(p);
  11236. switch(c){
  11237. case '=':
  11238. if(s === S_ATTR){//attrName
  11239. attrName = source.slice(start,p);
  11240. s = S_EQ;
  11241. }else if(s === S_ATTR_SPACE){
  11242. s = S_EQ;
  11243. }else{
  11244. //fatalError: equal must after attrName or space after attrName
  11245. throw new Error('attribute equal must after attrName');
  11246. }
  11247. break;
  11248. case '\'':
  11249. case '"':
  11250. if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  11251. ){//equal
  11252. if(s === S_ATTR){
  11253. errorHandler.warning('attribute value must after "="')
  11254. attrName = source.slice(start,p)
  11255. }
  11256. start = p+1;
  11257. p = source.indexOf(c,start)
  11258. if(p>0){
  11259. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  11260. el.add(attrName,value,start-1);
  11261. s = S_ATTR_END;
  11262. }else{
  11263. //fatalError: no end quot match
  11264. throw new Error('attribute value no end \''+c+'\' match');
  11265. }
  11266. }else if(s == S_ATTR_NOQUOT_VALUE){
  11267. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  11268. //console.log(attrName,value,start,p)
  11269. el.add(attrName,value,start);
  11270. //console.dir(el)
  11271. errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
  11272. start = p+1;
  11273. s = S_ATTR_END
  11274. }else{
  11275. //fatalError: no equal before
  11276. throw new Error('attribute value must after "="');
  11277. }
  11278. break;
  11279. case '/':
  11280. switch(s){
  11281. case S_TAG:
  11282. el.setTagName(source.slice(start,p));
  11283. case S_ATTR_END:
  11284. case S_TAG_SPACE:
  11285. case S_TAG_CLOSE:
  11286. s =S_TAG_CLOSE;
  11287. el.closed = true;
  11288. case S_ATTR_NOQUOT_VALUE:
  11289. case S_ATTR:
  11290. case S_ATTR_SPACE:
  11291. break;
  11292. //case S_EQ:
  11293. default:
  11294. throw new Error("attribute invalid close char('/')")
  11295. }
  11296. break;
  11297. case ''://end document
  11298. //throw new Error('unexpected end of input')
  11299. errorHandler.error('unexpected end of input');
  11300. if(s == S_TAG){
  11301. el.setTagName(source.slice(start,p));
  11302. }
  11303. return p;
  11304. case '>':
  11305. switch(s){
  11306. case S_TAG:
  11307. el.setTagName(source.slice(start,p));
  11308. case S_ATTR_END:
  11309. case S_TAG_SPACE:
  11310. case S_TAG_CLOSE:
  11311. break;//normal
  11312. case S_ATTR_NOQUOT_VALUE://Compatible state
  11313. case S_ATTR:
  11314. value = source.slice(start,p);
  11315. if(value.slice(-1) === '/'){
  11316. el.closed = true;
  11317. value = value.slice(0,-1)
  11318. }
  11319. case S_ATTR_SPACE:
  11320. if(s === S_ATTR_SPACE){
  11321. value = attrName;
  11322. }
  11323. if(s == S_ATTR_NOQUOT_VALUE){
  11324. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  11325. el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
  11326. }else{
  11327. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
  11328. errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
  11329. }
  11330. el.add(value,value,start)
  11331. }
  11332. break;
  11333. case S_EQ:
  11334. throw new Error('attribute value missed!!');
  11335. }
  11336. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  11337. return p;
  11338. /*xml space '\x20' | #x9 | #xD | #xA; */
  11339. case '\u0080':
  11340. c = ' ';
  11341. default:
  11342. if(c<= ' '){//space
  11343. switch(s){
  11344. case S_TAG:
  11345. el.setTagName(source.slice(start,p));//tagName
  11346. s = S_TAG_SPACE;
  11347. break;
  11348. case S_ATTR:
  11349. attrName = source.slice(start,p)
  11350. s = S_ATTR_SPACE;
  11351. break;
  11352. case S_ATTR_NOQUOT_VALUE:
  11353. var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  11354. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  11355. el.add(attrName,value,start)
  11356. case S_ATTR_END:
  11357. s = S_TAG_SPACE;
  11358. break;
  11359. //case S_TAG_SPACE:
  11360. //case S_EQ:
  11361. //case S_ATTR_SPACE:
  11362. // void();break;
  11363. //case S_TAG_CLOSE:
  11364. //ignore warning
  11365. }
  11366. }else{//not space
  11367. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  11368. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  11369. switch(s){
  11370. //case S_TAG:void();break;
  11371. //case S_ATTR:void();break;
  11372. //case S_ATTR_NOQUOT_VALUE:void();break;
  11373. case S_ATTR_SPACE:
  11374. var tagName = el.tagName;
  11375. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
  11376. errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
  11377. }
  11378. el.add(attrName,attrName,start);
  11379. start = p;
  11380. s = S_ATTR;
  11381. break;
  11382. case S_ATTR_END:
  11383. errorHandler.warning('attribute space is required"'+attrName+'"!!')
  11384. case S_TAG_SPACE:
  11385. s = S_ATTR;
  11386. start = p;
  11387. break;
  11388. case S_EQ:
  11389. s = S_ATTR_NOQUOT_VALUE;
  11390. start = p;
  11391. break;
  11392. case S_TAG_CLOSE:
  11393. throw new Error("elements closed character '/' and '>' must be connected to");
  11394. }
  11395. }
  11396. }//end outer switch
  11397. //console.log('p++',p)
  11398. p++;
  11399. }
  11400. }
  11401. /**
  11402. * @return true if has new namespace define
  11403. */
  11404. function appendElement(el,domBuilder,currentNSMap){
  11405. var tagName = el.tagName;
  11406. var localNSMap = null;
  11407. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  11408. var i = el.length;
  11409. while(i--){
  11410. var a = el[i];
  11411. var qName = a.qName;
  11412. var value = a.value;
  11413. var nsp = qName.indexOf(':');
  11414. if(nsp>0){
  11415. var prefix = a.prefix = qName.slice(0,nsp);
  11416. var localName = qName.slice(nsp+1);
  11417. var nsPrefix = prefix === 'xmlns' && localName
  11418. }else{
  11419. localName = qName;
  11420. prefix = null
  11421. nsPrefix = qName === 'xmlns' && ''
  11422. }
  11423. //can not set prefix,because prefix !== ''
  11424. a.localName = localName ;
  11425. //prefix == null for no ns prefix attribute
  11426. if(nsPrefix !== false){//hack!!
  11427. if(localNSMap == null){
  11428. localNSMap = {}
  11429. //console.log(currentNSMap,0)
  11430. _copy(currentNSMap,currentNSMap={})
  11431. //console.log(currentNSMap,1)
  11432. }
  11433. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  11434. a.uri = 'http://www.w3.org/2000/xmlns/'
  11435. domBuilder.startPrefixMapping(nsPrefix, value)
  11436. }
  11437. }
  11438. var i = el.length;
  11439. while(i--){
  11440. a = el[i];
  11441. var prefix = a.prefix;
  11442. if(prefix){//no prefix attribute has no namespace
  11443. if(prefix === 'xml'){
  11444. a.uri = 'http://www.w3.org/XML/1998/namespace';
  11445. }if(prefix !== 'xmlns'){
  11446. a.uri = currentNSMap[prefix || '']
  11447. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  11448. }
  11449. }
  11450. }
  11451. var nsp = tagName.indexOf(':');
  11452. if(nsp>0){
  11453. prefix = el.prefix = tagName.slice(0,nsp);
  11454. localName = el.localName = tagName.slice(nsp+1);
  11455. }else{
  11456. prefix = null;//important!!
  11457. localName = el.localName = tagName;
  11458. }
  11459. //no prefix element has default namespace
  11460. var ns = el.uri = currentNSMap[prefix || ''];
  11461. domBuilder.startElement(ns,localName,tagName,el);
  11462. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  11463. //localNSMap = null
  11464. if(el.closed){
  11465. domBuilder.endElement(ns,localName,tagName);
  11466. if(localNSMap){
  11467. for(prefix in localNSMap){
  11468. domBuilder.endPrefixMapping(prefix)
  11469. }
  11470. }
  11471. }else{
  11472. el.currentNSMap = currentNSMap;
  11473. el.localNSMap = localNSMap;
  11474. //parseStack.push(el);
  11475. return true;
  11476. }
  11477. }
  11478. function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
  11479. if(/^(?:script|textarea)$/i.test(tagName)){
  11480. var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
  11481. var text = source.substring(elStartEnd+1,elEndStart);
  11482. if(/[&<]/.test(text)){
  11483. if(/^script$/i.test(tagName)){
  11484. //if(!/\]\]>/.test(text)){
  11485. //lexHandler.startCDATA();
  11486. domBuilder.characters(text,0,text.length);
  11487. //lexHandler.endCDATA();
  11488. return elEndStart;
  11489. //}
  11490. }//}else{//text area
  11491. text = text.replace(/&#?\w+;/g,entityReplacer);
  11492. domBuilder.characters(text,0,text.length);
  11493. return elEndStart;
  11494. //}
  11495. }
  11496. }
  11497. return elStartEnd+1;
  11498. }
  11499. function fixSelfClosed(source,elStartEnd,tagName,closeMap){
  11500. //if(tagName in closeMap){
  11501. var pos = closeMap[tagName];
  11502. if(pos == null){
  11503. //console.log(tagName)
  11504. pos = source.lastIndexOf('</'+tagName+'>')
  11505. if(pos<elStartEnd){//忘记闭合
  11506. pos = source.lastIndexOf('</'+tagName)
  11507. }
  11508. closeMap[tagName] =pos
  11509. }
  11510. return pos<elStartEnd;
  11511. //}
  11512. }
  11513. function _copy(source,target){
  11514. for(var n in source){target[n] = source[n]}
  11515. }
  11516. function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
  11517. var next= source.charAt(start+2)
  11518. switch(next){
  11519. case '-':
  11520. if(source.charAt(start + 3) === '-'){
  11521. var end = source.indexOf('-->',start+4);
  11522. //append comment source.substring(4,end)//<!--
  11523. if(end>start){
  11524. domBuilder.comment(source,start+4,end-start-4);
  11525. return end+3;
  11526. }else{
  11527. errorHandler.error("Unclosed comment");
  11528. return -1;
  11529. }
  11530. }else{
  11531. //error
  11532. return -1;
  11533. }
  11534. default:
  11535. if(source.substr(start+3,6) == 'CDATA['){
  11536. var end = source.indexOf(']]>',start+9);
  11537. domBuilder.startCDATA();
  11538. domBuilder.characters(source,start+9,end-start-9);
  11539. domBuilder.endCDATA()
  11540. return end+3;
  11541. }
  11542. //<!DOCTYPE
  11543. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  11544. var matchs = split(source,start);
  11545. var len = matchs.length;
  11546. if(len>1 && /!doctype/i.test(matchs[0][0])){
  11547. var name = matchs[1][0];
  11548. var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0]
  11549. var sysid = len>4 && matchs[4][0];
  11550. var lastMatch = matchs[len-1]
  11551. domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
  11552. sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
  11553. domBuilder.endDTD();
  11554. return lastMatch.index+lastMatch[0].length
  11555. }
  11556. }
  11557. return -1;
  11558. }
  11559. function parseInstruction(source,start,domBuilder){
  11560. var end = source.indexOf('?>',start);
  11561. if(end){
  11562. var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  11563. if(match){
  11564. var len = match[0].length;
  11565. domBuilder.processingInstruction(match[1], match[2]) ;
  11566. return end+2;
  11567. }else{//error
  11568. return -1;
  11569. }
  11570. }
  11571. return -1;
  11572. }
  11573. /**
  11574. * @param source
  11575. */
  11576. function ElementAttributes(source){
  11577. }
  11578. ElementAttributes.prototype = {
  11579. setTagName:function(tagName){
  11580. if(!tagNamePattern.test(tagName)){
  11581. throw new Error('invalid tagName:'+tagName)
  11582. }
  11583. this.tagName = tagName
  11584. },
  11585. add:function(qName,value,offset){
  11586. if(!tagNamePattern.test(qName)){
  11587. throw new Error('invalid attribute:'+qName)
  11588. }
  11589. this[this.length++] = {qName:qName,value:value,offset:offset}
  11590. },
  11591. length:0,
  11592. getLocalName:function(i){return this[i].localName},
  11593. getLocator:function(i){return this[i].locator},
  11594. getQName:function(i){return this[i].qName},
  11595. getURI:function(i){return this[i].uri},
  11596. getValue:function(i){return this[i].value}
  11597. // ,getIndex:function(uri, localName)){
  11598. // if(localName){
  11599. //
  11600. // }else{
  11601. // var qName = uri
  11602. // }
  11603. // },
  11604. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  11605. // getType:function(uri,localName){}
  11606. // getType:function(i){},
  11607. }
  11608. function _set_proto_(thiz,parent){
  11609. thiz.__proto__ = parent;
  11610. return thiz;
  11611. }
  11612. if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){
  11613. _set_proto_ = function(thiz,parent){
  11614. function p(){};
  11615. p.prototype = parent;
  11616. p = new p();
  11617. for(parent in thiz){
  11618. p[parent] = thiz[parent];
  11619. }
  11620. return p;
  11621. }
  11622. }
  11623. function split(source,start){
  11624. var match;
  11625. var buf = [];
  11626. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  11627. reg.lastIndex = start;
  11628. reg.exec(source);//skip <
  11629. while(match = reg.exec(source)){
  11630. buf.push(match);
  11631. if(match[1])return buf;
  11632. }
  11633. }
  11634. exports.XMLReader = XMLReader;
  11635. /***/ }),
  11636. /* 47 */
  11637. /***/ (function(module, exports, __webpack_require__) {
  11638. "use strict";
  11639. Object.defineProperty(exports, "__esModule", {
  11640. value: true
  11641. });
  11642. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  11643. var _core = __webpack_require__(0);
  11644. var _queue = __webpack_require__(12);
  11645. var _queue2 = _interopRequireDefault(_queue);
  11646. var _epubcfi = __webpack_require__(1);
  11647. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  11648. var _constants = __webpack_require__(2);
  11649. var _eventEmitter = __webpack_require__(3);
  11650. var _eventEmitter2 = _interopRequireDefault(_eventEmitter);
  11651. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11652. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11653. /**
  11654. * Find Locations for a Book
  11655. * @param {Spine} spine
  11656. * @param {request} request
  11657. * @param {number} [pause=100]
  11658. */
  11659. var Locations = function () {
  11660. function Locations(spine, request, pause) {
  11661. _classCallCheck(this, Locations);
  11662. this.spine = spine;
  11663. this.request = request;
  11664. this.pause = pause || 100;
  11665. this.q = new _queue2.default(this);
  11666. this.epubcfi = new _epubcfi2.default();
  11667. this._locations = [];
  11668. this.total = 0;
  11669. this.break = 150;
  11670. this._current = 0;
  11671. this.currentLocation = '';
  11672. this._currentCfi = '';
  11673. this.processingTimeout = undefined;
  11674. }
  11675. /**
  11676. * Load all of sections in the book to generate locations
  11677. * @param {int} chars how many chars to split on
  11678. * @return {object} locations
  11679. */
  11680. _createClass(Locations, [{
  11681. key: "generate",
  11682. value: function generate(chars) {
  11683. if (chars) {
  11684. this.break = chars;
  11685. }
  11686. this.q.pause();
  11687. this.spine.each(function (section) {
  11688. if (section.linear) {
  11689. this.q.enqueue(this.process.bind(this), section);
  11690. }
  11691. }.bind(this));
  11692. return this.q.run().then(function () {
  11693. this.total = this._locations.length - 1;
  11694. if (this._currentCfi) {
  11695. this.currentLocation = this._currentCfi;
  11696. }
  11697. return this._locations;
  11698. // console.log(this.percentage(this.book.rendition.location.start), this.percentage(this.book.rendition.location.end));
  11699. }.bind(this));
  11700. }
  11701. }, {
  11702. key: "createRange",
  11703. value: function createRange() {
  11704. return {
  11705. startContainer: undefined,
  11706. startOffset: undefined,
  11707. endContainer: undefined,
  11708. endOffset: undefined
  11709. };
  11710. }
  11711. }, {
  11712. key: "process",
  11713. value: function process(section) {
  11714. return section.load(this.request).then(function (contents) {
  11715. var completed = new _core.defer();
  11716. var locations = this.parse(contents, section.cfiBase);
  11717. this._locations = this._locations.concat(locations);
  11718. section.unload();
  11719. this.processingTimeout = setTimeout(function () {
  11720. return completed.resolve(locations);
  11721. }, this.pause);
  11722. return completed.promise;
  11723. }.bind(this));
  11724. }
  11725. }, {
  11726. key: "parse",
  11727. value: function parse(contents, cfiBase, chars) {
  11728. var locations = [];
  11729. var range;
  11730. var doc = contents.ownerDocument;
  11731. var body = (0, _core.qs)(doc, "body");
  11732. var counter = 0;
  11733. var prev;
  11734. var _break = chars || this.break;
  11735. var parser = function parser(node) {
  11736. var len = node.length;
  11737. var dist;
  11738. var pos = 0;
  11739. if (node.textContent.trim().length === 0) {
  11740. return false; // continue
  11741. }
  11742. // Start range
  11743. if (counter == 0) {
  11744. range = this.createRange();
  11745. range.startContainer = node;
  11746. range.startOffset = 0;
  11747. }
  11748. dist = _break - counter;
  11749. // Node is smaller than a break,
  11750. // skip over it
  11751. if (dist > len) {
  11752. counter += len;
  11753. pos = len;
  11754. }
  11755. while (pos < len) {
  11756. dist = _break - counter;
  11757. if (counter === 0) {
  11758. // Start new range
  11759. pos += 1;
  11760. range = this.createRange();
  11761. range.startContainer = node;
  11762. range.startOffset = pos;
  11763. }
  11764. // pos += dist;
  11765. // Gone over
  11766. if (pos + dist >= len) {
  11767. // Continue counter for next node
  11768. counter += len - pos;
  11769. // break
  11770. pos = len;
  11771. // At End
  11772. } else {
  11773. // Advance pos
  11774. pos += dist;
  11775. // End the previous range
  11776. range.endContainer = node;
  11777. range.endOffset = pos;
  11778. // cfi = section.cfiFromRange(range);
  11779. var cfi = new _epubcfi2.default(range, cfiBase).toString();
  11780. locations.push(cfi);
  11781. counter = 0;
  11782. }
  11783. }
  11784. prev = node;
  11785. };
  11786. (0, _core.sprint)(body, parser.bind(this));
  11787. // Close remaining
  11788. if (range && range.startContainer && prev) {
  11789. range.endContainer = prev;
  11790. range.endOffset = prev.length;
  11791. var cfi = new _epubcfi2.default(range, cfiBase).toString();
  11792. locations.push(cfi);
  11793. counter = 0;
  11794. }
  11795. return locations;
  11796. }
  11797. /**
  11798. * Get a location from an EpubCFI
  11799. * @param {EpubCFI} cfi
  11800. * @return {number}
  11801. */
  11802. }, {
  11803. key: "locationFromCfi",
  11804. value: function locationFromCfi(cfi) {
  11805. var loc = void 0;
  11806. if (_epubcfi2.default.prototype.isCfiString(cfi)) {
  11807. cfi = new _epubcfi2.default(cfi);
  11808. }
  11809. // Check if the location has not been set yet
  11810. if (this._locations.length === 0) {
  11811. return -1;
  11812. }
  11813. loc = (0, _core.locationOf)(cfi, this._locations, this.epubcfi.compare);
  11814. if (loc > this.total) {
  11815. return this.total;
  11816. }
  11817. return loc;
  11818. }
  11819. /**
  11820. * Get a percentage position in locations from an EpubCFI
  11821. * @param {EpubCFI} cfi
  11822. * @return {number}
  11823. */
  11824. }, {
  11825. key: "percentageFromCfi",
  11826. value: function percentageFromCfi(cfi) {
  11827. if (this._locations.length === 0) {
  11828. return null;
  11829. }
  11830. // Find closest cfi
  11831. var loc = this.locationFromCfi(cfi);
  11832. // Get percentage in total
  11833. return this.percentageFromLocation(loc);
  11834. }
  11835. /**
  11836. * Get a percentage position from a location index
  11837. * @param {number} location
  11838. * @return {number}
  11839. */
  11840. }, {
  11841. key: "percentageFromLocation",
  11842. value: function percentageFromLocation(loc) {
  11843. if (!loc || !this.total) {
  11844. return 0;
  11845. }
  11846. return loc / this.total;
  11847. }
  11848. /**
  11849. * Get an EpubCFI from location index
  11850. * @param {number} loc
  11851. * @return {EpubCFI} cfi
  11852. */
  11853. }, {
  11854. key: "cfiFromLocation",
  11855. value: function cfiFromLocation(loc) {
  11856. var cfi = -1;
  11857. // check that pg is an int
  11858. if (typeof loc != "number") {
  11859. loc = parseInt(loc);
  11860. }
  11861. if (loc >= 0 && loc < this._locations.length) {
  11862. cfi = this._locations[loc];
  11863. }
  11864. return cfi;
  11865. }
  11866. /**
  11867. * Get an EpubCFI from location percentage
  11868. * @param {number} percentage
  11869. * @return {EpubCFI} cfi
  11870. */
  11871. }, {
  11872. key: "cfiFromPercentage",
  11873. value: function cfiFromPercentage(percentage) {
  11874. var loc = void 0;
  11875. if (percentage > 1) {
  11876. console.warn("Normalize cfiFromPercentage value to between 0 - 1");
  11877. }
  11878. // Make sure 1 goes to very end
  11879. if (percentage >= 1) {
  11880. var cfi = new _epubcfi2.default(this._locations[this.total]);
  11881. cfi.collapse();
  11882. return cfi.toString();
  11883. }
  11884. loc = Math.ceil(this.total * percentage);
  11885. return this.cfiFromLocation(loc);
  11886. }
  11887. /**
  11888. * Load locations from JSON
  11889. * @param {json} locations
  11890. */
  11891. }, {
  11892. key: "load",
  11893. value: function load(locations) {
  11894. if (typeof locations === "string") {
  11895. this._locations = JSON.parse(locations);
  11896. } else {
  11897. this._locations = locations;
  11898. }
  11899. this.total = this._locations.length - 1;
  11900. return this._locations;
  11901. }
  11902. /**
  11903. * Save locations to JSON
  11904. * @return {json}
  11905. */
  11906. }, {
  11907. key: "save",
  11908. value: function save() {
  11909. return JSON.stringify(this._locations);
  11910. }
  11911. }, {
  11912. key: "getCurrent",
  11913. value: function getCurrent() {
  11914. return this._current;
  11915. }
  11916. }, {
  11917. key: "setCurrent",
  11918. value: function setCurrent(curr) {
  11919. var loc;
  11920. if (typeof curr == "string") {
  11921. this._currentCfi = curr;
  11922. } else if (typeof curr == "number") {
  11923. this._current = curr;
  11924. } else {
  11925. return;
  11926. }
  11927. if (this._locations.length === 0) {
  11928. return;
  11929. }
  11930. if (typeof curr == "string") {
  11931. loc = this.locationFromCfi(curr);
  11932. this._current = loc;
  11933. } else {
  11934. loc = curr;
  11935. }
  11936. this.emit(_constants.EVENTS.LOCATIONS.CHANGED, {
  11937. percentage: this.percentageFromLocation(loc)
  11938. });
  11939. }
  11940. /**
  11941. * Get the current location
  11942. */
  11943. }, {
  11944. key: "length",
  11945. /**
  11946. * Locations length
  11947. */
  11948. value: function length() {
  11949. return this._locations.length;
  11950. }
  11951. }, {
  11952. key: "destroy",
  11953. value: function destroy() {
  11954. this.spine = undefined;
  11955. this.request = undefined;
  11956. this.pause = undefined;
  11957. this.q.stop();
  11958. this.q = undefined;
  11959. this.epubcfi = undefined;
  11960. this._locations = undefined;
  11961. this.total = undefined;
  11962. this.break = undefined;
  11963. this._current = undefined;
  11964. this.currentLocation = undefined;
  11965. this._currentCfi = undefined;
  11966. clearTimeout(this.processingTimeout);
  11967. }
  11968. }, {
  11969. key: "currentLocation",
  11970. get: function get() {
  11971. return this._current;
  11972. }
  11973. /**
  11974. * Set the current location
  11975. */
  11976. ,
  11977. set: function set(curr) {
  11978. this.setCurrent(curr);
  11979. }
  11980. }]);
  11981. return Locations;
  11982. }();
  11983. (0, _eventEmitter2.default)(Locations.prototype);
  11984. exports.default = Locations;
  11985. module.exports = exports["default"];
  11986. /***/ }),
  11987. /* 48 */
  11988. /***/ (function(module, exports, __webpack_require__) {
  11989. "use strict";
  11990. Object.defineProperty(exports, "__esModule", {
  11991. value: true
  11992. });
  11993. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  11994. var _pathWebpack = __webpack_require__(6);
  11995. var _pathWebpack2 = _interopRequireDefault(_pathWebpack);
  11996. var _core = __webpack_require__(0);
  11997. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11998. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11999. /**
  12000. * Handles Parsing and Accessing an Epub Container
  12001. * @class
  12002. * @param {document} [containerDocument] xml document
  12003. */
  12004. var Container = function () {
  12005. function Container(containerDocument) {
  12006. _classCallCheck(this, Container);
  12007. this.packagePath = '';
  12008. this.directory = '';
  12009. this.encoding = '';
  12010. if (containerDocument) {
  12011. this.parse(containerDocument);
  12012. }
  12013. }
  12014. /**
  12015. * Parse the Container XML
  12016. * @param {document} containerDocument
  12017. */
  12018. _createClass(Container, [{
  12019. key: "parse",
  12020. value: function parse(containerDocument) {
  12021. //-- <rootfile full-path="OPS/package.opf" media-type="application/oebps-package+xml"/>
  12022. var rootfile;
  12023. if (!containerDocument) {
  12024. throw new Error("Container File Not Found");
  12025. }
  12026. rootfile = (0, _core.qs)(containerDocument, "rootfile");
  12027. if (!rootfile) {
  12028. throw new Error("No RootFile Found");
  12029. }
  12030. this.packagePath = rootfile.getAttribute("full-path");
  12031. this.directory = _pathWebpack2.default.dirname(this.packagePath);
  12032. this.encoding = containerDocument.xmlEncoding;
  12033. }
  12034. }, {
  12035. key: "destroy",
  12036. value: function destroy() {
  12037. this.packagePath = undefined;
  12038. this.directory = undefined;
  12039. this.encoding = undefined;
  12040. }
  12041. }]);
  12042. return Container;
  12043. }();
  12044. exports.default = Container;
  12045. module.exports = exports["default"];
  12046. /***/ }),
  12047. /* 49 */
  12048. /***/ (function(module, exports, __webpack_require__) {
  12049. "use strict";
  12050. Object.defineProperty(exports, "__esModule", {
  12051. value: true
  12052. });
  12053. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  12054. var _core = __webpack_require__(0);
  12055. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12056. /**
  12057. * Open Packaging Format Parser
  12058. * @class
  12059. * @param {document} packageDocument OPF XML
  12060. */
  12061. var Packaging = function () {
  12062. function Packaging(packageDocument) {
  12063. _classCallCheck(this, Packaging);
  12064. this.manifest = {};
  12065. this.navPath = '';
  12066. this.ncxPath = '';
  12067. this.coverPath = '';
  12068. this.spineNodeIndex = 0;
  12069. this.spine = [];
  12070. this.metadata = {};
  12071. if (packageDocument) {
  12072. this.parse(packageDocument);
  12073. }
  12074. }
  12075. /**
  12076. * Parse OPF XML
  12077. * @param {document} packageDocument OPF XML
  12078. * @return {object} parsed package parts
  12079. */
  12080. _createClass(Packaging, [{
  12081. key: 'parse',
  12082. value: function parse(packageDocument) {
  12083. var metadataNode, manifestNode, spineNode;
  12084. if (!packageDocument) {
  12085. throw new Error("Package File Not Found");
  12086. }
  12087. metadataNode = (0, _core.qs)(packageDocument, "metadata");
  12088. if (!metadataNode) {
  12089. throw new Error("No Metadata Found");
  12090. }
  12091. manifestNode = (0, _core.qs)(packageDocument, "manifest");
  12092. if (!manifestNode) {
  12093. throw new Error("No Manifest Found");
  12094. }
  12095. spineNode = (0, _core.qs)(packageDocument, "spine");
  12096. if (!spineNode) {
  12097. throw new Error("No Spine Found");
  12098. }
  12099. this.manifest = this.parseManifest(manifestNode);
  12100. this.navPath = this.findNavPath(manifestNode);
  12101. this.ncxPath = this.findNcxPath(manifestNode, spineNode);
  12102. this.coverPath = this.findCoverPath(packageDocument);
  12103. this.spineNodeIndex = (0, _core.indexOfElementNode)(spineNode);
  12104. this.spine = this.parseSpine(spineNode, this.manifest);
  12105. this.uniqueIdentifier = this.findUniqueIdentifier(packageDocument);
  12106. this.metadata = this.parseMetadata(metadataNode);
  12107. this.metadata.direction = spineNode.getAttribute("page-progression-direction");
  12108. return {
  12109. "metadata": this.metadata,
  12110. "spine": this.spine,
  12111. "manifest": this.manifest,
  12112. "navPath": this.navPath,
  12113. "ncxPath": this.ncxPath,
  12114. "coverPath": this.coverPath,
  12115. "spineNodeIndex": this.spineNodeIndex
  12116. };
  12117. }
  12118. /**
  12119. * Parse Metadata
  12120. * @private
  12121. * @param {node} xml
  12122. * @return {object} metadata
  12123. */
  12124. }, {
  12125. key: 'parseMetadata',
  12126. value: function parseMetadata(xml) {
  12127. var metadata = {};
  12128. metadata.title = this.getElementText(xml, "title");
  12129. metadata.creator = this.getElementText(xml, "creator");
  12130. metadata.description = this.getElementText(xml, "description");
  12131. metadata.pubdate = this.getElementText(xml, "date");
  12132. metadata.publisher = this.getElementText(xml, "publisher");
  12133. metadata.identifier = this.getElementText(xml, "identifier");
  12134. metadata.language = this.getElementText(xml, "language");
  12135. metadata.rights = this.getElementText(xml, "rights");
  12136. metadata.modified_date = this.getPropertyText(xml, "dcterms:modified");
  12137. metadata.layout = this.getPropertyText(xml, "rendition:layout");
  12138. metadata.orientation = this.getPropertyText(xml, "rendition:orientation");
  12139. metadata.flow = this.getPropertyText(xml, "rendition:flow");
  12140. metadata.viewport = this.getPropertyText(xml, "rendition:viewport");
  12141. metadata.media_active_class = this.getPropertyText(xml, "media:active-class");
  12142. // metadata.page_prog_dir = packageXml.querySelector("spine").getAttribute("page-progression-direction");
  12143. return metadata;
  12144. }
  12145. /**
  12146. * Parse Manifest
  12147. * @private
  12148. * @param {node} manifestXml
  12149. * @return {object} manifest
  12150. */
  12151. }, {
  12152. key: 'parseManifest',
  12153. value: function parseManifest(manifestXml) {
  12154. var manifest = {};
  12155. //-- Turn items into an array
  12156. // var selected = manifestXml.querySelectorAll("item");
  12157. var selected = (0, _core.qsa)(manifestXml, "item");
  12158. var items = Array.prototype.slice.call(selected);
  12159. //-- Create an object with the id as key
  12160. items.forEach(function (item) {
  12161. var id = item.getAttribute("id"),
  12162. href = item.getAttribute("href") || "",
  12163. type = item.getAttribute("media-type") || "",
  12164. overlay = item.getAttribute("media-overlay") || "",
  12165. properties = item.getAttribute("properties") || "";
  12166. manifest[id] = {
  12167. "href": href,
  12168. // "url" : href,
  12169. "type": type,
  12170. "overlay": overlay,
  12171. "properties": properties.length ? properties.split(" ") : []
  12172. };
  12173. });
  12174. return manifest;
  12175. }
  12176. /**
  12177. * Parse Spine
  12178. * @private
  12179. * @param {node} spineXml
  12180. * @param {Packaging.manifest} manifest
  12181. * @return {object} spine
  12182. */
  12183. }, {
  12184. key: 'parseSpine',
  12185. value: function parseSpine(spineXml, manifest) {
  12186. var spine = [];
  12187. var selected = (0, _core.qsa)(spineXml, "itemref");
  12188. var items = Array.prototype.slice.call(selected);
  12189. // var epubcfi = new EpubCFI();
  12190. //-- Add to array to mantain ordering and cross reference with manifest
  12191. items.forEach(function (item, index) {
  12192. var idref = item.getAttribute("idref");
  12193. // var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id);
  12194. var props = item.getAttribute("properties") || "";
  12195. var propArray = props.length ? props.split(" ") : [];
  12196. // var manifestProps = manifest[Id].properties;
  12197. // var manifestPropArray = manifestProps.length ? manifestProps.split(" ") : [];
  12198. var itemref = {
  12199. "idref": idref,
  12200. "linear": item.getAttribute("linear") || "yes",
  12201. "properties": propArray,
  12202. // "href" : manifest[Id].href,
  12203. // "url" : manifest[Id].url,
  12204. "index": index
  12205. // "cfiBase" : cfiBase
  12206. };
  12207. spine.push(itemref);
  12208. });
  12209. return spine;
  12210. }
  12211. /**
  12212. * Find Unique Identifier
  12213. * @private
  12214. * @param {node} packageXml
  12215. * @return {string} Unique Identifier text
  12216. */
  12217. }, {
  12218. key: 'findUniqueIdentifier',
  12219. value: function findUniqueIdentifier(packageXml) {
  12220. var uniqueIdentifierId = packageXml.documentElement.getAttribute("unique-identifier");
  12221. if (!uniqueIdentifierId) {
  12222. return "";
  12223. }
  12224. var identifier = packageXml.getElementById(uniqueIdentifierId);
  12225. if (!identifier) {
  12226. return "";
  12227. }
  12228. if (identifier.localName === "identifier" && identifier.namespaceURI === "http://purl.org/dc/elements/1.1/") {
  12229. return identifier.childNodes[0].nodeValue.trim();
  12230. }
  12231. return "";
  12232. }
  12233. /**
  12234. * Find TOC NAV
  12235. * @private
  12236. * @param {element} manifestNode
  12237. * @return {string}
  12238. */
  12239. }, {
  12240. key: 'findNavPath',
  12241. value: function findNavPath(manifestNode) {
  12242. // Find item with property "nav"
  12243. // Should catch nav irregardless of order
  12244. // var node = manifestNode.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']");
  12245. var node = (0, _core.qsp)(manifestNode, "item", { "properties": "nav" });
  12246. return node ? node.getAttribute("href") : false;
  12247. }
  12248. /**
  12249. * Find TOC NCX
  12250. * media-type="application/x-dtbncx+xml" href="toc.ncx"
  12251. * @private
  12252. * @param {element} manifestNode
  12253. * @param {element} spineNode
  12254. * @return {string}
  12255. */
  12256. }, {
  12257. key: 'findNcxPath',
  12258. value: function findNcxPath(manifestNode, spineNode) {
  12259. // var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']");
  12260. var node = (0, _core.qsp)(manifestNode, "item", { "media-type": "application/x-dtbncx+xml" });
  12261. var tocId;
  12262. // If we can't find the toc by media-type then try to look for id of the item in the spine attributes as
  12263. // according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2,
  12264. // "The item that describes the NCX must be referenced by the spine toc attribute."
  12265. if (!node) {
  12266. tocId = spineNode.getAttribute("toc");
  12267. if (tocId) {
  12268. // node = manifestNode.querySelector("item[id='" + tocId + "']");
  12269. node = manifestNode.querySelector('#' + tocId);
  12270. }
  12271. }
  12272. return node ? node.getAttribute("href") : false;
  12273. }
  12274. /**
  12275. * Find the Cover Path
  12276. * <item properties="cover-image" id="ci" href="cover.svg" media-type="image/svg+xml" />
  12277. * Fallback for Epub 2.0
  12278. * @private
  12279. * @param {node} packageXml
  12280. * @return {string} href
  12281. */
  12282. }, {
  12283. key: 'findCoverPath',
  12284. value: function findCoverPath(packageXml) {
  12285. var pkg = (0, _core.qs)(packageXml, "package");
  12286. var epubVersion = pkg.getAttribute("version");
  12287. if (epubVersion === "2.0") {
  12288. var metaCover = (0, _core.qsp)(packageXml, "meta", { "name": "cover" });
  12289. if (metaCover) {
  12290. var coverId = metaCover.getAttribute("content");
  12291. // var cover = packageXml.querySelector("item[id='" + coverId + "']");
  12292. var cover = packageXml.getElementById(coverId);
  12293. return cover ? cover.getAttribute("href") : "";
  12294. } else {
  12295. return false;
  12296. }
  12297. } else {
  12298. // var node = packageXml.querySelector("item[properties='cover-image']");
  12299. var node = (0, _core.qsp)(packageXml, "item", { "properties": "cover-image" });
  12300. return node ? node.getAttribute("href") : "";
  12301. }
  12302. }
  12303. /**
  12304. * Get text of a namespaced element
  12305. * @private
  12306. * @param {node} xml
  12307. * @param {string} tag
  12308. * @return {string} text
  12309. */
  12310. }, {
  12311. key: 'getElementText',
  12312. value: function getElementText(xml, tag) {
  12313. var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag);
  12314. var el;
  12315. if (!found || found.length === 0) return "";
  12316. el = found[0];
  12317. if (el.childNodes.length) {
  12318. return el.childNodes[0].nodeValue;
  12319. }
  12320. return "";
  12321. }
  12322. /**
  12323. * Get text by property
  12324. * @private
  12325. * @param {node} xml
  12326. * @param {string} property
  12327. * @return {string} text
  12328. */
  12329. }, {
  12330. key: 'getPropertyText',
  12331. value: function getPropertyText(xml, property) {
  12332. var el = (0, _core.qsp)(xml, "meta", { "property": property });
  12333. if (el && el.childNodes.length) {
  12334. return el.childNodes[0].nodeValue;
  12335. }
  12336. return "";
  12337. }
  12338. /**
  12339. * Load JSON Manifest
  12340. * @param {document} packageDocument OPF XML
  12341. * @return {object} parsed package parts
  12342. */
  12343. }, {
  12344. key: 'load',
  12345. value: function load(json) {
  12346. var _this = this;
  12347. this.metadata = json.metadata;
  12348. var spine = json.readingOrder || json.spine;
  12349. this.spine = spine.map(function (item, index) {
  12350. item.index = index;
  12351. return item;
  12352. });
  12353. json.resources.forEach(function (item, index) {
  12354. _this.manifest[index] = item;
  12355. if (item.rel && item.rel[0] === "cover") {
  12356. _this.coverPath = item.href;
  12357. }
  12358. });
  12359. this.spineNodeIndex = 0;
  12360. this.toc = json.toc.map(function (item, index) {
  12361. item.label = item.title;
  12362. return item;
  12363. });
  12364. return {
  12365. "metadata": this.metadata,
  12366. "spine": this.spine,
  12367. "manifest": this.manifest,
  12368. "navPath": this.navPath,
  12369. "ncxPath": this.ncxPath,
  12370. "coverPath": this.coverPath,
  12371. "spineNodeIndex": this.spineNodeIndex,
  12372. "toc": this.toc
  12373. };
  12374. }
  12375. }, {
  12376. key: 'destroy',
  12377. value: function destroy() {
  12378. this.manifest = undefined;
  12379. this.navPath = undefined;
  12380. this.ncxPath = undefined;
  12381. this.coverPath = undefined;
  12382. this.spineNodeIndex = undefined;
  12383. this.spine = undefined;
  12384. this.metadata = undefined;
  12385. }
  12386. }]);
  12387. return Packaging;
  12388. }();
  12389. exports.default = Packaging;
  12390. module.exports = exports['default'];
  12391. /***/ }),
  12392. /* 50 */
  12393. /***/ (function(module, exports, __webpack_require__) {
  12394. "use strict";
  12395. Object.defineProperty(exports, "__esModule", {
  12396. value: true
  12397. });
  12398. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  12399. var _core = __webpack_require__(0);
  12400. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12401. /**
  12402. * Navigation Parser
  12403. * @param {document} xml navigation html / xhtml / ncx
  12404. */
  12405. var Navigation = function () {
  12406. function Navigation(xml) {
  12407. _classCallCheck(this, Navigation);
  12408. this.toc = [];
  12409. this.tocByHref = {};
  12410. this.tocById = {};
  12411. this.landmarks = [];
  12412. this.landmarksByType = {};
  12413. this.length = 0;
  12414. if (xml) {
  12415. this.parse(xml);
  12416. }
  12417. }
  12418. /**
  12419. * Parse out the navigation items
  12420. * @param {document} xml navigation html / xhtml / ncx
  12421. */
  12422. _createClass(Navigation, [{
  12423. key: "parse",
  12424. value: function parse(xml) {
  12425. var isXml = xml.nodeType;
  12426. var html = void 0;
  12427. var ncx = void 0;
  12428. if (isXml) {
  12429. html = (0, _core.qs)(xml, "html");
  12430. ncx = (0, _core.qs)(xml, "ncx");
  12431. }
  12432. if (!isXml) {
  12433. this.toc = this.load(xml);
  12434. } else if (html) {
  12435. this.toc = this.parseNav(xml);
  12436. this.landmarks = this.parseLandmarks(xml);
  12437. } else if (ncx) {
  12438. this.toc = this.parseNcx(xml);
  12439. }
  12440. this.length = 0;
  12441. this.unpack(this.toc);
  12442. }
  12443. /**
  12444. * Unpack navigation items
  12445. * @private
  12446. * @param {array} toc
  12447. */
  12448. }, {
  12449. key: "unpack",
  12450. value: function unpack(toc) {
  12451. var item;
  12452. for (var i = 0; i < toc.length; i++) {
  12453. item = toc[i];
  12454. if (item.href) {
  12455. this.tocByHref[item.href] = i;
  12456. }
  12457. if (item.id) {
  12458. this.tocById[item.id] = i;
  12459. }
  12460. this.length++;
  12461. if (item.subitems.length) {
  12462. this.unpack(item.subitems);
  12463. }
  12464. }
  12465. }
  12466. /**
  12467. * Get an item from the navigation
  12468. * @param {string} target
  12469. * @return {object} navItem
  12470. */
  12471. }, {
  12472. key: "get",
  12473. value: function get(target) {
  12474. var index;
  12475. if (!target) {
  12476. return this.toc;
  12477. }
  12478. if (target.indexOf("#") === 0) {
  12479. index = this.tocById[target.substring(1)];
  12480. } else if (target in this.tocByHref) {
  12481. index = this.tocByHref[target];
  12482. }
  12483. return this.toc[index];
  12484. }
  12485. /**
  12486. * Get a landmark by type
  12487. * List of types: https://idpf.github.io/epub-vocabs/structure/
  12488. * @param {string} type
  12489. * @return {object} landmarkItem
  12490. */
  12491. }, {
  12492. key: "landmark",
  12493. value: function landmark(type) {
  12494. var index;
  12495. if (!type) {
  12496. return this.landmarks;
  12497. }
  12498. index = this.landmarksByType[type];
  12499. return this.landmarks[index];
  12500. }
  12501. /**
  12502. * Parse toc from a Epub > 3.0 Nav
  12503. * @private
  12504. * @param {document} navHtml
  12505. * @return {array} navigation list
  12506. */
  12507. }, {
  12508. key: "parseNav",
  12509. value: function parseNav(navHtml) {
  12510. var navElement = (0, _core.querySelectorByType)(navHtml, "nav", "toc");
  12511. var navItems = navElement ? (0, _core.qsa)(navElement, "li") : [];
  12512. var length = navItems.length;
  12513. var i;
  12514. var toc = {};
  12515. var list = [];
  12516. var item, parent;
  12517. if (!navItems || length === 0) return list;
  12518. for (i = 0; i < length; ++i) {
  12519. item = this.navItem(navItems[i]);
  12520. if (item) {
  12521. toc[item.id] = item;
  12522. if (!item.parent) {
  12523. list.push(item);
  12524. } else {
  12525. parent = toc[item.parent];
  12526. parent.subitems.push(item);
  12527. }
  12528. }
  12529. }
  12530. return list;
  12531. }
  12532. /**
  12533. * Create a navItem
  12534. * @private
  12535. * @param {element} item
  12536. * @return {object} navItem
  12537. */
  12538. }, {
  12539. key: "navItem",
  12540. value: function navItem(item) {
  12541. var id = item.getAttribute("id") || undefined;
  12542. var content = (0, _core.filterChildren)(item, "a", true);
  12543. if (!content) {
  12544. return;
  12545. }
  12546. var src = content.getAttribute("href") || "";
  12547. if (!id) {
  12548. id = src;
  12549. }
  12550. var text = content.textContent || "";
  12551. var subitems = [];
  12552. var parentItem = (0, _core.getParentByTagName)(item, "li");
  12553. var parent = void 0;
  12554. if (parentItem) {
  12555. parent = parentItem.getAttribute("id");
  12556. if (!parent) {
  12557. var parentContent = (0, _core.filterChildren)(parentItem, "a", true);
  12558. parent = parentContent && parentContent.getAttribute("href");
  12559. }
  12560. }
  12561. while (!parent && parentItem) {
  12562. parentItem = (0, _core.getParentByTagName)(parentItem, "li");
  12563. if (parentItem) {
  12564. parent = parentItem.getAttribute("id");
  12565. if (!parent) {
  12566. var _parentContent = (0, _core.filterChildren)(parentItem, "a", true);
  12567. parent = _parentContent && _parentContent.getAttribute("href");
  12568. }
  12569. }
  12570. }
  12571. return {
  12572. "id": id,
  12573. "href": src,
  12574. "label": text,
  12575. "subitems": subitems,
  12576. "parent": parent
  12577. };
  12578. }
  12579. /**
  12580. * Parse landmarks from a Epub > 3.0 Nav
  12581. * @private
  12582. * @param {document} navHtml
  12583. * @return {array} landmarks list
  12584. */
  12585. }, {
  12586. key: "parseLandmarks",
  12587. value: function parseLandmarks(navHtml) {
  12588. var navElement = (0, _core.querySelectorByType)(navHtml, "nav", "landmarks");
  12589. var navItems = navElement ? (0, _core.qsa)(navElement, "li") : [];
  12590. var length = navItems.length;
  12591. var i;
  12592. var list = [];
  12593. var item;
  12594. if (!navItems || length === 0) return list;
  12595. for (i = 0; i < length; ++i) {
  12596. item = this.landmarkItem(navItems[i]);
  12597. if (item) {
  12598. list.push(item);
  12599. this.landmarksByType[item.type] = i;
  12600. }
  12601. }
  12602. return list;
  12603. }
  12604. /**
  12605. * Create a landmarkItem
  12606. * @private
  12607. * @param {element} item
  12608. * @return {object} landmarkItem
  12609. */
  12610. }, {
  12611. key: "landmarkItem",
  12612. value: function landmarkItem(item) {
  12613. var content = (0, _core.filterChildren)(item, "a", true);
  12614. if (!content) {
  12615. return;
  12616. }
  12617. var type = content.getAttributeNS("http://www.idpf.org/2007/ops", "type") || undefined;
  12618. var href = content.getAttribute("href") || "";
  12619. var text = content.textContent || "";
  12620. return {
  12621. "href": href,
  12622. "label": text,
  12623. "type": type
  12624. };
  12625. }
  12626. /**
  12627. * Parse from a Epub > 3.0 NC
  12628. * @private
  12629. * @param {document} navHtml
  12630. * @return {array} navigation list
  12631. */
  12632. }, {
  12633. key: "parseNcx",
  12634. value: function parseNcx(tocXml) {
  12635. var navPoints = (0, _core.qsa)(tocXml, "navPoint");
  12636. var length = navPoints.length;
  12637. var i;
  12638. var toc = {};
  12639. var list = [];
  12640. var item, parent;
  12641. if (!navPoints || length === 0) return list;
  12642. for (i = 0; i < length; ++i) {
  12643. item = this.ncxItem(navPoints[i]);
  12644. toc[item.id] = item;
  12645. if (!item.parent) {
  12646. list.push(item);
  12647. } else {
  12648. parent = toc[item.parent];
  12649. parent.subitems.push(item);
  12650. }
  12651. }
  12652. return list;
  12653. }
  12654. /**
  12655. * Create a ncxItem
  12656. * @private
  12657. * @param {element} item
  12658. * @return {object} ncxItem
  12659. */
  12660. }, {
  12661. key: "ncxItem",
  12662. value: function ncxItem(item) {
  12663. var id = item.getAttribute("id") || false,
  12664. content = (0, _core.qs)(item, "content"),
  12665. src = content.getAttribute("src"),
  12666. navLabel = (0, _core.qs)(item, "navLabel"),
  12667. text = navLabel.textContent ? navLabel.textContent : "",
  12668. subitems = [],
  12669. parentNode = item.parentNode,
  12670. parent;
  12671. if (parentNode && parentNode.nodeName === "navPoint") {
  12672. parent = parentNode.getAttribute("id");
  12673. }
  12674. return {
  12675. "id": id,
  12676. "href": src,
  12677. "label": text,
  12678. "subitems": subitems,
  12679. "parent": parent
  12680. };
  12681. }
  12682. /**
  12683. * Load Spine Items
  12684. * @param {object} json the items to be loaded
  12685. * @return {Array} navItems
  12686. */
  12687. }, {
  12688. key: "load",
  12689. value: function load(json) {
  12690. var _this = this;
  12691. return json.map(function (item) {
  12692. item.label = item.title;
  12693. item.subitems = item.children ? _this.load(item.children) : [];
  12694. return item;
  12695. });
  12696. }
  12697. /**
  12698. * forEach pass through
  12699. * @param {Function} fn function to run on each item
  12700. * @return {method} forEach loop
  12701. */
  12702. }, {
  12703. key: "forEach",
  12704. value: function forEach(fn) {
  12705. return this.toc.forEach(fn);
  12706. }
  12707. }]);
  12708. return Navigation;
  12709. }();
  12710. exports.default = Navigation;
  12711. module.exports = exports["default"];
  12712. /***/ }),
  12713. /* 51 */
  12714. /***/ (function(module, exports, __webpack_require__) {
  12715. "use strict";
  12716. Object.defineProperty(exports, "__esModule", {
  12717. value: true
  12718. });
  12719. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  12720. var _replacements = __webpack_require__(7);
  12721. var _core = __webpack_require__(0);
  12722. var _url = __webpack_require__(5);
  12723. var _url2 = _interopRequireDefault(_url);
  12724. var _mime = __webpack_require__(17);
  12725. var _mime2 = _interopRequireDefault(_mime);
  12726. var _path = __webpack_require__(4);
  12727. var _path2 = _interopRequireDefault(_path);
  12728. var _pathWebpack = __webpack_require__(6);
  12729. var _pathWebpack2 = _interopRequireDefault(_pathWebpack);
  12730. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12731. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12732. /**
  12733. * Handle Package Resources
  12734. * @class
  12735. * @param {Manifest} manifest
  12736. * @param {object} [options]
  12737. * @param {string} [options.replacements="base64"]
  12738. * @param {Archive} [options.archive]
  12739. * @param {method} [options.resolver]
  12740. */
  12741. var Resources = function () {
  12742. function Resources(manifest, options) {
  12743. _classCallCheck(this, Resources);
  12744. this.settings = {
  12745. replacements: options && options.replacements || "base64",
  12746. archive: options && options.archive,
  12747. resolver: options && options.resolver,
  12748. request: options && options.request
  12749. };
  12750. this.manifest = manifest;
  12751. this.resources = Object.keys(manifest).map(function (key) {
  12752. return manifest[key];
  12753. });
  12754. this.replacementUrls = [];
  12755. this.html = [];
  12756. this.assets = [];
  12757. this.css = [];
  12758. this.urls = [];
  12759. this.cssUrls = [];
  12760. this.split();
  12761. this.splitUrls();
  12762. }
  12763. /**
  12764. * Split resources by type
  12765. * @private
  12766. */
  12767. _createClass(Resources, [{
  12768. key: "split",
  12769. value: function split() {
  12770. // HTML
  12771. this.html = this.resources.filter(function (item) {
  12772. if (item.type === "application/xhtml+xml" || item.type === "text/html") {
  12773. return true;
  12774. }
  12775. });
  12776. // Exclude HTML
  12777. this.assets = this.resources.filter(function (item) {
  12778. if (item.type !== "application/xhtml+xml" && item.type !== "text/html") {
  12779. return true;
  12780. }
  12781. });
  12782. // Only CSS
  12783. this.css = this.resources.filter(function (item) {
  12784. if (item.type === "text/css") {
  12785. return true;
  12786. }
  12787. });
  12788. }
  12789. /**
  12790. * Convert split resources into Urls
  12791. * @private
  12792. */
  12793. }, {
  12794. key: "splitUrls",
  12795. value: function splitUrls() {
  12796. // All Assets Urls
  12797. this.urls = this.assets.map(function (item) {
  12798. return item.href;
  12799. }.bind(this));
  12800. // Css Urls
  12801. this.cssUrls = this.css.map(function (item) {
  12802. return item.href;
  12803. });
  12804. }
  12805. /**
  12806. * Create a url to a resource
  12807. * @param {string} url
  12808. * @return {Promise<string>} Promise resolves with url string
  12809. */
  12810. }, {
  12811. key: "createUrl",
  12812. value: function createUrl(url) {
  12813. var parsedUrl = new _url2.default(url);
  12814. var mimeType = _mime2.default.lookup(parsedUrl.filename);
  12815. if (this.settings.archive) {
  12816. return this.settings.archive.createUrl(url, { "base64": this.settings.replacements === "base64" });
  12817. } else {
  12818. if (this.settings.replacements === "base64") {
  12819. return this.settings.request(url, 'blob').then(function (blob) {
  12820. return (0, _core.blob2base64)(blob);
  12821. }).then(function (blob) {
  12822. return (0, _core.createBase64Url)(blob, mimeType);
  12823. });
  12824. } else {
  12825. return this.settings.request(url, 'blob').then(function (blob) {
  12826. return (0, _core.createBlobUrl)(blob, mimeType);
  12827. });
  12828. }
  12829. }
  12830. }
  12831. /**
  12832. * Create blob urls for all the assets
  12833. * @return {Promise} returns replacement urls
  12834. */
  12835. }, {
  12836. key: "replacements",
  12837. value: function replacements() {
  12838. var _this = this;
  12839. if (this.settings.replacements === "none") {
  12840. return new Promise(function (resolve) {
  12841. resolve(this.urls);
  12842. }.bind(this));
  12843. }
  12844. var replacements = this.urls.map(function (url) {
  12845. var absolute = _this.settings.resolver(url);
  12846. return _this.createUrl(absolute).catch(function (err) {
  12847. console.error(err);
  12848. return null;
  12849. });
  12850. });
  12851. return Promise.all(replacements).then(function (replacementUrls) {
  12852. _this.replacementUrls = replacementUrls.filter(function (url) {
  12853. return typeof url === "string";
  12854. });
  12855. return replacementUrls;
  12856. });
  12857. }
  12858. /**
  12859. * Replace URLs in CSS resources
  12860. * @private
  12861. * @param {Archive} [archive]
  12862. * @param {method} [resolver]
  12863. * @return {Promise}
  12864. */
  12865. }, {
  12866. key: "replaceCss",
  12867. value: function replaceCss(archive, resolver) {
  12868. var replaced = [];
  12869. archive = archive || this.settings.archive;
  12870. resolver = resolver || this.settings.resolver;
  12871. this.cssUrls.forEach(function (href) {
  12872. var replacement = this.createCssFile(href, archive, resolver).then(function (replacementUrl) {
  12873. // switch the url in the replacementUrls
  12874. var indexInUrls = this.urls.indexOf(href);
  12875. if (indexInUrls > -1) {
  12876. this.replacementUrls[indexInUrls] = replacementUrl;
  12877. }
  12878. }.bind(this));
  12879. replaced.push(replacement);
  12880. }.bind(this));
  12881. return Promise.all(replaced);
  12882. }
  12883. /**
  12884. * Create a new CSS file with the replaced URLs
  12885. * @private
  12886. * @param {string} href the original css file
  12887. * @return {Promise} returns a BlobUrl to the new CSS file or a data url
  12888. */
  12889. }, {
  12890. key: "createCssFile",
  12891. value: function createCssFile(href) {
  12892. var _this2 = this;
  12893. var newUrl;
  12894. if (_pathWebpack2.default.isAbsolute(href)) {
  12895. return new Promise(function (resolve) {
  12896. resolve();
  12897. });
  12898. }
  12899. var absolute = this.settings.resolver(href);
  12900. // Get the text of the css file from the archive
  12901. var textResponse;
  12902. if (this.settings.archive) {
  12903. textResponse = this.settings.archive.getText(absolute);
  12904. } else {
  12905. textResponse = this.settings.request(absolute, "text");
  12906. }
  12907. // Get asset links relative to css file
  12908. var relUrls = this.urls.map(function (assetHref) {
  12909. var resolved = _this2.settings.resolver(assetHref);
  12910. var relative = new _path2.default(absolute).relative(resolved);
  12911. return relative;
  12912. });
  12913. if (!textResponse) {
  12914. // file not found, don't replace
  12915. return new Promise(function (resolve) {
  12916. resolve();
  12917. });
  12918. }
  12919. return textResponse.then(function (text) {
  12920. // Replacements in the css text
  12921. text = (0, _replacements.substitute)(text, relUrls, _this2.replacementUrls);
  12922. // Get the new url
  12923. if (_this2.settings.replacements === "base64") {
  12924. newUrl = (0, _core.createBase64Url)(text, "text/css");
  12925. } else {
  12926. newUrl = (0, _core.createBlobUrl)(text, "text/css");
  12927. }
  12928. return newUrl;
  12929. }, function (err) {
  12930. // handle response errors
  12931. return new Promise(function (resolve) {
  12932. resolve();
  12933. });
  12934. });
  12935. }
  12936. /**
  12937. * Resolve all resources URLs relative to an absolute URL
  12938. * @param {string} absolute to be resolved to
  12939. * @param {resolver} [resolver]
  12940. * @return {string[]} array with relative Urls
  12941. */
  12942. }, {
  12943. key: "relativeTo",
  12944. value: function relativeTo(absolute, resolver) {
  12945. resolver = resolver || this.settings.resolver;
  12946. // Get Urls relative to current sections
  12947. return this.urls.map(function (href) {
  12948. var resolved = resolver(href);
  12949. var relative = new _path2.default(absolute).relative(resolved);
  12950. return relative;
  12951. }.bind(this));
  12952. }
  12953. /**
  12954. * Get a URL for a resource
  12955. * @param {string} path
  12956. * @return {string} url
  12957. */
  12958. }, {
  12959. key: "get",
  12960. value: function get(path) {
  12961. var indexInUrls = this.urls.indexOf(path);
  12962. if (indexInUrls === -1) {
  12963. return;
  12964. }
  12965. if (this.replacementUrls.length) {
  12966. return new Promise(function (resolve, reject) {
  12967. resolve(this.replacementUrls[indexInUrls]);
  12968. }.bind(this));
  12969. } else {
  12970. return this.createUrl(path);
  12971. }
  12972. }
  12973. /**
  12974. * Substitute urls in content, with replacements,
  12975. * relative to a url if provided
  12976. * @param {string} content
  12977. * @param {string} [url] url to resolve to
  12978. * @return {string} content with urls substituted
  12979. */
  12980. }, {
  12981. key: "substitute",
  12982. value: function substitute(content, url) {
  12983. var relUrls;
  12984. if (url) {
  12985. relUrls = this.relativeTo(url);
  12986. } else {
  12987. relUrls = this.urls;
  12988. }
  12989. return (0, _replacements.substitute)(content, relUrls, this.replacementUrls);
  12990. }
  12991. }, {
  12992. key: "destroy",
  12993. value: function destroy() {
  12994. this.settings = undefined;
  12995. this.manifest = undefined;
  12996. this.resources = undefined;
  12997. this.replacementUrls = undefined;
  12998. this.html = undefined;
  12999. this.assets = undefined;
  13000. this.css = undefined;
  13001. this.urls = undefined;
  13002. this.cssUrls = undefined;
  13003. }
  13004. }]);
  13005. return Resources;
  13006. }();
  13007. exports.default = Resources;
  13008. module.exports = exports["default"];
  13009. /***/ }),
  13010. /* 52 */
  13011. /***/ (function(module, exports, __webpack_require__) {
  13012. "use strict";
  13013. Object.defineProperty(exports, "__esModule", {
  13014. value: true
  13015. });
  13016. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13017. var _epubcfi = __webpack_require__(1);
  13018. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  13019. var _core = __webpack_require__(0);
  13020. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13021. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13022. /**
  13023. * Page List Parser
  13024. * @param {document} [xml]
  13025. */
  13026. var PageList = function () {
  13027. function PageList(xml) {
  13028. _classCallCheck(this, PageList);
  13029. this.pages = [];
  13030. this.locations = [];
  13031. this.epubcfi = new _epubcfi2.default();
  13032. this.firstPage = 0;
  13033. this.lastPage = 0;
  13034. this.totalPages = 0;
  13035. this.toc = undefined;
  13036. this.ncx = undefined;
  13037. if (xml) {
  13038. this.pageList = this.parse(xml);
  13039. }
  13040. if (this.pageList && this.pageList.length) {
  13041. this.process(this.pageList);
  13042. }
  13043. }
  13044. /**
  13045. * Parse PageList Xml
  13046. * @param {document} xml
  13047. */
  13048. _createClass(PageList, [{
  13049. key: "parse",
  13050. value: function parse(xml) {
  13051. var html = (0, _core.qs)(xml, "html");
  13052. var ncx = (0, _core.qs)(xml, "ncx");
  13053. if (html) {
  13054. return this.parseNav(xml);
  13055. } else if (ncx) {
  13056. // Not supported
  13057. // return this.parseNcx(xml);
  13058. return;
  13059. }
  13060. }
  13061. /**
  13062. * Parse a Nav PageList
  13063. * @private
  13064. * @param {node} navHtml
  13065. * @return {PageList.item[]} list
  13066. */
  13067. }, {
  13068. key: "parseNav",
  13069. value: function parseNav(navHtml) {
  13070. var navElement = (0, _core.querySelectorByType)(navHtml, "nav", "page-list");
  13071. var navItems = navElement ? (0, _core.qsa)(navElement, "li") : [];
  13072. var length = navItems.length;
  13073. var i;
  13074. var list = [];
  13075. var item;
  13076. if (!navItems || length === 0) return list;
  13077. for (i = 0; i < length; ++i) {
  13078. item = this.item(navItems[i]);
  13079. list.push(item);
  13080. }
  13081. return list;
  13082. }
  13083. /**
  13084. * Page List Item
  13085. * @private
  13086. * @param {node} item
  13087. * @return {object} pageListItem
  13088. */
  13089. }, {
  13090. key: "item",
  13091. value: function item(_item) {
  13092. var content = (0, _core.qs)(_item, "a"),
  13093. href = content.getAttribute("href") || "",
  13094. text = content.textContent || "",
  13095. page = parseInt(text),
  13096. isCfi = href.indexOf("epubcfi"),
  13097. split,
  13098. packageUrl,
  13099. cfi;
  13100. if (isCfi != -1) {
  13101. split = href.split("#");
  13102. packageUrl = split[0];
  13103. cfi = split.length > 1 ? split[1] : false;
  13104. return {
  13105. "cfi": cfi,
  13106. "href": href,
  13107. "packageUrl": packageUrl,
  13108. "page": page
  13109. };
  13110. } else {
  13111. return {
  13112. "href": href,
  13113. "page": page
  13114. };
  13115. }
  13116. }
  13117. /**
  13118. * Process pageList items
  13119. * @private
  13120. * @param {array} pageList
  13121. */
  13122. }, {
  13123. key: "process",
  13124. value: function process(pageList) {
  13125. pageList.forEach(function (item) {
  13126. this.pages.push(item.page);
  13127. if (item.cfi) {
  13128. this.locations.push(item.cfi);
  13129. }
  13130. }, this);
  13131. this.firstPage = parseInt(this.pages[0]);
  13132. this.lastPage = parseInt(this.pages[this.pages.length - 1]);
  13133. this.totalPages = this.lastPage - this.firstPage;
  13134. }
  13135. /**
  13136. * Get a PageList result from a EpubCFI
  13137. * @param {string} cfi EpubCFI String
  13138. * @return {number} page
  13139. */
  13140. }, {
  13141. key: "pageFromCfi",
  13142. value: function pageFromCfi(cfi) {
  13143. var pg = -1;
  13144. // Check if the pageList has not been set yet
  13145. if (this.locations.length === 0) {
  13146. return -1;
  13147. }
  13148. // TODO: check if CFI is valid?
  13149. // check if the cfi is in the location list
  13150. // var index = this.locations.indexOf(cfi);
  13151. var index = (0, _core.indexOfSorted)(cfi, this.locations, this.epubcfi.compare);
  13152. if (index != -1) {
  13153. pg = this.pages[index];
  13154. } else {
  13155. // Otherwise add it to the list of locations
  13156. // Insert it in the correct position in the locations page
  13157. //index = EPUBJS.core.insert(cfi, this.locations, this.epubcfi.compare);
  13158. index = (0, _core.locationOf)(cfi, this.locations, this.epubcfi.compare);
  13159. // Get the page at the location just before the new one, or return the first
  13160. pg = index - 1 >= 0 ? this.pages[index - 1] : this.pages[0];
  13161. if (pg !== undefined) {
  13162. // Add the new page in so that the locations and page array match up
  13163. //this.pages.splice(index, 0, pg);
  13164. } else {
  13165. pg = -1;
  13166. }
  13167. }
  13168. return pg;
  13169. }
  13170. /**
  13171. * Get an EpubCFI from a Page List Item
  13172. * @param {string | number} pg
  13173. * @return {string} cfi
  13174. */
  13175. }, {
  13176. key: "cfiFromPage",
  13177. value: function cfiFromPage(pg) {
  13178. var cfi = -1;
  13179. // check that pg is an int
  13180. if (typeof pg != "number") {
  13181. pg = parseInt(pg);
  13182. }
  13183. // check if the cfi is in the page list
  13184. // Pages could be unsorted.
  13185. var index = this.pages.indexOf(pg);
  13186. if (index != -1) {
  13187. cfi = this.locations[index];
  13188. }
  13189. // TODO: handle pages not in the list
  13190. return cfi;
  13191. }
  13192. /**
  13193. * Get a Page from Book percentage
  13194. * @param {number} percent
  13195. * @return {number} page
  13196. */
  13197. }, {
  13198. key: "pageFromPercentage",
  13199. value: function pageFromPercentage(percent) {
  13200. var pg = Math.round(this.totalPages * percent);
  13201. return pg;
  13202. }
  13203. /**
  13204. * Returns a value between 0 - 1 corresponding to the location of a page
  13205. * @param {number} pg the page
  13206. * @return {number} percentage
  13207. */
  13208. }, {
  13209. key: "percentageFromPage",
  13210. value: function percentageFromPage(pg) {
  13211. var percentage = (pg - this.firstPage) / this.totalPages;
  13212. return Math.round(percentage * 1000) / 1000;
  13213. }
  13214. /**
  13215. * Returns a value between 0 - 1 corresponding to the location of a cfi
  13216. * @param {string} cfi EpubCFI String
  13217. * @return {number} percentage
  13218. */
  13219. }, {
  13220. key: "percentageFromCfi",
  13221. value: function percentageFromCfi(cfi) {
  13222. var pg = this.pageFromCfi(cfi);
  13223. var percentage = this.percentageFromPage(pg);
  13224. return percentage;
  13225. }
  13226. /**
  13227. * Destroy
  13228. */
  13229. }, {
  13230. key: "destroy",
  13231. value: function destroy() {
  13232. this.pages = undefined;
  13233. this.locations = undefined;
  13234. this.epubcfi = undefined;
  13235. this.pageList = undefined;
  13236. this.toc = undefined;
  13237. this.ncx = undefined;
  13238. }
  13239. }]);
  13240. return PageList;
  13241. }();
  13242. exports.default = PageList;
  13243. module.exports = exports["default"];
  13244. /***/ }),
  13245. /* 53 */
  13246. /***/ (function(module, exports, __webpack_require__) {
  13247. "use strict";
  13248. Object.defineProperty(exports, "__esModule", {
  13249. value: true
  13250. });
  13251. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13252. var _core = __webpack_require__(0);
  13253. var _constants = __webpack_require__(2);
  13254. var _eventEmitter = __webpack_require__(3);
  13255. var _eventEmitter2 = _interopRequireDefault(_eventEmitter);
  13256. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13257. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13258. /**
  13259. * Figures out the CSS values to apply for a layout
  13260. * @class
  13261. * @param {object} settings
  13262. * @param {string} [settings.layout='reflowable']
  13263. * @param {string} [settings.spread]
  13264. * @param {number} [settings.minSpreadWidth=800]
  13265. * @param {boolean} [settings.evenSpreads=false]
  13266. */
  13267. var Layout = function () {
  13268. function Layout(settings) {
  13269. _classCallCheck(this, Layout);
  13270. this.settings = settings;
  13271. this.name = settings.layout || "reflowable";
  13272. this._spread = settings.spread === "none" ? false : true;
  13273. this._minSpreadWidth = settings.minSpreadWidth || 800;
  13274. this._evenSpreads = settings.evenSpreads || false;
  13275. if (settings.flow === "scrolled" || settings.flow === "scrolled-continuous" || settings.flow === "scrolled-doc") {
  13276. this._flow = "scrolled";
  13277. } else {
  13278. this._flow = "paginated";
  13279. }
  13280. this.width = 0;
  13281. this.height = 0;
  13282. this.spreadWidth = 0;
  13283. this.delta = 0;
  13284. this.columnWidth = 0;
  13285. this.gap = 0;
  13286. this.divisor = 1;
  13287. this.props = {
  13288. name: this.name,
  13289. spread: this._spread,
  13290. flow: this._flow,
  13291. width: 0,
  13292. height: 0,
  13293. spreadWidth: 0,
  13294. delta: 0,
  13295. columnWidth: 0,
  13296. gap: 0,
  13297. divisor: 1
  13298. };
  13299. }
  13300. /**
  13301. * Switch the flow between paginated and scrolled
  13302. * @param {string} flow paginated | scrolled
  13303. * @return {string} simplified flow
  13304. */
  13305. _createClass(Layout, [{
  13306. key: "flow",
  13307. value: function flow(_flow) {
  13308. if (typeof _flow != "undefined") {
  13309. if (_flow === "scrolled" || _flow === "scrolled-continuous" || _flow === "scrolled-doc") {
  13310. this._flow = "scrolled";
  13311. } else {
  13312. this._flow = "paginated";
  13313. }
  13314. // this.props.flow = this._flow;
  13315. this.update({ flow: this._flow });
  13316. }
  13317. return this._flow;
  13318. }
  13319. /**
  13320. * Switch between using spreads or not, and set the
  13321. * width at which they switch to single.
  13322. * @param {string} spread "none" | "always" | "auto"
  13323. * @param {number} min integer in pixels
  13324. * @return {boolean} spread true | false
  13325. */
  13326. }, {
  13327. key: "spread",
  13328. value: function spread(_spread, min) {
  13329. if (_spread) {
  13330. this._spread = _spread === "none" ? false : true;
  13331. // this.props.spread = this._spread;
  13332. this.update({ spread: this._spread });
  13333. }
  13334. if (min >= 0) {
  13335. this._minSpreadWidth = min;
  13336. }
  13337. return this._spread;
  13338. }
  13339. /**
  13340. * Calculate the dimensions of the pagination
  13341. * @param {number} _width width of the rendering
  13342. * @param {number} _height height of the rendering
  13343. * @param {number} _gap width of the gap between columns
  13344. */
  13345. }, {
  13346. key: "calculate",
  13347. value: function calculate(_width, _height, _gap) {
  13348. var divisor = 1;
  13349. var gap = _gap || 0;
  13350. //-- Check the width and create even width columns
  13351. // var fullWidth = Math.floor(_width);
  13352. var width = _width;
  13353. var height = _height;
  13354. var section = Math.floor(width / 12);
  13355. var columnWidth;
  13356. var spreadWidth;
  13357. var pageWidth;
  13358. var delta;
  13359. if (this._spread && width >= this._minSpreadWidth) {
  13360. divisor = 2;
  13361. } else {
  13362. divisor = 1;
  13363. }
  13364. if (this.name === "reflowable" && this._flow === "paginated" && !(_gap >= 0)) {
  13365. gap = section % 2 === 0 ? section : section - 1;
  13366. }
  13367. if (this.name === "pre-paginated") {
  13368. gap = 0;
  13369. }
  13370. //-- Double Page
  13371. if (divisor > 1) {
  13372. // width = width - gap;
  13373. // columnWidth = (width - gap) / divisor;
  13374. // gap = gap / divisor;
  13375. columnWidth = width / divisor - gap;
  13376. pageWidth = columnWidth + gap;
  13377. } else {
  13378. columnWidth = width;
  13379. pageWidth = width;
  13380. }
  13381. if (this.name === "pre-paginated" && divisor > 1) {
  13382. width = columnWidth;
  13383. }
  13384. spreadWidth = columnWidth * divisor + gap;
  13385. delta = width;
  13386. this.width = width;
  13387. this.height = height;
  13388. this.spreadWidth = spreadWidth;
  13389. this.pageWidth = pageWidth;
  13390. this.delta = delta;
  13391. this.columnWidth = columnWidth;
  13392. this.gap = gap;
  13393. this.divisor = divisor;
  13394. // this.props.width = width;
  13395. // this.props.height = _height;
  13396. // this.props.spreadWidth = spreadWidth;
  13397. // this.props.pageWidth = pageWidth;
  13398. // this.props.delta = delta;
  13399. //
  13400. // this.props.columnWidth = colWidth;
  13401. // this.props.gap = gap;
  13402. // this.props.divisor = divisor;
  13403. this.update({
  13404. width: width,
  13405. height: height,
  13406. spreadWidth: spreadWidth,
  13407. pageWidth: pageWidth,
  13408. delta: delta,
  13409. columnWidth: columnWidth,
  13410. gap: gap,
  13411. divisor: divisor
  13412. });
  13413. }
  13414. /**
  13415. * Apply Css to a Document
  13416. * @param {Contents} contents
  13417. * @return {Promise}
  13418. */
  13419. }, {
  13420. key: "format",
  13421. value: function format(contents) {
  13422. var formating;
  13423. if (this.name === "pre-paginated") {
  13424. formating = contents.fit(this.columnWidth, this.height);
  13425. } else if (this._flow === "paginated") {
  13426. formating = contents.columns(this.width, this.height, this.columnWidth, this.gap);
  13427. } else {
  13428. // scrolled
  13429. formating = contents.size(this.width, null);
  13430. }
  13431. return formating; // might be a promise in some View Managers
  13432. }
  13433. /**
  13434. * Count number of pages
  13435. * @param {number} totalLength
  13436. * @param {number} pageLength
  13437. * @return {{spreads: Number, pages: Number}}
  13438. */
  13439. }, {
  13440. key: "count",
  13441. value: function count(totalLength, pageLength) {
  13442. var spreads = void 0,
  13443. pages = void 0;
  13444. if (this.name === "pre-paginated") {
  13445. spreads = 1;
  13446. pages = 1;
  13447. } else if (this._flow === "paginated") {
  13448. pageLength = pageLength || this.delta;
  13449. spreads = Math.ceil(totalLength / pageLength);
  13450. pages = spreads * this.divisor;
  13451. } else {
  13452. // scrolled
  13453. pageLength = pageLength || this.height;
  13454. spreads = Math.ceil(totalLength / pageLength);
  13455. pages = spreads;
  13456. }
  13457. return {
  13458. spreads: spreads,
  13459. pages: pages
  13460. };
  13461. }
  13462. /**
  13463. * Update props that have changed
  13464. * @private
  13465. * @param {object} props
  13466. */
  13467. }, {
  13468. key: "update",
  13469. value: function update(props) {
  13470. var _this = this;
  13471. // Remove props that haven't changed
  13472. Object.keys(props).forEach(function (propName) {
  13473. if (_this.props[propName] === props[propName]) {
  13474. delete props[propName];
  13475. }
  13476. });
  13477. if (Object.keys(props).length > 0) {
  13478. var newProps = (0, _core.extend)(this.props, props);
  13479. this.emit(_constants.EVENTS.LAYOUT.UPDATED, newProps, props);
  13480. }
  13481. }
  13482. }]);
  13483. return Layout;
  13484. }();
  13485. (0, _eventEmitter2.default)(Layout.prototype);
  13486. exports.default = Layout;
  13487. module.exports = exports["default"];
  13488. /***/ }),
  13489. /* 54 */
  13490. /***/ (function(module, exports, __webpack_require__) {
  13491. "use strict";
  13492. Object.defineProperty(exports, "__esModule", {
  13493. value: true
  13494. });
  13495. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  13496. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13497. var _url = __webpack_require__(5);
  13498. var _url2 = _interopRequireDefault(_url);
  13499. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13500. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13501. /**
  13502. * Themes to apply to displayed content
  13503. * @class
  13504. * @param {Rendition} rendition
  13505. */
  13506. var Themes = function () {
  13507. function Themes(rendition) {
  13508. _classCallCheck(this, Themes);
  13509. this.rendition = rendition;
  13510. this._themes = {
  13511. "default": {
  13512. "rules": {},
  13513. "url": "",
  13514. "serialized": ""
  13515. }
  13516. };
  13517. this._overrides = {};
  13518. this._current = "default";
  13519. this._injected = [];
  13520. this.rendition.hooks.content.register(this.inject.bind(this));
  13521. this.rendition.hooks.content.register(this.overrides.bind(this));
  13522. }
  13523. /**
  13524. * Add themes to be used by a rendition
  13525. * @param {object | string}
  13526. * @example themes.register("light", "http://example.com/light.css")
  13527. * @example themes.register("light", { "body": { "color": "purple"}})
  13528. * @example themes.register({ "light" : {...}, "dark" : {...}})
  13529. */
  13530. _createClass(Themes, [{
  13531. key: "register",
  13532. value: function register() {
  13533. if (arguments.length === 0) {
  13534. return;
  13535. }
  13536. if (arguments.length === 1 && _typeof(arguments[0]) === "object") {
  13537. return this.registerThemes(arguments[0]);
  13538. }
  13539. if (arguments.length === 1 && typeof arguments[0] === "string") {
  13540. return this.default(arguments[0]);
  13541. }
  13542. if (arguments.length === 2 && typeof arguments[1] === "string") {
  13543. return this.registerUrl(arguments[0], arguments[1]);
  13544. }
  13545. if (arguments.length === 2 && _typeof(arguments[1]) === "object") {
  13546. return this.registerRules(arguments[0], arguments[1]);
  13547. }
  13548. }
  13549. /**
  13550. * Add a default theme to be used by a rendition
  13551. * @param {object | string} theme
  13552. * @example themes.register("http://example.com/default.css")
  13553. * @example themes.register({ "body": { "color": "purple"}})
  13554. */
  13555. }, {
  13556. key: "default",
  13557. value: function _default(theme) {
  13558. if (!theme) {
  13559. return;
  13560. }
  13561. if (typeof theme === "string") {
  13562. return this.registerUrl("default", theme);
  13563. }
  13564. if ((typeof theme === "undefined" ? "undefined" : _typeof(theme)) === "object") {
  13565. return this.registerRules("default", theme);
  13566. }
  13567. }
  13568. /**
  13569. * Register themes object
  13570. * @param {object} themes
  13571. */
  13572. }, {
  13573. key: "registerThemes",
  13574. value: function registerThemes(themes) {
  13575. for (var theme in themes) {
  13576. if (themes.hasOwnProperty(theme)) {
  13577. if (typeof themes[theme] === "string") {
  13578. this.registerUrl(theme, themes[theme]);
  13579. } else {
  13580. this.registerRules(theme, themes[theme]);
  13581. }
  13582. }
  13583. }
  13584. }
  13585. /**
  13586. * Register a url
  13587. * @param {string} name
  13588. * @param {string} input
  13589. */
  13590. }, {
  13591. key: "registerUrl",
  13592. value: function registerUrl(name, input) {
  13593. var url = new _url2.default(input);
  13594. this._themes[name] = { "url": url.toString() };
  13595. if (this._injected[name]) {
  13596. this.update(name);
  13597. }
  13598. }
  13599. /**
  13600. * Register rule
  13601. * @param {string} name
  13602. * @param {object} rules
  13603. */
  13604. }, {
  13605. key: "registerRules",
  13606. value: function registerRules(name, rules) {
  13607. this._themes[name] = { "rules": rules };
  13608. // TODO: serialize css rules
  13609. if (this._injected[name]) {
  13610. this.update(name);
  13611. }
  13612. }
  13613. /**
  13614. * Select a theme
  13615. * @param {string} name
  13616. */
  13617. }, {
  13618. key: "select",
  13619. value: function select(name) {
  13620. var prev = this._current;
  13621. var contents;
  13622. this._current = name;
  13623. this.update(name);
  13624. contents = this.rendition.getContents();
  13625. contents.forEach(function (content) {
  13626. content.removeClass(prev);
  13627. content.addClass(name);
  13628. });
  13629. }
  13630. /**
  13631. * Update a theme
  13632. * @param {string} name
  13633. */
  13634. }, {
  13635. key: "update",
  13636. value: function update(name) {
  13637. var _this = this;
  13638. var contents = this.rendition.getContents();
  13639. contents.forEach(function (content) {
  13640. _this.add(name, content);
  13641. });
  13642. }
  13643. /**
  13644. * Inject all themes into contents
  13645. * @param {Contents} contents
  13646. */
  13647. }, {
  13648. key: "inject",
  13649. value: function inject(contents) {
  13650. var links = [];
  13651. var themes = this._themes;
  13652. var theme;
  13653. for (var name in themes) {
  13654. if (themes.hasOwnProperty(name) && (name === this._current || name === "default")) {
  13655. theme = themes[name];
  13656. if (theme.rules && Object.keys(theme.rules).length > 0 || theme.url && links.indexOf(theme.url) === -1) {
  13657. this.add(name, contents);
  13658. }
  13659. this._injected.push(name);
  13660. }
  13661. }
  13662. if (this._current != "default") {
  13663. contents.addClass(this._current);
  13664. }
  13665. }
  13666. /**
  13667. * Add Theme to contents
  13668. * @param {string} name
  13669. * @param {Contents} contents
  13670. */
  13671. }, {
  13672. key: "add",
  13673. value: function add(name, contents) {
  13674. var theme = this._themes[name];
  13675. if (!theme || !contents) {
  13676. return;
  13677. }
  13678. if (theme.url) {
  13679. contents.addStylesheet(theme.url);
  13680. } else if (theme.serialized) {
  13681. // TODO: handle serialized
  13682. } else if (theme.rules) {
  13683. contents.addStylesheetRules(theme.rules);
  13684. theme.injected = true;
  13685. }
  13686. }
  13687. /**
  13688. * Add override
  13689. * @param {string} name
  13690. * @param {string} value
  13691. * @param {boolean} priority
  13692. */
  13693. }, {
  13694. key: "override",
  13695. value: function override(name, value, priority) {
  13696. var _this2 = this;
  13697. var contents = this.rendition.getContents();
  13698. this._overrides[name] = {
  13699. value: value,
  13700. priority: priority === true
  13701. };
  13702. contents.forEach(function (content) {
  13703. content.css(name, _this2._overrides[name].value, _this2._overrides[name].priority);
  13704. });
  13705. }
  13706. /**
  13707. * Add all overrides
  13708. * @param {Content} content
  13709. */
  13710. }, {
  13711. key: "overrides",
  13712. value: function overrides(contents) {
  13713. var overrides = this._overrides;
  13714. for (var rule in overrides) {
  13715. if (overrides.hasOwnProperty(rule)) {
  13716. contents.css(rule, overrides[rule].value, overrides[rule].priority);
  13717. }
  13718. }
  13719. }
  13720. /**
  13721. * Adjust the font size of a rendition
  13722. * @param {number} size
  13723. */
  13724. }, {
  13725. key: "fontSize",
  13726. value: function fontSize(size) {
  13727. this.override("font-size", size);
  13728. }
  13729. /**
  13730. * Adjust the font-family of a rendition
  13731. * @param {string} f
  13732. */
  13733. }, {
  13734. key: "font",
  13735. value: function font(f) {
  13736. this.override("font-family", f, true);
  13737. }
  13738. }, {
  13739. key: "destroy",
  13740. value: function destroy() {
  13741. this.rendition = undefined;
  13742. this._themes = undefined;
  13743. this._overrides = undefined;
  13744. this._current = undefined;
  13745. this._injected = undefined;
  13746. }
  13747. }]);
  13748. return Themes;
  13749. }();
  13750. exports.default = Themes;
  13751. module.exports = exports["default"];
  13752. /***/ }),
  13753. /* 55 */
  13754. /***/ (function(module, exports, __webpack_require__) {
  13755. "use strict";
  13756. Object.defineProperty(exports, "__esModule", {
  13757. value: true
  13758. });
  13759. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13760. var _eventEmitter = __webpack_require__(3);
  13761. var _eventEmitter2 = _interopRequireDefault(_eventEmitter);
  13762. var _epubcfi = __webpack_require__(1);
  13763. var _epubcfi2 = _interopRequireDefault(_epubcfi);
  13764. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13765. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13766. /**
  13767. * Handles managing adding & removing Annotations
  13768. * @param {Rendition} rendition
  13769. * @class
  13770. */
  13771. var Annotations = function () {
  13772. function Annotations(rendition) {
  13773. _classCallCheck(this, Annotations);
  13774. this.rendition = rendition;
  13775. this.highlights = [];
  13776. this.underlines = [];
  13777. this.marks = [];
  13778. this._annotations = {};
  13779. this._annotationsBySectionIndex = {};
  13780. this.rendition.hooks.render.register(this.inject.bind(this));
  13781. this.rendition.hooks.unloaded.register(this.clear.bind(this));
  13782. }
  13783. /**
  13784. * Add an annotation to store
  13785. * @param {string} type Type of annotation to add: "highlight", "underline", "mark"
  13786. * @param {EpubCFI} cfiRange EpubCFI range to attach annotation to
  13787. * @param {object} data Data to assign to annotation
  13788. * @param {function} [cb] Callback after annotation is added
  13789. * @param {string} className CSS class to assign to annotation
  13790. * @param {object} styles CSS styles to assign to annotation
  13791. * @returns {Annotation} annotation
  13792. */
  13793. _createClass(Annotations, [{
  13794. key: "add",
  13795. value: function add(type, cfiRange, data, cb, className, styles) {
  13796. var hash = encodeURI(cfiRange);
  13797. var cfi = new _epubcfi2.default(cfiRange);
  13798. var sectionIndex = cfi.spinePos;
  13799. var annotation = new Annotation({
  13800. type: type,
  13801. cfiRange: cfiRange,
  13802. data: data,
  13803. sectionIndex: sectionIndex,
  13804. cb: cb,
  13805. className: className,
  13806. styles: styles
  13807. });
  13808. this._annotations[hash] = annotation;
  13809. if (sectionIndex in this._annotationsBySectionIndex) {
  13810. this._annotationsBySectionIndex[sectionIndex].push(hash);
  13811. } else {
  13812. this._annotationsBySectionIndex[sectionIndex] = [hash];
  13813. }
  13814. var views = this.rendition.views();
  13815. views.forEach(function (view) {
  13816. if (annotation.sectionIndex === view.index) {
  13817. annotation.attach(view);
  13818. }
  13819. });
  13820. return annotation;
  13821. }
  13822. /**
  13823. * Remove an annotation from store
  13824. * @param {EpubCFI} cfiRange EpubCFI range the annotation is attached to
  13825. * @param {string} type Type of annotation to add: "highlight", "underline", "mark"
  13826. */
  13827. }, {
  13828. key: "remove",
  13829. value: function remove(cfiRange, type) {
  13830. var _this = this;
  13831. var hash = encodeURI(cfiRange);
  13832. if (hash in this._annotations) {
  13833. var annotation = this._annotations[hash];
  13834. if (type && annotation.type !== type) {
  13835. return;
  13836. }
  13837. var views = this.rendition.views();
  13838. views.forEach(function (view) {
  13839. _this._removeFromAnnotationBySectionIndex(annotation.sectionIndex, hash);
  13840. if (annotation.sectionIndex === view.index) {
  13841. annotation.detach(view);
  13842. }
  13843. });
  13844. delete this._annotations[hash];
  13845. }
  13846. }
  13847. /**
  13848. * Remove an annotations by Section Index
  13849. * @private
  13850. */
  13851. }, {
  13852. key: "_removeFromAnnotationBySectionIndex",
  13853. value: function _removeFromAnnotationBySectionIndex(sectionIndex, hash) {
  13854. this._annotationsBySectionIndex[sectionIndex] = this._annotationsAt(sectionIndex).filter(function (h) {
  13855. return h !== hash;
  13856. });
  13857. }
  13858. /**
  13859. * Get annotations by Section Index
  13860. * @private
  13861. */
  13862. }, {
  13863. key: "_annotationsAt",
  13864. value: function _annotationsAt(index) {
  13865. return this._annotationsBySectionIndex[index];
  13866. }
  13867. /**
  13868. * Add a highlight to the store
  13869. * @param {EpubCFI} cfiRange EpubCFI range to attach annotation to
  13870. * @param {object} data Data to assign to annotation
  13871. * @param {function} cb Callback after annotation is added
  13872. * @param {string} className CSS class to assign to annotation
  13873. * @param {object} styles CSS styles to assign to annotation
  13874. */
  13875. }, {
  13876. key: "highlight",
  13877. value: function highlight(cfiRange, data, cb, className, styles) {
  13878. this.add("highlight", cfiRange, data, cb, className, styles);
  13879. }
  13880. /**
  13881. * Add a underline to the store
  13882. * @param {EpubCFI} cfiRange EpubCFI range to attach annotation to
  13883. * @param {object} data Data to assign to annotation
  13884. * @param {function} cb Callback after annotation is added
  13885. * @param {string} className CSS class to assign to annotation
  13886. * @param {object} styles CSS styles to assign to annotation
  13887. */
  13888. }, {
  13889. key: "underline",
  13890. value: function underline(cfiRange, data, cb, className, styles) {
  13891. this.add("underline", cfiRange, data, cb, className, styles);
  13892. }
  13893. /**
  13894. * Add a mark to the store
  13895. * @param {EpubCFI} cfiRange EpubCFI range to attach annotation to
  13896. * @param {object} data Data to assign to annotation
  13897. * @param {function} cb Callback after annotation is added
  13898. */
  13899. }, {
  13900. key: "mark",
  13901. value: function mark(cfiRange, data, cb) {
  13902. this.add("mark", cfiRange, data, cb);
  13903. }
  13904. /**
  13905. * iterate over annotations in the store
  13906. */
  13907. }, {
  13908. key: "each",
  13909. value: function each() {
  13910. return this._annotations.forEach.apply(this._annotations, arguments);
  13911. }
  13912. /**
  13913. * Hook for injecting annotation into a view
  13914. * @param {View} view
  13915. * @private
  13916. */
  13917. }, {
  13918. key: "inject",
  13919. value: function inject(view) {
  13920. var _this2 = this;
  13921. var sectionIndex = view.index;
  13922. if (sectionIndex in this._annotationsBySectionIndex) {
  13923. var annotations = this._annotationsBySectionIndex[sectionIndex];
  13924. annotations.forEach(function (hash) {
  13925. var annotation = _this2._annotations[hash];
  13926. annotation.attach(view);
  13927. });
  13928. }
  13929. }
  13930. /**
  13931. * Hook for removing annotation from a view
  13932. * @param {View} view
  13933. * @private
  13934. */
  13935. }, {
  13936. key: "clear",
  13937. value: function clear(view) {
  13938. var _this3 = this;
  13939. var sectionIndex = view.index;
  13940. if (sectionIndex in this._annotationsBySectionIndex) {
  13941. var annotations = this._annotationsBySectionIndex[sectionIndex];
  13942. annotations.forEach(function (hash) {
  13943. var annotation = _this3._annotations[hash];
  13944. annotation.detach(view);
  13945. });
  13946. }
  13947. }
  13948. /**
  13949. * [Not Implemented] Show annotations
  13950. * @TODO: needs implementation in View
  13951. */
  13952. }, {
  13953. key: "show",
  13954. value: function show() {}
  13955. /**
  13956. * [Not Implemented] Hide annotations
  13957. * @TODO: needs implementation in View
  13958. */
  13959. }, {
  13960. key: "hide",
  13961. value: function hide() {}
  13962. }]);
  13963. return Annotations;
  13964. }();
  13965. /**
  13966. * Annotation object
  13967. * @class
  13968. * @param {object} options
  13969. * @param {string} options.type Type of annotation to add: "highlight", "underline", "mark"
  13970. * @param {EpubCFI} options.cfiRange EpubCFI range to attach annotation to
  13971. * @param {object} options.data Data to assign to annotation
  13972. * @param {int} options.sectionIndex Index in the Spine of the Section annotation belongs to
  13973. * @param {function} [options.cb] Callback after annotation is added
  13974. * @param {string} className CSS class to assign to annotation
  13975. * @param {object} styles CSS styles to assign to annotation
  13976. * @returns {Annotation} annotation
  13977. */
  13978. var Annotation = function () {
  13979. function Annotation(_ref) {
  13980. var type = _ref.type,
  13981. cfiRange = _ref.cfiRange,
  13982. data = _ref.data,
  13983. sectionIndex = _ref.sectionIndex,
  13984. cb = _ref.cb,
  13985. className = _ref.className,
  13986. styles = _ref.styles;
  13987. _classCallCheck(this, Annotation);
  13988. this.type = type;
  13989. this.cfiRange = cfiRange;
  13990. this.data = data;
  13991. this.sectionIndex = sectionIndex;
  13992. this.mark = undefined;
  13993. this.cb = cb;
  13994. this.className = className;
  13995. this.styles = styles;
  13996. }
  13997. /**
  13998. * Update stored data
  13999. * @param {object} data
  14000. */
  14001. _createClass(Annotation, [{
  14002. key: "update",
  14003. value: function update(data) {
  14004. this.data = data;
  14005. }
  14006. /**
  14007. * Add to a view
  14008. * @param {View} view
  14009. */
  14010. }, {
  14011. key: "attach",
  14012. value: function attach(view) {
  14013. var cfiRange = this.cfiRange,
  14014. data = this.data,
  14015. type = this.type,
  14016. mark = this.mark,
  14017. cb = this.cb,
  14018. className = this.className,
  14019. styles = this.styles;
  14020. var result = void 0;
  14021. if (type === "highlight") {
  14022. result = view.highlight(cfiRange, data, cb, className, styles);
  14023. } else if (type === "underline") {
  14024. result = view.underline(cfiRange, data, cb, className, styles);
  14025. } else if (type === "mark") {
  14026. result = view.mark(cfiRange, data, cb);
  14027. }
  14028. this.mark = result;
  14029. return result;
  14030. }
  14031. /**
  14032. * Remove from a view
  14033. * @param {View} view
  14034. */
  14035. }, {
  14036. key: "detach",
  14037. value: function detach(view) {
  14038. var cfiRange = this.cfiRange,
  14039. type = this.type;
  14040. var result = void 0;
  14041. if (view) {
  14042. if (type === "highlight") {
  14043. result = view.unhighlight(cfiRange);
  14044. } else if (type === "underline") {
  14045. result = view.ununderline(cfiRange);
  14046. } else if (type === "mark") {
  14047. result = view.unmark(cfiRange);
  14048. }
  14049. }
  14050. this.mark = undefined;
  14051. return result;
  14052. }
  14053. /**
  14054. * [Not Implemented] Get text of an annotation
  14055. * @TODO: needs implementation in contents
  14056. */
  14057. }, {
  14058. key: "text",
  14059. value: function text() {}
  14060. }]);
  14061. return Annotation;
  14062. }();
  14063. (0, _eventEmitter2.default)(Annotation.prototype);
  14064. exports.default = Annotations;
  14065. module.exports = exports["default"];
  14066. /***/ }),
  14067. /* 56 */
  14068. /***/ (function(module, exports, __webpack_require__) {
  14069. "use strict";
  14070. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  14071. Object.defineProperty(exports, "__esModule", {
  14072. value: true
  14073. });
  14074. exports.Underline = exports.Highlight = exports.Mark = exports.Pane = undefined;
  14075. var _get = function get(object, property, receiver) {
  14076. if (object === null) object = Function.prototype;var desc = Object.getOwnPropertyDescriptor(object, property);if (desc === undefined) {
  14077. var parent = Object.getPrototypeOf(object);if (parent === null) {
  14078. return undefined;
  14079. } else {
  14080. return get(parent, property, receiver);
  14081. }
  14082. } else if ("value" in desc) {
  14083. return desc.value;
  14084. } else {
  14085. var getter = desc.get;if (getter === undefined) {
  14086. return undefined;
  14087. }return getter.call(receiver);
  14088. }
  14089. };
  14090. var _createClass = function () {
  14091. function defineProperties(target, props) {
  14092. for (var i = 0; i < props.length; i++) {
  14093. var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
  14094. }
  14095. }return function (Constructor, protoProps, staticProps) {
  14096. if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  14097. };
  14098. }();
  14099. var _svg = __webpack_require__(57);
  14100. var _svg2 = _interopRequireDefault(_svg);
  14101. var _events = __webpack_require__(58);
  14102. var _events2 = _interopRequireDefault(_events);
  14103. function _interopRequireDefault(obj) {
  14104. return obj && obj.__esModule ? obj : { default: obj };
  14105. }
  14106. function _possibleConstructorReturn(self, call) {
  14107. if (!self) {
  14108. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  14109. }return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
  14110. }
  14111. function _inherits(subClass, superClass) {
  14112. if (typeof superClass !== "function" && superClass !== null) {
  14113. throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
  14114. }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  14115. }
  14116. function _classCallCheck(instance, Constructor) {
  14117. if (!(instance instanceof Constructor)) {
  14118. throw new TypeError("Cannot call a class as a function");
  14119. }
  14120. }
  14121. var Pane = exports.Pane = function () {
  14122. function Pane(target) {
  14123. var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document.body;
  14124. _classCallCheck(this, Pane);
  14125. this.target = target;
  14126. this.element = _svg2.default.createElement('svg');
  14127. this.marks = [];
  14128. // Match the coordinates of the target element
  14129. this.element.style.position = 'absolute';
  14130. // Disable pointer events
  14131. this.element.setAttribute('pointer-events', 'none');
  14132. // Set up mouse event proxying between the target element and the marks
  14133. _events2.default.proxyMouse(this.target, this.marks);
  14134. this.container = container;
  14135. this.container.appendChild(this.element);
  14136. this.render();
  14137. }
  14138. _createClass(Pane, [{
  14139. key: 'addMark',
  14140. value: function addMark(mark) {
  14141. var g = _svg2.default.createElement('g');
  14142. this.element.appendChild(g);
  14143. mark.bind(g, this.container);
  14144. this.marks.push(mark);
  14145. mark.render();
  14146. return mark;
  14147. }
  14148. }, {
  14149. key: 'removeMark',
  14150. value: function removeMark(mark) {
  14151. var idx = this.marks.indexOf(mark);
  14152. if (idx === -1) {
  14153. return;
  14154. }
  14155. var el = mark.unbind();
  14156. this.element.removeChild(el);
  14157. this.marks.splice(idx, 1);
  14158. }
  14159. }, {
  14160. key: 'render',
  14161. value: function render() {
  14162. setCoords(this.element, coords(this.target, this.container));
  14163. var _iteratorNormalCompletion = true;
  14164. var _didIteratorError = false;
  14165. var _iteratorError = undefined;
  14166. try {
  14167. for (var _iterator = this.marks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  14168. var m = _step.value;
  14169. m.render();
  14170. }
  14171. } catch (err) {
  14172. _didIteratorError = true;
  14173. _iteratorError = err;
  14174. } finally {
  14175. try {
  14176. if (!_iteratorNormalCompletion && _iterator.return) {
  14177. _iterator.return();
  14178. }
  14179. } finally {
  14180. if (_didIteratorError) {
  14181. throw _iteratorError;
  14182. }
  14183. }
  14184. }
  14185. }
  14186. }]);
  14187. return Pane;
  14188. }();
  14189. var Mark = exports.Mark = function () {
  14190. function Mark() {
  14191. _classCallCheck(this, Mark);
  14192. this.element = null;
  14193. }
  14194. _createClass(Mark, [{
  14195. key: 'bind',
  14196. value: function bind(element, container) {
  14197. this.element = element;
  14198. this.container = container;
  14199. }
  14200. }, {
  14201. key: 'unbind',
  14202. value: function unbind() {
  14203. var el = this.element;
  14204. this.element = null;
  14205. return el;
  14206. }
  14207. }, {
  14208. key: 'render',
  14209. value: function render() {}
  14210. }, {
  14211. key: 'dispatchEvent',
  14212. value: function dispatchEvent(e) {
  14213. if (!this.element) return;
  14214. this.element.dispatchEvent(e);
  14215. }
  14216. }, {
  14217. key: 'getBoundingClientRect',
  14218. value: function getBoundingClientRect() {
  14219. return this.element.getBoundingClientRect();
  14220. }
  14221. }, {
  14222. key: 'getClientRects',
  14223. value: function getClientRects() {
  14224. var rects = [];
  14225. var el = this.element.firstChild;
  14226. while (el) {
  14227. rects.push(el.getBoundingClientRect());
  14228. el = el.nextSibling;
  14229. }
  14230. return rects;
  14231. }
  14232. }, {
  14233. key: 'filteredRanges',
  14234. value: function filteredRanges() {
  14235. var rects = Array.from(this.range.getClientRects());
  14236. // De-duplicate the boxes
  14237. return rects.filter(function (box) {
  14238. for (var i = 0; i < rects.length; i++) {
  14239. if (rects[i] === box) {
  14240. return true;
  14241. }
  14242. var contained = contains(rects[i], box);
  14243. if (contained) {
  14244. return false;
  14245. }
  14246. }
  14247. return true;
  14248. });
  14249. }
  14250. }]);
  14251. return Mark;
  14252. }();
  14253. var Highlight = exports.Highlight = function (_Mark) {
  14254. _inherits(Highlight, _Mark);
  14255. function Highlight(range, className, data, attributes) {
  14256. _classCallCheck(this, Highlight);
  14257. var _this = _possibleConstructorReturn(this, (Highlight.__proto__ || Object.getPrototypeOf(Highlight)).call(this));
  14258. _this.range = range;
  14259. _this.className = className;
  14260. _this.data = data || {};
  14261. _this.attributes = attributes || {};
  14262. return _this;
  14263. }
  14264. _createClass(Highlight, [{
  14265. key: 'bind',
  14266. value: function bind(element, container) {
  14267. _get(Highlight.prototype.__proto__ || Object.getPrototypeOf(Highlight.prototype), 'bind', this).call(this, element, container);
  14268. for (var attr in this.data) {
  14269. if (this.data.hasOwnProperty(attr)) {
  14270. this.element.dataset[attr] = this.data[attr];
  14271. }
  14272. }
  14273. for (var attr in this.attributes) {
  14274. if (this.attributes.hasOwnProperty(attr)) {
  14275. this.element.setAttribute(attr, this.attributes[attr]);
  14276. }
  14277. }
  14278. if (this.className) {
  14279. this.element.classList.add(this.className);
  14280. }
  14281. }
  14282. }, {
  14283. key: 'render',
  14284. value: function render() {
  14285. // Empty element
  14286. while (this.element.firstChild) {
  14287. this.element.removeChild(this.element.firstChild);
  14288. }
  14289. var docFrag = this.element.ownerDocument.createDocumentFragment();
  14290. var filtered = this.filteredRanges();
  14291. var offset = this.element.getBoundingClientRect();
  14292. var container = this.container.getBoundingClientRect();
  14293. for (var i = 0, len = filtered.length; i < len; i++) {
  14294. var r = filtered[i];
  14295. var el = _svg2.default.createElement('rect');
  14296. el.setAttribute('x', r.left - offset.left + container.left);
  14297. el.setAttribute('y', r.top - offset.top + container.top);
  14298. el.setAttribute('height', r.height);
  14299. el.setAttribute('width', r.width);
  14300. docFrag.appendChild(el);
  14301. }
  14302. this.element.appendChild(docFrag);
  14303. }
  14304. }]);
  14305. return Highlight;
  14306. }(Mark);
  14307. var Underline = exports.Underline = function (_Highlight) {
  14308. _inherits(Underline, _Highlight);
  14309. function Underline(range, className, data, attributes) {
  14310. _classCallCheck(this, Underline);
  14311. return _possibleConstructorReturn(this, (Underline.__proto__ || Object.getPrototypeOf(Underline)).call(this, range, className, data, attributes));
  14312. }
  14313. _createClass(Underline, [{
  14314. key: 'render',
  14315. value: function render() {
  14316. // Empty element
  14317. while (this.element.firstChild) {
  14318. this.element.removeChild(this.element.firstChild);
  14319. }
  14320. var docFrag = this.element.ownerDocument.createDocumentFragment();
  14321. var filtered = this.filteredRanges();
  14322. var offset = this.element.getBoundingClientRect();
  14323. var container = this.container.getBoundingClientRect();
  14324. for (var i = 0, len = filtered.length; i < len; i++) {
  14325. var r = filtered[i];
  14326. var rect = _svg2.default.createElement('rect');
  14327. rect.setAttribute('x', r.left - offset.left + container.left);
  14328. rect.setAttribute('y', r.top - offset.top + container.top);
  14329. rect.setAttribute('height', r.height);
  14330. rect.setAttribute('width', r.width);
  14331. rect.setAttribute('fill', 'none');
  14332. var line = _svg2.default.createElement('line');
  14333. line.setAttribute('x1', r.left - offset.left + container.left);
  14334. line.setAttribute('x2', r.left - offset.left + container.left + r.width);
  14335. line.setAttribute('y1', r.top - offset.top + container.top + r.height - 1);
  14336. line.setAttribute('y2', r.top - offset.top + container.top + r.height - 1);
  14337. line.setAttribute('stroke-width', 1);
  14338. line.setAttribute('stroke', 'black'); //TODO: match text color?
  14339. line.setAttribute('stroke-linecap', 'square');
  14340. docFrag.appendChild(rect);
  14341. docFrag.appendChild(line);
  14342. }
  14343. this.element.appendChild(docFrag);
  14344. }
  14345. }]);
  14346. return Underline;
  14347. }(Highlight);
  14348. function coords(el, container) {
  14349. var offset = container.getBoundingClientRect();
  14350. var rect = el.getBoundingClientRect();
  14351. return {
  14352. top: rect.top - offset.top,
  14353. left: rect.left - offset.left,
  14354. height: el.scrollHeight,
  14355. width: el.scrollWidth
  14356. };
  14357. }
  14358. function setCoords(el, coords) {
  14359. el.style.top = coords.top + 'px';
  14360. el.style.left = coords.left + 'px';
  14361. el.style.height = coords.height + 'px';
  14362. el.style.width = coords.width + 'px';
  14363. }
  14364. function contains(rect1, rect2) {
  14365. return rect2.right <= rect1.right && rect2.left >= rect1.left && rect2.top >= rect1.top && rect2.bottom <= rect1.bottom;
  14366. }
  14367. /***/ }),
  14368. /* 57 */
  14369. /***/ (function(module, exports, __webpack_require__) {
  14370. "use strict";
  14371. Object.defineProperty(exports, "__esModule", {
  14372. value: true
  14373. });
  14374. exports.createElement = createElement;
  14375. function createElement(name) {
  14376. return document.createElementNS('http://www.w3.org/2000/svg', name);
  14377. }
  14378. exports.default = {
  14379. createElement: createElement
  14380. };
  14381. /***/ }),
  14382. /* 58 */
  14383. /***/ (function(module, exports, __webpack_require__) {
  14384. "use strict";
  14385. Object.defineProperty(exports, "__esModule", {
  14386. value: true
  14387. });
  14388. exports.proxyMouse = proxyMouse;
  14389. exports.clone = clone;
  14390. // import 'babelify/polyfill'; // needed for Object.assign
  14391. exports.default = {
  14392. proxyMouse: proxyMouse
  14393. };
  14394. /**
  14395. * Start proxying all mouse events that occur on the target node to each node in
  14396. * a set of tracked nodes.
  14397. *
  14398. * The items in tracked do not strictly have to be DOM Nodes, but they do have
  14399. * to have dispatchEvent, getBoundingClientRect, and getClientRects methods.
  14400. *
  14401. * @param target {Node} The node on which to listen for mouse events.
  14402. * @param tracked {Node[]} A (possibly mutable) array of nodes to which to proxy
  14403. * events.
  14404. */
  14405. function proxyMouse(target, tracked) {
  14406. function dispatch(e) {
  14407. // We walk through the set of tracked elements in reverse order so that
  14408. // events are sent to those most recently added first.
  14409. //
  14410. // This is the least surprising behaviour as it simulates the way the
  14411. // browser would work if items added later were drawn "on top of"
  14412. // earlier ones.
  14413. for (var i = tracked.length - 1; i >= 0; i--) {
  14414. var t = tracked[i];
  14415. var x = e.clientX;
  14416. var y = e.clientY;
  14417. if (e.touches && e.touches.length) {
  14418. x = e.touches[0].clientX;
  14419. y = e.touches[0].clientY;
  14420. }
  14421. if (!contains(t, target, x, y)) {
  14422. continue;
  14423. }
  14424. // The event targets this mark, so dispatch a cloned event:
  14425. t.dispatchEvent(clone(e));
  14426. // We only dispatch the cloned event to the first matching mark.
  14427. break;
  14428. }
  14429. }
  14430. if (target.nodeName === "iframe" || target.nodeName === "IFRAME") {
  14431. try {
  14432. // Try to get the contents if same domain
  14433. this.target = target.contentDocument;
  14434. } catch (err) {
  14435. this.target = target;
  14436. }
  14437. } else {
  14438. this.target = target;
  14439. }
  14440. var _arr = ['mouseup', 'mousedown', 'click', 'touchstart'];
  14441. for (var _i = 0; _i < _arr.length; _i++) {
  14442. var ev = _arr[_i];
  14443. this.target.addEventListener(ev, function (e) {
  14444. return dispatch(e);
  14445. }, false);
  14446. }
  14447. }
  14448. /**
  14449. * Clone a mouse event object.
  14450. *
  14451. * @param e {MouseEvent} A mouse event object to clone.
  14452. * @returns {MouseEvent}
  14453. */
  14454. function clone(e) {
  14455. var opts = Object.assign({}, e, { bubbles: false });
  14456. try {
  14457. return new MouseEvent(e.type, opts);
  14458. } catch (err) {
  14459. // compat: webkit
  14460. var copy = document.createEvent('MouseEvents');
  14461. copy.initMouseEvent(e.type, false, opts.cancelable, opts.view, opts.detail, opts.screenX, opts.screenY, opts.clientX, opts.clientY, opts.ctrlKey, opts.altKey, opts.shiftKey, opts.metaKey, opts.button, opts.relatedTarget);
  14462. return copy;
  14463. }
  14464. }
  14465. /**
  14466. * Check if the item contains the point denoted by the passed coordinates
  14467. * @param item {Object} An object with getBoundingClientRect and getClientRects
  14468. * methods.
  14469. * @param x {Number}
  14470. * @param y {Number}
  14471. * @returns {Boolean}
  14472. */
  14473. function contains(item, target, x, y) {
  14474. // offset
  14475. var offset = target.getBoundingClientRect();
  14476. function rectContains(r, x, y) {
  14477. var top = r.top - offset.top;
  14478. var left = r.left - offset.left;
  14479. var bottom = top + r.height;
  14480. var right = left + r.width;
  14481. return top <= y && left <= x && bottom > y && right > x;
  14482. }
  14483. // Check overall bounding box first
  14484. var rect = item.getBoundingClientRect();
  14485. if (!rectContains(rect, x, y)) {
  14486. return false;
  14487. }
  14488. // Then continue to check each child rect
  14489. var rects = item.getClientRects();
  14490. for (var i = 0, len = rects.length; i < len; i++) {
  14491. if (rectContains(rects[i], x, y)) {
  14492. return true;
  14493. }
  14494. }
  14495. return false;
  14496. }
  14497. /***/ }),
  14498. /* 59 */
  14499. /***/ (function(module, exports, __webpack_require__) {
  14500. "use strict";
  14501. Object.defineProperty(exports, "__esModule", {
  14502. value: true
  14503. });
  14504. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  14505. var _core = __webpack_require__(0);
  14506. var _throttle = __webpack_require__(60);
  14507. var _throttle2 = _interopRequireDefault(_throttle);
  14508. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14509. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14510. var Stage = function () {
  14511. function Stage(_options) {
  14512. _classCallCheck(this, Stage);
  14513. this.settings = _options || {};
  14514. this.id = "epubjs-container-" + (0, _core.uuid)();
  14515. this.container = this.create(this.settings);
  14516. if (this.settings.hidden) {
  14517. this.wrapper = this.wrap(this.container);
  14518. }
  14519. }
  14520. /*
  14521. * Creates an element to render to.
  14522. * Resizes to passed width and height or to the elements size
  14523. */
  14524. _createClass(Stage, [{
  14525. key: "create",
  14526. value: function create(options) {
  14527. var height = options.height; // !== false ? options.height : "100%";
  14528. var width = options.width; // !== false ? options.width : "100%";
  14529. var overflow = options.overflow || false;
  14530. var axis = options.axis || "vertical";
  14531. var direction = options.direction;
  14532. if (options.height && (0, _core.isNumber)(options.height)) {
  14533. height = options.height + "px";
  14534. }
  14535. if (options.width && (0, _core.isNumber)(options.width)) {
  14536. width = options.width + "px";
  14537. }
  14538. // Create new container element
  14539. var container = document.createElement("div");
  14540. container.id = this.id;
  14541. container.classList.add("epub-container");
  14542. // Style Element
  14543. // container.style.fontSize = "0";
  14544. container.style.wordSpacing = "0";
  14545. container.style.lineHeight = "0";
  14546. container.style.verticalAlign = "top";
  14547. container.style.position = "relative";
  14548. if (axis === "horizontal") {
  14549. // container.style.whiteSpace = "nowrap";
  14550. container.style.display = "flex";
  14551. container.style.flexDirection = "row";
  14552. container.style.flexWrap = "nowrap";
  14553. }
  14554. if (width) {
  14555. container.style.width = width;
  14556. }
  14557. if (height) {
  14558. container.style.height = height;
  14559. }
  14560. if (overflow) {
  14561. container.style.overflow = overflow;
  14562. }
  14563. if (direction) {
  14564. container.dir = direction;
  14565. container.style["direction"] = direction;
  14566. }
  14567. if (direction && this.settings.fullsize) {
  14568. document.body.style["direction"] = direction;
  14569. }
  14570. return container;
  14571. }
  14572. }, {
  14573. key: "wrap",
  14574. value: function wrap(container) {
  14575. var wrapper = document.createElement("div");
  14576. wrapper.style.visibility = "hidden";
  14577. wrapper.style.overflow = "hidden";
  14578. wrapper.style.width = "0";
  14579. wrapper.style.height = "0";
  14580. wrapper.appendChild(container);
  14581. return wrapper;
  14582. }
  14583. }, {
  14584. key: "getElement",
  14585. value: function getElement(_element) {
  14586. var element;
  14587. if ((0, _core.isElement)(_element)) {
  14588. element = _element;
  14589. } else if (typeof _element === "string") {
  14590. element = document.getElementById(_element);
  14591. }
  14592. if (!element) {
  14593. throw new Error("Not an Element");
  14594. }
  14595. return element;
  14596. }
  14597. }, {
  14598. key: "attachTo",
  14599. value: function attachTo(what) {
  14600. var element = this.getElement(what);
  14601. var base;
  14602. if (!element) {
  14603. return;
  14604. }
  14605. if (this.settings.hidden) {
  14606. base = this.wrapper;
  14607. } else {
  14608. base = this.container;
  14609. }
  14610. element.appendChild(base);
  14611. this.element = element;
  14612. return element;
  14613. }
  14614. }, {
  14615. key: "getContainer",
  14616. value: function getContainer() {
  14617. return this.container;
  14618. }
  14619. }, {
  14620. key: "onResize",
  14621. value: function onResize(func) {
  14622. // Only listen to window for resize event if width and height are not fixed.
  14623. // This applies if it is set to a percent or auto.
  14624. if (!(0, _core.isNumber)(this.settings.width) || !(0, _core.isNumber)(this.settings.height)) {
  14625. this.resizeFunc = (0, _throttle2.default)(func, 50);
  14626. window.addEventListener("resize", this.resizeFunc, false);
  14627. }
  14628. }
  14629. }, {
  14630. key: "onOrientationChange",
  14631. value: function onOrientationChange(func) {
  14632. this.orientationChangeFunc = func;
  14633. window.addEventListener("orientationchange", this.orientationChangeFunc, false);
  14634. }
  14635. }, {
  14636. key: "size",
  14637. value: function size(width, height) {
  14638. var bounds;
  14639. // var width = _width || this.settings.width;
  14640. // var height = _height || this.settings.height;
  14641. // If width or height are set to false, inherit them from containing element
  14642. if (width === null) {
  14643. bounds = this.element.getBoundingClientRect();
  14644. if (bounds.width) {
  14645. width = Math.floor(bounds.width);
  14646. this.container.style.width = width + "px";
  14647. }
  14648. } else {
  14649. if ((0, _core.isNumber)(width)) {
  14650. this.container.style.width = width + "px";
  14651. } else {
  14652. this.container.style.width = width;
  14653. }
  14654. }
  14655. if (height === null) {
  14656. bounds = bounds || this.element.getBoundingClientRect();
  14657. if (bounds.height) {
  14658. height = bounds.height;
  14659. this.container.style.height = height + "px";
  14660. }
  14661. } else {
  14662. if ((0, _core.isNumber)(height)) {
  14663. this.container.style.height = height + "px";
  14664. } else {
  14665. this.container.style.height = height;
  14666. }
  14667. }
  14668. if (!(0, _core.isNumber)(width)) {
  14669. bounds = this.container.getBoundingClientRect();
  14670. width = Math.floor(bounds.width);
  14671. //height = bounds.height;
  14672. }
  14673. if (!(0, _core.isNumber)(height)) {
  14674. bounds = bounds || this.container.getBoundingClientRect();
  14675. //width = bounds.width;
  14676. height = bounds.height;
  14677. }
  14678. this.containerStyles = window.getComputedStyle(this.container);
  14679. this.containerPadding = {
  14680. left: parseFloat(this.containerStyles["padding-left"]) || 0,
  14681. right: parseFloat(this.containerStyles["padding-right"]) || 0,
  14682. top: parseFloat(this.containerStyles["padding-top"]) || 0,
  14683. bottom: parseFloat(this.containerStyles["padding-bottom"]) || 0
  14684. };
  14685. // Bounds not set, get them from window
  14686. var _windowBounds = (0, _core.windowBounds)();
  14687. var bodyStyles = window.getComputedStyle(document.body);
  14688. var bodyPadding = {
  14689. left: parseFloat(bodyStyles["padding-left"]) || 0,
  14690. right: parseFloat(bodyStyles["padding-right"]) || 0,
  14691. top: parseFloat(bodyStyles["padding-top"]) || 0,
  14692. bottom: parseFloat(bodyStyles["padding-bottom"]) || 0
  14693. };
  14694. if (!width) {
  14695. width = _windowBounds.width - bodyPadding.left - bodyPadding.right;
  14696. }
  14697. if (this.settings.fullsize && !height || !height) {
  14698. height = _windowBounds.height - bodyPadding.top - bodyPadding.bottom;
  14699. }
  14700. return {
  14701. width: width - this.containerPadding.left - this.containerPadding.right,
  14702. height: height - this.containerPadding.top - this.containerPadding.bottom
  14703. };
  14704. }
  14705. }, {
  14706. key: "bounds",
  14707. value: function bounds() {
  14708. var box = void 0;
  14709. if (this.container.style.overflow !== "visible") {
  14710. box = this.container && this.container.getBoundingClientRect();
  14711. }
  14712. if (!box || !box.width || !box.height) {
  14713. return (0, _core.windowBounds)();
  14714. } else {
  14715. return box;
  14716. }
  14717. }
  14718. }, {
  14719. key: "getSheet",
  14720. value: function getSheet() {
  14721. var style = document.createElement("style");
  14722. // WebKit hack --> https://davidwalsh.name/add-rules-stylesheets
  14723. style.appendChild(document.createTextNode(""));
  14724. document.head.appendChild(style);
  14725. return style.sheet;
  14726. }
  14727. }, {
  14728. key: "addStyleRules",
  14729. value: function addStyleRules(selector, rulesArray) {
  14730. var scope = "#" + this.id + " ";
  14731. var rules = "";
  14732. if (!this.sheet) {
  14733. this.sheet = this.getSheet();
  14734. }
  14735. rulesArray.forEach(function (set) {
  14736. for (var prop in set) {
  14737. if (set.hasOwnProperty(prop)) {
  14738. rules += prop + ":" + set[prop] + ";";
  14739. }
  14740. }
  14741. });
  14742. this.sheet.insertRule(scope + selector + " {" + rules + "}", 0);
  14743. }
  14744. }, {
  14745. key: "axis",
  14746. value: function axis(_axis) {
  14747. if (_axis === "horizontal") {
  14748. this.container.style.display = "flex";
  14749. this.container.style.flexDirection = "row";
  14750. this.container.style.flexWrap = "nowrap";
  14751. } else {
  14752. this.container.style.display = "block";
  14753. }
  14754. }
  14755. // orientation(orientation) {
  14756. // if (orientation === "landscape") {
  14757. //
  14758. // } else {
  14759. //
  14760. // }
  14761. //
  14762. // this.orientation = orientation;
  14763. // }
  14764. }, {
  14765. key: "direction",
  14766. value: function direction(dir) {
  14767. if (this.container) {
  14768. this.container.dir = dir;
  14769. this.container.style["direction"] = dir;
  14770. }
  14771. if (this.settings.fullsize) {
  14772. document.body.style["direction"] = dir;
  14773. }
  14774. }
  14775. }, {
  14776. key: "destroy",
  14777. value: function destroy() {
  14778. var base;
  14779. if (this.element) {
  14780. if (this.settings.hidden) {
  14781. base = this.wrapper;
  14782. } else {
  14783. base = this.container;
  14784. }
  14785. if (this.element.contains(this.container)) {
  14786. this.element.removeChild(this.container);
  14787. }
  14788. window.removeEventListener("resize", this.resizeFunc);
  14789. window.removeEventListener("orientationChange", this.orientationChangeFunc);
  14790. }
  14791. }
  14792. }]);
  14793. return Stage;
  14794. }();
  14795. exports.default = Stage;
  14796. module.exports = exports["default"];
  14797. /***/ }),
  14798. /* 60 */
  14799. /***/ (function(module, exports, __webpack_require__) {
  14800. var debounce = __webpack_require__(21),
  14801. isObject = __webpack_require__(15);
  14802. /** Error message constants. */
  14803. var FUNC_ERROR_TEXT = 'Expected a function';
  14804. /**
  14805. * Creates a throttled function that only invokes `func` at most once per
  14806. * every `wait` milliseconds. The throttled function comes with a `cancel`
  14807. * method to cancel delayed `func` invocations and a `flush` method to
  14808. * immediately invoke them. Provide `options` to indicate whether `func`
  14809. * should be invoked on the leading and/or trailing edge of the `wait`
  14810. * timeout. The `func` is invoked with the last arguments provided to the
  14811. * throttled function. Subsequent calls to the throttled function return the
  14812. * result of the last `func` invocation.
  14813. *
  14814. * **Note:** If `leading` and `trailing` options are `true`, `func` is
  14815. * invoked on the trailing edge of the timeout only if the throttled function
  14816. * is invoked more than once during the `wait` timeout.
  14817. *
  14818. * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
  14819. * until to the next tick, similar to `setTimeout` with a timeout of `0`.
  14820. *
  14821. * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
  14822. * for details over the differences between `_.throttle` and `_.debounce`.
  14823. *
  14824. * @static
  14825. * @memberOf _
  14826. * @since 0.1.0
  14827. * @category Function
  14828. * @param {Function} func The function to throttle.
  14829. * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
  14830. * @param {Object} [options={}] The options object.
  14831. * @param {boolean} [options.leading=true]
  14832. * Specify invoking on the leading edge of the timeout.
  14833. * @param {boolean} [options.trailing=true]
  14834. * Specify invoking on the trailing edge of the timeout.
  14835. * @returns {Function} Returns the new throttled function.
  14836. * @example
  14837. *
  14838. * // Avoid excessively updating the position while scrolling.
  14839. * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
  14840. *
  14841. * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
  14842. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
  14843. * jQuery(element).on('click', throttled);
  14844. *
  14845. * // Cancel the trailing throttled invocation.
  14846. * jQuery(window).on('popstate', throttled.cancel);
  14847. */
  14848. function throttle(func, wait, options) {
  14849. var leading = true,
  14850. trailing = true;
  14851. if (typeof func != 'function') {
  14852. throw new TypeError(FUNC_ERROR_TEXT);
  14853. }
  14854. if (isObject(options)) {
  14855. leading = 'leading' in options ? !!options.leading : leading;
  14856. trailing = 'trailing' in options ? !!options.trailing : trailing;
  14857. }
  14858. return debounce(func, wait, {
  14859. 'leading': leading,
  14860. 'maxWait': wait,
  14861. 'trailing': trailing
  14862. });
  14863. }
  14864. module.exports = throttle;
  14865. /***/ }),
  14866. /* 61 */
  14867. /***/ (function(module, exports, __webpack_require__) {
  14868. var root = __webpack_require__(22);
  14869. /**
  14870. * Gets the timestamp of the number of milliseconds that have elapsed since
  14871. * the Unix epoch (1 January 1970 00:00:00 UTC).
  14872. *
  14873. * @static
  14874. * @memberOf _
  14875. * @since 2.4.0
  14876. * @category Date
  14877. * @returns {number} Returns the timestamp.
  14878. * @example
  14879. *
  14880. * _.defer(function(stamp) {
  14881. * console.log(_.now() - stamp);
  14882. * }, _.now());
  14883. * // => Logs the number of milliseconds it took for the deferred invocation.
  14884. */
  14885. var now = function() {
  14886. return root.Date.now();
  14887. };
  14888. module.exports = now;
  14889. /***/ }),
  14890. /* 62 */
  14891. /***/ (function(module, exports, __webpack_require__) {
  14892. /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
  14893. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  14894. module.exports = freeGlobal;
  14895. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8)))
  14896. /***/ }),
  14897. /* 63 */
  14898. /***/ (function(module, exports, __webpack_require__) {
  14899. var isObject = __webpack_require__(15),
  14900. isSymbol = __webpack_require__(64);
  14901. /** Used as references for various `Number` constants. */
  14902. var NAN = 0 / 0;
  14903. /** Used to match leading and trailing whitespace. */
  14904. var reTrim = /^\s+|\s+$/g;
  14905. /** Used to detect bad signed hexadecimal string values. */
  14906. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  14907. /** Used to detect binary string values. */
  14908. var reIsBinary = /^0b[01]+$/i;
  14909. /** Used to detect octal string values. */
  14910. var reIsOctal = /^0o[0-7]+$/i;
  14911. /** Built-in method references without a dependency on `root`. */
  14912. var freeParseInt = parseInt;
  14913. /**
  14914. * Converts `value` to a number.
  14915. *
  14916. * @static
  14917. * @memberOf _
  14918. * @since 4.0.0
  14919. * @category Lang
  14920. * @param {*} value The value to process.
  14921. * @returns {number} Returns the number.
  14922. * @example
  14923. *
  14924. * _.toNumber(3.2);
  14925. * // => 3.2
  14926. *
  14927. * _.toNumber(Number.MIN_VALUE);
  14928. * // => 5e-324
  14929. *
  14930. * _.toNumber(Infinity);
  14931. * // => Infinity
  14932. *
  14933. * _.toNumber('3.2');
  14934. * // => 3.2
  14935. */
  14936. function toNumber(value) {
  14937. if (typeof value == 'number') {
  14938. return value;
  14939. }
  14940. if (isSymbol(value)) {
  14941. return NAN;
  14942. }
  14943. if (isObject(value)) {
  14944. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  14945. value = isObject(other) ? (other + '') : other;
  14946. }
  14947. if (typeof value != 'string') {
  14948. return value === 0 ? value : +value;
  14949. }
  14950. value = value.replace(reTrim, '');
  14951. var isBinary = reIsBinary.test(value);
  14952. return (isBinary || reIsOctal.test(value))
  14953. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  14954. : (reIsBadHex.test(value) ? NAN : +value);
  14955. }
  14956. module.exports = toNumber;
  14957. /***/ }),
  14958. /* 64 */
  14959. /***/ (function(module, exports, __webpack_require__) {
  14960. var baseGetTag = __webpack_require__(65),
  14961. isObjectLike = __webpack_require__(68);
  14962. /** `Object#toString` result references. */
  14963. var symbolTag = '[object Symbol]';
  14964. /**
  14965. * Checks if `value` is classified as a `Symbol` primitive or object.
  14966. *
  14967. * @static
  14968. * @memberOf _
  14969. * @since 4.0.0
  14970. * @category Lang
  14971. * @param {*} value The value to check.
  14972. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  14973. * @example
  14974. *
  14975. * _.isSymbol(Symbol.iterator);
  14976. * // => true
  14977. *
  14978. * _.isSymbol('abc');
  14979. * // => false
  14980. */
  14981. function isSymbol(value) {
  14982. return typeof value == 'symbol' ||
  14983. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  14984. }
  14985. module.exports = isSymbol;
  14986. /***/ }),
  14987. /* 65 */
  14988. /***/ (function(module, exports, __webpack_require__) {
  14989. var Symbol = __webpack_require__(23),
  14990. getRawTag = __webpack_require__(66),
  14991. objectToString = __webpack_require__(67);
  14992. /** `Object#toString` result references. */
  14993. var nullTag = '[object Null]',
  14994. undefinedTag = '[object Undefined]';
  14995. /** Built-in value references. */
  14996. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  14997. /**
  14998. * The base implementation of `getTag` without fallbacks for buggy environments.
  14999. *
  15000. * @private
  15001. * @param {*} value The value to query.
  15002. * @returns {string} Returns the `toStringTag`.
  15003. */
  15004. function baseGetTag(value) {
  15005. if (value == null) {
  15006. return value === undefined ? undefinedTag : nullTag;
  15007. }
  15008. return (symToStringTag && symToStringTag in Object(value))
  15009. ? getRawTag(value)
  15010. : objectToString(value);
  15011. }
  15012. module.exports = baseGetTag;
  15013. /***/ }),
  15014. /* 66 */
  15015. /***/ (function(module, exports, __webpack_require__) {
  15016. var Symbol = __webpack_require__(23);
  15017. /** Used for built-in method references. */
  15018. var objectProto = Object.prototype;
  15019. /** Used to check objects for own properties. */
  15020. var hasOwnProperty = objectProto.hasOwnProperty;
  15021. /**
  15022. * Used to resolve the
  15023. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  15024. * of values.
  15025. */
  15026. var nativeObjectToString = objectProto.toString;
  15027. /** Built-in value references. */
  15028. var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
  15029. /**
  15030. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  15031. *
  15032. * @private
  15033. * @param {*} value The value to query.
  15034. * @returns {string} Returns the raw `toStringTag`.
  15035. */
  15036. function getRawTag(value) {
  15037. var isOwn = hasOwnProperty.call(value, symToStringTag),
  15038. tag = value[symToStringTag];
  15039. try {
  15040. value[symToStringTag] = undefined;
  15041. var unmasked = true;
  15042. } catch (e) {}
  15043. var result = nativeObjectToString.call(value);
  15044. if (unmasked) {
  15045. if (isOwn) {
  15046. value[symToStringTag] = tag;
  15047. } else {
  15048. delete value[symToStringTag];
  15049. }
  15050. }
  15051. return result;
  15052. }
  15053. module.exports = getRawTag;
  15054. /***/ }),
  15055. /* 67 */
  15056. /***/ (function(module, exports) {
  15057. /** Used for built-in method references. */
  15058. var objectProto = Object.prototype;
  15059. /**
  15060. * Used to resolve the
  15061. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  15062. * of values.
  15063. */
  15064. var nativeObjectToString = objectProto.toString;
  15065. /**
  15066. * Converts `value` to a string using `Object.prototype.toString`.
  15067. *
  15068. * @private
  15069. * @param {*} value The value to convert.
  15070. * @returns {string} Returns the converted string.
  15071. */
  15072. function objectToString(value) {
  15073. return nativeObjectToString.call(value);
  15074. }
  15075. module.exports = objectToString;
  15076. /***/ }),
  15077. /* 68 */
  15078. /***/ (function(module, exports) {
  15079. /**
  15080. * Checks if `value` is object-like. A value is object-like if it's not `null`
  15081. * and has a `typeof` result of "object".
  15082. *
  15083. * @static
  15084. * @memberOf _
  15085. * @since 4.0.0
  15086. * @category Lang
  15087. * @param {*} value The value to check.
  15088. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  15089. * @example
  15090. *
  15091. * _.isObjectLike({});
  15092. * // => true
  15093. *
  15094. * _.isObjectLike([1, 2, 3]);
  15095. * // => true
  15096. *
  15097. * _.isObjectLike(_.noop);
  15098. * // => false
  15099. *
  15100. * _.isObjectLike(null);
  15101. * // => false
  15102. */
  15103. function isObjectLike(value) {
  15104. return value != null && typeof value == 'object';
  15105. }
  15106. module.exports = isObjectLike;
  15107. /***/ }),
  15108. /* 69 */
  15109. /***/ (function(module, exports, __webpack_require__) {
  15110. "use strict";
  15111. Object.defineProperty(exports, "__esModule", {
  15112. value: true
  15113. });
  15114. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  15115. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  15116. var Views = function () {
  15117. function Views(container) {
  15118. _classCallCheck(this, Views);
  15119. this.container = container;
  15120. this._views = [];
  15121. this.length = 0;
  15122. this.hidden = false;
  15123. }
  15124. _createClass(Views, [{
  15125. key: "all",
  15126. value: function all() {
  15127. return this._views;
  15128. }
  15129. }, {
  15130. key: "first",
  15131. value: function first() {
  15132. return this._views[0];
  15133. }
  15134. }, {
  15135. key: "last",
  15136. value: function last() {
  15137. return this._views[this._views.length - 1];
  15138. }
  15139. }, {
  15140. key: "indexOf",
  15141. value: function indexOf(view) {
  15142. return this._views.indexOf(view);
  15143. }
  15144. }, {
  15145. key: "slice",
  15146. value: function slice() {
  15147. return this._views.slice.apply(this._views, arguments);
  15148. }
  15149. }, {
  15150. key: "get",
  15151. value: function get(i) {
  15152. return this._views[i];
  15153. }
  15154. }, {
  15155. key: "append",
  15156. value: function append(view) {
  15157. this._views.push(view);
  15158. if (this.container) {
  15159. this.container.appendChild(view.element);
  15160. }
  15161. this.length++;
  15162. return view;
  15163. }
  15164. }, {
  15165. key: "prepend",
  15166. value: function prepend(view) {
  15167. this._views.unshift(view);
  15168. if (this.container) {
  15169. this.container.insertBefore(view.element, this.container.firstChild);
  15170. }
  15171. this.length++;
  15172. return view;
  15173. }
  15174. }, {
  15175. key: "insert",
  15176. value: function insert(view, index) {
  15177. this._views.splice(index, 0, view);
  15178. if (this.container) {
  15179. if (index < this.container.children.length) {
  15180. this.container.insertBefore(view.element, this.container.children[index]);
  15181. } else {
  15182. this.container.appendChild(view.element);
  15183. }
  15184. }
  15185. this.length++;
  15186. return view;
  15187. }
  15188. }, {
  15189. key: "remove",
  15190. value: function remove(view) {
  15191. var index = this._views.indexOf(view);
  15192. if (index > -1) {
  15193. this._views.splice(index, 1);
  15194. }
  15195. this.destroy(view);
  15196. this.length--;
  15197. }
  15198. }, {
  15199. key: "destroy",
  15200. value: function destroy(view) {
  15201. if (view.displayed) {
  15202. view.destroy();
  15203. }
  15204. if (this.container) {
  15205. this.container.removeChild(view.element);
  15206. }
  15207. view = null;
  15208. }
  15209. // Iterators
  15210. }, {
  15211. key: "forEach",
  15212. value: function forEach() {
  15213. return this._views.forEach.apply(this._views, arguments);
  15214. }
  15215. }, {
  15216. key: "clear",
  15217. value: function clear() {
  15218. // Remove all views
  15219. var view;
  15220. var len = this.length;
  15221. if (!this.length) return;
  15222. for (var i = 0; i < len; i++) {
  15223. view = this._views[i];
  15224. this.destroy(view);
  15225. }
  15226. this._views = [];
  15227. this.length = 0;
  15228. }
  15229. }, {
  15230. key: "find",
  15231. value: function find(section) {
  15232. var view;
  15233. var len = this.length;
  15234. for (var i = 0; i < len; i++) {
  15235. view = this._views[i];
  15236. if (view.displayed && view.section.index == section.index) {
  15237. return view;
  15238. }
  15239. }
  15240. }
  15241. }, {
  15242. key: "displayed",
  15243. value: function displayed() {
  15244. var displayed = [];
  15245. var view;
  15246. var len = this.length;
  15247. for (var i = 0; i < len; i++) {
  15248. view = this._views[i];
  15249. if (view.displayed) {
  15250. displayed.push(view);
  15251. }
  15252. }
  15253. return displayed;
  15254. }
  15255. }, {
  15256. key: "show",
  15257. value: function show() {
  15258. var view;
  15259. var len = this.length;
  15260. for (var i = 0; i < len; i++) {
  15261. view = this._views[i];
  15262. if (view.displayed) {
  15263. view.show();
  15264. }
  15265. }
  15266. this.hidden = false;
  15267. }
  15268. }, {
  15269. key: "hide",
  15270. value: function hide() {
  15271. var view;
  15272. var len = this.length;
  15273. for (var i = 0; i < len; i++) {
  15274. view = this._views[i];
  15275. if (view.displayed) {
  15276. view.hide();
  15277. }
  15278. }
  15279. this.hidden = true;
  15280. }
  15281. }]);
  15282. return Views;
  15283. }();
  15284. exports.default = Views;
  15285. module.exports = exports["default"];
  15286. /***/ }),
  15287. /* 70 */
  15288. /***/ (function(module, exports, __webpack_require__) {
  15289. "use strict";
  15290. Object.defineProperty(exports, "__esModule", {
  15291. value: true
  15292. });
  15293. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  15294. var _core = __webpack_require__(0);
  15295. var _request = __webpack_require__(11);
  15296. var _request2 = _interopRequireDefault(_request);
  15297. var _mime = __webpack_require__(17);
  15298. var _mime2 = _interopRequireDefault(_mime);
  15299. var _path = __webpack_require__(4);
  15300. var _path2 = _interopRequireDefault(_path);
  15301. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15302. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  15303. /**
  15304. * Handles Unzipping a requesting files from an Epub Archive
  15305. * @class
  15306. */
  15307. var Archive = function () {
  15308. function Archive() {
  15309. _classCallCheck(this, Archive);
  15310. this.zip = undefined;
  15311. this.urlCache = {};
  15312. this.checkRequirements();
  15313. }
  15314. /**
  15315. * Checks to see if JSZip exists in global namspace,
  15316. * Requires JSZip if it isn't there
  15317. * @private
  15318. */
  15319. _createClass(Archive, [{
  15320. key: "checkRequirements",
  15321. value: function checkRequirements() {
  15322. try {
  15323. if (typeof JSZip === "undefined") {
  15324. var _JSZip = __webpack_require__(71);
  15325. this.zip = new _JSZip();
  15326. } else {
  15327. this.zip = new JSZip();
  15328. }
  15329. } catch (e) {
  15330. throw new Error("JSZip lib not loaded");
  15331. }
  15332. }
  15333. /**
  15334. * Open an archive
  15335. * @param {binary} input
  15336. * @param {boolean} [isBase64] tells JSZip if the input data is base64 encoded
  15337. * @return {Promise} zipfile
  15338. */
  15339. }, {
  15340. key: "open",
  15341. value: function open(input, isBase64) {
  15342. return this.zip.loadAsync(input, { "base64": isBase64 });
  15343. }
  15344. /**
  15345. * Load and Open an archive
  15346. * @param {string} zipUrl
  15347. * @param {boolean} [isBase64] tells JSZip if the input data is base64 encoded
  15348. * @return {Promise} zipfile
  15349. */
  15350. }, {
  15351. key: "openUrl",
  15352. value: function openUrl(zipUrl, isBase64) {
  15353. return (0, _request2.default)(zipUrl, "binary").then(function (data) {
  15354. return this.zip.loadAsync(data, { "base64": isBase64 });
  15355. }.bind(this));
  15356. }
  15357. /**
  15358. * Request a url from the archive
  15359. * @param {string} url a url to request from the archive
  15360. * @param {string} [type] specify the type of the returned result
  15361. * @return {Promise<Blob | string | JSON | Document | XMLDocument>}
  15362. */
  15363. }, {
  15364. key: "request",
  15365. value: function request(url, type) {
  15366. var deferred = new _core.defer();
  15367. var response;
  15368. var path = new _path2.default(url);
  15369. // If type isn't set, determine it from the file extension
  15370. if (!type) {
  15371. type = path.extension;
  15372. }
  15373. if (type == "blob") {
  15374. response = this.getBlob(url);
  15375. } else {
  15376. response = this.getText(url);
  15377. }
  15378. if (response) {
  15379. response.then(function (r) {
  15380. var result = this.handleResponse(r, type);
  15381. deferred.resolve(result);
  15382. }.bind(this));
  15383. } else {
  15384. deferred.reject({
  15385. message: "File not found in the epub: " + url,
  15386. stack: new Error().stack
  15387. });
  15388. }
  15389. return deferred.promise;
  15390. }
  15391. /**
  15392. * Handle the response from request
  15393. * @private
  15394. * @param {any} response
  15395. * @param {string} [type]
  15396. * @return {any} the parsed result
  15397. */
  15398. }, {
  15399. key: "handleResponse",
  15400. value: function handleResponse(response, type) {
  15401. var r;
  15402. if (type == "json") {
  15403. r = JSON.parse(response);
  15404. } else if ((0, _core.isXml)(type)) {
  15405. r = (0, _core.parse)(response, "text/xml");
  15406. } else if (type == "xhtml") {
  15407. r = (0, _core.parse)(response, "application/xhtml+xml");
  15408. } else if (type == "html" || type == "htm") {
  15409. r = (0, _core.parse)(response, "text/html");
  15410. } else {
  15411. r = response;
  15412. }
  15413. return r;
  15414. }
  15415. /**
  15416. * Get a Blob from Archive by Url
  15417. * @param {string} url
  15418. * @param {string} [mimeType]
  15419. * @return {Blob}
  15420. */
  15421. }, {
  15422. key: "getBlob",
  15423. value: function getBlob(url, mimeType) {
  15424. var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash
  15425. var entry = this.zip.file(decodededUrl);
  15426. if (entry) {
  15427. mimeType = mimeType || _mime2.default.lookup(entry.name);
  15428. return entry.async("uint8array").then(function (uint8array) {
  15429. return new Blob([uint8array], { type: mimeType });
  15430. });
  15431. }
  15432. }
  15433. /**
  15434. * Get Text from Archive by Url
  15435. * @param {string} url
  15436. * @param {string} [encoding]
  15437. * @return {string}
  15438. */
  15439. }, {
  15440. key: "getText",
  15441. value: function getText(url, encoding) {
  15442. var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash
  15443. var entry = this.zip.file(decodededUrl);
  15444. if (entry) {
  15445. return entry.async("string").then(function (text) {
  15446. return text;
  15447. });
  15448. }
  15449. }
  15450. /**
  15451. * Get a base64 encoded result from Archive by Url
  15452. * @param {string} url
  15453. * @param {string} [mimeType]
  15454. * @return {string} base64 encoded
  15455. */
  15456. }, {
  15457. key: "getBase64",
  15458. value: function getBase64(url, mimeType) {
  15459. var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash
  15460. var entry = this.zip.file(decodededUrl);
  15461. if (entry) {
  15462. mimeType = mimeType || _mime2.default.lookup(entry.name);
  15463. return entry.async("base64").then(function (data) {
  15464. return "data:" + mimeType + ";base64," + data;
  15465. });
  15466. }
  15467. }
  15468. /**
  15469. * Create a Url from an unarchived item
  15470. * @param {string} url
  15471. * @param {object} [options.base64] use base64 encoding or blob url
  15472. * @return {Promise} url promise with Url string
  15473. */
  15474. }, {
  15475. key: "createUrl",
  15476. value: function createUrl(url, options) {
  15477. var deferred = new _core.defer();
  15478. var _URL = window.URL || window.webkitURL || window.mozURL;
  15479. var tempUrl;
  15480. var response;
  15481. var useBase64 = options && options.base64;
  15482. if (url in this.urlCache) {
  15483. deferred.resolve(this.urlCache[url]);
  15484. return deferred.promise;
  15485. }
  15486. if (useBase64) {
  15487. response = this.getBase64(url);
  15488. if (response) {
  15489. response.then(function (tempUrl) {
  15490. this.urlCache[url] = tempUrl;
  15491. deferred.resolve(tempUrl);
  15492. }.bind(this));
  15493. }
  15494. } else {
  15495. response = this.getBlob(url);
  15496. if (response) {
  15497. response.then(function (blob) {
  15498. tempUrl = _URL.createObjectURL(blob);
  15499. this.urlCache[url] = tempUrl;
  15500. deferred.resolve(tempUrl);
  15501. }.bind(this));
  15502. }
  15503. }
  15504. if (!response) {
  15505. deferred.reject({
  15506. message: "File not found in the epub: " + url,
  15507. stack: new Error().stack
  15508. });
  15509. }
  15510. return deferred.promise;
  15511. }
  15512. /**
  15513. * Revoke Temp Url for a achive item
  15514. * @param {string} url url of the item in the archive
  15515. */
  15516. }, {
  15517. key: "revokeUrl",
  15518. value: function revokeUrl(url) {
  15519. var _URL = window.URL || window.webkitURL || window.mozURL;
  15520. var fromCache = this.urlCache[url];
  15521. if (fromCache) _URL.revokeObjectURL(fromCache);
  15522. }
  15523. }, {
  15524. key: "destroy",
  15525. value: function destroy() {
  15526. var _URL = window.URL || window.webkitURL || window.mozURL;
  15527. for (var fromCache in this.urlCache) {
  15528. _URL.revokeObjectURL(fromCache);
  15529. }
  15530. this.zip = undefined;
  15531. this.urlCache = {};
  15532. }
  15533. }]);
  15534. return Archive;
  15535. }();
  15536. exports.default = Archive;
  15537. module.exports = exports["default"];
  15538. /***/ }),
  15539. /* 71 */
  15540. /***/ (function(module, exports) {
  15541. if(typeof __WEBPACK_EXTERNAL_MODULE_71__ === 'undefined') {var e = new Error("Cannot find module \"jszip\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  15542. module.exports = __WEBPACK_EXTERNAL_MODULE_71__;
  15543. /***/ }),
  15544. /* 72 */
  15545. /***/ (function(module, exports, __webpack_require__) {
  15546. "use strict";
  15547. /* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* From https://github.com/webcomponents/URL/blob/master/url.js
  15548. * Added UMD, file link handling */
  15549. /* Any copyright is dedicated to the Public Domain.
  15550. * http://creativecommons.org/publicdomain/zero/1.0/ */
  15551. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  15552. (function (root, factory) {
  15553. // Fix for this being undefined in modules
  15554. if (!root) {
  15555. root = window || global;
  15556. }
  15557. if (( false ? 'undefined' : _typeof(module)) === 'object' && module.exports) {
  15558. // Node
  15559. module.exports = factory(root);
  15560. } else if (true) {
  15561. // AMD. Register as an anonymous module.
  15562. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
  15563. __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
  15564. (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
  15565. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  15566. } else {
  15567. // Browser globals (root is window)
  15568. root.URL = factory(root);
  15569. }
  15570. })(undefined, function (scope) {
  15571. // feature detect for URL constructor
  15572. var hasWorkingUrl = false;
  15573. if (!scope.forceJURL) {
  15574. try {
  15575. var u = new URL('b', 'http://a');
  15576. u.pathname = 'c%20d';
  15577. hasWorkingUrl = u.href === 'http://a/c%20d';
  15578. } catch (e) {}
  15579. }
  15580. if (hasWorkingUrl) return scope.URL;
  15581. var relative = Object.create(null);
  15582. relative['ftp'] = 21;
  15583. relative['file'] = 0;
  15584. relative['gopher'] = 70;
  15585. relative['http'] = 80;
  15586. relative['https'] = 443;
  15587. relative['ws'] = 80;
  15588. relative['wss'] = 443;
  15589. var relativePathDotMapping = Object.create(null);
  15590. relativePathDotMapping['%2e'] = '.';
  15591. relativePathDotMapping['.%2e'] = '..';
  15592. relativePathDotMapping['%2e.'] = '..';
  15593. relativePathDotMapping['%2e%2e'] = '..';
  15594. function isRelativeScheme(scheme) {
  15595. return relative[scheme] !== undefined;
  15596. }
  15597. function invalid() {
  15598. clear.call(this);
  15599. this._isInvalid = true;
  15600. }
  15601. function IDNAToASCII(h) {
  15602. if ('' == h) {
  15603. invalid.call(this);
  15604. }
  15605. // XXX
  15606. return h.toLowerCase();
  15607. }
  15608. function percentEscape(c) {
  15609. var unicode = c.charCodeAt(0);
  15610. if (unicode > 0x20 && unicode < 0x7F &&
  15611. // " # < > ? `
  15612. [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1) {
  15613. return c;
  15614. }
  15615. return encodeURIComponent(c);
  15616. }
  15617. function percentEscapeQuery(c) {
  15618. // XXX This actually needs to encode c using encoding and then
  15619. // convert the bytes one-by-one.
  15620. var unicode = c.charCodeAt(0);
  15621. if (unicode > 0x20 && unicode < 0x7F &&
  15622. // " # < > ` (do not escape '?')
  15623. [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1) {
  15624. return c;
  15625. }
  15626. return encodeURIComponent(c);
  15627. }
  15628. var EOF = undefined,
  15629. ALPHA = /[a-zA-Z]/,
  15630. ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  15631. function parse(input, stateOverride, base) {
  15632. function err(message) {
  15633. errors.push(message);
  15634. }
  15635. var state = stateOverride || 'scheme start',
  15636. cursor = 0,
  15637. buffer = '',
  15638. seenAt = false,
  15639. seenBracket = false,
  15640. errors = [];
  15641. loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) {
  15642. var c = input[cursor];
  15643. switch (state) {
  15644. case 'scheme start':
  15645. if (c && ALPHA.test(c)) {
  15646. buffer += c.toLowerCase(); // ASCII-safe
  15647. state = 'scheme';
  15648. } else if (!stateOverride) {
  15649. buffer = '';
  15650. state = 'no scheme';
  15651. continue;
  15652. } else {
  15653. err('Invalid scheme.');
  15654. break loop;
  15655. }
  15656. break;
  15657. case 'scheme':
  15658. if (c && ALPHANUMERIC.test(c)) {
  15659. buffer += c.toLowerCase(); // ASCII-safe
  15660. } else if (':' == c) {
  15661. this._scheme = buffer;
  15662. buffer = '';
  15663. if (stateOverride) {
  15664. break loop;
  15665. }
  15666. if (isRelativeScheme(this._scheme)) {
  15667. this._isRelative = true;
  15668. }
  15669. if ('file' == this._scheme) {
  15670. state = 'relative';
  15671. } else if (this._isRelative && base && base._scheme == this._scheme) {
  15672. state = 'relative or authority';
  15673. } else if (this._isRelative) {
  15674. state = 'authority first slash';
  15675. } else {
  15676. state = 'scheme data';
  15677. }
  15678. } else if (!stateOverride) {
  15679. buffer = '';
  15680. cursor = 0;
  15681. state = 'no scheme';
  15682. continue;
  15683. } else if (EOF == c) {
  15684. break loop;
  15685. } else {
  15686. err('Code point not allowed in scheme: ' + c);
  15687. break loop;
  15688. }
  15689. break;
  15690. case 'scheme data':
  15691. if ('?' == c) {
  15692. this._query = '?';
  15693. state = 'query';
  15694. } else if ('#' == c) {
  15695. this._fragment = '#';
  15696. state = 'fragment';
  15697. } else {
  15698. // XXX error handling
  15699. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  15700. this._schemeData += percentEscape(c);
  15701. }
  15702. }
  15703. break;
  15704. case 'no scheme':
  15705. if (!base || !isRelativeScheme(base._scheme)) {
  15706. err('Missing scheme.');
  15707. invalid.call(this);
  15708. } else {
  15709. state = 'relative';
  15710. continue;
  15711. }
  15712. break;
  15713. case 'relative or authority':
  15714. if ('/' == c && '/' == input[cursor + 1]) {
  15715. state = 'authority ignore slashes';
  15716. } else {
  15717. err('Expected /, got: ' + c);
  15718. state = 'relative';
  15719. continue;
  15720. }
  15721. break;
  15722. case 'relative':
  15723. this._isRelative = true;
  15724. if ('file' != this._scheme) this._scheme = base._scheme;
  15725. if (EOF == c) {
  15726. this._host = base._host;
  15727. this._port = base._port;
  15728. this._path = base._path.slice();
  15729. this._query = base._query;
  15730. this._username = base._username;
  15731. this._password = base._password;
  15732. break loop;
  15733. } else if ('/' == c || '\\' == c) {
  15734. if ('\\' == c) err('\\ is an invalid code point.');
  15735. state = 'relative slash';
  15736. } else if ('?' == c) {
  15737. this._host = base._host;
  15738. this._port = base._port;
  15739. this._path = base._path.slice();
  15740. this._query = '?';
  15741. this._username = base._username;
  15742. this._password = base._password;
  15743. state = 'query';
  15744. } else if ('#' == c) {
  15745. this._host = base._host;
  15746. this._port = base._port;
  15747. this._path = base._path.slice();
  15748. this._query = base._query;
  15749. this._fragment = '#';
  15750. this._username = base._username;
  15751. this._password = base._password;
  15752. state = 'fragment';
  15753. } else {
  15754. var nextC = input[cursor + 1];
  15755. var nextNextC = input[cursor + 2];
  15756. if ('file' != this._scheme || !ALPHA.test(c) || nextC != ':' && nextC != '|' || EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC) {
  15757. this._host = base._host;
  15758. this._port = base._port;
  15759. this._username = base._username;
  15760. this._password = base._password;
  15761. this._path = base._path.slice();
  15762. this._path.pop();
  15763. }
  15764. state = 'relative path';
  15765. continue;
  15766. }
  15767. break;
  15768. case 'relative slash':
  15769. if ('/' == c || '\\' == c) {
  15770. if ('\\' == c) {
  15771. err('\\ is an invalid code point.');
  15772. }
  15773. if ('file' == this._scheme) {
  15774. state = 'file host';
  15775. } else {
  15776. state = 'authority ignore slashes';
  15777. }
  15778. } else {
  15779. if ('file' != this._scheme) {
  15780. this._host = base._host;
  15781. this._port = base._port;
  15782. this._username = base._username;
  15783. this._password = base._password;
  15784. }
  15785. state = 'relative path';
  15786. continue;
  15787. }
  15788. break;
  15789. case 'authority first slash':
  15790. if ('/' == c) {
  15791. state = 'authority second slash';
  15792. } else {
  15793. err("Expected '/', got: " + c);
  15794. state = 'authority ignore slashes';
  15795. continue;
  15796. }
  15797. break;
  15798. case 'authority second slash':
  15799. state = 'authority ignore slashes';
  15800. if ('/' != c) {
  15801. err("Expected '/', got: " + c);
  15802. continue;
  15803. }
  15804. break;
  15805. case 'authority ignore slashes':
  15806. if ('/' != c && '\\' != c) {
  15807. state = 'authority';
  15808. continue;
  15809. } else {
  15810. err('Expected authority, got: ' + c);
  15811. }
  15812. break;
  15813. case 'authority':
  15814. if ('@' == c) {
  15815. if (seenAt) {
  15816. err('@ already seen.');
  15817. buffer += '%40';
  15818. }
  15819. seenAt = true;
  15820. for (var i = 0; i < buffer.length; i++) {
  15821. var cp = buffer[i];
  15822. if ('\t' == cp || '\n' == cp || '\r' == cp) {
  15823. err('Invalid whitespace in authority.');
  15824. continue;
  15825. }
  15826. // XXX check URL code points
  15827. if (':' == cp && null === this._password) {
  15828. this._password = '';
  15829. continue;
  15830. }
  15831. var tempC = percentEscape(cp);
  15832. null !== this._password ? this._password += tempC : this._username += tempC;
  15833. }
  15834. buffer = '';
  15835. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  15836. cursor -= buffer.length;
  15837. buffer = '';
  15838. state = 'host';
  15839. continue;
  15840. } else {
  15841. buffer += c;
  15842. }
  15843. break;
  15844. case 'file host':
  15845. if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  15846. if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) {
  15847. state = 'relative path';
  15848. } else if (buffer.length == 0) {
  15849. state = 'relative path start';
  15850. } else {
  15851. this._host = IDNAToASCII.call(this, buffer);
  15852. buffer = '';
  15853. state = 'relative path start';
  15854. }
  15855. continue;
  15856. } else if ('\t' == c || '\n' == c || '\r' == c) {
  15857. err('Invalid whitespace in file host.');
  15858. } else {
  15859. buffer += c;
  15860. }
  15861. break;
  15862. case 'host':
  15863. case 'hostname':
  15864. if (':' == c && !seenBracket) {
  15865. // XXX host parsing
  15866. this._host = IDNAToASCII.call(this, buffer);
  15867. buffer = '';
  15868. state = 'port';
  15869. if ('hostname' == stateOverride) {
  15870. break loop;
  15871. }
  15872. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) {
  15873. this._host = IDNAToASCII.call(this, buffer);
  15874. buffer = '';
  15875. state = 'relative path start';
  15876. if (stateOverride) {
  15877. break loop;
  15878. }
  15879. continue;
  15880. } else if ('\t' != c && '\n' != c && '\r' != c) {
  15881. if ('[' == c) {
  15882. seenBracket = true;
  15883. } else if (']' == c) {
  15884. seenBracket = false;
  15885. }
  15886. buffer += c;
  15887. } else {
  15888. err('Invalid code point in host/hostname: ' + c);
  15889. }
  15890. break;
  15891. case 'port':
  15892. if (/[0-9]/.test(c)) {
  15893. buffer += c;
  15894. } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) {
  15895. if ('' != buffer) {
  15896. var temp = parseInt(buffer, 10);
  15897. if (temp != relative[this._scheme]) {
  15898. this._port = temp + '';
  15899. }
  15900. buffer = '';
  15901. }
  15902. if (stateOverride) {
  15903. break loop;
  15904. }
  15905. state = 'relative path start';
  15906. continue;
  15907. } else if ('\t' == c || '\n' == c || '\r' == c) {
  15908. err('Invalid code point in port: ' + c);
  15909. } else {
  15910. invalid.call(this);
  15911. }
  15912. break;
  15913. case 'relative path start':
  15914. if ('\\' == c) err("'\\' not allowed in path.");
  15915. state = 'relative path';
  15916. if ('/' != c && '\\' != c) {
  15917. continue;
  15918. }
  15919. break;
  15920. case 'relative path':
  15921. if (EOF == c || '/' == c || '\\' == c || !stateOverride && ('?' == c || '#' == c)) {
  15922. if ('\\' == c) {
  15923. err('\\ not allowed in relative path.');
  15924. }
  15925. var tmp;
  15926. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  15927. buffer = tmp;
  15928. }
  15929. if ('..' == buffer) {
  15930. this._path.pop();
  15931. if ('/' != c && '\\' != c) {
  15932. this._path.push('');
  15933. }
  15934. } else if ('.' == buffer && '/' != c && '\\' != c) {
  15935. this._path.push('');
  15936. } else if ('.' != buffer) {
  15937. if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') {
  15938. buffer = buffer[0] + ':';
  15939. }
  15940. this._path.push(buffer);
  15941. }
  15942. buffer = '';
  15943. if ('?' == c) {
  15944. this._query = '?';
  15945. state = 'query';
  15946. } else if ('#' == c) {
  15947. this._fragment = '#';
  15948. state = 'fragment';
  15949. }
  15950. } else if ('\t' != c && '\n' != c && '\r' != c) {
  15951. buffer += percentEscape(c);
  15952. }
  15953. break;
  15954. case 'query':
  15955. if (!stateOverride && '#' == c) {
  15956. this._fragment = '#';
  15957. state = 'fragment';
  15958. } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  15959. this._query += percentEscapeQuery(c);
  15960. }
  15961. break;
  15962. case 'fragment':
  15963. if (EOF != c && '\t' != c && '\n' != c && '\r' != c) {
  15964. this._fragment += c;
  15965. }
  15966. break;
  15967. }
  15968. cursor++;
  15969. }
  15970. }
  15971. function clear() {
  15972. this._scheme = '';
  15973. this._schemeData = '';
  15974. this._username = '';
  15975. this._password = null;
  15976. this._host = '';
  15977. this._port = '';
  15978. this._path = [];
  15979. this._query = '';
  15980. this._fragment = '';
  15981. this._isInvalid = false;
  15982. this._isRelative = false;
  15983. }
  15984. // Does not process domain names or IP addresses.
  15985. // Does not handle encoding for the query parameter.
  15986. function jURL(url, base /* , encoding */) {
  15987. if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base));
  15988. this._url = url;
  15989. clear.call(this);
  15990. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  15991. // encoding = encoding || 'utf-8'
  15992. parse.call(this, input, null, base);
  15993. }
  15994. jURL.prototype = {
  15995. toString: function toString() {
  15996. return this.href;
  15997. },
  15998. get href() {
  15999. if (this._isInvalid) return this._url;
  16000. var authority = '';
  16001. if ('' != this._username || null != this._password) {
  16002. authority = this._username + (null != this._password ? ':' + this._password : '') + '@';
  16003. }
  16004. return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment;
  16005. },
  16006. set href(href) {
  16007. clear.call(this);
  16008. parse.call(this, href);
  16009. },
  16010. get protocol() {
  16011. return this._scheme + ':';
  16012. },
  16013. set protocol(protocol) {
  16014. if (this._isInvalid) return;
  16015. parse.call(this, protocol + ':', 'scheme start');
  16016. },
  16017. get host() {
  16018. return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host;
  16019. },
  16020. set host(host) {
  16021. if (this._isInvalid || !this._isRelative) return;
  16022. parse.call(this, host, 'host');
  16023. },
  16024. get hostname() {
  16025. return this._host;
  16026. },
  16027. set hostname(hostname) {
  16028. if (this._isInvalid || !this._isRelative) return;
  16029. parse.call(this, hostname, 'hostname');
  16030. },
  16031. get port() {
  16032. return this._port;
  16033. },
  16034. set port(port) {
  16035. if (this._isInvalid || !this._isRelative) return;
  16036. parse.call(this, port, 'port');
  16037. },
  16038. get pathname() {
  16039. return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData;
  16040. },
  16041. set pathname(pathname) {
  16042. if (this._isInvalid || !this._isRelative) return;
  16043. this._path = [];
  16044. parse.call(this, pathname, 'relative path start');
  16045. },
  16046. get search() {
  16047. return this._isInvalid || !this._query || '?' == this._query ? '' : this._query;
  16048. },
  16049. set search(search) {
  16050. if (this._isInvalid || !this._isRelative) return;
  16051. this._query = '?';
  16052. if ('?' == search[0]) search = search.slice(1);
  16053. parse.call(this, search, 'query');
  16054. },
  16055. get hash() {
  16056. return this._isInvalid || !this._fragment || '#' == this._fragment ? '' : this._fragment;
  16057. },
  16058. set hash(hash) {
  16059. if (this._isInvalid) return;
  16060. this._fragment = '#';
  16061. if ('#' == hash[0]) hash = hash.slice(1);
  16062. parse.call(this, hash, 'fragment');
  16063. },
  16064. get origin() {
  16065. var host;
  16066. if (this._isInvalid || !this._scheme) {
  16067. return '';
  16068. }
  16069. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  16070. // Gecko throws error for "data://"
  16071. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  16072. // Gecko returns String("") for file: mailto:
  16073. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  16074. switch (this._scheme) {
  16075. case 'file':
  16076. return 'file://'; // EPUBJS Added
  16077. case 'data':
  16078. case 'javascript':
  16079. case 'mailto':
  16080. return 'null';
  16081. }
  16082. host = this.host;
  16083. if (!host) {
  16084. return '';
  16085. }
  16086. return this._scheme + '://' + host;
  16087. }
  16088. };
  16089. // Copy over the static methods
  16090. var OriginalURL = scope.URL;
  16091. if (OriginalURL) {
  16092. jURL.createObjectURL = function (blob) {
  16093. // IE extension allows a second optional options argument.
  16094. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  16095. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  16096. };
  16097. jURL.revokeObjectURL = function (url) {
  16098. OriginalURL.revokeObjectURL(url);
  16099. };
  16100. }
  16101. return jURL;
  16102. });
  16103. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8), __webpack_require__(73)(module)))
  16104. /***/ }),
  16105. /* 73 */
  16106. /***/ (function(module, exports) {
  16107. module.exports = function(module) {
  16108. if(!module.webpackPolyfill) {
  16109. module.deprecate = function() {};
  16110. module.paths = [];
  16111. // module.parent = undefined by default
  16112. if(!module.children) module.children = [];
  16113. Object.defineProperty(module, "loaded", {
  16114. enumerable: true,
  16115. get: function() {
  16116. return module.l;
  16117. }
  16118. });
  16119. Object.defineProperty(module, "id", {
  16120. enumerable: true,
  16121. get: function() {
  16122. return module.i;
  16123. }
  16124. });
  16125. module.webpackPolyfill = 1;
  16126. }
  16127. return module;
  16128. };
  16129. /***/ })
  16130. /******/ ]);
  16131. });
  16132. //# sourceMappingURL=epub.js.map