:sparkles: Update Termynal modifications, update first steps to use it
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Make Termynal have fixed sizes, add "fast" button, use it in first steps
authored by Sebastián Ramírez · committed by Sebastián Ramírez · parent e91c5a4 · Browse files · 4 files·+244 added−194 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+244 added−194 removed
- other:+244 added−194 removed
Provenance
- Commit
bed4e2b- Tree
77e7528- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
Sebastián Ramírez <tiangolo@gmail.com>- Parent
e91c5a4
4 files changed+244 added−194 removed
modified:docs/css/termynal.css+6 added
49 unmodified lines505152535455565758596061626344 unmodified lines49 unmodified lines width: 100%; text-align: center;}
a[data-terminal-control] { text-align: right; display: block; color: #aebbff;}
[data-ty] { display: block; line-height: 2;}44 unmodified linesmodified:docs/js/custom.js+72 added-57 removed
123345678910119121314151314151617181920212223161718192021222324252425262728263031323334353637382728293031404142434445464748495051525354555657585960616263323334353637383940416667686970714243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091document.querySelectorAll(".use-termynal").forEach(node => { node.style.display = "block"; new Termynal(node); new Termynal(node, { lineDelay: 500 });});const progressLiteralStart = "---> 100%";const promptLiteralStart = "$ ";const termynalActivateClass = "termy";let termynals = [];
function loadVisibleTermynals() {function createTermynals() { 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 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 = []; }); dataValue = {}; if (isBlankSpace) { dataValue["delay"] = 0; } } 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); 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 = []; } saveBuffer(); const div = document.createElement("div"); node.replaceWith(div); const termynal = new Termynal(div, { lineData: useLines }); } 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, noInit: true, lineDelay: 500 }); termynals.push(termynal); });}
function loadVisibleTermynals() { termynals = termynals.filter(termynal => { if (termynal.container.getBoundingClientRect().top - innerHeight <= 0) { termynal.init(); return false; } return true; });}window.addEventListener("scroll", loadVisibleTermynals);createTermynals();loadVisibleTermynals();modified:docs/js/termynal.js+71 added-7 removed
28 unmodified lines29 */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.startDelay33+ this.originalStartDelay = this.startDelay = options.startDelay34 || parseFloat(this.container.getAttribute(`${this.pfx}-startDelay`)) || 600;35- this.typeDelay = options.typeDelay35+ this.originalTypeDelay = this.typeDelay = options.typeDelay36 || parseFloat(this.container.getAttribute(`${this.pfx}-typeDelay`)) || 90;37- this.lineDelay = options.lineDelay37+ 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.progressChar2 unmodified lines44 || 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 }51 52+ 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+ }70+71 /**72 * Initialise the widget, get lines, clear container and start animation.73 */74 init() {55- // Appends dynamically loaded lines to existing line elements.56- this.lines = [...this.container.querySelectorAll(`[${this.pfx}]`)].concat(this.lineData);57-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 */ 4 unmodified lines83 containerStyle.height : undefined;84 85 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 }92 93 /**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);99 100 for (let line of this.lines) {101 const type = line.getAttribute(this.pfx);16 unmodified lines118 }119 120 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 }128 129+ generateRestart() {130+ const restart = document.createElement('a')131+ restart.onclick = (e) => {132+ e.preventDefault()133+ this.container.innerHTML = ''134+ this.init()135+ }136+ restart.href = '#'137+ restart.setAttribute('data-terminal-control', '')138+ restart.innerHTML = "restart \u27f3" // Refresh emoji139+ return restart140+ }141+ 142+ generateFinish() {143+ const finish = document.createElement('a')144+ finish.onclick = (e) => {145+ e.preventDefault()146+ this.lineDelay = 0147+ this.typeDelay = 0148+ this.startDelay = 0149+ }150+ finish.href = '#'151+ finish.setAttribute('data-terminal-control', '')152+ finish.innerHTML = "fast \u2b95" // Fast emoji arrow153+ this.finishElement = finish154+ return finish155+ }156+157+ addRestart() {158+ const restart = this.generateRestart()159+ this.container.appendChild(restart)160+ }161+162+ addFinish() {163+ const finish = this.generateFinish()164+ this.container.appendChild(finish)165+ }166+167 /**168 * Animate a typed line.169 * @param {Node} line - The line element to render.170 */171 async type(line) {172 const chars = [...line.textContent];109- const delay = line.getAttribute(`${this.pfx}-typeDelay`) || this.typeDelay;173 line.textContent = '';174 this.container.appendChild(line);175 176 for (let char of chars) {177+ const delay = line.getAttribute(`${this.pfx}-typeDelay`) || this.typeDelay;178 await this._wait(delay);179 line.textContent += char;180 }181 }85 unmodified linesmodified:docs/tutorial/first-steps.md+95 added-130 removed
8 unmodified lines9 Copy that to a file `main.py`.10 11 Test it:12 13-```bash14-python main.py15-```13+<div class="termy">14 17-You will see an output like:15+```console16+$ python main.py17 19-```hl_lines=""18 Hello World21-```19 23-It just prints "Hello World".20+// It just prints "Hello World".21 25-If you type:22+// Now check the --help23+$ python main.py --help24 27-```bash28-python main.py --help29-```30-31-it shows:32-33-```25 Usage: main.py [OPTIONS]26 27 Options:28 --help Show this message and exit.29 ```30 40-...but this program is still not very useful. Let's increase that.31+</div>32 33+...but this program is still not very useful. Let's extend it.34+35 ## What is a **CLI argument**36 37 Here we will use the word **CLI argument** to refer to **CLI parameters** passed in some specific order to the CLI application. By default, they are *required*.38 39 If you go to your terminal and type:40 41+<div class="termy">42+43 ```bash49-ls ./myproject44+$ ls ./myproject45+46+first-steps.md intro.md47 ```48 49+</div>50+51 `ls` will show the contents of the directory `./myproject`.52 54-* `ls` is the *command* (or "program", "CLI app").55-* `./myproject` is a *CLI argument*.53+* `ls` is the *program* (or "command", "CLI app").54+* `./myproject` is a *CLI argument*, in this case it refers to the path of a directory.55 56 They are a bit different from **CLI options** that you will see later below.57 58 ## Add a CLI argument3 unmodified lines62 ```Python hl_lines="4 5"63 {!./src/first_steps/tutorial002.py!}64 ```65 67-If you run it without the argument:66+<div class="termy">67 69-```bash70-python main.py71-```68+```console69 73-it shows:70+$ python main.py71 75-```72+// If you run it without the argument, it shows a nice error73+74 Usage: main.py [OPTIONS] NAME75 Try "main.py --help" for help.76 77 Error: Missing argument "NAME".80-```78 82-Now pass that `name` *CLI argument*:79+// Now pass that NAME CLI argument80+$ python main.py Camila81 84-```bash85-python main.py Camila86-```82+Hello Camila83 88-it shows:89-84+// Here "Camila" is the CLI argument85 ```91-Hello Camila92-```86 94-Here `Camila` is the *CLI argument*.87+</div>88 89 ## Two CLI arguments90 91 Now extend that to have 2 arguments, `name` and `lastname`:1 unmodified line93 ```Python hl_lines="4 5"94 {!./src/first_steps/tutorial003.py!}95 ```96 104-Now get the help:97+<div class="termy">98 106-```bash107-python main.py --help108-```99+```console100+// Check the main --help101+$ python main.py --help102 110-it shows:111-112-```103 Usage: main.py [OPTIONS] NAME LASTNAME104 105 Options:106 --help Show this message and exit.117-```107 119-There are now 2 *CLI arguments*, `name` and `lastname`.108+// There are now 2 CLI arguments, name and lastname109 121-Now pass a single `name` argument:110+// Now pass a single name argument111+$ python main.py Camila112 123-```bash124-python main.py Camila125-```126-127-it shows:128-129-```113 Usage: main.py [OPTIONS] NAME LASTNAME114 Try "main.py --help" for help.115 116 Error: Missing argument "LASTNAME".134-```117 136-These 2 arguments are required, so, pass both:118+// These 2 arguments are required, so, pass both:119+$ python main.py Camila Gutiérrez120 138-```bash139-python main.py Camila Gutiérrez140-```141-142-it shows:143-144-```121 Hello Camila Gutiérrez122 ```123 124+</div>125+126 !!! tip127 Notice that the order is important. The last name has to go after the first name.128 129 If you called it with:130 153- ```bash154- python main.py Gutiérrez Camila131 ```132+ $ python main.py Gutiérrez Camila133+ ```134 135 your app wouldn't have a way to know which is the `name` and which the `lastname`. It expects the first *CLI argument* to be the `name` and the second *CLI argument* to be the `lastname`.136 137 ## What is a **CLI option**138 139 Here we will use the word **CLI option** to refer to *CLI parameters* passed to the CLI application with a specific name. For example, if you go to your terminal and type:140 141+<div class="termy">142+163-```bash164-ls ./myproject --size143+```console144+$ ls ./myproject --size145+146+12 first-steps.md 4 intro.md147 ```148 149+</div>150+151 `ls` will show the contents of the directory `./myproject` with their `size`.152 169-* `ls` is the *command* (or "program", "CLI app").153+* `ls` is the *program* (or "command", "CLI app").154 * `./myproject` is a *CLI argument*.155 * `--size` is an optional *CLI option*.156 157 The program knows it has to show the size because it sees `--size`, not because of the order.1 unmodified line159 A *CLI option* like `--size` doesn't depend on the order like a *CLI argument*.160 161 So, if you put the `--size` *before* the *CLI argument*, it still works:162 163+<div class="termy">164+179-```bash180-ls --size ./myproject165+```console166+$ ls --size ./myproject167+168+12 first-steps.md 4 intro.md169 ```170 171+</div>172+173 The main visual difference between a *CLI option* and and a *CLI argument* is that the *CLI option* has `--` prepended to the name, like in "`--size`".174 175 A *CLI option* doesn't depend on the order because it has a predefined name (here it's `--size`). This is because the CLI app is looking specifically for a literal `--size` parameter or "flag", with that specific "name" (here the specific name is "`--size`"). The CLI app will check if you typed it or not, it will be actively looking for `--size` even if you didn't type it (to check if it's there or not).176 17 unmodified lines194 ```195 196 Here `formal` is a `bool` that is `False` by default.197 208-If you get the help:198+<div class="termy">199 210-```bash211-python main.py --help212-```200+```console201+// Get the help202+$ python main.py --help203 214-it shows:215-216-```204 Usage: main.py [OPTIONS] NAME LASTNAME205 206 Options:207 --formal / --no-formal208 --help Show this message and exit.209 ```210 211+</div>212+213 !!! tip214 Notice that it automatically creates a `--formal` and a `--no-formal` because it detected that `formal` is a `bool`.215 216 Now call it normally:217 229-```bash230-python main.py Camila Gutiérrez231-```218+<div class="termy">219 233-it still shows:220+```console221+$ python main.py Camila Gutiérrez222 235-```223 Hello Camila Gutiérrez237-```224 239-But if you pass `--formal`:225+// But if you pass --formal226+$ python main.py Camila Gutiérrez --formal227 241-```bash242-python main.py Camila Gutiérrez --formal243-```228+Good day Ms. Camila Gutiérrez.229 245-it shows:230+// And as --formal is a CLI option you can put it anywhere in this command231+$ python main.py Camila --formal Gutiérrez232 247-```233 Good day Ms. Camila Gutiérrez.249-```234 251-And as `formal` is a *CLI option*, you can put it anywhere in this command:235+$ python main.py --formal Camila Gutiérrez236 253-```bash254-python main.py Camila --formal Gutiérrez255-```256-257-and:258-259-```bash260-python main.py --formal Camila Gutiérrez261-```262-263-both still show:264-265-```237 Good day Ms. Camila Gutiérrez.238 ```239 240+</div>241+242 ## A *CLI option* with a value243 244 To convert the `lastname` from a *CLI argument* to a *CLI option*, give it a default value of `""`:245 2 unmodified lines248 ```249 250 As `lastname` now has a default value of `""` (an empty string) it is no longer required in the function, and **Typer** will now by default make it an optional *CLI option*.251 279-If you get the help:252+<div class="termy">253 281-```bash282-python main.py --help283-```254+```console255+$ python main.py --help256 285-it now shows:286-287-```257 Usage: main.py [OPTIONS] NAME258 259 Options:260 --lastname TEXT261 --formal / --no-formal262 --help Show this message and exit.263 ```264 265+</div>266+267 !!! tip268 Notice the `--lastname`, and notice that it takes a textual value.269 270 A *CLI option* with a value like `--lastname` (contrary to a *CLI option* without a value, a `bool` flag, like `--formal` or `--size`) takes as its value whatever is at the *right side* of the *CLI option*.271 301-If you call it without a `--lastname`:272+<div class="termy">273 303-```bash304-python main.py Camila305-```274+```console275+// Call it without a --lastname276+$ python main.py Camila277 307-it shows:308-309-```278 Hello Camila311-```279 313-and you can pass the `--lastname`:280+// Pass the --lastname281+$ python main.py Camila --lastname Gutiérrez282 315-```bash316-python main.py Camila --lastname Gutiérrez317-```318-319-and it shows:320-321-```283 Hello Camila Gutiérrez284 ```285 286+</div>287+288 !!! tip289 Notice that "`Gutiérrez`" is at the right side of `--lastname`. A *CLI option* with a value takes as its value whatever is at the *right side*.290 291 And as `--lastname` is now a *CLI option* that doesn't depend on the order, you can pass it before the name:292 330-```bash331-python main.py --lastname Gutiérrez Camila332-```293+<div class="termy">294 334-and it will still work normally:295+```console296+$ python main.py --lastname Gutiérrez Camila297 336-```298+// and it will still work normally299+300 Hello Camila Gutiérrez301 ```302 303+</div>304+305 ## Arguments, options, parameters, optional, required306 307 Be aware that these terms refer to multiple things depending on the context, and sadly, those "contexts" mix frequently, so it's easy to get confused.308 65 unmodified lines