mod.jsvar ge,v,ut,Qr,W,st,lt,Pe,Me,Ce,Re,Zr,te={},dt=[],en=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ne=Array.isArray;function U(e,t){for(var r in t)e[r]=t[r];return e}function pt(e){var t=e.parentNode;t&&t.removeChild(e)}function g(e,t,r){var n,o,s,i={};for(s in t)s=="key"?n=t[s]:s=="ref"?o=t[s]:i[s]=t[s];if(arguments.length>2&&(i.children=arguments.length>3?ge.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(s in e.defaultProps)i[s]===void 0&&(i[s]=e.defaultProps[s]);return pe(e,i,n,o,null)}function pe(e,t,r,n,o){var s={type:e,props:t,key:r,ref:n,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:o??++ut,__i:-1,__u:0};return o==null&&v.vnode!=null&&v.vnode(s),s}function M(e){return e.children}function fe(e,t){this.props=e,this.context=t}function V(e,t){if(t==null)return e.__?V(e.__,e.__i+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"?V(e):null}function ft(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 ft(e)}}function it(e){(!e.__d&&(e.__d=!0)&&W.push(e)&&!me.__r++||st!==v.debounceRendering)&&((st=v.debounceRendering)||lt)(me)}function me(){var e,t,r,n,o,s,i,a;for(W.sort(Pe);e=W.shift();)e.__d&&(t=W.length,n=void 0,s=(o=(r=e).__v).__e,i=[],a=[],r.__P&&((n=U({},o)).__v=o.__v+1,v.vnode&&v.vnode(n),je(r.__P,n,o,r.__n,r.__P.namespaceURI,32&o.__u?[s]:null,i,s??V(o),!!(32&o.__u),a),n.__v=o.__v,n.__.__k[n.__i]=n,ht(i,n,a),n.__e!=s&&ft(n)),W.length>t&&W.sort(Pe));me.__r=0}function mt(e,t,r,n,o,s,i,a,u,l,d){var c,f,p,E,w,b=n&&n.__k||dt,m=t.length;for(r.__d=u,tn(r,t,b),u=r.__d,c=0;c<m;c++)(p=r.__k[c])!=null&&typeof p!="boolean"&&typeof p!="function"&&(f=p.__i===-1?te:b[p.__i]||te,p.__i=c,je(e,p,f,o,s,i,a,u,l,d),E=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&Oe(f.ref,null,p),d.push(p.ref,p.__c||E,p)),w==null&&E!=null&&(w=E),65536&p.__u||f.__k===p.__k?(u&&typeof p.type=="string"&&!e.contains(u)&&(u=V(f)),u=gt(p,u,e)):typeof p.type=="function"&&p.__d!==void 0?u=p.__d:E&&(u=E.nextSibling),p.__d=void 0,p.__u&=-196609);r.__d=u,r.__e=w}function tn(e,t,r){var n,o,s,i,a,u=t.length,l=r.length,d=l,c=0;for(e.__k=[],n=0;n<u;n++)i=n+c,(o=e.__k[n]=(o=t[n])==null||typeof o=="boolean"||typeof o=="function"?null:typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?pe(null,o,null,null,null):Ne(o)?pe(M,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?pe(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o)!=null?(o.__=e,o.__b=e.__b+1,a=rn(o,r,i,d),o.__i=a,s=null,a!==-1&&(d--,(s=r[a])&&(s.__u|=131072)),s==null||s.__v===null?(a==-1&&c--,typeof o.type!="function"&&(o.__u|=65536)):a!==i&&(a==i-1?c=a-i:a==i+1?c++:a>i?d>u-i?c+=a-i:c--:a<i&&c++,a!==n+c&&(o.__u|=65536))):(s=r[i])&&s.key==null&&s.__e&&!(131072&s.__u)&&(s.__e==e.__d&&(e.__d=V(s)),Ie(s,s,!1),r[i]=null,d--);if(d)for(n=0;n<l;n++)(s=r[n])!=null&&!(131072&s.__u)&&(s.__e==e.__d&&(e.__d=V(s)),Ie(s,s))}function gt(e,t,r){var n,o;if(typeof e.type=="function"){for(n=e.__k,o=0;n&&o<n.length;o++)n[o]&&(n[o].__=e,t=gt(n[o],t,r));return t}e.__e!=t&&(r.insertBefore(e.__e,t||null),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType===8);return t}function rn(e,t,r,n){var o=e.key,s=e.type,i=r-1,a=r+1,u=t[r];if(u===null||u&&o==u.key&&s===u.type&&!(131072&u.__u))return r;if(n>(u!=null&&!(131072&u.__u)?1:0))for(;i>=0||a<t.length;){if(i>=0){if((u=t[i])&&!(131072&u.__u)&&o==u.key&&s===u.type)return i;i--}if(a<t.length){if((u=t[a])&&!(131072&u.__u)&&o==u.key&&s===u.type)return a;a++}}return-1}function at(e,t,r){t[0]==="-"?e.setProperty(t,r??""):e[t]=r==null?"":typeof r!="number"||en.test(t)?r:r+"px"}function de(e,t,r,n,o){var s;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")s=t!==(t=t.replace(/(PointerCapture)$|Capture$/i,"$1")),t=t.toLowerCase()in e||t==="onFocusOut"||t==="onFocusIn"?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=r,r?n?r.u=n.u:(r.u=Me,e.addEventListener(t,s?Re:Ce,s)):e.removeEventListener(t,s?Re:Ce,s);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=r??"";break e}catch{}typeof r=="function"||(r==null||r===!1&&t[4]!=="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&r==1?"":r))}}function ct(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t.t==null)t.t=Me++;else if(t.t<r.u)return;return r(v.event?v.event(t):t)}}}function je(e,t,r,n,o,s,i,a,u,l){var d,c,f,p,E,w,b,m,y,H,B,G,$,Z,J,ee,h=t.type;if(t.constructor!==void 0)return null;128&r.__u&&(u=!!(32&r.__u),s=[a=t.__e=r.__e]),(d=v.__b)&&d(t);e:if(typeof h=="function")try{if(m=t.props,y="prototype"in h&&h.prototype.render,H=(d=h.contextType)&&n[d.__c],B=d?H?H.props.value:d.__:n,r.__c?b=(c=t.__c=r.__c).__=c.__E:(y?t.__c=c=new h(m,B):(t.__c=c=new fe(m,B),c.constructor=h,c.render=on),H&&H.sub(c),c.props=m,c.state||(c.state={}),c.context=B,c.__n=n,f=c.__d=!0,c.__h=[],c._sb=[]),y&&c.__s==null&&(c.__s=c.state),y&&h.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=U({},c.__s)),U(c.__s,h.getDerivedStateFromProps(m,c.__s))),p=c.props,E=c.state,c.__v=t,f)y&&h.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),y&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if(y&&h.getDerivedStateFromProps==null&&m!==p&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(m,B),!c.__e&&(c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(m,c.__s,B)===!1||t.__v===r.__v)){for(t.__v!==r.__v&&(c.props=m,c.state=c.__s,c.__d=!1),t.__e=r.__e,t.__k=r.__k,t.__k.forEach(function(C){C&&(C.__=t)}),G=0;G<c._sb.length;G++)c.__h.push(c._sb[G]);c._sb=[],c.__h.length&&i.push(c);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(m,c.__s,B),y&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(p,E,w)})}if(c.context=B,c.props=m,c.__P=e,c.__e=!1,$=v.__r,Z=0,y){for(c.state=c.__s,c.__d=!1,$&&$(t),d=c.render(c.props,c.state,c.context),J=0;J<c._sb.length;J++)c.__h.push(c._sb[J]);c._sb=[]}else do c.__d=!1,$&&$(t),d=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++Z<25);c.state=c.__s,c.getChildContext!=null&&(n=U(U({},n),c.getChildContext())),y&&!f&&c.getSnapshotBeforeUpdate!=null&&(w=c.getSnapshotBeforeUpdate(p,E)),mt(e,Ne(ee=d!=null&&d.type===M&&d.key==null?d.props.children:d)?ee:[ee],t,r,n,o,s,i,a,u,l),c.base=t.__e,t.__u&=-161,c.__h.length&&i.push(c),b&&(c.__E=c.__=null)}catch(C){t.__v=null,u||s!=null?(t.__e=a,t.__u|=u?160:32,s[s.indexOf(a)]=null):(t.__e=r.__e,t.__k=r.__k),v.__e(C,t,r)}else s==null&&t.__v===r.__v?(t.__k=r.__k,t.__e=r.__e):t.__e=nn(r.__e,t,r,n,o,s,i,u,l);(d=v.diffed)&&d(t)}function ht(e,t,r){t.__d=void 0;for(var n=0;n<r.length;n++)Oe(r[n],r[++n],r[++n]);v.__c&&v.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(s){s.call(o)})}catch(s){v.__e(s,o.__v)}})}function nn(e,t,r,n,o,s,i,a,u){var l,d,c,f,p,E,w,b=r.props,m=t.props,y=t.type;if(y==="svg"?o="http://www.w3.org/2000/svg":y==="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((p=s[l])&&"setAttribute"in p==!!y&&(y?p.localName===y:p.nodeType===3)){e=p,s[l]=null;break}}if(e==null){if(y===null)return document.createTextNode(m);e=document.createElementNS(o,y,m.is&&m),s=null,a=!1}if(y===null)b===m||a&&e.data===m||(e.data=m);else{if(s=s&&ge.call(e.childNodes),b=r.props||te,!a&&s!=null)for(b={},l=0;l<e.attributes.length;l++)b[(p=e.attributes[l]).name]=p.value;for(l in b)if(p=b[l],l!="children"){if(l=="dangerouslySetInnerHTML")c=p;else if(l!=="key"&&!(l in m)){if(l=="value"&&"defaultValue"in m||l=="checked"&&"defaultChecked"in m)continue;de(e,l,null,p,o)}}for(l in m)p=m[l],l=="children"?f=p:l=="dangerouslySetInnerHTML"?d=p:l=="value"?E=p:l=="checked"?w=p:l==="key"||a&&typeof p!="function"||b[l]===p||de(e,l,p,b[l],o);if(d)a||c&&(d.__html===c.__html||d.__html===e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(c&&(e.innerHTML=""),mt(e,Ne(f)?f:[f],t,r,n,y==="foreignObject"?"http://www.w3.org/1999/xhtml":o,s,i,s?s[0]:r.__k&&V(r,0),a,u),s!=null)for(l=s.length;l--;)s[l]!=null&&pt(s[l]);a||(l="value",E!==void 0&&(E!==e[l]||y==="progress"&&!E||y==="option"&&E!==b[l])&&de(e,l,E,b[l],o),l="checked",w!==void 0&&w!==e[l]&&de(e,l,w,b[l],o))}return e}function Oe(e,t,r){try{typeof e=="function"?e(t):e.current=t}catch(n){v.__e(n,r)}}function Ie(e,t,r){var n,o;if(v.unmount&&v.unmount(e),(n=e.ref)&&(n.current&&n.current!==e.__e||Oe(n,null,t)),(n=e.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(s){v.__e(s,t)}n.base=n.__P=null}if(n=e.__k)for(o=0;o<n.length;o++)n[o]&&Ie(n[o],t,r||typeof e.type!="function");r||e.__e==null||pt(e.__e),e.__c=e.__=e.__e=e.__d=void 0}function on(e,t,r){return this.constructor(e,r)}function De(e,t,r){var n,o,s,i;v.__&&v.__(e,t),o=(n=typeof r=="function")?null:r&&r.__k||t.__k,s=[],i=[],je(t,e=(!n&&r||t).__k=g(M,null,[e]),o||te,te,t.namespaceURI,!n&&r?[r]:o?null:t.firstChild?ge.call(t.childNodes):null,s,!n&&r?r:o?o.__e:t.firstChild,n,i),ht(s,e,i)}ge=dt.slice,v={__e:function(e,t,r,n){for(var o,s,i;t=t.__;)if((o=t.__c)&&!o.__)try{if((s=o.constructor)&&s.getDerivedStateFromError!=null&&(o.setState(s.getDerivedStateFromError(e)),i=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,n||{}),i=o.__d),i)return o.__E=o}catch(a){e=a}throw e}},ut=0,Qr=function(e){return e!=null&&e.constructor==null},fe.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=U({},this.state),typeof e=="function"&&(e=e(U({},r),this.props)),e&&U(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),it(this))},fe.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),it(this))},fe.prototype.render=M,W=[],lt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Pe=function(e,t){return e.__v.__b-t.__v.__b},me.__r=0,Me=0,Ce=ct(!1),Re=ct(!0),Zr=0;var re,k,Be,xt,ne=0,Lt=[],T=v,bt=T.__b,yt=T.__r,_t=T.diffed,Et=T.__c,vt=T.unmount,wt=T.__;function Fe(e,t){T.__h&&T.__h(k,e,ne||t),ne=0;var r=k.__H||(k.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function O(e){return ne=1,oe(St,e)}function oe(e,t,r){var n=Fe(re++,2);if(n.t=e,!n.__c&&(n.__=[r?r(t):St(void 0,t),function(a){var u=n.__N?n.__N[0]:n.__[0],l=n.t(u,a);u!==l&&(n.__N=[l,n.__[1]],n.__c.setState({}))}],n.__c=k,!k.u)){var o=function(a,u,l){if(!n.__c.__H)return!0;var d=n.__c.__H.__.filter(function(f){return!!f.__c});if(d.every(function(f){return!f.__N}))return!s||s.call(this,a,u,l);var c=!1;return d.forEach(function(f){if(f.__N){var p=f.__[0];f.__=f.__N,f.__N=void 0,p!==f.__[0]&&(c=!0)}}),!(!c&&n.__c.props===a)&&(!s||s.call(this,a,u,l))};k.u=!0;var s=k.shouldComponentUpdate,i=k.componentWillUpdate;k.componentWillUpdate=function(a,u,l){if(this.__e){var d=s;s=void 0,o(a,u,l),s=d}i&&i.call(this,a,u,l)},k.shouldComponentUpdate=o}return n.__N||n.__}function R(e,t){var r=Fe(re++,3);!T.__s&&Tt(r.__H,t)&&(r.__=e,r.i=t,k.__H.__h.push(r))}function se(e){return ne=5,P(function(){return{current:e}},[])}function P(e,t){var r=Fe(re++,7);return Tt(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function x(e,t){return ne=8,P(function(){return e},t)}function sn(){for(var e;e=Lt.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(he),e.__H.__h.forEach(Ae),e.__H.__h=[]}catch(t){e.__H.__h=[],T.__e(t,e.__v)}}T.__b=function(e){k=null,bt&&bt(e)},T.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),wt&&wt(e,t)},T.__r=function(e){yt&&yt(e),re=0;var t=(k=e.__c).__H;t&&(Be===k?(t.__h=[],k.__h=[],t.__.forEach(function(r){r.__N&&(r.__=r.__N),r.i=r.__N=void 0})):(t.__h.forEach(he),t.__h.forEach(Ae),t.__h=[],re=0)),Be=k},T.diffed=function(e){_t&&_t(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Lt.push(t)!==1&&xt===T.requestAnimationFrame||((xt=T.requestAnimationFrame)||an)(sn)),t.__H.__.forEach(function(r){r.i&&(r.__H=r.i),r.i=void 0})),Be=k=null},T.__c=function(e,t){t.some(function(r){try{r.__h.forEach(he),r.__h=r.__h.filter(function(n){return!n.__||Ae(n)})}catch(n){t.some(function(o){o.__h&&(o.__h=[])}),t=[],T.__e(n,r.__v)}}),Et&&Et(e,t)},T.unmount=function(e){vt&&vt(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{he(n)}catch(o){t=o}}),r.__H=void 0,t&&T.__e(t,r.__v))};var kt=typeof requestAnimationFrame=="function";function an(e){var t,r=function(){clearTimeout(n),kt&&cancelAnimationFrame(t),setTimeout(e)},n=setTimeout(r,100);kt&&(t=requestAnimationFrame(r))}function he(e){var t=k,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),k=t}function Ae(e){var t=k;e.__c=e.__(),k=t}function Tt(e,t){return!e||e.length!==t.length||t.some(function(r,n){return r!==e[n]})}function St(e,t){return typeof t=="function"?t(e):t}var ie=e=>e==null,xe=e=>typeof e=="string",be=e=>typeof e=="number";var cn=e=>typeof e=="object"&&e!==null,un=e=>cn(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 un(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};var Ct=!1;scrapbox.addListener("lines:changed",()=>Ct=!1);scrapbox.addListener("layout:changed",()=>Ct=!1);var Rt=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError(`"${t}" must be HTMLDivElememt but actual is "${e}"`)};var It=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError(`"${t}" must be HTMLTextAreaElement but actual is "${e}"`)};var He=()=>ln(document.getElementsByClassName("lines").item(0),"div.lines");var I=()=>{let e=document.getElementById("text-input");if(e)return It(e,"textarea#text-input"),e};var ln=(e,t)=>{if(e)return Rt(e,t),e};var $e=()=>{let e=He();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 Mt=e=>{if(ie(e))return;if(be(e))return pn(e)?.id;if(xe(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 pn=e=>{if(ie(e))return;if(be(e))return $e()[e];let t=Mt(e);return t?$e().find(r=>r.id===t):void 0},Nt=e=>{if(fn(e))return e;let t=Mt(e);if(ie(t))return t;let r=document.getElementById(`L${t}`);if(!ie(r))return r},fn=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var mn=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index");var Ue=(e,t)=>{let r=Nt(e)?.getElementsByClassName?.(`c-${t}`)?.[0];return mn(r)?r:void 0};var qe=e=>new Promise(t=>setTimeout(()=>t(),e));var jt=async e=>{let t=I();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 qe(1)};var z=e=>e.replaceAll(" ","_").toLowerCase(),Ot=e=>e.replaceAll("_"," "),D=e=>[...e].map((t,r)=>t===" "?"_":!bn.includes(t)||r===e.length-1&&yn.includes(t)?encodeURIComponent(t):t).join(""),bn='@$&+=:;",',yn=':;",';var X=()=>{let e=I();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(s=>s.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(s=>s.constructor.name==="Cursor");if(!n)throw Error('#text-input must has a "Cursor" store.');let o=r.find(s=>s.constructor.name==="Selection");if(!o)throw Error('#text-input must has a "Selection" store.');return{cursor:n,selection:o}};var Dt=()=>X().cursor;var Bt=()=>X().selection;var ae=e=>e===void 0?0:typeof e=="boolean"?Number(e):(e.capture?1:0)|(e.once?2:0)|(e.passive?4:0),At=e=>{if(e===0)return;let t={};return e&1&&(t.capture=!0),e&2&&(t.once=!0),e&4&&(t.passive=!0),t};var ye=new Map,Ke=new Map,Ft=(e,t,r)=>{let n=ye.get(e)??new Map,o=n.get(t)??new Set;if(o.has(ae(r)))return;if(o.add(ae(r)),n.set(t,o),ye.set(e,n),typeof r=="object"&&r?.once){let i=Ke.get(t)??new Map,a=ae(r),u=function(d){return _n(e,t,r),i.delete(a),t.call(this,d)};i.set(a,u),Ke.set(t,i);let l=I();if(!l)return;l.addEventListener(e,u,r)}let s=I();s&&s.addEventListener(e,t,r)};scrapbox.on("layout:changed",()=>{let e=I();if(e)for(let[t,r]of ye)for(let[n,o]of r)for(let s of o)e.addEventListener(t,n,At(s))});var _n=(e,t,r)=>{let n=ye.get(e);if(!n)return;let o=n.get(t);if(!o)return;let s=ae(r);if(o.delete(s),typeof r=="object"&&r?.once){let a=Ke.get(t);if(!a)return;let u=a.get(s);if(!u)return;let l=I();if(!l)return;l.removeEventListener(e,u,r),a.delete(s);return}let i=I();i&&i.removeEventListener(e,t,r)};var Ht=({title:e,projects:t,selected:r,confirm:n})=>g("div",{className:`candidate${r?" selected":""}`},g(En,{title:e,confirm:n}),t.map(o=>g(vn,{project:o.name,title:e,mark:o.mark,confirm:o.confirm}))),En=({title:e,confirm:t})=>g("a",{className:"button",tabIndex:0,role:"menuitem",href:`./${D(e)}`,onClick:$t(t)},e),vn=({project:e,title:t,mark:r,confirm:n})=>r===""?g(M,null):g("a",{className:"mark",tabIndex:0,href:`../${e}/${D(t)}`,onClick:$t(n),title:`/${e}/${D(t)}`},r instanceof URL?g("img",{src:r.href}):`[${r}]`),$t=e=>x(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var Ut=(e,t)=>{let[r,n]=O(null),o=x(u=>n(l=>{if(e.length===0)return null;if(l===null)return t(e[0]);let d=e.findIndex(c=>t(c)===l);return t(u?.cyclic?e[(d+1)%e.length]:e.at(d+1)??e[0])}),[e,t]),s=x(u=>n(l=>{if(e.length===0)return null;if(l===null)return t(e[e.length-1]);let d=e.findIndex(c=>t(c)===l);return d<0?t(e[e.length-1]):t(u?.cyclic?e[(d-1+e.length)%e.length]:e.at(d-1)??e[e.length-1])}),[e,t]),i=x(()=>n(e.length===0?null:t(e[0])),[e,t]),a=x(()=>n(e.length===0?null:t(e[e.length-1])),[e,t]);return{selectedId:r,next:o,prev:s,selectFirst:i,selectLast:a}};var qt=e=>{let[t,r]=O(null),n=P(()=>{let o=t?.getBoundingClientRect?.(),i=Ue(e.line,e.char)?.getBoundingClientRect?.();return!i||!o?{}:{top:`${i.bottom-o.top}px`,left:`${i?.left??0-o.left}px`,right:`${o.right-(i?.left??0)}px`}},[t,e.line,e.char]);return{updateStandardElement:r,...n}};var We="enableProjectsOnSuggestion",Kt=(e,t)=>{let[r,n]=O(_e([...e],t)),o=x((s,i)=>{wn(s,i,e,t),n(_e([...e],t))},[e,t.enableSelfProjectOnStart]);return R(()=>{let s=i=>{i.key===We&&n(_e([...e],t))};return addEventListener("storage",s),()=>removeEventListener("storage",s)},[e,t.enableSelfProjectOnStart]),{projects:r,set:o}},Ge=!0,_e=(e,t)=>{try{let r=localStorage.getItem(We);if(r===null)return Ee(e),e;let n=JSON.parse(r);return Array.isArray(n)&&n.every(o=>typeof o=="string")?!t.enableSelfProjectOnStart||!e.includes(scrapbox.Project.name)?n:n.includes(scrapbox.Project.name)?Ge?n:n.filter(o=>o!==scrapbox.Project.name):Ge?[...n,scrapbox.Project.name]:n:(Ee(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return Ee(e),e}},wn=(e,t,r,n)=>{let o=_e([...r],n);n.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(Ge=t),Ee(t?[...o,e]:o.filter(s=>s!==e))},Ee=e=>localStorage.setItem(We,JSON.stringify(e));var Gt=()=>P(()=>document.documentElement.dataset.os??"",[]);var ce=(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 Wt=({progress:e})=>g("div",{className:"progress",style:`background: linear-gradient(to right, var(--select-suggest-border-color, #eee) ${(e*100).toPrecision(3)}%, transparent ${(e*100).toPrecision(3)}%)`});var Xt=({position:e,start:t,enableSelfProjectOnStart:r,projects:n,...o})=>{let{projects:s,set:i}=Kt(n,{enableSelfProjectOnStart:r}),{updateStandardElement:a,top:u,left:l,right:d}=qt({line:e.line,char:t}),c=Gt();return g(M,null,g(Ln,{itemCount:o.items.length,enableProjects:s,projects:n,top:u,right:d,set:i,os:c,...o}),g(kn,{updateStandardElement:a,start:t,enableProjects:s,projects:n,top:u,left:l,os:c,...o}))},kn=({start:e,updateStandardElement:t,confirmAfter:r,cancel:n,query:o,enableProjects:s,projects:i,items:a,top:u,left:l,progress:d,callback:c,limit:f,mark:p,os:E})=>{let w=x((h,C,A)=>{let le=`[${C?`/${C}/${h}`:h}${A?.icon?".icon":""}]`;r((ot,{line:Yr})=>[`${[...ot].slice(0,e).join("")}${le}${[...ot].slice(e+[...o].length).join("")}`,{line:Yr,char:e+[...le].length}])},[e,o]),b=P(()=>i.size>1||!i.has(scrapbox.Project.name),[i]),m=P(()=>{let h=[];for(let C of a){if(h.length===f)break;C.projects.some(A=>s.includes(A))&&h.push({title:C.title,projects:C.projects.flatMap(A=>s.includes(A)?[{name:A,mark:b?ce(p[A]??"",import.meta.url)||A[0]:"",confirm:le=>w(C.title,A,le)}]:[]),confirm:A=>w(C.title,void 0,A)})}return h},[s,b,a,f,p,w]),{selectedId:y,next:H,prev:B,selectLast:G,selectFirst:$}=Ut(m,Vt),Z=x(h=>y===null?!1:(m.find(C=>Vt(C)===y)?.confirm?.(h),!0),[y,m]);R(()=>c(m.length===0?void 0:{selectNext:h=>(H(h),!0),selectPrev:h=>(B(h),!0),selectFirst:()=>($(),!0),selectLast:()=>(G(),!0),confirm:Z,cancel:()=>(n(),!0)}),[c,m.length,H,B,$,G,Z]);let J=P(()=>m.length>0&&u!=null&&l!=null?{top:u,left:l}:{display:"none"},[m.length,u,l]),ee=x(h=>{if(!h){t(h);return}let C=h.parentNode;if(!(C instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');t(C.host.parentElement)},[t]);return g("div",{ref:ee,className:"container candidates","data-os":E,style:J},m.map(h=>g(Ht,{key:h.title,...h,selected:y===h.title})),a.length>f&&g("div",{className:"counter"},`${a.length-f} more links`),g(Wt,{progress:d}))},Ln=({enableProjects:e,projects:t,projectScore:r,mark:n,itemCount:o,top:s,right:i,set:a,os:u,freezeUntil:l})=>{let d=P(()=>[...t].sort((f,p)=>(r.get(p)??0)-(r.get(f)??0)).flatMap(f=>r.has(f)?[{name:f,enable:e.includes(f),mark:ce(n[f]??"",import.meta.url)||f[0],score:r.get(f),onClick:()=>l(()=>{a(f,!e.includes(f)),I().focus()})}]:[]),[t,r,e,n]),c=P(()=>o>0&&s!=null&&i!=null&&t.size>1?{top:s,right:i}:{display:"none"},[s,i,o,t.size]);return g("div",{className:"container projects","data-os":u,style:c},d.map(f=>g(Tn,{key:f.name,...f})))},Tn=e=>g("div",{className:e.enable?"mark":"mark disabled","data-score":e.score.toPrecision(3),onClick:e.onClick,title:e.name},e.mark instanceof URL?g("img",{src:e.mark.href}):`[${e.mark}]`),Vt=e=>e.title;var N=!1,Ve=e=>{N=typeof e=="boolean"?e:new Set(e)},Y=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,...o)=>{N!==!0&&(!N||!N.has(e))||r(n,`%c${e}`,"color: gray",...o)}];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=>{let{fetch:t=globalThis.fetch,hostName:r="scrapbox.io",...n}=e;return{fetch:t,hostName:r,...n}};var ue=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"},S=async e=>{let t=e.clone(),r=await t.text(),n=Pt(r);if(!n)throw new ue(t);return{ok:!1,value:n}};var L=e=>`connect.sid=${e}`;var Jt=(e,t,r)=>{let{sid:n,hostName:o,followRename:s,projects:i}=_(r??{}),a=new URLSearchParams;a.append("followRename",`${s??!0}`);for(let l of i??[])a.append("projects",l);let u=`https://${o}/api/pages/${e}/${D(t)}?${a.toString()}`;return new Request(u,n?{headers:{Cookie:L(n)}}:void 0)},zt=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."}}:S(e),Xe=async(e,t,r)=>{let{fetch:n}=_(r??{}),o=Jt(e,t,r),s=await n(o);return await zt(s)};Xe.toRequest=Jt;Xe.fromResponse=zt;var Yt=(e,t)=>{let{sid:r,hostName:n,sort:o,limit:s,skip:i}=_(t??{}),a=new URLSearchParams;o!==void 0&&a.append("sort",o),s!==void 0&&a.append("limit",`${s}`),i!==void 0&&a.append("skip",`${i}`);let u=`https://${n}/api/pages/${e}?${a.toString()}`;return new Request(u,r?{headers:{Cookie:L(r)}}:void 0)},Qt=async e=>e.ok?{ok:!0,value:await e.json()}:S(e),Zt=async(e,t)=>{let{fetch:r}=_(t??{}),n=await r(Yt(e,t));return await Qt(n)};Zt.toRequest=Yt;Zt.fromResponse=Qt;var er=(e,t,r,n)=>{let{sid:o,hostName:s}=_(n??{}),i=`https://${s}/api/table/${e}/${D(t)}/${encodeURIComponent(r)}.csv`;return new Request(i,o?{headers:{Cookie:L(o)}}:void 0)},tr=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:S(e),rr=async(e,t,r,n)=>{let{fetch:o}=_(n??{}),s=er(e,t,r,n),i=await o(s);return await tr(i)};rr.toRequest=er;rr.fromResponse=tr;var nr=(e,t)=>{let{sid:r,hostName:n}=_(t??{});return new Request(`https://${n}/api/projects/${e}`,r?{headers:{Cookie:L(r)}}:void 0)},or=async e=>e.ok?{ok:!0,value:await e.json()}:S(e),ve=async(e,t)=>{let{fetch:r}=_(t??{}),n=nr(e,t),o=await r(n);return or(o)};ve.toRequest=nr;ve.fromResponse=or;var sr=(e,t)=>{let{sid:r,hostName:n}=_(t??{}),o=new URLSearchParams;for(let s of e)o.append("ids",s);return new Request(`https://${n}/api/projects?${o.toString()}`,r?{headers:{Cookie:L(r)}}:void 0)},ir=async e=>e.ok?{ok:!0,value:await e.json()}:S(e),we=async(e,t)=>{let{fetch:r}=_(t??{}),n=await r(sr(e,t));return ir(n)};we.toRequest=sr;we.fromResponse=ir;var ar=async(e,t)=>{let{sid:r,hostName:n,fetch:o,followingId:s}=_(t??{}),i=new Request(`https://${n}/api/pages/${e}/search/titles${s?`?followingId=${s}`:""}`,r?{headers:{Cookie:L(r)}}:void 0),a=await o(i);return a.ok?{ok:!0,value:{pages:await a.json(),followingId:a.headers.get("X-following-id")??""}}:a.status===422?{ok:!1,value:{name:"InvalidFollowingIdError",message:await a.text()}}:S(a)};var cr=(e,t,r,n)=>{let{sid:o,hostName:s}=_(n??{}),i=`https://${s}/api/code/${e}/${D(t)}/${D(r)}`;return new Request(i,o?{headers:{Cookie:L(o)}}:void 0)},ur=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"}}:S(e),lr=async(e,t,r,n)=>{let{fetch:o}=_(n??{}),s=cr(e,t,r,n),i=await o(s);return await ur(i)};lr.toRequest=cr;lr.fromResponse=ur;var Lc=new TextEncoder().encode("0123456789abcdef");var dr=e=>{let[t,r,n,...o]=e;return{title:t,links:o,image:r,exists:n>=0,updated:Math.min(0,n)}},pr=e=>[e.title,e.image,e.exists?e.updated:-1,...e.links];var fr=e=>{let t=new Map;for(let r of e){let n=z(r.title);t.set(n,{title:r.title,image:r.image,updated:r.updated,links:r.links,exists:!0});for(let o of r.links){let s=z(o);t.has(s)||t.set(s,{title:o,updated:0,links:[],exists:!1})}}return[...t.values()].map(r=>pr(r))};var mr=Y("scrapbox-storage:remote.ts"),gr=async e=>{let t,r=[],n=`download and create Links of "${e}"`;mr.time(n);do{let s=await ar(e,{followingId:t});if(!s.ok)return s;t=s.value.followingId,r.push(...s.value.pages)}while(t);let o=fr(r);return mr.timeEnd(n),{ok:!0,value:o}};async function*hr(e){let t=[],r=[],n=new Map;for(let s of e)s.id?t.push(s.id):r.push(s.project),n.set(s.project,s.checked);let o=await we(t);if(!o.ok)r=e.map(s=>s.project);else for(let s of o.value.projects)n.has(s.name)&&(yield{ok:!0,value:{...s,checked:n.get(s.name)??0}});for(let s of r){let i=await ve(s);yield i.ok?{ok:!0,value:{...i.value,checked:n.get(s)??0}}:{ok:!1,value:{...i.value,project:s}}}}var Ye=(e,t)=>t.some(r=>e instanceof r),xr,br;function Cn(){return xr||(xr=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Rn(){return br||(br=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Qe=new WeakMap,Je=new WeakMap,Le=new WeakMap;function In(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(q(e.result)),o()},i=()=>{n(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",i)});return Le.set(t,e),t}function Mn(e){if(Qe.has(e))return;let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{r(),o()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});Qe.set(e,t)}var Ze={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Qe.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return q(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 vr(e){Ze=e(Ze)}function Nn(e){return Rn().includes(e)?function(...t){return e.apply(et(this),t),q(this.request)}:function(...t){return q(e.apply(et(this),t))}}function jn(e){return typeof e=="function"?Nn(e):(e instanceof IDBTransaction&&Mn(e),Ye(e,Cn())?new Proxy(e,Ze):e)}function q(e){if(e instanceof IDBRequest)return In(e);if(Je.has(e))return Je.get(e);let t=jn(e);return t!==e&&(Je.set(e,t),Le.set(t,e)),t}var et=e=>Le.get(e);function wr(e,t,{blocked:r,upgrade:n,blocking:o,terminated:s}={}){let i=indexedDB.open(e,t),a=q(i);return n&&i.addEventListener("upgradeneeded",u=>{n(q(i.result),u.oldVersion,u.newVersion,q(i.transaction),u)}),r&&i.addEventListener("blocked",u=>r(u.oldVersion,u.newVersion,u)),a.then(u=>{s&&u.addEventListener("close",()=>s()),o&&u.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function kr(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",n=>t(n.oldVersion,n)),q(r).then(()=>{})}var On=["get","getKey","getAll","getAllKeys","count"],Dn=["put","add","delete","clear"],ze=new Map;function yr(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(ze.get(t))return ze.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=Dn.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||On.includes(r)))return;let s=async function(i,...a){let u=this.transaction(i,o?"readwrite":"readonly"),l=u.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),o&&u.done]))[0]};return ze.set(t,s),s}vr(e=>({...e,get:(t,r,n)=>yr(t,r)||e.get(t,r,n),has:(t,r)=>!!yr(t,r)||e.has(t,r)}));var Bn=["continue","continuePrimaryKey","advance"],_r={},tt=new WeakMap,Lr=new WeakMap,An={get(e,t){if(!Bn.includes(t))return e[t];let r=_r[t];return r||(r=_r[t]=function(...n){tt.set(this,Lr.get(this)[t](...n))}),r}};async function*Fn(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,An);for(Lr.set(r,t),Le.set(r,et(t));t;)yield r,t=await(tt.get(r)||t.continue()),tt.delete(r)}function Er(e,t){return t===Symbol.asyncIterator&&Ye(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Ye(e,[IDBIndex,IDBObjectStore])}vr(e=>({...e,get(t,r,n){return Er(t,r)?Fn:e.get(t,r,n)},has(t,r){return Er(t,r)||e.has(t,r)}}));var Tr=Y("scrapbox-storage:db.ts"),Sr,Te=async()=>(Sr??=await wr("scrapbox-storage",1,{upgrade(e){Tr.time("update DB");for(let t of e.objectStoreNames)e.deleteObjectStore(t);e.createObjectStore("links",{keyPath:"project"}),e.createObjectStore("status",{keyPath:"project"}),Tr.timeEnd("update DB")}}),Sr),Pr=async e=>(await Te()).put("links",e);var Se=new Map,Cr=e=>{let t={type:"update",projects:e};Rr(t);let r=new BroadcastChannel(Ir);r.postMessage(t),r.close()},Rr=e=>{for(let t of new Set(e.projects.flatMap(r=>[...Se.get(r)??[]])))t?.(e)},Ir="scrapbox-storage-notify",Hn=new BroadcastChannel(Ir);Hn.addEventListener("message",e=>Rr(e.data));var rt=(e,t)=>{for(let r of e){let n=Se.get(r)??new Set;n.add(t),Se.set(r,n)}return()=>{for(let r of e)Se.get(r)?.delete?.(t)}};var F=Y("scrapbox-storage:mod.ts"),Mr=async(e,t)=>{let r=await Te(),n=[],o=[];try{{F.debug("check updates of links...");let a=r.transaction("status","readwrite");await Promise.all(e.map(async u=>{let l=await a.store.get(u);if(l?.isValid===!1)return;let d=l?.checked??0,c=new Date().getTime()/1e3;if(d+t>c||l?.updating&&d+600>c)return;let f={project:u,id:l?.id,isValid:!0,checked:d,updated:l?.updated??0,updating:!0};n.push(f),a.store.put(f)})),await a.done,F.debug(`checked. ${n.length} projects maybe need upgrade.`)}if(n.length===0)return[];let s=[],i=[];for await(let a of hr(n)){if(!a.ok)switch(o.push({project:a.value.project,isValid:!1}),a.value.name){case"NotFoundError":F.warn(`"${a.value.project}" is not found.`);continue;case"NotMemberError":F.warn(`You are not a member of "${a.value.project}".`);continue;case"NotLoggedInError":F.warn(`You are not a member of "${a.value.project}" or You are not logged in yet.`);continue}if(a.value.updated<a.value.checked)F.debug(`no updates in "${a.value.name}"`);else{let u=await gr(a.value.name);if(!u.ok)throw Error(`${u.value.name} ${u.value.message}`);let l={project:a.value.name,links:u.value};i.push(l),F.time(`write data of "${a.value.name}"`),await Pr(l),s.push(a.value.name),F.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 s.length>0&&Cr(s),i}finally{let s=r.transaction("status","readwrite"),i=s.store;await Promise.all(o.map(a=>i.put(a))),await s.done}},Nr=async e=>{let t=[],r=new Date;{let o=(await Te()).transaction("links","readonly");await Promise.all(e.map(async s=>{let i=await o.store.get(s);t.push(i??{project:s,links:[]})})),await o.done}let n=new Date().getTime()-r.getTime();return F.debug(`Read links of ${e.length} projects in ${n}ms`),t};kr("userscript-links").catch(e=>console.error(e));var j=!1,jr=e=>{j=typeof e=="boolean"?e:new Set(e)},K=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)=>{j!==!0&&(!j||!j.has(e))||r(`%c${e}`,"color: gray",...n)}];case"assert":return[t,(n,...o)=>{j!==!0&&(!j||!j.has(e))||r(n,`%c${e}`,"color: gray",...o)}];case"time":case"timeEnd":return[t,n=>{j!==!0&&(!j||!j.has(e))||r(`${e} ${n}`)}];default:return[t,(...n)=>{if(!(j!==!0&&(!j||!j.has(e))))return r(...n)}]}}));var nt=K("scrapbox-select-suggestion:useSource.ts"),Or=e=>{let[t,r]=O([]),n=x(o=>{let s=new Date,i=new Map;for(let{project:l,links:d}of o)for(let c of d){let{title:f,updated:p,image:E}=dr(c),w=z(f),b=i.get(w);i.set(w,{title:b?.title??f,updated:Math.max(b?.updated??0,p),metadata:[...b?.metadata??[],{project:l,image:E}]})}let a=[...i.entries()].map(([l,d])=>({titleLc:l,...d})),u=new Date().getTime()-s.getTime();nt.debug(`Compiled ${a.length} source in ${u}ms`),nt.debug("Detect changes!"),r(a)},[]);return R(()=>{let o=!1,s=async()=>{let l=await Nr([...e]);o||n(l)};s();let i=rt([...e],({projects:l})=>{nt.debug(`Detect ${l.length} projects' update:`,l),s()}),a=()=>Mr([...e],600);a();let u=setInterval(a,600*1e3);return()=>{o=!0,clearInterval(u),i()}},[e]),t};var Dr=e=>{let t=P(()=>ce(e.style,import.meta.url),[e.style]);return g(M,null,t!==""&&(t instanceof URL?g("link",{rel:"stylesheet",href:t.href}):g("style",null,t)))};var Br=()=>g("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*Ar(e){if(!("nodes"in e))return;let t=0;function*r(n){for(let o of Array.isArray(n)?n:[n]){if(typeof o=="string"){t+=[...o].length;continue}switch(o.type){case"link":yield{whole:o.unit.whole,start:t},t+=[...o.unit.whole].length;break;case"indent":case"quote":t+=[...o.unit.tag].length,yield*r(o.children);break;case"deco":t+=[...o.unit.deco].length+2,yield*r(o.children),t++;break;case"strong":t+=2,yield*r(o.children),t+=2;break;default:t+=[...o.unit.whole].length;break}}}yield*r(e.nodes)}var Fr=(e,t)=>{if(t.type==="unlock"){if(!e.lock)return e;let{lock:i,...a}=e;return{...a}}if(e.lock)return e;switch(t.type){case"lock":{let{lock:i,...a}=e;return{lock:!0,...a}}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),o=t.lines?t.range.start.line!==t.range.end.line?`
`:[...t.lines[t.range.start.line].text].slice(r,n).join(""):"";if(Un(t.lines[t.position.line],o)&&e.type!=="cancelled")return{type:"completion",context:"selection",query:o,start:r,position:t.position};if(o!=="")return e.type==="completion"?{type:"ready"}:e;let s=$n(t.lines[t.position.line],t.position.char);return s?e.type==="cancelled"&&e.context==="input"?e:e.type==="completion"||t.type==="lines:changed"?{type:"completion",context:"input",query:s.whole,start:s.start,position:t.position}:e.type==="ready"?e:{type:"ready"}:e.type==="ready"?e:{type:"ready"}},$n=(e,t)=>{for(let{whole:r,start:n}of Ar(e))if(!(t<=n||n+[...r].length<=t))return{whole:r,start:n}},Un=(e,t)=>!(t.trim()===""||t.includes(`
`)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var Hr=()=>{let e=se(scrapbox.Page.lines),t=se(!1);return R(()=>{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)}},[]),x(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var qn=K("scrapbox-select-suggestion:useLifecycle.ts"),$r=()=>{let[e,t]=oe(Fr,{type:"ready"}),r=Hr(),n=P(()=>{let i;return a=>{i!==void 0&&clearTimeout(i),i=setTimeout(()=>{let{cursor:u,selection:l}=X();t({type:a,lines:r(),range:l.getRange({normalizeOrder:!0}),position:u.getPosition()})},a==="cursor:changed"?100:void 0)}},[]);R(()=>{let i=()=>{n("lines:changed")};scrapbox.addListener("lines:changed",i),scrapbox.addListener("layout:changed",i);let a=()=>{n("selection:changed")},u=Bt();return u.addChangeListener(a),()=>{scrapbox.removeListener("lines:changed",i),scrapbox.removeListener("layout:changed",i),u.removeChangeListener(a)}},[]),R(()=>{if(e.context!=="input")return;let i=()=>{n("cursor:changed")},a=Dt();return a.addChangeListener(i),()=>a.removeChangeListener(i)},[e.context]);let[o,s]=O(e);return o!==e&&(s(e),qn.debug("Detect changes",e)),{state:e,setEnable:x(i=>t({type:i?"enable":"disable"}),[]),cancel:x(()=>t({type:"cancel"}),[]),freezeUntil:x(i=>{t({type:"lock"});let a=i();if(a instanceof Promise)return a.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),confirmAfter:x(async i=>{let a=r();if(!a)return;t({type:"lock"});let{cursor:u,selection:l}=X(),d=u.getPosition().line,c=a[d].text,[f,p]=i(c,u.getPosition());l.setRange({start:{line:d,char:0},end:{line:d,char:[...c].length}}),await jt(f),u.setPosition(p),u.focus(),t({type:"unlock"}),t({type:"cancel"})},[])}};var Ur=(e,t)=>{let r=e.dist-t.dist;if(r!==0)return r;let n=e.matches.map(([i])=>i).sort(),o=t.matches.map(([i])=>i).sort();for(let i=0;i<n.length;i++){let a=n[i]-(o[i]??o.length);if(a!==0)return a}let s=e.title.length-t.title.length;return s!==0?s:t.updated-e.updated};var qr=e=>{let t=new Map,r=[...e].reverse();{let i=1;for(let a of r){t.set(a,(t.get(a)??0)|i);let u=a.toLowerCase();t.set(u,(t.get(u)??0)|i);let l=a.toUpperCase();t.set(l,(t.get(l)??0)|i),i<<=1}}let n=r.length,o=~(-1<<n),s=1<<n-1;return i=>{let a=0,u=o,l=[...i].reverse(),d=[],c=l.length;d[c]=n;for(let f of l){let p=t.get(f)??0,E=p|a,w=(p&u)+u^u|p,b=a|~(w|u),m=u&w;d[c-1]=d[c]+(b&s?1:m&s?-1:0),u=m<<1|~(E|b<<1),a=b<<1&E,c--}return d}};var Kn=[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],Kr=e=>{let t=Ot(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 o of t)n=Gn(o,n);return n}},Gn=(e,t)=>{let r=[...e].length,n=Kn[r],o=qr(e);return t.flatMap(({title:s,dist:i,matches:a,...u})=>{a??=[],i??=0;let l=o(s).flatMap((c,f)=>c<=n&&a.every(([p,E])=>f+r<=p||E<f)?[[f,c]]:[]);if(l.length===0)return[];let d=l.reduce((c,[f,p])=>(c.dist<=p||(c.dist=p,c.start=f),c),{dist:r,start:0});return a.push([d.start,d.start+r-1]),[{title:s,dist:d.dist+i,matches:a,...u}]})};var Wn=K("scrapbox-select-suggestion:cancelableSearch.ts");async function*Gr(e,t,r){let n=Kr(e);if(!n)return;let o=r?.chunk??1e3,s=Math.floor(t.length/o)+1,i=0,a=new Date;try{for(;i<s;i++)await new Promise(u=>requestAnimationFrame(u)),yield[n(t.slice(i*o,(i+1)*o)),(i+1)/s]}finally{let l=new Date().getTime()-a.getTime();Wn.debug(`search ${(i/s*100).toPrecision(3)}% of the source for "${e}" in ${l}ms`)}}function Wr(e,t){let r=null,n=null,o=(...s)=>{o.clear(),n=()=>{o.clear(),e.call(o,...s)},r=setTimeout(n,t)};return o.clear=()=>{typeof r=="number"&&(clearTimeout(r),r=null,n=null)},o.flush=()=>{n?.()},Object.defineProperty(o,"pending",{get:()=>typeof r=="number"}),o}var Vn=K("scrapbox-select-suggestion:useSearch.ts"),Vr=e=>{let t=x((o,s,i)=>{let a=!1,u=Gr(o,s,{chunk:5e3});return{run:async()=>{if(i){let f=[];for await(let[p]of u){if(a)return;f.push(...p)}n({progress:1,candidates:f});return}let l=Wr(n,500),d=!1,c=[];for await(let[f,p]of u){if(a){l.clear();return}c=[...c,...f],n({progress:p}),f.length!==0&&(l({progress:p,candidates:c}),d||(l.flush(),d=!0))}l({progress:1,candidates:c}),l.flush()},abort:()=>a=!0}},[]),[r,n]=oe(P(()=>Xn(t),[t]),{source:e});return[P(()=>{if(!Q(r))return;let[o,s]=Jn(r.candidates);return Vn.debug("Detect changes",{progress:r.progress,items:s}),{progress:r.progress,projectScore:o,items:s}},[r]),{search:x(o=>n({query:o}),[]),update:x(o=>n({source:o}),[])}]},Q=e=>"query"in e,Xn=e=>(t,r)=>{if("query"in r){let i=Q(t)?t.query:"";if(r.query===i)return t;let a=Q(t)?t.job:void 0;if(!r.query)return a?.abort?.(),{source:t.source};let{run:u,abort:l}=e(r.query,t.source,!1),d=a?.abort?.()?.then?.(u)??u();return{query:r.query,source:t.source,job:{done:d,abort:()=>(l(),d)},progress:0,candidates:!i||!Q(t)?[]:t.candidates}}if("source"in r){if(!Q(t))return r.source===t.source?t:r;let{source:i,job:a,...u}=t;if(r.source===i)return t;let{run:l,abort:d}=e(t.query,i,!1),c=a.done.then(l);return{source:r.source,job:{done:c,abort:()=>a.abort().then(()=>(d(),c))},...u}}if(!Q(t))return t;if(!r.candidates){let{progress:i,...a}=t;return i===r.progress?t:{progress:r.progress,...a}}let{candidates:n,progress:o,...s}=t;return n===r.candidates&&o===r.progress?t:{candidates:r.candidates??n,progress:r.progress,...s}},Jn=e=>{let t=new Map,r=[];for(let n of e.sort(Ur)){let o=n.metadata.map(({project:s})=>s);for(let s of o)t.set(s,(t.get(s)??0)+.5**n.dist);r.push({title:n.title,dist:n.dist,projects:o})}return[t,r]};var Xr=(e,t)=>{let r=se({...t});R(()=>(Object.assign(r.current,t),()=>{for(let n of Object.keys(t))delete r.current[n]}),[...Object.keys(t)].sort().map(n=>t[n])),R(()=>{e(r.current)},[e])};var zn={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},Jr=e=>{let t=Or(e.projects),[r,{update:n,search:o}]=Vr(t),{state:s,setEnable:i,...a}=$r();n(t),o(s.type==="completion"?s.context==="input"?s.query.slice(1,-1):s.query:"");let[u,l]=O(),{callback:d,style:c,...f}=e;return Xr(d,{enable:x(()=>i(!0),[]),disable:x(()=>i(!1),[]),...s.type!=="completion"||!u?zn:u}),g(M,null,g(Br,null),g(Dr,{style:c}),s.type==="completion"&&r&&g(Xt,{callback:l,...r,...s,...a,...f}))};var zr=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:o=!1,mark:s={},style:i="",enableSelfProjectOnStart:a=!0}=e??{},u=new Set([...a?[scrapbox.Project.name]:[],...e?.projects??[scrapbox.Project.name]]);return jr(o),Ve(o),new Promise(l=>De(g(Jr,{limit:n,projects:u,mark:s,style:i,callback:l,enableSelfProjectOnStart:a}),r))};var qd=async e=>{let t=await zr(e);Ft("keydown",r=>{if(!(r.metaKey||r.altKey)){switch(r.key){case"Tab":{if(r.ctrlKey||r.altKey||!(r.shiftKey?t.selectPrev?.({cyclic:!0}):t.selectNext?.({cyclic:!0})))return;break}case"Enter":{if(r.shiftKey||r.ctrlKey||r.altKey||!t.confirm?.())return;break}case"i":{if(r.shiftKey||!r.ctrlKey||r.altKey||!t.confirm?.({icon:!0}))return;break}case"Escape":{if(r.shiftKey||r.ctrlKey||r.altKey||!t.cancel?.())return;break}default:return}r.preventDefault(),r.stopPropagation()}})};export{qd as launch};