summernote.js 202 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145
  1. /**
  2. * Super simple wysiwyg editor v0.0.0-SNAPSHOT
  3. * http://summernote.org/
  4. *
  5. * summernote.js
  6. * Copyright 2013-2016 Alan Hong. and other contributors
  7. * summernote may be freely distributed under the MIT license./
  8. *
  9. * Date: 2020-06-24T01:17Z
  10. */
  11. (function (factory) {
  12. /* global define */
  13. if (typeof define === 'function' && define.amd) {
  14. // AMD. Register as an anonymous module.
  15. define(['jquery'], factory);
  16. } else if (typeof module === 'object' && module.exports) {
  17. // Node/CommonJS
  18. module.exports = factory(require('jquery'));
  19. } else {
  20. // Browser globals
  21. factory(window.jQuery);
  22. }
  23. }(function ($) {
  24. 'use strict';
  25. /**
  26. * @class core.func
  27. *
  28. * func utils (for high-order func's arg)
  29. *
  30. * @singleton
  31. * @alternateClassName func
  32. */
  33. var func = (function () {
  34. var eq = function (itemA) {
  35. return function (itemB) {
  36. return itemA === itemB;
  37. };
  38. };
  39. var eq2 = function (itemA, itemB) {
  40. return itemA === itemB;
  41. };
  42. var peq2 = function (propName) {
  43. return function (itemA, itemB) {
  44. return itemA[propName] === itemB[propName];
  45. };
  46. };
  47. var ok = function () {
  48. return true;
  49. };
  50. var fail = function () {
  51. return false;
  52. };
  53. var not = function (f) {
  54. return function () {
  55. return !f.apply(f, arguments);
  56. };
  57. };
  58. var and = function (fA, fB) {
  59. return function (item) {
  60. return fA(item) && fB(item);
  61. };
  62. };
  63. var self = function (a) {
  64. return a;
  65. };
  66. var invoke = function (obj, method) {
  67. return function () {
  68. return obj[method].apply(obj, arguments);
  69. };
  70. };
  71. var idCounter = 0;
  72. /**
  73. * generate a globally-unique id
  74. *
  75. * @param {String} [prefix]
  76. */
  77. var uniqueId = function (prefix) {
  78. var id = ++idCounter + '';
  79. return prefix ? prefix + id : id;
  80. };
  81. /**
  82. * returns bnd (bounds) from rect
  83. *
  84. * - IE Compatibility Issue: http://goo.gl/sRLOAo
  85. * - Scroll Issue: http://goo.gl/sNjUc
  86. *
  87. * @param {Rect} rect
  88. * @return {Object} bounds
  89. * @return {Number} bounds.top
  90. * @return {Number} bounds.left
  91. * @return {Number} bounds.width
  92. * @return {Number} bounds.height
  93. */
  94. var rect2bnd = function (rect) {
  95. var $document = $(document);
  96. return {
  97. top: rect.top + $document.scrollTop(),
  98. left: rect.left + $document.scrollLeft(),
  99. width: rect.right - rect.left,
  100. height: rect.bottom - rect.top
  101. };
  102. };
  103. /**
  104. * returns a copy of the object where the keys have become the values and the values the keys.
  105. * @param {Object} obj
  106. * @return {Object}
  107. */
  108. var invertObject = function (obj) {
  109. var inverted = {};
  110. for (var key in obj) {
  111. if (obj.hasOwnProperty(key)) {
  112. inverted[obj[key]] = key;
  113. }
  114. }
  115. return inverted;
  116. };
  117. /**
  118. * @param {String} namespace
  119. * @param {String} [prefix]
  120. * @return {String}
  121. */
  122. var namespaceToCamel = function (namespace, prefix) {
  123. prefix = prefix || '';
  124. return prefix + namespace.split('.').map(function (name) {
  125. return name.substring(0, 1).toUpperCase() + name.substring(1);
  126. }).join('');
  127. };
  128. /**
  129. * Returns a function, that, as long as it continues to be invoked, will not
  130. * be triggered. The function will be called after it stops being called for
  131. * N milliseconds. If `immediate` is passed, trigger the function on the
  132. * leading edge, instead of the trailing.
  133. * @param {Function} func
  134. * @param {Number} wait
  135. * @param {Boolean} immediate
  136. * @return {Function}
  137. */
  138. var debounce = function (func, wait, immediate) {
  139. var timeout;
  140. return function () {
  141. var context = this, args = arguments;
  142. var later = function () {
  143. timeout = null;
  144. if (!immediate) {
  145. func.apply(context, args);
  146. }
  147. };
  148. var callNow = immediate && !timeout;
  149. clearTimeout(timeout);
  150. timeout = setTimeout(later, wait);
  151. if (callNow) {
  152. func.apply(context, args);
  153. }
  154. };
  155. };
  156. return {
  157. eq: eq,
  158. eq2: eq2,
  159. peq2: peq2,
  160. ok: ok,
  161. fail: fail,
  162. self: self,
  163. not: not,
  164. and: and,
  165. invoke: invoke,
  166. uniqueId: uniqueId,
  167. rect2bnd: rect2bnd,
  168. invertObject: invertObject,
  169. namespaceToCamel: namespaceToCamel,
  170. debounce: debounce
  171. };
  172. })();
  173. /**
  174. * @class core.list
  175. *
  176. * list utils
  177. *
  178. * @singleton
  179. * @alternateClassName list
  180. */
  181. var list = (function () {
  182. /**
  183. * returns the first item of an array.
  184. *
  185. * @param {Array} array
  186. */
  187. var head = function (array) {
  188. return array[0];
  189. };
  190. /**
  191. * returns the last item of an array.
  192. *
  193. * @param {Array} array
  194. */
  195. var last = function (array) {
  196. return array[array.length - 1];
  197. };
  198. /**
  199. * returns everything but the last entry of the array.
  200. *
  201. * @param {Array} array
  202. */
  203. var initial = function (array) {
  204. return array.slice(0, array.length - 1);
  205. };
  206. /**
  207. * returns the rest of the items in an array.
  208. *
  209. * @param {Array} array
  210. */
  211. var tail = function (array) {
  212. return array.slice(1);
  213. };
  214. /**
  215. * returns item of array
  216. */
  217. var find = function (array, pred) {
  218. for (var idx = 0, len = array.length; idx < len; idx ++) {
  219. var item = array[idx];
  220. if (pred(item)) {
  221. return item;
  222. }
  223. }
  224. };
  225. /**
  226. * returns true if all of the values in the array pass the predicate truth test.
  227. */
  228. var all = function (array, pred) {
  229. for (var idx = 0, len = array.length; idx < len; idx ++) {
  230. if (!pred(array[idx])) {
  231. return false;
  232. }
  233. }
  234. return true;
  235. };
  236. /**
  237. * returns index of item
  238. */
  239. var indexOf = function (array, item) {
  240. return $.inArray(item, array);
  241. };
  242. /**
  243. * returns true if the value is present in the list.
  244. */
  245. var contains = function (array, item) {
  246. return indexOf(array, item) !== -1;
  247. };
  248. /**
  249. * get sum from a list
  250. *
  251. * @param {Array} array - array
  252. * @param {Function} fn - iterator
  253. */
  254. var sum = function (array, fn) {
  255. fn = fn || func.self;
  256. return array.reduce(function (memo, v) {
  257. return memo + fn(v);
  258. }, 0);
  259. };
  260. /**
  261. * returns a copy of the collection with array type.
  262. * @param {Collection} collection - collection eg) node.childNodes, ...
  263. */
  264. var from = function (collection) {
  265. var result = [], idx = -1, length = collection.length;
  266. while (++idx < length) {
  267. result[idx] = collection[idx];
  268. }
  269. return result;
  270. };
  271. /**
  272. * returns whether list is empty or not
  273. */
  274. var isEmpty = function (array) {
  275. return !array || !array.length;
  276. };
  277. /**
  278. * cluster elements by predicate function.
  279. *
  280. * @param {Array} array - array
  281. * @param {Function} fn - predicate function for cluster rule
  282. * @param {Array[]}
  283. */
  284. var clusterBy = function (array, fn) {
  285. if (!array.length) { return []; }
  286. var aTail = tail(array);
  287. return aTail.reduce(function (memo, v) {
  288. var aLast = last(memo);
  289. if (fn(last(aLast), v)) {
  290. aLast[aLast.length] = v;
  291. } else {
  292. memo[memo.length] = [v];
  293. }
  294. return memo;
  295. }, [[head(array)]]);
  296. };
  297. /**
  298. * returns a copy of the array with all false values removed
  299. *
  300. * @param {Array} array - array
  301. * @param {Function} fn - predicate function for cluster rule
  302. */
  303. var compact = function (array) {
  304. var aResult = [];
  305. for (var idx = 0, len = array.length; idx < len; idx ++) {
  306. if (array[idx]) { aResult.push(array[idx]); }
  307. }
  308. return aResult;
  309. };
  310. /**
  311. * produces a duplicate-free version of the array
  312. *
  313. * @param {Array} array
  314. */
  315. var unique = function (array) {
  316. var results = [];
  317. for (var idx = 0, len = array.length; idx < len; idx ++) {
  318. if (!contains(results, array[idx])) {
  319. results.push(array[idx]);
  320. }
  321. }
  322. return results;
  323. };
  324. /**
  325. * returns next item.
  326. * @param {Array} array
  327. */
  328. var next = function (array, item) {
  329. var idx = indexOf(array, item);
  330. if (idx === -1) { return null; }
  331. return array[idx + 1];
  332. };
  333. /**
  334. * returns prev item.
  335. * @param {Array} array
  336. */
  337. var prev = function (array, item) {
  338. var idx = indexOf(array, item);
  339. if (idx === -1) { return null; }
  340. return array[idx - 1];
  341. };
  342. return { head: head, last: last, initial: initial, tail: tail,
  343. prev: prev, next: next, find: find, contains: contains,
  344. all: all, sum: sum, from: from, isEmpty: isEmpty,
  345. clusterBy: clusterBy, compact: compact, unique: unique };
  346. })();
  347. var isSupportAmd = typeof define === 'function' && define.amd;
  348. /**
  349. * returns whether font is installed or not.
  350. *
  351. * @param {String} fontName
  352. * @return {Boolean}
  353. */
  354. var isFontInstalled = function (fontName) {
  355. var testFontName = fontName === 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS';
  356. var $tester = $('<div>').css({
  357. position: 'absolute',
  358. left: '-9999px',
  359. top: '-9999px',
  360. fontSize: '200px'
  361. }).text('mmmmmmmmmwwwwwww').appendTo(document.body);
  362. var originalWidth = $tester.css('fontFamily', testFontName).width();
  363. var width = $tester.css('fontFamily', fontName + ',' + testFontName).width();
  364. $tester.remove();
  365. return originalWidth !== width;
  366. };
  367. var userAgent = navigator.userAgent;
  368. var isMSIE = /MSIE|Trident/i.test(userAgent);
  369. var browserVersion;
  370. if (isMSIE) {
  371. var matches = /MSIE (\d+[.]\d+)/.exec(userAgent);
  372. if (matches) {
  373. browserVersion = parseFloat(matches[1]);
  374. }
  375. matches = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(userAgent);
  376. if (matches) {
  377. browserVersion = parseFloat(matches[1]);
  378. }
  379. }
  380. var isEdge = /Edge\/\d+/.test(userAgent);
  381. var hasCodeMirror = !!window.CodeMirror;
  382. if (!hasCodeMirror && isSupportAmd && typeof require !== 'undefined') {
  383. if (typeof require.resolve !== 'undefined') {
  384. try {
  385. // If CodeMirror can't be resolved, `require.resolve` will throw an
  386. // exception and `hasCodeMirror` won't be set to `true`.
  387. require.resolve('codemirror');
  388. hasCodeMirror = true;
  389. } catch (e) {
  390. // Do nothing.
  391. }
  392. } else if (typeof eval('require').specified !== 'undefined') {
  393. hasCodeMirror = eval('require').specified('codemirror');
  394. }
  395. }
  396. /**
  397. * @class core.agent
  398. *
  399. * Object which check platform and agent
  400. *
  401. * @singleton
  402. * @alternateClassName agent
  403. */
  404. var agent = {
  405. isMac: navigator.appVersion.indexOf('Mac') > -1,
  406. isMSIE: isMSIE,
  407. isEdge: isEdge,
  408. isFF: !isEdge && /firefox/i.test(userAgent),
  409. isPhantom: /PhantomJS/i.test(userAgent),
  410. isWebkit: !isEdge && /webkit/i.test(userAgent),
  411. isChrome: !isEdge && /chrome/i.test(userAgent),
  412. isSafari: !isEdge && /safari/i.test(userAgent),
  413. browserVersion: browserVersion,
  414. jqueryVersion: parseFloat($.fn.jquery),
  415. isSupportAmd: isSupportAmd,
  416. hasCodeMirror: hasCodeMirror,
  417. isFontInstalled: isFontInstalled,
  418. isW3CRangeSupport: !!document.createRange
  419. };
  420. var NBSP_CHAR = String.fromCharCode(160);
  421. var ZERO_WIDTH_NBSP_CHAR = '\ufeff';
  422. /**
  423. * @class core.dom
  424. *
  425. * Dom functions
  426. *
  427. * @singleton
  428. * @alternateClassName dom
  429. */
  430. var dom = (function () {
  431. /**
  432. * @method isEditable
  433. *
  434. * returns whether node is `note-editable` or not.
  435. *
  436. * @param {Node} node
  437. * @return {Boolean}
  438. */
  439. var isEditable = function (node) {
  440. return node && $(node).hasClass('note-editable');
  441. };
  442. /**
  443. * @method isControlSizing
  444. *
  445. * returns whether node is `note-control-sizing` or not.
  446. *
  447. * @param {Node} node
  448. * @return {Boolean}
  449. */
  450. var isControlSizing = function (node) {
  451. return node && $(node).hasClass('note-control-sizing');
  452. };
  453. /**
  454. * IBM Changes to summernote
  455. */
  456. /**
  457. * @method isTextFitted
  458. *
  459. * returns true if the node has the classname used in textFit.
  460. *
  461. * @param {String} className classname of the node
  462. * @return {Function}
  463. */
  464. var isTextFitted = function (className) {
  465. return className && className.toUpperCase().indexOf('TEXTFITTED') !== -1;
  466. };
  467. /**
  468. * @method makePredByNodeName
  469. *
  470. * returns predicate which judge whether nodeName is same
  471. *
  472. * @param {String} nodeName
  473. * @return {Function}
  474. */
  475. var makePredByNodeName = function (nodeName) {
  476. nodeName = nodeName.toUpperCase();
  477. return function (node) {
  478. return node && node.nodeName.toUpperCase() === nodeName && !isTextFitted(node.className);
  479. };
  480. };
  481. /**
  482. * @method isText
  483. *
  484. *
  485. *
  486. * @param {Node} node
  487. * @return {Boolean} true if node's type is text(3)
  488. */
  489. var isText = function (node) {
  490. return node && node.nodeType === 3;
  491. };
  492. /**
  493. * @method isElement
  494. *
  495. *
  496. *
  497. * @param {Node} node
  498. * @return {Boolean} true if node's type is element(1)
  499. */
  500. var isElement = function (node) {
  501. return node && node.nodeType === 1;
  502. };
  503. /**
  504. * ex) br, col, embed, hr, img, input, ...
  505. * @see http://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements
  506. */
  507. var isVoid = function (node) {
  508. return node && /^BR|^IMG|^HR|^IFRAME|^BUTTON/.test(node.nodeName.toUpperCase());
  509. };
  510. var isPara = function (node) {
  511. if (isEditable(node)) {
  512. return false;
  513. }
  514. // Chrome(v31.0), FF(v25.0.1) use DIV for paragraph
  515. return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase());
  516. };
  517. var isHeading = function (node) {
  518. return node && /^H[1-7]/.test(node.nodeName.toUpperCase());
  519. };
  520. var isPre = makePredByNodeName('PRE');
  521. var isLi = makePredByNodeName('LI');
  522. var isPurePara = function (node) {
  523. return isPara(node) && !isLi(node);
  524. };
  525. var isTable = makePredByNodeName('TABLE');
  526. var isData = makePredByNodeName('DATA');
  527. var isInline = function (node) {
  528. return !isBodyContainer(node) &&
  529. !isList(node) &&
  530. !isHr(node) &&
  531. !isPara(node) &&
  532. !isTable(node) &&
  533. !isBlockquote(node) &&
  534. !isData(node);
  535. };
  536. var isList = function (node) {
  537. return node && /^UL|^OL/.test(node.nodeName.toUpperCase());
  538. };
  539. var isHr = makePredByNodeName('HR');
  540. var isCell = function (node) {
  541. return node && /^TD|^TH/.test(node.nodeName.toUpperCase());
  542. };
  543. var isBlockquote = makePredByNodeName('BLOCKQUOTE');
  544. var isBodyContainer = function (node) {
  545. return isCell(node) || isBlockquote(node) || isEditable(node);
  546. };
  547. var isAnchor = makePredByNodeName('A');
  548. var isParaInline = function (node) {
  549. return isInline(node) && !!ancestor(node, isPara);
  550. };
  551. var isBodyInline = function (node) {
  552. return isInline(node) && !ancestor(node, isPara);
  553. };
  554. var isBody = makePredByNodeName('BODY');
  555. /**
  556. * returns whether nodeB is closest sibling of nodeA
  557. *
  558. * @param {Node} nodeA
  559. * @param {Node} nodeB
  560. * @return {Boolean}
  561. */
  562. var isClosestSibling = function (nodeA, nodeB) {
  563. return nodeA.nextSibling === nodeB ||
  564. nodeA.previousSibling === nodeB;
  565. };
  566. /**
  567. * returns array of closest siblings with node
  568. *
  569. * @param {Node} node
  570. * @param {function} [pred] - predicate function
  571. * @return {Node[]}
  572. */
  573. var withClosestSiblings = function (node, pred) {
  574. pred = pred || func.ok;
  575. var siblings = [];
  576. if (node.previousSibling && pred(node.previousSibling)) {
  577. siblings.push(node.previousSibling);
  578. }
  579. siblings.push(node);
  580. if (node.nextSibling && pred(node.nextSibling)) {
  581. siblings.push(node.nextSibling);
  582. }
  583. return siblings;
  584. };
  585. /**
  586. * blank HTML for cursor position
  587. * - [workaround] old IE only works with &nbsp;
  588. * - [workaround] IE11 and other browser works with bogus br
  589. */
  590. var blankHTML = agent.isMSIE && agent.browserVersion < 11 ? '&nbsp;' : '<br>';
  591. /**
  592. * @method nodeLength
  593. *
  594. * returns #text's text size or element's childNodes size
  595. *
  596. * @param {Node} node
  597. */
  598. var nodeLength = function (node) {
  599. if (isText(node)) {
  600. return node.nodeValue.length;
  601. }
  602. if (node) {
  603. return node.childNodes.length;
  604. }
  605. return 0;
  606. };
  607. /**
  608. * returns whether node is empty or not.
  609. *
  610. * @param {Node} node
  611. * @return {Boolean}
  612. */
  613. var isEmpty = function (node) {
  614. var len = nodeLength(node);
  615. if (len === 0) {
  616. return true;
  617. } else if (!isText(node) && len === 1 && (node.innerHTML === blankHTML || node.firstChild.innerHTML === blankHTML)) {
  618. // ex) <p><br></p>, <span><br></span>
  619. return true;
  620. } else if (list.all(node.childNodes, isText) && node.innerHTML === '') {
  621. // ex) <p></p>, <span></span>
  622. return true;
  623. }
  624. return false;
  625. };
  626. /**
  627. * padding blankHTML if node is empty (for cursor position)
  628. */
  629. var paddingBlankHTML = function (node) {
  630. if (!isVoid(node) && !nodeLength(node)) {
  631. node.innerHTML = blankHTML;
  632. }
  633. };
  634. /**
  635. * find nearest ancestor predicate hit
  636. *
  637. * @param {Node} node
  638. * @param {Function} pred - predicate function
  639. */
  640. var ancestor = function (node, pred) {
  641. while (node) {
  642. if (pred(node)) { return node; }
  643. if (isEditable(node)) { break; }
  644. node = node.parentNode;
  645. }
  646. return null;
  647. };
  648. /*
  649. *** IBM changes to summernote
  650. */
  651. /**
  652. * find nearest ancestor only single child blood line and predicate hit
  653. *
  654. * @param {Node} node
  655. * @param {Function} pred - predicate function
  656. */
  657. var singleChildAncestor = function (node, pred) {
  658. node = node.parentNode;
  659. while (node) {
  660. if (nodeLength(node) !== 1) { break; }
  661. if (pred(node)) { return node; }
  662. if (isEditable(node)) { break; }
  663. node = node.parentNode;
  664. }
  665. return null;
  666. };
  667. /**
  668. * returns new array of ancestor nodes (until predicate hit).
  669. *
  670. * @param {Node} node
  671. * @param {Function} [optional] pred - predicate function
  672. */
  673. var listAncestor = function (node, pred) {
  674. pred = pred || func.fail;
  675. var ancestors = [];
  676. ancestor(node, function (el) {
  677. if (!isEditable(el)) {
  678. ancestors.push(el);
  679. }
  680. return pred(el);
  681. });
  682. return ancestors;
  683. };
  684. /**
  685. * find farthest ancestor predicate hit
  686. */
  687. var lastAncestor = function (node, pred) {
  688. var ancestors = listAncestor(node);
  689. return list.last(ancestors.filter(pred));
  690. };
  691. /**
  692. * returns common ancestor node between two nodes.
  693. *
  694. * @param {Node} nodeA
  695. * @param {Node} nodeB
  696. */
  697. var commonAncestor = function (nodeA, nodeB) {
  698. var ancestors = listAncestor(nodeA);
  699. for (var n = nodeB; n; n = n.parentNode) {
  700. if ($.inArray(n, ancestors) > -1) { return n; }
  701. }
  702. return null; // difference document area
  703. };
  704. /**
  705. * listing all previous siblings (until predicate hit).
  706. *
  707. * @param {Node} node
  708. * @param {Function} [optional] pred - predicate function
  709. */
  710. var listPrev = function (node, pred) {
  711. pred = pred || func.fail;
  712. var nodes = [];
  713. while (node) {
  714. if (pred(node)) { break; }
  715. nodes.push(node);
  716. node = node.previousSibling;
  717. }
  718. return nodes;
  719. };
  720. /**
  721. * listing next siblings (until predicate hit).
  722. *
  723. * @param {Node} node
  724. * @param {Function} [pred] - predicate function
  725. */
  726. var listNext = function (node, pred) {
  727. pred = pred || func.fail;
  728. var nodes = [];
  729. while (node) {
  730. if (pred(node)) { break; }
  731. nodes.push(node);
  732. node = node.nextSibling;
  733. }
  734. return nodes;
  735. };
  736. /**
  737. * listing descendant nodes
  738. *
  739. * @param {Node} node
  740. * @param {Function} [pred] - predicate function
  741. */
  742. var listDescendant = function (node, pred) {
  743. var descendants = [];
  744. pred = pred || func.ok;
  745. // start DFS(depth first search) with node
  746. (function fnWalk(current) {
  747. if (node !== current && pred(current)) {
  748. descendants.push(current);
  749. }
  750. for (var idx = 0, len = current.childNodes.length; idx < len; idx++) {
  751. fnWalk(current.childNodes[idx]);
  752. }
  753. })(node);
  754. return descendants;
  755. };
  756. /**
  757. * wrap node with new tag.
  758. *
  759. * @param {Node} node
  760. * @param {Node} tagName of wrapper
  761. * @return {Node} - wrapper
  762. */
  763. var wrap = function (node, wrapperName) {
  764. var parent = node.parentNode;
  765. var wrapper = $('<' + wrapperName + '>')[0];
  766. parent.insertBefore(wrapper, node);
  767. wrapper.appendChild(node);
  768. return wrapper;
  769. };
  770. /**
  771. * insert node after preceding
  772. *
  773. * @param {Node} node
  774. * @param {Node} preceding - predicate function
  775. */
  776. var insertAfter = function (node, preceding) {
  777. var next = preceding.nextSibling, parent = preceding.parentNode;
  778. if (next) {
  779. parent.insertBefore(node, next);
  780. } else {
  781. parent.appendChild(node);
  782. }
  783. return node;
  784. };
  785. /**
  786. * append elements.
  787. *
  788. * @param {Node} node
  789. * @param {Collection} aChild
  790. */
  791. var appendChildNodes = function (node, aChild) {
  792. $.each(aChild, function (idx, child) {
  793. node.appendChild(child);
  794. });
  795. return node;
  796. };
  797. /**
  798. * returns whether boundaryPoint is left edge or not.
  799. *
  800. * @param {BoundaryPoint} point
  801. * @return {Boolean}
  802. */
  803. var isLeftEdgePoint = function (point) {
  804. return point.offset === 0;
  805. };
  806. /**
  807. * returns whether boundaryPoint is right edge or not.
  808. *
  809. * @param {BoundaryPoint} point
  810. * @return {Boolean}
  811. */
  812. var isRightEdgePoint = function (point) {
  813. return point.offset === nodeLength(point.node);
  814. };
  815. /**
  816. * returns whether boundaryPoint is edge or not.
  817. *
  818. * @param {BoundaryPoint} point
  819. * @return {Boolean}
  820. */
  821. var isEdgePoint = function (point) {
  822. return isLeftEdgePoint(point) || isRightEdgePoint(point);
  823. };
  824. /**
  825. * returns whether node is left edge of ancestor or not.
  826. *
  827. * @param {Node} node
  828. * @param {Node} ancestor
  829. * @return {Boolean}
  830. */
  831. var isLeftEdgeOf = function (node, ancestor) {
  832. while (node && node !== ancestor) {
  833. if (position(node) !== 0) {
  834. return false;
  835. }
  836. node = node.parentNode;
  837. }
  838. return true;
  839. };
  840. /**
  841. * returns whether node is right edge of ancestor or not.
  842. *
  843. * @param {Node} node
  844. * @param {Node} ancestor
  845. * @return {Boolean}
  846. */
  847. var isRightEdgeOf = function (node, ancestor) {
  848. if (!ancestor) {
  849. return false;
  850. }
  851. while (node && node !== ancestor) {
  852. if (position(node) !== nodeLength(node.parentNode) - 1) {
  853. return false;
  854. }
  855. node = node.parentNode;
  856. }
  857. return true;
  858. };
  859. /**
  860. * returns whether point is left edge of ancestor or not.
  861. * @param {BoundaryPoint} point
  862. * @param {Node} ancestor
  863. * @return {Boolean}
  864. */
  865. var isLeftEdgePointOf = function (point, ancestor) {
  866. return isLeftEdgePoint(point) && isLeftEdgeOf(point.node, ancestor);
  867. };
  868. /**
  869. * returns whether point is right edge of ancestor or not.
  870. * @param {BoundaryPoint} point
  871. * @param {Node} ancestor
  872. * @return {Boolean}
  873. */
  874. var isRightEdgePointOf = function (point, ancestor) {
  875. return isRightEdgePoint(point) && isRightEdgeOf(point.node, ancestor);
  876. };
  877. /**
  878. * returns offset from parent.
  879. *
  880. * @param {Node} node
  881. */
  882. var position = function (node) {
  883. var offset = 0;
  884. while ((node = node.previousSibling)) {
  885. offset += 1;
  886. }
  887. return offset;
  888. };
  889. var hasChildren = function (node) {
  890. return !!(node && node.childNodes && node.childNodes.length);
  891. };
  892. /**
  893. * returns previous boundaryPoint
  894. *
  895. * @param {BoundaryPoint} point
  896. * @param {Boolean} isSkipInnerOffset
  897. * @return {BoundaryPoint}
  898. */
  899. var prevPoint = function (point, isSkipInnerOffset) {
  900. var node, offset;
  901. if (point.offset === 0) {
  902. if (isEditable(point.node)) {
  903. return null;
  904. }
  905. node = point.node.parentNode;
  906. offset = position(point.node);
  907. } else if (hasChildren(point.node)) {
  908. node = point.node.childNodes[point.offset - 1];
  909. offset = nodeLength(node);
  910. } else {
  911. node = point.node;
  912. offset = isSkipInnerOffset ? 0 : point.offset - 1;
  913. }
  914. return {
  915. node: node,
  916. offset: offset
  917. };
  918. };
  919. /**
  920. * returns next boundaryPoint
  921. *
  922. * @param {BoundaryPoint} point
  923. * @param {Boolean} isSkipInnerOffset
  924. * @return {BoundaryPoint}
  925. */
  926. var nextPoint = function (point, isSkipInnerOffset) {
  927. var node, offset;
  928. if (nodeLength(point.node) === point.offset) {
  929. if (isEditable(point.node)) {
  930. return null;
  931. }
  932. node = point.node.parentNode;
  933. offset = position(point.node) + 1;
  934. } else if (hasChildren(point.node)) {
  935. node = point.node.childNodes[point.offset];
  936. offset = 0;
  937. } else {
  938. node = point.node;
  939. offset = isSkipInnerOffset ? nodeLength(point.node) : point.offset + 1;
  940. }
  941. return {
  942. node: node,
  943. offset: offset
  944. };
  945. };
  946. /**
  947. * returns whether pointA and pointB is same or not.
  948. *
  949. * @param {BoundaryPoint} pointA
  950. * @param {BoundaryPoint} pointB
  951. * @return {Boolean}
  952. */
  953. var isSamePoint = function (pointA, pointB) {
  954. return pointA.node === pointB.node && pointA.offset === pointB.offset;
  955. };
  956. /**
  957. * returns whether point is visible (can set cursor) or not.
  958. *
  959. * @param {BoundaryPoint} point
  960. * @return {Boolean}
  961. */
  962. var isVisiblePoint = function (point) {
  963. if (isText(point.node) || !hasChildren(point.node) || isEmpty(point.node)) {
  964. return true;
  965. }
  966. var leftNode = point.node.childNodes[point.offset - 1];
  967. var rightNode = point.node.childNodes[point.offset];
  968. if ((!leftNode || isVoid(leftNode)) && (!rightNode || isVoid(rightNode))) {
  969. return true;
  970. }
  971. return false;
  972. };
  973. /**
  974. * @method prevPointUtil
  975. *
  976. * @param {BoundaryPoint} point
  977. * @param {Function} pred
  978. * @return {BoundaryPoint}
  979. */
  980. var prevPointUntil = function (point, pred) {
  981. while (point) {
  982. if (pred(point)) {
  983. return point;
  984. }
  985. point = prevPoint(point);
  986. }
  987. return null;
  988. };
  989. /**
  990. * @method nextPointUntil
  991. *
  992. * @param {BoundaryPoint} point
  993. * @param {Function} pred
  994. * @return {BoundaryPoint}
  995. */
  996. var nextPointUntil = function (point, pred) {
  997. while (point) {
  998. if (pred(point)) {
  999. return point;
  1000. }
  1001. point = nextPoint(point);
  1002. }
  1003. return null;
  1004. };
  1005. /**
  1006. * returns whether point has character or not.
  1007. *
  1008. * @param {Point} point
  1009. * @return {Boolean}
  1010. */
  1011. var isCharPoint = function (point) {
  1012. if (!isText(point.node)) {
  1013. return false;
  1014. }
  1015. var ch = point.node.nodeValue.charAt(point.offset - 1);
  1016. return ch && (ch !== ' ' && ch !== NBSP_CHAR);
  1017. };
  1018. /**
  1019. * @method walkPoint
  1020. *
  1021. * @param {BoundaryPoint} startPoint
  1022. * @param {BoundaryPoint} endPoint
  1023. * @param {Function} handler
  1024. * @param {Boolean} isSkipInnerOffset
  1025. */
  1026. var walkPoint = function (startPoint, endPoint, handler, isSkipInnerOffset) {
  1027. var point = startPoint;
  1028. while (point) {
  1029. handler(point);
  1030. if (isSamePoint(point, endPoint)) {
  1031. break;
  1032. }
  1033. var isSkipOffset = isSkipInnerOffset &&
  1034. startPoint.node !== point.node &&
  1035. endPoint.node !== point.node;
  1036. point = nextPoint(point, isSkipOffset);
  1037. }
  1038. };
  1039. /**
  1040. * @method makeOffsetPath
  1041. *
  1042. * return offsetPath(array of offset) from ancestor
  1043. *
  1044. * @param {Node} ancestor - ancestor node
  1045. * @param {Node} node
  1046. */
  1047. var makeOffsetPath = function (ancestor, node) {
  1048. var ancestors = listAncestor(node, func.eq(ancestor));
  1049. return ancestors.map(position).reverse();
  1050. };
  1051. /**
  1052. * @method fromOffsetPath
  1053. *
  1054. * return element from offsetPath(array of offset)
  1055. *
  1056. * @param {Node} ancestor - ancestor node
  1057. * @param {array} offsets - offsetPath
  1058. */
  1059. var fromOffsetPath = function (ancestor, offsets) {
  1060. var current = ancestor;
  1061. for (var i = 0, len = offsets.length; i < len; i++) {
  1062. if (current.childNodes.length <= offsets[i]) {
  1063. current = current.childNodes[current.childNodes.length - 1];
  1064. } else {
  1065. current = current.childNodes[offsets[i]];
  1066. }
  1067. }
  1068. return current;
  1069. };
  1070. /**
  1071. * @method splitNode
  1072. *
  1073. * split element or #text
  1074. *
  1075. * @param {BoundaryPoint} point
  1076. * @param {Object} [options]
  1077. * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false
  1078. * @param {Boolean} [options.isNotSplitEdgePoint] - default: false
  1079. * @return {Node} right node of boundaryPoint
  1080. */
  1081. var splitNode = function (point, options) {
  1082. var isSkipPaddingBlankHTML = options && options.isSkipPaddingBlankHTML;
  1083. var isNotSplitEdgePoint = options && options.isNotSplitEdgePoint;
  1084. // edge case
  1085. if (isEdgePoint(point) && (isText(point.node) || isNotSplitEdgePoint)) {
  1086. if (isLeftEdgePoint(point)) {
  1087. return point.node;
  1088. } else if (isRightEdgePoint(point)) {
  1089. return point.node.nextSibling;
  1090. }
  1091. }
  1092. // split #text
  1093. if (isText(point.node)) {
  1094. return point.node.splitText(point.offset);
  1095. } else {
  1096. var childNode = point.node.childNodes[point.offset];
  1097. var clone = insertAfter(point.node.cloneNode(false), point.node);
  1098. appendChildNodes(clone, listNext(childNode));
  1099. if (!isSkipPaddingBlankHTML) {
  1100. paddingBlankHTML(point.node);
  1101. paddingBlankHTML(clone);
  1102. }
  1103. return clone;
  1104. }
  1105. };
  1106. /**
  1107. * @method splitTree
  1108. *
  1109. * split tree by point
  1110. *
  1111. * @param {Node} root - split root
  1112. * @param {BoundaryPoint} point
  1113. * @param {Object} [options]
  1114. * @param {Boolean} [options.isSkipPaddingBlankHTML] - default: false
  1115. * @param {Boolean} [options.isNotSplitEdgePoint] - default: false
  1116. * @return {Node} right node of boundaryPoint
  1117. */
  1118. var splitTree = function (root, point, options) {
  1119. // ex) [#text, <span>, <p>]
  1120. var ancestors = listAncestor(point.node, func.eq(root));
  1121. if (!ancestors.length) {
  1122. return null;
  1123. } else if (ancestors.length === 1) {
  1124. return splitNode(point, options);
  1125. }
  1126. return ancestors.reduce(function (node, parent) {
  1127. if (node === point.node) {
  1128. node = splitNode(point, options);
  1129. }
  1130. return splitNode({
  1131. node: parent,
  1132. offset: node ? dom.position(node) : nodeLength(parent)
  1133. }, options);
  1134. });
  1135. };
  1136. /**
  1137. * split point
  1138. *
  1139. * @param {Point} point
  1140. * @param {Boolean} isInline
  1141. * @return {Object}
  1142. */
  1143. var splitPoint = function (point, isInline) {
  1144. // find splitRoot, container
  1145. // - inline: splitRoot is a child of paragraph
  1146. // - block: splitRoot is a child of bodyContainer
  1147. var pred = isInline ? isPara : isBodyContainer;
  1148. var ancestors = listAncestor(point.node, pred);
  1149. var topAncestor = list.last(ancestors) || point.node;
  1150. var splitRoot, container;
  1151. if (pred(topAncestor)) {
  1152. splitRoot = ancestors[ancestors.length - 2];
  1153. container = topAncestor;
  1154. } else {
  1155. splitRoot = topAncestor;
  1156. container = splitRoot.parentNode;
  1157. }
  1158. // if splitRoot is exists, split with splitTree
  1159. var pivot = splitRoot && splitTree(splitRoot, point, {
  1160. isSkipPaddingBlankHTML: isInline,
  1161. isNotSplitEdgePoint: isInline
  1162. });
  1163. // if container is point.node, find pivot with point.offset
  1164. if (!pivot && container === point.node) {
  1165. pivot = point.node.childNodes[point.offset];
  1166. }
  1167. return {
  1168. rightNode: pivot,
  1169. container: container
  1170. };
  1171. };
  1172. var create = function (nodeName) {
  1173. return document.createElement(nodeName);
  1174. };
  1175. var createText = function (text) {
  1176. return document.createTextNode(text);
  1177. };
  1178. /**
  1179. * @method remove
  1180. *
  1181. * remove node, (isRemoveChild: remove child or not)
  1182. *
  1183. * @param {Node} node
  1184. * @param {Boolean} isRemoveChild
  1185. */
  1186. var remove = function (node, isRemoveChild) {
  1187. if (!node || !node.parentNode) { return; }
  1188. if (node.removeNode) { return node.removeNode(isRemoveChild); }
  1189. var parent = node.parentNode;
  1190. if (!isRemoveChild) {
  1191. var nodes = [];
  1192. var i, len;
  1193. for (i = 0, len = node.childNodes.length; i < len; i++) {
  1194. nodes.push(node.childNodes[i]);
  1195. }
  1196. for (i = 0, len = nodes.length; i < len; i++) {
  1197. parent.insertBefore(nodes[i], node);
  1198. }
  1199. }
  1200. parent.removeChild(node);
  1201. };
  1202. /**
  1203. * @method removeWhile
  1204. *
  1205. * @param {Node} node
  1206. * @param {Function} pred
  1207. */
  1208. var removeWhile = function (node, pred) {
  1209. while (node) {
  1210. if (isEditable(node) || !pred(node)) {
  1211. break;
  1212. }
  1213. var parent = node.parentNode;
  1214. remove(node);
  1215. node = parent;
  1216. }
  1217. };
  1218. /**
  1219. * @method replace
  1220. *
  1221. * replace node with provided nodeName
  1222. *
  1223. * @param {Node} node
  1224. * @param {String} nodeName
  1225. * @return {Node} - new node
  1226. */
  1227. var replace = function (node, nodeName) {
  1228. if (node.nodeName.toUpperCase() === nodeName.toUpperCase()) {
  1229. return node;
  1230. }
  1231. var newNode = create(nodeName);
  1232. if (node.style.cssText) {
  1233. newNode.style.cssText = node.style.cssText;
  1234. }
  1235. appendChildNodes(newNode, list.from(node.childNodes));
  1236. insertAfter(newNode, node);
  1237. remove(node);
  1238. return newNode;
  1239. };
  1240. var isTextarea = makePredByNodeName('TEXTAREA');
  1241. /**
  1242. * @param {jQuery} $node
  1243. * @param {Boolean} [stripLinebreaks] - default: false
  1244. */
  1245. var value = function ($node, stripLinebreaks) {
  1246. var val = isTextarea($node[0]) ? $node.val() : $node.html();
  1247. if (stripLinebreaks) {
  1248. return val.replace(/[\n\r]/g, '');
  1249. }
  1250. return val;
  1251. };
  1252. /**
  1253. * @method html
  1254. *
  1255. * get the HTML contents of node
  1256. *
  1257. * @param {jQuery} $node
  1258. * @param {Boolean} [isNewlineOnBlock]
  1259. */
  1260. var html = function ($node, isNewlineOnBlock) {
  1261. var markup = value($node);
  1262. if (isNewlineOnBlock) {
  1263. var regexTag = /<(\/?)(\b(?!!)[^>\s]*)(.*?)(\s*\/?>)/g;
  1264. markup = markup.replace(regexTag, function (match, endSlash, name) {
  1265. name = name.toUpperCase();
  1266. var isEndOfInlineContainer = /^DIV|^TD|^TH|^P|^LI|^H[1-7]/.test(name) &&
  1267. !!endSlash;
  1268. var isBlockNode = /^BLOCKQUOTE|^TABLE|^TBODY|^TR|^HR|^UL|^OL/.test(name);
  1269. return match + ((isEndOfInlineContainer || isBlockNode) ? '\n' : '');
  1270. });
  1271. markup = $.trim(markup);
  1272. }
  1273. return markup;
  1274. };
  1275. var posFromPlaceholder = function (placeholder) {
  1276. var $placeholder = $(placeholder);
  1277. var pos = $placeholder.offset();
  1278. var height = $placeholder.outerHeight(true); // include margin
  1279. return {
  1280. left: pos.left,
  1281. top: pos.top + height
  1282. };
  1283. };
  1284. var attachEvents = function ($node, events) {
  1285. Object.keys(events).forEach(function (key) {
  1286. $node.on(key, events[key]);
  1287. });
  1288. };
  1289. var detachEvents = function ($node, events) {
  1290. Object.keys(events).forEach(function (key) {
  1291. $node.off(key, events[key]);
  1292. });
  1293. };
  1294. return {
  1295. /** @property {String} NBSP_CHAR */
  1296. NBSP_CHAR: NBSP_CHAR,
  1297. /** @property {String} ZERO_WIDTH_NBSP_CHAR */
  1298. ZERO_WIDTH_NBSP_CHAR: ZERO_WIDTH_NBSP_CHAR,
  1299. /** @property {String} blank */
  1300. blank: blankHTML,
  1301. /** @property {String} emptyPara */
  1302. emptyPara: '<p>' + blankHTML + '</p>',
  1303. makePredByNodeName: makePredByNodeName,
  1304. isEditable: isEditable,
  1305. isControlSizing: isControlSizing,
  1306. isText: isText,
  1307. isElement: isElement,
  1308. isVoid: isVoid,
  1309. isPara: isPara,
  1310. isPurePara: isPurePara,
  1311. isHeading: isHeading,
  1312. isInline: isInline,
  1313. isBlock: func.not(isInline),
  1314. isBodyInline: isBodyInline,
  1315. isBody: isBody,
  1316. isParaInline: isParaInline,
  1317. isPre: isPre,
  1318. isList: isList,
  1319. isTable: isTable,
  1320. isData: isData,
  1321. isCell: isCell,
  1322. isBlockquote: isBlockquote,
  1323. isBodyContainer: isBodyContainer,
  1324. isAnchor: isAnchor,
  1325. isDiv: makePredByNodeName('DIV'),
  1326. isLi: isLi,
  1327. isBR: makePredByNodeName('BR'),
  1328. isSpan: makePredByNodeName('SPAN'),
  1329. isB: makePredByNodeName('B'),
  1330. isU: makePredByNodeName('U'),
  1331. isS: makePredByNodeName('S'),
  1332. isI: makePredByNodeName('I'),
  1333. isImg: makePredByNodeName('IMG'),
  1334. isTextarea: isTextarea,
  1335. isEmpty: isEmpty,
  1336. isEmptyAnchor: func.and(isAnchor, isEmpty),
  1337. isClosestSibling: isClosestSibling,
  1338. withClosestSiblings: withClosestSiblings,
  1339. nodeLength: nodeLength,
  1340. isLeftEdgePoint: isLeftEdgePoint,
  1341. isRightEdgePoint: isRightEdgePoint,
  1342. isEdgePoint: isEdgePoint,
  1343. isLeftEdgeOf: isLeftEdgeOf,
  1344. isRightEdgeOf: isRightEdgeOf,
  1345. isLeftEdgePointOf: isLeftEdgePointOf,
  1346. isRightEdgePointOf: isRightEdgePointOf,
  1347. prevPoint: prevPoint,
  1348. nextPoint: nextPoint,
  1349. isSamePoint: isSamePoint,
  1350. isVisiblePoint: isVisiblePoint,
  1351. prevPointUntil: prevPointUntil,
  1352. nextPointUntil: nextPointUntil,
  1353. isCharPoint: isCharPoint,
  1354. walkPoint: walkPoint,
  1355. ancestor: ancestor,
  1356. singleChildAncestor: singleChildAncestor,
  1357. listAncestor: listAncestor,
  1358. lastAncestor: lastAncestor,
  1359. listNext: listNext,
  1360. listPrev: listPrev,
  1361. listDescendant: listDescendant,
  1362. commonAncestor: commonAncestor,
  1363. wrap: wrap,
  1364. insertAfter: insertAfter,
  1365. appendChildNodes: appendChildNodes,
  1366. position: position,
  1367. hasChildren: hasChildren,
  1368. makeOffsetPath: makeOffsetPath,
  1369. fromOffsetPath: fromOffsetPath,
  1370. splitTree: splitTree,
  1371. splitPoint: splitPoint,
  1372. create: create,
  1373. createText: createText,
  1374. remove: remove,
  1375. removeWhile: removeWhile,
  1376. replace: replace,
  1377. html: html,
  1378. value: value,
  1379. posFromPlaceholder: posFromPlaceholder,
  1380. attachEvents: attachEvents,
  1381. detachEvents: detachEvents
  1382. };
  1383. })();
  1384. /**
  1385. * @param {jQuery} $note
  1386. * @param {Object} options
  1387. * @return {Context}
  1388. */
  1389. var Context = function ($note, options) {
  1390. var self = this;
  1391. var ui = $.summernote.ui;
  1392. this.memos = {};
  1393. this.modules = {};
  1394. this.layoutInfo = {};
  1395. this.options = options;
  1396. /**
  1397. * create layout and initialize modules and other resources
  1398. */
  1399. this.initialize = function () {
  1400. this.layoutInfo = ui.createLayout($note, options);
  1401. this._initialize();
  1402. $note.hide();
  1403. return this;
  1404. };
  1405. /**
  1406. * destroy modules and other resources and remove layout
  1407. */
  1408. this.destroy = function () {
  1409. this._destroy();
  1410. $note.removeData('summernote');
  1411. ui.removeLayout($note, this.layoutInfo);
  1412. };
  1413. /**
  1414. * destory modules and other resources and initialize it again
  1415. */
  1416. this.reset = function () {
  1417. var disabled = self.isDisabled();
  1418. this.code(dom.emptyPara);
  1419. this._destroy();
  1420. this._initialize();
  1421. if (disabled) {
  1422. self.disable();
  1423. }
  1424. };
  1425. this._initialize = function () {
  1426. // add optional buttons
  1427. var buttons = $.extend({}, this.options.buttons);
  1428. Object.keys(buttons).forEach(function (key) {
  1429. self.memo('button.' + key, buttons[key]);
  1430. });
  1431. var modules = $.extend({}, this.options.modules, $.summernote.plugins || {});
  1432. // add and initialize modules
  1433. Object.keys(modules).forEach(function (key) {
  1434. self.module(key, modules[key], true);
  1435. });
  1436. Object.keys(this.modules).forEach(function (key) {
  1437. self.initializeModule(key);
  1438. });
  1439. };
  1440. this._destroy = function () {
  1441. // destroy modules with reversed order
  1442. Object.keys(this.modules).reverse().forEach(function (key) {
  1443. self.removeModule(key);
  1444. });
  1445. Object.keys(this.memos).forEach(function (key) {
  1446. self.removeMemo(key);
  1447. });
  1448. // trigger custom onDestroy callback -- Summernote 0.8.3
  1449. this.triggerEvent('destroy', this);
  1450. };
  1451. this.code = function (html) {
  1452. var isActivated = this.invoke('codeview.isActivated');
  1453. if (html === undefined) {
  1454. this.invoke('codeview.sync');
  1455. return isActivated ? this.layoutInfo.codable.val() : this.layoutInfo.editable.html();
  1456. } else {
  1457. if (isActivated) {
  1458. this.layoutInfo.codable.val(html);
  1459. } else {
  1460. this.layoutInfo.editable.html(html);
  1461. }
  1462. $note.val(html);
  1463. this.triggerEvent('change', html);
  1464. }
  1465. };
  1466. this.isDisabled = function () {
  1467. return this.layoutInfo.editable.attr('contenteditable') === 'false';
  1468. };
  1469. this.enable = function () {
  1470. this.layoutInfo.editable.attr('contenteditable', true);
  1471. this.invoke('toolbar.activate', true);
  1472. };
  1473. this.disable = function () {
  1474. // close codeview if codeview is opend
  1475. if (this.invoke('codeview.isActivated')) {
  1476. this.invoke('codeview.deactivate');
  1477. }
  1478. this.layoutInfo.editable.attr('contenteditable', false);
  1479. this.invoke('toolbar.deactivate', true);
  1480. };
  1481. this.triggerEvent = function () {
  1482. var namespace = list.head(arguments);
  1483. var args = list.tail(list.from(arguments));
  1484. var callback = this.options.callbacks[func.namespaceToCamel(namespace, 'on')];
  1485. if (callback) {
  1486. callback.apply($note[0], args);
  1487. }
  1488. $note.trigger('summernote.' + namespace, args);
  1489. };
  1490. this.initializeModule = function (key) {
  1491. var module = this.modules[key];
  1492. module.shouldInitialize = module.shouldInitialize || func.ok;
  1493. if (!module.shouldInitialize()) {
  1494. return;
  1495. }
  1496. // initialize module
  1497. if (module.initialize) {
  1498. module.initialize();
  1499. }
  1500. // attach events
  1501. if (module.events) {
  1502. dom.attachEvents($note, module.events);
  1503. }
  1504. };
  1505. this.module = function (key, ModuleClass, withoutIntialize) {
  1506. if (arguments.length === 1) {
  1507. return this.modules[key];
  1508. }
  1509. this.modules[key] = new ModuleClass(this);
  1510. if (!withoutIntialize) {
  1511. this.initializeModule(key);
  1512. }
  1513. };
  1514. this.removeModule = function (key) {
  1515. var module = this.modules[key];
  1516. if (module.shouldInitialize()) {
  1517. if (module.events) {
  1518. dom.detachEvents($note, module.events);
  1519. }
  1520. if (module.destroy) {
  1521. module.destroy();
  1522. }
  1523. }
  1524. delete this.modules[key];
  1525. };
  1526. this.memo = function (key, obj) {
  1527. if (arguments.length === 1) {
  1528. return this.memos[key];
  1529. }
  1530. this.memos[key] = obj;
  1531. };
  1532. this.removeMemo = function (key) {
  1533. if (this.memos[key] && this.memos[key].destroy) {
  1534. this.memos[key].destroy();
  1535. }
  1536. delete this.memos[key];
  1537. };
  1538. this.createInvokeHandler = function (namespace, value) {
  1539. return function (event) {
  1540. event.preventDefault();
  1541. self.invoke(namespace, value || $(event.target).closest('[data-value]').data('value'));
  1542. };
  1543. };
  1544. this.invoke = function () {
  1545. var namespace = list.head(arguments);
  1546. var args = list.tail(list.from(arguments));
  1547. var splits = namespace.split('.');
  1548. var hasSeparator = splits.length > 1;
  1549. var moduleName = hasSeparator && list.head(splits);
  1550. var methodName = hasSeparator ? list.last(splits) : list.head(splits);
  1551. var module = this.modules[moduleName || 'editor'];
  1552. if (!moduleName && this[methodName]) {
  1553. return this[methodName].apply(this, args);
  1554. } else if (module && module[methodName] && module.shouldInitialize()) {
  1555. return module[methodName].apply(module, args);
  1556. }
  1557. };
  1558. return this.initialize();
  1559. };
  1560. $.fn.extend({
  1561. /**
  1562. * Summernote API
  1563. *
  1564. * @param {Object|String}
  1565. * @return {this}
  1566. */
  1567. summernote: function () {
  1568. var type = $.type(list.head(arguments));
  1569. var isExternalAPICalled = type === 'string';
  1570. var hasInitOptions = type === 'object';
  1571. var options = hasInitOptions ? list.head(arguments) : {};
  1572. options = $.extend({}, $.summernote.options, options);
  1573. options.langInfo = $.extend(true, {}, $.summernote.lang['en-US'], $.summernote.lang[options.lang]);
  1574. options.icons = $.extend(true, {}, $.summernote.options.icons, options.icons);
  1575. this.each(function (idx, note) {
  1576. var $note = $(note);
  1577. if (!$note.data('summernote')) {
  1578. var context = new Context($note, options);
  1579. $note.data('summernote', context);
  1580. $note.data('summernote').triggerEvent('init', context.layoutInfo);
  1581. }
  1582. });
  1583. var $note = this.first();
  1584. if ($note.length) {
  1585. var context = $note.data('summernote');
  1586. if (isExternalAPICalled) {
  1587. return context.invoke.apply(context, list.from(arguments));
  1588. } else if (options.focus) {
  1589. context.invoke('editor.focus');
  1590. }
  1591. }
  1592. return this;
  1593. }
  1594. });
  1595. var Renderer = function (markup, children, options, callback) {
  1596. this.render = function ($parent) {
  1597. var $node = $(markup);
  1598. if (options && options.contents) {
  1599. $node.html(options.contents);
  1600. }
  1601. if (options && options.className) {
  1602. $node.addClass(options.className);
  1603. }
  1604. if (options && options.data) {
  1605. $.each(options.data, function (k, v) {
  1606. $node.attr('data-' + k, v);
  1607. });
  1608. }
  1609. if (options && options.click) {
  1610. $node.on('click', options.click);
  1611. }
  1612. if (children) {
  1613. var $container = $node.find('.note-children-container');
  1614. children.forEach(function (child) {
  1615. child.render($container.length ? $container : $node);
  1616. });
  1617. }
  1618. if (callback) {
  1619. callback($node, options);
  1620. }
  1621. if (options && options.callback) {
  1622. options.callback($node);
  1623. }
  1624. if ($parent) {
  1625. $parent.append($node);
  1626. }
  1627. return $node;
  1628. };
  1629. };
  1630. var renderer = {
  1631. create: function (markup, callback) {
  1632. return function () {
  1633. var children = $.isArray(arguments[0]) ? arguments[0] : [];
  1634. var options = typeof arguments[1] === 'object' ? arguments[1] : arguments[0];
  1635. if (options && options.children) {
  1636. children = options.children;
  1637. }
  1638. return new Renderer(markup, children, options, callback);
  1639. };
  1640. }
  1641. };
  1642. var editor = renderer.create('<div class="note-editor note-frame panel panel-default"/>');
  1643. var toolbar = renderer.create('<div class="note-toolbar panel-heading"/>');
  1644. var editingArea = renderer.create('<div class="note-editing-area"/>');
  1645. var codable = renderer.create('<textarea class="note-codable"/>');
  1646. var editable = renderer.create('<div class="note-editable panel-body" contentEditable="true"/>');
  1647. var statusbar = renderer.create([
  1648. '<div class="note-statusbar">',
  1649. ' <div class="note-resizebar">',
  1650. ' <div class="note-icon-bar"/>',
  1651. ' <div class="note-icon-bar"/>',
  1652. ' <div class="note-icon-bar"/>',
  1653. ' </div>',
  1654. '</div>'
  1655. ].join(''));
  1656. var airEditor = renderer.create('<div class="note-editor"/>');
  1657. var airEditable = renderer.create('<div class="note-editable" contentEditable="true"/>');
  1658. var buttonGroup = renderer.create('<div class="note-btn-group btn-group">');
  1659. var button = renderer.create('<button type="button" class="note-btn btn btn-default btn-sm" tabindex="-1">', function ($node, options) {
  1660. if (options && options.tooltip) {
  1661. $node.attr({
  1662. title: options.tooltip
  1663. }).tooltip({
  1664. container: 'body',
  1665. trigger: 'hover',
  1666. placement: 'bottom'
  1667. });
  1668. }
  1669. });
  1670. var dropdown = renderer.create('<div class="dropdown-menu">', function ($node, options) {
  1671. var markup = $.isArray(options.items) ? options.items.map(function (item) {
  1672. var value = (typeof item === 'string') ? item : (item.value || '');
  1673. var content = options.template ? options.template(item) : item;
  1674. return '<li><a href="#" data-value="' + value + '">' + content + '</a></li>';
  1675. }).join('') : options.items;
  1676. $node.html(markup);
  1677. });
  1678. var dropdownCheck = renderer.create('<div class="dropdown-menu note-check">', function ($node, options) {
  1679. var markup = $.isArray(options.items) ? options.items.map(function (item) {
  1680. var value = (typeof item === 'string') ? item : (item.value || '');
  1681. var content = options.template ? options.template(item) : item;
  1682. return '<li><a href="#" data-value="' + value + '">' + icon(options.checkClassName) + ' ' + content + '</a></li>';
  1683. }).join('') : options.items;
  1684. $node.html(markup);
  1685. });
  1686. var palette = renderer.create('<div class="note-color-palette"/>', function ($node, options) {
  1687. var contents = [];
  1688. for (var row = 0, rowSize = options.colors.length; row < rowSize; row++) {
  1689. var eventName = options.eventName;
  1690. var colors = options.colors[row];
  1691. var buttons = [];
  1692. for (var col = 0, colSize = colors.length; col < colSize; col++) {
  1693. var color = colors[col];
  1694. buttons.push([
  1695. '<button type="button" class="note-color-btn"',
  1696. 'style="background-color:', color, '" ',
  1697. 'data-event="', eventName, '" ',
  1698. 'data-value="', color, '" ',
  1699. 'title="', color, '" ',
  1700. 'data-toggle="button" tabindex="-1"></button>'
  1701. ].join(''));
  1702. }
  1703. contents.push('<div class="note-color-row">' + buttons.join('') + '</div>');
  1704. }
  1705. $node.html(contents.join(''));
  1706. $node.find('.note-color-btn').tooltip({
  1707. container: 'body',
  1708. trigger: 'hover',
  1709. placement: 'bottom'
  1710. });
  1711. });
  1712. var dialog = renderer.create('<div class="modal" aria-hidden="false" tabindex="-1"/>', function ($node, options) {
  1713. if (options.fade) {
  1714. $node.addClass('fade');
  1715. }
  1716. $node.html([
  1717. '<div class="modal-dialog">',
  1718. ' <div class="modal-content">',
  1719. (options.title ?
  1720. ' <div class="modal-header">' +
  1721. ' <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
  1722. ' <h4 class="modal-title">' + options.title + '</h4>' +
  1723. ' </div>' : ''
  1724. ),
  1725. ' <div class="modal-body">' + options.body + '</div>',
  1726. (options.footer ?
  1727. ' <div class="modal-footer">' + options.footer + '</div>' : ''
  1728. ),
  1729. ' </div>',
  1730. '</div>'
  1731. ].join(''));
  1732. });
  1733. var popover = renderer.create([
  1734. '<div class="note-popover popover in">',
  1735. ' <div class="arrow"/>',
  1736. ' <div class="popover-content note-children-container"/>',
  1737. '</div>'
  1738. ].join(''), function ($node, options) {
  1739. var direction = typeof options.direction !== 'undefined' ? options.direction : 'bottom';
  1740. $node.addClass(direction);
  1741. if (options.hideArrow) {
  1742. $node.find('.arrow').hide();
  1743. }
  1744. });
  1745. var icon = function (iconClassName, tagName) {
  1746. tagName = tagName || 'i';
  1747. return '<' + tagName + ' class="' + iconClassName + '"/>';
  1748. };
  1749. var ui = {
  1750. editor: editor,
  1751. toolbar: toolbar,
  1752. editingArea: editingArea,
  1753. codable: codable,
  1754. editable: editable,
  1755. statusbar: statusbar,
  1756. airEditor: airEditor,
  1757. airEditable: airEditable,
  1758. buttonGroup: buttonGroup,
  1759. button: button,
  1760. dropdown: dropdown,
  1761. dropdownCheck: dropdownCheck,
  1762. palette: palette,
  1763. dialog: dialog,
  1764. popover: popover,
  1765. icon: icon,
  1766. toggleBtn: function ($btn, isEnable) {
  1767. $btn.toggleClass('disabled', !isEnable);
  1768. $btn.attr('disabled', !isEnable);
  1769. },
  1770. toggleBtnActive: function ($btn, isActive) {
  1771. $btn.toggleClass('active', isActive);
  1772. },
  1773. onDialogShown: function ($dialog, handler) {
  1774. $dialog.one('shown.bs.modal', handler);
  1775. },
  1776. onDialogHidden: function ($dialog, handler) {
  1777. $dialog.one('hidden.bs.modal', handler);
  1778. },
  1779. showDialog: function ($dialog) {
  1780. $dialog.modal('show');
  1781. },
  1782. hideDialog: function ($dialog) {
  1783. $dialog.modal('hide');
  1784. },
  1785. createLayout: function ($note, options) {
  1786. var $editor = (options.airMode ? ui.airEditor([
  1787. ui.editingArea([
  1788. ui.airEditable()
  1789. ])
  1790. ]) : ui.editor([
  1791. ui.toolbar(),
  1792. ui.editingArea([
  1793. ui.codable(),
  1794. ui.editable()
  1795. ]),
  1796. ui.statusbar()
  1797. ])).render();
  1798. $editor.insertAfter($note);
  1799. return {
  1800. note: $note,
  1801. editor: $editor,
  1802. toolbar: $editor.find('.note-toolbar'),
  1803. editingArea: $editor.find('.note-editing-area'),
  1804. editable: $editor.find('.note-editable'),
  1805. codable: $editor.find('.note-codable'),
  1806. statusbar: $editor.find('.note-statusbar')
  1807. };
  1808. },
  1809. removeLayout: function ($note, layoutInfo) {
  1810. $note.html(layoutInfo.editable.html());
  1811. layoutInfo.editor.remove();
  1812. $note.show();
  1813. }
  1814. };
  1815. $.summernote = $.summernote || {
  1816. lang: {}
  1817. };
  1818. $.extend($.summernote.lang, {
  1819. 'en-US': {
  1820. font: {
  1821. bold: 'Bold',
  1822. italic: 'Italic',
  1823. underline: 'Underline',
  1824. clear: 'Remove Font Style',
  1825. height: 'Line Height',
  1826. name: 'Font Family',
  1827. strikethrough: 'Strikethrough',
  1828. subscript: 'Subscript',
  1829. superscript: 'Superscript',
  1830. size: 'Font Size'
  1831. },
  1832. image: {
  1833. image: 'Picture',
  1834. insert: 'Insert Image',
  1835. resizeFull: 'Resize Full',
  1836. resizeHalf: 'Resize Half',
  1837. resizeQuarter: 'Resize Quarter',
  1838. floatLeft: 'Float Left',
  1839. floatRight: 'Float Right',
  1840. floatNone: 'Float None',
  1841. shapeRounded: 'Shape: Rounded',
  1842. shapeCircle: 'Shape: Circle',
  1843. shapeThumbnail: 'Shape: Thumbnail',
  1844. shapeNone: 'Shape: None',
  1845. dragImageHere: 'Drag image or text here',
  1846. dropImage: 'Drop image or Text',
  1847. selectFromFiles: 'Select from files',
  1848. maximumFileSize: 'Maximum file size',
  1849. maximumFileSizeError: 'Maximum file size exceeded.',
  1850. url: 'Image URL',
  1851. remove: 'Remove Image'
  1852. },
  1853. video: {
  1854. video: 'Video',
  1855. videoLink: 'Video Link',
  1856. insert: 'Insert Video',
  1857. url: 'Video URL?',
  1858. providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion or Youku)'
  1859. },
  1860. link: {
  1861. link: 'Link',
  1862. insert: 'Insert Link',
  1863. unlink: 'Unlink',
  1864. edit: 'Edit',
  1865. textToDisplay: 'Text to display',
  1866. url: 'To what URL should this link go?',
  1867. openInNewWindow: 'Open in new window'
  1868. },
  1869. table: {
  1870. table: 'Table'
  1871. },
  1872. hr: {
  1873. insert: 'Insert Horizontal Rule'
  1874. },
  1875. style: {
  1876. style: 'Style',
  1877. p: 'Normal', //summernote 0.8.3
  1878. blockquote: 'Quote',
  1879. pre: 'Code',
  1880. h1: 'Header 1',
  1881. h2: 'Header 2',
  1882. h3: 'Header 3',
  1883. h4: 'Header 4',
  1884. h5: 'Header 5',
  1885. h6: 'Header 6'
  1886. },
  1887. lists: {
  1888. unordered: 'Unordered list',
  1889. ordered: 'Ordered list'
  1890. },
  1891. options: {
  1892. help: 'Help',
  1893. fullscreen: 'Full Screen',
  1894. codeview: 'Code View'
  1895. },
  1896. paragraph: {
  1897. paragraph: 'Paragraph',
  1898. outdent: 'Outdent',
  1899. indent: 'Indent',
  1900. left: 'Align left',
  1901. center: 'Align center',
  1902. right: 'Align right',
  1903. justify: 'Justify full'
  1904. },
  1905. color: {
  1906. recent: 'Recent Color',
  1907. more: 'More Color',
  1908. background: 'Background Color',
  1909. foreground: 'Foreground Color',
  1910. transparent: 'Transparent',
  1911. setTransparent: 'Set transparent',
  1912. reset: 'Reset',
  1913. resetToDefault: 'Reset to default'
  1914. },
  1915. shortcut: {
  1916. shortcuts: 'Keyboard shortcuts',
  1917. close: 'Close',
  1918. textFormatting: 'Text formatting',
  1919. action: 'Action',
  1920. paragraphFormatting: 'Paragraph formatting',
  1921. documentStyle: 'Document Style',
  1922. extraKeys: 'Extra keys'
  1923. },
  1924. help: {
  1925. 'insertParagraph': 'Insert Paragraph',
  1926. 'undo': 'Undoes the last command',
  1927. 'redo': 'Redoes the last command',
  1928. 'tab': 'Tab',
  1929. 'untab': 'Untab',
  1930. 'bold': 'Set a bold style',
  1931. 'italic': 'Set a italic style',
  1932. 'underline': 'Set a underline style',
  1933. 'strikethrough': 'Set a strikethrough style',
  1934. 'removeFormat': 'Clean a style',
  1935. 'justifyLeft': 'Set left align',
  1936. 'justifyCenter': 'Set center align',
  1937. 'justifyRight': 'Set right align',
  1938. 'justifyFull': 'Set full align',
  1939. 'insertUnorderedList': 'Toggle unordered list',
  1940. 'insertOrderedList': 'Toggle ordered list',
  1941. 'outdent': 'Outdent on current paragraph',
  1942. 'indent': 'Indent on current paragraph',
  1943. 'formatPara': 'Change current block\'s format as a paragraph(P tag)',
  1944. 'formatH1': 'Change current block\'s format as H1',
  1945. 'formatH2': 'Change current block\'s format as H2',
  1946. 'formatH3': 'Change current block\'s format as H3',
  1947. 'formatH4': 'Change current block\'s format as H4',
  1948. 'formatH5': 'Change current block\'s format as H5',
  1949. 'formatH6': 'Change current block\'s format as H6',
  1950. 'insertHorizontalRule': 'Insert horizontal rule',
  1951. 'linkDialog.show': 'Show Link Dialog'
  1952. },
  1953. history: {
  1954. undo: 'Undo',
  1955. redo: 'Redo'
  1956. },
  1957. specialChar: {
  1958. specialChar: 'SPECIAL CHARACTERS',
  1959. select: 'Select Special characters'
  1960. }
  1961. }
  1962. });
  1963. /**
  1964. * @class core.key
  1965. *
  1966. * Object for keycodes.
  1967. *
  1968. * @singleton
  1969. * @alternateClassName key
  1970. */
  1971. var key = (function () {
  1972. var keyMap = {
  1973. 'BACKSPACE': 8,
  1974. 'TAB': 9,
  1975. 'ENTER': 13,
  1976. 'SPACE': 32,
  1977. // Arrow
  1978. 'LEFT': 37,
  1979. 'UP': 38,
  1980. 'RIGHT': 39,
  1981. 'DOWN': 40,
  1982. // Number: 0-9
  1983. 'NUM0': 48,
  1984. 'NUM1': 49,
  1985. 'NUM2': 50,
  1986. 'NUM3': 51,
  1987. 'NUM4': 52,
  1988. 'NUM5': 53,
  1989. 'NUM6': 54,
  1990. 'NUM7': 55,
  1991. 'NUM8': 56,
  1992. // Alphabet: a-z
  1993. 'B': 66,
  1994. 'E': 69,
  1995. 'I': 73,
  1996. 'J': 74,
  1997. 'K': 75,
  1998. 'L': 76,
  1999. 'R': 82,
  2000. 'S': 83,
  2001. 'U': 85,
  2002. 'V': 86,
  2003. 'Y': 89,
  2004. 'Z': 90,
  2005. 'SLASH': 191,
  2006. 'LEFTBRACKET': 219,
  2007. 'BACKSLASH': 220,
  2008. 'RIGHTBRACKET': 221
  2009. };
  2010. return {
  2011. /**
  2012. * @method isEdit
  2013. *
  2014. * @param {Number} keyCode
  2015. * @return {Boolean}
  2016. */
  2017. isEdit: function (keyCode) {
  2018. return list.contains([
  2019. keyMap.BACKSPACE,
  2020. keyMap.TAB,
  2021. keyMap.ENTER,
  2022. keyMap.SPACE
  2023. ], keyCode);
  2024. },
  2025. /**
  2026. * @method isMove
  2027. *
  2028. * @param {Number} keyCode
  2029. * @return {Boolean}
  2030. */
  2031. isMove: function (keyCode) {
  2032. return list.contains([
  2033. keyMap.LEFT,
  2034. keyMap.UP,
  2035. keyMap.RIGHT,
  2036. keyMap.DOWN
  2037. ], keyCode);
  2038. },
  2039. /**
  2040. * @property {Object} nameFromCode
  2041. * @property {String} nameFromCode.8 "BACKSPACE"
  2042. */
  2043. nameFromCode: func.invertObject(keyMap),
  2044. code: keyMap
  2045. };
  2046. })();
  2047. var range = (function () {
  2048. /**
  2049. * return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js
  2050. *
  2051. * @param {TextRange} textRange
  2052. * @param {Boolean} isStart
  2053. * @return {BoundaryPoint}
  2054. *
  2055. * @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx
  2056. */
  2057. var textRangeToPoint = function (textRange, isStart) {
  2058. var container = textRange.parentElement(), offset;
  2059. var tester = document.body.createTextRange(), prevContainer;
  2060. var childNodes = list.from(container.childNodes);
  2061. for (offset = 0; offset < childNodes.length; offset++) {
  2062. if (dom.isText(childNodes[offset])) {
  2063. continue;
  2064. }
  2065. tester.moveToElementText(childNodes[offset]);
  2066. if (tester.compareEndPoints('StartToStart', textRange) >= 0) {
  2067. break;
  2068. }
  2069. prevContainer = childNodes[offset];
  2070. }
  2071. if (offset !== 0 && dom.isText(childNodes[offset - 1])) {
  2072. var textRangeStart = document.body.createTextRange(), curTextNode = null;
  2073. textRangeStart.moveToElementText(prevContainer || container);
  2074. textRangeStart.collapse(!prevContainer);
  2075. curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild;
  2076. var pointTester = textRange.duplicate();
  2077. pointTester.setEndPoint('StartToStart', textRangeStart);
  2078. var textCount = pointTester.text.replace(/[\r\n]/g, '').length;
  2079. while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) {
  2080. textCount -= curTextNode.nodeValue.length;
  2081. curTextNode = curTextNode.nextSibling;
  2082. }
  2083. /* jshint ignore:start */
  2084. var dummy = curTextNode.nodeValue; // enforce IE to re-reference curTextNode, hack
  2085. /* jshint ignore:end */
  2086. if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) &&
  2087. textCount === curTextNode.nodeValue.length) {
  2088. textCount -= curTextNode.nodeValue.length;
  2089. curTextNode = curTextNode.nextSibling;
  2090. }
  2091. container = curTextNode;
  2092. offset = textCount;
  2093. }
  2094. return {
  2095. cont: container,
  2096. offset: offset
  2097. };
  2098. };
  2099. /**
  2100. * return TextRange from boundary point (inspired by google closure-library)
  2101. * @param {BoundaryPoint} point
  2102. * @return {TextRange}
  2103. */
  2104. var pointToTextRange = function (point) {
  2105. var textRangeInfo = function (container, offset) {
  2106. var node, isCollapseToStart;
  2107. if (dom.isText(container)) {
  2108. var prevTextNodes = dom.listPrev(container, func.not(dom.isText));
  2109. var prevContainer = list.last(prevTextNodes).previousSibling;
  2110. node = prevContainer || container.parentNode;
  2111. offset += list.sum(list.tail(prevTextNodes), dom.nodeLength);
  2112. isCollapseToStart = !prevContainer;
  2113. } else {
  2114. node = container.childNodes[offset] || container;
  2115. if (dom.isText(node)) {
  2116. return textRangeInfo(node, 0);
  2117. }
  2118. offset = 0;
  2119. isCollapseToStart = false;
  2120. }
  2121. return {
  2122. node: node,
  2123. collapseToStart: isCollapseToStart,
  2124. offset: offset
  2125. };
  2126. };
  2127. var textRange = document.body.createTextRange();
  2128. var info = textRangeInfo(point.node, point.offset);
  2129. textRange.moveToElementText(info.node);
  2130. textRange.collapse(info.collapseToStart);
  2131. textRange.moveStart('character', info.offset);
  2132. return textRange;
  2133. };
  2134. /**
  2135. * Wrapped Range
  2136. *
  2137. * @constructor
  2138. * @param {Node} sc - start container
  2139. * @param {Number} so - start offset
  2140. * @param {Node} ec - end container
  2141. * @param {Number} eo - end offset
  2142. */
  2143. var WrappedRange = function (sc, so, ec, eo) {
  2144. this.sc = sc;
  2145. this.so = so;
  2146. this.ec = ec;
  2147. this.eo = eo;
  2148. // nativeRange: get nativeRange from sc, so, ec, eo
  2149. var nativeRange = function () {
  2150. if (agent.isW3CRangeSupport) {
  2151. var w3cRange = document.createRange();
  2152. w3cRange.setStart(sc, so);
  2153. w3cRange.setEnd(ec, eo);
  2154. return w3cRange;
  2155. } else {
  2156. var textRange = pointToTextRange({
  2157. node: sc,
  2158. offset: so
  2159. });
  2160. textRange.setEndPoint('EndToEnd', pointToTextRange({
  2161. node: ec,
  2162. offset: eo
  2163. }));
  2164. return textRange;
  2165. }
  2166. };
  2167. this.getPoints = function () {
  2168. return {
  2169. sc: sc,
  2170. so: so,
  2171. ec: ec,
  2172. eo: eo
  2173. };
  2174. };
  2175. this.getStartPoint = function () {
  2176. return {
  2177. node: sc,
  2178. offset: so
  2179. };
  2180. };
  2181. this.getEndPoint = function () {
  2182. return {
  2183. node: ec,
  2184. offset: eo
  2185. };
  2186. };
  2187. /**
  2188. * select update visible range
  2189. */
  2190. this.select = function () {
  2191. var nativeRng = nativeRange();
  2192. if (agent.isW3CRangeSupport) {
  2193. var selection = document.getSelection();
  2194. if (selection.rangeCount > 0) {
  2195. selection.removeAllRanges();
  2196. }
  2197. selection.addRange(nativeRng);
  2198. } else {
  2199. nativeRng.select();
  2200. }
  2201. return this;
  2202. };
  2203. /**
  2204. * Moves the scrollbar to start container(sc) of current range
  2205. *
  2206. * @return {WrappedRange}
  2207. */
  2208. this.scrollIntoView = function (container) {
  2209. var height = $(container).height();
  2210. if (container.scrollTop + height < this.sc.offsetTop) {
  2211. container.scrollTop += Math.abs(container.scrollTop + height - this.sc.offsetTop);
  2212. }
  2213. return this;
  2214. };
  2215. /**
  2216. * @return {WrappedRange}
  2217. */
  2218. this.normalize = function () {
  2219. /**
  2220. * @param {BoundaryPoint} point
  2221. * @param {Boolean} isLeftToRight
  2222. * @return {BoundaryPoint}
  2223. */
  2224. var getVisiblePoint = function (point, isLeftToRight) {
  2225. if ((dom.isVisiblePoint(point) && !dom.isEdgePoint(point)) ||
  2226. (dom.isVisiblePoint(point) && dom.isRightEdgePoint(point) && !isLeftToRight) ||
  2227. (dom.isVisiblePoint(point) && dom.isLeftEdgePoint(point) && isLeftToRight) ||
  2228. (dom.isVisiblePoint(point) && dom.isBlock(point.node) && dom.isEmpty(point.node))) {
  2229. return point;
  2230. }
  2231. // point on block's edge
  2232. var block = dom.ancestor(point.node, dom.isBlock);
  2233. if (((dom.isLeftEdgePointOf(point, block) || dom.isVoid(dom.prevPoint(point).node)) && !isLeftToRight) ||
  2234. ((dom.isRightEdgePointOf(point, block) || dom.isVoid(dom.nextPoint(point).node)) && isLeftToRight)) {
  2235. // returns point already on visible point
  2236. if (dom.isVisiblePoint(point)) {
  2237. return point;
  2238. }
  2239. // reverse direction
  2240. isLeftToRight = !isLeftToRight;
  2241. }
  2242. var nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) :
  2243. dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint);
  2244. return nextPoint || point;
  2245. };
  2246. var endPoint = getVisiblePoint(this.getEndPoint(), false);
  2247. var startPoint = this.isCollapsed() ? endPoint : getVisiblePoint(this.getStartPoint(), true);
  2248. return new WrappedRange(
  2249. startPoint.node,
  2250. startPoint.offset,
  2251. endPoint.node,
  2252. endPoint.offset
  2253. );
  2254. };
  2255. /**
  2256. * returns matched nodes on range
  2257. *
  2258. * @param {Function} [pred] - predicate function
  2259. * @param {Object} [options]
  2260. * @param {Boolean} [options.includeAncestor]
  2261. * @param {Boolean} [options.fullyContains]
  2262. * @return {Node[]}
  2263. */
  2264. this.nodes = function (pred, options) {
  2265. pred = pred || func.ok;
  2266. var includeAncestor = options && options.includeAncestor;
  2267. var fullyContains = options && options.fullyContains;
  2268. // TODO compare points and sort
  2269. var startPoint = this.getStartPoint();
  2270. var endPoint = this.getEndPoint();
  2271. var nodes = [];
  2272. var leftEdgeNodes = [];
  2273. dom.walkPoint(startPoint, endPoint, function (point) {
  2274. if (dom.isEditable(point.node)) {
  2275. return;
  2276. }
  2277. var node;
  2278. if (fullyContains) {
  2279. if (dom.isLeftEdgePoint(point)) {
  2280. leftEdgeNodes.push(point.node);
  2281. }
  2282. if (dom.isRightEdgePoint(point) && list.contains(leftEdgeNodes, point.node)) {
  2283. node = point.node;
  2284. }
  2285. } else if (includeAncestor) {
  2286. node = dom.ancestor(point.node, pred);
  2287. } else {
  2288. node = point.node;
  2289. }
  2290. if (node && pred(node)) {
  2291. nodes.push(node);
  2292. }
  2293. }, true);
  2294. return list.unique(nodes);
  2295. };
  2296. /**
  2297. * returns commonAncestor of range
  2298. * @return {Element} - commonAncestor
  2299. */
  2300. this.commonAncestor = function () {
  2301. return dom.commonAncestor(sc, ec);
  2302. };
  2303. /**
  2304. * returns expanded range by pred
  2305. *
  2306. * @param {Function} pred - predicate function
  2307. * @return {WrappedRange}
  2308. */
  2309. this.expand = function (pred) {
  2310. var startAncestor = dom.ancestor(sc, pred);
  2311. var endAncestor = dom.ancestor(ec, pred);
  2312. if (!startAncestor && !endAncestor) {
  2313. return new WrappedRange(sc, so, ec, eo);
  2314. }
  2315. var boundaryPoints = this.getPoints();
  2316. if (startAncestor) {
  2317. boundaryPoints.sc = startAncestor;
  2318. boundaryPoints.so = 0;
  2319. }
  2320. if (endAncestor) {
  2321. boundaryPoints.ec = endAncestor;
  2322. boundaryPoints.eo = dom.nodeLength(endAncestor);
  2323. }
  2324. return new WrappedRange(
  2325. boundaryPoints.sc,
  2326. boundaryPoints.so,
  2327. boundaryPoints.ec,
  2328. boundaryPoints.eo
  2329. );
  2330. };
  2331. /**
  2332. * @param {Boolean} isCollapseToStart
  2333. * @return {WrappedRange}
  2334. */
  2335. this.collapse = function (isCollapseToStart) {
  2336. if (isCollapseToStart) {
  2337. return new WrappedRange(sc, so, sc, so);
  2338. } else {
  2339. return new WrappedRange(ec, eo, ec, eo);
  2340. }
  2341. };
  2342. /**
  2343. * splitText on range
  2344. */
  2345. this.splitText = function () {
  2346. var isSameContainer = sc === ec;
  2347. var boundaryPoints = this.getPoints();
  2348. if (dom.isText(ec) && !dom.isEdgePoint(this.getEndPoint())) {
  2349. ec.splitText(eo);
  2350. }
  2351. if (dom.isText(sc) && !dom.isEdgePoint(this.getStartPoint())) {
  2352. boundaryPoints.sc = sc.splitText(so);
  2353. boundaryPoints.so = 0;
  2354. if (isSameContainer) {
  2355. boundaryPoints.ec = boundaryPoints.sc;
  2356. boundaryPoints.eo = eo - so;
  2357. }
  2358. }
  2359. return new WrappedRange(
  2360. boundaryPoints.sc,
  2361. boundaryPoints.so,
  2362. boundaryPoints.ec,
  2363. boundaryPoints.eo
  2364. );
  2365. };
  2366. /**
  2367. * delete contents on range
  2368. * @return {WrappedRange}
  2369. */
  2370. this.deleteContents = function () {
  2371. if (this.isCollapsed()) {
  2372. return this;
  2373. }
  2374. var rng = this.splitText();
  2375. var nodes = rng.nodes(null, {
  2376. fullyContains: true
  2377. });
  2378. // find new cursor point
  2379. var point = dom.prevPointUntil(rng.getStartPoint(), function (point) {
  2380. return !list.contains(nodes, point.node);
  2381. });
  2382. var emptyParents = [];
  2383. $.each(nodes, function (idx, node) {
  2384. // find empty parents
  2385. var parent = node.parentNode;
  2386. if (point.node !== parent && dom.nodeLength(parent) === 1) {
  2387. emptyParents.push(parent);
  2388. }
  2389. dom.remove(node, false);
  2390. });
  2391. // remove empty parents
  2392. $.each(emptyParents, function (idx, node) {
  2393. dom.remove(node, false);
  2394. });
  2395. return new WrappedRange(
  2396. point.node,
  2397. point.offset,
  2398. point.node,
  2399. point.offset
  2400. ).normalize();
  2401. };
  2402. /**
  2403. * makeIsOn: return isOn(pred) function
  2404. */
  2405. var makeIsOn = function (pred) {
  2406. return function () {
  2407. var ancestor = dom.ancestor(sc, pred);
  2408. return !!ancestor && (ancestor === dom.ancestor(ec, pred));
  2409. };
  2410. };
  2411. // isOnEditable: judge whether range is on editable or not
  2412. this.isOnEditable = makeIsOn(dom.isEditable);
  2413. // isOnList: judge whether range is on list node or not
  2414. this.isOnList = makeIsOn(dom.isList);
  2415. // isOnAnchor: judge whether range is on anchor node or not
  2416. this.isOnAnchor = makeIsOn(dom.isAnchor);
  2417. // isOnCell: judge whether range is on cell node or not
  2418. this.isOnCell = makeIsOn(dom.isCell);
  2419. // isOnData: judge whether range is on data node or not
  2420. this.isOnData = makeIsOn(dom.isData);
  2421. /**
  2422. * @param {Function} pred
  2423. * @return {Boolean}
  2424. */
  2425. this.isLeftEdgeOf = function (pred) {
  2426. if (!dom.isLeftEdgePoint(this.getStartPoint())) {
  2427. return false;
  2428. }
  2429. var node = dom.ancestor(this.sc, pred);
  2430. return node && dom.isLeftEdgeOf(this.sc, node);
  2431. };
  2432. /**
  2433. * returns whether range was collapsed or not
  2434. */
  2435. this.isCollapsed = function () {
  2436. return sc === ec && so === eo;
  2437. };
  2438. /**
  2439. * wrap inline nodes which children of body with paragraph
  2440. *
  2441. * @return {WrappedRange}
  2442. */
  2443. this.wrapBodyInlineWithPara = function () {
  2444. if (dom.isBodyContainer(sc) && dom.isEmpty(sc)) {
  2445. sc.innerHTML = dom.emptyPara;
  2446. return new WrappedRange(sc.firstChild, 0, sc.firstChild, 0);
  2447. }
  2448. /**
  2449. * [workaround] firefox often create range on not visible point. so normalize here.
  2450. * - firefox: |<p>text</p>|
  2451. * - chrome: <p>|text|</p>
  2452. */
  2453. var rng = this.normalize();
  2454. if (dom.isParaInline(sc) || dom.isPara(sc)) {
  2455. return rng;
  2456. }
  2457. // find inline top ancestor
  2458. var topAncestor;
  2459. if (dom.isInline(rng.sc)) {
  2460. var ancestors = dom.listAncestor(rng.sc, func.not(dom.isInline));
  2461. topAncestor = list.last(ancestors);
  2462. if (!dom.isInline(topAncestor)) {
  2463. topAncestor = ancestors[ancestors.length - 2] || rng.sc.childNodes[rng.so];
  2464. }
  2465. } else {
  2466. topAncestor = rng.sc.childNodes[rng.so > 0 ? rng.so - 1 : 0];
  2467. }
  2468. // siblings not in paragraph
  2469. var inlineSiblings = dom.listPrev(topAncestor, dom.isParaInline).reverse();
  2470. inlineSiblings = inlineSiblings.concat(dom.listNext(topAncestor.nextSibling, dom.isParaInline));
  2471. // wrap with paragraph
  2472. if (inlineSiblings.length) {
  2473. var para = dom.wrap(list.head(inlineSiblings), 'p');
  2474. dom.appendChildNodes(para, list.tail(inlineSiblings));
  2475. }
  2476. return this.normalize();
  2477. };
  2478. /**
  2479. * insert node at current cursor
  2480. *
  2481. * @param {Node} node
  2482. * @return {Node}
  2483. */
  2484. this.insertNode = function (node) {
  2485. var rng = this.wrapBodyInlineWithPara().deleteContents();
  2486. var info = dom.splitPoint(rng.getStartPoint(), dom.isInline(node));
  2487. if (info.rightNode) {
  2488. info.rightNode.parentNode.insertBefore(node, info.rightNode);
  2489. } else {
  2490. info.container.appendChild(node);
  2491. }
  2492. return node;
  2493. };
  2494. /**
  2495. * insert html at current cursor
  2496. */
  2497. this.pasteHTML = function (markup) {
  2498. var contentsContainer = $('<div></div>').html(markup)[0];
  2499. var childNodes = list.from(contentsContainer.childNodes);
  2500. var rng = this.wrapBodyInlineWithPara().deleteContents();
  2501. return childNodes.reverse().map(function (childNode) {
  2502. return rng.insertNode(childNode);
  2503. }).reverse();
  2504. };
  2505. /**
  2506. * returns text in range
  2507. *
  2508. * @return {String}
  2509. */
  2510. this.toString = function () {
  2511. var nativeRng = nativeRange();
  2512. return agent.isW3CRangeSupport ? nativeRng.toString() : nativeRng.text;
  2513. };
  2514. /**
  2515. * returns range for word before cursor
  2516. *
  2517. * @param {Boolean} [findAfter] - find after cursor, default: false
  2518. * @return {WrappedRange}
  2519. */
  2520. this.getWordRange = function (findAfter) {
  2521. var endPoint = this.getEndPoint();
  2522. if (!dom.isCharPoint(endPoint)) {
  2523. return this;
  2524. }
  2525. var startPoint = dom.prevPointUntil(endPoint, function (point) {
  2526. return !dom.isCharPoint(point);
  2527. });
  2528. if (findAfter) {
  2529. endPoint = dom.nextPointUntil(endPoint, function (point) {
  2530. return !dom.isCharPoint(point);
  2531. });
  2532. }
  2533. return new WrappedRange(
  2534. startPoint.node,
  2535. startPoint.offset,
  2536. endPoint.node,
  2537. endPoint.offset
  2538. );
  2539. };
  2540. /**
  2541. * create offsetPath bookmark
  2542. *
  2543. * @param {Node} editable
  2544. */
  2545. this.bookmark = function (editable) {
  2546. return {
  2547. s: {
  2548. path: dom.makeOffsetPath(editable, sc),
  2549. offset: so
  2550. },
  2551. e: {
  2552. path: dom.makeOffsetPath(editable, ec),
  2553. offset: eo
  2554. }
  2555. };
  2556. };
  2557. /**
  2558. * create offsetPath bookmark base on paragraph
  2559. *
  2560. * @param {Node[]} paras
  2561. */
  2562. this.paraBookmark = function (paras) {
  2563. return {
  2564. s: {
  2565. path: list.tail(dom.makeOffsetPath(list.head(paras), sc)),
  2566. offset: so
  2567. },
  2568. e: {
  2569. path: list.tail(dom.makeOffsetPath(list.last(paras), ec)),
  2570. offset: eo
  2571. }
  2572. };
  2573. };
  2574. /**
  2575. * getClientRects
  2576. * @return {Rect[]}
  2577. */
  2578. this.getClientRects = function () {
  2579. var nativeRng = nativeRange();
  2580. return nativeRng.getClientRects();
  2581. };
  2582. };
  2583. /**
  2584. * @class core.range
  2585. *
  2586. * Data structure
  2587. * * BoundaryPoint: a point of dom tree
  2588. * * BoundaryPoints: two boundaryPoints corresponding to the start and the end of the Range
  2589. *
  2590. * See to http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Position
  2591. *
  2592. * @singleton
  2593. * @alternateClassName range
  2594. */
  2595. return {
  2596. /**
  2597. * create Range Object From arguments or Browser Selection
  2598. *
  2599. * @param {Node} sc - start container
  2600. * @param {Number} so - start offset
  2601. * @param {Node} ec - end container
  2602. * @param {Number} eo - end offset
  2603. * @return {WrappedRange}
  2604. */
  2605. create: function (sc, so, ec, eo) {
  2606. if (arguments.length === 4) {
  2607. return new WrappedRange(sc, so, ec, eo);
  2608. } else if (arguments.length === 2) { //collapsed
  2609. ec = sc;
  2610. eo = so;
  2611. return new WrappedRange(sc, so, ec, eo);
  2612. } else {
  2613. var wrappedRange = this.createFromSelection();
  2614. if (!wrappedRange && arguments.length === 1) {
  2615. wrappedRange = this.createFromNode(arguments[0]);
  2616. return wrappedRange.collapse(dom.emptyPara === arguments[0].innerHTML);
  2617. }
  2618. return wrappedRange;
  2619. }
  2620. },
  2621. createFromSelection: function () {
  2622. var sc, so, ec, eo;
  2623. if (agent.isW3CRangeSupport) {
  2624. var selection = document.getSelection();
  2625. if (!selection || selection.rangeCount === 0) {
  2626. return null;
  2627. } else {
  2628. // Firefox will crash if `anchorNode` is a restricted element
  2629. // this can happen if it comes from another origin or due to a bug
  2630. // ie https://bugzilla.mozilla.org/show_bug.cgi?id=1495482
  2631. try {
  2632. if (dom.isBody(selection.anchorNode)) {
  2633. // Firefox: returns entire body as range on initialization.
  2634. // We won't never need it.
  2635. return null;
  2636. }
  2637. } catch(e) {
  2638. return null;
  2639. }
  2640. }
  2641. var nativeRng = selection.getRangeAt(0);
  2642. sc = nativeRng.startContainer;
  2643. so = nativeRng.startOffset;
  2644. ec = nativeRng.endContainer;
  2645. eo = nativeRng.endOffset;
  2646. } else { // IE8: TextRange
  2647. var textRange = document.selection.createRange();
  2648. var textRangeEnd = textRange.duplicate();
  2649. textRangeEnd.collapse(false);
  2650. var textRangeStart = textRange;
  2651. textRangeStart.collapse(true);
  2652. var startPoint = textRangeToPoint(textRangeStart, true),
  2653. endPoint = textRangeToPoint(textRangeEnd, false);
  2654. // same visible point case: range was collapsed.
  2655. if (dom.isText(startPoint.node) && dom.isLeftEdgePoint(startPoint) &&
  2656. dom.isTextNode(endPoint.node) && dom.isRightEdgePoint(endPoint) &&
  2657. endPoint.node.nextSibling === startPoint.node) {
  2658. startPoint = endPoint;
  2659. }
  2660. sc = startPoint.cont;
  2661. so = startPoint.offset;
  2662. ec = endPoint.cont;
  2663. eo = endPoint.offset;
  2664. }
  2665. return new WrappedRange(sc, so, ec, eo);
  2666. },
  2667. /**
  2668. * @method
  2669. *
  2670. * create WrappedRange from node
  2671. *
  2672. * @param {Node} node
  2673. * @return {WrappedRange}
  2674. */
  2675. createFromNode: function (node) {
  2676. var sc = node;
  2677. var so = 0;
  2678. var ec = node;
  2679. var eo = dom.nodeLength(ec);
  2680. // browsers can't target a picture or void node
  2681. if (dom.isVoid(sc)) {
  2682. so = dom.listPrev(sc).length - 1;
  2683. sc = sc.parentNode;
  2684. }
  2685. if (dom.isBR(ec)) {
  2686. eo = dom.listPrev(ec).length - 1;
  2687. ec = ec.parentNode;
  2688. } else if (dom.isVoid(ec)) {
  2689. eo = dom.listPrev(ec).length;
  2690. ec = ec.parentNode;
  2691. }
  2692. return this.create(sc, so, ec, eo);
  2693. },
  2694. /**
  2695. * create WrappedRange from node after position
  2696. *
  2697. * @param {Node} node
  2698. * @return {WrappedRange}
  2699. */
  2700. createFromNodeBefore: function (node) {
  2701. return this.createFromNode(node).collapse(true);
  2702. },
  2703. /**
  2704. * create WrappedRange from node after position
  2705. *
  2706. * @param {Node} node
  2707. * @return {WrappedRange}
  2708. */
  2709. createFromNodeAfter: function (node) {
  2710. return this.createFromNode(node).collapse();
  2711. },
  2712. /**
  2713. * @method
  2714. *
  2715. * create WrappedRange from bookmark
  2716. *
  2717. * @param {Node} editable
  2718. * @param {Object} bookmark
  2719. * @return {WrappedRange}
  2720. */
  2721. createFromBookmark: function (editable, bookmark) {
  2722. var sc = dom.fromOffsetPath(editable, bookmark.s.path);
  2723. var so = bookmark.s.offset;
  2724. var ec = dom.fromOffsetPath(editable, bookmark.e.path);
  2725. var eo = bookmark.e.offset;
  2726. return new WrappedRange(sc, so, ec, eo);
  2727. },
  2728. /**
  2729. * @method
  2730. *
  2731. * create WrappedRange from paraBookmark
  2732. *
  2733. * @param {Object} bookmark
  2734. * @param {Node[]} paras
  2735. * @return {WrappedRange}
  2736. */
  2737. createFromParaBookmark: function (bookmark, paras) {
  2738. var so = bookmark.s.offset;
  2739. var eo = bookmark.e.offset;
  2740. var sc = dom.fromOffsetPath(list.head(paras), bookmark.s.path);
  2741. var ec = dom.fromOffsetPath(list.last(paras), bookmark.e.path);
  2742. return new WrappedRange(sc, so, ec, eo);
  2743. }
  2744. };
  2745. })();
  2746. /**
  2747. * @class core.async
  2748. *
  2749. * Async functions which returns `Promise`
  2750. *
  2751. * @singleton
  2752. * @alternateClassName async
  2753. */
  2754. var async = (function () {
  2755. /**
  2756. * @method readFileAsDataURL
  2757. *
  2758. * read contents of file as representing URL
  2759. *
  2760. * @param {File} file
  2761. * @return {Promise} - then: dataUrl
  2762. */
  2763. var readFileAsDataURL = function (file) {
  2764. return $.Deferred(function (deferred) {
  2765. $.extend(new FileReader(), {
  2766. onload: function (e) {
  2767. var dataURL = e.target.result;
  2768. deferred.resolve(dataURL);
  2769. },
  2770. onerror: function () {
  2771. deferred.reject(this);
  2772. }
  2773. }).readAsDataURL(file);
  2774. }).promise();
  2775. };
  2776. /**
  2777. * @method createImage
  2778. *
  2779. * create `<image>` from url string
  2780. *
  2781. * @param {String} url
  2782. * @return {Promise} - then: $image
  2783. */
  2784. var createImage = function (url) {
  2785. return $.Deferred(function (deferred) {
  2786. var $img = $('<img>');
  2787. $img.one('load', function () {
  2788. $img.off('error abort');
  2789. deferred.resolve($img);
  2790. }).one('error abort', function () {
  2791. $img.off('load').detach();
  2792. deferred.reject($img);
  2793. }).css({
  2794. display: 'none'
  2795. }).appendTo(document.body).attr('src', url);
  2796. }).promise();
  2797. };
  2798. return {
  2799. readFileAsDataURL: readFileAsDataURL,
  2800. createImage: createImage
  2801. };
  2802. })();
  2803. /**
  2804. * @class editing.History
  2805. *
  2806. * Editor History
  2807. *
  2808. */
  2809. var History = function ($editable) {
  2810. var stack = [], stackOffset = -1;
  2811. var editable = $editable[0];
  2812. var makeSnapshot = function () {
  2813. var rng = range.create(editable);
  2814. var emptyBookmark = {s: {path: [], offset: 0}, e: {path: [], offset: 0}};
  2815. return {
  2816. contents: $editable.html(),
  2817. bookmark: (rng ? rng.bookmark(editable) : emptyBookmark)
  2818. };
  2819. };
  2820. var applySnapshot = function (snapshot) {
  2821. if (snapshot.contents !== null) {
  2822. $editable.html(snapshot.contents);
  2823. }
  2824. if (snapshot.bookmark !== null) {
  2825. range.createFromBookmark(editable, snapshot.bookmark).select();
  2826. }
  2827. };
  2828. /**
  2829. * @method rewind
  2830. * Rewinds the history stack back to the first snapshot taken.
  2831. * Leaves the stack intact, so that "Redo" can still be used.
  2832. */
  2833. this.rewind = function () {
  2834. // Create snap shot if not yet recorded
  2835. if ($editable.html() !== stack[stackOffset].contents) {
  2836. this.recordUndo();
  2837. }
  2838. // Return to the first available snapshot.
  2839. stackOffset = 0;
  2840. // Apply that snapshot.
  2841. applySnapshot(stack[stackOffset]);
  2842. };
  2843. /**
  2844. * @method reset
  2845. * Resets the history stack completely; reverting to an empty editor.
  2846. */
  2847. this.reset = function () {
  2848. // Clear the stack.
  2849. stack = [];
  2850. // Restore stackOffset to its original value.
  2851. stackOffset = -1;
  2852. // Clear the editable area.
  2853. $editable.html('');
  2854. // Record our first snapshot (of nothing).
  2855. this.recordUndo();
  2856. };
  2857. /**
  2858. * undo
  2859. */
  2860. this.undo = function () {
  2861. // Create snap shot if not yet recorded
  2862. if ($editable.html() !== stack[stackOffset].contents) {
  2863. this.recordUndo();
  2864. }
  2865. if (0 < stackOffset) {
  2866. stackOffset--;
  2867. applySnapshot(stack[stackOffset]);
  2868. }
  2869. };
  2870. /**
  2871. * redo
  2872. */
  2873. this.redo = function () {
  2874. if (stack.length - 1 > stackOffset) {
  2875. stackOffset++;
  2876. applySnapshot(stack[stackOffset]);
  2877. }
  2878. };
  2879. /**
  2880. * recorded undo
  2881. */
  2882. this.recordUndo = function () {
  2883. stackOffset++;
  2884. // Wash out stack after stackOffset
  2885. if (stack.length > stackOffset) {
  2886. stack = stack.slice(0, stackOffset);
  2887. }
  2888. // Create new snapshot and push it to the end
  2889. stack.push(makeSnapshot());
  2890. };
  2891. };
  2892. /**
  2893. * @class editing.Style
  2894. *
  2895. * Style
  2896. *
  2897. */
  2898. var Style = function () {
  2899. /**
  2900. * @method jQueryCSS
  2901. *
  2902. * [workaround] for old jQuery
  2903. * passing an array of style properties to .css()
  2904. * will result in an object of property-value pairs.
  2905. * (compability with version < 1.9)
  2906. *
  2907. * @private
  2908. * @param {jQuery} $obj
  2909. * @param {Array} propertyNames - An array of one or more CSS properties.
  2910. * @return {Object}
  2911. */
  2912. var jQueryCSS = function ($obj, propertyNames) {
  2913. if (agent.jqueryVersion < 1.9) {
  2914. var result = {};
  2915. $.each(propertyNames, function (idx, propertyName) {
  2916. result[propertyName] = $obj.css(propertyName);
  2917. });
  2918. return result;
  2919. }
  2920. return $obj.css.call($obj, propertyNames);
  2921. };
  2922. /**
  2923. * returns style object from node
  2924. *
  2925. * @param {jQuery} $node
  2926. * @return {Object}
  2927. */
  2928. this.fromNode = function ($node) {
  2929. var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height', 'color'];
  2930. var styleInfo = jQueryCSS($node, properties) || {};
  2931. styleInfo['font-size'] = parseInt(styleInfo['font-size'], 10);
  2932. return styleInfo;
  2933. };
  2934. /**
  2935. * paragraph level style
  2936. *
  2937. * @param {WrappedRange} rng
  2938. * @param {Object} styleInfo
  2939. */
  2940. this.stylePara = function (rng, styleInfo) {
  2941. $.each(rng.nodes(dom.isPara, {
  2942. includeAncestor: true
  2943. }), function (idx, para) {
  2944. $(para).css(styleInfo);
  2945. });
  2946. };
  2947. /**
  2948. * insert and returns styleNodes on range.
  2949. *
  2950. * @param {WrappedRange} rng
  2951. * @param {Object} [options] - options for styleNodes
  2952. * @param {String} [options.nodeName] - default: `SPAN`
  2953. * @param {Boolean} [options.expandClosestSibling] - default: `false`
  2954. * @param {Boolean} [options.onlyPartialContains] - default: `false`
  2955. * @return {Node[]}
  2956. */
  2957. this.styleNodes = function (rng, options) {
  2958. rng = rng.splitText();
  2959. var nodeName = options && options.nodeName || 'SPAN';
  2960. var expandClosestSibling = !!(options && options.expandClosestSibling);
  2961. var onlyPartialContains = !!(options && options.onlyPartialContains);
  2962. if (rng.isCollapsed()) {
  2963. return [rng.insertNode(dom.create(nodeName))];
  2964. }
  2965. var pred = dom.makePredByNodeName(nodeName);
  2966. var nodes = rng.nodes(dom.isText, {
  2967. fullyContains: true
  2968. }).map(function (text) {
  2969. return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName);
  2970. });
  2971. if (expandClosestSibling) {
  2972. if (onlyPartialContains) {
  2973. var nodesInRange = rng.nodes();
  2974. // compose with partial contains predication
  2975. pred = func.and(pred, function (node) {
  2976. return list.contains(nodesInRange, node);
  2977. });
  2978. }
  2979. return nodes.map(function (node) {
  2980. var siblings = dom.withClosestSiblings(node, pred);
  2981. var head = list.head(siblings);
  2982. var tails = list.tail(siblings);
  2983. $.each(tails, function (idx, elem) {
  2984. dom.appendChildNodes(head, elem.childNodes);
  2985. dom.remove(elem);
  2986. });
  2987. return list.head(siblings);
  2988. });
  2989. } else {
  2990. return nodes;
  2991. }
  2992. };
  2993. /**
  2994. * get current style on cursor
  2995. *
  2996. * @param {WrappedRange} rng
  2997. * @return {Object} - object contains style properties.
  2998. */
  2999. this.current = function (rng) {
  3000. var $cont = $(!dom.isElement(rng.sc) ? rng.sc.parentNode : rng.sc);
  3001. var styleInfo = this.fromNode($cont);
  3002. // document.queryCommandState for toggle state
  3003. // [workaround] prevent Firefox nsresult: "0x80004005 (NS_ERROR_FAILURE)"
  3004. try {
  3005. styleInfo = $.extend(styleInfo, {
  3006. 'font-bold': document.queryCommandState('bold') ? 'bold' : 'normal',
  3007. 'font-italic': document.queryCommandState('italic') ? 'italic' : 'normal',
  3008. 'font-underline': document.queryCommandState('underline') ? 'underline' : 'normal',
  3009. 'font-subscript': document.queryCommandState('subscript') ? 'subscript' : 'normal',
  3010. 'font-superscript': document.queryCommandState('superscript') ? 'superscript' : 'normal',
  3011. 'font-strikethrough': document.queryCommandState('strikethrough') ? 'strikethrough' : 'normal'
  3012. });
  3013. } catch (e) {}
  3014. // list-style-type to list-style(unordered, ordered)
  3015. if (!rng.isOnList()) {
  3016. styleInfo['list-style'] = 'none';
  3017. } else {
  3018. var orderedTypes = ['circle', 'disc', 'disc-leading-zero', 'square'];
  3019. var isUnordered = $.inArray(styleInfo['list-style-type'], orderedTypes) > -1;
  3020. styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered';
  3021. }
  3022. var para = dom.ancestor(rng.sc, dom.isPara);
  3023. if (para && para.style['line-height']) {
  3024. styleInfo['line-height'] = para.style.lineHeight;
  3025. } else {
  3026. var lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10);
  3027. styleInfo['line-height'] = lineHeight.toFixed(1);
  3028. }
  3029. styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor);
  3030. styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable);
  3031. styleInfo.range = rng;
  3032. return styleInfo;
  3033. };
  3034. };
  3035. /**
  3036. * @class editing.Bullet
  3037. *
  3038. * @alternateClassName Bullet
  3039. */
  3040. var Bullet = function () {
  3041. var self = this;
  3042. /**
  3043. * toggle ordered list
  3044. */
  3045. this.insertOrderedList = function (editable) {
  3046. this.toggleList('OL', editable);
  3047. };
  3048. /**
  3049. * toggle unordered list
  3050. */
  3051. this.insertUnorderedList = function (editable) {
  3052. this.toggleList('UL', editable);
  3053. };
  3054. /**
  3055. * indent
  3056. */
  3057. this.indent = function (editable) {
  3058. var self = this;
  3059. var rng = range.create(editable).wrapBodyInlineWithPara();
  3060. var paras = rng.nodes(dom.isPara, { includeAncestor: true });
  3061. var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
  3062. $.each(clustereds, function (idx, paras) {
  3063. var head = list.head(paras);
  3064. if (dom.isLi(head)) {
  3065. self.wrapList(paras, head.parentNode.nodeName);
  3066. } else {
  3067. $.each(paras, function (idx, para) {
  3068. $(para).css('marginLeft', function (idx, val) {
  3069. return (parseInt(val, 10) || 0) + 25;
  3070. });
  3071. });
  3072. }
  3073. });
  3074. rng.select();
  3075. };
  3076. /**
  3077. * outdent
  3078. */
  3079. this.outdent = function (editable) {
  3080. var self = this;
  3081. var rng = range.create(editable).wrapBodyInlineWithPara();
  3082. var paras = rng.nodes(dom.isPara, { includeAncestor: true });
  3083. var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
  3084. $.each(clustereds, function (idx, paras) {
  3085. var head = list.head(paras);
  3086. if (dom.isLi(head)) {
  3087. self.releaseList([paras]);
  3088. } else {
  3089. $.each(paras, function (idx, para) {
  3090. $(para).css('marginLeft', function (idx, val) {
  3091. val = (parseInt(val, 10) || 0);
  3092. return val > 25 ? val - 25 : '';
  3093. });
  3094. });
  3095. }
  3096. });
  3097. rng.select();
  3098. };
  3099. /**
  3100. * toggle list
  3101. *
  3102. * @param {String} listName - OL or UL
  3103. */
  3104. this.toggleList = function (listName, editable) {
  3105. var rng = range.create(editable).wrapBodyInlineWithPara();
  3106. var paras = rng.nodes(dom.isPara, { includeAncestor: true });
  3107. var bookmark = rng.paraBookmark(paras);
  3108. var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
  3109. // paragraph to list
  3110. if (list.find(paras, dom.isPurePara)) {
  3111. var wrappedParas = [];
  3112. $.each(clustereds, function (idx, paras) {
  3113. wrappedParas = wrappedParas.concat(self.wrapList(paras, listName));
  3114. });
  3115. paras = wrappedParas;
  3116. // list to paragraph or change list style
  3117. } else {
  3118. var diffLists = rng.nodes(dom.isList, {
  3119. includeAncestor: true
  3120. }).filter(function (listNode) {
  3121. return !$.nodeName(listNode, listName);
  3122. });
  3123. if (diffLists.length) {
  3124. $.each(diffLists, function (idx, listNode) {
  3125. dom.replace(listNode, listName);
  3126. });
  3127. } else {
  3128. paras = this.releaseList(clustereds, true);
  3129. }
  3130. }
  3131. range.createFromParaBookmark(bookmark, paras).select();
  3132. };
  3133. /**
  3134. * @param {Node[]} paras
  3135. * @param {String} listName
  3136. * @return {Node[]}
  3137. */
  3138. this.wrapList = function (paras, listName) {
  3139. var head = list.head(paras);
  3140. var last = list.last(paras);
  3141. var prevList = dom.isList(head.previousSibling) && head.previousSibling;
  3142. var nextList = dom.isList(last.nextSibling) && last.nextSibling;
  3143. var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last);
  3144. // P to LI
  3145. paras = paras.map(function (para) {
  3146. return dom.isPurePara(para) ? dom.replace(para, 'LI') : para;
  3147. });
  3148. // append to list(<ul>, <ol>)
  3149. dom.appendChildNodes(listNode, paras);
  3150. if (nextList) {
  3151. dom.appendChildNodes(listNode, list.from(nextList.childNodes));
  3152. dom.remove(nextList);
  3153. }
  3154. return paras;
  3155. };
  3156. /**
  3157. * @method releaseList
  3158. *
  3159. * @param {Array[]} clustereds
  3160. * @param {Boolean} isEscapseToBody
  3161. * @return {Node[]}
  3162. */
  3163. this.releaseList = function (clustereds, isEscapseToBody) {
  3164. var releasedParas = [];
  3165. $.each(clustereds, function (idx, paras) {
  3166. var head = list.head(paras);
  3167. var last = list.last(paras);
  3168. var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) :
  3169. head.parentNode;
  3170. var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, {
  3171. node: last.parentNode,
  3172. offset: dom.position(last) + 1
  3173. }, {
  3174. isSkipPaddingBlankHTML: true
  3175. }) : null;
  3176. var middleList = dom.splitTree(headList, {
  3177. node: head.parentNode,
  3178. offset: dom.position(head)
  3179. }, {
  3180. isSkipPaddingBlankHTML: true
  3181. });
  3182. paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) :
  3183. list.from(middleList.childNodes).filter(dom.isLi);
  3184. // LI to P
  3185. if (isEscapseToBody || !dom.isList(headList.parentNode)) {
  3186. paras = paras.map(function (para) {
  3187. return dom.replace(para, 'P');
  3188. });
  3189. }
  3190. $.each(list.from(paras).reverse(), function (idx, para) {
  3191. dom.insertAfter(para, headList);
  3192. });
  3193. // remove empty lists
  3194. var rootLists = list.compact([headList, middleList, lastList]);
  3195. $.each(rootLists, function (idx, rootList) {
  3196. var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList));
  3197. $.each(listNodes.reverse(), function (idx, listNode) {
  3198. if (!dom.nodeLength(listNode)) {
  3199. dom.remove(listNode, true);
  3200. }
  3201. });
  3202. });
  3203. releasedParas = releasedParas.concat(paras);
  3204. });
  3205. return releasedParas;
  3206. };
  3207. };
  3208. /**
  3209. * @class editing.Typing
  3210. *
  3211. * Typing
  3212. *
  3213. */
  3214. var Typing = function () {
  3215. // a Bullet instance to toggle lists off
  3216. var bullet = new Bullet();
  3217. /**
  3218. * insert tab
  3219. *
  3220. * @param {WrappedRange} rng
  3221. * @param {Number} tabsize
  3222. */
  3223. this.insertTab = function (rng, tabsize) {
  3224. var tab = dom.createText(new Array(tabsize + 1).join(dom.NBSP_CHAR));
  3225. rng = rng.deleteContents();
  3226. rng.insertNode(tab, true);
  3227. rng = range.create(tab, tabsize);
  3228. rng.select();
  3229. };
  3230. /**
  3231. * insert paragraph
  3232. */
  3233. this.insertParagraph = function (editable) {
  3234. var rng = range.create(editable);
  3235. // deleteContents on range.
  3236. rng = rng.deleteContents();
  3237. // Wrap range if it needs to be wrapped by paragraph
  3238. rng = rng.wrapBodyInlineWithPara();
  3239. // finding paragraph
  3240. var splitRoot = dom.ancestor(rng.sc, dom.isPara);
  3241. var nextPara;
  3242. // on paragraph: split paragraph
  3243. if (splitRoot) {
  3244. // if it is an empty line with li
  3245. if (dom.isEmpty(splitRoot) && dom.isLi(splitRoot)) {
  3246. // toogle UL/OL and escape
  3247. bullet.toggleList(splitRoot.parentNode.nodeName);
  3248. return;
  3249. // if it is an empty line with para on blockquote
  3250. } else if (dom.isEmpty(splitRoot) && dom.isPara(splitRoot) && dom.isBlockquote(splitRoot.parentNode)) {
  3251. // escape blockquote
  3252. dom.insertAfter(splitRoot, splitRoot.parentNode);
  3253. nextPara = splitRoot;
  3254. // if new line has content (not a line break)
  3255. } else {
  3256. nextPara = dom.splitTree(splitRoot, rng.getStartPoint());
  3257. var emptyAnchors = dom.listDescendant(splitRoot, dom.isEmptyAnchor);
  3258. emptyAnchors = emptyAnchors.concat(dom.listDescendant(nextPara, dom.isEmptyAnchor));
  3259. $.each(emptyAnchors, function (idx, anchor) {
  3260. dom.remove(anchor);
  3261. });
  3262. // replace empty heading or pre with P tag
  3263. if ((dom.isHeading(nextPara) || dom.isPre(nextPara)) && dom.isEmpty(nextPara)) {
  3264. nextPara = dom.replace(nextPara, 'p');
  3265. }
  3266. }
  3267. // no paragraph: insert empty paragraph
  3268. } else {
  3269. var next = rng.sc.childNodes[rng.so];
  3270. nextPara = $(dom.emptyPara)[0];
  3271. if (next) {
  3272. rng.sc.insertBefore(nextPara, next);
  3273. } else {
  3274. rng.sc.appendChild(nextPara);
  3275. }
  3276. }
  3277. range.create(nextPara, 0).normalize().select().scrollIntoView(editable);
  3278. };
  3279. };
  3280. /**
  3281. * @class editing.Table
  3282. *
  3283. * Table
  3284. *
  3285. */
  3286. var Table = function () {
  3287. /**
  3288. * handle tab key
  3289. *
  3290. * @param {WrappedRange} rng
  3291. * @param {Boolean} isShift
  3292. */
  3293. this.tab = function (rng, isShift) {
  3294. var cell = dom.ancestor(rng.commonAncestor(), dom.isCell);
  3295. var table = dom.ancestor(cell, dom.isTable);
  3296. var cells = dom.listDescendant(table, dom.isCell);
  3297. var nextCell = list[isShift ? 'prev' : 'next'](cells, cell);
  3298. if (nextCell) {
  3299. range.create(nextCell, 0).select();
  3300. }
  3301. };
  3302. /**
  3303. * create empty table element
  3304. *
  3305. * @param {Number} rowCount
  3306. * @param {Number} colCount
  3307. * @return {Node}
  3308. */
  3309. this.createTable = function (colCount, rowCount, options) {
  3310. var tds = [], tdHTML;
  3311. for (var idxCol = 0; idxCol < colCount; idxCol++) {
  3312. tds.push('<td>' + dom.blank + '</td>');
  3313. }
  3314. tdHTML = tds.join('');
  3315. var trs = [], trHTML;
  3316. for (var idxRow = 0; idxRow < rowCount; idxRow++) {
  3317. trs.push('<tr>' + tdHTML + '</tr>');
  3318. }
  3319. trHTML = trs.join('');
  3320. var $table = $('<table>' + trHTML + '</table>');
  3321. if (options && options.tableClassName) {
  3322. $table.addClass(options.tableClassName);
  3323. }
  3324. return $table[0];
  3325. };
  3326. };
  3327. var KEY_BOGUS = 'bogus';
  3328. /**
  3329. * @class Editor
  3330. */
  3331. var Editor = function (context) {
  3332. var self = this;
  3333. var $note = context.layoutInfo.note;
  3334. var $editor = context.layoutInfo.editor;
  3335. var $editable = context.layoutInfo.editable;
  3336. var options = context.options;
  3337. var lang = options.langInfo;
  3338. var editable = $editable[0];
  3339. var lastRange = null;
  3340. var style = new Style();
  3341. var table = new Table();
  3342. var typing = new Typing();
  3343. var bullet = new Bullet();
  3344. var history = new History($editable);
  3345. this.initialize = function () {
  3346. // bind custom events
  3347. $editable.on('keydown', function (event) {
  3348. if (event.keyCode === key.code.ENTER) {
  3349. context.triggerEvent('enter', event);
  3350. }
  3351. context.triggerEvent('keydown', event);
  3352. if (!event.isDefaultPrevented()) {
  3353. if (options.shortcuts) {
  3354. self.handleKeyMap(event);
  3355. } else {
  3356. self.preventDefaultEditableShortCuts(event);
  3357. }
  3358. }
  3359. }).on('keyup', function (event) {
  3360. context.triggerEvent('keyup', event);
  3361. }).on('focus', function (event) {
  3362. context.triggerEvent('focus', event);
  3363. }).on('blur', function (event) {
  3364. context.triggerEvent('blur', event);
  3365. }).on('mousedown', function (event) {
  3366. context.triggerEvent('mousedown', event);
  3367. }).on('mouseup', function (event) {
  3368. context.triggerEvent('mouseup', event);
  3369. }).on('scroll', function (event) {
  3370. context.triggerEvent('scroll', event);
  3371. }).on('paste', function (event) {
  3372. context.triggerEvent('paste', event);
  3373. });
  3374. // init content before set event
  3375. $editable.html(dom.html($note) || dom.emptyPara);
  3376. // [workaround] IE doesn't have input events for contentEditable
  3377. // - see: https://goo.gl/4bfIvA
  3378. var changeEventName = agent.isMSIE ? 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted' : 'input';
  3379. $editable.on(changeEventName, func.debounce(function () {
  3380. context.triggerEvent('change', $editable.html());
  3381. }, 250));
  3382. $editor.on('focusin', function (event) {
  3383. context.triggerEvent('focusin', event);
  3384. }).on('focusout', function (event) {
  3385. context.triggerEvent('focusout', event);
  3386. });
  3387. if (!options.airMode) {
  3388. if (options.width) {
  3389. $editor.outerWidth(options.width);
  3390. }
  3391. if (options.height) {
  3392. $editable.outerHeight(options.height);
  3393. }
  3394. if (options.maxHeight) {
  3395. $editable.css('max-height', options.maxHeight);
  3396. }
  3397. if (options.minHeight) {
  3398. $editable.css('min-height', options.minHeight);
  3399. }
  3400. }
  3401. history.recordUndo();
  3402. };
  3403. this.destroy = function () {
  3404. $editable.off();
  3405. };
  3406. this.handleKeyMap = function (event) {
  3407. var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc'];
  3408. var keys = [];
  3409. if (event.metaKey) { keys.push('CMD'); }
  3410. if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); }
  3411. if (event.shiftKey) { keys.push('SHIFT'); }
  3412. var keyName = key.nameFromCode[event.keyCode];
  3413. if (keyName) {
  3414. keys.push(keyName);
  3415. }
  3416. var eventName = keyMap[keys.join('+')];
  3417. if (eventName) {
  3418. event.preventDefault();
  3419. context.invoke(eventName);
  3420. } else if (key.isEdit(event.keyCode)) {
  3421. this.afterCommand();
  3422. }
  3423. };
  3424. this.preventDefaultEditableShortCuts = function (event) {
  3425. // B(Bold, 66) / I(Italic, 73) / U(Underline, 85)
  3426. if ((event.ctrlKey || event.metaKey) &&
  3427. list.contains([66, 73, 85], event.keyCode)) {
  3428. event.preventDefault();
  3429. }
  3430. };
  3431. /**
  3432. * create range
  3433. * @return {WrappedRange}
  3434. */
  3435. this.createRange = function () {
  3436. this.focus();
  3437. return range.create(editable);
  3438. };
  3439. /**
  3440. * saveRange
  3441. *
  3442. * save current range
  3443. *
  3444. * @param {Boolean} [thenCollapse=false]
  3445. */
  3446. this.saveRange = function (thenCollapse) {
  3447. lastRange = this.createRange();
  3448. if (thenCollapse) {
  3449. lastRange.collapse().select();
  3450. }
  3451. };
  3452. /**
  3453. * restoreRange
  3454. *
  3455. * restore lately range
  3456. */
  3457. this.restoreRange = function () {
  3458. if (lastRange) {
  3459. lastRange.select();
  3460. this.focus();
  3461. }
  3462. };
  3463. this.saveTarget = function (node) {
  3464. $editable.data('target', node);
  3465. };
  3466. this.clearTarget = function () {
  3467. $editable.removeData('target');
  3468. };
  3469. this.restoreTarget = function () {
  3470. return $editable.data('target');
  3471. };
  3472. /**
  3473. * currentStyle
  3474. *
  3475. * current style
  3476. * @return {Object|Boolean} unfocus
  3477. */
  3478. this.currentStyle = function () {
  3479. var rng = range.create();
  3480. if (rng) {
  3481. rng = rng.normalize();
  3482. }
  3483. return rng ? style.current(rng) : style.fromNode($editable);
  3484. };
  3485. /**
  3486. * style from node
  3487. *
  3488. * @param {jQuery} $node
  3489. * @return {Object}
  3490. */
  3491. this.styleFromNode = function ($node) {
  3492. return style.fromNode($node);
  3493. };
  3494. /**
  3495. * undo
  3496. */
  3497. this.undo = function () {
  3498. context.triggerEvent('before.command', $editable.html());
  3499. history.undo();
  3500. context.triggerEvent('change', $editable.html());
  3501. };
  3502. context.memo('help.undo', lang.help.undo);
  3503. /**
  3504. * redo
  3505. */
  3506. this.redo = function () {
  3507. context.triggerEvent('before.command', $editable.html());
  3508. history.redo();
  3509. context.triggerEvent('change', $editable.html());
  3510. };
  3511. context.memo('help.redo', lang.help.redo);
  3512. /**
  3513. * before command
  3514. */
  3515. var beforeCommand = this.beforeCommand = function () {
  3516. context.triggerEvent('before.command', $editable.html());
  3517. // keep focus on editable before command execution
  3518. self.focus();
  3519. };
  3520. /**
  3521. * after command
  3522. * @param {Boolean} isPreventTrigger
  3523. */
  3524. var afterCommand = this.afterCommand = function (isPreventTrigger) {
  3525. history.recordUndo();
  3526. if (!isPreventTrigger) {
  3527. context.triggerEvent('change', $editable.html());
  3528. }
  3529. };
  3530. /* jshint ignore:start */
  3531. // native commands(with execCommand), generate function for execCommand
  3532. var commands = ['bold', 'italic', 'underline', 'strikethrough', 'superscript',
  3533. 'subscript', 'justifyLeft', 'justifyCenter', 'justifyRight',
  3534. 'justifyFull','formatBlock', 'removeFormat', 'backColor',
  3535. 'foreColor', 'fontName'];
  3536. for (var idx = 0, len = commands.length; idx < len; idx ++) {
  3537. this[commands[idx]] = (function (sCmd) {
  3538. return function (value) {
  3539. beforeCommand();
  3540. document.execCommand(sCmd, false, value);
  3541. afterCommand(true);
  3542. };
  3543. })(commands[idx]);
  3544. context.memo('help.' + commands[idx], lang.help[commands[idx]]);
  3545. }
  3546. /* jshint ignore:end */
  3547. /**
  3548. * handle tab key
  3549. */
  3550. this.tab = function () {
  3551. var rng = this.createRange();
  3552. if (rng.isCollapsed() && rng.isOnCell()) {
  3553. table.tab(rng);
  3554. } else {
  3555. beforeCommand();
  3556. typing.insertTab(rng, options.tabSize);
  3557. afterCommand();
  3558. }
  3559. };
  3560. context.memo('help.tab', lang.help.tab);
  3561. /**
  3562. * handle shift+tab key
  3563. */
  3564. this.untab = function () {
  3565. var rng = this.createRange();
  3566. if (rng.isCollapsed() && rng.isOnCell()) {
  3567. table.tab(rng, true);
  3568. }
  3569. };
  3570. context.memo('help.untab', lang.help.untab);
  3571. /**
  3572. *+------------------------------------------------------------------------+
  3573. *| oliviaperryman / agaouaou: Start of IBM Changes to Summernote
  3574. *+------------------------------------------------------------------------+
  3575. * addClassToSelection
  3576. * @param {Object} options Object with the classes to add or remove
  3577. * @param {String} options.add Class to add
  3578. * @param {String} options.remove Class to remove
  3579. * @param {Range} rangeParam Range of the selectin
  3580. **/
  3581. this.updateClassToSelection = function (options, rangeParam) {
  3582. var rng;
  3583. if (rangeParam) {
  3584. rng = rangeParam;
  3585. } else {
  3586. rng = this.createRange();
  3587. }
  3588. // Do not look for span if we're only removing a class.
  3589. if ( !(rng.toString() === '' && !options.add) ) {
  3590. var spans = style.styleNodes(rng);
  3591. if (rng && options.remove) {
  3592. $(spans).each(function () {
  3593. $(this).removeClass(options.remove);
  3594. });
  3595. }
  3596. if (rng && options.add) {
  3597. $(spans).each(function () {
  3598. $(this).addClass(options.add);
  3599. });
  3600. }
  3601. if (rng && rng.isCollapsed()) {
  3602. var firstSpan = list.head(spans);
  3603. if (firstSpan && !dom.nodeLength(firstSpan)) {
  3604. firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR;
  3605. range.createFromNodeAfter(firstSpan.firstChild).select();
  3606. $editable.data(KEY_BOGUS, firstSpan);
  3607. }
  3608. }
  3609. }
  3610. };
  3611. /**
  3612. *+------------------------------------------------------------------------+
  3613. *| End of IBM changes to Summernote
  3614. *+------------------------------------------------------------------------+
  3615. **/
  3616. /**
  3617. * run given function between beforeCommand and afterCommand
  3618. */
  3619. this.wrapCommand = function (fn) {
  3620. return function () {
  3621. beforeCommand();
  3622. fn.apply(self, arguments);
  3623. afterCommand();
  3624. };
  3625. };
  3626. /**
  3627. * insert paragraph
  3628. */
  3629. this.insertParagraph = this.wrapCommand(function () {
  3630. typing.insertParagraph(editable);
  3631. });
  3632. context.memo('help.insertParagraph', lang.help.insertParagraph);
  3633. this.insertOrderedList = this.wrapCommand(function () {
  3634. bullet.insertOrderedList(editable);
  3635. });
  3636. context.memo('help.insertOrderedList', lang.help.insertOrderedList);
  3637. this.insertUnorderedList = this.wrapCommand(function () {
  3638. bullet.insertUnorderedList(editable);
  3639. });
  3640. context.memo('help.insertUnorderedList', lang.help.insertUnorderedList);
  3641. this.indent = this.wrapCommand(function () {
  3642. bullet.indent(editable);
  3643. });
  3644. context.memo('help.indent', lang.help.indent);
  3645. this.outdent = this.wrapCommand(function () {
  3646. bullet.outdent(editable);
  3647. });
  3648. context.memo('help.outdent', lang.help.outdent);
  3649. /**
  3650. * insert image
  3651. *
  3652. * @param {String} src
  3653. * @param {String|Function} param
  3654. * @return {Promise}
  3655. */
  3656. this.insertImage = function (src, param) {
  3657. return async.createImage(src, param).then(function ($image) {
  3658. beforeCommand();
  3659. if (typeof param === 'function') {
  3660. param($image);
  3661. } else {
  3662. if (typeof param === 'string') {
  3663. $image.attr('data-filename', param);
  3664. }
  3665. $image.css('width', Math.min($editable.width(), $image.width()));
  3666. }
  3667. $image.show();
  3668. range.create(editable).insertNode($image[0]);
  3669. range.createFromNodeAfter($image[0]).select();
  3670. afterCommand();
  3671. }).fail(function (e) {
  3672. context.triggerEvent('image.upload.error', e);
  3673. });
  3674. };
  3675. /**
  3676. * insertImages
  3677. * @param {File[]} files
  3678. */
  3679. this.insertImages = function (files) {
  3680. $.each(files, function (idx, file) {
  3681. var filename = file.name;
  3682. if (options.maximumImageFileSize && options.maximumImageFileSize < file.size) {
  3683. context.triggerEvent('image.upload.error', lang.image.maximumFileSizeError);
  3684. } else {
  3685. async.readFileAsDataURL(file).then(function (dataURL) {
  3686. return self.insertImage(dataURL, filename);
  3687. }).fail(function () {
  3688. context.triggerEvent('image.upload.error');
  3689. });
  3690. }
  3691. });
  3692. };
  3693. /**
  3694. * insertImagesOrCallback
  3695. * @param {File[]} files
  3696. */
  3697. this.insertImagesOrCallback = function (files) {
  3698. var callbacks = options.callbacks;
  3699. // If onImageUpload options setted
  3700. if (callbacks.onImageUpload) {
  3701. context.triggerEvent('image.upload', files);
  3702. // else insert Image as dataURL
  3703. } else {
  3704. this.insertImages(files);
  3705. }
  3706. };
  3707. /**
  3708. * insertNode
  3709. * insert node
  3710. * @param {Node} node
  3711. */
  3712. this.insertNode = this.wrapCommand(function (node) {
  3713. var rng = this.createRange();
  3714. rng.insertNode(node);
  3715. range.createFromNodeAfter(node).select();
  3716. });
  3717. /**
  3718. * insert text
  3719. * @param {String} text
  3720. */
  3721. this.insertText = this.wrapCommand(function (text) {
  3722. var rng = this.createRange();
  3723. var textNode = rng.insertNode(dom.createText(text));
  3724. range.create(textNode, dom.nodeLength(textNode)).select();
  3725. });
  3726. /**
  3727. * return selected plain text
  3728. * @return {String} text
  3729. */
  3730. this.getSelectedText = function () {
  3731. var rng = this.createRange();
  3732. // if range on anchor, expand range with anchor
  3733. if (rng.isOnAnchor()) {
  3734. rng = range.createFromNode(dom.ancestor(rng.sc, dom.isAnchor));
  3735. }
  3736. return rng.toString();
  3737. };
  3738. /**
  3739. * paste HTML
  3740. * @param {String} markup
  3741. */
  3742. this.pasteHTML = this.wrapCommand(function (markup) {
  3743. var contents = this.createRange().pasteHTML(markup);
  3744. range.createFromNodeAfter(list.last(contents)).select();
  3745. });
  3746. /**
  3747. * formatBlock
  3748. *
  3749. * @param {String} tagName
  3750. */
  3751. this.formatBlock = this.wrapCommand(function (tagName) {
  3752. // [workaround] for MSIE, IE need `<`
  3753. tagName = agent.isMSIE ? '<' + tagName + '>' : tagName;
  3754. document.execCommand('FormatBlock', false, tagName);
  3755. });
  3756. this.formatPara = function () {
  3757. this.formatBlock('P');
  3758. };
  3759. context.memo('help.formatPara', lang.help.formatPara);
  3760. /* jshint ignore:start */
  3761. for (var idx = 1; idx <= 6; idx ++) {
  3762. this['formatH' + idx] = function (idx) {
  3763. return function () {
  3764. this.formatBlock('H' + idx);
  3765. };
  3766. }(idx);
  3767. context.memo('help.formatH'+idx, lang.help['formatH' + idx]);
  3768. };
  3769. /* jshint ignore:end */
  3770. /**
  3771. * fontSize
  3772. *
  3773. * @param {String} value - px
  3774. */
  3775. this.fontSize = function (value) {
  3776. var rng = this.createRange();
  3777. var spans = style.styleNodes(rng);
  3778. if (rng && rng.isCollapsed()) {
  3779. var firstSpan = list.head(spans);
  3780. $(spans).css({
  3781. 'font-size': value + 'px'
  3782. });
  3783. // [workaround] added styled bogus span for style
  3784. // - also bogus character needed for cursor position
  3785. if (firstSpan && !dom.nodeLength(firstSpan)) {
  3786. firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR;
  3787. range.createFromNodeAfter(firstSpan.firstChild).select();
  3788. $editable.data(KEY_BOGUS, firstSpan);
  3789. }
  3790. } else {
  3791. beforeCommand();
  3792. $(spans).css({
  3793. 'font-size': value + 'px'
  3794. });
  3795. afterCommand();
  3796. }
  3797. };
  3798. /**
  3799. * insert horizontal rule
  3800. */
  3801. this.insertHorizontalRule = this.wrapCommand(function () {
  3802. var hrNode = this.createRange().insertNode(dom.create('HR'));
  3803. if (hrNode.nextSibling) {
  3804. range.create(hrNode.nextSibling, 0).normalize().select();
  3805. }
  3806. });
  3807. context.memo('help.insertHorizontalRule', lang.help.insertHorizontalRule);
  3808. /**
  3809. * remove bogus node and character
  3810. */
  3811. this.removeBogus = function () {
  3812. var bogusNode = $editable.data(KEY_BOGUS);
  3813. if (!bogusNode) {
  3814. return;
  3815. }
  3816. var textNode = list.find(list.from(bogusNode.childNodes), dom.isText);
  3817. var bogusCharIdx = textNode.nodeValue.indexOf(dom.ZERO_WIDTH_NBSP_CHAR);
  3818. if (bogusCharIdx !== -1) {
  3819. textNode.deleteData(bogusCharIdx, 1);
  3820. }
  3821. if (dom.isEmpty(bogusNode)) {
  3822. dom.remove(bogusNode);
  3823. }
  3824. $editable.removeData(KEY_BOGUS);
  3825. };
  3826. /**
  3827. * lineHeight
  3828. * @param {String} value
  3829. */
  3830. this.lineHeight = this.wrapCommand(function (value) {
  3831. style.stylePara(this.createRange(), {
  3832. lineHeight: value
  3833. });
  3834. });
  3835. /**
  3836. * unlink
  3837. *
  3838. * @type command
  3839. */
  3840. this.unlink = function () {
  3841. var rng = this.createRange();
  3842. if (rng.isOnAnchor()) {
  3843. var anchor = dom.ancestor(rng.sc, dom.isAnchor);
  3844. rng = range.createFromNode(anchor);
  3845. rng.select();
  3846. beforeCommand();
  3847. document.execCommand('unlink');
  3848. afterCommand();
  3849. }
  3850. };
  3851. /**
  3852. * create link (command)
  3853. *
  3854. * @param {Object} linkInfo
  3855. */
  3856. this.createLink = this.wrapCommand(function (linkInfo) {
  3857. var linkUrl = linkInfo.url;
  3858. var linkText = linkInfo.text;
  3859. var isNewWindow = linkInfo.isNewWindow;
  3860. var rng = linkInfo.range || this.createRange();
  3861. var isTextChanged = rng.toString() !== linkText;
  3862. // handle spaced urls from input
  3863. if (typeof linkUrl === 'string') {
  3864. linkUrl = linkUrl.trim();
  3865. }
  3866. if (options.onCreateLink) {
  3867. linkUrl = options.onCreateLink(linkUrl);
  3868. } else { // summernote 0.8.3
  3869. // if url doesn't match an URL schema, set http:// as default
  3870. linkUrl = /^[A-Za-z][A-Za-z0-9+-.]*\:[\/\/]?/.test(linkUrl) ?
  3871. linkUrl : 'http://' + linkUrl;
  3872. }
  3873. var anchors = [];
  3874. if (isTextChanged) {
  3875. rng = rng.deleteContents();
  3876. var anchor = rng.insertNode($('<A>' + linkText + '</A>')[0]);
  3877. anchors.push(anchor);
  3878. } else {
  3879. anchors = style.styleNodes(rng, {
  3880. nodeName: 'A',
  3881. expandClosestSibling: true,
  3882. onlyPartialContains: true
  3883. });
  3884. }
  3885. $.each(anchors, function (idx, anchor) {
  3886. $(anchor).attr('href', linkUrl);
  3887. if (isNewWindow) {
  3888. $(anchor).attr('target', '_blank');
  3889. } else {
  3890. $(anchor).removeAttr('target');
  3891. }
  3892. });
  3893. var startRange = range.createFromNodeBefore(list.head(anchors));
  3894. var startPoint = startRange.getStartPoint();
  3895. var endRange = range.createFromNodeAfter(list.last(anchors));
  3896. var endPoint = endRange.getEndPoint();
  3897. range.create(
  3898. startPoint.node,
  3899. startPoint.offset,
  3900. endPoint.node,
  3901. endPoint.offset
  3902. ).select();
  3903. });
  3904. /**
  3905. * returns link info
  3906. *
  3907. * @return {Object}
  3908. * @return {WrappedRange} return.range
  3909. * @return {String} return.text
  3910. * @return {Boolean} [return.isNewWindow=true]
  3911. * @return {String} [return.url=""]
  3912. */
  3913. this.getLinkInfo = function () {
  3914. var rng = this.createRange().expand(dom.isAnchor);
  3915. // Get the first anchor on range(for edit).
  3916. var $anchor = $(list.head(rng.nodes(dom.isAnchor)));
  3917. return {
  3918. range: rng,
  3919. text: rng.toString(),
  3920. isNewWindow: $anchor.length ? $anchor.attr('target') === '_blank' : false,
  3921. url: $anchor.length ? $anchor.attr('href') : ''
  3922. };
  3923. };
  3924. /**
  3925. * setting color
  3926. *
  3927. * @param {Object} sObjColor color code
  3928. * @param {String} sObjColor.foreColor foreground color
  3929. * @param {String} sObjColor.backColor background color
  3930. */
  3931. this.color = this.wrapCommand(function (colorInfo) {
  3932. var foreColor = colorInfo.foreColor;
  3933. var backColor = colorInfo.backColor;
  3934. if (foreColor) { document.execCommand('foreColor', false, foreColor); }
  3935. if (backColor) { document.execCommand('backColor', false, backColor); }
  3936. });
  3937. /**
  3938. * insert Table
  3939. *
  3940. * @param {String} dimension of table (ex : "5x5")
  3941. */
  3942. this.insertTable = this.wrapCommand(function (dim) {
  3943. var dimension = dim.split('x');
  3944. var rng = this.createRange().deleteContents();
  3945. rng.insertNode(table.createTable(dimension[0], dimension[1], options));
  3946. });
  3947. /**
  3948. * float me
  3949. *
  3950. * @param {String} value
  3951. */
  3952. this.floatMe = this.wrapCommand(function (value) {
  3953. var $target = $(this.restoreTarget());
  3954. $target.css('float', value);
  3955. });
  3956. /**
  3957. * resize overlay element
  3958. * @param {String} value
  3959. */
  3960. this.resize = this.wrapCommand(function (value) {
  3961. var $target = $(this.restoreTarget());
  3962. $target.css({
  3963. width: value * 100 + '%',
  3964. height: ''
  3965. });
  3966. });
  3967. /**
  3968. * @param {Position} pos
  3969. * @param {jQuery} $target - target element
  3970. * @param {Boolean} [bKeepRatio] - keep ratio
  3971. */
  3972. this.resizeTo = function (pos, $target, bKeepRatio) {
  3973. var imageSize;
  3974. if (bKeepRatio) {
  3975. var newRatio = pos.y / pos.x;
  3976. var ratio = $target.data('ratio');
  3977. imageSize = {
  3978. width: ratio > newRatio ? pos.x : pos.y / ratio,
  3979. height: ratio > newRatio ? pos.x * ratio : pos.y
  3980. };
  3981. } else {
  3982. imageSize = {
  3983. width: pos.x,
  3984. height: pos.y
  3985. };
  3986. }
  3987. $target.css(imageSize);
  3988. };
  3989. /**
  3990. * remove media object
  3991. */
  3992. this.removeMedia = this.wrapCommand(function () {
  3993. var $target = $(this.restoreTarget()).detach();
  3994. context.triggerEvent('media.delete', $target, $editable);
  3995. });
  3996. /**
  3997. * returns whether editable area has focus or not.
  3998. */
  3999. this.hasFocus = function () {
  4000. return $editable.is(':focus');
  4001. };
  4002. /**
  4003. * set focus
  4004. */
  4005. this.focus = function () {
  4006. // [workaround] Screen will move when page is scolled in IE.
  4007. // - do focus when not focused
  4008. if (!this.hasFocus()) {
  4009. $editable.focus();
  4010. }
  4011. };
  4012. /**
  4013. * returns whether contents is empty or not.
  4014. * @return {Boolean}
  4015. */
  4016. this.isEmpty = function () {
  4017. return dom.isEmpty($editable[0]) || dom.emptyPara === $editable.html();
  4018. };
  4019. /**
  4020. * Removes all contents and restores the editable instance to an _emptyPara_.
  4021. */
  4022. this.empty = function () {
  4023. context.invoke('code', dom.emptyPara);
  4024. };
  4025. };
  4026. var Clipboard = function (context) {
  4027. var self = this;
  4028. var $editable = context.layoutInfo.editable;
  4029. this.events = {
  4030. 'summernote.keydown': function (we, e) {
  4031. if (self.needKeydownHook()) {
  4032. if ((e.ctrlKey || e.metaKey) && e.keyCode === key.code.V) {
  4033. context.invoke('editor.saveRange');
  4034. self.$paste.focus();
  4035. setTimeout(function () {
  4036. self.pasteByHook();
  4037. }, 0);
  4038. }
  4039. }
  4040. }
  4041. };
  4042. this.needKeydownHook = function () {
  4043. return (agent.isMSIE && agent.browserVersion > 10) || agent.isFF;
  4044. };
  4045. this.initialize = function () {
  4046. // [workaround] getting image from clipboard
  4047. // - IE11 and Firefox: CTRL+v hook
  4048. // - Webkit: event.clipboardData
  4049. if (this.needKeydownHook()) {
  4050. this.$paste = $('<div tabindex="-1" />').attr('contenteditable', true).css({
  4051. position: 'absolute',
  4052. left: -100000,
  4053. opacity: 0
  4054. });
  4055. $editable.before(this.$paste);
  4056. this.$paste.on('paste', function (event) {
  4057. context.triggerEvent('paste', event);
  4058. });
  4059. } else {
  4060. $editable.on('paste', this.pasteByEvent);
  4061. }
  4062. };
  4063. this.destroy = function () {
  4064. if (this.needKeydownHook()) {
  4065. this.$paste.remove();
  4066. this.$paste = null;
  4067. }
  4068. };
  4069. this.pasteByHook = function () {
  4070. var node = this.$paste[0].firstChild;
  4071. if (dom.isImg(node)) {
  4072. var dataURI = node.src;
  4073. var decodedData = atob(dataURI.split(',')[1]);
  4074. var array = new Uint8Array(decodedData.length);
  4075. for (var i = 0; i < decodedData.length; i++) {
  4076. array[i] = decodedData.charCodeAt(i);
  4077. }
  4078. var blob = new Blob([array], { type: 'image/png' });
  4079. blob.name = 'clipboard.png';
  4080. context.invoke('editor.restoreRange');
  4081. context.invoke('editor.focus');
  4082. context.invoke('editor.insertImagesOrCallback', [blob]);
  4083. } else {
  4084. var pasteContent = $('<div />').html(this.$paste.html()).html();
  4085. context.invoke('editor.restoreRange');
  4086. context.invoke('editor.focus');
  4087. if (pasteContent) {
  4088. context.invoke('editor.pasteHTML', pasteContent);
  4089. }
  4090. }
  4091. this.$paste.empty();
  4092. };
  4093. /**
  4094. * paste by clipboard event
  4095. *
  4096. * @param {Event} event
  4097. */
  4098. this.pasteByEvent = function (event) {
  4099. var clipboardData = event.originalEvent.clipboardData;
  4100. if (clipboardData && clipboardData.items && clipboardData.items.length) {
  4101. var item = list.head(clipboardData.items);
  4102. if (item.kind === 'file' && item.type.indexOf('image/') !== -1) {
  4103. context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]);
  4104. }
  4105. context.invoke('editor.afterCommand');
  4106. }
  4107. };
  4108. };
  4109. var Dropzone = function (context) {
  4110. var $document = $(document);
  4111. var $editor = context.layoutInfo.editor;
  4112. var $editable = context.layoutInfo.editable;
  4113. var options = context.options;
  4114. var lang = options.langInfo;
  4115. var documentEventHandlers = {};
  4116. var $dropzone = $([
  4117. '<div class="note-dropzone">',
  4118. ' <div class="note-dropzone-message"/>',
  4119. '</div>'
  4120. ].join('')).prependTo($editor);
  4121. var detachDocumentEvent = function () {
  4122. Object.keys(documentEventHandlers).forEach(function (key) {
  4123. $document.off(key.substr(2).toLowerCase(), documentEventHandlers[key]);
  4124. });
  4125. documentEventHandlers = {};
  4126. };
  4127. /**
  4128. * attach Drag and Drop Events
  4129. */
  4130. this.initialize = function () {
  4131. if (options.disableDragAndDrop) {
  4132. // prevent default drop event
  4133. documentEventHandlers.onDrop = function (e) {
  4134. e.preventDefault();
  4135. };
  4136. $document.on('drop', documentEventHandlers.onDrop);
  4137. } else {
  4138. this.attachDragAndDropEvent();
  4139. }
  4140. };
  4141. /**
  4142. * attach Drag and Drop Events
  4143. */
  4144. this.attachDragAndDropEvent = function () {
  4145. var collection = $(),
  4146. $dropzoneMessage = $dropzone.find('.note-dropzone-message');
  4147. documentEventHandlers.onDragenter = function (e) {
  4148. var isCodeview = context.invoke('codeview.isActivated');
  4149. var hasEditorSize = $editor.width() > 0 && $editor.height() > 0;
  4150. if (!isCodeview && !collection.length && hasEditorSize) {
  4151. $editor.addClass('dragover');
  4152. $dropzone.width($editor.width());
  4153. $dropzone.height($editor.height());
  4154. $dropzoneMessage.text(lang.image.dragImageHere);
  4155. }
  4156. collection = collection.add(e.target);
  4157. };
  4158. documentEventHandlers.onDragleave = function (e) {
  4159. collection = collection.not(e.target);
  4160. if (!collection.length) {
  4161. $editor.removeClass('dragover');
  4162. }
  4163. };
  4164. documentEventHandlers.onDrop = function () {
  4165. collection = $();
  4166. $editor.removeClass('dragover');
  4167. };
  4168. // show dropzone on dragenter when dragging a object to document
  4169. // -but only if the editor is visible, i.e. has a positive width and height
  4170. $document.on('dragenter', documentEventHandlers.onDragenter)
  4171. .on('dragleave', documentEventHandlers.onDragleave)
  4172. .on('drop', documentEventHandlers.onDrop);
  4173. // change dropzone's message on hover.
  4174. $dropzone.on('dragenter', function () {
  4175. $dropzone.addClass('hover');
  4176. $dropzoneMessage.text(lang.image.dropImage);
  4177. }).on('dragleave', function () {
  4178. $dropzone.removeClass('hover');
  4179. $dropzoneMessage.text(lang.image.dragImageHere);
  4180. });
  4181. // attach dropImage
  4182. $dropzone.on('drop', function (event) {
  4183. var dataTransfer = event.originalEvent.dataTransfer;
  4184. if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
  4185. event.preventDefault();
  4186. $editable.focus();
  4187. context.invoke('editor.insertImagesOrCallback', dataTransfer.files);
  4188. } else {
  4189. $.each(dataTransfer.types, function (idx, type) {
  4190. var content = dataTransfer.getData(type);
  4191. if (type.toLowerCase().indexOf('text') > -1) {
  4192. context.invoke('editor.pasteHTML', content);
  4193. } else {
  4194. $(content).each(function () {
  4195. context.invoke('editor.insertNode', this);
  4196. });
  4197. }
  4198. });
  4199. }
  4200. }).on('dragover', false); // prevent default dragover event
  4201. };
  4202. this.destroy = function () {
  4203. detachDocumentEvent();
  4204. };
  4205. };
  4206. var CodeMirror;
  4207. if (agent.hasCodeMirror) {
  4208. if (agent.isSupportAmd) {
  4209. require(['codemirror'], function (cm) {
  4210. CodeMirror = cm;
  4211. });
  4212. } else {
  4213. CodeMirror = window.CodeMirror;
  4214. }
  4215. }
  4216. /**
  4217. * @class Codeview
  4218. */
  4219. var Codeview = function (context) {
  4220. var $editor = context.layoutInfo.editor;
  4221. var $editable = context.layoutInfo.editable;
  4222. var $codable = context.layoutInfo.codable;
  4223. var options = context.options;
  4224. this.sync = function () {
  4225. var isCodeview = this.isActivated();
  4226. if (isCodeview && agent.hasCodeMirror) {
  4227. $codable.data('cmEditor').save();
  4228. }
  4229. };
  4230. /**
  4231. * @return {Boolean}
  4232. */
  4233. this.isActivated = function () {
  4234. return $editor.hasClass('codeview');
  4235. };
  4236. /**
  4237. * toggle codeview
  4238. */
  4239. this.toggle = function () {
  4240. if (this.isActivated()) {
  4241. this.deactivate();
  4242. } else {
  4243. this.activate();
  4244. }
  4245. context.triggerEvent('codeview.toggled');
  4246. };
  4247. /**
  4248. * activate code view
  4249. */
  4250. this.activate = function () {
  4251. $codable.val(dom.html($editable, options.prettifyHtml));
  4252. $codable.height($editable.height());
  4253. context.invoke('toolbar.updateCodeview', true);
  4254. $editor.addClass('codeview');
  4255. $codable.focus();
  4256. // activate CodeMirror as codable
  4257. if (agent.hasCodeMirror) {
  4258. var cmEditor = CodeMirror.fromTextArea($codable[0], options.codemirror);
  4259. // CodeMirror TernServer
  4260. if (options.codemirror.tern) {
  4261. var server = new CodeMirror.TernServer(options.codemirror.tern);
  4262. cmEditor.ternServer = server;
  4263. cmEditor.on('cursorActivity', function (cm) {
  4264. server.updateArgHints(cm);
  4265. });
  4266. }
  4267. // CodeMirror hasn't Padding.
  4268. cmEditor.setSize(null, $editable.outerHeight());
  4269. $codable.data('cmEditor', cmEditor);
  4270. }
  4271. };
  4272. /**
  4273. * deactivate code view
  4274. */
  4275. this.deactivate = function () {
  4276. // deactivate CodeMirror as codable
  4277. if (agent.hasCodeMirror) {
  4278. var cmEditor = $codable.data('cmEditor');
  4279. $codable.val(cmEditor.getValue());
  4280. cmEditor.toTextArea();
  4281. }
  4282. var value = dom.value($codable, options.prettifyHtml) || dom.emptyPara;
  4283. var isChange = $editable.html() !== value;
  4284. $editable.html(value);
  4285. $editable.height(options.height ? $codable.height() : 'auto');
  4286. $editor.removeClass('codeview');
  4287. if (isChange) {
  4288. context.triggerEvent('change', $editable.html(), $editable);
  4289. }
  4290. $editable.focus();
  4291. context.invoke('toolbar.updateCodeview', false);
  4292. };
  4293. this.destroy = function () {
  4294. if (this.isActivated()) {
  4295. this.deactivate();
  4296. }
  4297. };
  4298. };
  4299. var EDITABLE_PADDING = 24;
  4300. var Statusbar = function (context) {
  4301. var $document = $(document);
  4302. var $statusbar = context.layoutInfo.statusbar;
  4303. var $editable = context.layoutInfo.editable;
  4304. var options = context.options;
  4305. this.initialize = function () {
  4306. if (options.airMode || options.disableResizeEditor) {
  4307. this.destroy(); //summernote 0.8.3
  4308. return;
  4309. }
  4310. $statusbar.on('mousedown', function (event) {
  4311. event.preventDefault();
  4312. event.stopPropagation();
  4313. var editableTop = $editable.offset().top - $document.scrollTop();
  4314. $document.on('mousemove', function (event) {
  4315. var height = event.clientY - (editableTop + EDITABLE_PADDING);
  4316. height = (options.minheight > 0) ? Math.max(height, options.minheight) : height;
  4317. height = (options.maxHeight > 0) ? Math.min(height, options.maxHeight) : height;
  4318. $editable.height(height);
  4319. }).one('mouseup', function () {
  4320. $document.off('mousemove');
  4321. });
  4322. });
  4323. };
  4324. this.destroy = function () {
  4325. $statusbar.off();
  4326. $statusbar.remove();
  4327. };
  4328. };
  4329. var Fullscreen = function (context) {
  4330. var $editor = context.layoutInfo.editor;
  4331. var $toolbar = context.layoutInfo.toolbar;
  4332. var $editable = context.layoutInfo.editable;
  4333. var $codable = context.layoutInfo.codable;
  4334. var $window = $(window);
  4335. var $scrollbar = $('html, body');
  4336. /**
  4337. * toggle fullscreen
  4338. */
  4339. this.toggle = function () {
  4340. var resize = function (size) {
  4341. $editable.css('height', size.h);
  4342. $codable.css('height', size.h);
  4343. if ($codable.data('cmeditor')) {
  4344. $codable.data('cmeditor').setsize(null, size.h);
  4345. }
  4346. };
  4347. $editor.toggleClass('fullscreen');
  4348. if (this.isFullscreen()) {
  4349. $editable.data('orgHeight', $editable.css('height'));
  4350. $window.on('resize', function () {
  4351. resize({
  4352. h: $window.height() - $toolbar.outerHeight()
  4353. });
  4354. }).trigger('resize');
  4355. $scrollbar.css('overflow', 'hidden');
  4356. } else {
  4357. $window.off('resize');
  4358. resize({
  4359. h: $editable.data('orgHeight')
  4360. });
  4361. $scrollbar.css('overflow', 'visible');
  4362. }
  4363. context.invoke('toolbar.updateFullscreen', this.isFullscreen());
  4364. };
  4365. this.isFullscreen = function () {
  4366. return $editor.hasClass('fullscreen');
  4367. };
  4368. };
  4369. var Handle = function (context) {
  4370. var self = this;
  4371. var $document = $(document);
  4372. var $editingArea = context.layoutInfo.editingArea;
  4373. var options = context.options;
  4374. this.events = {
  4375. 'summernote.mousedown': function (we, e) {
  4376. if (self.update(e.target)) {
  4377. e.preventDefault();
  4378. }
  4379. },
  4380. 'summernote.keyup summernote.scroll summernote.change summernote.dialog.shown': function () {
  4381. self.update();
  4382. }
  4383. };
  4384. this.initialize = function () {
  4385. this.$handle = $([
  4386. '<div class="note-handle">',
  4387. '<div class="note-control-selection">',
  4388. '<div class="note-control-selection-bg"></div>',
  4389. '<div class="note-control-holder note-control-nw"></div>',
  4390. '<div class="note-control-holder note-control-ne"></div>',
  4391. '<div class="note-control-holder note-control-sw"></div>',
  4392. '<div class="',
  4393. (options.disableResizeImage ? 'note-control-holder' : 'note-control-sizing'),
  4394. ' note-control-se"></div>',
  4395. (options.disableResizeImage ? '' : '<div class="note-control-selection-info"></div>'),
  4396. '</div>',
  4397. '</div>'
  4398. ].join('')).prependTo($editingArea);
  4399. this.$handle.on('mousedown', function (event) {
  4400. if (dom.isControlSizing(event.target)) {
  4401. event.preventDefault();
  4402. event.stopPropagation();
  4403. var $target = self.$handle.find('.note-control-selection').data('target'),
  4404. posStart = $target.offset(),
  4405. scrollTop = $document.scrollTop();
  4406. $document.on('mousemove', function (event) {
  4407. context.invoke('editor.resizeTo', {
  4408. x: event.clientX - posStart.left,
  4409. y: event.clientY - (posStart.top - scrollTop)
  4410. }, $target, !event.shiftKey);
  4411. self.update($target[0]);
  4412. }).one('mouseup', function (e) {
  4413. e.preventDefault();
  4414. $document.off('mousemove');
  4415. context.invoke('editor.afterCommand');
  4416. });
  4417. if (!$target.data('ratio')) { // original ratio.
  4418. $target.data('ratio', $target.height() / $target.width());
  4419. }
  4420. }
  4421. });
  4422. };
  4423. this.destroy = function () {
  4424. this.$handle.remove();
  4425. };
  4426. this.update = function (target) {
  4427. var isImage = dom.isImg(target);
  4428. var $selection = this.$handle.find('.note-control-selection');
  4429. context.invoke('imagePopover.update', target);
  4430. if (isImage) {
  4431. var $image = $(target);
  4432. var pos = $image.position();
  4433. // include margin
  4434. var imageSize = {
  4435. w: $image.outerWidth(true),
  4436. h: $image.outerHeight(true)
  4437. };
  4438. $selection.css({
  4439. display: 'block',
  4440. left: pos.left,
  4441. top: pos.top,
  4442. width: imageSize.w,
  4443. height: imageSize.h
  4444. }).data('target', $image); // save current image element.
  4445. var sizingText = imageSize.w + 'x' + imageSize.h;
  4446. $selection.find('.note-control-selection-info').text(sizingText);
  4447. context.invoke('editor.saveTarget', target);
  4448. } else {
  4449. this.hide();
  4450. }
  4451. return isImage;
  4452. };
  4453. /**
  4454. * hide
  4455. *
  4456. * @param {jQuery} $handle
  4457. */
  4458. this.hide = function () {
  4459. context.invoke('editor.clearTarget');
  4460. this.$handle.children().hide();
  4461. };
  4462. };
  4463. var AutoLink = function (context) {
  4464. var self = this;
  4465. var defaultScheme = 'http://';
  4466. var linkPattern = /^([A-Za-z][A-Za-z0-9+-.]*\:[\/\/]?|mailto:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i;
  4467. this.events = {
  4468. 'summernote.keyup': function (we, e) {
  4469. if (!e.isDefaultPrevented()) {
  4470. self.handleKeyup(e);
  4471. }
  4472. },
  4473. 'summernote.keydown': function (we, e) {
  4474. self.handleKeydown(e);
  4475. }
  4476. };
  4477. this.initialize = function () {
  4478. this.lastWordRange = null;
  4479. };
  4480. this.destroy = function () {
  4481. this.lastWordRange = null;
  4482. };
  4483. this.replace = function () {
  4484. if (!this.lastWordRange) {
  4485. return;
  4486. }
  4487. var keyword = this.lastWordRange.toString();
  4488. var match = keyword.match(linkPattern);
  4489. if (match && (match[1] || match[2])) {
  4490. var link = match[1] ? keyword : defaultScheme + keyword;
  4491. var node = $('<a />').html(keyword).attr('href', link)[0];
  4492. this.lastWordRange.insertNode(node);
  4493. this.lastWordRange = null;
  4494. context.invoke('editor.focus');
  4495. }
  4496. };
  4497. this.handleKeydown = function (e) {
  4498. if (list.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) {
  4499. var wordRange = context.invoke('editor.createRange').getWordRange();
  4500. this.lastWordRange = wordRange;
  4501. }
  4502. };
  4503. this.handleKeyup = function (e) {
  4504. if (list.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) {
  4505. this.replace();
  4506. }
  4507. };
  4508. };
  4509. /**
  4510. * textarea auto sync.
  4511. */
  4512. var AutoSync = function (context) {
  4513. var $note = context.layoutInfo.note;
  4514. this.events = {
  4515. 'summernote.change': function () {
  4516. $note.val(context.invoke('code'));
  4517. }
  4518. };
  4519. this.shouldInitialize = function () {
  4520. return dom.isTextarea($note[0]);
  4521. };
  4522. };
  4523. var Placeholder = function (context) {
  4524. var self = this;
  4525. var $editingArea = context.layoutInfo.editingArea;
  4526. var options = context.options;
  4527. this.events = {
  4528. 'summernote.init summernote.change': function () {
  4529. self.update();
  4530. },
  4531. 'summernote.codeview.toggled': function () {
  4532. self.update();
  4533. }
  4534. };
  4535. this.shouldInitialize = function () {
  4536. return !!options.placeholder;
  4537. };
  4538. this.initialize = function () {
  4539. this.$placeholder = $('<div class="note-placeholder">');
  4540. this.$placeholder.on('click', function () {
  4541. context.invoke('focus');
  4542. }).text(options.placeholder).prependTo($editingArea);
  4543. };
  4544. this.destroy = function () {
  4545. this.$placeholder.remove();
  4546. };
  4547. this.update = function () {
  4548. var isShow = !context.invoke('codeview.isActivated') && context.invoke('editor.isEmpty');
  4549. this.$placeholder.toggle(isShow);
  4550. };
  4551. };
  4552. var Buttons = function (context) {
  4553. var self = this;
  4554. var ui = $.summernote.ui;
  4555. var $toolbar = context.layoutInfo.toolbar;
  4556. var options = context.options;
  4557. var lang = options.langInfo;
  4558. var invertedKeyMap = func.invertObject(options.keyMap[agent.isMac ? 'mac' : 'pc']);
  4559. var representShortcut = this.representShortcut = function (editorMethod) {
  4560. var shortcut = invertedKeyMap[editorMethod];
  4561. if (!options.shortcuts || !shortcut) {
  4562. return '';
  4563. }
  4564. if (agent.isMac) {
  4565. shortcut = shortcut.replace('CMD', '⌘').replace('SHIFT', '⇧');
  4566. }
  4567. shortcut = shortcut.replace('BACKSLASH', '\\')
  4568. .replace('SLASH', '/')
  4569. .replace('LEFTBRACKET', '[')
  4570. .replace('RIGHTBRACKET', ']');
  4571. return ' (' + shortcut + ')';
  4572. };
  4573. this.initialize = function () {
  4574. this.addToolbarButtons();
  4575. this.addImagePopoverButtons();
  4576. this.addLinkPopoverButtons();
  4577. this.fontInstalledMap = {};
  4578. };
  4579. this.destroy = function () {
  4580. delete this.fontInstalledMap;
  4581. };
  4582. this.isFontInstalled = function (name) {
  4583. if (!self.fontInstalledMap.hasOwnProperty(name)) {
  4584. self.fontInstalledMap[name] = agent.isFontInstalled(name) ||
  4585. list.contains(options.fontNamesIgnoreCheck, name);
  4586. }
  4587. return self.fontInstalledMap[name];
  4588. };
  4589. this.addToolbarButtons = function () {
  4590. context.memo('button.style', function () {
  4591. return ui.buttonGroup([
  4592. ui.button({
  4593. className: 'dropdown-toggle',
  4594. contents: ui.icon(options.icons.magic) + ' ' + ui.icon(options.icons.caret, 'span'),
  4595. tooltip: lang.style.style,
  4596. data: {
  4597. toggle: 'dropdown'
  4598. }
  4599. }),
  4600. ui.dropdown({
  4601. className: 'dropdown-style',
  4602. items: context.options.styleTags,
  4603. template: function (item) {
  4604. if (typeof item === 'string') {
  4605. item = { tag: item, title: (lang.style.hasOwnProperty(item) ? lang.style[item] : item) };
  4606. }
  4607. var tag = item.tag;
  4608. var title = item.title;
  4609. var style = item.style ? ' style="' + item.style + '" ' : '';
  4610. var className = item.className ? ' class="' + item.className + '"' : '';
  4611. return '<' + tag + style + className + '>' + title + '</' + tag + '>';
  4612. },
  4613. click: context.createInvokeHandler('editor.formatBlock')
  4614. })
  4615. ]).render();
  4616. });
  4617. context.memo('button.bold', function () {
  4618. return ui.button({
  4619. className: 'note-btn-bold',
  4620. contents: ui.icon(options.icons.bold),
  4621. tooltip: lang.font.bold + representShortcut('bold'),
  4622. click: context.createInvokeHandler('editor.bold')
  4623. }).render();
  4624. });
  4625. context.memo('button.italic', function () {
  4626. return ui.button({
  4627. className: 'note-btn-italic',
  4628. contents: ui.icon(options.icons.italic),
  4629. tooltip: lang.font.italic + representShortcut('italic'),
  4630. click: context.createInvokeHandler('editor.italic')
  4631. }).render();
  4632. });
  4633. context.memo('button.underline', function () {
  4634. return ui.button({
  4635. className: 'note-btn-underline',
  4636. contents: ui.icon(options.icons.underline),
  4637. tooltip: lang.font.underline + representShortcut('underline'),
  4638. click: context.createInvokeHandler('editor.underline')
  4639. }).render();
  4640. });
  4641. context.memo('button.clear', function () {
  4642. return ui.button({
  4643. contents: ui.icon(options.icons.eraser),
  4644. tooltip: lang.font.clear + representShortcut('removeFormat'),
  4645. click: context.createInvokeHandler('editor.removeFormat')
  4646. }).render();
  4647. });
  4648. context.memo('button.strikethrough', function () {
  4649. return ui.button({
  4650. className: 'note-btn-strikethrough',
  4651. contents: ui.icon(options.icons.strikethrough),
  4652. tooltip: lang.font.strikethrough + representShortcut('strikethrough'),
  4653. click: context.createInvokeHandler('editor.strikethrough')
  4654. }).render();
  4655. });
  4656. context.memo('button.superscript', function () {
  4657. return ui.button({
  4658. className: 'note-btn-superscript',
  4659. contents: ui.icon(options.icons.superscript),
  4660. tooltip: lang.font.superscript,
  4661. click: context.createInvokeHandler('editor.superscript')
  4662. }).render();
  4663. });
  4664. context.memo('button.subscript', function () {
  4665. return ui.button({
  4666. className: 'note-btn-subscript',
  4667. contents: ui.icon(options.icons.subscript),
  4668. tooltip: lang.font.subscript,
  4669. click: context.createInvokeHandler('editor.subscript')
  4670. }).render();
  4671. });
  4672. context.memo('button.fontname', function () {
  4673. return ui.buttonGroup([
  4674. ui.button({
  4675. className: 'dropdown-toggle',
  4676. contents: '<span class="note-current-fontname"/> ' + ui.icon(options.icons.caret, 'span'),
  4677. tooltip: lang.font.name,
  4678. data: {
  4679. toggle: 'dropdown'
  4680. }
  4681. }),
  4682. ui.dropdownCheck({
  4683. className: 'dropdown-fontname',
  4684. checkClassName: options.icons.menuCheck,
  4685. items: options.fontNames.filter(self.isFontInstalled),
  4686. template: function (item) {
  4687. return '<span style="font-family:' + item + '">' + item + '</span>';
  4688. },
  4689. click: context.createInvokeHandler('editor.fontName')
  4690. })
  4691. ]).render();
  4692. });
  4693. context.memo('button.fontsize', function () {
  4694. return ui.buttonGroup([
  4695. ui.button({
  4696. className: 'dropdown-toggle',
  4697. contents: '<span class="note-current-fontsize"/>' + ui.icon(options.icons.caret, 'span'),
  4698. tooltip: lang.font.size,
  4699. data: {
  4700. toggle: 'dropdown'
  4701. }
  4702. }),
  4703. ui.dropdownCheck({
  4704. className: 'dropdown-fontsize',
  4705. checkClassName: options.icons.menuCheck,
  4706. items: options.fontSizes,
  4707. click: context.createInvokeHandler('editor.fontSize')
  4708. })
  4709. ]).render();
  4710. });
  4711. context.memo('button.color', function () {
  4712. return ui.buttonGroup({
  4713. className: 'note-color',
  4714. children: [
  4715. ui.button({
  4716. className: 'note-current-color-button',
  4717. contents: ui.icon(options.icons.font + ' note-recent-color'),
  4718. tooltip: lang.color.recent,
  4719. click: function (e) {
  4720. var $button = $(e.currentTarget);
  4721. context.invoke('editor.color', {
  4722. backColor: $button.attr('data-backColor'),
  4723. foreColor: $button.attr('data-foreColor')
  4724. });
  4725. },
  4726. callback: function ($button) {
  4727. var $recentColor = $button.find('.note-recent-color');
  4728. $recentColor.css('background-color', '#FFFF00');
  4729. $button.attr('data-backColor', '#FFFF00');
  4730. }
  4731. }),
  4732. ui.button({
  4733. className: 'dropdown-toggle',
  4734. contents: ui.icon(options.icons.caret, 'span'),
  4735. tooltip: lang.color.more,
  4736. data: {
  4737. toggle: 'dropdown'
  4738. }
  4739. }),
  4740. ui.dropdown({
  4741. items: [
  4742. '<li>',
  4743. '<div class="btn-group">',
  4744. ' <div class="note-palette-title">' + lang.color.background + '</div>',
  4745. ' <div>',
  4746. ' <button type="button" class="note-color-reset btn btn-default" data-event="backColor" data-value="inherit">',
  4747. lang.color.transparent,
  4748. ' </button>',
  4749. ' </div>',
  4750. ' <div class="note-holder" data-event="backColor"/>',
  4751. '</div>',
  4752. '<div class="btn-group">',
  4753. ' <div class="note-palette-title">' + lang.color.foreground + '</div>',
  4754. ' <div>',
  4755. ' <button type="button" class="note-color-reset btn btn-default" data-event="removeFormat" data-value="foreColor">',
  4756. lang.color.resetToDefault,
  4757. ' </button>',
  4758. ' </div>',
  4759. ' <div class="note-holder" data-event="foreColor"/>',
  4760. '</div>',
  4761. '</li>'
  4762. ].join(''),
  4763. callback: function ($dropdown) {
  4764. $dropdown.find('.note-holder').each(function () {
  4765. var $holder = $(this);
  4766. $holder.append(ui.palette({
  4767. colors: options.colors,
  4768. eventName: $holder.data('event')
  4769. }).render());
  4770. });
  4771. },
  4772. click: function (event) {
  4773. var $button = $(event.target);
  4774. var eventName = $button.data('event');
  4775. var value = $button.data('value');
  4776. if (eventName && value) {
  4777. var key = eventName === 'backColor' ? 'background-color' : 'color';
  4778. var $color = $button.closest('.note-color').find('.note-recent-color');
  4779. var $currentButton = $button.closest('.note-color').find('.note-current-color-button');
  4780. $color.css(key, value);
  4781. $currentButton.attr('data-' + eventName, value);
  4782. context.invoke('editor.' + eventName, value);
  4783. }
  4784. }
  4785. })
  4786. ]
  4787. }).render();
  4788. });
  4789. context.memo('button.ul', function () {
  4790. return ui.button({
  4791. contents: ui.icon(options.icons.unorderedlist),
  4792. tooltip: lang.lists.unordered + representShortcut('insertUnorderedList'),
  4793. click: context.createInvokeHandler('editor.insertUnorderedList')
  4794. }).render();
  4795. });
  4796. context.memo('button.ol', function () {
  4797. return ui.button({
  4798. contents: ui.icon(options.icons.orderedlist),
  4799. tooltip: lang.lists.ordered + representShortcut('insertOrderedList'),
  4800. click: context.createInvokeHandler('editor.insertOrderedList')
  4801. }).render();
  4802. });
  4803. var justifyLeft = ui.button({
  4804. contents: ui.icon(options.icons.alignLeft),
  4805. tooltip: lang.paragraph.left + representShortcut('justifyLeft'),
  4806. click: context.createInvokeHandler('editor.justifyLeft')
  4807. });
  4808. var justifyCenter = ui.button({
  4809. contents: ui.icon(options.icons.alignCenter),
  4810. tooltip: lang.paragraph.center + representShortcut('justifyCenter'),
  4811. click: context.createInvokeHandler('editor.justifyCenter')
  4812. });
  4813. var justifyRight = ui.button({
  4814. contents: ui.icon(options.icons.alignRight),
  4815. tooltip: lang.paragraph.right + representShortcut('justifyRight'),
  4816. click: context.createInvokeHandler('editor.justifyRight')
  4817. });
  4818. var justifyFull = ui.button({
  4819. contents: ui.icon(options.icons.alignJustify),
  4820. tooltip: lang.paragraph.justify + representShortcut('justifyFull'),
  4821. click: context.createInvokeHandler('editor.justifyFull')
  4822. });
  4823. var outdent = ui.button({
  4824. contents: ui.icon(options.icons.outdent),
  4825. tooltip: lang.paragraph.outdent + representShortcut('outdent'),
  4826. click: context.createInvokeHandler('editor.outdent')
  4827. });
  4828. var indent = ui.button({
  4829. contents: ui.icon(options.icons.indent),
  4830. tooltip: lang.paragraph.indent + representShortcut('indent'),
  4831. click: context.createInvokeHandler('editor.indent')
  4832. });
  4833. context.memo('button.justifyLeft', func.invoke(justifyLeft, 'render'));
  4834. context.memo('button.justifyCenter', func.invoke(justifyCenter, 'render'));
  4835. context.memo('button.justifyRight', func.invoke(justifyRight, 'render'));
  4836. context.memo('button.justifyFull', func.invoke(justifyFull, 'render'));
  4837. context.memo('button.outdent', func.invoke(outdent, 'render'));
  4838. context.memo('button.indent', func.invoke(indent, 'render'));
  4839. context.memo('button.paragraph', function () {
  4840. return ui.buttonGroup([
  4841. ui.button({
  4842. className: 'dropdown-toggle',
  4843. contents: ui.icon(options.icons.alignLeft) + ' ' + ui.icon(options.icons.caret, 'span'),
  4844. tooltip: lang.paragraph.paragraph,
  4845. data: {
  4846. toggle: 'dropdown'
  4847. }
  4848. }),
  4849. ui.dropdown([
  4850. ui.buttonGroup({
  4851. className: 'note-align',
  4852. children: [justifyLeft, justifyCenter, justifyRight, justifyFull]
  4853. }),
  4854. ui.buttonGroup({
  4855. className: 'note-list',
  4856. children: [outdent, indent]
  4857. })
  4858. ])
  4859. ]).render();
  4860. });
  4861. context.memo('button.height', function () {
  4862. return ui.buttonGroup([
  4863. ui.button({
  4864. className: 'dropdown-toggle',
  4865. contents: ui.icon(options.icons.textHeight) + ' ' + ui.icon(options.icons.caret, 'span'),
  4866. tooltip: lang.font.height,
  4867. data: {
  4868. toggle: 'dropdown'
  4869. }
  4870. }),
  4871. ui.dropdownCheck({
  4872. items: options.lineHeights,
  4873. checkClassName: options.icons.menuCheck,
  4874. className: 'dropdown-line-height',
  4875. click: context.createInvokeHandler('editor.lineHeight')
  4876. })
  4877. ]).render();
  4878. });
  4879. context.memo('button.table', function () {
  4880. return ui.buttonGroup([
  4881. ui.button({
  4882. className: 'dropdown-toggle',
  4883. contents: ui.icon(options.icons.table) + ' ' + ui.icon(options.icons.caret, 'span'),
  4884. tooltip: lang.table.table,
  4885. data: {
  4886. toggle: 'dropdown'
  4887. }
  4888. }),
  4889. ui.dropdown({
  4890. className: 'note-table',
  4891. items: [
  4892. '<div class="note-dimension-picker">',
  4893. ' <div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"/>',
  4894. ' <div class="note-dimension-picker-highlighted"/>',
  4895. ' <div class="note-dimension-picker-unhighlighted"/>',
  4896. '</div>',
  4897. '<div class="note-dimension-display">1 x 1</div>'
  4898. ].join('')
  4899. })
  4900. ], {
  4901. callback: function ($node) {
  4902. var $catcher = $node.find('.note-dimension-picker-mousecatcher');
  4903. $catcher.css({
  4904. width: options.insertTableMaxSize.col + 'em',
  4905. height: options.insertTableMaxSize.row + 'em'
  4906. }).mousedown(context.createInvokeHandler('editor.insertTable'))
  4907. .on('mousemove', self.tableMoveHandler);
  4908. }
  4909. }).render();
  4910. });
  4911. context.memo('button.link', function () {
  4912. return ui.button({
  4913. contents: ui.icon(options.icons.link),
  4914. tooltip: lang.link.link + representShortcut('linkDialog.show'),
  4915. click: context.createInvokeHandler('linkDialog.show')
  4916. }).render();
  4917. });
  4918. context.memo('button.picture', function () {
  4919. return ui.button({
  4920. contents: ui.icon(options.icons.picture),
  4921. tooltip: lang.image.image,
  4922. click: context.createInvokeHandler('imageDialog.show')
  4923. }).render();
  4924. });
  4925. context.memo('button.video', function () {
  4926. return ui.button({
  4927. contents: ui.icon(options.icons.video),
  4928. tooltip: lang.video.video,
  4929. click: context.createInvokeHandler('videoDialog.show')
  4930. }).render();
  4931. });
  4932. context.memo('button.hr', function () {
  4933. return ui.button({
  4934. contents: ui.icon(options.icons.minus),
  4935. tooltip: lang.hr.insert + representShortcut('insertHorizontalRule'),
  4936. click: context.createInvokeHandler('editor.insertHorizontalRule')
  4937. }).render();
  4938. });
  4939. context.memo('button.fullscreen', function () {
  4940. return ui.button({
  4941. className: 'btn-fullscreen',
  4942. contents: ui.icon(options.icons.arrowsAlt),
  4943. tooltip: lang.options.fullscreen,
  4944. click: context.createInvokeHandler('fullscreen.toggle')
  4945. }).render();
  4946. });
  4947. context.memo('button.codeview', function () {
  4948. return ui.button({
  4949. className: 'btn-codeview',
  4950. contents: ui.icon(options.icons.code),
  4951. tooltip: lang.options.codeview,
  4952. click: context.createInvokeHandler('codeview.toggle')
  4953. }).render();
  4954. });
  4955. context.memo('button.redo', function () {
  4956. return ui.button({
  4957. contents: ui.icon(options.icons.redo),
  4958. tooltip: lang.history.redo + representShortcut('redo'),
  4959. click: context.createInvokeHandler('editor.redo')
  4960. }).render();
  4961. });
  4962. context.memo('button.undo', function () {
  4963. return ui.button({
  4964. contents: ui.icon(options.icons.undo),
  4965. tooltip: lang.history.undo + representShortcut('undo'),
  4966. click: context.createInvokeHandler('editor.undo')
  4967. }).render();
  4968. });
  4969. context.memo('button.help', function () {
  4970. return ui.button({
  4971. contents: ui.icon(options.icons.question),
  4972. tooltip: lang.options.help,
  4973. click: context.createInvokeHandler('helpDialog.show')
  4974. }).render();
  4975. });
  4976. };
  4977. /**
  4978. * image : [
  4979. * ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
  4980. * ['float', ['floatLeft', 'floatRight', 'floatNone' ]],
  4981. * ['remove', ['removeMedia']]
  4982. * ],
  4983. */
  4984. this.addImagePopoverButtons = function () {
  4985. // Image Size Buttons
  4986. context.memo('button.imageSize100', function () {
  4987. return ui.button({
  4988. contents: '<span class="note-fontsize-10">100%</span>',
  4989. tooltip: lang.image.resizeFull,
  4990. click: context.createInvokeHandler('editor.resize', '1')
  4991. }).render();
  4992. });
  4993. context.memo('button.imageSize50', function () {
  4994. return ui.button({
  4995. contents: '<span class="note-fontsize-10">50%</span>',
  4996. tooltip: lang.image.resizeHalf,
  4997. click: context.createInvokeHandler('editor.resize', '0.5')
  4998. }).render();
  4999. });
  5000. context.memo('button.imageSize25', function () {
  5001. return ui.button({
  5002. contents: '<span class="note-fontsize-10">25%</span>',
  5003. tooltip: lang.image.resizeQuarter,
  5004. click: context.createInvokeHandler('editor.resize', '0.25')
  5005. }).render();
  5006. });
  5007. // Float Buttons
  5008. context.memo('button.floatLeft', function () {
  5009. return ui.button({
  5010. contents: ui.icon(options.icons.alignLeft),
  5011. tooltip: lang.image.floatLeft,
  5012. click: context.createInvokeHandler('editor.floatMe', 'left')
  5013. }).render();
  5014. });
  5015. context.memo('button.floatRight', function () {
  5016. return ui.button({
  5017. contents: ui.icon(options.icons.alignRight),
  5018. tooltip: lang.image.floatRight,
  5019. click: context.createInvokeHandler('editor.floatMe', 'right')
  5020. }).render();
  5021. });
  5022. context.memo('button.floatNone', function () {
  5023. return ui.button({
  5024. contents: ui.icon(options.icons.alignJustify),
  5025. tooltip: lang.image.floatNone,
  5026. click: context.createInvokeHandler('editor.floatMe', 'none')
  5027. }).render();
  5028. });
  5029. // Remove Buttons
  5030. context.memo('button.removeMedia', function () {
  5031. return ui.button({
  5032. contents: ui.icon(options.icons.trash),
  5033. tooltip: lang.image.remove,
  5034. click: context.createInvokeHandler('editor.removeMedia')
  5035. }).render();
  5036. });
  5037. };
  5038. this.addLinkPopoverButtons = function () {
  5039. context.memo('button.linkDialogShow', function () {
  5040. return ui.button({
  5041. contents: ui.icon(options.icons.link),
  5042. tooltip: lang.link.edit,
  5043. click: context.createInvokeHandler('linkDialog.show')
  5044. }).render();
  5045. });
  5046. context.memo('button.unlink', function () {
  5047. return ui.button({
  5048. contents: ui.icon(options.icons.unlink),
  5049. tooltip: lang.link.unlink,
  5050. click: context.createInvokeHandler('editor.unlink')
  5051. }).render();
  5052. });
  5053. };
  5054. this.build = function ($container, groups) {
  5055. for (var groupIdx = 0, groupLen = groups.length; groupIdx < groupLen; groupIdx++) {
  5056. var group = groups[groupIdx];
  5057. var groupName = group[0];
  5058. var buttons = group[1];
  5059. var $group = ui.buttonGroup({
  5060. className: 'note-' + groupName
  5061. }).render();
  5062. for (var idx = 0, len = buttons.length; idx < len; idx++) {
  5063. var button = context.memo('button.' + buttons[idx]);
  5064. if (button) {
  5065. $group.append(typeof button === 'function' ? button(context) : button);
  5066. }
  5067. }
  5068. $group.appendTo($container);
  5069. }
  5070. };
  5071. this.updateCurrentStyle = function () {
  5072. var styleInfo = context.invoke('editor.currentStyle');
  5073. this.updateBtnStates({
  5074. '.note-btn-bold': function () {
  5075. return styleInfo['font-bold'] === 'bold';
  5076. },
  5077. '.note-btn-italic': function () {
  5078. return styleInfo['font-italic'] === 'italic';
  5079. },
  5080. '.note-btn-underline': function () {
  5081. return styleInfo['font-underline'] === 'underline';
  5082. },
  5083. '.note-btn-subscript': function () {
  5084. return styleInfo['font-subscript'] === 'subscript';
  5085. },
  5086. '.note-btn-superscript': function () {
  5087. return styleInfo['font-superscript'] === 'superscript';
  5088. },
  5089. '.note-btn-strikethrough': function () {
  5090. return styleInfo['font-strikethrough'] === 'strikethrough';
  5091. }
  5092. });
  5093. if (styleInfo['font-family']) {
  5094. var fontNames = styleInfo['font-family'].split(',').map(function (name) {
  5095. return name.replace(/[\'\"]/g, '')
  5096. .replace(/\s+$/, '')
  5097. .replace(/^\s+/, '');
  5098. });
  5099. var fontName = list.find(fontNames, self.isFontInstalled);
  5100. $toolbar.find('.dropdown-fontname li a').each(function () {
  5101. // always compare string to avoid creating another func.
  5102. var isChecked = ($(this).data('value') + '') === (fontName + '');
  5103. this.className = isChecked ? 'checked' : '';
  5104. });
  5105. $toolbar.find('.note-current-fontname').text(fontName);
  5106. }
  5107. if (styleInfo['font-size']) {
  5108. var fontSize = styleInfo['font-size'];
  5109. $toolbar.find('.dropdown-fontsize li a').each(function () {
  5110. // always compare with string to avoid creating another func.
  5111. var isChecked = ($(this).data('value') + '') === (fontSize + '');
  5112. this.className = isChecked ? 'checked' : '';
  5113. });
  5114. $toolbar.find('.note-current-fontsize').text(fontSize);
  5115. }
  5116. if (styleInfo['line-height']) {
  5117. var lineHeight = styleInfo['line-height'];
  5118. $toolbar.find('.dropdown-line-height li a').each(function () {
  5119. // always compare with string to avoid creating another func.
  5120. var isChecked = ($(this).data('value') + '') === (lineHeight + '');
  5121. this.className = isChecked ? 'checked' : '';
  5122. });
  5123. }
  5124. };
  5125. this.updateBtnStates = function (infos) {
  5126. $.each(infos, function (selector, pred) {
  5127. ui.toggleBtnActive($toolbar.find(selector), pred());
  5128. });
  5129. };
  5130. this.tableMoveHandler = function (event) {
  5131. var PX_PER_EM = 18;
  5132. var $picker = $(event.target.parentNode); // target is mousecatcher
  5133. var $dimensionDisplay = $picker.next();
  5134. var $catcher = $picker.find('.note-dimension-picker-mousecatcher');
  5135. var $highlighted = $picker.find('.note-dimension-picker-highlighted');
  5136. var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted');
  5137. var posOffset;
  5138. // HTML5 with jQuery - e.offsetX is undefined in Firefox
  5139. if (event.offsetX === undefined) {
  5140. var posCatcher = $(event.target).offset();
  5141. posOffset = {
  5142. x: event.pageX - posCatcher.left,
  5143. y: event.pageY - posCatcher.top
  5144. };
  5145. } else {
  5146. posOffset = {
  5147. x: event.offsetX,
  5148. y: event.offsetY
  5149. };
  5150. }
  5151. var dim = {
  5152. c: Math.ceil(posOffset.x / PX_PER_EM) || 1,
  5153. r: Math.ceil(posOffset.y / PX_PER_EM) || 1
  5154. };
  5155. $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' });
  5156. $catcher.data('value', dim.c + 'x' + dim.r);
  5157. if (3 < dim.c && dim.c < options.insertTableMaxSize.col) {
  5158. $unhighlighted.css({ width: dim.c + 1 + 'em'});
  5159. }
  5160. if (3 < dim.r && dim.r < options.insertTableMaxSize.row) {
  5161. $unhighlighted.css({ height: dim.r + 1 + 'em'});
  5162. }
  5163. $dimensionDisplay.html(dim.c + ' x ' + dim.r);
  5164. };
  5165. };
  5166. var Toolbar = function (context) {
  5167. var ui = $.summernote.ui;
  5168. var $note = context.layoutInfo.note;
  5169. var $toolbar = context.layoutInfo.toolbar;
  5170. var options = context.options;
  5171. this.shouldInitialize = function () {
  5172. return !options.airMode;
  5173. };
  5174. this.initialize = function () {
  5175. options.toolbar = options.toolbar || [];
  5176. if (!options.toolbar.length) {
  5177. $toolbar.hide();
  5178. } else {
  5179. context.invoke('buttons.build', $toolbar, options.toolbar);
  5180. }
  5181. if (options.toolbarContainer) {
  5182. $toolbar.appendTo(options.toolbarContainer);
  5183. }
  5184. $note.on('summernote.keyup summernote.mouseup summernote.change', function () {
  5185. context.invoke('buttons.updateCurrentStyle');
  5186. });
  5187. context.invoke('buttons.updateCurrentStyle');
  5188. };
  5189. this.destroy = function () {
  5190. $toolbar.children().remove();
  5191. };
  5192. this.updateFullscreen = function (isFullscreen) {
  5193. ui.toggleBtnActive($toolbar.find('.btn-fullscreen'), isFullscreen);
  5194. };
  5195. this.updateCodeview = function (isCodeview) {
  5196. ui.toggleBtnActive($toolbar.find('.btn-codeview'), isCodeview);
  5197. if (isCodeview) {
  5198. this.deactivate();
  5199. } else {
  5200. this.activate();
  5201. }
  5202. };
  5203. this.activate = function (isIncludeCodeview) {
  5204. var $btn = $toolbar.find('button');
  5205. if (!isIncludeCodeview) {
  5206. $btn = $btn.not('.btn-codeview');
  5207. }
  5208. ui.toggleBtn($btn, true);
  5209. };
  5210. this.deactivate = function (isIncludeCodeview) {
  5211. var $btn = $toolbar.find('button');
  5212. if (!isIncludeCodeview) {
  5213. $btn = $btn.not('.btn-codeview');
  5214. }
  5215. ui.toggleBtn($btn, false);
  5216. };
  5217. };
  5218. var LinkDialog = function (context) {
  5219. var self = this;
  5220. var ui = $.summernote.ui;
  5221. var $editor = context.layoutInfo.editor;
  5222. var options = context.options;
  5223. var lang = options.langInfo;
  5224. this.shouldInitialize = function () {
  5225. return !options.airMode;
  5226. };
  5227. this.initialize = function () {
  5228. var $container = options.dialogsInBody ? $(document.body) : $editor;
  5229. var body = '<div class="form-group">' +
  5230. '<label>' + lang.link.textToDisplay + '</label>' +
  5231. '<input class="note-link-text form-control" type="text" />' +
  5232. '</div>' +
  5233. '<div class="form-group">' +
  5234. '<label>' + lang.link.url + '</label>' +
  5235. '<input class="note-link-url form-control" type="text" value="http://" />' +
  5236. '</div>' +
  5237. (!options.disableLinkTarget ?
  5238. '<div class="checkbox">' +
  5239. '<label>' + '<input type="checkbox" checked> ' + lang.link.openInNewWindow + '</label>' +
  5240. '</div>' : ''
  5241. );
  5242. var footer = '<button href="#" class="btn btn-primary note-link-btn disabled" disabled>' + lang.link.insert + '</button>';
  5243. this.$dialog = ui.dialog({
  5244. className: 'link-dialog',
  5245. title: lang.link.insert,
  5246. fade: options.dialogsFade,
  5247. body: body,
  5248. footer: footer
  5249. }).render().appendTo($container);
  5250. };
  5251. this.destroy = function () {
  5252. ui.hideDialog(this.$dialog);
  5253. this.$dialog.remove();
  5254. };
  5255. this.bindEnterKey = function ($input, $btn) {
  5256. $input.on('keypress', function (event) {
  5257. if (event.keyCode === key.code.ENTER) {
  5258. $btn.trigger('click');
  5259. }
  5260. });
  5261. };
  5262. /**
  5263. * toggle update button
  5264. */
  5265. this.toggleLinkBtn = function ($linkBtn, $linkText, $linkUrl) {
  5266. ui.toggleBtn($linkBtn, $linkText.val() && $linkUrl.val());
  5267. };
  5268. /**
  5269. * Show link dialog and set event handlers on dialog controls.
  5270. *
  5271. * @param {Object} linkInfo
  5272. * @return {Promise}
  5273. */
  5274. this.showLinkDialog = function (linkInfo) {
  5275. return $.Deferred(function (deferred) {
  5276. var $linkText = self.$dialog.find('.note-link-text'),
  5277. $linkUrl = self.$dialog.find('.note-link-url'),
  5278. $linkBtn = self.$dialog.find('.note-link-btn'),
  5279. $openInNewWindow = self.$dialog.find('input[type=checkbox]');
  5280. ui.onDialogShown(self.$dialog, function () {
  5281. context.triggerEvent('dialog.shown');
  5282. // if no url was given, copy text to url
  5283. if (!linkInfo.url) {
  5284. linkInfo.url = linkInfo.text;
  5285. }
  5286. $linkText.val(linkInfo.text);
  5287. var handleLinkTextUpdate = function () {
  5288. self.toggleLinkBtn($linkBtn, $linkText, $linkUrl);
  5289. // if linktext was modified by keyup,
  5290. // stop cloning text from linkUrl
  5291. linkInfo.text = $linkText.val();
  5292. };
  5293. $linkText.on('input', handleLinkTextUpdate).on('paste', function () {
  5294. setTimeout(handleLinkTextUpdate, 0);
  5295. });
  5296. var handleLinkUrlUpdate = function () {
  5297. self.toggleLinkBtn($linkBtn, $linkText, $linkUrl);
  5298. // display same link on `Text to display` input
  5299. // when create a new link
  5300. if (!linkInfo.text) {
  5301. $linkText.val($linkUrl.val());
  5302. }
  5303. };
  5304. $linkUrl.on('input', handleLinkUrlUpdate).on('paste', function () {
  5305. setTimeout(handleLinkUrlUpdate, 0);
  5306. }).val(linkInfo.url).trigger('focus');
  5307. self.toggleLinkBtn($linkBtn, $linkText, $linkUrl);
  5308. self.bindEnterKey($linkUrl, $linkBtn);
  5309. self.bindEnterKey($linkText, $linkBtn);
  5310. $openInNewWindow.prop('checked', linkInfo.isNewWindow);
  5311. $linkBtn.one('click', function (event) {
  5312. event.preventDefault();
  5313. deferred.resolve({
  5314. range: linkInfo.range,
  5315. url: $linkUrl.val(),
  5316. text: $linkText.val(),
  5317. isNewWindow: $openInNewWindow.is(':checked')
  5318. });
  5319. self.$dialog.modal('hide');
  5320. });
  5321. });
  5322. ui.onDialogHidden(self.$dialog, function () {
  5323. // detach events
  5324. $linkText.off('input paste keypress');
  5325. $linkUrl.off('input paste keypress');
  5326. $linkBtn.off('click');
  5327. if (deferred.state() === 'pending') {
  5328. deferred.reject();
  5329. }
  5330. });
  5331. ui.showDialog(self.$dialog);
  5332. }).promise();
  5333. };
  5334. /**
  5335. * @param {Object} layoutInfo
  5336. */
  5337. this.show = function () {
  5338. var linkInfo = context.invoke('editor.getLinkInfo');
  5339. context.invoke('editor.saveRange');
  5340. this.showLinkDialog(linkInfo).then(function (linkInfo) {
  5341. context.invoke('editor.restoreRange');
  5342. context.invoke('editor.createLink', linkInfo);
  5343. }).fail(function () {
  5344. context.invoke('editor.restoreRange');
  5345. });
  5346. };
  5347. context.memo('help.linkDialog.show', options.langInfo.help['linkDialog.show']);
  5348. };
  5349. var LinkPopover = function (context) {
  5350. var self = this;
  5351. var ui = $.summernote.ui;
  5352. var options = context.options;
  5353. this.events = {
  5354. 'summernote.keyup summernote.mouseup summernote.change summernote.scroll': function () {
  5355. self.update();
  5356. },
  5357. 'summernote.dialog.shown': function () {
  5358. self.hide();
  5359. }
  5360. };
  5361. this.shouldInitialize = function () {
  5362. return !list.isEmpty(options.popover.link);
  5363. };
  5364. this.initialize = function () {
  5365. this.$popover = ui.popover({
  5366. className: 'note-link-popover',
  5367. callback: function ($node) {
  5368. var $content = $node.find('.popover-content');
  5369. $content.prepend('<span><a target="_blank"></a>&nbsp;</span>');
  5370. }
  5371. }).render().appendTo('body');
  5372. var $content = this.$popover.find('.popover-content');
  5373. context.invoke('buttons.build', $content, options.popover.link);
  5374. };
  5375. this.destroy = function () {
  5376. this.$popover.remove();
  5377. };
  5378. this.update = function () {
  5379. // Prevent focusing on editable when invoke('code') is executed
  5380. if (!context.invoke('editor.hasFocus')) {
  5381. this.hide();
  5382. return;
  5383. }
  5384. var rng = context.invoke('editor.createRange');
  5385. if (rng.isCollapsed() && rng.isOnAnchor()) {
  5386. var anchor = dom.ancestor(rng.sc, dom.isAnchor);
  5387. var href = $(anchor).attr('href');
  5388. this.$popover.find('a').attr('href', href).html(href);
  5389. var pos = dom.posFromPlaceholder(anchor);
  5390. this.$popover.css({
  5391. display: 'block',
  5392. left: pos.left,
  5393. top: pos.top
  5394. });
  5395. } else {
  5396. this.hide();
  5397. }
  5398. };
  5399. this.hide = function () {
  5400. this.$popover.hide();
  5401. };
  5402. };
  5403. var ImageDialog = function (context) {
  5404. var self = this;
  5405. var ui = $.summernote.ui;
  5406. var $editor = context.layoutInfo.editor;
  5407. var options = context.options;
  5408. var lang = options.langInfo;
  5409. this.shouldInitialize = function () {
  5410. return !options.airMode;
  5411. };
  5412. this.initialize = function () {
  5413. var $container = options.dialogsInBody ? $(document.body) : $editor;
  5414. var imageLimitation = '';
  5415. if (options.maximumImageFileSize) {
  5416. var unit = Math.floor(Math.log(options.maximumImageFileSize) / Math.log(1024));
  5417. var readableSize = (options.maximumImageFileSize / Math.pow(1024, unit)).toFixed(2) * 1 +
  5418. ' ' + ' KMGTP'[unit] + 'B';
  5419. imageLimitation = '<small>' + lang.image.maximumFileSize + ' : ' + readableSize + '</small>';
  5420. }
  5421. var body = '<div class="form-group note-group-select-from-files">' +
  5422. '<label>' + lang.image.selectFromFiles + '</label>' +
  5423. '<input class="note-image-input form-control" type="file" name="files" accept="image/*" multiple="multiple" />' +
  5424. imageLimitation +
  5425. '</div>' +
  5426. '<div class="form-group note-group-image-url" style="overflow:auto;">' +
  5427. '<label>' + lang.image.url + '</label>' +
  5428. '<input class="note-image-url form-control col-md-12" type="text" />' +
  5429. '</div>';
  5430. var footer = '<button href="#" class="btn btn-primary note-image-btn disabled" disabled>' + lang.image.insert + '</button>';
  5431. this.$dialog = ui.dialog({
  5432. title: lang.image.insert,
  5433. fade: options.dialogsFade,
  5434. body: body,
  5435. footer: footer
  5436. }).render().appendTo($container);
  5437. };
  5438. this.destroy = function () {
  5439. ui.hideDialog(this.$dialog);
  5440. this.$dialog.remove();
  5441. };
  5442. this.bindEnterKey = function ($input, $btn) {
  5443. $input.on('keypress', function (event) {
  5444. if (event.keyCode === key.code.ENTER) {
  5445. $btn.trigger('click');
  5446. }
  5447. });
  5448. };
  5449. this.show = function () {
  5450. context.invoke('editor.saveRange');
  5451. this.showImageDialog().then(function (data) {
  5452. // [workaround] hide dialog before restore range for IE range focus
  5453. ui.hideDialog(self.$dialog);
  5454. context.invoke('editor.restoreRange');
  5455. if (typeof data === 'string') { // image url
  5456. context.invoke('editor.insertImage', data);
  5457. } else { // array of files
  5458. context.invoke('editor.insertImagesOrCallback', data);
  5459. }
  5460. }).fail(function () {
  5461. context.invoke('editor.restoreRange');
  5462. });
  5463. };
  5464. /**
  5465. * show image dialog
  5466. *
  5467. * @param {jQuery} $dialog
  5468. * @return {Promise}
  5469. */
  5470. this.showImageDialog = function () {
  5471. return $.Deferred(function (deferred) {
  5472. var $imageInput = self.$dialog.find('.note-image-input'),
  5473. $imageUrl = self.$dialog.find('.note-image-url'),
  5474. $imageBtn = self.$dialog.find('.note-image-btn');
  5475. ui.onDialogShown(self.$dialog, function () {
  5476. context.triggerEvent('dialog.shown');
  5477. // Cloning imageInput to clear element.
  5478. $imageInput.replaceWith($imageInput.clone()
  5479. .on('change', function () {
  5480. deferred.resolve(this.files || this.value);
  5481. })
  5482. .val('')
  5483. );
  5484. $imageBtn.click(function (event) {
  5485. event.preventDefault();
  5486. deferred.resolve($imageUrl.val());
  5487. });
  5488. $imageUrl.on('keyup paste', function () {
  5489. var url = $imageUrl.val();
  5490. ui.toggleBtn($imageBtn, url);
  5491. }).val('').trigger('focus');
  5492. self.bindEnterKey($imageUrl, $imageBtn);
  5493. });
  5494. ui.onDialogHidden(self.$dialog, function () {
  5495. $imageInput.off('change');
  5496. $imageUrl.off('keyup paste keypress');
  5497. $imageBtn.off('click');
  5498. if (deferred.state() === 'pending') {
  5499. deferred.reject();
  5500. }
  5501. });
  5502. ui.showDialog(self.$dialog);
  5503. });
  5504. };
  5505. };
  5506. var ImagePopover = function (context) {
  5507. var ui = $.summernote.ui;
  5508. var options = context.options;
  5509. this.shouldInitialize = function () {
  5510. return !list.isEmpty(options.popover.image);
  5511. };
  5512. this.initialize = function () {
  5513. this.$popover = ui.popover({
  5514. className: 'note-image-popover'
  5515. }).render().appendTo('body');
  5516. var $content = this.$popover.find('.popover-content');
  5517. context.invoke('buttons.build', $content, options.popover.image);
  5518. };
  5519. this.destroy = function () {
  5520. this.$popover.remove();
  5521. };
  5522. this.update = function (target) {
  5523. if (dom.isImg(target)) {
  5524. var pos = dom.posFromPlaceholder(target);
  5525. this.$popover.css({
  5526. display: 'block',
  5527. left: pos.left,
  5528. top: pos.top
  5529. });
  5530. } else {
  5531. this.hide();
  5532. }
  5533. };
  5534. this.hide = function () {
  5535. this.$popover.hide();
  5536. };
  5537. };
  5538. var VideoDialog = function (context) {
  5539. var self = this;
  5540. var ui = $.summernote.ui;
  5541. var $editor = context.layoutInfo.editor;
  5542. var options = context.options;
  5543. var lang = options.langInfo;
  5544. this.shouldInitialize = function () {
  5545. return !options.airMode;
  5546. };
  5547. this.initialize = function () {
  5548. var $container = options.dialogsInBody ? $(document.body) : $editor;
  5549. var body = '<div class="form-group row-fluid">' +
  5550. '<label>' + lang.video.url + ' <small class="text-muted">' + lang.video.providers + '</small></label>' +
  5551. '<input class="note-video-url form-control span12" type="text" />' +
  5552. '</div>';
  5553. var footer = '<button href="#" class="btn btn-primary note-video-btn disabled" disabled>' + lang.video.insert + '</button>';
  5554. this.$dialog = ui.dialog({
  5555. title: lang.video.insert,
  5556. fade: options.dialogsFade,
  5557. body: body,
  5558. footer: footer
  5559. }).render().appendTo($container);
  5560. };
  5561. this.destroy = function () {
  5562. ui.hideDialog(this.$dialog);
  5563. this.$dialog.remove();
  5564. };
  5565. this.bindEnterKey = function ($input, $btn) {
  5566. $input.on('keypress', function (event) {
  5567. if (event.keyCode === key.code.ENTER) {
  5568. $btn.trigger('click');
  5569. }
  5570. });
  5571. };
  5572. this.createVideoNode = function (url) {
  5573. // video url patterns(youtube, instagram, vimeo, dailymotion, youku, mp4, ogg, webm)
  5574. var ytRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  5575. var ytMatch = url.match(ytRegExp);
  5576. var igRegExp = /(?:www\.|\/\/)instagram\.com\/p\/(.[a-zA-Z0-9_-]*)/;
  5577. var igMatch = url.match(igRegExp);
  5578. var vRegExp = /\/\/vine\.co\/v\/([a-zA-Z0-9]+)/;
  5579. var vMatch = url.match(vRegExp);
  5580. var vimRegExp = /\/\/(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/;
  5581. var vimMatch = url.match(vimRegExp);
  5582. var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/;
  5583. var dmMatch = url.match(dmRegExp);
  5584. var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/;
  5585. var youkuMatch = url.match(youkuRegExp);
  5586. var mp4RegExp = /^.+.(mp4|m4v)$/;
  5587. var mp4Match = url.match(mp4RegExp);
  5588. var oggRegExp = /^.+.(ogg|ogv)$/;
  5589. var oggMatch = url.match(oggRegExp);
  5590. var webmRegExp = /^.+.(webm)$/;
  5591. var webmMatch = url.match(webmRegExp);
  5592. var $video;
  5593. if (ytMatch && ytMatch[1].length === 11) {
  5594. var youtubeId = ytMatch[1];
  5595. $video = $('<iframe>')
  5596. .attr('frameborder', 0)
  5597. .attr('src', '//www.youtube.com/embed/' + youtubeId)
  5598. .attr('width', '640').attr('height', '360');
  5599. } else if (igMatch && igMatch[0].length) {
  5600. $video = $('<iframe>')
  5601. .attr('frameborder', 0)
  5602. .attr('src', 'https://instagram.com/p/' + igMatch[1] + '/embed/')
  5603. .attr('width', '612').attr('height', '710')
  5604. .attr('scrolling', 'no')
  5605. .attr('allowtransparency', 'true');
  5606. } else if (vMatch && vMatch[0].length) {
  5607. $video = $('<iframe>')
  5608. .attr('frameborder', 0)
  5609. .attr('src', vMatch[0] + '/embed/simple')
  5610. .attr('width', '600').attr('height', '600')
  5611. .attr('class', 'vine-embed');
  5612. } else if (vimMatch && vimMatch[3].length) {
  5613. $video = $('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>')
  5614. .attr('frameborder', 0)
  5615. .attr('src', '//player.vimeo.com/video/' + vimMatch[3])
  5616. .attr('width', '640').attr('height', '360');
  5617. } else if (dmMatch && dmMatch[2].length) {
  5618. $video = $('<iframe>')
  5619. .attr('frameborder', 0)
  5620. .attr('src', '//www.dailymotion.com/embed/video/' + dmMatch[2])
  5621. .attr('width', '640').attr('height', '360');
  5622. } else if (youkuMatch && youkuMatch[1].length) {
  5623. $video = $('<iframe webkitallowfullscreen mozallowfullscreen allowfullscreen>')
  5624. .attr('frameborder', 0)
  5625. .attr('height', '498')
  5626. .attr('width', '510')
  5627. .attr('src', '//player.youku.com/embed/' + youkuMatch[1]);
  5628. } else if (mp4Match || oggMatch || webmMatch) {
  5629. $video = $('<video controls>')
  5630. .attr('src', url)
  5631. .attr('width', '640').attr('height', '360');
  5632. } else {
  5633. // this is not a known video link. Now what, Cat? Now what?
  5634. return false;
  5635. }
  5636. $video.addClass('note-video-clip');
  5637. return $video[0];
  5638. };
  5639. this.show = function () {
  5640. var text = context.invoke('editor.getSelectedText');
  5641. context.invoke('editor.saveRange');
  5642. this.showVideoDialog(text).then(function (url) {
  5643. // [workaround] hide dialog before restore range for IE range focus
  5644. ui.hideDialog(self.$dialog);
  5645. context.invoke('editor.restoreRange');
  5646. // build node
  5647. var $node = self.createVideoNode(url);
  5648. if ($node) {
  5649. // insert video node
  5650. context.invoke('editor.insertNode', $node);
  5651. }
  5652. }).fail(function () {
  5653. context.invoke('editor.restoreRange');
  5654. });
  5655. };
  5656. /**
  5657. * show image dialog
  5658. *
  5659. * @param {jQuery} $dialog
  5660. * @return {Promise}
  5661. */
  5662. this.showVideoDialog = function (text) {
  5663. return $.Deferred(function (deferred) {
  5664. var $videoUrl = self.$dialog.find('.note-video-url'),
  5665. $videoBtn = self.$dialog.find('.note-video-btn');
  5666. ui.onDialogShown(self.$dialog, function () {
  5667. context.triggerEvent('dialog.shown');
  5668. $videoUrl.val(text).on('input', function () {
  5669. ui.toggleBtn($videoBtn, $videoUrl.val());
  5670. }).trigger('focus');
  5671. $videoBtn.click(function (event) {
  5672. event.preventDefault();
  5673. deferred.resolve($videoUrl.val());
  5674. });
  5675. self.bindEnterKey($videoUrl, $videoBtn);
  5676. });
  5677. ui.onDialogHidden(self.$dialog, function () {
  5678. $videoUrl.off('input');
  5679. $videoBtn.off('click');
  5680. if (deferred.state() === 'pending') {
  5681. deferred.reject();
  5682. }
  5683. });
  5684. ui.showDialog(self.$dialog);
  5685. });
  5686. };
  5687. };
  5688. var HelpDialog = function (context) {
  5689. var self = this;
  5690. var ui = $.summernote.ui;
  5691. var $editor = context.layoutInfo.editor;
  5692. var options = context.options;
  5693. var lang = options.langInfo;
  5694. this.shouldInitialize = function () {
  5695. return !options.airMode;
  5696. };
  5697. this.createShortCutList = function () {
  5698. var keyMap = options.keyMap[agent.isMac ? 'mac' : 'pc'];
  5699. return Object.keys(keyMap).map(function (key) {
  5700. var command = keyMap[key];
  5701. var $row = $('<div><div class="help-list-item"/></div>');
  5702. $row.append($('<label><kbd>' + key + '</kdb></label>').css({
  5703. 'width': 180,
  5704. 'margin-right': 10
  5705. })).append($('<span/>').html(context.memo('help.' + command) || command));
  5706. return $row.html();
  5707. }).join('');
  5708. };
  5709. this.initialize = function () {
  5710. var $container = options.dialogsInBody ? $(document.body) : $editor;
  5711. var body = [
  5712. '<p class="text-center">',
  5713. '<a href="http://summernote.org/" target="_blank">Summernote 0.0.0-SNAPSHOT</a> · ',
  5714. '<a href="https://github.com/summernote/summernote" target="_blank">Project</a> · ',
  5715. '<a href="https://github.com/summernote/summernote/issues" target="_blank">Issues</a>',
  5716. '</p>'
  5717. ].join('');
  5718. this.$dialog = ui.dialog({
  5719. title: lang.options.help,
  5720. fade: options.dialogsFade,
  5721. body: this.createShortCutList(),
  5722. footer: body,
  5723. callback: function ($node) {
  5724. $node.find('.modal-body').css({
  5725. 'max-height': 300,
  5726. 'overflow': 'scroll'
  5727. });
  5728. }
  5729. }).render().appendTo($container);
  5730. };
  5731. this.destroy = function () {
  5732. ui.hideDialog(this.$dialog);
  5733. this.$dialog.remove();
  5734. };
  5735. /**
  5736. * show help dialog
  5737. *
  5738. * @return {Promise}
  5739. */
  5740. this.showHelpDialog = function () {
  5741. return $.Deferred(function (deferred) {
  5742. ui.onDialogShown(self.$dialog, function () {
  5743. context.triggerEvent('dialog.shown');
  5744. deferred.resolve();
  5745. });
  5746. ui.showDialog(self.$dialog);
  5747. }).promise();
  5748. };
  5749. this.show = function () {
  5750. context.invoke('editor.saveRange');
  5751. this.showHelpDialog().then(function () {
  5752. context.invoke('editor.restoreRange');
  5753. });
  5754. };
  5755. };
  5756. var AirPopover = function (context) {
  5757. var self = this;
  5758. var ui = $.summernote.ui;
  5759. var options = context.options;
  5760. var AIR_MODE_POPOVER_X_OFFSET = 20;
  5761. this.events = {
  5762. 'summernote.keyup summernote.mouseup summernote.scroll': function () {
  5763. self.update();
  5764. },
  5765. 'summernote.change summernote.dialog.shown': function () {
  5766. self.hide();
  5767. },
  5768. 'summernote.focusout': function (we, e) {
  5769. // [workaround] Firefox doesn't support relatedTarget on focusout
  5770. // - Ignore hide action on focus out in FF.
  5771. if (agent.isFF) {
  5772. return;
  5773. }
  5774. if (!e.relatedTarget || !dom.ancestor(e.relatedTarget, func.eq(self.$popover[0]))) {
  5775. self.hide();
  5776. }
  5777. }
  5778. };
  5779. this.shouldInitialize = function () {
  5780. return options.airMode && !list.isEmpty(options.popover.air);
  5781. };
  5782. this.initialize = function () {
  5783. this.$popover = ui.popover({
  5784. className: 'note-air-popover'
  5785. }).render().appendTo('body');
  5786. var $content = this.$popover.find('.popover-content');
  5787. context.invoke('buttons.build', $content, options.popover.air);
  5788. };
  5789. this.destroy = function () {
  5790. this.$popover.remove();
  5791. };
  5792. this.update = function () {
  5793. var styleInfo = context.invoke('editor.currentStyle');
  5794. if (styleInfo.range && !styleInfo.range.isCollapsed()) {
  5795. var rect = list.last(styleInfo.range.getClientRects());
  5796. if (rect) {
  5797. var bnd = func.rect2bnd(rect);
  5798. this.$popover.css({
  5799. display: 'block',
  5800. left: Math.max(bnd.left + bnd.width / 2, 0) - AIR_MODE_POPOVER_X_OFFSET,
  5801. top: bnd.top + bnd.height
  5802. });
  5803. }
  5804. } else {
  5805. this.hide();
  5806. }
  5807. };
  5808. this.hide = function () {
  5809. this.$popover.hide();
  5810. };
  5811. };
  5812. var HintPopover = function (context) {
  5813. var self = this;
  5814. var ui = $.summernote.ui;
  5815. var POPOVER_DIST = 5;
  5816. var hint = context.options.hint || [];
  5817. var direction = context.options.hintDirection || 'bottom';
  5818. var hints = $.isArray(hint) ? hint : [hint];
  5819. this.events = {
  5820. 'summernote.keyup': function (we, e) {
  5821. if (!e.isDefaultPrevented()) {
  5822. self.handleKeyup(e);
  5823. }
  5824. },
  5825. 'summernote.keydown': function (we, e) {
  5826. self.handleKeydown(e);
  5827. },
  5828. 'summernote.dialog.shown': function () {
  5829. self.hide();
  5830. }
  5831. };
  5832. this.shouldInitialize = function () {
  5833. return hints.length > 0;
  5834. };
  5835. this.initialize = function () {
  5836. this.lastWordRange = null;
  5837. this.$popover = ui.popover({
  5838. className: 'note-hint-popover',
  5839. hideArrow: true,
  5840. direction: ''
  5841. }).render().appendTo('body');
  5842. this.$popover.hide();
  5843. this.$content = this.$popover.find('.popover-content');
  5844. this.$content.on('click', '.note-hint-item', function () {
  5845. self.$content.find('.active').removeClass('active');
  5846. $(this).addClass('active');
  5847. self.replace();
  5848. });
  5849. };
  5850. this.destroy = function () {
  5851. this.$popover.remove();
  5852. };
  5853. this.selectItem = function ($item) {
  5854. this.$content.find('.active').removeClass('active');
  5855. $item.addClass('active');
  5856. this.$content[0].scrollTop = $item[0].offsetTop - (this.$content.innerHeight() / 2);
  5857. };
  5858. this.moveDown = function () {
  5859. var $current = this.$content.find('.note-hint-item.active');
  5860. var $next = $current.next();
  5861. if ($next.length) {
  5862. this.selectItem($next);
  5863. } else {
  5864. var $nextGroup = $current.parent().next();
  5865. if (!$nextGroup.length) {
  5866. $nextGroup = this.$content.find('.note-hint-group').first();
  5867. }
  5868. this.selectItem($nextGroup.find('.note-hint-item').first());
  5869. }
  5870. };
  5871. this.moveUp = function () {
  5872. var $current = this.$content.find('.note-hint-item.active');
  5873. var $prev = $current.prev();
  5874. if ($prev.length) {
  5875. this.selectItem($prev);
  5876. } else {
  5877. var $prevGroup = $current.parent().prev();
  5878. if (!$prevGroup.length) {
  5879. $prevGroup = this.$content.find('.note-hint-group').last();
  5880. }
  5881. this.selectItem($prevGroup.find('.note-hint-item').last());
  5882. }
  5883. };
  5884. this.replace = function () {
  5885. var $item = this.$content.find('.note-hint-item.active');
  5886. if ($item.length) {
  5887. var node = this.nodeFromItem($item);
  5888. this.lastWordRange.insertNode(node);
  5889. range.createFromNode(node).collapse().select();
  5890. this.lastWordRange = null;
  5891. this.hide();
  5892. context.invoke('editor.focus');
  5893. }
  5894. };
  5895. this.nodeFromItem = function ($item) {
  5896. var hint = hints[$item.data('index')];
  5897. var item = $item.data('item');
  5898. var node = hint.content ? hint.content(item) : item;
  5899. if (typeof node === 'string') {
  5900. node = dom.createText(node);
  5901. }
  5902. return node;
  5903. };
  5904. this.createItemTemplates = function (hintIdx, items) {
  5905. var hint = hints[hintIdx];
  5906. return items.map(function (item, idx) {
  5907. var $item = $('<div class="note-hint-item"/>');
  5908. $item.append(hint.template ? hint.template(item) : item + '');
  5909. $item.data({
  5910. 'index': hintIdx,
  5911. 'item': item
  5912. });
  5913. if (hintIdx === 0 && idx === 0) {
  5914. $item.addClass('active');
  5915. }
  5916. return $item;
  5917. });
  5918. };
  5919. this.handleKeydown = function (e) {
  5920. if (!this.$popover.is(':visible')) {
  5921. return;
  5922. }
  5923. if (e.keyCode === key.code.ENTER) {
  5924. e.preventDefault();
  5925. this.replace();
  5926. } else if (e.keyCode === key.code.UP) {
  5927. e.preventDefault();
  5928. this.moveUp();
  5929. } else if (e.keyCode === key.code.DOWN) {
  5930. e.preventDefault();
  5931. this.moveDown();
  5932. }
  5933. };
  5934. this.searchKeyword = function (index, keyword, callback) {
  5935. var hint = hints[index];
  5936. if (hint && hint.match.test(keyword) && hint.search) {
  5937. var matches = hint.match.exec(keyword);
  5938. hint.search(matches[1], callback);
  5939. } else {
  5940. callback();
  5941. }
  5942. };
  5943. this.createGroup = function (idx, keyword) {
  5944. var $group = $('<div class="note-hint-group note-hint-group-' + idx + '"/>');
  5945. this.searchKeyword(idx, keyword, function (items) {
  5946. items = items || [];
  5947. if (items.length) {
  5948. $group.html(self.createItemTemplates(idx, items));
  5949. self.show();
  5950. }
  5951. });
  5952. return $group;
  5953. };
  5954. this.handleKeyup = function (e) {
  5955. if (list.contains([key.code.ENTER, key.code.UP, key.code.DOWN], e.keyCode)) {
  5956. if (e.keyCode === key.code.ENTER) {
  5957. if (this.$popover.is(':visible')) {
  5958. return;
  5959. }
  5960. }
  5961. } else {
  5962. var wordRange = context.invoke('editor.createRange').getWordRange();
  5963. var keyword = wordRange.toString();
  5964. if (hints.length && keyword) {
  5965. this.$content.empty();
  5966. var bnd = func.rect2bnd(list.last(wordRange.getClientRects()));
  5967. if (bnd) {
  5968. this.$popover.hide();
  5969. this.lastWordRange = wordRange;
  5970. hints.forEach(function (hint, idx) {
  5971. if (hint.match.test(keyword)) {
  5972. self.createGroup(idx, keyword).appendTo(self.$content);
  5973. }
  5974. });
  5975. // set position for popover after group is created
  5976. if (direction === 'top') {
  5977. this.$popover.css({
  5978. left: bnd.left,
  5979. top: bnd.top - this.$popover.outerHeight() - POPOVER_DIST
  5980. });
  5981. } else {
  5982. this.$popover.css({
  5983. left: bnd.left,
  5984. top: bnd.top + bnd.height + POPOVER_DIST
  5985. });
  5986. }
  5987. }
  5988. } else {
  5989. this.hide();
  5990. }
  5991. }
  5992. };
  5993. this.show = function () {
  5994. this.$popover.show();
  5995. };
  5996. this.hide = function () {
  5997. this.$popover.hide();
  5998. };
  5999. };
  6000. $.summernote = $.extend($.summernote, {
  6001. version: '0.0.0-SNAPSHOT',
  6002. ui: ui,
  6003. dom: dom,
  6004. plugins: {},
  6005. options: {
  6006. modules: {
  6007. 'editor': Editor,
  6008. 'clipboard': Clipboard,
  6009. 'dropzone': Dropzone,
  6010. 'codeview': Codeview,
  6011. 'statusbar': Statusbar,
  6012. 'fullscreen': Fullscreen,
  6013. 'handle': Handle,
  6014. // FIXME: HintPopover must be front of autolink
  6015. // - Script error about range when Enter key is pressed on hint popover
  6016. 'hintPopover': HintPopover,
  6017. 'autoLink': AutoLink,
  6018. 'autoSync': AutoSync,
  6019. 'placeholder': Placeholder,
  6020. 'buttons': Buttons,
  6021. 'toolbar': Toolbar,
  6022. 'linkDialog': LinkDialog,
  6023. 'linkPopover': LinkPopover,
  6024. 'imageDialog': ImageDialog,
  6025. 'imagePopover': ImagePopover,
  6026. 'videoDialog': VideoDialog,
  6027. 'helpDialog': HelpDialog,
  6028. 'airPopover': AirPopover
  6029. },
  6030. buttons: {},
  6031. lang: 'en-US',
  6032. // toolbar
  6033. toolbar: [
  6034. ['style', ['style']],
  6035. ['font', ['bold', 'underline', 'clear']],
  6036. ['fontname', ['fontname']],
  6037. ['color', ['color']],
  6038. ['para', ['ul', 'ol', 'paragraph']],
  6039. ['table', ['table']],
  6040. ['insert', ['link', 'picture', 'video']],
  6041. ['view', ['fullscreen', 'codeview', 'help']]
  6042. ],
  6043. // popover
  6044. popover: {
  6045. image: [
  6046. ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
  6047. ['float', ['floatLeft', 'floatRight', 'floatNone']],
  6048. ['remove', ['removeMedia']]
  6049. ],
  6050. link: [
  6051. ['link', ['linkDialogShow', 'unlink']]
  6052. ],
  6053. air: [
  6054. ['color', ['color']],
  6055. ['font', ['bold', 'underline', 'clear']],
  6056. ['para', ['ul', 'paragraph']],
  6057. ['table', ['table']],
  6058. ['insert', ['link', 'picture']]
  6059. ]
  6060. },
  6061. // air mode: inline editor
  6062. airMode: false,
  6063. width: null,
  6064. height: null,
  6065. focus: false,
  6066. tabSize: 4,
  6067. styleWithSpan: true,
  6068. shortcuts: true,
  6069. textareaAutoSync: true,
  6070. direction: null,
  6071. styleTags: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
  6072. fontNames: [
  6073. 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New',
  6074. 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande',
  6075. 'Tahoma', 'Times New Roman', 'Verdana'
  6076. ],
  6077. fontSizes: ['8', '9', '10', '11', '12', '14', '18', '24', '36'],
  6078. // pallete colors(n x n)
  6079. colors: [
  6080. ['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF'],
  6081. ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'],
  6082. ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'],
  6083. ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'],
  6084. ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'],
  6085. ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'],
  6086. ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'],
  6087. ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031']
  6088. ],
  6089. lineHeights: ['1.0', '1.2', '1.4', '1.5', '1.6', '1.8', '2.0', '3.0'],
  6090. tableClassName: 'table table-bordered',
  6091. insertTableMaxSize: {
  6092. col: 10,
  6093. row: 10
  6094. },
  6095. dialogsInBody: false,
  6096. dialogsFade: false,
  6097. maximumImageFileSize: null,
  6098. callbacks: {
  6099. onInit: null,
  6100. onFocus: null,
  6101. onBlur: null,
  6102. onEnter: null,
  6103. onKeyup: null,
  6104. onKeydown: null,
  6105. onImageUpload: null,
  6106. onImageUploadError: null
  6107. },
  6108. codemirror: {
  6109. mode: 'text/html',
  6110. htmlMode: true,
  6111. lineNumbers: true
  6112. },
  6113. keyMap: {
  6114. pc: {
  6115. 'ENTER': 'insertParagraph',
  6116. 'CTRL+Z': 'undo',
  6117. 'CTRL+Y': 'redo',
  6118. 'TAB': 'tab',
  6119. 'SHIFT+TAB': 'untab',
  6120. 'CTRL+B': 'bold',
  6121. 'CTRL+I': 'italic',
  6122. 'CTRL+U': 'underline',
  6123. 'CTRL+SHIFT+S': 'strikethrough',
  6124. 'CTRL+BACKSLASH': 'removeFormat',
  6125. 'CTRL+SHIFT+L': 'justifyLeft',
  6126. 'CTRL+SHIFT+E': 'justifyCenter',
  6127. 'CTRL+SHIFT+R': 'justifyRight',
  6128. 'CTRL+SHIFT+J': 'justifyFull',
  6129. 'CTRL+SHIFT+NUM7': 'insertUnorderedList',
  6130. 'CTRL+SHIFT+NUM8': 'insertOrderedList',
  6131. 'CTRL+LEFTBRACKET': 'outdent',
  6132. 'CTRL+RIGHTBRACKET': 'indent',
  6133. 'CTRL+NUM0': 'formatPara',
  6134. 'CTRL+NUM1': 'formatH1',
  6135. 'CTRL+NUM2': 'formatH2',
  6136. 'CTRL+NUM3': 'formatH3',
  6137. 'CTRL+NUM4': 'formatH4',
  6138. 'CTRL+NUM5': 'formatH5',
  6139. 'CTRL+NUM6': 'formatH6',
  6140. 'CTRL+ENTER': 'insertHorizontalRule',
  6141. 'CTRL+K': 'linkDialog.show'
  6142. },
  6143. mac: {
  6144. 'ENTER': 'insertParagraph',
  6145. 'CMD+Z': 'undo',
  6146. 'CMD+SHIFT+Z': 'redo',
  6147. 'TAB': 'tab',
  6148. 'SHIFT+TAB': 'untab',
  6149. 'CMD+B': 'bold',
  6150. 'CMD+I': 'italic',
  6151. 'CMD+U': 'underline',
  6152. 'CMD+SHIFT+S': 'strikethrough',
  6153. 'CMD+BACKSLASH': 'removeFormat',
  6154. 'CMD+SHIFT+L': 'justifyLeft',
  6155. 'CMD+SHIFT+E': 'justifyCenter',
  6156. 'CMD+SHIFT+R': 'justifyRight',
  6157. 'CMD+SHIFT+J': 'justifyFull',
  6158. 'CMD+SHIFT+NUM7': 'insertUnorderedList',
  6159. 'CMD+SHIFT+NUM8': 'insertOrderedList',
  6160. 'CMD+LEFTBRACKET': 'outdent',
  6161. 'CMD+RIGHTBRACKET': 'indent',
  6162. 'CMD+NUM0': 'formatPara',
  6163. 'CMD+NUM1': 'formatH1',
  6164. 'CMD+NUM2': 'formatH2',
  6165. 'CMD+NUM3': 'formatH3',
  6166. 'CMD+NUM4': 'formatH4',
  6167. 'CMD+NUM5': 'formatH5',
  6168. 'CMD+NUM6': 'formatH6',
  6169. 'CMD+ENTER': 'insertHorizontalRule',
  6170. 'CMD+K': 'linkDialog.show'
  6171. }
  6172. },
  6173. icons: {
  6174. 'align': 'note-icon-align',
  6175. 'alignCenter': 'note-icon-align-center',
  6176. 'alignJustify': 'note-icon-align-justify',
  6177. 'alignLeft': 'note-icon-align-left',
  6178. 'alignRight': 'note-icon-align-right',
  6179. 'indent': 'note-icon-align-indent',
  6180. 'outdent': 'note-icon-align-outdent',
  6181. 'arrowsAlt': 'note-icon-arrows-alt',
  6182. 'bold': 'note-icon-bold',
  6183. 'caret': 'note-icon-caret',
  6184. 'circle': 'note-icon-circle',
  6185. 'close': 'note-icon-close',
  6186. 'code': 'note-icon-code',
  6187. 'eraser': 'note-icon-eraser',
  6188. 'font': 'note-icon-font',
  6189. 'frame': 'note-icon-frame',
  6190. 'italic': 'note-icon-italic',
  6191. 'link': 'note-icon-link',
  6192. 'unlink': 'note-icon-chain-broken',
  6193. 'magic': 'note-icon-magic',
  6194. 'menuCheck': 'note-icon-check',
  6195. 'minus': 'note-icon-minus',
  6196. 'orderedlist': 'note-icon-orderedlist',
  6197. 'pencil': 'note-icon-pencil',
  6198. 'picture': 'note-icon-picture',
  6199. 'question': 'note-icon-question',
  6200. 'redo': 'note-icon-redo',
  6201. 'square': 'note-icon-square',
  6202. 'strikethrough': 'note-icon-strikethrough',
  6203. 'subscript': 'note-icon-subscript',
  6204. 'superscript': 'note-icon-superscript',
  6205. 'table': 'note-icon-table',
  6206. 'textHeight': 'note-icon-text-height',
  6207. 'trash': 'note-icon-trash',
  6208. 'underline': 'note-icon-underline',
  6209. 'undo': 'note-icon-undo',
  6210. 'unorderedlist': 'note-icon-unorderedlist',
  6211. 'video': 'note-icon-video'
  6212. }
  6213. }
  6214. });
  6215. }));