Created
December 31, 2025 19:50
-
-
Save havenwood/f5cde3eda188a5085407e931612ad140 to your computer and use it in GitHub Desktop.
An example custom HTML element that shows formatted byte sizes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ByteSize extends HTMLElement { | |
| static observedAttributes = ["si"]; | |
| static #binaryUnits = ["B", "KiB", "MiB", "GiB", "TiB"]; | |
| static #siUnits = ["B", "KB", "MB", "GB", "TB"]; | |
| #initialized = false; | |
| #bytes = 0; | |
| get si() { | |
| return this.hasAttribute("si"); | |
| } | |
| set si(value) { | |
| this.toggleAttribute("si", Boolean(value)); | |
| } | |
| connectedCallback() { | |
| const text = this.textContent.trim(); | |
| if (!text) return; | |
| this.#bytes = Number(text); | |
| this.#initialized = true; | |
| this.#render(); | |
| } | |
| attributeChangedCallback() { | |
| if (this.#initialized) this.#render(); | |
| } | |
| #render() { | |
| const bytes = this.#bytes; | |
| const formatted = this.#format(bytes); | |
| if (formatted === null) return; | |
| const exact = `${bytes.toLocaleString()} bytes`; | |
| this.textContent = formatted; | |
| this.title = exact; | |
| this.ariaLabel = `${formatted} (${exact})`; | |
| } | |
| #format(bytes) { | |
| if (!Number.isFinite(bytes)) return null; | |
| if (bytes === 0) return "0 B"; | |
| const base = this.si ? 1000 : 1024; | |
| const units = this.si ? ByteSize.#siUnits : ByteSize.#binaryUnits; | |
| const abs = Math.abs(bytes); | |
| const exp = Math.min( | |
| Math.floor(Math.log(abs) / Math.log(base)), | |
| units.length - 1 | |
| ); | |
| const size = bytes / base ** exp; | |
| return `${Number.isInteger(size) ? size : size.toFixed(2)} ${units[exp]}`; | |
| } | |
| } | |
| customElements.define("byte-size", ByteSize); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment