js(async () => {
const projectName = 'programming-notes';
const pageTitle = '補完windowのonClickテスト';
const promises = [
import(`/api/code/${projectName}/scrapbox-suggest-container/test-dom.js`),
//import(`/api/code/${projectName}/scrapbox-suggest-container/test-dark-theme.js`),
import(`/api/code/${projectName}/scrapbox-suggest-container/script.js`),
];
const promise = import(`/api/code/${projectName}/${pageTitle}/test1-project-list.js`);
const worker = new Worker(`/api/code/${projectName}/${pageTitle}/test1-worker.js`);
worker.postMessage({type: 'fetch', projects: (await promise).projects});
const [{editor, cursor},] = await Promise.all(promises);
// 入力補完windowを作る
const suggestBox = document.createElement('suggest-container');
editor.append(suggestBox);
// とりあえず、cursorに追随するだけにする
const observer = new MutationObserver(() =>{
suggestBox.show({
top: parseInt(cursor.style.top) + 14,
left: parseInt(cursor.style.left),
});
});
observer.observe(cursor, {attributes: true});
// tabキーで選択する
editor.addEventListener('keydown', e => {
if (this.hidden) return;
if (e.key === 'i' && e.ctrlKey) {
e.preventDefault();
e.stopPropagation();
suggestBox.selectedItem.click({}, true);
return;
}
if (e.key !== 'Tab') return;
if (e.altKey || e.ctrlKey) return;
e.preventDefault();
e.stopPropagation();
if (e.shiftKey) {
suggestBox.selectPrevious({wrap: true});
} else {
suggestBox.selectNext({wrap: true});
}
});
// あいまい検索して、候補を入力補完windowに追加する
window.search = (word, {limit = 30, timeout = 10000,} = {}) => {
// 時間がかかるようであればLoading表示をする
const timer = setTimeout(() => {
const image = /paper-dark-dark|default-dark/
.test(document.head.parentElement.dataset.projectTheme) ?
'https://img.icons8.com/ios/180/FFFFFF/loading.png' :
'https://img.icons8.com/ios/180/loading.png';
suggestBox.pushFirst({text: 'Loading...', image,});
}, 1000);
worker.postMessage({type: 'search', word, limit, timeout});
worker.addEventListener('message', ({data: {links}}) => {
clearTimeout(timer);
suggestBox.clear();
suggestBox.push(...links.flat().map(link => {
return {
text: link,
link: `https://scrapbox.io${link}`,
onClick: (e, icon) => {
if (e.ctrlKey) {
window.open(`https://scrapbox.io${link}`);
return;
}
const text = icon ? `[${link}.icon]` : `[${link}]`;
insertText(text);
},
};
}));
}, {once: true});
};
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);
}
})();