trpl-zh-cn/ferris.js

65 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-12-06 22:53:14 +08:00
var ferrisTypes = [
{
attr: 'does_not_compile',
2022-07-18 14:27:32 +08:00
title: '这段代码无法通过编译!'
},
{
attr: 'panics',
2022-07-18 14:27:32 +08:00
title: '这段代码会 Panic'
},
{
attr: 'not_desired_behavior',
2022-07-18 14:27:32 +08:00
title: '这段代码的运行结果不符合预期。'
}
]
document.addEventListener('DOMContentLoaded', () => {
for (var ferrisType of ferrisTypes) {
attachFerrises(ferrisType)
}
})
2022-02-06 22:46:20 +08:00
function attachFerrises(type) {
var elements = document.getElementsByClassName(type.attr)
for (var codeBlock of elements) {
2022-02-06 22:46:20 +08:00
var lines = codeBlock.innerText.replace(/\n$/, '').split(/\n/).length
var size = 'large'
if (lines < 4) {
size = 'small'
2018-12-06 22:53:14 +08:00
}
2022-02-06 22:46:20 +08:00
var container = prepareFerrisContainer(codeBlock, size == 'small')
container.appendChild(createFerris(type, size))
}
}
function prepareFerrisContainer(element, useButtons) {
var foundButtons = element.parentElement.querySelector('.buttons')
if (useButtons && foundButtons) {
return foundButtons
2018-12-06 22:53:14 +08:00
}
2022-02-06 22:46:20 +08:00
var div = document.createElement('div')
div.classList.add('ferris-container')
element.parentElement.insertBefore(div, element)
return div
}
2022-02-06 22:46:20 +08:00
function createFerris(type, size) {
var a = document.createElement('a')
a.setAttribute('href', 'ch00-00-introduction.html#ferris')
a.setAttribute('target', '_blank')
var img = document.createElement('img')
img.setAttribute('src', 'img/ferris/' + type.attr + '.svg')
img.setAttribute('title', type.title)
2022-02-06 22:46:20 +08:00
img.classList.add('ferris')
img.classList.add('ferris-' + size)
a.appendChild(img)
2022-02-06 22:46:20 +08:00
return a
}