import { encodeTitleURI, patch } from "../scrapbox-userscript-std/websocket.ts"; /** 同期設定 */ export interface SyncInit { /** projectLastAccessedを書き出すページのproject name */ project: string; /** projectLastAccessedを書き出すページのpage title * * @default ".watchlistrc" */ title?: string; } /** watchListを全てのデバイスで同期する * * @param init watchListの保存先ページを決める */ export const sync = async (init: SyncInit): Promise => { const title = init.title ?? ".watchlistrc"; const filename = "projectsLastAccessed.json"; // scrapbox.ioに保存したwatchListを取得する const res = await fetch( `https://${location.hostname}/api/code/${init.project}/${encodeTitleURI(title)}/${filename}` ); const json = res.ok ? await res.json() : {}; const prevText = localStorage.getItem("projectsLastAccessed") ?? "{}"; /** 端末に保存されたwatchList */ const prev = JSON.parse(prevText); // projectおよびそのアクセス日時を更新する const keys = [...new Set([...Object.keys(json), ...Object.keys(prev)])]; // 一番新しいアクセス日時を採用する const newData = keys.map((key) => [key, Math.max(json[key] ?? 0, prev[key] ?? 0)]); // 端末とscrapbox.ioに新しいwatchListデータを保存する localStorage.setItem("projectsLastAccessed", JSON.stringify(Object.fromEntries(newData))); await patch(init.project, title, () => [ title, "This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.", "", `code:${filename}`, ` ${prevText}`, "", ]); };