テーブルを横スクロールできるようにする
code:script.js
// Functions
/** @param {HTMLElement} movedElem */
const scrollWholeTable = movedElem => {
const tableName = movedElem.className.match(new RegExp(${CLASS_COMMON}-\\d+))0 for (let tableElem of document.querySelectorAll(.${tableName})) {
if (tableElem === movedElem) { continue }
tableElem.scrollLeft = movedElem.scrollLeft
}
}
/**
* @param {HTMLElement} line
* @return {HTMLElement}
*/
const line2Elem = line => document.getElementById(L${line.id})
// ticking=falseのときだけ再描画を依頼、再描画時にfalseに戻すことでイベントを間引く
/** @return {function(HTMLElement)} */
const tickClosure = () => {
let ticking = false
const scrollWholeTableWithTick = movedElem => e => {
if (!ticking) {
window.requestAnimationFrame(() => {
scrollWholeTable(movedElem)
ticking = false
})
ticking = true
}
}
return scrollWholeTableWithTick
}
// Settings
const CLASS_COMMON = 'scrollTable'
const CLASS_BOTTOM = ${CLASS_COMMON}Bottom
const getTableUniqueName = n => ${CLASS_COMMON}-${n}
// main
const enableTableScroll = () => {
let isTable = false
let nTable = 0
let currentTableName = ''
let currentLineElem
// Scrapbox側のDOM操作(例: cursor-line付与)でtable名のクラスが消える問題対策
const ensureTableName = mut => {
const withPrefix = mut => mut.target.classList.contains(CLASS_COMMON)
if ((mut.type === 'attributes') && !withPrefix(mut)) { enableTableScroll() }
}
const observer = new MutationObserver(mutations => mutations.forEach(ensureTableName))
// テーブルへのクラス名付与
// テーブル最下行を特別扱いしたいので、逆順に読む
for (const line of scrapbox.Page.lines.reverse()) {
if ('tableBlock' in line) {
const tableRowElem = line2Elem(line).querySelector('.table-block-row')
if (!tableRowElem) { isTable = false; continue } // テーブルヘッダ = 逆順での読み終わり行
const addClass = _className => tableRowElem.classList.add(_className)
// テーブル最下行発見
if (!isTable) {
isTable = true
nTable++
currentTableName = getTableUniqueName(nTable)
addClass(CLASS_BOTTOM)
}
// テーブル共通処理
addClass(CLASS_COMMON)
addClass(currentTableName)
// 他を追従させる処理 + DOM変化をobserveしてクラス名消失を防ぐ
const scrollWholeTableWithTick = tickClosure()
tableRowElem.addEventListener('scroll', scrollWholeTableWithTick(tableRowElem))
// onclick?でDOM更新されてクラス名が消えてしまうので、監視して再度付与
observer.observe(tableRowElem, { attributes: true })
}
}
}
enableTableScroll()
scrapbox.on('lines:changed', enableTableScroll)