scrapbox-url-customizer
code:insertText.js
export function insertText({text}) {
const cursor = document.getElementById('text-input');
cursor.focus();
cursor.value = text;
const uiEvent = document.createEvent('UIEvent');
uiEvent.initEvent('input', true, false);
cursor.dispatchEvent(uiEvent);
}
code:script.js
import {convertWholeText} from './convert.js';
import {insertText} from './insertText.js';
export const execute = (config = []) =>
scrapbox.PopupMenu.addButton({
title: text => /https?:\/\/\S+/.test(text) ? 'URL' : '.',// URLがなければボタンを押しにくくする
onClick: text => {
if (!/https?:\/\/\S+/.test(text)) return; // URLがなければ何もしない
convertWholeText(text, config).then(text => insertText({text}));
/*const cursor = document.getElementById('text-input');
convertWholeText(text, config).then(text => insertText({ text, cursor }));*/
return '';// 入力しやすいよう選択範囲を先に消しておく
},
});
複数のURLを含んだテキストをまとめて変換する
code:convert.js
export async function convertWholeText(text, config = []) {
const urls = text.match(/https?:\/\/\S+/g) ?? [];
if (urls.length === 0) return undefined;
const links = await Promise.all(urls.map(url => convert(url, config)));
let map = {};
for (let i = 0; i < urls.length; i++) {
}
//console.log(map);
const result = text.replace(/https?:\/\/\S+/g, match => mapmatch ?? match); //console.log(result);
return result;
}
async function convert(url, config) {
if (!window.fetchURLInfo) {
return;
}
const pending = fetchURLInfo(url);
// hashを分離する
const urlObj = new URL(url);
//console.log(urlObj);
let hash = urlObj.hash !== '' ? decodeURIComponent(urlObj.hash).slice(1) : ''; // #をとる let pureURL = ${urlObj.origin}${urlObj.pathname}${urlObj.search};
const {title, meta, DOM} = await fetchURLInfo(pureURL, {DOM: true});
//console.log({title, meta, DOM});
return (config.find(({match}) => match.test(url))?.text ?? defaultConfig)({
url,
pureURL,
title,
hash,
meta,
dom: DOM,
});
}
const format = text => text
.trim().replace(/\n\r\f/g, '').replace(' ?'[').replace(' ?', ']'); function defaultConfig({url, title, hash, dom}) {
if (!title) return url;
const subtitle = dom.getElementById(hash)?.textContent;
return subtitle ?
[${url} ${format(subtitle)} | ${format(title)}] :
[${url} ${format(title)}];
}