クリップボードからコードブロックへ貼り付けるUserScript
UserScript用コード
code:script.ts
await run();
code:script.js
var x=e=>{let{fetch:t=globalThis.fetch,hostName:n="scrapbox.io",...o}=e;return{fetch:t,hostName:n,...o}},ve=e=>typeof e=="object"&&e!==null,xe=e=>ve(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,Ee=e=>{try{let t=typeof e=="string"?JSON.parse(e):e;return xe(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}},D=class extends Error{name;constructor(e){super(${e.status} ${e.statusText} when fetching ${e.url}),this.response=e,this.name="UnexpectedResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,D)}response},I=async e=>{let t=e.clone(),n=await t.text(),o=Ee(n);if(!o)throw new D(t);return{ok:!1,value:o}},B=e=>connect.sid=${e},Ce=async e=>{let{sid:t,hostName:n,fetch:o}=x(e??{}),r=new Request(https://${n}/api/users/me,t?{headers:{Cookie:B(t)}}:void 0),i=await o(r);if(!i.ok)throw new D(i);return await i.json()},ke=e=>...e.map((t,n)=>t===" "?"_":!Ne.includes(t)||n===e.length-1&&Le.includes(t)?encodeURIComponent(t):t).join(""),Ne='@$&+=:;",',Le=':;",',J=(e,t,n)=>{let{sid:o,hostName:r,followRename:i,projects:a}=x(n??{}),l=new URLSearchParams;l.append("followRename",${i??!0});for(let c of a??[])l.append("projects",c);let s=https://${r}/api/pages/${e}/${ke(t)}?${l.toString()};return new Request(s,o?{headers:{Cookie:B(o)}}:void 0)},G=async e=>e.ok?{ok:!0,value:await e.json()}:e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:I(e),j=async(e,t,n)=>{let{fetch:o}=x(n??{}),r=J(e,t,n),i=await o(r);return await G(i)};j.toRequest=J,j.fromResponse=G;var X=(e,t)=>{let{sid:n,hostName:o,sort:r,limit:i,skip:a}=x(t??{}),l=new URLSearchParams;r!==void 0&&l.append("sort",r),i!==void 0&&l.append("limit",${i}),a!==void 0&&l.append("skip",${a});let s=https://${o}/api/pages/${e}?${l.toString()};return new Request(s,n?{headers:{Cookie:B(n)}}:void 0)},ee=async e=>e.ok?{ok:!0,value:await e.json()}:I(e),_=async(e,t)=>{let{fetch:n}=x(t??{}),o=await n(X(e,t));return await ee(o)};_.toRequest=X,_.fromResponse=ee;var te=(e,t)=>{let{sid:n,hostName:o}=x(t??{});return new Request(https://${o}/api/projects/${e},n?{headers:{Cookie:B(n)}}:void 0)},ne=async e=>e.ok?{ok:!0,value:await e.json()}:I(e),S=async(e,t)=>{let{fetch:n}=x(t??{}),o=te(e,t),r=await n(o);return ne(r)};S.toRequest=te,S.fromResponse=ne;var oe=(e,t)=>{let{sid:n,hostName:o}=x(t??{}),r=new URLSearchParams;for(let i of e)r.append("ids",i);return new Request(https://${o}/api/projects?${r.toString()},n?{headers:{Cookie:B(n)}}:void 0)},re=async e=>e.ok?{ok:!0,value:await e.json()}:I(e),W=async(e,t)=>{let{fetch:n}=x(t??{}),o=await n(oe(e,t));return re(o)};W.toRequest=oe,W.fromResponse=re;var R=async(e,t)=>{let n=await j(e,t);if(!n.ok)throw new Error(You have no privilege of editing "/${e}/${t}".);let{commitId:o,persistent:r,image:i,links:a,lines:l,id:s,pin:c}=n.value;return{commitId:o,pageId:s,persistent:r,image:i,links:a,pin:c,lines:l}},Oe="4.2.0";async function T(){let e=(await Be())("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"]});return await new Promise((t,n)=>{let o=r=>n(r);e.once("connect",()=>{e.off("disconnect",o),t()}),e.once("disconnect",o)}),e}function Be(){let e=https://cdnjs.cloudflare.com/ajax/libs/socket.io/${Oe}/socket.io.min.js;if(document.querySelector(script[src="${e}"]))return Promise.resolve(window.io);let t=document.createElement("script");return t.src=e,new Promise((n,o)=>{t.onload=()=>n(window.io),t.onerror=r=>o(r),document.head.append(t)})}function $e(e,t=9e4){function n(r,i){let a;return new Promise((l,s)=>{let c=u=>{clearTimeout(a),s(new Error(u))};e.emit(r,i,u=>{clearTimeout(a),e.off("disconnect",c),u.error&&s(new Error(JSON.stringify(u.error))),"data"in u?l(u?.data):l(void 0)}),a=setTimeout(()=>{e.off("disconnect",c),s(new Error(Timeout: exceeded ${t}ms))},t),e.once("disconnect",c)})}async function*o(...r){let i,a=()=>new Promise(s=>i=s),l=s=>{i?.(s)};for(let s of r)e.on(s,l);try{for(;;)yield await a()}finally{for(let s of r)e.off(s,l)}}return{request:n,response:o}}var A,ie=async()=>{if(A!==void 0)return A;let e=await Ce();if(e.isGuest)throw new Error("this script can only be executed by Logged in users");return A=e.id,A},M=new Map,Ae=async e=>{let t=M.get(e);if(t!==void 0)return t;let n=await S(e);if(!n.ok){let{name:r,message:i}=n.value;throw new Error(${r} ${i})}let{id:o}=n.value;return M.set(e,o),o},U=e=>e.padStart(8,"0"),Ie=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),n=Math.floor(16777214*Math.random()).toString(16);return${U(t).slice(-8)}${e.slice(-6)}0000${U(n)}},Y=async(e,t,n)=>t.length===0?{commitId:n.parentId}:await e("socket.io-request",{method:"commit",data:{kind:"page",...n,changes:t,cursor:null,freeze:!0}}),je=async(e,t,{project:n,title:o,retry:r=3,parentId:i,...a})=>{try{i=(await Y(e,t,{parentId:i,...a})).commitId}catch{console.log("Faild to push a commit. Retry after pulling new commits");for(let l=0;l<r;l++){let{commitId:s}=await R(n,o);i=s;try{i=(await Y(e,t,{parentId:i,...a})).commitId,console.log("Success in retrying");break}catch{continue}}throw Error("Faild to retry pushing.")}return i};async function Se(e,t,n,o,r,i){leta,l=await Promise.all(Ae(n),i??ie()),{request:s}=$e(r);return await je(s,e,{parentId:t.commitId,projectId:a,pageId:t.pageId,userId:l,project:n,title:o,retry:3})}function ae(e){let t=e.match(/^(\s*)code:(.+?)(\(.+\)){0,1}\s*$/);if(t===null)return null;let n=t2.trim(),o="";if(t3===void 0){let r=n.match(/.+\.(.*)$/);if(r===null)o=n;else{if(r1==="")return null;o=r1.trim()}}else o=t3.slice(1,-1);return{filename:n,lang:o,indent:t1.length}}function P(e){return e.titleLine.text.length-e.titleLine.text.trimStart().length+1}var z=async(e,t)=>{let n=await Fe(e),o=[],r={isCodeBlock:!1,filename:"",lang:"",indent:0};for(let i of n)if(r.isCodeBlock){if(Re(i.text,r.indent)===null){oo.length-1.nextLine=i,r.isCodeBlock=!1;continue}oo.length-1.bodyLines.push(i)}else{let a=ae(i.text);if(a===null){r.isCodeBlock=!1;continue}r={isCodeBlock:!0,...a},o.push({filename:r.filename,lang:r.lang,titleLine:i,bodyLines:[],nextLine:null,pageInfo:{projectName:e.project,pageTitle:e.title}})}return o.filter(i=>De(i,t))};async function Fe(e){return e.lines!==void 0?e.lines:(await R(e.project,e.title)).lines}function De(e,t){let n=(o,r)=>!o||o===r;return n(t?.filename,e.filename)&&n(t?.lang,e.lang)&&n(t?.titleLineId,e.titleLine.id)}function Re(e,t){let n=e.match(/^(\s*)(.*)$/);if(n===null||n.length<2)return null;let o=n1,r=n2;return o.length<=t?null:o.slice(o.length-t)+r}var Te=(e,t)=>{let n=e.length>t.length,o=n?t:e,r=n?e:t,i=o.length+1,a=o.length+r.length+3,l=new Array(a);l.fill(-1);let s=[];function c(d,b,E){let v=Math.max(b,E),$=v-d;for(;$<o.length&&v<r.length&&o$===rv;)++$,++v;return ld+i=s.length,s.push([{x:$,y:v},ld+(b>E?-1:1)+i]),v}let u=new Array(a);u.fill(-1);let y=-1,p=r.length-o.length;do{++y;for(let d=-y;d<=p-1;++d)ud+i=c(d,ud-1+i+1,ud+1+i);for(let d=p+y;d>=p+1;--d)ud+i=c(d,ud-1+i+1,ud+1+i);up+i=c(p,up-1+i+1,up+1+i)}while(up+i!==r.length);let f=[],g=lp+i;for(;g!==-1;)f.push(sg0),g=sg1;return{from:e,to:t,editDistance:p+y*2,buildSES:function*(){let d=0,b=0;for(let{x:E,y:v}of ze(f))for(;d<E||b<v;)v-E>b-d?(yield{value:rb,type:n?"deleted":"added"},++b):v-E<b-d?(yield{value:od,type:n?"added":"deleted"},++d):(yield{value:od,type:"common"},++d,++b)}}};function*Pe(e){let t=[],n=[];function*o(){if(t.length>n.length){for(let r=0;r<n.length;r++)yield V(tr,nr);for(let r=n.length;r<t.length;r++)yield tr}else{for(let r=0;r<t.length;r++)yield V(tr,nr);for(let r=t.length;r<n.length;r++)yield nr}t=[],n=[]}for(let r of e)switch(r.type){case"added":t.push(r);break;case"deleted":n.push(r);break;case"common":yield*o(),yield r;break}yield*o()}var V=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*ze(e){for(let t=e.length-1;t>=0;t--)yield et}function*Ke(e,t,{userId:n}){let{buildSES:o}=Te(e.map(({text:a})=>a),t),r=0,i=e0.id;for(let a of Pe(o())){switch(a.type){case"added":yield{_insert:i,lines:{id:Ie(n),text:a.value}};continue;case"deleted":yield{_delete:i,lines:-1};break;case"replaced":yield{_update:i,lines:{text:a.value}};break}r++,i=er?.id??"_end"}}var m=(e,{parseOnNested:t,parseOnQuoted:n,patterns:o})=>(r,i,a)=>{var l,s,c,u,y,p;if(!t&&i.nested)return(l=a?.())!==null&&l!==void 0?l:[];if(!n&&i.quoted)return(s=a?.())!==null&&s!==void 0?s:[];for(let f of o){let g=f.exec(r);if(g===null)continue;let d=r.substring(0,g.index),b=r.substring(g.index+((u=(c=g0)===null||c===void 0?void 0:c.length)!==null&&u!==void 0?u:0)),E=e((y=g0)!==null&&y!==void 0?y:"",i);return...N(d,i),...E,...N(b,i)}return(p=a?.())!==null&&p!==void 0?p:[]},h=e=>{type:"plain",raw:e,text:e},qe=m(h,{parseOnNested:!0,parseOnQuoted:!0,patterns:/^()(.*)()$/}),Qe=/^>.*$/,_e=(e,t)=>t.context==="table"?h(e,t):{type:"quote",raw:e,nodes:N(e.substring(1),{...t,quoted:!0})},We=m(_e,{parseOnNested:!1,parseOnQuoted:!1,patterns:Qe}),Me=/^\? .+$/,Ue=(e,t)=>t.context==="table"?h(e,t):{type:"helpfeel",raw:e,text:e.substring(2)},Ye=m(Ue,{parseOnNested:!1,parseOnQuoted:!1,patterns:Me}),Ve=/\[\[https?:\/\/^\s\]+\.(?:png|jpe?g|gif|svg)\]\]/i,Ze=/\[\[https?:\/\/(?:0-9a-z-+\.)?gyazo\.com\/0-9a-f{32}\]\]/,He=(e,t)=>{if(t.context==="table")return h(e,t);let n=e.substring(2,e.length-2),o=/^https?:\/\/(0-9a-z-\.)?gyazo\.com\/0-9a-f{32}$/.test(n);return[{type:"strongImage",raw:e,src:o?${n}/thumb/1000:n}]},Je=m(He,{parseOnNested:!1,parseOnQuoted:!0,patterns:Ve,Ze}),Ge=/\^[\*\.icon(?:\*1-9\d*)?\]/;function le(e){return(t,n)=>{if(e==="strongIcon"&&n.context==="table")return h(t,n);let o=e==="icon"?t.substring(1,t.length-1):t.substring(2,t.length-2),r=o.lastIndexOf(".icon"),i=o.substring(0,r),a=i.startsWith("/")?"root":"relative",l=o.substring(r+5,o.length),s=l.startsWith("*")?parseInt(l.substring(1),10):1;return new Array(s).fill({}).map(()=>({path:i,pathType:a,type:e,raw:t}))}}var Xe=le("icon"),et=m(Xe,{parseOnNested:!0,parseOnQuoted:!0,patterns:Ge}),tt=/\[\^[\*\.icon(?:\*\d+)?\]\]/,nt=le("strongIcon"),ot=m(nt,{parseOnNested:!1,parseOnQuoted:!0,patterns:tt}),rt=/\[\[(?:[^[]|\^[]).*?\]*\]\]/,it=(e,t)=>t.context==="table"?h(e,t):{type:"strong",raw:e,nodes:N(e.substring(2,e.length-2),{...t,nested:!0})},at=m(it,{parseOnNested:!1,parseOnQuoted:!0,patterns:rt}),lt=/\\$ .+? \/,st=/\[\$ [^\+\]/,ut=(e,t)=>t.context==="table"?h(e,t):{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ")?2:1))}],ct=m(ut,{parseOnNested:!1,parseOnQuoted:!0,patterns:lt,st}),dt=/\!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\+\]|^\])+\]/,pt=(e,t)=>{if(t.context==="table")return h(e,t);let n=e.indexOf(" "),o=e.substring(1,n),r=e.substring(n+1,e.length-1),i=new Set(o);if(i.has("*")){let a=o.split("*").length-1;i.delete("*"),i.add(*-${Math.min(a,10)})}return{type:"decoration",raw:e,rawDecos:o,decos:Array.from(i),nodes:N(r,{...t,nested:!0})}},ft=m(pt,{parseOnNested:!1,parseOnQuoted:!0,patterns:dt}),gt=/.*?/,mt=(e,t)=>t.context==="table"?h(e,t):{type:"code",raw:e,text:e.substring(1,e.length-1)},ht=m(mt,{parseOnNested:!1,parseOnQuoted:!0,patterns:gt}),yt=/^$% .+$/,bt=(e,t)=>{var n;if(t.context==="table")return h(e,t);let o=(n=e0)!==null&&n!==void 0?n:"",r=e.substring(2);return{type:"commandLine",raw:e,symbol:o,text:r}},wt=m(bt,{parseOnNested:!1,parseOnQuoted:!1,patterns:yt}),vt=/\\s+\/,xt=(e,t)=>t.context==="table"?h(e,t):{type:"blank",raw:e,text:e.substring(1,e.length-1)},Et=m(xt,{parseOnNested:!1,parseOnQuoted:!0,patterns:vt}),Ct=/\[https?:\/\/^\s\]+\.(?:png|jpe?g|gif|svg)(?:\?^\\s]+)?(?:\s+https?:\/\/^\s\]+)?\]/i,kt=/\[https?:\/\/^\s\]+\s+https?:\/\/^\s\]+\.(?:png|jpe?g|gif|svg)(?:\?^\\s]+)?\]/i,Nt=/\[https?:\/\/(?:0-9a-z-+\.)?gyazo\.com\/0-9a-f{32}(?:\/raw)?(?:\s+https?:\/\/^\s\]+)?\]/,Lt=/\[https?:\/\/^\s\]+\s+https?:\/\/(?:0-9a-z-+\.)?gyazo\.com\/0-9a-f{32}(?:\/raw)?\]/,Ot=e=>/^https?:\/\/^\s\]+\.(png|jpe?g|gif|svg)(\?^\\s]+)?$/i.test(e)||Bt(e),Bt=e=>/^https?:\/\/(0-9a-z-\.)?gyazo\.com\/0-9a-f{32}(\/raw)?$/.test(e),$t=(e,t)=>{if(t.context==="table")return h(e,t);let n=e.search(/\s/),o=n!==-1?e.substring(1,n):e.substring(1,e.length-1),r=n!==-1?e.substring(n,e.length-1).trimLeft():"",i,a=Ot(r)?r,o:o,r;return[{type:"image",raw:e,src:/^https?:\/\/(0-9a-z-\.)?gyazo\.com\/0-9a-f{32}$/.test(i)?${i}/thumb/1000:i,link:a}]},At=m($t,{parseOnNested:!0,parseOnQuoted:!0,patterns:Ct,kt,Nt,Lt}),It=/\[https?:\/\/^\s\]+\s+^\]*^\s\]/,jt=/\^[\*^\s\s+https?:\/\/^\s\]+\]/,St=/\[https?:\/\/^\s\]+\]/,Ft=/https?:\/\/^\s+/,Dt=(e,t)=>{if(t.context==="table")return h(e,t);let n=e.startsWith("")&&e.endsWith("")?e.substring(1,e.length-1):e,o=/^https?:\/\/^\s\]/.test(n),r=(o?/^https?:\/\/^\s\]+/:/https?:\/\/^\s\]+$/).exec(n);if(r?.0===void 0)return[];let i=o?n.substring(r0.length):n.substring(0,r.index-1);return[{type:"link",raw:e,pathType:"absolute",href:r0,content:i.trim()}]},Rt=m(Dt,{parseOnNested:!0,parseOnQuoted:!0,patterns:It,jt,St,Ft}),se=/\[(^\]*^\s)\s+(NS\d+(?:\.\d+)?,EW\d+(?:\.\d+)?(?:,Z\d+)?)\]/,ue=/\[(NS\d+(?:\.\d+)?,EW\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+(^\]*^\s))?\]/,Tt=e=>{lett="",n="",o=""=e.split(","),r=parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),i=parseFloat(n.replace(/^E/,"").replace(/^W/,"-")),a=/^Z\d+$/.test(o)?parseInt(o.replace(/^Z/,""),10):14;return{latitude:r,longitude:i,zoom:a}},Pt=(e,t)=>{var n;if(t.context==="table")return h(e,t);let o=(n=e.match(se))!==null&&n!==void 0?n:e.match(ue);if(o===null)return[];let r=e.startsWith("[N")||e.startsWith("[S"),,i="",a=""=r?o:[o0,o2,o1],{latitude:l,longitude:s,zoom:c}=Tt(i),u=a!==""?https://www.google.com/maps/place/${encodeURIComponent(a)}/@${l},${s},${c}z:https://www.google.com/maps/@${l},${s},${c}z;return{type:"googleMap",raw:e,latitude:l,longitude:s,zoom:c,place:a,url:u}},zt=m(Pt,{parseOnNested:!1,parseOnQuoted:!0,patterns:se,ue}),Kt=/\[\/?[^\]+\]/,qt=e=>{let t=e.substring(1,e.length-1);return{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}},Qt=m(qt,{parseOnNested:!0,parseOnQuoted:!0,patterns:Kt}),_t=/(?:^|\s)#\S+/,Wt=(e,t)=>{if(t.context==="table")return h(e,t);if(e.startsWith("#"))return{type:"hashTag",raw:e,href:e.substring(1)};let n=e.substring(0,1),o=e.substring(1);return...h(n,t),{type:"hashTag",raw:o,href:o.substring(1)}},Mt=m(Wt,{parseOnNested:!0,parseOnQuoted:!0,patterns:_t}),Ut=/^0-9+\. .*$/,Yt=(e,t)=>{if(t.context==="table")return h(e,t);let n=e.indexOf(" "),o=e.substring(0,n-1),r=parseInt(o,10),i=e.substring(n+1,e.length);return{type:"numberList",raw:e,rawNumber:o,number:r,nodes:N(i,{...t,nested:!0})}},Vt=m(Yt,{parseOnNested:!1,parseOnQuoted:!1,patterns:Ut}),Zt=(e,t,n)=>{var o;return e===""?[]:(o=n?.())!==null&&o!==void 0?o:[]},Ht=(...e)=>(t,n)=>e.reduceRight((o,r)=>()=>r(t,n,o),()=>qe(t,n))(),N=Ht(Zt,We,Ye,ht,wt,ct,Et,ft,Je,ot,at,At,Rt,et,zt,Qt,Mt,Vt);function ce(e){if(Array.isArray(e)||!(e instanceof Object))return!1;let t=e,{filename:n,content:o,lang:r}=t;return typeof n=="string"&&(typeof o=="string"||Array.isArray(o)&&(o.length==0||typeof o0=="string"))&&(typeof r=="string"||r===void 0)}var de=async(e,t,n)=>{let o={socket:n?.socket??await T(),debug:!1},r=n?{...o,...n}:o,{projectName:i,pageTitle:a}=t.pageInfo,l,s=await Promise.all(R(i,a),ie()),c=Jt(e),u=P(t),y=t.bodyLines.map(g=>({...g,text:g.text.slice(u)})),p=Ke(y,c,{userId:s}),f=[...Gt(...p,t)];if(ce(e)){let g=Xt(e,t);g&&f.push(g)}r.debug&&(console.log("%cvvv original code block vvv","color: limegreen;"),console.log(t),console.log("%cvvv new codes vvv","color: limegreen;"),console.log(e),console.log("%cvvv commits vvv","color: limegreen;"),console.log(f)),await Se(f,l,i,a,r.socket,s),n?.socket||r.socket.disconnect()};function Jt(e){let t=ce(e)?e.content:e;return Array.isArray(t)?t:t.split(` )}function*Gt(e,t){let{nextLine:n}=t,o=" ".repeat(P(t));for(let r of e)"_delete"in r?yield r:"_update"in r?yield{...r,lines:{...r.lines,text:o+r.lines.text}}:r._insert!="_end"||n===null?yield{...r,lines:{...r.lines,text:o+r.lines.text}}:yield{_insert:n.id,lines:{...r.lines,text:o+r.lines.text}}}function Xt(e,t){let n=t.titleLine.id,o=ae(t.titleLine.text);if(o&&e.filename.trim()==o.filename&&e.lang?.trim()==o.lang)return null;let r=(()=>{let a=e.filename.match(/.+\.(.*)$/);return a===null?e.filename:a[1]===""?"":a[1].trim()})(),i=e.filename+(e.lang&&e.lang!=r?(${e.lang}):"");return{_update:n,lines:{text:" ".repeat(P(t)-1)+"code:"+i}}}function en(){let e,t;return{promise:new Promise((n,o)=>{[e,t]=[n,o]}),resolve:e||(()=>{}),reject:t||(()=>{})}}function tn(e){let t="";for(let[n,o]of Object.entries(e))t+=pe(o,n);return t}function pe(e,t){let n="",o=[],r=[];for(let[i,a]of Object.entries(e))typeof a=="number"||typeof a=="string"?r.push({name:i,value:a}):o.push({name:i,style:a});if(r.length>0){let i=t,a="";for(let l of r)a+=${l.name}:${l.value};;n+=${i}{${a}}}if(o.length>0)for(let i of o){let a=nn(i.name,t);n+=pe(i.style,a)}return n}function nn(e,t){let n=t===void 0?"":t.trim(),o=e.trim();return o.includes("&")?o.replace("&",n):n+" "+o}var on={"#background":{position:"fixed","z-index":2e3,top:"40px",width:"100%",height:"100%","background-color":"hsl(0deg 0% 0% / 50%)"},".alert-bg":{position:"absolute",display:"block",width:"100%",height:"100%","background-color":"transparent"},".container":{position:"absolute",display:"flex","max-width":"50em",top:"60px",left:"1em",right:"1em",margin:"auto",padding:"1em 1.2em 1.2em","font-size":"15px",border:"1px solid black","border-radius":"10px","flex-direction":"column","background-color":"hsl(0deg 0% 100% / 85%)",".title":{margin:"0 0 5px","font-size":"1.2em","font-weight":900},".description":{margin:"0 0 5px"},".input-area":{textarea:{width:"100%",height:"5em"}},".button-area":{display:"flex","flex-direction":"row","justify-content":"space-evenly",button:{padding:"5px","min-width":"5em",border:"solid 2px hsl(0deg 0% 42%)","border-radius":"10px"}}}},w={OK:{label:"OK",useInputForm:!1,onClick:()=>({button:"OK"}),className:"button-OK"},CANCEL:{label:"\u30AD\u30E3\u30F3\u30BB\u30EB",useInputForm:!1,onClick:()=>({button:"CANCEL"}),className:"button-CANCEL"},YES:{label:"\u306F\u3044",useInputForm:!1,onClick:()=>({button:"YES"}),className:"button-YES"},NO:{label:"\u3044\u3044\u3048",useInputForm:!1,onClick:()=>({button:"NO"}),className:"button-NO"},ENTER:{label:"\u6C7A\u5B9A",useInputForm:!0,onClick:e=>({button:"ENTER",inputValue:e.InputValue}),className:"button-ENTER"}},fe=[];function rn(e){let{type:t,listener:n}=e;document.addEventListener(t,n),fe.push({type:t,listener:n})}function an(){for(let e of fe)document.removeEventListener(e.type,e.listener)}var ge="scrapbox-alert",K={OK:{buttons:[w.OK],priorityCancelButtonIndex:0},OK_CANCEL:{buttons:[w.OK,w.CANCEL],priorityCancelButtonIndex:1},YES_NO:{buttons:[w.YES,w.NO]},YES_NO_CANCEL:{buttons:[w.YES,w.NO,w.CANCEL],priorityCancelButtonIndex:2},ENTER:{buttons:[w.ENTER],priorityEnterButtonIndex:0},ENTER_CANCEL:{buttons:[w.ENTER,w.CANCEL],priorityEnterButtonIndex:0,priorityCancelButtonIndex:1}};async function me(e=K.OK,t,n,o){let{background:r,inputArea:i,buttonArea:a}=ln(t,n),l=document.createElement("textarea"),s=en();cn(e.buttons)&&(o&&(l.textContent=o),i.append(l));let c=un(e.buttons,s,l);a.append(...c);let u=e.priorityEnterButtonIndex?e.priorityEnterButtonIndex:0,y=c[u],p=e.priorityCancelButtonIndex?c[e.priorityCancelButtonIndex]:void 0;return l.addEventListener("keydown",f=>{f.key==="Enter"&&f.ctrlKey&&!f.shiftKey&&!f.altKey&&!f.metaKey&&y.click()}),r.onclick=()=>{p&&p.click()},p&&rn({type:"keydown",listener:f=>{f.key==="Escape"&&!f.ctrlKey&&!f.shiftKey&&!f.altKey&&!f.metaKey&&p.click()}}),s.promise}function ln(e,t){let n=document.createElement("div");n.id=ge,document.body.append(n);let o=n.attachShadow({mode:"open"}),r=document.createElement("div");r.id="background";let i=document.createElement("style");i.textContent=tn(on);let a=document.createElement("div");a.className="alert-bg";let l=document.createElement("div");l.className="container";let s=document.createElement("p");s.className="title",s.textContent=e||"";let c=document.createElement("div");if(c.className="description",t){let p=t.split(
);for(let f of p){let g=document.createElement("span");g.textContent=f;let d=document.createElement("br");c.append(g,d)}}let u=document.createElement("div");u.className="input-area";let y=document.createElement("div");return y.className="button-area",l.append(s,c,u,y),r.append(a,l,i),o.append(r),{background:a,inputArea:u,buttonArea:y}}function sn(){let e=document.getElementById(ge);e!==null&&(an(),e.remove())}function un(e,t,n){let o=[];for(let r of e){let i=document.createElement("button");i.textContent=r.label,r.className&&i.classList.add(r.className),i.onclick=()=>{function a(){return r.useInputForm?(console.log(textContent: ${n?.value}),n?.value?r.onClick({InputValue:n?.value}):r.onClick({InputValue:""})):r.onClick(void 0)}t.resolve(a()),sn()},o.push(i)}return o}function cn(e){for(let t of e)if(t.useInputForm)return!0;return!1}var L=[],O;function dn(e){L.push(e),O===void 0&&gn()}async function q(){if(L.length<=0)return;let e=[{cursorLineId:fn()}],t=[];for(let n of L)t.push(n(...e));await Promise.all(t)}function pn(){for(;L.length>0;)L.shift()}function fn(){let e=document.querySelector(".page .lines")?.children;if(e===void 0)return null;for(let t=0;t<e.length;t++){let n=e[t];if(n instanceof HTMLDivElement){for(let o of n.classList)if(o=="cursor-line")return n.id.slice(1)}}return null}function gn(){let e=document.querySelector("#editor .cursor");if(e==null||!(e instanceof HTMLElement))return;let t={attributes:!0};O=new MutationObserver(q),O.observe(e,t),scrapbox.on("project:changed",mn)}function mn(){pn(),O!==void 0&&O.disconnect()}var he=HTMLSpanElement,C=[],ye=[],Z=!1;async function hn(e,t){let n=Array.isArray(e)?e:[e],{titleLine:o,pageInfo:r}=t;if(r.pageTitle!=scrapbox.Page.title||r.projectName!=scrapbox.Project.name)return;console.debug("attachedCodeBlocks: %o",C);let i=C.find(a=>a.codeBlock.titleLine.id==o.id);if(console.debug("attached: %o",i),i===void 0){C.push({codeBlock:t,buttons:n});return}for(let a of n){let l=i.buttons.findIndex(s=>s.title==a.title);l<0?i.buttons.push(a):i.buttons[l]=a}await be()}async function yn(e){let t=Array.isArray(e)?e:[e];ye.push(...t),await be()}function bn(e,t){let n=Array.isArray(e)?e:[e],o=C.find(r=>r.codeBlock.titleLine.id==t.titleLine.id);o!==void 0&&(o.buttons=o.buttons.filter(r=>{n.some(i=>{r.title==i.title})}))}async function be(){Z||(dn(e=>{for(let{codeBlock:t,buttons:n}of C){let o=[...ye,...n],r=t.titleLine.id,i=wn(r);if(i!==null){if(e.cursorLineId!=r){En(o,i);continue}xn(o,i,t)}}}),Z=!0),await H(),scrapbox.on("lines:changed",H)}async function H(){scrapbox.Page.title!==null&&(C=(await z({project:scrapbox.Project.name,title:scrapbox.Page.title,lines:scrapbox.Page.lines})).map(e=>C.find(t=>t.codeBlock.titleLine.id==e.titleLine.id)??{codeBlock:e,buttons:[]}))}function wn(e){let t=#L${e} .code-block .code-block-start .tool-buttons;return document.querySelector(t)}function vn(e,t){let n=[];for(let o of e){let r=document.createElement("span");r.title=o.title,r.classList.add("button",o.title.toLowerCase()),r.onclick=a=>o.onClick(a,t);let i=document.createElement("i");i.classList.add(...o.iconClass),r.append(i),n.push(r)}return n}function xn(e,t,n){let o=t.children;for(let r of e)Array(...o).some(i=>i instanceof he?i.title==r.title:!1)||t.append(...vn([r],n))}function En(e,t){let n=t.children,o=[];for(let r of n)if(r instanceof he)for(let i of e)r.title==i.title&&o.push(r);o.forEach(r=>r.remove())}var k=[],Q,F=!1,Cn={title:"Paste",iconClass:["fa-regular","fa-paste"],onClick:async(e,t)=>{if(e.preventDefault(),scrapbox.Page.title===null)return;let n=(await navigator.clipboard.readText().catch(async()=>{await me(K.OK,"\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u5185\u306E\u30C6\u30AD\u30B9\u30C8\u306E\u53D6\u5F97\u306B\u5931\u6557\u3057\u307E\u3057\u305F","\u30D6\u30E9\u30A6\u30B6\u306E\u6A29\u9650\u8A2D\u5B9A\u306B\u3066\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u3078\u306E\u30A2\u30AF\u30BB\u30B9\u3092\u8A31\u53EF\u3057\u3066\u3044\u308B\u304B\u3054\u78BA\u8A8D\u4E0B\u3055\u3044\u3002")}))?.replaceAll(\r ,
);if(n===void 0)return;let o=await z({project:scrapbox.Project.name,title:scrapbox.Page.title,lines:scrapbox.Page.lines},{titleLineId:t.titleLine.id});if(o.length<=0)return;let r=o[0],i=r.titleLine.text.length-r.titleLine.text.trimStart().length+1,a=r.bodyLines.map(l=>l.text.slice(i)).join(
);console.debug("target code block: %o",r),console.debug("clipboard text: %o",n),console.debug("code of adding history: %o",a),await Ln({prevCode:a,targetCodeBlock:r}),await de(n,r,{socket:Q})}},we={title:"Undo",iconClass:["fa-solid","fa-arrow-rotate-left"],onClick:async(e,t)=>{if(scrapbox.Page.title===null)return;let n=await z({project:scrapbox.Project.name,title:scrapbox.Page.title,lines:scrapbox.Page.lines},{titleLineId:t.titleLine.id});if(n.length<=0)return;let o=n[0],r=o.titleLine.text.length-o.titleLine.text.trimStart().length+1,i=o.bodyLines.map(s=>s.text.slice(r)).join(
),a=k.find(s=>s.targetCodeBlock.titleLine.id==o.titleLine.id);if(a===void 0)return;let{prevCode:l}=a;console.debug("prev code: %o",l),console.debug("now code: %o",i),!(!F&&(await me(K.OK_CANCEL,"\u30B3\u30FC\u30C9\u30D6\u30ED\u30C3\u30AF\u306E\u4E2D\u8EAB\u3092\u623B\u3057\u3066\u3082\u5927\u4E08\u592B\u3067\u3059\u304B\uFF1F",\u524D\u56DE\u306E\u8CBC\u308A\u4ED8\u3051\u6642\u304B\u3089\u3001\u30B3\u30FC\u30C9\u30D6\u30ED\u30C3\u30AF\u3078\u7DE8\u96C6\u304C\u52A0\u3048\u3089\u308C\u3066\u3044\u305F\u5834\u5408\u3001\u30B3\u30FC\u30C9\u30D6\u30ED\u30C3\u30AF\u3092\u8CBC\u308A\u4ED8\u3051\u524D\u306E\u72B6\u614B\u306B\u623B\u3059\u3068\u3001\u8CBC\u308A\u4ED8\u3051\u5F8C\u306B\u52A0\u3048\u305F\u7DE8\u96C6\u306F\u7834\u68C4\u3055\u308C\u623B\u3059\u3053\u3068\u304C\u3067\u304D\u306A\u304F\u306A\u308A\u307E\u3059\u3002
`)).button!="OK")&&(await On(a),await de(l,o,{socket:Q}))}};async function kn(e){Q=e?.socket??await T(),F=e?.noUndoAlert??F,await Nn()}async function Nn(){await yn(Cn)}async function Ln(e){let{targetCodeBlock:t}=e,n=k.findIndex(o=>o.targetCodeBlock.titleLine.id==t.titleLine.id);n<0?k.push(e):kn=e,await hn(we,e.targetCodeBlock),await q()}async function On(e){k=k.filter(t=>{t.targetCodeBlock.titleLine.id!=e.targetCodeBlock.titleLine.id}),await bn(we,e.targetCodeBlock),await q()}await kn({socket:await T(),noUndoAlert:!0});