選択範囲に似ているリンクを入力補完するUserScript
code:script.js
var le,g,et,Mr,W,tt,Ye,Rr,ie={},rt=[],Cr=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|inech|zoo|^ord|itera/i;function A(e,t){for(var r in t)er=tr;return e}function nt(e){var t=e.parentNode;t&&t.removeChild(e)}function x(e,t,r){var n,s,o,c={};for(o in t)o=="key"?n=to:o=="ref"?s=to:co=to;if(arguments.length>2&&(c.children=arguments.length>3?le.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(o in e.defaultProps)co===void 0&&(co=e.defaultPropso);return oe(e,c,n,s,null)}function oe(e,t,r,n,s){var o={type:e,props:t,key:r,ref:n,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:s??++et};return s==null&&g.vnode!=null&&g.vnode(o),o}function N(e){return e.children}function se(e,t){this.props=e,this.context=t}function K(e,t){if(t==null)return e.__?K(e.__,e.__.__k.indexOf(e)+1):null;for(var r;t<e.__k.length;t++)if((r=e.__kt)!=null&&r.__e!=null)return r.__e;return typeof e.type=="function"?K(e):null}function ot(e){var t,r;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((r=e.__kt)!=null&&r.__e!=null){e.__e=e.__c.base=r.__e;break}return ot(e)}}function Je(e){(!e.__d&&(e.__d=!0)&&W.push(e)&&!ae.__r++||Ye!==g.debounceRendering)&&((Ye=g.debounceRendering)||tt)(ae)}function ae(){for(var e;ae.__r=W.length;)e=W.sort(function(t,r){return t.__v.__b-r.__v.__b}),W=[],e.some(function(t){var r,n,s,o,c,l;t.__d&&(c=(o=(r=t).__v).__e,(l=r.__P)&&(n=[],(s=A({},o)).__v=o.__v+1,Le(l,o,s,r.__n,l.ownerSVGElement!==void 0,o.__h!=null?c:null,n,c??K(o),o.__h),ct(n,o),o.__e!=c&&ot(o)))})}function st(e,t,r,n,s,o,c,l,a,u){var i,m,p,d,f,M,h,b=n&&n.__k||rt,_=b.length;for(r.__k=[],i=0;i<t.length;i++)if((d=r.__ki=(d=ti)==null||typeof d=="boolean"?null:typeof d=="string"||typeof d=="number"||typeof d=="bigint"?oe(null,d,null,null,d):Array.isArray(d)?oe(N,{children:d},null,null,null):d.__b>0?oe(d.type,d.props,d.key,null,d.__v):d)!=null){if(d.__=r,d.__b=r.__b+1,(p=bi)===null||p&&d.key==p.key&&d.type===p.type)bi=void 0;else for(m=0;m<_;m++){if((p=bm)&&d.key==p.key&&d.type===p.type){bm=void 0;break}p=null}Le(e,d,p=p||ie,s,o,c,l,a,u),f=d.__e,(m=d.ref)&&p.ref!=m&&(h||(h=[]),p.ref&&h.push(p.ref,null,d),h.push(m,d.__c||f,d)),f!=null?(M==null&&(M=f),typeof d.type=="function"&&d.__k===p.__k?d.__d=a=it(d,a,e):a=at(e,d,p,b,f,a),typeof r.type=="function"&&(r.__d=a)):a&&p.__e==a&&a.parentNode!=e&&(a=K(p))}for(r.__e=M,i=_;i--;)bi!=null&&(typeof r.type=="function"&&bi.__e!=null&&bi.__e==r.__d&&(r.__d=K(n,i+1)),ut(bi,bi));if(h)for(i=0;i<h.length;i++)lt(hi,h++i,h++i)}function it(e,t,r){for(var n,s=e.__k,o=0;s&&o<s.length;o++)(n=so)&&(n.__=e,t=typeof n.type=="function"?it(n,t,r):at(r,n,n,s,n.__e,t));return t}function at(e,t,r,n,s,o){var c,l,a;if(t.__d!==void 0)c=t.__d,t.__d=void 0;else if(r==null||s!=o||s.parentNode==null)e:if(o==null||o.parentNode!==e)e.appendChild(s),c=null;else{for(l=o,a=0;(l=l.nextSibling)&&a<n.length;a+=2)if(l==s)break e;e.insertBefore(s,o),c=o}return c!==void 0?c:s.nextSibling}function Nr(e,t,r,n,s){var o;for(o in r)o==="children"||o==="key"||o in t||ce(e,o,null,ro,n);for(o in t)s&&typeof to!="function"||o==="children"||o==="key"||o==="value"||o==="checked"||ro===to||ce(e,o,to,ro,n)}function ze(e,t,r){t0==="-"?e.setProperty(t,r):et=r==null?"":typeof r!="number"||Cr.test(t)?r:r+"px"}function ce(e,t,r,n,s){var o;e:if(t==="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof n=="string"&&(e.style.cssText=n=""),n)for(t in n)r&&t in r||ze(e.style,t,"");if(r)for(t in r)n&&rt===nt||ze(e.style,t,rt)}else if(t0==="o"&&t1==="n")o=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.lt+o=r,r?n||e.addEventListener(t,o?Ze:Qe,o):e.removeEventListener(t,o?Ze:Qe,o);else if(t!=="dangerouslySetInnerHTML"){if(s)t=t.replace(/xlinkH:h/,"h").replace(/sName$/,"s");else if(t!=="href"&&t!=="list"&&t!=="form"&&t!=="tabIndex"&&t!=="download"&&t in e)try{et=r??"";break e}catch{}typeof r=="function"||(r!=null&&(r!==!1||t0==="a"&&t1==="r")?e.setAttribute(t,r):e.removeAttribute(t))}}function Qe(e){this.le.type+!1(g.event?g.event(e):e)}function Ze(e){this.le.type+!0(g.event?g.event(e):e)}function Le(e,t,r,n,s,o,c,l,a){var u,i,m,p,d,f,M,h,b,_,S,v=t.type;if(t.constructor!==void 0)return null;r.__h!=null&&(a=r.__h,l=t.__e=r.__e,t.__h=null,o=l),(u=g.__b)&&u(t);try{e:if(typeof v=="function"){if(h=t.props,b=(u=v.contextType)&&nu.__c,_=u?b?b.props.value:u.__:n,r.__c?M=(i=t.__c=r.__c).__=i.__E:("prototype"in v&&v.prototype.render?t.__c=i=new v(h,_):(t.__c=i=new se(h,_),i.constructor=v,i.render=Dr),b&&b.sub(i),i.props=h,i.state||(i.state={}),i.context=_,i.__n=n,m=i.__d=!0,i.__h=[]),i.__s==null&&(i.__s=i.state),v.getDerivedStateFromProps!=null&&(i.__s==i.state&&(i.__s=A({},i.__s)),A(i.__s,v.getDerivedStateFromProps(h,i.__s))),p=i.props,d=i.state,m)v.getDerivedStateFromProps==null&&i.componentWillMount!=null&&i.componentWillMount(),i.componentDidMount!=null&&i.__h.push(i.componentDidMount);else{if(v.getDerivedStateFromProps==null&&h!==p&&i.componentWillReceiveProps!=null&&i.componentWillReceiveProps(h,_),!i.__e&&i.shouldComponentUpdate!=null&&i.shouldComponentUpdate(h,i.__s,_)===!1||t.__v===r.__v){i.props=h,i.state=i.__s,t.__v!==r.__v&&(i.__d=!1),i.__v=t,t.__e=r.__e,t.__k=r.__k,t.__k.forEach(function(B){B&&(B.__=t)}),i.__h.length&&c.push(i);break e}i.componentWillUpdate!=null&&i.componentWillUpdate(h,i.__s,_),i.componentDidUpdate!=null&&i.__h.push(function(){i.componentDidUpdate(p,d,f)})}i.context=_,i.props=h,i.state=i.__s,(u=g.__r)&&u(t),i.__d=!1,i.__v=t,i.__P=e,u=i.render(i.props,i.state,i.context),i.state=i.__s,i.getChildContext!=null&&(n=A(A({},n),i.getChildContext())),m||i.getSnapshotBeforeUpdate==null||(f=i.getSnapshotBeforeUpdate(p,d)),S=u!=null&&u.type===N&&u.key==null?u.props.children:u,st(e,Array.isArray(S)?S:S,t,r,n,s,o,c,l,a),i.base=t.__e,t.__h=null,i.__h.length&&c.push(i),M&&(i.__E=i.__=null),i.__e=!1}else o==null&&t.__v===r.__v?(t.__k=r.__k,t.__e=r.__e):t.__e=jr(r.__e,t,r,n,s,o,c,a);(u=g.diffed)&&u(t)}catch(B){t.__v=null,(a||o!=null)&&(t.__e=l,t.__h=!!a,oo.indexOf(l)=null),g.__e(B,t,r)}}function ct(e,t){g.__c&&g.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(n){n.call(r)})}catch(n){g.__e(n,r.__v)}})}function jr(e,t,r,n,s,o,c,l){var a,u,i,m=r.props,p=t.props,d=t.type,f=0;if(d==="svg"&&(s=!0),o!=null){for(;f<o.length;f++)if((a=of)&&"setAttribute"in a==!!d&&(d?a.localName===d:a.nodeType===3)){e=a,of=null;break}}if(e==null){if(d===null)return document.createTextNode(p);e=s?document.createElementNS("http://www.w3.org/2000/svg",d):document.createElement(d,p.is&&p),o=null,l=!1}if(d===null)m===p||l&&e.data===p||(e.data=p);else{if(o=o&&le.call(e.childNodes),u=(m=r.props||ie).dangerouslySetInnerHTML,i=p.dangerouslySetInnerHTML,!l){if(o!=null)for(m={},f=0;f<e.attributes.length;f++)m[e.attributes[f].name]=e.attributes[f].value;(i||u)&&(i&&(u&&i.__html==u.__html||i.__html===e.innerHTML)||(e.innerHTML=i&&i.__html||""))}if(Nr(e,p,m,s,l),i)t.__k=[];else if(f=t.props.children,st(e,Array.isArray(f)?f:f,t,r,n,s&&d!=="foreignObject",o,c,o?o0:r.__k&&K(r,0),l),o!=null)for(f=o.length;f--;)of!=null&&nt(of);l||("value"in p&&(f=p.value)!==void 0&&(f!==m.value||f!==e.value||d==="progress"&&!f)&&ce(e,"value",f,m.value,!1),"checked"in p&&(f=p.checked)!==void 0&&f!==e.checked&&ce(e,"checked",f,m.checked,!1))}return e}function lt(e,t,r){try{typeof e=="function"?e(t):e.current=t}catch(n){g.__e(n,r)}}function ut(e,t,r){var n,s;if(g.unmount&&g.unmount(e),(n=e.ref)&&(n.current&&n.current!==e.__e||lt(n,null,t)),(n=e.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){g.__e(o,t)}n.base=n.__P=null}if(n=e.__k)for(s=0;s<n.length;s++)ns&&ut(ns,t,typeof e.type!="function");r||e.__e==null||nt(e.__e),e.__e=e.__d=void 0}function Dr(e,t,r){return this.constructor(e,r)}function Pe(e,t,r){var n,s,o;g.__&&g.__(e,t),s=(n=typeof r=="function")?null:r&&r.__k||t.__k,o=[],Le(t,e=(!n&&r||t).__k=x(N,null,e),s||ie,ie,t.ownerSVGElement!==void 0,!n&&r?r:s?null:t.firstChild?le.call(t.childNodes):null,o,!n&&r?r:s?s.__e:t.firstChild,n),ct(o,e)}le=rt.slice,g={__e:function(e,t){for(var r,n,s;t=t.__;)if((r=t.__c)&&!r.__)try{if((n=r.constructor)&&n.getDerivedStateFromError!=null&&(r.setState(n.getDerivedStateFromError(e)),s=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(e),s=r.__d),s)return r.__E=r}catch(o){e=o}throw e}},et=0,Mr=function(e){return e!=null&&e.constructor===void 0},se.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=A({},this.state),typeof e=="function"&&(e=e(A({},r),this.props)),e&&A(r,e),e!=null&&this.__v&&(t&&this.__h.push(t),Je(this))},se.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Je(this))},se.prototype.render=N,W=[],tt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ae.__r=0,Rr=0;var de,D,dt,X=0,Se=[],pt=g.__b,mt=g.__r,ft=g.diffed,gt=g.__c,ht=g.unmount;function Ie(e,t){g.__h&&g.__h(D,e,X||t),X=0;var r=D.__H||(D.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__e}function C(e){return X=1,Me(bt,e)}function Me(e,t,r){var n=Ie(de++,2);return n.t=e,n.__c||(n.__=[r?r(t):bt(void 0,t),function(s){var o=n.t(n.__0,s);n.__0!==o&&(n.__=[o,n.__1],n.__c.setState({}))}],n.__c=D),n.__}function k(e,t){var r=Ie(de++,3);!g.__s&&_t(r.__H,t)&&(r.__=e,r.__H=t,D.__H.__h.push(r))}function pe(e){return X=5,j(function(){return{current:e}},[])}function j(e,t){var r=Ie(de++,7);return _t(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function T(e,t){return X=8,j(function(){return e},t)}function Or(){var e;for(Se.sort(function(t,r){return t.__v.__b-r.__v.__b});e=Se.pop();)if(e.__P)try{e.__H.__h.forEach(ue),e.__H.__h.forEach(Te),e.__H.__h=[]}catch(t){e.__H.__h=[],g.__e(t,e.__v)}}g.__b=function(e){D=null,pt&&pt(e)},g.__r=function(e){mt&&mt(e),de=0;var t=(D=e.__c).__H;t&&(t.__h.forEach(ue),t.__h.forEach(Te),t.__h=[])},g.diffed=function(e){ft&&ft(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(Se.push(t)!==1&&dt===g.requestAnimationFrame||((dt=g.requestAnimationFrame)||function(r){var n,s=function(){clearTimeout(o),xt&&cancelAnimationFrame(n),setTimeout(r)},o=setTimeout(s,100);xt&&(n=requestAnimationFrame(s))})(Or)),D=null},g.__c=function(e,t){t.some(function(r){try{r.__h.forEach(ue),r.__h=r.__h.filter(function(n){return!n.__||Te(n)})}catch(n){t.some(function(s){s.__h&&(s.__h=[])}),t=[],g.__e(n,r.__v)}}),gt&>(e,t)},g.unmount=function(e){ht&&ht(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{ue(n)}catch(s){t=s}}),t&&g.__e(t,r.__v))};var xt=typeof requestAnimationFrame=="function";function ue(e){var t=D,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),D=t}function Te(e){var t=D;e.__c=e.__(),D=t}function _t(e,t){return!e||e.length!==t.length||t.some(function(r,n){return r!==en})}function bt(e,t){return typeof t=="function"?t(e):t}var Y=e=>e==null,me=e=>typeof e=="string",fe=e=>typeof e=="number";var Br=e=>typeof e=="object"&&e!==null,Hr=e=>Br(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,yt=e=>{try{let t=typeof e=="string"?JSON.parse(e):e;return Hr(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};var Et=(e,t)=>{if(!Array.isArray(e))throw new TypeError("${t}" must be an array but actual is "${e}")};var vt=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var F=()=>{let e=document.getElementById("text-input");if(e)return vt(e,"textarea#text-input"),e};var kt=e=>{if(Y(e))return;if(fe(e))return $r(e)?.id;if(me(e))return e.startsWith("L")?e.slice(1):e;if(e.classList.contains("line"))return e.id.slice(1);let t=e.closest(".line");if(t)return t.id.slice(1)};var $r=e=>{if(Y(e))return;if(fe(e))return wt()e;let t=kt(e);return t?wt().find(r=>r.id===t):void 0},Re=e=>{if(Ar(e))return e;let t=kt(e);if(Y(t))return t;let r=document.getElementById(L${t});if(!Y(r))return r},Ar=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var wt=()=>(Et(scrapbox.Page.lines,"scrapbox.Page.lines"),scrapbox.Page.lines);var Ur=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index");var J=(e,t)=>{let r=Re(e)?.getElementsByClassName?.(c-${t})?.0;return Ur(r)?r:void 0};var G=(e,t)=>{let{noModifiedKeys:r=!1,...n}=t??{},s={bubbles:!0,cancelable:!0,keyCode:qre,...r?{}:{...n}},o=F();if(!o)throw Error("#text-input must exist.");o.dispatchEvent(new KeyboardEvent("keydown",s)),o.dispatchEvent(new KeyboardEvent("keyup",s))},qr={Backspace:8,Tab:9,Enter:13,Delete:46,Escape:27," ":32,PageUp:33,PageDown:34,End:35,Home:36,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,a:65,A:65,b:66,B:66,c:67,C:67,d:68,D:68,e:69,E:69,f:70,F:70,g:71,G:71,h:72,H:72,i:73,I:73,j:74,J:74,k:75,K:75,l:76,L:76,m:77,M:77,n:78,N:78,o:79,O:79,p:80,P:80,q:81,Q:81,r:82,R:82,s:83,S:83,t:84,T:84,u:85,U:85,v:86,V:86,w:87,W:87,x:88,X:88,y:89,Y:89,z:90,Z:90,0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,F1:113,F2:114,F3:115,F4:116,F5:117,F6:118,F7:119,F8:120,F9:121,F10:122,F11:123,F12:124,":":186,"*":186,";":187,"+":187,"-":189,"=":189,".":190,">":190,"/":191,"?":191,"@":192,"":192,"[":219,"{":219,"\\":220,"|":220,"]":221,"}":221,"^":222,"~":222,_:226};var ge=e=>new Promise(t=>setTimeout(()=>t(),e));var Lt=async(e,t)=>{let r={button:t.button??0,clientX:t.X,clientY:t.Y,bubbles:!0,cancelable:!0,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,view:window};e.dispatchEvent(new MouseEvent("mousedown",r)),e.dispatchEvent(new MouseEvent("mouseup",r)),e.dispatchEvent(new MouseEvent("click",r)),await ge(10)};var Pt=e=>{let{top:t,bottom:r}=e.getBoundingClientRect();return t>=0&&r<=window.innerHeight};function*Ce(e,t){for(let r=e;r<t;r++)yield r}var St=()=>{G("Home"),G("Home")};var Tt=async e=>{await Gr(Re(e))},Gr=async e=>{if(!e)throw Error("The target line DOM is failed to find.");Pt(e)||e.scrollIntoView({block:"center"});let{right:t,top:r,height:n}=e.getElementsByClassName("text")[0].getBoundingClientRect();await Lt(e,{X:t+1,Y:r+n/2})};var It=async(e,t,r)=>{await Tt(e),St();for(let n of Ce(e,t))G("ArrowDown",{shiftKey:!0});G("End",{shiftKey:!0}),await Ne(r)};var Ne=async e=>{let t=F();if(!t)throw Error("#text-input is not ditected.");t.focus(),t.value=e;let r=new InputEvent("input",{bubbles:!0});t.dispatchEvent(r),await ge(1)};var z=e=>e.replaceAll(" ","_").toLowerCase(),Mt=e=>e.replaceAll("_"," "),$=e=>[...e].map((t,r)=>t===" "?"_":!Vr.includes(t)||r===e.length-1&&Wr.includes(t)?encodeURIComponent(t):t).join(""),Vr='@$&+=:;",',Wr=':;",';var he=()=>{let e=F();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(o=>o.startsWith("__reactFiber"));if(!t)throw Error('#text-input must has the property whose name starts with "__reactFiber"');let r=e[t].return.return.stateNode._stores,n=r.find(o=>o.constructor.name==="Cursor");if(!n)throw Error('#text-input must has a "Cursor" store.');let s=r.find(o=>o.constructor.name==="Selection");if(!s)throw Error('#text-input must has a "Selection" store.');return{cursor:n,selection:s}};var Q=()=>he().cursor;var Rt=()=>he().selection;var Ct=()=>{let[e,t]=C({start:{line:0,char:0},end:{line:0,char:0}}),[r,n]=C("");return k(()=>{let s=Rt(),o=()=>{t(s.getRange()),n(s.getSelectedText())};return s.addChangeListener(o),()=>s.removeChangeListener(o)},[]),{text:r,range:e}};var Nt=({title:e,projects:t,selected:r,confirm:n})=>x("div",{className:candidate${r?" selected":""}},x(Xr,{title:e,confirm:n}),t.map(s=>x(Yr,{project:s.name,title:e,mark:s.mark,confirm:s.confirm}))),Xr=({title:e,confirm:t})=>x("a",{className:"button",tabIndex:0,role:"menuitem",href:./${$(e)},onClick:jt(t)},e),Yr=({project:e,title:t,mark:r,confirm:n})=>r===""?x(N,null):x("a",{className:"mark",tabIndex:0,href:../${e}/${$(t)},onClick:jt(n),title:/${e}/${$(t)}},r instanceof URL?x("img",{src:r.href}):${r}),jt=e=>T(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var Dt=e=>{let[t,r]=C(-1);k(()=>r(-1),[e]);let n=T(l=>r(a=>l?.cyclic?(a+1)%e:Math.min(a+1,e)),[e]),s=T(l=>r(a=>a<0?e-1:l?.cyclic?(a+e-1)%e:Math.max(a-1,0)),[e]),o=T(()=>r(0),[]),c=T(()=>r(e-1),[e]);return{selectedIndex:t,next:n,prev:s,selectFirst:o,selectLast:c}};var xe=(e,t)=>t.some(r=>e instanceof r),Ot,Bt;function Jr(){return Ot||(Ot=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function zr(){return Bt||(Bt=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Ht=new WeakMap,De=new WeakMap,Ft=new WeakMap,je=new WeakMap,Z=new WeakMap;function Qr(e){let t=new Promise((r,n)=>{let s=()=>{e.removeEventListener("success",o),e.removeEventListener("error",c)},o=()=>{r(O(e.result)),s()},c=()=>{n(e.error),s()};e.addEventListener("success",o),e.addEventListener("error",c)});return t.then(r=>{r instanceof IDBCursor&&Ht.set(r,e)}).catch(()=>{}),Z.set(t,e),t}function Zr(e){if(De.has(e))return;let t=new Promise((r,n)=>{let s=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",c),e.removeEventListener("abort",c)},o=()=>{r(),s()},c=()=>{n(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",o),e.addEventListener("error",c),e.addEventListener("abort",c)});De.set(e,t)}var Oe={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return De.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Ft.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return O(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function V(e){Oe=e(Oe)}function en(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(U(this),t,...r);return Ft.set(n,t.sort?t.sort():[t]),O(n)}:zr().includes(e)?function(...t){return e.apply(U(this),t),O(Ht.get(this))}:function(...t){return O(e.apply(U(this),t))}}function tn(e){return typeof e=="function"?en(e):(e instanceof IDBTransaction&&Zr(e),xe(e,Jr())?new Proxy(e,Oe):e)}function O(e){if(e instanceof IDBRequest)return Qr(e);if(je.has(e))return je.get(e);let t=tn(e);return t!==e&&(je.set(e,t),Z.set(t,e)),t}var U=e=>Z.get(e);var rn=["get","getKey","getAll","getAllKeys","count"],nn=["put","add","delete","clear"],Be=new Map;function $t(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Be.get(t))return Be.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,s=nn.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(s||rn.includes(r)))return;let o=async function(c,...l){let a=this.transaction(c,s?"readwrite":"readonly"),u=a.store;return n&&(u=u.index(l.shift())),(await Promise.all([u[r](...l),s&&a.done]))[0]};return Be.set(t,o),o}V(e=>({...e,get:(t,r,n)=>$t(t,r)||e.get(t,r,n),has:(t,r)=>!!$t(t,r)||e.has(t,r)}));var on=["continue","continuePrimaryKey","advance"],At={},He=new WeakMap,qt=new WeakMap,sn={get(e,t){if(!on.includes(t))return e[t];let r=At[t];return r||(r=At[t]=function(...n){He.set(this,qt.get(this)[t](...n))}),r}};async function*an(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,sn);for(qt.set(r,t),Z.set(r,U(t));t;)yield r,t=await(He.get(r)||t.continue()),He.delete(r)}function Ut(e,t){return t===Symbol.asyncIterator&&xe(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&xe(e,[IDBIndex,IDBObjectStore])}V(e=>({...e,get(t,r,n){return Ut(t,r)?an:e.get(t,r,n)},has(t,r){return Ut(t,r)||e.has(t,r)}}));function Gt(e,t,{blocked:r,upgrade:n,blocking:s,terminated:o}={}){let c=indexedDB.open(e,t),l=O(c);return n&&c.addEventListener("upgradeneeded",a=>{n(O(c.result),a.oldVersion,a.newVersion,O(c.transaction),a)}),r&&c.addEventListener("blocked",a=>r(a.oldVersion,a.newVersion,a)),l.then(a=>{o&&a.addEventListener("close",()=>o()),s&&a.addEventListener("versionchange",u=>s(u.oldVersion,u.newVersion,u))}).catch(()=>{}),l}var cn=["get","getKey","getAll","getAllKeys","count"],ln=["put","add","delete","clear"],Fe=new Map;function Kt(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Fe.get(t))return Fe.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,s=ln.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(s||cn.includes(r)))return;let o=async function(c,...l){let a=this.transaction(c,s?"readwrite":"readonly"),u=a.store;return n&&(u=u.index(l.shift())),(await Promise.all([u[r](...l),s&&a.done]))[0]};return Fe.set(t,o),o}V(e=>({...e,get:(t,r,n)=>Kt(t,r)||e.get(t,r,n),has:(t,r)=>!!Kt(t,r)||e.has(t,r)}));var E=e=>{let{fetch:t=globalThis.fetch,hostName:r="scrapbox.io",...n}=e;return{fetch:t,hostName:r,...n}};var _e=class e extends Error{constructor(r){super(${r.status} ${r.statusText} when fetching ${r.url});this.response=r;Error.captureStackTrace&&Error.captureStackTrace(this,e)}name="UnexpectedResponseError"},I=async e=>{let t=e.clone(),r=await t.text(),n=yt(r);if(!n)throw new _e(t);return{ok:!1,value:n}};var L=e=>connect.sid=${e};var Vt=(e,t,r)=>{let{sid:n,hostName:s,followRename:o,projects:c}=E(r??{}),l=new URLSearchParams;l.append("followRename",${o??!0});for(let u of c??[])l.append("projects",u);let a=https://${s}/api/pages/${e}/${$(t)}?${l.toString()};return new Request(a,n?{headers:{Cookie:L(n)}}:void 0)},Wt=async e=>e.ok?{ok:!0,value:await e.json()}:e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:I(e),Xt=async(e,t,r)=>{let{fetch:n}=E(r??{}),s=Vt(e,t,r),o=await n(s);return await Wt(o)};Xt.toRequest=Vt;Xt.fromResponse=Wt;var Yt=(e,t)=>{let{sid:r,hostName:n,sort:s,limit:o,skip:c}=E(t??{}),l=new URLSearchParams;s!==void 0&&l.append("sort",s),o!==void 0&&l.append("limit",${o}),c!==void 0&&l.append("skip",${c});let a=https://${n}/api/pages/${e}?${l.toString()};return new Request(a,r?{headers:{Cookie:L(r)}}:void 0)},Jt=async e=>e.ok?{ok:!0,value:await e.json()}:I(e),zt=async(e,t)=>{let{fetch:r}=E(t??{}),n=await r(Yt(e,t));return await Jt(n)};zt.toRequest=Yt;zt.fromResponse=Jt;var Qt=(e,t,r,n)=>{let{sid:s,hostName:o}=E(n??{}),c=https://${o}/api/table/${e}/${$(t)}/${encodeURIComponent(r)}.csv;return new Request(c,s?{headers:{Cookie:L(s)}}:void 0)},Zt=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:I(e),er=async(e,t,r,n)=>{let{fetch:s}=E(n??{}),o=Qt(e,t,r,n),c=await s(o);return await Zt(c)};er.toRequest=Qt;er.fromResponse=Zt;var tr=(e,t)=>{let{sid:r,hostName:n}=E(t??{});return new Request(https://${n}/api/projects/${e},r?{headers:{Cookie:L(r)}}:void 0)},rr=async e=>e.ok?{ok:!0,value:await e.json()}:I(e),ee=async(e,t)=>{let{fetch:r}=E(t??{}),n=tr(e,t),s=await r(n);return rr(s)};ee.toRequest=tr;ee.fromResponse=rr;var nr=(e,t)=>{let{sid:r,hostName:n}=E(t??{}),s=new URLSearchParams;for(let o of e)s.append("ids",o);return new Request(https://${n}/api/projects?${s.toString()},r?{headers:{Cookie:L(r)}}:void 0)},or=async e=>e.ok?{ok:!0,value:await e.json()}:I(e),te=async(e,t)=>{let{fetch:r}=E(t??{}),n=await r(nr(e,t));return or(n)};te.toRequest=nr;te.fromResponse=or;var sr=async(e,t)=>{let{sid:r,hostName:n,fetch:s,followingId:o}=E(t??{}),c=new Request(https://${n}/api/pages/${e}/search/titles${o??followingId=${o}:""},r?{headers:{Cookie:L(r)}}:void 0),l=await s(c);return l.ok?{ok:!0,value:{pages:await l.json(),followingId:l.headers.get("X-following-id")??""}}:l.status===422?{ok:!1,value:{name:"InvalidFollowingIdError",message:await l.text()}}:I(l)},Ae=async(e,t)=>{let r=await sr(e,t);return r.ok?async function*(){yield r.value.pages;let n=r.value.followingId;for(;n;){let s=await sr(e,{followingId:n,...t});if(!s.ok)throw new Error("The authorization cannot be unavailable");yield s.value.pages,n=s.value.followingId}}():r.value};var ir=!1,ar=e=>{ir=e},un="[scrapbox-select-suggestion]",P=Object.fromEntries([...Object.entries(console)].map(([e,t])=>typeof t!="function"?[e,t]:[e,(r,...n)=>{ir&&t(typeof r=="string"?${un} ${r}:r,...n)}]));var cr=async(e,t)=>{let r=await Ue(),n="[scrapbox-select-suggestion]";P.debug("check updates of links...");let s=[],o=[];try{{let a=r.transaction("status","readwrite");await Promise.all(e.map(async u=>{let i=await a.store.get(u);if(i?.isValid===!1)return;let m=i?.checked??0,p=new Date().getTime()/1e3;if(m+t>p||i?.updating&&m+600>p)return;let d={project:u,id:i?.id,isValid:!0,checked:m,updated:i?.updated??0,updating:!0};s.push(d),a.store.put(d)})),await a.done}if(P.debug(checked. ${s.length} projects maybe need upgrade.),s.length===0)return[];let c=new BroadcastChannel(dr),l=[];for await(let a of dn(s)){if(!a.ok)switch(o.push({project:a.value.project,isValid:!1}),a.value.name){case"NotFoundError":console.warn(${n} "${a.value.project}" is not found.);continue;case"NotMemberError":console.warn(${n} You are not a member of "${a.value.project}".);continue;case"NotLoggedInError":console.warn(${n} You are not a member of "${a.value.project}" or You are not logged in yet.);continue}if(a.value.updated<a.value.checked)P.debug(no updates in "${a.value.name}");else{let u={project:a.value.name,links:await mn(a.value.name)};l.push(u),P.time(write data of "${a.value.name}"),await pn(u),c.postMessage({type:"update",project:a.value.name}),P.timeEnd(write data of "${a.value.name}")}o.push({project:a.value.name,isValid:!0,id:a.value.id,checked:new Date().getTime()/1e3,updated:a.value.updated,updating:!1})}return c.close(),l}finally{let c=r.transaction("status","readwrite"),l=c.store;await Promise.all(o.map(a=>l.put(a))),await c.done}},lr=async e=>{let t=[],r=read links of ${e.length} projects;P.time(r);{let n=(await Ue()).transaction("source","readonly");await Promise.all(e.map(async s=>{let o=await n.store.get(s);o?t.push(o):t.push({project:s,links:[]})})),await n.done}return P.timeEnd(r),t},ur=(e,t)=>{let r=new BroadcastChannel(dr),n=s=>{e.includes(s.data.project)&&t(s.data)};return r.addEventListener("message",n),()=>{r.removeEventListener("message",n),r.close()}},be,Ue=async()=>be||(be=await Gt("userscript-links",5,{upgrade(e){P.time("update DB");for(let t of e.objectStoreNames)e.deleteObjectStore(t);e.createObjectStore("source",{keyPath:"project"}),e.createObjectStore("status",{keyPath:"project"}),P.timeEnd("update DB")}}),be);async function*dn(e){let t=[],r=[],n=new Map;for(let o of e)o.id?t.push(o.id):r.push(o.project),n.set(o.project,o.checked);let s=await te(t);if(!s.ok)r=e.map(o=>o.project);else for(let o of s.value.projects)n.has(o.name)&&(yield{ok:!0,value:{...o,checked:n.get(o.name)??0}});for(let o of r){let c=await ee(o);yield c.ok?{ok:!0,value:{...c.value,checked:n.get(o)??0}}:{ok:!1,value:{...c.value,project:o}}}}var pn=async e=>(await Ue()).put("source",e),dr="userscript-store-notify",mn=async e=>{let t=await Ae(e);if("name"in t)throw console.error(t),new Error(${t.name}: ${t.message});let r=download and create Links of "${e}";P.time(r);let n=new Map;for await(let s of t)for(let o of s){let c=z(o.title),l=n.get(c);n.set(c,{title:o.title,hasIcon:o.hasIcon,updated:o.updated,links:o.links.length,linked:l?.linked??0});for(let a of o.links){let u=z(a),i=n.get(u);n.set(u,{title:i?.title??a,hasIcon:i?.hasIcon??!1,updated:i?.updated??0,links:i?.links??0,linked:(i?.linked??0)+1})}}return P.timeEnd(r),[...n.entries()].map(([s,o])=>[o.title,s,o.hasIcon,o.links,o.linked,o.updated])};var pr=e=>{let[t,r]=C([]),n=T(s=>{let o=new Map;for(let{project:c,links:l}of s)for(let[a,u,i,,,m]of l){let p=o.get(u);o.set(u,{title:p?.title??a,updated:Math.max(p?.updated??0,m),metadata:[...p?.metadata??[],{project:c,hasIcon:i}]})}r([...o.entries()].map(([c,l])=>({titleLc:c,...l})))},[]);return k(()=>{let s=!1,o=async()=>{let i=await lr(e);s||n(i)};o();let c,l=ur(e,()=>{clearTimeout(c),c=setTimeout(o,1e4)}),a=async()=>{(await cr(e,600)).length===0||s||o()};a();let u=setInterval(a,600*1e3);return()=>{s=!0,clearTimeout(c),clearInterval(u),l()}},[e]),t};var mr=e=>{let t=pe(null),r=j(()=>{if(!t.current)return{};let n=t.current.parentNode;if(!(n instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');let s=n.host?.parentElement?.getBoundingClientRect?.(),c=J(e.line,e.char)?.getBoundingClientRect?.();return!c||!s?{}:{top:${c.bottom-s.top}px,left:${c?.left??0-s.left}px,right:${s.right-(c?.left??0)}px}},[e.line,e.char]);return{ref:t,...r}};var fr=e=>{let t=new Map,r=[...e].reverse();{let c=1;for(let l of r){t.set(l,(t.get(l)??0)|c);let a=l.toLowerCase();t.set(a,(t.get(a)??0)|c);let u=l.toUpperCase();t.set(u,(t.get(u)??0)|c),c<<=1}}let n=r.length,s=~(-1<<n),o=1<<n-1;return c=>{let l=0,a=s,u=[...c].reverse(),i=[],m=u.length;i[m]=n;for(let p of u){let d=t.get(p)??0,f=d|l,M=(d&a)+a^a|d,h=l|~(M|a),b=a&M;i[m-1]=i[m]+(h&o?1:b&o?-1:0),a=b<<1|~(f|h<<1),l=h<<1&f,m--}return i}};var fn=[0,0,0,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6],gr=e=>{let t=Mt(e.trim()).split(/\s+/).sort((r,n)=>n.length-r.length);if(!(t.length===0||t.every(r=>r==="")))return r=>{let n=[...r];for(let s of t)n=gn(s,n);return n}},gn=(e,t)=>{let r=[...e].length,n=fn[r],s=fr(e);return t.flatMap(({title:o,dist:c,matches:l,...a})=>{l??=[],c??=0;let u=s(o).flatMap((m,p)=>m<=n&&l.every(([d,f])=>p+r<=d||f<p)?[[p,m]]:[]);if(u.length===0)return[];let i=u.reduce((m,[p,d])=>(m.dist<=d||(m.dist=d,m.start=p),m),{dist:r,start:0});return l.push([i.start,i.start+r-1]),[{title:o,dist:i.dist+c,matches:l,...a}]})};var hr=(e,t,r,n)=>{let s=gr(e);if(!s)return r([]),()=>{};let o=!1,c,l=[],a=()=>{r(l),c=void 0},u=n?.chunk??1e3,i=Math.floor(t.length/u)+1;return(async()=>{for(let m=0;m<i;m++){if(await new Promise(p=>requestAnimationFrame(p)),o)return;P.time(${m}/${i-1} search for "${e}"),l.push(...s(t.slice(m*u,(m+1)*u))),P.timeEnd(${m}/${i-1} search for "${e}"),c===void 0&&(a(),c=setTimeout(a,n?.interval??500))}})(),()=>{o=!0,clearTimeout(c)}};var xr=e=>{let t=Object.fromEntries(e.map((r,n)=>[r,n]));return(r,n)=>{let s=r.dist-n.dist;if(s!==0)return s;let o=r.matches.map(([u])=>u).sort(),c=n.matches.map(([u])=>u).sort();for(let u=0;u<o.length;u++){let i=o[u]-(c[u]??c.length);if(i!==0)return i}let l=r.title.length-n.title.length;if(l!==0)return l;let a=Math.min(...r.metadata.map(u=>t[u.project]??e.length))-Math.min(...n.metadata.map(u=>t[u.project]??e.length));return a!==0?a:n.updated-r.updated}};var Ke="enableProjectsOnSuggestion",_r=(e,t)=>{let[r,n]=C(ye(e,t)),s=T((o,c)=>{hn(o,c,e,t),n(ye(e,t))},[e,t.enableSelfProjectOnStart]);return k(()=>{let o=c=>{c.key===Ke&&n(ye(e,t))};return addEventListener("storage",o),()=>removeEventListener("storage",o)},[e,t.enableSelfProjectOnStart]),{projects:r,set:s}},qe=!0,ye=(e,t)=>{try{let r=localStorage.getItem(Ke);if(r===null)return Ee(e),e;let n=JSON.parse(r);return Array.isArray(n)&&n.every(s=>typeof s=="string")?!t.enableSelfProjectOnStart||!e.includes(scrapbox.Project.name)?n:n.includes(scrapbox.Project.name)?qe?n:n.filter(s=>s!==scrapbox.Project.name):qe?[...n,scrapbox.Project.name]:n:(Ee(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return Ee(e),e}},hn=(e,t,r,n)=>{let s=ye(r,n);n.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(qe=t),Ee(t?[...s,e]:s.filter(o=>o!==e))},Ee=e=>localStorage.setItem(Ke,JSON.stringify(e));var re=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(n){if(!(n instanceof TypeError))throw n;return e}}};var br=({query:e,position:t,state:r,limit:n,range:s,context:o,enableSelfProjectOnStart:c,callback:l,projects:a,dispatch:u,mark:i})=>{let{projects:m,set:p}=_r(a,{enableSelfProjectOnStart:c}),d=pr(a),[f,M]=C([]),h=j(()=>xr(a),[a]);k(()=>{if(r!=="completion"){M([]);return}return hr(e,d,w=>M(w.sort(h).map(y=>({title:y.title,projects:y.metadata.map(({project:R})=>R)}))),{chunk:5e3})},[r,d,e,h]);let b=T((w,y)=>{u({type:"cancel"});let R=y?/${y}/${w}:${w};if(o==="selection"){Ne(R);return}let ke=Q().getPosition().line;if(scrapbox.Layout!=="page")return;let Xe=scrapbox.Page.lines[ke].text;It(ke,ke,${Xe.slice(0,s?.start??0)}${R}${Xe.slice((s?.end??0)+1)})},[o,s?.start,s?.end]),_=j(()=>{P.time("filtering by projects");let w=f.filter(y=>y.projects.some(R=>m.includes(R))).slice(0,n).map(y=>({title:y.title,projects:y.projects.flatMap(R=>m.includes(R)?[{name:R,mark:R===scrapbox.Project.name&&a.length<2?"":re(i[R]??"",import.meta.url)||R[0],confirm:()=>b(y.title,R)}]:[]),confirm:()=>b(y.title)}));return P.timeEnd("filtering by projects"),w},[m,a.length,f,n,i,b]),{selectedIndex:S,next:v,prev:B,selectLast:H,selectFirst:ne}=Dt(_.length),Ve=T(()=>S===-1?!1:(_.at(S)?.confirm?.(),!0),[S,_]);k(()=>l(_.length===0?void 0:{selectNext:w=>(v(w),!0),selectPrev:w=>(B(w),!0),selectFirst:()=>(ne(),!0),selectLast:()=>(H(),!0),confirm:Ve,cancel:()=>(u({type:"cancel"}),!0)}),[l,v,B,ne,H,Ve]);let Pr=j(()=>{let w=new Set;for(let y of f)for(let R of y.projects)w.add(R);return a.flatMap(y=>w.has(y)?[{name:y,enable:m.includes(y),mark:re(i[y]??"",import.meta.url)||y[0],onClick:()=>{p(y,!m.includes(y)),F().focus()}}]:[])},[f,a,m,i]),{ref:Sr,top:q,left:ve,right:we}=mr(t??{line:0,char:0}),Tr=j(()=>r==="completion"&&_.length>0&&q!=null&&ve!=null?{top:q,left:ve}:{display:"none"},[_.length,q,ve,r]),We=j(()=>document.documentElement.dataset.os??"",[]),Ir=j(()=>r==="completion"&&f.length>0&&q!=null&&we!=null&&a.length>1?{top:q,right:we}:{display:"none"},[q,we,f.length,a.length,r]);return x(N,null,x("div",{className:"container projects","data-os":We,style:Ir},Pr.map(w=>x(xn,{...w}))),x("div",{ref:Sr,className:"container candidates","data-os":We,style:Tr},_.map((w,y)=>x(Nt,{key:w.title,...w,selected:S===y})),f.length>n&&x("div",{className:"counter"},${f.length-n} more links)))},xn=e=>x("div",{className:e.enable?"mark":"mark disabled",onClick:e.onClick,title:e.name},e.mark instanceof URL?x("img",{src:e.mark.href}):${e.mark});var yr=e=>{let t=j(()=>re(e.style,import.meta.url),[e.style]);return x(N,null,t!==""&&(t instanceof URL?x("link",{rel:"stylesheet",href:t.href}):x("style",null,t)))};var Er=()=>x("style",null,.container { position: absolute;
margin-top: 14px;
max-height: 80vh;
z-index: 301;
background-color: var(--select-suggest-bg, #111); font-family: var(--select-suggest-font-family, "Open Sans", Helvetica, Arial, "Hiragino Sans", sans-serif);
font-size: 14px;
color: var(--select-suggest-text-color, #eee); border-radius: 4px;
}
.candidates {
max-width: 80vw;
}
font-size:11px;
}
.projects {
margin-right: 4px;
display: grid;
grid-template-rows: repeat(4, min-content);
grid-auto-flow: column;
direction: rtl;
}
padding: 6px;
}
.candidates > :not(:first-child) {
border-top: 1px solid var(--select-suggest-border-color, #eee); }
.candidates > *{
line-height: 1.2em;
padding: 0.5em 10px;
}
.candidate {
display: flex;
}
a {
display: block;
text-decoration: none;
color: inherit;
}
a:not(.mark) {
width: 100%;
}
.selected a {
background-color: var(--select-suggest-selected-bg, #222); text-decoration: underline
}
img {
height: 1.3em;
width: 1.3em;
position: relative;
object-fit: cover;
object-position: 0% 0%;
}
.disabled {
filter: grayscale(1.0) opacity(0.5);
}
.counter {
color: var(--select-suggest-information-text-color, #aaa); font-size: 80%;
font-style: italic;
});var Ge=(e,t)=>{let r=J(e,t);if(!r)return;let n=r.closest('a.page-link:not([type="hashTag"])');if(!n)return;if(!(n instanceof HTMLAnchorElement))throw TypeError('a.page-link:not([type="hashTag"]) is not HTMLAnchorElement');let s=n.getElementsByClassName("char-index");if(s.length===0)throw Error("a.page-link must have a char at least.");let o=parseInt(s[0].dataset.charIndex??"0"),c=parseInt(s[s.length-1].dataset.charIndex??"0"),a=n.closest(".cursor-line")!=null?{start:o,end:c}:{start:o-1,end:c+1};if(a.start!==t)return a};var vr=(e,t)=>{let{state:r,...n}=e;if(r==="disabled")return t.type==="enable"?{state:"idle",...n}:e;switch(t.type){case"completionupdate":{let{type:s,...o}=t;return e.state==="canceled"?e:{state:"completion",...o}}case"completionend":return r==="idle"?e:{state:"idle",...n};case"cancel":return r==="canceled"?e:{state:"canceled",...n};case"disable":return{state:"disabled",...n};case"enable":return e}};var wr={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},kr=e=>{let{callback:t,projects:r,style:n,...s}=e,[o,c]=Me(vr,{state:"idle",query:""}),[l,a]=C(!1);k(()=>{if(l){c({type:"disable"});return}let _=()=>c({type:scrapbox.Layout==="page"?"enable":"disable"});return _(),scrapbox.addListener("layout:changed",_),()=>scrapbox.removeListener("layout:changed",_)},[l]);let{text:u,range:i}=Ct();k(()=>{if(o.state!=="idle"&&o.state!=="completion"&&o.state!=="canceled"||scrapbox.Layout!=="page")return;let _=scrapbox.Page.lines[i.start.line];if(!_n(_,u)){o.state==="completion"&&o.context==="input"||(console.info("End completion due to no selection"),c({type:"completionend"}));return}if(o.state==="canceled")return;let S=Math.min(i.start.line,i.end.line),v=i.start.line<i.end.line?i.start.char:i.start.line===i.start.line?Math.min(i.start.char,i.end.char):i.end.char;c({type:"completionupdate",query:u.trim(),context:"selection",position:{line:S,char:v}})},[o.state,o.context,u,i]);let[m,p]=C(!1);k(()=>{if(o.state!=="idle"&&o.state!=="completion"&&o.state!=="canceled"){p(!1);return}if(o.state==="completion"&&o.context==="selection"){p(!1);return}let _=Q(),S=()=>{let{line:v,char:B}=_.getPosition(),H=Ge(v,B);if(!H){p(!1),c({type:"completionend"});return}if(p(o.state!=="canceled"),scrapbox.Layout!=="page"||o.state==="canceled")return;let ne=scrapbox.Page.lines[v];c({type:"completionupdate",query:ne.text.slice(H.start+1,H.end),context:"input",range:H,position:{line:v,char:H.start}})};return scrapbox.addListener("lines:changed",S),()=>scrapbox.removeListener("lines:changed",S)},[o.state,o.context]),k(()=>{if(!m)return;let _=Q(),S=()=>{let{line:v,char:B}=_.getPosition();Ge(v,B)||c({type:"completionend"})};return _.addChangeListener(S),()=>_.removeChangeListener(S)},[m]);let d=T(()=>a(!1),[]),f=T(()=>a(!0),[]),M=pe({...wr,enable:d,disable:f}),[h,b]=C();return k(()=>{Object.assign(M.current,o.state!=="completion"||!h?wr:h)},[o.state,h]),k(()=>t(M.current),[t]),x(N,null,x(Er,null),x(yr,{style:n}),x(br,{callback:b,projects:r,dispatch:c,...o,...s}))},_n=(e,t)=>!(t.trim()===""||t.includes(
`)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var Lr=e=>{let t=document.createElement("div");t.dataset.userscriptName="scrapbox-select-suggestion";let r=t.attachShadow({mode:"open"});document.body.append(t);let{limit:n=5,debug:s=!1,mark:o={},style:c="",enableSelfProjectOnStart:l=!0}=e??{},a=(()=>{if(!e?.projects||e.projects.length===0)returnscrapbox.Project.name;let u=l?scrapbox.Project.name,...e.projects:e.projects;return u.filter((i,m)=>!u.some((p,d)=>d<m&&p===i))})();return ar(s),new Promise(u=>Pe(x(kr,{limit:n,projects:a,mark:o,style:c,callback:u,enableSelfProjectOnStart:l}),r))};await Lr();