ScrapHTMLEditor@0.1.0
2023-01-16
10:08:15 インデントを削りすぎていた
09:29:23 更新が反映されないバグの修正中
10:00:59 直した
2021-09-24
11:17:43 更新が反映されない時がある
console.log()で更新状況を読んでみないとわからないな
code:js
await import("/api/code/takker/ScrapHTMLEditor/script.js");
code:app.ts
import { Scrapbox } from "../scrapbox-jp%2Ftypes/userscript.ts";
declare const scrapbox: Scrapbox;
let tab: WindowProxy | null;
let prevHTML = "";
const fileName = "index.html";
let blobURL: string | undefined = undefined;
const findHTMLBlock = (): string | undefined => {
if (scrapbox.Layout !== "page") return;
let lines: string[] = [];
let indent = 0;
for (const line of scrapbox.Page.lines) {
if (!("codeBlock" in line)) continue;
if (line.codeBlock.filename !== fileName) continue;
if (line.codeBlock.start) {
// コードブロックのタイトルのindent数分だけ削る
indent = line.codeBlock.indent;
continue;
}
}
if (lines.length === 0) return;
return lines.join("\n");
};
const updateTab = () => {
const html = findHTMLBlock();
if (!html) return;
if (prevHTML === html) return;
console.debug({before: prevHTML, after:html});
prevHTML = html;
if (blobURL) URL.revokeObjectURL(blobURL);
blobURL = URL.createObjectURL(
new Blob(html, { type: "text/html" }) );
if (!tab) {
tab = window.open(blobURL);
} else {
tab.location.href = blobURL;
}
};
let timer: number | undefined;
const callback = () => {
clearTimeout(timer);
if (tab?.closed) {
scrapbox.off("lines:changed", callback);
return;
}
timer = setTimeout(updateTab, 500);
};
updateTab();
scrapbox.on("lines:changed", callback);
code:script.js
var o,i="",a="index.html",t,f=()=>{if(scrapbox.Layout!=="page")return;let e=[],c=0;for(let n of scrapbox.Page.lines)if("codeBlock"in n&&n.codeBlock.filename===a){if(n.codeBlock.start){c=n.codeBlock.indent;continue}e.push(...n.text.slice(c).join(""))}if(e.length!==0)return e.join(` `)},r=()=>{let e=f();!e||i!==e&&(console.debug({before:i,after:e}),i=e,t&&URL.revokeObjectURL(t),t=URL.createObjectURL(new Blob(e,{type:"text/html"})),o?o.location.href=t:o=window.open(t))},l,s=()=>{if(clearTimeout(l),o?.closed){scrapbox.off("lines:changed",s);return}l=setTimeout(r,500)};r();scrapbox.on("lines:changed",s); code:index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello, world from Scrapbox!</title>
<meta charset="utf-8"></meta>
</head>
<body>
<h1>Heading 1</h1>
<p>
てすとてすと
</p>
</body>
</html>