closure-range.js 355 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666
  1. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Bootstrap for the Google JS Library (Closure).
  16. *
  17. * In uncompiled mode base.js will write out Closure's deps file, unless the
  18. * global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to
  19. * include their own deps file(s) from different locations.
  20. *
  21. */
  22. /**
  23. * Base namespace for the Closure library. Checks to see goog is
  24. * already defined in the current scope before assigning to prevent
  25. * clobbering if base.js is loaded more than once.
  26. *
  27. * @const
  28. */
  29. var goog = _WIN.goog = _WIN.goog || {};
  30. /**
  31. * Reference to the global context. In most cases this will be 'window'.
  32. */
  33. goog.global = _WIN;
  34. /**
  35. * @define {string} LOCALE defines the locale being used for compilation. It is
  36. * used to select locale specific data to be compiled in js binary. BUILD rule
  37. * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler
  38. * option.
  39. *
  40. * Take into account that the locale code format is important. You should use
  41. * the canonical Unicode format with hyphen as a delimiter. Language must be
  42. * lowercase, Language Script - Capitalized, Region - UPPERCASE.
  43. * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.
  44. *
  45. * See more info about locale codes here:
  46. * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers
  47. *
  48. * For language codes you should use values defined by ISO 693-1. See it here
  49. * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from
  50. * this rule: the Hebrew language. For legacy reasons the old code (iw) should
  51. * be used instead of the new code (he), see http://wiki/Main/IIISynonyms.
  52. */
  53. goog.LOCALE = 'en'; // default to en
  54. /**
  55. * Creates object stubs for a namespace. When present in a file, goog.provide
  56. * also indicates that the file defines the indicated object. Calls to
  57. * goog.provide are resolved by the compiler if --closure_pass is set.
  58. * @param {string} name name of the object that this file defines.
  59. */
  60. goog.provide = function(name) {
  61. goog.exportPath_(name);
  62. };
  63. /**
  64. * Builds an object structure for the provided namespace path,
  65. * ensuring that names that already exist are not overwritten. For
  66. * example:
  67. * "a.b.c" -> a = {};a.b={};a.b.c={};
  68. * Used by goog.provide and goog.exportSymbol.
  69. * @param {string} name name of the object that this file defines.
  70. * @param {*=} opt_object the object to expose at the end of the path.
  71. * @param {Object=} opt_objectToExportTo The object to add the path to; default
  72. * is |goog.global|.
  73. * @private
  74. */
  75. goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
  76. var parts = name.split('.');
  77. var cur = opt_objectToExportTo || goog.global;
  78. // Internet Explorer exhibits strange behavior when throwing errors from
  79. // methods externed in this manner. See the testExportSymbolExceptions in
  80. // base_test.html for an example.
  81. if (!(parts[0] in cur) && cur.execScript) {
  82. cur.execScript('var ' + parts[0]);
  83. }
  84. // Certain browsers cannot parse code in the form for((a in b); c;);
  85. // This pattern is produced by the JSCompiler when it collapses the
  86. // statement above into the conditional loop below. To prevent this from
  87. // happening, use a for-loop and reserve the init logic as below.
  88. // Parentheses added to eliminate strict JS warning in Firefox.
  89. for (var part; parts.length && (part = parts.shift());) {
  90. if (!parts.length && goog.isDef(opt_object)) {
  91. // last part and we have an object; use it
  92. cur[part] = opt_object;
  93. } else if (cur[part]) {
  94. cur = cur[part];
  95. } else {
  96. cur = cur[part] = {};
  97. }
  98. }
  99. };
  100. /**
  101. * When defining a class Foo with an abstract method bar(), you can do:
  102. *
  103. * Foo.prototype.bar = goog.abstractMethod
  104. *
  105. * Now if a subclass of Foo fails to override bar(), an error
  106. * will be thrown when bar() is invoked.
  107. *
  108. * Note: This does not take the name of the function to override as
  109. * an argument because that would make it more difficult to obfuscate
  110. * our JavaScript code.
  111. *
  112. * @type {!Function}
  113. * @throws {Error} when invoked to indicate the method should be
  114. * overridden.
  115. */
  116. goog.abstractMethod = function() {
  117. throw Error('unimplemented abstract method');
  118. };
  119. //==============================================================================
  120. // Language Enhancements
  121. //==============================================================================
  122. /**
  123. * This is a "fixed" version of the typeof operator. It differs from the typeof
  124. * operator in such a way that null returns 'null' and arrays return 'array'.
  125. * @param {*} value The value to get the type of.
  126. * @return {string} The name of the type.
  127. */
  128. goog.typeOf = function(value) {
  129. var s = typeof value;
  130. if (s == 'object') {
  131. if (value) {
  132. // Check these first, so we can avoid calling Object.prototype.toString if
  133. // possible.
  134. //
  135. // IE improperly marshals tyepof across execution contexts, but a
  136. // cross-context object will still return _FALSE for "instanceof Object".
  137. if (value instanceof Array) {
  138. return 'array';
  139. } else if (value instanceof Object) {
  140. return s;
  141. }
  142. // HACK: In order to use an Object prototype method on the arbitrary
  143. // value, the compiler requires the value be cast to type Object,
  144. // even though the ECMA spec explicitly allows it.
  145. var className = Object.prototype.toString.call(
  146. /** @type {Object} */ (value));
  147. // In Firefox 3.6, attempting to access iframe window objects' length
  148. // property throws an NS_ERROR_FAILURE, so we need to special-case it
  149. // here.
  150. if (className == '[object Window]') {
  151. return 'object';
  152. }
  153. // We cannot always use constructor == Array or instanceof Array because
  154. // different frames have different Array objects. In IE6, if the iframe
  155. // where the array was created is destroyed, the array loses its
  156. // prototype. Then dereferencing val.splice here throws an exception, so
  157. // we can't use goog.isFunction. Calling typeof directly returns 'unknown'
  158. // so that will work. In this case, this function will return _FALSE and
  159. // most array functions will still work because the array is still
  160. // array-like (supports length and []) even though it has lost its
  161. // prototype.
  162. // Mark Miller noticed that Object.prototype.toString
  163. // allows access to the unforgeable [[Class]] property.
  164. // 15.2.4.2 Object.prototype.toString ( )
  165. // When the toString method is called, the following steps are taken:
  166. // 1. Get the [[Class]] property of this object.
  167. // 2. Compute a string value by concatenating the three strings
  168. // "[object ", Result(1), and "]".
  169. // 3. Return Result(2).
  170. // and this behavior survives the destruction of the execution context.
  171. if ((className == '[object Array]' ||
  172. // In IE all non value types are wrapped as objects across window
  173. // boundaries (not iframe though) so we have to do object detection
  174. // for this edge case
  175. typeof value.length == 'number' &&
  176. typeof value.splice != _UNDEFINED+'' &&
  177. typeof value.propertyIsEnumerable != _UNDEFINED+'' &&
  178. !value.propertyIsEnumerable('splice')
  179. )) {
  180. return 'array';
  181. }
  182. // HACK: There is still an array case that fails.
  183. // function ArrayImpostor() {}
  184. // ArrayImpostor.prototype = [];
  185. // var impostor = new ArrayImpostor;
  186. // this can be fixed by getting rid of the fast path
  187. // (value instanceof Array) and solely relying on
  188. // (value && Object.prototype.toString.vall(value) === '[object Array]')
  189. // but that would require many more function calls and is not warranted
  190. // unless closure code is receiving objects from untrusted sources.
  191. // IE in cross-window calls does not correctly marshal the function type
  192. // (it appears just as an object) so we cannot use just typeof val ==
  193. // 'function'. However, if the object has a call property, it is a
  194. // function.
  195. if ((className == '[object Function]' ||
  196. typeof value.call != _UNDEFINED+'' &&
  197. typeof value.propertyIsEnumerable != _UNDEFINED+'' &&
  198. !value.propertyIsEnumerable('call'))) {
  199. return 'function';
  200. }
  201. } else {
  202. return _NULL+'';
  203. }
  204. } else if (s == 'function' && typeof value.call == _UNDEFINED+'') {
  205. // In Safari typeof nodeList returns 'function', and on Firefox
  206. // typeof behaves similarly for HTML{Applet,Embed,Object}Elements
  207. // and RegExps. We would like to return object for those and we can
  208. // detect an invalid function by making sure that the function
  209. // object has a call method.
  210. return 'object';
  211. }
  212. return s;
  213. };
  214. /**
  215. * Returns true if the specified value is not |undefined|.
  216. * WARNING: Do not use this to test if an object has a property. Use the in
  217. * operator instead. Additionally, this function assumes that the global
  218. * undefined variable has not been redefined.
  219. * @param {*} val Variable to test.
  220. * @return {boolean} Whether variable is defined.
  221. */
  222. goog.isDef = function(val) {
  223. return val !== _UNDEFINED;
  224. };
  225. /**
  226. * Returns true if the specified value is |null|
  227. * @param {*} val Variable to test.
  228. * @return {boolean} Whether variable is null.
  229. */
  230. goog.isNull = function(val) {
  231. return val === _NULL;
  232. };
  233. /**
  234. * Returns true if the specified value is defined and not null
  235. * @param {*} val Variable to test.
  236. * @return {boolean} Whether variable is defined and not null.
  237. */
  238. goog.isDefAndNotNull = function(val) {
  239. // Note that undefined == null.
  240. return val != _NULL;
  241. };
  242. /**
  243. * Returns true if the specified value is an array
  244. * @param {*} val Variable to test.
  245. * @return {boolean} Whether variable is an array.
  246. */
  247. goog.isArray = function(val) {
  248. return goog.typeOf(val) == 'array';
  249. };
  250. /**
  251. * Returns true if the object looks like an array. To qualify as array like
  252. * the value needs to be either a NodeList or an object with a Number length
  253. * property.
  254. * @param {*} val Variable to test.
  255. * @return {boolean} Whether variable is an array.
  256. */
  257. goog.isArrayLike = function(val) {
  258. var type = goog.typeOf(val);
  259. return type == 'array' || type == 'object' && typeof val.length == 'number';
  260. };
  261. /**
  262. * Returns true if the object looks like a Date. To qualify as Date-like
  263. * the value needs to be an object and have a getFullYear() function.
  264. * @param {*} val Variable to test.
  265. * @return {boolean} Whether variable is a like a Date.
  266. */
  267. goog.isDateLike = function(val) {
  268. return goog.isObject(val) && typeof val.getFullYear == 'function';
  269. };
  270. /**
  271. * Returns true if the specified value is a string
  272. * @param {*} val Variable to test.
  273. * @return {boolean} Whether variable is a string.
  274. */
  275. goog.isString = function(val) {
  276. return typeof val == 'string';
  277. };
  278. /**
  279. * Returns true if the specified value is a boolean
  280. * @param {*} val Variable to test.
  281. * @return {boolean} Whether variable is boolean.
  282. */
  283. goog.isBoolean = function(val) {
  284. return typeof val == 'boolean';
  285. };
  286. /**
  287. * Returns true if the specified value is a number
  288. * @param {*} val Variable to test.
  289. * @return {boolean} Whether variable is a number.
  290. */
  291. goog.isNumber = function(val) {
  292. return typeof val == 'number';
  293. };
  294. /**
  295. * Returns true if the specified value is a function
  296. * @param {*} val Variable to test.
  297. * @return {boolean} Whether variable is a function.
  298. */
  299. goog.isFunction = function(val) {
  300. return goog.typeOf(val) == 'function';
  301. };
  302. /**
  303. * Returns true if the specified value is an object. This includes arrays
  304. * and functions.
  305. * @param {*} val Variable to test.
  306. * @return {boolean} Whether variable is an object.
  307. */
  308. goog.isObject = function(val) {
  309. var type = goog.typeOf(val);
  310. return type == 'object' || type == 'array' || type == 'function';
  311. };
  312. /**
  313. * Gets a unique ID for an object. This mutates the object so that further
  314. * calls with the same object as a parameter returns the same value. The unique
  315. * ID is guaranteed to be unique across the current session amongst objects that
  316. * are passed into {@code getUid}. There is no guarantee that the ID is unique
  317. * or consistent across sessions. It is unsafe to generate unique ID for
  318. * function prototypes.
  319. *
  320. * @param {Object} obj The object to get the unique ID for.
  321. * @return {number} The unique ID for the object.
  322. */
  323. goog.getUid = function(obj) {
  324. // TODO(user): Make the type stricter, do not accept null.
  325. // In Opera window.hasOwnProperty exists but always returns _FALSE so we avoid
  326. // using it. As a consequence the unique ID generated for BaseClass.prototype
  327. // and SubClass.prototype will be the same.
  328. return obj[goog.UID_PROPERTY_] ||
  329. (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
  330. };
  331. /**
  332. * Name for unique ID property. Initialized in a way to help avoid collisions
  333. * with other closure javascript on the same page.
  334. * @type {string}
  335. * @private
  336. */
  337. goog.UID_PROPERTY_ = 'closure_uid_' +
  338. Math.floor(Math.random() * 2147483648).toString(36);
  339. /**
  340. * Counter for UID.
  341. * @type {number}
  342. * @private
  343. */
  344. goog.uidCounter_ = 0;
  345. /**
  346. * Forward declaration for the clone method. This is necessary until the
  347. * compiler can better support duck-typing constructs as used in
  348. * goog.cloneObject.
  349. *
  350. * TODO(user): Remove once the JSCompiler can infer that the check for
  351. * proto.clone is safe in goog.cloneObject.
  352. *
  353. * @type {Function}
  354. */
  355. Object.prototype.clone;
  356. /**
  357. * A native implementation of goog.bind.
  358. * @param {Function} fn A function to partially apply.
  359. * @param {Object|undefined} selfObj Specifies the object which |this| should
  360. * point to when the function is run. If the value is null or undefined, it
  361. * will default to the global object.
  362. * @param {...*} var_args Additional arguments that are partially
  363. * applied to the function.
  364. * @return {!Function} A partially-applied form of the function bind() was
  365. * invoked as a method of.
  366. * @private
  367. * @suppress {deprecated} The compiler thinks that Function.prototype.bind
  368. * is deprecated because some people have declared a pure-JS version.
  369. * Only the pure-JS version is truly deprecated.
  370. */
  371. goog.bindNative_ = function(fn, selfObj, var_args) {
  372. return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
  373. };
  374. /**
  375. * A pure-JS implementation of goog.bind.
  376. * @param {Function} fn A function to partially apply.
  377. * @param {Object|undefined} selfObj Specifies the object which |this| should
  378. * point to when the function is run. If the value is null or undefined, it
  379. * will default to the global object.
  380. * @param {...*} var_args Additional arguments that are partially
  381. * applied to the function.
  382. * @return {!Function} A partially-applied form of the function bind() was
  383. * invoked as a method of.
  384. * @private
  385. */
  386. goog.bindJs_ = function(fn, selfObj, var_args) {
  387. var context = selfObj || goog.global;
  388. if (arguments.length > 2) {
  389. var boundArgs = Array.prototype.slice.call(arguments, 2);
  390. return function() {
  391. // Prepend the bound arguments to the current arguments.
  392. var newArgs = Array.prototype.slice.call(arguments);
  393. Array.prototype.unshift.apply(newArgs, boundArgs);
  394. return fn.apply(context, newArgs);
  395. };
  396. } else {
  397. return function() {
  398. return fn.apply(context, arguments);
  399. };
  400. }
  401. };
  402. /**
  403. * Partially applies this function to a particular 'this object' and zero or
  404. * more arguments. The result is a new function with some arguments of the first
  405. * function pre-filled and the value of |this| 'pre-specified'.<br><br>
  406. *
  407. * Remaining arguments specified at call-time are appended to the pre-
  408. * specified ones.<br><br>
  409. *
  410. * Also see: {@link #partial}.<br><br>
  411. *
  412. * Usage:
  413. * <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2');
  414. * barMethBound('arg3', 'arg4');</pre>
  415. *
  416. * @param {Function} fn A function to partially apply.
  417. * @param {Object|undefined} selfObj Specifies the object which |this| should
  418. * point to when the function is run. If the value is null or undefined, it
  419. * will default to the global object.
  420. * @param {...*} var_args Additional arguments that are partially
  421. * applied to the function.
  422. * @return {!Function} A partially-applied form of the function bind() was
  423. * invoked as a method of.
  424. * @suppress {deprecated} See above.
  425. */
  426. goog.bind = function(fn, selfObj, var_args) {
  427. // TODO(nicksantos): narrow the type signature.
  428. if (Function.prototype.bind &&
  429. // NOTE(nicksantos): Somebody pulled base.js into the default
  430. // Chrome extension environment. This means that for Chrome extensions,
  431. // they get the implementation of Function.prototype.bind that
  432. // calls goog.bind instead of the native one. Even worse, we don't want
  433. // to introduce a circular dependency between goog.bind and
  434. // Function.prototype.bind, so we have to hack this to make sure it
  435. // works correctly.
  436. Function.prototype.bind.toString().indexOf('native code') != -1) {
  437. goog.bind = goog.bindNative_;
  438. } else {
  439. goog.bind = goog.bindJs_;
  440. }
  441. return goog.bind.apply(_NULL, arguments);
  442. };
  443. /**
  444. * Like bind(), except that a 'this object' is not required. Useful when the
  445. * target function is already bound.
  446. *
  447. * Usage:
  448. * var g = partial(f, arg1, arg2);
  449. * g(arg3, arg4);
  450. *
  451. * @param {Function} fn A function to partially apply.
  452. * @param {...*} var_args Additional arguments that are partially
  453. * applied to fn.
  454. * @return {!Function} A partially-applied form of the function bind() was
  455. * invoked as a method of.
  456. */
  457. goog.partial = function(fn, var_args) {
  458. var args = Array.prototype.slice.call(arguments, 1);
  459. return function() {
  460. // Prepend the bound arguments to the current arguments.
  461. var newArgs = Array.prototype.slice.call(arguments);
  462. newArgs.unshift.apply(newArgs, args);
  463. return fn.apply(this, newArgs);
  464. };
  465. };
  466. /**
  467. * @return {number} An integer value representing the number of milliseconds
  468. * between midnight, January 1, 1970 and the current time.
  469. */
  470. goog.now = Date.now || (function() {
  471. // Unary plus operator converts its operand to a number which in the case of
  472. // a date is done by calling getTime().
  473. return +new Date();
  474. });
  475. /**
  476. * Inherit the prototype methods from one constructor into another.
  477. *
  478. * Usage:
  479. * <pre>
  480. * function ParentClass(a, b) { }
  481. * ParentClass.prototype.foo = function(a) { }
  482. *
  483. * function ChildClass(a, b, c) {
  484. * ParentClass.call(this, a, b);
  485. * }
  486. *
  487. * goog.inherits(ChildClass, ParentClass);
  488. *
  489. * var child = new ChildClass('a', 'b', 'see');
  490. * child.foo(); // works
  491. * </pre>
  492. *
  493. * In addition, a superclass' implementation of a method can be invoked
  494. * as follows:
  495. *
  496. * <pre>
  497. * ChildClass.prototype.foo = function(a) {
  498. * ChildClass.superClass_.foo.call(this, a);
  499. * // other code
  500. * };
  501. * </pre>
  502. *
  503. * @param {Function} childCtor Child class.
  504. * @param {Function} parentCtor Parent class.
  505. */
  506. goog.inherits = function(childCtor, parentCtor) {
  507. /** @constructor */
  508. function tempCtor() {};
  509. tempCtor.prototype = parentCtor.prototype;
  510. childCtor.superClass_ = parentCtor.prototype;
  511. childCtor.prototype = new tempCtor();
  512. childCtor.prototype.constructor = childCtor;
  513. };
  514. /**
  515. * Call up to the superclass.
  516. *
  517. * If this is called from a constructor, then this calls the superclass
  518. * contructor with arguments 1-N.
  519. *
  520. * If this is called from a prototype method, then you must pass
  521. * the name of the method as the second argument to this function. If
  522. * you do not, you will get a runtime error. This calls the superclass'
  523. * method with arguments 2-N.
  524. *
  525. * This function only works if you use goog.inherits to express
  526. * inheritance relationships between your classes.
  527. *
  528. * This function is a compiler primitive. At compile-time, the
  529. * compiler will do macro expansion to remove a lot of
  530. * the extra overhead that this function introduces. The compiler
  531. * will also enforce a lot of the assumptions that this function
  532. * makes, and treat it as a compiler error if you break them.
  533. *
  534. * @param {!Object} me Should always be "this".
  535. * @param {*=} opt_methodName The method name if calling a super method.
  536. * @param {...*} var_args The rest of the arguments.
  537. * @return {*} The return value of the superclass method.
  538. */
  539. goog.base = function(me, opt_methodName, var_args) {
  540. var caller = arguments.callee.caller;
  541. if (caller.superClass_) {
  542. // This is a constructor. Call the superclass constructor.
  543. return caller.superClass_.constructor.apply(
  544. me, Array.prototype.slice.call(arguments, 1));
  545. }
  546. var args = Array.prototype.slice.call(arguments, 2);
  547. var foundCaller = _FALSE;
  548. for (var ctor = me.constructor;
  549. ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
  550. if (ctor.prototype[opt_methodName] === caller) {
  551. foundCaller = _TRUE;
  552. } else if (foundCaller) {
  553. return ctor.prototype[opt_methodName].apply(me, args);
  554. }
  555. }
  556. // If we did not find the caller in the prototype chain,
  557. // then one of two things happened:
  558. // 1) The caller is an instance method.
  559. // 2) This method was not called by the right caller.
  560. if (me[opt_methodName] === caller) {
  561. return me.constructor.prototype[opt_methodName].apply(me, args);
  562. } else {
  563. throw Error(
  564. 'goog.base called from a method of one name ' +
  565. 'to a method of a different name');
  566. }
  567. };
  568. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  569. //
  570. // Licensed under the Apache License, Version 2.0 (the "License");
  571. // you may not use this file except in compliance with the License.
  572. // You may obtain a copy of the License at
  573. //
  574. // http://www.apache.org/licenses/LICENSE-2.0
  575. //
  576. // Unless required by applicable law or agreed to in writing, software
  577. // distributed under the License is distributed on an "AS-IS" BASIS,
  578. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  579. // See the License for the specific language governing permissions and
  580. // limitations under the License.
  581. /**
  582. * @fileoverview Utilities for string manipulation.
  583. */
  584. /**
  585. * Namespace for string utilities
  586. */
  587. goog.provide('goog.string');
  588. goog.provide('goog.string.Unicode');
  589. /**
  590. * Common Unicode string characters.
  591. * @enum {string}
  592. */
  593. goog.string.Unicode = {
  594. NBSP: '\xa0'
  595. };
  596. /**
  597. * Fast prefix-checker.
  598. * @param {string} str The string to check.
  599. * @param {string} prefix A string to look for at the start of {@code str}.
  600. * @return {boolean} True if {@code str} begins with {@code prefix}.
  601. */
  602. goog.string.startsWith = function(str, prefix) {
  603. return str.lastIndexOf(prefix, 0) == 0;
  604. };
  605. /**
  606. * Checks if a string is empty or contains only whitespaces.
  607. * @param {string} str The string to check.
  608. * @return {boolean} True if {@code str} is empty or whitespace only.
  609. */
  610. goog.string.isEmpty = function(str) {
  611. // testing length == 0 first is actually slower in all browsers (about the
  612. // same in Opera).
  613. // Since IE doesn't include non-breaking-space (0xa0) in their \s character
  614. // class (as required by section 7.2 of the ECMAScript spec), we explicitly
  615. // include it in the regexp to enforce consistent cross-browser behavior.
  616. return /^[\s\xa0]*$/.test(str);
  617. };
  618. /**
  619. * Takes a string and replaces newlines with a space. Multiple lines are
  620. * replaced with a single space.
  621. * @param {string} str The string from which to strip newlines.
  622. * @return {string} A copy of {@code str} stripped of newlines.
  623. */
  624. // FTDUEDTR-1183
  625. goog.string.stripNewlines = function(str) {
  626. return str.replace(/ ?(\r\n|\r|\n)+/g, ' ');
  627. };
  628. /**
  629. * Replaces Windows and Mac new lines with unix style: \r or \r\n with \n.
  630. * @param {string} str The string to in which to canonicalize newlines.
  631. * @return {string} {@code str} A copy of {@code} with canonicalized newlines.
  632. */
  633. goog.string.canonicalizeNewlines = function(str) {
  634. return str.replace(/(\r\n|\r|\n)/g, '\n');
  635. };
  636. /**
  637. * Trims white spaces to the left and right of a string.
  638. * @param {string} str The string to trim.
  639. * @return {string} A trimmed copy of {@code str}.
  640. */
  641. goog.string.trim = function(str) {
  642. // Since IE doesn't include non-breaking-space (0xa0) in their \s character
  643. // class (as required by section 7.2 of the ECMAScript spec), we explicitly
  644. // include it in the regexp to enforce consistent cross-browser behavior.
  645. return str.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
  646. };
  647. /**
  648. * Escape double quote '"' characters in addition to '&', '<', and '>' so that a
  649. * string can be included in an HTML tag attribute value within double quotes.
  650. *
  651. * It should be noted that > doesn't need to be escaped for the HTML or XML to
  652. * be valid, but it has been decided to escape it for consistency with other
  653. * implementations.
  654. *
  655. * NOTE(user):
  656. * HtmlEscape is often called during the generation of large blocks of HTML.
  657. * Using statics for the regular expressions and strings is an optimization
  658. * that can more than half the amount of time IE spends in this function for
  659. * large apps, since strings and regexes both contribute to GC allocations.
  660. *
  661. * Testing for the presence of a character before escaping increases the number
  662. * of function calls, but actually provides a speed increase for the average
  663. * case -- since the average case often doesn't require the escaping of all 4
  664. * characters and indexOf() is much cheaper than replace().
  665. * The worst case does suffer slightly from the additional calls, therefore the
  666. * opt_isLikelyToContainHtmlChars option has been included for situations
  667. * where all 4 HTML entities are very likely to be present and need escaping.
  668. *
  669. * Some benchmarks (times tended to fluctuate +-0.05ms):
  670. * FireFox IE6
  671. * (no chars / average (mix of cases) / all 4 chars)
  672. * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80
  673. * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84
  674. * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85
  675. *
  676. * An additional advantage of checking if replace actually needs to be called
  677. * is a reduction in the number of object allocations, so as the size of the
  678. * application grows the difference between the various methods would increase.
  679. *
  680. * @param {string} str string to be escaped.
  681. * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see
  682. * if the character needs replacing - use this option if you expect each of
  683. * the characters to appear often. Leave _FALSE if you expect few html
  684. * characters to occur in your strings, such as if you are escaping HTML.
  685. * @return {string} An escaped copy of {@code str}.
  686. */
  687. goog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {
  688. if (opt_isLikelyToContainHtmlChars) {
  689. return str.replace(goog.string.amperRe_, '&amp;')
  690. .replace(goog.string.ltRe_, '&lt;')
  691. .replace(goog.string.gtRe_, '&gt;')
  692. .replace(goog.string.quotRe_, '&quot;');
  693. } else {
  694. // quick test helps in the case when there are no chars to replace, in
  695. // worst case this makes barely a difference to the time taken
  696. if (!goog.string.allRe_.test(str)) return str;
  697. // str.indexOf is faster than regex.test in this case
  698. if (str.indexOf('&') != -1) {
  699. str = str.replace(goog.string.amperRe_, '&amp;');
  700. }
  701. if (str.indexOf('<') != -1) {
  702. str = str.replace(goog.string.ltRe_, '&lt;');
  703. }
  704. if (str.indexOf('>') != -1) {
  705. str = str.replace(goog.string.gtRe_, '&gt;');
  706. }
  707. if (str.indexOf('"') != -1) {
  708. str = str.replace(goog.string.quotRe_, '&quot;');
  709. }
  710. return str;
  711. }
  712. };
  713. /**
  714. * Regular expression that matches an ampersand, for use in escaping.
  715. * @type {RegExp}
  716. * @private
  717. */
  718. goog.string.amperRe_ = /&/g;
  719. /**
  720. * Regular expression that matches a less than sign, for use in escaping.
  721. * @type {RegExp}
  722. * @private
  723. */
  724. goog.string.ltRe_ = /</g;
  725. /**
  726. * Regular expression that matches a greater than sign, for use in escaping.
  727. * @type {RegExp}
  728. * @private
  729. */
  730. goog.string.gtRe_ = />/g;
  731. /**
  732. * Regular expression that matches a double quote, for use in escaping.
  733. * @type {RegExp}
  734. * @private
  735. */
  736. goog.string.quotRe_ = /\"/g;
  737. /**
  738. * Regular expression that matches any character that needs to be escaped.
  739. * @type {RegExp}
  740. * @private
  741. */
  742. goog.string.allRe_ = /[&<>\"]/;
  743. /**
  744. * Checks whether a string contains a given character.
  745. * @param {string} s The string to test.
  746. * @param {string} ss The substring to test for.
  747. * @return {boolean} True if {@code s} contains {@code ss}.
  748. */
  749. goog.string.contains = function(s, ss) {
  750. return s.indexOf(ss) != -1;
  751. };
  752. /**
  753. * Concatenates string expressions. This is useful
  754. * since some browsers are very inefficient when it comes to using plus to
  755. * concat strings. Be careful when using null and undefined here since
  756. * these will not be included in the result. If you need to represent these
  757. * be sure to cast the argument to a String first.
  758. * For example:
  759. * <pre>buildString('a', 'b', 'c', 'd') -> 'abcd'
  760. * buildString(null, undefined) -> ''
  761. * </pre>
  762. * @param {...*} var_args A list of strings to concatenate. If not a string,
  763. * it will be casted to one.
  764. * @return {string} The concatenation of {@code var_args}.
  765. */
  766. goog.string.buildString = function(var_args) {
  767. return Array.prototype.join.call(arguments, '');
  768. };
  769. /**
  770. * Compares two version numbers.
  771. *
  772. * @param {string|number} version1 Version of first item.
  773. * @param {string|number} version2 Version of second item.
  774. *
  775. * @return {number} 1 if {@code version1} is higher.
  776. * 0 if arguments are equal.
  777. * -1 if {@code version2} is higher.
  778. */
  779. goog.string.compareVersions = function(version1, version2) {
  780. var order = 0;
  781. // Trim leading and trailing whitespace and split the versions into
  782. // subversions.
  783. var v1Subs = goog.string.trim(String(version1)).split('.');
  784. var v2Subs = goog.string.trim(String(version2)).split('.');
  785. var subCount = Math.max(v1Subs.length, v2Subs.length);
  786. // Iterate over the subversions, as long as they appear to be equivalent.
  787. for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {
  788. var v1Sub = v1Subs[subIdx] || '';
  789. var v2Sub = v2Subs[subIdx] || '';
  790. // Split the subversions into pairs of numbers and qualifiers (like 'b').
  791. // Two different RegExp objects are needed because they are both using
  792. // the 'g' flag.
  793. var v1CompParser = new RegExp('(\\d*)(\\D*)', 'g');
  794. var v2CompParser = new RegExp('(\\d*)(\\D*)', 'g');
  795. do {
  796. var v1Comp = v1CompParser.exec(v1Sub) || ['', '', ''];
  797. var v2Comp = v2CompParser.exec(v2Sub) || ['', '', ''];
  798. // Break if there are no more matches.
  799. if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {
  800. break;
  801. }
  802. // Parse the numeric part of the subversion. A missing number is
  803. // equivalent to 0.
  804. var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);
  805. var v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);
  806. // Compare the subversion components. The number has the highest
  807. // precedence. Next, if the numbers are equal, a subversion without any
  808. // qualifier is always higher than a subversion with any qualifier. Next,
  809. // the qualifiers are compared as strings.
  810. order = goog.string.compareElements_(v1CompNum, v2CompNum) ||
  811. goog.string.compareElements_(v1Comp[2].length == 0,
  812. v2Comp[2].length == 0) ||
  813. goog.string.compareElements_(v1Comp[2], v2Comp[2]);
  814. // Stop as soon as an inequality is discovered.
  815. } while (order == 0);
  816. }
  817. return order;
  818. };
  819. /**
  820. * Compares elements of a version number.
  821. *
  822. * @param {string|number|boolean} left An element from a version number.
  823. * @param {string|number|boolean} right An element from a version number.
  824. *
  825. * @return {number} 1 if {@code left} is higher.
  826. * 0 if arguments are equal.
  827. * -1 if {@code right} is higher.
  828. * @private
  829. */
  830. goog.string.compareElements_ = function(left, right) {
  831. if (left < right) {
  832. return -1;
  833. } else if (left > right) {
  834. return 1;
  835. }
  836. return 0;
  837. };
  838. /**
  839. * The most recent unique ID. |0 is equivalent to Math.floor in this case.
  840. * @type {number}
  841. * @private
  842. */
  843. goog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;
  844. /**
  845. * Generates and returns a string which is unique in the current document.
  846. * This is useful, for example, to create unique IDs for DOM elements.
  847. * @return {string} A unique id.
  848. */
  849. goog.string.createUniqueString = function() {
  850. return 'goog_' + goog.string.uniqueStringCounter_++;
  851. };
  852. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  853. //
  854. // Licensed under the Apache License, Version 2.0 (the "License");
  855. // you may not use this file except in compliance with the License.
  856. // You may obtain a copy of the License at
  857. //
  858. // http://www.apache.org/licenses/LICENSE-2.0
  859. //
  860. // Unless required by applicable law or agreed to in writing, software
  861. // distributed under the License is distributed on an "AS-IS" BASIS,
  862. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  863. // See the License for the specific language governing permissions and
  864. // limitations under the License.
  865. /**
  866. * @fileoverview Rendering engine detection.
  867. * @see <a href="http://www.useragentstring.com/">User agent strings</a>
  868. * For information on the browser brand (such as Safari versus Chrome), see
  869. * goog.userAgent.product.
  870. * @see ../demos/useragent.html
  871. */
  872. goog.provide('goog.userAgent');
  873. //goog.require('goog.string');
  874. /**
  875. * @define {boolean} Whether we know at compile-time that the browser is IE.
  876. */
  877. goog.userAgent.ASSUME_IE = _FALSE;
  878. /**
  879. * @define {boolean} Whether we know at compile-time that the browser is GECKO.
  880. */
  881. goog.userAgent.ASSUME_GECKO = _FALSE;
  882. /**
  883. * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.
  884. */
  885. goog.userAgent.ASSUME_WEBKIT = _FALSE;
  886. /**
  887. * @define {boolean} Whether we know at compile-time that the browser is a
  888. * mobile device running WebKit e.g. iPhone or Android.
  889. */
  890. goog.userAgent.ASSUME_MOBILE_WEBKIT = _FALSE;
  891. /**
  892. * @define {boolean} Whether we know at compile-time that the browser is OPERA.
  893. */
  894. goog.userAgent.ASSUME_OPERA = _FALSE;
  895. /**
  896. * @define {boolean} Whether the
  897. * {@code goog.userAgent.isVersionOrHigher}
  898. * function will return true for any version.
  899. */
  900. goog.userAgent.ASSUME_ANY_VERSION = _FALSE;
  901. /**
  902. * Whether we know the browser engine at compile-time.
  903. * @type {boolean}
  904. * @private
  905. */
  906. goog.userAgent.BROWSER_KNOWN_ =
  907. goog.userAgent.ASSUME_IE ||
  908. goog.userAgent.ASSUME_GECKO ||
  909. goog.userAgent.ASSUME_MOBILE_WEBKIT ||
  910. goog.userAgent.ASSUME_WEBKIT ||
  911. goog.userAgent.ASSUME_OPERA;
  912. /**
  913. * Returns the userAgent string for the current browser.
  914. * Some user agents (I'm thinking of you, Gears WorkerPool) do not expose a
  915. * navigator object off the global scope. In that case we return null.
  916. *
  917. * @return {?string} The userAgent string or null if there is none.
  918. */
  919. goog.userAgent.getUserAgentString = function() {
  920. return goog.global['navigator'] ? goog.global['navigator'].userAgent : _NULL;
  921. };
  922. /**
  923. * @return {Object} The native navigator object.
  924. */
  925. goog.userAgent.getNavigator = function() {
  926. // Need a local navigator reference instead of using the global one,
  927. // to avoid the rare case where they reference different objects.
  928. // (goog.gears.FakeWorkerPool, for example).
  929. return goog.global['navigator'];
  930. };
  931. /**
  932. * Initializer for goog.userAgent.
  933. *
  934. * This is a named function so that it can be stripped via the jscompiler
  935. * option for stripping types.
  936. * @private
  937. */
  938. goog.userAgent.init_ = function() {
  939. /**
  940. * Whether the user agent string denotes Opera.
  941. * @type {boolean}
  942. * @private
  943. */
  944. goog.userAgent.detectedOpera_ = _FALSE;
  945. /**
  946. * Whether the user agent string denotes Internet Explorer. This includes
  947. * other browsers using Trident as its rendering engine. For example AOL
  948. * and Netscape 8
  949. * @type {boolean}
  950. * @private
  951. */
  952. goog.userAgent.detectedIe_ = _FALSE;
  953. /**
  954. * Whether the user agent string denotes WebKit. WebKit is the rendering
  955. * engine that Safari, Android and others use.
  956. * @type {boolean}
  957. * @private
  958. */
  959. goog.userAgent.detectedWebkit_ = _FALSE;
  960. /**
  961. * Whether the user agent string denotes a mobile device.
  962. * @type {boolean}
  963. * @private
  964. */
  965. goog.userAgent.detectedMobile_ = _FALSE;
  966. /**
  967. * Whether the user agent string denotes Gecko. Gecko is the rendering
  968. * engine used by Mozilla, Mozilla Firefox, Camino and many more.
  969. * @type {boolean}
  970. * @private
  971. */
  972. goog.userAgent.detectedGecko_ = _FALSE;
  973. var ua;
  974. if (!goog.userAgent.BROWSER_KNOWN_ &&
  975. (ua = goog.userAgent.getUserAgentString())) {
  976. var navigator = goog.userAgent.getNavigator();
  977. goog.userAgent.detectedOpera_ = goog.string.startsWith(ua, 'Opera');
  978. goog.userAgent.detectedIe_ = !goog.userAgent.detectedOpera_ &&
  979. (goog.string.contains(ua, 'MSIE') ||
  980. goog.string.contains(ua, 'Trident'));
  981. goog.userAgent.detectedWebkit_ = !goog.userAgent.detectedOpera_ &&
  982. goog.string.contains(ua, 'WebKit');
  983. // WebKit also gives navigator.product string equal to 'Gecko'.
  984. goog.userAgent.detectedMobile_ = goog.userAgent.detectedWebkit_ &&
  985. goog.string.contains(ua, 'Mobile');
  986. goog.userAgent.detectedGecko_ = !goog.userAgent.detectedOpera_ &&
  987. !goog.userAgent.detectedWebkit_ && !goog.userAgent.detectedIe_ &&
  988. navigator.product == 'Gecko';
  989. }
  990. };
  991. if (!goog.userAgent.BROWSER_KNOWN_) {
  992. goog.userAgent.init_();
  993. }
  994. /**
  995. * Whether the user agent is Opera.
  996. * @type {boolean}
  997. */
  998. goog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?
  999. goog.userAgent.ASSUME_OPERA : goog.userAgent.detectedOpera_;
  1000. /**
  1001. * Whether the user agent is Internet Explorer. This includes other browsers
  1002. * using Trident as its rendering engine. For example AOL and Netscape 8
  1003. * @type {boolean}
  1004. */
  1005. goog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?
  1006. goog.userAgent.ASSUME_IE : goog.userAgent.detectedIe_;
  1007. /**
  1008. * Whether the user agent is Gecko. Gecko is the rendering engine used by
  1009. * Mozilla, Mozilla Firefox, Camino and many more.
  1010. * @type {boolean}
  1011. */
  1012. goog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?
  1013. goog.userAgent.ASSUME_GECKO :
  1014. goog.userAgent.detectedGecko_;
  1015. /**
  1016. * Whether the user agent is WebKit. WebKit is the rendering engine that
  1017. * Safari, Android and others use.
  1018. * @type {boolean}
  1019. */
  1020. goog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?
  1021. goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :
  1022. goog.userAgent.detectedWebkit_;
  1023. /**
  1024. * Whether the user agent is running on a mobile device.
  1025. * @type {boolean}
  1026. */
  1027. goog.userAgent.MOBILE = goog.userAgent.ASSUME_MOBILE_WEBKIT ||
  1028. goog.userAgent.detectedMobile_;
  1029. /**
  1030. * Used while transitioning code to use WEBKIT instead.
  1031. * @type {boolean}
  1032. * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.
  1033. * TODO(nicksantos): Delete this from goog.userAgent.
  1034. */
  1035. goog.userAgent.SAFARI = goog.userAgent.WEBKIT;
  1036. /**
  1037. * @return {string} the platform (operating system) the user agent is running
  1038. * on. Default to empty string because navigator.platform may not be defined
  1039. * (on Rhino, for example).
  1040. * @private
  1041. */
  1042. goog.userAgent.determinePlatform_ = function() {
  1043. var navigator = goog.userAgent.getNavigator();
  1044. return navigator && navigator.platform || '';
  1045. };
  1046. /**
  1047. * The platform (operating system) the user agent is running on. Default to
  1048. * empty string because navigator.platform may not be defined (on Rhino, for
  1049. * example).
  1050. * @type {string}
  1051. */
  1052. goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();
  1053. /**
  1054. * @define {boolean} Whether the user agent is running on a Macintosh operating
  1055. * system.
  1056. */
  1057. goog.userAgent.ASSUME_MAC = _FALSE;
  1058. /**
  1059. * @define {boolean} Whether the user agent is running on a Windows operating
  1060. * system.
  1061. */
  1062. goog.userAgent.ASSUME_WINDOWS = _FALSE;
  1063. /**
  1064. * @define {boolean} Whether the user agent is running on a Linux operating
  1065. * system.
  1066. */
  1067. goog.userAgent.ASSUME_LINUX = _FALSE;
  1068. /**
  1069. * @define {boolean} Whether the user agent is running on a X11 windowing
  1070. * system.
  1071. */
  1072. goog.userAgent.ASSUME_X11 = _FALSE;
  1073. /**
  1074. * @type {boolean}
  1075. * @private
  1076. */
  1077. goog.userAgent.PLATFORM_KNOWN_ =
  1078. goog.userAgent.ASSUME_MAC ||
  1079. goog.userAgent.ASSUME_WINDOWS ||
  1080. goog.userAgent.ASSUME_LINUX ||
  1081. goog.userAgent.ASSUME_X11;
  1082. /**
  1083. * Initialize the goog.userAgent constants that define which platform the user
  1084. * agent is running on.
  1085. * @private
  1086. */
  1087. goog.userAgent.initPlatform_ = function() {
  1088. /**
  1089. * Whether the user agent is running on a Macintosh operating system.
  1090. * @type {boolean}
  1091. * @private
  1092. */
  1093. goog.userAgent.detectedMac_ =goog.string.contains(goog.userAgent.PLATFORM,
  1094. 'Mac');
  1095. /**
  1096. * Whether the user agent is running on a Windows operating system.
  1097. * @type {boolean}
  1098. * @private
  1099. */
  1100. goog.userAgent.detectedWindows_ = goog.string.contains(
  1101. goog.userAgent.PLATFORM, 'Win');
  1102. /**
  1103. * Whether the user agent is running on a Linux operating system.
  1104. * @type {boolean}
  1105. * @private
  1106. */
  1107. goog.userAgent.detectedLinux_ = goog.string.contains(goog.userAgent.PLATFORM,
  1108. 'Linux');
  1109. /**
  1110. * Whether the user agent is running on a X11 windowing system.
  1111. * @type {boolean}
  1112. * @private
  1113. */
  1114. goog.userAgent.detectedX11_ = !!goog.userAgent.getNavigator() &&
  1115. goog.string.contains(goog.userAgent.getNavigator()['appVersion'] || '',
  1116. 'X11');
  1117. };
  1118. if (!goog.userAgent.PLATFORM_KNOWN_) {
  1119. goog.userAgent.initPlatform_();
  1120. }
  1121. /**
  1122. * Whether the user agent is running on a Macintosh operating system.
  1123. * @type {boolean}
  1124. */
  1125. goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?
  1126. goog.userAgent.ASSUME_MAC : goog.userAgent.detectedMac_;
  1127. /**
  1128. * Whether the user agent is running on a Windows operating system.
  1129. * @type {boolean}
  1130. */
  1131. goog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?
  1132. goog.userAgent.ASSUME_WINDOWS : goog.userAgent.detectedWindows_;
  1133. /**
  1134. * Whether the user agent is running on a Linux operating system.
  1135. * @type {boolean}
  1136. */
  1137. goog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?
  1138. goog.userAgent.ASSUME_LINUX : goog.userAgent.detectedLinux_;
  1139. /**
  1140. * Whether the user agent is running on a X11 windowing system.
  1141. * @type {boolean}
  1142. */
  1143. goog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?
  1144. goog.userAgent.ASSUME_X11 : goog.userAgent.detectedX11_;
  1145. /**
  1146. * @return {string} The string that describes the version number of the user
  1147. * agent.
  1148. * @private
  1149. */
  1150. goog.userAgent.determineVersion_ = function() {
  1151. // All browsers have different ways to detect the version and they all have
  1152. // different naming schemes.
  1153. // version is a string rather than a number because it may contain 'b', 'a',
  1154. // and so on.
  1155. var version = '', re;
  1156. if (goog.userAgent.OPERA && goog.global['opera']) {
  1157. var operaVersion = goog.global['opera'].version;
  1158. version = typeof operaVersion == 'function' ? operaVersion() : operaVersion;
  1159. } else {
  1160. if (goog.userAgent.GECKO) {
  1161. re = /rv\:([^\);]+)(\)|;)/;
  1162. } else if (goog.userAgent.IE) {
  1163. re = /MSIE\s+([^\);]+)(\)|;)/;
  1164. } else if (goog.userAgent.WEBKIT) {
  1165. // WebKit/125.4
  1166. re = /WebKit\/(\S+)/;
  1167. }
  1168. if (re) {
  1169. var arr = re.exec(goog.userAgent.getUserAgentString());
  1170. version = arr ? arr[1] : '';
  1171. }
  1172. }
  1173. if (goog.userAgent.IE) {
  1174. // IE9 can be in document mode 9 but be reporting an inconsistent user agent
  1175. // version. If it is identifying as a version lower than 9 we take the
  1176. // documentMode as the version instead. IE8 has similar behavior.
  1177. // It is recommended to set the X-UA-Compatible header to ensure that IE9
  1178. // uses documentMode 9.
  1179. var docMode = goog.userAgent.getDocumentMode_();
  1180. if (docMode > parseFloat(version)) {
  1181. return String(docMode);
  1182. }
  1183. }
  1184. return version;
  1185. };
  1186. /**
  1187. * @return {number|undefined} Returns the document mode (for testing).
  1188. * @private
  1189. */
  1190. goog.userAgent.getDocumentMode_ = function() {
  1191. // NOTE(user): goog.userAgent may be used in context where there is no DOM.
  1192. var doc = goog.global['document'];
  1193. return doc ? doc['documentMode'] : _UNDEFINED;
  1194. };
  1195. /**
  1196. * The version of the user agent. This is a string because it might contain
  1197. * 'b' (as in beta) as well as multiple dots.
  1198. * @type {string}
  1199. */
  1200. goog.userAgent.VERSION = goog.userAgent.determineVersion_();
  1201. /**
  1202. * Compares two version numbers.
  1203. *
  1204. * @param {string} v1 Version of first item.
  1205. * @param {string} v2 Version of second item.
  1206. *
  1207. * @return {number} 1 if first argument is higher
  1208. * 0 if arguments are equal
  1209. * -1 if second argument is higher.
  1210. * @deprecated Use goog.string.compareVersions.
  1211. */
  1212. goog.userAgent.compare = function(v1, v2) {
  1213. return goog.string.compareVersions(v1, v2);
  1214. };
  1215. /**
  1216. * Cache for {@link goog.userAgent.isVersion}. Calls to compareVersions are
  1217. * surprisingly expensive and as a browsers version number is unlikely to change
  1218. * during a session we cache the results.
  1219. * @type {Object}
  1220. * @private
  1221. */
  1222. goog.userAgent.isVersionOrHigherCache_ = {};
  1223. /**
  1224. * Whether the user agent version is higher or the same as the given version.
  1225. * NOTE: When checking the version numbers for Firefox and Safari, be sure to
  1226. * use the engine's version, not the browser's version number. For example,
  1227. * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.
  1228. * Opera and Internet Explorer versions match the product release number.<br>
  1229. * @see <a href="http://en.wikipedia.org/wiki/Safari_version_history">
  1230. * Webkit</a>
  1231. * @see <a href="http://en.wikipedia.org/wiki/Gecko_engine">Gecko</a>
  1232. *
  1233. * @param {string|number} version The version to check.
  1234. * @return {boolean} Whether the user agent version is higher or the same as
  1235. * the given version.
  1236. */
  1237. goog.userAgent.isVersionOrHigher = function(version) {
  1238. return goog.userAgent.ASSUME_ANY_VERSION ||
  1239. goog.userAgent.isVersionOrHigherCache_[version] ||
  1240. (goog.userAgent.isVersionOrHigherCache_[version] =
  1241. goog.string.compareVersions(goog.userAgent.VERSION, version) >= 0);
  1242. };
  1243. /**
  1244. * Deprecated alias to {@code goog.userAgent.isVersionOrHigher}.
  1245. * @param {string|number} version The version to check.
  1246. * @return {boolean} Whether the user agent version is higher or the same as
  1247. * the given version.
  1248. * @deprecated Use goog.userAgent.isVersionOrHigher().
  1249. */
  1250. goog.userAgent.isVersion = goog.userAgent.isVersionOrHigher;
  1251. /**
  1252. * Cache for {@link goog.userAgent.isDocumentMode}.
  1253. * Browsers document mode version number is unlikely to change during a session
  1254. * we cache the results.
  1255. * @type {Object}
  1256. * @private
  1257. */
  1258. goog.userAgent.isDocumentModeCache_ = {};
  1259. /**
  1260. * Whether the IE effective document mode is higher or the same as the given
  1261. * document mode version.
  1262. * NOTE: Only for IE, return false for another browser.
  1263. *
  1264. * @param {number} documentMode The document mode version to check.
  1265. * @return {boolean} Whether the IE effective document mode is higher or the
  1266. * same as the given version.
  1267. */
  1268. goog.userAgent.isDocumentModeOrHigher = function(documentMode) {
  1269. return goog.userAgent.IE && goog.userAgent.DOCUMENT_MODE >= documentMode;
  1270. };
  1271. /**
  1272. * Deprecated alias to {@code goog.userAgent.isDocumentModeOrHigher}.
  1273. * @param {number} version The version to check.
  1274. * @return {boolean} Whether the IE effective document mode is higher or the
  1275. * same as the given version.
  1276. * @deprecated Use goog.userAgent.isDocumentModeOrHigher().
  1277. */
  1278. goog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;
  1279. /**
  1280. * For IE version < 7, documentMode is undefined, so attempt to use the
  1281. * CSS1Compat property to see if we are in standards mode. If we are in
  1282. * standards mode, treat the browser version as the document mode. Otherwise,
  1283. * IE is emulating version 5.
  1284. * @type {number|undefined}
  1285. * @const
  1286. */
  1287. goog.userAgent.DOCUMENT_MODE = (function() {
  1288. var doc = goog.global['document'];
  1289. if (!doc || !goog.userAgent.IE) {
  1290. return undefined;
  1291. }
  1292. var mode = goog.userAgent.getDocumentMode_();
  1293. return mode || (doc['compatMode'] == 'CSS1Compat' ?
  1294. parseInt(goog.userAgent.VERSION, 10) : 5);
  1295. })();
  1296. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  1297. //
  1298. // Licensed under the Apache License, Version 2.0 (the "License");
  1299. // you may not use this file except in compliance with the License.
  1300. // You may obtain a copy of the License at
  1301. //
  1302. // http://www.apache.org/licenses/LICENSE-2.0
  1303. //
  1304. // Unless required by applicable law or agreed to in writing, software
  1305. // distributed under the License is distributed on an "AS-IS" BASIS,
  1306. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1307. // See the License for the specific language governing permissions and
  1308. // limitations under the License.
  1309. /**
  1310. * @fileoverview Utilities for manipulating arrays.
  1311. *
  1312. */
  1313. goog.provide('goog.array');
  1314. goog.provide('goog.array.ArrayLike');
  1315. /**
  1316. * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should
  1317. * rely on Array.prototype functions, if available.
  1318. *
  1319. * The Array.prototype functions can be defined by external libraries like
  1320. * Prototype and setting this flag to _FALSE forces closure to use its own
  1321. * goog.array implementation.
  1322. *
  1323. * If your javascript can be loaded by a third party site and you are wary about
  1324. * relying on the prototype functions, specify
  1325. * "--define goog.NATIVE_ARRAY_PROTOTYPES=_FALSE" to the JSCompiler.
  1326. */
  1327. goog.NATIVE_ARRAY_PROTOTYPES = _TRUE;
  1328. /**
  1329. * @typedef {Array|NodeList|Arguments|{length: number}}
  1330. */
  1331. goog.array.ArrayLike;
  1332. /**
  1333. * Returns the last element in an array without removing it.
  1334. * @param {goog.array.ArrayLike} array The array.
  1335. * @return {*} Last item in array.
  1336. */
  1337. goog.array.peek = function(array) {
  1338. return array[array.length - 1];
  1339. };
  1340. /**
  1341. * Reference to the original {@code Array.prototype}.
  1342. * @private
  1343. */
  1344. goog.array.ARRAY_PROTOTYPE_ = Array.prototype;
  1345. // NOTE(user): Since most of the array functions are generic it allows you to
  1346. // pass an array-like object. Strings have a length and are considered array-
  1347. // like. However, the 'in' operator does not work on strings so we cannot just
  1348. // use the array path even if the browser supports indexing into strings. We
  1349. // therefore end up splitting the string.
  1350. /**
  1351. * Returns the index of the first element of an array with a specified
  1352. * value, or -1 if the element is not present in the array.
  1353. *
  1354. * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}
  1355. *
  1356. * @param {goog.array.ArrayLike} arr The array to be searched.
  1357. * @param {*} obj The object for which we are searching.
  1358. * @param {number=} opt_fromIndex The index at which to start the search. If
  1359. * omitted the search starts at index 0.
  1360. * @return {number} The index of the first matching array element.
  1361. */
  1362. goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&
  1363. goog.array.ARRAY_PROTOTYPE_.indexOf ?
  1364. function(arr, obj, opt_fromIndex) {
  1365. return goog.array.ARRAY_PROTOTYPE_.indexOf.call(arr, obj, opt_fromIndex);
  1366. } :
  1367. function(arr, obj, opt_fromIndex) {
  1368. var fromIndex = opt_fromIndex == _NULL ?
  1369. 0 : (opt_fromIndex < 0 ?
  1370. Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex);
  1371. if (goog.isString(arr)) {
  1372. // Array.prototype.indexOf uses === so only strings should be found.
  1373. if (!goog.isString(obj) || obj.length != 1) {
  1374. return -1;
  1375. }
  1376. return arr.indexOf(obj, fromIndex);
  1377. }
  1378. for (var i = fromIndex; i < arr.length; i++) {
  1379. if (i in arr && arr[i] === obj)
  1380. return i;
  1381. }
  1382. return -1;
  1383. };
  1384. /**
  1385. * Calls a function for each element in an array.
  1386. *
  1387. * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}
  1388. *
  1389. * @param {goog.array.ArrayLike} arr Array or array like object over
  1390. * which to iterate.
  1391. * @param {Function} f The function to call for every element. This function
  1392. * takes 3 arguments (the element, the index and the array). The return
  1393. * value is ignored. The function is called only for indexes of the array
  1394. * which have assigned values; it is not called for indexes which have
  1395. * been deleted or which have never been assigned values.
  1396. *
  1397. * @param {Object=} opt_obj The object to be used as the value of 'this'
  1398. * within f.
  1399. */
  1400. goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&
  1401. goog.array.ARRAY_PROTOTYPE_.forEach ?
  1402. function(arr, f, opt_obj) {
  1403. goog.array.ARRAY_PROTOTYPE_.forEach.call(arr, f, opt_obj);
  1404. } :
  1405. function(arr, f, opt_obj) {
  1406. var l = arr.length; // must be fixed during loop... see docs
  1407. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  1408. for (var i = 0; i < l; i++) {
  1409. if (i in arr2) {
  1410. f.call(opt_obj, arr2[i], i, arr);
  1411. }
  1412. }
  1413. };
  1414. /**
  1415. * Calls a function for each element in an array, starting from the last
  1416. * element rather than the first.
  1417. *
  1418. * @param {goog.array.ArrayLike} arr The array over which to iterate.
  1419. * @param {Function} f The function to call for every element. This function
  1420. * takes 3 arguments (the element, the index and the array). The return
  1421. * value is ignored.
  1422. * @param {Object=} opt_obj The object to be used as the value of 'this'
  1423. * within f.
  1424. */
  1425. goog.array.forEachRight = function(arr, f, opt_obj) {
  1426. var l = arr.length; // must be fixed during loop... see docs
  1427. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  1428. for (var i = l - 1; i >= 0; --i) {
  1429. if (i in arr2) {
  1430. f.call(opt_obj, arr2[i], i, arr);
  1431. }
  1432. }
  1433. };
  1434. /**
  1435. * Calls a function for each element in an array, and if the function returns
  1436. * true adds the element to a new array.
  1437. *
  1438. * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}
  1439. *
  1440. * @param {goog.array.ArrayLike} arr The array over which to iterate.
  1441. * @param {Function} f The function to call for every element. This function
  1442. * takes 3 arguments (the element, the index and the array) and must
  1443. * return a Boolean. If the return value is true the element is added to the
  1444. * result array. If it is _FALSE the element is not included.
  1445. * @param {Object=} opt_obj The object to be used as the value of 'this'
  1446. * within f.
  1447. * @return {!Array} a new array in which only elements that passed the test are
  1448. * present.
  1449. */
  1450. goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&
  1451. goog.array.ARRAY_PROTOTYPE_.filter ?
  1452. function(arr, f, opt_obj) {
  1453. return goog.array.ARRAY_PROTOTYPE_.filter.call(arr, f, opt_obj);
  1454. } :
  1455. function(arr, f, opt_obj) {
  1456. var l = arr.length; // must be fixed during loop... see docs
  1457. var res = [];
  1458. var resLength = 0;
  1459. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  1460. for (var i = 0; i < l; i++) {
  1461. if (i in arr2) {
  1462. var val = arr2[i]; // in case f mutates arr2
  1463. if (f.call(opt_obj, val, i, arr)) {
  1464. res[resLength++] = val;
  1465. }
  1466. }
  1467. }
  1468. return res;
  1469. };
  1470. /**
  1471. * Calls a function for each element in an array and inserts the result into a
  1472. * new array.
  1473. *
  1474. * See {@link http://tinyurl.com/developer-mozilla-org-array-map}
  1475. *
  1476. * @param {goog.array.ArrayLike} arr The array over which to iterate.
  1477. * @param {Function} f The function to call for every element. This function
  1478. * takes 3 arguments (the element, the index and the array) and should
  1479. * return something. The result will be inserted into a new array.
  1480. * @param {Object=} opt_obj The object to be used as the value of 'this'
  1481. * within f.
  1482. * @return {!Array} a new array with the results from f.
  1483. */
  1484. goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&
  1485. goog.array.ARRAY_PROTOTYPE_.map ?
  1486. function(arr, f, opt_obj) {
  1487. return goog.array.ARRAY_PROTOTYPE_.map.call(arr, f, opt_obj);
  1488. } :
  1489. function(arr, f, opt_obj) {
  1490. var l = arr.length; // must be fixed during loop... see docs
  1491. var res = new Array(l);
  1492. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  1493. for (var i = 0; i < l; i++) {
  1494. if (i in arr2) {
  1495. res[i] = f.call(opt_obj, arr2[i], i, arr);
  1496. }
  1497. }
  1498. return res;
  1499. };
  1500. /**
  1501. * Calls f for each element of an array. If any call returns true, some()
  1502. * returns true (without checking the remaining elements). If all calls
  1503. * return _FALSE, some() returns _FALSE.
  1504. *
  1505. * See {@link http://tinyurl.com/developer-mozilla-org-array-some}
  1506. *
  1507. * @param {goog.array.ArrayLike} arr The array to check.
  1508. * @param {Function} f The function to call for every element. This function
  1509. * takes 3 arguments (the element, the index and the array) and must
  1510. * return a Boolean.
  1511. * @param {Object=} opt_obj The object to be used as the value of 'this'
  1512. * within f.
  1513. * @return {boolean} true if any element passes the test.
  1514. */
  1515. goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&
  1516. goog.array.ARRAY_PROTOTYPE_.some ?
  1517. function(arr, f, opt_obj) {
  1518. return goog.array.ARRAY_PROTOTYPE_.some.call(arr, f, opt_obj);
  1519. } :
  1520. function(arr, f, opt_obj) {
  1521. var l = arr.length; // must be fixed during loop... see docs
  1522. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  1523. for (var i = 0; i < l; i++) {
  1524. if (i in arr2 && f.call(opt_obj, arr2[i], i, arr)) {
  1525. return _TRUE;
  1526. }
  1527. }
  1528. return _FALSE;
  1529. };
  1530. /**
  1531. * Call f for each element of an array. If all calls return true, every()
  1532. * returns true. If any call returns _FALSE, every() returns _FALSE and
  1533. * does not continue to check the remaining elements.
  1534. *
  1535. * See {@link http://tinyurl.com/developer-mozilla-org-array-every}
  1536. *
  1537. * @param {goog.array.ArrayLike} arr The array to check.
  1538. * @param {Function} f The function to call for every element. This function
  1539. * takes 3 arguments (the element, the index and the array) and must
  1540. * return a Boolean.
  1541. * @param {Object=} opt_obj The object to be used as the value of 'this'
  1542. * within f.
  1543. * @return {boolean} _FALSE if any element fails the test.
  1544. */
  1545. goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&
  1546. goog.array.ARRAY_PROTOTYPE_.every ?
  1547. function(arr, f, opt_obj) {
  1548. return goog.array.ARRAY_PROTOTYPE_.every.call(arr, f, opt_obj);
  1549. } :
  1550. function(arr, f, opt_obj) {
  1551. var l = arr.length; // must be fixed during loop... see docs
  1552. var arr2 = goog.isString(arr) ? arr.split('') : arr;
  1553. for (var i = 0; i < l; i++) {
  1554. if (i in arr2 && !f.call(opt_obj, arr2[i], i, arr)) {
  1555. return _FALSE;
  1556. }
  1557. }
  1558. return _TRUE;
  1559. };
  1560. /**
  1561. * Whether the array contains the given object.
  1562. * @param {goog.array.ArrayLike} arr The array to test for the presence of the
  1563. * element.
  1564. * @param {*} obj The object for which to test.
  1565. * @return {boolean} true if obj is present.
  1566. */
  1567. goog.array.contains = function(arr, obj) {
  1568. return goog.array.indexOf(arr, obj) >= 0;
  1569. };
  1570. /**
  1571. * Whether the array is empty.
  1572. * @param {goog.array.ArrayLike} arr The array to test.
  1573. * @return {boolean} true if empty.
  1574. */
  1575. goog.array.isEmpty = function(arr) {
  1576. return arr.length == 0;
  1577. };
  1578. /**
  1579. * Clears the array.
  1580. * @param {goog.array.ArrayLike} arr Array or array like object to clear.
  1581. */
  1582. goog.array.clear = function(arr) {
  1583. // For non real arrays we don't have the magic length so we delete the
  1584. // indices.
  1585. if (!goog.isArray(arr)) {
  1586. for (var i = arr.length - 1; i >= 0; i--) {
  1587. delete arr[i];
  1588. }
  1589. }
  1590. arr.length = 0;
  1591. };
  1592. /**
  1593. * Inserts an object at the given index of the array.
  1594. * @param {goog.array.ArrayLike} arr The array to modify.
  1595. * @param {*} obj The object to insert.
  1596. * @param {number=} opt_i The index at which to insert the object. If omitted,
  1597. * treated as 0. A negative index is counted from the end of the array.
  1598. */
  1599. goog.array.insertAt = function(arr, obj, opt_i) {
  1600. goog.array.splice(arr, opt_i, 0, obj);
  1601. };
  1602. /**
  1603. * Removes the first occurrence of a particular value from an array.
  1604. * @param {goog.array.ArrayLike} arr Array from which to remove value.
  1605. * @param {*} obj Object to remove.
  1606. * @return {boolean} True if an element was removed.
  1607. */
  1608. goog.array.remove = function(arr, obj) {
  1609. var i = goog.array.indexOf(arr, obj);
  1610. var rv;
  1611. if ((rv = i >= 0)) {
  1612. goog.array.removeAt(arr, i);
  1613. }
  1614. return rv;
  1615. };
  1616. /**
  1617. * Removes from an array the element at index i
  1618. * @param {goog.array.ArrayLike} arr Array or array like object from which to
  1619. * remove value.
  1620. * @param {number} i The index to remove.
  1621. * @return {boolean} True if an element was removed.
  1622. */
  1623. goog.array.removeAt = function(arr, i) {
  1624. // use generic form of splice
  1625. // splice returns the removed items and if successful the length of that
  1626. // will be 1
  1627. return goog.array.ARRAY_PROTOTYPE_.splice.call(arr, i, 1).length == 1;
  1628. };
  1629. /**
  1630. * Returns a new array that is the result of joining the arguments. If arrays
  1631. * are passed then their items are added, however, if non-arrays are passed they
  1632. * will be added to the return array as is.
  1633. *
  1634. * Note that ArrayLike objects will be added as is, rather than having their
  1635. * items added.
  1636. *
  1637. * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
  1638. * goog.array.concat(0, [1, 2]) -> [0, 1, 2]
  1639. * goog.array.concat([1, 2], null) -> [1, 2, null]
  1640. *
  1641. * There is bug in all current versions of IE (6, 7 and 8) where arrays created
  1642. * in an iframe become corrupted soon (not immediately) after the iframe is
  1643. * destroyed. This is common if loading data via goog.net.IframeIo, for example.
  1644. * This corruption only affects the concat method which will start throwing
  1645. * Catastrophic Errors (#-2147418113).
  1646. *
  1647. * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.
  1648. *
  1649. * Internally goog.array should use this, so that all methods will continue to
  1650. * work on these broken array objects.
  1651. *
  1652. * @param {...*} var_args Items to concatenate. Arrays will have each item
  1653. * added, while primitives and objects will be added as is.
  1654. * @return {!Array} The new resultant array.
  1655. */
  1656. goog.array.concat = function(var_args) {
  1657. return goog.array.ARRAY_PROTOTYPE_.concat.apply(
  1658. goog.array.ARRAY_PROTOTYPE_, arguments);
  1659. };
  1660. /**
  1661. * Does a shallow copy of an array.
  1662. * @param {goog.array.ArrayLike} arr Array or array-like object to clone.
  1663. * @return {!Array} Clone of the input array.
  1664. */
  1665. goog.array.clone = function(arr) {
  1666. if (goog.isArray(arr)) {
  1667. return goog.array.concat(/** @type {!Array} */ (arr));
  1668. } else { // array like
  1669. // Concat does not work with non arrays.
  1670. var rv = [];
  1671. for (var i = 0, len = arr.length; i < len; i++) {
  1672. rv[i] = arr[i];
  1673. }
  1674. return rv;
  1675. }
  1676. };
  1677. /**
  1678. * Converts an object to an array.
  1679. * @param {goog.array.ArrayLike} object The object to convert to an array.
  1680. * @return {!Array} The object converted into an array. If object has a
  1681. * length property, every property indexed with a non-negative number
  1682. * less than length will be included in the result. If object does not
  1683. * have a length property, an empty array will be returned.
  1684. */
  1685. goog.array.toArray = function(object) {
  1686. if (goog.isArray(object)) {
  1687. // This fixes the JS compiler warning and forces the Object to an Array type
  1688. return goog.array.concat(/** @type {!Array} */ (object));
  1689. }
  1690. // Clone what we hope to be an array-like object to an array.
  1691. // We could check isArrayLike() first, but no check we perform would be as
  1692. // reliable as simply making the call.
  1693. return goog.array.clone(/** @type {Array} */ (object));
  1694. };
  1695. /**
  1696. * Adds or removes elements from an array. This is a generic version of Array
  1697. * splice. This means that it might work on other objects similar to arrays,
  1698. * such as the arguments object.
  1699. *
  1700. * @param {goog.array.ArrayLike} arr The array to modify.
  1701. * @param {number|undefined} index The index at which to start changing the
  1702. * array. If not defined, treated as 0.
  1703. * @param {number} howMany How many elements to remove (0 means no removal. A
  1704. * value below 0 is treated as zero and so is any other non number. Numbers
  1705. * are floored).
  1706. * @param {...*} var_args Optional, additional elements to insert into the
  1707. * array.
  1708. * @return {!Array} the removed elements.
  1709. */
  1710. goog.array.splice = function(arr, index, howMany, var_args) {
  1711. return goog.array.ARRAY_PROTOTYPE_.splice.apply(
  1712. arr, goog.array.slice(arguments, 1));
  1713. };
  1714. /**
  1715. * Returns a new array from a segment of an array. This is a generic version of
  1716. * Array slice. This means that it might work on other objects similar to
  1717. * arrays, such as the arguments object.
  1718. *
  1719. * @param {goog.array.ArrayLike} arr The array from which to copy a segment.
  1720. * @param {number} start The index of the first element to copy.
  1721. * @param {number=} opt_end The index after the last element to copy.
  1722. * @return {!Array} A new array containing the specified segment of the original
  1723. * array.
  1724. */
  1725. goog.array.slice = function(arr, start, opt_end) {
  1726. // passing 1 arg to slice is not the same as passing 2 where the second is
  1727. // null or undefined (in that case the second argument is treated as 0).
  1728. // we could use slice on the arguments object and then use apply instead of
  1729. // testing the length
  1730. if (arguments.length <= 2) {
  1731. return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start);
  1732. } else {
  1733. return goog.array.ARRAY_PROTOTYPE_.slice.call(arr, start, opt_end);
  1734. }
  1735. };
  1736. /**
  1737. * Sorts the specified array into ascending order. If no opt_compareFn is
  1738. * specified, elements are compared using
  1739. * <code>goog.array.defaultCompare</code>, which compares the elements using
  1740. * the built in < and > operators. This will produce the expected behavior
  1741. * for homogeneous arrays of String(s) and Number(s), unlike the native sort,
  1742. * but will give unpredictable results for heterogenous lists of strings and
  1743. * numbers with different numbers of digits.
  1744. *
  1745. * This sort is not guaranteed to be stable.
  1746. *
  1747. * Runtime: Same as <code>Array.prototype.sort</code>
  1748. *
  1749. * @param {Array} arr The array to be sorted.
  1750. * @param {Function=} opt_compareFn Optional comparison function by which the
  1751. * array is to be ordered. Should take 2 arguments to compare, and return a
  1752. * negative number, zero, or a positive number depending on whether the
  1753. * first argument is less than, equal to, or greater than the second.
  1754. */
  1755. goog.array.sort = function(arr, opt_compareFn) {
  1756. // TODO(user): Update type annotation since null is not accepted.
  1757. goog.array.ARRAY_PROTOTYPE_.sort.call(
  1758. arr, opt_compareFn || goog.array.defaultCompare);
  1759. };
  1760. /**
  1761. * Compares two arrays for equality. Two arrays are considered equal if they
  1762. * have the same length and their corresponding elements are equal according to
  1763. * the comparison function.
  1764. *
  1765. * @param {goog.array.ArrayLike} arr1 The first array to compare.
  1766. * @param {goog.array.ArrayLike} arr2 The second array to compare.
  1767. * @param {Function=} opt_equalsFn Optional comparison function.
  1768. * Should take 2 arguments to compare, and return true if the arguments
  1769. * are equal. Defaults to {@link goog.array.defaultCompareEquality} which
  1770. * compares the elements using the built-in '===' operator.
  1771. * @return {boolean} Whether the two arrays are equal.
  1772. */
  1773. goog.array.equals = function(arr1, arr2, opt_equalsFn) {
  1774. if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||
  1775. arr1.length != arr2.length) {
  1776. return _FALSE;
  1777. }
  1778. var l = arr1.length;
  1779. var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;
  1780. for (var i = 0; i < l; i++) {
  1781. if (!equalsFn(arr1[i], arr2[i])) {
  1782. return _FALSE;
  1783. }
  1784. }
  1785. return _TRUE;
  1786. };
  1787. /**
  1788. * @deprecated Use {@link goog.array.equals}.
  1789. * @param {goog.array.ArrayLike} arr1 See {@link goog.array.equals}.
  1790. * @param {goog.array.ArrayLike} arr2 See {@link goog.array.equals}.
  1791. * @param {Function=} opt_equalsFn See {@link goog.array.equals}.
  1792. * @return {boolean} See {@link goog.array.equals}.
  1793. */
  1794. goog.array.compare = function(arr1, arr2, opt_equalsFn) {
  1795. return goog.array.equals(arr1, arr2, opt_equalsFn);
  1796. };
  1797. /**
  1798. * Compares its two arguments for order, using the built in < and >
  1799. * operators.
  1800. * @param {*} a The first object to be compared.
  1801. * @param {*} b The second object to be compared.
  1802. * @return {number} A negative number, zero, or a positive number as the first
  1803. * argument is less than, equal to, or greater than the second.
  1804. */
  1805. goog.array.defaultCompare = function(a, b) {
  1806. return a > b ? 1 : a < b ? -1 : 0;
  1807. };
  1808. /**
  1809. * Compares its two arguments for equality, using the built in === operator.
  1810. * @param {*} a The first object to compare.
  1811. * @param {*} b The second object to compare.
  1812. * @return {boolean} True if the two arguments are equal, _FALSE otherwise.
  1813. */
  1814. goog.array.defaultCompareEquality = function(a, b) {
  1815. return a === b;
  1816. };
  1817. /**
  1818. * Returns an array consisting of the given value repeated N times.
  1819. *
  1820. * @param {*} value The value to repeat.
  1821. * @param {number} n The repeat count.
  1822. * @return {!Array.<*>} An array with the repeated value.
  1823. */
  1824. goog.array.repeat = function(value, n) {
  1825. var array = [];
  1826. for (var i = 0; i < n; i++) {
  1827. array[i] = value;
  1828. }
  1829. return array;
  1830. };
  1831. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  1832. //
  1833. // Licensed under the Apache License, Version 2.0 (the "License");
  1834. // you may not use this file except in compliance with the License.
  1835. // You may obtain a copy of the License at
  1836. //
  1837. // http://www.apache.org/licenses/LICENSE-2.0
  1838. //
  1839. // Unless required by applicable law or agreed to in writing, software
  1840. // distributed under the License is distributed on an "AS-IS" BASIS,
  1841. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1842. // See the License for the specific language governing permissions and
  1843. // limitations under the License.
  1844. /**
  1845. * @fileoverview Utilities for adding, removing and setting classes.
  1846. *
  1847. */
  1848. goog.provide('goog.dom.classes');
  1849. //goog.require('goog.array');
  1850. /**
  1851. * Gets an array of class names on an element
  1852. * @param {Node} element DOM node to get class of.
  1853. * @return {Array} Class names on {@code element}.
  1854. */
  1855. goog.dom.classes.get = function(element) {
  1856. var className = element.className;
  1857. // Some types of elements don't have a className in IE (e.g. iframes).
  1858. // Furthermore, in Firefox, className is not a string when the element is
  1859. // an SVG element.
  1860. return className && typeof className.split == 'function' ?
  1861. className.split(/\s+/) : [];
  1862. };
  1863. /**
  1864. * Adds a class or classes to an element. Does not add multiples of class names.
  1865. * @param {Node} element DOM node to add class to.
  1866. * @param {...string} var_args Class names to add.
  1867. * @return {boolean} Whether class was added (or all classes were added).
  1868. */
  1869. goog.dom.classes.add = function(element, var_args) {
  1870. var classes = goog.dom.classes.get(element);
  1871. var args = goog.array.slice(arguments, 1);
  1872. var b = goog.dom.classes.add_(classes, args);
  1873. element.className = classes.join(' ');
  1874. return b;
  1875. };
  1876. /**
  1877. * Helper method for {@link goog.dom.classes.add} and
  1878. * {@link goog.dom.classes.addRemove}. Adds one or more classes to the supplied
  1879. * classes array.
  1880. * @param {Array.<string>} classes All class names for the element, will be
  1881. * updated to have the classes supplied in {@code args} added.
  1882. * @param {Array.<string>} args Class names to add.
  1883. * @return {boolean} Whether all classes in were added.
  1884. * @private
  1885. */
  1886. goog.dom.classes.add_ = function(classes, args) {
  1887. var rv = 0;
  1888. for (var i = 0; i < args.length; i++) {
  1889. if (!goog.array.contains(classes, args[i])) {
  1890. classes.push(args[i]);
  1891. rv++;
  1892. }
  1893. }
  1894. return rv == args.length;
  1895. };
  1896. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  1897. //
  1898. // Licensed under the Apache License, Version 2.0 (the "License");
  1899. // you may not use this file except in compliance with the License.
  1900. // You may obtain a copy of the License at
  1901. //
  1902. // http://www.apache.org/licenses/LICENSE-2.0
  1903. //
  1904. // Unless required by applicable law or agreed to in writing, software
  1905. // distributed under the License is distributed on an "AS-IS" BASIS,
  1906. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1907. // See the License for the specific language governing permissions and
  1908. // limitations under the License.
  1909. /**
  1910. * @fileoverview Utilities for manipulating objects/maps/hashes.
  1911. */
  1912. goog.provide('goog.object');
  1913. /**
  1914. * Calls a function for each element in an object/map/hash.
  1915. *
  1916. * @param {Object} obj The object over which to iterate.
  1917. * @param {Function} f The function to call for every element. This function
  1918. * takes 3 arguments (the element, the index and the object)
  1919. * and the return value is irrelevant.
  1920. * @param {Object=} opt_obj This is used as the 'this' object within f.
  1921. */
  1922. goog.object.forEach = function(obj, f, opt_obj) {
  1923. for (var key in obj) {
  1924. f.call(opt_obj, obj[key], key, obj);
  1925. }
  1926. };
  1927. /**
  1928. * Calls a function for each element in an object/map/hash. If that call returns
  1929. * true, adds the element to a new object.
  1930. *
  1931. * @param {Object} obj The object over which to iterate.
  1932. * @param {Function} f The function to call for every element. This
  1933. * function takes 3 arguments (the element, the index and the object)
  1934. * and should return a boolean. If the return value is true the
  1935. * element is added to the result object. If it is _FALSE the
  1936. * element is not included.
  1937. * @param {Object=} opt_obj This is used as the 'this' object within f.
  1938. * @return {!Object} a new object in which only elements that passed the test
  1939. * are present.
  1940. */
  1941. goog.object.filter = function(obj, f, opt_obj) {
  1942. var res = {};
  1943. for (var key in obj) {
  1944. if (f.call(opt_obj, obj[key], key, obj)) {
  1945. res[key] = obj[key];
  1946. }
  1947. }
  1948. return res;
  1949. };
  1950. /**
  1951. * For every element in an object/map/hash calls a function and inserts the
  1952. * result into a new object.
  1953. *
  1954. * @param {Object} obj The object over which to iterate.
  1955. * @param {Function} f The function to call for every element. This function
  1956. * takes 3 arguments (the element, the index and the object)
  1957. * and should return something. The result will be inserted
  1958. * into a new object.
  1959. * @param {Object=} opt_obj This is used as the 'this' object within f.
  1960. * @return {!Object} a new object with the results from f.
  1961. */
  1962. goog.object.map = function(obj, f, opt_obj) {
  1963. var res = {};
  1964. for (var key in obj) {
  1965. res[key] = f.call(opt_obj, obj[key], key, obj);
  1966. }
  1967. return res;
  1968. };
  1969. /**
  1970. * Calls a function for each element in an object/map/hash. If
  1971. * all calls return true, returns true. If any call returns _FALSE, returns
  1972. * _FALSE at this point and does not continue to check the remaining elements.
  1973. *
  1974. * @param {Object} obj The object to check.
  1975. * @param {Function} f The function to call for every element. This function
  1976. * takes 3 arguments (the element, the index and the object) and should
  1977. * return a boolean.
  1978. * @param {Object=} opt_obj This is used as the 'this' object within f.
  1979. * @return {boolean} _FALSE if any element fails the test.
  1980. */
  1981. goog.object.every = function(obj, f, opt_obj) {
  1982. for (var key in obj) {
  1983. if (!f.call(opt_obj, obj[key], key, obj)) {
  1984. return _FALSE;
  1985. }
  1986. }
  1987. return _TRUE;
  1988. };
  1989. /**
  1990. * Returns the number of key-value pairs in the object map.
  1991. *
  1992. * @param {Object} obj The object for which to get the number of key-value
  1993. * pairs.
  1994. * @return {number} The number of key-value pairs in the object map.
  1995. */
  1996. goog.object.getCount = function(obj) {
  1997. // JS1.5 has __count__ but it has been deprecated so it raises a warning...
  1998. // in other words do not use. Also __count__ only includes the fields on the
  1999. // actual object and not in the prototype chain.
  2000. var rv = 0;
  2001. for (var key in obj) {
  2002. rv++;
  2003. }
  2004. return rv;
  2005. };
  2006. /**
  2007. * Whether the object/hash/map contains the given object as a value.
  2008. * An alias for goog.object.containsValue(obj, val).
  2009. *
  2010. * @param {Object} obj The object in which to look for val.
  2011. * @param {*} val The object for which to check.
  2012. * @return {boolean} true if val is present.
  2013. */
  2014. goog.object.contains = function(obj, val) {
  2015. return goog.object.containsValue(obj, val);
  2016. };
  2017. /**
  2018. * Returns the values of the object/map/hash.
  2019. *
  2020. * @param {Object} obj The object from which to get the values.
  2021. * @return {!Array} The values in the object/map/hash.
  2022. */
  2023. goog.object.getValues = function(obj) {
  2024. var res = [];
  2025. var i = 0;
  2026. for (var key in obj) {
  2027. res[i++] = obj[key];
  2028. }
  2029. return res;
  2030. };
  2031. /**
  2032. * Returns the keys of the object/map/hash.
  2033. *
  2034. * @param {Object} obj The object from which to get the keys.
  2035. * @return {!Array.<string>} Array of property keys.
  2036. */
  2037. goog.object.getKeys = function(obj) {
  2038. var res = [];
  2039. var i = 0;
  2040. for (var key in obj) {
  2041. res[i++] = key;
  2042. }
  2043. return res;
  2044. };
  2045. /**
  2046. * Whether the object/map/hash contains the given value. This is O(n).
  2047. *
  2048. * @param {Object} obj The object in which to look for val.
  2049. * @param {*} val The value for which to check.
  2050. * @return {boolean} true If the map contains the value.
  2051. */
  2052. goog.object.containsValue = function(obj, val) {
  2053. for (var key in obj) {
  2054. if (obj[key] == val) {
  2055. return _TRUE;
  2056. }
  2057. }
  2058. return _FALSE;
  2059. };
  2060. /**
  2061. * Whether the object/map/hash is empty.
  2062. *
  2063. * @param {Object} obj The object to test.
  2064. * @return {boolean} true if obj is empty.
  2065. */
  2066. goog.object.isEmpty = function(obj) {
  2067. for (var key in obj) {
  2068. return _FALSE;
  2069. }
  2070. return _TRUE;
  2071. };
  2072. /**
  2073. * Removes all key value pairs from the object/map/hash.
  2074. *
  2075. * @param {Object} obj The object to clear.
  2076. */
  2077. goog.object.clear = function(obj) {
  2078. for (var i in obj) {
  2079. delete obj[i];
  2080. }
  2081. };
  2082. /**
  2083. * Removes a key-value pair based on the key.
  2084. *
  2085. * @param {Object} obj The object from which to remove the key.
  2086. * @param {*} key The key to remove.
  2087. * @return {boolean} Whether an element was removed.
  2088. */
  2089. goog.object.remove = function(obj, key) {
  2090. var rv;
  2091. if ((rv = key in obj)) {
  2092. delete obj[key];
  2093. }
  2094. return rv;
  2095. };
  2096. /**
  2097. * Adds a key-value pair to the object. Throws an exception if the key is
  2098. * already in use. Use set if you want to change an existing pair.
  2099. *
  2100. * @param {Object} obj The object to which to add the key-value pair.
  2101. * @param {string} key The key to add.
  2102. * @param {*} val The value to add.
  2103. */
  2104. goog.object.add = function(obj, key, val) {
  2105. if (key in obj) {
  2106. throw Error('The object already contains the key "' + key + '"');
  2107. }
  2108. goog.object.set(obj, key, val);
  2109. };
  2110. /**
  2111. * Returns the value for the given key.
  2112. *
  2113. * @param {Object} obj The object from which to get the value.
  2114. * @param {string} key The key for which to get the value.
  2115. * @param {*=} opt_val The value to return if no item is found for the given
  2116. * key (default is undefined).
  2117. * @return {*} The value for the given key.
  2118. */
  2119. goog.object.get = function(obj, key, opt_val) {
  2120. if (key in obj) {
  2121. return obj[key];
  2122. }
  2123. return opt_val;
  2124. };
  2125. /**
  2126. * Adds a key-value pair to the object/map/hash.
  2127. *
  2128. * @param {Object} obj The object to which to add the key-value pair.
  2129. * @param {string} key The key to add.
  2130. * @param {*} value The value to add.
  2131. */
  2132. goog.object.set = function(obj, key, value) {
  2133. obj[key] = value;
  2134. };
  2135. /**
  2136. * Does a flat clone of the object.
  2137. *
  2138. * @param {Object} obj Object to clone.
  2139. * @return {!Object} Clone of the input object.
  2140. */
  2141. goog.object.clone = function(obj) {
  2142. // We cannot use the prototype trick because a lot of methods depend on where
  2143. // the actual key is set.
  2144. var res = {};
  2145. for (var key in obj) {
  2146. res[key] = obj[key];
  2147. }
  2148. return res;
  2149. // We could also use goog.mixin but I wanted this to be independent from that.
  2150. };
  2151. /**
  2152. * The names of the fields that are defined on Object.prototype.
  2153. * @type {Array.<string>}
  2154. * @private
  2155. */
  2156. goog.object.PROTOTYPE_FIELDS_ = [
  2157. 'constructor',
  2158. 'hasOwnProperty',
  2159. 'isPrototypeOf',
  2160. 'propertyIsEnumerable',
  2161. 'toLocaleString',
  2162. 'toString',
  2163. 'valueOf'
  2164. ];
  2165. /**
  2166. * Extends an object with another object.
  2167. * This operates 'in-place'; it does not create a new Object.
  2168. *
  2169. * Example:
  2170. * var o = {};
  2171. * goog.object.extend(o, {a: 0, b: 1});
  2172. * o; // {a: 0, b: 1}
  2173. * goog.object.extend(o, {c: 2});
  2174. * o; // {a: 0, b: 1, c: 2}
  2175. *
  2176. * @param {Object} target The object to modify.
  2177. * @param {...Object} var_args The objects from which values will be copied.
  2178. */
  2179. goog.object.extend = function(target, var_args) {
  2180. var key, source;
  2181. for (var i = 1; i < arguments.length; i++) {
  2182. source = arguments[i];
  2183. for (key in source) {
  2184. target[key] = source[key];
  2185. }
  2186. // For IE the for-in-loop does not contain any properties that are not
  2187. // enumerable on the prototype object (for example isPrototypeOf from
  2188. // Object.prototype) and it will also not include 'replace' on objects that
  2189. // extend String and change 'replace' (not that it is common for anyone to
  2190. // extend anything except Object).
  2191. for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {
  2192. key = goog.object.PROTOTYPE_FIELDS_[j];
  2193. if (Object.prototype.hasOwnProperty.call(source, key)) {
  2194. target[key] = source[key];
  2195. }
  2196. }
  2197. }
  2198. };
  2199. /**
  2200. * Creates a new object built from the key-value pairs provided as arguments.
  2201. * @param {...*} var_args If only one argument is provided and it is an array
  2202. * then this is used as the arguments, otherwise even arguments are used as
  2203. * the property names and odd arguments are used as the property values.
  2204. * @return {!Object} The new object.
  2205. * @throws {Error} If there are uneven number of arguments or there is only one
  2206. * non array argument.
  2207. */
  2208. goog.object.create = function(var_args) {
  2209. var argLength = arguments.length;
  2210. if (argLength == 1 && goog.isArray(arguments[0])) {
  2211. return goog.object.create.apply(_NULL, arguments[0]);
  2212. }
  2213. if (argLength % 2) {
  2214. throw Error('Uneven number of arguments');
  2215. }
  2216. var rv = {};
  2217. for (var i = 0; i < argLength; i += 2) {
  2218. rv[arguments[i]] = arguments[i + 1];
  2219. }
  2220. return rv;
  2221. };
  2222. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  2223. //
  2224. // Licensed under the Apache License, Version 2.0 (the "License");
  2225. // you may not use this file except in compliance with the License.
  2226. // You may obtain a copy of the License at
  2227. //
  2228. // http://www.apache.org/licenses/LICENSE-2.0
  2229. //
  2230. // Unless required by applicable law or agreed to in writing, software
  2231. // distributed under the License is distributed on an "AS-IS" BASIS,
  2232. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2233. // See the License for the specific language governing permissions and
  2234. // limitations under the License.
  2235. /**
  2236. * @fileoverview Defines the goog.dom.TagName enum. This enumerates
  2237. * all html tag names specified by the W3C HTML 4.01 Specification.
  2238. * Reference http://www.w3.org/TR/html401/index/elements.html.
  2239. */
  2240. goog.provide('goog.dom.TagName');
  2241. /**
  2242. * Enum of all html tag names specified by the W3C HTML 4.01 Specification.
  2243. * Reference http://www.w3.org/TR/html401/index/elements.html
  2244. * @enum {string}
  2245. */
  2246. goog.dom.TagName = {
  2247. A: 'A',
  2248. ABBR: 'ABBR',
  2249. ACRONYM: 'ACRONYM',
  2250. ADDRESS: 'ADDRESS',
  2251. APPLET: 'APPLET',
  2252. AREA: 'AREA',
  2253. B: 'B',
  2254. BASE: 'BASE',
  2255. BASEFONT: 'BASEFONT',
  2256. BDO: 'BDO',
  2257. BIG: 'BIG',
  2258. BLOCKQUOTE: 'BLOCKQUOTE',
  2259. BODY: 'BODY',
  2260. BR: 'BR',
  2261. BUTTON: 'BUTTON',
  2262. CANVAS: 'CANVAS',
  2263. CAPTION: 'CAPTION',
  2264. CENTER: 'CENTER',
  2265. CITE: 'CITE',
  2266. CODE: 'CODE',
  2267. COL: 'COL',
  2268. COLGROUP: 'COLGROUP',
  2269. DD: 'DD',
  2270. DEL: 'DEL',
  2271. DFN: 'DFN',
  2272. DIR: 'DIR',
  2273. DIV: 'DIV',
  2274. DL: 'DL',
  2275. DT: 'DT',
  2276. EM: 'EM',
  2277. FIELDSET: 'FIELDSET',
  2278. FONT: 'FONT',
  2279. FORM: 'FORM',
  2280. FRAME: 'FRAME',
  2281. FRAMESET: 'FRAMESET',
  2282. H1: 'H1',
  2283. H2: 'H2',
  2284. H3: 'H3',
  2285. H4: 'H4',
  2286. H5: 'H5',
  2287. H6: 'H6',
  2288. HEAD: 'HEAD',
  2289. HR: 'HR',
  2290. HTML: 'HTML',
  2291. I: 'I',
  2292. IFRAME: 'IFRAME',
  2293. IMG: 'IMG',
  2294. INPUT: 'INPUT',
  2295. INS: 'INS',
  2296. ISINDEX: 'ISINDEX',
  2297. KBD: 'KBD',
  2298. LABEL: 'LABEL',
  2299. LEGEND: 'LEGEND',
  2300. LI: 'LI',
  2301. LINK: 'LINK',
  2302. MAP: 'MAP',
  2303. MENU: 'MENU',
  2304. META: 'META',
  2305. NOFRAMES: 'NOFRAMES',
  2306. NOSCRIPT: 'NOSCRIPT',
  2307. OBJECT: 'OBJECT',
  2308. OL: 'OL',
  2309. OPTGROUP: 'OPTGROUP',
  2310. OPTION: 'OPTION',
  2311. P: 'P',
  2312. PARAM: 'PARAM',
  2313. PRE: 'PRE',
  2314. Q: 'Q',
  2315. S: 'S',
  2316. SAMP: 'SAMP',
  2317. SCRIPT: 'SCRIPT',
  2318. SELECT: 'SELECT',
  2319. SMALL: 'SMALL',
  2320. SPAN: 'SPAN',
  2321. STRIKE: 'STRIKE',
  2322. STRONG: 'STRONG',
  2323. STYLE: 'STYLE',
  2324. SUB: 'SUB',
  2325. SUP: 'SUP',
  2326. TABLE: 'TABLE',
  2327. TBODY: 'TBODY',
  2328. TD: 'TD',
  2329. TEXTAREA: 'TEXTAREA',
  2330. TFOOT: 'TFOOT',
  2331. TH: 'TH',
  2332. THEAD: 'THEAD',
  2333. TITLE: 'TITLE',
  2334. TR: 'TR',
  2335. TT: 'TT',
  2336. U: 'U',
  2337. UL: 'UL',
  2338. VAR: 'VAR'
  2339. };
  2340. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  2341. //
  2342. // Licensed under the Apache License, Version 2.0 (the "License");
  2343. // you may not use this file except in compliance with the License.
  2344. // You may obtain a copy of the License at
  2345. //
  2346. // http://www.apache.org/licenses/LICENSE-2.0
  2347. //
  2348. // Unless required by applicable law or agreed to in writing, software
  2349. // distributed under the License is distributed on an "AS-IS" BASIS,
  2350. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2351. // See the License for the specific language governing permissions and
  2352. // limitations under the License.
  2353. /**
  2354. * @fileoverview A utility class for representing two-dimensional sizes.
  2355. */
  2356. goog.provide('goog.math.Size');
  2357. /**
  2358. * Class for representing sizes consisting of a width and height. Undefined
  2359. * width and height support is deprecated and results in compiler warning.
  2360. * @param {number} width Width.
  2361. * @param {number} height Height.
  2362. * @constructor
  2363. */
  2364. goog.math.Size = function(width, height) {
  2365. /**
  2366. * Width
  2367. * @type {number}
  2368. */
  2369. this.width = width;
  2370. /**
  2371. * Height
  2372. * @type {number}
  2373. */
  2374. this.height = height;
  2375. };
  2376. /**
  2377. * Compares sizes for equality.
  2378. * @param {goog.math.Size} a A Size.
  2379. * @param {goog.math.Size} b A Size.
  2380. * @return {boolean} True iff the sizes have equal widths and equal
  2381. * heights, or if both are null.
  2382. */
  2383. goog.math.Size.equals = function(a, b) {
  2384. if (a == b) {
  2385. return _TRUE;
  2386. }
  2387. if (!a || !b) {
  2388. return _FALSE;
  2389. }
  2390. return a.width == b.width && a.height == b.height;
  2391. };
  2392. /**
  2393. * @return {!goog.math.Size} A new copy of the Size.
  2394. */
  2395. goog.math.Size.prototype.clone = function() {
  2396. return new goog.math.Size(this.width, this.height);
  2397. };
  2398. /**
  2399. * @return {number} The area of the size (width * height).
  2400. */
  2401. goog.math.Size.prototype.area = function() {
  2402. return this.width * this.height;
  2403. };
  2404. /**
  2405. * @return {boolean} True if the size has zero area, _FALSE if both dimensions
  2406. * are non-zero numbers.
  2407. */
  2408. goog.math.Size.prototype.isEmpty = function() {
  2409. return !this.area();
  2410. };
  2411. // Copyright 2010 The Closure Library Authors. All Rights Reserved.
  2412. //
  2413. // Licensed under the Apache License, Version 2.0 (the "License");
  2414. // you may not use this file except in compliance with the License.
  2415. // You may obtain a copy of the License at
  2416. //
  2417. // http://www.apache.org/licenses/LICENSE-2.0
  2418. //
  2419. // Unless required by applicable law or agreed to in writing, software
  2420. // distributed under the License is distributed on an "AS-IS" BASIS,
  2421. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2422. // See the License for the specific language governing permissions and
  2423. // limitations under the License.
  2424. /**
  2425. * @fileoverview Browser capability checks for the dom package.
  2426. *
  2427. */
  2428. goog.provide('goog.dom.BrowserFeature');
  2429. //goog.require('goog.userAgent');
  2430. /**
  2431. * Enum of browser capabilities.
  2432. * @enum {boolean}
  2433. */
  2434. goog.dom.BrowserFeature = {
  2435. /**
  2436. * Whether attributes 'name' and 'type' can be added to an element after it's
  2437. * created. _FALSE in Internet Explorer prior to version 9.
  2438. */
  2439. CAN_ADD_NAME_OR_TYPE_ATTRIBUTES: !goog.userAgent.IE ||
  2440. goog.userAgent.isVersion('9'),
  2441. /**
  2442. * Whether we can use element.children to access an element's Element
  2443. * children. Available since Gecko 1.9.1, IE 9. (IE<9 also includes comment
  2444. * nodes in the collection.)
  2445. */
  2446. CAN_USE_CHILDREN_ATTRIBUTE: !goog.userAgent.GECKO && !goog.userAgent.IE ||
  2447. goog.userAgent.IE && goog.userAgent.isVersion('9') ||
  2448. goog.userAgent.GECKO && goog.userAgent.isVersion('1.9.1'),
  2449. /**
  2450. * Opera, Safari 3, and Internet Explorer 9 all support innerText but they
  2451. * include text nodes in script and style tags.
  2452. */
  2453. CAN_USE_INNER_TEXT: goog.userAgent.IE && !goog.userAgent.isVersion('9'),
  2454. /**
  2455. * Whether NoScope elements need a scoped element written before them in
  2456. * innerHTML.
  2457. * MSDN: http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx#1
  2458. */
  2459. INNER_HTML_NEEDS_SCOPED_ELEMENT: goog.userAgent.IE
  2460. };
  2461. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2462. //
  2463. // Licensed under the Apache License, Version 2.0 (the "License");
  2464. // you may not use this file except in compliance with the License.
  2465. // You may obtain a copy of the License at
  2466. //
  2467. // http://www.apache.org/licenses/LICENSE-2.0
  2468. //
  2469. // Unless required by applicable law or agreed to in writing, software
  2470. // distributed under the License is distributed on an "AS-IS" BASIS,
  2471. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2472. // See the License for the specific language governing permissions and
  2473. // limitations under the License.
  2474. /**
  2475. * @fileoverview A utility class for representing two-dimensional positions.
  2476. */
  2477. goog.provide('goog.math.Coordinate');
  2478. /**
  2479. * Class for representing coordinates and positions.
  2480. * @param {number=} opt_x Left, defaults to 0.
  2481. * @param {number=} opt_y Top, defaults to 0.
  2482. * @constructor
  2483. */
  2484. goog.math.Coordinate = function(opt_x, opt_y) {
  2485. /**
  2486. * X-value
  2487. * @type {number}
  2488. */
  2489. this.x = goog.isDef(opt_x) ? opt_x : 0;
  2490. /**
  2491. * Y-value
  2492. * @type {number}
  2493. */
  2494. this.y = goog.isDef(opt_y) ? opt_y : 0;
  2495. };
  2496. /**
  2497. * Returns a new copy of the coordinate.
  2498. * @return {!goog.math.Coordinate} A clone of this coordinate.
  2499. */
  2500. goog.math.Coordinate.prototype.clone = function() {
  2501. return new goog.math.Coordinate(this.x, this.y);
  2502. };
  2503. /**
  2504. * Compares coordinates for equality.
  2505. * @param {goog.math.Coordinate} a A Coordinate.
  2506. * @param {goog.math.Coordinate} b A Coordinate.
  2507. * @return {boolean} True iff the coordinates are equal, or if both are null.
  2508. */
  2509. goog.math.Coordinate.equals = function(a, b) {
  2510. if (a == b) {
  2511. return _TRUE;
  2512. }
  2513. if (!a || !b) {
  2514. return _FALSE;
  2515. }
  2516. return a.x == b.x && a.y == b.y;
  2517. };
  2518. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2519. //
  2520. // Licensed under the Apache License, Version 2.0 (the "License");
  2521. // you may not use this file except in compliance with the License.
  2522. // You may obtain a copy of the License at
  2523. //
  2524. // http://www.apache.org/licenses/LICENSE-2.0
  2525. //
  2526. // Unless required by applicable law or agreed to in writing, software
  2527. // distributed under the License is distributed on an "AS-IS" BASIS,
  2528. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2529. // See the License for the specific language governing permissions and
  2530. // limitations under the License.
  2531. /**
  2532. * @fileoverview Utilities for manipulating the browser's Document Object Model
  2533. * Inspiration taken *heavily* from mochikit (http://mochikit.com/).
  2534. *
  2535. * You can use {@link goog.dom.DomHelper} to create new dom helpers that refer
  2536. * to a different document object. This is useful if you are working with
  2537. * frames or multiple windows.
  2538. *
  2539. */
  2540. // TODO(user): Rename/refactor getTextContent and getRawTextContent. The problem
  2541. // is that getTextContent should mimic the DOM3 textContent. We should add a
  2542. // getInnerText (or getText) which tries to return the visible text, innerText.
  2543. goog.provide('goog.dom');
  2544. goog.provide('goog.dom.DomHelper');
  2545. goog.provide('goog.dom.NodeType');
  2546. //goog.require('goog.array');
  2547. //goog.require('goog.dom.BrowserFeature');
  2548. //goog.require('goog.dom.TagName');
  2549. //goog.require('goog.dom.classes');
  2550. //goog.require('goog.math.Coordinate');
  2551. //goog.require('goog.math.Size');
  2552. //goog.require('goog.object');
  2553. //goog.require('goog.string');
  2554. //goog.require('goog.userAgent');
  2555. /**
  2556. * @define {boolean} Whether we know at compile time that the browser is in
  2557. * quirks mode.
  2558. */
  2559. goog.dom.ASSUME_QUIRKS_MODE = _FALSE;
  2560. /**
  2561. * @define {boolean} Whether we know at compile time that the browser is in
  2562. * standards compliance mode.
  2563. */
  2564. goog.dom.ASSUME_STANDARDS_MODE = _FALSE;
  2565. /**
  2566. * Whether we know the compatibility mode at compile time.
  2567. * @type {boolean}
  2568. * @private
  2569. */
  2570. goog.dom.COMPAT_MODE_KNOWN_ =
  2571. goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE;
  2572. /**
  2573. * Enumeration for DOM node types (for reference)
  2574. * @enum {number}
  2575. */
  2576. goog.dom.NodeType = {
  2577. ELEMENT: 1,
  2578. ATTRIBUTE: 2,
  2579. TEXT: 3,
  2580. CDATA_SECTION: 4,
  2581. ENTITY_REFERENCE: 5,
  2582. ENTITY: 6,
  2583. PROCESSING_INSTRUCTION: 7,
  2584. COMMENT: 8,
  2585. DOCUMENT: 9,
  2586. DOCUMENT_TYPE: 10,
  2587. DOCUMENT_FRAGMENT: 11,
  2588. NOTATION: 12
  2589. };
  2590. /**
  2591. * Gets the DomHelper object for the document where the element resides.
  2592. * @param {Node|Window=} opt_element If present, gets the DomHelper for this
  2593. * element.
  2594. * @return {!goog.dom.DomHelper} The DomHelper.
  2595. */
  2596. goog.dom.getDomHelper = function(opt_element) {
  2597. return opt_element ?
  2598. new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) :
  2599. (goog.dom.defaultDomHelper_ ||
  2600. (goog.dom.defaultDomHelper_ = new goog.dom.DomHelper()));
  2601. };
  2602. /**
  2603. * Cached default DOM helper.
  2604. * @type {goog.dom.DomHelper}
  2605. * @private
  2606. */
  2607. goog.dom.defaultDomHelper_;
  2608. /**
  2609. * Gets the document object being used by the dom library.
  2610. * @return {!Document} Document object.
  2611. */
  2612. goog.dom.getDocument = function() {
  2613. return document;
  2614. };
  2615. /**
  2616. * Alias for getElementById. If a DOM node is passed in then we just return
  2617. * that.
  2618. * @param {string|Element} element Element ID or a DOM node.
  2619. * @return {Element} The element with the given ID, or the node passed in.
  2620. */
  2621. goog.dom.getElement = function(element) {
  2622. return goog.isString(element) ?
  2623. _DOC.getElementById(element) : element;
  2624. };
  2625. /**
  2626. * Alias for getElement.
  2627. * @param {string|Element} element Element ID or a DOM node.
  2628. * @return {Element} The element with the given ID, or the node passed in.
  2629. * @deprecated Use {@link goog.dom.getElement} instead.
  2630. */
  2631. goog.dom.$ = goog.dom.getElement;
  2632. /**
  2633. * Looks up elements by both tag and class name, using browser native functions
  2634. * ({@code querySelectorAll}, {@code getElementsByTagName} or
  2635. * {@code getElementsByClassName}) where possible. This function
  2636. * is a useful, if limited, way of collecting a list of DOM elements
  2637. * with certain characteristics. {@code goog.dom.query} offers a
  2638. * more powerful and general solution which allows matching on CSS3
  2639. * selector expressions, but at increased cost in code size. If all you
  2640. * need is particular tags belonging to a single class, this function
  2641. * is fast and sleek.
  2642. *
  2643. * @see {goog.dom.query}
  2644. *
  2645. * @param {?string=} opt_tag Element tag name.
  2646. * @param {?string=} opt_class Optional class name.
  2647. * @param {Document|Element=} opt_el Optional element to look in.
  2648. * @return { {length: number} } Array-like list of elements (only a length
  2649. * property and numerical indices are guaranteed to exist).
  2650. */
  2651. goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) {
  2652. return goog.dom.getElementsByTagNameAndClass_(document, opt_tag, opt_class,
  2653. opt_el);
  2654. };
  2655. /**
  2656. * Returns an array of all the elements with the provided className.
  2657. * @see {goog.dom.query}
  2658. * @param {!string} className the name of the class to look for.
  2659. * @param {Document|Element=} opt_el Optional element to look in.
  2660. * @return { {length: number} } The items found with the class name provided.
  2661. */
  2662. goog.dom.getElementsByClass = function(className, opt_el) {
  2663. var parent = opt_el || document;
  2664. if (goog.dom.canUseQuerySelector_(parent)) {
  2665. return parent.querySelectorAll('.' + className);
  2666. } else if (parent.getElementsByClassName) {
  2667. return parent.getElementsByClassName(className);
  2668. }
  2669. return goog.dom.getElementsByTagNameAndClass_(
  2670. document, '*', className, opt_el);
  2671. };
  2672. /**
  2673. * Returns the first element with the provided className.
  2674. * @see {goog.dom.query}
  2675. * @param {!string} className the name of the class to look for.
  2676. * @param {Element|Document=} opt_el Optional element to look in.
  2677. * @return {Element} The first item with the class name provided.
  2678. */
  2679. goog.dom.getElementByClass = function(className, opt_el) {
  2680. var parent = opt_el || document;
  2681. var retVal = _NULL;
  2682. if (goog.dom.canUseQuerySelector_(parent)) {
  2683. retVal = parent.querySelector('.' + className);
  2684. } else {
  2685. retVal = goog.dom.getElementsByClass(className, opt_el)[0];
  2686. }
  2687. return retVal || _NULL;
  2688. };
  2689. /**
  2690. * Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and
  2691. * fast W3C Selectors API. However, the version of WebKit that shipped with
  2692. * Safari 3.1 and Chrome has a bug where it will not correctly match mixed-
  2693. * case class name selectors in quirks mode.
  2694. * @param {!Element|Document} parent The parent document object.
  2695. * @return {boolean} whether or not we can use parent.querySelector* APIs.
  2696. * @private
  2697. */
  2698. goog.dom.canUseQuerySelector_ = function(parent) {
  2699. return parent.querySelectorAll &&
  2700. parent.querySelector &&
  2701. (!goog.userAgent.WEBKIT || goog.dom.isCss1CompatMode_(document) ||
  2702. goog.userAgent.isVersion('528'));
  2703. };
  2704. /**
  2705. * Helper for {@code getElementsByTagNameAndClass}.
  2706. * @param {!Document} doc The document to get the elements in.
  2707. * @param {?string=} opt_tag Element tag name.
  2708. * @param {?string=} opt_class Optional class name.
  2709. * @param {Document|Element=} opt_el Optional element to look in.
  2710. * @return { {length: number} } Array-like list of elements (only a length
  2711. * property and numerical indices are guaranteed to exist).
  2712. * @private
  2713. */
  2714. goog.dom.getElementsByTagNameAndClass_ = function(doc, opt_tag, opt_class,
  2715. opt_el) {
  2716. var parent = opt_el || doc;
  2717. var tagName = (opt_tag && opt_tag != '*') ? opt_tag.toUpperCase() : '';
  2718. if (goog.dom.canUseQuerySelector_(parent) &&
  2719. (tagName || opt_class)) {
  2720. var query = tagName + (opt_class ? '.' + opt_class : '');
  2721. return parent.querySelectorAll(query);
  2722. }
  2723. // Use the native getElementsByClassName if available, under the assumption
  2724. // that even when the tag name is specified, there will be fewer elements to
  2725. // filter through when going by class than by tag name
  2726. if (opt_class && parent.getElementsByClassName) {
  2727. var els = parent.getElementsByClassName(opt_class);
  2728. if (tagName) {
  2729. var arrayLike = {};
  2730. var len = 0;
  2731. // Filter for specific tags if requested.
  2732. for (var i = 0, el; el = els[i]; i++) {
  2733. if (tagName == el.nodeName) {
  2734. arrayLike[len++] = el;
  2735. }
  2736. }
  2737. arrayLike.length = len;
  2738. return arrayLike;
  2739. } else {
  2740. return els;
  2741. }
  2742. }
  2743. var els = parent.getElementsByTagName(tagName || '*');
  2744. if (opt_class) {
  2745. var arrayLike = {};
  2746. var len = 0;
  2747. for (var i = 0, el; el = els[i]; i++) {
  2748. var className = el.className;
  2749. // Check if className has a split function since SVG className does not.
  2750. if (typeof className.split == 'function' &&
  2751. goog.array.contains(className.split(/\s+/), opt_class)) {
  2752. arrayLike[len++] = el;
  2753. }
  2754. }
  2755. arrayLike.length = len;
  2756. return arrayLike;
  2757. } else {
  2758. return els;
  2759. }
  2760. };
  2761. /**
  2762. * Alias for {@code getElementsByTagNameAndClass}.
  2763. * @param {?string=} opt_tag Element tag name.
  2764. * @param {?string=} opt_class Optional class name.
  2765. * @param {Element=} opt_el Optional element to look in.
  2766. * @return { {length: number} } Array-like list of elements (only a length
  2767. * property and numerical indices are guaranteed to exist).
  2768. * @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead.
  2769. */
  2770. goog.dom.$$ = goog.dom.getElementsByTagNameAndClass;
  2771. /**
  2772. * Sets multiple properties on a node.
  2773. * @param {Element} element DOM node to set properties on.
  2774. * @param {Object} properties Hash of property:value pairs.
  2775. */
  2776. goog.dom.setProperties = function(element, properties) {
  2777. goog.object.forEach(properties, function(val, key) {
  2778. if (key == 'style') {
  2779. element.style.cssText = val;
  2780. } else if (key == 'class') {
  2781. element.className = val;
  2782. } else if (key == 'for') {
  2783. element.htmlFor = val;
  2784. } else if (key in goog.dom.DIRECT_ATTRIBUTE_MAP_) {
  2785. element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val);
  2786. } else {
  2787. element[key] = val;
  2788. }
  2789. });
  2790. };
  2791. /**
  2792. * Map of attributes that should be set using
  2793. * element.setAttribute(key, val) instead of element[key] = val. Used
  2794. * by goog.dom.setProperties.
  2795. *
  2796. * @type {Object}
  2797. * @private
  2798. */
  2799. goog.dom.DIRECT_ATTRIBUTE_MAP_ = {
  2800. 'cellpadding': 'cellPadding',
  2801. 'cellspacing': 'cellSpacing',
  2802. 'colspan': 'colSpan',
  2803. 'rowspan': 'rowSpan',
  2804. 'valign': 'vAlign',
  2805. 'height': 'height',
  2806. 'width': 'width',
  2807. 'usemap': 'useMap',
  2808. 'frameborder': 'frameBorder',
  2809. 'maxlength': 'maxLength',
  2810. 'type': 'type'
  2811. };
  2812. /**
  2813. * Gets the dimensions of the viewport.
  2814. *
  2815. * Gecko Standards mode:
  2816. * docEl.clientWidth Width of viewport excluding scrollbar.
  2817. * win.innerWidth Width of viewport including scrollbar.
  2818. * body.clientWidth Width of body element.
  2819. *
  2820. * docEl.clientHeight Height of viewport excluding scrollbar.
  2821. * win.innerHeight Height of viewport including scrollbar.
  2822. * body.clientHeight Height of document.
  2823. *
  2824. * Gecko Backwards compatible mode:
  2825. * docEl.clientWidth Width of viewport excluding scrollbar.
  2826. * win.innerWidth Width of viewport including scrollbar.
  2827. * body.clientWidth Width of viewport excluding scrollbar.
  2828. *
  2829. * docEl.clientHeight Height of document.
  2830. * win.innerHeight Height of viewport including scrollbar.
  2831. * body.clientHeight Height of viewport excluding scrollbar.
  2832. *
  2833. * IE6/7 Standards mode:
  2834. * docEl.clientWidth Width of viewport excluding scrollbar.
  2835. * win.innerWidth Undefined.
  2836. * body.clientWidth Width of body element.
  2837. *
  2838. * docEl.clientHeight Height of viewport excluding scrollbar.
  2839. * win.innerHeight Undefined.
  2840. * body.clientHeight Height of document element.
  2841. *
  2842. * IE5 + IE6/7 Backwards compatible mode:
  2843. * docEl.clientWidth 0.
  2844. * win.innerWidth Undefined.
  2845. * body.clientWidth Width of viewport excluding scrollbar.
  2846. *
  2847. * docEl.clientHeight 0.
  2848. * win.innerHeight Undefined.
  2849. * body.clientHeight Height of viewport excluding scrollbar.
  2850. *
  2851. * Opera 9 Standards and backwards compatible mode:
  2852. * docEl.clientWidth Width of viewport excluding scrollbar.
  2853. * win.innerWidth Width of viewport including scrollbar.
  2854. * body.clientWidth Width of viewport excluding scrollbar.
  2855. *
  2856. * docEl.clientHeight Height of document.
  2857. * win.innerHeight Height of viewport including scrollbar.
  2858. * body.clientHeight Height of viewport excluding scrollbar.
  2859. *
  2860. * WebKit:
  2861. * Safari 2
  2862. * docEl.clientHeight Same as scrollHeight.
  2863. * docEl.clientWidth Same as innerWidth.
  2864. * win.innerWidth Width of viewport excluding scrollbar.
  2865. * win.innerHeight Height of the viewport including scrollbar.
  2866. * frame.innerHeight Height of the viewport exluding scrollbar.
  2867. *
  2868. * Safari 3 (tested in 522)
  2869. *
  2870. * docEl.clientWidth Width of viewport excluding scrollbar.
  2871. * docEl.clientHeight Height of viewport excluding scrollbar in strict mode.
  2872. * body.clientHeight Height of viewport excluding scrollbar in quirks mode.
  2873. *
  2874. * @param {Window=} opt_window Optional window element to test.
  2875. * @return {!goog.math.Size} Object with values 'width' and 'height'.
  2876. */
  2877. goog.dom.getViewportSize = function(opt_window) {
  2878. // TODO(user): This should not take an argument
  2879. return goog.dom.getViewportSize_(opt_window || window);
  2880. };
  2881. /**
  2882. * Helper for {@code getViewportSize}.
  2883. * @param {Window} win The window to get the view port size for.
  2884. * @return {!goog.math.Size} Object with values 'width' and 'height'.
  2885. * @private
  2886. */
  2887. goog.dom.getViewportSize_ = function(win) {
  2888. var doc = win.document;
  2889. if (goog.userAgent.WEBKIT && !goog.userAgent.isVersion('500') &&
  2890. !goog.userAgent.MOBILE) {
  2891. // TODO(user): Sometimes we get something that isn't a valid window
  2892. // object. In this case we just revert to the current window. We need to
  2893. // figure out when this happens and find a real fix for it.
  2894. // See the comments on goog.dom.getWindow.
  2895. if (typeof win.innerHeight == _UNDEFINED+'') {
  2896. win = window;
  2897. }
  2898. var innerHeight = win.innerHeight;
  2899. var scrollHeight = win.document.documentElement.scrollHeight;
  2900. if (win == win.top) {
  2901. if (scrollHeight < innerHeight) {
  2902. innerHeight -= 15; // Scrollbars are 15px wide on Mac
  2903. }
  2904. }
  2905. return new goog.math.Size(win.innerWidth, innerHeight);
  2906. }
  2907. var el = goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body;
  2908. return new goog.math.Size(el.clientWidth, el.clientHeight);
  2909. };
  2910. /**
  2911. * Gets the window object associated with the given document.
  2912. *
  2913. * @param {Document=} opt_doc Document object to get window for.
  2914. * @return {Window} The window associated with the given document.
  2915. */
  2916. goog.dom.getWindow = function(opt_doc) {
  2917. // TODO(user): This should not take an argument.
  2918. return opt_doc ? goog.dom.getWindow_(opt_doc) : window;
  2919. };
  2920. /**
  2921. * Helper for {@code getWindow}.
  2922. *
  2923. * @param {!Document} doc Document object to get window for.
  2924. * @return {!Window} The window associated with the given document.
  2925. * @private
  2926. */
  2927. goog.dom.getWindow_ = function(doc) {
  2928. return doc.parentWindow || doc.defaultView;
  2929. };
  2930. /**
  2931. * Returns a dom node with a set of attributes. This function accepts varargs
  2932. * for subsequent nodes to be added. Subsequent nodes will be added to the
  2933. * first node as childNodes.
  2934. *
  2935. * So:
  2936. * <code>createDom('div', null, createDom('p'), createDom('p'));</code>
  2937. * would return a div with two child paragraphs
  2938. *
  2939. * @param {string} tagName Tag to create.
  2940. * @param {Object|Array.<string>|string=} opt_attributes If object, then a map
  2941. * of name-value pairs for attributes. If a string, then this is the
  2942. * className of the new element. If an array, the elements will be joined
  2943. * together as the className of the new element.
  2944. * @param {...Object|string|Array|NodeList} var_args Further DOM nodes or
  2945. * strings for text nodes. If one of the var_args is an array or NodeList,i
  2946. * its elements will be added as childNodes instead.
  2947. * @return {!Element} Reference to a DOM node.
  2948. */
  2949. goog.dom.createDom = function(tagName, opt_attributes, var_args) {
  2950. return goog.dom.createDom_(document, arguments);
  2951. };
  2952. /**
  2953. * Helper for {@code createDom}.
  2954. * @param {!Document} doc The document to create the DOM in.
  2955. * @param {!Arguments} args Argument object passed from the callers. See
  2956. * {@code goog.dom.createDom} for details.
  2957. * @return {!Element} Reference to a DOM node.
  2958. * @private
  2959. */
  2960. goog.dom.createDom_ = function(doc, args) {
  2961. var tagName = args[0];
  2962. var attributes = args[1];
  2963. // Internet Explorer is dumb: http://msdn.microsoft.com/workshop/author/
  2964. // dhtml/reference/properties/name_2.asp
  2965. // Also does not allow setting of 'type' attribute on 'input' or 'button'.
  2966. if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes &&
  2967. (attributes.name || attributes.type)) {
  2968. var tagNameArr = ['<', tagName];
  2969. if (attributes.name) {
  2970. tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name),
  2971. '"');
  2972. }
  2973. if (attributes.type) {
  2974. tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type),
  2975. '"');
  2976. // Clone attributes map to remove 'type' without mutating the input.
  2977. var clone = {};
  2978. goog.object.extend(clone, attributes);
  2979. attributes = clone;
  2980. delete attributes.type;
  2981. }
  2982. tagNameArr.push('>');
  2983. tagName = tagNameArr.join('');
  2984. }
  2985. var element = doc.createElement(tagName);
  2986. if (attributes) {
  2987. if (goog.isString(attributes)) {
  2988. element.className = attributes;
  2989. } else if (goog.isArray(attributes)) {
  2990. goog.dom.classes.add.apply(_NULL, [element].concat(attributes));
  2991. } else {
  2992. goog.dom.setProperties(element, attributes);
  2993. }
  2994. }
  2995. if (args.length > 2) {
  2996. goog.dom.append_(doc, element, args, 2);
  2997. }
  2998. return element;
  2999. };
  3000. /**
  3001. * Appends a node with text or other nodes.
  3002. * @param {!Document} doc The document to create new nodes in.
  3003. * @param {!Node} parent The node to append nodes to.
  3004. * @param {!Arguments} args The values to add. See {@code goog.dom.append}.
  3005. * @param {number} startIndex The index of the array to start from.
  3006. * @private
  3007. */
  3008. goog.dom.append_ = function(doc, parent, args, startIndex) {
  3009. function childHandler(child) {
  3010. // TODO(user): More coercion, ala MochiKit?
  3011. if (child) {
  3012. parent.appendChild(goog.isString(child) ?
  3013. doc.createTextNode(child) : child);
  3014. }
  3015. }
  3016. for (var i = startIndex; i < args.length; i++) {
  3017. var arg = args[i];
  3018. // TODO(user): Fix isArrayLike to return _FALSE for a text node.
  3019. if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) {
  3020. // If the argument is a node list, not a real array, use a clone,
  3021. // because forEach can't be used to mutate a NodeList.
  3022. goog.array.forEach(goog.dom.isNodeList(arg) ?
  3023. goog.array.clone(arg) : arg,
  3024. childHandler);
  3025. } else {
  3026. childHandler(arg);
  3027. }
  3028. }
  3029. };
  3030. /**
  3031. * Alias for {@code createDom}.
  3032. * @param {string} tagName Tag to create.
  3033. * @param {string|Object=} opt_attributes If object, then a map of name-value
  3034. * pairs for attributes. If a string, then this is the className of the new
  3035. * element.
  3036. * @param {...Object|string|Array|NodeList} var_args Further DOM nodes or
  3037. * strings for text nodes. If one of the var_args is an array, its
  3038. * children will be added as childNodes instead.
  3039. * @return {!Element} Reference to a DOM node.
  3040. * @deprecated Use {@link goog.dom.createDom} instead.
  3041. */
  3042. goog.dom.$dom = goog.dom.createDom;
  3043. /**
  3044. * Creates a new element.
  3045. * @param {string} name Tag name.
  3046. * @return {!Element} The new element.
  3047. */
  3048. goog.dom.createElement = function(name) {
  3049. return _DOC.createElement(name);
  3050. };
  3051. /**
  3052. * Creates a new text node.
  3053. * @param {string} content Content.
  3054. * @return {!Text} The new text node.
  3055. */
  3056. goog.dom.createTextNode = function(content) {
  3057. return _DOC.createTextNode(content);
  3058. };
  3059. /**
  3060. * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
  3061. * mode, _FALSE otherwise.
  3062. * @param {Document} doc The document to check.
  3063. * @return {boolean} True if in CSS1-compatible mode.
  3064. * @private
  3065. */
  3066. goog.dom.isCss1CompatMode_ = function(doc) {
  3067. if (goog.dom.COMPAT_MODE_KNOWN_) {
  3068. return goog.dom.ASSUME_STANDARDS_MODE;
  3069. }
  3070. return doc.compatMode == 'CSS1Compat';
  3071. };
  3072. /**
  3073. * Determines if the given node can contain children, intended to be used for
  3074. * HTML generation.
  3075. *
  3076. * IE natively supports node.canHaveChildren but has inconsistent behavior.
  3077. * Prior to IE8 the base tag allows children and in IE9 all nodes return true
  3078. * for canHaveChildren.
  3079. *
  3080. * In practice all non-IE browsers allow you to add children to any node, but
  3081. * the behavior is inconsistent:
  3082. *
  3083. * <pre>
  3084. * var a = document.createElement('br');
  3085. * a.appendChild(document.createTextNode('foo'));
  3086. * a.appendChild(document.createTextNode('bar'));
  3087. * console.log(a.childNodes.length); // 2
  3088. * console.log(a.innerHTML); // Chrome: "", IE9: "foobar", FF3.5: "foobar"
  3089. * </pre>
  3090. *
  3091. * TODO(user): Rename shouldAllowChildren() ?
  3092. *
  3093. * @param {Node} node The node to check.
  3094. * @return {boolean} Whether the node can contain children.
  3095. */
  3096. goog.dom.canHaveChildren_OLD = function(node) {
  3097. if (node.nodeType != goog.dom.NodeType.ELEMENT) {
  3098. return _FALSE;
  3099. }
  3100. switch (node.tagName) {
  3101. case goog.dom.TagName.APPLET:
  3102. case goog.dom.TagName.AREA:
  3103. case goog.dom.TagName.BASE:
  3104. case goog.dom.TagName.BR:
  3105. case goog.dom.TagName.COL:
  3106. case goog.dom.TagName.FRAME:
  3107. case goog.dom.TagName.HR:
  3108. case goog.dom.TagName.IMG:
  3109. case goog.dom.TagName.INPUT:
  3110. case goog.dom.TagName.IFRAME:
  3111. case goog.dom.TagName.ISINDEX:
  3112. case goog.dom.TagName.LINK:
  3113. case goog.dom.TagName.NOFRAMES:
  3114. case goog.dom.TagName.NOSCRIPT:
  3115. case goog.dom.TagName.META:
  3116. case goog.dom.TagName.OBJECT:
  3117. case goog.dom.TagName.PARAM:
  3118. case goog.dom.TagName.SCRIPT:
  3119. case goog.dom.TagName.STYLE:
  3120. return _FALSE;
  3121. }
  3122. return _TRUE;
  3123. };
  3124. goog.dom.TAGS_CANT_HAVE_CHILDREN = {
  3125. APPLET: _TRUE,
  3126. AREA: _TRUE,
  3127. BASE: _TRUE,
  3128. BR: _TRUE,
  3129. COL: _TRUE,
  3130. FRAME: _TRUE,
  3131. HR: _TRUE,
  3132. IMG: _TRUE,
  3133. INPUT: _TRUE,
  3134. IFRAME: _TRUE,
  3135. ISINDEX: _TRUE,
  3136. LINK: _TRUE,
  3137. NOFRAMES: _TRUE,
  3138. NOSCRIPT: _TRUE,
  3139. META: _TRUE,
  3140. OBJECT: _TRUE,
  3141. PARAM: _TRUE,
  3142. SCRIPT: _TRUE,
  3143. STYLE: _TRUE
  3144. };
  3145. goog.dom.canHaveChildren = function(node) {
  3146. return node.nodeType == goog.dom.NodeType.ELEMENT &&
  3147. !goog.dom.TAGS_CANT_HAVE_CHILDREN[node.tagName];
  3148. };
  3149. /**
  3150. * Appends a child to a node.
  3151. * @param {Node} parent Parent.
  3152. * @param {Node} child Child.
  3153. */
  3154. goog.dom.appendChild = function(parent, child) {
  3155. parent.appendChild(child);
  3156. };
  3157. /**
  3158. * Appends a node with text or other nodes.
  3159. * @param {!Node} parent The node to append nodes to.
  3160. * @param {...goog.dom.Appendable} var_args The things to append to the node.
  3161. * If this is a Node it is appended as is.
  3162. * If this is a string then a text node is appended.
  3163. * If this is an array like object then fields 0 to length - 1 are appended.
  3164. */
  3165. goog.dom.append = function(parent, var_args) {
  3166. goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1);
  3167. };
  3168. /**
  3169. * Removes all the child nodes on a DOM node.
  3170. * @param {Node} node Node to remove children from.
  3171. */
  3172. goog.dom.removeChildren = function(node) {
  3173. // Note: Iterations over live collections can be slow, this is the fastest
  3174. // we could find. The double parenthesis are used to prevent JsCompiler and
  3175. // strict warnings.
  3176. var child;
  3177. while ((child = node.firstChild)) {
  3178. node.removeChild(child);
  3179. }
  3180. };
  3181. /**
  3182. * Inserts a new node before an existing reference node (i.e. as the previous
  3183. * sibling). If the reference node has no parent, then does nothing.
  3184. * @param {Node} newNode Node to insert.
  3185. * @param {Node} refNode Reference node to insert before.
  3186. */
  3187. goog.dom.insertSiblingBefore = function(newNode, refNode) {
  3188. if (refNode.parentNode) {
  3189. refNode.parentNode.insertBefore(newNode, refNode);
  3190. }
  3191. };
  3192. /**
  3193. * Inserts a new node after an existing reference node (i.e. as the next
  3194. * sibling). If the reference node has no parent, then does nothing.
  3195. * @param {Node} newNode Node to insert.
  3196. * @param {Node} refNode Reference node to insert after.
  3197. */
  3198. goog.dom.insertSiblingAfter = function(newNode, refNode) {
  3199. if (refNode.parentNode) {
  3200. refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
  3201. }
  3202. };
  3203. /**
  3204. * Removes a node from its parent.
  3205. * @param {Node} node The node to remove.
  3206. * @return {Node} The node removed if removed; else, null.
  3207. */
  3208. goog.dom.removeNode = function(node) {
  3209. return node && node.parentNode ? node.parentNode.removeChild(node) : _NULL;
  3210. };
  3211. /**
  3212. * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
  3213. * parent.
  3214. * @param {Node} newNode Node to insert.
  3215. * @param {Node} oldNode Node to replace.
  3216. */
  3217. goog.dom.replaceNode = function(newNode, oldNode) {
  3218. var parent = oldNode.parentNode;
  3219. if (parent) {
  3220. parent.replaceChild(newNode, oldNode);
  3221. }
  3222. };
  3223. /**
  3224. * Flattens an element. That is, removes it and replace it with its children.
  3225. * Does nothing if the element is not in the document.
  3226. * @param {Element} element The element to flatten.
  3227. * @return {Element|undefined} The original element, detached from the document
  3228. * tree, sans children; or undefined, if the element was not in the
  3229. * document to begin with.
  3230. */
  3231. goog.dom.flattenElement = function(element) {
  3232. var child, parent = element.parentNode;
  3233. if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {
  3234. // Use IE DOM method (supported by Opera too) if available
  3235. if (element.removeNode) {
  3236. return /** @type {Element} */ (element.removeNode(_FALSE));
  3237. } else {
  3238. // Move all children of the original node up one level.
  3239. while ((child = element.firstChild)) {
  3240. parent.insertBefore(child, element);
  3241. }
  3242. // Detach the original element.
  3243. return /** @type {Element} */ (goog.dom.removeNode(element));
  3244. }
  3245. }
  3246. };
  3247. /**
  3248. * Whether the object looks like a DOM node.
  3249. * @param {*} obj The object being tested for node likeness.
  3250. * @return {boolean} Whether the object looks like a DOM node.
  3251. */
  3252. goog.dom.isNodeLike = function(obj) {
  3253. return goog.isObject(obj) && obj.nodeType > 0;
  3254. };
  3255. /**
  3256. * Whether a node contains another node.
  3257. * @param {Node} parent The node that should contain the other node.
  3258. * @param {Node} descendant The node to test presence of.
  3259. * @return {boolean} Whether the parent node contains the descendent node.
  3260. */
  3261. goog.dom.contains = function(parent, descendant) {
  3262. // We use browser specific methods for this if available since it is faster
  3263. // that way.
  3264. // IE DOM
  3265. if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) {
  3266. return parent == descendant || parent.contains(descendant);
  3267. }
  3268. // W3C DOM Level 3
  3269. if (typeof parent.compareDocumentPosition != _UNDEFINED+'') {
  3270. return parent == descendant ||
  3271. Boolean(parent.compareDocumentPosition(descendant) & 16);
  3272. }
  3273. // W3C DOM Level 1
  3274. while (descendant && parent != descendant) {
  3275. descendant = descendant.parentNode;
  3276. }
  3277. return descendant == parent;
  3278. };
  3279. /**
  3280. * Compares the document order of two nodes, returning 0 if they are the same
  3281. * node, a negative number if node1 is before node2, and a positive number if
  3282. * node2 is before node1. Note that we compare the order the tags appear in the
  3283. * document so in the tree <b><i>text</i></b> the B node is considered to be
  3284. * before the I node.
  3285. *
  3286. * @param {Node} node1 The first node to compare.
  3287. * @param {Node} node2 The second node to compare.
  3288. * @return {number} 0 if the nodes are the same node, a negative number if node1
  3289. * is before node2, and a positive number if node2 is before node1.
  3290. */
  3291. goog.dom.compareNodeOrder = function(node1, node2) {
  3292. // Fall out quickly for equality.
  3293. if (node1 == node2) {
  3294. return 0;
  3295. }
  3296. // Use compareDocumentPosition where available
  3297. if (node1.compareDocumentPosition) {
  3298. // 4 is the bitmask for FOLLOWS.
  3299. return node1.compareDocumentPosition(node2) & 2 ? 1 : -1;
  3300. }
  3301. // Process in IE using sourceIndex - we check to see if the first node has
  3302. // a source index or if its parent has one.
  3303. if ('sourceIndex' in node1 ||
  3304. (node1.parentNode && 'sourceIndex' in node1.parentNode)) {
  3305. var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT;
  3306. var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT;
  3307. if (isElement1 && isElement2) {
  3308. return node1.sourceIndex - node2.sourceIndex;
  3309. } else {
  3310. var parent1 = node1.parentNode;
  3311. var parent2 = node2.parentNode;
  3312. if (parent1 == parent2) {
  3313. return goog.dom.compareSiblingOrder_(node1, node2);
  3314. }
  3315. if (!isElement1 && goog.dom.contains(parent1, node2)) {
  3316. return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2);
  3317. }
  3318. if (!isElement2 && goog.dom.contains(parent2, node1)) {
  3319. return goog.dom.compareParentsDescendantNodeIe_(node2, node1);
  3320. }
  3321. return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) -
  3322. (isElement2 ? node2.sourceIndex : parent2.sourceIndex);
  3323. }
  3324. }
  3325. // For Safari, we compare ranges.
  3326. var doc = goog.dom.getOwnerDocument(node1);
  3327. var range1, range2;
  3328. range1 = doc.createRange();
  3329. range1.selectNode(node1);
  3330. range1.collapse(_TRUE);
  3331. range2 = doc.createRange();
  3332. range2.selectNode(node2);
  3333. range2.collapse(_TRUE);
  3334. return range1.compareBoundaryPoints(goog.global['Range'].START_TO_END,
  3335. range2);
  3336. };
  3337. /**
  3338. * Utility function to compare the position of two nodes, when
  3339. * {@code textNode}'s parent is an ancestor of {@code node}. If this entry
  3340. * condition is not met, this function will attempt to reference a null object.
  3341. * @param {Node} textNode The textNode to compare.
  3342. * @param {Node} node The node to compare.
  3343. * @return {number} -1 if node is before textNode, +1 otherwise.
  3344. * @private
  3345. */
  3346. goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) {
  3347. var parent = textNode.parentNode;
  3348. if (parent == node) {
  3349. // If textNode is a child of node, then node comes first.
  3350. return -1;
  3351. }
  3352. var sibling = node;
  3353. while (sibling.parentNode != parent) {
  3354. sibling = sibling.parentNode;
  3355. }
  3356. return goog.dom.compareSiblingOrder_(sibling, textNode);
  3357. };
  3358. /**
  3359. * Utility function to compare the position of two nodes known to be non-equal
  3360. * siblings.
  3361. * @param {Node} node1 The first node to compare.
  3362. * @param {Node} node2 The second node to compare.
  3363. * @return {number} -1 if node1 is before node2, +1 otherwise.
  3364. * @private
  3365. */
  3366. goog.dom.compareSiblingOrder_ = function(node1, node2) {
  3367. var s = node2;
  3368. while ((s = s.previousSibling)) {
  3369. if (s == node1) {
  3370. // We just found node1 before node2.
  3371. return -1;
  3372. }
  3373. }
  3374. // Since we didn't find it, node1 must be after node2.
  3375. return 1;
  3376. };
  3377. /**
  3378. * Find the deepest common ancestor of the given nodes.
  3379. * @param {...Node} var_args The nodes to find a common ancestor of.
  3380. * @return {Node} The common ancestor of the nodes, or null if there is none.
  3381. * null will only be returned if two or more of the nodes are from different
  3382. * documents.
  3383. */
  3384. goog.dom.findCommonAncestor = function(var_args) {
  3385. var i, count = arguments.length;
  3386. if (!count) {
  3387. return _NULL;
  3388. } else if (count == 1) {
  3389. return arguments[0];
  3390. }
  3391. var paths = [];
  3392. var minLength = Infinity;
  3393. for (i = 0; i < count; i++) {
  3394. // Compute the list of ancestors.
  3395. var ancestors = [];
  3396. var node = arguments[i];
  3397. while (node) {
  3398. ancestors.unshift(node);
  3399. node = node.parentNode;
  3400. }
  3401. // Save the list for comparison.
  3402. paths.push(ancestors);
  3403. minLength = Math.min(minLength, ancestors.length);
  3404. }
  3405. var output = _NULL;
  3406. for (i = 0; i < minLength; i++) {
  3407. var first = paths[0][i];
  3408. for (var j = 1; j < count; j++) {
  3409. if (first != paths[j][i]) {
  3410. return output;
  3411. }
  3412. }
  3413. output = first;
  3414. }
  3415. return output;
  3416. };
  3417. /**
  3418. * Returns the owner document for a node.
  3419. * @param {Node|Window} node The node to get the document for.
  3420. * @return {!Document} The document owning the node.
  3421. */
  3422. goog.dom.getOwnerDocument = function(node) {
  3423. // TODO(user): Remove IE5 code.
  3424. // IE5 uses document instead of ownerDocument
  3425. return /** @type {!Document} */ (
  3426. node.nodeType == goog.dom.NodeType.DOCUMENT ? node :
  3427. node.ownerDocument || node.document);
  3428. };
  3429. /**
  3430. * Gets the outerHTML of a node, which islike innerHTML, except that it
  3431. * actually contains the HTML of the node itself.
  3432. * @param {Element} element The element to get the HTML of.
  3433. * @return {string} The outerHTML of the given element.
  3434. */
  3435. goog.dom.getOuterHtml = function(element) {
  3436. // IE, Opera and WebKit all have outerHTML.
  3437. if ('outerHTML' in element) {
  3438. return element.outerHTML;
  3439. } else {
  3440. var doc = goog.dom.getOwnerDocument(element);
  3441. var div = doc.createElement('div');
  3442. div.appendChild(element.cloneNode(_TRUE));
  3443. return div.innerHTML;
  3444. }
  3445. };
  3446. /**
  3447. * Map of tags whose content to ignore when calculating text length.
  3448. * @type {Object}
  3449. * @private
  3450. */
  3451. goog.dom.TAGS_TO_IGNORE_ = {
  3452. 'SCRIPT': 1,
  3453. 'STYLE': 1,
  3454. 'HEAD': 1,
  3455. 'IFRAME': 1,
  3456. 'OBJECT': 1
  3457. };
  3458. /**
  3459. * Map of tags which have predefined values with regard to whitespace.
  3460. * @type {Object}
  3461. * @private
  3462. */
  3463. goog.dom.PREDEFINED_TAG_VALUES_ = {'IMG': ' ', 'BR': '\n'};
  3464. /**
  3465. * Returns the text content of the current node, without markup and invisible
  3466. * symbols. New lines are stripped and whitespace is collapsed,
  3467. * such that each character would be visible.
  3468. *
  3469. * In browsers that support it, innerText is used. Other browsers attempt to
  3470. * simulate it via node traversal. Line breaks are canonicalized in IE.
  3471. *
  3472. * @param {Node} node The node from which we are getting content.
  3473. * @return {string} The text content.
  3474. */
  3475. goog.dom.getTextContent = function(node) {
  3476. var textContent;
  3477. // Note(user): IE9, Opera, and Safara 3 support innerText but they include
  3478. // text nodes in script tags. So we revert to use a user agent test here.
  3479. if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && ('innerText' in node)) {
  3480. textContent = goog.string.canonicalizeNewlines(node.innerText);
  3481. // Unfortunately .innerText() returns text with &shy; symbols
  3482. // We need to filter it out and then remove duplicate whitespaces
  3483. } else {
  3484. var buf = [];
  3485. goog.dom.getTextContent_(node, buf, _TRUE);
  3486. textContent = buf.join('');
  3487. }
  3488. // Strip &shy; entities. goog.format.insertWordBreaks inserts them in Opera.
  3489. textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, '');
  3490. // Strip &#8203; entities. goog.format.insertWordBreaks inserts them in IE8.
  3491. textContent = textContent.replace(/\u200B/g, '');
  3492. // Skip this replacement on IE, which automatically turns &nbsp; into ' '
  3493. // and / +/ into ' ' when reading innerText.
  3494. if (!goog.userAgent.IE) {
  3495. textContent = textContent.replace(/ +/g, ' ');
  3496. }
  3497. if (textContent != ' ') {
  3498. textContent = textContent.replace(/^\s*/, '');
  3499. }
  3500. return textContent;
  3501. };
  3502. /**
  3503. * Returns the text content of the current node, without markup.
  3504. *
  3505. * Unlike {@code getTextContent} this method does not collapse whitespaces
  3506. * or normalize lines breaks.
  3507. *
  3508. * @param {Node} node The node from which we are getting content.
  3509. * @return {string} The raw text content.
  3510. */
  3511. goog.dom.getRawTextContent = function(node) {
  3512. var buf = [];
  3513. goog.dom.getTextContent_(node, buf, _FALSE);
  3514. return buf.join('');
  3515. };
  3516. /**
  3517. * Recursive support function for text content retrieval.
  3518. *
  3519. * @param {Node} node The node from which we are getting content.
  3520. * @param {Array} buf string buffer.
  3521. * @param {boolean} normalizeWhitespace Whether to normalize whitespace.
  3522. * @private
  3523. */
  3524. goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) {
  3525. if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) {
  3526. // ignore certain tags
  3527. } else if (node.nodeType == goog.dom.NodeType.TEXT) {
  3528. if (normalizeWhitespace) {
  3529. buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, ''));
  3530. } else {
  3531. buf.push(node.nodeValue);
  3532. }
  3533. } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
  3534. buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]);
  3535. } else {
  3536. var child = node.firstChild;
  3537. while (child) {
  3538. goog.dom.getTextContent_(child, buf, normalizeWhitespace);
  3539. child = child.nextSibling;
  3540. }
  3541. }
  3542. };
  3543. /**
  3544. * Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
  3545. * the object must have a numeric length property and an item function (which
  3546. * has type 'string' on IE for some reason).
  3547. * @param {Object} val Object to test.
  3548. * @return {boolean} Whether the object is a NodeList.
  3549. */
  3550. goog.dom.isNodeList = function(val) {
  3551. // TODO(user): Now the isNodeList is part of goog.dom we can use
  3552. // goog.userAgent to make this simpler.
  3553. // A NodeList must have a length property of type 'number' on all platforms.
  3554. if (val && typeof val.length == 'number') {
  3555. // A NodeList is an object everywhere except Safari, where it's a function.
  3556. if (goog.isObject(val)) {
  3557. // A NodeList must have an item function (on non-IE platforms) or an item
  3558. // property of type 'string' (on IE).
  3559. return typeof val.item == 'function' || typeof val.item == 'string';
  3560. } else if (goog.isFunction(val)) {
  3561. // On Safari, a NodeList is a function with an item property that is also
  3562. // a function.
  3563. return typeof val.item == 'function';
  3564. }
  3565. }
  3566. // Not a NodeList.
  3567. return _FALSE;
  3568. };
  3569. /**
  3570. * Create an instance of a DOM helper with a new document object.
  3571. * @param {Document=} opt_document Document object to associate with this
  3572. * DOM helper.
  3573. * @constructor
  3574. */
  3575. goog.dom.DomHelper = function(opt_document) {
  3576. /**
  3577. * Reference to the document object to use
  3578. * @type {!Document}
  3579. * @private
  3580. */
  3581. this.document_ = opt_document || goog.global.document || document;
  3582. };
  3583. /**
  3584. * Gets the dom helper object for the document where the element resides.
  3585. * @param {Node=} opt_node If present, gets the DomHelper for this node.
  3586. * @return {!goog.dom.DomHelper} The DomHelper.
  3587. */
  3588. goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper;
  3589. /**
  3590. * Sets the document object.
  3591. * @param {!Document} document Document object.
  3592. */
  3593. goog.dom.DomHelper.prototype.setDocument = function(document) {
  3594. this.document_ = document;
  3595. };
  3596. /**
  3597. * Gets the document object being used by the dom library.
  3598. * @return {!Document} Document object.
  3599. */
  3600. goog.dom.DomHelper.prototype.getDocument = function() {
  3601. return this.document_;
  3602. };
  3603. /**
  3604. * Alias for {@code getElementById}. If a DOM node is passed in then we just
  3605. * return that.
  3606. * @param {string|Element} element Element ID or a DOM node.
  3607. * @return {Element} The element with the given ID, or the node passed in.
  3608. */
  3609. goog.dom.DomHelper.prototype.getElement = function(element) {
  3610. if (goog.isString(element)) {
  3611. return this.document_.getElementById(element);
  3612. } else {
  3613. return element;
  3614. }
  3615. };
  3616. /**
  3617. * Alias for {@code getElement}.
  3618. * @param {string|Element} element Element ID or a DOM node.
  3619. * @return {Element} The element with the given ID, or the node passed in.
  3620. * @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead.
  3621. */
  3622. goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement;
  3623. /**
  3624. * Looks up elements by both tag and class name, using browser native functions
  3625. * ({@code querySelectorAll}, {@code getElementsByTagName} or
  3626. * {@code getElementsByClassName}) where possible. The returned array is a live
  3627. * NodeList or a static list depending on the code path taken.
  3628. *
  3629. * @see goog.dom.query
  3630. *
  3631. * @param {?string=} opt_tag Element tag name or * for all tags.
  3632. * @param {?string=} opt_class Optional class name.
  3633. * @param {Document|Element=} opt_el Optional element to look in.
  3634. * @return { {length: number} } Array-like list of elements (only a length
  3635. * property and numerical indices are guaranteed to exist).
  3636. */
  3637. goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(opt_tag,
  3638. opt_class,
  3639. opt_el) {
  3640. return goog.dom.getElementsByTagNameAndClass_(this.document_, opt_tag,
  3641. opt_class, opt_el);
  3642. };
  3643. /**
  3644. * Returns an array of all the elements with the provided className.
  3645. * @see {goog.dom.query}
  3646. * @param {!string} className the name of the class to look for.
  3647. * @param {Element|Document=} opt_el Optional element to look in.
  3648. * @return { {length: number} } The items found with the class name provided.
  3649. */
  3650. goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) {
  3651. var doc = opt_el || this.document_;
  3652. return goog.dom.getElementsByClass(className, doc);
  3653. };
  3654. /**
  3655. * Returns the first element we find matching the provided class name.
  3656. * @see {goog.dom.query}
  3657. * @param {!string} className the name of the class to look for.
  3658. * @param {Element|Document=} opt_el Optional element to look in.
  3659. * @return {Element} The first item found with the class name provided.
  3660. */
  3661. goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) {
  3662. var doc = opt_el || this.document_;
  3663. return goog.dom.getElementByClass(className, doc);
  3664. };
  3665. /**
  3666. * Alias for {@code getElementsByTagNameAndClass}.
  3667. * @deprecated Use DomHelper getElementsByTagNameAndClass.
  3668. * @see goog.dom.query
  3669. *
  3670. * @param {?string=} opt_tag Element tag name.
  3671. * @param {?string=} opt_class Optional class name.
  3672. * @param {Element=} opt_el Optional element to look in.
  3673. * @return { {length: number} } Array-like list of elements (only a length
  3674. * property and numerical indices are guaranteed to exist).
  3675. */
  3676. goog.dom.DomHelper.prototype.$$ =
  3677. goog.dom.DomHelper.prototype.getElementsByTagNameAndClass;
  3678. /**
  3679. * Sets a number of properties on a node.
  3680. * @param {Element} element DOM node to set properties on.
  3681. * @param {Object} properties Hash of property:value pairs.
  3682. */
  3683. goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties;
  3684. /**
  3685. * Gets the dimensions of the viewport.
  3686. * @param {Window=} opt_window Optional window element to test. Defaults to
  3687. * the window of the Dom Helper.
  3688. * @return {!goog.math.Size} Object with values 'width' and 'height'.
  3689. */
  3690. goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) {
  3691. // TODO(user): This should not take an argument. That breaks the rule of a
  3692. // a DomHelper representing a single frame/window/document.
  3693. return goog.dom.getViewportSize(opt_window || this.getWindow());
  3694. };
  3695. /**
  3696. * Typedef for use with goog.dom.createDom and goog.dom.append.
  3697. * @typedef {Object|string|Array|NodeList}
  3698. */
  3699. goog.dom.Appendable;
  3700. /**
  3701. * Returns a dom node with a set of attributes. This function accepts varargs
  3702. * for subsequent nodes to be added. Subsequent nodes will be added to the
  3703. * first node as childNodes.
  3704. *
  3705. * So:
  3706. * <code>createDom('div', null, createDom('p'), createDom('p'));</code>
  3707. * would return a div with two child paragraphs
  3708. *
  3709. * An easy way to move all child nodes of an existing element to a new parent
  3710. * element is:
  3711. * <code>createDom('div', null, oldElement.childNodes);</code>
  3712. * which will remove all child nodes from the old element and add them as
  3713. * child nodes of the new DIV.
  3714. *
  3715. * @param {string} tagName Tag to create.
  3716. * @param {Object|string=} opt_attributes If object, then a map of name-value
  3717. * pairs for attributes. If a string, then this is the className of the new
  3718. * element.
  3719. * @param {...goog.dom.Appendable} var_args Further DOM nodes or
  3720. * strings for text nodes. If one of the var_args is an array or
  3721. * NodeList, its elements will be added as childNodes instead.
  3722. * @return {!Element} Reference to a DOM node.
  3723. */
  3724. goog.dom.DomHelper.prototype.createDom = function(tagName,
  3725. opt_attributes,
  3726. var_args) {
  3727. return goog.dom.createDom_(this.document_, arguments);
  3728. };
  3729. /**
  3730. * Alias for {@code createDom}.
  3731. * @param {string} tagName Tag to create.
  3732. * @param {Object|string=} opt_attributes If object, then a map of name-value
  3733. * pairs for attributes. If a string, then this is the className of the new
  3734. * element.
  3735. * @param {...goog.dom.Appendable} var_args Further DOM nodes or strings for
  3736. * text nodes. If one of the var_args is an array, its children will be
  3737. * added as childNodes instead.
  3738. * @return {!Element} Reference to a DOM node.
  3739. * @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead.
  3740. */
  3741. goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom;
  3742. /**
  3743. * Creates a new element.
  3744. * @param {string} name Tag name.
  3745. * @return {!Element} The new element.
  3746. */
  3747. goog.dom.DomHelper.prototype.createElement = function(name) {
  3748. return this.document_.createElement(name);
  3749. };
  3750. /**
  3751. * Creates a new text node.
  3752. * @param {string} content Content.
  3753. * @return {!Text} The new text node.
  3754. */
  3755. goog.dom.DomHelper.prototype.createTextNode = function(content) {
  3756. return this.document_.createTextNode(content);
  3757. };
  3758. /**
  3759. * Gets the window object associated with the document.
  3760. * @return {!Window} The window associated with the given document.
  3761. */
  3762. goog.dom.DomHelper.prototype.getWindow = function() {
  3763. return goog.dom.getWindow_(this.document_);
  3764. };
  3765. /**
  3766. * Appends a child to a node.
  3767. * @param {Node} parent Parent.
  3768. * @param {Node} child Child.
  3769. */
  3770. goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild;
  3771. /**
  3772. * Appends a node with text or other nodes.
  3773. * @param {!Node} parent The node to append nodes to.
  3774. * @param {...goog.dom.Appendable} var_args The things to append to the node.
  3775. * If this is a Node it is appended as is.
  3776. * If this is a string then a text node is appended.
  3777. * If this is an array like object then fields 0 to length - 1 are appended.
  3778. */
  3779. goog.dom.DomHelper.prototype.append = goog.dom.append;
  3780. /**
  3781. * Removes all the child nodes on a DOM node.
  3782. * @param {Node} node Node to remove children from.
  3783. */
  3784. goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren;
  3785. /**
  3786. * Inserts a new node before an existing reference node (i.e., as the previous
  3787. * sibling). If the reference node has no parent, then does nothing.
  3788. * @param {Node} newNode Node to insert.
  3789. * @param {Node} refNode Reference node to insert before.
  3790. */
  3791. goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore;
  3792. /**
  3793. * Inserts a new node after an existing reference node (i.e., as the next
  3794. * sibling). If the reference node has no parent, then does nothing.
  3795. * @param {Node} newNode Node to insert.
  3796. * @param {Node} refNode Reference node to insert after.
  3797. */
  3798. goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter;
  3799. /**
  3800. * Removes a node from its parent.
  3801. * @param {Node} node The node to remove.
  3802. * @return {Node} The node removed if removed; else, null.
  3803. */
  3804. goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode;
  3805. /**
  3806. * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
  3807. * parent.
  3808. * @param {Node} newNode Node to insert.
  3809. * @param {Node} oldNode Node to replace.
  3810. */
  3811. goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode;
  3812. /**
  3813. * Flattens an element. That is, removes it and replace it with its children.
  3814. * @param {Element} element The element to flatten.
  3815. * @return {Element|undefined} The original element, detached from the document
  3816. * tree, sans children, or undefined if the element was already not in the
  3817. * document.
  3818. */
  3819. goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement;
  3820. /**
  3821. * Whether the object looks like a DOM node.
  3822. * @param {*} obj The object being tested for node likeness.
  3823. * @return {boolean} Whether the object looks like a DOM node.
  3824. */
  3825. goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike;
  3826. /**
  3827. * Whether a node contains another node.
  3828. * @param {Node} parent The node that should contain the other node.
  3829. * @param {Node} descendant The node to test presence of.
  3830. * @return {boolean} Whether the parent node contains the descendent node.
  3831. */
  3832. goog.dom.DomHelper.prototype.contains = goog.dom.contains;
  3833. /**
  3834. * Returns the owner document for a node.
  3835. * @param {Node} node The node to get the document for.
  3836. * @return {!Document} The document owning the node.
  3837. */
  3838. goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument;
  3839. /**
  3840. * Returns the text contents of the current node, without markup. New lines are
  3841. * stripped and whitespace is collapsed, such that each character would be
  3842. * visible.
  3843. *
  3844. * In browsers that support it, innerText is used. Other browsers attempt to
  3845. * simulate it via node traversal. Line breaks are canonicalized in IE.
  3846. *
  3847. * @param {Node} node The node from which we are getting content.
  3848. * @return {string} The text content.
  3849. */
  3850. goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent;
  3851. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  3852. //
  3853. // Licensed under the Apache License, Version 2.0 (the "License");
  3854. // you may not use this file except in compliance with the License.
  3855. // You may obtain a copy of the License at
  3856. //
  3857. // http://www.apache.org/licenses/LICENSE-2.0
  3858. //
  3859. // Unless required by applicable law or agreed to in writing, software
  3860. // distributed under the License is distributed on an "AS-IS" BASIS,
  3861. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3862. // See the License for the specific language governing permissions and
  3863. // limitations under the License.
  3864. /**
  3865. * @fileoverview Python style iteration utilities.
  3866. */
  3867. goog.provide('goog.iter');
  3868. goog.provide('goog.iter.Iterator');
  3869. goog.provide('goog.iter.StopIteration');
  3870. //goog.require('goog.array');
  3871. // TODO(user): Add more functions from Python's itertools.
  3872. // http://docs.python.org/library/itertools.html
  3873. /**
  3874. * @typedef {goog.iter.Iterator|{length:number}|{__iterator__}}
  3875. */
  3876. goog.iter.Iterable;
  3877. // For script engines that already support iterators.
  3878. if ('StopIteration' in goog.global) {
  3879. /**
  3880. * Singleton Error object that is used to terminate iterations.
  3881. * @type {Error}
  3882. */
  3883. goog.iter.StopIteration = goog.global['StopIteration'];
  3884. } else {
  3885. /**
  3886. * Singleton Error object that is used to terminate iterations.
  3887. * @type {Error}
  3888. * @suppress {duplicate}
  3889. */
  3890. goog.iter.StopIteration = Error('StopIteration');
  3891. }
  3892. /**
  3893. * Class/interface for iterators. An iterator needs to implement a {@code next}
  3894. * method and it needs to throw a {@code goog.iter.StopIteration} when the
  3895. * iteration passes beyond the end. Iterators have no {@code hasNext} method.
  3896. * It is recommended to always use the helper functions to iterate over the
  3897. * iterator or in case you are only targeting JavaScript 1.7 for in loops.
  3898. * @constructor
  3899. */
  3900. goog.iter.Iterator = function() {};
  3901. /**
  3902. * Returns the next value of the iteration. This will throw the object
  3903. * {@see goog.iter#StopIteration} when the iteration passes the end.
  3904. * @return {*} Any object or value.
  3905. */
  3906. goog.iter.Iterator.prototype.next = function() {
  3907. throw goog.iter.StopIteration;
  3908. };
  3909. /**
  3910. * Returns the {@code Iterator} object itself. This is used to implement
  3911. * the iterator protocol in JavaScript 1.7
  3912. * @param {boolean=} opt_keys Whether to return the keys or values. Default is
  3913. * to only return the values. This is being used by the for-in loop (true)
  3914. * and the for-each-in loop (_FALSE). Even though the param gives a hint
  3915. * about what the iterator will return there is no guarantee that it will
  3916. * return the keys when true is passed.
  3917. * @return {!goog.iter.Iterator} The object itself.
  3918. */
  3919. goog.iter.Iterator.prototype.__iterator__ = function(opt_keys) {
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns an iterator that knows how to iterate over the values in the object.
  3924. * @param {goog.iter.Iterable} iterable If the object is an iterator it
  3925. * will be returned as is. If the object has a {@code __iterator__} method
  3926. * that will be called to get the value iterator. If the object is an
  3927. * array-like object we create an iterator for that.
  3928. * @return {!goog.iter.Iterator} An iterator that knows how to iterate over the
  3929. * values in {@code iterable}.
  3930. */
  3931. goog.iter.toIterator = function(iterable) {
  3932. if (iterable instanceof goog.iter.Iterator) {
  3933. return iterable;
  3934. }
  3935. if (typeof iterable.__iterator__ == 'function') {
  3936. return iterable.__iterator__(_FALSE);
  3937. }
  3938. if (goog.isArrayLike(iterable)) {
  3939. var i = 0;
  3940. var newIter = new goog.iter.Iterator;
  3941. newIter.next = function() {
  3942. while (_TRUE) {
  3943. if (i >= iterable.length) {
  3944. throw goog.iter.StopIteration;
  3945. }
  3946. // Don't include deleted elements.
  3947. if (!(i in iterable)) {
  3948. i++;
  3949. continue;
  3950. }
  3951. return iterable[i++];
  3952. }
  3953. };
  3954. return newIter;
  3955. }
  3956. // TODO(user): Should we fall back on goog.structs.getValues()?
  3957. throw Error('Not implemented');
  3958. };
  3959. /**
  3960. * Calls a function for each element in the iterator with the element of the
  3961. * iterator passed as argument.
  3962. *
  3963. * @param {goog.iter.Iterable} iterable The iterator to iterate
  3964. * over. If the iterable is an object {@code toIterator} will be called on
  3965. * it.
  3966. * @param {Function} f The function to call for every element. This function
  3967. * takes 3 arguments (the element, undefined, and the iterator) and the
  3968. * return value is irrelevant. The reason for passing undefined as the
  3969. * second argument is so that the same function can be used in
  3970. * {@see goog.array#forEach} as well as others.
  3971. * @param {Object=} opt_obj The object to be used as the value of 'this' within
  3972. * {@code f}.
  3973. */
  3974. goog.iter.forEach = function(iterable, f, opt_obj) {
  3975. if (goog.isArrayLike(iterable)) {
  3976. /** @preserveTry */
  3977. try {
  3978. goog.array.forEach((/** @type {goog.array.ArrayLike} */ iterable), f,
  3979. opt_obj);
  3980. } catch (ex) {
  3981. if (ex !== goog.iter.StopIteration) {
  3982. throw ex;
  3983. }
  3984. }
  3985. } else {
  3986. iterable = goog.iter.toIterator(iterable);
  3987. /** @preserveTry */
  3988. try {
  3989. while (_TRUE) {
  3990. f.call(opt_obj, iterable.next(), _UNDEFINED, iterable);
  3991. }
  3992. } catch (ex) {
  3993. if (ex !== goog.iter.StopIteration) {
  3994. throw ex;
  3995. }
  3996. }
  3997. }
  3998. };
  3999. /**
  4000. * Calls a function for every element in the iterator, and if the function
  4001. * returns true adds the element to a new iterator.
  4002. *
  4003. * @param {goog.iter.Iterable} iterable The iterator to iterate over.
  4004. * @param {Function} f The function to call for every element. This function
  4005. * takes 3 arguments (the element, undefined, and the iterator) and should
  4006. * return a boolean. If the return value is true the element will be
  4007. * included in the returned iteror. If it is _FALSE the element is not
  4008. * included.
  4009. * @param {Object=} opt_obj The object to be used as the value of 'this' within
  4010. * {@code f}.
  4011. * @return {!goog.iter.Iterator} A new iterator in which only elements that
  4012. * passed the test are present.
  4013. */
  4014. goog.iter.filter = function(iterable, f, opt_obj) {
  4015. iterable = goog.iter.toIterator(iterable);
  4016. var newIter = new goog.iter.Iterator;
  4017. newIter.next = function() {
  4018. while (_TRUE) {
  4019. var val = iterable.next();
  4020. if (f.call(opt_obj, val, _UNDEFINED, iterable)) {
  4021. return val;
  4022. }
  4023. }
  4024. };
  4025. return newIter;
  4026. };
  4027. /**
  4028. * Joins the values in a iterator with a delimiter.
  4029. * @param {goog.iter.Iterable} iterable The iterator to get the values from.
  4030. * @param {string} deliminator The text to put between the values.
  4031. * @return {string} The joined value string.
  4032. */
  4033. goog.iter.join = function(iterable, deliminator) {
  4034. return goog.iter.toArray(iterable).join(deliminator);
  4035. };
  4036. /**
  4037. * For every element in the iterator call a function and return a new iterator
  4038. * with that value.
  4039. *
  4040. * @param {goog.iter.Iterable} iterable The iterator to iterate over.
  4041. * @param {Function} f The function to call for every element. This function
  4042. * takes 3 arguments (the element, undefined, and the iterator) and should
  4043. * return a new value.
  4044. * @param {Object=} opt_obj The object to be used as the value of 'this' within
  4045. * {@code f}.
  4046. * @return {!goog.iter.Iterator} A new iterator that returns the results of
  4047. * applying the function to each element in the original iterator.
  4048. */
  4049. goog.iter.map = function(iterable, f, opt_obj) {
  4050. iterable = goog.iter.toIterator(iterable);
  4051. var newIter = new goog.iter.Iterator;
  4052. newIter.next = function() {
  4053. while (_TRUE) {
  4054. var val = iterable.next();
  4055. return f.call(opt_obj, val, _UNDEFINED, iterable);
  4056. }
  4057. };
  4058. return newIter;
  4059. };
  4060. /**
  4061. * Goes through the values in the iterator. Calls f for each these and if any of
  4062. * them returns true, this returns true (without checking the rest). If all
  4063. * return _FALSE this will return _FALSE.
  4064. *
  4065. * @param {goog.iter.Iterable} iterable The iterator object.
  4066. * @param {Function} f The function to call for every value. This function
  4067. * takes 3 arguments (the value, undefined, and the iterator) and should
  4068. * return a boolean.
  4069. * @param {Object=} opt_obj The object to be used as the value of 'this' within
  4070. * {@code f}.
  4071. * @return {boolean} true if any value passes the test.
  4072. */
  4073. goog.iter.some = function(iterable, f, opt_obj) {
  4074. iterable = goog.iter.toIterator(iterable);
  4075. /** @preserveTry */
  4076. try {
  4077. while (_TRUE) {
  4078. if (f.call(opt_obj, iterable.next(), _UNDEFINED, iterable)) {
  4079. return _TRUE;
  4080. }
  4081. }
  4082. } catch (ex) {
  4083. if (ex !== goog.iter.StopIteration) {
  4084. throw ex;
  4085. }
  4086. }
  4087. return _FALSE;
  4088. };
  4089. /**
  4090. * Goes through the values in the iterator. Calls f for each these and if any of
  4091. * them returns _FALSE this returns _FALSE (without checking the rest). If all
  4092. * return true this will return true.
  4093. *
  4094. * @param {goog.iter.Iterable} iterable The iterator object.
  4095. * @param {Function} f The function to call for every value. This function
  4096. * takes 3 arguments (the value, undefined, and the iterator) and should
  4097. * return a boolean.
  4098. * @param {Object=} opt_obj The object to be used as the value of 'this' within
  4099. * {@code f}.
  4100. * @return {boolean} true if every value passes the test.
  4101. */
  4102. goog.iter.every = function(iterable, f, opt_obj) {
  4103. iterable = goog.iter.toIterator(iterable);
  4104. /** @preserveTry */
  4105. try {
  4106. while (_TRUE) {
  4107. if (!f.call(opt_obj, iterable.next(), _UNDEFINED, iterable)) {
  4108. return _FALSE;
  4109. }
  4110. }
  4111. } catch (ex) {
  4112. if (ex !== goog.iter.StopIteration) {
  4113. throw ex;
  4114. }
  4115. }
  4116. return _TRUE;
  4117. };
  4118. /**
  4119. * Converts the iterator to an array
  4120. * @param {goog.iter.Iterable} iterable The iterator to convert to an array.
  4121. * @return {!Array} An array of the elements the iterator iterates over.
  4122. */
  4123. goog.iter.toArray = function(iterable) {
  4124. // Fast path for array-like.
  4125. if (goog.isArrayLike(iterable)) {
  4126. return goog.array.toArray((/** @type {!goog.array.ArrayLike} */ iterable));
  4127. }
  4128. iterable = goog.iter.toIterator(iterable);
  4129. var array = [];
  4130. goog.iter.forEach(iterable, function(val) {
  4131. array.push(val);
  4132. });
  4133. return array;
  4134. };
  4135. /**
  4136. * Iterates over 2 iterators and returns true if they contain the same sequence
  4137. * of elements and have the same length.
  4138. * @param {goog.iter.Iterable} iterable1 The first iterable object.
  4139. * @param {goog.iter.Iterable} iterable2 The second iterable object.
  4140. * @return {boolean} true if the iterators contain the same sequence of
  4141. * elements and have the same length.
  4142. */
  4143. goog.iter.equals = function(iterable1, iterable2) {
  4144. iterable1 = goog.iter.toIterator(iterable1);
  4145. iterable2 = goog.iter.toIterator(iterable2);
  4146. var b1, b2;
  4147. /** @preserveTry */
  4148. try {
  4149. while (_TRUE) {
  4150. b1 = b2 = _FALSE;
  4151. var val1 = iterable1.next();
  4152. b1 = _TRUE;
  4153. var val2 = iterable2.next();
  4154. b2 = _TRUE;
  4155. if (val1 != val2) {
  4156. return _FALSE;
  4157. }
  4158. }
  4159. } catch (ex) {
  4160. if (ex !== goog.iter.StopIteration) {
  4161. throw ex;
  4162. } else {
  4163. if (b1 && !b2) {
  4164. // iterable1 done but iterable2 is not done.
  4165. return _FALSE;
  4166. }
  4167. if (!b2) {
  4168. /** @preserveTry */
  4169. try {
  4170. // iterable2 not done?
  4171. val2 = iterable2.next();
  4172. // iterable2 not done but iterable1 is done
  4173. return _FALSE;
  4174. } catch (ex1) {
  4175. if (ex1 !== goog.iter.StopIteration) {
  4176. throw ex1;
  4177. }
  4178. // iterable2 done as well... They are equal
  4179. return _TRUE;
  4180. }
  4181. }
  4182. }
  4183. }
  4184. return _FALSE;
  4185. };
  4186. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  4187. //
  4188. // Licensed under the Apache License, Version 2.0 (the "License");
  4189. // you may not use this file except in compliance with the License.
  4190. // You may obtain a copy of the License at
  4191. //
  4192. // http://www.apache.org/licenses/LICENSE-2.0
  4193. //
  4194. // Unless required by applicable law or agreed to in writing, software
  4195. // distributed under the License is distributed on an "AS-IS" BASIS,
  4196. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4197. // See the License for the specific language governing permissions and
  4198. // limitations under the License.
  4199. /**
  4200. * @fileoverview Iterator subclass for DOM tree traversal.
  4201. *
  4202. * @author robbyw@google.com (Robby Walker)
  4203. */
  4204. goog.provide('goog.dom.TagIterator');
  4205. goog.provide('goog.dom.TagWalkType');
  4206. //goog.require('goog.dom.NodeType');
  4207. //goog.require('goog.iter.Iterator');
  4208. //goog.require('goog.iter.StopIteration');
  4209. /**
  4210. * There are three types of token:
  4211. * <ol>
  4212. * <li>{@code START_TAG} - The beginning of a tag.
  4213. * <li>{@code OTHER} - Any non-element node position.
  4214. * <li>{@code END_TAG} - The end of a tag.
  4215. * </ol>
  4216. * Users of this enumeration can rely on {@code START_TAG + END_TAG = 0} and
  4217. * that {@code OTHER = 0}.
  4218. *
  4219. * @enum {number}
  4220. */
  4221. goog.dom.TagWalkType = {
  4222. START_TAG: 1,
  4223. OTHER: 0,
  4224. END_TAG: -1
  4225. };
  4226. /**
  4227. * A DOM tree traversal iterator.
  4228. *
  4229. * Starting with the given node, the iterator walks the DOM in order, reporting
  4230. * events for the start and end of Elements, and the presence of text nodes. For
  4231. * example:
  4232. *
  4233. * <pre>
  4234. * &lt;div&gt;1&lt;span&gt;2&lt;/span&gt;3&lt;/div&gt;
  4235. * </pre>
  4236. *
  4237. * Will return the following nodes:
  4238. *
  4239. * <code>[div, 1, span, 2, span, 3, div]</code>
  4240. *
  4241. * With the following states:
  4242. *
  4243. * <code>[START, OTHER, START, OTHER, END, OTHER, END]</code>
  4244. *
  4245. * And the following depths
  4246. *
  4247. * <code>[1, 1, 2, 2, 1, 1, 0]</code>
  4248. *
  4249. * Imagining <code>|</code> represents iterator position, the traversal stops at
  4250. * each of the following locations:
  4251. *
  4252. * <pre>
  4253. * &lt;div&gt;|1|&lt;span&gt;|2|&lt;/span&gt;|3|&lt;/div&gt;|
  4254. * </pre>
  4255. *
  4256. * The iterator can also be used in reverse mode, which will return the nodes
  4257. * and states in the opposite order. The depths will be slightly different
  4258. * since, like in normal mode, the depth is computed *after* the given node.
  4259. *
  4260. * Lastly, it is possible to create an iterator that is unconstrained, meaning
  4261. * that it will continue iterating until the end of the document instead of
  4262. * until exiting the start node.
  4263. *
  4264. * @param {Node=} opt_node The start node. If unspecified or null, defaults to
  4265. * an empty iterator.
  4266. * @param {boolean=} opt_reversed Whether to traverse the tree in reverse.
  4267. * @param {boolean=} opt_unconstrained Whether the iterator is not constrained
  4268. * to the starting node and its children.
  4269. * @param {goog.dom.TagWalkType?=} opt_tagType The type of the position.
  4270. * Defaults to the start of the given node for forward iterators, and
  4271. * the end of the node for reverse iterators.
  4272. * @param {number=} opt_depth The starting tree depth.
  4273. * @constructor
  4274. * @extends {goog.iter.Iterator}
  4275. */
  4276. goog.dom.TagIterator = function(opt_node, opt_reversed,
  4277. opt_unconstrained, opt_tagType, opt_depth) {
  4278. this.reversed = !!opt_reversed;
  4279. if (opt_node) {
  4280. this.setPosition(opt_node, opt_tagType);
  4281. }
  4282. this.depth = opt_depth != _UNDEFINED ? opt_depth : this.tagType || 0;
  4283. if (this.reversed) {
  4284. this.depth *= -1;
  4285. }
  4286. this.constrained = !opt_unconstrained;
  4287. };
  4288. goog.inherits(goog.dom.TagIterator, goog.iter.Iterator);
  4289. /**
  4290. * The node this position is located on.
  4291. * @type {Node}
  4292. */
  4293. goog.dom.TagIterator.prototype.node = _NULL;
  4294. /**
  4295. * The type of this position.
  4296. * @type {goog.dom.TagWalkType}
  4297. */
  4298. goog.dom.TagIterator.prototype.tagType = goog.dom.TagWalkType.OTHER;
  4299. /**
  4300. * The tree depth of this position relative to where the iterator started. The
  4301. * depth is considered to be the tree depth just past the current node, so if an
  4302. * iterator is at position <pre>
  4303. * <div>|</div>
  4304. * </pre>
  4305. * (i.e. the node is the div and the type is START_TAG) its depth will be 1.
  4306. * @type {number}
  4307. */
  4308. goog.dom.TagIterator.prototype.depth;
  4309. /**
  4310. * Whether the node iterator is moving in reverse.
  4311. * @type {boolean}
  4312. */
  4313. goog.dom.TagIterator.prototype.reversed;
  4314. /**
  4315. * Whether the iterator is constrained to the starting node and its children.
  4316. * @type {boolean}
  4317. */
  4318. goog.dom.TagIterator.prototype.constrained;
  4319. /**
  4320. * Whether iteration has started.
  4321. * @type {boolean}
  4322. * @private
  4323. */
  4324. goog.dom.TagIterator.prototype.started_ = _FALSE;
  4325. /**
  4326. * Set the position of the iterator. Overwrite the tree node and the position
  4327. * type which can be one of the {@link goog.dom.TagWalkType} token types.
  4328. * Only overwrites the tree depth when the parameter is specified.
  4329. * @param {Node} node The node to set the position to.
  4330. * @param {goog.dom.TagWalkType?=} opt_tagType The type of the position
  4331. * Defaults to the start of the given node.
  4332. * @param {number=} opt_depth The tree depth.
  4333. */
  4334. goog.dom.TagIterator.prototype.setPosition = function(node,
  4335. opt_tagType, opt_depth) {
  4336. this.node = node;
  4337. if (node) {
  4338. if (goog.isNumber(opt_tagType)) {
  4339. this.tagType = opt_tagType;
  4340. } else {
  4341. // Auto-determine the proper type
  4342. this.tagType = this.node.nodeType != goog.dom.NodeType.ELEMENT ?
  4343. goog.dom.TagWalkType.OTHER :
  4344. this.reversed ? goog.dom.TagWalkType.END_TAG :
  4345. goog.dom.TagWalkType.START_TAG;
  4346. }
  4347. }
  4348. if (goog.isNumber(opt_depth)) {
  4349. this.depth = opt_depth;
  4350. }
  4351. };
  4352. /**
  4353. * Replace this iterator's values with values from another.
  4354. * @param {goog.dom.TagIterator} other The iterator to copy.
  4355. * @protected
  4356. */
  4357. goog.dom.TagIterator.prototype.copyFrom = function(other) {
  4358. this.node = other.node;
  4359. this.tagType = other.tagType;
  4360. this.depth = other.depth;
  4361. this.reversed = other.reversed;
  4362. this.constrained = other.constrained;
  4363. };
  4364. /**
  4365. * @return {goog.dom.TagIterator} A copy of this iterator.
  4366. */
  4367. goog.dom.TagIterator.prototype.clone = function() {
  4368. return new goog.dom.TagIterator(this.node, this.reversed,
  4369. !this.constrained, this.tagType, this.depth);
  4370. };
  4371. /**
  4372. * Skip the current tag.
  4373. */
  4374. goog.dom.TagIterator.prototype.skipTag = function() {
  4375. var check = this.reversed ? goog.dom.TagWalkType.END_TAG :
  4376. goog.dom.TagWalkType.START_TAG;
  4377. if (this.tagType == check) {
  4378. this.tagType = /** @type {goog.dom.TagWalkType} */ (check * -1);
  4379. this.depth += this.tagType * (this.reversed ? -1 : 1);
  4380. }
  4381. };
  4382. /**
  4383. * Restart the current tag.
  4384. */
  4385. goog.dom.TagIterator.prototype.restartTag = function() {
  4386. var check = this.reversed ? goog.dom.TagWalkType.START_TAG :
  4387. goog.dom.TagWalkType.END_TAG;
  4388. if (this.tagType == check) {
  4389. this.tagType = /** @type {goog.dom.TagWalkType} */ (check * -1);
  4390. this.depth += this.tagType * (this.reversed ? -1 : 1);
  4391. }
  4392. };
  4393. /**
  4394. * Move to the next position in the DOM tree.
  4395. * @return {Node} Returns the next node, or throws a goog.iter.StopIteration
  4396. * exception if the end of the iterator's range has been reached.
  4397. */
  4398. goog.dom.TagIterator.prototype.next = function() {
  4399. var node;
  4400. if (this.started_) {
  4401. if (!this.node || this.constrained && this.depth == 0) {
  4402. throw goog.iter.StopIteration;
  4403. }
  4404. node = this.node;
  4405. var startType = this.reversed ? goog.dom.TagWalkType.END_TAG :
  4406. goog.dom.TagWalkType.START_TAG;
  4407. if (this.tagType == startType) {
  4408. // If we have entered the tag, test if there are any children to move to.
  4409. var child = this.reversed ? node.lastChild : node.firstChild;
  4410. if (child) {
  4411. this.setPosition(child);
  4412. } else {
  4413. // If not, move on to exiting this tag.
  4414. this.setPosition(node,
  4415. /** @type {goog.dom.TagWalkType} */ (startType * -1));
  4416. }
  4417. } else {
  4418. var sibling = this.reversed ? node.previousSibling : node.nextSibling;
  4419. // by simonz
  4420. // <span><div></span><strong></strong></div> 인 경우에 IE에서 무한 loop가 발생한다.
  4421. // strong을 iteration하지 않고 빠져나가도록 수정을 했다.
  4422. if (sibling && node.parentNode == sibling.parentNode) {
  4423. // if (sibling) {
  4424. // Try to move to the next node.
  4425. this.setPosition(sibling);
  4426. } else {
  4427. // If no such node exists, exit our parent.
  4428. this.setPosition(node.parentNode,
  4429. /** @type {goog.dom.TagWalkType} */ (startType * -1));
  4430. }
  4431. }
  4432. this.depth += this.tagType * (this.reversed ? -1 : 1);
  4433. } else {
  4434. this.started_ = _TRUE;
  4435. }
  4436. // Check the new position for being last, and return it if it's not.
  4437. node = this.node;
  4438. if (!this.node) {
  4439. throw goog.iter.StopIteration;
  4440. }
  4441. return node;
  4442. };
  4443. /**
  4444. * @return {boolean} Whether next has ever been called on this iterator.
  4445. * @protected
  4446. */
  4447. goog.dom.TagIterator.prototype.isStarted = function() {
  4448. return this.started_;
  4449. };
  4450. /**
  4451. * @return {boolean} Whether this iterator's position is a start tag position.
  4452. */
  4453. goog.dom.TagIterator.prototype.isStartTag = function() {
  4454. return this.tagType == goog.dom.TagWalkType.START_TAG;
  4455. };
  4456. /**
  4457. * @return {boolean} Whether this iterator's position is an end tag position.
  4458. */
  4459. goog.dom.TagIterator.prototype.isEndTag = function() {
  4460. return this.tagType == goog.dom.TagWalkType.END_TAG;
  4461. };
  4462. /**
  4463. * Test if two iterators are at the same position - i.e. if the node and tagType
  4464. * is the same. This will still return true if the two iterators are moving in
  4465. * opposite directions or have different constraints.
  4466. * @param {goog.dom.TagIterator} other The iterator to compare to.
  4467. * @return {boolean} Whether the two iterators are at the same position.
  4468. */
  4469. goog.dom.TagIterator.prototype.equals = function(other) {
  4470. // Nodes must be equal, and we must either have reached the end of our tree
  4471. // or be at the same position.
  4472. return other.node == this.node && (!this.node ||
  4473. other.tagType == this.tagType);
  4474. };
  4475. /**
  4476. * Replace the current node with the list of nodes. Reset the iterator so that
  4477. * it visits the first of the nodes next.
  4478. * @param {...Object} var_args A list of nodes to replace the current node with.
  4479. * If the first argument is array-like, it will be used, otherwise all the
  4480. * arguments are assumed to be nodes.
  4481. */
  4482. goog.dom.TagIterator.prototype.splice = function(var_args) {
  4483. // Reset the iterator so that it iterates over the first replacement node in
  4484. // the arguments on the next iteration.
  4485. var node = this.node;
  4486. this.restartTag();
  4487. this.reversed = !this.reversed;
  4488. goog.dom.TagIterator.prototype.next.call(this);
  4489. this.reversed = !this.reversed;
  4490. // Replace the node with the arguments.
  4491. var arr = goog.isArrayLike(arguments[0]) ? arguments[0] : arguments;
  4492. for (var i = arr.length - 1; i >= 0; i--) {
  4493. goog.dom.insertSiblingAfter(arr[i], node);
  4494. }
  4495. goog.dom.removeNode(node);
  4496. };
  4497. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  4498. //
  4499. // Licensed under the Apache License, Version 2.0 (the "License");
  4500. // you may not use this file except in compliance with the License.
  4501. // You may obtain a copy of the License at
  4502. //
  4503. // http://www.apache.org/licenses/LICENSE-2.0
  4504. //
  4505. // Unless required by applicable law or agreed to in writing, software
  4506. // distributed under the License is distributed on an "AS-IS" BASIS,
  4507. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4508. // See the License for the specific language governing permissions and
  4509. // limitations under the License.
  4510. /**
  4511. * @fileoverview Generics method for collection-like classes and objects.
  4512. *
  4513. *
  4514. * This file contains functions to work with collections. It supports using
  4515. * Map, Set, Array and Object and other classes that implement collection-like
  4516. * methods.
  4517. */
  4518. goog.provide('goog.structs');
  4519. //goog.require('goog.array');
  4520. //goog.require('goog.object');
  4521. // We treat an object as a dictionary if it has getKeys or it is an object that
  4522. // isn't arrayLike.
  4523. /**
  4524. * Returns the number of values in the collection-like object.
  4525. * @param {Object} col The collection-like object.
  4526. * @return {number} The number of values in the collection-like object.
  4527. */
  4528. goog.structs.getCount = function(col) {
  4529. if (typeof col.getCount == 'function') {
  4530. return col.getCount();
  4531. }
  4532. if (goog.isArrayLike(col) || goog.isString(col)) {
  4533. return col.length;
  4534. }
  4535. return goog.object.getCount(col);
  4536. };
  4537. /**
  4538. * Returns the values of the collection-like object.
  4539. * @param {Object} col The collection-like object.
  4540. * @return {!Array} The values in the collection-like object.
  4541. */
  4542. goog.structs.getValues = function(col) {
  4543. if (typeof col.getValues == 'function') {
  4544. return col.getValues();
  4545. }
  4546. if (goog.isString(col)) {
  4547. return col.split('');
  4548. }
  4549. if (goog.isArrayLike(col)) {
  4550. var rv = [];
  4551. var l = col.length;
  4552. for (var i = 0; i < l; i++) {
  4553. rv.push(col[i]);
  4554. }
  4555. return rv;
  4556. }
  4557. return goog.object.getValues(col);
  4558. };
  4559. /**
  4560. * Returns the keys of the collection. Some collections have no notion of
  4561. * keys/indexes and this function will return undefined in those cases.
  4562. * @param {Object} col The collection-like object.
  4563. * @return {!Array|undefined} The keys in the collection.
  4564. */
  4565. goog.structs.getKeys = function(col) {
  4566. if (typeof col.getKeys == 'function') {
  4567. return col.getKeys();
  4568. }
  4569. // if we have getValues but no getKeys we know this is a key-less collection
  4570. if (typeof col.getValues == 'function') {
  4571. return _UNDEFINED;
  4572. }
  4573. if (goog.isArrayLike(col) || goog.isString(col)) {
  4574. var rv = [];
  4575. var l = col.length;
  4576. for (var i = 0; i < l; i++) {
  4577. rv.push(i);
  4578. }
  4579. return rv;
  4580. }
  4581. return goog.object.getKeys(col);
  4582. };
  4583. /**
  4584. * Whether the collection contains the given value. This is O(n) and uses
  4585. * equals (==) to test the existence.
  4586. * @param {Object} col The collection-like object.
  4587. * @param {*} val The value to check for.
  4588. * @return {boolean} True if the map contains the value.
  4589. */
  4590. goog.structs.contains = function(col, val) {
  4591. if (typeof col.contains == 'function') {
  4592. return col.contains(val);
  4593. }
  4594. if (typeof col.containsValue == 'function') {
  4595. return col.containsValue(val);
  4596. }
  4597. if (goog.isArrayLike(col) || goog.isString(col)) {
  4598. return goog.array.contains(/** @type {Array} */ (col), val);
  4599. }
  4600. return goog.object.containsValue(col, val);
  4601. };
  4602. /**
  4603. * Whether the collection is empty.
  4604. * @param {Object} col The collection-like object.
  4605. * @return {boolean} True if empty.
  4606. */
  4607. goog.structs.isEmpty = function(col) {
  4608. if (typeof col.isEmpty == 'function') {
  4609. return col.isEmpty();
  4610. }
  4611. // We do not use goog.string.isEmpty because here we treat the string as
  4612. // collection and as such even whitespace matters
  4613. if (goog.isArrayLike(col) || goog.isString(col)) {
  4614. return goog.array.isEmpty(/** @type {Array} */ (col));
  4615. }
  4616. return goog.object.isEmpty(col);
  4617. };
  4618. /**
  4619. * Removes all the elements from the collection.
  4620. * @param {Object} col The collection-like object.
  4621. */
  4622. goog.structs.clear = function(col) {
  4623. // NOTE(user): This should not contain strings because strings are immutable
  4624. if (typeof col.clear == 'function') {
  4625. col.clear();
  4626. } else if (goog.isArrayLike(col)) {
  4627. goog.array.clear((/** @type {goog.array.ArrayLike} */ col));
  4628. } else {
  4629. goog.object.clear(col);
  4630. }
  4631. };
  4632. /**
  4633. * Calls a function for each value in a collection. The function takes
  4634. * three arguments; the value, the key and the collection.
  4635. *
  4636. * @param {Object} col The collection-like object.
  4637. * @param {Function} f The function to call for every value. This function takes
  4638. * 3 arguments (the value, the key or undefined if the collection has no
  4639. * notion of keys, and the collection) and the return value is irrelevant.
  4640. * @param {Object=} opt_obj The object to be used as the value of 'this'
  4641. * within {@code f}.
  4642. */
  4643. goog.structs.forEach = function(col, f, opt_obj) {
  4644. if (typeof col.forEach == 'function') {
  4645. col.forEach(f, opt_obj);
  4646. } else if (goog.isArrayLike(col) || goog.isString(col)) {
  4647. goog.array.forEach(/** @type {Array} */ (col), f, opt_obj);
  4648. } else {
  4649. var keys = goog.structs.getKeys(col);
  4650. var values = goog.structs.getValues(col);
  4651. var l = values.length;
  4652. for (var i = 0; i < l; i++) {
  4653. f.call(opt_obj, values[i], keys && keys[i], col);
  4654. }
  4655. }
  4656. };
  4657. /**
  4658. * Calls a function for every value in the collection. When a call returns true,
  4659. * adds the value to a new collection (Array is returned by default).
  4660. *
  4661. * @param {Object} col The collection-like object.
  4662. * @param {Function} f The function to call for every value. This function takes
  4663. * 3 arguments (the value, the key or undefined if the collection has no
  4664. * notion of keys, and the collection) and should return a Boolean. If the
  4665. * return value is true the value is added to the result collection. If it
  4666. * is _FALSE the value is not included.
  4667. * @param {Object=} opt_obj The object to be used as the value of 'this'
  4668. * within {@code f}.
  4669. * @return {!Object|!Array} A new collection where the passed values are
  4670. * present. If col is a key-less collection an array is returned. If col
  4671. * has keys and values a plain old JS object is returned.
  4672. */
  4673. goog.structs.filter = function(col, f, opt_obj) {
  4674. if (typeof col.filter == 'function') {
  4675. return col.filter(f, opt_obj);
  4676. }
  4677. if (goog.isArrayLike(col) || goog.isString(col)) {
  4678. return goog.array.filter(/** @type {!Array} */ (col), f, opt_obj);
  4679. }
  4680. var rv;
  4681. var keys = goog.structs.getKeys(col);
  4682. var values = goog.structs.getValues(col);
  4683. var l = values.length;
  4684. if (keys) {
  4685. rv = {};
  4686. for (var i = 0; i < l; i++) {
  4687. if (f.call(opt_obj, values[i], keys[i], col)) {
  4688. rv[keys[i]] = values[i];
  4689. }
  4690. }
  4691. } else {
  4692. // We should not use goog.array.filter here since we want to make sure that
  4693. // the index is undefined as well as make sure that col is passed to the
  4694. // function.
  4695. rv = [];
  4696. for (var i = 0; i < l; i++) {
  4697. if (f.call(opt_obj, values[i], _UNDEFINED, col)) {
  4698. rv.push(values[i]);
  4699. }
  4700. }
  4701. }
  4702. return rv;
  4703. };
  4704. /**
  4705. * Calls a function for every value in the collection and adds the result into a
  4706. * new collection (defaults to creating a new Array).
  4707. *
  4708. * @param {Object} col The collection-like object.
  4709. * @param {Function} f The function to call for every value. This function
  4710. * takes 3 arguments (the value, the key or undefined if the collection has
  4711. * no notion of keys, and the collection) and should return something. The
  4712. * result will be used as the value in the new collection.
  4713. * @param {Object=} opt_obj The object to be used as the value of 'this'
  4714. * within {@code f}.
  4715. * @return {!Object|!Array} A new collection with the new values. If col is a
  4716. * key-less collection an array is returned. If col has keys and values a
  4717. * plain old JS object is returned.
  4718. */
  4719. goog.structs.map = function(col, f, opt_obj) {
  4720. if (typeof col.map == 'function') {
  4721. return col.map(f, opt_obj);
  4722. }
  4723. if (goog.isArrayLike(col) || goog.isString(col)) {
  4724. return goog.array.map(/** @type {!Array} */ (col), f, opt_obj);
  4725. }
  4726. var rv;
  4727. var keys = goog.structs.getKeys(col);
  4728. var values = goog.structs.getValues(col);
  4729. var l = values.length;
  4730. if (keys) {
  4731. rv = {};
  4732. for (var i = 0; i < l; i++) {
  4733. rv[keys[i]] = f.call(opt_obj, values[i], keys[i], col);
  4734. }
  4735. } else {
  4736. // We should not use goog.array.map here since we want to make sure that
  4737. // the index is undefined as well as make sure that col is passed to the
  4738. // function.
  4739. rv = [];
  4740. for (var i = 0; i < l; i++) {
  4741. rv[i] = f.call(opt_obj, values[i], _UNDEFINED, col);
  4742. }
  4743. }
  4744. return rv;
  4745. };
  4746. /**
  4747. * Calls f for each value in a collection. If any call returns true this returns
  4748. * true (without checking the rest). If all returns _FALSE this returns _FALSE.
  4749. *
  4750. * @param {Object|Array|string} col The collection-like object.
  4751. * @param {Function} f The function to call for every value. This function takes
  4752. * 3 arguments (the value, the key or undefined if the collection has no
  4753. * notion of keys, and the collection) and should return a Boolean.
  4754. * @param {Object=} opt_obj The object to be used as the value of 'this'
  4755. * within {@code f}.
  4756. * @return {boolean} True if any value passes the test.
  4757. */
  4758. goog.structs.some = function(col, f, opt_obj) {
  4759. if (typeof col.some == 'function') {
  4760. return col.some(f, opt_obj);
  4761. }
  4762. if (goog.isArrayLike(col) || goog.isString(col)) {
  4763. return goog.array.some(/** @type {!Array} */ (col), f, opt_obj);
  4764. }
  4765. var keys = goog.structs.getKeys(col);
  4766. var values = goog.structs.getValues(col);
  4767. var l = values.length;
  4768. for (var i = 0; i < l; i++) {
  4769. if (f.call(opt_obj, values[i], keys && keys[i], col)) {
  4770. return _TRUE;
  4771. }
  4772. }
  4773. return _FALSE;
  4774. };
  4775. /**
  4776. * Calls f for each value in a collection. If all calls return true this return
  4777. * true this returns true. If any returns _FALSE this returns _FALSE at this point
  4778. * and does not continue to check the remaining values.
  4779. *
  4780. * @param {Object} col The collection-like object.
  4781. * @param {Function} f The function to call for every value. This function takes
  4782. * 3 arguments (the value, the key or undefined if the collection has no
  4783. * notion of keys, and the collection) and should return a Boolean.
  4784. * @param {Object=} opt_obj The object to be used as the value of 'this'
  4785. * within {@code f}.
  4786. * @return {boolean} True if all key-value pairs pass the test.
  4787. */
  4788. goog.structs.every = function(col, f, opt_obj) {
  4789. if (typeof col.every == 'function') {
  4790. return col.every(f, opt_obj);
  4791. }
  4792. if (goog.isArrayLike(col) || goog.isString(col)) {
  4793. return goog.array.every(/** @type {!Array} */ (col), f, opt_obj);
  4794. }
  4795. var keys = goog.structs.getKeys(col);
  4796. var values = goog.structs.getValues(col);
  4797. var l = values.length;
  4798. for (var i = 0; i < l; i++) {
  4799. if (!f.call(opt_obj, values[i], keys && keys[i], col)) {
  4800. return _FALSE;
  4801. }
  4802. }
  4803. return _TRUE;
  4804. };
  4805. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  4806. //
  4807. // Licensed under the Apache License, Version 2.0 (the "License");
  4808. // you may not use this file except in compliance with the License.
  4809. // You may obtain a copy of the License at
  4810. //
  4811. // http://www.apache.org/licenses/LICENSE-2.0
  4812. //
  4813. // Unless required by applicable law or agreed to in writing, software
  4814. // distributed under the License is distributed on an "AS-IS" BASIS,
  4815. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4816. // See the License for the specific language governing permissions and
  4817. // limitations under the License.
  4818. /**
  4819. * @fileoverview Datastructure: Hash Map.
  4820. *
  4821. *
  4822. * This file contains an implementation of a Map structure. It implements a lot
  4823. * of the methods used in goog.structs so those functions work on hashes. For
  4824. * convenience with common usage the methods accept any type for the key, though
  4825. * internally they will be cast to strings.
  4826. */
  4827. goog.provide('goog.structs.Map');
  4828. //goog.require('goog.iter.Iterator');
  4829. //goog.require('goog.iter.StopIteration');
  4830. //goog.require('goog.object');
  4831. //goog.require('goog.structs');
  4832. /**
  4833. * Class for Hash Map datastructure.
  4834. * @param {*=} opt_map Map or Object to initialize the map with.
  4835. * @param {...*} var_args If 2 or more arguments are present then they
  4836. * will be used as key-value pairs.
  4837. * @constructor
  4838. */
  4839. goog.structs.Map = function(opt_map, var_args) {
  4840. /**
  4841. * Underlying JS object used to implement the map.
  4842. * @type {!Object}
  4843. * @private
  4844. */
  4845. this.map_ = {};
  4846. /**
  4847. * An array of keys. This is necessary for two reasons:
  4848. * 1. Iterating the keys using for (var key in this.map_) allocates an
  4849. * object for every key in IE which is really bad for IE6 GC perf.
  4850. * 2. Without a side data structure, we would need to escape all the keys
  4851. * as that would be the only way we could tell during iteration if the
  4852. * key was an internal key or a property of the object.
  4853. *
  4854. * This array can contain deleted keys so it's necessary to check the map
  4855. * as well to see if the key is still in the map (this doesn't require a
  4856. * memory allocation in IE).
  4857. * @type {!Array.<string>}
  4858. * @private
  4859. */
  4860. this.keys_ = [];
  4861. var argLength = arguments.length;
  4862. if (argLength > 1) {
  4863. if (argLength % 2) {
  4864. throw Error('Uneven number of arguments');
  4865. }
  4866. for (var i = 0; i < argLength; i += 2) {
  4867. this.set(arguments[i], arguments[i + 1]);
  4868. }
  4869. } else if (opt_map) {
  4870. this.addAll(/** @type {Object} */ (opt_map));
  4871. }
  4872. };
  4873. /**
  4874. * The number of key value pairs in the map.
  4875. * @private
  4876. * @type {number}
  4877. */
  4878. goog.structs.Map.prototype.count_ = 0;
  4879. /**
  4880. * Version used to detect changes while iterating.
  4881. * @private
  4882. * @type {number}
  4883. */
  4884. goog.structs.Map.prototype.version_ = 0;
  4885. /**
  4886. * @return {number} The number of key-value pairs in the map.
  4887. */
  4888. goog.structs.Map.prototype.getCount = function() {
  4889. return this.count_;
  4890. };
  4891. /**
  4892. * Returns the values of the map.
  4893. * @return {!Array} The values in the map.
  4894. */
  4895. goog.structs.Map.prototype.getValues = function() {
  4896. this.cleanupKeysArray_();
  4897. var rv = [];
  4898. for (var i = 0; i < this.keys_.length; i++) {
  4899. var key = this.keys_[i];
  4900. rv.push(this.map_[key]);
  4901. }
  4902. return rv;
  4903. };
  4904. /**
  4905. * Returns the keys of the map.
  4906. * @return {!Array.<string>} Array of string values.
  4907. */
  4908. goog.structs.Map.prototype.getKeys = function() {
  4909. this.cleanupKeysArray_();
  4910. return /** @type {!Array.<string>} */ (this.keys_.concat());
  4911. };
  4912. /**
  4913. * Whether the map contains the given key.
  4914. * @param {*} key The key to check for.
  4915. * @return {boolean} Whether the map contains the key.
  4916. */
  4917. goog.structs.Map.prototype.containsKey = function(key) {
  4918. return goog.structs.Map.hasKey_(this.map_, key);
  4919. };
  4920. /**
  4921. * Whether the map contains the given value. This is O(n).
  4922. * @param {*} val The value to check for.
  4923. * @return {boolean} Whether the map contains the value.
  4924. */
  4925. goog.structs.Map.prototype.containsValue = function(val) {
  4926. for (var i = 0; i < this.keys_.length; i++) {
  4927. var key = this.keys_[i];
  4928. if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) {
  4929. return _TRUE;
  4930. }
  4931. }
  4932. return _FALSE;
  4933. };
  4934. /**
  4935. * Whether this map is equal to the argument map.
  4936. * @param {goog.structs.Map} otherMap The map against which to test equality.
  4937. * @param {function(*, *) : boolean=} opt_equalityFn Optional equality function
  4938. * to test equality of values. If not specified, this will test whether
  4939. * the values contained in each map are identical objects.
  4940. * @return {boolean} Whether the maps are equal.
  4941. */
  4942. goog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) {
  4943. if (this === otherMap) {
  4944. return _TRUE;
  4945. }
  4946. if (this.count_ != otherMap.getCount()) {
  4947. return _FALSE;
  4948. }
  4949. var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals;
  4950. this.cleanupKeysArray_();
  4951. for (var key, i = 0; key = this.keys_[i]; i++) {
  4952. if (!equalityFn(this.get(key), otherMap.get(key))) {
  4953. return _FALSE;
  4954. }
  4955. }
  4956. return _TRUE;
  4957. };
  4958. /**
  4959. * Default equality test for values.
  4960. * @param {*} a The first value.
  4961. * @param {*} b The second value.
  4962. * @return {boolean} Whether a and b reference the same object.
  4963. */
  4964. goog.structs.Map.defaultEquals = function(a, b) {
  4965. return a === b;
  4966. };
  4967. /**
  4968. * @return {boolean} Whether the map is empty.
  4969. */
  4970. goog.structs.Map.prototype.isEmpty = function() {
  4971. return this.count_ == 0;
  4972. };
  4973. /**
  4974. * Removes all key-value pairs from the map.
  4975. */
  4976. goog.structs.Map.prototype.clear = function() {
  4977. this.map_ = {};
  4978. this.keys_.length = 0;
  4979. this.count_ = 0;
  4980. this.version_ = 0;
  4981. };
  4982. /**
  4983. * Removes a key-value pair based on the key. This is O(logN) amortized due to
  4984. * updating the keys array whenever the count becomes half the size of the keys
  4985. * in the keys array.
  4986. * @param {*} key The key to remove.
  4987. * @return {boolean} Whether object was removed.
  4988. */
  4989. goog.structs.Map.prototype.remove = function(key) {
  4990. if (goog.structs.Map.hasKey_(this.map_, key)) {
  4991. delete this.map_[key];
  4992. this.count_--;
  4993. this.version_++;
  4994. // clean up the keys array if the threshhold is hit
  4995. if (this.keys_.length > 2 * this.count_) {
  4996. this.cleanupKeysArray_();
  4997. }
  4998. return _TRUE;
  4999. }
  5000. return _FALSE;
  5001. };
  5002. /**
  5003. * Cleans up the temp keys array by removing entries that are no longer in the
  5004. * map.
  5005. * @private
  5006. */
  5007. goog.structs.Map.prototype.cleanupKeysArray_ = function() {
  5008. if (this.count_ != this.keys_.length) {
  5009. // First remove keys that are no longer in the map.
  5010. var srcIndex = 0;
  5011. var destIndex = 0;
  5012. while (srcIndex < this.keys_.length) {
  5013. var key = this.keys_[srcIndex];
  5014. if (goog.structs.Map.hasKey_(this.map_, key)) {
  5015. this.keys_[destIndex++] = key;
  5016. }
  5017. srcIndex++;
  5018. }
  5019. this.keys_.length = destIndex;
  5020. }
  5021. if (this.count_ != this.keys_.length) {
  5022. // If the count still isn't correct, that means we have duplicates. This can
  5023. // happen when the same key is added and removed multiple times. Now we have
  5024. // to allocate one extra Object to remove the duplicates. This could have
  5025. // been done in the first pass, but in the common case, we can avoid
  5026. // allocating an extra object by only doing this when necessary.
  5027. var seen = {};
  5028. var srcIndex = 0;
  5029. var destIndex = 0;
  5030. while (srcIndex < this.keys_.length) {
  5031. var key = this.keys_[srcIndex];
  5032. if (!(goog.structs.Map.hasKey_(seen, key))) {
  5033. this.keys_[destIndex++] = key;
  5034. seen[key] = 1;
  5035. }
  5036. srcIndex++;
  5037. }
  5038. this.keys_.length = destIndex;
  5039. }
  5040. };
  5041. /**
  5042. * Returns the value for the given key. If the key is not found and the default
  5043. * value is not given this will return {@code undefined}.
  5044. * @param {*} key The key to get the value for.
  5045. * @param {*=} opt_val The value to return if no item is found for the given
  5046. * key, defaults to undefined.
  5047. * @return {*} The value for the given key.
  5048. */
  5049. goog.structs.Map.prototype.get = function(key, opt_val) {
  5050. if (goog.structs.Map.hasKey_(this.map_, key)) {
  5051. return this.map_[key];
  5052. }
  5053. return opt_val;
  5054. };
  5055. /**
  5056. * Adds a key-value pair to the map.
  5057. * @param {*} key The key.
  5058. * @param {*} value The value to add.
  5059. */
  5060. goog.structs.Map.prototype.set = function(key, value) {
  5061. if (!(goog.structs.Map.hasKey_(this.map_, key))) {
  5062. this.count_++;
  5063. this.keys_.push(key);
  5064. // Only change the version if we add a new key.
  5065. this.version_++;
  5066. }
  5067. this.map_[key] = value;
  5068. };
  5069. /**
  5070. * Adds multiple key-value pairs from another goog.structs.Map or Object.
  5071. * @param {Object} map Object containing the data to add.
  5072. */
  5073. goog.structs.Map.prototype.addAll = function(map) {
  5074. var keys, values;
  5075. if (map instanceof goog.structs.Map) {
  5076. keys = map.getKeys();
  5077. values = map.getValues();
  5078. } else {
  5079. keys = goog.object.getKeys(map);
  5080. values = goog.object.getValues(map);
  5081. }
  5082. // we could use goog.array.forEach here but I don't want to introduce that
  5083. // dependency just for this.
  5084. for (var i = 0; i < keys.length; i++) {
  5085. this.set(keys[i], values[i]);
  5086. }
  5087. };
  5088. /**
  5089. * Clones a map and returns a new map.
  5090. * @return {!goog.structs.Map} A new map with the same key-value pairs.
  5091. */
  5092. goog.structs.Map.prototype.clone = function() {
  5093. return new goog.structs.Map(this);
  5094. };
  5095. /**
  5096. * @return {!Object} Object representation of the map.
  5097. */
  5098. goog.structs.Map.prototype.toObject = function() {
  5099. this.cleanupKeysArray_();
  5100. var obj = {};
  5101. for (var i = 0; i < this.keys_.length; i++) {
  5102. var key = this.keys_[i];
  5103. obj[key] = this.map_[key];
  5104. }
  5105. return obj;
  5106. };
  5107. /**
  5108. * Returns an iterator that iterates over the values or the keys in the map.
  5109. * This throws an exception if the map was mutated since the iterator was
  5110. * created.
  5111. * @param {boolean=} opt_keys True to iterate over the keys. _FALSE to iterate
  5112. * over the values. The default value is _FALSE.
  5113. * @return {!goog.iter.Iterator} An iterator over the values or keys in the map.
  5114. */
  5115. goog.structs.Map.prototype.__iterator__ = function(opt_keys) {
  5116. // Clean up keys to minimize the risk of iterating over dead keys.
  5117. this.cleanupKeysArray_();
  5118. var i = 0;
  5119. var keys = this.keys_;
  5120. var map = this.map_;
  5121. var version = this.version_;
  5122. var selfObj = this;
  5123. var newIter = new goog.iter.Iterator;
  5124. newIter.next = function() {
  5125. while (_TRUE) {
  5126. if (version != selfObj.version_) {
  5127. throw Error('The map has changed since the iterator was created');
  5128. }
  5129. if (i >= keys.length) {
  5130. throw goog.iter.StopIteration;
  5131. }
  5132. var key = keys[i++];
  5133. return opt_keys ? key : map[key];
  5134. }
  5135. };
  5136. return newIter;
  5137. };
  5138. /**
  5139. * Safe way to test for hasOwnProperty. It even allows testing for
  5140. * 'hasOwnProperty'.
  5141. * @param {Object} obj The object to test for presence of the given key.
  5142. * @param {*} key The key to check for.
  5143. * @return {boolean} Whether the object has the key.
  5144. * @private
  5145. */
  5146. goog.structs.Map.hasKey_ = function(obj, key) {
  5147. return Object.prototype.hasOwnProperty.call(obj, key);
  5148. };
  5149. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  5150. //
  5151. // Licensed under the Apache License, Version 2.0 (the "License");
  5152. // you may not use this file except in compliance with the License.
  5153. // You may obtain a copy of the License at
  5154. //
  5155. // http://www.apache.org/licenses/LICENSE-2.0
  5156. //
  5157. // Unless required by applicable law or agreed to in writing, software
  5158. // distributed under the License is distributed on an "AS-IS" BASIS,
  5159. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5160. // See the License for the specific language governing permissions and
  5161. // limitations under the License.
  5162. /**
  5163. * @fileoverview Datastructure: Set.
  5164. *
  5165. *
  5166. * This class implements a set data structure. Adding and removing is O(1). It
  5167. * supports both object and primitive values. Be careful because you can add
  5168. * both 1 and new Number(1), because these are not the same. You can even add
  5169. * multiple new Number(1) because these are not equal.
  5170. */
  5171. goog.provide('goog.structs.Set');
  5172. //goog.require('goog.structs');
  5173. //goog.require('goog.structs.Map');
  5174. /**
  5175. * A set that can contain both primitives and objects. Adding and removing
  5176. * elements is O(1). Primitives are treated as identical if they have the same
  5177. * type and convert to the same string. Objects are treated as identical only
  5178. * if they are references to the same object. WARNING: A goog.structs.Set can
  5179. * contain both 1 and (new Number(1)), because they are not the same. WARNING:
  5180. * Adding (new Number(1)) twice will yield two distinct elements, because they
  5181. * are two different objects. WARNING: Any object that is added to a
  5182. * goog.structs.Set will be modified! Because goog.getUid() is used to
  5183. * identify objects, every object in the set will be mutated.
  5184. * @param {Array|Object=} opt_values Initial values to start with.
  5185. * @constructor
  5186. */
  5187. goog.structs.Set = function(opt_values) {
  5188. this.map_ = new goog.structs.Map;
  5189. if (opt_values) {
  5190. this.addAll(opt_values);
  5191. }
  5192. };
  5193. /**
  5194. * Obtains a unique key for an element of the set. Primitives will yield the
  5195. * same key if they have the same type and convert to the same string. Object
  5196. * references will yield the same key only if they refer to the same object.
  5197. * @param {*} val Object or primitive value to get a key for.
  5198. * @return {string} A unique key for this value/object.
  5199. * @private
  5200. */
  5201. goog.structs.Set.getKey_ = function(val) {
  5202. var type = typeof val;
  5203. if (type == 'object' && val || type == 'function') {
  5204. return 'o' + goog.getUid(/** @type {Object} */ (val));
  5205. } else {
  5206. return type.substr(0, 1) + val;
  5207. }
  5208. };
  5209. /**
  5210. * @return {number} The number of elements in the set.
  5211. */
  5212. goog.structs.Set.prototype.getCount = function() {
  5213. return this.map_.getCount();
  5214. };
  5215. /**
  5216. * Add a primitive or an object to the set.
  5217. * @param {*} element The primitive or object to add.
  5218. */
  5219. goog.structs.Set.prototype.add = function(element) {
  5220. this.map_.set(goog.structs.Set.getKey_(element), element);
  5221. };
  5222. /**
  5223. * Adds all the values in the given collection to this set.
  5224. * @param {Array|Object} col A collection containing the elements to add.
  5225. */
  5226. goog.structs.Set.prototype.addAll = function(col) {
  5227. var values = goog.structs.getValues(col);
  5228. var l = values.length;
  5229. for (var i = 0; i < l; i++) {
  5230. this.add(values[i]);
  5231. }
  5232. };
  5233. /**
  5234. * Removes the given element from this set.
  5235. * @param {*} element The primitive or object to remove.
  5236. * @return {boolean} Whether the element was found and removed.
  5237. */
  5238. goog.structs.Set.prototype.remove = function(element) {
  5239. return this.map_.remove(goog.structs.Set.getKey_(element));
  5240. };
  5241. /**
  5242. * Removes all elements from this set.
  5243. */
  5244. goog.structs.Set.prototype.clear = function() {
  5245. this.map_.clear();
  5246. };
  5247. /**
  5248. * Tests whether this set is empty.
  5249. * @return {boolean} True if there are no elements in this set.
  5250. */
  5251. goog.structs.Set.prototype.isEmpty = function() {
  5252. return this.map_.isEmpty();
  5253. };
  5254. /**
  5255. * Tests whether this set contains the given element.
  5256. * @param {*} element The primitive or object to test for.
  5257. * @return {boolean} True if this set contains the given element.
  5258. */
  5259. goog.structs.Set.prototype.contains = function(element) {
  5260. return this.map_.containsKey(goog.structs.Set.getKey_(element));
  5261. };
  5262. /**
  5263. * Tests whether this set contains all the values in a given collection.
  5264. * Repeated elements in the collection are ignored, e.g. (new
  5265. * goog.structs.Set([1, 2])).containsAll([1, 1]) is True.
  5266. * @param {Object} col A collection-like object.
  5267. * @return {boolean} True if the set contains all elements.
  5268. */
  5269. goog.structs.Set.prototype.containsAll = function(col) {
  5270. return goog.structs.every(col, this.contains, this);
  5271. };
  5272. /**
  5273. * Returns an array containing all the elements in this set.
  5274. * @return {Array} An array containing all the elements in this set.
  5275. */
  5276. goog.structs.Set.prototype.getValues = function() {
  5277. return this.map_.getValues();
  5278. };
  5279. /**
  5280. * Creates a shallow clone of this set.
  5281. * @return {goog.structs.Set} A new set containing all the same elements as
  5282. * this set.
  5283. */
  5284. goog.structs.Set.prototype.clone = function() {
  5285. return new goog.structs.Set(this);
  5286. };
  5287. /**
  5288. * Tests whether the given collection consists of the same elements as this set,
  5289. * regardless of order, without repetition. Primitives are treated as equal if
  5290. * they have the same type and convert to the same string; objects are treated
  5291. * as equal if they are references to the same object. This operation is O(n).
  5292. * @param {Object} col A collection.
  5293. * @return {boolean} True if the given collection consists of the same elements
  5294. * as this set, regardless of order, without repetition.
  5295. */
  5296. goog.structs.Set.prototype.equals = function(col) {
  5297. return this.getCount() == goog.structs.getCount(col) && this.isSubsetOf(col);
  5298. };
  5299. /**
  5300. * Tests whether the given collection contains all the elements in this set.
  5301. * Primitives are treated as equal if they have the same type and convert to the
  5302. * same string; objects are treated as equal if they are references to the same
  5303. * object. This operation is O(n).
  5304. * @param {Object} col A collection.
  5305. * @return {boolean} True if this set is a subset of the given collection.
  5306. */
  5307. goog.structs.Set.prototype.isSubsetOf = function(col) {
  5308. var colCount = goog.structs.getCount(col);
  5309. if (this.getCount() > colCount) {
  5310. return _FALSE;
  5311. }
  5312. // TODO(user) Find the minimal collection size where the conversion makes
  5313. // the contains() method faster.
  5314. if (!(col instanceof goog.structs.Set) && colCount > 5) {
  5315. // Convert to a goog.structs.Set so that goog.structs.contains runs in
  5316. // O(1) time instead of O(n) time.
  5317. col = new goog.structs.Set(col);
  5318. }
  5319. return goog.structs.every(this, function(value) {
  5320. return goog.structs.contains(col, value);
  5321. });
  5322. };
  5323. /**
  5324. * Returns an iterator that iterates over the elements in this set.
  5325. * @param {boolean=} opt_keys This argument is ignored.
  5326. * @return {goog.iter.Iterator} An iterator over the elements in this set.
  5327. */
  5328. goog.structs.Set.prototype.__iterator__ = function(opt_keys) {
  5329. return this.map_.__iterator__(_FALSE);
  5330. };
  5331. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  5332. //
  5333. // Licensed under the Apache License, Version 2.0 (the "License");
  5334. // you may not use this file except in compliance with the License.
  5335. // You may obtain a copy of the License at
  5336. //
  5337. // http://www.apache.org/licenses/LICENSE-2.0
  5338. //
  5339. // Unless required by applicable law or agreed to in writing, software
  5340. // distributed under the License is distributed on an "AS-IS" BASIS,
  5341. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5342. // See the License for the specific language governing permissions and
  5343. // limitations under the License.
  5344. //goog.require('goog.array');
  5345. //goog.require('goog.string');
  5346. //goog.require('goog.structs.Set');
  5347. // Copyright 2011 The Closure Library Authors. All Rights Reserved.
  5348. //
  5349. // Licensed under the Apache License, Version 2.0 (the "License");
  5350. // you may not use this file except in compliance with the License.
  5351. // You may obtain a copy of the License at
  5352. //
  5353. // http://www.apache.org/licenses/LICENSE-2.0
  5354. //
  5355. // Unless required by applicable law or agreed to in writing, software
  5356. // distributed under the License is distributed on an "AS-IS" BASIS,
  5357. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5358. // See the License for the specific language governing permissions and
  5359. // limitations under the License.
  5360. /**
  5361. * @fileoverview Definition of the disposable interface. A disposable object
  5362. * has a dispose method to to clean up references and resources.
  5363. */
  5364. goog.provide('goog.disposable.IDisposable');
  5365. /**
  5366. * Interface for a disposable object. If a instance requires cleanup
  5367. * (references COM objects, DOM notes, or other disposable objects), it should
  5368. * implement this interface (it may subclass goog.Disposable).
  5369. * @interface
  5370. */
  5371. goog.disposable.IDisposable = function() {};
  5372. /**
  5373. * Disposes of the object and its resources.
  5374. * @return {void} Nothing.
  5375. */
  5376. goog.disposable.IDisposable.prototype.dispose;
  5377. /**
  5378. * @return {boolean} Whether the object has been disposed of.
  5379. */
  5380. goog.disposable.IDisposable.prototype.isDisposed;
  5381. // Copyright 2005 The Closure Library Authors. All Rights Reserved.
  5382. //
  5383. // Licensed under the Apache License, Version 2.0 (the "License");
  5384. // you may not use this file except in compliance with the License.
  5385. // You may obtain a copy of the License at
  5386. //
  5387. // http://www.apache.org/licenses/LICENSE-2.0
  5388. //
  5389. // Unless required by applicable law or agreed to in writing, software
  5390. // distributed under the License is distributed on an "AS-IS" BASIS,
  5391. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5392. // See the License for the specific language governing permissions and
  5393. // limitations under the License.
  5394. /**
  5395. * @fileoverview Implements the disposable interface. The dispose method is used
  5396. * to clean up references and resources.
  5397. */
  5398. goog.provide('goog.Disposable');
  5399. goog.provide('goog.dispose');
  5400. //goog.require('goog.disposable.IDisposable');
  5401. /**
  5402. * Class that provides the basic implementation for disposable objects. If your
  5403. * class holds one or more references to COM objects, DOM nodes, or other
  5404. * disposable objects, it should extend this class or implement the disposable
  5405. * interface (defined in goog.disposable.IDisposable).
  5406. * @constructor
  5407. * @implements {goog.disposable.IDisposable}
  5408. */
  5409. goog.Disposable = function() {
  5410. if (goog.Disposable.ENABLE_MONITORING) {
  5411. goog.Disposable.instances_[goog.getUid(this)] = this;
  5412. }
  5413. };
  5414. /**
  5415. * @define {boolean} Whether to enable the monitoring of the goog.Disposable
  5416. * instances. Switching on the monitoring is only recommended for debugging
  5417. * because it has a significant impact on performance and memory usage.
  5418. * If switched off, the monitoring code compiles down to 0 bytes.
  5419. * The monitoring expects that all disposable objects call the
  5420. * {@code goog.Disposable} base constructor.
  5421. */
  5422. goog.Disposable.ENABLE_MONITORING = _FALSE;
  5423. /**
  5424. * Maps the unique ID of every undisposed {@code goog.Disposable} object to
  5425. * the object itself.
  5426. * @type {!Object.<number, !goog.Disposable>}
  5427. * @private
  5428. */
  5429. goog.Disposable.instances_ = {};
  5430. /**
  5431. * Whether the object has been disposed of.
  5432. * @type {boolean}
  5433. * @private
  5434. */
  5435. goog.Disposable.prototype.disposed_ = _FALSE;
  5436. /**
  5437. * @return {boolean} Whether the object has been disposed of.
  5438. */
  5439. goog.Disposable.prototype.isDisposed = function() {
  5440. return this.disposed_;
  5441. };
  5442. /**
  5443. * @return {boolean} Whether the object has been disposed of.
  5444. * @deprecated Use {@link #isDisposed} instead.
  5445. */
  5446. goog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;
  5447. /**
  5448. * Disposes of the object. If the object hasn't already been disposed of, calls
  5449. * {@link #disposeInternal}. Classes that extend {@code goog.Disposable} should
  5450. * override {@link #disposeInternal} in order to delete references to COM
  5451. * objects, DOM nodes, and other disposable objects.
  5452. *
  5453. * @return {void} Nothing.
  5454. */
  5455. goog.Disposable.prototype.dispose = function() {
  5456. if (!this.disposed_) {
  5457. // Set disposed_ to true first, in case during the chain of disposal this
  5458. // gets disposed recursively.
  5459. this.disposed_ = _TRUE;
  5460. this.disposeInternal();
  5461. if (goog.Disposable.ENABLE_MONITORING) {
  5462. var uid = goog.getUid(this);
  5463. if (!goog.Disposable.instances_.hasOwnProperty(uid)) {
  5464. throw Error(this + ' did not call the goog.Disposable base ' +
  5465. 'constructor or was disposed of after a clearUndisposedObjects ' +
  5466. 'call');
  5467. }
  5468. delete goog.Disposable.instances_[uid];
  5469. }
  5470. }
  5471. };
  5472. /**
  5473. * Deletes or nulls out any references to COM objects, DOM nodes, or other
  5474. * disposable objects. Classes that extend {@code goog.Disposable} should
  5475. * override this method. For example:
  5476. * <pre>
  5477. * mypackage.MyClass = function() {
  5478. * goog.Disposable.call(this);
  5479. * // Constructor logic specific to MyClass.
  5480. * ...
  5481. * };
  5482. * goog.inherits(mypackage.MyClass, goog.Disposable);
  5483. *
  5484. * mypackage.MyClass.prototype.disposeInternal = function() {
  5485. * mypackage.MyClass.superClass_.disposeInternal.call(this);
  5486. * // Dispose logic specific to MyClass.
  5487. * ...
  5488. * };
  5489. * </pre>
  5490. * @protected
  5491. */
  5492. goog.Disposable.prototype.disposeInternal = function() {
  5493. // No-op in the base class.
  5494. };
  5495. /**
  5496. * Calls {@code dispose} on the argument if it supports it. If obj is not an
  5497. * object with a dispose() method, this is a no-op.
  5498. * @param {*} obj The object to dispose of.
  5499. */
  5500. goog.dispose = function(obj) {
  5501. if (obj && typeof obj.dispose == 'function') {
  5502. obj.dispose();
  5503. }
  5504. };
  5505. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  5506. //
  5507. // Licensed under the Apache License, Version 2.0 (the "License");
  5508. // you may not use this file except in compliance with the License.
  5509. // You may obtain a copy of the License at
  5510. //
  5511. // http://www.apache.org/licenses/LICENSE-2.0
  5512. //
  5513. // Unless required by applicable law or agreed to in writing, software
  5514. // distributed under the License is distributed on an "AS-IS" BASIS,
  5515. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5516. // See the License for the specific language governing permissions and
  5517. // limitations under the License.
  5518. /**
  5519. * @fileoverview A generic interface for saving and restoring ranges.
  5520. *
  5521. * @author robbyw@google.com (Robby Walker)
  5522. */
  5523. goog.provide('goog.dom.SavedRange');
  5524. //goog.require('goog.Disposable');
  5525. /**
  5526. * Abstract interface for a saved range.
  5527. * @constructor
  5528. * @extends {goog.Disposable}
  5529. */
  5530. goog.dom.SavedRange = function() {
  5531. goog.Disposable.call(this);
  5532. };
  5533. goog.inherits(goog.dom.SavedRange, goog.Disposable);
  5534. /**
  5535. * Restores the range and by default disposes of the saved copy. Take note:
  5536. * this means the by default SavedRange objects are single use objects.
  5537. * @param {boolean=} opt_stayAlive Whether this SavedRange should stay alive
  5538. * (not be disposed) after restoring the range. Defaults to _FALSE (dispose).
  5539. * @return {goog.dom.AbstractRange} The restored range.
  5540. */
  5541. goog.dom.SavedRange.prototype.restore = function(opt_stayAlive) {
  5542. var range = this.restoreInternal();
  5543. if (!opt_stayAlive) {
  5544. this.dispose();
  5545. }
  5546. return range;
  5547. };
  5548. /**
  5549. * Internal method to restore the saved range.
  5550. * @return {goog.dom.AbstractRange} The restored range.
  5551. */
  5552. goog.dom.SavedRange.prototype.restoreInternal = goog.abstractMethod;
  5553. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  5554. //
  5555. // Licensed under the Apache License, Version 2.0 (the "License");
  5556. // you may not use this file except in compliance with the License.
  5557. // You may obtain a copy of the License at
  5558. //
  5559. // http://www.apache.org/licenses/LICENSE-2.0
  5560. //
  5561. // Unless required by applicable law or agreed to in writing, software
  5562. // distributed under the License is distributed on an "AS-IS" BASIS,
  5563. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5564. // See the License for the specific language governing permissions and
  5565. // limitations under the License.
  5566. /**
  5567. * @fileoverview An API for saving and restoring ranges as HTML carets.
  5568. *
  5569. * @author nicksantos@google.com (Nick Santos)
  5570. */
  5571. goog.provide('goog.dom.SavedCaretRange');
  5572. //goog.require('goog.array');
  5573. //goog.require('goog.dom');
  5574. //goog.require('goog.dom.SavedRange');
  5575. //goog.require('goog.dom.TagName');
  5576. //goog.require('goog.string');
  5577. /**
  5578. * A struct for holding context about saved selections.
  5579. * This can be used to preserve the selection and restore while the DOM is
  5580. * manipulated, or through an asynchronous call. Use goog.dom.Range factory
  5581. * methods to obtain an {@see goog.dom.AbstractRange} instance, and use
  5582. * {@see goog.dom.AbstractRange#saveUsingCarets} to obtain a SavedCaretRange.
  5583. * For editor ranges under content-editable elements or design-mode iframes,
  5584. * prefer using {@see goog.editor.range.saveUsingNormalizedCarets}.
  5585. * @param {goog.dom.AbstractRange} range The range being saved.
  5586. * @constructor
  5587. * @extends {goog.dom.SavedRange}
  5588. */
  5589. goog.dom.SavedCaretRange = function(range) {
  5590. goog.dom.SavedRange.call(this);
  5591. /**
  5592. * The DOM id of the caret at the start of the range.
  5593. * @type {string}
  5594. * @private
  5595. */
  5596. this.startCaretId_ = goog.string.createUniqueString();
  5597. /**
  5598. * The DOM id of the caret at the end of the range.
  5599. * @type {string}
  5600. * @private
  5601. */
  5602. this.endCaretId_ = goog.string.createUniqueString();
  5603. /**
  5604. * A DOM helper for storing the current document context.
  5605. * @type {goog.dom.DomHelper}
  5606. * @private
  5607. */
  5608. this.dom_ = goog.dom.getDomHelper(range.getDocument());
  5609. range.surroundWithNodes(this.createCaret_(_TRUE), this.createCaret_(_FALSE));
  5610. this.removeIncidentalTextNode_();
  5611. };
  5612. goog.inherits(goog.dom.SavedCaretRange, goog.dom.SavedRange);
  5613. /**
  5614. * Gets carets.
  5615. * @param {boolean} start If true, returns the start caret. Otherwise, get the
  5616. * end caret.
  5617. * @return {Element} The start or end caret in the given document.
  5618. */
  5619. goog.dom.SavedCaretRange.prototype.getCaret = function(start) {
  5620. return this.dom_.getElement(start ? this.startCaretId_ : this.endCaretId_);
  5621. };
  5622. goog.dom.SavedCaretRange.prototype.removeIncidentalTextNode_ = function() {
  5623. var startCaret = this.getCaret(_TRUE);
  5624. this.removeIfEmptyText_(startCaret.previousSibling);
  5625. this.removeIfEmptyText_(startCaret.nextSibling);
  5626. var endCaret = this.getCaret(_FALSE);
  5627. this.removeIfEmptyText_(endCaret.previousSibling);
  5628. this.removeIfEmptyText_(endCaret.nextSibling);
  5629. };
  5630. goog.dom.SavedCaretRange.prototype.removeIfEmptyText_ = function(node) {
  5631. if (node && node.nodeType === goog.dom.NodeType.TEXT && !node.nodeValue) {
  5632. goog.dom.removeNode(node);
  5633. }
  5634. }
  5635. /**
  5636. * Removes the carets from the current restoration document.
  5637. * @param {goog.dom.AbstractRange=} opt_range A range whose offsets have already
  5638. * been adjusted for caret removal; it will be adjusted if it is also
  5639. * affected by post-removal operations, such as text node normalization.
  5640. * @return {goog.dom.AbstractRange|undefined} The adjusted range, if opt_range
  5641. * was provided.
  5642. */
  5643. goog.dom.SavedCaretRange.prototype.removeCarets = function(opt_range) {
  5644. goog.dom.removeNode(this.getCaret(_TRUE));
  5645. goog.dom.removeNode(this.getCaret(_FALSE));
  5646. return opt_range;
  5647. };
  5648. /**
  5649. * Reconstruct the selection from the given saved range. Removes carets after
  5650. * restoring the selection. If restore does not dispose this saved range, it may
  5651. * only be restored a second time if innerHTML or some other mechanism is used
  5652. * to restore the carets to the dom.
  5653. * @return {goog.dom.AbstractRange?} Restored selection.
  5654. * @override
  5655. * @protected
  5656. */
  5657. goog.dom.SavedCaretRange.prototype.restoreInternal = function() {
  5658. var range = _NULL;
  5659. var startCaret = this.getCaret(_TRUE);
  5660. var endCaret = this.getCaret(_FALSE);
  5661. if (startCaret && endCaret) {
  5662. var startNode = startCaret.parentNode;
  5663. var startOffset = goog.array.indexOf(startNode.childNodes, startCaret);
  5664. var endNode = endCaret.parentNode;
  5665. var endOffset = goog.array.indexOf(endNode.childNodes, endCaret);
  5666. range = goog.dom.Range.createFromNodes(startNode, startOffset + 1,
  5667. endNode, endOffset);
  5668. range.select();
  5669. }
  5670. return range;
  5671. };
  5672. //goog.dom.SavedCaretRange.prototype.restoreInternal = function() {
  5673. // var range = null;
  5674. // var startCaret = this.getCaret(true);
  5675. // var endCaret = this.getCaret(false);
  5676. // if (startCaret && endCaret) {
  5677. // var startNode = startCaret.parentNode;
  5678. // var startOffset = goog.array.indexOf(startNode.childNodes, startCaret);
  5679. // var endNode = endCaret.parentNode;
  5680. // var endOffset = goog.array.indexOf(endNode.childNodes, endCaret);
  5681. // if (endNode == startNode) {
  5682. // // Compensate for the start caret being removed.
  5683. // endOffset -= 1;
  5684. // }
  5685. // range = goog.dom.Range.createFromNodes(startNode, startOffset,
  5686. // endNode, endOffset);
  5687. // range = this.removeCarets(range);
  5688. //// range.select();
  5689. // } else {
  5690. // // If only one caret was found, remove it.
  5691. // this.removeCarets();
  5692. // }
  5693. // return range;
  5694. //};
  5695. /**
  5696. * Dispose the saved range and remove the carets from the DOM.
  5697. * @override
  5698. * @protected
  5699. */
  5700. goog.dom.SavedCaretRange.prototype.disposeInternal = function() {
  5701. this.removeCarets();
  5702. this.dom_ = _NULL;
  5703. };
  5704. /**
  5705. * Creates a caret element.
  5706. * @param {boolean} start If true, creates the start caret. Otherwise,
  5707. * creates the end caret.
  5708. * @return {Element} The new caret element.
  5709. * @private
  5710. */
  5711. goog.dom.SavedCaretRange.prototype.createCaret_ = function(start) {
  5712. return this.dom_.createDom(goog.dom.TagName.SPAN,
  5713. {'id': start ? this.startCaretId_ : this.endCaretId_});
  5714. };
  5715. /**
  5716. * A regex that will match all saved range carets in a string.
  5717. * @type {RegExp}
  5718. */
  5719. goog.dom.SavedCaretRange.CARET_REGEX = /<span\s+id="?goog_\d+"?><\/span>/ig;
  5720. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  5721. //
  5722. // Licensed under the Apache License, Version 2.0 (the "License");
  5723. // you may not use this file except in compliance with the License.
  5724. // You may obtain a copy of the License at
  5725. //
  5726. // http://www.apache.org/licenses/LICENSE-2.0
  5727. //
  5728. // Unless required by applicable law or agreed to in writing, software
  5729. // distributed under the License is distributed on an "AS-IS" BASIS,
  5730. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5731. // See the License for the specific language governing permissions and
  5732. // limitations under the License.
  5733. /**
  5734. * @fileoverview Interface definitions for working with ranges
  5735. * in HTML documents.
  5736. *
  5737. * @author robbyw@google.com (Robby Walker)
  5738. */
  5739. goog.provide('goog.dom.AbstractRange');
  5740. goog.provide('goog.dom.RangeIterator');
  5741. goog.provide('goog.dom.RangeType');
  5742. //goog.require('goog.dom');
  5743. //goog.require('goog.dom.NodeType');
  5744. //goog.require('goog.dom.SavedCaretRange');
  5745. //goog.require('goog.dom.TagIterator');
  5746. //goog.require('goog.userAgent');
  5747. /**
  5748. * Types of ranges.
  5749. * @enum {string}
  5750. */
  5751. goog.dom.RangeType = {
  5752. TEXT: 'text',
  5753. CONTROL: 'control',
  5754. MULTI: 'mutli'
  5755. };
  5756. /**
  5757. * Creates a new selection with no properties. Do not use this constructor -
  5758. * use one of the goog.dom.Range.from* methods instead.
  5759. * @constructor
  5760. */
  5761. goog.dom.AbstractRange = function() {
  5762. };
  5763. /**
  5764. * Gets the browser native selection object from the given window.
  5765. * @param {Window} win The window to get the selection object from.
  5766. * @return {Object} The browser native selection object, or null if it could
  5767. * not be retrieved.
  5768. */
  5769. goog.dom.AbstractRange.getBrowserSelectionForWindow = function(win) {
  5770. if (win.getSelection) {
  5771. // W3C
  5772. return win.getSelection();
  5773. } else {
  5774. // IE
  5775. var doc = win.document;
  5776. var sel = doc.selection;
  5777. if (sel) {
  5778. // IE has a bug where it sometimes returns a selection from the wrong
  5779. // document. Catching these cases now helps us avoid problems later.
  5780. try {
  5781. var range = sel.createRange();
  5782. // Only TextRanges have a parentElement method.
  5783. if (range.parentElement) {
  5784. if (range.parentElement().document != doc) {
  5785. return _NULL;
  5786. }
  5787. } else if (!range.length || range.item(0).document != doc) {
  5788. // For ControlRanges, check that the range has items, and that
  5789. // the first item in the range is in the correct document.
  5790. return _NULL;
  5791. }
  5792. } catch (e) {
  5793. // If the selection is in the wrong document, and the wrong document is
  5794. // in a different domain, IE will throw an exception.
  5795. return _NULL;
  5796. }
  5797. // TODO(user|robbyw) Sometimes IE 6 returns a selection instance
  5798. // when there is no selection. This object has a 'type' property equals
  5799. // to 'None' and a typeDetail property bound to undefined. Ideally this
  5800. // function should not return this instance.
  5801. return sel;
  5802. }
  5803. return _NULL;
  5804. }
  5805. };
  5806. /**
  5807. * Tests if the given Object is a controlRange.
  5808. * @param {Object} range The range object to test.
  5809. * @return {boolean} Whether the given Object is a controlRange.
  5810. */
  5811. goog.dom.AbstractRange.isNativeControlRange = function(range) {
  5812. // For now, tests for presence of a control range function.
  5813. return !!range && !!range.addElement;
  5814. };
  5815. /**
  5816. * @return {goog.dom.AbstractRange} A clone of this range.
  5817. */
  5818. goog.dom.AbstractRange.prototype.clone = goog.abstractMethod;
  5819. /**
  5820. * @return {goog.dom.RangeType} The type of range represented by this object.
  5821. */
  5822. goog.dom.AbstractRange.prototype.getType = goog.abstractMethod;
  5823. /**
  5824. * @return {Range|TextRange} The native browser range object.
  5825. */
  5826. goog.dom.AbstractRange.prototype.getBrowserRangeObject = goog.abstractMethod;
  5827. /**
  5828. * Sets the native browser range object, overwriting any state this range was
  5829. * storing.
  5830. * @param {Range|TextRange} nativeRange The native browser range object.
  5831. * @return {boolean} Whether the given range was accepted. If not, the caller
  5832. * will need to call goog.dom.Range.createFromBrowserRange to create a new
  5833. * range object.
  5834. */
  5835. goog.dom.AbstractRange.prototype.setBrowserRangeObject = function(nativeRange) {
  5836. return _FALSE;
  5837. };
  5838. /**
  5839. * @return {number} The number of text ranges in this range.
  5840. */
  5841. goog.dom.AbstractRange.prototype.getTextRangeCount = goog.abstractMethod;
  5842. /**
  5843. * Get the i-th text range in this range. The behavior is undefined if
  5844. * i >= getTextRangeCount or i < 0.
  5845. * @param {number} i The range number to retrieve.
  5846. * @return {goog.dom.TextRange} The i-th text range.
  5847. */
  5848. goog.dom.AbstractRange.prototype.getTextRange = goog.abstractMethod;
  5849. /**
  5850. * Gets an array of all text ranges this range is comprised of. For non-multi
  5851. * ranges, returns a single element array containing this.
  5852. * @return {Array.<goog.dom.TextRange>} Array of text ranges.
  5853. */
  5854. goog.dom.AbstractRange.prototype.getTextRanges = function() {
  5855. var output = [];
  5856. for (var i = 0, len = this.getTextRangeCount(); i < len; i++) {
  5857. output.push(this.getTextRange(i));
  5858. }
  5859. return output;
  5860. };
  5861. /**
  5862. * @return {Node} The deepest node that contains the entire range.
  5863. */
  5864. goog.dom.AbstractRange.prototype.getContainer = goog.abstractMethod;
  5865. /**
  5866. * @return {Node} The element or text node the range starts in. For text
  5867. * ranges, the range comprises all text between the start and end position.
  5868. * For other types of range, start and end give bounds of the range but
  5869. * do not imply all nodes in those bounds are selected.
  5870. */
  5871. goog.dom.AbstractRange.prototype.getStartNode = goog.abstractMethod;
  5872. /**
  5873. * @return {number} The offset into the node the range starts in. For text
  5874. * nodes, this is an offset into the node value. For elements, this is
  5875. * an offset into the childNodes array.
  5876. */
  5877. goog.dom.AbstractRange.prototype.getStartOffset = goog.abstractMethod;
  5878. /**
  5879. * @return {Node} The element or text node the range ends in.
  5880. */
  5881. goog.dom.AbstractRange.prototype.getEndNode = goog.abstractMethod;
  5882. /**
  5883. * @return {number} The offset into the node the range ends in. For text
  5884. * nodes, this is an offset into the node value. For elements, this is
  5885. * an offset into the childNodes array.
  5886. */
  5887. goog.dom.AbstractRange.prototype.getEndOffset = goog.abstractMethod;
  5888. /**
  5889. * @return {Node} The element or text node the range is anchored at.
  5890. */
  5891. goog.dom.AbstractRange.prototype.getAnchorNode = function() {
  5892. return this.isReversed() ? this.getEndNode() : this.getStartNode();
  5893. };
  5894. /**
  5895. * @return {number} The offset into the node the range is anchored at. For
  5896. * text nodes, this is an offset into the node value. For elements, this
  5897. * is an offset into the childNodes array.
  5898. */
  5899. goog.dom.AbstractRange.prototype.getAnchorOffset = function() {
  5900. return this.isReversed() ? this.getEndOffset() : this.getStartOffset();
  5901. };
  5902. /**
  5903. * @return {Node} The element or text node the range is focused at - i.e. where
  5904. * the cursor is.
  5905. */
  5906. goog.dom.AbstractRange.prototype.getFocusNode = function() {
  5907. return this.isReversed() ? this.getStartNode() : this.getEndNode();
  5908. };
  5909. /**
  5910. * @return {number} The offset into the node the range is focused at - i.e.
  5911. * where the cursor is. For text nodes, this is an offset into the node
  5912. * value. For elements, this is an offset into the childNodes array.
  5913. */
  5914. goog.dom.AbstractRange.prototype.getFocusOffset = function() {
  5915. return this.isReversed() ? this.getStartOffset() : this.getEndOffset();
  5916. };
  5917. /**
  5918. * @return {boolean} Whether the selection is reversed.
  5919. */
  5920. goog.dom.AbstractRange.prototype.isReversed = function() {
  5921. return _FALSE;
  5922. };
  5923. /**
  5924. * @return {Document} The document this selection is a part of.
  5925. */
  5926. goog.dom.AbstractRange.prototype.getDocument = function() {
  5927. // Using start node in IE was crashing the browser in some cases so use
  5928. // getContainer for that browser. It's also faster for IE, but still slower
  5929. // than start node for other browsers so we continue to use getStartNode when
  5930. // it is not problematic. See bug 1687309.
  5931. return goog.dom.getOwnerDocument(goog.userAgent.IE ?
  5932. this.getContainer() : this.getStartNode());
  5933. };
  5934. /**
  5935. * @return {Window} The window this selection is a part of.
  5936. */
  5937. goog.dom.AbstractRange.prototype.getWindow = function() {
  5938. return goog.dom.getWindow(this.getDocument());
  5939. };
  5940. /**
  5941. * Tests if this range contains the given range.
  5942. * @param {goog.dom.AbstractRange} range The range to test.
  5943. * @param {boolean=} opt_allowPartial If true, the range can be partially
  5944. * contained in the selection, otherwise the range must be entirely
  5945. * contained.
  5946. * @return {boolean} Whether this range contains the given range.
  5947. */
  5948. goog.dom.AbstractRange.prototype.containsRange = goog.abstractMethod;
  5949. /**
  5950. * Tests if this range contains the given node.
  5951. * @param {Node} node The node to test for.
  5952. * @param {boolean=} opt_allowPartial If not set or _FALSE, the node must be
  5953. * entirely contained in the selection for this function to return true.
  5954. * @return {boolean} Whether this range contains the given node.
  5955. */
  5956. goog.dom.AbstractRange.prototype.containsNode = function(node,
  5957. opt_allowPartial) {
  5958. return this.containsRange(goog.dom.Range.createFromNodeContents(node),
  5959. opt_allowPartial);
  5960. };
  5961. /**
  5962. * Tests whether this range is valid (i.e. whether its endpoints are still in
  5963. * the document). A range becomes invalid when, after this object was created,
  5964. * either one or both of its endpoints are removed from the document. Use of
  5965. * an invalid range can lead to runtime errors, particularly in IE.
  5966. * @return {boolean} Whether the range is valid.
  5967. */
  5968. goog.dom.AbstractRange.prototype.isRangeInDocument = goog.abstractMethod;
  5969. /**
  5970. * @return {boolean} Whether the range is collapsed.
  5971. */
  5972. goog.dom.AbstractRange.prototype.isCollapsed = goog.abstractMethod;
  5973. /**
  5974. * @return {string} The text content of the range.
  5975. */
  5976. goog.dom.AbstractRange.prototype.getText = goog.abstractMethod;
  5977. /**
  5978. * Returns the HTML fragment this range selects. This is slow on all browsers.
  5979. * The HTML fragment may not be valid HTML, for instance if the user selects
  5980. * from a to b inclusively in the following html:
  5981. *
  5982. * &gt;div&lt;a&gt;/div&lt;b
  5983. *
  5984. * This method will return
  5985. *
  5986. * a&lt;/div&gt;b
  5987. *
  5988. * If you need valid HTML, use {@link #getValidHtml} instead.
  5989. *
  5990. * @return {string} HTML fragment of the range, does not include context
  5991. * containing elements.
  5992. */
  5993. goog.dom.AbstractRange.prototype.getHtmlFragment = goog.abstractMethod;
  5994. /**
  5995. * Returns valid HTML for this range. This is fast on IE, and semi-fast on
  5996. * other browsers.
  5997. * @return {string} Valid HTML of the range, including context containing
  5998. * elements.
  5999. */
  6000. goog.dom.AbstractRange.prototype.getValidHtml = goog.abstractMethod;
  6001. /**
  6002. * Returns pastable HTML for this range. This guarantees that any child items
  6003. * that must have specific ancestors will have them, for instance all TDs will
  6004. * be contained in a TR in a TBODY in a TABLE and all LIs will be contained in
  6005. * a UL or OL as appropriate. This is semi-fast on all browsers.
  6006. * @return {string} Pastable HTML of the range, including context containing
  6007. * elements.
  6008. */
  6009. goog.dom.AbstractRange.prototype.getPastableHtml = goog.abstractMethod;
  6010. /**
  6011. * Returns a RangeIterator over the contents of the range. Regardless of the
  6012. * direction of the range, the iterator will move in document order.
  6013. * @param {boolean=} opt_keys Unused for this iterator.
  6014. * @return {goog.dom.RangeIterator} An iterator over tags in the range.
  6015. */
  6016. goog.dom.AbstractRange.prototype.__iterator__ = goog.abstractMethod;
  6017. // RANGE ACTIONS
  6018. /**
  6019. * Sets this range as the selection in its window.
  6020. */
  6021. goog.dom.AbstractRange.prototype.select = goog.abstractMethod;
  6022. /**
  6023. * Removes the contents of the range from the document.
  6024. */
  6025. goog.dom.AbstractRange.prototype.removeContents = goog.abstractMethod;
  6026. /**
  6027. * Inserts a node before (or after) the range. The range may be disrupted
  6028. * beyond recovery because of the way this splits nodes.
  6029. * @param {Node} node The node to insert.
  6030. * @param {boolean} before True to insert before, _FALSE to insert after.
  6031. * @return {Node} The node added to the document. This may be different
  6032. * than the node parameter because on IE we have to clone it.
  6033. */
  6034. goog.dom.AbstractRange.prototype.insertNode = goog.abstractMethod;
  6035. /**
  6036. * Surrounds this range with the two given nodes. The range may be disrupted
  6037. * beyond recovery because of the way this splits nodes.
  6038. * @param {Element} startNode The node to insert at the start.
  6039. * @param {Element} endNode The node to insert at the end.
  6040. */
  6041. goog.dom.AbstractRange.prototype.surroundWithNodes = goog.abstractMethod;
  6042. // SAVE/RESTORE
  6043. /**
  6044. * Saves the range so that if the start and end nodes are left alone, it can
  6045. * be restored.
  6046. * @return {goog.dom.SavedRange} A range representation that can be restored
  6047. * as long as the endpoint nodes of the selection are not modified.
  6048. */
  6049. goog.dom.AbstractRange.prototype.saveUsingDom = goog.abstractMethod;
  6050. /**
  6051. * Saves the range using HTML carets. As long as the carets remained in the
  6052. * HTML, the range can be restored...even when the HTML is copied across
  6053. * documents.
  6054. * @return {goog.dom.SavedCaretRange?} A range representation that can be
  6055. * restored as long as carets are not removed. Returns null if carets
  6056. * could not be created.
  6057. */
  6058. goog.dom.AbstractRange.prototype.saveUsingCarets = function() {
  6059. return (this.getStartNode() && this.getEndNode()) ?
  6060. new goog.dom.SavedCaretRange(this) : _NULL;
  6061. };
  6062. // RANGE MODIFICATION
  6063. /**
  6064. * Collapses the range to one of its boundary points.
  6065. * @param {boolean} toAnchor Whether to collapse to the anchor of the range.
  6066. */
  6067. goog.dom.AbstractRange.prototype.collapse = goog.abstractMethod;
  6068. // RANGE ITERATION
  6069. /**
  6070. * Subclass of goog.dom.TagIterator that iterates over a DOM range. It
  6071. * adds functions to determine the portion of each text node that is selected.
  6072. * @param {Node} node The node to start traversal at. When null, creates an
  6073. * empty iterator.
  6074. * @param {boolean=} opt_reverse Whether to traverse nodes in reverse.
  6075. * @constructor
  6076. * @extends {goog.dom.TagIterator}
  6077. */
  6078. goog.dom.RangeIterator = function(node, opt_reverse) {
  6079. goog.dom.TagIterator.call(this, node, opt_reverse, _TRUE);
  6080. };
  6081. goog.inherits(goog.dom.RangeIterator, goog.dom.TagIterator);
  6082. /**
  6083. * @return {number} The offset into the current node, or -1 if the current node
  6084. * is not a text node.
  6085. */
  6086. goog.dom.RangeIterator.prototype.getStartTextOffset = goog.abstractMethod;
  6087. /**
  6088. * @return {number} The end offset into the current node, or -1 if the current
  6089. * node is not a text node.
  6090. */
  6091. goog.dom.RangeIterator.prototype.getEndTextOffset = goog.abstractMethod;
  6092. /**
  6093. * @return {Node} node The iterator's start node.
  6094. */
  6095. goog.dom.RangeIterator.prototype.getStartNode = goog.abstractMethod;
  6096. /**
  6097. * @return {Node} The iterator's end node.
  6098. */
  6099. goog.dom.RangeIterator.prototype.getEndNode = goog.abstractMethod;
  6100. /**
  6101. * @return {boolean} Whether a call to next will fail.
  6102. */
  6103. goog.dom.RangeIterator.prototype.isLast = goog.abstractMethod;
  6104. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  6105. //
  6106. // Licensed under the Apache License, Version 2.0 (the "License");
  6107. // you may not use this file except in compliance with the License.
  6108. // You may obtain a copy of the License at
  6109. //
  6110. // http://www.apache.org/licenses/LICENSE-2.0
  6111. //
  6112. // Unless required by applicable law or agreed to in writing, software
  6113. // distributed under the License is distributed on an "AS-IS" BASIS,
  6114. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6115. // See the License for the specific language governing permissions and
  6116. // limitations under the License.
  6117. /**
  6118. * @fileoverview Utilities for working with ranges comprised of multiple
  6119. * sub-ranges.
  6120. *
  6121. * @author robbyw@google.com (Robby Walker)
  6122. * @author jparent@google.com (Julie Parent)
  6123. */
  6124. goog.provide('goog.dom.AbstractMultiRange');
  6125. //goog.require('goog.array');
  6126. //goog.require('goog.dom');
  6127. //goog.require('goog.dom.AbstractRange');
  6128. /**
  6129. * Creates a new multi range with no properties. Do not use this
  6130. * constructor: use one of the goog.dom.Range.createFrom* methods instead.
  6131. * @constructor
  6132. * @extends {goog.dom.AbstractRange}
  6133. */
  6134. goog.dom.AbstractMultiRange = function() {
  6135. };
  6136. goog.inherits(goog.dom.AbstractMultiRange, goog.dom.AbstractRange);
  6137. /** @inheritDoc */
  6138. goog.dom.AbstractMultiRange.prototype.containsRange = function(
  6139. otherRange, opt_allowPartial) {
  6140. // TODO(user): This will incorrectly return _FALSE if two (or more) adjacent
  6141. // elements are both in the control range, and are also in the text range
  6142. // being compared to.
  6143. var ranges = this.getTextRanges();
  6144. var otherRanges = otherRange.getTextRanges();
  6145. var fn = opt_allowPartial ? goog.array.some : goog.array.every;
  6146. return fn(otherRanges, function(otherRange) {
  6147. return goog.array.some(ranges, function(range) {
  6148. return range.containsRange(otherRange, opt_allowPartial);
  6149. });
  6150. });
  6151. };
  6152. /** @inheritDoc */
  6153. goog.dom.AbstractMultiRange.prototype.insertNode = function(node, before) {
  6154. if (before) {
  6155. goog.dom.insertSiblingBefore(node, this.getStartNode());
  6156. } else {
  6157. goog.dom.insertSiblingAfter(node, this.getEndNode());
  6158. }
  6159. return node;
  6160. };
  6161. /** @inheritDoc */
  6162. goog.dom.AbstractMultiRange.prototype.surroundWithNodes = function(startNode,
  6163. endNode) {
  6164. this.insertNode(startNode, _TRUE);
  6165. this.insertNode(endNode, _FALSE);
  6166. };
  6167. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  6168. //
  6169. // Licensed under the Apache License, Version 2.0 (the "License");
  6170. // you may not use this file except in compliance with the License.
  6171. // You may obtain a copy of the License at
  6172. //
  6173. // http://www.apache.org/licenses/LICENSE-2.0
  6174. //
  6175. // Unless required by applicable law or agreed to in writing, software
  6176. // distributed under the License is distributed on an "AS-IS" BASIS,
  6177. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6178. // See the License for the specific language governing permissions and
  6179. // limitations under the License.
  6180. /**
  6181. * @fileoverview Iterator between two DOM text range positions.
  6182. *
  6183. * @author robbyw@google.com (Robby Walker)
  6184. */
  6185. goog.provide('goog.dom.TextRangeIterator');
  6186. //goog.require('goog.array');
  6187. //goog.require('goog.dom.NodeType');
  6188. //goog.require('goog.dom.RangeIterator');
  6189. //goog.require('goog.dom.TagName');
  6190. //goog.require('goog.iter.StopIteration');
  6191. /**
  6192. * Subclass of goog.dom.TagIterator that iterates over a DOM range. It
  6193. * adds functions to determine the portion of each text node that is selected.
  6194. *
  6195. * @param {Node} startNode The starting node position.
  6196. * @param {number} startOffset The offset in to startNode. If startNode is
  6197. * an element, indicates an offset in to childNodes. If startNode is a
  6198. * text node, indicates an offset in to nodeValue.
  6199. * @param {Node} endNode The ending node position.
  6200. * @param {number} endOffset The offset in to endNode. If endNode is
  6201. * an element, indicates an offset in to childNodes. If endNode is a
  6202. * text node, indicates an offset in to nodeValue.
  6203. * @param {boolean=} opt_reverse Whether to traverse nodes in reverse.
  6204. * @constructor
  6205. * @extends {goog.dom.RangeIterator}
  6206. */
  6207. goog.dom.TextRangeIterator = function(startNode, startOffset, endNode,
  6208. endOffset, opt_reverse) {
  6209. var goNext;
  6210. if (startNode) {
  6211. this.startNode_ = startNode;
  6212. this.startOffset_ = startOffset;
  6213. this.endNode_ = endNode;
  6214. this.endOffset_ = endOffset;
  6215. // Skip to the offset nodes - being careful to special case BRs since these
  6216. // have no children but still can appear as the startContainer of a range.
  6217. if (startNode.nodeType == goog.dom.NodeType.ELEMENT &&
  6218. startNode.tagName != goog.dom.TagName.BR) {
  6219. var startChildren = startNode.childNodes;
  6220. var candidate = startChildren[startOffset];
  6221. if (candidate) {
  6222. this.startNode_ = candidate;
  6223. this.startOffset_ = 0;
  6224. } else {
  6225. if (startChildren.length) {
  6226. this.startNode_ =
  6227. /** @type {Node} */ (goog.array.peek(startChildren));
  6228. }
  6229. goNext = _TRUE;
  6230. }
  6231. }
  6232. if (endNode.nodeType == goog.dom.NodeType.ELEMENT) {
  6233. this.endNode_ = endNode.childNodes[endOffset];
  6234. if (this.endNode_) {
  6235. this.endOffset_ = 0;
  6236. } else {
  6237. // The offset was past the last element.
  6238. this.endNode_ = endNode;
  6239. }
  6240. }
  6241. }
  6242. goog.dom.RangeIterator.call(this, opt_reverse ? this.endNode_ :
  6243. this.startNode_, opt_reverse);
  6244. if (goNext) {
  6245. try {
  6246. this.next();
  6247. } catch (e) {
  6248. if (e != goog.iter.StopIteration) {
  6249. throw e;
  6250. }
  6251. }
  6252. }
  6253. };
  6254. goog.inherits(goog.dom.TextRangeIterator, goog.dom.RangeIterator);
  6255. /**
  6256. * The first node in the selection.
  6257. * @type {Node}
  6258. * @private
  6259. */
  6260. goog.dom.TextRangeIterator.prototype.startNode_ = _NULL;
  6261. /**
  6262. * The last node in the selection.
  6263. * @type {Node}
  6264. * @private
  6265. */
  6266. goog.dom.TextRangeIterator.prototype.endNode_ = _NULL;
  6267. /**
  6268. * The offset within the first node in the selection.
  6269. * @type {number}
  6270. * @private
  6271. */
  6272. goog.dom.TextRangeIterator.prototype.startOffset_ = 0;
  6273. /**
  6274. * The offset within the last node in the selection.
  6275. * @type {number}
  6276. * @private
  6277. */
  6278. goog.dom.TextRangeIterator.prototype.endOffset_ = 0;
  6279. /** @inheritDoc */
  6280. goog.dom.TextRangeIterator.prototype.getStartTextOffset = function() {
  6281. // Offsets only apply to text nodes. If our current node is the start node,
  6282. // return the saved offset. Otherwise, return 0.
  6283. return this.node.nodeType != goog.dom.NodeType.TEXT ? -1 :
  6284. this.node == this.startNode_ ? this.startOffset_ : 0;
  6285. };
  6286. /** @inheritDoc */
  6287. goog.dom.TextRangeIterator.prototype.getEndTextOffset = function() {
  6288. // Offsets only apply to text nodes. If our current node is the end node,
  6289. // return the saved offset. Otherwise, return the length of the node.
  6290. return this.node.nodeType != goog.dom.NodeType.TEXT ? -1 :
  6291. this.node == this.endNode_ ? this.endOffset_ : this.node.nodeValue.length;
  6292. };
  6293. /** @inheritDoc */
  6294. goog.dom.TextRangeIterator.prototype.getStartNode = function() {
  6295. return this.startNode_;
  6296. };
  6297. /**
  6298. * Change the start node of the iterator.
  6299. * @param {Node} node The new start node.
  6300. */
  6301. goog.dom.TextRangeIterator.prototype.setStartNode = function(node) {
  6302. if (!this.isStarted()) {
  6303. this.setPosition(node);
  6304. }
  6305. this.startNode_ = node;
  6306. this.startOffset_ = 0;
  6307. };
  6308. /** @inheritDoc */
  6309. goog.dom.TextRangeIterator.prototype.getEndNode = function() {
  6310. return this.endNode_;
  6311. };
  6312. /**
  6313. * Change the end node of the iterator.
  6314. * @param {Node} node The new end node.
  6315. */
  6316. goog.dom.TextRangeIterator.prototype.setEndNode = function(node) {
  6317. this.endNode_ = node;
  6318. this.endOffset_ = 0;
  6319. };
  6320. /** @inheritDoc */
  6321. goog.dom.TextRangeIterator.prototype.isLast = function() {
  6322. return this.isStarted() && this.node == this.endNode_ &&
  6323. (!this.endOffset_ || !this.isStartTag());
  6324. };
  6325. /**
  6326. * Move to the next position in the selection.
  6327. * Throws {@code goog.iter.StopIteration} when it passes the end of the range.
  6328. * @return {Node} The node at the next position.
  6329. */
  6330. goog.dom.TextRangeIterator.prototype.next = function() {
  6331. if (this.isLast()) {
  6332. throw goog.iter.StopIteration;
  6333. }
  6334. // Call the super function.
  6335. return goog.dom.TextRangeIterator.superClass_.next.call(this);
  6336. };
  6337. /** @inheritDoc */
  6338. goog.dom.TextRangeIterator.prototype.skipTag = function() {
  6339. goog.dom.TextRangeIterator.superClass_.skipTag.apply(this);
  6340. // If the node we are skipping contains the end node, we just skipped past
  6341. // the end, so we stop the iteration.
  6342. if (goog.dom.contains(this.node, this.endNode_)) {
  6343. throw goog.iter.StopIteration;
  6344. }
  6345. };
  6346. /**
  6347. * Replace this iterator's values with values from another.
  6348. * @param {goog.dom.TextRangeIterator} other The iterator to copy.
  6349. * @protected
  6350. */
  6351. goog.dom.TextRangeIterator.prototype.copyFrom = function(other) {
  6352. this.startNode_ = other.startNode_;
  6353. this.endNode_ = other.endNode_;
  6354. this.startOffset_ = other.startOffset_;
  6355. this.endOffset_ = other.endOffset_;
  6356. this.isReversed_ = other.isReversed_;
  6357. goog.dom.TextRangeIterator.superClass_.copyFrom.call(this, other);
  6358. };
  6359. /**
  6360. * @return {goog.dom.TextRangeIterator} An identical iterator.
  6361. */
  6362. goog.dom.TextRangeIterator.prototype.clone = function() {
  6363. var copy = new goog.dom.TextRangeIterator(this.startNode_,
  6364. this.startOffset_, this.endNode_, this.endOffset_, this.isReversed_);
  6365. copy.copyFrom(this);
  6366. return copy;
  6367. };
  6368. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  6369. //
  6370. // Licensed under the Apache License, Version 2.0 (the "License");
  6371. // you may not use this file except in compliance with the License.
  6372. // You may obtain a copy of the License at
  6373. //
  6374. // http://www.apache.org/licenses/LICENSE-2.0
  6375. //
  6376. // Unless required by applicable law or agreed to in writing, software
  6377. // distributed under the License is distributed on an "AS-IS" BASIS,
  6378. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6379. // See the License for the specific language governing permissions and
  6380. // limitations under the License.
  6381. /**
  6382. * @fileoverview Detection of JScript version.
  6383. *
  6384. */
  6385. goog.provide('goog.userAgent.jscript');
  6386. //goog.require('goog.string');
  6387. /**
  6388. * @define {boolean} True if it is known at compile time that the runtime
  6389. * environment will not be using JScript.
  6390. */
  6391. goog.userAgent.jscript.ASSUME_NO_JSCRIPT = _FALSE;
  6392. /**
  6393. * Initializer for goog.userAgent.jscript. Detects if the user agent is using
  6394. * Microsoft JScript and which version of it.
  6395. *
  6396. * This is a named function so that it can be stripped via the jscompiler
  6397. * option for stripping types.
  6398. * @private
  6399. */
  6400. goog.userAgent.jscript.init_ = function() {
  6401. var hasScriptEngine = 'ScriptEngine' in goog.global;
  6402. /**
  6403. * @type {boolean}
  6404. * @private
  6405. */
  6406. goog.userAgent.jscript.DETECTED_HAS_JSCRIPT_ =
  6407. hasScriptEngine && goog.global['ScriptEngine']() == 'JScript';
  6408. /**
  6409. * @type {string}
  6410. * @private
  6411. */
  6412. goog.userAgent.jscript.DETECTED_VERSION_ =
  6413. goog.userAgent.jscript.DETECTED_HAS_JSCRIPT_ ?
  6414. (goog.global['ScriptEngineMajorVersion']() + '.' +
  6415. goog.global['ScriptEngineMinorVersion']() + '.' +
  6416. goog.global['ScriptEngineBuildVersion']()) :
  6417. '0';
  6418. };
  6419. if (!goog.userAgent.jscript.ASSUME_NO_JSCRIPT) {
  6420. goog.userAgent.jscript.init_();
  6421. }
  6422. /**
  6423. * Whether we detect that the user agent is using Microsoft JScript.
  6424. * @type {boolean}
  6425. */
  6426. goog.userAgent.jscript.HAS_JSCRIPT = goog.userAgent.jscript.ASSUME_NO_JSCRIPT ?
  6427. _FALSE : goog.userAgent.jscript.DETECTED_HAS_JSCRIPT_;
  6428. /**
  6429. * The installed version of JScript.
  6430. * @type {string}
  6431. */
  6432. goog.userAgent.jscript.VERSION = goog.userAgent.jscript.ASSUME_NO_JSCRIPT ?
  6433. '0' : goog.userAgent.jscript.DETECTED_VERSION_;
  6434. /**
  6435. * Whether the installed version of JScript is as new or newer than a given
  6436. * version.
  6437. * @param {string} version The version to check.
  6438. * @return {boolean} Whether the installed version of JScript is as new or
  6439. * newer than the given version.
  6440. */
  6441. goog.userAgent.jscript.isVersion = function(version) {
  6442. return goog.string.compareVersions(goog.userAgent.jscript.VERSION,
  6443. version) >= 0;
  6444. };
  6445. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  6446. //
  6447. // Licensed under the Apache License, Version 2.0 (the "License");
  6448. // you may not use this file except in compliance with the License.
  6449. // You may obtain a copy of the License at
  6450. //
  6451. // http://www.apache.org/licenses/LICENSE-2.0
  6452. //
  6453. // Unless required by applicable law or agreed to in writing, software
  6454. // distributed under the License is distributed on an "AS-IS" BASIS,
  6455. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6456. // See the License for the specific language governing permissions and
  6457. // limitations under the License.
  6458. /**
  6459. * @fileoverview Utility for fast string concatenation.
  6460. */
  6461. goog.provide('goog.string.StringBuffer');
  6462. //goog.require('goog.userAgent.jscript');
  6463. /**
  6464. * Utility class to facilitate much faster string concatenation in IE,
  6465. * using Array.join() rather than the '+' operator. For other browsers
  6466. * we simply use the '+' operator.
  6467. *
  6468. * @param {Object|number|string|boolean=} opt_a1 Optional first initial item
  6469. * to append.
  6470. * @param {...Object|number|string|boolean} var_args Other initial items to
  6471. * append, e.g., new goog.string.StringBuffer('foo', 'bar').
  6472. * @constructor
  6473. */
  6474. goog.string.StringBuffer = function(opt_a1, var_args) {
  6475. /**
  6476. * Internal buffer for the string to be concatenated.
  6477. * @type {string|Array}
  6478. * @private
  6479. */
  6480. this.buffer_ = goog.userAgent.jscript.HAS_JSCRIPT ? [] : '';
  6481. if (opt_a1 != _NULL) {
  6482. this.append.apply(this, arguments);
  6483. }
  6484. };
  6485. /**
  6486. * Sets the contents of the string buffer object, replacing what's currently
  6487. * there.
  6488. *
  6489. * @param {string} s String to set.
  6490. */
  6491. goog.string.StringBuffer.prototype.set = function(s) {
  6492. this.clear();
  6493. this.append(s);
  6494. };
  6495. if (goog.userAgent.jscript.HAS_JSCRIPT) {
  6496. /**
  6497. * Length of internal buffer (faster than calling buffer_.length).
  6498. * Only used if buffer_ is an array.
  6499. * @type {number}
  6500. * @private
  6501. */
  6502. goog.string.StringBuffer.prototype.bufferLength_ = 0;
  6503. /**
  6504. * Appends one or more items to the buffer.
  6505. *
  6506. * Calling this with null, undefined, or empty arguments is an error.
  6507. *
  6508. * @param {Object|number|string|boolean} a1 Required first string.
  6509. * @param {Object|number|string|boolean=} opt_a2 Optional second string.
  6510. * @param {...Object|number|string|boolean} var_args Other items to append,
  6511. * e.g., sb.append('foo', 'bar', 'baz').
  6512. * @return {goog.string.StringBuffer} This same StringBuffer object.
  6513. */
  6514. goog.string.StringBuffer.prototype.append = function(a1, opt_a2, var_args) {
  6515. // IE version.
  6516. if (opt_a2 == _NULL) { // second argument is undefined (null == undefined)
  6517. // Array assignment is 2x faster than Array push. Also, use a1
  6518. // directly to avoid arguments instantiation, another 2x improvement.
  6519. this.buffer_[this.bufferLength_++] = a1;
  6520. } else {
  6521. this.buffer_.push.apply(/** @type {Array} */ (this.buffer_), arguments);
  6522. this.bufferLength_ = this.buffer_.length;
  6523. }
  6524. return this;
  6525. };
  6526. } else {
  6527. /**
  6528. * Appends one or more items to the buffer.
  6529. *
  6530. * Calling this with null, undefined, or empty arguments is an error.
  6531. *
  6532. * @param {Object|number|string|boolean} a1 Required first string.
  6533. * @param {Object|number|string|boolean=} opt_a2 Optional second string.
  6534. * @param {...Object|number|string|boolean} var_args Other items to append,
  6535. * e.g., sb.append('foo', 'bar', 'baz').
  6536. * @return {goog.string.StringBuffer} This same StringBuffer object.
  6537. * @suppress {duplicate}
  6538. */
  6539. goog.string.StringBuffer.prototype.append = function(a1, opt_a2, var_args) {
  6540. // W3 version.
  6541. // Use a1 directly to avoid arguments instantiation for single-arg case.
  6542. this.buffer_ += a1;
  6543. if (opt_a2 != _NULL) { // second argument is undefined (null == undefined)
  6544. for (var i = 1; i < arguments.length; i++) {
  6545. this.buffer_ += arguments[i];
  6546. }
  6547. }
  6548. return this;
  6549. };
  6550. }
  6551. /**
  6552. * Clears the internal buffer.
  6553. */
  6554. goog.string.StringBuffer.prototype.clear = function() {
  6555. if (goog.userAgent.jscript.HAS_JSCRIPT) {
  6556. this.buffer_.length = 0; // Reuse the array to avoid creating new object.
  6557. this.bufferLength_ = 0;
  6558. } else {
  6559. this.buffer_ = '';
  6560. }
  6561. };
  6562. /**
  6563. * Returns the length of the current contents of the buffer. In IE, this is
  6564. * O(n) where n = number of appends, so to avoid quadratic behavior, do not call
  6565. * this after every append.
  6566. *
  6567. * @return {number} the length of the current contents of the buffer.
  6568. */
  6569. goog.string.StringBuffer.prototype.getLength = function() {
  6570. return this.toString().length;
  6571. };
  6572. /**
  6573. * Returns the concatenated string.
  6574. *
  6575. * @return {string} The concatenated string.
  6576. */
  6577. goog.string.StringBuffer.prototype.toString = function() {
  6578. if (goog.userAgent.jscript.HAS_JSCRIPT) {
  6579. var str = this.buffer_.join('');
  6580. // Given a string with the entire contents, simplify the StringBuffer by
  6581. // setting its contents to only be this string, rather than many fragments.
  6582. this.clear();
  6583. if (str) {
  6584. this.append(str);
  6585. }
  6586. return str;
  6587. } else {
  6588. return /** @type {string} */ (this.buffer_);
  6589. }
  6590. };
  6591. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  6592. //
  6593. // Licensed under the Apache License, Version 2.0 (the "License");
  6594. // you may not use this file except in compliance with the License.
  6595. // You may obtain a copy of the License at
  6596. //
  6597. // http://www.apache.org/licenses/LICENSE-2.0
  6598. //
  6599. // Unless required by applicable law or agreed to in writing, software
  6600. // distributed under the License is distributed on an "AS-IS" BASIS,
  6601. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6602. // See the License for the specific language governing permissions and
  6603. // limitations under the License.
  6604. /**
  6605. * @fileoverview Simple struct for endpoints of a range.
  6606. *
  6607. * @author robbyw@google.com (Robby Walker)
  6608. */
  6609. goog.provide('goog.dom.RangeEndpoint');
  6610. /**
  6611. * Constants for selection endpoints.
  6612. * @enum {number}
  6613. */
  6614. goog.dom.RangeEndpoint = {
  6615. START: 1,
  6616. END: 0
  6617. };
  6618. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  6619. //
  6620. // Licensed under the Apache License, Version 2.0 (the "License");
  6621. // you may not use this file except in compliance with the License.
  6622. // You may obtain a copy of the License at
  6623. //
  6624. // http://www.apache.org/licenses/LICENSE-2.0
  6625. //
  6626. // Unless required by applicable law or agreed to in writing, software
  6627. // distributed under the License is distributed on an "AS-IS" BASIS,
  6628. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6629. // See the License for the specific language governing permissions and
  6630. // limitations under the License.
  6631. /**
  6632. * @fileoverview Definition of the browser range interface.
  6633. *
  6634. * DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
  6635. *
  6636. * @author robbyw@google.com (Robby Walker)
  6637. * @author ojan@google.com (Ojan Vafai)
  6638. * @author jparent@google.com (Julie Parent)
  6639. */
  6640. goog.provide('goog.dom.browserrange.AbstractRange');
  6641. //goog.require('goog.dom');
  6642. //goog.require('goog.dom.NodeType');
  6643. //goog.require('goog.dom.RangeEndpoint');
  6644. //goog.require('goog.dom.TagName');
  6645. //goog.require('goog.dom.TextRangeIterator');
  6646. //goog.require('goog.iter');
  6647. //goog.require('goog.string');
  6648. //goog.require('goog.string.StringBuffer');
  6649. //goog.require('goog.userAgent');
  6650. /**
  6651. * The constructor for abstract ranges. Don't call this from subclasses.
  6652. * @constructor
  6653. */
  6654. goog.dom.browserrange.AbstractRange = function() {
  6655. };
  6656. /**
  6657. * @return {goog.dom.browserrange.AbstractRange} A clone of this range.
  6658. */
  6659. goog.dom.browserrange.AbstractRange.prototype.clone = goog.abstractMethod;
  6660. /**
  6661. * Returns the browser native implementation of the range. Please refrain from
  6662. * using this function - if you find you need the range please add wrappers for
  6663. * the functionality you need rather than just using the native range.
  6664. * @return {Range|TextRange} The browser native range object.
  6665. */
  6666. goog.dom.browserrange.AbstractRange.prototype.getBrowserRange =
  6667. goog.abstractMethod;
  6668. /**
  6669. * Returns the deepest node in the tree that contains the entire range.
  6670. * @return {Node} The deepest node that contains the entire range.
  6671. */
  6672. goog.dom.browserrange.AbstractRange.prototype.getContainer =
  6673. goog.abstractMethod;
  6674. /**
  6675. * Returns the node the range starts in.
  6676. * @return {Node} The element or text node the range starts in.
  6677. */
  6678. goog.dom.browserrange.AbstractRange.prototype.getStartNode =
  6679. goog.abstractMethod;
  6680. /**
  6681. * Returns the offset into the node the range starts in.
  6682. * @return {number} The offset into the node the range starts in. For text
  6683. * nodes, this is an offset into the node value. For elements, this is
  6684. * an offset into the childNodes array.
  6685. */
  6686. goog.dom.browserrange.AbstractRange.prototype.getStartOffset =
  6687. goog.abstractMethod;
  6688. /**
  6689. * Returns the node the range ends in.
  6690. * @return {Node} The element or text node the range ends in.
  6691. */
  6692. goog.dom.browserrange.AbstractRange.prototype.getEndNode =
  6693. goog.abstractMethod;
  6694. /**
  6695. * Returns the offset into the node the range ends in.
  6696. * @return {number} The offset into the node the range ends in. For text
  6697. * nodes, this is an offset into the node value. For elements, this is
  6698. * an offset into the childNodes array.
  6699. */
  6700. goog.dom.browserrange.AbstractRange.prototype.getEndOffset =
  6701. goog.abstractMethod;
  6702. /**
  6703. * Compares one endpoint of this range with the endpoint of another browser
  6704. * native range object.
  6705. * @param {Range|TextRange} range The browser native range to compare against.
  6706. * @param {goog.dom.RangeEndpoint} thisEndpoint The endpoint of this range
  6707. * to compare with.
  6708. * @param {goog.dom.RangeEndpoint} otherEndpoint The endpoint of the other
  6709. * range to compare with.
  6710. * @return {number} 0 if the endpoints are equal, negative if this range
  6711. * endpoint comes before the other range endpoint, and positive otherwise.
  6712. */
  6713. goog.dom.browserrange.AbstractRange.prototype.compareBrowserRangeEndpoints =
  6714. goog.abstractMethod;
  6715. /**
  6716. * Tests if this range contains the given range.
  6717. * @param {goog.dom.browserrange.AbstractRange} abstractRange The range to test.
  6718. * @param {boolean=} opt_allowPartial If not set or _FALSE, the range must be
  6719. * entirely contained in the selection for this function to return true.
  6720. * @return {boolean} Whether this range contains the given range.
  6721. */
  6722. goog.dom.browserrange.AbstractRange.prototype.containsRange =
  6723. function(abstractRange, opt_allowPartial) {
  6724. // IE sometimes misreports the boundaries for collapsed ranges. So if the
  6725. // other range is collapsed, make sure the whole range is contained. This is
  6726. // logically equivalent, and works around IE's bug.
  6727. var checkPartial = opt_allowPartial && !abstractRange.isCollapsed();
  6728. var range = abstractRange.getBrowserRange();
  6729. var start = goog.dom.RangeEndpoint.START, end = goog.dom.RangeEndpoint.END;
  6730. /** {@preserveTry} */
  6731. try {
  6732. if (checkPartial) {
  6733. // There are two ways to not overlap. Being before, and being after.
  6734. // Before is represented by this.end before range.start: comparison < 0.
  6735. // After is represented by this.start after range.end: comparison > 0.
  6736. // The below is the negation of not overlapping.
  6737. return this.compareBrowserRangeEndpoints(range, end, start) >= 0 &&
  6738. this.compareBrowserRangeEndpoints(range, start, end) <= 0;
  6739. } else {
  6740. // Return true if this range bounds the parameter range from both sides.
  6741. return this.compareBrowserRangeEndpoints(range, end, end) >= 0 &&
  6742. this.compareBrowserRangeEndpoints(range, start, start) <= 0;
  6743. }
  6744. } catch (e) {
  6745. if (!goog.userAgent.IE) {
  6746. throw e;
  6747. }
  6748. // IE sometimes throws exceptions when one range is invalid, i.e. points
  6749. // to a node that has been removed from the document. Return _FALSE in this
  6750. // case.
  6751. return _FALSE;
  6752. }
  6753. };
  6754. /**
  6755. * Tests if this range contains the given node.
  6756. * @param {Node} node The node to test.
  6757. * @param {boolean=} opt_allowPartial If not set or _FALSE, the node must be
  6758. * entirely contained in the selection for this function to return true.
  6759. * @return {boolean} Whether this range contains the given node.
  6760. */
  6761. goog.dom.browserrange.AbstractRange.prototype.containsNode = function(node,
  6762. opt_allowPartial) {
  6763. return this.containsRange(
  6764. goog.dom.browserrange.createRangeFromNodeContents(node),
  6765. opt_allowPartial);
  6766. };
  6767. /**
  6768. * Tests if the selection is collapsed - i.e. is just a caret.
  6769. * @return {boolean} Whether the range is collapsed.
  6770. */
  6771. goog.dom.browserrange.AbstractRange.prototype.isCollapsed =
  6772. goog.abstractMethod;
  6773. /**
  6774. * @return {string} The text content of the range.
  6775. */
  6776. goog.dom.browserrange.AbstractRange.prototype.getText =
  6777. goog.abstractMethod;
  6778. /**
  6779. * Returns the HTML fragment this range selects. This is slow on all browsers.
  6780. * @return {string} HTML fragment of the range, does not include context
  6781. * containing elements.
  6782. */
  6783. goog.dom.browserrange.AbstractRange.prototype.getHtmlFragment = function() {
  6784. var output = new goog.string.StringBuffer();
  6785. goog.iter.forEach(this, function(node, ignore, it) {
  6786. if (node.nodeType == goog.dom.NodeType.TEXT) {
  6787. output.append(goog.string.htmlEscape(node.nodeValue.substring(
  6788. it.getStartTextOffset(), it.getEndTextOffset())));
  6789. } else if (node.nodeType == goog.dom.NodeType.ELEMENT) {
  6790. if (it.isEndTag()) {
  6791. if (goog.dom.canHaveChildren(node)) {
  6792. output.append('</' + node.tagName + '>');
  6793. }
  6794. } else {
  6795. var shallow = node.cloneNode(_FALSE);
  6796. var html = goog.dom.getOuterHtml(shallow);
  6797. if (goog.userAgent.IE && node.tagName == goog.dom.TagName.LI) {
  6798. // For an LI, IE just returns "<li>" with no closing tag
  6799. output.append(html);
  6800. } else {
  6801. var index = html.lastIndexOf('<');
  6802. output.append(index ? html.substr(0, index) : html);
  6803. }
  6804. }
  6805. }
  6806. }, this);
  6807. return output.toString();
  6808. };
  6809. /**
  6810. * Returns valid HTML for this range. This is fast on IE, and semi-fast on
  6811. * other browsers.
  6812. * @return {string} Valid HTML of the range, including context containing
  6813. * elements.
  6814. */
  6815. goog.dom.browserrange.AbstractRange.prototype.getValidHtml =
  6816. goog.abstractMethod;
  6817. /**
  6818. * Returns a RangeIterator over the contents of the range. Regardless of the
  6819. * direction of the range, the iterator will move in document order.
  6820. * @param {boolean=} opt_keys Unused for this iterator.
  6821. * @return {goog.dom.RangeIterator} An iterator over tags in the range.
  6822. */
  6823. goog.dom.browserrange.AbstractRange.prototype.__iterator__ = function(
  6824. opt_keys) {
  6825. return new goog.dom.TextRangeIterator(this.getStartNode(),
  6826. this.getStartOffset(), this.getEndNode(), this.getEndOffset());
  6827. };
  6828. // SELECTION MODIFICATION
  6829. /**
  6830. * Set this range as the selection in its window.
  6831. * @param {boolean=} opt_reverse Whether to select the range in reverse,
  6832. * if possible.
  6833. */
  6834. goog.dom.browserrange.AbstractRange.prototype.select =
  6835. goog.abstractMethod;
  6836. /**
  6837. * Removes the contents of the range from the document. As a side effect, the
  6838. * selection will be collapsed. The behavior of content removal is normalized
  6839. * across browsers. For instance, IE sometimes creates extra text nodes that
  6840. * a W3C browser does not. That behavior is corrected for.
  6841. */
  6842. goog.dom.browserrange.AbstractRange.prototype.removeContents =
  6843. goog.abstractMethod;
  6844. /**
  6845. * Surrounds the text range with the specified element (on Mozilla) or with a
  6846. * clone of the specified element (on IE). Returns a reference to the
  6847. * surrounding element if the operation was successful; returns null if the
  6848. * operation failed.
  6849. * @param {Element} element The element with which the selection is to be
  6850. * surrounded.
  6851. * @return {Element} The surrounding element (same as the argument on Mozilla,
  6852. * but not on IE), or null if unsuccessful.
  6853. */
  6854. goog.dom.browserrange.AbstractRange.prototype.surroundContents =
  6855. goog.abstractMethod;
  6856. /**
  6857. * Inserts a node before (or after) the range. The range may be disrupted
  6858. * beyond recovery because of the way this splits nodes.
  6859. * @param {Node} node The node to insert.
  6860. * @param {boolean} before True to insert before, _FALSE to insert after.
  6861. * @return {Node} The node added to the document. This may be different
  6862. * than the node parameter because on IE we have to clone it.
  6863. */
  6864. goog.dom.browserrange.AbstractRange.prototype.insertNode =
  6865. goog.abstractMethod;
  6866. /**
  6867. * Surrounds this range with the two given nodes. The range may be disrupted
  6868. * beyond recovery because of the way this splits nodes.
  6869. * @param {Element} startNode The node to insert at the start.
  6870. * @param {Element} endNode The node to insert at the end.
  6871. */
  6872. goog.dom.browserrange.AbstractRange.prototype.surroundWithNodes =
  6873. goog.abstractMethod;
  6874. /**
  6875. * Collapses the range to one of its boundary points.
  6876. * @param {boolean} toStart Whether to collapse to the start of the range.
  6877. */
  6878. goog.dom.browserrange.AbstractRange.prototype.collapse =
  6879. goog.abstractMethod;
  6880. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  6881. //
  6882. // Licensed under the Apache License, Version 2.0 (the "License");
  6883. // you may not use this file except in compliance with the License.
  6884. // You may obtain a copy of the License at
  6885. //
  6886. // http://www.apache.org/licenses/LICENSE-2.0
  6887. //
  6888. // Unless required by applicable law or agreed to in writing, software
  6889. // distributed under the License is distributed on an "AS-IS" BASIS,
  6890. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6891. // See the License for the specific language governing permissions and
  6892. // limitations under the License.
  6893. /**
  6894. * @fileoverview Definition of the W3C spec following range wrapper.
  6895. *
  6896. * DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
  6897. *
  6898. * @author robbyw@google.com (Robby Walker)
  6899. * @author ojan@google.com (Ojan Vafai)
  6900. * @author jparent@google.com (Julie Parent)
  6901. */
  6902. goog.provide('goog.dom.browserrange.W3cRange');
  6903. //goog.require('goog.dom');
  6904. //goog.require('goog.dom.NodeType');
  6905. //goog.require('goog.dom.RangeEndpoint');
  6906. //goog.require('goog.dom.browserrange.AbstractRange');
  6907. //goog.require('goog.string');
  6908. /**
  6909. * The constructor for W3C specific browser ranges.
  6910. * @param {Range} range The range object.
  6911. * @constructor
  6912. * @extends {goog.dom.browserrange.AbstractRange}
  6913. */
  6914. goog.dom.browserrange.W3cRange = function(range) {
  6915. this.range_ = range;
  6916. };
  6917. goog.inherits(goog.dom.browserrange.W3cRange,
  6918. goog.dom.browserrange.AbstractRange);
  6919. /**
  6920. * Returns a browser range spanning the given node's contents.
  6921. * @param {Node} node The node to select.
  6922. * @return {Range} A browser range spanning the node's contents.
  6923. * @protected
  6924. */
  6925. goog.dom.browserrange.W3cRange.getBrowserRangeForNode = function(node) {
  6926. var nodeRange = goog.dom.getOwnerDocument(node).createRange();
  6927. if (node.nodeType == goog.dom.NodeType.TEXT) {
  6928. nodeRange.setStart(node, 0);
  6929. nodeRange.setEnd(node, node.length);
  6930. } else {
  6931. if (!goog.dom.browserrange.canContainRangeEndpoint(node)) {
  6932. var rangeParent = node.parentNode;
  6933. var rangeStartOffset = goog.array.indexOf(rangeParent.childNodes, node);
  6934. nodeRange.setStart(rangeParent, rangeStartOffset);
  6935. nodeRange.setEnd(rangeParent, rangeStartOffset + 1);
  6936. } else {
  6937. var tempNode, leaf = node;
  6938. while ((tempNode = leaf.firstChild) &&
  6939. goog.dom.browserrange.canContainRangeEndpoint(tempNode)) {
  6940. leaf = tempNode;
  6941. }
  6942. nodeRange.setStart(leaf, 0);
  6943. leaf = node;
  6944. while ((tempNode = leaf.lastChild) &&
  6945. goog.dom.browserrange.canContainRangeEndpoint(tempNode)) {
  6946. leaf = tempNode;
  6947. }
  6948. nodeRange.setEnd(leaf, leaf.nodeType == goog.dom.NodeType.ELEMENT ?
  6949. leaf.childNodes.length : leaf.length);
  6950. }
  6951. }
  6952. return nodeRange;
  6953. };
  6954. /**
  6955. * Returns a browser range spanning the given nodes.
  6956. * @param {Node} startNode The node to start with - should not be a BR.
  6957. * @param {number} startOffset The offset within the start node.
  6958. * @param {Node} endNode The node to end with - should not be a BR.
  6959. * @param {number} endOffset The offset within the end node.
  6960. * @return {Range} A browser range spanning the node's contents.
  6961. * @protected
  6962. */
  6963. goog.dom.browserrange.W3cRange.getBrowserRangeForNodes = function(startNode,
  6964. startOffset, endNode, endOffset) {
  6965. // Create and return the range.
  6966. var nodeRange = goog.dom.getOwnerDocument(startNode).createRange();
  6967. nodeRange.setStart(startNode, startOffset);
  6968. nodeRange.setEnd(endNode, endOffset);
  6969. return nodeRange;
  6970. };
  6971. /**
  6972. * Creates a range object that selects the given node's text.
  6973. * @param {Node} node The node to select.
  6974. * @return {goog.dom.browserrange.W3cRange} A Gecko range wrapper object.
  6975. */
  6976. goog.dom.browserrange.W3cRange.createFromNodeContents = function(node) {
  6977. return new goog.dom.browserrange.W3cRange(
  6978. goog.dom.browserrange.W3cRange.getBrowserRangeForNode(node));
  6979. };
  6980. /**
  6981. * Creates a range object that selects between the given nodes.
  6982. * @param {Node} startNode The node to start with.
  6983. * @param {number} startOffset The offset within the start node.
  6984. * @param {Node} endNode The node to end with.
  6985. * @param {number} endOffset The offset within the end node.
  6986. * @return {goog.dom.browserrange.W3cRange} A wrapper object.
  6987. */
  6988. goog.dom.browserrange.W3cRange.createFromNodes = function(startNode,
  6989. startOffset, endNode, endOffset) {
  6990. return new goog.dom.browserrange.W3cRange(
  6991. goog.dom.browserrange.W3cRange.getBrowserRangeForNodes(startNode,
  6992. startOffset, endNode, endOffset));
  6993. };
  6994. /**
  6995. * @return {goog.dom.browserrange.W3cRange} A clone of this range.
  6996. */
  6997. goog.dom.browserrange.W3cRange.prototype.clone = function() {
  6998. return new this.constructor(this.range_.cloneRange());
  6999. };
  7000. /** @inheritDoc */
  7001. goog.dom.browserrange.W3cRange.prototype.getBrowserRange = function() {
  7002. return this.range_;
  7003. };
  7004. /** @inheritDoc */
  7005. goog.dom.browserrange.W3cRange.prototype.getContainer = function() {
  7006. return this.range_.commonAncestorContainer;
  7007. };
  7008. /** @inheritDoc */
  7009. goog.dom.browserrange.W3cRange.prototype.getStartNode = function() {
  7010. return this.range_.startContainer;
  7011. };
  7012. /** @inheritDoc */
  7013. goog.dom.browserrange.W3cRange.prototype.getStartOffset = function() {
  7014. return this.range_.startOffset;
  7015. };
  7016. /** @inheritDoc */
  7017. goog.dom.browserrange.W3cRange.prototype.getEndNode = function() {
  7018. return this.range_.endContainer;
  7019. };
  7020. /** @inheritDoc */
  7021. goog.dom.browserrange.W3cRange.prototype.getEndOffset = function() {
  7022. return this.range_.endOffset;
  7023. };
  7024. /** @inheritDoc */
  7025. goog.dom.browserrange.W3cRange.prototype.compareBrowserRangeEndpoints =
  7026. function(range, thisEndpoint, otherEndpoint) {
  7027. return this.range_.compareBoundaryPoints(
  7028. otherEndpoint == goog.dom.RangeEndpoint.START ?
  7029. (thisEndpoint == goog.dom.RangeEndpoint.START ?
  7030. goog.global['Range'].START_TO_START :
  7031. goog.global['Range'].START_TO_END) :
  7032. (thisEndpoint == goog.dom.RangeEndpoint.START ?
  7033. goog.global['Range'].END_TO_START :
  7034. goog.global['Range'].END_TO_END),
  7035. /** @type {Range} */ (range));
  7036. };
  7037. /** @inheritDoc */
  7038. goog.dom.browserrange.W3cRange.prototype.isCollapsed = function() {
  7039. return this.range_.collapsed;
  7040. };
  7041. /** @inheritDoc */
  7042. goog.dom.browserrange.W3cRange.prototype.getText = function() {
  7043. return this.range_.toString();
  7044. };
  7045. /** @inheritDoc */
  7046. goog.dom.browserrange.W3cRange.prototype.getValidHtml = function() {
  7047. var div = goog.dom.getDomHelper(this.range_.startContainer).createDom('div');
  7048. div.appendChild(this.range_.cloneContents());
  7049. var result = div.innerHTML;
  7050. if (goog.string.startsWith(result, '<') ||
  7051. !this.isCollapsed() && !goog.string.contains(result, '<')) {
  7052. // We attempt to mimic IE, which returns no containing element when a
  7053. // only text nodes are selected, does return the containing element when
  7054. // the selection is empty, and does return the element when multiple nodes
  7055. // are selected.
  7056. return result;
  7057. }
  7058. var container = this.getContainer();
  7059. container = container.nodeType == goog.dom.NodeType.ELEMENT ? container :
  7060. container.parentNode;
  7061. var html = goog.dom.getOuterHtml(
  7062. /** @type {Element} */ (container.cloneNode(_FALSE)));
  7063. return html.replace('>', '>' + result);
  7064. };
  7065. // SELECTION MODIFICATION
  7066. /** @inheritDoc */
  7067. goog.dom.browserrange.W3cRange.prototype.select = function(reverse) {
  7068. var win = goog.dom.getWindow(goog.dom.getOwnerDocument(this.getStartNode()));
  7069. this.selectInternal(win.getSelection(), reverse);
  7070. };
  7071. /**
  7072. * Select this range.
  7073. * @param {Selection} selection Browser selection object.
  7074. * @param {*} reverse Whether to select this range in reverse.
  7075. * @protected
  7076. */
  7077. goog.dom.browserrange.W3cRange.prototype.selectInternal = function(selection,
  7078. reverse) {
  7079. // Browser-specific tricks are needed to create reversed selections
  7080. // programatically. For this generic W3C codepath, ignore the reverse
  7081. // parameter.
  7082. selection.removeAllRanges();
  7083. selection.addRange(this.range_);
  7084. };
  7085. /** @inheritDoc */
  7086. goog.dom.browserrange.W3cRange.prototype.removeContents = function() {
  7087. var range = this.range_;
  7088. range.extractContents();
  7089. if (range.startContainer.hasChildNodes()) {
  7090. // Remove any now empty nodes surrounding the extracted contents.
  7091. var rangeStartContainer =
  7092. range.startContainer.childNodes[range.startOffset];
  7093. if (rangeStartContainer) {
  7094. var rangePrevious = rangeStartContainer.previousSibling;
  7095. if (goog.dom.getRawTextContent(rangeStartContainer) == '') {
  7096. goog.dom.removeNode(rangeStartContainer);
  7097. }
  7098. if (rangePrevious && goog.dom.getRawTextContent(rangePrevious) == '') {
  7099. goog.dom.removeNode(rangePrevious);
  7100. }
  7101. }
  7102. }
  7103. };
  7104. /** @inheritDoc */
  7105. goog.dom.browserrange.W3cRange.prototype.surroundContents = function(element) {
  7106. this.range_.surroundContents(element);
  7107. return element;
  7108. };
  7109. /** @inheritDoc */
  7110. goog.dom.browserrange.W3cRange.prototype.insertNode = function(node, before) {
  7111. var range = this.range_.cloneRange();
  7112. range.collapse(before);
  7113. range.insertNode(node);
  7114. range.detach();
  7115. return node;
  7116. };
  7117. /** @inheritDoc */
  7118. goog.dom.browserrange.W3cRange.prototype.surroundWithNodes = function(
  7119. startNode, endNode) {
  7120. var win = goog.dom.getWindow(
  7121. goog.dom.getOwnerDocument(this.getStartNode()));
  7122. var selectionRange = goog.dom.Range.createFromWindow(win);
  7123. if (selectionRange) {
  7124. var sNode = selectionRange.getStartNode();
  7125. var eNode = selectionRange.getEndNode();
  7126. var sOffset = selectionRange.getStartOffset();
  7127. var eOffset = selectionRange.getEndOffset();
  7128. }
  7129. var clone1 = this.range_.cloneRange();
  7130. var clone2 = this.range_.cloneRange();
  7131. clone1.collapse(_FALSE);
  7132. clone2.collapse(_TRUE);
  7133. clone1.insertNode(endNode);
  7134. clone2.insertNode(startNode);
  7135. clone1.detach();
  7136. clone2.detach();
  7137. if (selectionRange) {
  7138. // There are 4 ways that surroundWithNodes can wreck the saved
  7139. // selection object. All of them happen when an inserted node splits
  7140. // a text node, and one of the end points of the selection was in the
  7141. // latter half of that text node.
  7142. //
  7143. // Clients of this library should use saveUsingCarets to avoid this
  7144. // problem. Unfortunately, saveUsingCarets uses this method, so that's
  7145. // not really an option for us. :( We just recompute the offsets.
  7146. var isInsertedNode = function(n) {
  7147. return n == startNode || n == endNode;
  7148. };
  7149. if (sNode.nodeType == goog.dom.NodeType.TEXT) {
  7150. while (sOffset > sNode.length) {
  7151. sOffset -= sNode.length;
  7152. do {
  7153. sNode = sNode.nextSibling;
  7154. } while (isInsertedNode(sNode));
  7155. }
  7156. }
  7157. if (eNode.nodeType == goog.dom.NodeType.TEXT) {
  7158. while (eOffset > eNode.length) {
  7159. eOffset -= eNode.length;
  7160. do {
  7161. eNode = eNode.nextSibling;
  7162. } while (isInsertedNode(eNode));
  7163. }
  7164. }
  7165. goog.dom.Range.createFromNodes(
  7166. sNode, /** @type {number} */ (sOffset),
  7167. eNode, /** @type {number} */ (eOffset)).select();
  7168. }
  7169. };
  7170. /** @inheritDoc */
  7171. goog.dom.browserrange.W3cRange.prototype.collapse = function(toStart) {
  7172. this.range_.collapse(toStart);
  7173. };
  7174. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  7175. //
  7176. // Licensed under the Apache License, Version 2.0 (the "License");
  7177. // you may not use this file except in compliance with the License.
  7178. // You may obtain a copy of the License at
  7179. //
  7180. // http://www.apache.org/licenses/LICENSE-2.0
  7181. //
  7182. // Unless required by applicable law or agreed to in writing, software
  7183. // distributed under the License is distributed on an "AS-IS" BASIS,
  7184. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7185. // See the License for the specific language governing permissions and
  7186. // limitations under the License.
  7187. /**
  7188. * @fileoverview Definition of the WebKit specific range wrapper. Inherits most
  7189. * functionality from W3CRange, but adds exceptions as necessary.
  7190. *
  7191. * DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
  7192. *
  7193. * @author robbyw@google.com (Robby Walker)
  7194. */
  7195. goog.provide('goog.dom.browserrange.WebKitRange');
  7196. //goog.require('goog.dom.RangeEndpoint');
  7197. //goog.require('goog.dom.browserrange.W3cRange');
  7198. //goog.require('goog.userAgent');
  7199. /**
  7200. * The constructor for WebKit specific browser ranges.
  7201. * @param {Range} range The range object.
  7202. * @constructor
  7203. * @extends {goog.dom.browserrange.W3cRange}
  7204. */
  7205. goog.dom.browserrange.WebKitRange = function(range) {
  7206. goog.dom.browserrange.W3cRange.call(this, range);
  7207. };
  7208. goog.inherits(goog.dom.browserrange.WebKitRange,
  7209. goog.dom.browserrange.W3cRange);
  7210. /**
  7211. * Creates a range object that selects the given node's text.
  7212. * @param {Node} node The node to select.
  7213. * @return {goog.dom.browserrange.WebKitRange} A WebKit range wrapper object.
  7214. */
  7215. goog.dom.browserrange.WebKitRange.createFromNodeContents = function(node) {
  7216. return new goog.dom.browserrange.WebKitRange(
  7217. goog.dom.browserrange.W3cRange.getBrowserRangeForNode(node));
  7218. };
  7219. /**
  7220. * Creates a range object that selects between the given nodes.
  7221. * @param {Node} startNode The node to start with.
  7222. * @param {number} startOffset The offset within the start node.
  7223. * @param {Node} endNode The node to end with.
  7224. * @param {number} endOffset The offset within the end node.
  7225. * @return {goog.dom.browserrange.WebKitRange} A wrapper object.
  7226. */
  7227. goog.dom.browserrange.WebKitRange.createFromNodes = function(startNode,
  7228. startOffset, endNode, endOffset) {
  7229. return new goog.dom.browserrange.WebKitRange(
  7230. goog.dom.browserrange.W3cRange.getBrowserRangeForNodes(startNode,
  7231. startOffset, endNode, endOffset));
  7232. };
  7233. /** @inheritDoc */
  7234. goog.dom.browserrange.WebKitRange.prototype.compareBrowserRangeEndpoints =
  7235. function(range, thisEndpoint, otherEndpoint) {
  7236. // Webkit pre-528 has some bugs where compareBoundaryPoints() doesn't work the
  7237. // way it is supposed to, but if we reverse the sense of two comparisons,
  7238. // it works fine.
  7239. // https://bugs.webkit.org/show_bug.cgi?id=20738
  7240. if (goog.userAgent.isVersion('528')) {
  7241. return (goog.dom.browserrange.WebKitRange.superClass_.
  7242. compareBrowserRangeEndpoints.call(
  7243. this, range, thisEndpoint, otherEndpoint));
  7244. }
  7245. return this.range_.compareBoundaryPoints(
  7246. otherEndpoint == goog.dom.RangeEndpoint.START ?
  7247. (thisEndpoint == goog.dom.RangeEndpoint.START ?
  7248. goog.global['Range'].START_TO_START :
  7249. goog.global['Range'].END_TO_START) : // Sense reversed
  7250. (thisEndpoint == goog.dom.RangeEndpoint.START ?
  7251. goog.global['Range'].START_TO_END : // Sense reversed
  7252. goog.global['Range'].END_TO_END),
  7253. /** @type {Range} */ (range));
  7254. };
  7255. /** @inheritDoc */
  7256. goog.dom.browserrange.WebKitRange.prototype.selectInternal = function(
  7257. selection, reversed) {
  7258. // Unselect everything. This addresses a bug in Webkit where it sometimes
  7259. // caches the old selection.
  7260. // https://bugs.webkit.org/show_bug.cgi?id=20117
  7261. selection.removeAllRanges();
  7262. if (reversed) {
  7263. selection.setBaseAndExtent(this.getEndNode(), this.getEndOffset(),
  7264. this.getStartNode(), this.getStartOffset());
  7265. } else {
  7266. selection.setBaseAndExtent(this.getStartNode(), this.getStartOffset(),
  7267. this.getEndNode(), this.getEndOffset());
  7268. }
  7269. };
  7270. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  7271. //
  7272. // Licensed under the Apache License, Version 2.0 (the "License");
  7273. // you may not use this file except in compliance with the License.
  7274. // You may obtain a copy of the License at
  7275. //
  7276. // http://www.apache.org/licenses/LICENSE-2.0
  7277. //
  7278. // Unless required by applicable law or agreed to in writing, software
  7279. // distributed under the License is distributed on an "AS-IS" BASIS,
  7280. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7281. // See the License for the specific language governing permissions and
  7282. // limitations under the License.
  7283. /**
  7284. * @fileoverview Iterator subclass for DOM tree traversal.
  7285. *
  7286. * @author robbyw@google.com (Robby Walker)
  7287. */
  7288. goog.provide('goog.dom.NodeIterator');
  7289. //goog.require('goog.dom.TagIterator');
  7290. /**
  7291. * A DOM tree traversal iterator.
  7292. *
  7293. * Starting with the given node, the iterator walks the DOM in order, reporting
  7294. * events for each node. The iterator acts as a prefix iterator:
  7295. *
  7296. * <pre>
  7297. * &lt;div&gt;1&lt;span&gt;2&lt;/span&gt;3&lt;/div&gt;
  7298. * </pre>
  7299. *
  7300. * Will return the following nodes:
  7301. *
  7302. * <code>[div, 1, span, 2, 3]</code>
  7303. *
  7304. * With the following depths
  7305. *
  7306. * <code>[1, 1, 2, 2, 1]</code>
  7307. *
  7308. * Imagining <code>|</code> represents iterator position, the traversal stops at
  7309. * each of the following locations:
  7310. *
  7311. * <pre>&lt;div&gt;|1|&lt;span&gt;|2|&lt;/span&gt;3|&lt;/div&gt;</pre>
  7312. *
  7313. * The iterator can also be used in reverse mode, which will return the nodes
  7314. * and states in the opposite order. The depths will be slightly different
  7315. * since, like in normal mode, the depth is computed *after* the last move.
  7316. *
  7317. * Lastly, it is possible to create an iterator that is unconstrained, meaning
  7318. * that it will continue iterating until the end of the document instead of
  7319. * until exiting the start node.
  7320. *
  7321. * @param {Node=} opt_node The start node. Defaults to an empty iterator.
  7322. * @param {boolean=} opt_reversed Whether to traverse the tree in reverse.
  7323. * @param {boolean=} opt_unconstrained Whether the iterator is not constrained
  7324. * to the starting node and its children.
  7325. * @param {number=} opt_depth The starting tree depth.
  7326. * @constructor
  7327. * @extends {goog.dom.TagIterator}
  7328. */
  7329. goog.dom.NodeIterator = function(opt_node, opt_reversed,
  7330. opt_unconstrained, opt_depth) {
  7331. goog.dom.TagIterator.call(this, opt_node, opt_reversed, opt_unconstrained,
  7332. _NULL, opt_depth);
  7333. };
  7334. goog.inherits(goog.dom.NodeIterator, goog.dom.TagIterator);
  7335. /**
  7336. * Moves to the next position in the DOM tree.
  7337. * @return {Node} Returns the next node, or throws a goog.iter.StopIteration
  7338. * exception if the end of the iterator's range has been reached.
  7339. */
  7340. goog.dom.NodeIterator.prototype.next = function() {
  7341. do {
  7342. goog.dom.NodeIterator.superClass_.next.call(this);
  7343. } while (this.isEndTag());
  7344. return this.node;
  7345. };
  7346. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  7347. //
  7348. // Licensed under the Apache License, Version 2.0 (the "License");
  7349. // you may not use this file except in compliance with the License.
  7350. // You may obtain a copy of the License at
  7351. //
  7352. // http://www.apache.org/licenses/LICENSE-2.0
  7353. //
  7354. // Unless required by applicable law or agreed to in writing, software
  7355. // distributed under the License is distributed on an "AS-IS" BASIS,
  7356. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7357. // See the License for the specific language governing permissions and
  7358. // limitations under the License.
  7359. /**
  7360. * @fileoverview Definition of the IE browser specific range wrapper.
  7361. *
  7362. * DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
  7363. *
  7364. * @author robbyw@google.com (Robby Walker)
  7365. * @author ojan@google.com (Ojan Vafai)
  7366. * @author jparent@google.com (Julie Parent)
  7367. */
  7368. goog.provide('goog.dom.browserrange.IeRange');
  7369. //goog.require('goog.array');
  7370. //goog.require('goog.dom');
  7371. //goog.require('goog.dom.NodeIterator');
  7372. //goog.require('goog.dom.NodeType');
  7373. //goog.require('goog.dom.RangeEndpoint');
  7374. //goog.require('goog.dom.TagName');
  7375. //goog.require('goog.dom.browserrange.AbstractRange');
  7376. //goog.require('goog.iter');
  7377. //goog.require('goog.iter.StopIteration');
  7378. //goog.require('goog.string');
  7379. /**
  7380. * The constructor for IE specific browser ranges.
  7381. * @param {TextRange} range The range object.
  7382. * @param {Document} doc The document the range exists in.
  7383. * @constructor
  7384. * @extends {goog.dom.browserrange.AbstractRange}
  7385. */
  7386. goog.dom.browserrange.IeRange = function(range, doc) {
  7387. /**
  7388. * The browser range object this class wraps.
  7389. * @type {TextRange}
  7390. * @private
  7391. */
  7392. this.range_ = range;
  7393. /**
  7394. * The document the range exists in.
  7395. * @type {Document}
  7396. * @private
  7397. */
  7398. this.doc_ = doc;
  7399. };
  7400. goog.inherits(goog.dom.browserrange.IeRange,
  7401. goog.dom.browserrange.AbstractRange);
  7402. /**
  7403. * Returns a browser range spanning the given node's contents.
  7404. * @param {Node} node The node to select.
  7405. * @return {TextRange} A browser range spanning the node's contents.
  7406. * @private
  7407. */
  7408. goog.dom.browserrange.IeRange.getBrowserRangeForNode_ = function(node) {
  7409. var nodeRange = goog.dom.getOwnerDocument(node).body.createTextRange();
  7410. if (node.nodeType == goog.dom.NodeType.ELEMENT) {
  7411. // Elements are easy.
  7412. nodeRange.moveToElementText(node);
  7413. // Note(user) : If there are no child nodes of the element, the
  7414. // range.htmlText includes the element's outerHTML. The range created above
  7415. // is not collapsed, and should be collapsed explicitly.
  7416. // Example : node = <div></div>
  7417. // But if the node is sth like <br>, it shouldnt be collapsed.
  7418. if (goog.dom.browserrange.canContainRangeEndpoint(node) &&
  7419. !node.childNodes.length) {
  7420. nodeRange.collapse(_FALSE);
  7421. }
  7422. } else {
  7423. // Text nodes are hard.
  7424. // Compute the offset from the nearest element related position.
  7425. var offset = 0;
  7426. var sibling = node;
  7427. while (sibling = sibling.previousSibling) {
  7428. var nodeType = sibling.nodeType;
  7429. if (nodeType == goog.dom.NodeType.TEXT) {
  7430. offset += sibling.length;
  7431. } else if (nodeType == goog.dom.NodeType.ELEMENT) {
  7432. // Move to the space after this element.
  7433. nodeRange.moveToElementText(sibling);
  7434. break;
  7435. }
  7436. }
  7437. if (!sibling) {
  7438. nodeRange.moveToElementText(node.parentNode);
  7439. }
  7440. nodeRange.collapse(!sibling);
  7441. if (offset) {
  7442. nodeRange.move('character', offset);
  7443. }
  7444. nodeRange.moveEnd('character', node.length);
  7445. }
  7446. return nodeRange;
  7447. };
  7448. /**
  7449. * Returns a browser range spanning the given nodes.
  7450. * @param {Node} startNode The node to start with.
  7451. * @param {number} startOffset The offset within the start node.
  7452. * @param {Node} endNode The node to end with.
  7453. * @param {number} endOffset The offset within the end node.
  7454. * @return {TextRange} A browser range spanning the node's contents.
  7455. * @private
  7456. */
  7457. goog.dom.browserrange.IeRange.getBrowserRangeForNodes_ = function(startNode,
  7458. startOffset, endNode, endOffset) {
  7459. // Create a range starting at the correct start position.
  7460. var child, collapse = _FALSE;
  7461. if (startNode.nodeType == goog.dom.NodeType.ELEMENT) {
  7462. child = startNode.childNodes[startOffset];
  7463. collapse = !child;
  7464. startNode = child || startNode.lastChild || startNode;
  7465. startOffset = 0;
  7466. }
  7467. var leftRange = goog.dom.browserrange.IeRange.
  7468. getBrowserRangeForNode_(startNode);
  7469. // This happens only when startNode is a text node.
  7470. if (startOffset) {
  7471. leftRange.move('character', startOffset);
  7472. }
  7473. // The range movements in IE are still an approximation to the standard W3C
  7474. // behavior, and IE has its trickery when it comes to htmlText and text
  7475. // properties of the range. So we short-circuit computation whenever we can.
  7476. if (startNode == endNode && startOffset == endOffset) {
  7477. leftRange.collapse(_TRUE);
  7478. return leftRange;
  7479. }
  7480. // This can happen only when the startNode is an element, and there is no node
  7481. // at the given offset. We start at the last point inside the startNode in
  7482. // that case.
  7483. if (collapse) {
  7484. leftRange.collapse(_FALSE);
  7485. }
  7486. // Create a range that ends at the right position.
  7487. collapse = _FALSE;
  7488. if (endNode.nodeType == goog.dom.NodeType.ELEMENT) {
  7489. child = endNode.childNodes[endOffset];
  7490. endNode = child || endNode.lastChild || endNode;
  7491. endOffset = 0;
  7492. collapse = !child;
  7493. }
  7494. var rightRange = goog.dom.browserrange.IeRange.
  7495. getBrowserRangeForNode_(endNode);
  7496. rightRange.collapse(!collapse);
  7497. if (endOffset) {
  7498. rightRange.moveEnd('character', endOffset);
  7499. }
  7500. // Merge and return.
  7501. leftRange.setEndPoint('EndToEnd', rightRange);
  7502. return leftRange;
  7503. };
  7504. /**
  7505. * Create a range object that selects the given node's text.
  7506. * @param {Node} node The node to select.
  7507. * @return {goog.dom.browserrange.IeRange} An IE range wrapper object.
  7508. */
  7509. goog.dom.browserrange.IeRange.createFromNodeContents = function(node) {
  7510. var range = new goog.dom.browserrange.IeRange(
  7511. goog.dom.browserrange.IeRange.getBrowserRangeForNode_(node),
  7512. goog.dom.getOwnerDocument(node));
  7513. if (!goog.dom.browserrange.canContainRangeEndpoint(node)) {
  7514. range.startNode_ = range.endNode_ = range.parentNode_ = node.parentNode;
  7515. range.startOffset_ = goog.array.indexOf(range.parentNode_.childNodes, node);
  7516. range.endOffset_ = range.startOffset_ + 1;
  7517. } else {
  7518. // Note(user) : Emulate the behavior of W3CRange - Go to deepest possible
  7519. // range containers on both edges. It seems W3CRange did this to match the
  7520. // IE behavior, and now it is a circle. Changing W3CRange may break clients
  7521. // in all sorts of ways.
  7522. var tempNode, leaf = node;
  7523. while ((tempNode = leaf.firstChild) &&
  7524. goog.dom.browserrange.canContainRangeEndpoint(tempNode)) {
  7525. leaf = tempNode;
  7526. }
  7527. range.startNode_ = leaf;
  7528. range.startOffset_ = 0;
  7529. leaf = node;
  7530. while ((tempNode = leaf.lastChild) &&
  7531. goog.dom.browserrange.canContainRangeEndpoint(tempNode)) {
  7532. leaf = tempNode;
  7533. }
  7534. range.endNode_ = leaf;
  7535. range.endOffset_ = leaf.nodeType == goog.dom.NodeType.ELEMENT ?
  7536. leaf.childNodes.length : leaf.length;
  7537. range.parentNode_ = node;
  7538. }
  7539. return range;
  7540. };
  7541. /**
  7542. * Static method that returns the proper type of browser range.
  7543. * @param {Node} startNode The node to start with.
  7544. * @param {number} startOffset The offset within the start node.
  7545. * @param {Node} endNode The node to end with.
  7546. * @param {number} endOffset The offset within the end node.
  7547. * @return {goog.dom.browserrange.AbstractRange} A wrapper object.
  7548. */
  7549. goog.dom.browserrange.IeRange.createFromNodes = function(startNode,
  7550. startOffset, endNode, endOffset) {
  7551. var range = new goog.dom.browserrange.IeRange(
  7552. goog.dom.browserrange.IeRange.getBrowserRangeForNodes_(startNode,
  7553. startOffset, endNode, endOffset),
  7554. goog.dom.getOwnerDocument(startNode));
  7555. range.startNode_ = startNode;
  7556. range.startOffset_ = startOffset;
  7557. range.endNode_ = endNode;
  7558. range.endOffset_ = endOffset;
  7559. return range;
  7560. };
  7561. // Even though goog.dom.TextRange does similar caching to below, keeping these
  7562. // caches allows for better performance in the get*Offset methods.
  7563. /**
  7564. * Lazy cache of the node containing the entire selection.
  7565. * @type {Node}
  7566. * @private
  7567. */
  7568. goog.dom.browserrange.IeRange.prototype.parentNode_ = _NULL;
  7569. /**
  7570. * Lazy cache of the node containing the start of the selection.
  7571. * @type {Node}
  7572. * @private
  7573. */
  7574. goog.dom.browserrange.IeRange.prototype.startNode_ = _NULL;
  7575. /**
  7576. * Lazy cache of the node containing the end of the selection.
  7577. * @type {Node}
  7578. * @private
  7579. */
  7580. goog.dom.browserrange.IeRange.prototype.endNode_ = _NULL;
  7581. /**
  7582. * Lazy cache of the offset in startNode_ where this range starts.
  7583. * @type {number}
  7584. * @private
  7585. */
  7586. goog.dom.browserrange.IeRange.prototype.startOffset_ = -1;
  7587. /**
  7588. * Lazy cache of the offset in endNode_ where this range ends.
  7589. * @type {number}
  7590. * @private
  7591. */
  7592. goog.dom.browserrange.IeRange.prototype.endOffset_ = -1;
  7593. /**
  7594. * @return {goog.dom.browserrange.IeRange} A clone of this range.
  7595. */
  7596. goog.dom.browserrange.IeRange.prototype.clone = function() {
  7597. var range = new goog.dom.browserrange.IeRange(
  7598. this.range_.duplicate(), this.doc_);
  7599. range.parentNode_ = this.parentNode_;
  7600. range.startNode_ = this.startNode_;
  7601. range.endNode_ = this.endNode_;
  7602. return range;
  7603. };
  7604. /** @inheritDoc */
  7605. goog.dom.browserrange.IeRange.prototype.getBrowserRange = function() {
  7606. return this.range_;
  7607. };
  7608. /**
  7609. * Clears the cached values for containers.
  7610. * @private
  7611. */
  7612. goog.dom.browserrange.IeRange.prototype.clearCachedValues_ = function() {
  7613. this.parentNode_ = this.startNode_ = this.endNode_ = _NULL;
  7614. this.startOffset_ = this.endOffset_ = -1;
  7615. };
  7616. /** @inheritDoc */
  7617. goog.dom.browserrange.IeRange.prototype.getContainer = function() {
  7618. if (!this.parentNode_) {
  7619. var selectText = this.range_.text;
  7620. // If the selection ends with spaces, we need to remove these to get the
  7621. // parent container of only the real contents. This is to get around IE's
  7622. // inconsistency where it selects the spaces after a word when you double
  7623. // click, but leaves out the spaces during execCommands.
  7624. var range = this.range_.duplicate();
  7625. // We can't use goog.string.trimRight, as that will remove other whitespace
  7626. // too.
  7627. var rightTrimmedSelectText = selectText.replace(/ +$/, '');
  7628. var numSpacesAtEnd = selectText.length - rightTrimmedSelectText.length;
  7629. if (numSpacesAtEnd) {
  7630. range.moveEnd('character', -numSpacesAtEnd);
  7631. }
  7632. // Get the parent node. This should be the end, but alas, it is not.
  7633. var parent = range.parentElement();
  7634. var htmlText = range.htmlText;
  7635. var htmlTextLen = goog.string.stripNewlines(htmlText).length;
  7636. if (this.isCollapsed() && htmlTextLen > 0) {
  7637. return (this.parentNode_ = parent);
  7638. }
  7639. // Deal with selection bug where IE thinks one of the selection's children
  7640. // is actually the selection's parent. Relies on the assumption that the
  7641. // HTML text of the parent container is longer than the length of the
  7642. // selection's HTML text.
  7643. // Also note IE will sometimes insert \r and \n whitespace, which should be
  7644. // disregarded. Otherwise the loop may run too long and return wrong parent
  7645. while (htmlTextLen > goog.string.stripNewlines(parent.outerHTML).length) {
  7646. parent = parent.parentNode;
  7647. }
  7648. // Deal with IE's selecting the outer tags when you double click
  7649. // If the innerText is the same, then we just want the inner node
  7650. while (parent.childNodes.length == 1 &&
  7651. parent.firstChild && // FTDUEDTR-1212
  7652. parent.innerText == goog.dom.browserrange.IeRange.getNodeText_(
  7653. parent.firstChild)) {
  7654. // A container should be an element which can have children or a text
  7655. // node. Elements like IMG, BR, etc. can not be containers.
  7656. if (!goog.dom.browserrange.canContainRangeEndpoint(parent.firstChild)) {
  7657. break;
  7658. }
  7659. parent = parent.firstChild;
  7660. }
  7661. // If the selection is empty, we may need to do extra work to position it
  7662. // properly.
  7663. if (selectText.length == 0) {
  7664. parent = this.findDeepestContainer_(parent);
  7665. }
  7666. this.parentNode_ = parent;
  7667. }
  7668. return this.parentNode_;
  7669. };
  7670. /**
  7671. * Helper method to find the deepest parent for this range, starting
  7672. * the search from {@code node}, which must contain the range.
  7673. * @param {Node} node The node to start the search from.
  7674. * @return {Node} The deepest parent for this range.
  7675. * @private
  7676. */
  7677. goog.dom.browserrange.IeRange.prototype.findDeepestContainer_ = function(node) {
  7678. var childNodes = node.childNodes;
  7679. for (var i = 0, len = childNodes.length; i < len; i++) {
  7680. var child = childNodes[i];
  7681. if (goog.dom.browserrange.canContainRangeEndpoint(child)) {
  7682. var childRange =
  7683. goog.dom.browserrange.IeRange.getBrowserRangeForNode_(child);
  7684. var start = goog.dom.RangeEndpoint.START;
  7685. var end = goog.dom.RangeEndpoint.END;
  7686. // There are two types of erratic nodes where the range over node has
  7687. // different htmlText than the node's outerHTML.
  7688. // Case 1 - A node with magic &nbsp; child. In this case :
  7689. // nodeRange.htmlText shows &nbsp; ('<p>&nbsp;</p>), while
  7690. // node.outerHTML doesn't show the magic node (<p></p>).
  7691. // Case 2 - Empty span. In this case :
  7692. // node.outerHTML shows '<span></span>'
  7693. // node.htmlText is just empty string ''.
  7694. var isChildRangeErratic = (childRange.htmlText != child.outerHTML);
  7695. // Moreover the inRange comparison fails only when the
  7696. var isNativeInRangeErratic = this.isCollapsed() && isChildRangeErratic;
  7697. // In case 2 mentioned above, childRange is also collapsed. So we need to
  7698. // compare start of this range with both start and end of child range.
  7699. var inChildRange = isNativeInRangeErratic ?
  7700. (this.compareBrowserRangeEndpoints(childRange, start, start) >= 0 &&
  7701. this.compareBrowserRangeEndpoints(childRange, start, end) <= 0) :
  7702. this.range_.inRange(childRange);
  7703. if (inChildRange) {
  7704. return this.findDeepestContainer_(child);
  7705. }
  7706. }
  7707. }
  7708. return node;
  7709. };
  7710. /** @inheritDoc */
  7711. goog.dom.browserrange.IeRange.prototype.getStartNode = function() {
  7712. if (!this.startNode_) {
  7713. this.startNode_ = this.getEndpointNode_(goog.dom.RangeEndpoint.START);
  7714. if (this.isCollapsed()) {
  7715. this.endNode_ = this.startNode_;
  7716. }
  7717. }
  7718. return this.startNode_;
  7719. };
  7720. /** @inheritDoc */
  7721. goog.dom.browserrange.IeRange.prototype.getStartOffset = function() {
  7722. if (this.startOffset_ < 0) {
  7723. this.startOffset_ = this.getOffset_(goog.dom.RangeEndpoint.START);
  7724. if (this.isCollapsed()) {
  7725. this.endOffset_ = this.startOffset_;
  7726. }
  7727. }
  7728. return this.startOffset_;
  7729. };
  7730. /** @inheritDoc */
  7731. goog.dom.browserrange.IeRange.prototype.getEndNode = function() {
  7732. if (this.isCollapsed()) {
  7733. return this.getStartNode();
  7734. }
  7735. if (!this.endNode_) {
  7736. this.endNode_ = this.getEndpointNode_(goog.dom.RangeEndpoint.END);
  7737. }
  7738. return this.endNode_;
  7739. };
  7740. /** @inheritDoc */
  7741. goog.dom.browserrange.IeRange.prototype.getEndOffset = function() {
  7742. if (this.isCollapsed()) {
  7743. return this.getStartOffset();
  7744. }
  7745. if (this.endOffset_ < 0) {
  7746. this.endOffset_ = this.getOffset_(goog.dom.RangeEndpoint.END);
  7747. if (this.isCollapsed()) {
  7748. this.startOffset_ = this.endOffset_;
  7749. }
  7750. }
  7751. return this.endOffset_;
  7752. };
  7753. /** @inheritDoc */
  7754. goog.dom.browserrange.IeRange.prototype.compareBrowserRangeEndpoints = function(
  7755. range, thisEndpoint, otherEndpoint) {
  7756. return this.range_.compareEndPoints(
  7757. (thisEndpoint == goog.dom.RangeEndpoint.START ? 'Start' : 'End') +
  7758. 'To' +
  7759. (otherEndpoint == goog.dom.RangeEndpoint.START ? 'Start' : 'End'),
  7760. range);
  7761. };
  7762. /**
  7763. * Recurses to find the correct node for the given endpoint.
  7764. * @param {goog.dom.RangeEndpoint} endpoint The endpoint to get the node for.
  7765. * @param {Node=} opt_node Optional node to start the search from.
  7766. * @return {Node} The deepest node containing the endpoint.
  7767. * @private
  7768. */
  7769. goog.dom.browserrange.IeRange.prototype.getEndpointNode_ = function(endpoint,
  7770. opt_node) {
  7771. /** @type {Node} */
  7772. var node = opt_node || this.getContainer();
  7773. // If we're at a leaf in the DOM, we're done.
  7774. if (!node || !node.firstChild) {
  7775. return node;
  7776. }
  7777. var start = goog.dom.RangeEndpoint.START, end = goog.dom.RangeEndpoint.END;
  7778. var isStartEndpoint = endpoint == start;
  7779. // Find the first/last child that overlaps the selection.
  7780. // NOTE(user) : One of the children can be the magic &nbsp; node. This
  7781. // node will have only nodeType property as valid and accessible. All other
  7782. // dom related properties like ownerDocument, parentNode, nextSibling etc
  7783. // cause error when accessed. Therefore use the for-loop on childNodes to
  7784. // iterate.
  7785. for (var j = 0, length = node.childNodes.length; j < length; j++) {
  7786. var i = isStartEndpoint ? j : length - j - 1;
  7787. var child = node.childNodes[i];
  7788. var childRange;
  7789. try {
  7790. childRange = goog.dom.browserrange.createRangeFromNodeContents(child);
  7791. } catch (e) {
  7792. // If the child is the magic &nbsp; node, then the above will throw
  7793. // error. The magic node exists only when editing using keyboard, so can
  7794. // not add any unit test.
  7795. continue;
  7796. }
  7797. var ieRange = childRange.getBrowserRange();
  7798. // Case 1 : Finding end points when this range is collapsed.
  7799. // Note that in case of collapsed range, getEnd{Node,Offset} call
  7800. // getStart{Node,Offset}.
  7801. if (this.isCollapsed()) {
  7802. // Handle situations where caret is not in a text node. In such cases,
  7803. // the adjacent child won't be a valid range endpoint container.
  7804. if (!goog.dom.browserrange.canContainRangeEndpoint(child)) {
  7805. // The following handles a scenario like <div><BR>[caret]<BR></div>,
  7806. // where point should be (div, 1).
  7807. if (this.compareBrowserRangeEndpoints(ieRange, start, start) == 0) {
  7808. this.startOffset_ = this.endOffset_ = i;
  7809. return node;
  7810. }
  7811. } else if (childRange.containsRange(this)) {
  7812. // For collapsed range, we should invert the containsRange check with
  7813. // childRange.
  7814. return this.getEndpointNode_(endpoint, child);
  7815. }
  7816. // Case 2 - The first child encountered to have overlap this range is
  7817. // contained entirely in this range.
  7818. } else if (this.containsRange(childRange)) {
  7819. // If it is an element which can not be a range endpoint container, the
  7820. // current child offset can be used to deduce the endpoint offset.
  7821. if (!goog.dom.browserrange.canContainRangeEndpoint(child)) {
  7822. // Container can't be any deeper, so current node is the container.
  7823. if (isStartEndpoint) {
  7824. this.startOffset_ = i;
  7825. } else {
  7826. this.endOffset_ = i + 1;
  7827. }
  7828. return node;
  7829. }
  7830. // If child can contain range endpoints, recurse inside this child.
  7831. while(child.childNodes.length == 1) {
  7832. child = child.firstChild;
  7833. }
  7834. return this.getEndpointNode_(endpoint, child);
  7835. // Case 3 - Partial non-adjacency overlap.
  7836. } else if (this.compareBrowserRangeEndpoints(ieRange, start, end) < 0 &&
  7837. this.compareBrowserRangeEndpoints(ieRange, end, start) > 0) {
  7838. // If this child overlaps the selection partially, recurse down to find
  7839. // the first/last child the next level down that overlaps the selection
  7840. // completely. We do not consider edge-adjacency (== 0) as overlap.
  7841. while(child.childNodes.length == 1 && child.firstChild) {
  7842. child = child.firstChild;
  7843. }
  7844. return this.getEndpointNode_(endpoint, child);
  7845. }
  7846. }
  7847. // None of the children of this node overlapped the selection, that means
  7848. // the selection starts/ends in this node directly.
  7849. return node;
  7850. };
  7851. /**
  7852. * Compares one endpoint of this range with the endpoint of a node.
  7853. * For internal methods, we should prefer this method to containsNode.
  7854. * containsNode has a lot of _FALSE negatives when we're dealing with
  7855. * {@code <br>} tags.
  7856. *
  7857. * @param {Node} node The node to compare against.
  7858. * @param {goog.dom.RangeEndpoint} thisEndpoint The endpoint of this range
  7859. * to compare with.
  7860. * @param {goog.dom.RangeEndpoint} otherEndpoint The endpoint of the node
  7861. * to compare with.
  7862. * @return {number} 0 if the endpoints are equal, negative if this range
  7863. * endpoint comes before the other node endpoint, and positive otherwise.
  7864. * @private
  7865. */
  7866. goog.dom.browserrange.IeRange.prototype.compareNodeEndpoints_ =
  7867. function(node, thisEndpoint, otherEndpoint) {
  7868. return this.range_.compareEndPoints(
  7869. (thisEndpoint == goog.dom.RangeEndpoint.START ? 'Start' : 'End') +
  7870. 'To' +
  7871. (otherEndpoint == goog.dom.RangeEndpoint.START ? 'Start' : 'End'),
  7872. goog.dom.browserrange.createRangeFromNodeContents(node).
  7873. getBrowserRange());
  7874. };
  7875. /**
  7876. * Returns the offset into the start/end container.
  7877. * @param {goog.dom.RangeEndpoint} endpoint The endpoint to get the offset for.
  7878. * @param {Node=} opt_container The container to get the offset relative to.
  7879. * Defaults to the value returned by getStartNode/getEndNode.
  7880. * @return {number} The offset.
  7881. * @private
  7882. */
  7883. goog.dom.browserrange.IeRange.prototype.getOffset_ = function(endpoint,
  7884. opt_container) {
  7885. var isStartEndpoint = endpoint == goog.dom.RangeEndpoint.START;
  7886. var container = opt_container ||
  7887. (isStartEndpoint ? this.getStartNode() : this.getEndNode());
  7888. if (container.nodeType == goog.dom.NodeType.ELEMENT) {
  7889. // Find the first/last child that overlaps the selection
  7890. var children = container.childNodes;
  7891. var len = children.length;
  7892. var edge = isStartEndpoint ? 0 : len - 1;
  7893. var sign = isStartEndpoint ? 1 : - 1;
  7894. // We find the index in the child array of the endpoint of the selection.
  7895. for (var i = edge; i >= 0 && i < len; i += sign) {
  7896. var child = children[i];
  7897. // Ignore the child nodes, which could be end point containers.
  7898. if (goog.dom.browserrange.canContainRangeEndpoint(child)) {
  7899. continue;
  7900. }
  7901. // Stop looping when we reach the edge of the selection.
  7902. var endPointCompare =
  7903. this.compareNodeEndpoints_(child, endpoint, endpoint);
  7904. if (endPointCompare == 0) {
  7905. return isStartEndpoint ? i : i + 1;
  7906. }
  7907. }
  7908. // When starting from the end in an empty container, we erroneously return
  7909. // -1: fix this to return 0.
  7910. return i == -1 ? 0 : i;
  7911. } else {
  7912. // Get a temporary range object.
  7913. var range = this.range_.duplicate();
  7914. // Create a range that selects the entire container.
  7915. var nodeRange = goog.dom.browserrange.IeRange.getBrowserRangeForNode_(
  7916. container);
  7917. // Now, intersect our range with the container range - this should give us
  7918. // the part of our selection that is in the container.
  7919. range.setEndPoint(isStartEndpoint ? 'EndToEnd' : 'StartToStart', nodeRange);
  7920. var rangeLength = range.text.length;
  7921. return isStartEndpoint ? container.length - rangeLength : rangeLength;
  7922. }
  7923. };
  7924. /**
  7925. * Returns the text of the given node. Uses IE specific properties.
  7926. * @param {Node} node The node to retrieve the text of.
  7927. * @return {string} The node's text.
  7928. * @private
  7929. */
  7930. goog.dom.browserrange.IeRange.getNodeText_ = function(node) {
  7931. return node.nodeType == goog.dom.NodeType.TEXT ?
  7932. node.nodeValue : node.innerText;
  7933. };
  7934. /**
  7935. * Tests whether this range is valid (i.e. whether its endpoints are still in
  7936. * the document). A range becomes invalid when, after this object was created,
  7937. * either one or both of its endpoints are removed from the document. Use of
  7938. * an invalid range can lead to runtime errors, particularly in IE.
  7939. * @return {boolean} Whether the range is valid.
  7940. */
  7941. goog.dom.browserrange.IeRange.prototype.isRangeInDocument = function() {
  7942. var range = this.doc_.body.createTextRange();
  7943. range.moveToElementText(this.doc_.body);
  7944. return this.containsRange(
  7945. new goog.dom.browserrange.IeRange(range, this.doc_), _TRUE);
  7946. };
  7947. /** @inheritDoc */
  7948. goog.dom.browserrange.IeRange.prototype.isCollapsed = function() {
  7949. // Note(user) : The earlier implementation used (range.text == ''), but this
  7950. // fails when (range.htmlText == '<br>')
  7951. // Alternative: this.range_.htmlText == '';
  7952. return this.range_.compareEndPoints('StartToEnd', this.range_) == 0;
  7953. };
  7954. /** @inheritDoc */
  7955. goog.dom.browserrange.IeRange.prototype.getText = function() {
  7956. return this.range_.text;
  7957. };
  7958. /** @inheritDoc */
  7959. goog.dom.browserrange.IeRange.prototype.getValidHtml = function() {
  7960. return this.range_.htmlText;
  7961. };
  7962. // SELECTION MODIFICATION
  7963. /** @inheritDoc */
  7964. goog.dom.browserrange.IeRange.prototype.select = function(opt_reverse) {
  7965. // IE doesn't support programmatic reversed selections.
  7966. this.range_.select();
  7967. };
  7968. /** @inheritDoc */
  7969. goog.dom.browserrange.IeRange.prototype.removeContents = function() {
  7970. if (this.range_.htmlText) {
  7971. // Store some before-removal state.
  7972. var startNode = this.getStartNode();
  7973. var endNode = this.getEndNode();
  7974. var oldText = this.range_.text;
  7975. // IE sometimes deletes nodes unrelated to the selection. This trick fixes
  7976. // that problem most of the time. Even though it looks like a no-op, it is
  7977. // somehow changing IE's internal state such that empty unrelated nodes are
  7978. // no longer deleted.
  7979. var clone = this.range_.duplicate();
  7980. clone.moveStart('character', 1);
  7981. clone.moveStart('character', -1);
  7982. // However, sometimes when the range is empty, moving the start back and
  7983. // forth ends up changing the range. This indicates a case we need to
  7984. // handle manually.
  7985. if (clone.text != oldText) {
  7986. // Delete all nodes entirely contained in the range.
  7987. var iter = new goog.dom.NodeIterator(startNode, _FALSE, _TRUE);
  7988. var toDelete = [];
  7989. goog.iter.forEach(iter, function(node) {
  7990. // Any text node we encounter here is by definition contained entirely
  7991. // in the range.
  7992. if (node.nodeType != goog.dom.NodeType.TEXT &&
  7993. this.containsNode(node)) {
  7994. toDelete.push(node);
  7995. iter.skipTag();
  7996. }
  7997. if (node == endNode) {
  7998. throw goog.iter.StopIteration;
  7999. }
  8000. });
  8001. this.collapse(_TRUE);
  8002. goog.array.forEach(toDelete, goog.dom.removeNode);
  8003. this.clearCachedValues_();
  8004. return;
  8005. }
  8006. // Outside of the unfortunate cases where we have to handle deletion
  8007. // manually, we can use the browser's native deletion code.
  8008. this.range_ = clone;
  8009. this.range_.text = '';
  8010. this.clearCachedValues_();
  8011. // Unfortunately, when deleting a portion of a single text node, IE creates
  8012. // an extra text node unlike other browsers which just change the text in
  8013. // the node. We normalize for that behavior here, making IE behave like all
  8014. // the other browsers.
  8015. var newStartNode = this.getStartNode();
  8016. var newStartOffset = this.getStartOffset();
  8017. /** @preserveTry */
  8018. try {
  8019. var sibling = startNode.nextSibling;
  8020. if (startNode == endNode && startNode.parentNode &&
  8021. startNode.nodeType == goog.dom.NodeType.TEXT &&
  8022. sibling && sibling.nodeType == goog.dom.NodeType.TEXT) {
  8023. startNode.nodeValue += sibling.nodeValue;
  8024. goog.dom.removeNode(sibling);
  8025. // Make sure to reselect the appropriate position.
  8026. this.range_ = goog.dom.browserrange.IeRange.getBrowserRangeForNode_(
  8027. newStartNode);
  8028. this.range_.move('character', newStartOffset);
  8029. this.clearCachedValues_();
  8030. }
  8031. } catch (e) {
  8032. // IE throws errors on orphaned nodes.
  8033. }
  8034. }
  8035. };
  8036. /**
  8037. * @param {TextRange} range The range to get a dom helper for.
  8038. * @return {goog.dom.DomHelper} A dom helper for the document the range
  8039. * resides in.
  8040. * @private
  8041. */
  8042. goog.dom.browserrange.IeRange.getDomHelper_ = function(range) {
  8043. return goog.dom.getDomHelper(range.parentElement());
  8044. };
  8045. /**
  8046. * Pastes the given element into the given range, returning the resulting
  8047. * element.
  8048. * @param {TextRange} range The range to paste into.
  8049. * @param {Element} element The node to insert a copy of.
  8050. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper object for the document
  8051. * the range resides in.
  8052. * @return {Element} The resulting copy of element.
  8053. * @private
  8054. */
  8055. goog.dom.browserrange.IeRange.pasteElement_ = function(range, element,
  8056. opt_domHelper) {
  8057. opt_domHelper = opt_domHelper || goog.dom.browserrange.IeRange.getDomHelper_(
  8058. range);
  8059. // Make sure the node has a unique id.
  8060. var id;
  8061. var originalId = id = element.id;
  8062. if (!id) {
  8063. id = element.id = goog.string.createUniqueString();
  8064. }
  8065. // Insert (a clone of) the node.
  8066. range.pasteHTML(element.outerHTML);
  8067. // Pasting the outerHTML of the modified element into the document creates
  8068. // a clone of the element argument. We want to return a reference to the
  8069. // clone, not the original. However we need to remove the temporary ID
  8070. // first.
  8071. element = opt_domHelper.getElement(id);
  8072. // If element is null here, we failed.
  8073. if (element) {
  8074. if (!originalId) {
  8075. element.removeAttribute('id');
  8076. }
  8077. }
  8078. return element;
  8079. };
  8080. /** @inheritDoc */
  8081. goog.dom.browserrange.IeRange.prototype.surroundContents = function(element) {
  8082. // Make sure the element is detached from the document.
  8083. goog.dom.removeNode(element);
  8084. // IE more or less guarantees that range.htmlText is well-formed & valid.
  8085. element.innerHTML = this.range_.htmlText;
  8086. element = goog.dom.browserrange.IeRange.pasteElement_(this.range_, element);
  8087. // If element is null here, we failed.
  8088. if (element) {
  8089. this.range_.moveToElementText(element);
  8090. }
  8091. this.clearCachedValues_();
  8092. return element;
  8093. };
  8094. /**
  8095. * Internal handler for inserting a node.
  8096. * @param {TextRange} clone A clone of this range's browser range object.
  8097. * @param {Node} node The node to insert.
  8098. * @param {boolean} before Whether to insert the node before or after the range.
  8099. * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use.
  8100. * @return {Node} The resulting copy of node.
  8101. * @private
  8102. */
  8103. goog.dom.browserrange.IeRange.insertNode_ = function(clone, node,
  8104. before, opt_domHelper) {
  8105. // Get a DOM helper.
  8106. opt_domHelper = opt_domHelper || goog.dom.browserrange.IeRange.getDomHelper_(
  8107. clone);
  8108. // If it's not an element, wrap it in one.
  8109. var isNonElement;
  8110. if (node.nodeType != goog.dom.NodeType.ELEMENT) {
  8111. isNonElement = _TRUE;
  8112. node = opt_domHelper.createDom(goog.dom.TagName.DIV, _NULL, node);
  8113. }
  8114. clone.collapse(before);
  8115. node = goog.dom.browserrange.IeRange.pasteElement_(clone,
  8116. /** @type {Element} */ (node), opt_domHelper);
  8117. // If we didn't want an element, unwrap the element and return the node.
  8118. if (isNonElement) {
  8119. // pasteElement_() may have returned a copy of the wrapper div, and the
  8120. // node it wraps could also be a new copy. So we must extract that new
  8121. // node from the new wrapper.
  8122. var newNonElement = node.firstChild;
  8123. opt_domHelper.flattenElement(node);
  8124. node = newNonElement;
  8125. }
  8126. return node;
  8127. };
  8128. /** @inheritDoc */
  8129. goog.dom.browserrange.IeRange.prototype.insertNode = function(node, before) {
  8130. var output = goog.dom.browserrange.IeRange.insertNode_(
  8131. this.range_.duplicate(), node, before);
  8132. this.clearCachedValues_();
  8133. return output;
  8134. };
  8135. /** @inheritDoc */
  8136. goog.dom.browserrange.IeRange.prototype.surroundWithNodes = function(
  8137. startNode, endNode) {
  8138. var clone1 = this.range_.duplicate();
  8139. var clone2 = this.range_.duplicate();
  8140. goog.dom.browserrange.IeRange.insertNode_(clone1, startNode, _TRUE);
  8141. goog.dom.browserrange.IeRange.insertNode_(clone2, endNode, _FALSE);
  8142. this.clearCachedValues_();
  8143. };
  8144. /** @inheritDoc */
  8145. goog.dom.browserrange.IeRange.prototype.collapse = function(toStart) {
  8146. this.range_.collapse(toStart);
  8147. if (toStart) {
  8148. this.endNode_ = this.startNode_;
  8149. this.endOffset_ = this.startOffset_;
  8150. } else {
  8151. this.startNode_ = this.endNode_;
  8152. this.startOffset_ = this.endOffset_;
  8153. }
  8154. };
  8155. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  8156. //
  8157. // Licensed under the Apache License, Version 2.0 (the "License");
  8158. // you may not use this file except in compliance with the License.
  8159. // You may obtain a copy of the License at
  8160. //
  8161. // http://www.apache.org/licenses/LICENSE-2.0
  8162. //
  8163. // Unless required by applicable law or agreed to in writing, software
  8164. // distributed under the License is distributed on an "AS-IS" BASIS,
  8165. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8166. // See the License for the specific language governing permissions and
  8167. // limitations under the License.
  8168. /**
  8169. * @fileoverview Definition of the Gecko specific range wrapper. Inherits most
  8170. * functionality from W3CRange, but adds exceptions as necessary.
  8171. *
  8172. * DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
  8173. *
  8174. * @author robbyw@google.com (Robby Walker)
  8175. */
  8176. goog.provide('goog.dom.browserrange.GeckoRange');
  8177. //goog.require('goog.dom.browserrange.W3cRange');
  8178. /**
  8179. * The constructor for Gecko specific browser ranges.
  8180. * @param {Range} range The range object.
  8181. * @constructor
  8182. * @extends {goog.dom.browserrange.W3cRange}
  8183. */
  8184. goog.dom.browserrange.GeckoRange = function(range) {
  8185. goog.dom.browserrange.W3cRange.call(this, range);
  8186. };
  8187. goog.inherits(goog.dom.browserrange.GeckoRange, goog.dom.browserrange.W3cRange);
  8188. /**
  8189. * Creates a range object that selects the given node's text.
  8190. * @param {Node} node The node to select.
  8191. * @return {goog.dom.browserrange.GeckoRange} A Gecko range wrapper object.
  8192. */
  8193. goog.dom.browserrange.GeckoRange.createFromNodeContents = function(node) {
  8194. return new goog.dom.browserrange.GeckoRange(
  8195. goog.dom.browserrange.W3cRange.getBrowserRangeForNode(node));
  8196. };
  8197. /**
  8198. * Creates a range object that selects between the given nodes.
  8199. * @param {Node} startNode The node to start with.
  8200. * @param {number} startOffset The offset within the node to start.
  8201. * @param {Node} endNode The node to end with.
  8202. * @param {number} endOffset The offset within the node to end.
  8203. * @return {goog.dom.browserrange.GeckoRange} A wrapper object.
  8204. */
  8205. goog.dom.browserrange.GeckoRange.createFromNodes = function(startNode,
  8206. startOffset, endNode, endOffset) {
  8207. return new goog.dom.browserrange.GeckoRange(
  8208. goog.dom.browserrange.W3cRange.getBrowserRangeForNodes(startNode,
  8209. startOffset, endNode, endOffset));
  8210. };
  8211. /** @inheritDoc */
  8212. goog.dom.browserrange.GeckoRange.prototype.selectInternal = function(
  8213. selection, reversed) {
  8214. var anchorNode = reversed ? this.getEndNode() : this.getStartNode();
  8215. var anchorOffset = reversed ? this.getEndOffset() : this.getStartOffset();
  8216. var focusNode = reversed ? this.getStartNode() : this.getEndNode();
  8217. var focusOffset = reversed ? this.getStartOffset() : this.getEndOffset();
  8218. selection.collapse(anchorNode, anchorOffset);
  8219. if (anchorNode != focusNode || anchorOffset != focusOffset) {
  8220. selection.extend(focusNode, focusOffset);
  8221. }
  8222. };
  8223. // Copyright 2009 The Closure Library Authors. All Rights Reserved.
  8224. //
  8225. // Licensed under the Apache License, Version 2.0 (the "License");
  8226. // you may not use this file except in compliance with the License.
  8227. // You may obtain a copy of the License at
  8228. //
  8229. // http://www.apache.org/licenses/LICENSE-2.0
  8230. //
  8231. // Unless required by applicable law or agreed to in writing, software
  8232. // distributed under the License is distributed on an "AS-IS" BASIS,
  8233. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8234. // See the License for the specific language governing permissions and
  8235. // limitations under the License.
  8236. /**
  8237. * @fileoverview Definition of the Opera specific range wrapper. Inherits most
  8238. * functionality from W3CRange, but adds exceptions as necessary.
  8239. *
  8240. * DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
  8241. *
  8242. */
  8243. goog.provide('goog.dom.browserrange.OperaRange');
  8244. //goog.require('goog.dom.browserrange.W3cRange');
  8245. /**
  8246. * The constructor for Opera specific browser ranges.
  8247. * @param {Range} range The range object.
  8248. * @constructor
  8249. * @extends {goog.dom.browserrange.W3cRange}
  8250. */
  8251. goog.dom.browserrange.OperaRange = function(range) {
  8252. goog.dom.browserrange.W3cRange.call(this, range);
  8253. };
  8254. goog.inherits(goog.dom.browserrange.OperaRange, goog.dom.browserrange.W3cRange);
  8255. /**
  8256. * Creates a range object that selects the given node's text.
  8257. * @param {Node} node The node to select.
  8258. * @return {goog.dom.browserrange.OperaRange} A Opera range wrapper object.
  8259. */
  8260. goog.dom.browserrange.OperaRange.createFromNodeContents = function(node) {
  8261. return new goog.dom.browserrange.OperaRange(
  8262. goog.dom.browserrange.W3cRange.getBrowserRangeForNode(node));
  8263. };
  8264. /**
  8265. * Creates a range object that selects between the given nodes.
  8266. * @param {Node} startNode The node to start with.
  8267. * @param {number} startOffset The offset within the node to start.
  8268. * @param {Node} endNode The node to end with.
  8269. * @param {number} endOffset The offset within the node to end.
  8270. * @return {goog.dom.browserrange.OperaRange} A wrapper object.
  8271. */
  8272. goog.dom.browserrange.OperaRange.createFromNodes = function(startNode,
  8273. startOffset, endNode, endOffset) {
  8274. return new goog.dom.browserrange.OperaRange(
  8275. goog.dom.browserrange.W3cRange.getBrowserRangeForNodes(startNode,
  8276. startOffset, endNode, endOffset));
  8277. };
  8278. /** @inheritDoc */
  8279. goog.dom.browserrange.OperaRange.prototype.selectInternal = function(
  8280. selection, reversed) {
  8281. // Avoid using addRange as we have to removeAllRanges first, which
  8282. // blurs editable fields in Opera.
  8283. selection.collapse(this.getStartNode(), this.getStartOffset());
  8284. if (this.getEndNode() != this.getStartNode() ||
  8285. this.getEndOffset() != this.getStartOffset()) {
  8286. selection.extend(this.getEndNode(), this.getEndOffset());
  8287. }
  8288. // This can happen if the range isn't in an editable field.
  8289. if (selection.rangeCount == 0) {
  8290. selection.addRange(this.range_);
  8291. }
  8292. };
  8293. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  8294. //
  8295. // Licensed under the Apache License, Version 2.0 (the "License");
  8296. // you may not use this file except in compliance with the License.
  8297. // You may obtain a copy of the License at
  8298. //
  8299. // http://www.apache.org/licenses/LICENSE-2.0
  8300. //
  8301. // Unless required by applicable law or agreed to in writing, software
  8302. // distributed under the License is distributed on an "AS-IS" BASIS,
  8303. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8304. // See the License for the specific language governing permissions and
  8305. // limitations under the License.
  8306. /**
  8307. * @fileoverview Definition of the browser range namespace and interface, as
  8308. * well as several useful utility functions.
  8309. *
  8310. * DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
  8311. *
  8312. * @author robbyw@google.com (Robby Walker)
  8313. * @author ojan@google.com (Ojan Vafai)
  8314. * @author jparent@google.com (Julie Parent)
  8315. *
  8316. * @supported IE6, IE7, FF1.5+, Safari.
  8317. */
  8318. goog.provide('goog.dom.browserrange');
  8319. goog.provide('goog.dom.browserrange.Error');
  8320. //goog.require('goog.dom');
  8321. //goog.require('goog.dom.browserrange.GeckoRange');
  8322. //goog.require('goog.dom.browserrange.IeRange');
  8323. //goog.require('goog.dom.browserrange.OperaRange');
  8324. //goog.require('goog.dom.browserrange.W3cRange');
  8325. //goog.require('goog.dom.browserrange.WebKitRange');
  8326. //goog.require('goog.userAgent');
  8327. /**
  8328. * Common error constants.
  8329. * @enum {string}
  8330. */
  8331. goog.dom.browserrange.Error = {
  8332. NOT_IMPLEMENTED: 'Not Implemented'
  8333. };
  8334. // NOTE(robbyw): While it would be nice to eliminate the duplicate switches
  8335. // below, doing so uncovers bugs in the JsCompiler in which
  8336. // necessary code is stripped out.
  8337. /**
  8338. * Static method that returns the proper type of browser range.
  8339. * @param {Range|TextRange} range A browser range object.
  8340. * @return {goog.dom.browserrange.AbstractRange} A wrapper object.
  8341. */
  8342. goog.dom.browserrange.createRange = function(range) {
  8343. if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
  8344. return new goog.dom.browserrange.IeRange(
  8345. /** @type {TextRange} */ (range),
  8346. goog.dom.getOwnerDocument(range.parentElement()));
  8347. } else if (goog.userAgent.WEBKIT) {
  8348. return new goog.dom.browserrange.WebKitRange(
  8349. /** @type {Range} */ (range));
  8350. } else if (goog.userAgent.GECKO) {
  8351. return new goog.dom.browserrange.GeckoRange(
  8352. /** @type {Range} */ (range));
  8353. } else if (goog.userAgent.OPERA) {
  8354. return new goog.dom.browserrange.OperaRange(
  8355. /** @type {Range} */ (range));
  8356. } else {
  8357. // Default other browsers, including Opera, to W3c ranges.
  8358. return new goog.dom.browserrange.W3cRange(
  8359. /** @type {Range} */ (range));
  8360. }
  8361. };
  8362. /**
  8363. * Static method that returns the proper type of browser range.
  8364. * @param {Node} node The node to select.
  8365. * @return {goog.dom.browserrange.AbstractRange} A wrapper object.
  8366. */
  8367. goog.dom.browserrange.createRangeFromNodeContents = function(node) {
  8368. if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
  8369. return goog.dom.browserrange.IeRange.createFromNodeContents(node);
  8370. } else if (goog.userAgent.WEBKIT) {
  8371. return goog.dom.browserrange.WebKitRange.createFromNodeContents(node);
  8372. } else if (goog.userAgent.GECKO) {
  8373. return goog.dom.browserrange.GeckoRange.createFromNodeContents(node);
  8374. } else if (goog.userAgent.OPERA) {
  8375. return goog.dom.browserrange.OperaRange.createFromNodeContents(node);
  8376. } else {
  8377. // Default other browsers to W3c ranges.
  8378. return goog.dom.browserrange.W3cRange.createFromNodeContents(node);
  8379. }
  8380. };
  8381. /**
  8382. * Static method that returns the proper type of browser range.
  8383. * @param {Node} startNode The node to start with.
  8384. * @param {number} startOffset The offset within the node to start. This is
  8385. * either the index into the childNodes array for element startNodes or
  8386. * the index into the character array for text startNodes.
  8387. * @param {Node} endNode The node to end with.
  8388. * @param {number} endOffset The offset within the node to end. This is
  8389. * either the index into the childNodes array for element endNodes or
  8390. * the index into the character array for text endNodes.
  8391. * @return {goog.dom.browserrange.AbstractRange} A wrapper object.
  8392. */
  8393. goog.dom.browserrange.createRangeFromNodes = function(startNode, startOffset,
  8394. endNode, endOffset) {
  8395. if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
  8396. return goog.dom.browserrange.IeRange.createFromNodes(startNode, startOffset,
  8397. endNode, endOffset);
  8398. } else if (goog.userAgent.WEBKIT) {
  8399. return goog.dom.browserrange.WebKitRange.createFromNodes(startNode,
  8400. startOffset, endNode, endOffset);
  8401. } else if (goog.userAgent.GECKO) {
  8402. return goog.dom.browserrange.GeckoRange.createFromNodes(startNode,
  8403. startOffset, endNode, endOffset);
  8404. } else if (goog.userAgent.OPERA) {
  8405. return goog.dom.browserrange.OperaRange.createFromNodes(startNode,
  8406. startOffset, endNode, endOffset);
  8407. } else {
  8408. // Default other browsers to W3c ranges.
  8409. return goog.dom.browserrange.W3cRange.createFromNodes(startNode,
  8410. startOffset, endNode, endOffset);
  8411. }
  8412. };
  8413. /**
  8414. * Tests whether the given node can contain a range end point.
  8415. * @param {Node} node The node to check.
  8416. * @return {boolean} Whether the given node can contain a range end point.
  8417. */
  8418. goog.dom.browserrange.canContainRangeEndpoint = function(node) {
  8419. // NOTE(user, bloom): This is not complete, as divs with style -
  8420. // 'display:inline-block' or 'position:absolute' can also not contain range
  8421. // endpoints. A more complete check is to see if that element can be partially
  8422. // selected (can be container) or not.
  8423. return goog.dom.canHaveChildren(node) ||
  8424. node.nodeType == goog.dom.NodeType.TEXT;
  8425. };
  8426. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  8427. //
  8428. // Licensed under the Apache License, Version 2.0 (the "License");
  8429. // you may not use this file except in compliance with the License.
  8430. // You may obtain a copy of the License at
  8431. //
  8432. // http://www.apache.org/licenses/LICENSE-2.0
  8433. //
  8434. // Unless required by applicable law or agreed to in writing, software
  8435. // distributed under the License is distributed on an "AS-IS" BASIS,
  8436. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8437. // See the License for the specific language governing permissions and
  8438. // limitations under the License.
  8439. /**
  8440. * @fileoverview Utilities for working with text ranges in HTML documents.
  8441. *
  8442. * @author robbyw@google.com (Robby Walker)
  8443. * @author ojan@google.com (Ojan Vafai)
  8444. * @author jparent@google.com (Julie Parent)
  8445. */
  8446. goog.provide('goog.dom.TextRange');
  8447. //goog.require('goog.array');
  8448. //goog.require('goog.dom');
  8449. //goog.require('goog.dom.AbstractRange');
  8450. //goog.require('goog.dom.RangeType');
  8451. //goog.require('goog.dom.SavedRange');
  8452. //goog.require('goog.dom.TagName');
  8453. //goog.require('goog.dom.TextRangeIterator');
  8454. //goog.require('goog.dom.browserrange');
  8455. //goog.require('goog.string');
  8456. //goog.require('goog.userAgent');
  8457. /**
  8458. * Create a new text selection with no properties. Do not use this constructor:
  8459. * use one of the goog.dom.Range.createFrom* methods instead.
  8460. * @constructor
  8461. * @extends {goog.dom.AbstractRange}
  8462. */
  8463. goog.dom.TextRange = function() {
  8464. };
  8465. goog.inherits(goog.dom.TextRange, goog.dom.AbstractRange);
  8466. /**
  8467. * Create a new range wrapper from the given browser range object. Do not use
  8468. * this method directly - please use goog.dom.Range.createFrom* instead.
  8469. * @param {Range|TextRange} range The browser range object.
  8470. * @param {boolean=} opt_isReversed Whether the focus node is before the anchor
  8471. * node.
  8472. * @return {goog.dom.TextRange} A range wrapper object.
  8473. */
  8474. goog.dom.TextRange.createFromBrowserRange = function(range, opt_isReversed) {
  8475. return goog.dom.TextRange.createFromBrowserRangeWrapper_(
  8476. goog.dom.browserrange.createRange(range), opt_isReversed);
  8477. };
  8478. /**
  8479. * Create a new range wrapper from the given browser range wrapper.
  8480. * @param {goog.dom.browserrange.AbstractRange} browserRange The browser range
  8481. * wrapper.
  8482. * @param {boolean=} opt_isReversed Whether the focus node is before the anchor
  8483. * node.
  8484. * @return {goog.dom.TextRange} A range wrapper object.
  8485. * @private
  8486. */
  8487. goog.dom.TextRange.createFromBrowserRangeWrapper_ = function(browserRange,
  8488. opt_isReversed) {
  8489. var range = new goog.dom.TextRange();
  8490. // Initialize the range as a browser range wrapper type range.
  8491. range.browserRangeWrapper_ = browserRange;
  8492. range.isReversed_ = !!opt_isReversed;
  8493. return range;
  8494. };
  8495. /**
  8496. * Create a new range wrapper that selects the given node's text. Do not use
  8497. * this method directly - please use goog.dom.Range.createFrom* instead.
  8498. * @param {Node} node The node to select.
  8499. * @param {boolean=} opt_isReversed Whether the focus node is before the anchor
  8500. * node.
  8501. * @return {goog.dom.TextRange} A range wrapper object.
  8502. */
  8503. goog.dom.TextRange.createFromNodeContents = function(node, opt_isReversed) {
  8504. return goog.dom.TextRange.createFromBrowserRangeWrapper_(
  8505. goog.dom.browserrange.createRangeFromNodeContents(node),
  8506. opt_isReversed);
  8507. };
  8508. /**
  8509. * Create a new range wrapper that selects the area between the given nodes,
  8510. * accounting for the given offsets. Do not use this method directly - please
  8511. * use goog.dom.Range.createFrom* instead.
  8512. * @param {Node} anchorNode The node to start with.
  8513. * @param {number} anchorOffset The offset within the node to start.
  8514. * @param {Node} focusNode The node to end with.
  8515. * @param {number} focusOffset The offset within the node to end.
  8516. * @return {goog.dom.TextRange} A range wrapper object.
  8517. */
  8518. goog.dom.TextRange.createFromNodes = function(anchorNode, anchorOffset,
  8519. focusNode, focusOffset) {
  8520. var range = new goog.dom.TextRange();
  8521. range.isReversed_ = goog.dom.Range.isReversed(anchorNode, anchorOffset,
  8522. focusNode, focusOffset);
  8523. // Avoid selecting BRs directly
  8524. if (anchorNode.tagName == 'BR') {
  8525. var parent = anchorNode.parentNode;
  8526. anchorOffset = goog.array.indexOf(parent.childNodes, anchorNode);
  8527. anchorNode = parent;
  8528. }
  8529. if (focusNode.tagName == 'BR') {
  8530. var parent = focusNode.parentNode;
  8531. focusOffset = goog.array.indexOf(parent.childNodes, focusNode);
  8532. focusNode = parent;
  8533. }
  8534. // Initialize the range as a W3C style range.
  8535. if (range.isReversed_) {
  8536. range.startNode_ = focusNode;
  8537. range.startOffset_ = focusOffset;
  8538. range.endNode_ = anchorNode;
  8539. range.endOffset_ = anchorOffset;
  8540. } else {
  8541. range.startNode_ = anchorNode;
  8542. range.startOffset_ = anchorOffset;
  8543. range.endNode_ = focusNode;
  8544. range.endOffset_ = focusOffset;
  8545. }
  8546. return range;
  8547. };
  8548. // Representation 1: a browser range wrapper.
  8549. /**
  8550. * The browser specific range wrapper. This can be null if one of the other
  8551. * representations of the range is specified.
  8552. * @type {goog.dom.browserrange.AbstractRange?}
  8553. * @private
  8554. */
  8555. goog.dom.TextRange.prototype.browserRangeWrapper_ = _NULL;
  8556. // Representation 2: two endpoints specified as nodes + offsets
  8557. /**
  8558. * The start node of the range. This can be null if one of the other
  8559. * representations of the range is specified.
  8560. * @type {Node}
  8561. * @private
  8562. */
  8563. goog.dom.TextRange.prototype.startNode_ = _NULL;
  8564. /**
  8565. * The start offset of the range. This can be null if one of the other
  8566. * representations of the range is specified.
  8567. * @type {?number}
  8568. * @private
  8569. */
  8570. goog.dom.TextRange.prototype.startOffset_ = _NULL;
  8571. /**
  8572. * The end node of the range. This can be null if one of the other
  8573. * representations of the range is specified.
  8574. * @type {Node}
  8575. * @private
  8576. */
  8577. goog.dom.TextRange.prototype.endNode_ = _NULL;
  8578. /**
  8579. * The end offset of the range. This can be null if one of the other
  8580. * representations of the range is specified.
  8581. * @type {?number}
  8582. * @private
  8583. */
  8584. goog.dom.TextRange.prototype.endOffset_ = _NULL;
  8585. /**
  8586. * Whether the focus node is before the anchor node.
  8587. * @type {boolean}
  8588. * @private
  8589. */
  8590. goog.dom.TextRange.prototype.isReversed_ = _FALSE;
  8591. // Method implementations
  8592. /**
  8593. * @return {goog.dom.TextRange} A clone of this range.
  8594. */
  8595. goog.dom.TextRange.prototype.clone = function() {
  8596. var range = new goog.dom.TextRange();
  8597. range.browserRangeWrapper_ = this.browserRangeWrapper_;
  8598. range.startNode_ = this.startNode_;
  8599. range.startOffset_ = this.startOffset_;
  8600. range.endNode_ = this.endNode_;
  8601. range.endOffset_ = this.endOffset_;
  8602. range.isReversed_ = this.isReversed_;
  8603. return range;
  8604. };
  8605. /** @inheritDoc */
  8606. goog.dom.TextRange.prototype.getType = function() {
  8607. return goog.dom.RangeType.TEXT;
  8608. };
  8609. /** @inheritDoc */
  8610. goog.dom.TextRange.prototype.getBrowserRangeObject = function() {
  8611. return this.getBrowserRangeWrapper_().getBrowserRange();
  8612. };
  8613. /** @inheritDoc */
  8614. goog.dom.TextRange.prototype.setBrowserRangeObject = function(nativeRange) {
  8615. // Test if it's a control range by seeing if a control range only method
  8616. // exists.
  8617. if (goog.dom.AbstractRange.isNativeControlRange(nativeRange)) {
  8618. return _FALSE;
  8619. }
  8620. this.browserRangeWrapper_ = goog.dom.browserrange.createRange(
  8621. nativeRange);
  8622. this.clearCachedValues_();
  8623. return _TRUE;
  8624. };
  8625. /**
  8626. * Clear all cached values.
  8627. * @private
  8628. */
  8629. goog.dom.TextRange.prototype.clearCachedValues_ = function() {
  8630. this.startNode_ = this.startOffset_ = this.endNode_ = this.endOffset_ = _NULL;
  8631. };
  8632. /** @inheritDoc */
  8633. goog.dom.TextRange.prototype.getTextRangeCount = function() {
  8634. return 1;
  8635. };
  8636. /** @inheritDoc */
  8637. goog.dom.TextRange.prototype.getTextRange = function(i) {
  8638. return this;
  8639. };
  8640. /**
  8641. * @return {goog.dom.browserrange.AbstractRange} The range wrapper object.
  8642. * @private
  8643. */
  8644. goog.dom.TextRange.prototype.getBrowserRangeWrapper_ = function() {
  8645. return this.browserRangeWrapper_ ||
  8646. (this.browserRangeWrapper_ = goog.dom.browserrange.createRangeFromNodes(
  8647. this.getStartNode(), this.getStartOffset(),
  8648. this.getEndNode(), this.getEndOffset()));
  8649. };
  8650. /** @inheritDoc */
  8651. goog.dom.TextRange.prototype.getContainer = function() {
  8652. return this.getBrowserRangeWrapper_().getContainer();
  8653. };
  8654. /** @inheritDoc */
  8655. goog.dom.TextRange.prototype.getStartNode = function() {
  8656. return this.startNode_ ||
  8657. (this.startNode_ = this.getBrowserRangeWrapper_().getStartNode());
  8658. };
  8659. /** @inheritDoc */
  8660. goog.dom.TextRange.prototype.getStartOffset = function() {
  8661. return this.startOffset_ != _NULL ? this.startOffset_ :
  8662. (this.startOffset_ = this.getBrowserRangeWrapper_().getStartOffset());
  8663. };
  8664. /** @inheritDoc */
  8665. goog.dom.TextRange.prototype.getEndNode = function() {
  8666. return this.endNode_ ||
  8667. (this.endNode_ = this.getBrowserRangeWrapper_().getEndNode());
  8668. };
  8669. /** @inheritDoc */
  8670. goog.dom.TextRange.prototype.getEndOffset = function() {
  8671. return this.endOffset_ != _NULL ? this.endOffset_ :
  8672. (this.endOffset_ = this.getBrowserRangeWrapper_().getEndOffset());
  8673. };
  8674. /**
  8675. * Moves a TextRange to the provided nodes and offsets.
  8676. * @param {Node} startNode The node to start with.
  8677. * @param {number} startOffset The offset within the node to start.
  8678. * @param {Node} endNode The node to end with.
  8679. * @param {number} endOffset The offset within the node to end.
  8680. * @param {boolean} isReversed Whether the range is reversed.
  8681. */
  8682. goog.dom.TextRange.prototype.moveToNodes = function(startNode, startOffset,
  8683. endNode, endOffset,
  8684. isReversed) {
  8685. this.startNode_ = startNode;
  8686. this.startOffset_ = startOffset;
  8687. this.endNode_ = endNode;
  8688. this.endOffset_ = endOffset;
  8689. this.isReversed_ = isReversed;
  8690. this.browserRangeWrapper_ = _NULL;
  8691. };
  8692. /** @inheritDoc */
  8693. goog.dom.TextRange.prototype.isReversed = function() {
  8694. return this.isReversed_;
  8695. };
  8696. /** @inheritDoc */
  8697. goog.dom.TextRange.prototype.containsRange = function(otherRange,
  8698. opt_allowPartial) {
  8699. var otherRangeType = otherRange.getType();
  8700. if (otherRangeType == goog.dom.RangeType.TEXT) {
  8701. return this.getBrowserRangeWrapper_().containsRange(
  8702. otherRange.getBrowserRangeWrapper_(), opt_allowPartial);
  8703. } else if (otherRangeType == goog.dom.RangeType.CONTROL) {
  8704. var elements = otherRange.getElements();
  8705. var fn = opt_allowPartial ? goog.array.some : goog.array.every;
  8706. return fn(elements, function(el) {
  8707. return this.containsNode(el, opt_allowPartial);
  8708. }, this);
  8709. }
  8710. return _FALSE;
  8711. };
  8712. /**
  8713. * Tests if the given node is in a document.
  8714. * @param {Node} node The node to check.
  8715. * @return {boolean} Whether the given node is in the given document.
  8716. */
  8717. goog.dom.TextRange.isAttachedNode = function(node) {
  8718. if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
  8719. var returnValue = _FALSE;
  8720. /** @preserveTry */
  8721. try {
  8722. returnValue = node.parentNode;
  8723. } catch (e) {
  8724. // IE sometimes throws Invalid Argument errors when a node is detached.
  8725. // Note: trying to return a value from the above try block can cause IE
  8726. // to crash. It is necessary to use the local returnValue
  8727. }
  8728. return !!returnValue;
  8729. } else {
  8730. return goog.dom.contains(node.ownerDocument.body, node);
  8731. }
  8732. };
  8733. /** @inheritDoc */
  8734. goog.dom.TextRange.prototype.isRangeInDocument = function() {
  8735. // Ensure any cached nodes are in the document. IE also allows ranges to
  8736. // become detached, so we check if the range is still in the document as
  8737. // well for IE.
  8738. return (!this.startNode_ ||
  8739. goog.dom.TextRange.isAttachedNode(this.startNode_)) &&
  8740. (!this.endNode_ ||
  8741. goog.dom.TextRange.isAttachedNode(this.endNode_)) &&
  8742. (!(goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) ||
  8743. this.getBrowserRangeWrapper_().isRangeInDocument());
  8744. };
  8745. /** @inheritDoc */
  8746. goog.dom.TextRange.prototype.isCollapsed = function() {
  8747. return this.getBrowserRangeWrapper_().isCollapsed();
  8748. };
  8749. /** @inheritDoc */
  8750. goog.dom.TextRange.prototype.getText = function() {
  8751. return this.getBrowserRangeWrapper_().getText();
  8752. };
  8753. /** @inheritDoc */
  8754. goog.dom.TextRange.prototype.getHtmlFragment = function() {
  8755. // TODO(robbyw): Generalize the code in browserrange so it is static and
  8756. // just takes an iterator. This would mean we don't always have to create a
  8757. // browser range.
  8758. return this.getBrowserRangeWrapper_().getHtmlFragment();
  8759. };
  8760. /** @inheritDoc */
  8761. goog.dom.TextRange.prototype.getValidHtml = function() {
  8762. return this.getBrowserRangeWrapper_().getValidHtml();
  8763. };
  8764. /** @inheritDoc */
  8765. goog.dom.TextRange.prototype.getPastableHtml = function() {
  8766. // TODO(robbyw): Get any attributes the table or tr has.
  8767. var html = this.getValidHtml();
  8768. if (html.match(/^\s*<td\b/i)) {
  8769. // Match html starting with a TD.
  8770. html = '<table><tbody><tr>' + html + '</tr></tbody></table>';
  8771. } else if (html.match(/^\s*<tr\b/i)) {
  8772. // Match html starting with a TR.
  8773. html = '<table><tbody>' + html + '</tbody></table>';
  8774. } else if (html.match(/^\s*<tbody\b/i)) {
  8775. // Match html starting with a TBODY.
  8776. html = '<table>' + html + '</table>';
  8777. } else if (html.match(/^\s*<li\b/i)) {
  8778. // Match html starting with an LI.
  8779. var container = this.getContainer();
  8780. var tagType = goog.dom.TagName.UL;
  8781. while (container) {
  8782. if (container.tagName == goog.dom.TagName.OL) {
  8783. tagType = goog.dom.TagName.OL;
  8784. break;
  8785. } else if (container.tagName == goog.dom.TagName.UL) {
  8786. break;
  8787. }
  8788. container = container.parentNode;
  8789. }
  8790. html = goog.string.buildString('<', tagType, '>', html, '</', tagType, '>');
  8791. }
  8792. return html;
  8793. };
  8794. /**
  8795. * Returns a TextRangeIterator over the contents of the range. Regardless of
  8796. * the direction of the range, the iterator will move in document order.
  8797. * @param {boolean=} opt_keys Unused for this iterator.
  8798. * @return {goog.dom.TextRangeIterator} An iterator over tags in the range.
  8799. */
  8800. goog.dom.TextRange.prototype.__iterator__ = function(opt_keys) {
  8801. return new goog.dom.TextRangeIterator(this.getStartNode(),
  8802. this.getStartOffset(), this.getEndNode(), this.getEndOffset());
  8803. };
  8804. // RANGE ACTIONS
  8805. /** @inheritDoc */
  8806. goog.dom.TextRange.prototype.select = function() {
  8807. this.getBrowserRangeWrapper_().select(this.isReversed_);
  8808. };
  8809. /** @inheritDoc */
  8810. goog.dom.TextRange.prototype.removeContents = function() {
  8811. this.getBrowserRangeWrapper_().removeContents();
  8812. this.clearCachedValues_();
  8813. };
  8814. /**
  8815. * Surrounds the text range with the specified element (on Mozilla) or with a
  8816. * clone of the specified element (on IE). Returns a reference to the
  8817. * surrounding element if the operation was successful; returns null if the
  8818. * operation failed.
  8819. * @param {Element} element The element with which the selection is to be
  8820. * surrounded.
  8821. * @return {Element} The surrounding element (same as the argument on Mozilla,
  8822. * but not on IE), or null if unsuccessful.
  8823. */
  8824. goog.dom.TextRange.prototype.surroundContents = function(element) {
  8825. var output = this.getBrowserRangeWrapper_().surroundContents(element);
  8826. this.clearCachedValues_();
  8827. return output;
  8828. };
  8829. /** @inheritDoc */
  8830. goog.dom.TextRange.prototype.insertNode = function(node, before) {
  8831. var output = this.getBrowserRangeWrapper_().insertNode(node, before);
  8832. this.clearCachedValues_();
  8833. return output;
  8834. };
  8835. /** @inheritDoc */
  8836. goog.dom.TextRange.prototype.surroundWithNodes = function(startNode, endNode) {
  8837. this.getBrowserRangeWrapper_().surroundWithNodes(startNode, endNode);
  8838. this.clearCachedValues_();
  8839. };
  8840. // SAVE/RESTORE
  8841. /** @inheritDoc */
  8842. goog.dom.TextRange.prototype.saveUsingDom = function() {
  8843. return new goog.dom.DomSavedTextRange_(this);
  8844. };
  8845. // RANGE MODIFICATION
  8846. /** @inheritDoc */
  8847. goog.dom.TextRange.prototype.collapse = function(toAnchor) {
  8848. var toStart = this.isReversed() ? !toAnchor : toAnchor;
  8849. if (this.browserRangeWrapper_) {
  8850. this.browserRangeWrapper_.collapse(toStart);
  8851. }
  8852. if (toStart) {
  8853. this.endNode_ = this.startNode_;
  8854. this.endOffset_ = this.startOffset_;
  8855. } else {
  8856. this.startNode_ = this.endNode_;
  8857. this.startOffset_ = this.endOffset_;
  8858. }
  8859. // Collapsed ranges can't be reversed
  8860. this.isReversed_ = _FALSE;
  8861. };
  8862. // SAVED RANGE OBJECTS
  8863. /**
  8864. * A SavedRange implementation using DOM endpoints.
  8865. * @param {goog.dom.AbstractRange} range The range to save.
  8866. * @constructor
  8867. * @extends {goog.dom.SavedRange}
  8868. * @private
  8869. */
  8870. goog.dom.DomSavedTextRange_ = function(range) {
  8871. /**
  8872. * The anchor node.
  8873. * @type {Node}
  8874. * @private
  8875. */
  8876. this.anchorNode_ = range.getAnchorNode();
  8877. /**
  8878. * The anchor node offset.
  8879. * @type {number}
  8880. * @private
  8881. */
  8882. this.anchorOffset_ = range.getAnchorOffset();
  8883. /**
  8884. * The focus node.
  8885. * @type {Node}
  8886. * @private
  8887. */
  8888. this.focusNode_ = range.getFocusNode();
  8889. /**
  8890. * The focus node offset.
  8891. * @type {number}
  8892. * @private
  8893. */
  8894. this.focusOffset_ = range.getFocusOffset();
  8895. };
  8896. goog.inherits(goog.dom.DomSavedTextRange_, goog.dom.SavedRange);
  8897. /**
  8898. * @return {goog.dom.AbstractRange} The restored range.
  8899. */
  8900. goog.dom.DomSavedTextRange_.prototype.restoreInternal = function() {
  8901. return goog.dom.Range.createFromNodes(this.anchorNode_, this.anchorOffset_,
  8902. this.focusNode_, this.focusOffset_);
  8903. };
  8904. /** @inheritDoc */
  8905. goog.dom.DomSavedTextRange_.prototype.disposeInternal = function() {
  8906. goog.dom.DomSavedTextRange_.superClass_.disposeInternal.call(this);
  8907. this.anchorNode_ = _NULL;
  8908. this.focusNode_ = _NULL;
  8909. };
  8910. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  8911. //
  8912. // Licensed under the Apache License, Version 2.0 (the "License");
  8913. // you may not use this file except in compliance with the License.
  8914. // You may obtain a copy of the License at
  8915. //
  8916. // http://www.apache.org/licenses/LICENSE-2.0
  8917. //
  8918. // Unless required by applicable law or agreed to in writing, software
  8919. // distributed under the License is distributed on an "AS-IS" BASIS,
  8920. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8921. // See the License for the specific language governing permissions and
  8922. // limitations under the License.
  8923. /**
  8924. * @fileoverview Utilities for working with W3C multi-part ranges.
  8925. *
  8926. * @author robbyw@google.com (Robby Walker)
  8927. */
  8928. goog.provide('goog.dom.MultiRange');
  8929. goog.provide('goog.dom.MultiRangeIterator');
  8930. ////goog.require('goog.array');
  8931. //goog.require('goog.dom.AbstractMultiRange');
  8932. //goog.require('goog.dom.AbstractRange');
  8933. //goog.require('goog.dom.RangeIterator');
  8934. //goog.require('goog.dom.RangeType');
  8935. //goog.require('goog.dom.SavedRange');
  8936. //goog.require('goog.dom.TextRange');
  8937. //goog.require('goog.iter.StopIteration');
  8938. /**
  8939. * Creates a new multi part range with no properties. Do not use this
  8940. * constructor: use one of the goog.dom.Range.createFrom* methods instead.
  8941. * @constructor
  8942. * @extends {goog.dom.AbstractMultiRange}
  8943. */
  8944. goog.dom.MultiRange = function() {
  8945. /**
  8946. * Array of browser sub-ranges comprising this multi-range.
  8947. * @type {Array.<Range>}
  8948. * @private
  8949. */
  8950. this.browserRanges_ = [];
  8951. /**
  8952. * Lazily initialized array of range objects comprising this multi-range.
  8953. * @type {Array.<goog.dom.TextRange>}
  8954. * @private
  8955. */
  8956. this.ranges_ = [];
  8957. /**
  8958. * Lazily computed sorted version of ranges_, sorted by start point.
  8959. * @type {Array.<goog.dom.TextRange>?}
  8960. * @private
  8961. */
  8962. this.sortedRanges_ = _NULL;
  8963. /**
  8964. * Lazily computed container node.
  8965. * @type {Node}
  8966. * @private
  8967. */
  8968. this.container_ = _NULL;
  8969. };
  8970. goog.inherits(goog.dom.MultiRange, goog.dom.AbstractMultiRange);
  8971. /**
  8972. * Creates a new range wrapper from the given browser selection object. Do not
  8973. * use this method directly - please use goog.dom.Range.createFrom* instead.
  8974. * @param {Selection} selection The browser selection object.
  8975. * @return {goog.dom.MultiRange} A range wrapper object.
  8976. */
  8977. goog.dom.MultiRange.createFromBrowserSelection = function(selection) {
  8978. var range = new goog.dom.MultiRange();
  8979. for (var i = 0, len = selection.rangeCount; i < len; i++) {
  8980. range.browserRanges_.push(selection.getRangeAt(i));
  8981. }
  8982. return range;
  8983. };
  8984. /**
  8985. * Creates a new range wrapper from the given browser ranges. Do not
  8986. * use this method directly - please use goog.dom.Range.createFrom* instead.
  8987. * @param {Array.<Range>} browserRanges The browser ranges.
  8988. * @return {goog.dom.MultiRange} A range wrapper object.
  8989. */
  8990. goog.dom.MultiRange.createFromBrowserRanges = function(browserRanges) {
  8991. var range = new goog.dom.MultiRange();
  8992. range.browserRanges_ = goog.array.clone(browserRanges);
  8993. return range;
  8994. };
  8995. /**
  8996. * Creates a new range wrapper from the given goog.dom.TextRange objects. Do
  8997. * not use this method directly - please use goog.dom.Range.createFrom* instead.
  8998. * @param {Array.<goog.dom.TextRange>} textRanges The text range objects.
  8999. * @return {goog.dom.MultiRange} A range wrapper object.
  9000. */
  9001. goog.dom.MultiRange.createFromTextRanges = function(textRanges) {
  9002. var range = new goog.dom.MultiRange();
  9003. range.ranges_ = textRanges;
  9004. range.browserRanges_ = textRanges.map(function(range) { // modified
  9005. return range.getBrowserRangeObject();
  9006. });
  9007. return range;
  9008. };
  9009. // Method implementations
  9010. /**
  9011. * Clears cached values. Should be called whenever this.browserRanges_ is
  9012. * modified.
  9013. * @private
  9014. */
  9015. goog.dom.MultiRange.prototype.clearCachedValues_ = function() {
  9016. this.ranges_ = [];
  9017. this.sortedRanges_ = _NULL;
  9018. this.container_ = _NULL;
  9019. };
  9020. /**
  9021. * @return {goog.dom.MultiRange} A clone of this range.
  9022. */
  9023. goog.dom.MultiRange.prototype.clone = function() {
  9024. return goog.dom.MultiRange.createFromBrowserRanges(this.browserRanges_);
  9025. };
  9026. /** @inheritDoc */
  9027. goog.dom.MultiRange.prototype.getType = function() {
  9028. return goog.dom.RangeType.MULTI;
  9029. };
  9030. /** @inheritDoc */
  9031. goog.dom.MultiRange.prototype.getBrowserRangeObject = function() {
  9032. // NOTE(robbyw): This method does not make sense for multi-ranges.
  9033. return this.browserRanges_[0];
  9034. };
  9035. /** @inheritDoc */
  9036. goog.dom.MultiRange.prototype.setBrowserRangeObject = function(nativeRange) {
  9037. // TODO(robbyw): Look in to adding setBrowserSelectionObject.
  9038. return _FALSE;
  9039. };
  9040. /** @inheritDoc */
  9041. goog.dom.MultiRange.prototype.getTextRangeCount = function() {
  9042. return this.browserRanges_.length;
  9043. };
  9044. /** @inheritDoc */
  9045. goog.dom.MultiRange.prototype.getTextRange = function(i) {
  9046. if (!this.ranges_[i]) {
  9047. this.ranges_[i] = goog.dom.TextRange.createFromBrowserRange(
  9048. this.browserRanges_[i]);
  9049. }
  9050. return this.ranges_[i];
  9051. };
  9052. /** @inheritDoc */
  9053. goog.dom.MultiRange.prototype.getContainer = function() {
  9054. if (!this.container_) {
  9055. var nodes = [];
  9056. for (var i = 0, len = this.getTextRangeCount(); i < len; i++) {
  9057. nodes.push(this.getTextRange(i).getContainer());
  9058. }
  9059. this.container_ = goog.dom.findCommonAncestor.apply(_NULL, nodes);
  9060. }
  9061. return this.container_;
  9062. };
  9063. /**
  9064. * @return {Array.<goog.dom.TextRange>} An array of sub-ranges, sorted by start
  9065. * point.
  9066. */
  9067. goog.dom.MultiRange.prototype.getSortedRanges = function() {
  9068. if (!this.sortedRanges_) {
  9069. this.sortedRanges_ = this.getTextRanges();
  9070. this.sortedRanges_.sort(function(a, b) {
  9071. var aStartNode = a.getStartNode();
  9072. var aStartOffset = a.getStartOffset();
  9073. var bStartNode = b.getStartNode();
  9074. var bStartOffset = b.getStartOffset();
  9075. if (aStartNode == bStartNode && aStartOffset == bStartOffset) {
  9076. return 0;
  9077. }
  9078. return goog.dom.Range.isReversed(aStartNode, aStartOffset, bStartNode,
  9079. bStartOffset) ? 1 : -1;
  9080. });
  9081. }
  9082. return this.sortedRanges_;
  9083. };
  9084. /** @inheritDoc */
  9085. goog.dom.MultiRange.prototype.getStartNode = function() {
  9086. return this.getSortedRanges()[0].getStartNode();
  9087. };
  9088. /** @inheritDoc */
  9089. goog.dom.MultiRange.prototype.getStartOffset = function() {
  9090. return this.getSortedRanges()[0].getStartOffset();
  9091. };
  9092. /** @inheritDoc */
  9093. goog.dom.MultiRange.prototype.getEndNode = function() {
  9094. // NOTE(robbyw): This may return the wrong node if any subranges overlap.
  9095. return this.getSortedRanges().last().getEndNode(); // modified
  9096. };
  9097. /** @inheritDoc */
  9098. goog.dom.MultiRange.prototype.getEndOffset = function() {
  9099. // NOTE(robbyw): This may return the wrong value if any subranges overlap.
  9100. return this.getSortedRanges().last().getEndOffset(); // modified
  9101. };
  9102. /** @inheritDoc */
  9103. goog.dom.MultiRange.prototype.isRangeInDocument = function() {
  9104. return this.getTextRanges().every(function(range) { // modified
  9105. return range.isRangeInDocument();
  9106. });
  9107. };
  9108. /** @inheritDoc */
  9109. goog.dom.MultiRange.prototype.isCollapsed = function() {
  9110. return this.browserRanges_.length == 0 ||
  9111. this.browserRanges_.length == 1 && this.getTextRange(0).isCollapsed();
  9112. };
  9113. /** @inheritDoc */
  9114. goog.dom.MultiRange.prototype.getText = function() {
  9115. return this.getTextRanges().map(function(range) { // modified
  9116. return range.getText();
  9117. }).join('');
  9118. };
  9119. /** @inheritDoc */
  9120. goog.dom.MultiRange.prototype.getHtmlFragment = function() {
  9121. return this.getValidHtml();
  9122. };
  9123. /** @inheritDoc */
  9124. goog.dom.MultiRange.prototype.getValidHtml = function() {
  9125. // NOTE(robbyw): This does not behave well if the sub-ranges overlap.
  9126. return this.getTextRanges().map(function(range) { // modified
  9127. return range.getValidHtml();
  9128. }).join('');
  9129. };
  9130. /** @inheritDoc */
  9131. goog.dom.MultiRange.prototype.getPastableHtml = function() {
  9132. // TODO(robbyw): This should probably do something smart like group TR and TD
  9133. // selections in to the same table.
  9134. return this.getValidHtml();
  9135. };
  9136. /** @inheritDoc */
  9137. goog.dom.MultiRange.prototype.__iterator__ = function(opt_keys) {
  9138. return new goog.dom.MultiRangeIterator(this);
  9139. };
  9140. // RANGE ACTIONS
  9141. /** @inheritDoc */
  9142. goog.dom.MultiRange.prototype.select = function() {
  9143. var selection = goog.dom.AbstractRange.getBrowserSelectionForWindow(
  9144. this.getWindow());
  9145. selection.removeAllRanges();
  9146. for (var i = 0, len = this.getTextRangeCount(); i < len; i++) {
  9147. selection.addRange(this.getTextRange(i).getBrowserRangeObject());
  9148. }
  9149. };
  9150. /** @inheritDoc */
  9151. goog.dom.MultiRange.prototype.removeContents = function() {
  9152. this.getTextRanges().each(function(range) { // modified
  9153. range.removeContents();
  9154. });
  9155. };
  9156. // SAVE/RESTORE
  9157. /** @inheritDoc */
  9158. goog.dom.MultiRange.prototype.saveUsingDom = function() {
  9159. return new goog.dom.DomSavedMultiRange_(this);
  9160. };
  9161. // RANGE MODIFICATION
  9162. /**
  9163. * Collapses this range to a single point, either the first or last point
  9164. * depending on the parameter. This will result in the number of ranges in this
  9165. * multi range becoming 1.
  9166. * @param {boolean} toAnchor Whether to collapse to the anchor.
  9167. */
  9168. goog.dom.MultiRange.prototype.collapse = function(toAnchor) {
  9169. if (!this.isCollapsed()) {
  9170. var range = toAnchor ? this.getTextRange(0) : this.getTextRange(
  9171. this.getTextRangeCount() - 1);
  9172. this.clearCachedValues_();
  9173. range.collapse(toAnchor);
  9174. this.ranges_ = [range];
  9175. this.sortedRanges_ = [range];
  9176. this.browserRanges_ = [range.getBrowserRangeObject()];
  9177. }
  9178. };
  9179. // SAVED RANGE OBJECTS
  9180. /**
  9181. * A SavedRange implementation using DOM endpoints.
  9182. * @param {goog.dom.MultiRange} range The range to save.
  9183. * @constructor
  9184. * @extends {goog.dom.SavedRange}
  9185. * @private
  9186. */
  9187. goog.dom.DomSavedMultiRange_ = function(range) {
  9188. /**
  9189. * Array of saved ranges.
  9190. * @type {Array.<goog.dom.SavedRange>}
  9191. * @private
  9192. */
  9193. this.savedRanges_ = range.getTextRanges().map(function(range) { // modified
  9194. return range.saveUsingDom();
  9195. });
  9196. };
  9197. goog.inherits(goog.dom.DomSavedMultiRange_, goog.dom.SavedRange);
  9198. /**
  9199. * @return {goog.dom.MultiRange} The restored range.
  9200. */
  9201. goog.dom.DomSavedMultiRange_.prototype.restoreInternal = function() {
  9202. var ranges = this.savedRanges_.map(function(savedRange) { // modified
  9203. return savedRange.restore();
  9204. });
  9205. return goog.dom.MultiRange.createFromTextRanges(ranges);
  9206. };
  9207. /** @inheritDoc */
  9208. goog.dom.DomSavedMultiRange_.prototype.disposeInternal = function() {
  9209. goog.dom.DomSavedMultiRange_.superClass_.disposeInternal.call(this);
  9210. this.savedRanges_.map(function(savedRange) { // modified
  9211. savedRange.dispose();
  9212. });
  9213. delete this.savedRanges_;
  9214. };
  9215. // RANGE ITERATION
  9216. /**
  9217. * Subclass of goog.dom.TagIterator that iterates over a DOM range. It
  9218. * adds functions to determine the portion of each text node that is selected.
  9219. *
  9220. * @param {goog.dom.MultiRange} range The range to traverse.
  9221. * @constructor
  9222. * @extends {goog.dom.RangeIterator}
  9223. */
  9224. goog.dom.MultiRangeIterator = function(range) {
  9225. if (range) {
  9226. this.iterators_ = range.getSortedRanges().map(
  9227. function(r) {
  9228. return goog.iter.toIterator(r);
  9229. });
  9230. }
  9231. goog.dom.RangeIterator.call(
  9232. this, range ? this.getStartNode() : _NULL, _FALSE);
  9233. };
  9234. goog.inherits(goog.dom.MultiRangeIterator, goog.dom.RangeIterator);
  9235. /**
  9236. * The list of range iterators left to traverse.
  9237. * @type {Array.<goog.dom.RangeIterator>?}
  9238. * @private
  9239. */
  9240. goog.dom.MultiRangeIterator.prototype.iterators_ = _NULL;
  9241. /**
  9242. * The index of the current sub-iterator being traversed.
  9243. * @type {number}
  9244. * @private
  9245. */
  9246. goog.dom.MultiRangeIterator.prototype.currentIdx_ = 0;
  9247. /** @inheritDoc */
  9248. goog.dom.MultiRangeIterator.prototype.getStartTextOffset = function() {
  9249. return this.iterators_[this.currentIdx_].getStartTextOffset();
  9250. };
  9251. /** @inheritDoc */
  9252. goog.dom.MultiRangeIterator.prototype.getEndTextOffset = function() {
  9253. return this.iterators_[this.currentIdx_].getEndTextOffset();
  9254. };
  9255. /** @inheritDoc */
  9256. goog.dom.MultiRangeIterator.prototype.getStartNode = function() {
  9257. return this.iterators_[0].getStartNode();
  9258. };
  9259. /** @inheritDoc */
  9260. goog.dom.MultiRangeIterator.prototype.getEndNode = function() {
  9261. return this.iterators_.last().getEndNode();
  9262. };
  9263. /** @inheritDoc */
  9264. goog.dom.MultiRangeIterator.prototype.isLast = function() {
  9265. return this.iterators_[this.currentIdx_].isLast();
  9266. };
  9267. /** @inheritDoc */
  9268. goog.dom.MultiRangeIterator.prototype.next = function() {
  9269. /** @preserveTry */
  9270. try {
  9271. var it = this.iterators_[this.currentIdx_];
  9272. var next = it.next();
  9273. this.setPosition(it.node, it.tagType, it.depth);
  9274. return next;
  9275. } catch (ex) {
  9276. if (ex !== goog.iter.StopIteration ||
  9277. this.iterators_.length - 1 == this.currentIdx_) {
  9278. throw ex;
  9279. } else {
  9280. // In case we got a StopIteration, increment counter and try again.
  9281. this.currentIdx_++;
  9282. return this.next();
  9283. }
  9284. }
  9285. };
  9286. /**
  9287. * Replaces this iterator's values with values from another.
  9288. * @param {goog.dom.MultiRangeIterator} other The iterator to copy.
  9289. * @protected
  9290. */
  9291. goog.dom.MultiRangeIterator.prototype.copyFrom = function(other) {
  9292. this.iterators_ = goog.array.clone(other.iterators_);
  9293. goog.dom.MultiRangeIterator.superClass_.copyFrom.call(this, other);
  9294. };
  9295. /**
  9296. * @return {goog.dom.MultiRangeIterator} An identical iterator.
  9297. */
  9298. goog.dom.MultiRangeIterator.prototype.clone = function() {
  9299. var copy = new goog.dom.MultiRangeIterator(_NULL);
  9300. copy.copyFrom(this);
  9301. return copy;
  9302. };
  9303. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  9304. //
  9305. // Licensed under the Apache License, Version 2.0 (the "License");
  9306. // you may not use this file except in compliance with the License.
  9307. // You may obtain a copy of the License at
  9308. //
  9309. // http://www.apache.org/licenses/LICENSE-2.0
  9310. //
  9311. // Unless required by applicable law or agreed to in writing, software
  9312. // distributed under the License is distributed on an "AS-IS" BASIS,
  9313. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9314. // See the License for the specific language governing permissions and
  9315. // limitations under the License.
  9316. /**
  9317. * @fileoverview Utilities for working with IE control ranges.
  9318. *
  9319. * @author robbyw@google.com (Robby Walker)
  9320. * @author jparent@google.com (Julie Parent)
  9321. */
  9322. goog.provide('goog.dom.ControlRange');
  9323. goog.provide('goog.dom.ControlRangeIterator');
  9324. //goog.require('goog.dom');
  9325. //goog.require('goog.dom.AbstractMultiRange');
  9326. //goog.require('goog.dom.AbstractRange');
  9327. //goog.require('goog.dom.RangeIterator');
  9328. //goog.require('goog.dom.RangeType');
  9329. //goog.require('goog.dom.SavedRange');
  9330. //goog.require('goog.dom.TagWalkType');
  9331. //goog.require('goog.dom.TextRange');
  9332. //goog.require('goog.iter.StopIteration');
  9333. //goog.require('goog.userAgent');
  9334. /**
  9335. * Create a new control selection with no properties. Do not use this
  9336. * constructor: use one of the goog.dom.Range.createFrom* methods instead.
  9337. * @constructor
  9338. * @extends {goog.dom.AbstractMultiRange}
  9339. */
  9340. goog.dom.ControlRange = function() {
  9341. };
  9342. goog.inherits(goog.dom.ControlRange, goog.dom.AbstractMultiRange);
  9343. /**
  9344. * Create a new range wrapper from the given browser range object. Do not use
  9345. * this method directly - please use goog.dom.Range.createFrom* instead.
  9346. * @param {Object} controlRange The browser range object.
  9347. * @return {goog.dom.ControlRange} A range wrapper object.
  9348. */
  9349. goog.dom.ControlRange.createFromBrowserRange = function(controlRange) {
  9350. var range = new goog.dom.ControlRange();
  9351. range.range_ = controlRange;
  9352. return range;
  9353. };
  9354. /**
  9355. * Create a new range wrapper that selects the given element. Do not use
  9356. * this method directly - please use goog.dom.Range.createFrom* instead.
  9357. * @param {...Element} var_args The element(s) to select.
  9358. * @return {goog.dom.ControlRange} A range wrapper object.
  9359. */
  9360. goog.dom.ControlRange.createFromElements = function(var_args) {
  9361. var range = goog.dom.getOwnerDocument(arguments[0]).body.createControlRange();
  9362. for (var i = 0, len = arguments.length; i < len; i++) {
  9363. range.addElement(arguments[i]);
  9364. }
  9365. return goog.dom.ControlRange.createFromBrowserRange(range);
  9366. };
  9367. /**
  9368. * The IE control range obejct.
  9369. * @type {Object}
  9370. * @private
  9371. */
  9372. goog.dom.ControlRange.prototype.range_ = _NULL;
  9373. /**
  9374. * Cached list of elements.
  9375. * @type {Array.<Element>?}
  9376. * @private
  9377. */
  9378. goog.dom.ControlRange.prototype.elements_ = _NULL;
  9379. /**
  9380. * Cached sorted list of elements.
  9381. * @type {Array.<Element>?}
  9382. * @private
  9383. */
  9384. goog.dom.ControlRange.prototype.sortedElements_ = _NULL;
  9385. // Method implementations
  9386. /**
  9387. * Clear cached values.
  9388. * @private
  9389. */
  9390. goog.dom.ControlRange.prototype.clearCachedValues_ = function() {
  9391. this.elements_ = _NULL;
  9392. this.sortedElements_ = _NULL;
  9393. };
  9394. /**
  9395. * @return {goog.dom.ControlRange} A clone of this range.
  9396. */
  9397. goog.dom.ControlRange.prototype.clone = function() {
  9398. return goog.dom.ControlRange.createFromElements.apply(this,
  9399. this.getElements());
  9400. };
  9401. /** @inheritDoc */
  9402. goog.dom.ControlRange.prototype.getType = function() {
  9403. return goog.dom.RangeType.CONTROL;
  9404. };
  9405. /** @inheritDoc */
  9406. goog.dom.ControlRange.prototype.getBrowserRangeObject = function() {
  9407. return this.range_ || _DOC.body.createControlRange();
  9408. };
  9409. /** @inheritDoc */
  9410. goog.dom.ControlRange.prototype.setBrowserRangeObject = function(nativeRange) {
  9411. if (!goog.dom.AbstractRange.isNativeControlRange(nativeRange)) {
  9412. return _FALSE;
  9413. }
  9414. this.range_ = nativeRange;
  9415. return _TRUE;
  9416. };
  9417. /** @inheritDoc */
  9418. goog.dom.ControlRange.prototype.getTextRangeCount = function() {
  9419. return this.range_ ? this.range_.length : 0;
  9420. };
  9421. /** @inheritDoc */
  9422. goog.dom.ControlRange.prototype.getTextRange = function(i) {
  9423. return goog.dom.TextRange.createFromNodeContents(this.range_.item(i));
  9424. };
  9425. /** @inheritDoc */
  9426. goog.dom.ControlRange.prototype.getContainer = function() {
  9427. return goog.dom.findCommonAncestor.apply(_NULL, this.getElements());
  9428. };
  9429. /** @inheritDoc */
  9430. goog.dom.ControlRange.prototype.getStartNode = function() {
  9431. return this.getSortedElements()[0];
  9432. };
  9433. /** @inheritDoc */
  9434. goog.dom.ControlRange.prototype.getStartOffset = function() {
  9435. return 0;
  9436. };
  9437. /** @inheritDoc */
  9438. goog.dom.ControlRange.prototype.getEndNode = function() {
  9439. var sorted = this.getSortedElements();
  9440. var startsLast = /** @type {Node} */ (sorted.last()); // modified
  9441. return /** @type {Node} */ (sorted.find(function(el) {
  9442. return goog.dom.contains(el, startsLast);
  9443. }));
  9444. };
  9445. /** @inheritDoc */
  9446. goog.dom.ControlRange.prototype.getEndOffset = function() {
  9447. return this.getEndNode().childNodes.length;
  9448. };
  9449. // TODO(robbyw): Figure out how to unify getElements with TextRange API.
  9450. /**
  9451. * @return {Array.<Element>} Array of elements in the control range.
  9452. */
  9453. goog.dom.ControlRange.prototype.getElements = function() {
  9454. if (!this.elements_) {
  9455. this.elements_ = [];
  9456. if (this.range_) {
  9457. for (var i = 0; i < this.range_.length; i++) {
  9458. this.elements_.push(this.range_.item(i));
  9459. }
  9460. }
  9461. }
  9462. return this.elements_;
  9463. };
  9464. /**
  9465. * @return {Array.<Element>} Array of elements comprising the control range,
  9466. * sorted by document order.
  9467. */
  9468. goog.dom.ControlRange.prototype.getSortedElements = function() {
  9469. if (!this.sortedElements_) {
  9470. this.sortedElements_ = this.getElements().concat();
  9471. this.sortedElements_.sort(function(a, b) {
  9472. return a.sourceIndex - b.sourceIndex;
  9473. });
  9474. }
  9475. return this.sortedElements_;
  9476. };
  9477. /** @inheritDoc */
  9478. goog.dom.ControlRange.prototype.isRangeInDocument = function() {
  9479. var returnValue = _FALSE;
  9480. try {
  9481. returnValue = this.getElements().every(function(element) { // modified
  9482. // On IE, this throws an exception when the range is detached.
  9483. return goog.userAgent.IE ?
  9484. element.parentNode :
  9485. goog.dom.contains(element.ownerDocument.body, element);
  9486. });
  9487. } catch (e) {
  9488. // IE sometimes throws Invalid Argument errors for detached elements.
  9489. // Note: trying to return a value from the above try block can cause IE
  9490. // to crash. It is necessary to use the local returnValue.
  9491. }
  9492. return returnValue;
  9493. };
  9494. /** @inheritDoc */
  9495. goog.dom.ControlRange.prototype.isCollapsed = function() {
  9496. return !this.range_ || !this.range_.length;
  9497. };
  9498. /** @inheritDoc */
  9499. goog.dom.ControlRange.prototype.getText = function() {
  9500. // TODO(robbyw): What about for table selections? Should those have text?
  9501. return '';
  9502. };
  9503. /** @inheritDoc */
  9504. goog.dom.ControlRange.prototype.getHtmlFragment = function() {
  9505. return this.getSortedElements().map(goog.dom.getOuterHtml). // modified
  9506. join('');
  9507. };
  9508. /** @inheritDoc */
  9509. goog.dom.ControlRange.prototype.getValidHtml = function() {
  9510. return this.getHtmlFragment();
  9511. };
  9512. /** @inheritDoc */
  9513. goog.dom.ControlRange.prototype.getPastableHtml =
  9514. goog.dom.ControlRange.prototype.getValidHtml;
  9515. /** @inheritDoc */
  9516. goog.dom.ControlRange.prototype.__iterator__ = function(opt_keys) {
  9517. return new goog.dom.ControlRangeIterator(this);
  9518. };
  9519. // RANGE ACTIONS
  9520. /** @inheritDoc */
  9521. goog.dom.ControlRange.prototype.select = function() {
  9522. if (this.range_) {
  9523. this.range_.select();
  9524. }
  9525. };
  9526. /** @inheritDoc */
  9527. goog.dom.ControlRange.prototype.removeContents = function() {
  9528. // TODO(robbyw): Test implementing with execCommand('Delete')
  9529. if (this.range_) {
  9530. var nodes = [];
  9531. for (var i = 0, len = this.range_.length; i < len; i++) {
  9532. nodes.push(this.range_.item(i));
  9533. }
  9534. nodes.each(goog.dom.removeNode); // modified
  9535. this.collapse(_FALSE);
  9536. }
  9537. };
  9538. // SAVE/RESTORE
  9539. /** @inheritDoc */
  9540. goog.dom.ControlRange.prototype.saveUsingDom = function() {
  9541. return new goog.dom.DomSavedControlRange_(this);
  9542. };
  9543. // RANGE MODIFICATION
  9544. /** @inheritDoc */
  9545. goog.dom.ControlRange.prototype.collapse = function(toAnchor) {
  9546. // TODO(robbyw): Should this return a text range? If so, API needs to change.
  9547. this.range_ = _NULL;
  9548. this.clearCachedValues_();
  9549. };
  9550. // SAVED RANGE OBJECTS
  9551. /**
  9552. * A SavedRange implementation using DOM endpoints.
  9553. * @param {goog.dom.ControlRange} range The range to save.
  9554. * @constructor
  9555. * @extends {goog.dom.SavedRange}
  9556. * @private
  9557. */
  9558. goog.dom.DomSavedControlRange_ = function(range) {
  9559. /**
  9560. * The element list.
  9561. * @type {Array.<Element>}
  9562. * @private
  9563. */
  9564. this.elements_ = range.getElements();
  9565. };
  9566. goog.inherits(goog.dom.DomSavedControlRange_, goog.dom.SavedRange);
  9567. /**
  9568. * @return {goog.dom.ControlRange} The restored range.
  9569. */
  9570. goog.dom.DomSavedControlRange_.prototype.restoreInternal = function() {
  9571. var doc = this.elements_.length ?
  9572. goog.dom.getOwnerDocument(this.elements_[0]) : document;
  9573. var controlRange = doc.body.createControlRange();
  9574. for (var i = 0, len = this.elements_.length; i < len; i++) {
  9575. controlRange.addElement(this.elements_[i]);
  9576. }
  9577. return goog.dom.ControlRange.createFromBrowserRange(controlRange);
  9578. };
  9579. /** @inheritDoc */
  9580. goog.dom.DomSavedControlRange_.prototype.disposeInternal = function() {
  9581. goog.dom.DomSavedControlRange_.superClass_.disposeInternal.call(this);
  9582. delete this.elements_;
  9583. };
  9584. // RANGE ITERATION
  9585. /**
  9586. * Subclass of goog.dom.TagIterator that iterates over a DOM range. It
  9587. * adds functions to determine the portion of each text node that is selected.
  9588. *
  9589. * @param {goog.dom.ControlRange?} range The range to traverse.
  9590. * @constructor
  9591. * @extends {goog.dom.RangeIterator}
  9592. */
  9593. goog.dom.ControlRangeIterator = function(range) {
  9594. if (range) {
  9595. this.elements_ = range.getSortedElements();
  9596. this.startNode_ = this.elements_.shift();
  9597. this.endNode_ = /** @type {Node} */ (this.elements_.last()) || // modified
  9598. this.startNode_;
  9599. }
  9600. goog.dom.RangeIterator.call(this, this.startNode_, _FALSE);
  9601. };
  9602. goog.inherits(goog.dom.ControlRangeIterator, goog.dom.RangeIterator);
  9603. /**
  9604. * The first node in the selection.
  9605. * @type {Node}
  9606. * @private
  9607. */
  9608. goog.dom.ControlRangeIterator.prototype.startNode_ = _NULL;
  9609. /**
  9610. * The last node in the selection.
  9611. * @type {Node}
  9612. * @private
  9613. */
  9614. goog.dom.ControlRangeIterator.prototype.endNode_ = _NULL;
  9615. /**
  9616. * The list of elements left to traverse.
  9617. * @type {Array.<Element>?}
  9618. * @private
  9619. */
  9620. goog.dom.ControlRangeIterator.prototype.elements_ = _NULL;
  9621. /** @inheritDoc */
  9622. goog.dom.ControlRangeIterator.prototype.getStartTextOffset = function() {
  9623. return 0;
  9624. };
  9625. /** @inheritDoc */
  9626. goog.dom.ControlRangeIterator.prototype.getEndTextOffset = function() {
  9627. return 0;
  9628. };
  9629. /** @inheritDoc */
  9630. goog.dom.ControlRangeIterator.prototype.getStartNode = function() {
  9631. return this.startNode_;
  9632. };
  9633. /** @inheritDoc */
  9634. goog.dom.ControlRangeIterator.prototype.getEndNode = function() {
  9635. return this.endNode_;
  9636. };
  9637. /** @inheritDoc */
  9638. goog.dom.ControlRangeIterator.prototype.isLast = function() {
  9639. return !this.depth && !this.elements_.length;
  9640. };
  9641. /**
  9642. * Move to the next position in the selection.
  9643. * Throws {@code goog.iter.StopIteration} when it passes the end of the range.
  9644. * @return {Node} The node at the next position.
  9645. */
  9646. goog.dom.ControlRangeIterator.prototype.next = function() {
  9647. // Iterate over each element in the range, and all of its children.
  9648. if (this.isLast()) {
  9649. throw goog.iter.StopIteration;
  9650. } else if (!this.depth) {
  9651. var el = this.elements_.shift();
  9652. this.setPosition(el,
  9653. goog.dom.TagWalkType.START_TAG,
  9654. goog.dom.TagWalkType.START_TAG);
  9655. return el;
  9656. }
  9657. // Call the super function.
  9658. return goog.dom.ControlRangeIterator.superClass_.next.call(this);
  9659. };
  9660. /**
  9661. * Replace this iterator's values with values from another.
  9662. * @param {goog.dom.ControlRangeIterator} other The iterator to copy.
  9663. * @protected
  9664. */
  9665. goog.dom.ControlRangeIterator.prototype.copyFrom = function(other) {
  9666. this.elements_ = other.elements_;
  9667. this.startNode_ = other.startNode_;
  9668. this.endNode_ = other.endNode_;
  9669. goog.dom.ControlRangeIterator.superClass_.copyFrom.call(this, other);
  9670. };
  9671. /**
  9672. * @return {goog.dom.ControlRangeIterator} An identical iterator.
  9673. */
  9674. goog.dom.ControlRangeIterator.prototype.clone = function() {
  9675. var copy = new goog.dom.ControlRangeIterator(_NULL);
  9676. copy.copyFrom(this);
  9677. return copy;
  9678. };
  9679. // Copyright 2007 The Closure Library Authors. All Rights Reserved.
  9680. //
  9681. // Licensed under the Apache License, Version 2.0 (the "License");
  9682. // you may not use this file except in compliance with the License.
  9683. // You may obtain a copy of the License at
  9684. //
  9685. // http://www.apache.org/licenses/LICENSE-2.0
  9686. //
  9687. // Unless required by applicable law or agreed to in writing, software
  9688. // distributed under the License is distributed on an "AS-IS" BASIS,
  9689. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9690. // See the License for the specific language governing permissions and
  9691. // limitations under the License.
  9692. /**
  9693. * @fileoverview Utilities for working with ranges in HTML documents.
  9694. *
  9695. * @author robbyw@google.com (Robby Walker)
  9696. * @author ojan@google.com (Ojan Vafai)
  9697. * @author jparent@google.com (Julie Parent)
  9698. */
  9699. goog.provide('goog.dom.Range');
  9700. //goog.require('goog.dom');
  9701. //goog.require('goog.dom.AbstractRange');
  9702. //goog.require('goog.dom.ControlRange');
  9703. //goog.require('goog.dom.MultiRange');
  9704. //goog.require('goog.dom.NodeType');
  9705. //goog.require('goog.dom.TextRange');
  9706. //goog.require('goog.userAgent');
  9707. /**
  9708. * Create a new selection from the given browser window's current selection.
  9709. * Note that this object does not auto-update if the user changes their
  9710. * selection and should be used as a snapshot.
  9711. * @param {Window=} opt_win The window to get the selection of. Defaults to the
  9712. * window this class was defined in.
  9713. * @return {goog.dom.AbstractRange?} A range wrapper object, or null if there
  9714. * was an error.
  9715. */
  9716. goog.dom.Range.createFromWindow = function(opt_win) {
  9717. var sel = goog.dom.AbstractRange.getBrowserSelectionForWindow(
  9718. opt_win || window);
  9719. return sel && goog.dom.Range.createFromBrowserSelection(sel);
  9720. };
  9721. /**
  9722. * Create a new range wrapper from the given browser selection object. Note
  9723. * that this object does not auto-update if the user changes their selection and
  9724. * should be used as a snapshot.
  9725. * @param {!Object} selection The browser selection object.
  9726. * @return {goog.dom.AbstractRange?} A range wrapper object or null if there
  9727. * was an error.
  9728. */
  9729. goog.dom.Range.createFromBrowserSelection = function(selection) {
  9730. var range;
  9731. var isReversed = _FALSE;
  9732. if (selection.createRange) {
  9733. /** @preserveTry */
  9734. try {
  9735. range = selection.createRange();
  9736. } catch (e) {
  9737. // Access denied errors can be thrown here in IE if the selection was
  9738. // a flash obj or if there are cross domain issues
  9739. return _NULL;
  9740. }
  9741. } else if (selection.rangeCount) {
  9742. if (selection.rangeCount > 1) {
  9743. return goog.dom.MultiRange.createFromBrowserSelection(
  9744. /** @type {Selection} */ (selection));
  9745. } else {
  9746. range = selection.getRangeAt(0);
  9747. isReversed = goog.dom.Range.isReversed(selection.anchorNode,
  9748. selection.anchorOffset, selection.focusNode, selection.focusOffset);
  9749. }
  9750. } else {
  9751. return _NULL;
  9752. }
  9753. return goog.dom.Range.createFromBrowserRange(range, isReversed);
  9754. };
  9755. /**
  9756. * Create a new range wrapper from the given browser range object.
  9757. * @param {Range|TextRange} range The browser range object.
  9758. * @param {boolean=} opt_isReversed Whether the focus node is before the anchor
  9759. * node.
  9760. * @return {goog.dom.AbstractRange} A range wrapper object.
  9761. */
  9762. goog.dom.Range.createFromBrowserRange = function(range, opt_isReversed) {
  9763. // Create an IE control range when appropriate.
  9764. return goog.dom.AbstractRange.isNativeControlRange(range) ?
  9765. goog.dom.ControlRange.createFromBrowserRange(range) :
  9766. goog.dom.TextRange.createFromBrowserRange(range, opt_isReversed);
  9767. };
  9768. /**
  9769. * Create a new range wrapper that selects the given node's text.
  9770. * @param {Node} node The node to select.
  9771. * @param {boolean=} opt_isReversed Whether the focus node is before the anchor
  9772. * node.
  9773. * @return {goog.dom.AbstractRange} A range wrapper object.
  9774. */
  9775. goog.dom.Range.createFromNodeContents = function(node, opt_isReversed) {
  9776. return goog.dom.TextRange.createFromNodeContents(node, opt_isReversed);
  9777. };
  9778. /**
  9779. * Create a new range wrapper that represents a caret at the given node,
  9780. * accounting for the given offset. This always creates a TextRange, regardless
  9781. * of whether node is an image node or other control range type node.
  9782. * @param {Node} node The node to place a caret at.
  9783. * @param {number} offset The offset within the node to place the caret at.
  9784. * @return {goog.dom.AbstractRange} A range wrapper object.
  9785. */
  9786. goog.dom.Range.createCaret = function(node, offset) {
  9787. return goog.dom.TextRange.createFromNodes(node, offset, node, offset);
  9788. };
  9789. /**
  9790. * Create a new range wrapper that selects the area between the given nodes,
  9791. * accounting for the given offsets.
  9792. * @param {Node} startNode The node to start with.
  9793. * @param {number} startOffset The offset within the node to start.
  9794. * @param {Node} endNode The node to end with.
  9795. * @param {number} endOffset The offset within the node to end.
  9796. * @return {goog.dom.AbstractRange} A range wrapper object.
  9797. */
  9798. goog.dom.Range.createFromNodes = function(startNode, startOffset, endNode,
  9799. endOffset) {
  9800. return goog.dom.TextRange.createFromNodes(startNode, startOffset, endNode,
  9801. endOffset);
  9802. };
  9803. /**
  9804. * Clears the window's selection.
  9805. * @param {Window=} opt_win The window to get the selection of. Defaults to the
  9806. * window this class was defined in.
  9807. */
  9808. goog.dom.Range.clearSelection = function(opt_win) {
  9809. var sel = goog.dom.AbstractRange.getBrowserSelectionForWindow(
  9810. opt_win || window);
  9811. if (!sel) {
  9812. return;
  9813. }
  9814. if (sel.empty) {
  9815. // We can't just check that the selection is empty, becuase IE
  9816. // sometimes gets confused.
  9817. try {
  9818. sel.empty();
  9819. } catch (e) {
  9820. // Emptying an already empty selection throws an exception in IE
  9821. }
  9822. } else {
  9823. sel.removeAllRanges();
  9824. }
  9825. };
  9826. /**
  9827. * Returns whether the focus position occurs before the anchor position.
  9828. * @param {Node} anchorNode The node to start with.
  9829. * @param {number} anchorOffset The offset within the node to start.
  9830. * @param {Node} focusNode The node to end with.
  9831. * @param {number} focusOffset The offset within the node to end.
  9832. * @return {boolean} Whether the focus position occurs before the anchor
  9833. * position.
  9834. */
  9835. goog.dom.Range.isReversed = function(anchorNode, anchorOffset, focusNode,
  9836. focusOffset) {
  9837. if (anchorNode == focusNode) {
  9838. return focusOffset < anchorOffset;
  9839. }
  9840. var child;
  9841. if (anchorNode.nodeType == goog.dom.NodeType.ELEMENT && anchorOffset) {
  9842. child = anchorNode.childNodes[anchorOffset];
  9843. if (child) {
  9844. anchorNode = child;
  9845. anchorOffset = 0;
  9846. } else if (goog.dom.contains(anchorNode, focusNode)) {
  9847. // If focus node is contained in anchorNode, it must be before the
  9848. // end of the node. Hence we are reversed.
  9849. return _TRUE;
  9850. }
  9851. }
  9852. if (focusNode.nodeType == goog.dom.NodeType.ELEMENT && focusOffset) {
  9853. child = focusNode.childNodes[focusOffset];
  9854. if (child) {
  9855. focusNode = child;
  9856. focusOffset = 0;
  9857. } else if (goog.dom.contains(focusNode, anchorNode)) {
  9858. // If anchor node is contained in focusNode, it must be before the
  9859. // end of the node. Hence we are not reversed.
  9860. return _FALSE;
  9861. }
  9862. }
  9863. return (goog.dom.compareNodeOrder(anchorNode, focusNode) ||
  9864. anchorOffset - focusOffset) > 0;
  9865. };
  9866. goog.provide("export_dep");
  9867. //goog.require('goog.dom.ControlRange');
  9868. //goog.require('goog.dom.MultiRange');
  9869. //goog.require('goog.dom.Range');