From 7b29a0d319bd81e0917e76964d2dc3252d57d2fd Mon Sep 17 00:00:00 2001 From: Youri van den Bogert Date: Tue, 3 Feb 2026 14:47:51 +0100 Subject: [PATCH] Notify users that there are comments on the page --- ReleaseNotes.wiki | 4 ++ extension.json | 5 +- i18n/en.json | 3 +- i18n/nl.json | 3 +- resources/frontend/dist/smartcomments.min.js | 6 +-- .../frontend/dist/smartcomments.min.js.map | 2 +- resources/frontend/src/App.js | 6 +-- resources/frontend/src/store/appStateStore.js | 51 +++++++++++++++++++ 8 files changed, 67 insertions(+), 13 deletions(-) diff --git a/ReleaseNotes.wiki b/ReleaseNotes.wiki index d06ee49..8cf3507 100644 --- a/ReleaseNotes.wiki +++ b/ReleaseNotes.wiki @@ -1,5 +1,9 @@ +; Version 2.1.8 (Feb 3, 2026) +* Added 'X no. of comments on page' while viewing a page + ; Version 2.1.7, Version 2.1.6 (Dec 19, 2025) * Change logic to how an image gets uploaded + ; Version 2.1.5 (Nov 24, 2025) * Changed dutch i18n strings * Fixed where if an error occured the i18n key instead of msg gets shown diff --git a/extension.json b/extension.json index 51d002b..4740f2d 100644 --- a/extension.json +++ b/extension.json @@ -6,7 +6,7 @@ "Robin van der Wiel", "Yvar Nanlohij" ], - "version": "2.1.7", + "version": "2.1.8", "url": "https://www.archixl.nl", "descriptionmsg": "sc-desc", "license-name": "GPL-2.0+", @@ -130,7 +130,8 @@ "sc-selection-generic-error", "sc-show-screenshot-full-size", "sc-broken-comments-below", - "sc-enabled-smartcomments" + "sc-enabled-smartcomments", + "sc-popup-msg" ] } }, diff --git a/i18n/en.json b/i18n/en.json index 37f59b0..78e299b 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -67,8 +67,7 @@ "sc-property-revision": "Revision", "sc-property-position": "Position on page", "sc-popup-title": "Replies", - "sc-popup-msg-single": "We found #X# comment in the current revision of this page. You can view it by enabling the comment mode.", - "sc-popup-msg-multiple": "We found #X# comments in the current revision of this page. You can view them by enabling the comment mode.", + "sc-popup-msg": "We found $1 {{PLURAL:$1|comment|comments}} in the current revision of this page. You can view {{PLURAL:$1|it|them}} by enabling the comment mode.", "sc-popup-enabled-highlighting-title": "Comments", "sc-popup-enabled-highlighting-msg": "Make a text selection to create a comment", "sc-popup-unlocalized-comments-title": "Whoops!", diff --git a/i18n/nl.json b/i18n/nl.json index ba1fc59..3f96a44 100644 --- a/i18n/nl.json +++ b/i18n/nl.json @@ -67,8 +67,7 @@ "sc-property-revision": "Revisie", "sc-property-position": "Positie op pagina", "sc-popup-title": "Reacties", - "sc-popup-msg-single": "Er is #X# opmerking gevonden in de huidige revisie van deze pagina. Je kunt deze zien door de opmerkingenmodus in te schakelen.", - "sc-popup-msg-multiple": "Er zijn #X# opmerkingen gevonden in de huidige revisie van deze pagina. Je kunt ze zien door de opmerkingenmodus in te schakelen.", + "sc-popup-msg": "Er {{PLURAL:$1|is|zijn}} $1 {{PLURAL:$1|opmerking|opmerkingen}} gevonden in de huidige revisie van deze pagina. Je kunt {{PLURAL:$1|deze|ze}} zien door de opmerkingenmodus in te schakelen.", "sc-popup-enabled-highlighting-title": "Opmerkingen", "sc-popup-enabled-highlighting-msg": "Selecteer een stukje tekst om er een opmerking over te plaatsen", "sc-popup-unlocalized-comments-title": "Whoops!", diff --git a/resources/frontend/dist/smartcomments.min.js b/resources/frontend/dist/smartcomments.min.js index 7b782a9..cc80442 100644 --- a/resources/frontend/dist/smartcomments.min.js +++ b/resources/frontend/dist/smartcomments.min.js @@ -8,8 +8,8 @@ var __defProp=Object.defineProperty,__defNormalProp=(A,e,t)=>e in A?__defProp(A, /*! #__NO_SIDE_EFFECTS__ */function e(A){const e=Object.create(null);for(const t of A.split(","))e[t]=1;return A=>A in e}const t="production"!==A.NODE_ENV?Object.freeze({}):{},n="production"!==A.NODE_ENV?Object.freeze([]):[],r=()=>{},o=()=>!1,i=A=>111===A.charCodeAt(0)&&110===A.charCodeAt(1)&&(A.charCodeAt(2)>122||A.charCodeAt(2)<97),s=A=>A.startsWith("onUpdate:"),a=Object.assign,c=(A,e)=>{const t=A.indexOf(e);t>-1&&A.splice(t,1)},l=Object.prototype.hasOwnProperty,u=(A,e)=>l.call(A,e),d=Array.isArray,g=A=>"[object Map]"===Q(A),h=A=>"[object Set]"===Q(A),p=A=>"function"==typeof A,B=A=>"string"==typeof A,f=A=>"symbol"==typeof A,m=A=>null!==A&&"object"==typeof A,w=A=>(m(A)||p(A))&&p(A.then)&&p(A.catch),C=Object.prototype.toString,Q=A=>C.call(A),y=A=>Q(A).slice(8,-1),E=A=>"[object Object]"===Q(A),v=A=>B(A)&&"NaN"!==A&&"-"!==A[0]&&""+parseInt(A,10)===A,U=e(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),F=e("bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo"),b=A=>{const e=Object.create(null);return t=>e[t]||(e[t]=A(t))},H=/-(\w)/g,I=b((A=>A.replace(H,((A,e)=>e?e.toUpperCase():"")))),S=/\B([A-Z])/g,N=b((A=>A.replace(S,"-$1").toLowerCase())),x=b((A=>A.charAt(0).toUpperCase()+A.slice(1))),D=b((A=>A?`on${x(A)}`:"")),O=(A,e)=>!Object.is(A,e),T=(A,...e)=>{for(let t=0;t{Object.defineProperty(A,e,{configurable:!0,enumerable:!1,writable:n,value:t})},_=A=>{const e=parseFloat(A);return isNaN(e)?A:e};let R;const K=()=>R||(R="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{});function k(A){if(d(A)){const e={};for(let t=0;t{if(A){const t=A.split(V);t.length>1&&(e[t[0].trim()]=t[1].trim())}})),e}function W(A){let e="";if(B(A))e=A;else if(d(A))for(let t=0;t!(!A||!0!==A.__v_isRef),q=A=>B(A)?A:null==A?"":d(A)||m(A)&&(A.toString===C||!p(A.toString))?z(A)?q(A.value):JSON.stringify(A,AA,2):String(A),AA=(A,e)=>z(e)?AA(A,e.value):g(e)?{[`Map(${e.size})`]:[...e.entries()].reduce(((A,[e,t],n)=>(A[eA(e,n)+" =>"]=t,A)),{})}:h(e)?{[`Set(${e.size})`]:[...e.values()].map((A=>eA(A)))}:f(e)?eA(e):!m(e)||d(e)||E(e)?e:String(e),eA=(A,e="")=>{var t;return f(A)?`Symbol(${null!=(t=A.description)?t:e})`:A};var tA={};function nA(A,...e){console.warn(`[Vue warn] ${A}`,...e)}let rA,oA;class iA{constructor(A=!1){this.detached=A,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=rA,!A&&rA&&(this.index=(rA.scopes||(rA.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){let A,e;if(this._isPaused=!0,this.scopes)for(A=0,e=this.scopes.length;A0&&0===--this._on&&(rA=this.prevScope,this.prevScope=void 0)}stop(A){if(this._active){let e,t;for(this._active=!1,e=0,t=this.effects.length;e0)return;if(dA){let A=dA;for(dA=void 0;A;){const e=A.next;A.next=void 0,A.flags&=-9,A=e}}let A;for(;uA;){let t=uA;for(uA=void 0;t;){const n=t.next;if(t.next=void 0,t.flags&=-9,1&t.flags)try{t.trigger()}catch(e){A||(A=e)}t=n}}if(A)throw A}function fA(A){for(let e=A.deps;e;e=e.nextDep)e.version=-1,e.prevActiveLink=e.dep.activeLink,e.dep.activeLink=e}function mA(A){let e,t=A.depsTail,n=t;for(;n;){const A=n.prevDep;-1===n.version?(n===t&&(t=A),QA(n),yA(n)):e=n,n.dep.activeLink=n.prevActiveLink,n.prevActiveLink=void 0,n=A}A.deps=e,A.depsTail=t}function wA(A){for(let e=A.deps;e;e=e.nextDep)if(e.dep.version!==e.version||e.dep.computed&&(CA(e.dep.computed)||e.dep.version!==e.version))return!0;return!!A._dirty}function CA(A){if(4&A.flags&&!(16&A.flags))return;if(A.flags&=-17,A.globalVersion===HA)return;if(A.globalVersion=HA,!A.isSSR&&128&A.flags&&(!A.deps&&!A._dirty||!wA(A)))return;A.flags|=2;const e=A.dep,t=oA,n=EA;oA=A,EA=!0;try{fA(A);const t=A.fn(A._value);(0===e.version||O(t,A._value))&&(A.flags|=128,A._value=t,e.version++)}catch(r){throw e.version++,r}finally{oA=t,EA=n,mA(A),A.flags&=-3}}function QA(A,e=!1){const{dep:t,prevSub:n,nextSub:r}=A;if(n&&(n.nextSub=r,A.prevSub=void 0),r&&(r.prevSub=n,A.nextSub=void 0),"production"!==tA.NODE_ENV&&t.subsHead===A&&(t.subsHead=r),t.subs===A&&(t.subs=n,!n&&t.computed)){t.computed.flags&=-5;for(let A=t.computed.deps;A;A=A.nextDep)QA(A,!0)}e||--t.sc||!t.map||t.map.delete(t.key)}function yA(A){const{prevDep:e,nextDep:t}=A;e&&(e.nextDep=t,A.prevDep=void 0),t&&(t.prevDep=e,A.nextDep=void 0)}let EA=!0;const vA=[];function UA(){vA.push(EA),EA=!1}function FA(){const A=vA.pop();EA=void 0===A||A}function bA(A){const{cleanup:e}=A;if(A.cleanup=void 0,e){const A=oA;oA=void 0;try{e()}finally{oA=A}}}let HA=0;class IA{constructor(A,e){this.sub=A,this.dep=e,this.version=e.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class SA{constructor(A){this.computed=A,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,"production"!==tA.NODE_ENV&&(this.subsHead=void 0)}track(A){if(!oA||!EA||oA===this.computed)return;let e=this.activeLink;if(void 0===e||e.sub!==oA)e=this.activeLink=new IA(oA,this),oA.deps?(e.prevDep=oA.depsTail,oA.depsTail.nextDep=e,oA.depsTail=e):oA.deps=oA.depsTail=e,NA(e);else if(-1===e.version&&(e.version=this.version,e.nextDep)){const A=e.nextDep;A.prevDep=e.prevDep,e.prevDep&&(e.prevDep.nextDep=A),e.prevDep=oA.depsTail,e.nextDep=void 0,oA.depsTail.nextDep=e,oA.depsTail=e,oA.deps===e&&(oA.deps=A)}return"production"!==tA.NODE_ENV&&oA.onTrack&&oA.onTrack(a({effect:oA},A)),e}trigger(A){this.version++,HA++,this.notify(A)}notify(A){pA();try{if("production"!==tA.NODE_ENV)for(let e=this.subsHead;e;e=e.nextSub)!e.sub.onTrigger||8&e.sub.flags||e.sub.onTrigger(a({effect:e.sub},A));for(let A=this.subs;A;A=A.prevSub)A.sub.notify()&&A.sub.dep.notify()}finally{BA()}}}function NA(A){if(A.dep.sc++,4&A.sub.flags){const e=A.dep.computed;if(e&&!A.dep.subs){e.flags|=20;for(let A=e.deps;A;A=A.nextDep)NA(A)}const t=A.dep.subs;t!==A&&(A.prevSub=t,t&&(t.nextSub=A)),"production"!==tA.NODE_ENV&&void 0===A.dep.subsHead&&(A.dep.subsHead=A),A.dep.subs=A}}const xA=new WeakMap,DA=Symbol("production"!==tA.NODE_ENV?"Object iterate":""),OA=Symbol("production"!==tA.NODE_ENV?"Map keys iterate":""),TA=Symbol("production"!==tA.NODE_ENV?"Array iterate":"");function LA(A,e,t){if(EA&&oA){let n=xA.get(A);n||xA.set(A,n=new Map);let r=n.get(t);r||(n.set(t,r=new SA),r.map=n,r.key=t),"production"!==tA.NODE_ENV?r.track({target:A,type:e,key:t}):r.track()}}function _A(A,e,t,n,r,o){const i=xA.get(A);if(!i)return void HA++;const s=i=>{i&&("production"!==tA.NODE_ENV?i.trigger({target:A,type:e,key:t,newValue:n,oldValue:r,oldTarget:o}):i.trigger())};if(pA(),"clear"===e)i.forEach(s);else{const r=d(A),o=r&&v(t);if(r&&"length"===t){const A=Number(n);i.forEach(((e,t)=>{("length"===t||t===TA||!f(t)&&t>=A)&&s(e)}))}else switch((void 0!==t||i.has(void 0))&&s(i.get(t)),o&&s(i.get(TA)),e){case"add":r?o&&s(i.get("length")):(s(i.get(DA)),g(A)&&s(i.get(OA)));break;case"delete":r||(s(i.get(DA)),g(A)&&s(i.get(OA)));break;case"set":g(A)&&s(i.get(DA))}}BA()}function RA(A){const e=Ue(A);return e===A?e:(LA(e,"iterate",TA),Ee(A)?e:e.map(be))}function KA(A){return LA(A=Ue(A),"iterate",TA),A}const kA={__proto__:null,[Symbol.iterator](){return MA(this,Symbol.iterator,be)},concat(...A){return RA(this).concat(...A.map((A=>d(A)?RA(A):A)))},entries(){return MA(this,"entries",(A=>(A[1]=be(A[1]),A)))},every(A,e){return PA(this,"every",A,e,void 0,arguments)},filter(A,e){return PA(this,"filter",A,e,(A=>A.map(be)),arguments)},find(A,e){return PA(this,"find",A,e,be,arguments)},findIndex(A,e){return PA(this,"findIndex",A,e,void 0,arguments)},findLast(A,e){return PA(this,"findLast",A,e,be,arguments)},findLastIndex(A,e){return PA(this,"findLastIndex",A,e,void 0,arguments)},forEach(A,e){return PA(this,"forEach",A,e,void 0,arguments)},includes(...A){return WA(this,"includes",A)},indexOf(...A){return WA(this,"indexOf",A)},join(A){return RA(this).join(A)},lastIndexOf(...A){return WA(this,"lastIndexOf",A)},map(A,e){return PA(this,"map",A,e,void 0,arguments)},pop(){return XA(this,"pop")},push(...A){return XA(this,"push",A)},reduce(A,...e){return GA(this,"reduce",A,e)},reduceRight(A,...e){return GA(this,"reduceRight",A,e)},shift(){return XA(this,"shift")},some(A,e){return PA(this,"some",A,e,void 0,arguments)},splice(...A){return XA(this,"splice",A)},toReversed(){return RA(this).toReversed()},toSorted(A){return RA(this).toSorted(A)},toSpliced(...A){return RA(this).toSpliced(...A)},unshift(...A){return XA(this,"unshift",A)},values(){return MA(this,"values",be)}};function MA(A,e,t){const n=KA(A),r=n[e]();return n===A||Ee(A)||(r._next=r.next,r.next=()=>{const A=r._next();return A.value&&(A.value=t(A.value)),A}),r}const VA=Array.prototype;function PA(A,e,t,n,r,o){const i=KA(A),s=i!==A&&!Ee(A),a=i[e];if(a!==VA[e]){const e=a.apply(A,o);return s?be(e):e}let c=t;i!==A&&(s?c=function(e,n){return t.call(this,be(e),n,A)}:t.length>2&&(c=function(e,n){return t.call(this,e,n,A)}));const l=a.call(i,c,n);return s&&r?r(l):l}function GA(A,e,t,n){const r=KA(A);let o=t;return r!==A&&(Ee(A)?t.length>3&&(o=function(e,n,r){return t.call(this,e,n,r,A)}):o=function(e,n,r){return t.call(this,e,be(n),r,A)}),r[e](o,...n)}function WA(A,e,t){const n=Ue(A);LA(n,"iterate",TA);const r=n[e](...t);return-1!==r&&!1!==r||!ve(t[0])?r:(t[0]=Ue(t[0]),n[e](...t))}function XA(A,e,t=[]){UA(),pA();const n=Ue(A)[e].apply(A,t);return BA(),FA(),n}const JA=e("__proto__,__v_isRef,__isVue"),$A=new Set(Object.getOwnPropertyNames(Symbol).filter((A=>"arguments"!==A&&"caller"!==A)).map((A=>Symbol[A])).filter(f));function YA(A){f(A)||(A=String(A));const e=Ue(this);return LA(e,"has",A),e.hasOwnProperty(A)}class jA{constructor(A=!1,e=!1){this._isReadonly=A,this._isShallow=e}get(A,e,t){if("__v_skip"===e)return A.__v_skip;const n=this._isReadonly,r=this._isShallow;if("__v_isReactive"===e)return!n;if("__v_isReadonly"===e)return n;if("__v_isShallow"===e)return r;if("__v_raw"===e)return t===(n?r?Be:pe:r?he:ge).get(A)||Object.getPrototypeOf(A)===Object.getPrototypeOf(t)?A:void 0;const o=d(A);if(!n){let A;if(o&&(A=kA[e]))return A;if("hasOwnProperty"===e)return YA}const i=Reflect.get(A,e,Ie(A)?A:t);return(f(e)?$A.has(e):JA(e))?i:(n||LA(A,"get",e),r?i:Ie(i)?o&&v(e)?i:i.value:m(i)?n?me(i):fe(i):i)}}class ZA extends jA{constructor(A=!1){super(!1,A)}set(A,e,t,n){let r=A[e];if(!this._isShallow){const e=ye(r);if(Ee(t)||ye(t)||(r=Ue(r),t=Ue(t)),!d(A)&&Ie(r)&&!Ie(t))return!e&&(r.value=t,!0)}const o=d(A)&&v(e)?Number(e)A,re=A=>Reflect.getPrototypeOf(A);function oe(A){return function(...e){if("production"!==tA.NODE_ENV){const t=e[0]?`on key "${e[0]}" `:"";nA(`${x(A)} operation ${t}failed: target is readonly.`,Ue(this))}return"delete"!==A&&("clear"===A?void 0:this)}}function ie(A,e){const t={get(t){const n=this.__v_raw,r=Ue(n),o=Ue(t);A||(O(t,o)&&LA(r,"get",t),LA(r,"get",o));const{has:i}=re(r),s=e?ne:A?He:be;return i.call(r,t)?s(n.get(t)):i.call(r,o)?s(n.get(o)):void(n!==r&&n.get(t))},get size(){const e=this.__v_raw;return!A&&LA(Ue(e),"iterate",DA),Reflect.get(e,"size",e)},has(e){const t=this.__v_raw,n=Ue(t),r=Ue(e);return A||(O(e,r)&&LA(n,"has",e),LA(n,"has",r)),e===r?t.has(e):t.has(e)||t.has(r)},forEach(t,n){const r=this,o=r.__v_raw,i=Ue(o),s=e?ne:A?He:be;return!A&&LA(i,"iterate",DA),o.forEach(((A,e)=>t.call(n,s(A),s(e),r)))}};a(t,A?{add:oe("add"),set:oe("set"),delete:oe("delete"),clear:oe("clear")}:{add(A){e||Ee(A)||ye(A)||(A=Ue(A));const t=Ue(this);return re(t).has.call(t,A)||(t.add(A),_A(t,"add",A,A)),this},set(A,t){e||Ee(t)||ye(t)||(t=Ue(t));const n=Ue(this),{has:r,get:o}=re(n);let i=r.call(n,A);i?"production"!==tA.NODE_ENV&&de(n,r,A):(A=Ue(A),i=r.call(n,A));const s=o.call(n,A);return n.set(A,t),i?O(t,s)&&_A(n,"set",A,t,s):_A(n,"add",A,t),this},delete(A){const e=Ue(this),{has:t,get:n}=re(e);let r=t.call(e,A);r?"production"!==tA.NODE_ENV&&de(e,t,A):(A=Ue(A),r=t.call(e,A));const o=n?n.call(e,A):void 0,i=e.delete(A);return r&&_A(e,"delete",A,void 0,o),i},clear(){const A=Ue(this),e=0!==A.size,t="production"!==tA.NODE_ENV?g(A)?new Map(A):new Set(A):void 0,n=A.clear();return e&&_A(A,"clear",void 0,void 0,t),n}});return["keys","values","entries",Symbol.iterator].forEach((n=>{t[n]=function(A,e,t){return function(...n){const r=this.__v_raw,o=Ue(r),i=g(o),s="entries"===A||A===Symbol.iterator&&i,a="keys"===A&&i,c=r[A](...n),l=t?ne:e?He:be;return!e&&LA(o,"iterate",a?OA:DA),{next(){const{value:A,done:e}=c.next();return e?{value:A,done:e}:{value:s?[l(A[0]),l(A[1])]:l(A),done:e}},[Symbol.iterator](){return this}}}}(n,A,e)})),t}function se(A,e){const t=ie(A,e);return(e,n,r)=>"__v_isReactive"===n?!A:"__v_isReadonly"===n?A:"__v_raw"===n?e:Reflect.get(u(t,n)&&n in e?t:e,n,r)}const ae={get:se(!1,!1)},ce={get:se(!1,!0)},le={get:se(!0,!1)},ue={get:se(!0,!0)};function de(A,e,t){const n=Ue(t);if(n!==t&&e.call(A,n)){const e=y(A);nA(`Reactive ${e} contains both the raw and reactive versions of the same object${"Map"===e?" as keys":""}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`)}}const ge=new WeakMap,he=new WeakMap,pe=new WeakMap,Be=new WeakMap;function fe(A){return ye(A)?A:Ce(A,!1,qA,ae,ge)}function me(A){return Ce(A,!0,Ae,le,pe)}function we(A){return Ce(A,!0,te,ue,Be)}function Ce(A,e,t,n,r){if(!m(A))return"production"!==tA.NODE_ENV&&nA(`value cannot be made ${e?"readonly":"reactive"}: ${String(A)}`),A;if(A.__v_raw&&(!e||!A.__v_isReactive))return A;const o=(i=A).__v_skip||!Object.isExtensible(i)?0:function(A){switch(A){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}(y(i));var i;if(0===o)return A;const s=r.get(A);if(s)return s;const a=new Proxy(A,2===o?n:t);return r.set(A,a),a}function Qe(A){return ye(A)?Qe(A.__v_raw):!(!A||!A.__v_isReactive)}function ye(A){return!(!A||!A.__v_isReadonly)}function Ee(A){return!(!A||!A.__v_isShallow)}function ve(A){return!!A&&!!A.__v_raw}function Ue(A){const e=A&&A.__v_raw;return e?Ue(e):A}function Fe(A){return!u(A,"__v_skip")&&Object.isExtensible(A)&&L(A,"__v_skip",!0),A}const be=A=>m(A)?fe(A):A,He=A=>m(A)?me(A):A;function Ie(A){return!!A&&!0===A.__v_isRef}function Se(A){return function(A,e){if(Ie(A))return A;return new Ne(A,e)}(A,!1)}class Ne{constructor(A,e){this.dep=new SA,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=e?A:Ue(A),this._value=e?A:be(A),this.__v_isShallow=e}get value(){return"production"!==tA.NODE_ENV?this.dep.track({target:this,type:"get",key:"value"}):this.dep.track(),this._value}set value(A){const e=this._rawValue,t=this.__v_isShallow||Ee(A)||ye(A);A=t?A:Ue(A),O(A,e)&&(this._rawValue=A,this._value=t?A:be(A),"production"!==tA.NODE_ENV?this.dep.trigger({target:this,type:"set",key:"value",newValue:A,oldValue:e}):this.dep.trigger())}}function xe(A){return Ie(A)?A.value:A}const De={get:(A,e,t)=>"__v_raw"===e?A:xe(Reflect.get(A,e,t)),set:(A,e,t,n)=>{const r=A[e];return Ie(r)&&!Ie(t)?(r.value=t,!0):Reflect.set(A,e,t,n)}};function Oe(A){return Qe(A)?A:new Proxy(A,De)}function Te(A){"production"===tA.NODE_ENV||ve(A)||nA("toRefs() expects a reactive object but received a plain one.");const e=d(A)?new Array(A.length):{};for(const t in A)e[t]=Ke(A,t);return e}class Le{constructor(A,e,t){this._object=A,this._key=e,this._defaultValue=t,this.__v_isRef=!0,this._value=void 0}get value(){const A=this._object[this._key];return this._value=void 0===A?this._defaultValue:A}set value(A){this._object[this._key]=A}get dep(){return function(A,e){const t=xA.get(A);return t&&t.get(e)}(Ue(this._object),this._key)}}class _e{constructor(A){this._getter=A,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}}function Re(A,e,t){return Ie(A)?A:p(A)?new _e(A):m(A)&&arguments.length>1?Ke(A,e,t):Se(A)}function Ke(A,e,t){const n=A[e];return Ie(n)?n:new Le(A,e,t)}class ke{constructor(A,e,t){this.fn=A,this.setter=e,this._value=void 0,this.dep=new SA(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=HA-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!e,this.isSSR=t}notify(){if(this.flags|=16,!(8&this.flags)&&oA!==this)return hA(this,!0),!0}get value(){const A="production"!==tA.NODE_ENV?this.dep.track({target:this,type:"get",key:"value"}):this.dep.track();return CA(this),A&&(A.version=this.dep.version),this._value}set value(A){this.setter?this.setter(A):"production"!==tA.NODE_ENV&&nA("Write operation failed: computed value is readonly")}}const Me={},Ve=new WeakMap;let Pe;function Ge(A,e,n=t){const{immediate:o,deep:i,once:s,scheduler:a,augmentJob:l,call:u}=n,g=A=>{(n.onWarn||nA)("Invalid watch source: ",A,"A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.")},h=A=>i?A:Ee(A)||!1===i||0===i?We(A,1):We(A);let B,f,m,w,C=!1,Q=!1;if(Ie(A)?(f=()=>A.value,C=Ee(A)):Qe(A)?(f=()=>h(A),C=!0):d(A)?(Q=!0,C=A.some((A=>Qe(A)||Ee(A))),f=()=>A.map((A=>Ie(A)?A.value:Qe(A)?h(A):p(A)?u?u(A,2):A():void("production"!==tA.NODE_ENV&&g(A))))):p(A)?f=e?u?()=>u(A,2):A:()=>{if(m){UA();try{m()}finally{FA()}}const e=Pe;Pe=B;try{return u?u(A,3,[w]):A(w)}finally{Pe=e}}:(f=r,"production"!==tA.NODE_ENV&&g(A)),e&&i){const A=f,e=!0===i?1/0:i;f=()=>We(A(),e)}const y=aA(),E=()=>{B.stop(),y&&y.active&&c(y.effects,B)};if(s&&e){const A=e;e=(...e)=>{A(...e),E()}}let v=Q?new Array(A.length).fill(Me):Me;const U=A=>{if(1&B.flags&&(B.dirty||A))if(e){const A=B.run();if(i||C||(Q?A.some(((A,e)=>O(A,v[e]))):O(A,v))){m&&m();const t=Pe;Pe=B;try{const t=[A,v===Me?void 0:Q&&v[0]===Me?[]:v,w];v=A,u?u(e,3,t):e(...t)}finally{Pe=t}}}else B.run()};return l&&l(U),B=new lA(f),B.scheduler=a?()=>a(U,!1):U,w=A=>function(A,e=!1,t=Pe){if(t){let e=Ve.get(t);e||Ve.set(t,e=[]),e.push(A)}else"production"===tA.NODE_ENV||e||nA("onWatcherCleanup() was called when there was no active watcher to associate with.")}(A,!1,B),m=B.onStop=()=>{const A=Ve.get(B);if(A){if(u)u(A,4);else for(const e of A)e();Ve.delete(B)}},"production"!==tA.NODE_ENV&&(B.onTrack=n.onTrack,B.onTrigger=n.onTrigger),e?o?U(!0):v=B.run():a?a(U.bind(null,!0),!0):B.run(),E.pause=B.pause.bind(B),E.resume=B.resume.bind(B),E.stop=E,E}function We(A,e=1/0,t){if(e<=0||!m(A)||A.__v_skip)return A;if((t=t||new Set).has(A))return A;if(t.add(A),e--,Ie(A))We(A.value,e,t);else if(d(A))for(let n=0;n{We(A,e,t)}));else if(E(A)){for(const n in A)We(A[n],e,t);for(const n of Object.getOwnPropertySymbols(A))Object.prototype.propertyIsEnumerable.call(A,n)&&We(A[n],e,t)}return A}var Xe={};const Je=[];function $e(A){Je.push(A)}function Ye(){Je.pop()}let je=!1;function Ze(A,...e){if(je)return;je=!0,UA();const t=Je.length?Je[Je.length-1].component:null,n=t&&t.appContext.config.warnHandler,r=function(){let A=Je[Je.length-1];if(!A)return[];const e=[];for(;A;){const t=e[0];t&&t.vnode===A?t.recurseCount++:e.push({vnode:A,recurseCount:0});const n=A.component&&A.component.parent;A=n&&n.vnode}return e}();if(n)et(n,t,11,[A+e.map((A=>{var e,t;return null!=(t=null==(e=A.toString)?void 0:e.call(A))?t:JSON.stringify(A)})).join(""),t&&t.proxy,r.map((({vnode:A})=>`at <${Lo(t,A.type)}>`)).join("\n"),r]);else{const t=[`[Vue warn]: ${A}`,...e];r.length&&t.push("\n",...function(A){const e=[];return A.forEach(((A,t)=>{e.push(...0===t?[]:["\n"],...function({vnode:A,recurseCount:e}){const t=e>0?`... (${e} recursive calls)`:"",n=!!A.component&&null==A.component.parent,r=` at <${Lo(A.component,A.type,n)}`,o=">"+t;return A.props?[r,...ze(A.props),o]:[r+o]}(A))})),e}(r)),console.warn(...t)}FA(),je=!1}function ze(A){const e=[],t=Object.keys(A);return t.slice(0,3).forEach((t=>{e.push(...qe(t,A[t]))})),t.length>3&&e.push(" ..."),e}function qe(A,e,t){return B(e)?(e=JSON.stringify(e),t?e:[`${A}=${e}`]):"number"==typeof e||"boolean"==typeof e||null==e?t?e:[`${A}=${e}`]:Ie(e)?(e=qe(A,Ue(e.value),!0),t?e:[`${A}=Ref<`,e,">"]):p(e)?[`${A}=fn${e.name?`<${e.name}>`:""}`]:(e=Ue(e),t?e:[`${A}=`,e])}const At={sp:"serverPrefetch hook",bc:"beforeCreate hook",c:"created hook",bm:"beforeMount hook",m:"mounted hook",bu:"beforeUpdate hook",u:"updated",bum:"beforeUnmount hook",um:"unmounted hook",a:"activated hook",da:"deactivated hook",ec:"errorCaptured hook",rtc:"renderTracked hook",rtg:"renderTriggered hook",0:"setup function",1:"render function",2:"watcher getter",3:"watcher callback",4:"watcher cleanup function",5:"native event handler",6:"component event handler",7:"vnode hook",8:"directive hook",9:"transition hook",10:"app errorHandler",11:"app warnHandler",12:"ref function",13:"async component loader",14:"scheduler flush",15:"component update",16:"app unmount cleanup function"};function et(A,e,t,n){try{return n?A(...n):A()}catch(r){nt(r,e,t)}}function tt(A,e,t,n){if(p(A)){const r=et(A,e,t,n);return r&&w(r)&&r.catch((A=>{nt(A,e,t)})),r}if(d(A)){const r=[];for(let o=0;o=ft(t)?rt.push(A):rt.splice(function(A){let e=ot+1,t=rt.length;for(;e>>1,r=rt[n],o=ft(r);oft(A)-ft(e)));if(it.length=0,st)return void st.push(...e);for(st=e,"production"!==Xe.NODE_ENV&&(A=A||new Map),at=0;atnull==A.id?2&A.flags?-1:1/0:A.id;function mt(A){"production"!==Xe.NODE_ENV&&(A=A||new Map);const e="production"!==Xe.NODE_ENV?e=>wt(A,e):r;try{for(ot=0;ot100){const A=e.i,t=A&&To(A.type);return nt(`Maximum recursive updates exceeded${t?` in component <${t}>`:""}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.`,null,10),!0}return A.set(e,t+1),!1}let Ct=!1;const Qt=new Map;"production"!==Xe.NODE_ENV&&(K().__VUE_HMR_RUNTIME__={createRecord:Ft(Et),rerender:Ft((function(A,e){const t=yt.get(A);if(!t)return;t.initialDef.render=e,[...t.instances].forEach((A=>{e&&(A.render=e,vt(A.type).render=e),A.renderCache=[],Ct=!0,A.update(),Ct=!1}))})),reload:Ft((function(A,e){const t=yt.get(A);if(!t)return;e=vt(e),Ut(t.initialDef,e);const n=[...t.instances];for(let r=0;r{Ct=!0,A.parent.update(),Ct=!1,i.delete(A)})):A.appContext.reload?A.appContext.reload():"undefined"!=typeof window?window.location.reload():console.warn("[HMR] Root or manually mounted instance modified. Full reload required."),A.root.ce&&A!==A.root&&A.root.ce._removeChildStyle(o)}ht((()=>{Qt.clear()}))}))});const yt=new Map;function Et(A,e){return!yt.has(A)&&(yt.set(A,{initialDef:vt(e),instances:new Set}),!0)}function vt(A){return _o(A)?A.__vccOpts:A}function Ut(A,e){a(A,e);for(const t in A)"__file"===t||t in e||delete A[t]}function Ft(A){return(e,t)=>{try{return A(e,t)}catch(n){console.error(n),console.warn("[HMR] Something went wrong during Vue component hot-reload. Full reload required.")}}}let bt,Ht=[],It=!1;function St(A,...e){bt?bt.emit(A,...e):It||Ht.push({event:A,args:e})}function Nt(A,e){var t,n;if(bt=A,bt)bt.enabled=!0,Ht.forEach((({event:A,args:e})=>bt.emit(A,...e))),Ht=[];else if("undefined"!=typeof window&&window.HTMLElement&&!(null==(n=null==(t=window.navigator)?void 0:t.userAgent)?void 0:n.includes("jsdom"))){(e.__VUE_DEVTOOLS_HOOK_REPLAY__=e.__VUE_DEVTOOLS_HOOK_REPLAY__||[]).push((A=>{Nt(A,e)})),setTimeout((()=>{bt||(e.__VUE_DEVTOOLS_HOOK_REPLAY__=null,It=!0,Ht=[])}),3e3)}else It=!0,Ht=[]}const xt=Tt("component:added"),Dt=Tt("component:updated"),Ot=Tt("component:removed"); /*! #__NO_SIDE_EFFECTS__ */ function Tt(A){return e=>{St(A,e.appContext.app,e.uid,e.parent?e.parent.uid:void 0,e)}}const Lt=Rt("perf:start"),_t=Rt("perf:end");function Rt(A){return(e,t,n)=>{St(A,e.appContext.app,e.uid,e,t,n)}}let Kt=null,kt=null;function Mt(A){const e=Kt;return Kt=A,kt=A&&A.type.__scopeId||null,e}function Vt(A){F(A)&&Ze("Do not use built-in directive ids as custom directive id: "+A)}function Pt(A,e){if(null===Kt)return"production"!==Xe.NODE_ENV&&Ze("withDirectives can only be used inside render functions."),A;const n=xo(Kt),r=A.dirs||(A.dirs=[]);for(let o=0;oa({name:A.name},e,{setup:A}))():A}function $t(A){A.ids=[A.ids[0]+A.ids[2]+++"-",0,0]}const Yt=new WeakSet;function jt(A,e,n,r,o=!1){if(d(A))return void A.forEach(((A,t)=>jt(A,e&&(d(e)?e[t]:e),n,r,o)));if(Zt(r)&&!o)return void(512&r.shapeFlag&&r.type.__asyncResolved&&r.component.subTree.component&&jt(A,e,n,r.component.subTree));const i=4&r.shapeFlag?xo(r.component):r.el,s=o?null:i,{i:a,r:l}=A;if("production"!==Xe.NODE_ENV&&!a)return void Ze("Missing ref owner context. ref cannot be used on hoisted vnodes. A vnode with ref must be created inside the render function.");const g=e&&e.r,h=a.refs===t?a.refs={}:a.refs,f=a.setupState,m=Ue(f),w=f===t?()=>!1:A=>("production"===Xe.NODE_ENV||(u(m,A)&&!Ie(m[A])&&Ze(`Template ref "${A}" used on a non-ref value. It will not work in the production build.`),!Yt.has(m[A])))&&u(m,A);if(null!=g&&g!==l&&(B(g)?(h[g]=null,w(g)&&(f[g]=null)):Ie(g)&&(g.value=null)),p(l))et(l,a,12,[s,h]);else{const e=B(l),t=Ie(l);if(e||t){const r=()=>{if(A.f){const t=e?w(l)?f[l]:h[l]:l.value;o?d(t)&&c(t,i):d(t)?t.includes(i)||t.push(i):e?(h[l]=[i],w(l)&&(f[l]=h[l])):(l.value=[i],A.k&&(h[A.k]=l.value))}else e?(h[l]=s,w(l)&&(f[l]=s)):t?(l.value=s,A.k&&(h[A.k]=s)):"production"!==Xe.NODE_ENV&&Ze("Invalid template ref type:",l,`(${typeof l})`)};s?(r.id=-1,pr(r,n)):r()}else"production"!==Xe.NODE_ENV&&Ze("Invalid template ref type:",l,`(${typeof l})`)}}K().requestIdleCallback,K().cancelIdleCallback;const Zt=A=>!!A.type.__asyncLoader,zt=A=>A.type.__isKeepAlive;function qt(A,e){en(A,"a",e)}function An(A,e){en(A,"da",e)}function en(A,e,t=mo){const n=A.__wdc||(A.__wdc=()=>{let e=t;for(;e;){if(e.isDeactivated)return;e=e.parent}return A()});if(nn(e,n,t),t){let A=t.parent;for(;A&&A.parent;)zt(A.parent.vnode)&&tn(n,e,t,A),A=A.parent}}function tn(A,e,t,n){const r=nn(e,A,n,!0);un((()=>{c(n[e],r)}),t)}function nn(A,e,t=mo,n=!1){if(t){const r=t[A]||(t[A]=[]),o=e.__weh||(e.__weh=(...n)=>{UA();const r=yo(t),o=tt(e,t,A,n);return r(),FA(),o});return n?r.unshift(o):r.push(o),o}if("production"!==Xe.NODE_ENV){Ze(`${D(At[A].replace(/ hook$/,""))} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.`)}}const rn=A=>(e,t=mo)=>{bo&&"sp"!==A||nn(A,((...A)=>e(...A)),t)},on=rn("bm"),sn=rn("m"),an=rn("bu"),cn=rn("u"),ln=rn("bum"),un=rn("um"),dn=rn("sp"),gn=rn("rtg"),hn=rn("rtc");function pn(A,e=mo){nn("ec",A,e)}function Bn(A,e){return function(A,e,t=!0,n=!1){const r=Kt||mo;if(r){const o=r.type;{const A=To(o,!1);if(A&&(A===e||A===I(e)||A===x(I(e))))return o}const i=mn(r[A]||o[A],e)||mn(r.appContext[A],e);if(!i&&n)return o;if("production"!==Xe.NODE_ENV&&t&&!i){const t="\nIf this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.";Ze(`Failed to resolve ${A.slice(0,-1)}: ${e}${t}`)}return i}"production"!==Xe.NODE_ENV&&Ze(`resolve${x(A.slice(0,-1))} can only be used in render() or setup().`)}("components",A,!0,e)||A}const fn=Symbol.for("v-ndc");function mn(A,e){return A&&(A[e]||A[I(e)]||A[x(I(e))])}function wn(A,e,t,n){let r;const o=t,i=d(A);if(i||B(A)){let t=!1,n=!1;i&&Qe(A)&&(t=!Ee(A),n=ye(A),A=KA(A)),r=new Array(A.length);for(let i=0,s=A.length;ie(A,t,void 0,o)));else{const t=Object.keys(A);r=new Array(t.length);for(let n=0,i=t.length;nA?Fo(A)?xo(A):Cn(A.parent):null,Qn=a(Object.create(null),{$:A=>A,$el:A=>A.vnode.el,$data:A=>A.data,$props:A=>"production"!==Xe.NODE_ENV?we(A.props):A.props,$attrs:A=>"production"!==Xe.NODE_ENV?we(A.attrs):A.attrs,$slots:A=>"production"!==Xe.NODE_ENV?we(A.slots):A.slots,$refs:A=>"production"!==Xe.NODE_ENV?we(A.refs):A.refs,$parent:A=>Cn(A.parent),$root:A=>Cn(A.root),$host:A=>A.ce,$emit:A=>A.emit,$options:A=>Sn(A),$forceUpdate:A=>A.f||(A.f=()=>{dt(A.update)}),$nextTick:A=>A.n||(A.n=ut.bind(A.proxy)),$watch:A=>Fr.bind(A)}),yn=A=>"_"===A||"$"===A,En=(A,e)=>A!==t&&!A.__isScriptSetup&&u(A,e),vn={get({_:A},e){if("__v_skip"===e)return!0;const{ctx:n,setupState:r,data:o,props:i,accessCache:s,type:a,appContext:c}=A;if("production"!==Xe.NODE_ENV&&"__isVue"===e)return!0;let l;if("$"!==e[0]){const a=s[e];if(void 0!==a)switch(a){case 1:return r[e];case 2:return o[e];case 4:return n[e];case 3:return i[e]}else{if(En(r,e))return s[e]=1,r[e];if(o!==t&&u(o,e))return s[e]=2,o[e];if((l=A.propsOptions[0])&&u(l,e))return s[e]=3,i[e];if(n!==t&&u(n,e))return s[e]=4,n[e];Fn&&(s[e]=0)}}const d=Qn[e];let g,h;return d?("$attrs"===e?(LA(A.attrs,"get",""),"production"!==Xe.NODE_ENV&&Dr()):"production"!==Xe.NODE_ENV&&"$slots"===e&&LA(A,"get",e),d(A)):(g=a.__cssModules)&&(g=g[e])?g:n!==t&&u(n,e)?(s[e]=4,n[e]):(h=c.config.globalProperties,u(h,e)?h[e]:void("production"===Xe.NODE_ENV||!Kt||B(e)&&0===e.indexOf("__v")||(o!==t&&yn(e[0])&&u(o,e)?Ze(`Property ${JSON.stringify(e)} must be accessed via $data because it starts with a reserved character ("$" or "_") and is not proxied on the render context.`):A===Kt&&Ze(`Property ${JSON.stringify(e)} was accessed during render but is not defined on instance.`))))},set({_:A},e,n){const{data:r,setupState:o,ctx:i}=A;return En(o,e)?(o[e]=n,!0):"production"!==Xe.NODE_ENV&&o.__isScriptSetup&&u(o,e)?(Ze(`Cannot mutate \n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n","\n\n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n\n\n","import { ref } from \"vue\";\nimport {\n applyHighlights,\n clearAllHighlights,\n} from \"../../directives/highlightDirective.js\";\n\n/**\n * Composable for orchestrating the entire highlighting system\n * This handles DOM operations, event management, and integration with stores\n */\nfunction useHighlightOrchestrator(\n smartCommentsSetup,\n commentsStore,\n smartCommentsEvents,\n) {\n const isRefreshing = ref(false);\n\n /**\n * Get the target element for highlights\n */\n const getTargetElement = () => {\n return document.getElementById(\"mw-content-text\") || document.body;\n };\n\n /**\n * Handle highlight click events\n */\n const handleHighlightClick = (event, commentData, position) => {\n if (event && event.preventDefault) {\n event.preventDefault();\n }\n\n // Trigger events\n smartCommentsEvents.triggerHighlightClicked(commentData, position);\n smartCommentsEvents.triggerCommentGroupOpen(commentData, position);\n\n commentsStore.openCommentDialog(commentData, position);\n };\n\n /**\n * Reload highlights and update comments store\n */\n const reloadHighlightsAndComments = async () => {\n if (isRefreshing.value) return;\n\n try {\n isRefreshing.value = true;\n const targetElement = getTargetElement();\n\n // Clear existing highlights first\n if (smartCommentsSetup.highlightedAnchors?.value) {\n clearAllHighlights(\n targetElement,\n smartCommentsSetup.highlightedAnchors.value,\n );\n }\n\n // Reload comments and highlights from server\n await smartCommentsSetup.loadAndSetHighlights();\n\n // Update the comments store with the freshly loaded comments\n if (smartCommentsSetup.comments?.value !== undefined) {\n commentsStore.setComments(smartCommentsSetup.comments.value);\n } else {\n console.warn(\n \"useHighlightOrchestrator: comments.value is undefined after loadAndSetHighlights, setting empty array\",\n );\n commentsStore.setComments([]);\n }\n\n // Apply the fresh highlights\n if (smartCommentsSetup.highlightedAnchors?.value) {\n applyHighlights(\n targetElement,\n smartCommentsSetup.highlightedAnchors.value,\n handleHighlightClick,\n );\n }\n\n // Restore active highlight if dialog is open\n if (commentsStore.isCommentDialogVisible && commentsStore.activeComment) {\n const commentId =\n commentsStore.activeComment.data_id || commentsStore.activeComment.id;\n commentsStore.setActiveHighlight(commentId);\n }\n } catch (error) {\n console.error(\n \"useHighlightOrchestrator: Error reloading highlights:\",\n error,\n );\n } finally {\n isRefreshing.value = false;\n }\n };\n\n /**\n * Clear all highlights\n */\n const clearHighlights = () => {\n const targetElement = getTargetElement();\n if (smartCommentsSetup.highlightedAnchors?.value) {\n clearAllHighlights(\n targetElement,\n smartCommentsSetup.highlightedAnchors.value,\n );\n }\n };\n\n /**\n * Setup highlight refresh event listener\n */\n const setupHighlightRefreshListener = () => {\n const handleHighlightRefresh = async () => {\n await reloadHighlightsAndComments();\n };\n\n document.addEventListener(\n \"smartcomments:refresh-highlights\",\n handleHighlightRefresh,\n );\n\n return () => {\n document.removeEventListener(\n \"smartcomments:refresh-highlights\",\n handleHighlightRefresh,\n );\n };\n };\n\n /**\n * Manual highlight reload (for debugging)\n */\n const reloadHighlights = async (isEnabled) => {\n if (!isEnabled) {\n console.warn(\n \"useHighlightOrchestrator: Cannot reload highlights, system is disabled.\",\n );\n return;\n }\n\n if (!smartCommentsSetup?.loadAndSetHighlights) {\n console.error(\n \"useHighlightOrchestrator: smartCommentsSetup.loadAndSetHighlights not available.\",\n );\n return;\n }\n\n try {\n clearHighlights();\n await reloadHighlightsAndComments();\n } catch (error) {\n console.error(\"useHighlightOrchestrator reloadHighlights: Error:\", error);\n }\n };\n\n return {\n isRefreshing,\n reloadHighlightsAndComments,\n clearHighlights,\n setupHighlightRefreshListener,\n reloadHighlights,\n handleHighlightClick,\n };\n}\n\nexport default useHighlightOrchestrator;\n","/**\n * Composable for managing keyboard shortcuts\n */\nfunction useKeyboardShortcuts(commentsStore) {\n /**\n * Handle keyboard shortcuts\n */\n const handleKeydown = (event) => {\n if (event.key === \"Escape\" && commentsStore.isCommentDialogVisible) {\n // If image modal is open, close it first\n if (commentsStore.isImageModalVisible) {\n commentsStore.closeImageModal();\n } else {\n // Otherwise close the comment dialog\n commentsStore.closeCommentDialog();\n }\n } else if (event.key === \"ArrowDown\" && commentsStore.hasNextComment) {\n commentsStore.navigateComment(\"next\");\n } else if (event.key === \"ArrowUp\" && commentsStore.hasPreviousComment) {\n commentsStore.navigateComment(\"previous\");\n }\n };\n\n /**\n * Setup keyboard event listeners\n */\n const setupKeyboardShortcuts = () => {\n document.addEventListener(\"keydown\", handleKeydown);\n\n return () => {\n document.removeEventListener(\"keydown\", handleKeydown);\n };\n };\n\n return {\n setupKeyboardShortcuts,\n };\n}\n\nexport default useKeyboardShortcuts;\n","import { watch } from \"vue\";\n\n/**\n * Composable for managing CSS custom properties\n */\nfunction useCustomProperties(messages) {\n /**\n * Update CSS custom property for annotate tooltip text\n */\n const updateAnnotateTooltipText = (text) => {\n document.documentElement.style.setProperty(\n \"--smartcomments-annotate-text\",\n `\"${text}\"`,\n );\n };\n\n /**\n * Update CSS custom property for button open text\n */\n const updateButtonOpenText = (text) => {\n document.documentElement.style.setProperty(\n \"--smartcomments-button-open-text\",\n `\"${text}\"`,\n );\n };\n\n /**\n * Setup watchers for CSS custom properties\n */\n const setupCustomPropertiesWatchers = () => {\n const annotateTooltipText = () => messages.msg(\"sc-annotate-tooltip\");\n const buttonOpenText = () => messages.msg(\"sc-button-open\");\n\n // Initial setup\n updateAnnotateTooltipText(annotateTooltipText());\n updateButtonOpenText(buttonOpenText());\n\n // Watch for changes (e.g., language changes)\n const stopAnnotateWatcher = watch(annotateTooltipText, (newText) => {\n updateAnnotateTooltipText(newText);\n });\n\n const stopButtonWatcher = watch(buttonOpenText, (newText) => {\n updateButtonOpenText(newText);\n });\n\n return () => {\n stopAnnotateWatcher();\n stopButtonWatcher();\n };\n };\n\n return {\n setupCustomPropertiesWatchers,\n updateAnnotateTooltipText,\n updateButtonOpenText,\n };\n}\n\nexport default useCustomProperties;\n","/**\n * Composable for managing SmartComments event handlers\n */\nfunction useSmartCommentsEventHandlers(\n smartCommentsEvents,\n EVENTS,\n store,\n commentsStore,\n highlightsManager,\n) {\n /**\n * Setup SmartComments events\n */\n const setupSmartCommentsEvents = () => {\n const cleanupFunctions = [];\n\n // Listen for debug mode events\n cleanupFunctions.push(\n smartCommentsEvents.on(EVENTS.DEBUG_MODE, (event) => {\n if (event.detail.enabled && !store.isEnabled) {\n store.setEnabled(true);\n }\n }),\n );\n\n // Listen for selection active events\n cleanupFunctions.push(\n smartCommentsEvents.on(EVENTS.SELECTION_ACTIVE, (event) => {\n // Close any open comment dialogs when a new selection is made\n if (commentsStore.isCommentDialogVisible) {\n commentsStore.closeCommentDialog();\n }\n }),\n );\n\n // Listen for open comment events\n cleanupFunctions.push(\n smartCommentsEvents.on(EVENTS.OPEN_COMMENT_ID, (event) => {\n if (event.detail.commentId) {\n // Handle opening specific comment\n commentsStore.openCommentDialogById(event.detail.commentId);\n }\n }),\n );\n\n // Listen for open comment with position events\n cleanupFunctions.push(\n smartCommentsEvents.on(EVENTS.OPEN_COMMENT_WITH_POSITION, (event) => {\n if (event.detail.commentId && event.detail.position) {\n // Handle opening specific comment with custom position\n commentsStore.openCommentDialogByIdWithPosition(event.detail.commentId, event.detail.position);\n }\n }),\n );\n\n // Listen for comment created events\n cleanupFunctions.push(\n smartCommentsEvents.on(EVENTS.COMMENT_CREATED, (event) => {\n if (highlightsManager) {\n highlightsManager.reloadHighlightsAndComments();\n }\n }),\n );\n\n return () => {\n cleanupFunctions.forEach((cleanup) => cleanup());\n };\n };\n\n return {\n setupSmartCommentsEvents,\n };\n}\n\nexport default useSmartCommentsEventHandlers;\n","/**\n * Composable for managing URL navigation and parameters\n */\nfunction useUrlNavigation(commentsStore) {\n /**\n * Setup URL navigation handlers\n */\n const setupUrlNavigation = (isEnabled) => {\n // Handle URL changes (back/forward navigation)\n const handlePopState = async () => {\n if (isEnabled()) {\n await commentsStore.checkAndOpenCommentFromUrl();\n }\n };\n\n window.addEventListener(\"popstate\", handlePopState);\n\n return () => {\n window.removeEventListener(\"popstate\", handlePopState);\n };\n };\n\n /**\n * Check URL parameters and open comment (for debugging)\n */\n const checkUrlParameters = async (isEnabled) => {\n if (!isEnabled()) {\n console.warn(\n \"useUrlNavigation: Cannot check URL parameters, system is disabled.\",\n );\n return;\n }\n await commentsStore.checkAndOpenCommentFromUrl();\n };\n\n return {\n setupUrlNavigation,\n checkUrlParameters,\n };\n}\n\nexport default useUrlNavigation;\n","/**\n * Rangy, a cross-browser JavaScript range and selection library\n * https://github.com/timdown/rangy\n *\n * Copyright 2024, Tim Down\n * Licensed under the MIT license.\n * Version: 1.3.2\n * Build date: 2 November 2024\n */\n\n(function(factory, root) {\n if (typeof define == \"function\" && define.amd) {\n // AMD. Register as an anonymous module.\n define(factory);\n } else if (typeof module != \"undefined\" && typeof exports == \"object\") {\n // Node/CommonJS style\n module.exports = factory();\n } else {\n // No AMD or CommonJS support so we place Rangy in (probably) the global variable\n root.rangy = factory();\n }\n})(function() {\n\n var OBJECT = \"object\", FUNCTION = \"function\", UNDEFINED = \"undefined\";\n\n // Minimal set of properties required for DOM Level 2 Range compliance. Comparison constants such as START_TO_START\n // are omitted because ranges in KHTML do not have them but otherwise work perfectly well. See issue 113.\n var domRangeProperties = [\"startContainer\", \"startOffset\", \"endContainer\", \"endOffset\", \"collapsed\",\n \"commonAncestorContainer\"];\n\n // Minimal set of methods required for DOM Level 2 Range compliance\n var domRangeMethods = [\"setStart\", \"setStartBefore\", \"setStartAfter\", \"setEnd\", \"setEndBefore\",\n \"setEndAfter\", \"collapse\", \"selectNode\", \"selectNodeContents\", \"compareBoundaryPoints\", \"deleteContents\",\n \"extractContents\", \"cloneContents\", \"insertNode\", \"surroundContents\", \"cloneRange\", \"toString\", \"detach\"];\n\n var textRangeProperties = [\"boundingHeight\", \"boundingLeft\", \"boundingTop\", \"boundingWidth\", \"htmlText\", \"text\"];\n\n // Subset of TextRange's full set of methods that we're interested in\n var textRangeMethods = [\"collapse\", \"compareEndPoints\", \"duplicate\", \"moveToElementText\", \"parentElement\", \"select\",\n \"setEndPoint\", \"getBoundingClientRect\"];\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Trio of functions taken from Peter Michaux's article:\n // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting\n function isHostMethod(o, p) {\n var t = typeof o[p];\n return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == \"unknown\";\n }\n\n function isHostObject(o, p) {\n return !!(typeof o[p] == OBJECT && o[p]);\n }\n\n function isHostProperty(o, p) {\n return typeof o[p] != UNDEFINED;\n }\n\n // Creates a convenience function to save verbose repeated calls to tests functions\n function createMultiplePropertyTest(testFunc) {\n return function(o, props) {\n var i = props.length;\n while (i--) {\n if (!testFunc(o, props[i])) {\n return false;\n }\n }\n return true;\n };\n }\n\n // Next trio of functions are a convenience to save verbose repeated calls to previous two functions\n var areHostMethods = createMultiplePropertyTest(isHostMethod);\n var areHostObjects = createMultiplePropertyTest(isHostObject);\n var areHostProperties = createMultiplePropertyTest(isHostProperty);\n\n function isTextRange(range) {\n return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);\n }\n\n function getBody(doc) {\n return isHostObject(doc, \"body\") ? doc.body : doc.getElementsByTagName(\"body\")[0];\n }\n\n var forEach = [].forEach ?\n function(arr, func) {\n arr.forEach(func);\n } :\n function(arr, func) {\n for (var i = 0, len = arr.length; i < len; ++i) {\n func(arr[i], i);\n }\n };\n\n var modules = {};\n\n var isBrowser = (typeof window != UNDEFINED && typeof document != UNDEFINED);\n\n var util = {\n isHostMethod: isHostMethod,\n isHostObject: isHostObject,\n isHostProperty: isHostProperty,\n areHostMethods: areHostMethods,\n areHostObjects: areHostObjects,\n areHostProperties: areHostProperties,\n isTextRange: isTextRange,\n getBody: getBody,\n forEach: forEach\n };\n\n var api = {\n version: \"1.3.2\",\n initialized: false,\n isBrowser: isBrowser,\n supported: true,\n util: util,\n features: {},\n modules: modules,\n config: {\n alertOnFail: false,\n alertOnWarn: false,\n preferTextRange: false,\n autoInitialize: (typeof rangyAutoInitialize == UNDEFINED) ? true : rangyAutoInitialize\n }\n };\n\n function consoleLog(msg) {\n if (typeof console != UNDEFINED && isHostMethod(console, \"log\")) {\n console.log(msg);\n }\n }\n\n function alertOrLog(msg, shouldAlert) {\n if (isBrowser && shouldAlert) {\n alert(msg);\n } else {\n consoleLog(msg);\n }\n }\n\n function fail(reason) {\n api.initialized = true;\n api.supported = false;\n alertOrLog(\"Rangy is not supported in this environment. Reason: \" + reason, api.config.alertOnFail);\n }\n\n api.fail = fail;\n\n function warn(msg) {\n alertOrLog(\"Rangy warning: \" + msg, api.config.alertOnWarn);\n }\n\n api.warn = warn;\n\n // Add utility extend() method\n var extend;\n if ({}.hasOwnProperty) {\n util.extend = extend = function(obj, props, deep) {\n var o, p;\n for (var i in props) {\n if (i === \"__proto__\" || i === \"constructor\" || i === \"prototype\") {\n continue;\n }\n if (props.hasOwnProperty(i)) {\n o = obj[i];\n p = props[i];\n if (deep && o !== null && typeof o == \"object\" && p !== null && typeof p == \"object\") {\n extend(o, p, true);\n }\n obj[i] = p;\n }\n }\n // Special case for toString, which does not show up in for...in loops in IE <= 8\n if (props.hasOwnProperty(\"toString\")) {\n obj.toString = props.toString;\n }\n return obj;\n };\n\n util.createOptions = function(optionsParam, defaults) {\n var options = {};\n extend(options, defaults);\n if (optionsParam) {\n extend(options, optionsParam);\n }\n return options;\n };\n } else {\n fail(\"hasOwnProperty not supported\");\n }\n\n // Test whether we're in a browser and bail out if not\n if (!isBrowser) {\n fail(\"Rangy can only run in a browser\");\n }\n\n // Test whether Array.prototype.slice can be relied on for NodeLists and use an alternative toArray() if not\n (function() {\n var toArray;\n\n if (isBrowser) {\n var el = document.createElement(\"div\");\n el.appendChild(document.createElement(\"span\"));\n var slice = [].slice;\n try {\n if (slice.call(el.childNodes, 0)[0].nodeType == 1) {\n toArray = function(arrayLike) {\n return slice.call(arrayLike, 0);\n };\n }\n } catch (e) {}\n }\n\n if (!toArray) {\n toArray = function(arrayLike) {\n var arr = [];\n for (var i = 0, len = arrayLike.length; i < len; ++i) {\n arr[i] = arrayLike[i];\n }\n return arr;\n };\n }\n\n util.toArray = toArray;\n })();\n\n // Very simple event handler wrapper function that doesn't attempt to solve issues such as \"this\" handling or\n // normalization of event properties because we don't need this.\n var addListener;\n if (isBrowser) {\n if (isHostMethod(document, \"addEventListener\")) {\n addListener = function(obj, eventType, listener) {\n obj.addEventListener(eventType, listener, false);\n };\n } else if (isHostMethod(document, \"attachEvent\")) {\n addListener = function(obj, eventType, listener) {\n obj.attachEvent(\"on\" + eventType, listener);\n };\n } else {\n fail(\"Document does not have required addEventListener or attachEvent method\");\n }\n\n util.addListener = addListener;\n }\n\n var initListeners = [];\n\n function getErrorDesc(ex) {\n return ex.message || ex.description || String(ex);\n }\n\n // Initialization\n function init() {\n if (!isBrowser || api.initialized) {\n return;\n }\n var testRange;\n var implementsDomRange = false, implementsTextRange = false;\n\n // First, perform basic feature tests\n\n if (isHostMethod(document, \"createRange\")) {\n testRange = document.createRange();\n if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {\n implementsDomRange = true;\n }\n }\n\n var body = getBody(document);\n if (!body || body.nodeName.toLowerCase() != \"body\") {\n fail(\"No body element found\");\n return;\n }\n\n if (body && isHostMethod(body, \"createTextRange\")) {\n testRange = body.createTextRange();\n if (isTextRange(testRange)) {\n implementsTextRange = true;\n }\n }\n\n if (!implementsDomRange && !implementsTextRange) {\n fail(\"Neither Range nor TextRange are available\");\n return;\n }\n\n api.initialized = true;\n api.features = {\n implementsDomRange: implementsDomRange,\n implementsTextRange: implementsTextRange\n };\n\n // Initialize modules\n var module, errorMessage;\n for (var moduleName in modules) {\n if ( (module = modules[moduleName]) instanceof Module ) {\n module.init(module, api);\n }\n }\n\n // Call init listeners\n for (var i = 0, len = initListeners.length; i < len; ++i) {\n try {\n initListeners[i](api);\n } catch (ex) {\n errorMessage = \"Rangy init listener threw an exception. Continuing. Detail: \" + getErrorDesc(ex);\n consoleLog(errorMessage);\n }\n }\n }\n\n function deprecationNotice(deprecated, replacement, module) {\n if (module) {\n deprecated += \" in module \" + module.name;\n }\n api.warn(\"DEPRECATED: \" + deprecated + \" is deprecated. Please use \" +\n replacement + \" instead.\");\n }\n\n function createAliasForDeprecatedMethod(owner, deprecated, replacement, module) {\n owner[deprecated] = function() {\n deprecationNotice(deprecated, replacement, module);\n return owner[replacement].apply(owner, util.toArray(arguments));\n };\n }\n\n util.deprecationNotice = deprecationNotice;\n util.createAliasForDeprecatedMethod = createAliasForDeprecatedMethod;\n\n // Allow external scripts to initialize this library in case it's loaded after the document has loaded\n api.init = init;\n\n // Execute listener immediately if already initialized\n api.addInitListener = function(listener) {\n if (api.initialized) {\n listener(api);\n } else {\n initListeners.push(listener);\n }\n };\n\n var shimListeners = [];\n\n api.addShimListener = function(listener) {\n shimListeners.push(listener);\n };\n\n function shim(win) {\n win = win || window;\n init();\n\n // Notify listeners\n for (var i = 0, len = shimListeners.length; i < len; ++i) {\n shimListeners[i](win);\n }\n }\n\n if (isBrowser) {\n api.shim = api.createMissingNativeApi = shim;\n createAliasForDeprecatedMethod(api, \"createMissingNativeApi\", \"shim\");\n }\n\n function Module(name, dependencies, initializer) {\n this.name = name;\n this.dependencies = dependencies;\n this.initialized = false;\n this.supported = false;\n this.initializer = initializer;\n }\n\n Module.prototype = {\n init: function() {\n var requiredModuleNames = this.dependencies || [];\n for (var i = 0, len = requiredModuleNames.length, requiredModule, moduleName; i < len; ++i) {\n moduleName = requiredModuleNames[i];\n\n requiredModule = modules[moduleName];\n if (!requiredModule || !(requiredModule instanceof Module)) {\n throw new Error(\"required module '\" + moduleName + \"' not found\");\n }\n\n requiredModule.init();\n\n if (!requiredModule.supported) {\n throw new Error(\"required module '\" + moduleName + \"' not supported\");\n }\n }\n\n // Now run initializer\n this.initializer(this);\n },\n\n fail: function(reason) {\n this.initialized = true;\n this.supported = false;\n throw new Error(reason);\n },\n\n warn: function(msg) {\n api.warn(\"Module \" + this.name + \": \" + msg);\n },\n\n deprecationNotice: function(deprecated, replacement) {\n api.warn(\"DEPRECATED: \" + deprecated + \" in module \" + this.name + \" is deprecated. Please use \" +\n replacement + \" instead\");\n },\n\n createError: function(msg) {\n return new Error(\"Error in Rangy \" + this.name + \" module: \" + msg);\n }\n };\n\n function createModule(name, dependencies, initFunc) {\n var newModule = new Module(name, dependencies, function(module) {\n if (!module.initialized) {\n module.initialized = true;\n try {\n initFunc(api, module);\n module.supported = true;\n } catch (ex) {\n var errorMessage = \"Module '\" + name + \"' failed to load: \" + getErrorDesc(ex);\n consoleLog(errorMessage);\n if (ex.stack) {\n consoleLog(ex.stack);\n }\n }\n }\n });\n modules[name] = newModule;\n return newModule;\n }\n\n api.createModule = function(name) {\n // Allow 2 or 3 arguments (second argument is an optional array of dependencies)\n var initFunc, dependencies;\n if (arguments.length == 2) {\n initFunc = arguments[1];\n dependencies = [];\n } else {\n initFunc = arguments[2];\n dependencies = arguments[1];\n }\n\n var module = createModule(name, dependencies, initFunc);\n\n // Initialize the module immediately if the core is already initialized\n if (api.initialized && api.supported) {\n module.init();\n }\n };\n\n api.createCoreModule = function(name, dependencies, initFunc) {\n createModule(name, dependencies, initFunc);\n };\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Ensure rangy.rangePrototype and rangy.selectionPrototype are available immediately\n\n function RangePrototype() {}\n api.RangePrototype = RangePrototype;\n api.rangePrototype = new RangePrototype();\n\n function SelectionPrototype() {}\n api.selectionPrototype = new SelectionPrototype();\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // DOM utility methods used by Rangy\n api.createCoreModule(\"DomUtil\", [], function(api, module) {\n var UNDEF = \"undefined\";\n var util = api.util;\n var getBody = util.getBody;\n\n // Perform feature tests\n if (!util.areHostMethods(document, [\"createDocumentFragment\", \"createElement\", \"createTextNode\"])) {\n module.fail(\"document missing a Node creation method\");\n }\n\n if (!util.isHostMethod(document, \"getElementsByTagName\")) {\n module.fail(\"document missing getElementsByTagName method\");\n }\n\n var el = document.createElement(\"div\");\n if (!util.areHostMethods(el, [\"insertBefore\", \"appendChild\", \"cloneNode\"] ||\n !util.areHostObjects(el, [\"previousSibling\", \"nextSibling\", \"childNodes\", \"parentNode\"]))) {\n module.fail(\"Incomplete Element implementation\");\n }\n\n // innerHTML is required for Range's createContextualFragment method\n if (!util.isHostProperty(el, \"innerHTML\")) {\n module.fail(\"Element is missing innerHTML property\");\n }\n\n var textNode = document.createTextNode(\"test\");\n if (!util.areHostMethods(textNode, [\"splitText\", \"deleteData\", \"insertData\", \"appendData\", \"cloneNode\"] ||\n !util.areHostObjects(el, [\"previousSibling\", \"nextSibling\", \"childNodes\", \"parentNode\"]) ||\n !util.areHostProperties(textNode, [\"data\"]))) {\n module.fail(\"Incomplete Text Node implementation\");\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been\n // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that\n // contains just the document as a single element and the value searched for is the document.\n var arrayContains = /*Array.prototype.indexOf ?\n function(arr, val) {\n return arr.indexOf(val) > -1;\n }:*/\n\n function(arr, val) {\n var i = arr.length;\n while (i--) {\n if (arr[i] === val) {\n return true;\n }\n }\n return false;\n };\n\n // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI\n function isHtmlNamespace(node) {\n var ns;\n return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == \"http://www.w3.org/1999/xhtml\");\n }\n\n function parentElement(node) {\n var parent = node.parentNode;\n return (parent.nodeType == 1) ? parent : null;\n }\n\n function getNodeIndex(node) {\n var i = 0;\n while( (node = node.previousSibling) ) {\n ++i;\n }\n return i;\n }\n\n function getNodeLength(node) {\n switch (node.nodeType) {\n case 7:\n case 10:\n return 0;\n case 3:\n case 8:\n return node.length;\n default:\n return node.childNodes.length;\n }\n }\n\n function getCommonAncestor(node1, node2) {\n var ancestors = [], n;\n for (n = node1; n; n = n.parentNode) {\n ancestors.push(n);\n }\n\n for (n = node2; n; n = n.parentNode) {\n if (arrayContains(ancestors, n)) {\n return n;\n }\n }\n\n return null;\n }\n\n function isAncestorOf(ancestor, descendant, selfIsAncestor) {\n var n = selfIsAncestor ? descendant : descendant.parentNode;\n while (n) {\n if (n === ancestor) {\n return true;\n } else {\n n = n.parentNode;\n }\n }\n return false;\n }\n\n function isOrIsAncestorOf(ancestor, descendant) {\n return isAncestorOf(ancestor, descendant, true);\n }\n\n function getClosestAncestorIn(node, ancestor, selfIsAncestor) {\n var p, n = selfIsAncestor ? node : node.parentNode;\n while (n) {\n p = n.parentNode;\n if (p === ancestor) {\n return n;\n }\n n = p;\n }\n return null;\n }\n\n function isCharacterDataNode(node) {\n var t = node.nodeType;\n return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment\n }\n\n function isTextOrCommentNode(node) {\n if (!node) {\n return false;\n }\n var t = node.nodeType;\n return t == 3 || t == 8 ; // Text or Comment\n }\n\n function insertAfter(node, precedingNode) {\n var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;\n if (nextNode) {\n parent.insertBefore(node, nextNode);\n } else {\n parent.appendChild(node);\n }\n return node;\n }\n\n // Note that we cannot use splitText() because it is bugridden in IE 9.\n function splitDataNode(node, index, positionsToPreserve) {\n var newNode = node.cloneNode(false);\n newNode.deleteData(0, index);\n node.deleteData(index, node.length - index);\n insertAfter(newNode, node);\n\n // Preserve positions\n if (positionsToPreserve) {\n for (var i = 0, position; position = positionsToPreserve[i++]; ) {\n // Handle case where position was inside the portion of node after the split point\n if (position.node == node && position.offset > index) {\n position.node = newNode;\n position.offset -= index;\n }\n // Handle the case where the position is a node offset within node's parent\n else if (position.node == node.parentNode && position.offset > getNodeIndex(node)) {\n ++position.offset;\n }\n }\n }\n return newNode;\n }\n\n function getDocument(node) {\n if (node.nodeType == 9) {\n return node;\n } else if (typeof node.ownerDocument != UNDEF) {\n return node.ownerDocument;\n } else if (typeof node.document != UNDEF) {\n return node.document;\n } else if (node.parentNode) {\n return getDocument(node.parentNode);\n } else {\n throw module.createError(\"getDocument: no document found for node\");\n }\n }\n\n function getWindow(node) {\n var doc = getDocument(node);\n if (typeof doc.defaultView != UNDEF) {\n return doc.defaultView;\n } else if (typeof doc.parentWindow != UNDEF) {\n return doc.parentWindow;\n } else {\n throw module.createError(\"Cannot get a window object for node\");\n }\n }\n\n function getIframeDocument(iframeEl) {\n if (typeof iframeEl.contentDocument != UNDEF) {\n return iframeEl.contentDocument;\n } else if (typeof iframeEl.contentWindow != UNDEF) {\n return iframeEl.contentWindow.document;\n } else {\n throw module.createError(\"getIframeDocument: No Document object found for iframe element\");\n }\n }\n\n function getIframeWindow(iframeEl) {\n if (typeof iframeEl.contentWindow != UNDEF) {\n return iframeEl.contentWindow;\n } else if (typeof iframeEl.contentDocument != UNDEF) {\n return iframeEl.contentDocument.defaultView;\n } else {\n throw module.createError(\"getIframeWindow: No Window object found for iframe element\");\n }\n }\n\n // This looks bad. Is it worth it?\n function isWindow(obj) {\n return obj && util.isHostMethod(obj, \"setTimeout\") && util.isHostObject(obj, \"document\");\n }\n\n function getContentDocument(obj, module, methodName) {\n var doc;\n\n if (!obj) {\n doc = document;\n }\n\n // Test if a DOM node has been passed and obtain a document object for it if so\n else if (util.isHostProperty(obj, \"nodeType\")) {\n doc = (obj.nodeType == 1 && obj.tagName.toLowerCase() == \"iframe\") ?\n getIframeDocument(obj) : getDocument(obj);\n }\n\n // Test if the doc parameter appears to be a Window object\n else if (isWindow(obj)) {\n doc = obj.document;\n }\n\n if (!doc) {\n throw module.createError(methodName + \"(): Parameter must be a Window object or DOM node\");\n }\n\n return doc;\n }\n\n function getRootContainer(node) {\n var parent;\n while ( (parent = node.parentNode) ) {\n node = parent;\n }\n return node;\n }\n\n function comparePoints(nodeA, offsetA, nodeB, offsetB) {\n // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing\n var nodeC, root, childA, childB, n;\n if (nodeA == nodeB) {\n // Case 1: nodes are the same\n return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;\n } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {\n // Case 2: node C (container B or an ancestor) is a child node of A\n return offsetA <= getNodeIndex(nodeC) ? -1 : 1;\n } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {\n // Case 3: node C (container A or an ancestor) is a child node of B\n return getNodeIndex(nodeC) < offsetB ? -1 : 1;\n } else {\n root = getCommonAncestor(nodeA, nodeB);\n if (!root) {\n throw new Error(\"comparePoints error: nodes have no common ancestor\");\n }\n\n // Case 4: containers are siblings or descendants of siblings\n childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);\n childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);\n\n if (childA === childB) {\n // This shouldn't be possible\n throw module.createError(\"comparePoints got to case 4 and childA and childB are the same!\");\n } else {\n n = root.firstChild;\n while (n) {\n if (n === childA) {\n return -1;\n } else if (n === childB) {\n return 1;\n }\n n = n.nextSibling;\n }\n }\n }\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Test for IE's crash (IE 6/7) or exception (IE >= 8) when a reference to garbage-collected text node is queried\n var crashyTextNodes = false;\n\n function isBrokenNode(node) {\n var n;\n try {\n n = node.parentNode;\n return false;\n } catch (e) {\n return true;\n }\n }\n\n (function() {\n var el = document.createElement(\"b\");\n el.innerHTML = \"1\";\n var textNode = el.firstChild;\n el.innerHTML = \"
\";\n crashyTextNodes = isBrokenNode(textNode);\n\n api.features.crashyTextNodes = crashyTextNodes;\n })();\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n function inspectNode(node) {\n if (!node) {\n return \"[No node]\";\n }\n if (crashyTextNodes && isBrokenNode(node)) {\n return \"[Broken node]\";\n }\n if (isCharacterDataNode(node)) {\n return '\"' + node.data + '\"';\n }\n if (node.nodeType == 1) {\n var idAttr = node.id ? ' id=\"' + node.id + '\"' : \"\";\n return \"<\" + node.nodeName + idAttr + \">[index:\" + getNodeIndex(node) + \",length:\" + node.childNodes.length + \"][\" + (node.innerHTML || \"[innerHTML not supported]\").slice(0, 25) + \"]\";\n }\n return node.nodeName;\n }\n\n function fragmentFromNodeChildren(node) {\n var fragment = getDocument(node).createDocumentFragment(), child;\n while ( (child = node.firstChild) ) {\n fragment.appendChild(child);\n }\n return fragment;\n }\n\n var getComputedStyleProperty;\n if (typeof window.getComputedStyle != UNDEF) {\n getComputedStyleProperty = function(el, propName) {\n return getWindow(el).getComputedStyle(el, null)[propName];\n };\n } else if (typeof document.documentElement.currentStyle != UNDEF) {\n getComputedStyleProperty = function(el, propName) {\n return el.currentStyle ? el.currentStyle[propName] : \"\";\n };\n } else {\n module.fail(\"No means of obtaining computed style properties found\");\n }\n\n function createTestElement(doc, html, contentEditable) {\n var body = getBody(doc);\n var el = doc.createElement(\"div\");\n el.contentEditable = \"\" + !!contentEditable;\n if (html) {\n el.innerHTML = html;\n }\n\n // Insert the test element at the start of the body to prevent scrolling to the bottom in iOS (issue #292)\n var bodyFirstChild = body.firstChild;\n if (bodyFirstChild) {\n body.insertBefore(el, bodyFirstChild);\n } else {\n body.appendChild(el);\n }\n\n return el;\n }\n\n function removeNode(node) {\n return node.parentNode.removeChild(node);\n }\n\n function NodeIterator(root) {\n this.root = root;\n this._next = root;\n }\n\n NodeIterator.prototype = {\n _current: null,\n\n hasNext: function() {\n return !!this._next;\n },\n\n next: function() {\n var n = this._current = this._next;\n var child, next;\n if (this._current) {\n child = n.firstChild;\n if (child) {\n this._next = child;\n } else {\n next = null;\n while ((n !== this.root) && !(next = n.nextSibling)) {\n n = n.parentNode;\n }\n this._next = next;\n }\n }\n return this._current;\n },\n\n detach: function() {\n this._current = this._next = this.root = null;\n }\n };\n\n function createIterator(root) {\n return new NodeIterator(root);\n }\n\n function DomPosition(node, offset) {\n this.node = node;\n this.offset = offset;\n }\n\n DomPosition.prototype = {\n equals: function(pos) {\n return !!pos && this.node === pos.node && this.offset == pos.offset;\n },\n\n inspect: function() {\n return \"[DomPosition(\" + inspectNode(this.node) + \":\" + this.offset + \")]\";\n },\n\n toString: function() {\n return this.inspect();\n }\n };\n\n function DOMException(codeName) {\n this.code = this[codeName];\n this.codeName = codeName;\n this.message = \"DOMException: \" + this.codeName;\n }\n\n DOMException.prototype = {\n INDEX_SIZE_ERR: 1,\n HIERARCHY_REQUEST_ERR: 3,\n WRONG_DOCUMENT_ERR: 4,\n NO_MODIFICATION_ALLOWED_ERR: 7,\n NOT_FOUND_ERR: 8,\n NOT_SUPPORTED_ERR: 9,\n INVALID_STATE_ERR: 11,\n INVALID_NODE_TYPE_ERR: 24\n };\n\n DOMException.prototype.toString = function() {\n return this.message;\n };\n\n api.dom = {\n arrayContains: arrayContains,\n isHtmlNamespace: isHtmlNamespace,\n parentElement: parentElement,\n getNodeIndex: getNodeIndex,\n getNodeLength: getNodeLength,\n getCommonAncestor: getCommonAncestor,\n isAncestorOf: isAncestorOf,\n isOrIsAncestorOf: isOrIsAncestorOf,\n getClosestAncestorIn: getClosestAncestorIn,\n isCharacterDataNode: isCharacterDataNode,\n isTextOrCommentNode: isTextOrCommentNode,\n insertAfter: insertAfter,\n splitDataNode: splitDataNode,\n getDocument: getDocument,\n getWindow: getWindow,\n getIframeWindow: getIframeWindow,\n getIframeDocument: getIframeDocument,\n getBody: getBody,\n isWindow: isWindow,\n getContentDocument: getContentDocument,\n getRootContainer: getRootContainer,\n comparePoints: comparePoints,\n isBrokenNode: isBrokenNode,\n inspectNode: inspectNode,\n getComputedStyleProperty: getComputedStyleProperty,\n createTestElement: createTestElement,\n removeNode: removeNode,\n fragmentFromNodeChildren: fragmentFromNodeChildren,\n createIterator: createIterator,\n DomPosition: DomPosition\n };\n\n api.DOMException = DOMException;\n });\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Pure JavaScript implementation of DOM Range\n api.createCoreModule(\"DomRange\", [\"DomUtil\"], function(api, module) {\n var dom = api.dom;\n var util = api.util;\n var DomPosition = dom.DomPosition;\n var DOMException = api.DOMException;\n\n var isCharacterDataNode = dom.isCharacterDataNode;\n var getNodeIndex = dom.getNodeIndex;\n var isOrIsAncestorOf = dom.isOrIsAncestorOf;\n var getDocument = dom.getDocument;\n var comparePoints = dom.comparePoints;\n var splitDataNode = dom.splitDataNode;\n var getClosestAncestorIn = dom.getClosestAncestorIn;\n var getNodeLength = dom.getNodeLength;\n var arrayContains = dom.arrayContains;\n var getRootContainer = dom.getRootContainer;\n var crashyTextNodes = api.features.crashyTextNodes;\n\n var removeNode = dom.removeNode;\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Utility functions\n\n function isNonTextPartiallySelected(node, range) {\n return (node.nodeType != 3) &&\n (isOrIsAncestorOf(node, range.startContainer) || isOrIsAncestorOf(node, range.endContainer));\n }\n\n function getRangeDocument(range) {\n return range.document || getDocument(range.startContainer);\n }\n\n function getRangeRoot(range) {\n return getRootContainer(range.startContainer);\n }\n\n function getBoundaryBeforeNode(node) {\n return new DomPosition(node.parentNode, getNodeIndex(node));\n }\n\n function getBoundaryAfterNode(node) {\n return new DomPosition(node.parentNode, getNodeIndex(node) + 1);\n }\n\n function insertNodeAtPosition(node, n, o) {\n var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node;\n if (isCharacterDataNode(n)) {\n if (o == n.length) {\n dom.insertAfter(node, n);\n } else {\n n.parentNode.insertBefore(node, o == 0 ? n : splitDataNode(n, o));\n }\n } else if (o >= n.childNodes.length) {\n n.appendChild(node);\n } else {\n n.insertBefore(node, n.childNodes[o]);\n }\n return firstNodeInserted;\n }\n\n function rangesIntersect(rangeA, rangeB, touchingIsIntersecting) {\n assertRangeValid(rangeA);\n assertRangeValid(rangeB);\n\n if (getRangeDocument(rangeB) != getRangeDocument(rangeA)) {\n throw new DOMException(\"WRONG_DOCUMENT_ERR\");\n }\n\n var startComparison = comparePoints(rangeA.startContainer, rangeA.startOffset, rangeB.endContainer, rangeB.endOffset),\n endComparison = comparePoints(rangeA.endContainer, rangeA.endOffset, rangeB.startContainer, rangeB.startOffset);\n\n return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;\n }\n\n function cloneSubtree(iterator) {\n var partiallySelected;\n for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {\n partiallySelected = iterator.isPartiallySelectedSubtree();\n node = node.cloneNode(!partiallySelected);\n if (partiallySelected) {\n subIterator = iterator.getSubtreeIterator();\n node.appendChild(cloneSubtree(subIterator));\n subIterator.detach();\n }\n\n if (node.nodeType == 10) { // DocumentType\n throw new DOMException(\"HIERARCHY_REQUEST_ERR\");\n }\n frag.appendChild(node);\n }\n return frag;\n }\n\n function iterateSubtree(rangeIterator, func, iteratorState) {\n var it, n;\n iteratorState = iteratorState || { stop: false };\n for (var node, subRangeIterator; node = rangeIterator.next(); ) {\n if (rangeIterator.isPartiallySelectedSubtree()) {\n if (func(node) === false) {\n iteratorState.stop = true;\n return;\n } else {\n // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of\n // the node selected by the Range.\n subRangeIterator = rangeIterator.getSubtreeIterator();\n iterateSubtree(subRangeIterator, func, iteratorState);\n subRangeIterator.detach();\n if (iteratorState.stop) {\n return;\n }\n }\n } else {\n // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its\n // descendants\n it = dom.createIterator(node);\n while ( (n = it.next()) ) {\n if (func(n) === false) {\n iteratorState.stop = true;\n return;\n }\n }\n }\n }\n }\n\n function deleteSubtree(iterator) {\n var subIterator;\n while (iterator.next()) {\n if (iterator.isPartiallySelectedSubtree()) {\n subIterator = iterator.getSubtreeIterator();\n deleteSubtree(subIterator);\n subIterator.detach();\n } else {\n iterator.remove();\n }\n }\n }\n\n function extractSubtree(iterator) {\n for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {\n\n if (iterator.isPartiallySelectedSubtree()) {\n node = node.cloneNode(false);\n subIterator = iterator.getSubtreeIterator();\n node.appendChild(extractSubtree(subIterator));\n subIterator.detach();\n } else {\n iterator.remove();\n }\n if (node.nodeType == 10) { // DocumentType\n throw new DOMException(\"HIERARCHY_REQUEST_ERR\");\n }\n frag.appendChild(node);\n }\n return frag;\n }\n\n function getNodesInRange(range, nodeTypes, filter) {\n var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex;\n var filterExists = !!filter;\n if (filterNodeTypes) {\n regex = new RegExp(\"^(\" + nodeTypes.join(\"|\") + \")$\");\n }\n\n var nodes = [];\n iterateSubtree(new RangeIterator(range, false), function(node) {\n if (filterNodeTypes && !regex.test(node.nodeType)) {\n return;\n }\n if (filterExists && !filter(node)) {\n return;\n }\n // Don't include a boundary container if it is a character data node and the range does not contain any\n // of its character data. See issue 190.\n var sc = range.startContainer;\n if (node == sc && isCharacterDataNode(sc) && range.startOffset == sc.length) {\n return;\n }\n\n var ec = range.endContainer;\n if (node == ec && isCharacterDataNode(ec) && range.endOffset == 0) {\n return;\n }\n\n nodes.push(node);\n });\n return nodes;\n }\n\n function inspect(range) {\n var name = (typeof range.getName == \"undefined\") ? \"Range\" : range.getName();\n return \"[\" + name + \"(\" + dom.inspectNode(range.startContainer) + \":\" + range.startOffset + \", \" +\n dom.inspectNode(range.endContainer) + \":\" + range.endOffset + \")]\";\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange)\n\n function RangeIterator(range, clonePartiallySelectedTextNodes) {\n this.range = range;\n this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes;\n\n\n if (!range.collapsed) {\n this.sc = range.startContainer;\n this.so = range.startOffset;\n this.ec = range.endContainer;\n this.eo = range.endOffset;\n var root = range.commonAncestorContainer;\n\n if (this.sc === this.ec && isCharacterDataNode(this.sc)) {\n this.isSingleCharacterDataNode = true;\n this._first = this._last = this._next = this.sc;\n } else {\n this._first = this._next = (this.sc === root && !isCharacterDataNode(this.sc)) ?\n this.sc.childNodes[this.so] : getClosestAncestorIn(this.sc, root, true);\n this._last = (this.ec === root && !isCharacterDataNode(this.ec)) ?\n this.ec.childNodes[this.eo - 1] : getClosestAncestorIn(this.ec, root, true);\n }\n }\n }\n\n RangeIterator.prototype = {\n _current: null,\n _next: null,\n _first: null,\n _last: null,\n isSingleCharacterDataNode: false,\n\n reset: function() {\n this._current = null;\n this._next = this._first;\n },\n\n hasNext: function() {\n return !!this._next;\n },\n\n next: function() {\n // Move to next node\n var current = this._current = this._next;\n if (current) {\n this._next = (current !== this._last) ? current.nextSibling : null;\n\n // Check for partially selected text nodes\n if (isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) {\n if (current === this.ec) {\n (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo);\n }\n if (this._current === this.sc) {\n (current = current.cloneNode(true)).deleteData(0, this.so);\n }\n }\n }\n\n return current;\n },\n\n remove: function() {\n var current = this._current, start, end;\n\n if (isCharacterDataNode(current) && (current === this.sc || current === this.ec)) {\n start = (current === this.sc) ? this.so : 0;\n end = (current === this.ec) ? this.eo : current.length;\n if (start != end) {\n current.deleteData(start, end - start);\n }\n } else {\n if (current.parentNode) {\n removeNode(current);\n } else {\n }\n }\n },\n\n // Checks if the current node is partially selected\n isPartiallySelectedSubtree: function() {\n var current = this._current;\n return isNonTextPartiallySelected(current, this.range);\n },\n\n getSubtreeIterator: function() {\n var subRange;\n if (this.isSingleCharacterDataNode) {\n subRange = this.range.cloneRange();\n subRange.collapse(false);\n } else {\n subRange = new Range(getRangeDocument(this.range));\n var current = this._current;\n var startContainer = current, startOffset = 0, endContainer = current, endOffset = getNodeLength(current);\n\n if (isOrIsAncestorOf(current, this.sc)) {\n startContainer = this.sc;\n startOffset = this.so;\n }\n if (isOrIsAncestorOf(current, this.ec)) {\n endContainer = this.ec;\n endOffset = this.eo;\n }\n\n updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset);\n }\n return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes);\n },\n\n detach: function() {\n this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null;\n }\n };\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10];\n var rootContainerNodeTypes = [2, 9, 11];\n var readonlyNodeTypes = [5, 6, 10, 12];\n var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11];\n var surroundNodeTypes = [1, 3, 4, 5, 7, 8];\n\n function createAncestorFinder(nodeTypes) {\n return function(node, selfIsAncestor) {\n var t, n = selfIsAncestor ? node : node.parentNode;\n while (n) {\n t = n.nodeType;\n if (arrayContains(nodeTypes, t)) {\n return n;\n }\n n = n.parentNode;\n }\n return null;\n };\n }\n\n var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );\n var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);\n var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );\n var getElementAncestor = createAncestorFinder( [1] );\n\n function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {\n if (getDocTypeNotationEntityAncestor(node, allowSelf)) {\n throw new DOMException(\"INVALID_NODE_TYPE_ERR\");\n }\n }\n\n function assertValidNodeType(node, invalidTypes) {\n if (!arrayContains(invalidTypes, node.nodeType)) {\n throw new DOMException(\"INVALID_NODE_TYPE_ERR\");\n }\n }\n\n function assertValidOffset(node, offset) {\n if (offset < 0 || offset > (isCharacterDataNode(node) ? node.length : node.childNodes.length)) {\n throw new DOMException(\"INDEX_SIZE_ERR\");\n }\n }\n\n function assertSameDocumentOrFragment(node1, node2) {\n if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) {\n throw new DOMException(\"WRONG_DOCUMENT_ERR\");\n }\n }\n\n function assertNodeNotReadOnly(node) {\n if (getReadonlyAncestor(node, true)) {\n throw new DOMException(\"NO_MODIFICATION_ALLOWED_ERR\");\n }\n }\n\n function assertNode(node, codeName) {\n if (!node) {\n throw new DOMException(codeName);\n }\n }\n\n function isValidOffset(node, offset) {\n return offset <= (isCharacterDataNode(node) ? node.length : node.childNodes.length);\n }\n\n function isRangeValid(range) {\n return (!!range.startContainer && !!range.endContainer &&\n !(crashyTextNodes && (dom.isBrokenNode(range.startContainer) || dom.isBrokenNode(range.endContainer))) &&\n getRootContainer(range.startContainer) == getRootContainer(range.endContainer) &&\n isValidOffset(range.startContainer, range.startOffset) &&\n isValidOffset(range.endContainer, range.endOffset));\n }\n\n function assertRangeValid(range) {\n if (!isRangeValid(range)) {\n throw new Error(\"Range error: Range is not valid. This usually happens after DOM mutation. Range: (\" + range.inspect() + \")\");\n }\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Test the browser's innerHTML support to decide how to implement createContextualFragment\n var styleEl = document.createElement(\"style\");\n var htmlParsingConforms = false;\n try {\n styleEl.innerHTML = \"x\";\n htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Pre-Blink Opera incorrectly creates an element node\n } catch (e) {\n // IE 6 and 7 throw\n }\n\n api.features.htmlParsingConforms = htmlParsingConforms;\n\n var createContextualFragment = htmlParsingConforms ?\n\n // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See\n // discussion and base code for this implementation at issue 67.\n // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface\n // Thanks to Aleks Williams.\n function(fragmentStr) {\n // \"Let node the context object's start's node.\"\n var node = this.startContainer;\n var doc = getDocument(node);\n\n // \"If the context object's start's node is null, raise an INVALID_STATE_ERR\n // exception and abort these steps.\"\n if (!node) {\n throw new DOMException(\"INVALID_STATE_ERR\");\n }\n\n // \"Let element be as follows, depending on node's interface:\"\n // Document, Document Fragment: null\n var el = null;\n\n // \"Element: node\"\n if (node.nodeType == 1) {\n el = node;\n\n // \"Text, Comment: node's parentElement\"\n } else if (isCharacterDataNode(node)) {\n el = dom.parentElement(node);\n }\n\n // \"If either element is null or element's ownerDocument is an HTML document\n // and element's local name is \"html\" and element's namespace is the HTML\n // namespace\"\n if (el === null || (\n el.nodeName == \"HTML\" &&\n dom.isHtmlNamespace(getDocument(el).documentElement) &&\n dom.isHtmlNamespace(el)\n )) {\n\n // \"let element be a new Element with \"body\" as its local name and the HTML\n // namespace as its namespace.\"\"\n el = doc.createElement(\"body\");\n } else {\n el = el.cloneNode(false);\n }\n\n // \"If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm.\"\n // \"If the node's document is an XML document: Invoke the XML fragment parsing algorithm.\"\n // \"In either case, the algorithm must be invoked with fragment as the input\n // and element as the context element.\"\n el.innerHTML = fragmentStr;\n\n // \"If this raises an exception, then abort these steps. Otherwise, let new\n // children be the nodes returned.\"\n\n // \"Let fragment be a new DocumentFragment.\"\n // \"Append all new children to fragment.\"\n // \"Return fragment.\"\n return dom.fragmentFromNodeChildren(el);\n } :\n\n // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that\n // previous versions of Rangy used (with the exception of using a body element rather than a div)\n function(fragmentStr) {\n var doc = getRangeDocument(this);\n var el = doc.createElement(\"body\");\n el.innerHTML = fragmentStr;\n\n return dom.fragmentFromNodeChildren(el);\n };\n\n function splitRangeBoundaries(range, positionsToPreserve) {\n assertRangeValid(range);\n\n var sc = range.startContainer, so = range.startOffset, ec = range.endContainer, eo = range.endOffset;\n var startEndSame = (sc === ec);\n\n if (isCharacterDataNode(ec) && eo > 0 && eo < ec.length) {\n splitDataNode(ec, eo, positionsToPreserve);\n }\n\n if (isCharacterDataNode(sc) && so > 0 && so < sc.length) {\n sc = splitDataNode(sc, so, positionsToPreserve);\n if (startEndSame) {\n eo -= so;\n ec = sc;\n } else if (ec == sc.parentNode && eo >= getNodeIndex(sc)) {\n eo++;\n }\n so = 0;\n }\n range.setStartAndEnd(sc, so, ec, eo);\n }\n\n function rangeToHtml(range) {\n assertRangeValid(range);\n var container = range.commonAncestorContainer.parentNode.cloneNode(false);\n container.appendChild( range.cloneContents() );\n return container.innerHTML;\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n var rangeProperties = [\"startContainer\", \"startOffset\", \"endContainer\", \"endOffset\", \"collapsed\",\n \"commonAncestorContainer\"];\n\n var s2s = 0, s2e = 1, e2e = 2, e2s = 3;\n var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3;\n\n util.extend(api.rangePrototype, {\n compareBoundaryPoints: function(how, range) {\n assertRangeValid(this);\n assertSameDocumentOrFragment(this.startContainer, range.startContainer);\n\n var nodeA, offsetA, nodeB, offsetB;\n var prefixA = (how == e2s || how == s2s) ? \"start\" : \"end\";\n var prefixB = (how == s2e || how == s2s) ? \"start\" : \"end\";\n nodeA = this[prefixA + \"Container\"];\n offsetA = this[prefixA + \"Offset\"];\n nodeB = range[prefixB + \"Container\"];\n offsetB = range[prefixB + \"Offset\"];\n return comparePoints(nodeA, offsetA, nodeB, offsetB);\n },\n\n insertNode: function(node) {\n assertRangeValid(this);\n assertValidNodeType(node, insertableNodeTypes);\n assertNodeNotReadOnly(this.startContainer);\n\n if (isOrIsAncestorOf(node, this.startContainer)) {\n throw new DOMException(\"HIERARCHY_REQUEST_ERR\");\n }\n\n // No check for whether the container of the start of the Range is of a type that does not allow\n // children of the type of node: the browser's DOM implementation should do this for us when we attempt\n // to add the node\n\n var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset);\n this.setStartBefore(firstNodeInserted);\n },\n\n cloneContents: function() {\n assertRangeValid(this);\n\n var clone, frag;\n if (this.collapsed) {\n return getRangeDocument(this).createDocumentFragment();\n } else {\n if (this.startContainer === this.endContainer && isCharacterDataNode(this.startContainer)) {\n clone = this.startContainer.cloneNode(true);\n clone.data = clone.data.slice(this.startOffset, this.endOffset);\n frag = getRangeDocument(this).createDocumentFragment();\n frag.appendChild(clone);\n return frag;\n } else {\n var iterator = new RangeIterator(this, true);\n clone = cloneSubtree(iterator);\n iterator.detach();\n }\n return clone;\n }\n },\n\n canSurroundContents: function() {\n assertRangeValid(this);\n assertNodeNotReadOnly(this.startContainer);\n assertNodeNotReadOnly(this.endContainer);\n\n // Check if the contents can be surrounded. Specifically, this means whether the range partially selects\n // no non-text nodes.\n var iterator = new RangeIterator(this, true);\n var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||\n (iterator._last && isNonTextPartiallySelected(iterator._last, this)));\n iterator.detach();\n return !boundariesInvalid;\n },\n\n surroundContents: function(node) {\n assertValidNodeType(node, surroundNodeTypes);\n\n if (!this.canSurroundContents()) {\n throw new DOMException(\"INVALID_STATE_ERR\");\n }\n\n // Extract the contents\n var content = this.extractContents();\n\n // Clear the children of the node\n if (node.hasChildNodes()) {\n while (node.lastChild) {\n node.removeChild(node.lastChild);\n }\n }\n\n // Insert the new node and add the extracted contents\n insertNodeAtPosition(node, this.startContainer, this.startOffset);\n node.appendChild(content);\n\n this.selectNode(node);\n },\n\n cloneRange: function() {\n assertRangeValid(this);\n var range = new Range(getRangeDocument(this));\n var i = rangeProperties.length, prop;\n while (i--) {\n prop = rangeProperties[i];\n range[prop] = this[prop];\n }\n return range;\n },\n\n toString: function() {\n assertRangeValid(this);\n var sc = this.startContainer;\n if (sc === this.endContainer && isCharacterDataNode(sc)) {\n return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : \"\";\n } else {\n var textParts = [], iterator = new RangeIterator(this, true);\n iterateSubtree(iterator, function(node) {\n // Accept only text or CDATA nodes, not comments\n if (node.nodeType == 3 || node.nodeType == 4) {\n textParts.push(node.data);\n }\n });\n iterator.detach();\n return textParts.join(\"\");\n }\n },\n\n // The methods below are all non-standard. The following batch were introduced by Mozilla but have since\n // been removed from Mozilla.\n\n compareNode: function(node) {\n assertRangeValid(this);\n\n var parent = node.parentNode;\n var nodeIndex = getNodeIndex(node);\n\n if (!parent) {\n throw new DOMException(\"NOT_FOUND_ERR\");\n }\n\n var startComparison = this.comparePoint(parent, nodeIndex),\n endComparison = this.comparePoint(parent, nodeIndex + 1);\n\n if (startComparison < 0) { // Node starts before\n return (endComparison > 0) ? n_b_a : n_b;\n } else {\n return (endComparison > 0) ? n_a : n_i;\n }\n },\n\n comparePoint: function(node, offset) {\n assertRangeValid(this);\n assertNode(node, \"HIERARCHY_REQUEST_ERR\");\n assertSameDocumentOrFragment(node, this.startContainer);\n\n if (comparePoints(node, offset, this.startContainer, this.startOffset) < 0) {\n return -1;\n } else if (comparePoints(node, offset, this.endContainer, this.endOffset) > 0) {\n return 1;\n }\n return 0;\n },\n\n createContextualFragment: createContextualFragment,\n\n toHtml: function() {\n return rangeToHtml(this);\n },\n\n // touchingIsIntersecting determines whether this method considers a node that borders a range intersects\n // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default)\n intersectsNode: function(node, touchingIsIntersecting) {\n assertRangeValid(this);\n if (getRootContainer(node) != getRangeRoot(this)) {\n return false;\n }\n\n var parent = node.parentNode, offset = getNodeIndex(node);\n if (!parent) {\n return true;\n }\n\n var startComparison = comparePoints(parent, offset, this.endContainer, this.endOffset),\n endComparison = comparePoints(parent, offset + 1, this.startContainer, this.startOffset);\n\n return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;\n },\n\n isPointInRange: function(node, offset) {\n assertRangeValid(this);\n assertNode(node, \"HIERARCHY_REQUEST_ERR\");\n assertSameDocumentOrFragment(node, this.startContainer);\n\n return (comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) &&\n (comparePoints(node, offset, this.endContainer, this.endOffset) <= 0);\n },\n\n // The methods below are non-standard and invented by me.\n\n // Sharing a boundary start-to-end or end-to-start does not count as intersection.\n intersectsRange: function(range) {\n return rangesIntersect(this, range, false);\n },\n\n // Sharing a boundary start-to-end or end-to-start does count as intersection.\n intersectsOrTouchesRange: function(range) {\n return rangesIntersect(this, range, true);\n },\n\n intersection: function(range) {\n if (this.intersectsRange(range)) {\n var startComparison = comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset),\n endComparison = comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset);\n\n var intersectionRange = this.cloneRange();\n if (startComparison == -1) {\n intersectionRange.setStart(range.startContainer, range.startOffset);\n }\n if (endComparison == 1) {\n intersectionRange.setEnd(range.endContainer, range.endOffset);\n }\n return intersectionRange;\n }\n return null;\n },\n\n union: function(range) {\n if (this.intersectsOrTouchesRange(range)) {\n var unionRange = this.cloneRange();\n if (comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) {\n unionRange.setStart(range.startContainer, range.startOffset);\n }\n if (comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) {\n unionRange.setEnd(range.endContainer, range.endOffset);\n }\n return unionRange;\n } else {\n throw new DOMException(\"Ranges do not intersect\");\n }\n },\n\n containsNode: function(node, allowPartial) {\n if (allowPartial) {\n return this.intersectsNode(node, false);\n } else {\n return this.compareNode(node) == n_i;\n }\n },\n\n containsNodeContents: function(node) {\n return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, getNodeLength(node)) <= 0;\n },\n\n containsRange: function(range) {\n var intersection = this.intersection(range);\n return intersection !== null && range.equals(intersection);\n },\n\n containsNodeText: function(node) {\n var nodeRange = this.cloneRange();\n nodeRange.selectNode(node);\n var textNodes = nodeRange.getNodes([3]);\n if (textNodes.length > 0) {\n nodeRange.setStart(textNodes[0], 0);\n var lastTextNode = textNodes.pop();\n nodeRange.setEnd(lastTextNode, lastTextNode.length);\n return this.containsRange(nodeRange);\n } else {\n return this.containsNodeContents(node);\n }\n },\n\n getNodes: function(nodeTypes, filter) {\n assertRangeValid(this);\n return getNodesInRange(this, nodeTypes, filter);\n },\n\n getDocument: function() {\n return getRangeDocument(this);\n },\n\n collapseBefore: function(node) {\n this.setEndBefore(node);\n this.collapse(false);\n },\n\n collapseAfter: function(node) {\n this.setStartAfter(node);\n this.collapse(true);\n },\n\n getBookmark: function(containerNode) {\n var doc = getRangeDocument(this);\n var preSelectionRange = api.createRange(doc);\n containerNode = containerNode || dom.getBody(doc);\n preSelectionRange.selectNodeContents(containerNode);\n var range = this.intersection(preSelectionRange);\n var start = 0, end = 0;\n if (range) {\n preSelectionRange.setEnd(range.startContainer, range.startOffset);\n start = preSelectionRange.toString().length;\n end = start + range.toString().length;\n }\n\n return {\n start: start,\n end: end,\n containerNode: containerNode\n };\n },\n\n moveToBookmark: function(bookmark) {\n var containerNode = bookmark.containerNode;\n var charIndex = 0;\n this.setStart(containerNode, 0);\n this.collapse(true);\n var nodeStack = [containerNode], node, foundStart = false, stop = false;\n var nextCharIndex, i, childNodes;\n\n while (!stop && (node = nodeStack.pop())) {\n if (node.nodeType == 3) {\n nextCharIndex = charIndex + node.length;\n if (!foundStart && bookmark.start >= charIndex && bookmark.start <= nextCharIndex) {\n this.setStart(node, bookmark.start - charIndex);\n foundStart = true;\n }\n if (foundStart && bookmark.end >= charIndex && bookmark.end <= nextCharIndex) {\n this.setEnd(node, bookmark.end - charIndex);\n stop = true;\n }\n charIndex = nextCharIndex;\n } else {\n childNodes = node.childNodes;\n i = childNodes.length;\n while (i--) {\n nodeStack.push(childNodes[i]);\n }\n }\n }\n },\n\n getName: function() {\n return \"DomRange\";\n },\n\n equals: function(range) {\n return Range.rangesEqual(this, range);\n },\n\n isValid: function() {\n return isRangeValid(this);\n },\n\n inspect: function() {\n return inspect(this);\n },\n\n detach: function() {\n // In DOM4, detach() is now a no-op.\n }\n });\n\n function copyComparisonConstantsToObject(obj) {\n obj.START_TO_START = s2s;\n obj.START_TO_END = s2e;\n obj.END_TO_END = e2e;\n obj.END_TO_START = e2s;\n\n obj.NODE_BEFORE = n_b;\n obj.NODE_AFTER = n_a;\n obj.NODE_BEFORE_AND_AFTER = n_b_a;\n obj.NODE_INSIDE = n_i;\n }\n\n function copyComparisonConstants(constructor) {\n copyComparisonConstantsToObject(constructor);\n copyComparisonConstantsToObject(constructor.prototype);\n }\n\n function createRangeContentRemover(remover, boundaryUpdater) {\n return function() {\n assertRangeValid(this);\n\n var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer;\n\n var iterator = new RangeIterator(this, true);\n\n // Work out where to position the range after content removal\n var node, boundary;\n if (sc !== root) {\n node = getClosestAncestorIn(sc, root, true);\n boundary = getBoundaryAfterNode(node);\n sc = boundary.node;\n so = boundary.offset;\n }\n\n // Check none of the range is read-only\n iterateSubtree(iterator, assertNodeNotReadOnly);\n\n iterator.reset();\n\n // Remove the content\n var returnValue = remover(iterator);\n iterator.detach();\n\n // Move to the new position\n boundaryUpdater(this, sc, so, sc, so);\n\n return returnValue;\n };\n }\n\n function createPrototypeRange(constructor, boundaryUpdater) {\n function createBeforeAfterNodeSetter(isBefore, isStart) {\n return function(node) {\n assertValidNodeType(node, beforeAfterNodeTypes);\n assertValidNodeType(getRootContainer(node), rootContainerNodeTypes);\n\n var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node);\n (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset);\n };\n }\n\n function setRangeStart(range, node, offset) {\n var ec = range.endContainer, eo = range.endOffset;\n if (node !== range.startContainer || offset !== range.startOffset) {\n // Check the root containers of the range and the new boundary, and also check whether the new boundary\n // is after the current end. In either case, collapse the range to the new position\n if (getRootContainer(node) != getRootContainer(ec) || comparePoints(node, offset, ec, eo) == 1) {\n ec = node;\n eo = offset;\n }\n boundaryUpdater(range, node, offset, ec, eo);\n }\n }\n\n function setRangeEnd(range, node, offset) {\n var sc = range.startContainer, so = range.startOffset;\n if (node !== range.endContainer || offset !== range.endOffset) {\n // Check the root containers of the range and the new boundary, and also check whether the new boundary\n // is after the current end. In either case, collapse the range to the new position\n if (getRootContainer(node) != getRootContainer(sc) || comparePoints(node, offset, sc, so) == -1) {\n sc = node;\n so = offset;\n }\n boundaryUpdater(range, sc, so, node, offset);\n }\n }\n\n // Set up inheritance\n var F = function() {};\n F.prototype = api.rangePrototype;\n constructor.prototype = new F();\n\n util.extend(constructor.prototype, {\n setStart: function(node, offset) {\n assertNoDocTypeNotationEntityAncestor(node, true);\n assertValidOffset(node, offset);\n\n setRangeStart(this, node, offset);\n },\n\n setEnd: function(node, offset) {\n assertNoDocTypeNotationEntityAncestor(node, true);\n assertValidOffset(node, offset);\n\n setRangeEnd(this, node, offset);\n },\n\n /**\n * Convenience method to set a range's start and end boundaries. Overloaded as follows:\n * - Two parameters (node, offset) creates a collapsed range at that position\n * - Three parameters (node, startOffset, endOffset) creates a range contained with node starting at\n * startOffset and ending at endOffset\n * - Four parameters (startNode, startOffset, endNode, endOffset) creates a range starting at startOffset in\n * startNode and ending at endOffset in endNode\n */\n setStartAndEnd: function() {\n var args = arguments;\n var sc = args[0], so = args[1], ec = sc, eo = so;\n\n switch (args.length) {\n case 3:\n eo = args[2];\n break;\n case 4:\n ec = args[2];\n eo = args[3];\n break;\n }\n\n assertNoDocTypeNotationEntityAncestor(sc, true);\n assertValidOffset(sc, so);\n\n assertNoDocTypeNotationEntityAncestor(ec, true);\n assertValidOffset(ec, eo);\n\n boundaryUpdater(this, sc, so, ec, eo);\n },\n\n setBoundary: function(node, offset, isStart) {\n this[\"set\" + (isStart ? \"Start\" : \"End\")](node, offset);\n },\n\n setStartBefore: createBeforeAfterNodeSetter(true, true),\n setStartAfter: createBeforeAfterNodeSetter(false, true),\n setEndBefore: createBeforeAfterNodeSetter(true, false),\n setEndAfter: createBeforeAfterNodeSetter(false, false),\n\n collapse: function(isStart) {\n assertRangeValid(this);\n if (isStart) {\n boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset);\n } else {\n boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset);\n }\n },\n\n selectNodeContents: function(node) {\n assertNoDocTypeNotationEntityAncestor(node, true);\n\n boundaryUpdater(this, node, 0, node, getNodeLength(node));\n },\n\n selectNode: function(node) {\n assertNoDocTypeNotationEntityAncestor(node, false);\n assertValidNodeType(node, beforeAfterNodeTypes);\n\n var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node);\n boundaryUpdater(this, start.node, start.offset, end.node, end.offset);\n },\n\n extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater),\n\n deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater),\n\n canSurroundContents: function() {\n assertRangeValid(this);\n assertNodeNotReadOnly(this.startContainer);\n assertNodeNotReadOnly(this.endContainer);\n\n // Check if the contents can be surrounded. Specifically, this means whether the range partially selects\n // no non-text nodes.\n var iterator = new RangeIterator(this, true);\n var boundariesInvalid = (iterator._first && isNonTextPartiallySelected(iterator._first, this) ||\n (iterator._last && isNonTextPartiallySelected(iterator._last, this)));\n iterator.detach();\n return !boundariesInvalid;\n },\n\n splitBoundaries: function() {\n splitRangeBoundaries(this);\n },\n\n splitBoundariesPreservingPositions: function(positionsToPreserve) {\n splitRangeBoundaries(this, positionsToPreserve);\n },\n\n normalizeBoundaries: function() {\n assertRangeValid(this);\n\n var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;\n\n var mergeForward = function(node) {\n var sibling = node.nextSibling;\n if (sibling && sibling.nodeType == node.nodeType) {\n ec = node;\n eo = node.length;\n node.appendData(sibling.data);\n removeNode(sibling);\n }\n };\n\n var mergeBackward = function(node) {\n var sibling = node.previousSibling;\n if (sibling && sibling.nodeType == node.nodeType) {\n sc = node;\n var nodeLength = node.length;\n so = sibling.length;\n node.insertData(0, sibling.data);\n removeNode(sibling);\n if (sc == ec) {\n eo += so;\n ec = sc;\n } else if (ec == node.parentNode) {\n var nodeIndex = getNodeIndex(node);\n if (eo == nodeIndex) {\n ec = node;\n eo = nodeLength;\n } else if (eo > nodeIndex) {\n eo--;\n }\n }\n }\n };\n\n var normalizeStart = true;\n var sibling;\n\n if (isCharacterDataNode(ec)) {\n if (eo == ec.length) {\n mergeForward(ec);\n } else if (eo == 0) {\n sibling = ec.previousSibling;\n if (sibling && sibling.nodeType == ec.nodeType) {\n eo = sibling.length;\n if (sc == ec) {\n normalizeStart = false;\n }\n sibling.appendData(ec.data);\n removeNode(ec);\n ec = sibling;\n }\n }\n } else {\n if (eo > 0) {\n var endNode = ec.childNodes[eo - 1];\n if (endNode && isCharacterDataNode(endNode)) {\n mergeForward(endNode);\n }\n }\n normalizeStart = !this.collapsed;\n }\n\n if (normalizeStart) {\n if (isCharacterDataNode(sc)) {\n if (so == 0) {\n mergeBackward(sc);\n } else if (so == sc.length) {\n sibling = sc.nextSibling;\n if (sibling && sibling.nodeType == sc.nodeType) {\n if (ec == sibling) {\n ec = sc;\n eo += sc.length;\n }\n sc.appendData(sibling.data);\n removeNode(sibling);\n }\n }\n } else {\n if (so < sc.childNodes.length) {\n var startNode = sc.childNodes[so];\n if (startNode && isCharacterDataNode(startNode)) {\n mergeBackward(startNode);\n }\n }\n }\n } else {\n sc = ec;\n so = eo;\n }\n\n boundaryUpdater(this, sc, so, ec, eo);\n },\n\n collapseToPoint: function(node, offset) {\n assertNoDocTypeNotationEntityAncestor(node, true);\n assertValidOffset(node, offset);\n this.setStartAndEnd(node, offset);\n },\n\n parentElement: function() {\n assertRangeValid(this);\n var parentNode = this.commonAncestorContainer;\n return parentNode ? getElementAncestor(this.commonAncestorContainer, true) : null;\n }\n });\n\n copyComparisonConstants(constructor);\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Updates commonAncestorContainer and collapsed after boundary change\n function updateCollapsedAndCommonAncestor(range) {\n range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);\n range.commonAncestorContainer = range.collapsed ?\n range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer);\n }\n\n function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) {\n range.startContainer = startContainer;\n range.startOffset = startOffset;\n range.endContainer = endContainer;\n range.endOffset = endOffset;\n range.document = dom.getDocument(startContainer);\n updateCollapsedAndCommonAncestor(range);\n }\n\n function Range(doc) {\n updateBoundaries(this, doc, 0, doc, 0);\n }\n\n createPrototypeRange(Range, updateBoundaries);\n\n util.extend(Range, {\n rangeProperties: rangeProperties,\n RangeIterator: RangeIterator,\n copyComparisonConstants: copyComparisonConstants,\n createPrototypeRange: createPrototypeRange,\n inspect: inspect,\n toHtml: rangeToHtml,\n getRangeDocument: getRangeDocument,\n rangesEqual: function(r1, r2) {\n return r1.startContainer === r2.startContainer &&\n r1.startOffset === r2.startOffset &&\n r1.endContainer === r2.endContainer &&\n r1.endOffset === r2.endOffset;\n }\n });\n\n api.DomRange = Range;\n });\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Wrappers for the browser's native DOM Range and/or TextRange implementation\n api.createCoreModule(\"WrappedRange\", [\"DomRange\"], function(api, module) {\n var WrappedRange, WrappedTextRange;\n var dom = api.dom;\n var util = api.util;\n var DomPosition = dom.DomPosition;\n var DomRange = api.DomRange;\n var getBody = dom.getBody;\n var getContentDocument = dom.getContentDocument;\n var isCharacterDataNode = dom.isCharacterDataNode;\n\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n if (api.features.implementsDomRange) {\n // This is a wrapper around the browser's native DOM Range. It has two aims:\n // - Provide workarounds for specific browser bugs\n // - provide convenient extensions, which are inherited from Rangy's DomRange\n\n (function() {\n var rangeProto;\n var rangeProperties = DomRange.rangeProperties;\n\n function updateRangeProperties(range) {\n var i = rangeProperties.length, prop;\n while (i--) {\n prop = rangeProperties[i];\n range[prop] = range.nativeRange[prop];\n }\n // Fix for broken collapsed property in IE 9.\n range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);\n }\n\n function updateNativeRange(range, startContainer, startOffset, endContainer, endOffset) {\n var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset);\n var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset);\n var nativeRangeDifferent = !range.equals(range.nativeRange);\n\n // Always set both boundaries for the benefit of IE9 (see issue 35)\n if (startMoved || endMoved || nativeRangeDifferent) {\n range.setEnd(endContainer, endOffset);\n range.setStart(startContainer, startOffset);\n }\n }\n\n var createBeforeAfterNodeSetter;\n\n WrappedRange = function(range) {\n if (!range) {\n throw module.createError(\"WrappedRange: Range must be specified\");\n }\n this.nativeRange = range;\n updateRangeProperties(this);\n };\n\n DomRange.createPrototypeRange(WrappedRange, updateNativeRange);\n\n rangeProto = WrappedRange.prototype;\n\n rangeProto.selectNode = function(node) {\n this.nativeRange.selectNode(node);\n updateRangeProperties(this);\n };\n\n rangeProto.cloneContents = function() {\n return this.nativeRange.cloneContents();\n };\n\n // Due to a long-standing Firefox bug that I have not been able to find a reliable way to detect,\n // insertNode() is never delegated to the native range.\n\n rangeProto.surroundContents = function(node) {\n this.nativeRange.surroundContents(node);\n updateRangeProperties(this);\n };\n\n rangeProto.collapse = function(isStart) {\n this.nativeRange.collapse(isStart);\n updateRangeProperties(this);\n };\n\n rangeProto.cloneRange = function() {\n return new WrappedRange(this.nativeRange.cloneRange());\n };\n\n rangeProto.refresh = function() {\n updateRangeProperties(this);\n };\n\n rangeProto.toString = function() {\n return this.nativeRange.toString();\n };\n\n // Create test range and node for feature detection\n\n var testTextNode = document.createTextNode(\"test\");\n getBody(document).appendChild(testTextNode);\n var range = document.createRange();\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and\n // correct for it\n\n range.setStart(testTextNode, 0);\n range.setEnd(testTextNode, 0);\n\n try {\n range.setStart(testTextNode, 1);\n\n rangeProto.setStart = function(node, offset) {\n this.nativeRange.setStart(node, offset);\n updateRangeProperties(this);\n };\n\n rangeProto.setEnd = function(node, offset) {\n this.nativeRange.setEnd(node, offset);\n updateRangeProperties(this);\n };\n\n createBeforeAfterNodeSetter = function(name) {\n return function(node) {\n this.nativeRange[name](node);\n updateRangeProperties(this);\n };\n };\n\n } catch(ex) {\n\n rangeProto.setStart = function(node, offset) {\n try {\n this.nativeRange.setStart(node, offset);\n } catch (ex) {\n this.nativeRange.setEnd(node, offset);\n this.nativeRange.setStart(node, offset);\n }\n updateRangeProperties(this);\n };\n\n rangeProto.setEnd = function(node, offset) {\n try {\n this.nativeRange.setEnd(node, offset);\n } catch (ex) {\n this.nativeRange.setStart(node, offset);\n this.nativeRange.setEnd(node, offset);\n }\n updateRangeProperties(this);\n };\n\n createBeforeAfterNodeSetter = function(name, oppositeName) {\n return function(node) {\n try {\n this.nativeRange[name](node);\n } catch (ex) {\n this.nativeRange[oppositeName](node);\n this.nativeRange[name](node);\n }\n updateRangeProperties(this);\n };\n };\n }\n\n rangeProto.setStartBefore = createBeforeAfterNodeSetter(\"setStartBefore\", \"setEndBefore\");\n rangeProto.setStartAfter = createBeforeAfterNodeSetter(\"setStartAfter\", \"setEndAfter\");\n rangeProto.setEndBefore = createBeforeAfterNodeSetter(\"setEndBefore\", \"setStartBefore\");\n rangeProto.setEndAfter = createBeforeAfterNodeSetter(\"setEndAfter\", \"setStartAfter\");\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Always use DOM4-compliant selectNodeContents implementation: it's simpler and less code than testing\n // whether the native implementation can be trusted\n rangeProto.selectNodeContents = function(node) {\n this.setStartAndEnd(node, 0, dom.getNodeLength(node));\n };\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Test for and correct WebKit bug that has the behaviour of compareBoundaryPoints round the wrong way for\n // constants START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738\n\n range.selectNodeContents(testTextNode);\n range.setEnd(testTextNode, 3);\n\n var range2 = document.createRange();\n range2.selectNodeContents(testTextNode);\n range2.setEnd(testTextNode, 4);\n range2.setStart(testTextNode, 2);\n\n if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 &&\n range.compareBoundaryPoints(range.END_TO_START, range2) == 1) {\n // This is the wrong way round, so correct for it\n\n rangeProto.compareBoundaryPoints = function(type, range) {\n range = range.nativeRange || range;\n if (type == range.START_TO_END) {\n type = range.END_TO_START;\n } else if (type == range.END_TO_START) {\n type = range.START_TO_END;\n }\n return this.nativeRange.compareBoundaryPoints(type, range);\n };\n } else {\n rangeProto.compareBoundaryPoints = function(type, range) {\n return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range);\n };\n }\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Test for IE deleteContents() and extractContents() bug and correct it. See issue 107.\n\n var el = document.createElement(\"div\");\n el.innerHTML = \"123\";\n var textNode = el.firstChild;\n var body = getBody(document);\n body.appendChild(el);\n\n range.setStart(textNode, 1);\n range.setEnd(textNode, 2);\n range.deleteContents();\n\n if (textNode.data == \"13\") {\n // Behaviour is correct per DOM4 Range so wrap the browser's implementation of deleteContents() and\n // extractContents()\n rangeProto.deleteContents = function() {\n this.nativeRange.deleteContents();\n updateRangeProperties(this);\n };\n\n rangeProto.extractContents = function() {\n var frag = this.nativeRange.extractContents();\n updateRangeProperties(this);\n return frag;\n };\n } else {\n }\n\n body.removeChild(el);\n body = null;\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Test for existence of createContextualFragment and delegate to it if it exists\n if (util.isHostMethod(range, \"createContextualFragment\")) {\n rangeProto.createContextualFragment = function(fragmentStr) {\n return this.nativeRange.createContextualFragment(fragmentStr);\n };\n }\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Clean up\n getBody(document).removeChild(testTextNode);\n\n rangeProto.getName = function() {\n return \"WrappedRange\";\n };\n\n api.WrappedRange = WrappedRange;\n\n api.createNativeRange = function(doc) {\n doc = getContentDocument(doc, module, \"createNativeRange\");\n return doc.createRange();\n };\n })();\n }\n\n if (api.features.implementsTextRange) {\n /*\n This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement()\n method. For example, in the following (where pipes denote the selection boundaries):\n\n
  • | a
  • b |
\n\n var range = document.selection.createRange();\n alert(range.parentElement().id); // Should alert \"ul\" but alerts \"b\"\n\n This method returns the common ancestor node of the following:\n - the parentElement() of the textRange\n - the parentElement() of the textRange after calling collapse(true)\n - the parentElement() of the textRange after calling collapse(false)\n */\n var getTextRangeContainerElement = function(textRange) {\n var parentEl = textRange.parentElement();\n var range = textRange.duplicate();\n range.collapse(true);\n var startEl = range.parentElement();\n range = textRange.duplicate();\n range.collapse(false);\n var endEl = range.parentElement();\n var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl);\n\n return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);\n };\n\n var textRangeIsCollapsed = function(textRange) {\n return textRange.compareEndPoints(\"StartToEnd\", textRange) == 0;\n };\n\n // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started\n // out as an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/)\n // but has grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange\n // bugs, handling for inputs and images, plus optimizations.\n var getTextRangeBoundaryPosition = function(textRange, wholeRangeContainerElement, isStart, isCollapsed, startInfo) {\n var workingRange = textRange.duplicate();\n workingRange.collapse(isStart);\n var containerElement = workingRange.parentElement();\n\n // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so\n // check for that\n if (!dom.isOrIsAncestorOf(wholeRangeContainerElement, containerElement)) {\n containerElement = wholeRangeContainerElement;\n }\n\n\n // Deal with nodes that cannot \"contain rich HTML markup\". In practice, this means form inputs, images and\n // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx\n if (!containerElement.canHaveHTML) {\n var pos = new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement));\n return {\n boundaryPosition: pos,\n nodeInfo: {\n nodeIndex: pos.offset,\n containerElement: pos.node\n }\n };\n }\n\n var workingNode = dom.getDocument(containerElement).createElement(\"span\");\n\n // Workaround for HTML5 Shiv's insane violation of document.createElement(). See Rangy issue 104 and HTML5\n // Shiv issue 64: https://github.com/aFarkas/html5shiv/issues/64\n if (workingNode.parentNode) {\n dom.removeNode(workingNode);\n }\n\n var comparison, workingComparisonType = isStart ? \"StartToStart\" : \"StartToEnd\";\n var previousNode, nextNode, boundaryPosition, boundaryNode;\n var start = (startInfo && startInfo.containerElement == containerElement) ? startInfo.nodeIndex : 0;\n var childNodeCount = containerElement.childNodes.length;\n var end = childNodeCount;\n\n // Check end first. Code within the loop assumes that the endth child node of the container is definitely\n // after the range boundary.\n var nodeIndex = end;\n\n while (true) {\n if (nodeIndex == childNodeCount) {\n containerElement.appendChild(workingNode);\n } else {\n containerElement.insertBefore(workingNode, containerElement.childNodes[nodeIndex]);\n }\n workingRange.moveToElementText(workingNode);\n comparison = workingRange.compareEndPoints(workingComparisonType, textRange);\n if (comparison == 0 || start == end) {\n break;\n } else if (comparison == -1) {\n if (end == start + 1) {\n // We know the endth child node is after the range boundary, so we must be done.\n break;\n } else {\n start = nodeIndex;\n }\n } else {\n end = (end == start + 1) ? start : nodeIndex;\n }\n nodeIndex = Math.floor((start + end) / 2);\n containerElement.removeChild(workingNode);\n }\n\n\n // We've now reached or gone past the boundary of the text range we're interested in\n // so have identified the node we want\n boundaryNode = workingNode.nextSibling;\n\n if (comparison == -1 && boundaryNode && isCharacterDataNode(boundaryNode)) {\n // This is a character data node (text, comment, cdata). The working range is collapsed at the start of\n // the node containing the text range's boundary, so we move the end of the working range to the\n // boundary point and measure the length of its text to get the boundary's offset within the node.\n workingRange.setEndPoint(isStart ? \"EndToStart\" : \"EndToEnd\", textRange);\n\n var offset;\n\n if (/[\\r\\n]/.test(boundaryNode.data)) {\n /*\n For the particular case of a boundary within a text node containing rendered line breaks (within a\n
 element, for example), we need a slightly complicated approach to get the boundary's offset in\n                        IE. The facts:\n\n                        - Each line break is represented as \\r in the text node's data/nodeValue properties\n                        - Each line break is represented as \\r\\n in the TextRange's 'text' property\n                        - The 'text' property of the TextRange does not contain trailing line breaks\n\n                        To get round the problem presented by the final fact above, we can use the fact that TextRange's\n                        moveStart() and moveEnd() methods return the actual number of characters moved, which is not\n                        necessarily the same as the number of characters it was instructed to move. The simplest approach is\n                        to use this to store the characters moved when moving both the start and end of the range to the\n                        start of the document body and subtracting the start offset from the end offset (the\n                        \"move-negative-gazillion\" method). However, this is extremely slow when the document is large and\n                        the range is near the end of it. Clearly doing the mirror image (i.e. moving the range boundaries to\n                        the end of the document) has the same problem.\n\n                        Another approach that works is to use moveStart() to move the start boundary of the range up to the\n                        end boundary one character at a time and incrementing a counter with the value returned by the\n                        moveStart() call. However, the check for whether the start boundary has reached the end boundary is\n                        expensive, so this method is slow (although unlike \"move-negative-gazillion\" is largely unaffected\n                        by the location of the range within the document).\n\n                        The approach used below is a hybrid of the two methods above. It uses the fact that a string\n                        containing the TextRange's 'text' property with each \\r\\n converted to a single \\r character cannot\n                        be longer than the text of the TextRange, so the start of the range is moved that length initially\n                        and then a character at a time to make up for any trailing line breaks not contained in the 'text'\n                        property. This has good performance in most situations compared to the previous two methods.\n                        */\n                        var tempRange = workingRange.duplicate();\n                        var rangeLength = tempRange.text.replace(/\\r\\n/g, \"\\r\").length;\n\n                        offset = tempRange.moveStart(\"character\", rangeLength);\n                        while ( (comparison = tempRange.compareEndPoints(\"StartToEnd\", tempRange)) == -1) {\n                            offset++;\n                            tempRange.moveStart(\"character\", 1);\n                        }\n                    } else {\n                        offset = workingRange.text.length;\n                    }\n                    boundaryPosition = new DomPosition(boundaryNode, offset);\n                } else {\n\n                    // If the boundary immediately follows a character data node and this is the end boundary, we should favour\n                    // a position within that, and likewise for a start boundary preceding a character data node\n                    previousNode = (isCollapsed || !isStart) && workingNode.previousSibling;\n                    nextNode = (isCollapsed || isStart) && workingNode.nextSibling;\n                    if (nextNode && isCharacterDataNode(nextNode)) {\n                        boundaryPosition = new DomPosition(nextNode, 0);\n                    } else if (previousNode && isCharacterDataNode(previousNode)) {\n                        boundaryPosition = new DomPosition(previousNode, previousNode.data.length);\n                    } else {\n                        boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode));\n                    }\n                }\n\n                // Clean up\n                dom.removeNode(workingNode);\n\n                return {\n                    boundaryPosition: boundaryPosition,\n                    nodeInfo: {\n                        nodeIndex: nodeIndex,\n                        containerElement: containerElement\n                    }\n                };\n            };\n\n            // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that\n            // node. This function started out as an optimized version of code found in Tim Cameron Ryan's IERange\n            // (http://code.google.com/p/ierange/)\n            var createBoundaryTextRange = function(boundaryPosition, isStart) {\n                var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset;\n                var doc = dom.getDocument(boundaryPosition.node);\n                var workingNode, childNodes, workingRange = getBody(doc).createTextRange();\n                var nodeIsDataNode = isCharacterDataNode(boundaryPosition.node);\n\n                if (nodeIsDataNode) {\n                    boundaryNode = boundaryPosition.node;\n                    boundaryParent = boundaryNode.parentNode;\n                } else {\n                    childNodes = boundaryPosition.node.childNodes;\n                    boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null;\n                    boundaryParent = boundaryPosition.node;\n                }\n\n                // Position the range immediately before the node containing the boundary\n                workingNode = doc.createElement(\"span\");\n\n                // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within\n                // the element rather than immediately before or after it\n                workingNode.innerHTML = \"&#feff;\";\n\n                // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report\n                // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12\n                if (boundaryNode) {\n                    boundaryParent.insertBefore(workingNode, boundaryNode);\n                } else {\n                    boundaryParent.appendChild(workingNode);\n                }\n\n                workingRange.moveToElementText(workingNode);\n                workingRange.collapse(!isStart);\n\n                // Clean up\n                boundaryParent.removeChild(workingNode);\n\n                // Move the working range to the text offset, if required\n                if (nodeIsDataNode) {\n                    workingRange[isStart ? \"moveStart\" : \"moveEnd\"](\"character\", boundaryOffset);\n                }\n\n                return workingRange;\n            };\n\n            /*------------------------------------------------------------------------------------------------------------*/\n\n            // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a\n            // prototype\n\n            WrappedTextRange = function(textRange) {\n                this.textRange = textRange;\n                this.refresh();\n            };\n\n            WrappedTextRange.prototype = new DomRange(document);\n\n            WrappedTextRange.prototype.refresh = function() {\n                var start, end, startBoundary;\n\n                // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that.\n                var rangeContainerElement = getTextRangeContainerElement(this.textRange);\n\n                if (textRangeIsCollapsed(this.textRange)) {\n                    end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true,\n                        true).boundaryPosition;\n                } else {\n                    startBoundary = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false);\n                    start = startBoundary.boundaryPosition;\n\n                    // An optimization used here is that if the start and end boundaries have the same parent element, the\n                    // search scope for the end boundary can be limited to exclude the portion of the element that precedes\n                    // the start boundary\n                    end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false,\n                        startBoundary.nodeInfo).boundaryPosition;\n                }\n\n                this.setStart(start.node, start.offset);\n                this.setEnd(end.node, end.offset);\n            };\n\n            WrappedTextRange.prototype.getName = function() {\n                return \"WrappedTextRange\";\n            };\n\n            DomRange.copyComparisonConstants(WrappedTextRange);\n\n            var rangeToTextRange = function(range) {\n                if (range.collapsed) {\n                    return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);\n                } else {\n                    var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);\n                    var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false);\n                    var textRange = getBody( DomRange.getRangeDocument(range) ).createTextRange();\n                    textRange.setEndPoint(\"StartToStart\", startRange);\n                    textRange.setEndPoint(\"EndToEnd\", endRange);\n                    return textRange;\n                }\n            };\n\n            WrappedTextRange.rangeToTextRange = rangeToTextRange;\n\n            WrappedTextRange.prototype.toTextRange = function() {\n                return rangeToTextRange(this);\n            };\n\n            api.WrappedTextRange = WrappedTextRange;\n\n            // IE 9 and above have both implementations and Rangy makes both available. The next few lines sets which\n            // implementation to use by default.\n            if (!api.features.implementsDomRange || api.config.preferTextRange) {\n                // Add WrappedTextRange as the Range property of the global object to allow expression like Range.END_TO_END to work\n                var globalObj = (function(f) { return f(\"return this;\")(); })(Function);\n                if (typeof globalObj.Range == \"undefined\") {\n                    globalObj.Range = WrappedTextRange;\n                }\n\n                api.createNativeRange = function(doc) {\n                    doc = getContentDocument(doc, module, \"createNativeRange\");\n                    return getBody(doc).createTextRange();\n                };\n\n                api.WrappedRange = WrappedTextRange;\n            }\n        }\n\n        api.createRange = function(doc) {\n            doc = getContentDocument(doc, module, \"createRange\");\n            return new api.WrappedRange(api.createNativeRange(doc));\n        };\n\n        api.createRangyRange = function(doc) {\n            doc = getContentDocument(doc, module, \"createRangyRange\");\n            return new DomRange(doc);\n        };\n\n        util.createAliasForDeprecatedMethod(api, \"createIframeRange\", \"createRange\");\n        util.createAliasForDeprecatedMethod(api, \"createIframeRangyRange\", \"createRangyRange\");\n\n        api.addShimListener(function(win) {\n            var doc = win.document;\n            if (typeof doc.createRange == \"undefined\") {\n                doc.createRange = function() {\n                    return api.createRange(doc);\n                };\n            }\n            doc = win = null;\n        });\n    });\n\n    /*----------------------------------------------------------------------------------------------------------------*/\n\n    // This module creates a selection object wrapper that conforms as closely as possible to the Selection specification\n    // in the W3C Selection API spec (https://www.w3.org/TR/selection-api)\n    api.createCoreModule(\"WrappedSelection\", [\"DomRange\", \"WrappedRange\"], function(api, module) {\n        api.config.checkSelectionRanges = true;\n\n        var BOOLEAN = \"boolean\";\n        var NUMBER = \"number\";\n        var dom = api.dom;\n        var util = api.util;\n        var isHostMethod = util.isHostMethod;\n        var DomRange = api.DomRange;\n        var WrappedRange = api.WrappedRange;\n        var DOMException = api.DOMException;\n        var DomPosition = dom.DomPosition;\n        var getNativeSelection;\n        var selectionIsCollapsed;\n        var features = api.features;\n        var CONTROL = \"Control\";\n        var getDocument = dom.getDocument;\n        var getBody = dom.getBody;\n        var rangesEqual = DomRange.rangesEqual;\n\n\n        // Utility function to support direction parameters in the API that may be a string (\"backward\", \"backwards\",\n        // \"forward\" or \"forwards\") or a Boolean (true for backwards).\n        function isDirectionBackward(dir) {\n            return (typeof dir == \"string\") ? /^backward(s)?$/i.test(dir) : !!dir;\n        }\n\n        function getWindow(win, methodName) {\n            if (!win) {\n                return window;\n            } else if (dom.isWindow(win)) {\n                return win;\n            } else if (win instanceof WrappedSelection) {\n                return win.win;\n            } else {\n                var doc = dom.getContentDocument(win, module, methodName);\n                return dom.getWindow(doc);\n            }\n        }\n\n        function getWinSelection(winParam) {\n            return getWindow(winParam, \"getWinSelection\").getSelection();\n        }\n\n        function getDocSelection(winParam) {\n            return getWindow(winParam, \"getDocSelection\").document.selection;\n        }\n\n        function winSelectionIsBackward(sel) {\n            var backward = false;\n            if (sel.anchorNode) {\n                backward = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1);\n            }\n            return backward;\n        }\n\n        // Test for the Range/TextRange and Selection features required\n        // Test for ability to retrieve selection\n        var implementsWinGetSelection = isHostMethod(window, \"getSelection\"),\n            implementsDocSelection = util.isHostObject(document, \"selection\");\n\n        features.implementsWinGetSelection = implementsWinGetSelection;\n        features.implementsDocSelection = implementsDocSelection;\n\n        var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange);\n\n        if (useDocumentSelection) {\n            getNativeSelection = getDocSelection;\n            api.isSelectionValid = function(winParam) {\n                var doc = getWindow(winParam, \"isSelectionValid\").document, nativeSel = doc.selection;\n\n                // Check whether the selection TextRange is actually contained within the correct document\n                return (nativeSel.type != \"None\" || getDocument(nativeSel.createRange().parentElement()) == doc);\n            };\n        } else if (implementsWinGetSelection) {\n            getNativeSelection = getWinSelection;\n            api.isSelectionValid = function() {\n                return true;\n            };\n        } else {\n            module.fail(\"Neither document.selection or window.getSelection() detected.\");\n            return false;\n        }\n\n        api.getNativeSelection = getNativeSelection;\n\n        var testSelection = getNativeSelection();\n\n        // In Firefox, the selection is null in an iframe with display: none. See issue #138.\n        if (!testSelection) {\n            module.fail(\"Native selection was null (possibly issue 138?)\");\n            return false;\n        }\n\n        var testRange = api.createNativeRange(document);\n        var body = getBody(document);\n\n        // Obtaining a range from a selection\n        var selectionHasAnchorAndFocus = util.areHostProperties(testSelection,\n            [\"anchorNode\", \"focusNode\", \"anchorOffset\", \"focusOffset\"]);\n\n        features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus;\n\n        // Test for existence of native selection extend() method\n        var selectionHasExtend = isHostMethod(testSelection, \"extend\");\n        features.selectionHasExtend = selectionHasExtend;\n\n        // Test for existence of native selection setBaseAndExtent() method\n        var selectionHasSetBaseAndExtent = isHostMethod(testSelection, \"setBaseAndExtent\");\n        features.selectionHasSetBaseAndExtent = selectionHasSetBaseAndExtent;\n\n        // Test if rangeCount exists\n        var selectionHasRangeCount = (typeof testSelection.rangeCount == NUMBER);\n        features.selectionHasRangeCount = selectionHasRangeCount;\n\n        var selectionSupportsMultipleRanges = false;\n        var collapsedNonEditableSelectionsSupported = true;\n\n        var addRangeBackwardToNative = selectionHasExtend ?\n            function(nativeSelection, range) {\n                var doc = DomRange.getRangeDocument(range);\n                var endRange = api.createRange(doc);\n                endRange.collapseToPoint(range.endContainer, range.endOffset);\n                nativeSelection.addRange(getNativeRange(endRange));\n                nativeSelection.extend(range.startContainer, range.startOffset);\n            } : null;\n\n        if (util.areHostMethods(testSelection, [\"addRange\", \"getRangeAt\", \"removeAllRanges\"]) &&\n                typeof testSelection.rangeCount == NUMBER && features.implementsDomRange) {\n\n            (function() {\n                // Previously an iframe was used but this caused problems in some circumstances in IE, so tests are\n                // performed on the current document's selection. See issue 109.\n\n                // Note also that if a selection previously existed, it is wiped and later restored by these tests. This\n                // will result in the selection direction being reversed if the original selection was backwards and the\n                // browser does not support setting backwards selections (Internet Explorer, I'm looking at you).\n                var sel = window.getSelection();\n                if (sel) {\n                    // Store the current selection\n                    var originalSelectionRangeCount = sel.rangeCount;\n                    var selectionHasMultipleRanges = (originalSelectionRangeCount > 1);\n                    var originalSelectionRanges = [];\n                    var originalSelectionBackward = winSelectionIsBackward(sel);\n                    for (var i = 0; i < originalSelectionRangeCount; ++i) {\n                        originalSelectionRanges[i] = sel.getRangeAt(i);\n                    }\n\n                    // Create some test elements\n                    var testEl = dom.createTestElement(document, \"\", false);\n                    var textNode = testEl.appendChild( document.createTextNode(\"\\u00a0\\u00a0\\u00a0\") );\n\n                    // Test whether the native selection will allow a collapsed selection within a non-editable element\n                    var r1 = document.createRange();\n\n                    r1.setStart(textNode, 1);\n                    r1.collapse(true);\n                    sel.removeAllRanges();\n                    sel.addRange(r1);\n                    collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);\n                    sel.removeAllRanges();\n\n                    // Test whether the native selection is capable of supporting multiple ranges.\n                    if (!selectionHasMultipleRanges) {\n                        // Doing the original feature test here in Chrome 36 (and presumably later versions) prints a\n                        // console error of \"Discontiguous selection is not supported.\" that cannot be suppressed. There's\n                        // nothing we can do about this while retaining the feature test so we have to resort to a browser\n                        // sniff. I'm not happy about it. See\n                        // https://code.google.com/p/chromium/issues/detail?id=399791\n                        var chromeMatch = window.navigator.appVersion.match(/Chrome\\/(.*?) /);\n                        if (chromeMatch && parseInt(chromeMatch[1]) >= 36) {\n                            selectionSupportsMultipleRanges = false;\n                        } else {\n                            var r2 = r1.cloneRange();\n                            r1.setStart(textNode, 0);\n                            r2.setEnd(textNode, 3);\n                            r2.setStart(textNode, 2);\n                            sel.addRange(r1);\n                            sel.addRange(r2);\n                            selectionSupportsMultipleRanges = (sel.rangeCount == 2);\n                        }\n                    }\n\n                    // Clean up\n                    dom.removeNode(testEl);\n                    sel.removeAllRanges();\n\n                    for (i = 0; i < originalSelectionRangeCount; ++i) {\n                        if (i == 0 && originalSelectionBackward) {\n                            if (addRangeBackwardToNative) {\n                                addRangeBackwardToNative(sel, originalSelectionRanges[i]);\n                            } else {\n                                api.warn(\"Rangy initialization: original selection was backwards but selection has been restored forwards because the browser does not support Selection.extend\");\n                                sel.addRange(originalSelectionRanges[i]);\n                            }\n                        } else {\n                            sel.addRange(originalSelectionRanges[i]);\n                        }\n                    }\n                }\n            })();\n        }\n\n        features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges;\n        features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported;\n\n        // ControlRanges\n        var implementsControlRange = false, testControlRange;\n\n        if (body && isHostMethod(body, \"createControlRange\")) {\n            testControlRange = body.createControlRange();\n            if (util.areHostProperties(testControlRange, [\"item\", \"add\"])) {\n                implementsControlRange = true;\n            }\n        }\n        features.implementsControlRange = implementsControlRange;\n\n        // Selection collapsedness\n        if (selectionHasAnchorAndFocus) {\n            selectionIsCollapsed = function(sel) {\n                return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset;\n            };\n        } else {\n            selectionIsCollapsed = function(sel) {\n                return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false;\n            };\n        }\n\n        function updateAnchorAndFocusFromRange(sel, range, backward) {\n            var anchorPrefix = backward ? \"end\" : \"start\", focusPrefix = backward ? \"start\" : \"end\";\n            sel.anchorNode = range[anchorPrefix + \"Container\"];\n            sel.anchorOffset = range[anchorPrefix + \"Offset\"];\n            sel.focusNode = range[focusPrefix + \"Container\"];\n            sel.focusOffset = range[focusPrefix + \"Offset\"];\n        }\n\n        function updateAnchorAndFocusFromNativeSelection(sel) {\n            var nativeSel = sel.nativeSelection;\n            sel.anchorNode = nativeSel.anchorNode;\n            sel.anchorOffset = nativeSel.anchorOffset;\n            sel.focusNode = nativeSel.focusNode;\n            sel.focusOffset = nativeSel.focusOffset;\n        }\n\n        function updateEmptySelection(sel) {\n            sel.anchorNode = sel.focusNode = null;\n            sel.anchorOffset = sel.focusOffset = 0;\n            sel.rangeCount = 0;\n            sel.isCollapsed = true;\n            sel._ranges.length = 0;\n            updateType(sel);\n        }\n\n        function updateType(sel) {\n            sel.type = (sel.rangeCount == 0) ? \"None\" : (selectionIsCollapsed(sel) ? \"Caret\" : \"Range\");\n        }\n\n        function getNativeRange(range) {\n            var nativeRange;\n            if (range instanceof DomRange) {\n                nativeRange = api.createNativeRange(range.getDocument());\n                nativeRange.setEnd(range.endContainer, range.endOffset);\n                nativeRange.setStart(range.startContainer, range.startOffset);\n            } else if (range instanceof WrappedRange) {\n                nativeRange = range.nativeRange;\n            } else if (features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) {\n                nativeRange = range;\n            }\n            return nativeRange;\n        }\n\n        function rangeContainsSingleElement(rangeNodes) {\n            if (!rangeNodes.length || rangeNodes[0].nodeType != 1) {\n                return false;\n            }\n            for (var i = 1, len = rangeNodes.length; i < len; ++i) {\n                if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        function getSingleElementFromRange(range) {\n            var nodes = range.getNodes();\n            if (!rangeContainsSingleElement(nodes)) {\n                throw module.createError(\"getSingleElementFromRange: range \" + range.inspect() + \" did not consist of a single element\");\n            }\n            return nodes[0];\n        }\n\n        // Simple, quick test which only needs to distinguish between a TextRange and a ControlRange\n        function isTextRange(range) {\n            return !!range && typeof range.text != \"undefined\";\n        }\n\n        function updateFromTextRange(sel, range) {\n            // Create a Range from the selected TextRange\n            var wrappedRange = new WrappedRange(range);\n            sel._ranges = [wrappedRange];\n\n            updateAnchorAndFocusFromRange(sel, wrappedRange, false);\n            sel.rangeCount = 1;\n            sel.isCollapsed = wrappedRange.collapsed;\n            updateType(sel);\n        }\n\n        function updateControlSelection(sel) {\n            // Update the wrapped selection based on what's now in the native selection\n            sel._ranges.length = 0;\n            if (sel.docSelection.type == \"None\") {\n                updateEmptySelection(sel);\n            } else {\n                var controlRange = sel.docSelection.createRange();\n                if (isTextRange(controlRange)) {\n                    // This case (where the selection type is \"Control\" and calling createRange() on the selection returns\n                    // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected\n                    // ControlRange have been removed from the ControlRange and removed from the document.\n                    updateFromTextRange(sel, controlRange);\n                } else {\n                    sel.rangeCount = controlRange.length;\n                    var range, doc = getDocument(controlRange.item(0));\n                    for (var i = 0; i < sel.rangeCount; ++i) {\n                        range = api.createRange(doc);\n                        range.selectNode(controlRange.item(i));\n                        sel._ranges.push(range);\n                    }\n                    sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed;\n                    updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false);\n                    updateType(sel);\n                }\n            }\n        }\n\n        function addRangeToControlSelection(sel, range) {\n            var controlRange = sel.docSelection.createRange();\n            var rangeElement = getSingleElementFromRange(range);\n\n            // Create a new ControlRange containing all the elements in the selected ControlRange plus the element\n            // contained by the supplied range\n            var doc = getDocument(controlRange.item(0));\n            var newControlRange = getBody(doc).createControlRange();\n            for (var i = 0, len = controlRange.length; i < len; ++i) {\n                newControlRange.add(controlRange.item(i));\n            }\n            try {\n                newControlRange.add(rangeElement);\n            } catch (ex) {\n                throw module.createError(\"addRange(): Element within the specified Range could not be added to control selection (does it have layout?)\");\n            }\n            newControlRange.select();\n\n            // Update the wrapped selection based on what's now in the native selection\n            updateControlSelection(sel);\n        }\n\n        var getSelectionRangeAt;\n\n        if (isHostMethod(testSelection, \"getRangeAt\")) {\n            // try/catch is present because getRangeAt() must have thrown an error in some browser and some situation.\n            // Unfortunately, I didn't write a comment about the specifics and am now scared to take it out. Let that be a\n            // lesson to us all, especially me.\n            getSelectionRangeAt = function(sel, index) {\n                try {\n                    return sel.getRangeAt(index);\n                } catch (ex) {\n                    return null;\n                }\n            };\n        } else if (selectionHasAnchorAndFocus) {\n            getSelectionRangeAt = function(sel) {\n                var doc = getDocument(sel.anchorNode);\n                var range = api.createRange(doc);\n                range.setStartAndEnd(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset);\n\n                // Handle the case when the selection was selected backwards (from the end to the start in the\n                // document)\n                if (range.collapsed !== this.isCollapsed) {\n                    range.setStartAndEnd(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset);\n                }\n\n                return range;\n            };\n        }\n\n        function WrappedSelection(selection, docSelection, win) {\n            this.nativeSelection = selection;\n            this.docSelection = docSelection;\n            this._ranges = [];\n            this.win = win;\n            this.refresh();\n        }\n\n        WrappedSelection.prototype = api.selectionPrototype;\n\n        function deleteProperties(sel) {\n            sel.win = sel.anchorNode = sel.focusNode = sel._ranges = null;\n            sel.rangeCount = sel.anchorOffset = sel.focusOffset = 0;\n            sel.detached = true;\n            updateType(sel);\n        }\n\n        var cachedRangySelections = [];\n\n        function actOnCachedSelection(win, action) {\n            var i = cachedRangySelections.length, cached, sel;\n            while (i--) {\n                cached = cachedRangySelections[i];\n                sel = cached.selection;\n                if (action == \"deleteAll\") {\n                    deleteProperties(sel);\n                } else if (cached.win == win) {\n                    if (action == \"delete\") {\n                        cachedRangySelections.splice(i, 1);\n                        return true;\n                    } else {\n                        return sel;\n                    }\n                }\n            }\n            if (action == \"deleteAll\") {\n                cachedRangySelections.length = 0;\n            }\n            return null;\n        }\n\n        var getSelection = function(win) {\n            // Check if the parameter is a Rangy Selection object\n            if (win && win instanceof WrappedSelection) {\n                win.refresh();\n                return win;\n            }\n\n            win = getWindow(win, \"getNativeSelection\");\n\n            var sel = actOnCachedSelection(win);\n            var nativeSel = getNativeSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null;\n            if (sel) {\n                sel.nativeSelection = nativeSel;\n                sel.docSelection = docSel;\n                sel.refresh();\n            } else {\n                sel = new WrappedSelection(nativeSel, docSel, win);\n                cachedRangySelections.push( { win: win, selection: sel } );\n            }\n            return sel;\n        };\n\n        api.getSelection = getSelection;\n\n        util.createAliasForDeprecatedMethod(api, \"getIframeSelection\", \"getSelection\");\n\n        var selProto = WrappedSelection.prototype;\n\n        function createControlSelection(sel, ranges) {\n            // Ensure that the selection becomes of type \"Control\"\n            var doc = getDocument(ranges[0].startContainer);\n            var controlRange = getBody(doc).createControlRange();\n            for (var i = 0, el, len = ranges.length; i < len; ++i) {\n                el = getSingleElementFromRange(ranges[i]);\n                try {\n                    controlRange.add(el);\n                } catch (ex) {\n                    throw module.createError(\"setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)\");\n                }\n            }\n            controlRange.select();\n\n            // Update the wrapped selection based on what's now in the native selection\n            updateControlSelection(sel);\n        }\n\n        // Selecting a range\n        if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, [\"removeAllRanges\", \"addRange\"])) {\n            selProto.removeAllRanges = function() {\n                this.nativeSelection.removeAllRanges();\n                updateEmptySelection(this);\n            };\n\n            var addRangeBackward = function(sel, range) {\n                addRangeBackwardToNative(sel.nativeSelection, range);\n                sel.refresh();\n            };\n\n            if (selectionHasRangeCount) {\n                selProto.addRange = function(range, direction) {\n                    if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {\n                        addRangeToControlSelection(this, range);\n                    } else {\n                        if (isDirectionBackward(direction) && selectionHasExtend) {\n                            addRangeBackward(this, range);\n                        } else {\n                            var previousRangeCount;\n                            if (selectionSupportsMultipleRanges) {\n                                previousRangeCount = this.rangeCount;\n                            } else {\n                                this.removeAllRanges();\n                                previousRangeCount = 0;\n                            }\n                            // Clone the native range so that changing the selected range does not affect the selection.\n                            // This is contrary to the spec but is the only way to achieve consistency between browsers. See\n                            // issue 80.\n                            var clonedNativeRange = getNativeRange(range).cloneRange();\n                            try {\n                                this.nativeSelection.addRange(clonedNativeRange);\n                            } catch (ex) {\n                            }\n\n                            // Check whether adding the range was successful\n                            this.rangeCount = this.nativeSelection.rangeCount;\n\n                            if (this.rangeCount == previousRangeCount + 1) {\n                                // The range was added successfully\n\n                                // Check whether the range that we added to the selection is reflected in the last range extracted from\n                                // the selection\n                                if (api.config.checkSelectionRanges) {\n                                    var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1);\n                                    if (nativeRange && !rangesEqual(nativeRange, range)) {\n                                        // Happens in WebKit with, for example, a selection placed at the start of a text node\n                                        range = new WrappedRange(nativeRange);\n                                    }\n                                }\n                                this._ranges[this.rangeCount - 1] = range;\n                                updateAnchorAndFocusFromRange(this, range, selectionIsBackward(this.nativeSelection));\n                                this.isCollapsed = selectionIsCollapsed(this);\n                                updateType(this);\n                            } else {\n                                // The range was not added successfully. The simplest thing is to refresh\n                                this.refresh();\n                            }\n                        }\n                    }\n                };\n            } else {\n                selProto.addRange = function(range, direction) {\n                    if (isDirectionBackward(direction) && selectionHasExtend) {\n                        addRangeBackward(this, range);\n                    } else {\n                        this.nativeSelection.addRange(getNativeRange(range));\n                        this.refresh();\n                    }\n                };\n            }\n\n            selProto.setRanges = function(ranges) {\n                if (implementsControlRange && implementsDocSelection && ranges.length > 1) {\n                    createControlSelection(this, ranges);\n                } else {\n                    this.removeAllRanges();\n                    for (var i = 0, len = ranges.length; i < len; ++i) {\n                        this.addRange(ranges[i]);\n                    }\n                }\n            };\n        } else if (isHostMethod(testSelection, \"empty\") && isHostMethod(testRange, \"select\") &&\n                   implementsControlRange && useDocumentSelection) {\n\n            selProto.removeAllRanges = function() {\n                // Added try/catch as fix for issue #21\n                try {\n                    this.docSelection.empty();\n\n                    // Check for empty() not working (issue #24)\n                    if (this.docSelection.type != \"None\") {\n                        // Work around failure to empty a control selection by instead selecting a TextRange and then\n                        // calling empty()\n                        var doc;\n                        if (this.anchorNode) {\n                            doc = getDocument(this.anchorNode);\n                        } else if (this.docSelection.type == CONTROL) {\n                            var controlRange = this.docSelection.createRange();\n                            if (controlRange.length) {\n                                doc = getDocument( controlRange.item(0) );\n                            }\n                        }\n                        if (doc) {\n                            var textRange = getBody(doc).createTextRange();\n                            textRange.select();\n                            this.docSelection.empty();\n                        }\n                    }\n                } catch(ex) {}\n                updateEmptySelection(this);\n            };\n\n            selProto.addRange = function(range) {\n                if (this.docSelection.type == CONTROL) {\n                    addRangeToControlSelection(this, range);\n                } else {\n                    api.WrappedTextRange.rangeToTextRange(range).select();\n                    this._ranges[0] = range;\n                    this.rangeCount = 1;\n                    this.isCollapsed = this._ranges[0].collapsed;\n                    updateAnchorAndFocusFromRange(this, range, false);\n                    updateType(this);\n                }\n            };\n\n            selProto.setRanges = function(ranges) {\n                this.removeAllRanges();\n                var rangeCount = ranges.length;\n                if (rangeCount > 1) {\n                    createControlSelection(this, ranges);\n                } else if (rangeCount) {\n                    this.addRange(ranges[0]);\n                }\n            };\n        } else {\n            module.fail(\"No means of selecting a Range or TextRange was found\");\n            return false;\n        }\n\n        selProto.getRangeAt = function(index) {\n            if (index < 0 || index >= this.rangeCount) {\n                throw new DOMException(\"INDEX_SIZE_ERR\");\n            } else {\n                // Clone the range to preserve selection-range independence. See issue 80.\n                return this._ranges[index].cloneRange();\n            }\n        };\n\n        var refreshSelection;\n\n        if (useDocumentSelection) {\n            refreshSelection = function(sel) {\n                var range;\n                if (api.isSelectionValid(sel.win)) {\n                    range = sel.docSelection.createRange();\n                } else {\n                    range = getBody(sel.win.document).createTextRange();\n                    range.collapse(true);\n                }\n\n                if (sel.docSelection.type == CONTROL) {\n                    updateControlSelection(sel);\n                } else if (isTextRange(range)) {\n                    updateFromTextRange(sel, range);\n                } else {\n                    updateEmptySelection(sel);\n                }\n            };\n        } else if (isHostMethod(testSelection, \"getRangeAt\") && typeof testSelection.rangeCount == NUMBER) {\n            refreshSelection = function(sel) {\n                if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) {\n                    updateControlSelection(sel);\n                } else {\n                    sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount;\n                    if (sel.rangeCount) {\n                        for (var i = 0, len = sel.rangeCount; i < len; ++i) {\n                            sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i));\n                        }\n                        updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackward(sel.nativeSelection));\n                        sel.isCollapsed = selectionIsCollapsed(sel);\n                        updateType(sel);\n                    } else {\n                        updateEmptySelection(sel);\n                    }\n                }\n            };\n        } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && features.implementsDomRange) {\n            refreshSelection = function(sel) {\n                var range, nativeSel = sel.nativeSelection;\n                if (nativeSel.anchorNode) {\n                    range = getSelectionRangeAt(nativeSel, 0);\n                    sel._ranges = [range];\n                    sel.rangeCount = 1;\n                    updateAnchorAndFocusFromNativeSelection(sel);\n                    sel.isCollapsed = selectionIsCollapsed(sel);\n                    updateType(sel);\n                } else {\n                    updateEmptySelection(sel);\n                }\n            };\n        } else {\n            module.fail(\"No means of obtaining a Range or TextRange from the user's selection was found\");\n            return false;\n        }\n\n        selProto.refresh = function(checkForChanges) {\n            var oldRanges = checkForChanges ? this._ranges.slice(0) : null;\n            var oldAnchorNode = this.anchorNode, oldAnchorOffset = this.anchorOffset;\n\n            refreshSelection(this);\n            if (checkForChanges) {\n                // Check the range count first\n                var i = oldRanges.length;\n                if (i != this._ranges.length) {\n                    return true;\n                }\n\n                // Now check the direction. Checking the anchor position is the same is enough since we're checking all the\n                // ranges after this\n                if (this.anchorNode != oldAnchorNode || this.anchorOffset != oldAnchorOffset) {\n                    return true;\n                }\n\n                // Finally, compare each range in turn\n                while (i--) {\n                    if (!rangesEqual(oldRanges[i], this._ranges[i])) {\n                        return true;\n                    }\n                }\n                return false;\n            }\n        };\n\n        // Removal of a single range\n        var removeRangeManually = function(sel, range) {\n            var ranges = sel.getAllRanges();\n            sel.removeAllRanges();\n            for (var i = 0, len = ranges.length; i < len; ++i) {\n                if (!rangesEqual(range, ranges[i])) {\n                    sel.addRange(ranges[i]);\n                }\n            }\n            if (!sel.rangeCount) {\n                updateEmptySelection(sel);\n            }\n        };\n\n        if (implementsControlRange && implementsDocSelection) {\n            selProto.removeRange = function(range) {\n                if (this.docSelection.type == CONTROL) {\n                    var controlRange = this.docSelection.createRange();\n                    var rangeElement = getSingleElementFromRange(range);\n\n                    // Create a new ControlRange containing all the elements in the selected ControlRange minus the\n                    // element contained by the supplied range\n                    var doc = getDocument(controlRange.item(0));\n                    var newControlRange = getBody(doc).createControlRange();\n                    var el, removed = false;\n                    for (var i = 0, len = controlRange.length; i < len; ++i) {\n                        el = controlRange.item(i);\n                        if (el !== rangeElement || removed) {\n                            newControlRange.add(controlRange.item(i));\n                        } else {\n                            removed = true;\n                        }\n                    }\n                    newControlRange.select();\n\n                    // Update the wrapped selection based on what's now in the native selection\n                    updateControlSelection(this);\n                } else {\n                    removeRangeManually(this, range);\n                }\n            };\n        } else {\n            selProto.removeRange = function(range) {\n                removeRangeManually(this, range);\n            };\n        }\n\n        // Detecting if a selection is backward\n        var selectionIsBackward;\n        if (!useDocumentSelection && selectionHasAnchorAndFocus && features.implementsDomRange) {\n            selectionIsBackward = winSelectionIsBackward;\n\n            selProto.isBackward = function() {\n                return selectionIsBackward(this);\n            };\n        } else {\n            selectionIsBackward = selProto.isBackward = function() {\n                return false;\n            };\n        }\n\n        // Create an alias for backwards compatibility. From 1.3, everything is \"backward\" rather than \"backwards\"\n        selProto.isBackwards = selProto.isBackward;\n\n        // Selection stringifier\n        // This is conformant to the old HTML5 selections draft spec but differs from WebKit and Mozilla's implementation.\n        // The current spec does not yet define this method.\n        selProto.toString = function() {\n            var rangeTexts = [];\n            for (var i = 0, len = this.rangeCount; i < len; ++i) {\n                rangeTexts[i] = \"\" + this._ranges[i];\n            }\n            return rangeTexts.join(\"\");\n        };\n\n        function assertNodeInSameDocument(sel, node) {\n            if (sel.win.document != getDocument(node)) {\n                throw new DOMException(\"WRONG_DOCUMENT_ERR\");\n            }\n        }\n\n        function assertValidOffset(node, offset) {\n            if (offset < 0 || offset > (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length)) {\n                throw new DOMException(\"INDEX_SIZE_ERR\");\n            }\n        }\n\n        // No current browser conforms fully to the spec for this method, so Rangy's own method is always used\n        selProto.collapse = function(node, offset) {\n            assertNodeInSameDocument(this, node);\n            var range = api.createRange(node);\n            range.collapseToPoint(node, offset);\n            this.setSingleRange(range);\n            this.isCollapsed = true;\n        };\n\n        selProto.collapseToStart = function() {\n            if (this.rangeCount) {\n                var range = this._ranges[0];\n                this.collapse(range.startContainer, range.startOffset);\n            } else {\n                throw new DOMException(\"INVALID_STATE_ERR\");\n            }\n        };\n\n        selProto.collapseToEnd = function() {\n            if (this.rangeCount) {\n                var range = this._ranges[this.rangeCount - 1];\n                this.collapse(range.endContainer, range.endOffset);\n            } else {\n                throw new DOMException(\"INVALID_STATE_ERR\");\n            }\n        };\n\n        // The spec is very specific on how selectAllChildren should be implemented and not all browsers implement it as\n        // specified so the native implementation is never used by Rangy.\n        selProto.selectAllChildren = function(node) {\n            assertNodeInSameDocument(this, node);\n            var range = api.createRange(node);\n            range.selectNodeContents(node);\n            this.setSingleRange(range);\n        };\n\n        if (selectionHasSetBaseAndExtent) {\n            selProto.setBaseAndExtent = function(anchorNode, anchorOffset, focusNode, focusOffset) {\n                this.nativeSelection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);\n                this.refresh();\n            };\n        } else if (selectionHasExtend) {\n            selProto.setBaseAndExtent = function(anchorNode, anchorOffset, focusNode, focusOffset) {\n                assertValidOffset(anchorNode, anchorOffset);\n                assertValidOffset(focusNode, focusOffset);\n                assertNodeInSameDocument(this, anchorNode);\n                assertNodeInSameDocument(this, focusNode);\n                var range = api.createRange(node);\n                var isBackwards = (dom.comparePoints(anchorNode, anchorOffset, focusNode, focusOffset) == -1);\n                if (isBackwards) {\n                    range.setStartAndEnd(focusNode, focusOffset, anchorNode, anchorOffset);\n                } else {\n                    range.setStartAndEnd(anchorNode, anchorOffset, focusNode, focusOffset);\n                }\n                this.setSingleRange(range, isBackwards);\n            };\n        }\n\n        selProto.deleteFromDocument = function() {\n            // Sepcial behaviour required for IE's control selections\n            if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {\n                var controlRange = this.docSelection.createRange();\n                var element;\n                while (controlRange.length) {\n                    element = controlRange.item(0);\n                    controlRange.remove(element);\n                    dom.removeNode(element);\n                }\n                this.refresh();\n            } else if (this.rangeCount) {\n                var ranges = this.getAllRanges();\n                if (ranges.length) {\n                    this.removeAllRanges();\n                    for (var i = 0, len = ranges.length; i < len; ++i) {\n                        ranges[i].deleteContents();\n                    }\n                    // The spec says nothing about what the selection should contain after calling deleteContents on each\n                    // range. Firefox moves the selection to where the final selected range was, so we emulate that\n                    this.addRange(ranges[len - 1]);\n                }\n            }\n        };\n\n        // The following are non-standard extensions\n        selProto.eachRange = function(func, returnValue) {\n            for (var i = 0, len = this._ranges.length; i < len; ++i) {\n                if ( func( this.getRangeAt(i) ) ) {\n                    return returnValue;\n                }\n            }\n        };\n\n        selProto.getAllRanges = function() {\n            var ranges = [];\n            this.eachRange(function(range) {\n                ranges.push(range);\n            });\n            return ranges;\n        };\n\n        selProto.setSingleRange = function(range, direction) {\n            this.removeAllRanges();\n            this.addRange(range, direction);\n        };\n\n        selProto.callMethodOnEachRange = function(methodName, params) {\n            var results = [];\n            this.eachRange( function(range) {\n                results.push( range[methodName].apply(range, params || []) );\n            } );\n            return results;\n        };\n\n        function createStartOrEndSetter(isStart) {\n            return function(node, offset) {\n                var range;\n                if (this.rangeCount) {\n                    range = this.getRangeAt(0);\n                    range[\"set\" + (isStart ? \"Start\" : \"End\")](node, offset);\n                } else {\n                    range = api.createRange(this.win.document);\n                    range.setStartAndEnd(node, offset);\n                }\n                this.setSingleRange(range, this.isBackward());\n            };\n        }\n\n        selProto.setStart = createStartOrEndSetter(true);\n        selProto.setEnd = createStartOrEndSetter(false);\n\n        // Add select() method to Range prototype. Any existing selection will be removed.\n        api.rangePrototype.select = function(direction) {\n            getSelection( this.getDocument() ).setSingleRange(this, direction);\n        };\n\n        selProto.changeEachRange = function(func) {\n            var ranges = [];\n            var backward = this.isBackward();\n\n            this.eachRange(function(range) {\n                func(range);\n                ranges.push(range);\n            });\n\n            this.removeAllRanges();\n            if (backward && ranges.length == 1) {\n                this.addRange(ranges[0], \"backward\");\n            } else {\n                this.setRanges(ranges);\n            }\n        };\n\n        selProto.containsNode = function(node, allowPartial) {\n            return this.eachRange( function(range) {\n                return range.containsNode(node, allowPartial);\n            }, true ) || false;\n        };\n\n        selProto.getBookmark = function(containerNode) {\n            return {\n                backward: this.isBackward(),\n                rangeBookmarks: this.callMethodOnEachRange(\"getBookmark\", [containerNode])\n            };\n        };\n\n        selProto.moveToBookmark = function(bookmark) {\n            var selRanges = [];\n            for (var i = 0, rangeBookmark, range; rangeBookmark = bookmark.rangeBookmarks[i++]; ) {\n                range = api.createRange(this.win);\n                range.moveToBookmark(rangeBookmark);\n                selRanges.push(range);\n            }\n            if (bookmark.backward) {\n                this.setSingleRange(selRanges[0], \"backward\");\n            } else {\n                this.setRanges(selRanges);\n            }\n        };\n\n        selProto.saveRanges = function() {\n            return {\n                backward: this.isBackward(),\n                ranges: this.callMethodOnEachRange(\"cloneRange\")\n            };\n        };\n\n        selProto.restoreRanges = function(selRanges) {\n            this.removeAllRanges();\n            for (var i = 0, range; range = selRanges.ranges[i]; ++i) {\n                this.addRange(range, (selRanges.backward && i == 0));\n            }\n        };\n\n        selProto.toHtml = function() {\n            var rangeHtmls = [];\n            this.eachRange(function(range) {\n                rangeHtmls.push( DomRange.toHtml(range) );\n            });\n            return rangeHtmls.join(\"\");\n        };\n\n        if (features.implementsTextRange) {\n            selProto.getNativeTextRange = function() {\n                var sel, textRange;\n                if ( (sel = this.docSelection) ) {\n                    var range = sel.createRange();\n                    if (isTextRange(range)) {\n                        return range;\n                    } else {\n                        throw module.createError(\"getNativeTextRange: selection is a control selection\");\n                    }\n                } else if (this.rangeCount > 0) {\n                    return api.WrappedTextRange.rangeToTextRange( this.getRangeAt(0) );\n                } else {\n                    throw module.createError(\"getNativeTextRange: selection contains no range\");\n                }\n            };\n        }\n\n        function inspect(sel) {\n            var rangeInspects = [];\n            var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset);\n            var focus = new DomPosition(sel.focusNode, sel.focusOffset);\n            var name = (typeof sel.getName == \"function\") ? sel.getName() : \"Selection\";\n\n            if (typeof sel.rangeCount != \"undefined\") {\n                for (var i = 0, len = sel.rangeCount; i < len; ++i) {\n                    rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i));\n                }\n            }\n            return \"[\" + name + \"(Ranges: \" + rangeInspects.join(\", \") +\n                    \")(anchor: \" + anchor.inspect() + \", focus: \" + focus.inspect() + \"]\";\n        }\n\n        selProto.getName = function() {\n            return \"WrappedSelection\";\n        };\n\n        selProto.inspect = function() {\n            return inspect(this);\n        };\n\n        selProto.detach = function() {\n            actOnCachedSelection(this.win, \"delete\");\n            deleteProperties(this);\n        };\n\n        WrappedSelection.detachAll = function() {\n            actOnCachedSelection(null, \"deleteAll\");\n        };\n\n        WrappedSelection.inspect = inspect;\n        WrappedSelection.isDirectionBackward = isDirectionBackward;\n\n        api.Selection = WrappedSelection;\n\n        api.selectionPrototype = selProto;\n\n        api.addShimListener(function(win) {\n            if (typeof win.getSelection == \"undefined\") {\n                win.getSelection = function() {\n                    return getSelection(win);\n                };\n            }\n            win = null;\n        });\n    });\n    \n\n    /*----------------------------------------------------------------------------------------------------------------*/\n\n    // Wait for document to load before initializing\n    var docReady = false;\n\n    var loadHandler = function(e) {\n        if (!docReady) {\n            docReady = true;\n            if (!api.initialized && api.config.autoInitialize) {\n                init();\n            }\n        }\n    };\n\n    if (isBrowser) {\n        // Test whether the document has already been loaded and initialize immediately if so\n        if (document.readyState == \"complete\") {\n            loadHandler();\n        } else {\n            if (isHostMethod(document, \"addEventListener\")) {\n                document.addEventListener(\"DOMContentLoaded\", loadHandler, false);\n            }\n\n            // Add a fallback in case the DOMContentLoaded event isn't supported\n            addListener(window, \"load\", loadHandler);\n        }\n    }\n\n    return api;\n}, this);","/**\n * Class Applier module for Rangy.\n * Adds, removes and toggles classes on Ranges and Selections\n *\n * Part of Rangy, a cross-browser JavaScript range and selection library\n * https://github.com/timdown/rangy\n *\n * Depends on Rangy core.\n *\n * Copyright 2024, Tim Down\n * Licensed under the MIT license.\n * Version: 1.3.2\n * Build date: 2 November 2024\n */\n(function(factory, root) {\n    if (typeof define == \"function\" && define.amd) {\n        // AMD. Register as an anonymous module with a dependency on Rangy.\n        define([\"./rangy-core\"], factory);\n    } else if (typeof module != \"undefined\" && typeof exports == \"object\") {\n        // Node/CommonJS style\n        module.exports = factory( require(\"rangy\") );\n    } else {\n        // No AMD or CommonJS support so we use the rangy property of root (probably the global variable)\n        factory(root.rangy);\n    }\n})(function(rangy) {\n    rangy.createModule(\"ClassApplier\", [\"WrappedSelection\"], function(api, module) {\n        var dom = api.dom;\n        var DomPosition = dom.DomPosition;\n        var contains = dom.arrayContains;\n        var util = api.util;\n        var forEach = util.forEach;\n\n\n        var defaultTagName = \"span\";\n        var createElementNSSupported = util.isHostMethod(document, \"createElementNS\");\n\n        function each(obj, func) {\n            for (var i in obj) {\n                if (obj.hasOwnProperty(i)) {\n                    if (func(i, obj[i]) === false) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n\n        function trim(str) {\n            return str.replace(/^\\s\\s*/, \"\").replace(/\\s\\s*$/, \"\");\n        }\n\n        function classNameContainsClass(fullClassName, className) {\n            return !!fullClassName && new RegExp(\"(?:^|\\\\s)\" + className + \"(?:\\\\s|$)\").test(fullClassName);\n        }\n\n        // Inefficient, inelegant nonsense for IE's svg element, which has no classList and non-HTML className implementation\n        function hasClass(el, className) {\n            if (typeof el.classList == \"object\") {\n                return el.classList.contains(className);\n            } else {\n                var classNameSupported = (typeof el.className == \"string\");\n                var elClass = classNameSupported ? el.className : el.getAttribute(\"class\");\n                return classNameContainsClass(elClass, className);\n            }\n        }\n\n        function addClass(el, className) {\n            if (typeof el.classList == \"object\") {\n                el.classList.add(className);\n            } else {\n                var classNameSupported = (typeof el.className == \"string\");\n                var elClass = classNameSupported ? el.className : el.getAttribute(\"class\");\n                if (elClass) {\n                    if (!classNameContainsClass(elClass, className)) {\n                        elClass += \" \" + className;\n                    }\n                } else {\n                    elClass = className;\n                }\n                if (classNameSupported) {\n                    el.className = elClass;\n                } else {\n                    el.setAttribute(\"class\", elClass);\n                }\n            }\n        }\n\n        var removeClass = (function() {\n            function replacer(matched, whiteSpaceBefore, whiteSpaceAfter) {\n                return (whiteSpaceBefore && whiteSpaceAfter) ? \" \" : \"\";\n            }\n\n            return function(el, className) {\n                if (typeof el.classList == \"object\") {\n                    el.classList.remove(className);\n                } else {\n                    var classNameSupported = (typeof el.className == \"string\");\n                    var elClass = classNameSupported ? el.className : el.getAttribute(\"class\");\n                    elClass = elClass.replace(new RegExp(\"(^|\\\\s)\" + className + \"(\\\\s|$)\"), replacer);\n                    if (classNameSupported) {\n                        el.className = elClass;\n                    } else {\n                        el.setAttribute(\"class\", elClass);\n                    }\n                }\n            };\n        })();\n\n        function getClass(el) {\n            var classNameSupported = (typeof el.className == \"string\");\n            return classNameSupported ? el.className : el.getAttribute(\"class\");\n        }\n\n        function sortClassName(className) {\n            return className && className.split(/\\s+/).sort().join(\" \");\n        }\n\n        function getSortedClassName(el) {\n            return sortClassName( getClass(el) );\n        }\n\n        function haveSameClasses(el1, el2) {\n            return getSortedClassName(el1) == getSortedClassName(el2);\n        }\n\n        function hasAllClasses(el, className) {\n            var classes = className.split(/\\s+/);\n            for (var i = 0, len = classes.length; i < len; ++i) {\n                if (!hasClass(el, trim(classes[i]))) {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        function canTextBeStyled(textNode) {\n            var parent = textNode.parentNode;\n            return (parent && parent.nodeType == 1 && !/^(textarea|style|script|select|iframe)$/i.test(parent.nodeName));\n        }\n\n        function movePosition(position, oldParent, oldIndex, newParent, newIndex) {\n            var posNode = position.node, posOffset = position.offset;\n            var newNode = posNode, newOffset = posOffset;\n\n            if (posNode == newParent && posOffset > newIndex) {\n                ++newOffset;\n            }\n\n            if (posNode == oldParent && (posOffset == oldIndex  || posOffset == oldIndex + 1)) {\n                newNode = newParent;\n                newOffset += newIndex - oldIndex;\n            }\n\n            if (posNode == oldParent && posOffset > oldIndex + 1) {\n                --newOffset;\n            }\n\n            position.node = newNode;\n            position.offset = newOffset;\n        }\n\n        function movePositionWhenRemovingNode(position, parentNode, index) {\n            if (position.node == parentNode && position.offset > index) {\n                --position.offset;\n            }\n        }\n\n        function movePreservingPositions(node, newParent, newIndex, positionsToPreserve) {\n            // For convenience, allow newIndex to be -1 to mean \"insert at the end\".\n            if (newIndex == -1) {\n                newIndex = newParent.childNodes.length;\n            }\n\n            var oldParent = node.parentNode;\n            var oldIndex = dom.getNodeIndex(node);\n\n            forEach(positionsToPreserve, function(position) {\n                movePosition(position, oldParent, oldIndex, newParent, newIndex);\n            });\n\n            // Now actually move the node.\n            if (newParent.childNodes.length == newIndex) {\n                newParent.appendChild(node);\n            } else {\n                newParent.insertBefore(node, newParent.childNodes[newIndex]);\n            }\n        }\n\n        function removePreservingPositions(node, positionsToPreserve) {\n\n            var oldParent = node.parentNode;\n            var oldIndex = dom.getNodeIndex(node);\n\n            forEach(positionsToPreserve, function(position) {\n                movePositionWhenRemovingNode(position, oldParent, oldIndex);\n            });\n\n            dom.removeNode(node);\n        }\n\n        function moveChildrenPreservingPositions(node, newParent, newIndex, removeNode, positionsToPreserve) {\n            var child, children = [];\n            while ( (child = node.firstChild) ) {\n                movePreservingPositions(child, newParent, newIndex++, positionsToPreserve);\n                children.push(child);\n            }\n            if (removeNode) {\n                removePreservingPositions(node, positionsToPreserve);\n            }\n            return children;\n        }\n\n        function replaceWithOwnChildrenPreservingPositions(element, positionsToPreserve) {\n            return moveChildrenPreservingPositions(element, element.parentNode, dom.getNodeIndex(element), true, positionsToPreserve);\n        }\n\n        function rangeSelectsAnyText(range, textNode) {\n            var textNodeRange = range.cloneRange();\n            textNodeRange.selectNodeContents(textNode);\n\n            var intersectionRange = textNodeRange.intersection(range);\n            var text = intersectionRange ? intersectionRange.toString() : \"\";\n\n            return text != \"\";\n        }\n\n        function getEffectiveTextNodes(range) {\n            var nodes = range.getNodes([3]);\n\n            // Optimization as per issue 145\n\n            // Remove non-intersecting text nodes from the start of the range\n            var start = 0, node;\n            while ( (node = nodes[start]) && !rangeSelectsAnyText(range, node) ) {\n                ++start;\n            }\n\n            // Remove non-intersecting text nodes from the start of the range\n            var end = nodes.length - 1;\n            while ( (node = nodes[end]) && !rangeSelectsAnyText(range, node) ) {\n                --end;\n            }\n\n            return nodes.slice(start, end + 1);\n        }\n\n        function elementsHaveSameNonClassAttributes(el1, el2) {\n            if (el1.attributes.length != el2.attributes.length) return false;\n            for (var i = 0, len = el1.attributes.length, attr1, attr2, name; i < len; ++i) {\n                attr1 = el1.attributes[i];\n                name = attr1.name;\n                if (name != \"class\") {\n                    attr2 = el2.attributes.getNamedItem(name);\n                    if ( (attr1 === null) != (attr2 === null) ) return false;\n                    if (attr1.specified != attr2.specified) return false;\n                    if (attr1.specified && attr1.nodeValue !== attr2.nodeValue) return false;\n                }\n            }\n            return true;\n        }\n\n        function elementHasNonClassAttributes(el, exceptions) {\n            for (var i = 0, len = el.attributes.length, attrName; i < len; ++i) {\n                attrName = el.attributes[i].name;\n                if ( !(exceptions && contains(exceptions, attrName)) && el.attributes[i].specified && attrName != \"class\") {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        var getComputedStyleProperty = dom.getComputedStyleProperty;\n        var isEditableElement = (function() {\n            var testEl = document.createElement(\"div\");\n            return typeof testEl.isContentEditable == \"boolean\" ?\n                function (node) {\n                    return node && node.nodeType == 1 && node.isContentEditable;\n                } :\n                function (node) {\n                    if (!node || node.nodeType != 1 || node.contentEditable == \"false\") {\n                        return false;\n                    }\n                    return node.contentEditable == \"true\" || isEditableElement(node.parentNode);\n                };\n        })();\n\n        function isEditingHost(node) {\n            var parent;\n            return node && node.nodeType == 1 &&\n                (( (parent = node.parentNode) && parent.nodeType == 9 && parent.designMode == \"on\") ||\n                (isEditableElement(node) && !isEditableElement(node.parentNode)));\n        }\n\n        function isEditable(node) {\n            return (isEditableElement(node) || (node.nodeType != 1 && isEditableElement(node.parentNode))) && !isEditingHost(node);\n        }\n\n        var inlineDisplayRegex = /^inline(-block|-table)?$/i;\n\n        function isNonInlineElement(node) {\n            return node && node.nodeType == 1 && !inlineDisplayRegex.test(getComputedStyleProperty(node, \"display\"));\n        }\n\n        // White space characters as defined by HTML 4 (http://www.w3.org/TR/html401/struct/text.html)\n        var htmlNonWhiteSpaceRegex = /[^\\r\\n\\t\\f \\u200B]/;\n\n        function isUnrenderedWhiteSpaceNode(node) {\n            if (node.data.length == 0) {\n                return true;\n            }\n            if (htmlNonWhiteSpaceRegex.test(node.data)) {\n                return false;\n            }\n            var cssWhiteSpace = getComputedStyleProperty(node.parentNode, \"whiteSpace\");\n            switch (cssWhiteSpace) {\n                case \"pre\":\n                case \"pre-wrap\":\n                case \"-moz-pre-wrap\":\n                    return false;\n                case \"pre-line\":\n                    if (/[\\r\\n]/.test(node.data)) {\n                        return false;\n                    }\n            }\n\n            // We now have a whitespace-only text node that may be rendered depending on its context. If it is adjacent to a\n            // non-inline element, it will not be rendered. This seems to be a good enough definition.\n            return isNonInlineElement(node.previousSibling) || isNonInlineElement(node.nextSibling);\n        }\n\n        function getRangeBoundaries(ranges) {\n            var positions = [], i, range;\n            for (i = 0; range = ranges[i++]; ) {\n                positions.push(\n                    new DomPosition(range.startContainer, range.startOffset),\n                    new DomPosition(range.endContainer, range.endOffset)\n                );\n            }\n            return positions;\n        }\n\n        function updateRangesFromBoundaries(ranges, positions) {\n            for (var i = 0, range, start, end, len = ranges.length; i < len; ++i) {\n                range = ranges[i];\n                start = positions[i * 2];\n                end = positions[i * 2 + 1];\n                range.setStartAndEnd(start.node, start.offset, end.node, end.offset);\n            }\n        }\n\n        function isSplitPoint(node, offset) {\n            if (dom.isCharacterDataNode(node)) {\n                if (offset == 0) {\n                    return !!node.previousSibling;\n                } else if (offset == node.length) {\n                    return !!node.nextSibling;\n                } else {\n                    return true;\n                }\n            }\n\n            return offset > 0 && offset < node.childNodes.length;\n        }\n\n        function splitNodeAt(node, descendantNode, descendantOffset, positionsToPreserve) {\n            var newNode, parentNode;\n            var splitAtStart = (descendantOffset == 0);\n\n            if (dom.isAncestorOf(descendantNode, node)) {\n                return node;\n            }\n\n            if (dom.isCharacterDataNode(descendantNode)) {\n                var descendantIndex = dom.getNodeIndex(descendantNode);\n                if (descendantOffset == 0) {\n                    descendantOffset = descendantIndex;\n                } else if (descendantOffset == descendantNode.length) {\n                    descendantOffset = descendantIndex + 1;\n                } else {\n                    throw module.createError(\"splitNodeAt() should not be called with offset in the middle of a data node (\" +\n                        descendantOffset + \" in \" + descendantNode.data);\n                }\n                descendantNode = descendantNode.parentNode;\n            }\n\n            if (isSplitPoint(descendantNode, descendantOffset)) {\n                // descendantNode is now guaranteed not to be a text or other character node\n                newNode = descendantNode.cloneNode(false);\n                parentNode = descendantNode.parentNode;\n                if (newNode.id) {\n                    newNode.removeAttribute(\"id\");\n                }\n                var child, newChildIndex = 0;\n\n                while ( (child = descendantNode.childNodes[descendantOffset]) ) {\n                    movePreservingPositions(child, newNode, newChildIndex++, positionsToPreserve);\n                }\n                movePreservingPositions(newNode, parentNode, dom.getNodeIndex(descendantNode) + 1, positionsToPreserve);\n                return (descendantNode == node) ? newNode : splitNodeAt(node, parentNode, dom.getNodeIndex(newNode), positionsToPreserve);\n            } else if (node != descendantNode) {\n                newNode = descendantNode.parentNode;\n\n                // Work out a new split point in the parent node\n                var newNodeIndex = dom.getNodeIndex(descendantNode);\n\n                if (!splitAtStart) {\n                    newNodeIndex++;\n                }\n                return splitNodeAt(node, newNode, newNodeIndex, positionsToPreserve);\n            }\n            return node;\n        }\n\n        function areElementsMergeable(el1, el2) {\n            return el1.namespaceURI == el2.namespaceURI &&\n                el1.tagName.toLowerCase() == el2.tagName.toLowerCase() &&\n                haveSameClasses(el1, el2) &&\n                elementsHaveSameNonClassAttributes(el1, el2) &&\n                getComputedStyleProperty(el1, \"display\") == \"inline\" &&\n                getComputedStyleProperty(el2, \"display\") == \"inline\";\n        }\n\n        function createAdjacentMergeableTextNodeGetter(forward) {\n            var siblingPropName = forward ? \"nextSibling\" : \"previousSibling\";\n\n            return function(textNode, checkParentElement) {\n                var el = textNode.parentNode;\n                var adjacentNode = textNode[siblingPropName];\n                if (adjacentNode) {\n                    // Can merge if the node's previous/next sibling is a text node\n                    if (adjacentNode && adjacentNode.nodeType == 3) {\n                        return adjacentNode;\n                    }\n                } else if (checkParentElement) {\n                    // Compare text node parent element with its sibling\n                    adjacentNode = el[siblingPropName];\n                    if (adjacentNode && adjacentNode.nodeType == 1 && areElementsMergeable(el, adjacentNode)) {\n                        var adjacentNodeChild = adjacentNode[forward ? \"firstChild\" : \"lastChild\"];\n                        if (adjacentNodeChild && adjacentNodeChild.nodeType == 3) {\n                            return adjacentNodeChild;\n                        }\n                    }\n                }\n                return null;\n            };\n        }\n\n        var getPreviousMergeableTextNode = createAdjacentMergeableTextNodeGetter(false),\n            getNextMergeableTextNode = createAdjacentMergeableTextNodeGetter(true);\n\n    \n        function Merge(firstNode) {\n            this.isElementMerge = (firstNode.nodeType == 1);\n            this.textNodes = [];\n            var firstTextNode = this.isElementMerge ? firstNode.lastChild : firstNode;\n            if (firstTextNode) {\n                this.textNodes[0] = firstTextNode;\n            }\n        }\n\n        Merge.prototype = {\n            doMerge: function(positionsToPreserve) {\n                var textNodes = this.textNodes;\n                var firstTextNode = textNodes[0];\n                if (textNodes.length > 1) {\n                    var firstTextNodeIndex = dom.getNodeIndex(firstTextNode);\n                    var textParts = [], combinedTextLength = 0, textNode, parent;\n                    forEach(textNodes, function(textNode, i) {\n                        parent = textNode.parentNode;\n                        if (i > 0) {\n                            parent.removeChild(textNode);\n                            if (!parent.hasChildNodes()) {\n                                dom.removeNode(parent);\n                            }\n                            if (positionsToPreserve) {\n                                forEach(positionsToPreserve, function(position) {\n                                    // Handle case where position is inside the text node being merged into a preceding node\n                                    if (position.node == textNode) {\n                                        position.node = firstTextNode;\n                                        position.offset += combinedTextLength;\n                                    }\n                                    // Handle case where both text nodes precede the position within the same parent node\n                                    if (position.node == parent && position.offset > firstTextNodeIndex) {\n                                        --position.offset;\n                                        if (position.offset == firstTextNodeIndex + 1 && i < textNodes.length - 1) {\n                                            position.node = firstTextNode;\n                                            position.offset = combinedTextLength;\n                                        }\n                                    }\n                                });\n                            }\n                        }\n                        textParts[i] = textNode.data;\n                        combinedTextLength += textNode.data.length;\n                    });\n                    firstTextNode.data = textParts.join(\"\");\n                }\n                return firstTextNode.data;\n            },\n\n            getLength: function() {\n                var i = this.textNodes.length, len = 0;\n                while (i--) {\n                    len += this.textNodes[i].length;\n                }\n                return len;\n            },\n\n            toString: function() {\n                var textParts = [];\n                forEach(this.textNodes, function(textNode, i) {\n                    textParts[i] = \"'\" + textNode.data + \"'\";\n                });\n                return \"[Merge(\" + textParts.join(\",\") + \")]\";\n            }\n        };\n\n        var optionProperties = [\"elementTagName\", \"ignoreWhiteSpace\", \"applyToEditableOnly\", \"useExistingElements\",\n            \"removeEmptyElements\", \"onElementCreate\"];\n\n        // TODO: Populate this with every attribute name that corresponds to a property with a different name. Really??\n        var attrNamesForProperties = {};\n\n        function ClassApplier(className, options, tagNames) {\n            var normalize, i, len, propName, applier = this;\n            applier.cssClass = applier.className = className; // cssClass property is for backward compatibility\n\n            var elementPropertiesFromOptions = null, elementAttributes = {};\n\n            // Initialize from options object\n            if (typeof options == \"object\" && options !== null) {\n                if (typeof options.elementTagName !== \"undefined\") {\n                    options.elementTagName = options.elementTagName.toLowerCase();\n                }\n                tagNames = options.tagNames;\n                elementPropertiesFromOptions = options.elementProperties;\n                elementAttributes = options.elementAttributes;\n\n                for (i = 0; propName = optionProperties[i++]; ) {\n                    if (options.hasOwnProperty(propName)) {\n                        applier[propName] = options[propName];\n                    }\n                }\n                normalize = options.normalize;\n            } else {\n                normalize = options;\n            }\n\n            // Backward compatibility: the second parameter can also be a Boolean indicating to normalize after unapplying\n            applier.normalize = (typeof normalize == \"undefined\") ? true : normalize;\n\n            // Initialize element properties and attribute exceptions\n            applier.attrExceptions = [];\n            var el = document.createElement(applier.elementTagName);\n            applier.elementProperties = applier.copyPropertiesToElement(elementPropertiesFromOptions, el, true);\n            each(elementAttributes, function(attrName, attrValue) {\n                applier.attrExceptions.push(attrName);\n                // Ensure each attribute value is a string\n                elementAttributes[attrName] = \"\" + attrValue;\n            });\n            applier.elementAttributes = elementAttributes;\n\n            applier.elementSortedClassName = applier.elementProperties.hasOwnProperty(\"className\") ?\n                sortClassName(applier.elementProperties.className + \" \" + className) : className;\n\n            // Initialize tag names\n            applier.applyToAnyTagName = false;\n            var type = typeof tagNames;\n            if (type == \"string\") {\n                if (tagNames == \"*\") {\n                    applier.applyToAnyTagName = true;\n                } else {\n                    applier.tagNames = trim(tagNames.toLowerCase()).split(/\\s*,\\s*/);\n                }\n            } else if (type == \"object\" && typeof tagNames.length == \"number\") {\n                applier.tagNames = [];\n                for (i = 0, len = tagNames.length; i < len; ++i) {\n                    if (tagNames[i] == \"*\") {\n                        applier.applyToAnyTagName = true;\n                    } else {\n                        applier.tagNames.push(tagNames[i].toLowerCase());\n                    }\n                }\n            } else {\n                applier.tagNames = [applier.elementTagName];\n            }\n        }\n\n        ClassApplier.prototype = {\n            elementTagName: defaultTagName,\n            elementProperties: {},\n            elementAttributes: {},\n            ignoreWhiteSpace: true,\n            applyToEditableOnly: false,\n            useExistingElements: true,\n            removeEmptyElements: true,\n            onElementCreate: null,\n\n            copyPropertiesToElement: function(props, el, createCopy) {\n                var s, elStyle, elProps = {}, elPropsStyle, propValue, elPropValue, attrName;\n\n                for (var p in props) {\n                    if (props.hasOwnProperty(p)) {\n                        propValue = props[p];\n                        elPropValue = el[p];\n\n                        // Special case for class. The copied properties object has the applier's class as well as its own\n                        // to simplify checks when removing styling elements\n                        if (p == \"className\") {\n                            addClass(el, propValue);\n                            addClass(el, this.className);\n                            el[p] = sortClassName(el[p]);\n                            if (createCopy) {\n                                elProps[p] = propValue;\n                            }\n                        }\n\n                        // Special case for style\n                        else if (p == \"style\") {\n                            elStyle = elPropValue;\n                            if (createCopy) {\n                                elProps[p] = elPropsStyle = {};\n                            }\n                            for (s in props[p]) {\n                                if (props[p].hasOwnProperty(s)) {\n                                    elStyle[s] = propValue[s];\n                                    if (createCopy) {\n                                        elPropsStyle[s] = elStyle[s];\n                                    }\n                                }\n                            }\n                            this.attrExceptions.push(p);\n                        } else {\n                            el[p] = propValue;\n                            // Copy the property back from the dummy element so that later comparisons to check whether\n                            // elements may be removed are checking against the right value. For example, the href property\n                            // of an element returns a fully qualified URL even if it was previously assigned a relative\n                            // URL.\n                            if (createCopy) {\n                                elProps[p] = el[p];\n\n                                // Not all properties map to identically-named attributes\n                                attrName = attrNamesForProperties.hasOwnProperty(p) ? attrNamesForProperties[p] : p;\n                                this.attrExceptions.push(attrName);\n                            }\n                        }\n                    }\n                }\n\n                return createCopy ? elProps : \"\";\n            },\n\n            copyAttributesToElement: function(attrs, el) {\n                for (var attrName in attrs) {\n                    if (attrs.hasOwnProperty(attrName) && !/^class(?:Name)?$/i.test(attrName)) {\n                        el.setAttribute(attrName, attrs[attrName]);\n                    }\n                }\n            },\n\n            appliesToElement: function(el) {\n                return contains(this.tagNames, el.tagName.toLowerCase());\n            },\n\n            getEmptyElements: function(range) {\n                var applier = this;\n                return range.getNodes([1], function(el) {\n                    return applier.appliesToElement(el) && !el.hasChildNodes();\n                });\n            },\n\n            hasClass: function(node) {\n                return node.nodeType == 1 &&\n                    (this.applyToAnyTagName || this.appliesToElement(node)) &&\n                    hasClass(node, this.className);\n            },\n\n            getSelfOrAncestorWithClass: function(node) {\n                while (node) {\n                    if (this.hasClass(node)) {\n                        return node;\n                    }\n                    node = node.parentNode;\n                }\n                return null;\n            },\n\n            isModifiable: function(node) {\n                return !this.applyToEditableOnly || isEditable(node);\n            },\n\n            // White space adjacent to an unwrappable node can be ignored for wrapping\n            isIgnorableWhiteSpaceNode: function(node) {\n                return this.ignoreWhiteSpace && node && node.nodeType == 3 && isUnrenderedWhiteSpaceNode(node);\n            },\n\n            // Normalizes nodes after applying a class to a Range.\n            postApply: function(textNodes, range, positionsToPreserve, isUndo) {\n                var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1];\n                var merges = [], currentMerge;\n                var rangeStartNode = firstNode, rangeEndNode = lastNode;\n                var rangeStartOffset = 0, rangeEndOffset = lastNode.length;\n                var precedingTextNode;\n\n                // Check for every required merge and create a Merge object for each\n                forEach(textNodes, function(textNode) {\n                    precedingTextNode = getPreviousMergeableTextNode(textNode, !isUndo);\n                    if (precedingTextNode) {\n                        if (!currentMerge) {\n                            currentMerge = new Merge(precedingTextNode);\n                            merges.push(currentMerge);\n                        }\n                        currentMerge.textNodes.push(textNode);\n                        if (textNode === firstNode) {\n                            rangeStartNode = currentMerge.textNodes[0];\n                            rangeStartOffset = rangeStartNode.length;\n                        }\n                        if (textNode === lastNode) {\n                            rangeEndNode = currentMerge.textNodes[0];\n                            rangeEndOffset = currentMerge.getLength();\n                        }\n                    } else {\n                        currentMerge = null;\n                    }\n                });\n\n                // Test whether the first node after the range needs merging\n                var nextTextNode = getNextMergeableTextNode(lastNode, !isUndo);\n\n                if (nextTextNode) {\n                    if (!currentMerge) {\n                        currentMerge = new Merge(lastNode);\n                        merges.push(currentMerge);\n                    }\n                    currentMerge.textNodes.push(nextTextNode);\n                }\n\n                // Apply the merges\n                if (merges.length) {\n                    for (var i = 0, len = merges.length; i < len; ++i) {\n                        merges[i].doMerge(positionsToPreserve);\n                    }\n\n                    // Set the range boundaries\n                    range.setStartAndEnd(rangeStartNode, rangeStartOffset, rangeEndNode, rangeEndOffset);\n                }\n            },\n\n            createContainer: function(parentNode) {\n                var doc = dom.getDocument(parentNode);\n                var namespace;\n                var el = createElementNSSupported && !dom.isHtmlNamespace(parentNode) && (namespace = parentNode.namespaceURI) ?\n                    doc.createElementNS(parentNode.namespaceURI, this.elementTagName) :\n                    doc.createElement(this.elementTagName);\n\n                this.copyPropertiesToElement(this.elementProperties, el, false);\n                this.copyAttributesToElement(this.elementAttributes, el);\n                addClass(el, this.className);\n                if (this.onElementCreate) {\n                    this.onElementCreate(el, this);\n                }\n                return el;\n            },\n\n            elementHasProperties: function(el, props) {\n                var applier = this;\n                return each(props, function(p, propValue) {\n                    if (p == \"className\") {\n                        // For checking whether we should reuse an existing element, we just want to check that the element\n                        // has all the classes specified in the className property. When deciding whether the element is\n                        // removable when unapplying a class, there is separate special handling to check whether the\n                        // element has extra classes so the same simple check will do.\n                        return hasAllClasses(el, propValue);\n                    } else if (typeof propValue == \"object\") {\n                        if (!applier.elementHasProperties(el[p], propValue)) {\n                            return false;\n                        }\n                    } else if (el[p] !== propValue) {\n                        return false;\n                    }\n                });\n            },\n\n            elementHasAttributes: function(el, attrs) {\n                return each(attrs, function(name, value) {\n                    if (el.getAttribute(name) !== value) {\n                        return false;\n                    }\n                });\n            },\n\n            applyToTextNode: function(textNode, positionsToPreserve) {\n\n                // Check whether the text node can be styled. Text within a \n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n","\n\n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n\n\n","import { ref } from \"vue\";\nimport {\n  applyHighlights,\n  clearAllHighlights,\n} from \"../../directives/highlightDirective.js\";\n\n/**\n * Composable for orchestrating the entire highlighting system\n * This handles DOM operations, event management, and integration with stores\n */\nfunction useHighlightOrchestrator(\n  smartCommentsSetup,\n  commentsStore,\n  smartCommentsEvents,\n) {\n  const isRefreshing = ref(false);\n\n  /**\n   * Get the target element for highlights\n   */\n  const getTargetElement = () => {\n    return document.getElementById(\"mw-content-text\") || document.body;\n  };\n\n  /**\n   * Handle highlight click events\n   */\n  const handleHighlightClick = (event, commentData, position) => {\n    if (event && event.preventDefault) {\n      event.preventDefault();\n    }\n\n    // Trigger events\n    smartCommentsEvents.triggerHighlightClicked(commentData, position);\n    smartCommentsEvents.triggerCommentGroupOpen(commentData, position);\n\n    commentsStore.openCommentDialog(commentData, position);\n  };\n\n  /**\n   * Reload highlights and update comments store\n   */\n  const reloadHighlightsAndComments = async () => {\n    if (isRefreshing.value) return;\n\n    try {\n      isRefreshing.value = true;\n      const targetElement = getTargetElement();\n\n      // Clear existing highlights first\n      if (smartCommentsSetup.highlightedAnchors?.value) {\n        clearAllHighlights(\n          targetElement,\n          smartCommentsSetup.highlightedAnchors.value,\n        );\n      }\n\n      // Reload comments and highlights from server\n      await smartCommentsSetup.loadAndSetHighlights();\n\n      // Update the comments store with the freshly loaded comments\n      if (smartCommentsSetup.comments?.value !== undefined) {\n        commentsStore.setComments(smartCommentsSetup.comments.value);\n      } else {\n        console.warn(\n          \"useHighlightOrchestrator: comments.value is undefined after loadAndSetHighlights, setting empty array\",\n        );\n        commentsStore.setComments([]);\n      }\n\n      // Apply the fresh highlights\n      if (smartCommentsSetup.highlightedAnchors?.value) {\n        applyHighlights(\n          targetElement,\n          smartCommentsSetup.highlightedAnchors.value,\n          handleHighlightClick,\n        );\n      }\n\n      // Restore active highlight if dialog is open\n      if (commentsStore.isCommentDialogVisible && commentsStore.activeComment) {\n        const commentId =\n          commentsStore.activeComment.data_id || commentsStore.activeComment.id;\n        commentsStore.setActiveHighlight(commentId);\n      }\n    } catch (error) {\n      console.error(\n        \"useHighlightOrchestrator: Error reloading highlights:\",\n        error,\n      );\n    } finally {\n      isRefreshing.value = false;\n    }\n  };\n\n  /**\n   * Clear all highlights\n   */\n  const clearHighlights = () => {\n    const targetElement = getTargetElement();\n    if (smartCommentsSetup.highlightedAnchors?.value) {\n      clearAllHighlights(\n        targetElement,\n        smartCommentsSetup.highlightedAnchors.value,\n      );\n    }\n  };\n\n  /**\n   * Setup highlight refresh event listener\n   */\n  const setupHighlightRefreshListener = () => {\n    const handleHighlightRefresh = async () => {\n      await reloadHighlightsAndComments();\n    };\n\n    document.addEventListener(\n      \"smartcomments:refresh-highlights\",\n      handleHighlightRefresh,\n    );\n\n    return () => {\n      document.removeEventListener(\n        \"smartcomments:refresh-highlights\",\n        handleHighlightRefresh,\n      );\n    };\n  };\n\n  /**\n   * Manual highlight reload (for debugging)\n   */\n  const reloadHighlights = async (isEnabled) => {\n    if (!isEnabled) {\n      console.warn(\n        \"useHighlightOrchestrator: Cannot reload highlights, system is disabled.\",\n      );\n      return;\n    }\n\n    if (!smartCommentsSetup?.loadAndSetHighlights) {\n      console.error(\n        \"useHighlightOrchestrator: smartCommentsSetup.loadAndSetHighlights not available.\",\n      );\n      return;\n    }\n\n    try {\n      clearHighlights();\n      await reloadHighlightsAndComments();\n    } catch (error) {\n      console.error(\"useHighlightOrchestrator reloadHighlights: Error:\", error);\n    }\n  };\n\n  return {\n    isRefreshing,\n    reloadHighlightsAndComments,\n    clearHighlights,\n    setupHighlightRefreshListener,\n    reloadHighlights,\n    handleHighlightClick,\n  };\n}\n\nexport default useHighlightOrchestrator;\n","/**\n * Composable for managing keyboard shortcuts\n */\nfunction useKeyboardShortcuts(commentsStore) {\n  /**\n   * Handle keyboard shortcuts\n   */\n  const handleKeydown = (event) => {\n    if (event.key === \"Escape\" && commentsStore.isCommentDialogVisible) {\n      // If image modal is open, close it first\n      if (commentsStore.isImageModalVisible) {\n        commentsStore.closeImageModal();\n      } else {\n        // Otherwise close the comment dialog\n        commentsStore.closeCommentDialog();\n      }\n    } else if (event.key === \"ArrowDown\" && commentsStore.hasNextComment) {\n      commentsStore.navigateComment(\"next\");\n    } else if (event.key === \"ArrowUp\" && commentsStore.hasPreviousComment) {\n      commentsStore.navigateComment(\"previous\");\n    }\n  };\n\n  /**\n   * Setup keyboard event listeners\n   */\n  const setupKeyboardShortcuts = () => {\n    document.addEventListener(\"keydown\", handleKeydown);\n\n    return () => {\n      document.removeEventListener(\"keydown\", handleKeydown);\n    };\n  };\n\n  return {\n    setupKeyboardShortcuts,\n  };\n}\n\nexport default useKeyboardShortcuts;\n","import { watch } from \"vue\";\n\n/**\n * Composable for managing CSS custom properties\n */\nfunction useCustomProperties(messages) {\n  /**\n   * Update CSS custom property for annotate tooltip text\n   */\n  const updateAnnotateTooltipText = (text) => {\n    document.documentElement.style.setProperty(\n      \"--smartcomments-annotate-text\",\n      `\"${text}\"`,\n    );\n  };\n\n  /**\n   * Update CSS custom property for button open text\n   */\n  const updateButtonOpenText = (text) => {\n    document.documentElement.style.setProperty(\n      \"--smartcomments-button-open-text\",\n      `\"${text}\"`,\n    );\n  };\n\n  /**\n   * Setup watchers for CSS custom properties\n   */\n  const setupCustomPropertiesWatchers = () => {\n    const annotateTooltipText = () => messages.msg(\"sc-annotate-tooltip\");\n    const buttonOpenText = () => messages.msg(\"sc-button-open\");\n\n    // Initial setup\n    updateAnnotateTooltipText(annotateTooltipText());\n    updateButtonOpenText(buttonOpenText());\n\n    // Watch for changes (e.g., language changes)\n    const stopAnnotateWatcher = watch(annotateTooltipText, (newText) => {\n      updateAnnotateTooltipText(newText);\n    });\n\n    const stopButtonWatcher = watch(buttonOpenText, (newText) => {\n      updateButtonOpenText(newText);\n    });\n\n    return () => {\n      stopAnnotateWatcher();\n      stopButtonWatcher();\n    };\n  };\n\n  return {\n    setupCustomPropertiesWatchers,\n    updateAnnotateTooltipText,\n    updateButtonOpenText,\n  };\n}\n\nexport default useCustomProperties;\n","/**\n * Composable for managing SmartComments event handlers\n */\nfunction useSmartCommentsEventHandlers(\n  smartCommentsEvents,\n  EVENTS,\n  store,\n  commentsStore,\n  highlightsManager,\n) {\n  /**\n   * Setup SmartComments events\n   */\n  const setupSmartCommentsEvents = () => {\n    const cleanupFunctions = [];\n\n    // Listen for debug mode events\n    cleanupFunctions.push(\n      smartCommentsEvents.on(EVENTS.DEBUG_MODE, (event) => {\n        if (event.detail.enabled && !store.isEnabled) {\n          store.setEnabled(true);\n        }\n      }),\n    );\n\n    // Listen for selection active events\n    cleanupFunctions.push(\n      smartCommentsEvents.on(EVENTS.SELECTION_ACTIVE, (event) => {\n        // Close any open comment dialogs when a new selection is made\n        if (commentsStore.isCommentDialogVisible) {\n          commentsStore.closeCommentDialog();\n        }\n      }),\n    );\n\n    // Listen for open comment events\n    cleanupFunctions.push(\n      smartCommentsEvents.on(EVENTS.OPEN_COMMENT_ID, (event) => {\n        if (event.detail.commentId) {\n          // Handle opening specific comment\n          commentsStore.openCommentDialogById(event.detail.commentId);\n        }\n      }),\n    );\n\n    // Listen for open comment with position events\n    cleanupFunctions.push(\n      smartCommentsEvents.on(EVENTS.OPEN_COMMENT_WITH_POSITION, (event) => {\n        if (event.detail.commentId && event.detail.position) {\n          // Handle opening specific comment with custom position\n          commentsStore.openCommentDialogByIdWithPosition(event.detail.commentId, event.detail.position);\n        }\n      }),\n    );\n\n    // Listen for comment created events\n    cleanupFunctions.push(\n      smartCommentsEvents.on(EVENTS.COMMENT_CREATED, (event) => {\n        if (highlightsManager) {\n          highlightsManager.reloadHighlightsAndComments();\n        }\n      }),\n    );\n\n    return () => {\n      cleanupFunctions.forEach((cleanup) => cleanup());\n    };\n  };\n\n  return {\n    setupSmartCommentsEvents,\n  };\n}\n\nexport default useSmartCommentsEventHandlers;\n","/**\n * Composable for managing URL navigation and parameters\n */\nfunction useUrlNavigation(commentsStore) {\n  /**\n   * Setup URL navigation handlers\n   */\n  const setupUrlNavigation = (isEnabled) => {\n    // Handle URL changes (back/forward navigation)\n    const handlePopState = async () => {\n      if (isEnabled()) {\n        await commentsStore.checkAndOpenCommentFromUrl();\n      }\n    };\n\n    window.addEventListener(\"popstate\", handlePopState);\n\n    return () => {\n      window.removeEventListener(\"popstate\", handlePopState);\n    };\n  };\n\n  /**\n   * Check URL parameters and open comment (for debugging)\n   */\n  const checkUrlParameters = async (isEnabled) => {\n    if (!isEnabled()) {\n      console.warn(\n        \"useUrlNavigation: Cannot check URL parameters, system is disabled.\",\n      );\n      return;\n    }\n    await commentsStore.checkAndOpenCommentFromUrl();\n  };\n\n  return {\n    setupUrlNavigation,\n    checkUrlParameters,\n  };\n}\n\nexport default useUrlNavigation;\n","/**\n * Rangy, a cross-browser JavaScript range and selection library\n * https://github.com/timdown/rangy\n *\n * Copyright 2024, Tim Down\n * Licensed under the MIT license.\n * Version: 1.3.2\n * Build date: 2 November 2024\n */\n\n(function(factory, root) {\n    if (typeof define == \"function\" && define.amd) {\n        // AMD. Register as an anonymous module.\n        define(factory);\n    } else if (typeof module != \"undefined\" && typeof exports == \"object\") {\n        // Node/CommonJS style\n        module.exports = factory();\n    } else {\n        // No AMD or CommonJS support so we place Rangy in (probably) the global variable\n        root.rangy = factory();\n    }\n})(function() {\n\n    var OBJECT = \"object\", FUNCTION = \"function\", UNDEFINED = \"undefined\";\n\n    // Minimal set of properties required for DOM Level 2 Range compliance. Comparison constants such as START_TO_START\n    // are omitted because ranges in KHTML do not have them but otherwise work perfectly well. See issue 113.\n    var domRangeProperties = [\"startContainer\", \"startOffset\", \"endContainer\", \"endOffset\", \"collapsed\",\n        \"commonAncestorContainer\"];\n\n    // Minimal set of methods required for DOM Level 2 Range compliance\n    var domRangeMethods = [\"setStart\", \"setStartBefore\", \"setStartAfter\", \"setEnd\", \"setEndBefore\",\n        \"setEndAfter\", \"collapse\", \"selectNode\", \"selectNodeContents\", \"compareBoundaryPoints\", \"deleteContents\",\n        \"extractContents\", \"cloneContents\", \"insertNode\", \"surroundContents\", \"cloneRange\", \"toString\", \"detach\"];\n\n    var textRangeProperties = [\"boundingHeight\", \"boundingLeft\", \"boundingTop\", \"boundingWidth\", \"htmlText\", \"text\"];\n\n    // Subset of TextRange's full set of methods that we're interested in\n    var textRangeMethods = [\"collapse\", \"compareEndPoints\", \"duplicate\", \"moveToElementText\", \"parentElement\", \"select\",\n        \"setEndPoint\", \"getBoundingClientRect\"];\n\n    /*----------------------------------------------------------------------------------------------------------------*/\n\n    // Trio of functions taken from Peter Michaux's article:\n    // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting\n    function isHostMethod(o, p) {\n        var t = typeof o[p];\n        return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == \"unknown\";\n    }\n\n    function isHostObject(o, p) {\n        return !!(typeof o[p] == OBJECT && o[p]);\n    }\n\n    function isHostProperty(o, p) {\n        return typeof o[p] != UNDEFINED;\n    }\n\n    // Creates a convenience function to save verbose repeated calls to tests functions\n    function createMultiplePropertyTest(testFunc) {\n        return function(o, props) {\n            var i = props.length;\n            while (i--) {\n                if (!testFunc(o, props[i])) {\n                    return false;\n                }\n            }\n            return true;\n        };\n    }\n\n    // Next trio of functions are a convenience to save verbose repeated calls to previous two functions\n    var areHostMethods = createMultiplePropertyTest(isHostMethod);\n    var areHostObjects = createMultiplePropertyTest(isHostObject);\n    var areHostProperties = createMultiplePropertyTest(isHostProperty);\n\n    function isTextRange(range) {\n        return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);\n    }\n\n    function getBody(doc) {\n        return isHostObject(doc, \"body\") ? doc.body : doc.getElementsByTagName(\"body\")[0];\n    }\n\n    var forEach = [].forEach ?\n        function(arr, func) {\n            arr.forEach(func);\n        } :\n        function(arr, func) {\n            for (var i = 0, len = arr.length; i < len; ++i) {\n                func(arr[i], i);\n            }\n        };\n\n    var modules = {};\n\n    var isBrowser = (typeof window != UNDEFINED && typeof document != UNDEFINED);\n\n    var util = {\n        isHostMethod: isHostMethod,\n        isHostObject: isHostObject,\n        isHostProperty: isHostProperty,\n        areHostMethods: areHostMethods,\n        areHostObjects: areHostObjects,\n        areHostProperties: areHostProperties,\n        isTextRange: isTextRange,\n        getBody: getBody,\n        forEach: forEach\n    };\n\n    var api = {\n        version: \"1.3.2\",\n        initialized: false,\n        isBrowser: isBrowser,\n        supported: true,\n        util: util,\n        features: {},\n        modules: modules,\n        config: {\n            alertOnFail: false,\n            alertOnWarn: false,\n            preferTextRange: false,\n            autoInitialize: (typeof rangyAutoInitialize == UNDEFINED) ? true : rangyAutoInitialize\n        }\n    };\n\n    function consoleLog(msg) {\n        if (typeof console != UNDEFINED && isHostMethod(console, \"log\")) {\n            console.log(msg);\n        }\n    }\n\n    function alertOrLog(msg, shouldAlert) {\n        if (isBrowser && shouldAlert) {\n            alert(msg);\n        } else  {\n            consoleLog(msg);\n        }\n    }\n\n    function fail(reason) {\n        api.initialized = true;\n        api.supported = false;\n        alertOrLog(\"Rangy is not supported in this environment. Reason: \" + reason, api.config.alertOnFail);\n    }\n\n    api.fail = fail;\n\n    function warn(msg) {\n        alertOrLog(\"Rangy warning: \" + msg, api.config.alertOnWarn);\n    }\n\n    api.warn = warn;\n\n    // Add utility extend() method\n    var extend;\n    if ({}.hasOwnProperty) {\n        util.extend = extend = function(obj, props, deep) {\n            var o, p;\n            for (var i in props) {\n                if (i === \"__proto__\" || i === \"constructor\" || i === \"prototype\") {\n                    continue;\n                }\n                if (props.hasOwnProperty(i)) {\n                    o = obj[i];\n                    p = props[i];\n                    if (deep && o !== null && typeof o == \"object\" && p !== null && typeof p == \"object\") {\n                        extend(o, p, true);\n                    }\n                    obj[i] = p;\n                }\n            }\n            // Special case for toString, which does not show up in for...in loops in IE <= 8\n            if (props.hasOwnProperty(\"toString\")) {\n                obj.toString = props.toString;\n            }\n            return obj;\n        };\n\n        util.createOptions = function(optionsParam, defaults) {\n            var options = {};\n            extend(options, defaults);\n            if (optionsParam) {\n                extend(options, optionsParam);\n            }\n            return options;\n        };\n    } else {\n        fail(\"hasOwnProperty not supported\");\n    }\n\n    // Test whether we're in a browser and bail out if not\n    if (!isBrowser) {\n        fail(\"Rangy can only run in a browser\");\n    }\n\n    // Test whether Array.prototype.slice can be relied on for NodeLists and use an alternative toArray() if not\n    (function() {\n        var toArray;\n\n        if (isBrowser) {\n            var el = document.createElement(\"div\");\n            el.appendChild(document.createElement(\"span\"));\n            var slice = [].slice;\n            try {\n                if (slice.call(el.childNodes, 0)[0].nodeType == 1) {\n                    toArray = function(arrayLike) {\n                        return slice.call(arrayLike, 0);\n                    };\n                }\n            } catch (e) {}\n        }\n\n        if (!toArray) {\n            toArray = function(arrayLike) {\n                var arr = [];\n                for (var i = 0, len = arrayLike.length; i < len; ++i) {\n                    arr[i] = arrayLike[i];\n                }\n                return arr;\n            };\n        }\n\n        util.toArray = toArray;\n    })();\n\n    // Very simple event handler wrapper function that doesn't attempt to solve issues such as \"this\" handling or\n    // normalization of event properties because we don't need this.\n    var addListener;\n    if (isBrowser) {\n        if (isHostMethod(document, \"addEventListener\")) {\n            addListener = function(obj, eventType, listener) {\n                obj.addEventListener(eventType, listener, false);\n            };\n        } else if (isHostMethod(document, \"attachEvent\")) {\n            addListener = function(obj, eventType, listener) {\n                obj.attachEvent(\"on\" + eventType, listener);\n            };\n        } else {\n            fail(\"Document does not have required addEventListener or attachEvent method\");\n        }\n\n        util.addListener = addListener;\n    }\n\n    var initListeners = [];\n\n    function getErrorDesc(ex) {\n        return ex.message || ex.description || String(ex);\n    }\n\n    // Initialization\n    function init() {\n        if (!isBrowser || api.initialized) {\n            return;\n        }\n        var testRange;\n        var implementsDomRange = false, implementsTextRange = false;\n\n        // First, perform basic feature tests\n\n        if (isHostMethod(document, \"createRange\")) {\n            testRange = document.createRange();\n            if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {\n                implementsDomRange = true;\n            }\n        }\n\n        var body = getBody(document);\n        if (!body || body.nodeName.toLowerCase() != \"body\") {\n            fail(\"No body element found\");\n            return;\n        }\n\n        if (body && isHostMethod(body, \"createTextRange\")) {\n            testRange = body.createTextRange();\n            if (isTextRange(testRange)) {\n                implementsTextRange = true;\n            }\n        }\n\n        if (!implementsDomRange && !implementsTextRange) {\n            fail(\"Neither Range nor TextRange are available\");\n            return;\n        }\n\n        api.initialized = true;\n        api.features = {\n            implementsDomRange: implementsDomRange,\n            implementsTextRange: implementsTextRange\n        };\n\n        // Initialize modules\n        var module, errorMessage;\n        for (var moduleName in modules) {\n            if ( (module = modules[moduleName]) instanceof Module ) {\n                module.init(module, api);\n            }\n        }\n\n        // Call init listeners\n        for (var i = 0, len = initListeners.length; i < len; ++i) {\n            try {\n                initListeners[i](api);\n            } catch (ex) {\n                errorMessage = \"Rangy init listener threw an exception. Continuing. Detail: \" + getErrorDesc(ex);\n                consoleLog(errorMessage);\n            }\n        }\n    }\n\n    function deprecationNotice(deprecated, replacement, module) {\n        if (module) {\n            deprecated += \" in module \" + module.name;\n        }\n        api.warn(\"DEPRECATED: \" + deprecated + \" is deprecated. Please use \" +\n        replacement + \" instead.\");\n    }\n\n    function createAliasForDeprecatedMethod(owner, deprecated, replacement, module) {\n        owner[deprecated] = function() {\n            deprecationNotice(deprecated, replacement, module);\n            return owner[replacement].apply(owner, util.toArray(arguments));\n        };\n    }\n\n    util.deprecationNotice = deprecationNotice;\n    util.createAliasForDeprecatedMethod = createAliasForDeprecatedMethod;\n\n    // Allow external scripts to initialize this library in case it's loaded after the document has loaded\n    api.init = init;\n\n    // Execute listener immediately if already initialized\n    api.addInitListener = function(listener) {\n        if (api.initialized) {\n            listener(api);\n        } else {\n            initListeners.push(listener);\n        }\n    };\n\n    var shimListeners = [];\n\n    api.addShimListener = function(listener) {\n        shimListeners.push(listener);\n    };\n\n    function shim(win) {\n        win = win || window;\n        init();\n\n        // Notify listeners\n        for (var i = 0, len = shimListeners.length; i < len; ++i) {\n            shimListeners[i](win);\n        }\n    }\n\n    if (isBrowser) {\n        api.shim = api.createMissingNativeApi = shim;\n        createAliasForDeprecatedMethod(api, \"createMissingNativeApi\", \"shim\");\n    }\n\n    function Module(name, dependencies, initializer) {\n        this.name = name;\n        this.dependencies = dependencies;\n        this.initialized = false;\n        this.supported = false;\n        this.initializer = initializer;\n    }\n\n    Module.prototype = {\n        init: function() {\n            var requiredModuleNames = this.dependencies || [];\n            for (var i = 0, len = requiredModuleNames.length, requiredModule, moduleName; i < len; ++i) {\n                moduleName = requiredModuleNames[i];\n\n                requiredModule = modules[moduleName];\n                if (!requiredModule || !(requiredModule instanceof Module)) {\n                    throw new Error(\"required module '\" + moduleName + \"' not found\");\n                }\n\n                requiredModule.init();\n\n                if (!requiredModule.supported) {\n                    throw new Error(\"required module '\" + moduleName + \"' not supported\");\n                }\n            }\n\n            // Now run initializer\n            this.initializer(this);\n        },\n\n        fail: function(reason) {\n            this.initialized = true;\n            this.supported = false;\n            throw new Error(reason);\n        },\n\n        warn: function(msg) {\n            api.warn(\"Module \" + this.name + \": \" + msg);\n        },\n\n        deprecationNotice: function(deprecated, replacement) {\n            api.warn(\"DEPRECATED: \" + deprecated + \" in module \" + this.name + \" is deprecated. Please use \" +\n                replacement + \" instead\");\n        },\n\n        createError: function(msg) {\n            return new Error(\"Error in Rangy \" + this.name + \" module: \" + msg);\n        }\n    };\n\n    function createModule(name, dependencies, initFunc) {\n        var newModule = new Module(name, dependencies, function(module) {\n            if (!module.initialized) {\n                module.initialized = true;\n                try {\n                    initFunc(api, module);\n                    module.supported = true;\n                } catch (ex) {\n                    var errorMessage = \"Module '\" + name + \"' failed to load: \" + getErrorDesc(ex);\n                    consoleLog(errorMessage);\n                    if (ex.stack) {\n                        consoleLog(ex.stack);\n                    }\n                }\n            }\n        });\n        modules[name] = newModule;\n        return newModule;\n    }\n\n    api.createModule = function(name) {\n        // Allow 2 or 3 arguments (second argument is an optional array of dependencies)\n        var initFunc, dependencies;\n        if (arguments.length == 2) {\n            initFunc = arguments[1];\n            dependencies = [];\n        } else {\n            initFunc = arguments[2];\n            dependencies = arguments[1];\n        }\n\n        var module = createModule(name, dependencies, initFunc);\n\n        // Initialize the module immediately if the core is already initialized\n        if (api.initialized && api.supported) {\n            module.init();\n        }\n    };\n\n    api.createCoreModule = function(name, dependencies, initFunc) {\n        createModule(name, dependencies, initFunc);\n    };\n\n    /*----------------------------------------------------------------------------------------------------------------*/\n\n    // Ensure rangy.rangePrototype and rangy.selectionPrototype are available immediately\n\n    function RangePrototype() {}\n    api.RangePrototype = RangePrototype;\n    api.rangePrototype = new RangePrototype();\n\n    function SelectionPrototype() {}\n    api.selectionPrototype = new SelectionPrototype();\n\n    /*----------------------------------------------------------------------------------------------------------------*/\n\n    // DOM utility methods used by Rangy\n    api.createCoreModule(\"DomUtil\", [], function(api, module) {\n        var UNDEF = \"undefined\";\n        var util = api.util;\n        var getBody = util.getBody;\n\n        // Perform feature tests\n        if (!util.areHostMethods(document, [\"createDocumentFragment\", \"createElement\", \"createTextNode\"])) {\n            module.fail(\"document missing a Node creation method\");\n        }\n\n        if (!util.isHostMethod(document, \"getElementsByTagName\")) {\n            module.fail(\"document missing getElementsByTagName method\");\n        }\n\n        var el = document.createElement(\"div\");\n        if (!util.areHostMethods(el, [\"insertBefore\", \"appendChild\", \"cloneNode\"] ||\n                !util.areHostObjects(el, [\"previousSibling\", \"nextSibling\", \"childNodes\", \"parentNode\"]))) {\n            module.fail(\"Incomplete Element implementation\");\n        }\n\n        // innerHTML is required for Range's createContextualFragment method\n        if (!util.isHostProperty(el, \"innerHTML\")) {\n            module.fail(\"Element is missing innerHTML property\");\n        }\n\n        var textNode = document.createTextNode(\"test\");\n        if (!util.areHostMethods(textNode, [\"splitText\", \"deleteData\", \"insertData\", \"appendData\", \"cloneNode\"] ||\n                !util.areHostObjects(el, [\"previousSibling\", \"nextSibling\", \"childNodes\", \"parentNode\"]) ||\n                !util.areHostProperties(textNode, [\"data\"]))) {\n            module.fail(\"Incomplete Text Node implementation\");\n        }\n\n        /*----------------------------------------------------------------------------------------------------------------*/\n\n        // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been\n        // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that\n        // contains just the document as a single element and the value searched for is the document.\n        var arrayContains = /*Array.prototype.indexOf ?\n            function(arr, val) {\n                return arr.indexOf(val) > -1;\n            }:*/\n\n            function(arr, val) {\n                var i = arr.length;\n                while (i--) {\n                    if (arr[i] === val) {\n                        return true;\n                    }\n                }\n                return false;\n            };\n\n        // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI\n        function isHtmlNamespace(node) {\n            var ns;\n            return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == \"http://www.w3.org/1999/xhtml\");\n        }\n\n        function parentElement(node) {\n            var parent = node.parentNode;\n            return (parent.nodeType == 1) ? parent : null;\n        }\n\n        function getNodeIndex(node) {\n            var i = 0;\n            while( (node = node.previousSibling) ) {\n                ++i;\n            }\n            return i;\n        }\n\n        function getNodeLength(node) {\n            switch (node.nodeType) {\n                case 7:\n                case 10:\n                    return 0;\n                case 3:\n                case 8:\n                    return node.length;\n                default:\n                    return node.childNodes.length;\n            }\n        }\n\n        function getCommonAncestor(node1, node2) {\n            var ancestors = [], n;\n            for (n = node1; n; n = n.parentNode) {\n                ancestors.push(n);\n            }\n\n            for (n = node2; n; n = n.parentNode) {\n                if (arrayContains(ancestors, n)) {\n                    return n;\n                }\n            }\n\n            return null;\n        }\n\n        function isAncestorOf(ancestor, descendant, selfIsAncestor) {\n            var n = selfIsAncestor ? descendant : descendant.parentNode;\n            while (n) {\n                if (n === ancestor) {\n                    return true;\n                } else {\n                    n = n.parentNode;\n                }\n            }\n            return false;\n        }\n\n        function isOrIsAncestorOf(ancestor, descendant) {\n            return isAncestorOf(ancestor, descendant, true);\n        }\n\n        function getClosestAncestorIn(node, ancestor, selfIsAncestor) {\n            var p, n = selfIsAncestor ? node : node.parentNode;\n            while (n) {\n                p = n.parentNode;\n                if (p === ancestor) {\n                    return n;\n                }\n                n = p;\n            }\n            return null;\n        }\n\n        function isCharacterDataNode(node) {\n            var t = node.nodeType;\n            return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment\n        }\n\n        function isTextOrCommentNode(node) {\n            if (!node) {\n                return false;\n            }\n            var t = node.nodeType;\n            return t == 3 || t == 8 ; // Text or Comment\n        }\n\n        function insertAfter(node, precedingNode) {\n            var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;\n            if (nextNode) {\n                parent.insertBefore(node, nextNode);\n            } else {\n                parent.appendChild(node);\n            }\n            return node;\n        }\n\n        // Note that we cannot use splitText() because it is bugridden in IE 9.\n        function splitDataNode(node, index, positionsToPreserve) {\n            var newNode = node.cloneNode(false);\n            newNode.deleteData(0, index);\n            node.deleteData(index, node.length - index);\n            insertAfter(newNode, node);\n\n            // Preserve positions\n            if (positionsToPreserve) {\n                for (var i = 0, position; position = positionsToPreserve[i++]; ) {\n                    // Handle case where position was inside the portion of node after the split point\n                    if (position.node == node && position.offset > index) {\n                        position.node = newNode;\n                        position.offset -= index;\n                    }\n                    // Handle the case where the position is a node offset within node's parent\n                    else if (position.node == node.parentNode && position.offset > getNodeIndex(node)) {\n                        ++position.offset;\n                    }\n                }\n            }\n            return newNode;\n        }\n\n        function getDocument(node) {\n            if (node.nodeType == 9) {\n                return node;\n            } else if (typeof node.ownerDocument != UNDEF) {\n                return node.ownerDocument;\n            } else if (typeof node.document != UNDEF) {\n                return node.document;\n            } else if (node.parentNode) {\n                return getDocument(node.parentNode);\n            } else {\n                throw module.createError(\"getDocument: no document found for node\");\n            }\n        }\n\n        function getWindow(node) {\n            var doc = getDocument(node);\n            if (typeof doc.defaultView != UNDEF) {\n                return doc.defaultView;\n            } else if (typeof doc.parentWindow != UNDEF) {\n                return doc.parentWindow;\n            } else {\n                throw module.createError(\"Cannot get a window object for node\");\n            }\n        }\n\n        function getIframeDocument(iframeEl) {\n            if (typeof iframeEl.contentDocument != UNDEF) {\n                return iframeEl.contentDocument;\n            } else if (typeof iframeEl.contentWindow != UNDEF) {\n                return iframeEl.contentWindow.document;\n            } else {\n                throw module.createError(\"getIframeDocument: No Document object found for iframe element\");\n            }\n        }\n\n        function getIframeWindow(iframeEl) {\n            if (typeof iframeEl.contentWindow != UNDEF) {\n                return iframeEl.contentWindow;\n            } else if (typeof iframeEl.contentDocument != UNDEF) {\n                return iframeEl.contentDocument.defaultView;\n            } else {\n                throw module.createError(\"getIframeWindow: No Window object found for iframe element\");\n            }\n        }\n\n        // This looks bad. Is it worth it?\n        function isWindow(obj) {\n            return obj && util.isHostMethod(obj, \"setTimeout\") && util.isHostObject(obj, \"document\");\n        }\n\n        function getContentDocument(obj, module, methodName) {\n            var doc;\n\n            if (!obj) {\n                doc = document;\n            }\n\n            // Test if a DOM node has been passed and obtain a document object for it if so\n            else if (util.isHostProperty(obj, \"nodeType\")) {\n                doc = (obj.nodeType == 1 && obj.tagName.toLowerCase() == \"iframe\") ?\n                    getIframeDocument(obj) : getDocument(obj);\n            }\n\n            // Test if the doc parameter appears to be a Window object\n            else if (isWindow(obj)) {\n                doc = obj.document;\n            }\n\n            if (!doc) {\n                throw module.createError(methodName + \"(): Parameter must be a Window object or DOM node\");\n            }\n\n            return doc;\n        }\n\n        function getRootContainer(node) {\n            var parent;\n            while ( (parent = node.parentNode) ) {\n                node = parent;\n            }\n            return node;\n        }\n\n        function comparePoints(nodeA, offsetA, nodeB, offsetB) {\n            // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing\n            var nodeC, root, childA, childB, n;\n            if (nodeA == nodeB) {\n                // Case 1: nodes are the same\n                return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;\n            } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {\n                // Case 2: node C (container B or an ancestor) is a child node of A\n                return offsetA <= getNodeIndex(nodeC) ? -1 : 1;\n            } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {\n                // Case 3: node C (container A or an ancestor) is a child node of B\n                return getNodeIndex(nodeC) < offsetB  ? -1 : 1;\n            } else {\n                root = getCommonAncestor(nodeA, nodeB);\n                if (!root) {\n                    throw new Error(\"comparePoints error: nodes have no common ancestor\");\n                }\n\n                // Case 4: containers are siblings or descendants of siblings\n                childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);\n                childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);\n\n                if (childA === childB) {\n                    // This shouldn't be possible\n                    throw module.createError(\"comparePoints got to case 4 and childA and childB are the same!\");\n                } else {\n                    n = root.firstChild;\n                    while (n) {\n                        if (n === childA) {\n                            return -1;\n                        } else if (n === childB) {\n                            return 1;\n                        }\n                        n = n.nextSibling;\n                    }\n                }\n            }\n        }\n\n        /*----------------------------------------------------------------------------------------------------------------*/\n\n        // Test for IE's crash (IE 6/7) or exception (IE >= 8) when a reference to garbage-collected text node is queried\n        var crashyTextNodes = false;\n\n        function isBrokenNode(node) {\n            var n;\n            try {\n                n = node.parentNode;\n                return false;\n            } catch (e) {\n                return true;\n            }\n        }\n\n        (function() {\n            var el = document.createElement(\"b\");\n            el.innerHTML = \"1\";\n            var textNode = el.firstChild;\n            el.innerHTML = \"
\";\n crashyTextNodes = isBrokenNode(textNode);\n\n api.features.crashyTextNodes = crashyTextNodes;\n })();\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n function inspectNode(node) {\n if (!node) {\n return \"[No node]\";\n }\n if (crashyTextNodes && isBrokenNode(node)) {\n return \"[Broken node]\";\n }\n if (isCharacterDataNode(node)) {\n return '\"' + node.data + '\"';\n }\n if (node.nodeType == 1) {\n var idAttr = node.id ? ' id=\"' + node.id + '\"' : \"\";\n return \"<\" + node.nodeName + idAttr + \">[index:\" + getNodeIndex(node) + \",length:\" + node.childNodes.length + \"][\" + (node.innerHTML || \"[innerHTML not supported]\").slice(0, 25) + \"]\";\n }\n return node.nodeName;\n }\n\n function fragmentFromNodeChildren(node) {\n var fragment = getDocument(node).createDocumentFragment(), child;\n while ( (child = node.firstChild) ) {\n fragment.appendChild(child);\n }\n return fragment;\n }\n\n var getComputedStyleProperty;\n if (typeof window.getComputedStyle != UNDEF) {\n getComputedStyleProperty = function(el, propName) {\n return getWindow(el).getComputedStyle(el, null)[propName];\n };\n } else if (typeof document.documentElement.currentStyle != UNDEF) {\n getComputedStyleProperty = function(el, propName) {\n return el.currentStyle ? el.currentStyle[propName] : \"\";\n };\n } else {\n module.fail(\"No means of obtaining computed style properties found\");\n }\n\n function createTestElement(doc, html, contentEditable) {\n var body = getBody(doc);\n var el = doc.createElement(\"div\");\n el.contentEditable = \"\" + !!contentEditable;\n if (html) {\n el.innerHTML = html;\n }\n\n // Insert the test element at the start of the body to prevent scrolling to the bottom in iOS (issue #292)\n var bodyFirstChild = body.firstChild;\n if (bodyFirstChild) {\n body.insertBefore(el, bodyFirstChild);\n } else {\n body.appendChild(el);\n }\n\n return el;\n }\n\n function removeNode(node) {\n return node.parentNode.removeChild(node);\n }\n\n function NodeIterator(root) {\n this.root = root;\n this._next = root;\n }\n\n NodeIterator.prototype = {\n _current: null,\n\n hasNext: function() {\n return !!this._next;\n },\n\n next: function() {\n var n = this._current = this._next;\n var child, next;\n if (this._current) {\n child = n.firstChild;\n if (child) {\n this._next = child;\n } else {\n next = null;\n while ((n !== this.root) && !(next = n.nextSibling)) {\n n = n.parentNode;\n }\n this._next = next;\n }\n }\n return this._current;\n },\n\n detach: function() {\n this._current = this._next = this.root = null;\n }\n };\n\n function createIterator(root) {\n return new NodeIterator(root);\n }\n\n function DomPosition(node, offset) {\n this.node = node;\n this.offset = offset;\n }\n\n DomPosition.prototype = {\n equals: function(pos) {\n return !!pos && this.node === pos.node && this.offset == pos.offset;\n },\n\n inspect: function() {\n return \"[DomPosition(\" + inspectNode(this.node) + \":\" + this.offset + \")]\";\n },\n\n toString: function() {\n return this.inspect();\n }\n };\n\n function DOMException(codeName) {\n this.code = this[codeName];\n this.codeName = codeName;\n this.message = \"DOMException: \" + this.codeName;\n }\n\n DOMException.prototype = {\n INDEX_SIZE_ERR: 1,\n HIERARCHY_REQUEST_ERR: 3,\n WRONG_DOCUMENT_ERR: 4,\n NO_MODIFICATION_ALLOWED_ERR: 7,\n NOT_FOUND_ERR: 8,\n NOT_SUPPORTED_ERR: 9,\n INVALID_STATE_ERR: 11,\n INVALID_NODE_TYPE_ERR: 24\n };\n\n DOMException.prototype.toString = function() {\n return this.message;\n };\n\n api.dom = {\n arrayContains: arrayContains,\n isHtmlNamespace: isHtmlNamespace,\n parentElement: parentElement,\n getNodeIndex: getNodeIndex,\n getNodeLength: getNodeLength,\n getCommonAncestor: getCommonAncestor,\n isAncestorOf: isAncestorOf,\n isOrIsAncestorOf: isOrIsAncestorOf,\n getClosestAncestorIn: getClosestAncestorIn,\n isCharacterDataNode: isCharacterDataNode,\n isTextOrCommentNode: isTextOrCommentNode,\n insertAfter: insertAfter,\n splitDataNode: splitDataNode,\n getDocument: getDocument,\n getWindow: getWindow,\n getIframeWindow: getIframeWindow,\n getIframeDocument: getIframeDocument,\n getBody: getBody,\n isWindow: isWindow,\n getContentDocument: getContentDocument,\n getRootContainer: getRootContainer,\n comparePoints: comparePoints,\n isBrokenNode: isBrokenNode,\n inspectNode: inspectNode,\n getComputedStyleProperty: getComputedStyleProperty,\n createTestElement: createTestElement,\n removeNode: removeNode,\n fragmentFromNodeChildren: fragmentFromNodeChildren,\n createIterator: createIterator,\n DomPosition: DomPosition\n };\n\n api.DOMException = DOMException;\n });\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Pure JavaScript implementation of DOM Range\n api.createCoreModule(\"DomRange\", [\"DomUtil\"], function(api, module) {\n var dom = api.dom;\n var util = api.util;\n var DomPosition = dom.DomPosition;\n var DOMException = api.DOMException;\n\n var isCharacterDataNode = dom.isCharacterDataNode;\n var getNodeIndex = dom.getNodeIndex;\n var isOrIsAncestorOf = dom.isOrIsAncestorOf;\n var getDocument = dom.getDocument;\n var comparePoints = dom.comparePoints;\n var splitDataNode = dom.splitDataNode;\n var getClosestAncestorIn = dom.getClosestAncestorIn;\n var getNodeLength = dom.getNodeLength;\n var arrayContains = dom.arrayContains;\n var getRootContainer = dom.getRootContainer;\n var crashyTextNodes = api.features.crashyTextNodes;\n\n var removeNode = dom.removeNode;\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Utility functions\n\n function isNonTextPartiallySelected(node, range) {\n return (node.nodeType != 3) &&\n (isOrIsAncestorOf(node, range.startContainer) || isOrIsAncestorOf(node, range.endContainer));\n }\n\n function getRangeDocument(range) {\n return range.document || getDocument(range.startContainer);\n }\n\n function getRangeRoot(range) {\n return getRootContainer(range.startContainer);\n }\n\n function getBoundaryBeforeNode(node) {\n return new DomPosition(node.parentNode, getNodeIndex(node));\n }\n\n function getBoundaryAfterNode(node) {\n return new DomPosition(node.parentNode, getNodeIndex(node) + 1);\n }\n\n function insertNodeAtPosition(node, n, o) {\n var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node;\n if (isCharacterDataNode(n)) {\n if (o == n.length) {\n dom.insertAfter(node, n);\n } else {\n n.parentNode.insertBefore(node, o == 0 ? n : splitDataNode(n, o));\n }\n } else if (o >= n.childNodes.length) {\n n.appendChild(node);\n } else {\n n.insertBefore(node, n.childNodes[o]);\n }\n return firstNodeInserted;\n }\n\n function rangesIntersect(rangeA, rangeB, touchingIsIntersecting) {\n assertRangeValid(rangeA);\n assertRangeValid(rangeB);\n\n if (getRangeDocument(rangeB) != getRangeDocument(rangeA)) {\n throw new DOMException(\"WRONG_DOCUMENT_ERR\");\n }\n\n var startComparison = comparePoints(rangeA.startContainer, rangeA.startOffset, rangeB.endContainer, rangeB.endOffset),\n endComparison = comparePoints(rangeA.endContainer, rangeA.endOffset, rangeB.startContainer, rangeB.startOffset);\n\n return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;\n }\n\n function cloneSubtree(iterator) {\n var partiallySelected;\n for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {\n partiallySelected = iterator.isPartiallySelectedSubtree();\n node = node.cloneNode(!partiallySelected);\n if (partiallySelected) {\n subIterator = iterator.getSubtreeIterator();\n node.appendChild(cloneSubtree(subIterator));\n subIterator.detach();\n }\n\n if (node.nodeType == 10) { // DocumentType\n throw new DOMException(\"HIERARCHY_REQUEST_ERR\");\n }\n frag.appendChild(node);\n }\n return frag;\n }\n\n function iterateSubtree(rangeIterator, func, iteratorState) {\n var it, n;\n iteratorState = iteratorState || { stop: false };\n for (var node, subRangeIterator; node = rangeIterator.next(); ) {\n if (rangeIterator.isPartiallySelectedSubtree()) {\n if (func(node) === false) {\n iteratorState.stop = true;\n return;\n } else {\n // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of\n // the node selected by the Range.\n subRangeIterator = rangeIterator.getSubtreeIterator();\n iterateSubtree(subRangeIterator, func, iteratorState);\n subRangeIterator.detach();\n if (iteratorState.stop) {\n return;\n }\n }\n } else {\n // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its\n // descendants\n it = dom.createIterator(node);\n while ( (n = it.next()) ) {\n if (func(n) === false) {\n iteratorState.stop = true;\n return;\n }\n }\n }\n }\n }\n\n function deleteSubtree(iterator) {\n var subIterator;\n while (iterator.next()) {\n if (iterator.isPartiallySelectedSubtree()) {\n subIterator = iterator.getSubtreeIterator();\n deleteSubtree(subIterator);\n subIterator.detach();\n } else {\n iterator.remove();\n }\n }\n }\n\n function extractSubtree(iterator) {\n for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {\n\n if (iterator.isPartiallySelectedSubtree()) {\n node = node.cloneNode(false);\n subIterator = iterator.getSubtreeIterator();\n node.appendChild(extractSubtree(subIterator));\n subIterator.detach();\n } else {\n iterator.remove();\n }\n if (node.nodeType == 10) { // DocumentType\n throw new DOMException(\"HIERARCHY_REQUEST_ERR\");\n }\n frag.appendChild(node);\n }\n return frag;\n }\n\n function getNodesInRange(range, nodeTypes, filter) {\n var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex;\n var filterExists = !!filter;\n if (filterNodeTypes) {\n regex = new RegExp(\"^(\" + nodeTypes.join(\"|\") + \")$\");\n }\n\n var nodes = [];\n iterateSubtree(new RangeIterator(range, false), function(node) {\n if (filterNodeTypes && !regex.test(node.nodeType)) {\n return;\n }\n if (filterExists && !filter(node)) {\n return;\n }\n // Don't include a boundary container if it is a character data node and the range does not contain any\n // of its character data. See issue 190.\n var sc = range.startContainer;\n if (node == sc && isCharacterDataNode(sc) && range.startOffset == sc.length) {\n return;\n }\n\n var ec = range.endContainer;\n if (node == ec && isCharacterDataNode(ec) && range.endOffset == 0) {\n return;\n }\n\n nodes.push(node);\n });\n return nodes;\n }\n\n function inspect(range) {\n var name = (typeof range.getName == \"undefined\") ? \"Range\" : range.getName();\n return \"[\" + name + \"(\" + dom.inspectNode(range.startContainer) + \":\" + range.startOffset + \", \" +\n dom.inspectNode(range.endContainer) + \":\" + range.endOffset + \")]\";\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange)\n\n function RangeIterator(range, clonePartiallySelectedTextNodes) {\n this.range = range;\n this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes;\n\n\n if (!range.collapsed) {\n this.sc = range.startContainer;\n this.so = range.startOffset;\n this.ec = range.endContainer;\n this.eo = range.endOffset;\n var root = range.commonAncestorContainer;\n\n if (this.sc === this.ec && isCharacterDataNode(this.sc)) {\n this.isSingleCharacterDataNode = true;\n this._first = this._last = this._next = this.sc;\n } else {\n this._first = this._next = (this.sc === root && !isCharacterDataNode(this.sc)) ?\n this.sc.childNodes[this.so] : getClosestAncestorIn(this.sc, root, true);\n this._last = (this.ec === root && !isCharacterDataNode(this.ec)) ?\n this.ec.childNodes[this.eo - 1] : getClosestAncestorIn(this.ec, root, true);\n }\n }\n }\n\n RangeIterator.prototype = {\n _current: null,\n _next: null,\n _first: null,\n _last: null,\n isSingleCharacterDataNode: false,\n\n reset: function() {\n this._current = null;\n this._next = this._first;\n },\n\n hasNext: function() {\n return !!this._next;\n },\n\n next: function() {\n // Move to next node\n var current = this._current = this._next;\n if (current) {\n this._next = (current !== this._last) ? current.nextSibling : null;\n\n // Check for partially selected text nodes\n if (isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) {\n if (current === this.ec) {\n (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo);\n }\n if (this._current === this.sc) {\n (current = current.cloneNode(true)).deleteData(0, this.so);\n }\n }\n }\n\n return current;\n },\n\n remove: function() {\n var current = this._current, start, end;\n\n if (isCharacterDataNode(current) && (current === this.sc || current === this.ec)) {\n start = (current === this.sc) ? this.so : 0;\n end = (current === this.ec) ? this.eo : current.length;\n if (start != end) {\n current.deleteData(start, end - start);\n }\n } else {\n if (current.parentNode) {\n removeNode(current);\n } else {\n }\n }\n },\n\n // Checks if the current node is partially selected\n isPartiallySelectedSubtree: function() {\n var current = this._current;\n return isNonTextPartiallySelected(current, this.range);\n },\n\n getSubtreeIterator: function() {\n var subRange;\n if (this.isSingleCharacterDataNode) {\n subRange = this.range.cloneRange();\n subRange.collapse(false);\n } else {\n subRange = new Range(getRangeDocument(this.range));\n var current = this._current;\n var startContainer = current, startOffset = 0, endContainer = current, endOffset = getNodeLength(current);\n\n if (isOrIsAncestorOf(current, this.sc)) {\n startContainer = this.sc;\n startOffset = this.so;\n }\n if (isOrIsAncestorOf(current, this.ec)) {\n endContainer = this.ec;\n endOffset = this.eo;\n }\n\n updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset);\n }\n return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes);\n },\n\n detach: function() {\n this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null;\n }\n };\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10];\n var rootContainerNodeTypes = [2, 9, 11];\n var readonlyNodeTypes = [5, 6, 10, 12];\n var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11];\n var surroundNodeTypes = [1, 3, 4, 5, 7, 8];\n\n function createAncestorFinder(nodeTypes) {\n return function(node, selfIsAncestor) {\n var t, n = selfIsAncestor ? node : node.parentNode;\n while (n) {\n t = n.nodeType;\n if (arrayContains(nodeTypes, t)) {\n return n;\n }\n n = n.parentNode;\n }\n return null;\n };\n }\n\n var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );\n var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);\n var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );\n var getElementAncestor = createAncestorFinder( [1] );\n\n function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {\n if (getDocTypeNotationEntityAncestor(node, allowSelf)) {\n throw new DOMException(\"INVALID_NODE_TYPE_ERR\");\n }\n }\n\n function assertValidNodeType(node, invalidTypes) {\n if (!arrayContains(invalidTypes, node.nodeType)) {\n throw new DOMException(\"INVALID_NODE_TYPE_ERR\");\n }\n }\n\n function assertValidOffset(node, offset) {\n if (offset < 0 || offset > (isCharacterDataNode(node) ? node.length : node.childNodes.length)) {\n throw new DOMException(\"INDEX_SIZE_ERR\");\n }\n }\n\n function assertSameDocumentOrFragment(node1, node2) {\n if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) {\n throw new DOMException(\"WRONG_DOCUMENT_ERR\");\n }\n }\n\n function assertNodeNotReadOnly(node) {\n if (getReadonlyAncestor(node, true)) {\n throw new DOMException(\"NO_MODIFICATION_ALLOWED_ERR\");\n }\n }\n\n function assertNode(node, codeName) {\n if (!node) {\n throw new DOMException(codeName);\n }\n }\n\n function isValidOffset(node, offset) {\n return offset <= (isCharacterDataNode(node) ? node.length : node.childNodes.length);\n }\n\n function isRangeValid(range) {\n return (!!range.startContainer && !!range.endContainer &&\n !(crashyTextNodes && (dom.isBrokenNode(range.startContainer) || dom.isBrokenNode(range.endContainer))) &&\n getRootContainer(range.startContainer) == getRootContainer(range.endContainer) &&\n isValidOffset(range.startContainer, range.startOffset) &&\n isValidOffset(range.endContainer, range.endOffset));\n }\n\n function assertRangeValid(range) {\n if (!isRangeValid(range)) {\n throw new Error(\"Range error: Range is not valid. This usually happens after DOM mutation. Range: (\" + range.inspect() + \")\");\n }\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Test the browser's innerHTML support to decide how to implement createContextualFragment\n var styleEl = document.createElement(\"style\");\n var htmlParsingConforms = false;\n try {\n styleEl.innerHTML = \"x\";\n htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Pre-Blink Opera incorrectly creates an element node\n } catch (e) {\n // IE 6 and 7 throw\n }\n\n api.features.htmlParsingConforms = htmlParsingConforms;\n\n var createContextualFragment = htmlParsingConforms ?\n\n // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See\n // discussion and base code for this implementation at issue 67.\n // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface\n // Thanks to Aleks Williams.\n function(fragmentStr) {\n // \"Let node the context object's start's node.\"\n var node = this.startContainer;\n var doc = getDocument(node);\n\n // \"If the context object's start's node is null, raise an INVALID_STATE_ERR\n // exception and abort these steps.\"\n if (!node) {\n throw new DOMException(\"INVALID_STATE_ERR\");\n }\n\n // \"Let element be as follows, depending on node's interface:\"\n // Document, Document Fragment: null\n var el = null;\n\n // \"Element: node\"\n if (node.nodeType == 1) {\n el = node;\n\n // \"Text, Comment: node's parentElement\"\n } else if (isCharacterDataNode(node)) {\n el = dom.parentElement(node);\n }\n\n // \"If either element is null or element's ownerDocument is an HTML document\n // and element's local name is \"html\" and element's namespace is the HTML\n // namespace\"\n if (el === null || (\n el.nodeName == \"HTML\" &&\n dom.isHtmlNamespace(getDocument(el).documentElement) &&\n dom.isHtmlNamespace(el)\n )) {\n\n // \"let element be a new Element with \"body\" as its local name and the HTML\n // namespace as its namespace.\"\"\n el = doc.createElement(\"body\");\n } else {\n el = el.cloneNode(false);\n }\n\n // \"If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm.\"\n // \"If the node's document is an XML document: Invoke the XML fragment parsing algorithm.\"\n // \"In either case, the algorithm must be invoked with fragment as the input\n // and element as the context element.\"\n el.innerHTML = fragmentStr;\n\n // \"If this raises an exception, then abort these steps. Otherwise, let new\n // children be the nodes returned.\"\n\n // \"Let fragment be a new DocumentFragment.\"\n // \"Append all new children to fragment.\"\n // \"Return fragment.\"\n return dom.fragmentFromNodeChildren(el);\n } :\n\n // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that\n // previous versions of Rangy used (with the exception of using a body element rather than a div)\n function(fragmentStr) {\n var doc = getRangeDocument(this);\n var el = doc.createElement(\"body\");\n el.innerHTML = fragmentStr;\n\n return dom.fragmentFromNodeChildren(el);\n };\n\n function splitRangeBoundaries(range, positionsToPreserve) {\n assertRangeValid(range);\n\n var sc = range.startContainer, so = range.startOffset, ec = range.endContainer, eo = range.endOffset;\n var startEndSame = (sc === ec);\n\n if (isCharacterDataNode(ec) && eo > 0 && eo < ec.length) {\n splitDataNode(ec, eo, positionsToPreserve);\n }\n\n if (isCharacterDataNode(sc) && so > 0 && so < sc.length) {\n sc = splitDataNode(sc, so, positionsToPreserve);\n if (startEndSame) {\n eo -= so;\n ec = sc;\n } else if (ec == sc.parentNode && eo >= getNodeIndex(sc)) {\n eo++;\n }\n so = 0;\n }\n range.setStartAndEnd(sc, so, ec, eo);\n }\n\n function rangeToHtml(range) {\n assertRangeValid(range);\n var container = range.commonAncestorContainer.parentNode.cloneNode(false);\n container.appendChild( range.cloneContents() );\n return container.innerHTML;\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n var rangeProperties = [\"startContainer\", \"startOffset\", \"endContainer\", \"endOffset\", \"collapsed\",\n \"commonAncestorContainer\"];\n\n var s2s = 0, s2e = 1, e2e = 2, e2s = 3;\n var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3;\n\n util.extend(api.rangePrototype, {\n compareBoundaryPoints: function(how, range) {\n assertRangeValid(this);\n assertSameDocumentOrFragment(this.startContainer, range.startContainer);\n\n var nodeA, offsetA, nodeB, offsetB;\n var prefixA = (how == e2s || how == s2s) ? \"start\" : \"end\";\n var prefixB = (how == s2e || how == s2s) ? \"start\" : \"end\";\n nodeA = this[prefixA + \"Container\"];\n offsetA = this[prefixA + \"Offset\"];\n nodeB = range[prefixB + \"Container\"];\n offsetB = range[prefixB + \"Offset\"];\n return comparePoints(nodeA, offsetA, nodeB, offsetB);\n },\n\n insertNode: function(node) {\n assertRangeValid(this);\n assertValidNodeType(node, insertableNodeTypes);\n assertNodeNotReadOnly(this.startContainer);\n\n if (isOrIsAncestorOf(node, this.startContainer)) {\n throw new DOMException(\"HIERARCHY_REQUEST_ERR\");\n }\n\n // No check for whether the container of the start of the Range is of a type that does not allow\n // children of the type of node: the browser's DOM implementation should do this for us when we attempt\n // to add the node\n\n var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset);\n this.setStartBefore(firstNodeInserted);\n },\n\n cloneContents: function() {\n assertRangeValid(this);\n\n var clone, frag;\n if (this.collapsed) {\n return getRangeDocument(this).createDocumentFragment();\n } else {\n if (this.startContainer === this.endContainer && isCharacterDataNode(this.startContainer)) {\n clone = this.startContainer.cloneNode(true);\n clone.data = clone.data.slice(this.startOffset, this.endOffset);\n frag = getRangeDocument(this).createDocumentFragment();\n frag.appendChild(clone);\n return frag;\n } else {\n var iterator = new RangeIterator(this, true);\n clone = cloneSubtree(iterator);\n iterator.detach();\n }\n return clone;\n }\n },\n\n canSurroundContents: function() {\n assertRangeValid(this);\n assertNodeNotReadOnly(this.startContainer);\n assertNodeNotReadOnly(this.endContainer);\n\n // Check if the contents can be surrounded. Specifically, this means whether the range partially selects\n // no non-text nodes.\n var iterator = new RangeIterator(this, true);\n var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||\n (iterator._last && isNonTextPartiallySelected(iterator._last, this)));\n iterator.detach();\n return !boundariesInvalid;\n },\n\n surroundContents: function(node) {\n assertValidNodeType(node, surroundNodeTypes);\n\n if (!this.canSurroundContents()) {\n throw new DOMException(\"INVALID_STATE_ERR\");\n }\n\n // Extract the contents\n var content = this.extractContents();\n\n // Clear the children of the node\n if (node.hasChildNodes()) {\n while (node.lastChild) {\n node.removeChild(node.lastChild);\n }\n }\n\n // Insert the new node and add the extracted contents\n insertNodeAtPosition(node, this.startContainer, this.startOffset);\n node.appendChild(content);\n\n this.selectNode(node);\n },\n\n cloneRange: function() {\n assertRangeValid(this);\n var range = new Range(getRangeDocument(this));\n var i = rangeProperties.length, prop;\n while (i--) {\n prop = rangeProperties[i];\n range[prop] = this[prop];\n }\n return range;\n },\n\n toString: function() {\n assertRangeValid(this);\n var sc = this.startContainer;\n if (sc === this.endContainer && isCharacterDataNode(sc)) {\n return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : \"\";\n } else {\n var textParts = [], iterator = new RangeIterator(this, true);\n iterateSubtree(iterator, function(node) {\n // Accept only text or CDATA nodes, not comments\n if (node.nodeType == 3 || node.nodeType == 4) {\n textParts.push(node.data);\n }\n });\n iterator.detach();\n return textParts.join(\"\");\n }\n },\n\n // The methods below are all non-standard. The following batch were introduced by Mozilla but have since\n // been removed from Mozilla.\n\n compareNode: function(node) {\n assertRangeValid(this);\n\n var parent = node.parentNode;\n var nodeIndex = getNodeIndex(node);\n\n if (!parent) {\n throw new DOMException(\"NOT_FOUND_ERR\");\n }\n\n var startComparison = this.comparePoint(parent, nodeIndex),\n endComparison = this.comparePoint(parent, nodeIndex + 1);\n\n if (startComparison < 0) { // Node starts before\n return (endComparison > 0) ? n_b_a : n_b;\n } else {\n return (endComparison > 0) ? n_a : n_i;\n }\n },\n\n comparePoint: function(node, offset) {\n assertRangeValid(this);\n assertNode(node, \"HIERARCHY_REQUEST_ERR\");\n assertSameDocumentOrFragment(node, this.startContainer);\n\n if (comparePoints(node, offset, this.startContainer, this.startOffset) < 0) {\n return -1;\n } else if (comparePoints(node, offset, this.endContainer, this.endOffset) > 0) {\n return 1;\n }\n return 0;\n },\n\n createContextualFragment: createContextualFragment,\n\n toHtml: function() {\n return rangeToHtml(this);\n },\n\n // touchingIsIntersecting determines whether this method considers a node that borders a range intersects\n // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default)\n intersectsNode: function(node, touchingIsIntersecting) {\n assertRangeValid(this);\n if (getRootContainer(node) != getRangeRoot(this)) {\n return false;\n }\n\n var parent = node.parentNode, offset = getNodeIndex(node);\n if (!parent) {\n return true;\n }\n\n var startComparison = comparePoints(parent, offset, this.endContainer, this.endOffset),\n endComparison = comparePoints(parent, offset + 1, this.startContainer, this.startOffset);\n\n return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;\n },\n\n isPointInRange: function(node, offset) {\n assertRangeValid(this);\n assertNode(node, \"HIERARCHY_REQUEST_ERR\");\n assertSameDocumentOrFragment(node, this.startContainer);\n\n return (comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) &&\n (comparePoints(node, offset, this.endContainer, this.endOffset) <= 0);\n },\n\n // The methods below are non-standard and invented by me.\n\n // Sharing a boundary start-to-end or end-to-start does not count as intersection.\n intersectsRange: function(range) {\n return rangesIntersect(this, range, false);\n },\n\n // Sharing a boundary start-to-end or end-to-start does count as intersection.\n intersectsOrTouchesRange: function(range) {\n return rangesIntersect(this, range, true);\n },\n\n intersection: function(range) {\n if (this.intersectsRange(range)) {\n var startComparison = comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset),\n endComparison = comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset);\n\n var intersectionRange = this.cloneRange();\n if (startComparison == -1) {\n intersectionRange.setStart(range.startContainer, range.startOffset);\n }\n if (endComparison == 1) {\n intersectionRange.setEnd(range.endContainer, range.endOffset);\n }\n return intersectionRange;\n }\n return null;\n },\n\n union: function(range) {\n if (this.intersectsOrTouchesRange(range)) {\n var unionRange = this.cloneRange();\n if (comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) {\n unionRange.setStart(range.startContainer, range.startOffset);\n }\n if (comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) {\n unionRange.setEnd(range.endContainer, range.endOffset);\n }\n return unionRange;\n } else {\n throw new DOMException(\"Ranges do not intersect\");\n }\n },\n\n containsNode: function(node, allowPartial) {\n if (allowPartial) {\n return this.intersectsNode(node, false);\n } else {\n return this.compareNode(node) == n_i;\n }\n },\n\n containsNodeContents: function(node) {\n return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, getNodeLength(node)) <= 0;\n },\n\n containsRange: function(range) {\n var intersection = this.intersection(range);\n return intersection !== null && range.equals(intersection);\n },\n\n containsNodeText: function(node) {\n var nodeRange = this.cloneRange();\n nodeRange.selectNode(node);\n var textNodes = nodeRange.getNodes([3]);\n if (textNodes.length > 0) {\n nodeRange.setStart(textNodes[0], 0);\n var lastTextNode = textNodes.pop();\n nodeRange.setEnd(lastTextNode, lastTextNode.length);\n return this.containsRange(nodeRange);\n } else {\n return this.containsNodeContents(node);\n }\n },\n\n getNodes: function(nodeTypes, filter) {\n assertRangeValid(this);\n return getNodesInRange(this, nodeTypes, filter);\n },\n\n getDocument: function() {\n return getRangeDocument(this);\n },\n\n collapseBefore: function(node) {\n this.setEndBefore(node);\n this.collapse(false);\n },\n\n collapseAfter: function(node) {\n this.setStartAfter(node);\n this.collapse(true);\n },\n\n getBookmark: function(containerNode) {\n var doc = getRangeDocument(this);\n var preSelectionRange = api.createRange(doc);\n containerNode = containerNode || dom.getBody(doc);\n preSelectionRange.selectNodeContents(containerNode);\n var range = this.intersection(preSelectionRange);\n var start = 0, end = 0;\n if (range) {\n preSelectionRange.setEnd(range.startContainer, range.startOffset);\n start = preSelectionRange.toString().length;\n end = start + range.toString().length;\n }\n\n return {\n start: start,\n end: end,\n containerNode: containerNode\n };\n },\n\n moveToBookmark: function(bookmark) {\n var containerNode = bookmark.containerNode;\n var charIndex = 0;\n this.setStart(containerNode, 0);\n this.collapse(true);\n var nodeStack = [containerNode], node, foundStart = false, stop = false;\n var nextCharIndex, i, childNodes;\n\n while (!stop && (node = nodeStack.pop())) {\n if (node.nodeType == 3) {\n nextCharIndex = charIndex + node.length;\n if (!foundStart && bookmark.start >= charIndex && bookmark.start <= nextCharIndex) {\n this.setStart(node, bookmark.start - charIndex);\n foundStart = true;\n }\n if (foundStart && bookmark.end >= charIndex && bookmark.end <= nextCharIndex) {\n this.setEnd(node, bookmark.end - charIndex);\n stop = true;\n }\n charIndex = nextCharIndex;\n } else {\n childNodes = node.childNodes;\n i = childNodes.length;\n while (i--) {\n nodeStack.push(childNodes[i]);\n }\n }\n }\n },\n\n getName: function() {\n return \"DomRange\";\n },\n\n equals: function(range) {\n return Range.rangesEqual(this, range);\n },\n\n isValid: function() {\n return isRangeValid(this);\n },\n\n inspect: function() {\n return inspect(this);\n },\n\n detach: function() {\n // In DOM4, detach() is now a no-op.\n }\n });\n\n function copyComparisonConstantsToObject(obj) {\n obj.START_TO_START = s2s;\n obj.START_TO_END = s2e;\n obj.END_TO_END = e2e;\n obj.END_TO_START = e2s;\n\n obj.NODE_BEFORE = n_b;\n obj.NODE_AFTER = n_a;\n obj.NODE_BEFORE_AND_AFTER = n_b_a;\n obj.NODE_INSIDE = n_i;\n }\n\n function copyComparisonConstants(constructor) {\n copyComparisonConstantsToObject(constructor);\n copyComparisonConstantsToObject(constructor.prototype);\n }\n\n function createRangeContentRemover(remover, boundaryUpdater) {\n return function() {\n assertRangeValid(this);\n\n var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer;\n\n var iterator = new RangeIterator(this, true);\n\n // Work out where to position the range after content removal\n var node, boundary;\n if (sc !== root) {\n node = getClosestAncestorIn(sc, root, true);\n boundary = getBoundaryAfterNode(node);\n sc = boundary.node;\n so = boundary.offset;\n }\n\n // Check none of the range is read-only\n iterateSubtree(iterator, assertNodeNotReadOnly);\n\n iterator.reset();\n\n // Remove the content\n var returnValue = remover(iterator);\n iterator.detach();\n\n // Move to the new position\n boundaryUpdater(this, sc, so, sc, so);\n\n return returnValue;\n };\n }\n\n function createPrototypeRange(constructor, boundaryUpdater) {\n function createBeforeAfterNodeSetter(isBefore, isStart) {\n return function(node) {\n assertValidNodeType(node, beforeAfterNodeTypes);\n assertValidNodeType(getRootContainer(node), rootContainerNodeTypes);\n\n var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node);\n (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset);\n };\n }\n\n function setRangeStart(range, node, offset) {\n var ec = range.endContainer, eo = range.endOffset;\n if (node !== range.startContainer || offset !== range.startOffset) {\n // Check the root containers of the range and the new boundary, and also check whether the new boundary\n // is after the current end. In either case, collapse the range to the new position\n if (getRootContainer(node) != getRootContainer(ec) || comparePoints(node, offset, ec, eo) == 1) {\n ec = node;\n eo = offset;\n }\n boundaryUpdater(range, node, offset, ec, eo);\n }\n }\n\n function setRangeEnd(range, node, offset) {\n var sc = range.startContainer, so = range.startOffset;\n if (node !== range.endContainer || offset !== range.endOffset) {\n // Check the root containers of the range and the new boundary, and also check whether the new boundary\n // is after the current end. In either case, collapse the range to the new position\n if (getRootContainer(node) != getRootContainer(sc) || comparePoints(node, offset, sc, so) == -1) {\n sc = node;\n so = offset;\n }\n boundaryUpdater(range, sc, so, node, offset);\n }\n }\n\n // Set up inheritance\n var F = function() {};\n F.prototype = api.rangePrototype;\n constructor.prototype = new F();\n\n util.extend(constructor.prototype, {\n setStart: function(node, offset) {\n assertNoDocTypeNotationEntityAncestor(node, true);\n assertValidOffset(node, offset);\n\n setRangeStart(this, node, offset);\n },\n\n setEnd: function(node, offset) {\n assertNoDocTypeNotationEntityAncestor(node, true);\n assertValidOffset(node, offset);\n\n setRangeEnd(this, node, offset);\n },\n\n /**\n * Convenience method to set a range's start and end boundaries. Overloaded as follows:\n * - Two parameters (node, offset) creates a collapsed range at that position\n * - Three parameters (node, startOffset, endOffset) creates a range contained with node starting at\n * startOffset and ending at endOffset\n * - Four parameters (startNode, startOffset, endNode, endOffset) creates a range starting at startOffset in\n * startNode and ending at endOffset in endNode\n */\n setStartAndEnd: function() {\n var args = arguments;\n var sc = args[0], so = args[1], ec = sc, eo = so;\n\n switch (args.length) {\n case 3:\n eo = args[2];\n break;\n case 4:\n ec = args[2];\n eo = args[3];\n break;\n }\n\n assertNoDocTypeNotationEntityAncestor(sc, true);\n assertValidOffset(sc, so);\n\n assertNoDocTypeNotationEntityAncestor(ec, true);\n assertValidOffset(ec, eo);\n\n boundaryUpdater(this, sc, so, ec, eo);\n },\n\n setBoundary: function(node, offset, isStart) {\n this[\"set\" + (isStart ? \"Start\" : \"End\")](node, offset);\n },\n\n setStartBefore: createBeforeAfterNodeSetter(true, true),\n setStartAfter: createBeforeAfterNodeSetter(false, true),\n setEndBefore: createBeforeAfterNodeSetter(true, false),\n setEndAfter: createBeforeAfterNodeSetter(false, false),\n\n collapse: function(isStart) {\n assertRangeValid(this);\n if (isStart) {\n boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset);\n } else {\n boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset);\n }\n },\n\n selectNodeContents: function(node) {\n assertNoDocTypeNotationEntityAncestor(node, true);\n\n boundaryUpdater(this, node, 0, node, getNodeLength(node));\n },\n\n selectNode: function(node) {\n assertNoDocTypeNotationEntityAncestor(node, false);\n assertValidNodeType(node, beforeAfterNodeTypes);\n\n var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node);\n boundaryUpdater(this, start.node, start.offset, end.node, end.offset);\n },\n\n extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater),\n\n deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater),\n\n canSurroundContents: function() {\n assertRangeValid(this);\n assertNodeNotReadOnly(this.startContainer);\n assertNodeNotReadOnly(this.endContainer);\n\n // Check if the contents can be surrounded. Specifically, this means whether the range partially selects\n // no non-text nodes.\n var iterator = new RangeIterator(this, true);\n var boundariesInvalid = (iterator._first && isNonTextPartiallySelected(iterator._first, this) ||\n (iterator._last && isNonTextPartiallySelected(iterator._last, this)));\n iterator.detach();\n return !boundariesInvalid;\n },\n\n splitBoundaries: function() {\n splitRangeBoundaries(this);\n },\n\n splitBoundariesPreservingPositions: function(positionsToPreserve) {\n splitRangeBoundaries(this, positionsToPreserve);\n },\n\n normalizeBoundaries: function() {\n assertRangeValid(this);\n\n var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;\n\n var mergeForward = function(node) {\n var sibling = node.nextSibling;\n if (sibling && sibling.nodeType == node.nodeType) {\n ec = node;\n eo = node.length;\n node.appendData(sibling.data);\n removeNode(sibling);\n }\n };\n\n var mergeBackward = function(node) {\n var sibling = node.previousSibling;\n if (sibling && sibling.nodeType == node.nodeType) {\n sc = node;\n var nodeLength = node.length;\n so = sibling.length;\n node.insertData(0, sibling.data);\n removeNode(sibling);\n if (sc == ec) {\n eo += so;\n ec = sc;\n } else if (ec == node.parentNode) {\n var nodeIndex = getNodeIndex(node);\n if (eo == nodeIndex) {\n ec = node;\n eo = nodeLength;\n } else if (eo > nodeIndex) {\n eo--;\n }\n }\n }\n };\n\n var normalizeStart = true;\n var sibling;\n\n if (isCharacterDataNode(ec)) {\n if (eo == ec.length) {\n mergeForward(ec);\n } else if (eo == 0) {\n sibling = ec.previousSibling;\n if (sibling && sibling.nodeType == ec.nodeType) {\n eo = sibling.length;\n if (sc == ec) {\n normalizeStart = false;\n }\n sibling.appendData(ec.data);\n removeNode(ec);\n ec = sibling;\n }\n }\n } else {\n if (eo > 0) {\n var endNode = ec.childNodes[eo - 1];\n if (endNode && isCharacterDataNode(endNode)) {\n mergeForward(endNode);\n }\n }\n normalizeStart = !this.collapsed;\n }\n\n if (normalizeStart) {\n if (isCharacterDataNode(sc)) {\n if (so == 0) {\n mergeBackward(sc);\n } else if (so == sc.length) {\n sibling = sc.nextSibling;\n if (sibling && sibling.nodeType == sc.nodeType) {\n if (ec == sibling) {\n ec = sc;\n eo += sc.length;\n }\n sc.appendData(sibling.data);\n removeNode(sibling);\n }\n }\n } else {\n if (so < sc.childNodes.length) {\n var startNode = sc.childNodes[so];\n if (startNode && isCharacterDataNode(startNode)) {\n mergeBackward(startNode);\n }\n }\n }\n } else {\n sc = ec;\n so = eo;\n }\n\n boundaryUpdater(this, sc, so, ec, eo);\n },\n\n collapseToPoint: function(node, offset) {\n assertNoDocTypeNotationEntityAncestor(node, true);\n assertValidOffset(node, offset);\n this.setStartAndEnd(node, offset);\n },\n\n parentElement: function() {\n assertRangeValid(this);\n var parentNode = this.commonAncestorContainer;\n return parentNode ? getElementAncestor(this.commonAncestorContainer, true) : null;\n }\n });\n\n copyComparisonConstants(constructor);\n }\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Updates commonAncestorContainer and collapsed after boundary change\n function updateCollapsedAndCommonAncestor(range) {\n range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);\n range.commonAncestorContainer = range.collapsed ?\n range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer);\n }\n\n function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) {\n range.startContainer = startContainer;\n range.startOffset = startOffset;\n range.endContainer = endContainer;\n range.endOffset = endOffset;\n range.document = dom.getDocument(startContainer);\n updateCollapsedAndCommonAncestor(range);\n }\n\n function Range(doc) {\n updateBoundaries(this, doc, 0, doc, 0);\n }\n\n createPrototypeRange(Range, updateBoundaries);\n\n util.extend(Range, {\n rangeProperties: rangeProperties,\n RangeIterator: RangeIterator,\n copyComparisonConstants: copyComparisonConstants,\n createPrototypeRange: createPrototypeRange,\n inspect: inspect,\n toHtml: rangeToHtml,\n getRangeDocument: getRangeDocument,\n rangesEqual: function(r1, r2) {\n return r1.startContainer === r2.startContainer &&\n r1.startOffset === r2.startOffset &&\n r1.endContainer === r2.endContainer &&\n r1.endOffset === r2.endOffset;\n }\n });\n\n api.DomRange = Range;\n });\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n // Wrappers for the browser's native DOM Range and/or TextRange implementation\n api.createCoreModule(\"WrappedRange\", [\"DomRange\"], function(api, module) {\n var WrappedRange, WrappedTextRange;\n var dom = api.dom;\n var util = api.util;\n var DomPosition = dom.DomPosition;\n var DomRange = api.DomRange;\n var getBody = dom.getBody;\n var getContentDocument = dom.getContentDocument;\n var isCharacterDataNode = dom.isCharacterDataNode;\n\n\n /*----------------------------------------------------------------------------------------------------------------*/\n\n if (api.features.implementsDomRange) {\n // This is a wrapper around the browser's native DOM Range. It has two aims:\n // - Provide workarounds for specific browser bugs\n // - provide convenient extensions, which are inherited from Rangy's DomRange\n\n (function() {\n var rangeProto;\n var rangeProperties = DomRange.rangeProperties;\n\n function updateRangeProperties(range) {\n var i = rangeProperties.length, prop;\n while (i--) {\n prop = rangeProperties[i];\n range[prop] = range.nativeRange[prop];\n }\n // Fix for broken collapsed property in IE 9.\n range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);\n }\n\n function updateNativeRange(range, startContainer, startOffset, endContainer, endOffset) {\n var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset);\n var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset);\n var nativeRangeDifferent = !range.equals(range.nativeRange);\n\n // Always set both boundaries for the benefit of IE9 (see issue 35)\n if (startMoved || endMoved || nativeRangeDifferent) {\n range.setEnd(endContainer, endOffset);\n range.setStart(startContainer, startOffset);\n }\n }\n\n var createBeforeAfterNodeSetter;\n\n WrappedRange = function(range) {\n if (!range) {\n throw module.createError(\"WrappedRange: Range must be specified\");\n }\n this.nativeRange = range;\n updateRangeProperties(this);\n };\n\n DomRange.createPrototypeRange(WrappedRange, updateNativeRange);\n\n rangeProto = WrappedRange.prototype;\n\n rangeProto.selectNode = function(node) {\n this.nativeRange.selectNode(node);\n updateRangeProperties(this);\n };\n\n rangeProto.cloneContents = function() {\n return this.nativeRange.cloneContents();\n };\n\n // Due to a long-standing Firefox bug that I have not been able to find a reliable way to detect,\n // insertNode() is never delegated to the native range.\n\n rangeProto.surroundContents = function(node) {\n this.nativeRange.surroundContents(node);\n updateRangeProperties(this);\n };\n\n rangeProto.collapse = function(isStart) {\n this.nativeRange.collapse(isStart);\n updateRangeProperties(this);\n };\n\n rangeProto.cloneRange = function() {\n return new WrappedRange(this.nativeRange.cloneRange());\n };\n\n rangeProto.refresh = function() {\n updateRangeProperties(this);\n };\n\n rangeProto.toString = function() {\n return this.nativeRange.toString();\n };\n\n // Create test range and node for feature detection\n\n var testTextNode = document.createTextNode(\"test\");\n getBody(document).appendChild(testTextNode);\n var range = document.createRange();\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and\n // correct for it\n\n range.setStart(testTextNode, 0);\n range.setEnd(testTextNode, 0);\n\n try {\n range.setStart(testTextNode, 1);\n\n rangeProto.setStart = function(node, offset) {\n this.nativeRange.setStart(node, offset);\n updateRangeProperties(this);\n };\n\n rangeProto.setEnd = function(node, offset) {\n this.nativeRange.setEnd(node, offset);\n updateRangeProperties(this);\n };\n\n createBeforeAfterNodeSetter = function(name) {\n return function(node) {\n this.nativeRange[name](node);\n updateRangeProperties(this);\n };\n };\n\n } catch(ex) {\n\n rangeProto.setStart = function(node, offset) {\n try {\n this.nativeRange.setStart(node, offset);\n } catch (ex) {\n this.nativeRange.setEnd(node, offset);\n this.nativeRange.setStart(node, offset);\n }\n updateRangeProperties(this);\n };\n\n rangeProto.setEnd = function(node, offset) {\n try {\n this.nativeRange.setEnd(node, offset);\n } catch (ex) {\n this.nativeRange.setStart(node, offset);\n this.nativeRange.setEnd(node, offset);\n }\n updateRangeProperties(this);\n };\n\n createBeforeAfterNodeSetter = function(name, oppositeName) {\n return function(node) {\n try {\n this.nativeRange[name](node);\n } catch (ex) {\n this.nativeRange[oppositeName](node);\n this.nativeRange[name](node);\n }\n updateRangeProperties(this);\n };\n };\n }\n\n rangeProto.setStartBefore = createBeforeAfterNodeSetter(\"setStartBefore\", \"setEndBefore\");\n rangeProto.setStartAfter = createBeforeAfterNodeSetter(\"setStartAfter\", \"setEndAfter\");\n rangeProto.setEndBefore = createBeforeAfterNodeSetter(\"setEndBefore\", \"setStartBefore\");\n rangeProto.setEndAfter = createBeforeAfterNodeSetter(\"setEndAfter\", \"setStartAfter\");\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Always use DOM4-compliant selectNodeContents implementation: it's simpler and less code than testing\n // whether the native implementation can be trusted\n rangeProto.selectNodeContents = function(node) {\n this.setStartAndEnd(node, 0, dom.getNodeLength(node));\n };\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Test for and correct WebKit bug that has the behaviour of compareBoundaryPoints round the wrong way for\n // constants START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738\n\n range.selectNodeContents(testTextNode);\n range.setEnd(testTextNode, 3);\n\n var range2 = document.createRange();\n range2.selectNodeContents(testTextNode);\n range2.setEnd(testTextNode, 4);\n range2.setStart(testTextNode, 2);\n\n if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 &&\n range.compareBoundaryPoints(range.END_TO_START, range2) == 1) {\n // This is the wrong way round, so correct for it\n\n rangeProto.compareBoundaryPoints = function(type, range) {\n range = range.nativeRange || range;\n if (type == range.START_TO_END) {\n type = range.END_TO_START;\n } else if (type == range.END_TO_START) {\n type = range.START_TO_END;\n }\n return this.nativeRange.compareBoundaryPoints(type, range);\n };\n } else {\n rangeProto.compareBoundaryPoints = function(type, range) {\n return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range);\n };\n }\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Test for IE deleteContents() and extractContents() bug and correct it. See issue 107.\n\n var el = document.createElement(\"div\");\n el.innerHTML = \"123\";\n var textNode = el.firstChild;\n var body = getBody(document);\n body.appendChild(el);\n\n range.setStart(textNode, 1);\n range.setEnd(textNode, 2);\n range.deleteContents();\n\n if (textNode.data == \"13\") {\n // Behaviour is correct per DOM4 Range so wrap the browser's implementation of deleteContents() and\n // extractContents()\n rangeProto.deleteContents = function() {\n this.nativeRange.deleteContents();\n updateRangeProperties(this);\n };\n\n rangeProto.extractContents = function() {\n var frag = this.nativeRange.extractContents();\n updateRangeProperties(this);\n return frag;\n };\n } else {\n }\n\n body.removeChild(el);\n body = null;\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Test for existence of createContextualFragment and delegate to it if it exists\n if (util.isHostMethod(range, \"createContextualFragment\")) {\n rangeProto.createContextualFragment = function(fragmentStr) {\n return this.nativeRange.createContextualFragment(fragmentStr);\n };\n }\n\n /*--------------------------------------------------------------------------------------------------------*/\n\n // Clean up\n getBody(document).removeChild(testTextNode);\n\n rangeProto.getName = function() {\n return \"WrappedRange\";\n };\n\n api.WrappedRange = WrappedRange;\n\n api.createNativeRange = function(doc) {\n doc = getContentDocument(doc, module, \"createNativeRange\");\n return doc.createRange();\n };\n })();\n }\n\n if (api.features.implementsTextRange) {\n /*\n This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement()\n method. For example, in the following (where pipes denote the selection boundaries):\n\n
  • | a
  • b |
\n\n var range = document.selection.createRange();\n alert(range.parentElement().id); // Should alert \"ul\" but alerts \"b\"\n\n This method returns the common ancestor node of the following:\n - the parentElement() of the textRange\n - the parentElement() of the textRange after calling collapse(true)\n - the parentElement() of the textRange after calling collapse(false)\n */\n var getTextRangeContainerElement = function(textRange) {\n var parentEl = textRange.parentElement();\n var range = textRange.duplicate();\n range.collapse(true);\n var startEl = range.parentElement();\n range = textRange.duplicate();\n range.collapse(false);\n var endEl = range.parentElement();\n var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl);\n\n return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);\n };\n\n var textRangeIsCollapsed = function(textRange) {\n return textRange.compareEndPoints(\"StartToEnd\", textRange) == 0;\n };\n\n // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started\n // out as an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/)\n // but has grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange\n // bugs, handling for inputs and images, plus optimizations.\n var getTextRangeBoundaryPosition = function(textRange, wholeRangeContainerElement, isStart, isCollapsed, startInfo) {\n var workingRange = textRange.duplicate();\n workingRange.collapse(isStart);\n var containerElement = workingRange.parentElement();\n\n // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so\n // check for that\n if (!dom.isOrIsAncestorOf(wholeRangeContainerElement, containerElement)) {\n containerElement = wholeRangeContainerElement;\n }\n\n\n // Deal with nodes that cannot \"contain rich HTML markup\". In practice, this means form inputs, images and\n // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx\n if (!containerElement.canHaveHTML) {\n var pos = new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement));\n return {\n boundaryPosition: pos,\n nodeInfo: {\n nodeIndex: pos.offset,\n containerElement: pos.node\n }\n };\n }\n\n var workingNode = dom.getDocument(containerElement).createElement(\"span\");\n\n // Workaround for HTML5 Shiv's insane violation of document.createElement(). See Rangy issue 104 and HTML5\n // Shiv issue 64: https://github.com/aFarkas/html5shiv/issues/64\n if (workingNode.parentNode) {\n dom.removeNode(workingNode);\n }\n\n var comparison, workingComparisonType = isStart ? \"StartToStart\" : \"StartToEnd\";\n var previousNode, nextNode, boundaryPosition, boundaryNode;\n var start = (startInfo && startInfo.containerElement == containerElement) ? startInfo.nodeIndex : 0;\n var childNodeCount = containerElement.childNodes.length;\n var end = childNodeCount;\n\n // Check end first. Code within the loop assumes that the endth child node of the container is definitely\n // after the range boundary.\n var nodeIndex = end;\n\n while (true) {\n if (nodeIndex == childNodeCount) {\n containerElement.appendChild(workingNode);\n } else {\n containerElement.insertBefore(workingNode, containerElement.childNodes[nodeIndex]);\n }\n workingRange.moveToElementText(workingNode);\n comparison = workingRange.compareEndPoints(workingComparisonType, textRange);\n if (comparison == 0 || start == end) {\n break;\n } else if (comparison == -1) {\n if (end == start + 1) {\n // We know the endth child node is after the range boundary, so we must be done.\n break;\n } else {\n start = nodeIndex;\n }\n } else {\n end = (end == start + 1) ? start : nodeIndex;\n }\n nodeIndex = Math.floor((start + end) / 2);\n containerElement.removeChild(workingNode);\n }\n\n\n // We've now reached or gone past the boundary of the text range we're interested in\n // so have identified the node we want\n boundaryNode = workingNode.nextSibling;\n\n if (comparison == -1 && boundaryNode && isCharacterDataNode(boundaryNode)) {\n // This is a character data node (text, comment, cdata). The working range is collapsed at the start of\n // the node containing the text range's boundary, so we move the end of the working range to the\n // boundary point and measure the length of its text to get the boundary's offset within the node.\n workingRange.setEndPoint(isStart ? \"EndToStart\" : \"EndToEnd\", textRange);\n\n var offset;\n\n if (/[\\r\\n]/.test(boundaryNode.data)) {\n /*\n For the particular case of a boundary within a text node containing rendered line breaks (within a\n
 element, for example), we need a slightly complicated approach to get the boundary's offset in\n                        IE. The facts:\n\n                        - Each line break is represented as \\r in the text node's data/nodeValue properties\n                        - Each line break is represented as \\r\\n in the TextRange's 'text' property\n                        - The 'text' property of the TextRange does not contain trailing line breaks\n\n                        To get round the problem presented by the final fact above, we can use the fact that TextRange's\n                        moveStart() and moveEnd() methods return the actual number of characters moved, which is not\n                        necessarily the same as the number of characters it was instructed to move. The simplest approach is\n                        to use this to store the characters moved when moving both the start and end of the range to the\n                        start of the document body and subtracting the start offset from the end offset (the\n                        \"move-negative-gazillion\" method). However, this is extremely slow when the document is large and\n                        the range is near the end of it. Clearly doing the mirror image (i.e. moving the range boundaries to\n                        the end of the document) has the same problem.\n\n                        Another approach that works is to use moveStart() to move the start boundary of the range up to the\n                        end boundary one character at a time and incrementing a counter with the value returned by the\n                        moveStart() call. However, the check for whether the start boundary has reached the end boundary is\n                        expensive, so this method is slow (although unlike \"move-negative-gazillion\" is largely unaffected\n                        by the location of the range within the document).\n\n                        The approach used below is a hybrid of the two methods above. It uses the fact that a string\n                        containing the TextRange's 'text' property with each \\r\\n converted to a single \\r character cannot\n                        be longer than the text of the TextRange, so the start of the range is moved that length initially\n                        and then a character at a time to make up for any trailing line breaks not contained in the 'text'\n                        property. This has good performance in most situations compared to the previous two methods.\n                        */\n                        var tempRange = workingRange.duplicate();\n                        var rangeLength = tempRange.text.replace(/\\r\\n/g, \"\\r\").length;\n\n                        offset = tempRange.moveStart(\"character\", rangeLength);\n                        while ( (comparison = tempRange.compareEndPoints(\"StartToEnd\", tempRange)) == -1) {\n                            offset++;\n                            tempRange.moveStart(\"character\", 1);\n                        }\n                    } else {\n                        offset = workingRange.text.length;\n                    }\n                    boundaryPosition = new DomPosition(boundaryNode, offset);\n                } else {\n\n                    // If the boundary immediately follows a character data node and this is the end boundary, we should favour\n                    // a position within that, and likewise for a start boundary preceding a character data node\n                    previousNode = (isCollapsed || !isStart) && workingNode.previousSibling;\n                    nextNode = (isCollapsed || isStart) && workingNode.nextSibling;\n                    if (nextNode && isCharacterDataNode(nextNode)) {\n                        boundaryPosition = new DomPosition(nextNode, 0);\n                    } else if (previousNode && isCharacterDataNode(previousNode)) {\n                        boundaryPosition = new DomPosition(previousNode, previousNode.data.length);\n                    } else {\n                        boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode));\n                    }\n                }\n\n                // Clean up\n                dom.removeNode(workingNode);\n\n                return {\n                    boundaryPosition: boundaryPosition,\n                    nodeInfo: {\n                        nodeIndex: nodeIndex,\n                        containerElement: containerElement\n                    }\n                };\n            };\n\n            // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that\n            // node. This function started out as an optimized version of code found in Tim Cameron Ryan's IERange\n            // (http://code.google.com/p/ierange/)\n            var createBoundaryTextRange = function(boundaryPosition, isStart) {\n                var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset;\n                var doc = dom.getDocument(boundaryPosition.node);\n                var workingNode, childNodes, workingRange = getBody(doc).createTextRange();\n                var nodeIsDataNode = isCharacterDataNode(boundaryPosition.node);\n\n                if (nodeIsDataNode) {\n                    boundaryNode = boundaryPosition.node;\n                    boundaryParent = boundaryNode.parentNode;\n                } else {\n                    childNodes = boundaryPosition.node.childNodes;\n                    boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null;\n                    boundaryParent = boundaryPosition.node;\n                }\n\n                // Position the range immediately before the node containing the boundary\n                workingNode = doc.createElement(\"span\");\n\n                // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within\n                // the element rather than immediately before or after it\n                workingNode.innerHTML = \"&#feff;\";\n\n                // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report\n                // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12\n                if (boundaryNode) {\n                    boundaryParent.insertBefore(workingNode, boundaryNode);\n                } else {\n                    boundaryParent.appendChild(workingNode);\n                }\n\n                workingRange.moveToElementText(workingNode);\n                workingRange.collapse(!isStart);\n\n                // Clean up\n                boundaryParent.removeChild(workingNode);\n\n                // Move the working range to the text offset, if required\n                if (nodeIsDataNode) {\n                    workingRange[isStart ? \"moveStart\" : \"moveEnd\"](\"character\", boundaryOffset);\n                }\n\n                return workingRange;\n            };\n\n            /*------------------------------------------------------------------------------------------------------------*/\n\n            // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a\n            // prototype\n\n            WrappedTextRange = function(textRange) {\n                this.textRange = textRange;\n                this.refresh();\n            };\n\n            WrappedTextRange.prototype = new DomRange(document);\n\n            WrappedTextRange.prototype.refresh = function() {\n                var start, end, startBoundary;\n\n                // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that.\n                var rangeContainerElement = getTextRangeContainerElement(this.textRange);\n\n                if (textRangeIsCollapsed(this.textRange)) {\n                    end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true,\n                        true).boundaryPosition;\n                } else {\n                    startBoundary = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false);\n                    start = startBoundary.boundaryPosition;\n\n                    // An optimization used here is that if the start and end boundaries have the same parent element, the\n                    // search scope for the end boundary can be limited to exclude the portion of the element that precedes\n                    // the start boundary\n                    end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false,\n                        startBoundary.nodeInfo).boundaryPosition;\n                }\n\n                this.setStart(start.node, start.offset);\n                this.setEnd(end.node, end.offset);\n            };\n\n            WrappedTextRange.prototype.getName = function() {\n                return \"WrappedTextRange\";\n            };\n\n            DomRange.copyComparisonConstants(WrappedTextRange);\n\n            var rangeToTextRange = function(range) {\n                if (range.collapsed) {\n                    return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);\n                } else {\n                    var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);\n                    var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false);\n                    var textRange = getBody( DomRange.getRangeDocument(range) ).createTextRange();\n                    textRange.setEndPoint(\"StartToStart\", startRange);\n                    textRange.setEndPoint(\"EndToEnd\", endRange);\n                    return textRange;\n                }\n            };\n\n            WrappedTextRange.rangeToTextRange = rangeToTextRange;\n\n            WrappedTextRange.prototype.toTextRange = function() {\n                return rangeToTextRange(this);\n            };\n\n            api.WrappedTextRange = WrappedTextRange;\n\n            // IE 9 and above have both implementations and Rangy makes both available. The next few lines sets which\n            // implementation to use by default.\n            if (!api.features.implementsDomRange || api.config.preferTextRange) {\n                // Add WrappedTextRange as the Range property of the global object to allow expression like Range.END_TO_END to work\n                var globalObj = (function(f) { return f(\"return this;\")(); })(Function);\n                if (typeof globalObj.Range == \"undefined\") {\n                    globalObj.Range = WrappedTextRange;\n                }\n\n                api.createNativeRange = function(doc) {\n                    doc = getContentDocument(doc, module, \"createNativeRange\");\n                    return getBody(doc).createTextRange();\n                };\n\n                api.WrappedRange = WrappedTextRange;\n            }\n        }\n\n        api.createRange = function(doc) {\n            doc = getContentDocument(doc, module, \"createRange\");\n            return new api.WrappedRange(api.createNativeRange(doc));\n        };\n\n        api.createRangyRange = function(doc) {\n            doc = getContentDocument(doc, module, \"createRangyRange\");\n            return new DomRange(doc);\n        };\n\n        util.createAliasForDeprecatedMethod(api, \"createIframeRange\", \"createRange\");\n        util.createAliasForDeprecatedMethod(api, \"createIframeRangyRange\", \"createRangyRange\");\n\n        api.addShimListener(function(win) {\n            var doc = win.document;\n            if (typeof doc.createRange == \"undefined\") {\n                doc.createRange = function() {\n                    return api.createRange(doc);\n                };\n            }\n            doc = win = null;\n        });\n    });\n\n    /*----------------------------------------------------------------------------------------------------------------*/\n\n    // This module creates a selection object wrapper that conforms as closely as possible to the Selection specification\n    // in the W3C Selection API spec (https://www.w3.org/TR/selection-api)\n    api.createCoreModule(\"WrappedSelection\", [\"DomRange\", \"WrappedRange\"], function(api, module) {\n        api.config.checkSelectionRanges = true;\n\n        var BOOLEAN = \"boolean\";\n        var NUMBER = \"number\";\n        var dom = api.dom;\n        var util = api.util;\n        var isHostMethod = util.isHostMethod;\n        var DomRange = api.DomRange;\n        var WrappedRange = api.WrappedRange;\n        var DOMException = api.DOMException;\n        var DomPosition = dom.DomPosition;\n        var getNativeSelection;\n        var selectionIsCollapsed;\n        var features = api.features;\n        var CONTROL = \"Control\";\n        var getDocument = dom.getDocument;\n        var getBody = dom.getBody;\n        var rangesEqual = DomRange.rangesEqual;\n\n\n        // Utility function to support direction parameters in the API that may be a string (\"backward\", \"backwards\",\n        // \"forward\" or \"forwards\") or a Boolean (true for backwards).\n        function isDirectionBackward(dir) {\n            return (typeof dir == \"string\") ? /^backward(s)?$/i.test(dir) : !!dir;\n        }\n\n        function getWindow(win, methodName) {\n            if (!win) {\n                return window;\n            } else if (dom.isWindow(win)) {\n                return win;\n            } else if (win instanceof WrappedSelection) {\n                return win.win;\n            } else {\n                var doc = dom.getContentDocument(win, module, methodName);\n                return dom.getWindow(doc);\n            }\n        }\n\n        function getWinSelection(winParam) {\n            return getWindow(winParam, \"getWinSelection\").getSelection();\n        }\n\n        function getDocSelection(winParam) {\n            return getWindow(winParam, \"getDocSelection\").document.selection;\n        }\n\n        function winSelectionIsBackward(sel) {\n            var backward = false;\n            if (sel.anchorNode) {\n                backward = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1);\n            }\n            return backward;\n        }\n\n        // Test for the Range/TextRange and Selection features required\n        // Test for ability to retrieve selection\n        var implementsWinGetSelection = isHostMethod(window, \"getSelection\"),\n            implementsDocSelection = util.isHostObject(document, \"selection\");\n\n        features.implementsWinGetSelection = implementsWinGetSelection;\n        features.implementsDocSelection = implementsDocSelection;\n\n        var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange);\n\n        if (useDocumentSelection) {\n            getNativeSelection = getDocSelection;\n            api.isSelectionValid = function(winParam) {\n                var doc = getWindow(winParam, \"isSelectionValid\").document, nativeSel = doc.selection;\n\n                // Check whether the selection TextRange is actually contained within the correct document\n                return (nativeSel.type != \"None\" || getDocument(nativeSel.createRange().parentElement()) == doc);\n            };\n        } else if (implementsWinGetSelection) {\n            getNativeSelection = getWinSelection;\n            api.isSelectionValid = function() {\n                return true;\n            };\n        } else {\n            module.fail(\"Neither document.selection or window.getSelection() detected.\");\n            return false;\n        }\n\n        api.getNativeSelection = getNativeSelection;\n\n        var testSelection = getNativeSelection();\n\n        // In Firefox, the selection is null in an iframe with display: none. See issue #138.\n        if (!testSelection) {\n            module.fail(\"Native selection was null (possibly issue 138?)\");\n            return false;\n        }\n\n        var testRange = api.createNativeRange(document);\n        var body = getBody(document);\n\n        // Obtaining a range from a selection\n        var selectionHasAnchorAndFocus = util.areHostProperties(testSelection,\n            [\"anchorNode\", \"focusNode\", \"anchorOffset\", \"focusOffset\"]);\n\n        features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus;\n\n        // Test for existence of native selection extend() method\n        var selectionHasExtend = isHostMethod(testSelection, \"extend\");\n        features.selectionHasExtend = selectionHasExtend;\n\n        // Test for existence of native selection setBaseAndExtent() method\n        var selectionHasSetBaseAndExtent = isHostMethod(testSelection, \"setBaseAndExtent\");\n        features.selectionHasSetBaseAndExtent = selectionHasSetBaseAndExtent;\n\n        // Test if rangeCount exists\n        var selectionHasRangeCount = (typeof testSelection.rangeCount == NUMBER);\n        features.selectionHasRangeCount = selectionHasRangeCount;\n\n        var selectionSupportsMultipleRanges = false;\n        var collapsedNonEditableSelectionsSupported = true;\n\n        var addRangeBackwardToNative = selectionHasExtend ?\n            function(nativeSelection, range) {\n                var doc = DomRange.getRangeDocument(range);\n                var endRange = api.createRange(doc);\n                endRange.collapseToPoint(range.endContainer, range.endOffset);\n                nativeSelection.addRange(getNativeRange(endRange));\n                nativeSelection.extend(range.startContainer, range.startOffset);\n            } : null;\n\n        if (util.areHostMethods(testSelection, [\"addRange\", \"getRangeAt\", \"removeAllRanges\"]) &&\n                typeof testSelection.rangeCount == NUMBER && features.implementsDomRange) {\n\n            (function() {\n                // Previously an iframe was used but this caused problems in some circumstances in IE, so tests are\n                // performed on the current document's selection. See issue 109.\n\n                // Note also that if a selection previously existed, it is wiped and later restored by these tests. This\n                // will result in the selection direction being reversed if the original selection was backwards and the\n                // browser does not support setting backwards selections (Internet Explorer, I'm looking at you).\n                var sel = window.getSelection();\n                if (sel) {\n                    // Store the current selection\n                    var originalSelectionRangeCount = sel.rangeCount;\n                    var selectionHasMultipleRanges = (originalSelectionRangeCount > 1);\n                    var originalSelectionRanges = [];\n                    var originalSelectionBackward = winSelectionIsBackward(sel);\n                    for (var i = 0; i < originalSelectionRangeCount; ++i) {\n                        originalSelectionRanges[i] = sel.getRangeAt(i);\n                    }\n\n                    // Create some test elements\n                    var testEl = dom.createTestElement(document, \"\", false);\n                    var textNode = testEl.appendChild( document.createTextNode(\"\\u00a0\\u00a0\\u00a0\") );\n\n                    // Test whether the native selection will allow a collapsed selection within a non-editable element\n                    var r1 = document.createRange();\n\n                    r1.setStart(textNode, 1);\n                    r1.collapse(true);\n                    sel.removeAllRanges();\n                    sel.addRange(r1);\n                    collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);\n                    sel.removeAllRanges();\n\n                    // Test whether the native selection is capable of supporting multiple ranges.\n                    if (!selectionHasMultipleRanges) {\n                        // Doing the original feature test here in Chrome 36 (and presumably later versions) prints a\n                        // console error of \"Discontiguous selection is not supported.\" that cannot be suppressed. There's\n                        // nothing we can do about this while retaining the feature test so we have to resort to a browser\n                        // sniff. I'm not happy about it. See\n                        // https://code.google.com/p/chromium/issues/detail?id=399791\n                        var chromeMatch = window.navigator.appVersion.match(/Chrome\\/(.*?) /);\n                        if (chromeMatch && parseInt(chromeMatch[1]) >= 36) {\n                            selectionSupportsMultipleRanges = false;\n                        } else {\n                            var r2 = r1.cloneRange();\n                            r1.setStart(textNode, 0);\n                            r2.setEnd(textNode, 3);\n                            r2.setStart(textNode, 2);\n                            sel.addRange(r1);\n                            sel.addRange(r2);\n                            selectionSupportsMultipleRanges = (sel.rangeCount == 2);\n                        }\n                    }\n\n                    // Clean up\n                    dom.removeNode(testEl);\n                    sel.removeAllRanges();\n\n                    for (i = 0; i < originalSelectionRangeCount; ++i) {\n                        if (i == 0 && originalSelectionBackward) {\n                            if (addRangeBackwardToNative) {\n                                addRangeBackwardToNative(sel, originalSelectionRanges[i]);\n                            } else {\n                                api.warn(\"Rangy initialization: original selection was backwards but selection has been restored forwards because the browser does not support Selection.extend\");\n                                sel.addRange(originalSelectionRanges[i]);\n                            }\n                        } else {\n                            sel.addRange(originalSelectionRanges[i]);\n                        }\n                    }\n                }\n            })();\n        }\n\n        features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges;\n        features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported;\n\n        // ControlRanges\n        var implementsControlRange = false, testControlRange;\n\n        if (body && isHostMethod(body, \"createControlRange\")) {\n            testControlRange = body.createControlRange();\n            if (util.areHostProperties(testControlRange, [\"item\", \"add\"])) {\n                implementsControlRange = true;\n            }\n        }\n        features.implementsControlRange = implementsControlRange;\n\n        // Selection collapsedness\n        if (selectionHasAnchorAndFocus) {\n            selectionIsCollapsed = function(sel) {\n                return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset;\n            };\n        } else {\n            selectionIsCollapsed = function(sel) {\n                return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false;\n            };\n        }\n\n        function updateAnchorAndFocusFromRange(sel, range, backward) {\n            var anchorPrefix = backward ? \"end\" : \"start\", focusPrefix = backward ? \"start\" : \"end\";\n            sel.anchorNode = range[anchorPrefix + \"Container\"];\n            sel.anchorOffset = range[anchorPrefix + \"Offset\"];\n            sel.focusNode = range[focusPrefix + \"Container\"];\n            sel.focusOffset = range[focusPrefix + \"Offset\"];\n        }\n\n        function updateAnchorAndFocusFromNativeSelection(sel) {\n            var nativeSel = sel.nativeSelection;\n            sel.anchorNode = nativeSel.anchorNode;\n            sel.anchorOffset = nativeSel.anchorOffset;\n            sel.focusNode = nativeSel.focusNode;\n            sel.focusOffset = nativeSel.focusOffset;\n        }\n\n        function updateEmptySelection(sel) {\n            sel.anchorNode = sel.focusNode = null;\n            sel.anchorOffset = sel.focusOffset = 0;\n            sel.rangeCount = 0;\n            sel.isCollapsed = true;\n            sel._ranges.length = 0;\n            updateType(sel);\n        }\n\n        function updateType(sel) {\n            sel.type = (sel.rangeCount == 0) ? \"None\" : (selectionIsCollapsed(sel) ? \"Caret\" : \"Range\");\n        }\n\n        function getNativeRange(range) {\n            var nativeRange;\n            if (range instanceof DomRange) {\n                nativeRange = api.createNativeRange(range.getDocument());\n                nativeRange.setEnd(range.endContainer, range.endOffset);\n                nativeRange.setStart(range.startContainer, range.startOffset);\n            } else if (range instanceof WrappedRange) {\n                nativeRange = range.nativeRange;\n            } else if (features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) {\n                nativeRange = range;\n            }\n            return nativeRange;\n        }\n\n        function rangeContainsSingleElement(rangeNodes) {\n            if (!rangeNodes.length || rangeNodes[0].nodeType != 1) {\n                return false;\n            }\n            for (var i = 1, len = rangeNodes.length; i < len; ++i) {\n                if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        function getSingleElementFromRange(range) {\n            var nodes = range.getNodes();\n            if (!rangeContainsSingleElement(nodes)) {\n                throw module.createError(\"getSingleElementFromRange: range \" + range.inspect() + \" did not consist of a single element\");\n            }\n            return nodes[0];\n        }\n\n        // Simple, quick test which only needs to distinguish between a TextRange and a ControlRange\n        function isTextRange(range) {\n            return !!range && typeof range.text != \"undefined\";\n        }\n\n        function updateFromTextRange(sel, range) {\n            // Create a Range from the selected TextRange\n            var wrappedRange = new WrappedRange(range);\n            sel._ranges = [wrappedRange];\n\n            updateAnchorAndFocusFromRange(sel, wrappedRange, false);\n            sel.rangeCount = 1;\n            sel.isCollapsed = wrappedRange.collapsed;\n            updateType(sel);\n        }\n\n        function updateControlSelection(sel) {\n            // Update the wrapped selection based on what's now in the native selection\n            sel._ranges.length = 0;\n            if (sel.docSelection.type == \"None\") {\n                updateEmptySelection(sel);\n            } else {\n                var controlRange = sel.docSelection.createRange();\n                if (isTextRange(controlRange)) {\n                    // This case (where the selection type is \"Control\" and calling createRange() on the selection returns\n                    // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected\n                    // ControlRange have been removed from the ControlRange and removed from the document.\n                    updateFromTextRange(sel, controlRange);\n                } else {\n                    sel.rangeCount = controlRange.length;\n                    var range, doc = getDocument(controlRange.item(0));\n                    for (var i = 0; i < sel.rangeCount; ++i) {\n                        range = api.createRange(doc);\n                        range.selectNode(controlRange.item(i));\n                        sel._ranges.push(range);\n                    }\n                    sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed;\n                    updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false);\n                    updateType(sel);\n                }\n            }\n        }\n\n        function addRangeToControlSelection(sel, range) {\n            var controlRange = sel.docSelection.createRange();\n            var rangeElement = getSingleElementFromRange(range);\n\n            // Create a new ControlRange containing all the elements in the selected ControlRange plus the element\n            // contained by the supplied range\n            var doc = getDocument(controlRange.item(0));\n            var newControlRange = getBody(doc).createControlRange();\n            for (var i = 0, len = controlRange.length; i < len; ++i) {\n                newControlRange.add(controlRange.item(i));\n            }\n            try {\n                newControlRange.add(rangeElement);\n            } catch (ex) {\n                throw module.createError(\"addRange(): Element within the specified Range could not be added to control selection (does it have layout?)\");\n            }\n            newControlRange.select();\n\n            // Update the wrapped selection based on what's now in the native selection\n            updateControlSelection(sel);\n        }\n\n        var getSelectionRangeAt;\n\n        if (isHostMethod(testSelection, \"getRangeAt\")) {\n            // try/catch is present because getRangeAt() must have thrown an error in some browser and some situation.\n            // Unfortunately, I didn't write a comment about the specifics and am now scared to take it out. Let that be a\n            // lesson to us all, especially me.\n            getSelectionRangeAt = function(sel, index) {\n                try {\n                    return sel.getRangeAt(index);\n                } catch (ex) {\n                    return null;\n                }\n            };\n        } else if (selectionHasAnchorAndFocus) {\n            getSelectionRangeAt = function(sel) {\n                var doc = getDocument(sel.anchorNode);\n                var range = api.createRange(doc);\n                range.setStartAndEnd(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset);\n\n                // Handle the case when the selection was selected backwards (from the end to the start in the\n                // document)\n                if (range.collapsed !== this.isCollapsed) {\n                    range.setStartAndEnd(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset);\n                }\n\n                return range;\n            };\n        }\n\n        function WrappedSelection(selection, docSelection, win) {\n            this.nativeSelection = selection;\n            this.docSelection = docSelection;\n            this._ranges = [];\n            this.win = win;\n            this.refresh();\n        }\n\n        WrappedSelection.prototype = api.selectionPrototype;\n\n        function deleteProperties(sel) {\n            sel.win = sel.anchorNode = sel.focusNode = sel._ranges = null;\n            sel.rangeCount = sel.anchorOffset = sel.focusOffset = 0;\n            sel.detached = true;\n            updateType(sel);\n        }\n\n        var cachedRangySelections = [];\n\n        function actOnCachedSelection(win, action) {\n            var i = cachedRangySelections.length, cached, sel;\n            while (i--) {\n                cached = cachedRangySelections[i];\n                sel = cached.selection;\n                if (action == \"deleteAll\") {\n                    deleteProperties(sel);\n                } else if (cached.win == win) {\n                    if (action == \"delete\") {\n                        cachedRangySelections.splice(i, 1);\n                        return true;\n                    } else {\n                        return sel;\n                    }\n                }\n            }\n            if (action == \"deleteAll\") {\n                cachedRangySelections.length = 0;\n            }\n            return null;\n        }\n\n        var getSelection = function(win) {\n            // Check if the parameter is a Rangy Selection object\n            if (win && win instanceof WrappedSelection) {\n                win.refresh();\n                return win;\n            }\n\n            win = getWindow(win, \"getNativeSelection\");\n\n            var sel = actOnCachedSelection(win);\n            var nativeSel = getNativeSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null;\n            if (sel) {\n                sel.nativeSelection = nativeSel;\n                sel.docSelection = docSel;\n                sel.refresh();\n            } else {\n                sel = new WrappedSelection(nativeSel, docSel, win);\n                cachedRangySelections.push( { win: win, selection: sel } );\n            }\n            return sel;\n        };\n\n        api.getSelection = getSelection;\n\n        util.createAliasForDeprecatedMethod(api, \"getIframeSelection\", \"getSelection\");\n\n        var selProto = WrappedSelection.prototype;\n\n        function createControlSelection(sel, ranges) {\n            // Ensure that the selection becomes of type \"Control\"\n            var doc = getDocument(ranges[0].startContainer);\n            var controlRange = getBody(doc).createControlRange();\n            for (var i = 0, el, len = ranges.length; i < len; ++i) {\n                el = getSingleElementFromRange(ranges[i]);\n                try {\n                    controlRange.add(el);\n                } catch (ex) {\n                    throw module.createError(\"setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)\");\n                }\n            }\n            controlRange.select();\n\n            // Update the wrapped selection based on what's now in the native selection\n            updateControlSelection(sel);\n        }\n\n        // Selecting a range\n        if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, [\"removeAllRanges\", \"addRange\"])) {\n            selProto.removeAllRanges = function() {\n                this.nativeSelection.removeAllRanges();\n                updateEmptySelection(this);\n            };\n\n            var addRangeBackward = function(sel, range) {\n                addRangeBackwardToNative(sel.nativeSelection, range);\n                sel.refresh();\n            };\n\n            if (selectionHasRangeCount) {\n                selProto.addRange = function(range, direction) {\n                    if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {\n                        addRangeToControlSelection(this, range);\n                    } else {\n                        if (isDirectionBackward(direction) && selectionHasExtend) {\n                            addRangeBackward(this, range);\n                        } else {\n                            var previousRangeCount;\n                            if (selectionSupportsMultipleRanges) {\n                                previousRangeCount = this.rangeCount;\n                            } else {\n                                this.removeAllRanges();\n                                previousRangeCount = 0;\n                            }\n                            // Clone the native range so that changing the selected range does not affect the selection.\n                            // This is contrary to the spec but is the only way to achieve consistency between browsers. See\n                            // issue 80.\n                            var clonedNativeRange = getNativeRange(range).cloneRange();\n                            try {\n                                this.nativeSelection.addRange(clonedNativeRange);\n                            } catch (ex) {\n                            }\n\n                            // Check whether adding the range was successful\n                            this.rangeCount = this.nativeSelection.rangeCount;\n\n                            if (this.rangeCount == previousRangeCount + 1) {\n                                // The range was added successfully\n\n                                // Check whether the range that we added to the selection is reflected in the last range extracted from\n                                // the selection\n                                if (api.config.checkSelectionRanges) {\n                                    var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1);\n                                    if (nativeRange && !rangesEqual(nativeRange, range)) {\n                                        // Happens in WebKit with, for example, a selection placed at the start of a text node\n                                        range = new WrappedRange(nativeRange);\n                                    }\n                                }\n                                this._ranges[this.rangeCount - 1] = range;\n                                updateAnchorAndFocusFromRange(this, range, selectionIsBackward(this.nativeSelection));\n                                this.isCollapsed = selectionIsCollapsed(this);\n                                updateType(this);\n                            } else {\n                                // The range was not added successfully. The simplest thing is to refresh\n                                this.refresh();\n                            }\n                        }\n                    }\n                };\n            } else {\n                selProto.addRange = function(range, direction) {\n                    if (isDirectionBackward(direction) && selectionHasExtend) {\n                        addRangeBackward(this, range);\n                    } else {\n                        this.nativeSelection.addRange(getNativeRange(range));\n                        this.refresh();\n                    }\n                };\n            }\n\n            selProto.setRanges = function(ranges) {\n                if (implementsControlRange && implementsDocSelection && ranges.length > 1) {\n                    createControlSelection(this, ranges);\n                } else {\n                    this.removeAllRanges();\n                    for (var i = 0, len = ranges.length; i < len; ++i) {\n                        this.addRange(ranges[i]);\n                    }\n                }\n            };\n        } else if (isHostMethod(testSelection, \"empty\") && isHostMethod(testRange, \"select\") &&\n                   implementsControlRange && useDocumentSelection) {\n\n            selProto.removeAllRanges = function() {\n                // Added try/catch as fix for issue #21\n                try {\n                    this.docSelection.empty();\n\n                    // Check for empty() not working (issue #24)\n                    if (this.docSelection.type != \"None\") {\n                        // Work around failure to empty a control selection by instead selecting a TextRange and then\n                        // calling empty()\n                        var doc;\n                        if (this.anchorNode) {\n                            doc = getDocument(this.anchorNode);\n                        } else if (this.docSelection.type == CONTROL) {\n                            var controlRange = this.docSelection.createRange();\n                            if (controlRange.length) {\n                                doc = getDocument( controlRange.item(0) );\n                            }\n                        }\n                        if (doc) {\n                            var textRange = getBody(doc).createTextRange();\n                            textRange.select();\n                            this.docSelection.empty();\n                        }\n                    }\n                } catch(ex) {}\n                updateEmptySelection(this);\n            };\n\n            selProto.addRange = function(range) {\n                if (this.docSelection.type == CONTROL) {\n                    addRangeToControlSelection(this, range);\n                } else {\n                    api.WrappedTextRange.rangeToTextRange(range).select();\n                    this._ranges[0] = range;\n                    this.rangeCount = 1;\n                    this.isCollapsed = this._ranges[0].collapsed;\n                    updateAnchorAndFocusFromRange(this, range, false);\n                    updateType(this);\n                }\n            };\n\n            selProto.setRanges = function(ranges) {\n                this.removeAllRanges();\n                var rangeCount = ranges.length;\n                if (rangeCount > 1) {\n                    createControlSelection(this, ranges);\n                } else if (rangeCount) {\n                    this.addRange(ranges[0]);\n                }\n            };\n        } else {\n            module.fail(\"No means of selecting a Range or TextRange was found\");\n            return false;\n        }\n\n        selProto.getRangeAt = function(index) {\n            if (index < 0 || index >= this.rangeCount) {\n                throw new DOMException(\"INDEX_SIZE_ERR\");\n            } else {\n                // Clone the range to preserve selection-range independence. See issue 80.\n                return this._ranges[index].cloneRange();\n            }\n        };\n\n        var refreshSelection;\n\n        if (useDocumentSelection) {\n            refreshSelection = function(sel) {\n                var range;\n                if (api.isSelectionValid(sel.win)) {\n                    range = sel.docSelection.createRange();\n                } else {\n                    range = getBody(sel.win.document).createTextRange();\n                    range.collapse(true);\n                }\n\n                if (sel.docSelection.type == CONTROL) {\n                    updateControlSelection(sel);\n                } else if (isTextRange(range)) {\n                    updateFromTextRange(sel, range);\n                } else {\n                    updateEmptySelection(sel);\n                }\n            };\n        } else if (isHostMethod(testSelection, \"getRangeAt\") && typeof testSelection.rangeCount == NUMBER) {\n            refreshSelection = function(sel) {\n                if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) {\n                    updateControlSelection(sel);\n                } else {\n                    sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount;\n                    if (sel.rangeCount) {\n                        for (var i = 0, len = sel.rangeCount; i < len; ++i) {\n                            sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i));\n                        }\n                        updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackward(sel.nativeSelection));\n                        sel.isCollapsed = selectionIsCollapsed(sel);\n                        updateType(sel);\n                    } else {\n                        updateEmptySelection(sel);\n                    }\n                }\n            };\n        } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && features.implementsDomRange) {\n            refreshSelection = function(sel) {\n                var range, nativeSel = sel.nativeSelection;\n                if (nativeSel.anchorNode) {\n                    range = getSelectionRangeAt(nativeSel, 0);\n                    sel._ranges = [range];\n                    sel.rangeCount = 1;\n                    updateAnchorAndFocusFromNativeSelection(sel);\n                    sel.isCollapsed = selectionIsCollapsed(sel);\n                    updateType(sel);\n                } else {\n                    updateEmptySelection(sel);\n                }\n            };\n        } else {\n            module.fail(\"No means of obtaining a Range or TextRange from the user's selection was found\");\n            return false;\n        }\n\n        selProto.refresh = function(checkForChanges) {\n            var oldRanges = checkForChanges ? this._ranges.slice(0) : null;\n            var oldAnchorNode = this.anchorNode, oldAnchorOffset = this.anchorOffset;\n\n            refreshSelection(this);\n            if (checkForChanges) {\n                // Check the range count first\n                var i = oldRanges.length;\n                if (i != this._ranges.length) {\n                    return true;\n                }\n\n                // Now check the direction. Checking the anchor position is the same is enough since we're checking all the\n                // ranges after this\n                if (this.anchorNode != oldAnchorNode || this.anchorOffset != oldAnchorOffset) {\n                    return true;\n                }\n\n                // Finally, compare each range in turn\n                while (i--) {\n                    if (!rangesEqual(oldRanges[i], this._ranges[i])) {\n                        return true;\n                    }\n                }\n                return false;\n            }\n        };\n\n        // Removal of a single range\n        var removeRangeManually = function(sel, range) {\n            var ranges = sel.getAllRanges();\n            sel.removeAllRanges();\n            for (var i = 0, len = ranges.length; i < len; ++i) {\n                if (!rangesEqual(range, ranges[i])) {\n                    sel.addRange(ranges[i]);\n                }\n            }\n            if (!sel.rangeCount) {\n                updateEmptySelection(sel);\n            }\n        };\n\n        if (implementsControlRange && implementsDocSelection) {\n            selProto.removeRange = function(range) {\n                if (this.docSelection.type == CONTROL) {\n                    var controlRange = this.docSelection.createRange();\n                    var rangeElement = getSingleElementFromRange(range);\n\n                    // Create a new ControlRange containing all the elements in the selected ControlRange minus the\n                    // element contained by the supplied range\n                    var doc = getDocument(controlRange.item(0));\n                    var newControlRange = getBody(doc).createControlRange();\n                    var el, removed = false;\n                    for (var i = 0, len = controlRange.length; i < len; ++i) {\n                        el = controlRange.item(i);\n                        if (el !== rangeElement || removed) {\n                            newControlRange.add(controlRange.item(i));\n                        } else {\n                            removed = true;\n                        }\n                    }\n                    newControlRange.select();\n\n                    // Update the wrapped selection based on what's now in the native selection\n                    updateControlSelection(this);\n                } else {\n                    removeRangeManually(this, range);\n                }\n            };\n        } else {\n            selProto.removeRange = function(range) {\n                removeRangeManually(this, range);\n            };\n        }\n\n        // Detecting if a selection is backward\n        var selectionIsBackward;\n        if (!useDocumentSelection && selectionHasAnchorAndFocus && features.implementsDomRange) {\n            selectionIsBackward = winSelectionIsBackward;\n\n            selProto.isBackward = function() {\n                return selectionIsBackward(this);\n            };\n        } else {\n            selectionIsBackward = selProto.isBackward = function() {\n                return false;\n            };\n        }\n\n        // Create an alias for backwards compatibility. From 1.3, everything is \"backward\" rather than \"backwards\"\n        selProto.isBackwards = selProto.isBackward;\n\n        // Selection stringifier\n        // This is conformant to the old HTML5 selections draft spec but differs from WebKit and Mozilla's implementation.\n        // The current spec does not yet define this method.\n        selProto.toString = function() {\n            var rangeTexts = [];\n            for (var i = 0, len = this.rangeCount; i < len; ++i) {\n                rangeTexts[i] = \"\" + this._ranges[i];\n            }\n            return rangeTexts.join(\"\");\n        };\n\n        function assertNodeInSameDocument(sel, node) {\n            if (sel.win.document != getDocument(node)) {\n                throw new DOMException(\"WRONG_DOCUMENT_ERR\");\n            }\n        }\n\n        function assertValidOffset(node, offset) {\n            if (offset < 0 || offset > (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length)) {\n                throw new DOMException(\"INDEX_SIZE_ERR\");\n            }\n        }\n\n        // No current browser conforms fully to the spec for this method, so Rangy's own method is always used\n        selProto.collapse = function(node, offset) {\n            assertNodeInSameDocument(this, node);\n            var range = api.createRange(node);\n            range.collapseToPoint(node, offset);\n            this.setSingleRange(range);\n            this.isCollapsed = true;\n        };\n\n        selProto.collapseToStart = function() {\n            if (this.rangeCount) {\n                var range = this._ranges[0];\n                this.collapse(range.startContainer, range.startOffset);\n            } else {\n                throw new DOMException(\"INVALID_STATE_ERR\");\n            }\n        };\n\n        selProto.collapseToEnd = function() {\n            if (this.rangeCount) {\n                var range = this._ranges[this.rangeCount - 1];\n                this.collapse(range.endContainer, range.endOffset);\n            } else {\n                throw new DOMException(\"INVALID_STATE_ERR\");\n            }\n        };\n\n        // The spec is very specific on how selectAllChildren should be implemented and not all browsers implement it as\n        // specified so the native implementation is never used by Rangy.\n        selProto.selectAllChildren = function(node) {\n            assertNodeInSameDocument(this, node);\n            var range = api.createRange(node);\n            range.selectNodeContents(node);\n            this.setSingleRange(range);\n        };\n\n        if (selectionHasSetBaseAndExtent) {\n            selProto.setBaseAndExtent = function(anchorNode, anchorOffset, focusNode, focusOffset) {\n                this.nativeSelection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);\n                this.refresh();\n            };\n        } else if (selectionHasExtend) {\n            selProto.setBaseAndExtent = function(anchorNode, anchorOffset, focusNode, focusOffset) {\n                assertValidOffset(anchorNode, anchorOffset);\n                assertValidOffset(focusNode, focusOffset);\n                assertNodeInSameDocument(this, anchorNode);\n                assertNodeInSameDocument(this, focusNode);\n                var range = api.createRange(node);\n                var isBackwards = (dom.comparePoints(anchorNode, anchorOffset, focusNode, focusOffset) == -1);\n                if (isBackwards) {\n                    range.setStartAndEnd(focusNode, focusOffset, anchorNode, anchorOffset);\n                } else {\n                    range.setStartAndEnd(anchorNode, anchorOffset, focusNode, focusOffset);\n                }\n                this.setSingleRange(range, isBackwards);\n            };\n        }\n\n        selProto.deleteFromDocument = function() {\n            // Sepcial behaviour required for IE's control selections\n            if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {\n                var controlRange = this.docSelection.createRange();\n                var element;\n                while (controlRange.length) {\n                    element = controlRange.item(0);\n                    controlRange.remove(element);\n                    dom.removeNode(element);\n                }\n                this.refresh();\n            } else if (this.rangeCount) {\n                var ranges = this.getAllRanges();\n                if (ranges.length) {\n                    this.removeAllRanges();\n                    for (var i = 0, len = ranges.length; i < len; ++i) {\n                        ranges[i].deleteContents();\n                    }\n                    // The spec says nothing about what the selection should contain after calling deleteContents on each\n                    // range. Firefox moves the selection to where the final selected range was, so we emulate that\n                    this.addRange(ranges[len - 1]);\n                }\n            }\n        };\n\n        // The following are non-standard extensions\n        selProto.eachRange = function(func, returnValue) {\n            for (var i = 0, len = this._ranges.length; i < len; ++i) {\n                if ( func( this.getRangeAt(i) ) ) {\n                    return returnValue;\n                }\n            }\n        };\n\n        selProto.getAllRanges = function() {\n            var ranges = [];\n            this.eachRange(function(range) {\n                ranges.push(range);\n            });\n            return ranges;\n        };\n\n        selProto.setSingleRange = function(range, direction) {\n            this.removeAllRanges();\n            this.addRange(range, direction);\n        };\n\n        selProto.callMethodOnEachRange = function(methodName, params) {\n            var results = [];\n            this.eachRange( function(range) {\n                results.push( range[methodName].apply(range, params || []) );\n            } );\n            return results;\n        };\n\n        function createStartOrEndSetter(isStart) {\n            return function(node, offset) {\n                var range;\n                if (this.rangeCount) {\n                    range = this.getRangeAt(0);\n                    range[\"set\" + (isStart ? \"Start\" : \"End\")](node, offset);\n                } else {\n                    range = api.createRange(this.win.document);\n                    range.setStartAndEnd(node, offset);\n                }\n                this.setSingleRange(range, this.isBackward());\n            };\n        }\n\n        selProto.setStart = createStartOrEndSetter(true);\n        selProto.setEnd = createStartOrEndSetter(false);\n\n        // Add select() method to Range prototype. Any existing selection will be removed.\n        api.rangePrototype.select = function(direction) {\n            getSelection( this.getDocument() ).setSingleRange(this, direction);\n        };\n\n        selProto.changeEachRange = function(func) {\n            var ranges = [];\n            var backward = this.isBackward();\n\n            this.eachRange(function(range) {\n                func(range);\n                ranges.push(range);\n            });\n\n            this.removeAllRanges();\n            if (backward && ranges.length == 1) {\n                this.addRange(ranges[0], \"backward\");\n            } else {\n                this.setRanges(ranges);\n            }\n        };\n\n        selProto.containsNode = function(node, allowPartial) {\n            return this.eachRange( function(range) {\n                return range.containsNode(node, allowPartial);\n            }, true ) || false;\n        };\n\n        selProto.getBookmark = function(containerNode) {\n            return {\n                backward: this.isBackward(),\n                rangeBookmarks: this.callMethodOnEachRange(\"getBookmark\", [containerNode])\n            };\n        };\n\n        selProto.moveToBookmark = function(bookmark) {\n            var selRanges = [];\n            for (var i = 0, rangeBookmark, range; rangeBookmark = bookmark.rangeBookmarks[i++]; ) {\n                range = api.createRange(this.win);\n                range.moveToBookmark(rangeBookmark);\n                selRanges.push(range);\n            }\n            if (bookmark.backward) {\n                this.setSingleRange(selRanges[0], \"backward\");\n            } else {\n                this.setRanges(selRanges);\n            }\n        };\n\n        selProto.saveRanges = function() {\n            return {\n                backward: this.isBackward(),\n                ranges: this.callMethodOnEachRange(\"cloneRange\")\n            };\n        };\n\n        selProto.restoreRanges = function(selRanges) {\n            this.removeAllRanges();\n            for (var i = 0, range; range = selRanges.ranges[i]; ++i) {\n                this.addRange(range, (selRanges.backward && i == 0));\n            }\n        };\n\n        selProto.toHtml = function() {\n            var rangeHtmls = [];\n            this.eachRange(function(range) {\n                rangeHtmls.push( DomRange.toHtml(range) );\n            });\n            return rangeHtmls.join(\"\");\n        };\n\n        if (features.implementsTextRange) {\n            selProto.getNativeTextRange = function() {\n                var sel, textRange;\n                if ( (sel = this.docSelection) ) {\n                    var range = sel.createRange();\n                    if (isTextRange(range)) {\n                        return range;\n                    } else {\n                        throw module.createError(\"getNativeTextRange: selection is a control selection\");\n                    }\n                } else if (this.rangeCount > 0) {\n                    return api.WrappedTextRange.rangeToTextRange( this.getRangeAt(0) );\n                } else {\n                    throw module.createError(\"getNativeTextRange: selection contains no range\");\n                }\n            };\n        }\n\n        function inspect(sel) {\n            var rangeInspects = [];\n            var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset);\n            var focus = new DomPosition(sel.focusNode, sel.focusOffset);\n            var name = (typeof sel.getName == \"function\") ? sel.getName() : \"Selection\";\n\n            if (typeof sel.rangeCount != \"undefined\") {\n                for (var i = 0, len = sel.rangeCount; i < len; ++i) {\n                    rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i));\n                }\n            }\n            return \"[\" + name + \"(Ranges: \" + rangeInspects.join(\", \") +\n                    \")(anchor: \" + anchor.inspect() + \", focus: \" + focus.inspect() + \"]\";\n        }\n\n        selProto.getName = function() {\n            return \"WrappedSelection\";\n        };\n\n        selProto.inspect = function() {\n            return inspect(this);\n        };\n\n        selProto.detach = function() {\n            actOnCachedSelection(this.win, \"delete\");\n            deleteProperties(this);\n        };\n\n        WrappedSelection.detachAll = function() {\n            actOnCachedSelection(null, \"deleteAll\");\n        };\n\n        WrappedSelection.inspect = inspect;\n        WrappedSelection.isDirectionBackward = isDirectionBackward;\n\n        api.Selection = WrappedSelection;\n\n        api.selectionPrototype = selProto;\n\n        api.addShimListener(function(win) {\n            if (typeof win.getSelection == \"undefined\") {\n                win.getSelection = function() {\n                    return getSelection(win);\n                };\n            }\n            win = null;\n        });\n    });\n    \n\n    /*----------------------------------------------------------------------------------------------------------------*/\n\n    // Wait for document to load before initializing\n    var docReady = false;\n\n    var loadHandler = function(e) {\n        if (!docReady) {\n            docReady = true;\n            if (!api.initialized && api.config.autoInitialize) {\n                init();\n            }\n        }\n    };\n\n    if (isBrowser) {\n        // Test whether the document has already been loaded and initialize immediately if so\n        if (document.readyState == \"complete\") {\n            loadHandler();\n        } else {\n            if (isHostMethod(document, \"addEventListener\")) {\n                document.addEventListener(\"DOMContentLoaded\", loadHandler, false);\n            }\n\n            // Add a fallback in case the DOMContentLoaded event isn't supported\n            addListener(window, \"load\", loadHandler);\n        }\n    }\n\n    return api;\n}, this);","/**\n * Class Applier module for Rangy.\n * Adds, removes and toggles classes on Ranges and Selections\n *\n * Part of Rangy, a cross-browser JavaScript range and selection library\n * https://github.com/timdown/rangy\n *\n * Depends on Rangy core.\n *\n * Copyright 2024, Tim Down\n * Licensed under the MIT license.\n * Version: 1.3.2\n * Build date: 2 November 2024\n */\n(function(factory, root) {\n    if (typeof define == \"function\" && define.amd) {\n        // AMD. Register as an anonymous module with a dependency on Rangy.\n        define([\"./rangy-core\"], factory);\n    } else if (typeof module != \"undefined\" && typeof exports == \"object\") {\n        // Node/CommonJS style\n        module.exports = factory( require(\"rangy\") );\n    } else {\n        // No AMD or CommonJS support so we use the rangy property of root (probably the global variable)\n        factory(root.rangy);\n    }\n})(function(rangy) {\n    rangy.createModule(\"ClassApplier\", [\"WrappedSelection\"], function(api, module) {\n        var dom = api.dom;\n        var DomPosition = dom.DomPosition;\n        var contains = dom.arrayContains;\n        var util = api.util;\n        var forEach = util.forEach;\n\n\n        var defaultTagName = \"span\";\n        var createElementNSSupported = util.isHostMethod(document, \"createElementNS\");\n\n        function each(obj, func) {\n            for (var i in obj) {\n                if (obj.hasOwnProperty(i)) {\n                    if (func(i, obj[i]) === false) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n\n        function trim(str) {\n            return str.replace(/^\\s\\s*/, \"\").replace(/\\s\\s*$/, \"\");\n        }\n\n        function classNameContainsClass(fullClassName, className) {\n            return !!fullClassName && new RegExp(\"(?:^|\\\\s)\" + className + \"(?:\\\\s|$)\").test(fullClassName);\n        }\n\n        // Inefficient, inelegant nonsense for IE's svg element, which has no classList and non-HTML className implementation\n        function hasClass(el, className) {\n            if (typeof el.classList == \"object\") {\n                return el.classList.contains(className);\n            } else {\n                var classNameSupported = (typeof el.className == \"string\");\n                var elClass = classNameSupported ? el.className : el.getAttribute(\"class\");\n                return classNameContainsClass(elClass, className);\n            }\n        }\n\n        function addClass(el, className) {\n            if (typeof el.classList == \"object\") {\n                el.classList.add(className);\n            } else {\n                var classNameSupported = (typeof el.className == \"string\");\n                var elClass = classNameSupported ? el.className : el.getAttribute(\"class\");\n                if (elClass) {\n                    if (!classNameContainsClass(elClass, className)) {\n                        elClass += \" \" + className;\n                    }\n                } else {\n                    elClass = className;\n                }\n                if (classNameSupported) {\n                    el.className = elClass;\n                } else {\n                    el.setAttribute(\"class\", elClass);\n                }\n            }\n        }\n\n        var removeClass = (function() {\n            function replacer(matched, whiteSpaceBefore, whiteSpaceAfter) {\n                return (whiteSpaceBefore && whiteSpaceAfter) ? \" \" : \"\";\n            }\n\n            return function(el, className) {\n                if (typeof el.classList == \"object\") {\n                    el.classList.remove(className);\n                } else {\n                    var classNameSupported = (typeof el.className == \"string\");\n                    var elClass = classNameSupported ? el.className : el.getAttribute(\"class\");\n                    elClass = elClass.replace(new RegExp(\"(^|\\\\s)\" + className + \"(\\\\s|$)\"), replacer);\n                    if (classNameSupported) {\n                        el.className = elClass;\n                    } else {\n                        el.setAttribute(\"class\", elClass);\n                    }\n                }\n            };\n        })();\n\n        function getClass(el) {\n            var classNameSupported = (typeof el.className == \"string\");\n            return classNameSupported ? el.className : el.getAttribute(\"class\");\n        }\n\n        function sortClassName(className) {\n            return className && className.split(/\\s+/).sort().join(\" \");\n        }\n\n        function getSortedClassName(el) {\n            return sortClassName( getClass(el) );\n        }\n\n        function haveSameClasses(el1, el2) {\n            return getSortedClassName(el1) == getSortedClassName(el2);\n        }\n\n        function hasAllClasses(el, className) {\n            var classes = className.split(/\\s+/);\n            for (var i = 0, len = classes.length; i < len; ++i) {\n                if (!hasClass(el, trim(classes[i]))) {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        function canTextBeStyled(textNode) {\n            var parent = textNode.parentNode;\n            return (parent && parent.nodeType == 1 && !/^(textarea|style|script|select|iframe)$/i.test(parent.nodeName));\n        }\n\n        function movePosition(position, oldParent, oldIndex, newParent, newIndex) {\n            var posNode = position.node, posOffset = position.offset;\n            var newNode = posNode, newOffset = posOffset;\n\n            if (posNode == newParent && posOffset > newIndex) {\n                ++newOffset;\n            }\n\n            if (posNode == oldParent && (posOffset == oldIndex  || posOffset == oldIndex + 1)) {\n                newNode = newParent;\n                newOffset += newIndex - oldIndex;\n            }\n\n            if (posNode == oldParent && posOffset > oldIndex + 1) {\n                --newOffset;\n            }\n\n            position.node = newNode;\n            position.offset = newOffset;\n        }\n\n        function movePositionWhenRemovingNode(position, parentNode, index) {\n            if (position.node == parentNode && position.offset > index) {\n                --position.offset;\n            }\n        }\n\n        function movePreservingPositions(node, newParent, newIndex, positionsToPreserve) {\n            // For convenience, allow newIndex to be -1 to mean \"insert at the end\".\n            if (newIndex == -1) {\n                newIndex = newParent.childNodes.length;\n            }\n\n            var oldParent = node.parentNode;\n            var oldIndex = dom.getNodeIndex(node);\n\n            forEach(positionsToPreserve, function(position) {\n                movePosition(position, oldParent, oldIndex, newParent, newIndex);\n            });\n\n            // Now actually move the node.\n            if (newParent.childNodes.length == newIndex) {\n                newParent.appendChild(node);\n            } else {\n                newParent.insertBefore(node, newParent.childNodes[newIndex]);\n            }\n        }\n\n        function removePreservingPositions(node, positionsToPreserve) {\n\n            var oldParent = node.parentNode;\n            var oldIndex = dom.getNodeIndex(node);\n\n            forEach(positionsToPreserve, function(position) {\n                movePositionWhenRemovingNode(position, oldParent, oldIndex);\n            });\n\n            dom.removeNode(node);\n        }\n\n        function moveChildrenPreservingPositions(node, newParent, newIndex, removeNode, positionsToPreserve) {\n            var child, children = [];\n            while ( (child = node.firstChild) ) {\n                movePreservingPositions(child, newParent, newIndex++, positionsToPreserve);\n                children.push(child);\n            }\n            if (removeNode) {\n                removePreservingPositions(node, positionsToPreserve);\n            }\n            return children;\n        }\n\n        function replaceWithOwnChildrenPreservingPositions(element, positionsToPreserve) {\n            return moveChildrenPreservingPositions(element, element.parentNode, dom.getNodeIndex(element), true, positionsToPreserve);\n        }\n\n        function rangeSelectsAnyText(range, textNode) {\n            var textNodeRange = range.cloneRange();\n            textNodeRange.selectNodeContents(textNode);\n\n            var intersectionRange = textNodeRange.intersection(range);\n            var text = intersectionRange ? intersectionRange.toString() : \"\";\n\n            return text != \"\";\n        }\n\n        function getEffectiveTextNodes(range) {\n            var nodes = range.getNodes([3]);\n\n            // Optimization as per issue 145\n\n            // Remove non-intersecting text nodes from the start of the range\n            var start = 0, node;\n            while ( (node = nodes[start]) && !rangeSelectsAnyText(range, node) ) {\n                ++start;\n            }\n\n            // Remove non-intersecting text nodes from the start of the range\n            var end = nodes.length - 1;\n            while ( (node = nodes[end]) && !rangeSelectsAnyText(range, node) ) {\n                --end;\n            }\n\n            return nodes.slice(start, end + 1);\n        }\n\n        function elementsHaveSameNonClassAttributes(el1, el2) {\n            if (el1.attributes.length != el2.attributes.length) return false;\n            for (var i = 0, len = el1.attributes.length, attr1, attr2, name; i < len; ++i) {\n                attr1 = el1.attributes[i];\n                name = attr1.name;\n                if (name != \"class\") {\n                    attr2 = el2.attributes.getNamedItem(name);\n                    if ( (attr1 === null) != (attr2 === null) ) return false;\n                    if (attr1.specified != attr2.specified) return false;\n                    if (attr1.specified && attr1.nodeValue !== attr2.nodeValue) return false;\n                }\n            }\n            return true;\n        }\n\n        function elementHasNonClassAttributes(el, exceptions) {\n            for (var i = 0, len = el.attributes.length, attrName; i < len; ++i) {\n                attrName = el.attributes[i].name;\n                if ( !(exceptions && contains(exceptions, attrName)) && el.attributes[i].specified && attrName != \"class\") {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        var getComputedStyleProperty = dom.getComputedStyleProperty;\n        var isEditableElement = (function() {\n            var testEl = document.createElement(\"div\");\n            return typeof testEl.isContentEditable == \"boolean\" ?\n                function (node) {\n                    return node && node.nodeType == 1 && node.isContentEditable;\n                } :\n                function (node) {\n                    if (!node || node.nodeType != 1 || node.contentEditable == \"false\") {\n                        return false;\n                    }\n                    return node.contentEditable == \"true\" || isEditableElement(node.parentNode);\n                };\n        })();\n\n        function isEditingHost(node) {\n            var parent;\n            return node && node.nodeType == 1 &&\n                (( (parent = node.parentNode) && parent.nodeType == 9 && parent.designMode == \"on\") ||\n                (isEditableElement(node) && !isEditableElement(node.parentNode)));\n        }\n\n        function isEditable(node) {\n            return (isEditableElement(node) || (node.nodeType != 1 && isEditableElement(node.parentNode))) && !isEditingHost(node);\n        }\n\n        var inlineDisplayRegex = /^inline(-block|-table)?$/i;\n\n        function isNonInlineElement(node) {\n            return node && node.nodeType == 1 && !inlineDisplayRegex.test(getComputedStyleProperty(node, \"display\"));\n        }\n\n        // White space characters as defined by HTML 4 (http://www.w3.org/TR/html401/struct/text.html)\n        var htmlNonWhiteSpaceRegex = /[^\\r\\n\\t\\f \\u200B]/;\n\n        function isUnrenderedWhiteSpaceNode(node) {\n            if (node.data.length == 0) {\n                return true;\n            }\n            if (htmlNonWhiteSpaceRegex.test(node.data)) {\n                return false;\n            }\n            var cssWhiteSpace = getComputedStyleProperty(node.parentNode, \"whiteSpace\");\n            switch (cssWhiteSpace) {\n                case \"pre\":\n                case \"pre-wrap\":\n                case \"-moz-pre-wrap\":\n                    return false;\n                case \"pre-line\":\n                    if (/[\\r\\n]/.test(node.data)) {\n                        return false;\n                    }\n            }\n\n            // We now have a whitespace-only text node that may be rendered depending on its context. If it is adjacent to a\n            // non-inline element, it will not be rendered. This seems to be a good enough definition.\n            return isNonInlineElement(node.previousSibling) || isNonInlineElement(node.nextSibling);\n        }\n\n        function getRangeBoundaries(ranges) {\n            var positions = [], i, range;\n            for (i = 0; range = ranges[i++]; ) {\n                positions.push(\n                    new DomPosition(range.startContainer, range.startOffset),\n                    new DomPosition(range.endContainer, range.endOffset)\n                );\n            }\n            return positions;\n        }\n\n        function updateRangesFromBoundaries(ranges, positions) {\n            for (var i = 0, range, start, end, len = ranges.length; i < len; ++i) {\n                range = ranges[i];\n                start = positions[i * 2];\n                end = positions[i * 2 + 1];\n                range.setStartAndEnd(start.node, start.offset, end.node, end.offset);\n            }\n        }\n\n        function isSplitPoint(node, offset) {\n            if (dom.isCharacterDataNode(node)) {\n                if (offset == 0) {\n                    return !!node.previousSibling;\n                } else if (offset == node.length) {\n                    return !!node.nextSibling;\n                } else {\n                    return true;\n                }\n            }\n\n            return offset > 0 && offset < node.childNodes.length;\n        }\n\n        function splitNodeAt(node, descendantNode, descendantOffset, positionsToPreserve) {\n            var newNode, parentNode;\n            var splitAtStart = (descendantOffset == 0);\n\n            if (dom.isAncestorOf(descendantNode, node)) {\n                return node;\n            }\n\n            if (dom.isCharacterDataNode(descendantNode)) {\n                var descendantIndex = dom.getNodeIndex(descendantNode);\n                if (descendantOffset == 0) {\n                    descendantOffset = descendantIndex;\n                } else if (descendantOffset == descendantNode.length) {\n                    descendantOffset = descendantIndex + 1;\n                } else {\n                    throw module.createError(\"splitNodeAt() should not be called with offset in the middle of a data node (\" +\n                        descendantOffset + \" in \" + descendantNode.data);\n                }\n                descendantNode = descendantNode.parentNode;\n            }\n\n            if (isSplitPoint(descendantNode, descendantOffset)) {\n                // descendantNode is now guaranteed not to be a text or other character node\n                newNode = descendantNode.cloneNode(false);\n                parentNode = descendantNode.parentNode;\n                if (newNode.id) {\n                    newNode.removeAttribute(\"id\");\n                }\n                var child, newChildIndex = 0;\n\n                while ( (child = descendantNode.childNodes[descendantOffset]) ) {\n                    movePreservingPositions(child, newNode, newChildIndex++, positionsToPreserve);\n                }\n                movePreservingPositions(newNode, parentNode, dom.getNodeIndex(descendantNode) + 1, positionsToPreserve);\n                return (descendantNode == node) ? newNode : splitNodeAt(node, parentNode, dom.getNodeIndex(newNode), positionsToPreserve);\n            } else if (node != descendantNode) {\n                newNode = descendantNode.parentNode;\n\n                // Work out a new split point in the parent node\n                var newNodeIndex = dom.getNodeIndex(descendantNode);\n\n                if (!splitAtStart) {\n                    newNodeIndex++;\n                }\n                return splitNodeAt(node, newNode, newNodeIndex, positionsToPreserve);\n            }\n            return node;\n        }\n\n        function areElementsMergeable(el1, el2) {\n            return el1.namespaceURI == el2.namespaceURI &&\n                el1.tagName.toLowerCase() == el2.tagName.toLowerCase() &&\n                haveSameClasses(el1, el2) &&\n                elementsHaveSameNonClassAttributes(el1, el2) &&\n                getComputedStyleProperty(el1, \"display\") == \"inline\" &&\n                getComputedStyleProperty(el2, \"display\") == \"inline\";\n        }\n\n        function createAdjacentMergeableTextNodeGetter(forward) {\n            var siblingPropName = forward ? \"nextSibling\" : \"previousSibling\";\n\n            return function(textNode, checkParentElement) {\n                var el = textNode.parentNode;\n                var adjacentNode = textNode[siblingPropName];\n                if (adjacentNode) {\n                    // Can merge if the node's previous/next sibling is a text node\n                    if (adjacentNode && adjacentNode.nodeType == 3) {\n                        return adjacentNode;\n                    }\n                } else if (checkParentElement) {\n                    // Compare text node parent element with its sibling\n                    adjacentNode = el[siblingPropName];\n                    if (adjacentNode && adjacentNode.nodeType == 1 && areElementsMergeable(el, adjacentNode)) {\n                        var adjacentNodeChild = adjacentNode[forward ? \"firstChild\" : \"lastChild\"];\n                        if (adjacentNodeChild && adjacentNodeChild.nodeType == 3) {\n                            return adjacentNodeChild;\n                        }\n                    }\n                }\n                return null;\n            };\n        }\n\n        var getPreviousMergeableTextNode = createAdjacentMergeableTextNodeGetter(false),\n            getNextMergeableTextNode = createAdjacentMergeableTextNodeGetter(true);\n\n    \n        function Merge(firstNode) {\n            this.isElementMerge = (firstNode.nodeType == 1);\n            this.textNodes = [];\n            var firstTextNode = this.isElementMerge ? firstNode.lastChild : firstNode;\n            if (firstTextNode) {\n                this.textNodes[0] = firstTextNode;\n            }\n        }\n\n        Merge.prototype = {\n            doMerge: function(positionsToPreserve) {\n                var textNodes = this.textNodes;\n                var firstTextNode = textNodes[0];\n                if (textNodes.length > 1) {\n                    var firstTextNodeIndex = dom.getNodeIndex(firstTextNode);\n                    var textParts = [], combinedTextLength = 0, textNode, parent;\n                    forEach(textNodes, function(textNode, i) {\n                        parent = textNode.parentNode;\n                        if (i > 0) {\n                            parent.removeChild(textNode);\n                            if (!parent.hasChildNodes()) {\n                                dom.removeNode(parent);\n                            }\n                            if (positionsToPreserve) {\n                                forEach(positionsToPreserve, function(position) {\n                                    // Handle case where position is inside the text node being merged into a preceding node\n                                    if (position.node == textNode) {\n                                        position.node = firstTextNode;\n                                        position.offset += combinedTextLength;\n                                    }\n                                    // Handle case where both text nodes precede the position within the same parent node\n                                    if (position.node == parent && position.offset > firstTextNodeIndex) {\n                                        --position.offset;\n                                        if (position.offset == firstTextNodeIndex + 1 && i < textNodes.length - 1) {\n                                            position.node = firstTextNode;\n                                            position.offset = combinedTextLength;\n                                        }\n                                    }\n                                });\n                            }\n                        }\n                        textParts[i] = textNode.data;\n                        combinedTextLength += textNode.data.length;\n                    });\n                    firstTextNode.data = textParts.join(\"\");\n                }\n                return firstTextNode.data;\n            },\n\n            getLength: function() {\n                var i = this.textNodes.length, len = 0;\n                while (i--) {\n                    len += this.textNodes[i].length;\n                }\n                return len;\n            },\n\n            toString: function() {\n                var textParts = [];\n                forEach(this.textNodes, function(textNode, i) {\n                    textParts[i] = \"'\" + textNode.data + \"'\";\n                });\n                return \"[Merge(\" + textParts.join(\",\") + \")]\";\n            }\n        };\n\n        var optionProperties = [\"elementTagName\", \"ignoreWhiteSpace\", \"applyToEditableOnly\", \"useExistingElements\",\n            \"removeEmptyElements\", \"onElementCreate\"];\n\n        // TODO: Populate this with every attribute name that corresponds to a property with a different name. Really??\n        var attrNamesForProperties = {};\n\n        function ClassApplier(className, options, tagNames) {\n            var normalize, i, len, propName, applier = this;\n            applier.cssClass = applier.className = className; // cssClass property is for backward compatibility\n\n            var elementPropertiesFromOptions = null, elementAttributes = {};\n\n            // Initialize from options object\n            if (typeof options == \"object\" && options !== null) {\n                if (typeof options.elementTagName !== \"undefined\") {\n                    options.elementTagName = options.elementTagName.toLowerCase();\n                }\n                tagNames = options.tagNames;\n                elementPropertiesFromOptions = options.elementProperties;\n                elementAttributes = options.elementAttributes;\n\n                for (i = 0; propName = optionProperties[i++]; ) {\n                    if (options.hasOwnProperty(propName)) {\n                        applier[propName] = options[propName];\n                    }\n                }\n                normalize = options.normalize;\n            } else {\n                normalize = options;\n            }\n\n            // Backward compatibility: the second parameter can also be a Boolean indicating to normalize after unapplying\n            applier.normalize = (typeof normalize == \"undefined\") ? true : normalize;\n\n            // Initialize element properties and attribute exceptions\n            applier.attrExceptions = [];\n            var el = document.createElement(applier.elementTagName);\n            applier.elementProperties = applier.copyPropertiesToElement(elementPropertiesFromOptions, el, true);\n            each(elementAttributes, function(attrName, attrValue) {\n                applier.attrExceptions.push(attrName);\n                // Ensure each attribute value is a string\n                elementAttributes[attrName] = \"\" + attrValue;\n            });\n            applier.elementAttributes = elementAttributes;\n\n            applier.elementSortedClassName = applier.elementProperties.hasOwnProperty(\"className\") ?\n                sortClassName(applier.elementProperties.className + \" \" + className) : className;\n\n            // Initialize tag names\n            applier.applyToAnyTagName = false;\n            var type = typeof tagNames;\n            if (type == \"string\") {\n                if (tagNames == \"*\") {\n                    applier.applyToAnyTagName = true;\n                } else {\n                    applier.tagNames = trim(tagNames.toLowerCase()).split(/\\s*,\\s*/);\n                }\n            } else if (type == \"object\" && typeof tagNames.length == \"number\") {\n                applier.tagNames = [];\n                for (i = 0, len = tagNames.length; i < len; ++i) {\n                    if (tagNames[i] == \"*\") {\n                        applier.applyToAnyTagName = true;\n                    } else {\n                        applier.tagNames.push(tagNames[i].toLowerCase());\n                    }\n                }\n            } else {\n                applier.tagNames = [applier.elementTagName];\n            }\n        }\n\n        ClassApplier.prototype = {\n            elementTagName: defaultTagName,\n            elementProperties: {},\n            elementAttributes: {},\n            ignoreWhiteSpace: true,\n            applyToEditableOnly: false,\n            useExistingElements: true,\n            removeEmptyElements: true,\n            onElementCreate: null,\n\n            copyPropertiesToElement: function(props, el, createCopy) {\n                var s, elStyle, elProps = {}, elPropsStyle, propValue, elPropValue, attrName;\n\n                for (var p in props) {\n                    if (props.hasOwnProperty(p)) {\n                        propValue = props[p];\n                        elPropValue = el[p];\n\n                        // Special case for class. The copied properties object has the applier's class as well as its own\n                        // to simplify checks when removing styling elements\n                        if (p == \"className\") {\n                            addClass(el, propValue);\n                            addClass(el, this.className);\n                            el[p] = sortClassName(el[p]);\n                            if (createCopy) {\n                                elProps[p] = propValue;\n                            }\n                        }\n\n                        // Special case for style\n                        else if (p == \"style\") {\n                            elStyle = elPropValue;\n                            if (createCopy) {\n                                elProps[p] = elPropsStyle = {};\n                            }\n                            for (s in props[p]) {\n                                if (props[p].hasOwnProperty(s)) {\n                                    elStyle[s] = propValue[s];\n                                    if (createCopy) {\n                                        elPropsStyle[s] = elStyle[s];\n                                    }\n                                }\n                            }\n                            this.attrExceptions.push(p);\n                        } else {\n                            el[p] = propValue;\n                            // Copy the property back from the dummy element so that later comparisons to check whether\n                            // elements may be removed are checking against the right value. For example, the href property\n                            // of an element returns a fully qualified URL even if it was previously assigned a relative\n                            // URL.\n                            if (createCopy) {\n                                elProps[p] = el[p];\n\n                                // Not all properties map to identically-named attributes\n                                attrName = attrNamesForProperties.hasOwnProperty(p) ? attrNamesForProperties[p] : p;\n                                this.attrExceptions.push(attrName);\n                            }\n                        }\n                    }\n                }\n\n                return createCopy ? elProps : \"\";\n            },\n\n            copyAttributesToElement: function(attrs, el) {\n                for (var attrName in attrs) {\n                    if (attrs.hasOwnProperty(attrName) && !/^class(?:Name)?$/i.test(attrName)) {\n                        el.setAttribute(attrName, attrs[attrName]);\n                    }\n                }\n            },\n\n            appliesToElement: function(el) {\n                return contains(this.tagNames, el.tagName.toLowerCase());\n            },\n\n            getEmptyElements: function(range) {\n                var applier = this;\n                return range.getNodes([1], function(el) {\n                    return applier.appliesToElement(el) && !el.hasChildNodes();\n                });\n            },\n\n            hasClass: function(node) {\n                return node.nodeType == 1 &&\n                    (this.applyToAnyTagName || this.appliesToElement(node)) &&\n                    hasClass(node, this.className);\n            },\n\n            getSelfOrAncestorWithClass: function(node) {\n                while (node) {\n                    if (this.hasClass(node)) {\n                        return node;\n                    }\n                    node = node.parentNode;\n                }\n                return null;\n            },\n\n            isModifiable: function(node) {\n                return !this.applyToEditableOnly || isEditable(node);\n            },\n\n            // White space adjacent to an unwrappable node can be ignored for wrapping\n            isIgnorableWhiteSpaceNode: function(node) {\n                return this.ignoreWhiteSpace && node && node.nodeType == 3 && isUnrenderedWhiteSpaceNode(node);\n            },\n\n            // Normalizes nodes after applying a class to a Range.\n            postApply: function(textNodes, range, positionsToPreserve, isUndo) {\n                var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1];\n                var merges = [], currentMerge;\n                var rangeStartNode = firstNode, rangeEndNode = lastNode;\n                var rangeStartOffset = 0, rangeEndOffset = lastNode.length;\n                var precedingTextNode;\n\n                // Check for every required merge and create a Merge object for each\n                forEach(textNodes, function(textNode) {\n                    precedingTextNode = getPreviousMergeableTextNode(textNode, !isUndo);\n                    if (precedingTextNode) {\n                        if (!currentMerge) {\n                            currentMerge = new Merge(precedingTextNode);\n                            merges.push(currentMerge);\n                        }\n                        currentMerge.textNodes.push(textNode);\n                        if (textNode === firstNode) {\n                            rangeStartNode = currentMerge.textNodes[0];\n                            rangeStartOffset = rangeStartNode.length;\n                        }\n                        if (textNode === lastNode) {\n                            rangeEndNode = currentMerge.textNodes[0];\n                            rangeEndOffset = currentMerge.getLength();\n                        }\n                    } else {\n                        currentMerge = null;\n                    }\n                });\n\n                // Test whether the first node after the range needs merging\n                var nextTextNode = getNextMergeableTextNode(lastNode, !isUndo);\n\n                if (nextTextNode) {\n                    if (!currentMerge) {\n                        currentMerge = new Merge(lastNode);\n                        merges.push(currentMerge);\n                    }\n                    currentMerge.textNodes.push(nextTextNode);\n                }\n\n                // Apply the merges\n                if (merges.length) {\n                    for (var i = 0, len = merges.length; i < len; ++i) {\n                        merges[i].doMerge(positionsToPreserve);\n                    }\n\n                    // Set the range boundaries\n                    range.setStartAndEnd(rangeStartNode, rangeStartOffset, rangeEndNode, rangeEndOffset);\n                }\n            },\n\n            createContainer: function(parentNode) {\n                var doc = dom.getDocument(parentNode);\n                var namespace;\n                var el = createElementNSSupported && !dom.isHtmlNamespace(parentNode) && (namespace = parentNode.namespaceURI) ?\n                    doc.createElementNS(parentNode.namespaceURI, this.elementTagName) :\n                    doc.createElement(this.elementTagName);\n\n                this.copyPropertiesToElement(this.elementProperties, el, false);\n                this.copyAttributesToElement(this.elementAttributes, el);\n                addClass(el, this.className);\n                if (this.onElementCreate) {\n                    this.onElementCreate(el, this);\n                }\n                return el;\n            },\n\n            elementHasProperties: function(el, props) {\n                var applier = this;\n                return each(props, function(p, propValue) {\n                    if (p == \"className\") {\n                        // For checking whether we should reuse an existing element, we just want to check that the element\n                        // has all the classes specified in the className property. When deciding whether the element is\n                        // removable when unapplying a class, there is separate special handling to check whether the\n                        // element has extra classes so the same simple check will do.\n                        return hasAllClasses(el, propValue);\n                    } else if (typeof propValue == \"object\") {\n                        if (!applier.elementHasProperties(el[p], propValue)) {\n                            return false;\n                        }\n                    } else if (el[p] !== propValue) {\n                        return false;\n                    }\n                });\n            },\n\n            elementHasAttributes: function(el, attrs) {\n                return each(attrs, function(name, value) {\n                    if (el.getAttribute(name) !== value) {\n                        return false;\n                    }\n                });\n            },\n\n            applyToTextNode: function(textNode, positionsToPreserve) {\n\n                // Check whether the text node can be styled. Text within a