scrapbox-formatter
/emoji/warning.iconWIP
code:js
import("/api/code/takker/scrapbox-formatter/script.js");
構文エラーがあると変換に失敗する
結構便利かも
2021-10-09
2021-08-02
03:34:59 gitの方に色々コードを書いた
まだ途中
設計メモを書いたら実装再開する
2021-08-01
17:31:36 githubに移す
とりあえずrepo作った
2021-07-01
07:19:30 とりあえず動く
エラー処理もまだ
実装
dependencies
code:script.js
import { createTsFormatter } from "../dprint@scrapbox/script.js";
import { insertText } from "../scrapbox-insert-text-2/script.js";
import { packRows, parseToRows } from "../scrapbox-parser@7.1.0/script.js";
scrapbox.PopupMenu.addButton({
title: (text) => (/\n\s*code:/.test(text) ? "Format" : ""),
onClick: (text) => {
const blocks = packRows(parseToRows(text), { hasTitle: false });
(async () => {
const promises = blocks.map(async ({ type, rows }) => {
switch (type) {
case "line":
case "table":
return rows.map(row => row.text).join("\n");
case "codeBlock":
return await formatCodeBlock(rows);
}
});
const lines = await Promise.all(promises);
await insertText(lines.join("\n"));
})();
return "";
},
});
const fileTypes = {
javascript: "javascript",
js: "javascript",
jsx: "javascript",
mjs: "javascript",
typescript: "typescript",
ts: "typescript",
tsx: "typescript",
};
const parserConfig = {
javascript: {
indentWidth: 2,
lineWidth: 80,
semiColons: "always",
},
typescript: {
indentWidth: 2,
lineWidth: 80,
semiColons: "always",
},
};
async function formatCodeBlock(rows, config = {}) {
const fileLine = rows0.text; const extention = fileLine.match(/\.(.+)$/)?.1 ?? fileLine.match(/\((.+)\)$/)?.1 ?? fileLine.match(/\s*code:(.+)$/)?.1; const fileName = fileLine.match(/code:(^.+)\./)?.1 ?? fileLine.match(/code:(^.+)\(/)?.1 ?? "file";
const baseIndent = rows0.indent; const code = rows
.slice(1)
.map(row => row.text.slice(row.indent))
.join("\n");
// 設定ファイルを取得する
const _config = parserConfig[fileTypesextention]; // format対象でなければ何もしない
if (!_config) return rows.map(({ text: _text }) => _text).join("\n");
const formatter = await createTsFormatter();
const formattedCode = await formatter.formatText(
${fileName}.${extention},
code,
{ ..._config, ...config },
)
.split("\n")
.map(line => ${" ".repeat(baseIndent + 1)}${line})
.join("\n")
.trimEnd(); // prettierが末尾に改行を挿入するので削除する
}