:sparkles: Add termynal for awesome docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parents 7fc3d12, e3327b0 · Browse files · 6 files·+429 added−81 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+429 added−81 removed
- other:+429 added−81 removed
Provenance
- Commit
c004fb6- Tree
27b9004- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
7fc3d12- Parent 2
e3327b0
6 files changed+429 added−81 removed
added:docs/css/custom.css+4 added
1234.termynal-comment { color: #999; font-style: italic;}added:docs/css/termynal.css+101 added
1+/**2+ * termynal.js3+ *4+ * @author Ines Montani <ines@ines.io>5+ * @version 0.0.16+ * @license MIT7+ */8+9+:root {10+ --color-bg: #252a33;11+ --color-text: #eee;12+ --color-text-subtle: #a2a2a2;13+}14+15+[data-termynal] {16+ width: 750px;17+ max-width: 100%;18+ background: var(--color-bg);19+ color: var(--color-text);20+ font-size: 18px;21+ font-family: 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace;22+ border-radius: 4px;23+ padding: 75px 45px 35px;24+ position: relative;25+ -webkit-box-sizing: border-box;26+ box-sizing: border-box;27+}28+29+[data-termynal]:before {30+ content: '';31+ position: absolute;32+ top: 15px;33+ left: 15px;34+ display: inline-block;35+ width: 15px;36+ height: 15px;37+ border-radius: 50%;38+ /* A little hack to display the window buttons in one pseudo element. */39+ background: #d9515d;40+ -webkit-box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930;41+ box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930;42+}43+44+[data-termynal]:after {45+ content: 'bash';46+ position: absolute;47+ color: var(--color-text-subtle);48+ top: 5px;49+ left: 0;50+ width: 100%;51+ text-align: center;52+}53+54+[data-ty] {55+ display: block;56+ line-height: 2;57+}58+59+[data-ty]:before {60+ /* Set up defaults and ensure empty lines are displayed. */61+ content: '';62+ display: inline-block;63+ vertical-align: middle;64+}65+66+[data-ty="input"]:before,67+[data-ty-prompt]:before {68+ margin-right: 0.75em;69+ color: var(--color-text-subtle);70+}71+72+[data-ty="input"]:before {73+ content: '$';74+}75+76+[data-ty][data-ty-prompt]:before {77+ content: attr(data-ty-prompt);78+}79+80+[data-ty-cursor]:after {81+ content: attr(data-ty-cursor);82+ font-family: monospace;83+ margin-left: 0.5em;84+ -webkit-animation: blink 1s infinite;85+ animation: blink 1s infinite;86+}87+88+89+/* Cursor animation */90+91+@-webkit-keyframes blink {92+ 50% {93+ opacity: 0;94+ }95+}96+97+@keyframes blink {98+ 50% {99+ opacity: 0;100+ }101+}added:docs/js/custom.js+76 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576document.querySelectorAll(".use-termynal").forEach(node => { node.style.display = "block"; new Termynal(node);});const progressLiteralStart = "---> 100%";const promptLiteralStart = "$ ";const termynalActivateClass = "termy";
function loadVisibleTermynals() { document .querySelectorAll(`.${termynalActivateClass} .codehilite`) .forEach(node => { if (node.getBoundingClientRect().top - innerHeight <= 0) { const text = node.textContent; const lines = text.split("\n"); const useLines = []; let buffer = []; function saveBuffer() { if (buffer.length) { let isBlankSpace = true buffer.forEach(line => { if (line) { isBlankSpace = false } }) dataValue = {} if (isBlankSpace) { dataValue["delay"] = 0 } if (buffer.length > 1 && buffer[buffer.length - 1] === "") { // The last single <br> won't have effect // so put an additional one buffer.push(""); } const bufferValue = buffer.join("<br>"); dataValue["value"] = bufferValue useLines.push(dataValue); buffer = []; } } for (let line of lines) { if (line === progressLiteralStart) { saveBuffer(); useLines.push({ type: "progress" }); } else if (line.startsWith(promptLiteralStart)) { saveBuffer(); const value = line.replace(promptLiteralStart, "").trimEnd(); useLines.push({ type: "input", value: value }); } else if (line.startsWith("// ")) { saveBuffer(); const value = line.replace("// ", "").trimEnd(); useLines.push({ value: value, class: "termynal-comment", delay: 0 }); } else { buffer.push(line); } } saveBuffer(); const div = document.createElement("div"); node.replaceWith(div); const termynal = new Termynal(div, { lineData: useLines }); } });}window.addEventListener("scroll", loadVisibleTermynals);loadVisibleTermynals();added:docs/js/termynal.js+202 added
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+ */10+11+'use strict';12+13+/** Generate a terminal widget. */14+class 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.startDelay = options.startDelay34+ || parseFloat(this.container.getAttribute(`${this.pfx}-startDelay`)) || 600;35+ this.typeDelay = options.typeDelay36+ || parseFloat(this.container.getAttribute(`${this.pfx}-typeDelay`)) || 90;37+ 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+ if (!options.noInit) this.init()49+ }50+51+ /**52+ * Initialise the widget, get lines, clear container and start animation.53+ */54+ init() {55+ // Appends dynamically loaded lines to existing line elements.56+ this.lines = [...this.container.querySelectorAll(`[${this.pfx}]`)].concat(this.lineData);57+58+ /** 59+ * Calculates width and height of Termynal container.60+ * If container is empty and lines are dynamically loaded, defaults to browser `auto` or CSS.61+ */ 62+ const containerStyle = getComputedStyle(this.container);63+ this.container.style.width = containerStyle.width !== '0px' ? 64+ containerStyle.width : undefined;65+ this.container.style.minHeight = containerStyle.height !== '0px' ? 66+ containerStyle.height : undefined;67+68+ this.container.setAttribute('data-termynal', '');69+ this.container.innerHTML = '';70+ this.start();71+ }72+73+ /**74+ * Start the animation and rener the lines depending on their data attributes.75+ */76+ async start() {77+ await this._wait(this.startDelay);78+79+ for (let line of this.lines) {80+ const type = line.getAttribute(this.pfx);81+ const delay = line.getAttribute(`${this.pfx}-delay`) || this.lineDelay;82+83+ if (type == 'input') {84+ line.setAttribute(`${this.pfx}-cursor`, this.cursor);85+ await this.type(line);86+ await this._wait(delay);87+ }88+89+ else if (type == 'progress') {90+ await this.progress(line);91+ await this._wait(delay);92+ }93+94+ else {95+ this.container.appendChild(line);96+ await this._wait(delay);97+ }98+99+ line.removeAttribute(`${this.pfx}-cursor`);100+ }101+ }102+103+ /**104+ * Animate a typed line.105+ * @param {Node} line - The line element to render.106+ */107+ async type(line) {108+ const chars = [...line.textContent];109+ const delay = line.getAttribute(`${this.pfx}-typeDelay`) || this.typeDelay;110+ line.textContent = '';111+ this.container.appendChild(line);112+113+ for (let char of chars) {114+ await this._wait(delay);115+ line.textContent += char;116+ }117+ }118+119+ /**120+ * Animate a progress bar.121+ * @param {Node} line - The line element to render.122+ */123+ async progress(line) {124+ const progressLength = line.getAttribute(`${this.pfx}-progressLength`)125+ || this.progressLength;126+ const progressChar = line.getAttribute(`${this.pfx}-progressChar`)127+ || this.progressChar;128+ const chars = progressChar.repeat(progressLength);129+ const progressPercent = line.getAttribute(`${this.pfx}-progressPercent`)130+ || this.progressPercent;131+ line.textContent = '';132+ this.container.appendChild(line);133+134+ for (let i = 1; i < chars.length + 1; i++) {135+ await this._wait(this.typeDelay);136+ const percent = Math.round(i / chars.length * 100);137+ line.textContent = `${chars.slice(0, i)} ${percent}%`;138+ if (percent>progressPercent) {139+ break;140+ }141+ }142+ }143+144+ /**145+ * Helper function for animation delays, called with `await`.146+ * @param {number} time - Timeout, in ms.147+ */148+ _wait(time) {149+ return new Promise(resolve => setTimeout(resolve, time));150+ }151+152+ /**153+ * Converts line data objects into line elements.154+ * 155+ * @param {Object[]} lineData - Dynamically loaded lines.156+ * @param {Object} line - Line data object.157+ * @returns {Element[]} - Array of line elements.158+ */159+ lineDataToElements(lineData) {160+ return lineData.map(line => {161+ let div = document.createElement('div');162+ div.innerHTML = `<span ${this._attributes(line)}>${line.value || ''}</span>`;163+164+ return div.firstElementChild;165+ });166+ }167+168+ /**169+ * Helper function for generating attributes string.170+ * 171+ * @param {Object} line - Line data object.172+ * @returns {string} - String of attributes.173+ */174+ _attributes(line) {175+ let attrs = '';176+ for (let prop in line) {177+ // Custom add class178+ if (prop === 'class') {179+ attrs += ` class=${line[prop]} `180+ continue181+ }182+ attrs += this.pfx;183+184+ if (prop === 'type') {185+ attrs += `="${line[prop]}" `186+ } else if (prop !== 'value') {187+ attrs += `-${prop}="${line[prop]}" `188+ }189+ }190+191+ return attrs;192+ }193+}194+195+/**196+* HTML API: If current script has container(s) specified, initialise Termynal.197+*/198+if (document.currentScript.hasAttribute('data-termynal-container')) {199+ const containers = document.currentScript.getAttribute('data-termynal-container');200+ containers.split('|')201+ .forEach(container => new Termynal(container))202+}modified:docs/index.md+38 added-81 removed
42 unmodified lines43 Typer stands on the shoulders of a giant. Its only internal dependency is <a href="https://click.palletsprojects.com/" target="_blank">Click</a>.44 45 ## Installation46 47+<div class="termy">47-```bash48-pip install typer48+```console49+$ pip install typer50+---> 100%51+Successfully installed typer52 ```53+</div>54 55 ## Example56 57 ### The absolute minimum15 unmodified lines73 ### Run it74 75 Run your application:76 73-```bash74-python main.py75-```77+<div class="termy">78+```console79+// Run your application80+$ python main.py81 77-you will get a response like:78-79-```82+// You get a nice error, you are missing NAME83 Usage: main.py [OPTIONS] NAME84 Try "main.py --help" for help.85 86 Error: Missing argument "NAME".84-```87 86-Now pass the `NAME` *argument*:88+// You get a --help for free89+$ python main.py --help90 88-```bash89-python main.py Camila90-```91+Usage: main.py [OPTIONS] NAME92 92-You will get a response like:93+Options:94+ --help Show this message and exit.95 94-```96+// Now pass the NAME argument97+$ python main.py Camila98+99 Hello Camila96-```100 98-And you automatically get a `--help` command:99-100-```bash101-python main.py --help101+// It works! 🎉102 ```103+</div>104 104-shows:105-106-```107-Usage: main.py [OPTIONS] NAME108-109-Options:110- --help Show this message and exit.111-```112-105 ## Example upgrade106 107 This was the simplest example possible.108 36 unmodified lines145 * Execute the `app()` itself, as if it was a function (instead of `typer.run`).146 147 ### Run the upgraded example148 157-Get the main `--help`:149+<div class="termy">150+```console151+// Check the --help152+$ python main.py --help153 159-```bash160-python main.py --help161-```162-163-shows:164-165-```154 Usage: main.py [OPTIONS] COMMAND [ARGS]...155 156 Options:157 --help Show this message and exit.158 159 Commands:160 goodbye161 hello174-```162 176-You have 2 sub-commands (the 2 functions), `goodbye` and `hello`.163+// You have 2 sub-commands (the 2 functions): goodbye and hello164 178-Now get the help for `hello`:165+// Now get the --help for hello166 180-```bash181-python main.py hello --help167+$ python main.py hello --help182-```168 184-shows:185-186-```169 Usage: main.py hello [OPTIONS] NAME170 171 Options:172 --help Show this message and exit.191-```173 193-And now get the help for `goodbye`:174+// And now get the --help for goodbye175 195-```bash196-python main.py goodbye --help176+$ python main.py goodbye --help197-```177 199-shows:200-201-```178 Usage: main.py goodbye [OPTIONS] NAME179 180 Options:181 --formal / --no-formal182 --help Show this message and exit.207-```183 209-Notice how it automatically creates a `--formal` and `--no-formal` for your `bool` *option*.184+// Automatic --formal and --no-formal for the bool option 🎉185 211----186+// And if you use it with the hello command187 213-And of course, if you use it, it does what you expect:188+$ python main.py hello Camila189 215-```bash216-python main.py hello Camila217-```218-219-shows:220-221-```190 Hello Camila223-```191 225-Then:192+// And with the goodbye command193 227-```bash228-python main.py goodbye Camila194+$ python main.py goodbye Camila229-```195 231-shows:232-233-```196 Bye Camila!235-```197 237-And:198+// And with --formal199 239-```bash240-python main.py goodbye --formal Camila200+$ python main.py goodbye --formal Camila241-```201 243-shows:244-245-```202 Goodbye Ms. Camila. Have a good day.203 ```204+</div>205 206 ### Recap207 208 In summary, you declare **once** the types of parameters (*arguments* and *options*) as function parameters.54 unmodified linesmodified:mkdocs.yml+8 added
51 unmodified lines52535455565758596061626351 unmodified lines - type: 'medium' link: 'https://medium.com/@tiangolo' - type: 'globe' link: 'https://tiangolo.com'
extra_css: - 'css/termynal.css' - 'css/custom.css'
extra_javascript: - 'js/termynal.js' - 'js/custom.js'