script.js var se,h,Je,Xr,Q,Qe,Ze,Wr,ie={},et=[],Vr=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function q(e,t){for(var r in t)e[r]=t[r];return e}function tt(e){var t=e.parentNode;t&&t.removeChild(e)}function b(e,t,r){var n,s,o,a={};for(o in t)o=="key"?n=t[o]:o=="ref"?s=t[o]:a[o]=t[o];if(arguments.length>2&&(a.children=arguments.length>3?se.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(o in e.defaultProps)a[o]===void 0&&(a[o]=e.defaultProps[o]);return ae(e,a,n,s,null)}function ae(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??++Je};return s==null&&h.vnode!=null&&h.vnode(o),o}function I(e){return e.children}function ce(e,t){this.props=e,this.context=t}function Y(e,t){if(t==null)return e.__?Y(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"?Y(e):null}function rt(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 rt(e)}}function nt(e){(!e.__d&&(e.__d=!0)&&Q.push(e)&&!le.__r++||Ze!==h.debounceRendering)&&((Ze=h.debounceRendering)||Qe)(le)}function le(){for(var e;le.__r=Q.length;)e=Q.sort(function(t,r){return t.__v.__b-r.__v.__b}),Q=[],e.some(function(t){var r,n,s,o,a,i;t.__d&&(a=(o=(r=t).__v).__e,(i=r.__P)&&(n=[],(s=q({},o)).__v=o.__v+1,Te(i,o,s,r.__n,i.ownerSVGElement!==void 0,o.__h!=null?[a]:null,n,a??Y(o),o.__h),ut(n,o),o.__e!=a&&rt(o)))})}function ot(e,t,r,n,s,o,a,i,l,u){var c,m,d,p,f,y,g,x=n&&n.__k||et,w=x.length;for(r.__k=[],c=0;c<t.length;c++)if((p=r.__k[c]=(p=t[c])==null||typeof p=="boolean"?null:typeof p=="string"||typeof p=="number"||typeof p=="bigint"?ae(null,p,null,null,p):Array.isArray(p)?ae(I,{children:p},null,null,null):p.__b>0?ae(p.type,p.props,p.key,null,p.__v):p)!=null){if(p.__=r,p.__b=r.__b+1,(d=x[c])===null||d&&p.key==d.key&&p.type===d.type)x[c]=void 0;else for(m=0;m<w;m++){if((d=x[m])&&p.key==d.key&&p.type===d.type){x[m]=void 0;break}d=null}Te(e,p,d=d||ie,s,o,a,i,l,u),f=p.__e,(m=p.ref)&&d.ref!=m&&(g||(g=[]),d.ref&&g.push(d.ref,null,p),g.push(m,p.__c||f,p)),f!=null?(y==null&&(y=f),typeof p.type=="function"&&p.__k===d.__k?p.__d=l=st(p,l,e):l=it(e,p,d,x,f,l),typeof r.type=="function"&&(r.__d=l)):l&&d.__e==l&&l.parentNode!=e&&(l=Y(d))}for(r.__e=y,c=w;c--;)x[c]!=null&&(typeof r.type=="function"&&x[c].__e!=null&&x[c].__e==r.__d&&(r.__d=Y(n,c+1)),pt(x[c],x[c]));if(g)for(c=0;c<g.length;c++)dt(g[c],g[++c],g[++c])}function st(e,t,r){for(var n,s=e.__k,o=0;s&&o<s.length;o++)(n=s[o])&&(n.__=e,t=typeof n.type=="function"?st(n,t,r):it(r,n,n,s,n.__e,t));return t}function it(e,t,r,n,s,o){var a,i,l;if(t.__d!==void 0)a=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),a=null;else{for(i=o,l=0;(i=i.nextSibling)&&l<n.length;l+=2)if(i==s)break e;e.insertBefore(s,o),a=o}return a!==void 0?a:s.nextSibling}function Yr(e,t,r,n,s){var o;for(o in r)o==="children"||o==="key"||o in t||ue(e,o,null,r[o],n);for(o in t)s&&typeof t[o]!="function"||o==="children"||o==="key"||o==="value"||o==="checked"||r[o]===t[o]||ue(e,o,t[o],r[o],n)}function at(e,t,r){t[0]==="-"?e.setProperty(t,r):e[t]=r==null?"":typeof r!="number"||Vr.test(t)?r:r+"px"}function ue(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||at(e.style,t,"");if(r)for(t in r)n&&r[t]===n[t]||at(e.style,t,r[t])}else if(t[0]==="o"&&t[1]==="n")o=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=r,r?n||e.addEventListener(t,o?lt:ct,o):e.removeEventListener(t,o?lt:ct,o);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 ct(e){this.l[e.type+!1](h.event?h.event(e):e)}function lt(e){this.l[e.type+!0](h.event?h.event(e):e)}function Te(e,t,r,n,s,o,a,i,l){var u,c,m,d,p,f,y,g,x,w,P,v=t.type;if(t.constructor!==void 0)return null;r.__h!=null&&(l=r.__h,i=t.__e=r.__e,t.__h=null,o=[i]),(u=h.__b)&&u(t);try{e:if(typeof v=="function"){if(g=t.props,x=(u=v.contextType)&&n[u.__c],w=u?x?x.props.value:u.__:n,r.__c?y=(c=t.__c=r.__c).__=c.__E:("prototype"in v&&v.prototype.render?t.__c=c=new v(g,w):(t.__c=c=new ce(g,w),c.constructor=v,c.render=Jr),x&&x.sub(c),c.props=g,c.state||(c.state={}),c.context=w,c.__n=n,m=c.__d=!0,c.__h=[]),c.__s==null&&(c.__s=c.state),v.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=q({},c.__s)),q(c.__s,v.getDerivedStateFromProps(g,c.__s))),d=c.props,p=c.state,m)v.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if(v.getDerivedStateFromProps==null&&g!==d&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(g,w),!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(g,c.__s,w)===!1||t.__v===r.__v){c.props=g,c.state=c.__s,t.__v!==r.__v&&(c.__d=!1),c.__v=t,t.__e=r.__e,t.__k=r.__k,t.__k.forEach(function(M){M&&(M.__=t)}),c.__h.length&&a.push(c);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(g,c.__s,w),c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(d,p,f)})}c.context=w,c.props=g,c.state=c.__s,(u=h.__r)&&u(t),c.__d=!1,c.__v=t,c.__P=e,u=c.render(c.props,c.state,c.context),c.state=c.__s,c.getChildContext!=null&&(n=q(q({},n),c.getChildContext())),m||c.getSnapshotBeforeUpdate==null||(f=c.getSnapshotBeforeUpdate(d,p)),P=u!=null&&u.type===I&&u.key==null?u.props.children:u,ot(e,Array.isArray(P)?P:[P],t,r,n,s,o,a,i,l),c.base=t.__e,t.__h=null,c.__h.length&&a.push(c),y&&(c.__E=c.__=null),c.__e=!1}else o==null&&t.__v===r.__v?(t.__k=r.__k,t.__e=r.__e):t.__e=zr(r.__e,t,r,n,s,o,a,l);(u=h.diffed)&&u(t)}catch(M){t.__v=null,(l||o!=null)&&(t.__e=i,t.__h=!!l,o[o.indexOf(i)]=null),h.__e(M,t,r)}}function ut(e,t){h.__c&&h.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(n){n.call(r)})}catch(n){h.__e(n,r.__v)}})}function zr(e,t,r,n,s,o,a,i){var l,u,c,m=r.props,d=t.props,p=t.type,f=0;if(p==="svg"&&(s=!0),o!=null){for(;f<o.length;f++)if((l=o[f])&&"setAttribute"in l==!!p&&(p?l.localName===p:l.nodeType===3)){e=l,o[f]=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),o=null,i=!1}if(p===null)m===d||i&&e.data===d||(e.data=d);else{if(o=o&&se.call(e.childNodes),u=(m=r.props||ie).dangerouslySetInnerHTML,c=d.dangerouslySetInnerHTML,!i){if(o!=null)for(m={},f=0;f<e.attributes.length;f++)m[e.attributes[f].name]=e.attributes[f].value;(c||u)&&(c&&(u&&c.__html==u.__html||c.__html===e.innerHTML)||(e.innerHTML=c&&c.__html||""))}if(Yr(e,d,m,s,i),c)t.__k=[];else if(f=t.props.children,ot(e,Array.isArray(f)?f:[f],t,r,n,s&&p!=="foreignObject",o,a,o?o[0]:r.__k&&Y(r,0),i),o!=null)for(f=o.length;f--;)o[f]!=null&&tt(o[f]);i||("value"in d&&(f=d.value)!==void 0&&(f!==m.value||f!==e.value||p==="progress"&&!f)&&ue(e,"value",f,m.value,!1),"checked"in d&&(f=d.checked)!==void 0&&f!==e.checked&&ue(e,"checked",f,m.checked,!1))}return e}function dt(e,t,r){try{typeof e=="function"?e(t):e.current=t}catch(n){h.__e(n,r)}}function pt(e,t,r){var n,s;if(h.unmount&&h.unmount(e),(n=e.ref)&&(n.current&&n.current!==e.__e||dt(n,null,t)),(n=e.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){h.__e(o,t)}n.base=n.__P=null}if(n=e.__k)for(s=0;s<n.length;s++)n[s]&&pt(n[s],t,typeof e.type!="function");r||e.__e==null||tt(e.__e),e.__e=e.__d=void 0}function Jr(e,t,r){return this.constructor(e,r)}function Ce(e,t,r){var n,s,o;h.__&&h.__(e,t),s=(n=typeof r=="function")?null:r&&r.__k||t.__k,o=[],Te(t,e=(!n&&r||t).__k=b(I,null,[e]),s||ie,ie,t.ownerSVGElement!==void 0,!n&&r?[r]:s?null:t.firstChild?se.call(t.childNodes):null,o,!n&&r?r:s?s.__e:t.firstChild,n),ut(o,e)}se=et.slice,h={__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}},Je=0,Xr=function(e){return e!=null&&e.constructor===void 0},ce.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=q({},this.state),typeof e=="function"&&(e=e(q({},r),this.props)),e&&q(r,e),e!=null&&this.__v&&(t&&this.__h.push(t),nt(this))},ce.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),nt(this))},ce.prototype.render=I,Q=[],Qe=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,le.__r=0,Wr=0;var de,D,mt,Z=0,Se=[],ft=h.__b,gt=h.__r,ht=h.diffed,xt=h.__c,bt=h.unmount;function Pe(e,t){h.__h&&h.__h(D,e,Z||t),Z=0;var r=D.__H||(D.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function j(e){return Z=1,ee(wt,e)}function ee(e,t,r){var n=Pe(de++,2);return n.t=e,n.__c||(n.__=[r?r(t):wt(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 _(e,t){var r=Pe(de++,3);!h.__s&&Et(r.__H,t)&&(r.__=e,r.__H=t,D.__H.__h.push(r))}function A(e){return Z=5,C(function(){return{current:e}},[])}function C(e,t){var r=Pe(de++,7);return Et(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function k(e,t){return Z=8,C(function(){return e},t)}function Qr(){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(pe),e.__H.__h.forEach(Me),e.__H.__h=[]}catch(t){e.__H.__h=[],h.__e(t,e.__v)}}h.__b=function(e){D=null,ft&&ft(e)},h.__r=function(e){gt&>(e),de=0;var t=(D=e.__c).__H;t&&(t.__h.forEach(pe),t.__h.forEach(Me),t.__h=[])},h.diffed=function(e){ht&&ht(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(Se.push(t)!==1&&mt===h.requestAnimationFrame||((mt=h.requestAnimationFrame)||function(r){var n,s=function(){clearTimeout(o),yt&&cancelAnimationFrame(n),setTimeout(r)},o=setTimeout(s,100);yt&&(n=requestAnimationFrame(s))})(Qr)),D=null},h.__c=function(e,t){t.some(function(r){try{r.__h.forEach(pe),r.__h=r.__h.filter(function(n){return!n.__||Me(n)})}catch(n){t.some(function(s){s.__h&&(s.__h=[])}),t=[],h.__e(n,r.__v)}}),xt&&xt(e,t)},h.unmount=function(e){bt&&bt(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{pe(n)}catch(s){t=s}}),t&&h.__e(t,r.__v))};var yt=typeof requestAnimationFrame=="function";function pe(e){var t=D,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),D=t}function Me(e){var t=D;e.__c=e.__(),D=t}function Et(e,t){return!e||e.length!==t.length||t.some(function(r,n){return r!==e[n]})}function wt(e,t){return typeof t=="function"?t(e):t}var te=e=>e==null,me=e=>typeof e=="string",fe=e=>typeof e=="number";var kt=!1;scrapbox.addListener("lines:changed",()=>kt=!1);scrapbox.addListener("layout:changed",()=>kt=!1);var Lt=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError(`"${t}" must be HTMLDivElememt but actual is "${e}"`)};var vt=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError(`"${t}" must be HTMLTextAreaElement but actual is "${e}"`)};var Ie=()=>Zr(document.getElementsByClassName("lines").item(0),"div.lines");var K=()=>{let e=document.getElementById("text-input");if(!!e)return vt(e,"textarea#text-input"),e};var Zr=(e,t)=>{if(!!e)return Lt(e,t),e};var Re=()=>{let e=Ie();if(!e)throw Error("div.lines is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.lines must has the property whose name starts with "__reactFiber"');return e[t].return.stateNode.props.lines};var _t=e=>{if(te(e))return;if(fe(e))return en(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 en=e=>{if(te(e))return;if(fe(e))return Re()[e];let t=_t(e);return t?Re().find(r=>r.id===t):void 0},Tt=e=>{if(tn(e))return e;let t=_t(e);if(te(t))return t;let r=document.getElementById(`L${t}`);if(!te(r))return r},tn=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var rn=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index");var Ne=(e,t)=>{let r=Tt(e)?.getElementsByClassName?.(`c-${t}`)?.[0];return rn(r)?r:void 0};var De=e=>new Promise(t=>setTimeout(()=>t(),e));var Ct=async e=>{let t=K();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 De(1)};var je=e=>e.replaceAll(" ","_").toLowerCase(),St=e=>e.replaceAll("_"," "),re=e=>[...e].map((t,r)=>t===" "?"_":!an.includes(t)||r===e.length-1&&cn.includes(t)?encodeURIComponent(t):t).join(""),an='@$&+=:;",',cn=':;",';var W=()=>{let e=K();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 Pt=()=>W().cursor;var Mt=()=>W().selection;var It=({title:e,projects:t,selected:r,confirm:n})=>b("div",{className:`candidate${r?" selected":""}`},b(ln,{title:e,confirm:n}),t.map(s=>b(un,{project:s.name,title:e,mark:s.mark,confirm:s.confirm}))),ln=({title:e,confirm:t})=>b("a",{className:"button",tabIndex:0,role:"menuitem",href:`./${re(e)}`,onClick:Rt(t)},e),un=({project:e,title:t,mark:r,confirm:n})=>r===""?b(I,null):b("a",{className:"mark",tabIndex:0,href:`../${e}/${re(t)}`,onClick:Rt(n),title:`/${e}/${re(t)}`},r instanceof URL?b("img",{src:r.href}):`[${r}]`),Rt=e=>k(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var Nt=e=>{let[t,r]=j(-1);_(()=>r(-1),[e]);let n=k(i=>r(l=>i?.cyclic?(l+1)%e:Math.min(l+1,e)),[e]),s=k(i=>r(l=>l<0?e-1:i?.cyclic?(l+e-1)%e:Math.max(l-1,0)),[e]),o=k(()=>r(0),[]),a=k(()=>r(e-1),[e]);return{selectedIndex:t,next:n,prev:s,selectFirst:o,selectLast:a}};var Dt=e=>{let t=A(null),r=C(()=>{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?.(),a=Ne(e.line,e.char)?.getBoundingClientRect?.();return!a||!s?{}:{top:`${a.bottom-s.top}px`,left:`${a?.left??0-s.left}px`,right:`${s.right-(a?.left??0)}px`}},[t.current,e.line,e.char]);return{ref:t,...r}};var jt=(e,t)=>{let r=e.dist-t.dist;if(r!==0)return r;let n=e.matches.map(([a])=>a).sort(),s=t.matches.map(([a])=>a).sort();for(let a=0;a<n.length;a++){let i=n[a]-(s[a]??s.length);if(i!==0)return i}let o=e.title.length-t.title.length;return o!==0?o:t.updated-e.updated};var Bt=e=>{let t=new Map,r=[...e].reverse();{let a=1;for(let i of r){t.set(i,(t.get(i)??0)|a);let l=i.toLowerCase();t.set(l,(t.get(l)??0)|a);let u=i.toUpperCase();t.set(u,(t.get(u)??0)|a),a<<=1}}let n=r.length,s=~(~0<<n),o=1<<n-1;return a=>{let i=0,l=s,u=[...a].reverse(),c=[],m=u.length;c[m]=n;for(let d of u){let p=t.get(d)??0,f=p|i,y=(p&l)+l^l|p,g=i|~(y|l),x=l&y;c[m-1]=c[m]+((g&o)!=0?1:(x&o)!=0?-1:0),l=x<<1|~(f|g<<1),i=g<<1&f,m--}return c}};var dn=[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],Ht=e=>{let t=St(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=pn(s,n);return n}},pn=(e,t)=>{let r=[...e].length,n=dn[r],s=Bt(e);return t.flatMap(({title:o,dist:a,matches:i,...l})=>{i??=[],a??=0;let u=s(o).flatMap((m,d)=>m<=n&&i.every(([p,f])=>d+r<=p||f<d)?[[d,m]]:[]);if(u.length===0)return[];let c=u.reduce((m,[d,p])=>(m.dist<=p||(m.dist=p,m.start=d),m),{dist:r,start:0});return i.push([c.start,c.start+r-1]),[{title:o,dist:c.dist+a,matches:i,...l}]})};var R=!1,Ot=e=>{R=typeof e=="boolean"?e:new Set(e)},ge=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...n)=>r(`%c${e}`,"color: gray",...n)];case"log":case"info":case"debug":return[t,(...n)=>{R!==!0&&(!R||!R.has(e))||r(`%c${e}`,"color: gray",...n)}];case"assert":return[t,(n,...s)=>{R!==!0&&(!R||!R.has(e))||r(n,`%c${e}`,"color: gray",...s)}];case"time":case"timeEnd":return[t,n=>{R!==!0&&(!R||!R.has(e))||r(`${e} ${n}`)}];default:return[t,(...n)=>{if(!(R!==!0&&(!R||!R.has(e))))return r(...n)}]}}));var mn=ge("scrapbox-select-suggestion:useSearch.ts"),Ft=(e,t)=>{let[r,n]=ee(fn,{type:"query",source:t,query:e});_(()=>n({source:t}),[t]),_(()=>n({query:e}),[e]);let[s,o]=j(0),[a,i]=j([]),l=A(Promise.resolve());_(()=>{let m=!1;return l.current=(async()=>{await l.current;let d=[],p=gn(r.query,r.source,{chunk:5e3});if(r.type==="source"){for await(let[x]of p){if(m)return;d.push(...x)}o(1),i(d);return}let f,y=!1,g=0;for await(let[x,w]of p){if(m){clearTimeout(f);return}if(d.push(...x),g=w,o(g),x.length!==0){if(!y){i([...d]),y=!0;continue}f??=setTimeout(()=>{i([...d]),f=void 0},500)}}(f!==void 0||!y)&&(clearTimeout(f),i([...d]))})(),()=>m=!0},[r]);let[u,c]=C(()=>{let m=new Map,d=[];for(let p of a.sort(jt)){let f=p.metadata.map(({project:y})=>y);for(let y of f)m.set(y,(m.get(y)??0)+.5**p.dist);d.push({title:p.title,dist:p.dist,projects:f})}return[m,d]},[a]);return{projectScore:u,items:c,progress:s}},fn=(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*gn(e,t,r){let n=Ht(e);if(!n)return;let s=r?.chunk??1e3,o=Math.floor(t.length/s)+1,a=0,i=new Date;try{for(;a<o;a++)await new Promise(l=>requestAnimationFrame(l)),yield[n(t.slice(a*s,(a+1)*s)),(a+1)/o]}finally{let u=new Date().getTime()-i.getTime();mn.debug(`search ${(a/o*100).toPrecision(3)}% of the source for "${e}" in ${u}ms`)}}var Be="enableProjectsOnSuggestion",At=(e,t)=>{let[r,n]=j(he([...e],t)),s=k((o,a)=>{hn(o,a,e,t),n(he([...e],t))},[e,t.enableSelfProjectOnStart]);return _(()=>{let o=a=>{a.key===Be&&n(he([...e],t))};return addEventListener("storage",o),()=>removeEventListener("storage",o)},[e,t.enableSelfProjectOnStart]),{projects:r,set:s}},He=!0,he=(e,t)=>{try{let r=localStorage.getItem(Be);if(r===null)return xe(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)?He?n:n.filter(s=>s!==scrapbox.Project.name):He?[...n,scrapbox.Project.name]:n:(xe(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return xe(e),e}},hn=(e,t,r,n)=>{let s=he([...r],n);n.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(He=t),xe(t?[...s,e]:s.filter(o=>o!==e))},xe=e=>localStorage.setItem(Be,JSON.stringify(e));var Ut=()=>C(()=>document.documentElement.dataset.os??"",[]);var ne=(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 $t=({position:e,query:t,start:r,context:n,limit:s,enableSelfProjectOnStart:o,callback:a,projects:i,source:l,mark:u,confirmAfter:c,cancel:m,freezeUntil:d})=>{let{projectScore:p,items:f,progress:y}=Ft(n==="input"?t.slice(1,-1):t,l),{projects:g,set:x}=At(i,{enableSelfProjectOnStart:o}),{ref:w,top:P,left:v,right:M}=Dt({line:e.line,char:r}),B=Ut();return b(I,null,b(bn,{itemCount:f.length,...{enableProjects:g,projects:i,projectScore:p,freezeUntil:d,mark:u,top:P,right:M,set:x,os:B}}),b(xn,{divRef:w,...{start:r,confirmAfter:c,cancel:m,query:t,enableProjects:g,projects:i,items:f,top:P,left:v,progress:y,callback:a,limit:s,mark:u,os:B}}))},xn=({start:e,divRef:t,confirmAfter:r,cancel:n,query:s,enableProjects:o,projects:a,items:i,top:l,left:u,progress:c,callback:m,limit:d,mark:p,os:f})=>{let y=k((S,H)=>{let O=H?`[/${H}/${S}]`:`[${S}]`;r((ze,{line:Gr})=>[`${[...ze].slice(0,e).join("")}${O}${[...ze].slice(e+[...s].length).join("")}`,{line:Gr,char:e+[...O].length}])},[e,s]),g=C(()=>a.size>1||!a.has(scrapbox.Project.name),[a]),x=C(()=>{let S=[];for(let H of i){if(S.length===d)break;!H.projects.some(O=>o.includes(O))||S.push({title:H.title,projects:H.projects.flatMap(O=>o.includes(O)?[{name:O,mark:g?ne(p[O]??"",import.meta.url)||O[0]:"",confirm:()=>y(H.title,O)}]:[]),confirm:()=>y(H.title)})}return S},[o,g,i,d,p,y]),{selectedIndex:w,next:P,prev:v,selectLast:M,selectFirst:B}=Nt(x.length),X=k(()=>w===-1?!1:(x.at(w)?.confirm?.(),!0),[w,x]);_(()=>m(x.length===0?void 0:{selectNext:S=>(P(S),!0),selectPrev:S=>(v(S),!0),selectFirst:()=>(B(),!0),selectLast:()=>(M(),!0),confirm:X,cancel:()=>(n(),!0)}),[m,P,v,B,M,X]);let F=C(()=>x.length>0&&l!=null&&u!=null?{top:l,left:u}:{display:"none"},[x.length,l,u]);return b("div",{ref:t,className:"container candidates","data-os":f,style:F},x.map((S,H)=>b(It,{key:S.title,...S,selected:w===H})),i.length>d&&b("div",{className:"counter"},`${i.length-d} more links`),b("div",{className:"progress",style:`background: linear-gradient(to right, var(--select-suggest-border-color, #eee) ${(c*100).toPrecision(3)}%, transparent ${(c*100).toPrecision(3)}%)`}))},bn=({enableProjects:e,projects:t,projectScore:r,mark:n,itemCount:s,top:o,right:a,set:i,os:l,freezeUntil:u})=>{let c=C(()=>[...t].sort((d,p)=>(r.get(p)??0)-(r.get(d)??0)).flatMap(d=>r.has(d)?[{name:d,enable:e.includes(d),mark:ne(n[d]??"",import.meta.url)||d[0],score:r.get(d),onClick:()=>u(()=>{i(d,!e.includes(d)),K().focus()})}]:[]),[t,r,e,n]),m=C(()=>s>0&&o!=null&&a!=null&&t.size>1?{top:o,right:a}:{display:"none"},[o,a,s,t.size]);return b("div",{className:"container projects","data-os":l,style:m},c.map(d=>b(yn,{...d})))},yn=e=>b("div",{className:e.enable?"mark":"mark disabled","data-score":e.score.toPrecision(3),onClick:e.onClick,title:e.name},e.mark instanceof URL?b("img",{src:e.mark.href}):`[${e.mark}]`);var N=!1,Oe=e=>{N=typeof e=="boolean"?e:new Set(e)},z=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...n)=>r(`%c${e}`,"color: gray",...n)];case"log":case"info":case"debug":return[t,(...n)=>{N!==!0&&(!N||!N.has(e))||r(`%c${e}`,"color: gray",...n)}];case"assert":return[t,(n,...s)=>{N!==!0&&(!N||!N.has(e))||r(n,`%c${e}`,"color: gray",...s)}];case"time":case"timeEnd":return[t,n=>{N!==!0&&(!N||!N.has(e))||r(`${e} ${n}`)}];default:return[t,(...n)=>{if(!(N!==!0&&(!N||!N.has(e))))return r(...n)}]}}));var E=e=>{let{fetch:t=globalThis.fetch,hostName:r="scrapbox.io",...n}=e;return{fetch:t,hostName:r,...n}};var En=e=>typeof e=="object"&&e!==null,wn=e=>En(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,qt=e=>{try{let t=typeof e=="string"?JSON.parse(e):e;return wn(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};var J=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,J)}},T=async e=>{let t=e.clone(),r=await t.text(),n=qt(r);if(!n)throw new J(t);return{ok:!1,value:n}};var L=e=>`connect.sid=${e}`;var be=e=>e.replaceAll(" ","_").toLowerCase();var G=e=>[...e].map((t,r)=>t===" "?"_":!Ln.includes(t)||r===e.length-1&&vn.includes(t)?encodeURIComponent(t):t).join(""),Ln='@$&+=:;",',vn=':;",';var Kt=(e,t,r)=>{let{sid:n,hostName:s,followRename:o,projects:a}=E(r??{}),i=new URLSearchParams;i.append("followRename",`${o??!0}`);for(let u of a??[])i.append("projects",u);let l=`https://${s}/api/pages/${e}/${G(t)}?${i.toString()}`;return new Request(l,n?{headers:{Cookie:L(n)}}:void 0)},Gt=async e=>{if(!e.ok)return e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:T(e);let t=await e.json();return{ok:!0,value:t}},Fe=async(e,t,r)=>{let{fetch:n}=E(r??{}),s=Kt(e,t,r),o=await n(s);return await Gt(o)};Fe.toRequest=Kt;Fe.fromResponse=Gt;var Xt=(e,t)=>{let{sid:r,hostName:n,sort:s,limit:o,skip:a}=E(t??{}),i=new URLSearchParams;s!==void 0&&i.append("sort",s),o!==void 0&&i.append("limit",`${o}`),a!==void 0&&i.append("skip",`${a}`);let l=`https://${n}/api/pages/${e}?${i.toString()}`;return new Request(l,r?{headers:{Cookie:L(r)}}:void 0)},Wt=async e=>{if(!e.ok)return T(e);let t=await e.json();return{ok:!0,value:t}},Vt=async(e,t)=>{let{fetch:r}=E(t??{}),n=await r(Xt(e,t));return await Wt(n)};Vt.toRequest=Xt;Vt.fromResponse=Wt;var Yt=(e,t,r,n)=>{let{sid:s,hostName:o}=E(n??{}),a=`https://${o}/api/table/${e}/${G(t)}/${encodeURIComponent(r)}.csv`;return new Request(a,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."}}:T(e),Jt=async(e,t,r,n)=>{let{fetch:s}=E(n??{}),o=Yt(e,t,r,n),a=await s(o);return await zt(a)};Jt.toRequest=Yt;Jt.fromResponse=zt;var Qt=(e,t)=>{let{sid:r,hostName:n}=E(t??{});return new Request(`https://${n}/api/projects/${e}`,r?{headers:{Cookie:L(r)}}:void 0)},Zt=async e=>{if(!e.ok)return T(e);let t=await e.json();return{ok:!0,value:t}},oe=async(e,t)=>{let{fetch:r}=E(t??{}),n=Qt(e,t),s=await r(n);return Zt(s)};oe.toRequest=Qt;oe.fromResponse=Zt;var er=(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)},tr=async e=>{if(!e.ok)return T(e);let t=await e.json();return{ok:!0,value:t}},ye=async(e,t)=>{let{fetch:r}=E(t??{}),n=await r(er(e,t));return tr(n)};ye.toRequest=er;ye.fromResponse=tr;var rr=async(e,t)=>{let{sid:r,hostName:n,fetch:s,followingId:o}=E(t??{}),a=new Request(`https://${n}/api/pages/${e}/search/titles${o?`?followingId=${o}`:""}`,r?{headers:{Cookie:L(r)}}:void 0),i=await s(a);if(!i.ok)return i.status===422?{ok:!1,value:{name:"InvalidFollowingIdError",message:await i.text()}}:T(i);let l=await i.json();return{ok:!0,value:{pages:l,followingId:i.headers.get("X-following-id")??""}}};var Sc=new Map;var nr=(e,t,r,n)=>{let{sid:s,hostName:o}=E(n??{}),a=`https://${o}/api/code/${e}/${G(t)}/${G(r)}`;return new Request(a,s?{headers:{Cookie:L(s)}}:void 0)},or=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404&&e.headers.get("Content-Type")?.includes?.("text/plain")?{ok:!1,value:{name:"NotFoundError",message:"Code block is not found"}}:T(e),sr=async(e,t,r,n)=>{let{fetch:s}=E(n??{}),o=nr(e,t,r,n),a=await s(o);return await or(a)};sr.toRequest=nr;sr.fromResponse=or;var ir=new TextEncoder().encode("0123456789abcdef");function ar(e){let t=new Uint8Array(e.length*2);for(let r=0;r<t.length;r++){let n=e[r];t[r*2]=ir[n>>4],t[r*2+1]=ir[n&15]}return t}var cr="md5: `data` is invalid type",V=64,Ae=class{#e;#t;#r;#n;#o;#i;#s;#a;constructor(){this.#e=1732584193,this.#t=4023233417,this.#r=2562383102,this.#n=271733878,this.#o=new Uint8Array(V),this.#i=0,this.#s=0,this.#a=0}#l(t){let r=this.#s;r+=t,r>4294967295&&(this.#a+=1),this.#s=r>>>0}#c(t){let r=this.#e,n=this.#t,s=this.#r,o=this.#n,a=F=>t[F]|t[F+1]<<8|t[F+2]<<16|t[F+3]<<24,i=(F,S)=>F<<S|F>>>32-S,l=a(0),u=a(4),c=a(8),m=a(12),d=a(16),p=a(20),f=a(24),y=a(28),g=a(32),x=a(36),w=a(40),P=a(44),v=a(48),M=a(52),B=a(56),X=a(60);r=n+i(((s^o)&n^o)+r+l+3614090360,7),o=r+i(((n^s)&r^s)+o+u+3905402710,12),s=o+i(((r^n)&o^n)+s+c+606105819,17),n=s+i(((o^r)&s^r)+n+m+3250441966,22),r=n+i(((s^o)&n^o)+r+d+4118548399,7),o=r+i(((n^s)&r^s)+o+p+1200080426,12),s=o+i(((r^n)&o^n)+s+f+2821735955,17),n=s+i(((o^r)&s^r)+n+y+4249261313,22),r=n+i(((s^o)&n^o)+r+g+1770035416,7),o=r+i(((n^s)&r^s)+o+x+2336552879,12),s=o+i(((r^n)&o^n)+s+w+4294925233,17),n=s+i(((o^r)&s^r)+n+P+2304563134,22),r=n+i(((s^o)&n^o)+r+v+1804603682,7),o=r+i(((n^s)&r^s)+o+M+4254626195,12),s=o+i(((r^n)&o^n)+s+B+2792965006,17),n=s+i(((o^r)&s^r)+n+X+1236535329,22),r=n+i(((n^s)&o^s)+r+u+4129170786,5),o=r+i(((r^n)&s^n)+o+f+3225465664,9),s=o+i(((o^r)&n^r)+s+P+643717713,14),n=s+i(((s^o)&r^o)+n+l+3921069994,20),r=n+i(((n^s)&o^s)+r+p+3593408605,5),o=r+i(((r^n)&s^n)+o+w+38016083,9),s=o+i(((o^r)&n^r)+s+X+3634488961,14),n=s+i(((s^o)&r^o)+n+d+3889429448,20),r=n+i(((n^s)&o^s)+r+x+568446438,5),o=r+i(((r^n)&s^n)+o+B+3275163606,9),s=o+i(((o^r)&n^r)+s+m+4107603335,14),n=s+i(((s^o)&r^o)+n+g+1163531501,20),r=n+i(((n^s)&o^s)+r+M+2850285829,5),o=r+i(((r^n)&s^n)+o+c+4243563512,9),s=o+i(((o^r)&n^r)+s+y+1735328473,14),n=s+i(((s^o)&r^o)+n+v+2368359562,20),r=n+i((n^s^o)+r+p+4294588738,4),o=r+i((r^n^s)+o+g+2272392833,11),s=o+i((o^r^n)+s+P+1839030562,16),n=s+i((s^o^r)+n+B+4259657740,23),r=n+i((n^s^o)+r+u+2763975236,4),o=r+i((r^n^s)+o+d+1272893353,11),s=o+i((o^r^n)+s+y+4139469664,16),n=s+i((s^o^r)+n+w+3200236656,23),r=n+i((n^s^o)+r+M+681279174,4),o=r+i((r^n^s)+o+l+3936430074,11),s=o+i((o^r^n)+s+m+3572445317,16),n=s+i((s^o^r)+n+f+76029189,23),r=n+i((n^s^o)+r+x+3654602809,4),o=r+i((r^n^s)+o+v+3873151461,11),s=o+i((o^r^n)+s+X+530742520,16),n=s+i((s^o^r)+n+c+3299628645,23),r=n+i((s^(n|~o))+r+l+4096336452,6),o=r+i((n^(r|~s))+o+y+1126891415,10),s=o+i((r^(o|~n))+s+B+2878612391,15),n=s+i((o^(s|~r))+n+p+4237533241,21),r=n+i((s^(n|~o))+r+v+1700485571,6),o=r+i((n^(r|~s))+o+m+2399980690,10),s=o+i((r^(o|~n))+s+w+4293915773,15),n=s+i((o^(s|~r))+n+u+2240044497,21),r=n+i((s^(n|~o))+r+g+1873313359,6),o=r+i((n^(r|~s))+o+X+4264355552,10),s=o+i((r^(o|~n))+s+f+2734768916,15),n=s+i((o^(s|~r))+n+M+1309151649,21),r=n+i((s^(n|~o))+r+d+4149444226,6),o=r+i((n^(r|~s))+o+P+3174756917,10),s=o+i((r^(o|~n))+s+c+718787259,15),n=s+i((o^(s|~r))+n+x+3951481745,21),this.#e=this.#e+r>>>0,this.#t=this.#t+n>>>0,this.#r=this.#r+s>>>0,this.#n=this.#n+o>>>0}update(t){let r;if(typeof t=="string")r=new TextEncoder().encode(t);else if(typeof t=="object")if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))r=new Uint8Array(t);else throw new TypeError(cr);else throw new TypeError(cr);let n=this.#i,s=V-n;if(r.length<s)this.#o.set(r,n),n+=r.length;else{this.#o.set(r.slice(0,s),n),this.#c(this.#o);let o=s;for(;o+V<=r.length;)this.#c(r.slice(o,o+V)),o+=V;this.#o.fill(0).set(r.slice(o),0),n=r.length-o}return this.#i=n,this.#l(r.length),this}digest(){let t=V-this.#i;t<9&&(t+=V);let r=new Uint8Array(t);r[0]=128;let n=this.#s<<3,s=this.#a<<3|this.#s>>>29;r[r.length-8]=n&255,r[r.length-7]=n>>>8&255,r[r.length-6]=n>>>16&255,r[r.length-5]=n>>>24&255,r[r.length-4]=s&255,r[r.length-3]=s>>>8&255,r[r.length-2]=s>>>16&255,r[r.length-1]=s>>>24&255,this.update(r.buffer);let o=new ArrayBuffer(16),a=new DataView(o);return a.setUint32(0,this.#e,!0),a.setUint32(4,this.#t,!0),a.setUint32(8,this.#r,!0),a.setUint32(12,this.#n,!0),o}toString(t="hex"){let r=this.digest();switch(t){case"hex":return new TextDecoder().decode(ar(new Uint8Array(r)));case"base64":{let n=new Uint8Array(r),s="";for(let o=0;o<n.length;++o)s+=String.fromCharCode(n[o]);return btoa(s)}default:throw new Error("md5: invalid format")}}};var lr=!1;scrapbox.addListener("lines:changed",()=>lr=!1);scrapbox.addListener("layout:changed",()=>lr=!1);var dr=e=>{let[t,r,n,...s]=e;return{title:t,links:s,image:r,exists:n>=0,updated:Math.min(0,n)}},pr=e=>[e.title,e.image,e.exists?e.updated:-1,...e.links];var mr=e=>{let t=new Map;for(let r of e){let n=be(r.title);t.set(n,{title:r.title,image:r.image,updated:r.updated,links:r.links,exists:!0});for(let s of r.links){let o=be(s);t.has(o)||t.set(o,{title:s,updated:0,links:[],exists:!1})}}return[...t.values()].map(r=>pr(r))};var fr=z("scrapbox-storage:remote.ts"),gr=async e=>{let t,r=[],n=`download and create Links of "${e}"`;fr.time(n);do{let o=await rr(e,{followingId:t});if(!o.ok)return o;t=o.value.followingId,r.push(...o.value.pages)}while(t);let s=mr(r);return fr.timeEnd(n),{ok:!0,value:s}};async function*hr(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 ye(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 a=await oe(o);yield a.ok?{ok:!0,value:{...a.value,checked:n.get(o)??0}}:{ok:!1,value:{...a.value,project:o}}}}var $e=(e,t)=>t.some(r=>e instanceof r),xr,br;function Dn(){return xr||(xr=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function jn(){return br||(br=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var yr=new WeakMap,qe=new WeakMap,Er=new WeakMap,Ke=new WeakMap,we=new WeakMap;function Bn(e){let t=new Promise((r,n)=>{let s=()=>{e.removeEventListener("success",o),e.removeEventListener("error",a)},o=()=>{r(U(e.result)),s()},a=()=>{n(e.error),s()};e.addEventListener("success",o),e.addEventListener("error",a)});return t.then(r=>{r instanceof IDBCursor&&yr.set(r,e)}).catch(()=>{}),we.set(t,e),t}function Hn(e){if(qe.has(e))return;let t=new Promise((r,n)=>{let s=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",a),e.removeEventListener("abort",a)},o=()=>{r(),s()},a=()=>{n(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",o),e.addEventListener("error",a),e.addEventListener("abort",a)});qe.set(e,t)}var Ge={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return qe.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Er.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return U(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 wr(e){Ge=e(Ge)}function On(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(ke(this),t,...r);return Er.set(n,t.sort?t.sort():[t]),U(n)}:jn().includes(e)?function(...t){return e.apply(ke(this),t),U(yr.get(this))}:function(...t){return U(e.apply(ke(this),t))}}function Fn(e){return typeof e=="function"?On(e):(e instanceof IDBTransaction&&Hn(e),$e(e,Dn())?new Proxy(e,Ge):e)}function U(e){if(e instanceof IDBRequest)return Bn(e);if(Ke.has(e))return Ke.get(e);let t=Fn(e);return t!==e&&(Ke.set(e,t),we.set(t,e)),t}var ke=e=>we.get(e);function kr(e,t,{blocked:r,upgrade:n,blocking:s,terminated:o}={}){let a=indexedDB.open(e,t),i=U(a);return n&&a.addEventListener("upgradeneeded",l=>{n(U(a.result),l.oldVersion,l.newVersion,U(a.transaction),l)}),r&&a.addEventListener("blocked",l=>r(l.oldVersion,l.newVersion,l)),i.then(l=>{o&&l.addEventListener("close",()=>o()),s&&l.addEventListener("versionchange",u=>s(u.oldVersion,u.newVersion,u))}).catch(()=>{}),i}function Lr(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",n=>t(n.oldVersion,n)),U(r).then(()=>{})}var An=["get","getKey","getAll","getAllKeys","count"],Un=["put","add","delete","clear"],Xe=new Map;function vr(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Xe.get(t))return Xe.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,s=Un.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(s||An.includes(r)))return;let o=async function(a,...i){let l=this.transaction(a,s?"readwrite":"readonly"),u=l.store;return n&&(u=u.index(i.shift())),(await Promise.all([u[r](...i),s&&l.done]))[0]};return Xe.set(t,o),o}wr(e=>({...e,get:(t,r,n)=>vr(t,r)||e.get(t,r,n),has:(t,r)=>!!vr(t,r)||e.has(t,r)}));var $n=["continue","continuePrimaryKey","advance"],_r={},We=new WeakMap,Tr=new WeakMap,qn={get(e,t){if(!$n.includes(t))return e[t];let r=_r[t];return r||(r=_r[t]=function(...n){We.set(this,Tr.get(this)[t](...n))}),r}};async function*Kn(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,qn);for(Tr.set(r,t),we.set(r,ke(t));t;)yield r,t=await(We.get(r)||t.continue()),We.delete(r)}function Cr(e,t){return t===Symbol.asyncIterator&&$e(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&$e(e,[IDBIndex,IDBObjectStore])}wr(e=>({...e,get(t,r,n){return Cr(t,r)?Kn:e.get(t,r,n)},has(t,r){return Cr(t,r)||e.has(t,r)}}));var Sr=z("scrapbox-storage:db.ts"),Pr,Le=async()=>(Pr??=await kr("scrapbox-storage",1,{upgrade(e){Sr.time("update DB");for(let t of e.objectStoreNames)e.deleteObjectStore(t);e.createObjectStore("links",{keyPath:"project"}),e.createObjectStore("status",{keyPath:"project"}),Sr.timeEnd("update DB")}}),Pr),Mr=async e=>(await Le()).put("links",e);var ve=new Map,Ir=e=>{let t={type:"update",projects:e};Rr(t);let r=new BroadcastChannel(Nr);r.postMessage(t),r.close()},Rr=e=>{for(let t of new Set(e.projects.flatMap(r=>[...ve.get(r)??[]])))t?.(e)},Nr="scrapbox-storage-notify",Gn=new BroadcastChannel(Nr);Gn.addEventListener("message",e=>Rr(e.data));var Ve=(e,t)=>{for(let r of e){let n=ve.get(r)??new Set;n.add(t),ve.set(r,n)}return()=>{for(let r of e)ve.get(r)?.delete?.(t)}};var $=z("scrapbox-storage:mod.ts"),Dr=async(e,t)=>{let r=await Le(),n=[],s=[];try{{$.debug("check updates of links...");let i=r.transaction("status","readwrite");await Promise.all(e.map(async l=>{let u=await i.store.get(l);if(u?.isValid===!1)return;let c=u?.checked??0,m=new Date().getTime()/1e3;if(c+t>m||u?.updating&&c+600>m)return;let d={project:l,id:u?.id,isValid:!0,checked:c,updated:u?.updated??0,updating:!0};n.push(d),i.store.put(d)})),await i.done,$.debug(`checked. ${n.length} projects maybe need upgrade.`)}if(n.length===0)return[];let o=[],a=[];for await(let i of hr(n)){if(!i.ok)switch(s.push({project:i.value.project,isValid:!1}),i.value.name){case"NotFoundError":$.warn(`"${i.value.project}" is not found.`);continue;case"NotMemberError":$.warn(`You are not a member of "${i.value.project}".`);continue;case"NotLoggedInError":$.warn(`You are not a member of "${i.value.project}" or You are not logged in yet.`);continue}if(i.value.updated<i.value.checked)$.debug(`no updates in "${i.value.name}"`);else{let l=await gr(i.value.name);if(!l.ok)throw Error(`${l.value.name} ${l.value.message}`);let u={project:i.value.name,links:l.value};a.push(u),$.time(`write data of "${i.value.name}"`),await Mr(u),o.push(i.value.name),$.timeEnd(`write data of "${i.value.name}"`)}s.push({project:i.value.name,isValid:!0,id:i.value.id,checked:new Date().getTime()/1e3,updated:i.value.updated,updating:!1})}return o.length>0&&Ir(o),a}finally{let o=r.transaction("status","readwrite"),a=o.store;await Promise.all(s.map(i=>a.put(i))),await o.done}},jr=async e=>{let t=[],r=new Date;{let s=(await Le()).transaction("links","readonly");await Promise.all(e.map(async o=>{let a=await s.store.get(o);t.push(a??{project:o,links:[]})})),await s.done}let n=new Date().getTime()-r.getTime();return $.debug(`Read links of ${e.length} projects in ${n}ms`),t};Lr("userscript-links").catch(e=>console.error(e));var Ye=ge("scrapbox-select-suggestion:useSource.ts"),Br=e=>{let[t,r]=j([]),n=k(s=>{let o=new Date,a=new Map;for(let{project:u,links:c}of s)for(let m of c){let{title:d,updated:p,image:f}=dr(m),y=je(d),g=a.get(y);a.set(y,{title:g?.title??d,updated:Math.max(g?.updated??0,p),metadata:[...g?.metadata??[],{project:u,image:f}]})}let i=[...a.entries()].map(([u,c])=>({titleLc:u,...c})),l=new Date().getTime()-o.getTime();Ye.debug(`Compiled ${i.length} source in ${l}ms`),r(i)},[]);return _(()=>{let s=!1,o=async()=>{let m=await jr([...e]);s||n(m)};o();let a,i=new Set,l=Ve([...e],({projects:m})=>{for(let d of m)i.add(d);clearTimeout(a),a=setTimeout(()=>{Ye.debug(`Detect ${i.size} projects' update`),o(),i.clear()},1e4)}),u=async()=>{let m=await Dr([...e],600);m.length===0||s||(Ye.debug(`Detect ${m.length} projects' update`),o())};u();let c=setInterval(u,600*1e3);return()=>{s=!0,clearTimeout(a),clearInterval(c),l()}},[e]),t};var Hr=e=>{let t=C(()=>ne(e.style,import.meta.url),[e.style]);return b(I,null,t!==""&&(t instanceof URL?b("link",{rel:"stylesheet",href:t.href}):b("style",null,t)))};var Or=()=>b("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;
}
.progress[style] {
padding: unset;
border: unset;
height: 0.5px;
transition: background 0.1s;
}`);function*Fr(e){if(!("nodes"in e))return;let t=0;function*r(n){for(let s of Array.isArray(n)?n:[n]){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":case"quote":t+=[...s.unit.tag].length,yield*r(s.children);break;case"deco":t+=[...s.unit.deco].length+2,yield*r(s.children),t++;break;case"strong":t+=2,yield*r(s.children),t+=2;break;default:t+=[...s.unit.whole].length;break}}}yield*r(e.nodes)}var Ar=(e,t)=>{if(t.type==="unlock"){if(!e.lock)return e;let{lock:a,...i}=e;return{...i}}if(e.lock)return e;switch(t.type){case"lock":{let{lock:a,...i}=e;return{lock:!0,...i}}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),n=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,n).join(""):"";if(Wn(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 o=Xn(t.lines[t.position.line],t.position.char);return o?e.type==="cancelled"&&e.context==="input"?e:e.type==="completion"||t.type==="lines:changed"?{type:"completion",context:"input",query:o.whole,start:o.start,position:t.position}:e.type==="ready"?e:{type:"ready"}:e.type==="ready"?e:{type:"ready"}},Xn=(e,t)=>{for(let{whole:r,start:n}of Fr(e))if(!(t<=n||n+[...r].length<=t))return{whole:r,start:n}},Wn=(e,t)=>!(t.trim()===""||t.includes(`
`)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var Ur=()=>{let[e,t]=ee(Ar,{type:"ready"}),r=Vn(),n=C(()=>{let l;return u=>{l!==void 0&&clearTimeout(l),l=setTimeout(()=>{let{cursor:c,selection:m}=W();t({type:u,lines:r(),range:m.getRange({normalizeOrder:!0}),position:c.getPosition()})},u==="cursor:changed"?100:void 0)}},[]);_(()=>{let l=()=>{n("lines:changed")};return scrapbox.addListener("lines:changed",l),scrapbox.addListener("layout:changed",l),()=>{scrapbox.removeListener("lines:changed",l),scrapbox.removeListener("layout:changed",l)}},[]),_(()=>{let l=()=>{n("selection:changed")},u=Mt();return u.addChangeListener(l),()=>u.removeChangeListener(l)},[]),_(()=>{if(e.context!=="input")return;let l=()=>{n("cursor:changed")},u=Pt();return u.addChangeListener(l),()=>u.removeChangeListener(l)},[e.context]);let s=k(l=>t({type:l?"enable":"disable"}),[]),o=k(()=>t({type:"cancel"}),[]),a=k(l=>{t({type:"lock"});let u=l();if(u instanceof Promise)return u.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),i=k(async l=>{let u=r();if(!u)return;t({type:"lock"});let{cursor:c,selection:m}=W(),d=c.getPosition().line,p=u[d].text,[f,y]=l(p,c.getPosition());m.setRange({start:{line:d,char:0},end:{line:d,char:[...p].length}}),await Ct(f),c.setPosition(y),t({type:"unlock"}),t({type:"cancel"})},[]);return{state:e,setEnable:s,cancel:o,freezeUntil:a,confirmAfter:i}},Vn=()=>{let e=A(scrapbox.Page.lines),t=A(!1);return _(()=>{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)}},[]),k(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var $r={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},qr=e=>{let{state:t,setEnable:r,...n}=Ur(),s=k(()=>r(!0),[]),o=k(()=>r(!1),[]),a=A({...$r,enable:s,disable:o}),[i,l]=j();_(()=>{Object.assign(a.current,t.type!=="completion"||!i?$r:i)},[t.type,i]);let{callback:u,style:c,...m}=e;_(()=>u(a.current),[u]);let d=Br(m.projects);return b(I,null,b(Or,null),b(Hr,{style:c}),t.type==="completion"&&b($t,{callback:l,source:d,...t,...n,...m}))};var Kr=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:a="",enableSelfProjectOnStart:i=!0}=e??{},l=new Set([...i?[scrapbox.Project.name]:[],...e?.projects??[scrapbox.Project.name]]);return Ot(s),Oe(s),new Promise(u=>Ce(b(qr,{limit:n,projects:l,mark:o,style:a,callback:u,enableSelfProjectOnStart:i}),r))};var Yn=[scrapbox.Project.name,"yuyasurarin","villagepump","nishio","takker","shokai","discordwiki","work4ai"],_e=await Kr({limit:7,projects:Yn,mark:{yuyasurarin:"/api/pages/yuyasurarin/yuyasurarin/icon",villagepump:"/api/pages/villagepump/井戸端/icon",nishio:"/api/pages/nishio/nishio/icon",takker:"/api/pages/takker/takker/icon",shokai:"/api/pages/shokai/shokai/icon",discordwiki:"/api/pages/discordwiki/discord wiki/icon",work4ai:"/api/pages/work4ai/work4ai/icon"}});document.getElementById("text-input").addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey||e.altKey)){switch(e.key){case"Tab":{if(!(e.shiftKey?_e.selectPrev({cyclic:!0}):_e.selectNext({cyclic:!0})))return;break}case"Enter":{if(e.shiftKey||!_e.confirm())return;break}case"Escape":{if(e.shiftKey||!_e.cancel())return;break}default:return}e.preventDefault(),e.stopPropagation()}});