scrapbox-preview-box/parser
[scrapbox-preview-box]に表示するDOMを作るmodule[scrapbox-parser.min.js]を用いる要件タイトルは予め削って渡す[scrapbox-preview-boxで表示するテキストのDOM構造]をhtml文字列にして返す
emitChange
を導入する setTimeout
を使う title
と project
を設定する特別なmethodを使う /project/title
として一つの属性にまとめる #ditor
をscrollしたいときに面倒かも get title
と get project
を追加した <scrapbox-preview-box>
project
title
theme
<div>...</div>
<div>
で解析してhtmlにしたテキストを囲むだけconst css = `
:host {
padding: 5px 0px 5px 5px;
font-size: 11px;
line-height: 1.42857;
user-select: text;
position: absolute;
background-color: var(--page-bg, #fefefe);
color: var(--page-text-color, #4a4a4a);
border-radius: 4px;
box-shadow: 0 6px 12px rgba(0,0,0,0.175);
/*max-height: 80vh;
overflow-y: auto;*/
z-index: 9000;
}
`;
import {parse} from '../scrapbox-preview-box%2Fparser/script.js';
import {fragment, h} from '../easyDOMgenerator/script.js';
customElements.define('preview-box', class extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open', delegatesFocus: true});
shadow.innerHTML =
`<style>${css}</style>
<div id="box"></div>`;
this._box = shadow.getElementById('box');
this._onmouseenterCallback = undefined;
this._onmouseleaveCallback = undefined;
this._loading = undefined;
}
connectedCallback() {
this.hide();
}
get project() {
return this._project;
}
get title() {
return this._title;
}
set path(value) {
this.setAttribute('path', value);
}
set theme(value) {
this.setAttribute('theme', value);
}
position({top, left}) {
this.style.top = `${top}px`;
this.style.left = `${left}px`;
}
async show() {
await this._loading;
// 空っぽの場合は表示しない
// defaultで<style>が含まれるので、nodeが2個以上のときのみ表示する
if (this._box.childElementCount < 2) {
this.hide();
return;
}
this.hidden = false;
if(!this._lineId) return;
/*
// 行IDまでscrollする
// web page全体も一緒にscrollされてしまうので、その分を戻しておく
const scrollY = window.scrollY;
this.shadowRoot.getElementById(`L${this._lineId}`)?.scrollIntoView?.({block: 'start'});
window.scroll(0, scrollY);
*/
}
hide() {
this.hidden = true;
}
set onmouseenterInLink(callback) {
this.shadowRoot.removeEventListener('mouseenter', this._onmouseenterCallback, {capture: true});
this._onmouseenterCallback = e => {
if (!e.target.matches('.page-link')) return;
callback(e);
};
this.shadowRoot.addEventListener('mouseenter', this._onmouseenterCallback, {capture: true});
}
static get observedAttributes() {
return ['path', 'theme'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) return;
switch(name) {
case 'path':
const [project, title] = decodeURIComponent(newValue)
.match(/^\/([\w\-]+)\/(.+)$/).slice(1);
this._project = project;
this._title = title;
this._createBody();
break;
case 'theme':
// 未実装
break;
}
}
_createBody() {
if (!this._project || !this._title) return;
this._lineId = this._title.match(/#([\d\w+]+)$/)?.[1];
const title = this._lineId ? this._title.slice(0, -this._lineId.length - 1) : this._title;
this._loading = (async () => {
const res = await fetch(`/api/pages/${this._project}/${encodeURIComponent(title)}`);
if (!res.ok) {
this._replace(
document.createTextNode('An invalid page source.')
);
return;
}
let {lines} = await res.json();
// title行は除く
lines = lines.slice(1);
const lineDOMs = parse(lines, this._project, this._title);
if (!this._lineId) {
this._replace(...lineDOMs);
return;
}
// 行ID以降のみを表示する
const id = `L${this._lineId}`;
const index = lineDOMs.findIndex(dom => dom.id === id);
if (index < 0) {
this._replace(...lineDOMs);
return;
}
this._replace(lineDOMs[0], ...lineDOMs.slice(index)); // 先頭の<style>は削っちゃだめ
// 行ID部分をhighlightしておく
this.shadowRoot.getElementById(id).classList.add('permalink');
})();
}
_replace(...newElements) {
this._box.textContent = '';
if (newElements.length === 0) return;
this._box.append(...newElements);
}
});
export const previewBox = (...params) => h('preview-box', ...params);
import('/api/code/programming-notes/scrapbox-preview-box/test1.js');
import {previewBox as create} from './script.js';
import {scrapboxDOM} from '../scrapbox-dom-accessor/script.js';
(async () => {
const box = previewBox({path: '/programming-notes/scrapbox-preview-boxで表示するテキストのDOM構造'});
scrapboxDOM.editor.append(box);
const observer = new MutationObserver(async () =>{
box.position({
top: parseInt(scrapboxDOM.cursor.style.top) + 14,
left: parseInt(scrapboxDOM.cursor.style.left),
});
await box.show();
});
observer.observe(scrapboxDOM.cursor, {attributes: true});
})();
this.hide()
を previewBox.hide()
に直すのを忘れてた if (timer) return
を消したら直った this
ではなく this.shadowRoot
に対してevent listenerを登録したらうまくいった <preview-box>
に <preview-box>
を入れただけでは表示されない #editor
に全部配置するか? div#preview-box-list
みたいなのを用意して、その中に全て放り込んでおく #editor
に配置してもいいか max-width
を動的に指定する方法でもいいかimport('/api/code/programming-notes/scrapbox-preview-box/test2.js');
import {previewBox as create} from './script.js';
import {scrapboxDOM} from '../scrapbox-dom-accessor/script.js';
let timer = null;
(async () => {
const previewBox = await createPreviewBox(scrapboxDOM.editor);
scrapboxDOM.editor.addEventListener('mouseenter', ({target}) => {
if (!target.matches('.page-link')
|| scrapbox.Layout !== 'page') return;
onmouseenter(previewBox, {target});
}, {capture: true});
scrapboxDOM.editor.addEventListener('mouseleave', ({target}) => {
if (!target.matches('.page-link')
|| scrapbox.Layout !== 'page') return;
fadeoutCallback(previewBox)
}, {capture: true});
scrapboxDOM.editor.addEventListener('click', ({target}) => {
if (target.matches('preview-box')) return;
previewBox.hide();
}, {capture: true});
addEventListener('wheel', () => clearTimeout(timer));
})();
async function createPreviewBox(parentNode) {
const previewBox = await create();
let childBox = undefined;
previewBox.onmouseenterInLink = async (e) => {
if (!childBox) childBox = await createPreviewBox(previewBox);
onmouseenter(childBox, e);
};
previewBox.addEventListener('mouseenter', () => clearTimeout(timer));
previewBox.addEventListener('mouseleave', () => fadeoutCallback(previewBox));
previewBox.addEventListener('click', ({target}) => {
if (target.matches('preview-box')) return;
previewBox.hide();
});
parentNode.append(previewBox);
return previewBox;
}
function onmouseenter(previewBox, {target}) {
const [_, project, title] = target.href.match(/scrapbox\.io\/([^\/]+)\/(.+)$/);
previewBox.path = `/${project}/${title}`;
clearTimeout(timer);
timer = setTimeout(async () => {
const {top, left} = target.getBoundingClientRect();
const parent = previewBox.parentElement.getBoundingClientRect();
previewBox.position({
top: top + 18 - parent.top,
left: left - parent.left,
});
await previewBox.show();
}, 650);
target.addEventListener('mouseleave', () => {
clearTimeout(timer);
fadeoutCallback(previewBox);
}, {once: true});
}
function fadeoutCallback(previewBox) {
if (previewBox.hidden) return;
clearTimeout(timer);
timer = setTimeout(() => {
previewBox.hide();
}, 650);
}