razokulover
https://gyazo.com/93c1715c8c5c6ac07fd7a43aeb8f05aa
code:script.js
import '/api/code/shokai/ページの1部分を別のページに切り出すUserScript/script.js'
// 見出しを階層構造で見やすくする
(function () {
// Google 翻訳
scrapbox.PopupMenu.addButton({
title: 'Google翻訳',
onClick: text => window.open(https://translate.google.com/#ja/en/${text})
})
// daiiz氏の便利UserScript集から。ctrl+shift+vでリンク貼り付けするとタイトルまで取って来てくれるやつ
$('body').attr('data-daiiz-paste-url-title', 'ctrl');
scrapbox.PageMenu.addMenu({
title: '見出し',
onClick: () => {
scrapbox.PageMenu('見出し').removeAllItems()
var deepest = 0;
for (let line of scrapbox.Page.lines) {
if (!line.section.start) continue
var depth = line.nodes ? calcDepth(line.nodes) : 0
if (deepest < depth) deepest = depth
}
console.log('deepest index is ' + deepest)
let i = 0
for (let line of scrapbox.Page.lines) {
if (!line.section.start && !(i === 1 && line.text.match(/\[.+/))) continue
i += 1
const image = line.nodes && getIconUrl(line.nodes)
const noIcon = !!image
const title = line.nodes ? renderPlainText(line.nodes, {noIcon, level: 0}, deepest) : line.text
const onClick = () => location.hash = line.id
scrapbox.PageMenu('見出し').addItem({title, image, onClick})
}
}
})
function calcDepth (node) {
if (node instanceof Array) return node.map(node => calcDepth(node)).reduce(function(a,b) {return Math.max(a,b);}, 0)
if (typeof node === 'string') return 0
if (node.type == 'deco') {
var deco = '*'
for (var i=1; i<=5; i++) {
if (node.unit.deco == deco) return i
deco = deco + '*'
}
}
return calcDepth(node.children)
}
function renderPlainText (node, options, deepest) {
if (node instanceof Array) return node.map(node => renderPlainText(node, options, deepest)).join('')
if (typeof node === 'string') {
var indent = deepest - options.level
var item = node
if (options.level == 1) item = '・' + item
if (options.level == 2) item = '● ' + item
if (options.level == 3) item = '■ ' + item
if (options.level == 4) item = '■ ' + item
if (options.level == 5) item = '■ ' + item
for (var i=0; i<indent; i++) item = ' ' + item;
return item
}
var new_options = Object.assign({}, options)
switch (node.type) {
case 'icon':
case 'strong-icon':
return options.noIcon ? ' ' : node.unit.page
case 'deco':
new_options.level = 0
var deco = '*'
for (var i=1; i<=5; i++) {
if (node.unit.deco == deco) new_options.level = i
deco = deco + '*'
}
}
return renderPlainText(node.children, new_options, deepest)
}
function getIconUrl (node) {
if (/icon/.test(node.type)) {
return /api/pages/${node.unit.project||scrapbox.Project.name}/${node.unit.page}/icon
}
if (node instanceof Array) {
return node.map(getIconUrl).find(img => img)
}
return null
}
})()