rangy-core.js 158 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845
  1. /**
  2. * Rangy, a cross-browser JavaScript range and selection library
  3. * https://github.com/timdown/rangy
  4. *
  5. * Copyright 2015, Tim Down
  6. * Licensed under the MIT license.
  7. * Version: 1.3.0
  8. * Build date: 10 May 2015
  9. */
  10. (function(factory, root) {
  11. if (typeof define == "function" && define.amd) {
  12. // AMD. Register as an anonymous module.
  13. define(factory);
  14. } else if (typeof module != "undefined" && typeof exports == "object") {
  15. // Node/CommonJS style
  16. module.exports = factory();
  17. } else {
  18. // No AMD or CommonJS support so we place Rangy in (probably) the global variable
  19. root.rangy = factory();
  20. }
  21. })(function() {
  22. var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined";
  23. // Minimal set of properties required for DOM Level 2 Range compliance. Comparison constants such as START_TO_START
  24. // are omitted because ranges in KHTML do not have them but otherwise work perfectly well. See issue 113.
  25. var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
  26. "commonAncestorContainer"];
  27. // Minimal set of methods required for DOM Level 2 Range compliance
  28. var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore",
  29. "setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents",
  30. "extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"];
  31. var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"];
  32. // Subset of TextRange's full set of methods that we're interested in
  33. var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "moveToElementText", "parentElement", "select",
  34. "setEndPoint", "getBoundingClientRect"];
  35. /*----------------------------------------------------------------------------------------------------------------*/
  36. // Trio of functions taken from Peter Michaux's article:
  37. // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
  38. function isHostMethod(o, p) {
  39. var t = typeof o[p];
  40. return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown";
  41. }
  42. function isHostObject(o, p) {
  43. return !!(typeof o[p] == OBJECT && o[p]);
  44. }
  45. function isHostProperty(o, p) {
  46. return typeof o[p] != UNDEFINED;
  47. }
  48. // Creates a convenience function to save verbose repeated calls to tests functions
  49. function createMultiplePropertyTest(testFunc) {
  50. return function(o, props) {
  51. var i = props.length;
  52. while (i--) {
  53. if (!testFunc(o, props[i])) {
  54. return false;
  55. }
  56. }
  57. return true;
  58. };
  59. }
  60. // Next trio of functions are a convenience to save verbose repeated calls to previous two functions
  61. var areHostMethods = createMultiplePropertyTest(isHostMethod);
  62. var areHostObjects = createMultiplePropertyTest(isHostObject);
  63. var areHostProperties = createMultiplePropertyTest(isHostProperty);
  64. function isTextRange(range) {
  65. return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);
  66. }
  67. function getBody(doc) {
  68. return isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0];
  69. }
  70. var forEach = [].forEach ?
  71. function(arr, func) {
  72. arr.forEach(func);
  73. } :
  74. function(arr, func) {
  75. for (var i = 0, len = arr.length; i < len; ++i) {
  76. func(arr[i], i);
  77. }
  78. };
  79. var modules = {};
  80. var isBrowser = (typeof window != UNDEFINED && typeof document != UNDEFINED);
  81. var util = {
  82. isHostMethod: isHostMethod,
  83. isHostObject: isHostObject,
  84. isHostProperty: isHostProperty,
  85. areHostMethods: areHostMethods,
  86. areHostObjects: areHostObjects,
  87. areHostProperties: areHostProperties,
  88. isTextRange: isTextRange,
  89. getBody: getBody,
  90. forEach: forEach
  91. };
  92. var api = {
  93. version: "1.3.0",
  94. initialized: false,
  95. isBrowser: isBrowser,
  96. supported: true,
  97. util: util,
  98. features: {},
  99. modules: modules,
  100. config: {
  101. alertOnFail: false,
  102. alertOnWarn: false,
  103. preferTextRange: false,
  104. autoInitialize: (typeof rangyAutoInitialize == UNDEFINED) ? true : rangyAutoInitialize
  105. }
  106. };
  107. function consoleLog(msg) {
  108. if (typeof console != UNDEFINED && isHostMethod(console, "log")) {
  109. console.log(msg);
  110. }
  111. }
  112. function alertOrLog(msg, shouldAlert) {
  113. if (isBrowser && shouldAlert) {
  114. alert(msg);
  115. } else {
  116. consoleLog(msg);
  117. }
  118. }
  119. function fail(reason) {
  120. api.initialized = true;
  121. api.supported = false;
  122. alertOrLog("Rangy is not supported in this environment. Reason: " + reason, api.config.alertOnFail);
  123. }
  124. api.fail = fail;
  125. function warn(msg) {
  126. alertOrLog("Rangy warning: " + msg, api.config.alertOnWarn);
  127. }
  128. api.warn = warn;
  129. // Add utility extend() method
  130. var extend;
  131. if ({}.hasOwnProperty) {
  132. util.extend = extend = function(obj, props, deep) {
  133. var o, p;
  134. for (var i in props) {
  135. if (props.hasOwnProperty(i)) {
  136. o = obj[i];
  137. p = props[i];
  138. if (deep && o !== null && typeof o == "object" && p !== null && typeof p == "object") {
  139. extend(o, p, true);
  140. }
  141. obj[i] = p;
  142. }
  143. }
  144. // Special case for toString, which does not show up in for...in loops in IE <= 8
  145. if (props.hasOwnProperty("toString")) {
  146. obj.toString = props.toString;
  147. }
  148. return obj;
  149. };
  150. util.createOptions = function(optionsParam, defaults) {
  151. var options = {};
  152. extend(options, defaults);
  153. if (optionsParam) {
  154. extend(options, optionsParam);
  155. }
  156. return options;
  157. };
  158. } else {
  159. fail("hasOwnProperty not supported");
  160. }
  161. // Test whether we're in a browser and bail out if not
  162. if (!isBrowser) {
  163. fail("Rangy can only run in a browser");
  164. }
  165. // Test whether Array.prototype.slice can be relied on for NodeLists and use an alternative toArray() if not
  166. (function() {
  167. var toArray;
  168. if (isBrowser) {
  169. var el = document.createElement("div");
  170. el.appendChild(document.createElement("span"));
  171. var slice = [].slice;
  172. try {
  173. if (slice.call(el.childNodes, 0)[0].nodeType == 1) {
  174. toArray = function(arrayLike) {
  175. return slice.call(arrayLike, 0);
  176. };
  177. }
  178. } catch (e) {}
  179. }
  180. if (!toArray) {
  181. toArray = function(arrayLike) {
  182. var arr = [];
  183. for (var i = 0, len = arrayLike.length; i < len; ++i) {
  184. arr[i] = arrayLike[i];
  185. }
  186. return arr;
  187. };
  188. }
  189. util.toArray = toArray;
  190. })();
  191. // Very simple event handler wrapper function that doesn't attempt to solve issues such as "this" handling or
  192. // normalization of event properties
  193. var addListener;
  194. if (isBrowser) {
  195. if (isHostMethod(document, "addEventListener")) {
  196. addListener = function(obj, eventType, listener) {
  197. obj.addEventListener(eventType, listener, false);
  198. };
  199. } else if (isHostMethod(document, "attachEvent")) {
  200. addListener = function(obj, eventType, listener) {
  201. obj.attachEvent("on" + eventType, listener);
  202. };
  203. } else {
  204. fail("Document does not have required addEventListener or attachEvent method");
  205. }
  206. util.addListener = addListener;
  207. }
  208. var initListeners = [];
  209. function getErrorDesc(ex) {
  210. return ex.message || ex.description || String(ex);
  211. }
  212. // Initialization
  213. function init() {
  214. if (!isBrowser || api.initialized) {
  215. return;
  216. }
  217. var testRange;
  218. var implementsDomRange = false, implementsTextRange = false;
  219. // First, perform basic feature tests
  220. if (isHostMethod(document, "createRange")) {
  221. testRange = document.createRange();
  222. if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {
  223. implementsDomRange = true;
  224. }
  225. }
  226. var body = getBody(document);
  227. if (!body || body.nodeName.toLowerCase() != "body") {
  228. fail("No body element found");
  229. return;
  230. }
  231. if (body && isHostMethod(body, "createTextRange")) {
  232. testRange = body.createTextRange();
  233. if (isTextRange(testRange)) {
  234. implementsTextRange = true;
  235. }
  236. }
  237. if (!implementsDomRange && !implementsTextRange) {
  238. fail("Neither Range nor TextRange are available");
  239. return;
  240. }
  241. api.initialized = true;
  242. api.features = {
  243. implementsDomRange: implementsDomRange,
  244. implementsTextRange: implementsTextRange
  245. };
  246. // Initialize modules
  247. var module, errorMessage;
  248. for (var moduleName in modules) {
  249. if ( (module = modules[moduleName]) instanceof Module ) {
  250. module.init(module, api);
  251. }
  252. }
  253. // Call init listeners
  254. for (var i = 0, len = initListeners.length; i < len; ++i) {
  255. try {
  256. initListeners[i](api);
  257. } catch (ex) {
  258. errorMessage = "Rangy init listener threw an exception. Continuing. Detail: " + getErrorDesc(ex);
  259. consoleLog(errorMessage);
  260. }
  261. }
  262. }
  263. function deprecationNotice(deprecated, replacement, module) {
  264. if (module) {
  265. deprecated += " in module " + module.name;
  266. }
  267. api.warn("DEPRECATED: " + deprecated + " is deprecated. Please use " +
  268. replacement + " instead.");
  269. }
  270. function createAliasForDeprecatedMethod(owner, deprecated, replacement, module) {
  271. owner[deprecated] = function() {
  272. deprecationNotice(deprecated, replacement, module);
  273. return owner[replacement].apply(owner, util.toArray(arguments));
  274. };
  275. }
  276. util.deprecationNotice = deprecationNotice;
  277. util.createAliasForDeprecatedMethod = createAliasForDeprecatedMethod;
  278. // Allow external scripts to initialize this library in case it's loaded after the document has loaded
  279. api.init = init;
  280. // Execute listener immediately if already initialized
  281. api.addInitListener = function(listener) {
  282. if (api.initialized) {
  283. listener(api);
  284. } else {
  285. initListeners.push(listener);
  286. }
  287. };
  288. var shimListeners = [];
  289. api.addShimListener = function(listener) {
  290. shimListeners.push(listener);
  291. };
  292. function shim(win) {
  293. win = win || window;
  294. init();
  295. // Notify listeners
  296. for (var i = 0, len = shimListeners.length; i < len; ++i) {
  297. shimListeners[i](win);
  298. }
  299. }
  300. if (isBrowser) {
  301. api.shim = api.createMissingNativeApi = shim;
  302. createAliasForDeprecatedMethod(api, "createMissingNativeApi", "shim");
  303. }
  304. function Module(name, dependencies, initializer) {
  305. this.name = name;
  306. this.dependencies = dependencies;
  307. this.initialized = false;
  308. this.supported = false;
  309. this.initializer = initializer;
  310. }
  311. Module.prototype = {
  312. init: function() {
  313. var requiredModuleNames = this.dependencies || [];
  314. for (var i = 0, len = requiredModuleNames.length, requiredModule, moduleName; i < len; ++i) {
  315. moduleName = requiredModuleNames[i];
  316. requiredModule = modules[moduleName];
  317. if (!requiredModule || !(requiredModule instanceof Module)) {
  318. throw new Error("required module '" + moduleName + "' not found");
  319. }
  320. requiredModule.init();
  321. if (!requiredModule.supported) {
  322. throw new Error("required module '" + moduleName + "' not supported");
  323. }
  324. }
  325. // Now run initializer
  326. this.initializer(this);
  327. },
  328. fail: function(reason) {
  329. this.initialized = true;
  330. this.supported = false;
  331. throw new Error(reason);
  332. },
  333. warn: function(msg) {
  334. api.warn("Module " + this.name + ": " + msg);
  335. },
  336. deprecationNotice: function(deprecated, replacement) {
  337. api.warn("DEPRECATED: " + deprecated + " in module " + this.name + " is deprecated. Please use " +
  338. replacement + " instead");
  339. },
  340. createError: function(msg) {
  341. return new Error("Error in Rangy " + this.name + " module: " + msg);
  342. }
  343. };
  344. function createModule(name, dependencies, initFunc) {
  345. var newModule = new Module(name, dependencies, function(module) {
  346. if (!module.initialized) {
  347. module.initialized = true;
  348. try {
  349. initFunc(api, module);
  350. module.supported = true;
  351. } catch (ex) {
  352. var errorMessage = "Module '" + name + "' failed to load: " + getErrorDesc(ex);
  353. consoleLog(errorMessage);
  354. if (ex.stack) {
  355. consoleLog(ex.stack);
  356. }
  357. }
  358. }
  359. });
  360. modules[name] = newModule;
  361. return newModule;
  362. }
  363. api.createModule = function(name) {
  364. // Allow 2 or 3 arguments (second argument is an optional array of dependencies)
  365. var initFunc, dependencies;
  366. if (arguments.length == 2) {
  367. initFunc = arguments[1];
  368. dependencies = [];
  369. } else {
  370. initFunc = arguments[2];
  371. dependencies = arguments[1];
  372. }
  373. var module = createModule(name, dependencies, initFunc);
  374. // Initialize the module immediately if the core is already initialized
  375. if (api.initialized && api.supported) {
  376. module.init();
  377. }
  378. };
  379. api.createCoreModule = function(name, dependencies, initFunc) {
  380. createModule(name, dependencies, initFunc);
  381. };
  382. /*----------------------------------------------------------------------------------------------------------------*/
  383. // Ensure rangy.rangePrototype and rangy.selectionPrototype are available immediately
  384. function RangePrototype() {}
  385. api.RangePrototype = RangePrototype;
  386. api.rangePrototype = new RangePrototype();
  387. function SelectionPrototype() {}
  388. api.selectionPrototype = new SelectionPrototype();
  389. /*----------------------------------------------------------------------------------------------------------------*/
  390. // DOM utility methods used by Rangy
  391. api.createCoreModule("DomUtil", [], function(api, module) {
  392. var UNDEF = "undefined";
  393. var util = api.util;
  394. var getBody = util.getBody;
  395. // Perform feature tests
  396. if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) {
  397. module.fail("document missing a Node creation method");
  398. }
  399. if (!util.isHostMethod(document, "getElementsByTagName")) {
  400. module.fail("document missing getElementsByTagName method");
  401. }
  402. var el = document.createElement("div");
  403. if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] ||
  404. !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) {
  405. module.fail("Incomplete Element implementation");
  406. }
  407. // innerHTML is required for Range's createContextualFragment method
  408. if (!util.isHostProperty(el, "innerHTML")) {
  409. module.fail("Element is missing innerHTML property");
  410. }
  411. var textNode = document.createTextNode("test");
  412. if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] ||
  413. !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) ||
  414. !util.areHostProperties(textNode, ["data"]))) {
  415. module.fail("Incomplete Text Node implementation");
  416. }
  417. /*----------------------------------------------------------------------------------------------------------------*/
  418. // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been
  419. // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that
  420. // contains just the document as a single element and the value searched for is the document.
  421. var arrayContains = /*Array.prototype.indexOf ?
  422. function(arr, val) {
  423. return arr.indexOf(val) > -1;
  424. }:*/
  425. function(arr, val) {
  426. var i = arr.length;
  427. while (i--) {
  428. if (arr[i] === val) {
  429. return true;
  430. }
  431. }
  432. return false;
  433. };
  434. // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI
  435. function isHtmlNamespace(node) {
  436. var ns;
  437. return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml");
  438. }
  439. function parentElement(node) {
  440. var parent = node.parentNode;
  441. return (parent.nodeType == 1) ? parent : null;
  442. }
  443. function getNodeIndex(node) {
  444. var i = 0;
  445. while( (node = node.previousSibling) ) {
  446. ++i;
  447. }
  448. return i;
  449. }
  450. function getNodeLength(node) {
  451. switch (node.nodeType) {
  452. case 7:
  453. case 10:
  454. return 0;
  455. case 3:
  456. case 8:
  457. return node.length;
  458. default:
  459. return node.childNodes.length;
  460. }
  461. }
  462. function getCommonAncestor(node1, node2) {
  463. var ancestors = [], n;
  464. for (n = node1; n; n = n.parentNode) {
  465. ancestors.push(n);
  466. }
  467. for (n = node2; n; n = n.parentNode) {
  468. if (arrayContains(ancestors, n)) {
  469. return n;
  470. }
  471. }
  472. return null;
  473. }
  474. function isAncestorOf(ancestor, descendant, selfIsAncestor) {
  475. var n = selfIsAncestor ? descendant : descendant.parentNode;
  476. while (n) {
  477. if (n === ancestor) {
  478. return true;
  479. } else {
  480. n = n.parentNode;
  481. }
  482. }
  483. return false;
  484. }
  485. function isOrIsAncestorOf(ancestor, descendant) {
  486. return isAncestorOf(ancestor, descendant, true);
  487. }
  488. function getClosestAncestorIn(node, ancestor, selfIsAncestor) {
  489. var p, n = selfIsAncestor ? node : node.parentNode;
  490. while (n) {
  491. p = n.parentNode;
  492. if (p === ancestor) {
  493. return n;
  494. }
  495. n = p;
  496. }
  497. return null;
  498. }
  499. function isCharacterDataNode(node) {
  500. var t = node.nodeType;
  501. return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment
  502. }
  503. function isTextOrCommentNode(node) {
  504. if (!node) {
  505. return false;
  506. }
  507. var t = node.nodeType;
  508. return t == 3 || t == 8 ; // Text or Comment
  509. }
  510. function insertAfter(node, precedingNode) {
  511. var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;
  512. if (nextNode) {
  513. parent.insertBefore(node, nextNode);
  514. } else {
  515. parent.appendChild(node);
  516. }
  517. return node;
  518. }
  519. // Note that we cannot use splitText() because it is bugridden in IE 9.
  520. function splitDataNode(node, index, positionsToPreserve) {
  521. var newNode = node.cloneNode(false);
  522. newNode.deleteData(0, index);
  523. node.deleteData(index, node.length - index);
  524. insertAfter(newNode, node);
  525. // Preserve positions
  526. if (positionsToPreserve) {
  527. for (var i = 0, position; position = positionsToPreserve[i++]; ) {
  528. // Handle case where position was inside the portion of node after the split point
  529. if (position.node == node && position.offset > index) {
  530. position.node = newNode;
  531. position.offset -= index;
  532. }
  533. // Handle the case where the position is a node offset within node's parent
  534. else if (position.node == node.parentNode && position.offset > getNodeIndex(node)) {
  535. ++position.offset;
  536. }
  537. }
  538. }
  539. return newNode;
  540. }
  541. function getDocument(node) {
  542. if (node.nodeType == 9) {
  543. return node;
  544. } else if (typeof node.ownerDocument != UNDEF) {
  545. return node.ownerDocument;
  546. } else if (typeof node.document != UNDEF) {
  547. return node.document;
  548. } else if (node.parentNode) {
  549. return getDocument(node.parentNode);
  550. } else {
  551. throw module.createError("getDocument: no document found for node");
  552. }
  553. }
  554. function getWindow(node) {
  555. var doc = getDocument(node);
  556. if (typeof doc.defaultView != UNDEF) {
  557. return doc.defaultView;
  558. } else if (typeof doc.parentWindow != UNDEF) {
  559. return doc.parentWindow;
  560. } else {
  561. throw module.createError("Cannot get a window object for node");
  562. }
  563. }
  564. function getIframeDocument(iframeEl) {
  565. if (typeof iframeEl.contentDocument != UNDEF) {
  566. return iframeEl.contentDocument;
  567. } else if (typeof iframeEl.contentWindow != UNDEF) {
  568. return iframeEl.contentWindow.document;
  569. } else {
  570. throw module.createError("getIframeDocument: No Document object found for iframe element");
  571. }
  572. }
  573. function getIframeWindow(iframeEl) {
  574. if (typeof iframeEl.contentWindow != UNDEF) {
  575. return iframeEl.contentWindow;
  576. } else if (typeof iframeEl.contentDocument != UNDEF) {
  577. return iframeEl.contentDocument.defaultView;
  578. } else {
  579. throw module.createError("getIframeWindow: No Window object found for iframe element");
  580. }
  581. }
  582. // This looks bad. Is it worth it?
  583. function isWindow(obj) {
  584. return obj && util.isHostMethod(obj, "setTimeout") && util.isHostObject(obj, "document");
  585. }
  586. function getContentDocument(obj, module, methodName) {
  587. var doc;
  588. if (!obj) {
  589. doc = document;
  590. }
  591. // Test if a DOM node has been passed and obtain a document object for it if so
  592. else if (util.isHostProperty(obj, "nodeType")) {
  593. doc = (obj.nodeType == 1 && obj.tagName.toLowerCase() == "iframe") ?
  594. getIframeDocument(obj) : getDocument(obj);
  595. }
  596. // Test if the doc parameter appears to be a Window object
  597. else if (isWindow(obj)) {
  598. doc = obj.document;
  599. }
  600. if (!doc) {
  601. throw module.createError(methodName + "(): Parameter must be a Window object or DOM node");
  602. }
  603. return doc;
  604. }
  605. function getRootContainer(node) {
  606. var parent;
  607. while ( (parent = node.parentNode) ) {
  608. node = parent;
  609. }
  610. return node;
  611. }
  612. function comparePoints(nodeA, offsetA, nodeB, offsetB) {
  613. // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing
  614. var nodeC, root, childA, childB, n;
  615. if (nodeA == nodeB) {
  616. // Case 1: nodes are the same
  617. return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;
  618. } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {
  619. // Case 2: node C (container B or an ancestor) is a child node of A
  620. return offsetA <= getNodeIndex(nodeC) ? -1 : 1;
  621. } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {
  622. // Case 3: node C (container A or an ancestor) is a child node of B
  623. return getNodeIndex(nodeC) < offsetB ? -1 : 1;
  624. } else {
  625. root = getCommonAncestor(nodeA, nodeB);
  626. if (!root) {
  627. throw new Error("comparePoints error: nodes have no common ancestor");
  628. }
  629. // Case 4: containers are siblings or descendants of siblings
  630. childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);
  631. childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);
  632. if (childA === childB) {
  633. // This shouldn't be possible
  634. throw module.createError("comparePoints got to case 4 and childA and childB are the same!");
  635. } else {
  636. n = root.firstChild;
  637. while (n) {
  638. if (n === childA) {
  639. return -1;
  640. } else if (n === childB) {
  641. return 1;
  642. }
  643. n = n.nextSibling;
  644. }
  645. }
  646. }
  647. }
  648. /*----------------------------------------------------------------------------------------------------------------*/
  649. // Test for IE's crash (IE 6/7) or exception (IE >= 8) when a reference to garbage-collected text node is queried
  650. var crashyTextNodes = false;
  651. function isBrokenNode(node) {
  652. var n;
  653. try {
  654. n = node.parentNode;
  655. return false;
  656. } catch (e) {
  657. return true;
  658. }
  659. }
  660. (function() {
  661. var el = document.createElement("b");
  662. el.innerHTML = "1";
  663. var textNode = el.firstChild;
  664. el.innerHTML = "<br />";
  665. crashyTextNodes = isBrokenNode(textNode);
  666. api.features.crashyTextNodes = crashyTextNodes;
  667. })();
  668. /*----------------------------------------------------------------------------------------------------------------*/
  669. function inspectNode(node) {
  670. if (!node) {
  671. return "[No node]";
  672. }
  673. if (crashyTextNodes && isBrokenNode(node)) {
  674. return "[Broken node]";
  675. }
  676. if (isCharacterDataNode(node)) {
  677. return '"' + node.data + '"';
  678. }
  679. if (node.nodeType == 1) {
  680. var idAttr = node.id ? ' id="' + node.id + '"' : "";
  681. return "<" + node.nodeName + idAttr + ">[index:" + getNodeIndex(node) + ",length:" + node.childNodes.length + "][" + (node.innerHTML || "[innerHTML not supported]").slice(0, 25) + "]";
  682. }
  683. return node.nodeName;
  684. }
  685. function fragmentFromNodeChildren(node) {
  686. var fragment = getDocument(node).createDocumentFragment(), child;
  687. while ( (child = node.firstChild) ) {
  688. fragment.appendChild(child);
  689. }
  690. return fragment;
  691. }
  692. var getComputedStyleProperty;
  693. if (typeof window.getComputedStyle != UNDEF) {
  694. getComputedStyleProperty = function(el, propName) {
  695. return getWindow(el).getComputedStyle(el, null)[propName];
  696. };
  697. } else if (typeof document.documentElement.currentStyle != UNDEF) {
  698. getComputedStyleProperty = function(el, propName) {
  699. return el.currentStyle ? el.currentStyle[propName] : "";
  700. };
  701. } else {
  702. module.fail("No means of obtaining computed style properties found");
  703. }
  704. function createTestElement(doc, html, contentEditable) {
  705. var body = getBody(doc);
  706. var el = doc.createElement("div");
  707. el.contentEditable = "" + !!contentEditable;
  708. if (html) {
  709. el.innerHTML = html;
  710. }
  711. // Insert the test element at the start of the body to prevent scrolling to the bottom in iOS (issue #292)
  712. var bodyFirstChild = body.firstChild;
  713. if (bodyFirstChild) {
  714. body.insertBefore(el, bodyFirstChild);
  715. } else {
  716. body.appendChild(el);
  717. }
  718. return el;
  719. }
  720. function removeNode(node) {
  721. return node.parentNode.removeChild(node);
  722. }
  723. function NodeIterator(root) {
  724. this.root = root;
  725. this._next = root;
  726. }
  727. NodeIterator.prototype = {
  728. _current: null,
  729. hasNext: function() {
  730. return !!this._next;
  731. },
  732. next: function() {
  733. var n = this._current = this._next;
  734. var child, next;
  735. if (this._current) {
  736. child = n.firstChild;
  737. if (child) {
  738. this._next = child;
  739. } else {
  740. next = null;
  741. while ((n !== this.root) && !(next = n.nextSibling)) {
  742. n = n.parentNode;
  743. }
  744. this._next = next;
  745. }
  746. }
  747. return this._current;
  748. },
  749. detach: function() {
  750. this._current = this._next = this.root = null;
  751. }
  752. };
  753. function createIterator(root) {
  754. return new NodeIterator(root);
  755. }
  756. function DomPosition(node, offset) {
  757. this.node = node;
  758. this.offset = offset;
  759. }
  760. DomPosition.prototype = {
  761. equals: function(pos) {
  762. return !!pos && this.node === pos.node && this.offset == pos.offset;
  763. },
  764. inspect: function() {
  765. return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]";
  766. },
  767. toString: function() {
  768. return this.inspect();
  769. }
  770. };
  771. function DOMException(codeName) {
  772. this.code = this[codeName];
  773. this.codeName = codeName;
  774. this.message = "DOMException: " + this.codeName;
  775. }
  776. DOMException.prototype = {
  777. INDEX_SIZE_ERR: 1,
  778. HIERARCHY_REQUEST_ERR: 3,
  779. WRONG_DOCUMENT_ERR: 4,
  780. NO_MODIFICATION_ALLOWED_ERR: 7,
  781. NOT_FOUND_ERR: 8,
  782. NOT_SUPPORTED_ERR: 9,
  783. INVALID_STATE_ERR: 11,
  784. INVALID_NODE_TYPE_ERR: 24
  785. };
  786. DOMException.prototype.toString = function() {
  787. return this.message;
  788. };
  789. api.dom = {
  790. arrayContains: arrayContains,
  791. isHtmlNamespace: isHtmlNamespace,
  792. parentElement: parentElement,
  793. getNodeIndex: getNodeIndex,
  794. getNodeLength: getNodeLength,
  795. getCommonAncestor: getCommonAncestor,
  796. isAncestorOf: isAncestorOf,
  797. isOrIsAncestorOf: isOrIsAncestorOf,
  798. getClosestAncestorIn: getClosestAncestorIn,
  799. isCharacterDataNode: isCharacterDataNode,
  800. isTextOrCommentNode: isTextOrCommentNode,
  801. insertAfter: insertAfter,
  802. splitDataNode: splitDataNode,
  803. getDocument: getDocument,
  804. getWindow: getWindow,
  805. getIframeWindow: getIframeWindow,
  806. getIframeDocument: getIframeDocument,
  807. getBody: getBody,
  808. isWindow: isWindow,
  809. getContentDocument: getContentDocument,
  810. getRootContainer: getRootContainer,
  811. comparePoints: comparePoints,
  812. isBrokenNode: isBrokenNode,
  813. inspectNode: inspectNode,
  814. getComputedStyleProperty: getComputedStyleProperty,
  815. createTestElement: createTestElement,
  816. removeNode: removeNode,
  817. fragmentFromNodeChildren: fragmentFromNodeChildren,
  818. createIterator: createIterator,
  819. DomPosition: DomPosition
  820. };
  821. api.DOMException = DOMException;
  822. });
  823. /*----------------------------------------------------------------------------------------------------------------*/
  824. // Pure JavaScript implementation of DOM Range
  825. api.createCoreModule("DomRange", ["DomUtil"], function(api, module) {
  826. var dom = api.dom;
  827. var util = api.util;
  828. var DomPosition = dom.DomPosition;
  829. var DOMException = api.DOMException;
  830. var isCharacterDataNode = dom.isCharacterDataNode;
  831. var getNodeIndex = dom.getNodeIndex;
  832. var isOrIsAncestorOf = dom.isOrIsAncestorOf;
  833. var getDocument = dom.getDocument;
  834. var comparePoints = dom.comparePoints;
  835. var splitDataNode = dom.splitDataNode;
  836. var getClosestAncestorIn = dom.getClosestAncestorIn;
  837. var getNodeLength = dom.getNodeLength;
  838. var arrayContains = dom.arrayContains;
  839. var getRootContainer = dom.getRootContainer;
  840. var crashyTextNodes = api.features.crashyTextNodes;
  841. var removeNode = dom.removeNode;
  842. /*----------------------------------------------------------------------------------------------------------------*/
  843. // Utility functions
  844. function isNonTextPartiallySelected(node, range) {
  845. return (node.nodeType != 3) &&
  846. (isOrIsAncestorOf(node, range.startContainer) || isOrIsAncestorOf(node, range.endContainer));
  847. }
  848. function getRangeDocument(range) {
  849. return range.document || getDocument(range.startContainer);
  850. }
  851. function getRangeRoot(range) {
  852. return getRootContainer(range.startContainer);
  853. }
  854. function getBoundaryBeforeNode(node) {
  855. return new DomPosition(node.parentNode, getNodeIndex(node));
  856. }
  857. function getBoundaryAfterNode(node) {
  858. return new DomPosition(node.parentNode, getNodeIndex(node) + 1);
  859. }
  860. function insertNodeAtPosition(node, n, o) {
  861. var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node;
  862. if (isCharacterDataNode(n)) {
  863. if (o == n.length) {
  864. dom.insertAfter(node, n);
  865. } else {
  866. n.parentNode.insertBefore(node, o == 0 ? n : splitDataNode(n, o));
  867. }
  868. } else if (o >= n.childNodes.length) {
  869. n.appendChild(node);
  870. } else {
  871. n.insertBefore(node, n.childNodes[o]);
  872. }
  873. return firstNodeInserted;
  874. }
  875. function rangesIntersect(rangeA, rangeB, touchingIsIntersecting) {
  876. assertRangeValid(rangeA);
  877. assertRangeValid(rangeB);
  878. if (getRangeDocument(rangeB) != getRangeDocument(rangeA)) {
  879. throw new DOMException("WRONG_DOCUMENT_ERR");
  880. }
  881. var startComparison = comparePoints(rangeA.startContainer, rangeA.startOffset, rangeB.endContainer, rangeB.endOffset),
  882. endComparison = comparePoints(rangeA.endContainer, rangeA.endOffset, rangeB.startContainer, rangeB.startOffset);
  883. return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
  884. }
  885. function cloneSubtree(iterator) {
  886. var partiallySelected;
  887. for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
  888. partiallySelected = iterator.isPartiallySelectedSubtree();
  889. node = node.cloneNode(!partiallySelected);
  890. if (partiallySelected) {
  891. subIterator = iterator.getSubtreeIterator();
  892. node.appendChild(cloneSubtree(subIterator));
  893. subIterator.detach();
  894. }
  895. if (node.nodeType == 10) { // DocumentType
  896. throw new DOMException("HIERARCHY_REQUEST_ERR");
  897. }
  898. frag.appendChild(node);
  899. }
  900. return frag;
  901. }
  902. function iterateSubtree(rangeIterator, func, iteratorState) {
  903. var it, n;
  904. iteratorState = iteratorState || { stop: false };
  905. for (var node, subRangeIterator; node = rangeIterator.next(); ) {
  906. if (rangeIterator.isPartiallySelectedSubtree()) {
  907. if (func(node) === false) {
  908. iteratorState.stop = true;
  909. return;
  910. } else {
  911. // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of
  912. // the node selected by the Range.
  913. subRangeIterator = rangeIterator.getSubtreeIterator();
  914. iterateSubtree(subRangeIterator, func, iteratorState);
  915. subRangeIterator.detach();
  916. if (iteratorState.stop) {
  917. return;
  918. }
  919. }
  920. } else {
  921. // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its
  922. // descendants
  923. it = dom.createIterator(node);
  924. while ( (n = it.next()) ) {
  925. if (func(n) === false) {
  926. iteratorState.stop = true;
  927. return;
  928. }
  929. }
  930. }
  931. }
  932. }
  933. function deleteSubtree(iterator) {
  934. var subIterator;
  935. while (iterator.next()) {
  936. if (iterator.isPartiallySelectedSubtree()) {
  937. subIterator = iterator.getSubtreeIterator();
  938. deleteSubtree(subIterator);
  939. subIterator.detach();
  940. } else {
  941. iterator.remove();
  942. }
  943. }
  944. }
  945. function extractSubtree(iterator) {
  946. for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
  947. if (iterator.isPartiallySelectedSubtree()) {
  948. node = node.cloneNode(false);
  949. subIterator = iterator.getSubtreeIterator();
  950. node.appendChild(extractSubtree(subIterator));
  951. subIterator.detach();
  952. } else {
  953. iterator.remove();
  954. }
  955. if (node.nodeType == 10) { // DocumentType
  956. throw new DOMException("HIERARCHY_REQUEST_ERR");
  957. }
  958. frag.appendChild(node);
  959. }
  960. return frag;
  961. }
  962. function getNodesInRange(range, nodeTypes, filter) {
  963. var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex;
  964. var filterExists = !!filter;
  965. if (filterNodeTypes) {
  966. regex = new RegExp("^(" + nodeTypes.join("|") + ")$");
  967. }
  968. var nodes = [];
  969. iterateSubtree(new RangeIterator(range, false), function(node) {
  970. if (filterNodeTypes && !regex.test(node.nodeType)) {
  971. return;
  972. }
  973. if (filterExists && !filter(node)) {
  974. return;
  975. }
  976. // Don't include a boundary container if it is a character data node and the range does not contain any
  977. // of its character data. See issue 190.
  978. var sc = range.startContainer;
  979. if (node == sc && isCharacterDataNode(sc) && range.startOffset == sc.length) {
  980. return;
  981. }
  982. var ec = range.endContainer;
  983. if (node == ec && isCharacterDataNode(ec) && range.endOffset == 0) {
  984. return;
  985. }
  986. nodes.push(node);
  987. });
  988. return nodes;
  989. }
  990. function inspect(range) {
  991. var name = (typeof range.getName == "undefined") ? "Range" : range.getName();
  992. return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " +
  993. dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]";
  994. }
  995. /*----------------------------------------------------------------------------------------------------------------*/
  996. // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange)
  997. function RangeIterator(range, clonePartiallySelectedTextNodes) {
  998. this.range = range;
  999. this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes;
  1000. if (!range.collapsed) {
  1001. this.sc = range.startContainer;
  1002. this.so = range.startOffset;
  1003. this.ec = range.endContainer;
  1004. this.eo = range.endOffset;
  1005. var root = range.commonAncestorContainer;
  1006. if (this.sc === this.ec && isCharacterDataNode(this.sc)) {
  1007. this.isSingleCharacterDataNode = true;
  1008. this._first = this._last = this._next = this.sc;
  1009. } else {
  1010. this._first = this._next = (this.sc === root && !isCharacterDataNode(this.sc)) ?
  1011. this.sc.childNodes[this.so] : getClosestAncestorIn(this.sc, root, true);
  1012. this._last = (this.ec === root && !isCharacterDataNode(this.ec)) ?
  1013. this.ec.childNodes[this.eo - 1] : getClosestAncestorIn(this.ec, root, true);
  1014. }
  1015. }
  1016. }
  1017. RangeIterator.prototype = {
  1018. _current: null,
  1019. _next: null,
  1020. _first: null,
  1021. _last: null,
  1022. isSingleCharacterDataNode: false,
  1023. reset: function() {
  1024. this._current = null;
  1025. this._next = this._first;
  1026. },
  1027. hasNext: function() {
  1028. return !!this._next;
  1029. },
  1030. next: function() {
  1031. // Move to next node
  1032. var current = this._current = this._next;
  1033. if (current) {
  1034. this._next = (current !== this._last) ? current.nextSibling : null;
  1035. // Check for partially selected text nodes
  1036. if (isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) {
  1037. if (current === this.ec) {
  1038. (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo);
  1039. }
  1040. if (this._current === this.sc) {
  1041. (current = current.cloneNode(true)).deleteData(0, this.so);
  1042. }
  1043. }
  1044. }
  1045. return current;
  1046. },
  1047. remove: function() {
  1048. var current = this._current, start, end;
  1049. if (isCharacterDataNode(current) && (current === this.sc || current === this.ec)) {
  1050. start = (current === this.sc) ? this.so : 0;
  1051. end = (current === this.ec) ? this.eo : current.length;
  1052. if (start != end) {
  1053. current.deleteData(start, end - start);
  1054. }
  1055. } else {
  1056. if (current.parentNode) {
  1057. removeNode(current);
  1058. } else {
  1059. }
  1060. }
  1061. },
  1062. // Checks if the current node is partially selected
  1063. isPartiallySelectedSubtree: function() {
  1064. var current = this._current;
  1065. return isNonTextPartiallySelected(current, this.range);
  1066. },
  1067. getSubtreeIterator: function() {
  1068. var subRange;
  1069. if (this.isSingleCharacterDataNode) {
  1070. subRange = this.range.cloneRange();
  1071. subRange.collapse(false);
  1072. } else {
  1073. subRange = new Range(getRangeDocument(this.range));
  1074. var current = this._current;
  1075. var startContainer = current, startOffset = 0, endContainer = current, endOffset = getNodeLength(current);
  1076. if (isOrIsAncestorOf(current, this.sc)) {
  1077. startContainer = this.sc;
  1078. startOffset = this.so;
  1079. }
  1080. if (isOrIsAncestorOf(current, this.ec)) {
  1081. endContainer = this.ec;
  1082. endOffset = this.eo;
  1083. }
  1084. updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset);
  1085. }
  1086. return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes);
  1087. },
  1088. detach: function() {
  1089. this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null;
  1090. }
  1091. };
  1092. /*----------------------------------------------------------------------------------------------------------------*/
  1093. var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10];
  1094. var rootContainerNodeTypes = [2, 9, 11];
  1095. var readonlyNodeTypes = [5, 6, 10, 12];
  1096. var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11];
  1097. var surroundNodeTypes = [1, 3, 4, 5, 7, 8];
  1098. function createAncestorFinder(nodeTypes) {
  1099. return function(node, selfIsAncestor) {
  1100. var t, n = selfIsAncestor ? node : node.parentNode;
  1101. while (n) {
  1102. t = n.nodeType;
  1103. if (arrayContains(nodeTypes, t)) {
  1104. return n;
  1105. }
  1106. n = n.parentNode;
  1107. }
  1108. return null;
  1109. };
  1110. }
  1111. var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );
  1112. var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);
  1113. var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );
  1114. function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {
  1115. if (getDocTypeNotationEntityAncestor(node, allowSelf)) {
  1116. throw new DOMException("INVALID_NODE_TYPE_ERR");
  1117. }
  1118. }
  1119. function assertValidNodeType(node, invalidTypes) {
  1120. if (!arrayContains(invalidTypes, node.nodeType)) {
  1121. throw new DOMException("INVALID_NODE_TYPE_ERR");
  1122. }
  1123. }
  1124. function assertValidOffset(node, offset) {
  1125. if (offset < 0 || offset > (isCharacterDataNode(node) ? node.length : node.childNodes.length)) {
  1126. throw new DOMException("INDEX_SIZE_ERR");
  1127. }
  1128. }
  1129. function assertSameDocumentOrFragment(node1, node2) {
  1130. if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) {
  1131. throw new DOMException("WRONG_DOCUMENT_ERR");
  1132. }
  1133. }
  1134. function assertNodeNotReadOnly(node) {
  1135. if (getReadonlyAncestor(node, true)) {
  1136. throw new DOMException("NO_MODIFICATION_ALLOWED_ERR");
  1137. }
  1138. }
  1139. function assertNode(node, codeName) {
  1140. if (!node) {
  1141. throw new DOMException(codeName);
  1142. }
  1143. }
  1144. function isValidOffset(node, offset) {
  1145. return offset <= (isCharacterDataNode(node) ? node.length : node.childNodes.length);
  1146. }
  1147. function isRangeValid(range) {
  1148. return (!!range.startContainer && !!range.endContainer &&
  1149. !(crashyTextNodes && (dom.isBrokenNode(range.startContainer) || dom.isBrokenNode(range.endContainer))) &&
  1150. getRootContainer(range.startContainer) == getRootContainer(range.endContainer) &&
  1151. isValidOffset(range.startContainer, range.startOffset) &&
  1152. isValidOffset(range.endContainer, range.endOffset));
  1153. }
  1154. function assertRangeValid(range) {
  1155. if (!isRangeValid(range)) {
  1156. throw new Error("Range error: Range is not valid. This usually happens after DOM mutation. Range: (" + range.inspect() + ")");
  1157. }
  1158. }
  1159. /*----------------------------------------------------------------------------------------------------------------*/
  1160. // Test the browser's innerHTML support to decide how to implement createContextualFragment
  1161. var styleEl = document.createElement("style");
  1162. var htmlParsingConforms = false;
  1163. try {
  1164. styleEl.innerHTML = "<b>x</b>";
  1165. htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node
  1166. } catch (e) {
  1167. // IE 6 and 7 throw
  1168. }
  1169. api.features.htmlParsingConforms = htmlParsingConforms;
  1170. var createContextualFragment = htmlParsingConforms ?
  1171. // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See
  1172. // discussion and base code for this implementation at issue 67.
  1173. // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface
  1174. // Thanks to Aleks Williams.
  1175. function(fragmentStr) {
  1176. // "Let node the context object's start's node."
  1177. var node = this.startContainer;
  1178. var doc = getDocument(node);
  1179. // "If the context object's start's node is null, raise an INVALID_STATE_ERR
  1180. // exception and abort these steps."
  1181. if (!node) {
  1182. throw new DOMException("INVALID_STATE_ERR");
  1183. }
  1184. // "Let element be as follows, depending on node's interface:"
  1185. // Document, Document Fragment: null
  1186. var el = null;
  1187. // "Element: node"
  1188. if (node.nodeType == 1) {
  1189. el = node;
  1190. // "Text, Comment: node's parentElement"
  1191. } else if (isCharacterDataNode(node)) {
  1192. el = dom.parentElement(node);
  1193. }
  1194. // "If either element is null or element's ownerDocument is an HTML document
  1195. // and element's local name is "html" and element's namespace is the HTML
  1196. // namespace"
  1197. if (el === null || (
  1198. el.nodeName == "HTML" &&
  1199. dom.isHtmlNamespace(getDocument(el).documentElement) &&
  1200. dom.isHtmlNamespace(el)
  1201. )) {
  1202. // "let element be a new Element with "body" as its local name and the HTML
  1203. // namespace as its namespace.""
  1204. el = doc.createElement("body");
  1205. } else {
  1206. el = el.cloneNode(false);
  1207. }
  1208. // "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm."
  1209. // "If the node's document is an XML document: Invoke the XML fragment parsing algorithm."
  1210. // "In either case, the algorithm must be invoked with fragment as the input
  1211. // and element as the context element."
  1212. el.innerHTML = fragmentStr;
  1213. // "If this raises an exception, then abort these steps. Otherwise, let new
  1214. // children be the nodes returned."
  1215. // "Let fragment be a new DocumentFragment."
  1216. // "Append all new children to fragment."
  1217. // "Return fragment."
  1218. return dom.fragmentFromNodeChildren(el);
  1219. } :
  1220. // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that
  1221. // previous versions of Rangy used (with the exception of using a body element rather than a div)
  1222. function(fragmentStr) {
  1223. var doc = getRangeDocument(this);
  1224. var el = doc.createElement("body");
  1225. el.innerHTML = fragmentStr;
  1226. return dom.fragmentFromNodeChildren(el);
  1227. };
  1228. function splitRangeBoundaries(range, positionsToPreserve) {
  1229. assertRangeValid(range);
  1230. var sc = range.startContainer, so = range.startOffset, ec = range.endContainer, eo = range.endOffset;
  1231. var startEndSame = (sc === ec);
  1232. if (isCharacterDataNode(ec) && eo > 0 && eo < ec.length) {
  1233. splitDataNode(ec, eo, positionsToPreserve);
  1234. }
  1235. if (isCharacterDataNode(sc) && so > 0 && so < sc.length) {
  1236. sc = splitDataNode(sc, so, positionsToPreserve);
  1237. if (startEndSame) {
  1238. eo -= so;
  1239. ec = sc;
  1240. } else if (ec == sc.parentNode && eo >= getNodeIndex(sc)) {
  1241. eo++;
  1242. }
  1243. so = 0;
  1244. }
  1245. range.setStartAndEnd(sc, so, ec, eo);
  1246. }
  1247. function rangeToHtml(range) {
  1248. assertRangeValid(range);
  1249. var container = range.commonAncestorContainer.parentNode.cloneNode(false);
  1250. container.appendChild( range.cloneContents() );
  1251. return container.innerHTML;
  1252. }
  1253. /*----------------------------------------------------------------------------------------------------------------*/
  1254. var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
  1255. "commonAncestorContainer"];
  1256. var s2s = 0, s2e = 1, e2e = 2, e2s = 3;
  1257. var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3;
  1258. util.extend(api.rangePrototype, {
  1259. compareBoundaryPoints: function(how, range) {
  1260. assertRangeValid(this);
  1261. assertSameDocumentOrFragment(this.startContainer, range.startContainer);
  1262. var nodeA, offsetA, nodeB, offsetB;
  1263. var prefixA = (how == e2s || how == s2s) ? "start" : "end";
  1264. var prefixB = (how == s2e || how == s2s) ? "start" : "end";
  1265. nodeA = this[prefixA + "Container"];
  1266. offsetA = this[prefixA + "Offset"];
  1267. nodeB = range[prefixB + "Container"];
  1268. offsetB = range[prefixB + "Offset"];
  1269. return comparePoints(nodeA, offsetA, nodeB, offsetB);
  1270. },
  1271. insertNode: function(node) {
  1272. assertRangeValid(this);
  1273. assertValidNodeType(node, insertableNodeTypes);
  1274. assertNodeNotReadOnly(this.startContainer);
  1275. if (isOrIsAncestorOf(node, this.startContainer)) {
  1276. throw new DOMException("HIERARCHY_REQUEST_ERR");
  1277. }
  1278. // No check for whether the container of the start of the Range is of a type that does not allow
  1279. // children of the type of node: the browser's DOM implementation should do this for us when we attempt
  1280. // to add the node
  1281. var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset);
  1282. this.setStartBefore(firstNodeInserted);
  1283. },
  1284. cloneContents: function() {
  1285. assertRangeValid(this);
  1286. var clone, frag;
  1287. if (this.collapsed) {
  1288. return getRangeDocument(this).createDocumentFragment();
  1289. } else {
  1290. if (this.startContainer === this.endContainer && isCharacterDataNode(this.startContainer)) {
  1291. clone = this.startContainer.cloneNode(true);
  1292. clone.data = clone.data.slice(this.startOffset, this.endOffset);
  1293. frag = getRangeDocument(this).createDocumentFragment();
  1294. frag.appendChild(clone);
  1295. return frag;
  1296. } else {
  1297. var iterator = new RangeIterator(this, true);
  1298. clone = cloneSubtree(iterator);
  1299. iterator.detach();
  1300. }
  1301. return clone;
  1302. }
  1303. },
  1304. canSurroundContents: function() {
  1305. assertRangeValid(this);
  1306. assertNodeNotReadOnly(this.startContainer);
  1307. assertNodeNotReadOnly(this.endContainer);
  1308. // Check if the contents can be surrounded. Specifically, this means whether the range partially selects
  1309. // no non-text nodes.
  1310. var iterator = new RangeIterator(this, true);
  1311. var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
  1312. (iterator._last && isNonTextPartiallySelected(iterator._last, this)));
  1313. iterator.detach();
  1314. return !boundariesInvalid;
  1315. },
  1316. surroundContents: function(node) {
  1317. assertValidNodeType(node, surroundNodeTypes);
  1318. if (!this.canSurroundContents()) {
  1319. throw new DOMException("INVALID_STATE_ERR");
  1320. }
  1321. // Extract the contents
  1322. var content = this.extractContents();
  1323. // Clear the children of the node
  1324. if (node.hasChildNodes()) {
  1325. while (node.lastChild) {
  1326. node.removeChild(node.lastChild);
  1327. }
  1328. }
  1329. // Insert the new node and add the extracted contents
  1330. insertNodeAtPosition(node, this.startContainer, this.startOffset);
  1331. node.appendChild(content);
  1332. this.selectNode(node);
  1333. },
  1334. cloneRange: function() {
  1335. assertRangeValid(this);
  1336. var range = new Range(getRangeDocument(this));
  1337. var i = rangeProperties.length, prop;
  1338. while (i--) {
  1339. prop = rangeProperties[i];
  1340. range[prop] = this[prop];
  1341. }
  1342. return range;
  1343. },
  1344. toString: function() {
  1345. assertRangeValid(this);
  1346. var sc = this.startContainer;
  1347. if (sc === this.endContainer && isCharacterDataNode(sc)) {
  1348. return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : "";
  1349. } else {
  1350. var textParts = [], iterator = new RangeIterator(this, true);
  1351. iterateSubtree(iterator, function(node) {
  1352. // Accept only text or CDATA nodes, not comments
  1353. if (node.nodeType == 3 || node.nodeType == 4) {
  1354. textParts.push(node.data);
  1355. }
  1356. });
  1357. iterator.detach();
  1358. return textParts.join("");
  1359. }
  1360. },
  1361. // The methods below are all non-standard. The following batch were introduced by Mozilla but have since
  1362. // been removed from Mozilla.
  1363. compareNode: function(node) {
  1364. assertRangeValid(this);
  1365. var parent = node.parentNode;
  1366. var nodeIndex = getNodeIndex(node);
  1367. if (!parent) {
  1368. throw new DOMException("NOT_FOUND_ERR");
  1369. }
  1370. var startComparison = this.comparePoint(parent, nodeIndex),
  1371. endComparison = this.comparePoint(parent, nodeIndex + 1);
  1372. if (startComparison < 0) { // Node starts before
  1373. return (endComparison > 0) ? n_b_a : n_b;
  1374. } else {
  1375. return (endComparison > 0) ? n_a : n_i;
  1376. }
  1377. },
  1378. comparePoint: function(node, offset) {
  1379. assertRangeValid(this);
  1380. assertNode(node, "HIERARCHY_REQUEST_ERR");
  1381. assertSameDocumentOrFragment(node, this.startContainer);
  1382. if (comparePoints(node, offset, this.startContainer, this.startOffset) < 0) {
  1383. return -1;
  1384. } else if (comparePoints(node, offset, this.endContainer, this.endOffset) > 0) {
  1385. return 1;
  1386. }
  1387. return 0;
  1388. },
  1389. createContextualFragment: createContextualFragment,
  1390. toHtml: function() {
  1391. return rangeToHtml(this);
  1392. },
  1393. // touchingIsIntersecting determines whether this method considers a node that borders a range intersects
  1394. // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default)
  1395. intersectsNode: function(node, touchingIsIntersecting) {
  1396. assertRangeValid(this);
  1397. if (getRootContainer(node) != getRangeRoot(this)) {
  1398. return false;
  1399. }
  1400. var parent = node.parentNode, offset = getNodeIndex(node);
  1401. if (!parent) {
  1402. return true;
  1403. }
  1404. var startComparison = comparePoints(parent, offset, this.endContainer, this.endOffset),
  1405. endComparison = comparePoints(parent, offset + 1, this.startContainer, this.startOffset);
  1406. return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
  1407. },
  1408. isPointInRange: function(node, offset) {
  1409. assertRangeValid(this);
  1410. assertNode(node, "HIERARCHY_REQUEST_ERR");
  1411. assertSameDocumentOrFragment(node, this.startContainer);
  1412. return (comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) &&
  1413. (comparePoints(node, offset, this.endContainer, this.endOffset) <= 0);
  1414. },
  1415. // The methods below are non-standard and invented by me.
  1416. // Sharing a boundary start-to-end or end-to-start does not count as intersection.
  1417. intersectsRange: function(range) {
  1418. return rangesIntersect(this, range, false);
  1419. },
  1420. // Sharing a boundary start-to-end or end-to-start does count as intersection.
  1421. intersectsOrTouchesRange: function(range) {
  1422. return rangesIntersect(this, range, true);
  1423. },
  1424. intersection: function(range) {
  1425. if (this.intersectsRange(range)) {
  1426. var startComparison = comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset),
  1427. endComparison = comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset);
  1428. var intersectionRange = this.cloneRange();
  1429. if (startComparison == -1) {
  1430. intersectionRange.setStart(range.startContainer, range.startOffset);
  1431. }
  1432. if (endComparison == 1) {
  1433. intersectionRange.setEnd(range.endContainer, range.endOffset);
  1434. }
  1435. return intersectionRange;
  1436. }
  1437. return null;
  1438. },
  1439. union: function(range) {
  1440. if (this.intersectsOrTouchesRange(range)) {
  1441. var unionRange = this.cloneRange();
  1442. if (comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) {
  1443. unionRange.setStart(range.startContainer, range.startOffset);
  1444. }
  1445. if (comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) {
  1446. unionRange.setEnd(range.endContainer, range.endOffset);
  1447. }
  1448. return unionRange;
  1449. } else {
  1450. throw new DOMException("Ranges do not intersect");
  1451. }
  1452. },
  1453. containsNode: function(node, allowPartial) {
  1454. if (allowPartial) {
  1455. return this.intersectsNode(node, false);
  1456. } else {
  1457. return this.compareNode(node) == n_i;
  1458. }
  1459. },
  1460. containsNodeContents: function(node) {
  1461. return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, getNodeLength(node)) <= 0;
  1462. },
  1463. containsRange: function(range) {
  1464. var intersection = this.intersection(range);
  1465. return intersection !== null && range.equals(intersection);
  1466. },
  1467. containsNodeText: function(node) {
  1468. var nodeRange = this.cloneRange();
  1469. nodeRange.selectNode(node);
  1470. var textNodes = nodeRange.getNodes([3]);
  1471. if (textNodes.length > 0) {
  1472. nodeRange.setStart(textNodes[0], 0);
  1473. var lastTextNode = textNodes.pop();
  1474. nodeRange.setEnd(lastTextNode, lastTextNode.length);
  1475. return this.containsRange(nodeRange);
  1476. } else {
  1477. return this.containsNodeContents(node);
  1478. }
  1479. },
  1480. getNodes: function(nodeTypes, filter) {
  1481. assertRangeValid(this);
  1482. return getNodesInRange(this, nodeTypes, filter);
  1483. },
  1484. getDocument: function() {
  1485. return getRangeDocument(this);
  1486. },
  1487. collapseBefore: function(node) {
  1488. this.setEndBefore(node);
  1489. this.collapse(false);
  1490. },
  1491. collapseAfter: function(node) {
  1492. this.setStartAfter(node);
  1493. this.collapse(true);
  1494. },
  1495. getBookmark: function(containerNode) {
  1496. var doc = getRangeDocument(this);
  1497. var preSelectionRange = api.createRange(doc);
  1498. containerNode = containerNode || dom.getBody(doc);
  1499. preSelectionRange.selectNodeContents(containerNode);
  1500. var range = this.intersection(preSelectionRange);
  1501. var start = 0, end = 0;
  1502. if (range) {
  1503. preSelectionRange.setEnd(range.startContainer, range.startOffset);
  1504. start = preSelectionRange.toString().length;
  1505. end = start + range.toString().length;
  1506. }
  1507. return {
  1508. start: start,
  1509. end: end,
  1510. containerNode: containerNode
  1511. };
  1512. },
  1513. moveToBookmark: function(bookmark) {
  1514. var containerNode = bookmark.containerNode;
  1515. var charIndex = 0;
  1516. this.setStart(containerNode, 0);
  1517. this.collapse(true);
  1518. var nodeStack = [containerNode], node, foundStart = false, stop = false;
  1519. var nextCharIndex, i, childNodes;
  1520. while (!stop && (node = nodeStack.pop())) {
  1521. if (node.nodeType == 3) {
  1522. nextCharIndex = charIndex + node.length;
  1523. if (!foundStart && bookmark.start >= charIndex && bookmark.start <= nextCharIndex) {
  1524. this.setStart(node, bookmark.start - charIndex);
  1525. foundStart = true;
  1526. }
  1527. if (foundStart && bookmark.end >= charIndex && bookmark.end <= nextCharIndex) {
  1528. this.setEnd(node, bookmark.end - charIndex);
  1529. stop = true;
  1530. }
  1531. charIndex = nextCharIndex;
  1532. } else {
  1533. childNodes = node.childNodes;
  1534. i = childNodes.length;
  1535. while (i--) {
  1536. nodeStack.push(childNodes[i]);
  1537. }
  1538. }
  1539. }
  1540. },
  1541. getName: function() {
  1542. return "DomRange";
  1543. },
  1544. equals: function(range) {
  1545. return Range.rangesEqual(this, range);
  1546. },
  1547. isValid: function() {
  1548. return isRangeValid(this);
  1549. },
  1550. inspect: function() {
  1551. return inspect(this);
  1552. },
  1553. detach: function() {
  1554. // In DOM4, detach() is now a no-op.
  1555. }
  1556. });
  1557. function copyComparisonConstantsToObject(obj) {
  1558. obj.START_TO_START = s2s;
  1559. obj.START_TO_END = s2e;
  1560. obj.END_TO_END = e2e;
  1561. obj.END_TO_START = e2s;
  1562. obj.NODE_BEFORE = n_b;
  1563. obj.NODE_AFTER = n_a;
  1564. obj.NODE_BEFORE_AND_AFTER = n_b_a;
  1565. obj.NODE_INSIDE = n_i;
  1566. }
  1567. function copyComparisonConstants(constructor) {
  1568. copyComparisonConstantsToObject(constructor);
  1569. copyComparisonConstantsToObject(constructor.prototype);
  1570. }
  1571. function createRangeContentRemover(remover, boundaryUpdater) {
  1572. return function() {
  1573. assertRangeValid(this);
  1574. var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer;
  1575. var iterator = new RangeIterator(this, true);
  1576. // Work out where to position the range after content removal
  1577. var node, boundary;
  1578. if (sc !== root) {
  1579. node = getClosestAncestorIn(sc, root, true);
  1580. boundary = getBoundaryAfterNode(node);
  1581. sc = boundary.node;
  1582. so = boundary.offset;
  1583. }
  1584. // Check none of the range is read-only
  1585. iterateSubtree(iterator, assertNodeNotReadOnly);
  1586. iterator.reset();
  1587. // Remove the content
  1588. var returnValue = remover(iterator);
  1589. iterator.detach();
  1590. // Move to the new position
  1591. boundaryUpdater(this, sc, so, sc, so);
  1592. return returnValue;
  1593. };
  1594. }
  1595. function createPrototypeRange(constructor, boundaryUpdater) {
  1596. function createBeforeAfterNodeSetter(isBefore, isStart) {
  1597. return function(node) {
  1598. assertValidNodeType(node, beforeAfterNodeTypes);
  1599. assertValidNodeType(getRootContainer(node), rootContainerNodeTypes);
  1600. var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node);
  1601. (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset);
  1602. };
  1603. }
  1604. function setRangeStart(range, node, offset) {
  1605. var ec = range.endContainer, eo = range.endOffset;
  1606. if (node !== range.startContainer || offset !== range.startOffset) {
  1607. // Check the root containers of the range and the new boundary, and also check whether the new boundary
  1608. // is after the current end. In either case, collapse the range to the new position
  1609. if (getRootContainer(node) != getRootContainer(ec) || comparePoints(node, offset, ec, eo) == 1) {
  1610. ec = node;
  1611. eo = offset;
  1612. }
  1613. boundaryUpdater(range, node, offset, ec, eo);
  1614. }
  1615. }
  1616. function setRangeEnd(range, node, offset) {
  1617. var sc = range.startContainer, so = range.startOffset;
  1618. if (node !== range.endContainer || offset !== range.endOffset) {
  1619. // Check the root containers of the range and the new boundary, and also check whether the new boundary
  1620. // is after the current end. In either case, collapse the range to the new position
  1621. if (getRootContainer(node) != getRootContainer(sc) || comparePoints(node, offset, sc, so) == -1) {
  1622. sc = node;
  1623. so = offset;
  1624. }
  1625. boundaryUpdater(range, sc, so, node, offset);
  1626. }
  1627. }
  1628. // Set up inheritance
  1629. var F = function() {};
  1630. F.prototype = api.rangePrototype;
  1631. constructor.prototype = new F();
  1632. util.extend(constructor.prototype, {
  1633. setStart: function(node, offset) {
  1634. assertNoDocTypeNotationEntityAncestor(node, true);
  1635. assertValidOffset(node, offset);
  1636. setRangeStart(this, node, offset);
  1637. },
  1638. setEnd: function(node, offset) {
  1639. assertNoDocTypeNotationEntityAncestor(node, true);
  1640. assertValidOffset(node, offset);
  1641. setRangeEnd(this, node, offset);
  1642. },
  1643. /**
  1644. * Convenience method to set a range's start and end boundaries. Overloaded as follows:
  1645. * - Two parameters (node, offset) creates a collapsed range at that position
  1646. * - Three parameters (node, startOffset, endOffset) creates a range contained with node starting at
  1647. * startOffset and ending at endOffset
  1648. * - Four parameters (startNode, startOffset, endNode, endOffset) creates a range starting at startOffset in
  1649. * startNode and ending at endOffset in endNode
  1650. */
  1651. setStartAndEnd: function() {
  1652. var args = arguments;
  1653. var sc = args[0], so = args[1], ec = sc, eo = so;
  1654. switch (args.length) {
  1655. case 3:
  1656. eo = args[2];
  1657. break;
  1658. case 4:
  1659. ec = args[2];
  1660. eo = args[3];
  1661. break;
  1662. }
  1663. boundaryUpdater(this, sc, so, ec, eo);
  1664. },
  1665. setBoundary: function(node, offset, isStart) {
  1666. this["set" + (isStart ? "Start" : "End")](node, offset);
  1667. },
  1668. setStartBefore: createBeforeAfterNodeSetter(true, true),
  1669. setStartAfter: createBeforeAfterNodeSetter(false, true),
  1670. setEndBefore: createBeforeAfterNodeSetter(true, false),
  1671. setEndAfter: createBeforeAfterNodeSetter(false, false),
  1672. collapse: function(isStart) {
  1673. assertRangeValid(this);
  1674. if (isStart) {
  1675. boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset);
  1676. } else {
  1677. boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset);
  1678. }
  1679. },
  1680. selectNodeContents: function(node) {
  1681. assertNoDocTypeNotationEntityAncestor(node, true);
  1682. boundaryUpdater(this, node, 0, node, getNodeLength(node));
  1683. },
  1684. selectNode: function(node) {
  1685. assertNoDocTypeNotationEntityAncestor(node, false);
  1686. assertValidNodeType(node, beforeAfterNodeTypes);
  1687. var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node);
  1688. boundaryUpdater(this, start.node, start.offset, end.node, end.offset);
  1689. },
  1690. extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater),
  1691. deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater),
  1692. canSurroundContents: function() {
  1693. assertRangeValid(this);
  1694. assertNodeNotReadOnly(this.startContainer);
  1695. assertNodeNotReadOnly(this.endContainer);
  1696. // Check if the contents can be surrounded. Specifically, this means whether the range partially selects
  1697. // no non-text nodes.
  1698. var iterator = new RangeIterator(this, true);
  1699. var boundariesInvalid = (iterator._first && isNonTextPartiallySelected(iterator._first, this) ||
  1700. (iterator._last && isNonTextPartiallySelected(iterator._last, this)));
  1701. iterator.detach();
  1702. return !boundariesInvalid;
  1703. },
  1704. splitBoundaries: function() {
  1705. splitRangeBoundaries(this);
  1706. },
  1707. splitBoundariesPreservingPositions: function(positionsToPreserve) {
  1708. splitRangeBoundaries(this, positionsToPreserve);
  1709. },
  1710. normalizeBoundaries: function() {
  1711. assertRangeValid(this);
  1712. var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
  1713. var mergeForward = function(node) {
  1714. var sibling = node.nextSibling;
  1715. if (sibling && sibling.nodeType == node.nodeType) {
  1716. ec = node;
  1717. eo = node.length;
  1718. node.appendData(sibling.data);
  1719. removeNode(sibling);
  1720. }
  1721. };
  1722. var mergeBackward = function(node) {
  1723. var sibling = node.previousSibling;
  1724. if (sibling && sibling.nodeType == node.nodeType) {
  1725. sc = node;
  1726. var nodeLength = node.length;
  1727. so = sibling.length;
  1728. node.insertData(0, sibling.data);
  1729. removeNode(sibling);
  1730. if (sc == ec) {
  1731. eo += so;
  1732. ec = sc;
  1733. } else if (ec == node.parentNode) {
  1734. var nodeIndex = getNodeIndex(node);
  1735. if (eo == nodeIndex) {
  1736. ec = node;
  1737. eo = nodeLength;
  1738. } else if (eo > nodeIndex) {
  1739. eo--;
  1740. }
  1741. }
  1742. }
  1743. };
  1744. var normalizeStart = true;
  1745. var sibling;
  1746. if (isCharacterDataNode(ec)) {
  1747. if (eo == ec.length) {
  1748. mergeForward(ec);
  1749. } else if (eo == 0) {
  1750. sibling = ec.previousSibling;
  1751. if (sibling && sibling.nodeType == ec.nodeType) {
  1752. eo = sibling.length;
  1753. if (sc == ec) {
  1754. normalizeStart = false;
  1755. }
  1756. sibling.appendData(ec.data);
  1757. removeNode(ec);
  1758. ec = sibling;
  1759. }
  1760. }
  1761. } else {
  1762. if (eo > 0) {
  1763. var endNode = ec.childNodes[eo - 1];
  1764. if (endNode && isCharacterDataNode(endNode)) {
  1765. mergeForward(endNode);
  1766. }
  1767. }
  1768. normalizeStart = !this.collapsed;
  1769. }
  1770. if (normalizeStart) {
  1771. if (isCharacterDataNode(sc)) {
  1772. if (so == 0) {
  1773. mergeBackward(sc);
  1774. } else if (so == sc.length) {
  1775. sibling = sc.nextSibling;
  1776. if (sibling && sibling.nodeType == sc.nodeType) {
  1777. if (ec == sibling) {
  1778. ec = sc;
  1779. eo += sc.length;
  1780. }
  1781. sc.appendData(sibling.data);
  1782. removeNode(sibling);
  1783. }
  1784. }
  1785. } else {
  1786. if (so < sc.childNodes.length) {
  1787. var startNode = sc.childNodes[so];
  1788. if (startNode && isCharacterDataNode(startNode)) {
  1789. mergeBackward(startNode);
  1790. }
  1791. }
  1792. }
  1793. } else {
  1794. sc = ec;
  1795. so = eo;
  1796. }
  1797. boundaryUpdater(this, sc, so, ec, eo);
  1798. },
  1799. collapseToPoint: function(node, offset) {
  1800. assertNoDocTypeNotationEntityAncestor(node, true);
  1801. assertValidOffset(node, offset);
  1802. this.setStartAndEnd(node, offset);
  1803. }
  1804. });
  1805. copyComparisonConstants(constructor);
  1806. }
  1807. /*----------------------------------------------------------------------------------------------------------------*/
  1808. // Updates commonAncestorContainer and collapsed after boundary change
  1809. function updateCollapsedAndCommonAncestor(range) {
  1810. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
  1811. range.commonAncestorContainer = range.collapsed ?
  1812. range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer);
  1813. }
  1814. function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) {
  1815. range.startContainer = startContainer;
  1816. range.startOffset = startOffset;
  1817. range.endContainer = endContainer;
  1818. range.endOffset = endOffset;
  1819. range.document = dom.getDocument(startContainer);
  1820. updateCollapsedAndCommonAncestor(range);
  1821. }
  1822. function Range(doc) {
  1823. this.startContainer = doc;
  1824. this.startOffset = 0;
  1825. this.endContainer = doc;
  1826. this.endOffset = 0;
  1827. this.document = doc;
  1828. updateCollapsedAndCommonAncestor(this);
  1829. }
  1830. createPrototypeRange(Range, updateBoundaries);
  1831. util.extend(Range, {
  1832. rangeProperties: rangeProperties,
  1833. RangeIterator: RangeIterator,
  1834. copyComparisonConstants: copyComparisonConstants,
  1835. createPrototypeRange: createPrototypeRange,
  1836. inspect: inspect,
  1837. toHtml: rangeToHtml,
  1838. getRangeDocument: getRangeDocument,
  1839. rangesEqual: function(r1, r2) {
  1840. return r1.startContainer === r2.startContainer &&
  1841. r1.startOffset === r2.startOffset &&
  1842. r1.endContainer === r2.endContainer &&
  1843. r1.endOffset === r2.endOffset;
  1844. }
  1845. });
  1846. api.DomRange = Range;
  1847. });
  1848. /*----------------------------------------------------------------------------------------------------------------*/
  1849. // Wrappers for the browser's native DOM Range and/or TextRange implementation
  1850. api.createCoreModule("WrappedRange", ["DomRange"], function(api, module) {
  1851. var WrappedRange, WrappedTextRange;
  1852. var dom = api.dom;
  1853. var util = api.util;
  1854. var DomPosition = dom.DomPosition;
  1855. var DomRange = api.DomRange;
  1856. var getBody = dom.getBody;
  1857. var getContentDocument = dom.getContentDocument;
  1858. var isCharacterDataNode = dom.isCharacterDataNode;
  1859. /*----------------------------------------------------------------------------------------------------------------*/
  1860. if (api.features.implementsDomRange) {
  1861. // This is a wrapper around the browser's native DOM Range. It has two aims:
  1862. // - Provide workarounds for specific browser bugs
  1863. // - provide convenient extensions, which are inherited from Rangy's DomRange
  1864. (function() {
  1865. var rangeProto;
  1866. var rangeProperties = DomRange.rangeProperties;
  1867. function updateRangeProperties(range) {
  1868. var i = rangeProperties.length, prop;
  1869. while (i--) {
  1870. prop = rangeProperties[i];
  1871. range[prop] = range.nativeRange[prop];
  1872. }
  1873. // Fix for broken collapsed property in IE 9.
  1874. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
  1875. }
  1876. function updateNativeRange(range, startContainer, startOffset, endContainer, endOffset) {
  1877. var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset);
  1878. var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset);
  1879. var nativeRangeDifferent = !range.equals(range.nativeRange);
  1880. // Always set both boundaries for the benefit of IE9 (see issue 35)
  1881. if (startMoved || endMoved || nativeRangeDifferent) {
  1882. range.setEnd(endContainer, endOffset);
  1883. range.setStart(startContainer, startOffset);
  1884. }
  1885. }
  1886. var createBeforeAfterNodeSetter;
  1887. WrappedRange = function(range) {
  1888. if (!range) {
  1889. throw module.createError("WrappedRange: Range must be specified");
  1890. }
  1891. this.nativeRange = range;
  1892. updateRangeProperties(this);
  1893. };
  1894. DomRange.createPrototypeRange(WrappedRange, updateNativeRange);
  1895. rangeProto = WrappedRange.prototype;
  1896. rangeProto.selectNode = function(node) {
  1897. this.nativeRange.selectNode(node);
  1898. updateRangeProperties(this);
  1899. };
  1900. rangeProto.cloneContents = function() {
  1901. return this.nativeRange.cloneContents();
  1902. };
  1903. // Due to a long-standing Firefox bug that I have not been able to find a reliable way to detect,
  1904. // insertNode() is never delegated to the native range.
  1905. rangeProto.surroundContents = function(node) {
  1906. this.nativeRange.surroundContents(node);
  1907. updateRangeProperties(this);
  1908. };
  1909. rangeProto.collapse = function(isStart) {
  1910. this.nativeRange.collapse(isStart);
  1911. updateRangeProperties(this);
  1912. };
  1913. rangeProto.cloneRange = function() {
  1914. return new WrappedRange(this.nativeRange.cloneRange());
  1915. };
  1916. rangeProto.refresh = function() {
  1917. updateRangeProperties(this);
  1918. };
  1919. rangeProto.toString = function() {
  1920. return this.nativeRange.toString();
  1921. };
  1922. // Create test range and node for feature detection
  1923. var testTextNode = document.createTextNode("test");
  1924. getBody(document).appendChild(testTextNode);
  1925. var range = document.createRange();
  1926. /*--------------------------------------------------------------------------------------------------------*/
  1927. // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and
  1928. // correct for it
  1929. range.setStart(testTextNode, 0);
  1930. range.setEnd(testTextNode, 0);
  1931. try {
  1932. range.setStart(testTextNode, 1);
  1933. rangeProto.setStart = function(node, offset) {
  1934. this.nativeRange.setStart(node, offset);
  1935. updateRangeProperties(this);
  1936. };
  1937. rangeProto.setEnd = function(node, offset) {
  1938. this.nativeRange.setEnd(node, offset);
  1939. updateRangeProperties(this);
  1940. };
  1941. createBeforeAfterNodeSetter = function(name) {
  1942. return function(node) {
  1943. this.nativeRange[name](node);
  1944. updateRangeProperties(this);
  1945. };
  1946. };
  1947. } catch(ex) {
  1948. rangeProto.setStart = function(node, offset) {
  1949. try {
  1950. this.nativeRange.setStart(node, offset);
  1951. } catch (ex) {
  1952. this.nativeRange.setEnd(node, offset);
  1953. this.nativeRange.setStart(node, offset);
  1954. }
  1955. updateRangeProperties(this);
  1956. };
  1957. rangeProto.setEnd = function(node, offset) {
  1958. try {
  1959. this.nativeRange.setEnd(node, offset);
  1960. } catch (ex) {
  1961. this.nativeRange.setStart(node, offset);
  1962. this.nativeRange.setEnd(node, offset);
  1963. }
  1964. updateRangeProperties(this);
  1965. };
  1966. createBeforeAfterNodeSetter = function(name, oppositeName) {
  1967. return function(node) {
  1968. try {
  1969. this.nativeRange[name](node);
  1970. } catch (ex) {
  1971. this.nativeRange[oppositeName](node);
  1972. this.nativeRange[name](node);
  1973. }
  1974. updateRangeProperties(this);
  1975. };
  1976. };
  1977. }
  1978. rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore");
  1979. rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter");
  1980. rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore");
  1981. rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter");
  1982. /*--------------------------------------------------------------------------------------------------------*/
  1983. // Always use DOM4-compliant selectNodeContents implementation: it's simpler and less code than testing
  1984. // whether the native implementation can be trusted
  1985. rangeProto.selectNodeContents = function(node) {
  1986. this.setStartAndEnd(node, 0, dom.getNodeLength(node));
  1987. };
  1988. /*--------------------------------------------------------------------------------------------------------*/
  1989. // Test for and correct WebKit bug that has the behaviour of compareBoundaryPoints round the wrong way for
  1990. // constants START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738
  1991. range.selectNodeContents(testTextNode);
  1992. range.setEnd(testTextNode, 3);
  1993. var range2 = document.createRange();
  1994. range2.selectNodeContents(testTextNode);
  1995. range2.setEnd(testTextNode, 4);
  1996. range2.setStart(testTextNode, 2);
  1997. if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 &&
  1998. range.compareBoundaryPoints(range.END_TO_START, range2) == 1) {
  1999. // This is the wrong way round, so correct for it
  2000. rangeProto.compareBoundaryPoints = function(type, range) {
  2001. range = range.nativeRange || range;
  2002. if (type == range.START_TO_END) {
  2003. type = range.END_TO_START;
  2004. } else if (type == range.END_TO_START) {
  2005. type = range.START_TO_END;
  2006. }
  2007. return this.nativeRange.compareBoundaryPoints(type, range);
  2008. };
  2009. } else {
  2010. rangeProto.compareBoundaryPoints = function(type, range) {
  2011. return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range);
  2012. };
  2013. }
  2014. /*--------------------------------------------------------------------------------------------------------*/
  2015. // Test for IE deleteContents() and extractContents() bug and correct it. See issue 107.
  2016. var el = document.createElement("div");
  2017. el.innerHTML = "123";
  2018. var textNode = el.firstChild;
  2019. var body = getBody(document);
  2020. body.appendChild(el);
  2021. range.setStart(textNode, 1);
  2022. range.setEnd(textNode, 2);
  2023. range.deleteContents();
  2024. if (textNode.data == "13") {
  2025. // Behaviour is correct per DOM4 Range so wrap the browser's implementation of deleteContents() and
  2026. // extractContents()
  2027. rangeProto.deleteContents = function() {
  2028. this.nativeRange.deleteContents();
  2029. updateRangeProperties(this);
  2030. };
  2031. rangeProto.extractContents = function() {
  2032. var frag = this.nativeRange.extractContents();
  2033. updateRangeProperties(this);
  2034. return frag;
  2035. };
  2036. } else {
  2037. }
  2038. body.removeChild(el);
  2039. body = null;
  2040. /*--------------------------------------------------------------------------------------------------------*/
  2041. // Test for existence of createContextualFragment and delegate to it if it exists
  2042. if (util.isHostMethod(range, "createContextualFragment")) {
  2043. rangeProto.createContextualFragment = function(fragmentStr) {
  2044. return this.nativeRange.createContextualFragment(fragmentStr);
  2045. };
  2046. }
  2047. /*--------------------------------------------------------------------------------------------------------*/
  2048. // Clean up
  2049. getBody(document).removeChild(testTextNode);
  2050. rangeProto.getName = function() {
  2051. return "WrappedRange";
  2052. };
  2053. api.WrappedRange = WrappedRange;
  2054. api.createNativeRange = function(doc) {
  2055. doc = getContentDocument(doc, module, "createNativeRange");
  2056. return doc.createRange();
  2057. };
  2058. })();
  2059. }
  2060. if (api.features.implementsTextRange) {
  2061. /*
  2062. This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement()
  2063. method. For example, in the following (where pipes denote the selection boundaries):
  2064. <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul>
  2065. var range = document.selection.createRange();
  2066. alert(range.parentElement().id); // Should alert "ul" but alerts "b"
  2067. This method returns the common ancestor node of the following:
  2068. - the parentElement() of the textRange
  2069. - the parentElement() of the textRange after calling collapse(true)
  2070. - the parentElement() of the textRange after calling collapse(false)
  2071. */
  2072. var getTextRangeContainerElement = function(textRange) {
  2073. var parentEl = textRange.parentElement();
  2074. var range = textRange.duplicate();
  2075. range.collapse(true);
  2076. var startEl = range.parentElement();
  2077. range = textRange.duplicate();
  2078. range.collapse(false);
  2079. var endEl = range.parentElement();
  2080. var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl);
  2081. return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);
  2082. };
  2083. var textRangeIsCollapsed = function(textRange) {
  2084. return textRange.compareEndPoints("StartToEnd", textRange) == 0;
  2085. };
  2086. // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started
  2087. // out as an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/)
  2088. // but has grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange
  2089. // bugs, handling for inputs and images, plus optimizations.
  2090. var getTextRangeBoundaryPosition = function(textRange, wholeRangeContainerElement, isStart, isCollapsed, startInfo) {
  2091. var workingRange = textRange.duplicate();
  2092. workingRange.collapse(isStart);
  2093. var containerElement = workingRange.parentElement();
  2094. // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so
  2095. // check for that
  2096. if (!dom.isOrIsAncestorOf(wholeRangeContainerElement, containerElement)) {
  2097. containerElement = wholeRangeContainerElement;
  2098. }
  2099. // Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and
  2100. // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx
  2101. if (!containerElement.canHaveHTML) {
  2102. var pos = new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement));
  2103. return {
  2104. boundaryPosition: pos,
  2105. nodeInfo: {
  2106. nodeIndex: pos.offset,
  2107. containerElement: pos.node
  2108. }
  2109. };
  2110. }
  2111. var workingNode = dom.getDocument(containerElement).createElement("span");
  2112. // Workaround for HTML5 Shiv's insane violation of document.createElement(). See Rangy issue 104 and HTML5
  2113. // Shiv issue 64: https://github.com/aFarkas/html5shiv/issues/64
  2114. if (workingNode.parentNode) {
  2115. dom.removeNode(workingNode);
  2116. }
  2117. var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd";
  2118. var previousNode, nextNode, boundaryPosition, boundaryNode;
  2119. var start = (startInfo && startInfo.containerElement == containerElement) ? startInfo.nodeIndex : 0;
  2120. var childNodeCount = containerElement.childNodes.length;
  2121. var end = childNodeCount;
  2122. // Check end first. Code within the loop assumes that the endth child node of the container is definitely
  2123. // after the range boundary.
  2124. var nodeIndex = end;
  2125. while (true) {
  2126. if (nodeIndex == childNodeCount) {
  2127. containerElement.appendChild(workingNode);
  2128. } else {
  2129. containerElement.insertBefore(workingNode, containerElement.childNodes[nodeIndex]);
  2130. }
  2131. workingRange.moveToElementText(workingNode);
  2132. comparison = workingRange.compareEndPoints(workingComparisonType, textRange);
  2133. if (comparison == 0 || start == end) {
  2134. break;
  2135. } else if (comparison == -1) {
  2136. if (end == start + 1) {
  2137. // We know the endth child node is after the range boundary, so we must be done.
  2138. break;
  2139. } else {
  2140. start = nodeIndex;
  2141. }
  2142. } else {
  2143. end = (end == start + 1) ? start : nodeIndex;
  2144. }
  2145. nodeIndex = Math.floor((start + end) / 2);
  2146. containerElement.removeChild(workingNode);
  2147. }
  2148. // We've now reached or gone past the boundary of the text range we're interested in
  2149. // so have identified the node we want
  2150. boundaryNode = workingNode.nextSibling;
  2151. if (comparison == -1 && boundaryNode && isCharacterDataNode(boundaryNode)) {
  2152. // This is a character data node (text, comment, cdata). The working range is collapsed at the start of
  2153. // the node containing the text range's boundary, so we move the end of the working range to the
  2154. // boundary point and measure the length of its text to get the boundary's offset within the node.
  2155. workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange);
  2156. var offset;
  2157. if (/[\r\n]/.test(boundaryNode.data)) {
  2158. /*
  2159. For the particular case of a boundary within a text node containing rendered line breaks (within a
  2160. <pre> element, for example), we need a slightly complicated approach to get the boundary's offset in
  2161. IE. The facts:
  2162. - Each line break is represented as \r in the text node's data/nodeValue properties
  2163. - Each line break is represented as \r\n in the TextRange's 'text' property
  2164. - The 'text' property of the TextRange does not contain trailing line breaks
  2165. To get round the problem presented by the final fact above, we can use the fact that TextRange's
  2166. moveStart() and moveEnd() methods return the actual number of characters moved, which is not
  2167. necessarily the same as the number of characters it was instructed to move. The simplest approach is
  2168. to use this to store the characters moved when moving both the start and end of the range to the
  2169. start of the document body and subtracting the start offset from the end offset (the
  2170. "move-negative-gazillion" method). However, this is extremely slow when the document is large and
  2171. the range is near the end of it. Clearly doing the mirror image (i.e. moving the range boundaries to
  2172. the end of the document) has the same problem.
  2173. Another approach that works is to use moveStart() to move the start boundary of the range up to the
  2174. end boundary one character at a time and incrementing a counter with the value returned by the
  2175. moveStart() call. However, the check for whether the start boundary has reached the end boundary is
  2176. expensive, so this method is slow (although unlike "move-negative-gazillion" is largely unaffected
  2177. by the location of the range within the document).
  2178. The approach used below is a hybrid of the two methods above. It uses the fact that a string
  2179. containing the TextRange's 'text' property with each \r\n converted to a single \r character cannot
  2180. be longer than the text of the TextRange, so the start of the range is moved that length initially
  2181. and then a character at a time to make up for any trailing line breaks not contained in the 'text'
  2182. property. This has good performance in most situations compared to the previous two methods.
  2183. */
  2184. var tempRange = workingRange.duplicate();
  2185. var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length;
  2186. offset = tempRange.moveStart("character", rangeLength);
  2187. while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) {
  2188. offset++;
  2189. tempRange.moveStart("character", 1);
  2190. }
  2191. } else {
  2192. offset = workingRange.text.length;
  2193. }
  2194. boundaryPosition = new DomPosition(boundaryNode, offset);
  2195. } else {
  2196. // If the boundary immediately follows a character data node and this is the end boundary, we should favour
  2197. // a position within that, and likewise for a start boundary preceding a character data node
  2198. previousNode = (isCollapsed || !isStart) && workingNode.previousSibling;
  2199. nextNode = (isCollapsed || isStart) && workingNode.nextSibling;
  2200. if (nextNode && isCharacterDataNode(nextNode)) {
  2201. boundaryPosition = new DomPosition(nextNode, 0);
  2202. } else if (previousNode && isCharacterDataNode(previousNode)) {
  2203. boundaryPosition = new DomPosition(previousNode, previousNode.data.length);
  2204. } else {
  2205. boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode));
  2206. }
  2207. }
  2208. // Clean up
  2209. dom.removeNode(workingNode);
  2210. return {
  2211. boundaryPosition: boundaryPosition,
  2212. nodeInfo: {
  2213. nodeIndex: nodeIndex,
  2214. containerElement: containerElement
  2215. }
  2216. };
  2217. };
  2218. // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that
  2219. // node. This function started out as an optimized version of code found in Tim Cameron Ryan's IERange
  2220. // (http://code.google.com/p/ierange/)
  2221. var createBoundaryTextRange = function(boundaryPosition, isStart) {
  2222. var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset;
  2223. var doc = dom.getDocument(boundaryPosition.node);
  2224. var workingNode, childNodes, workingRange = getBody(doc).createTextRange();
  2225. var nodeIsDataNode = isCharacterDataNode(boundaryPosition.node);
  2226. if (nodeIsDataNode) {
  2227. boundaryNode = boundaryPosition.node;
  2228. boundaryParent = boundaryNode.parentNode;
  2229. } else {
  2230. childNodes = boundaryPosition.node.childNodes;
  2231. boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null;
  2232. boundaryParent = boundaryPosition.node;
  2233. }
  2234. // Position the range immediately before the node containing the boundary
  2235. workingNode = doc.createElement("span");
  2236. // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within
  2237. // the element rather than immediately before or after it
  2238. workingNode.innerHTML = "&#feff;";
  2239. // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report
  2240. // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12
  2241. if (boundaryNode) {
  2242. boundaryParent.insertBefore(workingNode, boundaryNode);
  2243. } else {
  2244. boundaryParent.appendChild(workingNode);
  2245. }
  2246. workingRange.moveToElementText(workingNode);
  2247. workingRange.collapse(!isStart);
  2248. // Clean up
  2249. boundaryParent.removeChild(workingNode);
  2250. // Move the working range to the text offset, if required
  2251. if (nodeIsDataNode) {
  2252. workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset);
  2253. }
  2254. return workingRange;
  2255. };
  2256. /*------------------------------------------------------------------------------------------------------------*/
  2257. // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a
  2258. // prototype
  2259. WrappedTextRange = function(textRange) {
  2260. this.textRange = textRange;
  2261. this.refresh();
  2262. };
  2263. WrappedTextRange.prototype = new DomRange(document);
  2264. WrappedTextRange.prototype.refresh = function() {
  2265. var start, end, startBoundary;
  2266. // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that.
  2267. var rangeContainerElement = getTextRangeContainerElement(this.textRange);
  2268. if (textRangeIsCollapsed(this.textRange)) {
  2269. end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true,
  2270. true).boundaryPosition;
  2271. } else {
  2272. startBoundary = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false);
  2273. start = startBoundary.boundaryPosition;
  2274. // An optimization used here is that if the start and end boundaries have the same parent element, the
  2275. // search scope for the end boundary can be limited to exclude the portion of the element that precedes
  2276. // the start boundary
  2277. end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false,
  2278. startBoundary.nodeInfo).boundaryPosition;
  2279. }
  2280. this.setStart(start.node, start.offset);
  2281. this.setEnd(end.node, end.offset);
  2282. };
  2283. WrappedTextRange.prototype.getName = function() {
  2284. return "WrappedTextRange";
  2285. };
  2286. DomRange.copyComparisonConstants(WrappedTextRange);
  2287. var rangeToTextRange = function(range) {
  2288. if (range.collapsed) {
  2289. return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
  2290. } else {
  2291. var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
  2292. var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false);
  2293. var textRange = getBody( DomRange.getRangeDocument(range) ).createTextRange();
  2294. textRange.setEndPoint("StartToStart", startRange);
  2295. textRange.setEndPoint("EndToEnd", endRange);
  2296. return textRange;
  2297. }
  2298. };
  2299. WrappedTextRange.rangeToTextRange = rangeToTextRange;
  2300. WrappedTextRange.prototype.toTextRange = function() {
  2301. return rangeToTextRange(this);
  2302. };
  2303. api.WrappedTextRange = WrappedTextRange;
  2304. // IE 9 and above have both implementations and Rangy makes both available. The next few lines sets which
  2305. // implementation to use by default.
  2306. if (!api.features.implementsDomRange || api.config.preferTextRange) {
  2307. // Add WrappedTextRange as the Range property of the global object to allow expression like Range.END_TO_END to work
  2308. var globalObj = (function(f) { return f("return this;")(); })(Function);
  2309. if (typeof globalObj.Range == "undefined") {
  2310. globalObj.Range = WrappedTextRange;
  2311. }
  2312. api.createNativeRange = function(doc) {
  2313. doc = getContentDocument(doc, module, "createNativeRange");
  2314. return getBody(doc).createTextRange();
  2315. };
  2316. api.WrappedRange = WrappedTextRange;
  2317. }
  2318. }
  2319. api.createRange = function(doc) {
  2320. doc = getContentDocument(doc, module, "createRange");
  2321. return new api.WrappedRange(api.createNativeRange(doc));
  2322. };
  2323. api.createRangyRange = function(doc) {
  2324. doc = getContentDocument(doc, module, "createRangyRange");
  2325. return new DomRange(doc);
  2326. };
  2327. util.createAliasForDeprecatedMethod(api, "createIframeRange", "createRange");
  2328. util.createAliasForDeprecatedMethod(api, "createIframeRangyRange", "createRangyRange");
  2329. api.addShimListener(function(win) {
  2330. var doc = win.document;
  2331. if (typeof doc.createRange == "undefined") {
  2332. doc.createRange = function() {
  2333. return api.createRange(doc);
  2334. };
  2335. }
  2336. doc = win = null;
  2337. });
  2338. });
  2339. /*----------------------------------------------------------------------------------------------------------------*/
  2340. // This module creates a selection object wrapper that conforms as closely as possible to the Selection specification
  2341. // in the HTML Editing spec (http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#selections)
  2342. api.createCoreModule("WrappedSelection", ["DomRange", "WrappedRange"], function(api, module) {
  2343. api.config.checkSelectionRanges = true;
  2344. var BOOLEAN = "boolean";
  2345. var NUMBER = "number";
  2346. var dom = api.dom;
  2347. var util = api.util;
  2348. var isHostMethod = util.isHostMethod;
  2349. var DomRange = api.DomRange;
  2350. var WrappedRange = api.WrappedRange;
  2351. var DOMException = api.DOMException;
  2352. var DomPosition = dom.DomPosition;
  2353. var getNativeSelection;
  2354. var selectionIsCollapsed;
  2355. var features = api.features;
  2356. var CONTROL = "Control";
  2357. var getDocument = dom.getDocument;
  2358. var getBody = dom.getBody;
  2359. var rangesEqual = DomRange.rangesEqual;
  2360. // Utility function to support direction parameters in the API that may be a string ("backward", "backwards",
  2361. // "forward" or "forwards") or a Boolean (true for backwards).
  2362. function isDirectionBackward(dir) {
  2363. return (typeof dir == "string") ? /^backward(s)?$/i.test(dir) : !!dir;
  2364. }
  2365. function getWindow(win, methodName) {
  2366. if (!win) {
  2367. return window;
  2368. } else if (dom.isWindow(win)) {
  2369. return win;
  2370. } else if (win instanceof WrappedSelection) {
  2371. return win.win;
  2372. } else {
  2373. var doc = dom.getContentDocument(win, module, methodName);
  2374. return dom.getWindow(doc);
  2375. }
  2376. }
  2377. function getWinSelection(winParam) {
  2378. return getWindow(winParam, "getWinSelection").getSelection();
  2379. }
  2380. function getDocSelection(winParam) {
  2381. return getWindow(winParam, "getDocSelection").document.selection;
  2382. }
  2383. function winSelectionIsBackward(sel) {
  2384. var backward = false;
  2385. if (sel.anchorNode) {
  2386. backward = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1);
  2387. }
  2388. return backward;
  2389. }
  2390. // Test for the Range/TextRange and Selection features required
  2391. // Test for ability to retrieve selection
  2392. var implementsWinGetSelection = isHostMethod(window, "getSelection"),
  2393. implementsDocSelection = util.isHostObject(document, "selection");
  2394. features.implementsWinGetSelection = implementsWinGetSelection;
  2395. features.implementsDocSelection = implementsDocSelection;
  2396. var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange);
  2397. if (useDocumentSelection) {
  2398. getNativeSelection = getDocSelection;
  2399. api.isSelectionValid = function(winParam) {
  2400. var doc = getWindow(winParam, "isSelectionValid").document, nativeSel = doc.selection;
  2401. // Check whether the selection TextRange is actually contained within the correct document
  2402. return (nativeSel.type != "None" || getDocument(nativeSel.createRange().parentElement()) == doc);
  2403. };
  2404. } else if (implementsWinGetSelection) {
  2405. getNativeSelection = getWinSelection;
  2406. api.isSelectionValid = function() {
  2407. return true;
  2408. };
  2409. } else {
  2410. module.fail("Neither document.selection or window.getSelection() detected.");
  2411. return false;
  2412. }
  2413. api.getNativeSelection = getNativeSelection;
  2414. var testSelection = getNativeSelection();
  2415. // In Firefox, the selection is null in an iframe with display: none. See issue #138.
  2416. if (!testSelection) {
  2417. module.fail("Native selection was null (possibly issue 138?)");
  2418. return false;
  2419. }
  2420. var testRange = api.createNativeRange(document);
  2421. var body = getBody(document);
  2422. // Obtaining a range from a selection
  2423. var selectionHasAnchorAndFocus = util.areHostProperties(testSelection,
  2424. ["anchorNode", "focusNode", "anchorOffset", "focusOffset"]);
  2425. features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus;
  2426. // Test for existence of native selection extend() method
  2427. var selectionHasExtend = isHostMethod(testSelection, "extend");
  2428. features.selectionHasExtend = selectionHasExtend;
  2429. // Test if rangeCount exists
  2430. var selectionHasRangeCount = (typeof testSelection.rangeCount == NUMBER);
  2431. features.selectionHasRangeCount = selectionHasRangeCount;
  2432. var selectionSupportsMultipleRanges = false;
  2433. var collapsedNonEditableSelectionsSupported = true;
  2434. var addRangeBackwardToNative = selectionHasExtend ?
  2435. function(nativeSelection, range) {
  2436. var doc = DomRange.getRangeDocument(range);
  2437. var endRange = api.createRange(doc);
  2438. endRange.collapseToPoint(range.endContainer, range.endOffset);
  2439. nativeSelection.addRange(getNativeRange(endRange));
  2440. nativeSelection.extend(range.startContainer, range.startOffset);
  2441. } : null;
  2442. if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) &&
  2443. typeof testSelection.rangeCount == NUMBER && features.implementsDomRange) {
  2444. (function() {
  2445. // Previously an iframe was used but this caused problems in some circumstances in IE, so tests are
  2446. // performed on the current document's selection. See issue 109.
  2447. // Note also that if a selection previously existed, it is wiped and later restored by these tests. This
  2448. // will result in the selection direction begin reversed if the original selection was backwards and the
  2449. // browser does not support setting backwards selections (Internet Explorer, I'm looking at you).
  2450. var sel = window.getSelection();
  2451. if (sel) {
  2452. // Store the current selection
  2453. var originalSelectionRangeCount = sel.rangeCount;
  2454. var selectionHasMultipleRanges = (originalSelectionRangeCount > 1);
  2455. var originalSelectionRanges = [];
  2456. var originalSelectionBackward = winSelectionIsBackward(sel);
  2457. for (var i = 0; i < originalSelectionRangeCount; ++i) {
  2458. originalSelectionRanges[i] = sel.getRangeAt(i);
  2459. }
  2460. // Create some test elements
  2461. var testEl = dom.createTestElement(document, "", false);
  2462. var textNode = testEl.appendChild( document.createTextNode("\u00a0\u00a0\u00a0") );
  2463. // Test whether the native selection will allow a collapsed selection within a non-editable element
  2464. var r1 = document.createRange();
  2465. r1.setStart(textNode, 1);
  2466. r1.collapse(true);
  2467. sel.removeAllRanges();
  2468. sel.addRange(r1);
  2469. collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);
  2470. sel.removeAllRanges();
  2471. // Test whether the native selection is capable of supporting multiple ranges.
  2472. if (!selectionHasMultipleRanges) {
  2473. // Doing the original feature test here in Chrome 36 (and presumably later versions) prints a
  2474. // console error of "Discontiguous selection is not supported." that cannot be suppressed. There's
  2475. // nothing we can do about this while retaining the feature test so we have to resort to a browser
  2476. // sniff. I'm not happy about it. See
  2477. // https://code.google.com/p/chromium/issues/detail?id=399791
  2478. var chromeMatch = window.navigator.appVersion.match(/Chrome\/(.*?) /);
  2479. if (chromeMatch && parseInt(chromeMatch[1]) >= 36) {
  2480. selectionSupportsMultipleRanges = false;
  2481. } else {
  2482. var r2 = r1.cloneRange();
  2483. r1.setStart(textNode, 0);
  2484. r2.setEnd(textNode, 3);
  2485. r2.setStart(textNode, 2);
  2486. sel.addRange(r1);
  2487. sel.addRange(r2);
  2488. selectionSupportsMultipleRanges = (sel.rangeCount == 2);
  2489. }
  2490. }
  2491. // Clean up
  2492. dom.removeNode(testEl);
  2493. sel.removeAllRanges();
  2494. for (i = 0; i < originalSelectionRangeCount; ++i) {
  2495. if (i == 0 && originalSelectionBackward) {
  2496. if (addRangeBackwardToNative) {
  2497. addRangeBackwardToNative(sel, originalSelectionRanges[i]);
  2498. } else {
  2499. api.warn("Rangy initialization: original selection was backwards but selection has been restored forwards because the browser does not support Selection.extend");
  2500. sel.addRange(originalSelectionRanges[i]);
  2501. }
  2502. } else {
  2503. sel.addRange(originalSelectionRanges[i]);
  2504. }
  2505. }
  2506. }
  2507. })();
  2508. }
  2509. features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges;
  2510. features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported;
  2511. // ControlRanges
  2512. var implementsControlRange = false, testControlRange;
  2513. if (body && isHostMethod(body, "createControlRange")) {
  2514. testControlRange = body.createControlRange();
  2515. if (util.areHostProperties(testControlRange, ["item", "add"])) {
  2516. implementsControlRange = true;
  2517. }
  2518. }
  2519. features.implementsControlRange = implementsControlRange;
  2520. // Selection collapsedness
  2521. if (selectionHasAnchorAndFocus) {
  2522. selectionIsCollapsed = function(sel) {
  2523. return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset;
  2524. };
  2525. } else {
  2526. selectionIsCollapsed = function(sel) {
  2527. return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false;
  2528. };
  2529. }
  2530. function updateAnchorAndFocusFromRange(sel, range, backward) {
  2531. var anchorPrefix = backward ? "end" : "start", focusPrefix = backward ? "start" : "end";
  2532. sel.anchorNode = range[anchorPrefix + "Container"];
  2533. sel.anchorOffset = range[anchorPrefix + "Offset"];
  2534. sel.focusNode = range[focusPrefix + "Container"];
  2535. sel.focusOffset = range[focusPrefix + "Offset"];
  2536. }
  2537. function updateAnchorAndFocusFromNativeSelection(sel) {
  2538. var nativeSel = sel.nativeSelection;
  2539. sel.anchorNode = nativeSel.anchorNode;
  2540. sel.anchorOffset = nativeSel.anchorOffset;
  2541. sel.focusNode = nativeSel.focusNode;
  2542. sel.focusOffset = nativeSel.focusOffset;
  2543. }
  2544. function updateEmptySelection(sel) {
  2545. sel.anchorNode = sel.focusNode = null;
  2546. sel.anchorOffset = sel.focusOffset = 0;
  2547. sel.rangeCount = 0;
  2548. sel.isCollapsed = true;
  2549. sel._ranges.length = 0;
  2550. }
  2551. function getNativeRange(range) {
  2552. var nativeRange;
  2553. if (range instanceof DomRange) {
  2554. nativeRange = api.createNativeRange(range.getDocument());
  2555. nativeRange.setEnd(range.endContainer, range.endOffset);
  2556. nativeRange.setStart(range.startContainer, range.startOffset);
  2557. } else if (range instanceof WrappedRange) {
  2558. nativeRange = range.nativeRange;
  2559. } else if (features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) {
  2560. nativeRange = range;
  2561. }
  2562. return nativeRange;
  2563. }
  2564. function rangeContainsSingleElement(rangeNodes) {
  2565. if (!rangeNodes.length || rangeNodes[0].nodeType != 1) {
  2566. return false;
  2567. }
  2568. for (var i = 1, len = rangeNodes.length; i < len; ++i) {
  2569. if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) {
  2570. return false;
  2571. }
  2572. }
  2573. return true;
  2574. }
  2575. function getSingleElementFromRange(range) {
  2576. var nodes = range.getNodes();
  2577. if (!rangeContainsSingleElement(nodes)) {
  2578. throw module.createError("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element");
  2579. }
  2580. return nodes[0];
  2581. }
  2582. // Simple, quick test which only needs to distinguish between a TextRange and a ControlRange
  2583. function isTextRange(range) {
  2584. return !!range && typeof range.text != "undefined";
  2585. }
  2586. function updateFromTextRange(sel, range) {
  2587. // Create a Range from the selected TextRange
  2588. var wrappedRange = new WrappedRange(range);
  2589. sel._ranges = [wrappedRange];
  2590. updateAnchorAndFocusFromRange(sel, wrappedRange, false);
  2591. sel.rangeCount = 1;
  2592. sel.isCollapsed = wrappedRange.collapsed;
  2593. }
  2594. function updateControlSelection(sel) {
  2595. // Update the wrapped selection based on what's now in the native selection
  2596. sel._ranges.length = 0;
  2597. if (sel.docSelection.type == "None") {
  2598. updateEmptySelection(sel);
  2599. } else {
  2600. var controlRange = sel.docSelection.createRange();
  2601. if (isTextRange(controlRange)) {
  2602. // This case (where the selection type is "Control" and calling createRange() on the selection returns
  2603. // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected
  2604. // ControlRange have been removed from the ControlRange and removed from the document.
  2605. updateFromTextRange(sel, controlRange);
  2606. } else {
  2607. sel.rangeCount = controlRange.length;
  2608. var range, doc = getDocument(controlRange.item(0));
  2609. for (var i = 0; i < sel.rangeCount; ++i) {
  2610. range = api.createRange(doc);
  2611. range.selectNode(controlRange.item(i));
  2612. sel._ranges.push(range);
  2613. }
  2614. sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed;
  2615. updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false);
  2616. }
  2617. }
  2618. }
  2619. function addRangeToControlSelection(sel, range) {
  2620. var controlRange = sel.docSelection.createRange();
  2621. var rangeElement = getSingleElementFromRange(range);
  2622. // Create a new ControlRange containing all the elements in the selected ControlRange plus the element
  2623. // contained by the supplied range
  2624. var doc = getDocument(controlRange.item(0));
  2625. var newControlRange = getBody(doc).createControlRange();
  2626. for (var i = 0, len = controlRange.length; i < len; ++i) {
  2627. newControlRange.add(controlRange.item(i));
  2628. }
  2629. try {
  2630. newControlRange.add(rangeElement);
  2631. } catch (ex) {
  2632. throw module.createError("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)");
  2633. }
  2634. newControlRange.select();
  2635. // Update the wrapped selection based on what's now in the native selection
  2636. updateControlSelection(sel);
  2637. }
  2638. var getSelectionRangeAt;
  2639. if (isHostMethod(testSelection, "getRangeAt")) {
  2640. // try/catch is present because getRangeAt() must have thrown an error in some browser and some situation.
  2641. // Unfortunately, I didn't write a comment about the specifics and am now scared to take it out. Let that be a
  2642. // lesson to us all, especially me.
  2643. getSelectionRangeAt = function(sel, index) {
  2644. try {
  2645. return sel.getRangeAt(index);
  2646. } catch (ex) {
  2647. return null;
  2648. }
  2649. };
  2650. } else if (selectionHasAnchorAndFocus) {
  2651. getSelectionRangeAt = function(sel) {
  2652. var doc = getDocument(sel.anchorNode);
  2653. var range = api.createRange(doc);
  2654. range.setStartAndEnd(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset);
  2655. // Handle the case when the selection was selected backwards (from the end to the start in the
  2656. // document)
  2657. if (range.collapsed !== this.isCollapsed) {
  2658. range.setStartAndEnd(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset);
  2659. }
  2660. return range;
  2661. };
  2662. }
  2663. function WrappedSelection(selection, docSelection, win) {
  2664. this.nativeSelection = selection;
  2665. this.docSelection = docSelection;
  2666. this._ranges = [];
  2667. this.win = win;
  2668. this.refresh();
  2669. }
  2670. WrappedSelection.prototype = api.selectionPrototype;
  2671. function deleteProperties(sel) {
  2672. sel.win = sel.anchorNode = sel.focusNode = sel._ranges = null;
  2673. sel.rangeCount = sel.anchorOffset = sel.focusOffset = 0;
  2674. sel.detached = true;
  2675. }
  2676. var cachedRangySelections = [];
  2677. function actOnCachedSelection(win, action) {
  2678. var i = cachedRangySelections.length, cached, sel;
  2679. while (i--) {
  2680. cached = cachedRangySelections[i];
  2681. sel = cached.selection;
  2682. if (action == "deleteAll") {
  2683. deleteProperties(sel);
  2684. } else if (cached.win == win) {
  2685. if (action == "delete") {
  2686. cachedRangySelections.splice(i, 1);
  2687. return true;
  2688. } else {
  2689. return sel;
  2690. }
  2691. }
  2692. }
  2693. if (action == "deleteAll") {
  2694. cachedRangySelections.length = 0;
  2695. }
  2696. return null;
  2697. }
  2698. var getSelection = function(win) {
  2699. // Check if the parameter is a Rangy Selection object
  2700. if (win && win instanceof WrappedSelection) {
  2701. win.refresh();
  2702. return win;
  2703. }
  2704. win = getWindow(win, "getNativeSelection");
  2705. var sel = actOnCachedSelection(win);
  2706. var nativeSel = getNativeSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null;
  2707. if (sel) {
  2708. sel.nativeSelection = nativeSel;
  2709. sel.docSelection = docSel;
  2710. sel.refresh();
  2711. } else {
  2712. sel = new WrappedSelection(nativeSel, docSel, win);
  2713. cachedRangySelections.push( { win: win, selection: sel } );
  2714. }
  2715. return sel;
  2716. };
  2717. api.getSelection = getSelection;
  2718. util.createAliasForDeprecatedMethod(api, "getIframeSelection", "getSelection");
  2719. var selProto = WrappedSelection.prototype;
  2720. function createControlSelection(sel, ranges) {
  2721. // Ensure that the selection becomes of type "Control"
  2722. var doc = getDocument(ranges[0].startContainer);
  2723. var controlRange = getBody(doc).createControlRange();
  2724. for (var i = 0, el, len = ranges.length; i < len; ++i) {
  2725. el = getSingleElementFromRange(ranges[i]);
  2726. try {
  2727. controlRange.add(el);
  2728. } catch (ex) {
  2729. throw module.createError("setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)");
  2730. }
  2731. }
  2732. controlRange.select();
  2733. // Update the wrapped selection based on what's now in the native selection
  2734. updateControlSelection(sel);
  2735. }
  2736. // Selecting a range
  2737. if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) {
  2738. selProto.removeAllRanges = function() {
  2739. this.nativeSelection.removeAllRanges();
  2740. updateEmptySelection(this);
  2741. };
  2742. var addRangeBackward = function(sel, range) {
  2743. addRangeBackwardToNative(sel.nativeSelection, range);
  2744. sel.refresh();
  2745. };
  2746. if (selectionHasRangeCount) {
  2747. selProto.addRange = function(range, direction) {
  2748. if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
  2749. addRangeToControlSelection(this, range);
  2750. } else {
  2751. if (isDirectionBackward(direction) && selectionHasExtend) {
  2752. addRangeBackward(this, range);
  2753. } else {
  2754. var previousRangeCount;
  2755. if (selectionSupportsMultipleRanges) {
  2756. previousRangeCount = this.rangeCount;
  2757. } else {
  2758. this.removeAllRanges();
  2759. previousRangeCount = 0;
  2760. }
  2761. // Clone the native range so that changing the selected range does not affect the selection.
  2762. // This is contrary to the spec but is the only way to achieve consistency between browsers. See
  2763. // issue 80.
  2764. var clonedNativeRange = getNativeRange(range).cloneRange();
  2765. try {
  2766. this.nativeSelection.addRange(clonedNativeRange);
  2767. } catch (ex) {
  2768. }
  2769. // Check whether adding the range was successful
  2770. this.rangeCount = this.nativeSelection.rangeCount;
  2771. if (this.rangeCount == previousRangeCount + 1) {
  2772. // The range was added successfully
  2773. // Check whether the range that we added to the selection is reflected in the last range extracted from
  2774. // the selection
  2775. if (api.config.checkSelectionRanges) {
  2776. var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1);
  2777. if (nativeRange && !rangesEqual(nativeRange, range)) {
  2778. // Happens in WebKit with, for example, a selection placed at the start of a text node
  2779. range = new WrappedRange(nativeRange);
  2780. }
  2781. }
  2782. this._ranges[this.rangeCount - 1] = range;
  2783. updateAnchorAndFocusFromRange(this, range, selectionIsBackward(this.nativeSelection));
  2784. this.isCollapsed = selectionIsCollapsed(this);
  2785. } else {
  2786. // The range was not added successfully. The simplest thing is to refresh
  2787. this.refresh();
  2788. }
  2789. }
  2790. }
  2791. };
  2792. } else {
  2793. selProto.addRange = function(range, direction) {
  2794. if (isDirectionBackward(direction) && selectionHasExtend) {
  2795. addRangeBackward(this, range);
  2796. } else {
  2797. this.nativeSelection.addRange(getNativeRange(range));
  2798. this.refresh();
  2799. }
  2800. };
  2801. }
  2802. selProto.setRanges = function(ranges) {
  2803. if (implementsControlRange && implementsDocSelection && ranges.length > 1) {
  2804. createControlSelection(this, ranges);
  2805. } else {
  2806. this.removeAllRanges();
  2807. for (var i = 0, len = ranges.length; i < len; ++i) {
  2808. this.addRange(ranges[i]);
  2809. }
  2810. }
  2811. };
  2812. } else if (isHostMethod(testSelection, "empty") && isHostMethod(testRange, "select") &&
  2813. implementsControlRange && useDocumentSelection) {
  2814. selProto.removeAllRanges = function() {
  2815. // Added try/catch as fix for issue #21
  2816. try {
  2817. this.docSelection.empty();
  2818. // Check for empty() not working (issue #24)
  2819. if (this.docSelection.type != "None") {
  2820. // Work around failure to empty a control selection by instead selecting a TextRange and then
  2821. // calling empty()
  2822. var doc;
  2823. if (this.anchorNode) {
  2824. doc = getDocument(this.anchorNode);
  2825. } else if (this.docSelection.type == CONTROL) {
  2826. var controlRange = this.docSelection.createRange();
  2827. if (controlRange.length) {
  2828. doc = getDocument( controlRange.item(0) );
  2829. }
  2830. }
  2831. if (doc) {
  2832. var textRange = getBody(doc).createTextRange();
  2833. textRange.select();
  2834. this.docSelection.empty();
  2835. }
  2836. }
  2837. } catch(ex) {}
  2838. updateEmptySelection(this);
  2839. };
  2840. selProto.addRange = function(range) {
  2841. if (this.docSelection.type == CONTROL) {
  2842. addRangeToControlSelection(this, range);
  2843. } else {
  2844. api.WrappedTextRange.rangeToTextRange(range).select();
  2845. this._ranges[0] = range;
  2846. this.rangeCount = 1;
  2847. this.isCollapsed = this._ranges[0].collapsed;
  2848. updateAnchorAndFocusFromRange(this, range, false);
  2849. }
  2850. };
  2851. selProto.setRanges = function(ranges) {
  2852. this.removeAllRanges();
  2853. var rangeCount = ranges.length;
  2854. if (rangeCount > 1) {
  2855. createControlSelection(this, ranges);
  2856. } else if (rangeCount) {
  2857. this.addRange(ranges[0]);
  2858. }
  2859. };
  2860. } else {
  2861. module.fail("No means of selecting a Range or TextRange was found");
  2862. return false;
  2863. }
  2864. selProto.getRangeAt = function(index) {
  2865. if (index < 0 || index >= this.rangeCount) {
  2866. throw new DOMException("INDEX_SIZE_ERR");
  2867. } else {
  2868. // Clone the range to preserve selection-range independence. See issue 80.
  2869. return this._ranges[index].cloneRange();
  2870. }
  2871. };
  2872. var refreshSelection;
  2873. if (useDocumentSelection) {
  2874. refreshSelection = function(sel) {
  2875. var range;
  2876. if (api.isSelectionValid(sel.win)) {
  2877. range = sel.docSelection.createRange();
  2878. } else {
  2879. range = getBody(sel.win.document).createTextRange();
  2880. range.collapse(true);
  2881. }
  2882. if (sel.docSelection.type == CONTROL) {
  2883. updateControlSelection(sel);
  2884. } else if (isTextRange(range)) {
  2885. updateFromTextRange(sel, range);
  2886. } else {
  2887. updateEmptySelection(sel);
  2888. }
  2889. };
  2890. } else if (isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == NUMBER) {
  2891. refreshSelection = function(sel) {
  2892. if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) {
  2893. updateControlSelection(sel);
  2894. } else {
  2895. sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount;
  2896. if (sel.rangeCount) {
  2897. for (var i = 0, len = sel.rangeCount; i < len; ++i) {
  2898. sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i));
  2899. }
  2900. updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackward(sel.nativeSelection));
  2901. sel.isCollapsed = selectionIsCollapsed(sel);
  2902. } else {
  2903. updateEmptySelection(sel);
  2904. }
  2905. }
  2906. };
  2907. } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && features.implementsDomRange) {
  2908. refreshSelection = function(sel) {
  2909. var range, nativeSel = sel.nativeSelection;
  2910. if (nativeSel.anchorNode) {
  2911. range = getSelectionRangeAt(nativeSel, 0);
  2912. sel._ranges = [range];
  2913. sel.rangeCount = 1;
  2914. updateAnchorAndFocusFromNativeSelection(sel);
  2915. sel.isCollapsed = selectionIsCollapsed(sel);
  2916. } else {
  2917. updateEmptySelection(sel);
  2918. }
  2919. };
  2920. } else {
  2921. module.fail("No means of obtaining a Range or TextRange from the user's selection was found");
  2922. return false;
  2923. }
  2924. selProto.refresh = function(checkForChanges) {
  2925. var oldRanges = checkForChanges ? this._ranges.slice(0) : null;
  2926. var oldAnchorNode = this.anchorNode, oldAnchorOffset = this.anchorOffset;
  2927. refreshSelection(this);
  2928. if (checkForChanges) {
  2929. // Check the range count first
  2930. var i = oldRanges.length;
  2931. if (i != this._ranges.length) {
  2932. return true;
  2933. }
  2934. // Now check the direction. Checking the anchor position is the same is enough since we're checking all the
  2935. // ranges after this
  2936. if (this.anchorNode != oldAnchorNode || this.anchorOffset != oldAnchorOffset) {
  2937. return true;
  2938. }
  2939. // Finally, compare each range in turn
  2940. while (i--) {
  2941. if (!rangesEqual(oldRanges[i], this._ranges[i])) {
  2942. return true;
  2943. }
  2944. }
  2945. return false;
  2946. }
  2947. };
  2948. // Removal of a single range
  2949. var removeRangeManually = function(sel, range) {
  2950. var ranges = sel.getAllRanges();
  2951. sel.removeAllRanges();
  2952. for (var i = 0, len = ranges.length; i < len; ++i) {
  2953. if (!rangesEqual(range, ranges[i])) {
  2954. sel.addRange(ranges[i]);
  2955. }
  2956. }
  2957. if (!sel.rangeCount) {
  2958. updateEmptySelection(sel);
  2959. }
  2960. };
  2961. if (implementsControlRange && implementsDocSelection) {
  2962. selProto.removeRange = function(range) {
  2963. if (this.docSelection.type == CONTROL) {
  2964. var controlRange = this.docSelection.createRange();
  2965. var rangeElement = getSingleElementFromRange(range);
  2966. // Create a new ControlRange containing all the elements in the selected ControlRange minus the
  2967. // element contained by the supplied range
  2968. var doc = getDocument(controlRange.item(0));
  2969. var newControlRange = getBody(doc).createControlRange();
  2970. var el, removed = false;
  2971. for (var i = 0, len = controlRange.length; i < len; ++i) {
  2972. el = controlRange.item(i);
  2973. if (el !== rangeElement || removed) {
  2974. newControlRange.add(controlRange.item(i));
  2975. } else {
  2976. removed = true;
  2977. }
  2978. }
  2979. newControlRange.select();
  2980. // Update the wrapped selection based on what's now in the native selection
  2981. updateControlSelection(this);
  2982. } else {
  2983. removeRangeManually(this, range);
  2984. }
  2985. };
  2986. } else {
  2987. selProto.removeRange = function(range) {
  2988. removeRangeManually(this, range);
  2989. };
  2990. }
  2991. // Detecting if a selection is backward
  2992. var selectionIsBackward;
  2993. if (!useDocumentSelection && selectionHasAnchorAndFocus && features.implementsDomRange) {
  2994. selectionIsBackward = winSelectionIsBackward;
  2995. selProto.isBackward = function() {
  2996. return selectionIsBackward(this);
  2997. };
  2998. } else {
  2999. selectionIsBackward = selProto.isBackward = function() {
  3000. return false;
  3001. };
  3002. }
  3003. // Create an alias for backwards compatibility. From 1.3, everything is "backward" rather than "backwards"
  3004. selProto.isBackwards = selProto.isBackward;
  3005. // Selection stringifier
  3006. // This is conformant to the old HTML5 selections draft spec but differs from WebKit and Mozilla's implementation.
  3007. // The current spec does not yet define this method.
  3008. selProto.toString = function() {
  3009. var rangeTexts = [];
  3010. for (var i = 0, len = this.rangeCount; i < len; ++i) {
  3011. rangeTexts[i] = "" + this._ranges[i];
  3012. }
  3013. return rangeTexts.join("");
  3014. };
  3015. function assertNodeInSameDocument(sel, node) {
  3016. if (sel.win.document != getDocument(node)) {
  3017. throw new DOMException("WRONG_DOCUMENT_ERR");
  3018. }
  3019. }
  3020. // No current browser conforms fully to the spec for this method, so Rangy's own method is always used
  3021. selProto.collapse = function(node, offset) {
  3022. assertNodeInSameDocument(this, node);
  3023. var range = api.createRange(node);
  3024. range.collapseToPoint(node, offset);
  3025. this.setSingleRange(range);
  3026. this.isCollapsed = true;
  3027. };
  3028. selProto.collapseToStart = function() {
  3029. if (this.rangeCount) {
  3030. var range = this._ranges[0];
  3031. this.collapse(range.startContainer, range.startOffset);
  3032. } else {
  3033. throw new DOMException("INVALID_STATE_ERR");
  3034. }
  3035. };
  3036. selProto.collapseToEnd = function() {
  3037. if (this.rangeCount) {
  3038. var range = this._ranges[this.rangeCount - 1];
  3039. this.collapse(range.endContainer, range.endOffset);
  3040. } else {
  3041. throw new DOMException("INVALID_STATE_ERR");
  3042. }
  3043. };
  3044. // The spec is very specific on how selectAllChildren should be implemented and not all browsers implement it as
  3045. // specified so the native implementation is never used by Rangy.
  3046. selProto.selectAllChildren = function(node) {
  3047. assertNodeInSameDocument(this, node);
  3048. var range = api.createRange(node);
  3049. range.selectNodeContents(node);
  3050. this.setSingleRange(range);
  3051. };
  3052. selProto.deleteFromDocument = function() {
  3053. // Sepcial behaviour required for IE's control selections
  3054. if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
  3055. var controlRange = this.docSelection.createRange();
  3056. var element;
  3057. while (controlRange.length) {
  3058. element = controlRange.item(0);
  3059. controlRange.remove(element);
  3060. dom.removeNode(element);
  3061. }
  3062. this.refresh();
  3063. } else if (this.rangeCount) {
  3064. var ranges = this.getAllRanges();
  3065. if (ranges.length) {
  3066. this.removeAllRanges();
  3067. for (var i = 0, len = ranges.length; i < len; ++i) {
  3068. ranges[i].deleteContents();
  3069. }
  3070. // The spec says nothing about what the selection should contain after calling deleteContents on each
  3071. // range. Firefox moves the selection to where the final selected range was, so we emulate that
  3072. this.addRange(ranges[len - 1]);
  3073. }
  3074. }
  3075. };
  3076. // The following are non-standard extensions
  3077. selProto.eachRange = function(func, returnValue) {
  3078. for (var i = 0, len = this._ranges.length; i < len; ++i) {
  3079. if ( func( this.getRangeAt(i) ) ) {
  3080. return returnValue;
  3081. }
  3082. }
  3083. };
  3084. selProto.getAllRanges = function() {
  3085. var ranges = [];
  3086. this.eachRange(function(range) {
  3087. ranges.push(range);
  3088. });
  3089. return ranges;
  3090. };
  3091. selProto.setSingleRange = function(range, direction) {
  3092. this.removeAllRanges();
  3093. this.addRange(range, direction);
  3094. };
  3095. selProto.callMethodOnEachRange = function(methodName, params) {
  3096. var results = [];
  3097. this.eachRange( function(range) {
  3098. results.push( range[methodName].apply(range, params || []) );
  3099. } );
  3100. return results;
  3101. };
  3102. function createStartOrEndSetter(isStart) {
  3103. return function(node, offset) {
  3104. var range;
  3105. if (this.rangeCount) {
  3106. range = this.getRangeAt(0);
  3107. range["set" + (isStart ? "Start" : "End")](node, offset);
  3108. } else {
  3109. range = api.createRange(this.win.document);
  3110. range.setStartAndEnd(node, offset);
  3111. }
  3112. this.setSingleRange(range, this.isBackward());
  3113. };
  3114. }
  3115. selProto.setStart = createStartOrEndSetter(true);
  3116. selProto.setEnd = createStartOrEndSetter(false);
  3117. // Add select() method to Range prototype. Any existing selection will be removed.
  3118. api.rangePrototype.select = function(direction) {
  3119. getSelection( this.getDocument() ).setSingleRange(this, direction);
  3120. };
  3121. selProto.changeEachRange = function(func) {
  3122. var ranges = [];
  3123. var backward = this.isBackward();
  3124. this.eachRange(function(range) {
  3125. func(range);
  3126. ranges.push(range);
  3127. });
  3128. this.removeAllRanges();
  3129. if (backward && ranges.length == 1) {
  3130. this.addRange(ranges[0], "backward");
  3131. } else {
  3132. this.setRanges(ranges);
  3133. }
  3134. };
  3135. selProto.containsNode = function(node, allowPartial) {
  3136. return this.eachRange( function(range) {
  3137. return range.containsNode(node, allowPartial);
  3138. }, true ) || false;
  3139. };
  3140. selProto.getBookmark = function(containerNode) {
  3141. return {
  3142. backward: this.isBackward(),
  3143. rangeBookmarks: this.callMethodOnEachRange("getBookmark", [containerNode])
  3144. };
  3145. };
  3146. selProto.moveToBookmark = function(bookmark) {
  3147. var selRanges = [];
  3148. for (var i = 0, rangeBookmark, range; rangeBookmark = bookmark.rangeBookmarks[i++]; ) {
  3149. range = api.createRange(this.win);
  3150. range.moveToBookmark(rangeBookmark);
  3151. selRanges.push(range);
  3152. }
  3153. if (bookmark.backward) {
  3154. this.setSingleRange(selRanges[0], "backward");
  3155. } else {
  3156. this.setRanges(selRanges);
  3157. }
  3158. };
  3159. selProto.saveRanges = function() {
  3160. return {
  3161. backward: this.isBackward(),
  3162. ranges: this.callMethodOnEachRange("cloneRange")
  3163. };
  3164. };
  3165. selProto.restoreRanges = function(selRanges) {
  3166. this.removeAllRanges();
  3167. for (var i = 0, range; range = selRanges.ranges[i]; ++i) {
  3168. this.addRange(range, (selRanges.backward && i == 0));
  3169. }
  3170. };
  3171. selProto.toHtml = function() {
  3172. var rangeHtmls = [];
  3173. this.eachRange(function(range) {
  3174. rangeHtmls.push( DomRange.toHtml(range) );
  3175. });
  3176. return rangeHtmls.join("");
  3177. };
  3178. if (features.implementsTextRange) {
  3179. selProto.getNativeTextRange = function() {
  3180. var sel, textRange;
  3181. if ( (sel = this.docSelection) ) {
  3182. var range = sel.createRange();
  3183. if (isTextRange(range)) {
  3184. return range;
  3185. } else {
  3186. throw module.createError("getNativeTextRange: selection is a control selection");
  3187. }
  3188. } else if (this.rangeCount > 0) {
  3189. return api.WrappedTextRange.rangeToTextRange( this.getRangeAt(0) );
  3190. } else {
  3191. throw module.createError("getNativeTextRange: selection contains no range");
  3192. }
  3193. };
  3194. }
  3195. function inspect(sel) {
  3196. var rangeInspects = [];
  3197. var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset);
  3198. var focus = new DomPosition(sel.focusNode, sel.focusOffset);
  3199. var name = (typeof sel.getName == "function") ? sel.getName() : "Selection";
  3200. if (typeof sel.rangeCount != "undefined") {
  3201. for (var i = 0, len = sel.rangeCount; i < len; ++i) {
  3202. rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i));
  3203. }
  3204. }
  3205. return "[" + name + "(Ranges: " + rangeInspects.join(", ") +
  3206. ")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]";
  3207. }
  3208. selProto.getName = function() {
  3209. return "WrappedSelection";
  3210. };
  3211. selProto.inspect = function() {
  3212. return inspect(this);
  3213. };
  3214. selProto.detach = function() {
  3215. actOnCachedSelection(this.win, "delete");
  3216. deleteProperties(this);
  3217. };
  3218. WrappedSelection.detachAll = function() {
  3219. actOnCachedSelection(null, "deleteAll");
  3220. };
  3221. WrappedSelection.inspect = inspect;
  3222. WrappedSelection.isDirectionBackward = isDirectionBackward;
  3223. api.Selection = WrappedSelection;
  3224. api.selectionPrototype = selProto;
  3225. api.addShimListener(function(win) {
  3226. if (typeof win.getSelection == "undefined") {
  3227. win.getSelection = function() {
  3228. return getSelection(win);
  3229. };
  3230. }
  3231. win = null;
  3232. });
  3233. });
  3234. /*----------------------------------------------------------------------------------------------------------------*/
  3235. // Wait for document to load before initializing
  3236. var docReady = false;
  3237. var loadHandler = function(e) {
  3238. if (!docReady) {
  3239. docReady = true;
  3240. if (!api.initialized && api.config.autoInitialize) {
  3241. init();
  3242. }
  3243. }
  3244. };
  3245. if (isBrowser) {
  3246. // Test whether the document has already been loaded and initialize immediately if so
  3247. if (document.readyState == "complete") {
  3248. loadHandler();
  3249. } else {
  3250. if (isHostMethod(document, "addEventListener")) {
  3251. document.addEventListener("DOMContentLoaded", loadHandler, false);
  3252. }
  3253. // Add a fallback in case the DOMContentLoaded event isn't supported
  3254. addListener(window, "load", loadHandler);
  3255. }
  3256. }
  3257. return api;
  3258. }, this);