pin-diary-X
タイトルの変更: yyyy-MM-dd から yyyy/M/dd 形式への変更。
ヘッダーの内容の追加: 指定された「Habbit」、「Task」、「Schedule」のセクションを含むよう変更
フッターの形式の変更: 日付リンクの形式を yyyy/M/dd とし、前日と翌日へのリンクに「←→」を使用 code:script.ts
import { launch } from "./mod.ts";
import {
makeDiary, filter,
} from "./template.ts";
launch(
"tkgshn-private",
{
makeDiary,
filter,
},
);
code:template.ts
import {
getDay,
getWeek,
addDays,
subDays,
subYears,
getYear,
lightFormat,
getDayOfYear,
getDaysInYear,
} from "./template_deps.ts";
const titleFormat = "yyyy-MM-dd";
const titleRegExp = /^\d{4}\/\d{1,2}\/\d{1,2}$/;
export function makeDiary(date: Date): {
title: string;
header: string[];
footer: string[];
} {
return {
title: lightFormat(date, "yyyy/M/dd"), // 日付形式の変更
header: [
"Habbit",
" 30min: workout",
"",
"Task",
"",
"Schedule",
"",
"Notes",
""
],
footer: [
[${lightFormat(subDays(date, 1), "yyyy/M/dd")}]←→[${lightFormat(addDays(date, 1), "yyyy/M/dd")}]
]
};
}
function youbiLine(date: Date): string {
const day = getDay(date);
.map((char, i) => (i === day ? [[${char}]] : char))
.join("");
}
export function filter(title: string, today: Date): boolean {
if (!titleRegExp.test(title)) return true;
return toTitle(today) === title;
}
function toTitle(date: Date): string {
return lightFormat(date, titleFormat);
}
code:template_deps.ts
// 一年の経過率を計算するのに必要
// 日付計算に使う
// 文字列変換に使う
code:mod.ts
/// <reference no-default-lib="true"/>
/// <reference lib="esnext"/>
/// <reference lib="dom"/>
import {
pin,
unpin,
patch,
useStatusBar,
sleep,
makeSocket,
disconnect,
format,
} from "./deps.ts";
import { listPinnedPages } from "./list.ts";
import type { Scrapbox, Socket } from "./deps.ts";
declare const scrapbox: Scrapbox;
export interface DiaryInit {
makeDiary: (date: Date) => {
title: string;
header: string[];
footer: string[];
},
filter: (title: string, today: Date) => boolean;
}
// initialize
export function launch(
project: string,
init: DiaryInit & { interval?: number },
) {
const interval = init.interval ?? 24 * 3600 * 1000;
const handleChange = () =>
scrapbox.Project.name === project ?
startObserve(project, interval, init) :
endObserve();
handleChange();
scrapbox.addListener("project:changed", handleChange);
}
let updateTimer: number | undefined;
async function startObserve(
project: string,
interval: number,
init: DiaryInit,
) {
endObserve();
await pinDiary(project, new Date(), init);
updateTimer = setInterval(
() => pinDiary(project, new Date(), init),
interval,
);
}
function endObserve() {
clearInterval(updateTimer);
}
export async function pinDiary(
project: string,
date: Date,
{ makeDiary, filter, }: DiaryInit,
): Promise<void> {
const { render, dispose } = useStatusBar();
let socket: Socket | undefined;
try {
// 今日以外の日付ページを外す
render(
{ type: "spinner" },
{ type: "text", text: unpin other diary pages...},
);
socket = await makeSocket();
for await (const { title } of listPinnedPages(project)) {
if (filter(title, date)) continue;
await unpin(project, title, { socket });
}
// 今日の日付ページをピン留めする
const { title, header, footer } = makeDiary(date);
render(
{ type: "spinner" },
{ type: "text", text: pin "/${project}/${title}"...},
);
await pin(project, title, { socket, create: true });
// 今日の日付ページにtemplateを挿入する
render(
{ type: "spinner" },
{ type: "text", text: format "/${project}/${title}"...},
);
await patch(project, title, (lines) => [
...format(
lines.slice(1).map(line => line.text),
header,
footer,
),
], { socket });
render(
{ type: "check-circle" },
{ type: "text", text: Pinned "/${project}/${title}".},
);
} catch(e: unknown) {
render(
{ type: "exclamation-triangle" },
{ type: "text", text: e instanceof Error ?
${e.name} ${e.message} :
Unknown error! (see developper console),
},
);
console.error(e);
} finally {
if (socket) await disconnect(socket);
await sleep(1000);
dispose();
}
}
code:list.ts
import { listPages, PageSummary } from "./deps.ts";
/** 全てのピン留めされたページを取得する */
export async function* listPinnedPages(project: string, skip = 0): AsyncGenerator<PageSummary> {
const { count, pages } = await ensureList(project, skip);
for (const page of pages) {
if (page.pin === 0) continue;
yield page;
}
// pinしたページこれ以上ないときは終了
if ((pages.at(-1)?.pin ?? 0) === 0) return;
yield* listPinnedPages(project, skip + 1000);
}
async function ensureList(project: string, skip: number) {
const result = await listPages(project, {
limit: 1000,
skip,
});
// login errorなどは全部例外として扱う
if (!result.ok) {
const error = new Error();
error.name = result.value.name;
error.message = result.value.message;
throw error;
}
return result.value;
}
code:deps.ts
export { patchTemplate as format } from "./format.ts";
export {
pin,
unpin,
patch,
useStatusBar,
makeSocket,
disconnect,
listPages,
export type {
Socket,
export {
sleep,
export type {
Scrapbox,
PageSummary,
code:format.ts
import { patchLines, findSplitIndex } from "./util.ts";
// linesにタイトルを入れないように
export function patchTemplate(lines: string[], headers: string[], footers: string[]): string[] {
// headerとfooterに相当する行を補う
const bodies = patchLines(
patchLines(lines, headers).reverse(),
).reverse();
// headerとfooterの間に余裕をもたせる
const headerStart = findSplitIndex(bodies, headers);
const footerStart = bodies.length - 1 - findSplitIndex(
);
return [
...bodies.slice(0, headerStart + 1),
"",
...bodies.slice(headerStart + 1, footerStart).join("\n").trim().split("\n"),
"",
...bodies.slice(footerStart),
];
}
code:util.ts
export function patchLines(lines: string[], appends: string[]) {
let index = 0;
const result = [] as string[];
for (let i = 0; i < appends.length; i++) {
const pos = lines.findIndex((line, j) => j >= index && line.trim() === appendsi.trim()); if (pos < 0) {
continue;
}
result.push(...lines.slice(index, pos + 1));
index = pos + 1;
}
result.push(...lines.slice(index));
return result;
}
export function findSplitIndex(lines: string[], query: string[]) {
let index = -1;
for (const text of query) {
const pos = lines.findIndex((line, j) => j > index && line.trim() === text.trim());
if (pos < 0) return -1;
index = pos;
}
return index;
}
つまり、上記のコードをコンパイルするイメージであっているのか? code:min.js
function z(e,t){let r=0,n=[];for(let o=0;o<t.length;o++){let s=e.findIndex((a,i)=>i>=r&&a.trim()===to.trim());if(s<0){n.push(to);continue}n.push(...e.slice(r,s+1)),r=s+1}return n.push(...e.slice(r)),n}function Q(e,t){let r=-1;for(let n of t){let o=e.findIndex((s,a)=>a>r&&s.trim()===n.trim());if(o<0)return-1;r=o}return r}function X(e,t,r){let n=z(z(e,t).reverse(),...r.reverse()).reverse(),o=Q(n,t),s=n.length-1-Q(...n.reverse(),...r.reverse());return[...n.slice(0,o+1),"",...n.slice(o+1,s).join(` ).trim().split(
),"",...n.slice(s)]}async function G(e){let t="https://scrapbox.io/api/users/me",r=await fetch(t,e?.sid?{headers:{Cookie:L(e.sid)}}:void 0);if(!r.ok)throw M("UnexpectedError",Unexpected error has occuerd when fetching "${t}");return await r.json()}var L=e=>connect.sid=${e};function Fe(e){return e!=null}function Ue(e){return Fe(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1}function N(e){try{let t=typeof e=="string"?JSON.parse(e):e;return Ue(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}}function M(e,t){let r=new Error;return r.name=e,r.message=t,r}var U=e=>e.replaceAll(" ","_").toLowerCase();var V=e=>[...e].map((t,r)=>t===" "?"_":!je.includes(t)||r===e.length-1&&We.includes(t)?encodeURIComponent(t):t).join(""),je='@$&+=:;",',We=':;",';async function ce(e,t,r){let n=https://scrapbox.io/api/pages/${e}/${V(t)}?followRename=${r?.followRename??!0},o=await fetch(n,r?.sid?{headers:{Cookie:L(r.sid)}}:void 0);if(!o.ok){let a=N(await o.text());if(!a)throw M("UnexpectedError",Unexpected error has occuerd when fetching "${n}");return{ok:!1,value:a}}return{ok:!0,value:await o.json()}}async function Z(e,t){let{sort:r,limit:n,skip:o}=t??{},s=new URLSearchParams;r!==void 0&&s.append("sort",r),n!==void 0&&s.append("limit",${n}),o!==void 0&&s.append("skip",${o});let a=https://scrapbox.io/api/pages/${e}?${s.toString()},i=await fetch(a,t?.sid?{headers:{Cookie:L(t.sid)}}:void 0);if(!i.ok){let p=N(await i.text());if(!p)throw M("UnexpectedError",Unexpected error has occuerd when fetching "${a}");return{ok:!1,value:p}}return{ok:!0,value:await i.json()}}async function ue(e,t){let r=https://scrapbox.io/api/projects/${e},n=await fetch(r,t?.sid?{headers:{Cookie:L(t.sid)}}:void 0);if(!n.ok){let s=N(await n.json());if(!s)throw M("UnexpectedError",Unexpected error has occuerd when fetching "${r}");return{ok:!1,value:s}}return{ok:!0,value:await n.json()}}var pe=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var me=()=>Ye(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),Ye=(e,t)=>{if(e)return pe(e,t),e};var j=e=>new Promise(t=>setTimeout(()=>t(),e));function J(){let e=me();if(!e)throw new Error("div.status-bar can't be found");let t=document.createElement("div");return e.append(t),{render:(...r)=>{t.textContent="";let n=fe(...r);n&&t.append(n)},dispose:()=>t.remove()}}function fe(...e){let t=e.flatMap(n=>{switch(n.type){case"spinner":return[Xe()];case"check-circle":return[Ge()];case"exclamation-triangle":return[Ve()];case"text":return[B(n.text)];case"group":{let o=fe(...n.items);return o?[o]:[]}}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r}function B(e){let t=document.createElement("span");return t.classList.add("item"),t.append(e),t}function Xe(){let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),B(e)}function Ge(){let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),B(e)}function Ve(){let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),B(e)}var Ze="4.2.0";async function v(){let t=(await Je())("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"]});return await new Promise((r,n)=>{let o=s=>n(s);t.once("connect",()=>{t.off("disconnect",o),r()}),t.once("disconnect",o)}),t}function Je(){let e=https://cdnjs.cloudflare.com/ajax/libs/socket.io/${Ze}/socket.io.min.js;if(document.querySelector(scriptsrc="${e}"))return Promise.resolve(window.io);let t=document.createElement("script");return t.src=e,new Promise((r,n)=>{t.onload=()=>r(window.io),t.onerror=o=>n(o),document.head.append(t)})}function C(e,t=9e4){function r(o,s){let a;return new Promise((i,c)=>{let p=u=>{clearTimeout(a),c(new Error(u))};e.emit(o,s,u=>{clearTimeout(a),e.off("disconnect",p),u.error&&c(new Error(JSON.stringify(u.error))),"data"in u?i(u?.data):i(void 0)}),a=setTimeout(()=>{e.off("disconnect",p),c(new Error(Timeout: exceeded ${t}ms))},t),e.once("disconnect",p)})}async function*n(...o){let s,a=()=>new Promise(c=>s=c),i=c=>{s?.(c)};for(let c of o)e.on(c,i);try{for(;;)yield await a()}finally{for(let c of o)e.off(c,i)}}return{request:r,response:n}}function ee(){return v()}async function S(e){if(e.connected)return;let t=new Promise(r=>e.once("connect",()=>r()));e.connect(),await t}async function T(e){if(e.disconnected)return;let t=new Promise(r=>{let n=o=>{o==="io client disconnect"&&(r(),e.off("disconnect",n))};e.on("disconnect",n)});e.disconnect(),await t}var Y;async function $(){if(Y!==void 0)return Y;let e=await G();if(e.isGuest)throw new Error("this script can only be executed by Logged in users");return Y=e.id,Y}var ge=new Map;async function P(e){let t=ge.get(e);if(t!==void 0)return t;let r=await ue(e);if(!r.ok){let{name:o,message:s}=r.value;throw new Error(${o} ${s})}let{id:n}=r.value;return ge.set(e,n),n}function he(e){return e.padStart(8,"0")}function xe(e){let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return${he(t).slice(-8)}${e.slice(-6)}0000${he(r)}}function we(e,t){let r=e.length>t.length,n=r?t:e,o=r?e:t,s=n.length+1,a=n.length+o.length+3,i=new Array(a);i.fill(-1);let c=[];function p(l,b,O){let k=Math.max(b,O),W=k-l;for(;W<n.length&&k<o.length&&n[W]===o[k];)++W,++k;return i[l+s]=c.length,c.push([{x:W,y:k},i[l+(b>O?-1:1)+s]]),k}let u=new Array(a);u.fill(-1);let y=-1,f=o.length-n.length;do{++y;for(let l=-y;l<=f-1;++l)u[l+s]=p(l,u[l-1+s]+1,u[l+1+s]);for(let l=f+y;l>=f+1;--l)u[l+s]=p(l,u[l-1+s]+1,u[l+1+s]);u[f+s]=p(f,u[f-1+s]+1,u[f+1+s])}while(u[f+s]!==o.length);let E=[],w=i[f+s];for(;w!==-1;)E.push(c[w][0]),w=c[w][1];return{from:e,to:t,editDistance:f+y*2,buildSES:function*(){let l=0,b=0;for(let{x:O,y:k}of et(E))for(;l<O||b<k;)k-O>b-l?(yield{value:o[b],type:r?"deleted":"added"},++b):k-O<b-l?(yield{value:n[l],type:r?"added":"deleted"},++l):(yield{value:n[l],type:"common"},++l,++b)}}}function*be(e){let t=[],r=[];function*n(){if(t.length>r.length){for(let o=0;o<r.length;o++)yield ye(t[o],r[o]);for(let o=r.length;o<t.length;o++)yield t[o]}else{for(let o=0;o<t.length;o++)yield ye(t[o],r[o]);for(let o=t.length;o<r.length;o++)yield r[o]}t=[],r=[]}for(let o of e)switch(o.type){case"added":t.push(o);break;case"deleted":r.push(o);break;case"common":yield*n(),yield o;break}yield*n()}function ye(e,t){return{value:e.value,oldValue:t.value,type:"replaced"}}function*et(e){for(let t=e.length-1;t>=0;t--)yield e[t]}function*Ee(e,t,{userId:r}){let{buildSES:n}=we(e.map(({text:a})=>a),t),o=0,s=e[0].id;for(let a of be(n())){switch(a.type){case"added":yield{_insert:s,lines:{id:xe(r),text:a.value}};continue;case"deleted":yield{_delete:s,lines:-1};break;case"replaced":yield{_update:s,lines:{text:a.value}};break}o++,s=e[o]?.id??"_end"}}var tt=e=>({type:"title",text:e.rows[0].text}),rt=e=>{let{rows:[t,...r]}=e,{indent:n=0,text:o=""}=t??{},s=o.replace(/^\s*code:/,"");return{indent:n,type:"codeBlock",fileName:s,content:r.map(a=>a.text.substring(n+1)).join( )}},g=(e,{parseOnNested:t,parseOnQuoted:r,patterns:n})=>(o,s,a)=>{var i,c,p,u,y,f;if(!t&&s.nested)return(i=a?.())!==null&&i!==void 0?i:[];if(!r&&s.quoted)return(c=a?.())!==null&&c!==void 0?c:[];for(let E of n){let w=E.exec(o);if(w===null)continue;let l=o.substring(0,w.index),b=o.substring(w.index+((u=(p=w[0])===null||p===void 0?void 0:p.length)!==null&&u!==void 0?u:0)),O=e((y=w[0])!==null&&y!==void 0?y:"",s);return[...H(l,s),...O,...H(b,s)]}return(f=a?.())!==null&&f!==void 0?f:[]},h=e=>[{type:"plain",raw:e,text:e}],nt=g(h,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),ot=/^>.*$/,st=(e,t)=>t.context==="table"?h(e,t):[{type:"quote",raw:e,nodes:H(e.substring(1),{...t,quoted:!0})}],it=g(st,{parseOnNested:!1,parseOnQuoted:!1,patterns:[ot]}),at=/^\? .+$/,ct=(e,t)=>t.context==="table"?h(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],ut=g(ct,{parseOnNested:!1,parseOnQuoted:!1,patterns:[at]}),pt=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,mt=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,lt=(e,t)=>{if(t.context==="table")return h(e,t);let r=e.substring(2,e.length-2),n=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(r);return[{type:"strongImage",raw:e,src:n?${r}/thumb/1000:r}]},dt=g(lt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[pt,mt]}),ft=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function ve(e){return(t,r)=>{if(e==="strongIcon"&&r.context==="table")return h(t,r);let n=e==="icon"?t.substring(1,t.length-1):t.substring(2,t.length-2),o=n.lastIndexOf(".icon"),s=n.substring(0,o),a=s.startsWith("/")?"root":"relative",i=n.substring(o+5,n.length),c=i.startsWith("*")?parseInt(i.substring(1),10):1;return new Array(c).fill({}).map(()=>({path:s,pathType:a,type:e,raw:t}))}}var gt=ve("icon"),ht=g(gt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ft]}),xt=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,yt=ve("strongIcon"),wt=g(yt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[xt]}),bt=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,Et=(e,t)=>t.context==="table"?h(e,t):[{type:"strong",raw:e,nodes:H(e.substring(2,e.length-2),{...t,nested:!0})}],kt=g(Et,{parseOnNested:!1,parseOnQuoted:!0,patterns:[bt]}),vt=/\[\$ .+? \]/,Tt=/\[\$ [^\]]+\]/,Dt=(e,t)=>t.context==="table"?h(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],Lt=g(Dt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[vt,Tt]}),Mt=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,It=(e,t)=>{if(t.context==="table")return h(e,t);let r=e.indexOf(" "),n=e.substring(1,r),o=e.substring(r+1,e.length-1),s=new Set(n);if(s.has("*")){let a=n.split("*").length-1;s.delete("*"),s.add(*-${Math.min(a,10)})}return[{type:"decoration",raw:e,rawDecos:n,decos:Array.from(s),nodes:H(o,{...t,nested:!0})}]},Ot=g(It,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Mt]}),Ct=/.*?/,Nt=(e,t)=>t.context==="table"?h(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],St=g(Nt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Ct]}),Pt=/^[$%] .+$/,Ht=(e,t)=>{var r;if(t.context==="table")return h(e,t);let n=(r=e[0])!==null&&r!==void 0?r:"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:n,text:o}]},At=g(Ht,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Pt]}),Rt=/\[\s+\]/,$t=(e,t)=>t.context==="table"?h(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],Ft=g($t,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Rt]}),Ut=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,jt=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,Wt=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,Bt=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,Yt=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||Kt(e),Kt=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 r=e.search(/\s/),n=r!==-1?e.substring(1,r):e.substring(1,e.length-1),o=r!==-1?e.substring(r,e.length-1).trimLeft():"",[s,a]=Yt(o)?[o,n]:[n,o];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?${s}/thumb/1000:s,link:a}]},qt=g(_t,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Ut,jt,Wt,Bt]}),zt=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,Qt=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,Xt=/\[https?:\/\/[^\s\]]+\]/,Gt=/https?:\/\/[^\s]+/,Vt=(e,t)=>{if(t.context==="table")return h(e,t);let r=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,n=/^https?:\/\/[^\s\]]/.test(r),o=(n?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(r);if(o?.[0]===void 0)return[];let s=n?r.substring(o[0].length):r.substring(0,o.index-1);return[{type:"link",raw:e,pathType:"absolute",href:o[0],content:s.trim()}]},Zt=g(Vt,{parseOnNested:!0,parseOnQuoted:!0,patterns:[zt,Qt,Xt,Gt]}),Te=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,De=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,Jt=e=>{let[t="",r="",n=""]=e.split(","),o=parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),a=/^Z\d+$/.test(n)?parseInt(n.replace(/^Z/,""),10):14;return{latitude:o,longitude:s,zoom:a}},er=(e,t)=>{var r;if(t.context==="table")return h(e,t);let n=(r=e.match(Te))!==null&&r!==void 0?r:e.match(De);if(n===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,s="",a=""]=o?n:[n[0],n[2],n[1]],{latitude:i,longitude:c,zoom:p}=Jt(s),u=a!==""?https://www.google.com/maps/place/${encodeURIComponent(a)}/@${i},${c},${p}z:https://www.google.com/maps/@${i},${c},${p}z;return[{type:"googleMap",raw:e,latitude:i,longitude:c,zoom:p,place:a,url:u}]},tr=g(er,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Te,De]}),rr=/\[\/?[^[\]]+\]/,nr=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},or=g(nr,{parseOnNested:!0,parseOnQuoted:!0,patterns:[rr]}),sr=/(?:^|\s)#\S+/,ir=(e,t)=>{if(t.context==="table")return h(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),n=e.substring(1);return[...h(r,t),{type:"hashTag",raw:n,href:n.substring(1)}]},ar=g(ir,{parseOnNested:!0,parseOnQuoted:!0,patterns:[sr]}),cr=(e,t,r)=>{var n;return e===""?[]:(n=r?.())!==null&&n!==void 0?n:[]},ur=(...e)=>(t,r)=>e.reduceRight((n,o)=>()=>o(t,r,n),()=>nt(t,r))(),H=ur(cr,it,ut,St,At,Lt,Ft,Ot,dt,wt,kt,qt,Zt,ht,tr,or,ar),pr=e=>{let{rows:[t,...r]}=e,{indent:n=0,text:o=""}=t??{},s=o.replace(/^\s*table:/,"");return{indent:n,type:"table",fileName:s,cells:r.map(a=>a.text.substring(n+1)).map(a=>a.split(" ").map(i=>H(i,{nested:!1,quoted:!1,context:"table"})))}},mr=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:H(r.substring(t),{nested:!1,quoted:!1,context:"line"})}},Le=e=>{switch(e.type){case"title":return tt(e);case"codeBlock":return rt(e);case"table":return pr(e);case"line":return mr(e)}},Me=e=>e.split( ).map(t=>{var r,n,o;return{indent:(o=(n=(r=/^\s+/.exec(t))===null||r===void 0?void 0:r[0])===null||n===void 0?void 0:n.length)!==null&&o!==void 0?o:0,text:t}}),lr=(e,t)=>{var r,n;return(e.type==="codeBlock"||e.type==="table")&&t.indent>((n=(r=e.rows[0])===null||r===void 0?void 0:r.indent)!==null&&n!==void 0?n:0)},ke=(e,t)=>{let r=e[e.length-1];return r!==void 0&&lr(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},Ie=(e,t)=>{var r;if(!((r=t.hasTitle)!==null&&r!==void 0)||r){let[n,...o]=e;return n===void 0?[]:[{type:"title",rows:[n]},...o.reduce(ke,[])]}return e.reduce(ke,[])};function Oe(e,t,{userId:r,head:n}){let o=t.flatMap(u=>u.split(
)),s=[...Ee(e,o,{userId:r})];(e[0].text!==o[0]||!n.persistent)&&s.push({title:o[0]});let a=e.slice(1,6).map(u=>u.text),i=o.slice(1,6);a.join("")!==i.join("")&&s.push({descriptions:i});let[c,p]=dr(o.join(
));return(n.links.length!==c.length||!n.links.every(u=>c.includes(u)))&&s.push({links:c}),n.image!==p&&s.push({image:p}),s}function dr(e){let t=Me(e),r=Ie(t,{hasTitle:!0}).flatMap(i=>{switch(i.type){case"codeBlock":case"title":return[];case"line":case"table":return[Le(i)]}}),n=new Map,o=[],s=null,a=i=>{switch(i.type){case"hashTag":if(n.has(U(i.href)))return;n.set(U(i.href),!1),o.push(i.href);return;case"link":if(i.pathType!=="relative"||n.get(U(i.href)))return;n.set(U(i.href),!0),o.push(i.href);return;case"image":case"strongImage":{s??=i.src.endsWith("/thumb/1000")?i.src.replace(/\/thumb\/1000$/,"/raw"):i.src;return}case"strong":case"quote":case"decoration":{for(let c of i.nodes)a(c);return}default:return}};for(let i of fr(r))a(i);return[o,s]}function*fr(e){for(let t of e)switch(t.type){case"codeBlock":case"title":continue;case"line":for(let r of t.nodes)yield r;continue;case"table":{for(let r of t.cells)for(let n of r)for(let o of n)yield o;continue}}}async function I(e,t){let r=await ce(e,t);if(!r.ok)throw new Error(You have no privilege of editing "/${e}/${t}".);let{commitId:n,persistent:o,image:s,links:a,lines:i,id:c,pin:p}=r.value;return{commitId:n,pageId:c,persistent:o,image:s,links:a,pin:p,lines:i}}async function K(e,t,r){return t.length===0?{commitId:r.parentId}:await e("socket.io-request",{method:"commit",data:{kind:"page",...r,changes:t,cursor:null,freeze:!0}})}async function A(e,t,{project:r,title:n,retry:o=3,parentId:s,...a}){try{s=(await K(e,t,{parentId:s,...a})).commitId}catch{console.log("Faild to push a commit. Retry after pulling new commits");for(let c=0;c<o;c++){let{commitId:p}=await I(r,n);s=p;try{s=(await K(e,t,{parentId:s,...a})).commitId,console.log("Success in retrying");break}catch{continue}}throw Error("Faild to retry pushing.")}return s}async function te(e,t,r,n){let[o,s,a]=await Promise.all([I(e,t),P(e),$()]),i=o,c=n?.socket,p=c??await v();await S(p);try{let{request:u}=C(p);for(let y=0;y<3;y++)try{let f=r(i.lines,i),E=f instanceof Promise?await f:f;if(!E)return;E.length===0&&await A(u,[{deleted:!0}],{projectId:s,pageId:i.pageId,parentId:i.commitId,userId:a,project:e,title:t});let w=Oe(i.lines,E,{userId:a,head:i});await K(u,w,{parentId:i.commitId,projectId:s,pageId:i.pageId,userId:a});break}catch{if(y===2)throw Error("Faild to retry pushing.");console.log("Faild to push a commit. Retry after pulling new commits");try{i=await I(e,t)}catch(E){throw E}}}finally{c||await T(p)}}async function re(e,t,r){let[n,o,s]=await Promise.all([I(e,t),P(e),$()]);if(n.pin>0||!n.persistent&&!(r?.create??!1))return;let a={parentId:n.commitId,projectId:o,pageId:n.pageId,userId:s,project:e,title:t},i=r?.socket,c=i??await v();await S(c);let{request:p}=C(c);if(!n.persistent){let u=await A(p,[{title:t}],a);a.parentId=u}try{await A(p,[{pin:gr()}],a)}finally{i||await T(c)}}async function ne(e,t,r){let[n,o,s]=await Promise.all([I(e,t),P(e),$()]);if(n.pin==0||!n.persistent)return;let a={parentId:n.commitId,projectId:o,pageId:n.pageId,userId:s,project:e,title:t},i=r?.socket,c=i??await v();await S(c);let{request:p}=C(c);try{await A(p,[{pin:0}],a)}finally{i||await T(c)}}var gr=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);async function*oe(e,t=0){let{count:r,pages:n}=await hr(e,t);for(let o of n)o.pin!==0&&(yield o);(n.at(-1)?.pin??0)!==0&&(yield*oe(e,t+1e3))}async function hr(e,t){let r=await Z(e,{limit:1e3,skip:t});if(!r.ok){let n=new Error;throw n.name=r.value.name,n.message=r.value.message,n}return r.value}function Ne(e,t){let r=t.interval??864e5,n=()=>scrapbox.Project.name===e?xr(e,r,t):Pe();n(),scrapbox.addListener("project:changed",n)}var Se;async function xr(e,t,r){Pe(),await Ce(e,new Date,r),Se=setInterval(()=>Ce(e,new Date,r),t)}function Pe(){clearInterval(Se)}async function Ce(e,t,{makeDiary:r,filter:n}){let{render:o,dispose:s}=J(),a;try{o({type:"spinner"},{type:"text",text:"unpin other diary pages..."}),a=await ee();for await(let{title:u}of oe(e))n(u,t)||await ne(e,u,{socket:a});let{title:i,header:c,footer:p}=r(t);o({type:"spinner"},{type:"text",text:pin "/${e}/${i}"...}),await re(e,i,{socket:a,create:!0}),o({type:"spinner"},{type:"text",text:format "/${e}/${i}"...}),await te(e,i,u=>[u[0].text,...X(u.slice(1).map(y=>y.text),c,p)],{socket:a}),o({type:"check-circle"},{type:"text",text:Pinned "/${e}/${i}".})}catch(i){o({type:"exclamation-triangle"},{type:"text",text:i instanceof Error?${i.name} ${i.message}:"Unknown error! (see developper console)"}),console.error(i)}finally{a&&await T(a),await j(1e3),s()}}function m(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function d(e){m(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<"u"&&(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 _(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 x(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 F(e,t){m(2,arguments);let r=d(e),n=x(t);return isNaN(n)?new Date(NaN):(n&&r.setDate(r.getDate()+n),r)}function q(e,t){m(2,arguments);let r=x(t);return F(e,-r)}function D(e,t){for(var r=e<0?"-":"",n=Math.abs(e).toString();n.length<t;)n="0"+n;return r+n}var yr={y(e,t){let r=e.getUTCFullYear(),n=r>0?r:1-r;return D(t==="yy"?n%100:n,t.length)},M(e,t){let r=e.getUTCMonth();return t==="M"?String(r+1):D(r+1,2)},d(e,t){return D(e.getUTCDate(),t.length)},a(e,t){let r=e.getUTCHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(e,t){return D(e.getUTCHours()%12||12,t.length)},H(e,t){return D(e.getUTCHours(),t.length)},m(e,t){return D(e.getUTCMinutes(),t.length)},s(e,t){return D(e.getUTCSeconds(),t.length)},S(e,t){let r=t.length,n=e.getUTCMilliseconds(),o=Math.floor(n*Math.pow(10,r-3));return D(o,t.length)}},Ae=yr;function se(e){m(1,arguments);var t=d(e);return!isNaN(t)}function ie(e,t){m(2,arguments);let r=d(e).getTime(),n=x(t);return new Date(r+n)}function ae(e,t){m(2,arguments);let r=x(t);return ie(e,-r)}var wr=/(\w)\1*|''|'(''|[^'])+('|$)|./g,br=/^'([^]*?)'?$/,Er=/''/g,kr=/[a-zA-Z]/;function R(e,t){m(2,arguments);let r=d(e);if(!se(r))throw new RangeError("Invalid time value");let n=_(r),o=ae(r,n),s=t.match(wr);return s?s.map(i=>{if(i==="''")return"'";let c=i[0];if(c==="'")return vr(i);let p=Ae[c];if(p)return p(o,i);if(c.match(kr))throw new RangeError("Format string contains an unescaped latin alphabet character "+c+"");return i}).join(""):""}function vr(e){let t=e.match(br);return t?t[1].replace(Er,"'"):e}var Dr="yyyy-MM-dd",Lr=/^\d{4}\/\d{1,2}\/\d{1,2}$/;function Re(e){return{title:R(e,"yyyy/M/dd"),header:["[** Habbit]"," 30min: workout"," 3times: [meditation]","","[** Task]","","[** Schedule]","","[** Notes]",""],footer:[${R(q(e,1),"yyyy/M/dd")}←→${R(F(e,1),"yyyy/M/dd")}`]}}function $e(e,t){return Lr.test(e)?Mr(t)===e:!0}function Mr(e){return R(e,Dr)}Ne("tkgshn-private",{makeDiary:Re,filter:$e});