Skip to content
Myr

termynal.js

This file

Path

docs/js/termynal.js

265 lines · 9.3 KiB · JavaScript

Last changed by

🐛 Fix showing `fast` button as external link in animated terminals in docs (#1912)Philipp Stahlbergbefore adoption904a3b2

History of this file

Take it

The walk stopped after 200 commits: lines older than 3780a29 point at it.

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

lines 1–129why, one step back
1/**
2 * termynal.js3 * A lightweight, modern and extensible animated terminal window, using4 * async/await.5 *6 * @author Ines Montani <ines@ines.io>7 * @version 0.0.18 * @license MIT9 */1011'use strict';1213/** Generate a terminal widget. */14class Termynal {15 /**16 * Construct the widget's settings.17 * @param {(string|Node)=} container - Query selector or container element.18 * @param {Object=} options - Custom settings.19 * @param {string} options.prefix - Prefix to use for data attributes.20 * @param {number} options.startDelay - Delay before animation, in ms.21 * @param {number} options.typeDelay - Delay between each typed character, in ms.22 * @param {number} options.lineDelay - Delay between each line, in ms.23 * @param {number} options.progressLength - Number of characters displayed as progress bar.24 * @param {string} options.progressChar – Character to use for progress bar, defaults to █.25 * @param {number} options.progressPercent - Max percent of progress.26 * @param {string} options.cursor – Character to use for cursor, defaults to ▋.27 * @param {Object[]} lineData - Dynamically loaded line data objects.28 * @param {boolean} options.noInit - Don't initialise the animation.29 */30 constructor(container = '#termynal', options = {}) {31 this.container = (typeof container === 'string') ? document.querySelector(container) : container;32 this.pfx = `data-${options.prefix || 'ty'}`;33 this.originalStartDelay = this.startDelay = options.startDelay34 || parseFloat(this.container.getAttribute(`${this.pfx}-startDelay`)) || 600;35 this.originalTypeDelay = this.typeDelay = options.typeDelay36 || parseFloat(this.container.getAttribute(`${this.pfx}-typeDelay`)) || 90;37 this.originalLineDelay = this.lineDelay = options.lineDelay38 || parseFloat(this.container.getAttribute(`${this.pfx}-lineDelay`)) || 1500;39 this.progressLength = options.progressLength40 || parseFloat(this.container.getAttribute(`${this.pfx}-progressLength`)) || 40;41 this.progressChar = options.progressChar42 || this.container.getAttribute(`${this.pfx}-progressChar`) || '█';43 this.progressPercent = options.progressPercent44 || parseFloat(this.container.getAttribute(`${this.pfx}-progressPercent`)) || 100;45 this.cursor = options.cursor46 || this.container.getAttribute(`${this.pfx}-cursor`) || '▋';47 this.lineData = this.lineDataToElements(options.lineData || []);48 this.loadLines()49 if (!options.noInit) this.init()50 }5152 loadLines() {53 // Load all the lines and create the container so that the size is fixed54 // Otherwise it would be changing and the user viewport would be constantly55 // moving as she/he scrolls56 const finish = this.generateFinish()57 finish.style.visibility = 'hidden'58 this.container.appendChild(finish)59 // Appends dynamically loaded lines to existing line elements.60 this.lines = [...this.container.querySelectorAll(`[${this.pfx}]`)].concat(this.lineData);61 for (let line of this.lines) {62 line.style.visibility = 'hidden'63 this.container.appendChild(line)64 }65 const restart = this.generateRestart()66 restart.style.visibility = 'hidden'67 this.container.appendChild(restart)68 this.container.setAttribute('data-termynal', '');69 }7071 /**72 * Initialise the widget, get lines, clear container and start animation.73 */74 init() {75 /**76 * Calculates width and height of Termynal container.77 * If container is empty and lines are dynamically loaded, defaults to browser `auto` or CSS.78 */79 const containerStyle = getComputedStyle(this.container);80 this.container.style.width = containerStyle.width !== '0px' ?81 containerStyle.width : undefined;82 this.container.style.minHeight = containerStyle.height !== '0px' ?83 containerStyle.height : undefined;8485 this.container.setAttribute('data-termynal', '');86 this.container.innerHTML = '';87 for (let line of this.lines) {88 line.style.visibility = 'visible'89 }90 this.start();91 }9293 /**94 * Start the animation and rener the lines depending on their data attributes.95 */96 async start() {97 this.addFinish()98 await this._wait(this.startDelay);99100 for (let line of this.lines) {101 const type = line.getAttribute(this.pfx);102 const delay = line.getAttribute(`${this.pfx}-delay`) || this.lineDelay;103104 if (type == 'input') {105 line.setAttribute(`${this.pfx}-cursor`, this.cursor);106 await this.type(line);107 await this._wait(delay);108 }109110 else if (type == 'progress') {111 await this.progress(line);112 await this._wait(delay);113 }114115 else {116 this.container.appendChild(line);117 await this._wait(delay);118 }119120 line.removeAttribute(`${this.pfx}-cursor`);121 }122 this.addRestart()123 this.finishElement.style.visibility = 'hidden'124 this.lineDelay = this.originalLineDelay125 this.typeDelay = this.originalTypeDelay126 this.startDelay = this.originalStartDelay127 }128129 generateRestart() {

🐛 Fix showing `fast` button as external link in animated terminals in docs (#1912)Philipp Stahlbergbefore adoption904a3b2

lines 130–133why, one step back
130 const restart = document.createElement('button')
131 restart.type = 'button'132133 restart.onclick = () => {

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

lines 134–136why, one step back
134 this.container.innerHTML = ''
135 this.init()136 }

🐛 Fix showing `fast` button as external link in animated terminals in docs (#1912)Philipp Stahlbergbefore adoption904a3b2

line 137why, one step back
137

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

lines 138–143why, one step back
138 restart.setAttribute('data-terminal-control', '')
139 restart.innerHTML = "restart ↻"140 return restart141 }142143 generateFinish() {

🐛 Fix showing `fast` button as external link in animated terminals in docs (#1912)Philipp Stahlbergbefore adoption904a3b2

lines 144–147why, one step back
144 const finish = document.createElement('button')
145 finish.type = 'button'146147 finish.onclick = () => {

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

lines 148–151why, one step back
148 this.lineDelay = 0
149 this.typeDelay = 0150 this.startDelay = 0151 }

🐛 Fix showing `fast` button as external link in animated terminals in docs (#1912)Philipp Stahlbergbefore adoption904a3b2

line 152why, one step back
152

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

lines 153–265why, one step back
153 finish.setAttribute('data-terminal-control', '')
154 finish.innerHTML = "fast →"155 this.finishElement = finish156 return finish157 }158159 addRestart() {160 const restart = this.generateRestart()161 this.container.appendChild(restart)162 }163164 addFinish() {165 const finish = this.generateFinish()166 this.container.appendChild(finish)167 }168169 /**170 * Animate a typed line.171 * @param {Node} line - The line element to render.172 */173 async type(line) {174 const chars = [...line.textContent];175 line.textContent = '';176 this.container.appendChild(line);177178 for (let char of chars) {179 const delay = line.getAttribute(`${this.pfx}-typeDelay`) || this.typeDelay;180 await this._wait(delay);181 line.textContent += char;182 }183 }184185 /**186 * Animate a progress bar.187 * @param {Node} line - The line element to render.188 */189 async progress(line) {190 const progressLength = line.getAttribute(`${this.pfx}-progressLength`)191 || this.progressLength;192 const progressChar = line.getAttribute(`${this.pfx}-progressChar`)193 || this.progressChar;194 const chars = progressChar.repeat(progressLength);195 const progressPercent = line.getAttribute(`${this.pfx}-progressPercent`)196 || this.progressPercent;197 line.textContent = '';198 this.container.appendChild(line);199200 for (let i = 1; i < chars.length + 1; i++) {201 await this._wait(this.typeDelay);202 const percent = Math.round(i / chars.length * 100);203 line.textContent = `${chars.slice(0, i)} ${percent}%`;204 if (percent>progressPercent) {205 break;206 }207 }208 }209210 /**211 * Helper function for animation delays, called with `await`.212 * @param {number} time - Timeout, in ms.213 */214 _wait(time) {215 return new Promise(resolve => setTimeout(resolve, time));216 }217218 /**219 * Converts line data objects into line elements.220 *221 * @param {Object[]} lineData - Dynamically loaded lines.222 * @param {Object} line - Line data object.223 * @returns {Element[]} - Array of line elements.224 */225 lineDataToElements(lineData) {226 return lineData.map(line => {227 let div = document.createElement('div');228 div.innerHTML = `<span ${this._attributes(line)}>${line.value || ''}</span>`;229230 return div.firstElementChild;231 });232 }233234 /**235 * Helper function for generating attributes string.236 *237 * @param {Object} line - Line data object.238 * @returns {string} - String of attributes.239 */240 _attributes(line) {241 let attrs = '';242 for (let prop in line) {243 // Custom add class244 if (prop === 'class') {245 attrs += ` class=${line[prop]} `246 continue247 }248 if (prop === 'type') {249 attrs += `${this.pfx}="${line[prop]}" `250 } else if (prop !== 'value') {251 attrs += `${this.pfx}-${prop}="${line[prop]}" `252 }253 }254 return attrs;255 }256}257258/**259* HTML API: If current script has container(s) specified, initialise Termynal.260*/261if (document.currentScript.hasAttribute('data-termynal-container')) {262 const containers = document.currentScript.getAttribute('data-termynal-container');263 containers.split('|')264 .forEach(container => new Termynal(container))265}