convert.jsexport 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++) {
if (!links[i]) break;
map[urls[i]]= links[i];
}
//console.log(map);
const result = text.replace(/https?:\/\/\S+/g, match => map[match] ?? match);
//console.log(result);
return result;
}
async function convert(url, config) {
if (!window.fetchURLInfo) {
alert('Please install "fetchURLInfo" from https://scrapbox.io/programming-notes/url-info-proxy');
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)}]`;
}