generated at
選択範囲に似ているリンクを入力補完するUserScript
詳細:
ここのページはMijinko_SDが使うためのソースコードを置いているだけです

文字選択するだけで、下部に既存のリンク一覧から似ているものを提案してくれる
とても便利Mijinko_SDMijinko_SDMijinko_SD

ソースコード
生成(任意でどちらかを使用する):
更新がめんどくさいのでボツMijinko_SD
v0.3.1で止まっている
v0.9.0のコードを使用している

読み込み例
自分のページに置くやつ
example.js
import { setup } from "/api/code/Mijinko/選択範囲に似ているリンクを入力補完するUserScript/script.js"; setup();

読み込み例2
Mijinko_SD井戸端で使っているやつ
ここ( export interface SetupInit )を見ながら setup() の引数を設定する
example2.js
import { setup } from "/api/code/Mijinko/選択範囲に似ているリンクを入力補完するUserScript/script.js"; setup({ projects: [ "villagepump", "Mijinko", "Mijinko-other" ], mark: { "villagepump": "/api/pages/villagepump/井戸端/icon", "Mijinko": "/api/pages/Mijinko/Mijinko_SD/icon", "Mijinko-other": "/api/pages/Mijinko-other/Mijinko_SD/icon", }, hideSelfMark: false, });

本体
script.js
var re,g,Ue,_r,V,Ae,qe,Er,oe={},Ke=[],kr=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function H(e,t){for(var r in t)e[r]=t[r];return e}function Ge(e){var t=e.parentNode;t&&t.removeChild(e)}function h(e,t,r){var o,s,n,c={};for(n in t)n=="key"?o=t[n]:n=="ref"?s=t[n]:c[n]=t[n];if(arguments.length>2&&(c.children=arguments.length>3?re.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(n in e.defaultProps)c[n]===void 0&&(c[n]=e.defaultProps[n]);return ne(e,c,o,s,null)}function ne(e,t,r,o,s){var n={type:e,props:t,key:r,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:s??++Ue};return s==null&&g.vnode!=null&&g.vnode(n),n}function I(e){return e.children}function se(e,t){this.props=e,this.context=t}function G(e,t){if(t==null)return e.__?G(e.__,e.__.__k.indexOf(e)+1):null;for(var r;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null)return r.__e;return typeof e.type=="function"?G(e):null}function We(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.__k[t])!=null&&r.__e!=null){e.__e=e.__c.base=r.__e;break}return We(e)}}function Ve(e){(!e.__d&&(e.__d=!0)&&V.push(e)&&!ie.__r++||qe!==g.debounceRendering)&&((qe=g.debounceRendering)||Ae)(ie)}function ie(){for(var e;ie.__r=V.length;)e=V.sort(function(t,r){return t.__v.__b-r.__v.__b}),V=[],e.some(function(t){var r,o,s,n,c,l;t.__d&&(c=(n=(r=t).__v).__e,(l=r.__P)&&(o=[],(s=H({},n)).__v=n.__v+1,ye(l,n,s,r.__n,l.ownerSVGElement!==void 0,n.__h!=null?[c]:null,o,c??G(n),n.__h),et(o,n),n.__e!=c&&We(n)))})}function Xe(e,t,r,o,s,n,c,l,a,u){var i,f,d,p,m,k,x,b=o&&o.__k||Ke,P=b.length;for(r.__k=[],i=0;i<t.length;i++)if((p=r.__k[i]=(p=t[i])==null||typeof p=="boolean"?null:typeof p=="string"||typeof p=="number"||typeof p=="bigint"?ne(null,p,null,null,p):Array.isArray(p)?ne(I,{children:p},null,null,null):p.__b>0?ne(p.type,p.props,p.key,null,p.__v):p)!=null){if(p.__=r,p.__b=r.__b+1,(d=b[i])===null||d&&p.key==d.key&&p.type===d.type)b[i]=void 0;else for(f=0;f<P;f++){if((d=b[f])&&p.key==d.key&&p.type===d.type){b[f]=void 0;break}d=null}ye(e,p,d=d||oe,s,n,c,l,a,u),m=p.__e,(f=p.ref)&&d.ref!=f&&(x||(x=[]),d.ref&&x.push(d.ref,null,p),x.push(f,p.__c||m,p)),m!=null?(k==null&&(k=m),typeof p.type=="function"&&p.__k===d.__k?p.__d=a=ze(p,a,e):a=Ye(e,p,d,b,m,a),typeof r.type=="function"&&(r.__d=a)):a&&d.__e==a&&a.parentNode!=e&&(a=G(d))}for(r.__e=k,i=P;i--;)b[i]!=null&&(typeof r.type=="function"&&b[i].__e!=null&&b[i].__e==r.__d&&(r.__d=G(o,i+1)),rt(b[i],b[i]));if(x)for(i=0;i<x.length;i++)tt(x[i],x[++i],x[++i])}function ze(e,t,r){for(var o,s=e.__k,n=0;s&&n<s.length;n++)(o=s[n])&&(o.__=e,t=typeof o.type=="function"?ze(o,t,r):Ye(r,o,o,s,o.__e,t));return t}function Ye(e,t,r,o,s,n){var c,l,a;if(t.__d!==void 0)c=t.__d,t.__d=void 0;else if(r==null||s!=n||s.parentNode==null)e:if(n==null||n.parentNode!==e)e.appendChild(s),c=null;else{for(l=n,a=0;(l=l.nextSibling)&&a<o.length;a+=2)if(l==s)break e;e.insertBefore(s,n),c=n}return c!==void 0?c:s.nextSibling}function wr(e,t,r,o,s){var n;for(n in r)n==="children"||n==="key"||n in t||ae(e,n,null,r[n],o);for(n in t)s&&typeof t[n]!="function"||n==="children"||n==="key"||n==="value"||n==="checked"||r[n]===t[n]||ae(e,n,t[n],r[n],o)}function Je(e,t,r){t[0]==="-"?e.setProperty(t,r):e[t]=r==null?"":typeof r!="number"||kr.test(t)?r:r+"px"}function ae(e,t,r,o,s){var n;e:if(t==="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof o=="string"&&(e.style.cssText=o=""),o)for(t in o)r&&t in r||Je(e.style,t,"");if(r)for(t in r)o&&r[t]===o[t]||Je(e.style,t,r[t])}else if(t[0]==="o"&&t[1]==="n")n=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+n]=r,r?o||e.addEventListener(t,n?Ze:Qe,n):e.removeEventListener(t,n?Ze:Qe,n);else if(t!=="dangerouslySetInnerHTML"){if(s)t=t.replace(/xlink[H:h]/,"h").replace(/sName$/,"s");else if(t!=="href"&&t!=="list"&&t!=="form"&&t!=="tabIndex"&&t!=="download"&&t in e)try{e[t]=r??"";break e}catch{}typeof r=="function"||(r!=null&&(r!==!1||t[0]==="a"&&t[1]==="r")?e.setAttribute(t,r):e.removeAttribute(t))}}function Qe(e){this.l[e.type+!1](g.event?g.event(e):e)}function Ze(e){this.l[e.type+!0](g.event?g.event(e):e)}function ye(e,t,r,o,s,n,c,l,a){var u,i,f,d,p,m,k,x,b,P,U,T=t.type;if(t.constructor!==void 0)return null;r.__h!=null&&(a=r.__h,l=t.__e=r.__e,t.__h=null,n=[l]),(u=g.__b)&&u(t);try{e:if(typeof T=="function"){if(x=t.props,b=(u=T.contextType)&&o[u.__c],P=u?b?b.props.value:u.__:o,r.__c?k=(i=t.__c=r.__c).__=i.__E:("prototype"in T&&T.prototype.render?t.__c=i=new T(x,P):(t.__c=i=new se(x,P),i.constructor=T,i.render=Lr),b&&b.sub(i),i.props=x,i.state||(i.state={}),i.context=P,i.__n=o,f=i.__d=!0,i.__h=[]),i.__s==null&&(i.__s=i.state),T.getDerivedStateFromProps!=null&&(i.__s==i.state&&(i.__s=H({},i.__s)),H(i.__s,T.getDerivedStateFromProps(x,i.__s))),d=i.props,p=i.state,f)T.getDerivedStateFromProps==null&&i.componentWillMount!=null&&i.componentWillMount(),i.componentDidMount!=null&&i.__h.push(i.componentDidMount);else{if(T.getDerivedStateFromProps==null&&x!==d&&i.componentWillReceiveProps!=null&&i.componentWillReceiveProps(x,P),!i.__e&&i.shouldComponentUpdate!=null&&i.shouldComponentUpdate(x,i.__s,P)===!1||t.__v===r.__v){i.props=x,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(A){A&&(A.__=t)}),i.__h.length&&c.push(i);break e}i.componentWillUpdate!=null&&i.componentWillUpdate(x,i.__s,P),i.componentDidUpdate!=null&&i.__h.push(function(){i.componentDidUpdate(d,p,m)})}i.context=P,i.props=x,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&&(o=H(H({},o),i.getChildContext())),f||i.getSnapshotBeforeUpdate==null||(m=i.getSnapshotBeforeUpdate(d,p)),U=u!=null&&u.type===I&&u.key==null?u.props.children:u,Xe(e,Array.isArray(U)?U:[U],t,r,o,s,n,c,l,a),i.base=t.__e,t.__h=null,i.__h.length&&c.push(i),k&&(i.__E=i.__=null),i.__e=!1}else n==null&&t.__v===r.__v?(t.__k=r.__k,t.__e=r.__e):t.__e=vr(r.__e,t,r,o,s,n,c,a);(u=g.diffed)&&u(t)}catch(A){t.__v=null,(a||n!=null)&&(t.__e=l,t.__h=!!a,n[n.indexOf(l)]=null),g.__e(A,t,r)}}function et(e,t){g.__c&&g.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(o){o.call(r)})}catch(o){g.__e(o,r.__v)}})}function vr(e,t,r,o,s,n,c,l){var a,u,i,f=r.props,d=t.props,p=t.type,m=0;if(p==="svg"&&(s=!0),n!=null){for(;m<n.length;m++)if((a=n[m])&&"setAttribute"in a==!!p&&(p?a.localName===p:a.nodeType===3)){e=a,n[m]=null;break}}if(e==null){if(p===null)return document.createTextNode(d);e=s?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,d.is&&d),n=null,l=!1}if(p===null)f===d||l&&e.data===d||(e.data=d);else{if(n=n&&re.call(e.childNodes),u=(f=r.props||oe).dangerouslySetInnerHTML,i=d.dangerouslySetInnerHTML,!l){if(n!=null)for(f={},m=0;m<e.attributes.length;m++)f[e.attributes[m].name]=e.attributes[m].value;(i||u)&&(i&&(u&&i.__html==u.__html||i.__html===e.innerHTML)||(e.innerHTML=i&&i.__html||""))}if(wr(e,d,f,s,l),i)t.__k=[];else if(m=t.props.children,Xe(e,Array.isArray(m)?m:[m],t,r,o,s&&p!=="foreignObject",n,c,n?n[0]:r.__k&&G(r,0),l),n!=null)for(m=n.length;m--;)n[m]!=null&&Ge(n[m]);l||("value"in d&&(m=d.value)!==void 0&&(m!==f.value||m!==e.value||p==="progress"&&!m)&&ae(e,"value",m,f.value,!1),"checked"in d&&(m=d.checked)!==void 0&&m!==e.checked&&ae(e,"checked",m,f.checked,!1))}return e}function tt(e,t,r){try{typeof e=="function"?e(t):e.current=t}catch(o){g.__e(o,r)}}function rt(e,t,r){var o,s;if(g.unmount&&g.unmount(e),(o=e.ref)&&(o.current&&o.current!==e.__e||tt(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(n){g.__e(n,t)}o.base=o.__P=null}if(o=e.__k)for(s=0;s<o.length;s++)o[s]&&rt(o[s],t,typeof e.type!="function");r||e.__e==null||Ge(e.__e),e.__e=e.__d=void 0}function Lr(e,t,r){return this.constructor(e,r)}function _e(e,t,r){var o,s,n;g.__&&g.__(e,t),s=(o=typeof r=="function")?null:r&&r.__k||t.__k,n=[],ye(t,e=(!o&&r||t).__k=h(I,null,[e]),s||oe,oe,t.ownerSVGElement!==void 0,!o&&r?[r]:s?null:t.firstChild?re.call(t.childNodes):null,n,!o&&r?r:s?s.__e:t.firstChild,o),et(n,e)}re=Ke.slice,g={__e:function(e,t){for(var r,o,s;t=t.__;)if((r=t.__c)&&!r.__)try{if((o=r.constructor)&&o.getDerivedStateFromError!=null&&(r.setState(o.getDerivedStateFromError(e)),s=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(e),s=r.__d),s)return r.__E=r}catch(n){e=n}throw e}},Ue=0,_r=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=H({},this.state),typeof e=="function"&&(e=e(H({},r),this.props)),e&&H(r,e),e!=null&&this.__v&&(t&&this.__h.push(t),Ve(this))},se.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ve(this))},se.prototype.render=I,V=[],Ae=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ie.__r=0,Er=0;var ce,C,ot,X=0,Ee=[],nt=g.__b,st=g.__r,it=g.diffed,at=g.__c,ct=g.unmount;function ke(e,t){g.__h&&g.__h(C,e,X||t),X=0;var r=C.__H||(C.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function D(e){return X=1,z(dt,e)}function z(e,t,r){var o=ke(ce++,2);return o.t=e,o.__c||(o.__=[r?r(t):dt(void 0,t),function(s){var n=o.t(o.__[0],s);o.__[0]!==n&&(o.__=[n,o.__[1]],o.__c.setState({}))}],o.__c=C),o.__}function w(e,t){var r=ke(ce++,3);!g.__s&&ut(r.__H,t)&&(r.__=e,r.__H=t,C.__H.__h.push(r))}function O(e){return X=5,L(function(){return{current:e}},[])}function L(e,t){var r=ke(ce++,7);return ut(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function _(e,t){return X=8,L(function(){return e},t)}function Sr(){var e;for(Ee.sort(function(t,r){return t.__v.__b-r.__v.__b});e=Ee.pop();)if(e.__P)try{e.__H.__h.forEach(le),e.__H.__h.forEach(we),e.__H.__h=[]}catch(t){e.__H.__h=[],g.__e(t,e.__v)}}g.__b=function(e){C=null,nt&&nt(e)},g.__r=function(e){st&&st(e),ce=0;var t=(C=e.__c).__H;t&&(t.__h.forEach(le),t.__h.forEach(we),t.__h=[])},g.diffed=function(e){it&&it(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(Ee.push(t)!==1&&ot===g.requestAnimationFrame||((ot=g.requestAnimationFrame)||function(r){var o,s=function(){clearTimeout(n),lt&&cancelAnimationFrame(o),setTimeout(r)},n=setTimeout(s,100);lt&&(o=requestAnimationFrame(s))})(Sr)),C=null},g.__c=function(e,t){t.some(function(r){try{r.__h.forEach(le),r.__h=r.__h.filter(function(o){return!o.__||we(o)})}catch(o){t.some(function(s){s.__h&&(s.__h=[])}),t=[],g.__e(o,r.__v)}}),at&&at(e,t)},g.unmount=function(e){ct&&ct(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(o){try{le(o)}catch(s){t=s}}),t&&g.__e(t,r.__v))};var lt=typeof requestAnimationFrame=="function";function le(e){var t=C,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),C=t}function we(e){var t=C;e.__c=e.__(),C=t}function ut(e,t){return!e||e.length!==t.length||t.some(function(r,o){return r!==e[o]})}function dt(e,t){return typeof t=="function"?t(e):t}var Y=e=>e==null,ue=e=>typeof e=="string",de=e=>typeof e=="number";var Pr=e=>typeof e=="object"&&e!==null,Tr=e=>Pr(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,pt=e=>{try{let t=typeof e=="string"?JSON.parse(e):e;return Tr(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};var ft=(e,t)=>{if(!Array.isArray(e))throw new TypeError(`"${t}" must be an array but actual is "${e}"`)};var mt=(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 mt(e,"textarea#text-input"),e};var gt=e=>{if(Y(e))return;if(de(e))return Ir(e)?.id;if(ue(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 Ir=e=>{if(Y(e))return;if(de(e))return xt()[e];let t=gt(e);return t?xt().find(r=>r.id===t):void 0},ht=e=>{if(Rr(e))return e;let t=gt(e);if(Y(t))return t;let r=document.getElementById(`L${t}`);if(!Y(r))return r},Rr=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var xt=()=>(ft(scrapbox.Page.lines,"scrapbox.Page.lines"),scrapbox.Page.lines);var Mr=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index");var ve=(e,t)=>{let r=ht(e)?.getElementsByClassName?.(`c-${t}`)?.[0];return Mr(r)?r:void 0};var Le=e=>new Promise(t=>setTimeout(()=>t(),e));var bt=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 Le(1)};var J=e=>e.replaceAll(" ","_").toLowerCase(),yt=e=>e.replaceAll("_"," "),B=e=>[...e].map((t,r)=>t===" "?"_":!Dr.includes(t)||r===e.length-1&&Or.includes(t)?encodeURIComponent(t):t).join(""),Dr='@$&+=:;",',Or=':;",';var q=()=>{let e=F();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(n=>n.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,o=r.find(n=>n.constructor.name==="Cursor");if(!o)throw Error('#text-input must has a "Cursor" store.');let s=r.find(n=>n.constructor.name==="Selection");if(!s)throw Error('#text-input must has a "Selection" store.');return{cursor:o,selection:s}};var _t=()=>q().cursor;var Et=()=>q().selection;var kt=({title:e,projects:t,selected:r,confirm:o})=>h("div",{className:`candidate${r?" selected":""}`},h(Br,{title:e,confirm:o}),t.map(s=>h(Hr,{project:s.name,title:e,mark:s.mark,confirm:s.confirm}))),Br=({title:e,confirm:t})=>h("a",{className:"button",tabIndex:0,role:"menuitem",href:`./${B(e)}`,onClick:wt(t)},e),Hr=({project:e,title:t,mark:r,confirm:o})=>r===""?h(I,null):h("a",{className:"mark",tabIndex:0,href:`../${e}/${B(t)}`,onClick:wt(o),title:`/${e}/${B(t)}`},r instanceof URL?h("img",{src:r.href}):`[${r}]`),wt=e=>_(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var vt=e=>{let[t,r]=D(-1);w(()=>r(-1),[e]);let o=_(l=>r(a=>l?.cyclic?(a+1)%e:Math.min(a+1,e)),[e]),s=_(l=>r(a=>a<0?e-1:l?.cyclic?(a+e-1)%e:Math.max(a-1,0)),[e]),n=_(()=>r(0),[]),c=_(()=>r(e-1),[e]);return{selectedIndex:t,next:o,prev:s,selectFirst:n,selectLast:c}};var Lt=e=>{let t=O(null),r=L(()=>{if(!t.current)return{};let o=t.current.parentNode;if(!(o instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');let s=o.host?.parentElement?.getBoundingClientRect?.(),c=ve(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`}},[t.current,e.line,e.char]);return{ref:t,...r}};var Se=(e,t)=>t.some(r=>e instanceof r),St,Pt;function Fr(){return St||(St=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function $r(){return Pt||(Pt=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Tt=new WeakMap,Pe=new WeakMap,It=new WeakMap,Te=new WeakMap,pe=new WeakMap;function Ur(e){let t=new Promise((r,o)=>{let s=()=>{e.removeEventListener("success",n),e.removeEventListener("error",c)},n=()=>{r($(e.result)),s()},c=()=>{o(e.error),s()};e.addEventListener("success",n),e.addEventListener("error",c)});return t.then(r=>{r instanceof IDBCursor&&Tt.set(r,e)}).catch(()=>{}),pe.set(t,e),t}function Ar(e){if(Pe.has(e))return;let t=new Promise((r,o)=>{let s=()=>{e.removeEventListener("complete",n),e.removeEventListener("error",c),e.removeEventListener("abort",c)},n=()=>{r(),s()},c=()=>{o(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",n),e.addEventListener("error",c),e.addEventListener("abort",c)});Pe.set(e,t)}var Ie={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Pe.get(e);if(t==="objectStoreNames")return e.objectStoreNames||It.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return $(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 Rt(e){Ie=e(Ie)}function qr(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let o=e.call(fe(this),t,...r);return It.set(o,t.sort?t.sort():[t]),$(o)}:$r().includes(e)?function(...t){return e.apply(fe(this),t),$(Tt.get(this))}:function(...t){return $(e.apply(fe(this),t))}}function Kr(e){return typeof e=="function"?qr(e):(e instanceof IDBTransaction&&Ar(e),Se(e,Fr())?new Proxy(e,Ie):e)}function $(e){if(e instanceof IDBRequest)return Ur(e);if(Te.has(e))return Te.get(e);let t=Kr(e);return t!==e&&(Te.set(e,t),pe.set(t,e)),t}var fe=e=>pe.get(e);function Mt(e,t,{blocked:r,upgrade:o,blocking:s,terminated:n}={}){let c=indexedDB.open(e,t),l=$(c);return o&&c.addEventListener("upgradeneeded",a=>{o($(c.result),a.oldVersion,a.newVersion,$(c.transaction),a)}),r&&c.addEventListener("blocked",a=>r(a.oldVersion,a.newVersion,a)),l.then(a=>{n&&a.addEventListener("close",()=>n()),s&&a.addEventListener("versionchange",u=>s(u.oldVersion,u.newVersion,u))}).catch(()=>{}),l}var Gr=["get","getKey","getAll","getAllKeys","count"],Wr=["put","add","delete","clear"],Re=new Map;function Ct(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Re.get(t))return Re.get(t);let r=t.replace(/FromIndex$/,""),o=t!==r,s=Wr.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!(s||Gr.includes(r)))return;let n=async function(c,...l){let a=this.transaction(c,s?"readwrite":"readonly"),u=a.store;return o&&(u=u.index(l.shift())),(await Promise.all([u[r](...l),s&&a.done]))[0]};return Re.set(t,n),n}Rt(e=>({...e,get:(t,r,o)=>Ct(t,r)||e.get(t,r,o),has:(t,r)=>!!Ct(t,r)||e.has(t,r)}));var Vr=["continue","continuePrimaryKey","advance"],Nt={},Me=new WeakMap,jt=new WeakMap,Xr={get(e,t){if(!Vr.includes(t))return e[t];let r=Nt[t];return r||(r=Nt[t]=function(...o){Me.set(this,jt.get(this)[t](...o))}),r}};async function*zr(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,Xr);for(jt.set(r,t),pe.set(r,fe(t));t;)yield r,t=await(Me.get(r)||t.continue()),Me.delete(r)}function Dt(e,t){return t===Symbol.asyncIterator&&Se(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Se(e,[IDBIndex,IDBObjectStore])}Rt(e=>({...e,get(t,r,o){return Dt(t,r)?zr:e.get(t,r,o)},has(t,r){return Dt(t,r)||e.has(t,r)}}));var E=e=>{let{fetch:t=globalThis.fetch,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var Q=class extends Error{constructor(t){super(`${t.status} ${t.statusText} when fetching ${t.url}`);this.response=t;this.name="UnexpectedResponseError";Error.captureStackTrace&&Error.captureStackTrace(this,Q)}},S=async e=>{let t=e.clone(),r=await t.text(),o=pt(r);if(!o)throw new Q(t);return{ok:!1,value:o}};var v=e=>`connect.sid=${e}`;var Ot=(e,t,r)=>{let{sid:o,hostName:s,followRename:n,projects:c}=E(r??{}),l=new URLSearchParams;l.append("followRename",`${n??!0}`);for(let u of c??[])l.append("projects",u);let a=`https://${s}/api/pages/${e}/${B(t)}?${l.toString()}`;return new Request(a,o?{headers:{Cookie:v(o)}}:void 0)},Bt=async e=>{if(!e.ok)return e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:S(e);let t=await e.json();return{ok:!0,value:t}},Ht=async(e,t,r)=>{let{fetch:o}=E(r??{}),s=Ot(e,t,r),n=await o(s);return await Bt(n)};Ht.toRequest=Ot;Ht.fromResponse=Bt;var Ft=(e,t)=>{let{sid:r,hostName:o,sort:s,limit:n,skip:c}=E(t??{}),l=new URLSearchParams;s!==void 0&&l.append("sort",s),n!==void 0&&l.append("limit",`${n}`),c!==void 0&&l.append("skip",`${c}`);let a=`https://${o}/api/pages/${e}?${l.toString()}`;return new Request(a,r?{headers:{Cookie:v(r)}}:void 0)},$t=async e=>{if(!e.ok)return S(e);let t=await e.json();return{ok:!0,value:t}},Ut=async(e,t)=>{let{fetch:r}=E(t??{}),o=await r(Ft(e,t));return await $t(o)};Ut.toRequest=Ft;Ut.fromResponse=$t;var At=(e,t,r,o)=>{let{sid:s,hostName:n}=E(o??{}),c=`https://${n}/api/table/${e}/${B(t)}/${encodeURIComponent(r)}.csv`;return new Request(c,s?{headers:{Cookie:v(s)}}:void 0)},qt=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:S(e),Kt=async(e,t,r,o)=>{let{fetch:s}=E(o??{}),n=At(e,t,r,o),c=await s(n);return await qt(c)};Kt.toRequest=At;Kt.fromResponse=qt;var Gt=(e,t)=>{let{sid:r,hostName:o}=E(t??{});return new Request(`https://${o}/api/projects/${e}`,r?{headers:{Cookie:v(r)}}:void 0)},Wt=async e=>{if(!e.ok)return S(e);let t=await e.json();return{ok:!0,value:t}},Z=async(e,t)=>{let{fetch:r}=E(t??{}),o=Gt(e,t),s=await r(o);return Wt(s)};Z.toRequest=Gt;Z.fromResponse=Wt;var Vt=(e,t)=>{let{sid:r,hostName:o}=E(t??{}),s=new URLSearchParams;for(let n of e)s.append("ids",n);return new Request(`https://${o}/api/projects?${s.toString()}`,r?{headers:{Cookie:v(r)}}:void 0)},Xt=async e=>{if(!e.ok)return S(e);let t=await e.json();return{ok:!0,value:t}},ee=async(e,t)=>{let{fetch:r}=E(t??{}),o=await r(Vt(e,t));return Xt(o)};ee.toRequest=Vt;ee.fromResponse=Xt;var zt=async(e,t)=>{let{sid:r,hostName:o,fetch:s,followingId:n}=E(t??{}),c=new Request(`https://${o}/api/pages/${e}/search/titles${n?`?followingId=${n}`:""}`,r?{headers:{Cookie:v(r)}}:void 0),l=await s(c);if(!l.ok)return l.status===422?{ok:!1,value:{name:"InvalidFollowingIdError",message:await l.text()}}:S(l);let a=await l.json();return{ok:!0,value:{pages:a,followingId:l.headers.get("X-following-id")??""}}},Ne=async(e,t)=>{let r=await zt(e,t);return r.ok?async function*(){yield r.value.pages;let o=r.value.followingId;for(;o;){let s=await zt(e,{followingId:o,...t});if(!s.ok)throw new Error("The authorization cannot be unavailable");yield s.value.pages,o=s.value.followingId}}():r.value};var R=!1,Yt=e=>{R=typeof e=="boolean"?e:new Set(e)},W=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(`%c${e}`,"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{R!==!0&&(!R||!R.has(e))||r(`%c${e}`,"color: gray",...o)}];case"assert":return[t,(o,...s)=>{R!==!0&&(!R||!R.has(e))||r(o,`%c${e}`,"color: gray",...s)}];case"time":case"timeEnd":return[t,o=>{R!==!0&&(!R||!R.has(e))||r(`${e} ${o}`)}];default:return[t,(...o)=>{if(!(R!==!0&&(!R||!R.has(e))))return r(...o)}]}}));var N=W("scrapbox-select-suggestion:storage.ts"),Jt=async(e,t)=>{let r=await je(),o="[scrapbox-select-suggestion]";N.debug("check updates of links...");let s=[],n=[];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 f=i?.checked??0,d=new Date().getTime()/1e3;if(f+t>d||i?.updating&&f+600>d)return;let p={project:u,id:i?.id,isValid:!0,checked:f,updated:i?.updated??0,updating:!0};s.push(p),a.store.put(p)})),await a.done}if(N.debug(`checked. ${s.length} projects maybe need upgrade.`),s.length===0)return[];let c=new BroadcastChannel(er),l=[];for await(let a of Yr(s)){if(!a.ok)switch(n.push({project:a.value.project,isValid:!1}),a.value.name){case"NotFoundError":console.warn(`${o} "${a.value.project}" is not found.`);continue;case"NotMemberError":console.warn(`${o} You are not a member of "${a.value.project}".`);continue;case"NotLoggedInError":console.warn(`${o} You are not a member of "${a.value.project}" or You are not logged in yet.`);continue}if(a.value.updated<a.value.checked)N.debug(`no updates in "${a.value.name}"`);else{let u={project:a.value.name,links:await Qr(a.value.name)};l.push(u),N.time(`write data of "${a.value.name}"`),await Jr(u),c.postMessage({type:"update",project:a.value.name}),N.timeEnd(`write data of "${a.value.name}"`)}n.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(n.map(a=>l.put(a))),await c.done}},Qt=async e=>{let t=[],r=`read links of ${e.length} projects`;N.time(r);{let o=(await je()).transaction("source","readonly");await Promise.all(e.map(async s=>{let n=await o.store.get(s);n?t.push(n):t.push({project:s,links:[]})})),await o.done}return N.timeEnd(r),t},Zt=(e,t)=>{let r=new BroadcastChannel(er),o=s=>{!e.includes(s.data.project)||t(s.data)};return r.addEventListener("message",o),()=>{r.removeEventListener("message",o),r.close()}},me,je=async()=>me||(me=await Mt("userscript-links",5,{upgrade(e){N.time("update DB");for(let t of e.objectStoreNames)e.deleteObjectStore(t);e.createObjectStore("source",{keyPath:"project"}),e.createObjectStore("status",{keyPath:"project"}),N.timeEnd("update DB")}}),me);async function*Yr(e){let t=[],r=[],o=new Map;for(let n of e)n.id?t.push(n.id):r.push(n.project),o.set(n.project,n.checked);let s=await ee(t);if(!s.ok)r=e.map(n=>n.project);else for(let n of s.value.projects)!o.has(n.name)||(yield{ok:!0,value:{...n,checked:o.get(n.name)??0}});for(let n of r){let c=await Z(n);yield c.ok?{ok:!0,value:{...c.value,checked:o.get(n)??0}}:{ok:!1,value:{...c.value,project:n}}}}var Jr=async e=>(await je()).put("source",e),er="userscript-store-notify",Qr=async e=>{let t=await Ne(e);if("name"in t)throw console.error(t),new Error(`${t.name}: ${t.message}`);let r=`download and create Links of "${e}"`;N.time(r);let o=new Map;for await(let s of t)for(let n of s){let c=J(n.title),l=o.get(c);o.set(c,{title:n.title,hasIcon:n.hasIcon,updated:n.updated,links:n.links.length,linked:l?.linked??0});for(let a of n.links){let u=J(a),i=o.get(u);o.set(u,{title:i?.title??a,hasIcon:i?.hasIcon??!1,updated:i?.updated??0,links:i?.links??0,linked:(i?.linked??0)+1})}}return N.timeEnd(r),[...o.entries()].map(([s,n])=>[n.title,s,n.hasIcon,n.links,n.linked,n.updated])};var Zr=W("scrapbox-select-suggestion:useSource.ts"),tr=e=>{let[t,r]=D([]),o=_(s=>{let n=new Date,c=new Map;for(let{project:u,links:i}of s)for(let[f,d,p,,,m]of i){let k=c.get(d);c.set(d,{title:k?.title??f,updated:Math.max(k?.updated??0,m),metadata:[...k?.metadata??[],{project:u,hasIcon:p}]})}let l=[...c.entries()].map(([u,i])=>({titleLc:u,...i})),a=new Date().getTime()-n.getTime();Zr.debug(`Compiled ${l.length} source in ${a}ms`),r(l)},[]);return w(()=>{let s=!1,n=async()=>{let i=await Qt([...e]);s||o(i)};n();let c,l=Zt([...e],()=>{clearTimeout(c),c=setTimeout(n,1e4)}),a=async()=>{(await Jt([...e],600)).length===0||s||n()};a();let u=setInterval(a,600*1e3);return()=>{s=!0,clearTimeout(c),clearInterval(u),l()}},[e]),t};var rr=(e,t)=>{let r=e.dist-t.dist;if(r!==0)return r;let o=e.matches.map(([c])=>c).sort(),s=t.matches.map(([c])=>c).sort();for(let c=0;c<o.length;c++){let l=o[c]-(s[c]??s.length);if(l!==0)return l}let n=e.title.length-t.title.length;return n!==0?n:t.updated-e.updated};var or=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 o=r.length,s=~(~0<<o),n=1<<o-1;return c=>{let l=0,a=s,u=[...c].reverse(),i=[],f=u.length;i[f]=o;for(let d of u){let p=t.get(d)??0,m=p|l,k=(p&a)+a^a|p,x=l|~(k|a),b=a&k;i[f-1]=i[f]+((x&n)!=0?1:(b&n)!=0?-1:0),a=b<<1|~(m|x<<1),l=x<<1&m,f--}return i}};var eo=[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],nr=e=>{let t=yt(e.trim()).split(/\s+/).sort((r,o)=>o.length-r.length);if(!(t.length===0||t.every(r=>r==="")))return r=>{let o=[...r];for(let s of t)o=to(s,o);return o}},to=(e,t)=>{let r=[...e].length,o=eo[r],s=or(e);return t.flatMap(({title:n,dist:c,matches:l,...a})=>{l??=[],c??=0;let u=s(n).flatMap((f,d)=>f<=o&&l.every(([p,m])=>d+r<=p||m<d)?[[d,f]]:[]);if(u.length===0)return[];let i=u.reduce((f,[d,p])=>(f.dist<=p||(f.dist=p,f.start=d),f),{dist:r,start:0});return l.push([i.start,i.start+r-1]),[{title:n,dist:i.dist+c,matches:l,...a}]})};var ro=W("scrapbox-select-suggestion:useSearch.ts"),sr=(e,t)=>{let r=tr(e),[o,s]=z(oo,{type:"query",source:r,query:t});w(()=>s({source:r}),[r]),w(()=>s({query:t}),[t]);let[n,c]=D([]),l=O(Promise.resolve());return w(()=>{let a=!1;return l.current=(async()=>{await l.current;let u=[],i,f=!1;for await(let d of no(o.query,o.source,{chunk:5e3})){if(a)return;u.push(...d),!(u.length===0||o.type==="source")&&(clearTimeout(i),i=setTimeout(()=>{f=!0,c(u)},500))}f||c(u)})(),()=>a=!0},[o]),L(()=>{let a=new Map,u=[];for(let i of n.sort(rr)){let f=i.metadata.map(({project:d})=>d);for(let d of f)a.set(d,(a.get(d)??0)+.5**i.dist);u.push({title:i.title,dist:i.dist,projects:f})}return{projectScore:a,items:u}},[n])},oo=(e,t)=>"query"in t?t.query===e.query?e:{type:"query",source:e.source,...t}:t.source===e.source?e:{type:"source",query:e.query,...t};async function*no(e,t,r){let o=nr(e);if(!o)return;let s=r?.chunk??1e3,n=Math.floor(t.length/s)+1,c=0,l=new Date;try{for(;c<n;c++)await new Promise(a=>requestAnimationFrame(a)),yield o(t.slice(c*s,(c+1)*s))}finally{let u=new Date().getTime()-l.getTime();ro.debug(`search ${(c/n*100).toPrecision(3)}% of the source for "${e}" in ${u}ms`)}}var De="enableProjectsOnSuggestion",ir=(e,t)=>{let[r,o]=D(ge([...e],t)),s=_((n,c)=>{so(n,c,e,t),o(ge([...e],t))},[e,t.enableSelfProjectOnStart]);return w(()=>{let n=c=>{c.key===De&&o(ge([...e],t))};return addEventListener("storage",n),()=>removeEventListener("storage",n)},[e,t.enableSelfProjectOnStart]),{projects:r,set:s}},Oe=!0,ge=(e,t)=>{try{let r=localStorage.getItem(De);if(r===null)return he(e),e;let o=JSON.parse(r);return Array.isArray(o)&&o.every(s=>typeof s=="string")?!t.enableSelfProjectOnStart||!e.includes(scrapbox.Project.name)?o:o.includes(scrapbox.Project.name)?Oe?o:o.filter(s=>s!==scrapbox.Project.name):Oe?[...o,scrapbox.Project.name]:o:(he(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return he(e),e}},so=(e,t,r,o)=>{let s=ge([...r],o);o.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(Oe=t),he(t?[...s,e]:s.filter(n=>n!==e))},he=e=>localStorage.setItem(De,JSON.stringify(e));var ar=()=>L(()=>document.documentElement.dataset.os??"",[]);var te=(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(o){if(!(o instanceof TypeError))throw o;return e}}};var cr=({position:e,query:t,start:r,context:o,limit:s,enableSelfProjectOnStart:n,callback:c,projects:l,mark:a,confirmAfter:u,cancel:i,freezeUntil:f})=>{let{projects:d,set:p}=ir(l,{enableSelfProjectOnStart:n}),{projectScore:m,items:k}=sr(l,o==="input"?t.slice(1,-1):t),x=_((y,M)=>{let j=M?`[/${M}/${y}]`:`[${y}]`;u($e=>`${[...$e].slice(0,r).join("")}${j}${[...$e].slice(r+[...t].length).join("")}`)},[r,t]),b=L(()=>{let y=[];for(let M of k){if(y.length===s)break;!M.projects.some(j=>d.includes(j))||y.push({title:M.title,projects:M.projects.flatMap(j=>d.includes(j)?[{name:j,mark:j===scrapbox.Project.name&&l.size<2?"":te(a[j]??"",import.meta.url)||j[0],confirm:()=>x(M.title,j)}]:[]),confirm:()=>x(M.title)})}return y},[d,l.size,k,s,a,x]),{selectedIndex:P,next:U,prev:T,selectLast:A,selectFirst:Be}=vt(b.length),He=_(()=>P===-1?!1:(b.at(P)?.confirm?.(),!0),[P,b]);w(()=>c(b.length===0?void 0:{selectNext:y=>(U(y),!0),selectPrev:y=>(T(y),!0),selectFirst:()=>(Be(),!0),selectLast:()=>(A(),!0),confirm:He,cancel:()=>(i(),!0)}),[c,U,T,Be,A,He]);let hr=L(()=>[...l].sort((y,M)=>(m.get(M)??0)-(m.get(y)??0)).flatMap(y=>m.has(y)?[{name:y,enable:d.includes(y),mark:te(a[y]??"",import.meta.url)||y[0],score:m.get(y),onClick:()=>f(()=>{p(y,!d.includes(y)),F().focus()})}]:[]),[m,d,a]),{ref:xr,top:K,left:xe,right:be}=Lt({line:e.line,char:r}),br=L(()=>b.length>0&&K!=null&&xe!=null?{top:K,left:xe}:{display:"none"},[b.length,K,xe]),yr=L(()=>k.length>0&&K!=null&&be!=null&&l.size>1?{top:K,right:be}:{display:"none"},[K,be,k.length,l.size]),Fe=ar();return h(I,null,h("div",{className:"container projects","data-os":Fe,style:yr},hr.map(y=>h(io,{...y}))),h("div",{ref:xr,className:"container candidates","data-os":Fe,style:br},b.map((y,M)=>h(kt,{key:y.title,...y,selected:P===M})),k.length>s&&h("div",{className:"counter"},`${k.length-s} more links`)))},io=e=>h("div",{className:e.enable?"mark":"mark disabled","data-score":e.score.toPrecision(3),onClick:e.onClick,title:e.name},e.mark instanceof URL?h("img",{src:e.mark.href}):`[${e.mark}]`);var lr=e=>{let t=L(()=>te(e.style,import.meta.url),[e.style]);return h(I,null,t!==""&&(t instanceof URL?h("link",{rel:"stylesheet",href:t.href}):h("style",null,t)))};var ur=()=>h("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; } .candidates:not([data-os*="android"]):not([data-os*="ios"]) { font-size:11px; } .projects { margin-right: 4px; display: grid; grid-template-rows: repeat(4, min-content); grid-auto-flow: column; direction: rtl; } .projects:is([data-os*="android"], [data-os*="ios"]) > * { 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; }`);function*dr(e){if(!("nodes"in e))return;let t=0;function*r(o){for(let s of Array.isArray(o)?o:[o]){if(typeof s=="string"){t+=[...s].length;continue}switch(s.type){case"link":yield{whole:s.unit.whole,start:t},t+=[...s.unit.whole].length;break;case"indent":t+=[...s.unit.tag].length,yield*r(s.children);break;case"quote":case"deco":case"strong":yield*r(s.children);break;default:t+=[...s.unit.whole].length;break}}}yield*r(e.nodes)}var pr=(e,t)=>{if(t.type==="unlock"){if(!e.lock)return e;let{lock:c,...l}=e;return{...l}}if(e.lock)return e;switch(t.type){case"lock":{let{lock:c,...l}=e;return{lock:!0,...l}}case"enable":return e.type==="disabled"&&e.isManuallyDisabled?{type:"ready"}:e;case"disable":return e.type==="disabled"&&e.isManuallyDisabled?e:{type:"disabled",isManuallyDisabled:!0}}if(e.type==="disabled")return e.isManuallyDisabled||!t.lines?e:{type:"ready"};if(t.type==="cancel")return e.type==="completion"?{type:"cancelled",context:e.context}:e;if(!t.lines)return{type:"disabled"};let r=Math.min(t.range.start.char,t.range.end.char),o=Math.max(t.range.start.char,t.range.end.char),s=t.lines?t.range.start.line!==t.range.end.line?` `:[...t.lines[t.range.start.line].text].slice(r,o).join(""):"";if(co(t.lines[t.position.line],s)&&e.type!=="cancelled")return{type:"completion",context:"selection",query:s,start:r,position:t.position};if(s!=="")return e.type==="completion"?{type:"ready"}:e;let n=ao(t.lines[t.position.line],t.position.char);return n?e.type==="cancelled"&&e.context==="input"?e:e.type==="completion"||t.type==="lines:changed"?{type:"completion",context:"input",query:n.whole,start:n.start,position:t.position}:e.type==="ready"?e:{type:"ready"}:e.type==="ready"?e:{type:"ready"}},ao=(e,t)=>{for(let{whole:r,start:o}of dr(e))if(!(t<=o||o+[...r].length<=t))return{whole:r,start:o}},co=(e,t)=>!(t.trim()===""||t.includes(` `)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var fr=()=>{let[e,t]=z(pr,{type:"ready"}),r=lo(),o=L(()=>{let a;return u=>{a!==void 0&&clearTimeout(a),a=setTimeout(()=>{let{cursor:i,selection:f}=q();t({type:u,lines:r(),range:f.getRange({normalizeOrder:!0}),position:i.getPosition()})},u==="cursor:changed"?100:void 0)}},[]);w(()=>{let a=()=>{o("lines:changed")};return scrapbox.addListener("lines:changed",a),scrapbox.addListener("layout:changed",a),()=>{scrapbox.removeListener("lines:changed",a),scrapbox.removeListener("layout:changed",a)}},[]),w(()=>{let a=()=>{o("selection:changed")},u=Et();return u.addChangeListener(a),()=>u.removeChangeListener(a)},[]),w(()=>{if(e.context!=="input")return;let a=()=>{o("cursor:changed")},u=_t();return u.addChangeListener(a),()=>u.removeChangeListener(a)},[e.context]);let s=_(a=>t({type:a?"enable":"disable"}),[]),n=_(()=>t({type:"cancel"}),[]),c=_(a=>{t({type:"lock"});let u=a();if(u instanceof Promise)return u.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),l=_(async a=>{let u=r();if(!u)return;t({type:"lock"});let{cursor:i,selection:f}=q(),d=i.getPosition().line,p=u[d].text,m=await Promise.resolve(a(p));f.setRange({start:{line:d,char:0},end:{line:d,char:[...p].length}}),await bt(m),t({type:"unlock"}),t({type:"cancel"})},[]);return{state:e,setEnable:s,cancel:n,freezeUntil:c,confirmAfter:l}},lo=()=>{let e=O(scrapbox.Page.lines),t=O(!1);return w(()=>{let r=()=>{t.current=!0};return scrapbox.addListener("lines:changed",r),scrapbox.addListener("layout:changed",r),()=>{scrapbox.removeListener("lines:changed",r),scrapbox.removeListener("layout:changed",r)}},[]),_(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var mr={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},gr=e=>{let{state:t,setEnable:r,...o}=fr(),s=_(()=>r(!0),[]),n=_(()=>r(!1),[]),c=O({...mr,enable:s,disable:n}),[l,a]=D();w(()=>{Object.assign(c.current,t.type!=="completion"||!l?mr:l)},[t.type,l]);let{callback:u,style:i,...f}=e;return w(()=>u(c.current),[u]),h(I,null,h(ur,null),h(lr,{style:i}),t.type==="completion"&&h(cr,{callback:a,...t,...o,...f}))};var Ic=e=>{let t=document.createElement("div");t.dataset.userscriptName="scrapbox-select-suggestion";let r=t.attachShadow({mode:"open"});document.body.append(t);let{limit:o=5,debug:s=!1,mark:n={},style:c="",enableSelfProjectOnStart:l=!0}=e??{},a=new Set([...l?[scrapbox.Project.name]:[],...e?.projects??[scrapbox.Project.name]]);return Yt(s),new Promise(u=>_e(h(gr,{limit:o,projects:a,mark:n,style:c,callback:u,enableSelfProjectOnStart:l}),r))};export{Ic as setup};