forked from rust-lang/book
-
Notifications
You must be signed in to change notification settings - Fork 103
/
ferris.js
100 lines (82 loc) · 2.49 KB
/
ferris.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// @ts-check
/**
* @typedef {{ attr: string, title: string }} FerrisType
*/
/** @type {Array<FerrisType>} */
const FERRIS_TYPES = [
{
attr: 'does_not_compile',
title: 'This code does not compile!'
},
{
attr: 'panics',
title: 'This code panics!'
},
{
attr: 'not_desired_behavior',
title: 'This code does not produce the desired behavior.'
}
]
document.addEventListener('DOMContentLoaded', () => {
for (let ferrisType of FERRIS_TYPES) {
attachFerrises(ferrisType)
}
})
/**
* @param {FerrisType} type
*/
function attachFerrises(type) {
let elements = document.getElementsByClassName(type.attr)
for (let codeBlock of elements) {
// Skip SVG etc.: in principle, these should never be attached to those, but
// this means if someone happens to have a browser extension which *is*
// attaching them, it will not break the code.
if (!(codeBlock instanceof HTMLElement)) {
continue
}
let lines = codeBlock.innerText.replace(/\n$/, '').split(/\n/).length
/** @type {'small' | 'large'} */
let size = lines < 4 ? 'small' : 'large'
let container = prepareFerrisContainer(codeBlock, size == 'small')
if (!container) {
continue
}
container.appendChild(createFerris(type, size))
}
}
/**
* @param {HTMLElement} element - Code block element to attach a Ferris to.
* @param {boolean} useButtons - Whether to attach to existing buttons.
* @returns {Element | null} - The container element to use.
*/
function prepareFerrisContainer(element, useButtons) {
let foundButtons = element.parentElement?.querySelector('.buttons')
if (useButtons && foundButtons) {
return foundButtons
}
let div = document.createElement('div')
div.classList.add('ferris-container')
if (!element.parentElement) {
console.error(`Could not install Ferris on ${element}, which is missing a parent`);
return null;
}
element.parentElement.insertBefore(div, element)
return div
}
/**
* @param {FerrisType} type
* @param {'small' | 'large'} size
* @returns {HTMLAnchorElement} - The generated anchor element.
*/
function createFerris(type, size) {
let a = document.createElement('a')
a.setAttribute('href', 'ch00-00-introduction.html#ferris')
a.setAttribute('target', '_blank')
let img = document.createElement('img')
img.setAttribute('src', 'img/ferris/' + type.attr + '.svg')
img.setAttribute('title', type.title)
img.classList.add('ferris')
img.classList.add('ferris-' + size)
a.appendChild(img)
return a
}