generated at
ToMyProj

$ deno check --remote -r=https://scrapbox.io https://scrapbox.io/api/code/takker/ToMyProj/script.ts
script.ts
import { getSnippet } from "./mod.ts"; import { open } from "../scrapbox-userscript-std/dom.ts"; import { Scrapbox } from "../scrapbox-jp%2Ftypes/userscript.ts"; declare const scrapbox: Scrapbox; export const setup = (project: string) => { scrapbox.PopupMenu.addButton({ title: (text) => text.includes("\n") ? `→${project}` : "", onClick: async () => { const { title, body } = getSnippet(project); await navigator.clipboard.writeText(body); if (!window.confirm("copied. create page?")) return; open(project, title, { body }); }, }); };

$ deno check --remote -r=https://scrapbox.io https://scrapbox.io/api/code/takker/ToMyProj/mod.ts
mod.ts
import { takeSelection, getLineId } from "../scrapbox-userscript-std/dom.ts"; import { getIndentCount } from "../scrapbox-userscript-std/text.ts"; import { getEachLatestDate } from "../getEachLatestDate/mod.ts"; import { lightFormat } from "../date-fns/lightFormat.ts"; import { Scrapbox } from "../scrapbox-jp%2Ftypes/userscript.ts"; declare const scrapbox: Scrapbox; export const getSnippet = (project: string): { title: string; body: string; } | undefined => { if (scrapbox.Layout !== "page") return; const selection = takeSelection(); const { start, end } = selection.getRange(); const id = getLineId(Math.min(start.line, end.line));
タイトルは元ページのタイトルをそのまま使う(/nishio/ToMyProj要素)
mod.ts
const title = scrapbox.Page.title;
mod.ts
const from = `${ project !== scrapbox.Project.name ? `/${scrapbox.Project.name}/` : "" }${title}${id ? `#${id}` : ""}`; const lines = selection.getSelectedText()
アイコンのパスを変える(/nishio/ToMyProj要素)
mod.ts
.replace(/\[([^\]\/]+).icon\]/gm, `[${ project !== scrapbox.Project.name ? `/${scrapbox.Project.name}/` : "" }$1.icon]`)
mod.ts
.split("\n"); const minIndentCount = Math.min(...lines.map((text) => getIndentCount(text))); const dates = getEachLatestDate(scrapbox.Page.lines.slice( Math.min(start.line, end.line), Math.max(start.line, end.line) + 1 ).map(({ updated }) => new Date(updated * 1000))); const body = [ `from [${from}]`, ...lines.map((text) => text.slice(minIndentCount)), "", ...dates.map((date) => `#${lightFormat(date, "yyyy-MM-dd HH:mm:ss")}`), ].join("\n"); return { title, body }; };

mod.js
var w=e=>e==null,g=e=>typeof e=="string",x=e=>typeof e=="number";var A=(e,t)=>{if(!Array.isArray(e))throw new TypeError(`"${t}" must be an array but actual is "${e}"`)};var S=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError(`"${t}" must be HTMLTextAreaElement but actual is "${e}"`)};var l=()=>{let e=document.getElementById("text-input");if(!!e)return S(e,"textarea#text-input"),e};var y=e=>e.match(/^(\s*)/)?.[1]?.length??0;var L=e=>{if(w(e))return;if(x(e))return U(e)?.id;if(g(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 U=e=>{if(w(e))return;if(x(e))return I()[e];let t=L(e);return t?I().find(n=>n.id===t):void 0};var I=()=>(A(scrapbox.Page.lines,"scrapbox.Page.lines"),scrapbox.Page.lines);var P=e=>e.replaceAll(" ","_").toLowerCase();var B=e=>[...e].map((t,n)=>t===" "?"_":!V.includes(t)||n===e.length-1&&z.includes(t)?encodeURIComponent(t):t).join(""),V='@$&+=:;",',z=':;",';var _=e=>{let t=JSON.parse(localStorage.getItem("pageTransitionContext")??""),n=e.type==="page"?e.from.project===e.to.project?e.from.title===e.to.title?{titleHint:e.to.title}:{linkFrom:e.from.title}:{linkFrom:`/${e.from.project}/${e.from.title}`}:{searchQuery:e.query};t[`page_${P(e.to.title)}`]=n,localStorage.setItem("pageTransitionContext",JSON.stringify(t))};var N=(e,t,n)=>{let r=new URL(`/${e}/${B(t)}`,location.href);if(n?.body&&(r.search=`?body=${encodeURIComponent(n.body)}`),n?.id&&(r.hash=`#${n.id}`),n?.context&&_({...n?.context,to:{project:e,title:t}}),n?.newTab!==!1&&(n?.newTab===!0||e!==scrapbox.Project.name)){window.open(r);return}if(n?.reload!==!1&&(n?.reload===!0||e!==scrapbox.Project.name)){window.open(r,"_self");return}let o=document.createElement("a");o.href=r.toString(),document.body.append(o),o.click(),o.remove()};var M=()=>{let e=l();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(a=>a.startsWith("__reactFiber"));if(!t)throw Error('#text-input must has the property whose name starts with "__reactFiber"');let n=e[t].return.return.stateNode._stores,r=n.find(a=>a.constructor.name==="Cursor");if(!r)throw Error('#text-input must has a "Cursor" store.');let o=n.find(a=>a.constructor.name==="Selection");if(!o)throw Error('#text-input must has a "Selection" store.');return{cursor:r,selection:o}};var O=()=>M().selection;function s(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function i(e){s(1,arguments);let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console!="undefined"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://git.io/fjule"),console.warn(new Error().stack)),new Date(NaN))}function h(e){return s(1,arguments),i(e).getFullYear()}function b(e){return s(1,arguments),i(e).getMonth()}function E(e){return s(1,arguments),i(e).getDate()}var K=e=>{let t=new Map;for(let n of e){let r=`${h(n)}-${b(n)}-${E(n)}`,o=t.get(r);o&&o.getTime()>n.getTime()||t.set(r,n)}return[...t.values()]};function c(e,t){for(var n=e<0?"-":"",r=Math.abs(e).toString();r.length<t;)r="0"+r;return n+r}var W={y(e,t){let n=e.getUTCFullYear(),r=n>0?n:1-n;return c(t==="yy"?r%100:r,t.length)},M(e,t){let n=e.getUTCMonth();return t==="M"?String(n+1):c(n+1,2)},d(e,t){return c(e.getUTCDate(),t.length)},a(e,t){let n=e.getUTCHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(e,t){return c(e.getUTCHours()%12||12,t.length)},H(e,t){return c(e.getUTCHours(),t.length)},m(e,t){return c(e.getUTCMinutes(),t.length)},s(e,t){return c(e.getUTCSeconds(),t.length)},S(e,t){let n=t.length,r=e.getUTCMilliseconds(),o=Math.floor(r*Math.pow(10,n-3));return c(o,t.length)}},F=W;function D(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function v(e){s(1,arguments);var t=i(e);return!isNaN(t)}function p(e){if(e===null||e===!0||e===!1)return NaN;let t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function k(e,t){s(2,arguments);let n=i(e).getTime(),r=p(t);return new Date(n+r)}function C(e,t){s(2,arguments);let n=p(t);return k(e,-n)}var Q=/(\w)\1*|''|'(''|[^'])+('|$)|./g,G=/^'([^]*?)'?$/,J=/''/g,Z=/[a-zA-Z]/;function T(e,t){s(2,arguments);let n=i(e);if(!v(n))throw new RangeError("Invalid time value");let r=D(n),o=C(n,r),a=t.match(Q);return a?a.map(u=>{if(u==="''")return"'";let m=u[0];if(m==="'")return ee(u);let f=F[m];if(f)return f(o,u);if(m.match(Z))throw new RangeError("Format string contains an unescaped latin alphabet character `"+m+"`");return u}).join(""):""}function ee(e){let t=e.match(G);return t?t[1].replace(J,"'"):e}var R=e=>{if(scrapbox.Layout!=="page")return;let t=O(),{start:n,end:r}=t.getRange(),o=L(Math.min(n.line,r.line)),a=scrapbox.Page.title,H=`${e!==scrapbox.Project.name?`/${scrapbox.Project.name}/`:""}${a}${o?`#${o}`:""}`,u=t.getSelectedText().replace(/\[([^\]\/]+).icon\]/gm,`[${e!==scrapbox.Project.name?`/${scrapbox.Project.name}/`:""}$1.icon]`).split(` `),m=Math.min(...u.map(d=>y(d))),f=K(scrapbox.Page.lines.slice(Math.min(n.line,r.line),Math.max(n.line,r.line)+1).map(({updated:d})=>new Date(d*1e3))),$=[`from [${H}]`,...u.map(d=>d.slice(m)),"",...f.map(d=>`#${T(d,"yyyy-MM-dd HH:mm:ss")}`)].join(` `);return{title:a,body:$}};var Yn=e=>{scrapbox.PopupMenu.addButton({title:t=>!t.includes(` `)?"":`→${e}`,onClick:async()=>{let{title:t,body:n}=R(e);await navigator.clipboard.writeText(n),!!window.confirm("copied. create page?")&&N(e,t,{body:n})}})};export{Yn as setup};

#2023-03-22 15:02:11