From 3d229e32ff21b1967aa78c82bb28f620b8212ff5 Mon Sep 17 00:00:00 2001 From: Afonso Jorge Ramos Date: Thu, 1 Oct 2026 16:19:01 +0200 Subject: [PATCH 1/6] ci: add CLI command reference check --- scripts/check-cli-commands.mjs | 169 +++++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 scripts/check-cli-commands.mjs diff --git a/scripts/check-cli-commands.mjs b/scripts/check-cli-commands.mjs new file mode 100644 index 0000000..f6732ab --- /dev/null +++ b/scripts/check-cli-commands.mjs @@ -0,0 +1,169 @@ +// Compares the commands documented in src/content/docs/cli/commands.md with +// the command tree of a spicetify binary, read from its recursive `--help`. +// +// Usage: node scripts/check-cli-commands.mjs +// (or set SPICETIFY_BIN) +// +// A command path counts as documented when commands.md has either: +// - a heading made of one code span, such as ### `pkg update` +// - a line in a bash/sh/shell/console code block that starts with +// `spicetify`, read word by word until the first token that is not a +// lowercase command word (an option, , [optional], quoted +// value or # comment). Write arguments in examples as placeholders so they +// are not read as subcommands. +// A parent command (such as `pkg`) is covered when one of its subcommands is. + +import { execFileSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; + +const DOCS_PAGE = 'src/content/docs/cli/commands.md'; + +// Commands that are intentionally left out of the command reference. +// Add a reason next to each entry. +const ALLOWLIST = new Set([]); + +// Top-level commands that only exist in the Linux build. When the binary is +// not a Linux build, documented paths under them are reported but not failed. +const LINUX_ONLY = new Set(['spotify']); + +const COMMAND_WORD = /^[a-z][a-z0-9-]*$/; + +function help(bin, args) { + return execFileSync(bin, [...args, '--help'], { + encoding: 'utf8', + env: { ...process.env, NO_COLOR: '1' }, + timeout: 15_000, + }); +} + +function subcommands(helpText) { + const names = []; + let inSection = false; + for (const line of helpText.split('\n')) { + if (/^(Sub)?[Cc]ommands:\s*$/.test(line)) { + inSection = true; + continue; + } + if (!inSection) continue; + const match = /^ {2}(\S+)/.exec(line); + if (!match) break; + if (match[1] !== 'help') names.push(match[1].replace(/,$/, '')); + } + return names; +} + +function cliCommands(bin) { + const paths = new Set(); + const walk = (prefix) => { + for (const name of subcommands(help(bin, prefix))) { + const next = [...prefix, name]; + paths.add(next.join(' ')); + walk(next); + } + }; + walk([]); + if (paths.size === 0) { + throw new Error(`${bin} --help listed no commands`); + } + return paths; +} + +function documentedCommands(markdown) { + const paths = new Set(); + let fence = null; + for (const line of markdown.split('\n')) { + const fenceMatch = /^\s*(`{3,}|~{3,})\s*(\S*)/.exec(line); + if (fenceMatch) { + if (fence === null) { + fence = { marker: fenceMatch[1], lang: fenceMatch[2].toLowerCase() }; + } else if (line.trim().startsWith(fence.marker)) { + fence = null; + } + continue; + } + if (fence === null) { + const heading = /^#{2,6}\s+`([^`]+)`\s*$/.exec(line); + if (heading) { + const words = heading[1].trim().replace(/^spicetify\s+/, ''); + paths.add(words.split(/\s+/).join(' ')); + } + continue; + } + if (!['bash', 'sh', 'shell', 'console'].includes(fence.lang)) continue; + const tokens = line + .trim() + .replace(/^\$\s+/, '') + .split(/\s+/); + if (tokens[0] !== 'spicetify') continue; + const words = []; + for (const token of tokens.slice(1)) { + if (!COMMAND_WORD.test(token)) break; + words.push(token); + } + if (words.length > 0) paths.add(words.join(' ')); + } + return paths; +} + +function main() { + const bin = process.argv[2] ?? process.env.SPICETIFY_BIN; + if (!bin) { + console.error( + 'Usage: node scripts/check-cli-commands.mjs ', + ); + process.exit(2); + } + + const cli = cliCommands(path.resolve(bin)); + const docs = documentedCommands( + readFileSync(path.resolve(process.cwd(), DOCS_PAGE), 'utf8'), + ); + const isLinuxBuild = [...LINUX_ONLY].every((name) => cli.has(name)); + + const covered = (command) => + [...docs].some((doc) => doc === command || doc.startsWith(`${command} `)); + const missing = [...cli].filter( + (command) => !covered(command) && !ALLOWLIST.has(command), + ); + const stale = []; + const unverifiable = []; + for (const doc of docs) { + if (cli.has(doc)) continue; + if (!isLinuxBuild && LINUX_ONLY.has(doc.split(' ')[0])) { + unverifiable.push(doc); + } else { + stale.push(doc); + } + } + + for (const entry of ALLOWLIST) { + if (!cli.has(entry)) { + console.warn(`warning: allowlisted command "${entry}" no longer exists`); + } else if (covered(entry)) { + console.warn(`warning: allowlisted command "${entry}" is documented`); + } + } + if (unverifiable.length > 0) { + console.warn( + `warning: not a Linux build, skipped Linux-only commands: ${unverifiable.sort().join(', ')}`, + ); + } + + console.log( + `CLI commands: ${cli.size}, documented in ${DOCS_PAGE}: ${docs.size}`, + ); + if (missing.length > 0) { + console.error(`\nMissing from ${DOCS_PAGE}:`); + for (const command of missing.sort()) + console.error(` spicetify ${command}`); + } + if (stale.length > 0) { + console.error(`\nDocumented but not in the CLI:`); + for (const command of stale.sort()) console.error(` spicetify ${command}`); + } + if (missing.length > 0 || stale.length > 0) process.exit(1); + console.log('CLI command reference is in sync.'); +} + +main(); From 92e1e8b44e10d4a4e85e009a0d45791e67cd6f6b Mon Sep 17 00:00:00 2001 From: Afonso Jorge Ramos Date: Thu, 1 Oct 2026 16:19:04 +0200 Subject: [PATCH 2/6] ci: add API wrapper reference check --- scripts/check-api-wrapper.mjs | 186 ++++++++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 scripts/check-api-wrapper.mjs diff --git a/scripts/check-api-wrapper.mjs b/scripts/check-api-wrapper.mjs new file mode 100644 index 0000000..14ba0df --- /dev/null +++ b/scripts/check-api-wrapper.mjs @@ -0,0 +1,186 @@ +// Compares the top-level members of `declare namespace Spicetify` in the +// CLI's globals.d.ts with the API wrapper reference. +// +// Usage: node scripts/check-api-wrapper.mjs [path-or-url-to-globals.d.ts] +// (defaults to the v3-beta branch of spicetify/cli) +// +// Members are the namespaces, functions, classes, enums and consts declared +// directly in the namespace. Type aliases and interfaces are types and are +// not checked. Members tagged @deprecated and members whose name starts with +// an underscore are skipped. +// +// A member counts as documented when, under development/api-wrapper (outside +// types/): +// - a page's frontmatter title is the member name, such as `title: Player` +// - a heading is a code span naming it, such as ## `Spicetify.Daemon` +// - a table row's first cell names it, such as | `Spicetify.React` | ... | +// Pages and headings that name something globals.d.ts does not declare fail +// as stale. Pages under legacy/ live outside this directory. + +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import ts from 'typescript'; + +const DEFAULT_SOURCE = + 'https://raw.githubusercontent.com/spicetify/cli/v3-beta/globals.d.ts'; +const DOCS_DIR = 'src/content/docs/development/api-wrapper'; +const INDEX_PAGES = new Set(['index.md', 'modules.md']); + +// Members that are intentionally left out of the reference. +const ALLOWLIST = new Map([ + ['test', 'debug helper that logs missing wrapper members'], +]); + +async function readSource(source) { + if (!/^https?:\/\//.test(source)) return readFileSync(source, 'utf8'); + const response = await fetch(source); + if (!response.ok) { + throw new Error(`Fetching ${source} failed: ${response.status}`); + } + return response.text(); +} + +function isDeprecated(node) { + return ts.getJSDocTags(node).some((tag) => tag.tagName.text === 'deprecated'); +} + +function declaredMembers(sourceText) { + const file = ts.createSourceFile( + 'globals.d.ts', + sourceText, + ts.ScriptTarget.Latest, + true, + ); + const members = new Map(); + const add = (name, node) => { + const deprecated = isDeprecated(node); + const previous = members.get(name); + members.set(name, { + deprecated: previous ? previous.deprecated && deprecated : deprecated, + }); + }; + + let found = false; + for (const statement of file.statements) { + if ( + !ts.isModuleDeclaration(statement) || + statement.name.text !== 'Spicetify' || + !statement.body || + !ts.isModuleBlock(statement.body) + ) { + continue; + } + found = true; + for (const node of statement.body.statements) { + if (ts.isVariableStatement(node)) { + for (const declaration of node.declarationList.declarations) { + if (ts.isIdentifier(declaration.name)) { + add(declaration.name.text, node); + } + } + } else if ( + (ts.isFunctionDeclaration(node) || + ts.isClassDeclaration(node) || + ts.isEnumDeclaration(node) || + ts.isModuleDeclaration(node)) && + node.name + ) { + add(node.name.text, node); + } + } + } + if (!found) throw new Error('No `declare namespace Spicetify` block found'); + return members; +} + +function markdownFiles(dir) { + return readdirSync(dir, { recursive: true }) + .map(String) + .filter( + (file) => /\.mdx?$/.test(file) && !file.startsWith(`types${path.sep}`), + ); +} + +function documentedMembers(root) { + const pages = new Map(); + const headings = new Map(); + const tableRows = new Map(); + const memberRef = /^`Spicetify\.([A-Za-z_$][\w$]*)[^`]*`$/; + + for (const file of markdownFiles(path.join(root, DOCS_DIR))) { + const where = path.join(DOCS_DIR, file); + const text = readFileSync(path.join(root, DOCS_DIR, file), 'utf8'); + + if (!INDEX_PAGES.has(file)) { + const frontmatter = /^---\n([\s\S]*?)\n---/.exec(text)?.[1] ?? ''; + const title = /^title:\s*['"]?(.+?)['"]?\s*$/m.exec(frontmatter)?.[1]; + if (title) pages.set(title.replace(/^Spicetify\./, ''), where); + } + + let inFence = false; + for (const line of text.split('\n')) { + if (/^\s*(`{3,}|~{3,})/.test(line)) { + inFence = !inFence; + continue; + } + if (inFence) continue; + const heading = /^#{1,6}\s+(`[^`]+`)\s*$/.exec(line); + const headingMember = heading && memberRef.exec(heading[1]); + if (headingMember) headings.set(headingMember[1], where); + const cell = /^\|\s*(`[^`]+`)\s*\|/.exec(line); + const cellMember = cell && memberRef.exec(cell[1]); + if (cellMember) tableRows.set(cellMember[1], where); + } + } + return { pages, headings, tableRows }; +} + +async function main() { + const source = process.argv[2] ?? DEFAULT_SOURCE; + const members = declaredMembers(await readSource(source)); + const { pages, headings, tableRows } = documentedMembers(process.cwd()); + const documented = (name) => + pages.has(name) || headings.has(name) || tableRows.has(name); + + const skipped = []; + const missing = []; + for (const [name, { deprecated }] of members) { + if (documented(name)) continue; + if (name.startsWith('_') || ALLOWLIST.has(name)) continue; + if (deprecated) skipped.push(name); + else missing.push(name); + } + + const stale = []; + for (const [kind, entries] of [ + ['page', pages], + ['heading', headings], + ]) { + for (const [name, where] of entries) { + if (!members.has(name)) stale.push(`${name} (${kind} in ${where})`); + } + } + + for (const name of ALLOWLIST.keys()) { + if (members.has(name) && documented(name)) { + console.warn(`warning: allowlisted member "${name}" is documented`); + } + } + if (skipped.length > 0) { + console.log(`Skipped deprecated members: ${skipped.sort().join(', ')}`); + } + + console.log(`Spicetify members in ${source}: ${members.size}`); + if (missing.length > 0) { + console.error(`\nUndocumented in ${DOCS_DIR}:`); + for (const name of missing.sort()) console.error(` Spicetify.${name}`); + } + if (stale.length > 0) { + console.error('\nDocumented but not declared in globals.d.ts:'); + for (const entry of stale.sort()) console.error(` Spicetify.${entry}`); + } + if (missing.length > 0 || stale.length > 0) process.exit(1); + console.log('API wrapper reference is in sync.'); +} + +await main(); From ec5481cfc6cd3ea268dd1b6af5848d0f87f530c6 Mon Sep 17 00:00:00 2001 From: Afonso Jorge Ramos Date: Thu, 1 Oct 2026 16:19:06 +0200 Subject: [PATCH 3/6] build: add scripts for the reference checks --- package.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 7b338b6..7f19552 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,9 @@ "lint": "oxlint", "lint:fix": "oxlint --fix", "format": "oxfmt", - "format:check": "oxfmt --check" + "format:check": "oxfmt --check", + "check:cli-commands": "node scripts/check-cli-commands.mjs", + "check:api-wrapper": "node scripts/check-api-wrapper.mjs" }, "dependencies": { "@astrojs/mdx": "^5.0.3", From a2d31e549e6fb72f2e74058d1d1f5c1b4902954e Mon Sep 17 00:00:00 2001 From: Afonso Jorge Ramos Date: Thu, 1 Oct 2026 16:19:08 +0200 Subject: [PATCH 4/6] ci: run reference checks on pull requests and weekly --- .github/workflows/reference-checks.yml | 62 ++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 .github/workflows/reference-checks.yml diff --git a/.github/workflows/reference-checks.yml b/.github/workflows/reference-checks.yml new file mode 100644 index 0000000..6d78197 --- /dev/null +++ b/.github/workflows/reference-checks.yml @@ -0,0 +1,62 @@ +name: Reference checks +on: + pull_request: + schedule: + - cron: '0 6 * * 1' + workflow_dispatch: + +permissions: + contents: read + +jobs: + cli-commands: + name: CLI command reference + runs-on: ubuntu-latest + steps: + - name: Checkout Repo + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Setup Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Download the latest v3 CLI + env: + GH_TOKEN: ${{ github.token }} + run: | + tag=$(gh release list -R spicetify/cli --exclude-drafts --limit 100 \ + --json tagName --jq '[.[] | select(.tagName | startswith("v3."))][0].tagName') + if [ -z "$tag" ]; then echo "No v3 release found" >&2; exit 1; fi + echo "Using spicetify/cli $tag" + asset="spicetify-${tag#v}-linux-x86_64.tar.zst" + mkdir -p "$RUNNER_TEMP/cli" + cd "$RUNNER_TEMP/cli" + gh release download "$tag" -R spicetify/cli -p "$asset" -p "$asset.sha256" + echo "$(cat "$asset.sha256") $asset" | sha256sum -c - + tar --zstd -xf "$asset" spicetify + + - name: Check CLI command reference + run: node scripts/check-cli-commands.mjs "$RUNNER_TEMP/cli/spicetify" + + api-wrapper: + name: API wrapper reference + runs-on: ubuntu-latest + steps: + - name: Checkout Repo + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Setup pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + + - name: Setup Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Check API wrapper reference + run: pnpm run check:api-wrapper From 49db5240faa3f164bec69001d7c37376e52516e5 Mon Sep 17 00:00:00 2001 From: Afonso Jorge Ramos Date: Thu, 1 Oct 2026 16:19:09 +0200 Subject: [PATCH 5/6] docs: describe the reference checks in the README --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 505437e..f0f19b1 100644 --- a/README.md +++ b/README.md @@ -10,3 +10,12 @@ pnpm dev ``` To fix or add a page, open an issue or a pull request. + +## Reference checks + +Two scripts check that the reference pages match the code, and the `Reference checks` workflow runs them on every pull request and weekly: + +- `pnpm run check:cli-commands ` compares `src/content/docs/cli/commands.md` with the commands in the binary's `--help`. CI uses the Linux x86_64 build of the newest v3 release, which includes the Linux-only `spotify` commands. +- `pnpm run check:api-wrapper [path-or-url]` compares the `development/api-wrapper` pages with the members of `declare namespace Spicetify` in the CLI's `globals.d.ts`, fetched from the `v3-beta` branch by default. + +The rules each check uses, and their allowlists, are at the top of the scripts in `scripts/`. From ae497a6ee8cfb99605abad85355771a9da2b826c Mon Sep 17 00:00:00 2001 From: Afonso Jorge Ramos Date: Thu, 1 Oct 2026 16:22:38 +0200 Subject: [PATCH 6/6] docs: document Color, Locale, extractColorPreset, Events and ContextMenuV2 --- src/config/sidebar.ts | 16 +++++++ .../development/api-wrapper/classes/color.md | 42 +++++++++++++++++++ .../api-wrapper/classes/context-menu.md | 36 ++++++++++++++++ .../functions/extract-color-preset.md | 32 ++++++++++++++ .../development/api-wrapper/methods/locale.md | 33 +++++++++++++++ .../api-wrapper/properties/events.md | 31 ++++++++++++++ 6 files changed, 190 insertions(+) create mode 100644 src/content/docs/development/api-wrapper/classes/color.md create mode 100644 src/content/docs/development/api-wrapper/functions/extract-color-preset.md create mode 100644 src/content/docs/development/api-wrapper/methods/locale.md create mode 100644 src/content/docs/development/api-wrapper/properties/events.md diff --git a/src/config/sidebar.ts b/src/config/sidebar.ts index 2a45817..d3667d6 100644 --- a/src/config/sidebar.ts +++ b/src/config/sidebar.ts @@ -80,6 +80,10 @@ export const sidebar: SidebarItem[] = [ label: 'URI', href: '/docs/development/api-wrapper/methods/uri', }, + { + label: 'Locale', + href: '/docs/development/api-wrapper/methods/locale', + }, { label: 'PopupModal', href: '/docs/development/api-wrapper/methods/popup-modal', @@ -109,6 +113,10 @@ export const sidebar: SidebarItem[] = [ label: 'Playbar', href: '/docs/development/api-wrapper/classes/playbar', }, + { + label: 'Color', + href: '/docs/development/api-wrapper/classes/color', + }, ], }, { @@ -126,6 +134,10 @@ export const sidebar: SidebarItem[] = [ label: 'colorExtractor', href: '/docs/development/api-wrapper/functions/color-extractor', }, + { + label: 'extractColorPreset', + href: '/docs/development/api-wrapper/functions/extract-color-preset', + }, { label: 'getAudioData', href: '/docs/development/api-wrapper/functions/get-audio-data', @@ -143,6 +155,10 @@ export const sidebar: SidebarItem[] = [ label: 'SVGIcons', href: '/docs/development/api-wrapper/properties/svgicons', }, + { + label: 'Events', + href: '/docs/development/api-wrapper/properties/events', + }, { label: 'Queue', href: '/docs/development/api-wrapper/properties/queue', diff --git a/src/content/docs/development/api-wrapper/classes/color.md b/src/content/docs/development/api-wrapper/classes/color.md new file mode 100644 index 0000000..8995129 --- /dev/null +++ b/src/content/docs/development/api-wrapper/classes/color.md @@ -0,0 +1,42 @@ +--- +title: Color +description: Spotify's color class, for converting and adjusting colors. +--- + +`Spicetify.Color` is Spotify's own color class. It holds a color as RGB, HSL and HSV with an alpha value, and converts it to CSS strings. [`extractColorPreset`](/docs/development/api-wrapper/functions/extract-color-preset) returns its colors as `Color` objects. + +```ts +class Color { + constructor(rgb: rgb, hsl: hsl, hsv: hsv, alpha?: number); + + static BLACK: Color; + static WHITE: Color; + static CSSFormat: Record<"HEX" | "HEXA" | "HSL" | "HSLA" | "RGB" | "RGBA", number>; + + static fromCSS(cssColor: string, alpha?: number): Color; + static fromHex(hex: string, alpha?: number): Color; + static fromRGB(rgb: rgb, alpha?: number): Color; + static fromHSL(hsl: hsl, alpha?: number): Color; + static fromHSV(hsv: hsv, alpha?: number): Color; + + a: number; + rgb: rgb; // { r, g, b } + hsl: hsl; // { h, s, l } + hsv: hsv; // { h, s, v } + + contrastAdjust(against: Color, strength?: number): Color; + toCSS(colorFormat: number): string; + stringify(): string; + toString(): string; +} +``` + +`fromCSS` throws when the string isn't a CSS color it supports, and the string must not contain spaces. `contrastAdjust` returns a color whose contrast against `against` is at least `strength`. Pass a value from `Color.CSSFormat` to `toCSS`. + +```ts +const accent = Spicetify.Color.fromHex('#1db954'); +const readable = accent.contrastAdjust(Spicetify.Color.BLACK); +element.style.color = readable.toCSS(Spicetify.Color.CSSFormat.RGBA); +``` + +`Spicetify.Color` exists once Spicetify has exposed Spotify's webpack modules. See [`Events.webpackLoaded`](/docs/development/api-wrapper/properties/events). diff --git a/src/content/docs/development/api-wrapper/classes/context-menu.md b/src/content/docs/development/api-wrapper/classes/context-menu.md index 97f8787..02fbe32 100644 --- a/src/content/docs/development/api-wrapper/classes/context-menu.md +++ b/src/content/docs/development/api-wrapper/classes/context-menu.md @@ -92,3 +92,39 @@ const shareMenu = new Spicetify.ContextMenu.SubMenu( shareMenu.register(); ``` + +## `Spicetify.ContextMenuV2` + +`Spicetify.ContextMenuV2` is the layer `ContextMenu` and `Menu` are built on. Its `Item` and `ItemSubMenu` classes take one options object, and the functions register any React element as a context-menu entry. + +```ts +namespace ContextMenuV2 { + class Item { + constructor(options: { + children: React.ReactNode; + disabled?: boolean; + leadingIcon?: Icon | string; + trailingIcon?: Icon | string; + divider?: "before" | "after" | "both"; + onClick: (context: Context, self: Item, event: React.MouseEvent) => void; + shouldAdd?: ShouldAddCallback; + }); + } + class ItemSubMenu { + constructor(options: { + text: string; + disabled?: boolean; + leadingIcon?: Icon | string; + divider?: "before" | "after" | "both"; + items: SubMenuItems; // an array or a Set + shouldAdd?: ShouldAddCallback; + }); + addItem(item: Item | ItemSubMenu): void; + removeItem(item: Item | ItemSubMenu): void; + } + function registerItem(item: React.ReactElement, shouldAdd?: ShouldAddCallback): void; + function unregisterItem(item: React.ReactElement): void; +} +``` + +Both classes have `register()` and `deregister()`, and setters for each option. Use `ContextMenuV2` when you need an option the `ContextMenu` constructors don't take, such as `divider`. diff --git a/src/content/docs/development/api-wrapper/functions/extract-color-preset.md b/src/content/docs/development/api-wrapper/functions/extract-color-preset.md new file mode 100644 index 0000000..5c7ffd5 --- /dev/null +++ b/src/content/docs/development/api-wrapper/functions/extract-color-preset.md @@ -0,0 +1,32 @@ +--- +title: extractColorPreset +description: Get the colors Spotify's own UI derives from an image. +--- + +`Spicetify.extractColorPreset` runs Spotify's color extraction on an image and returns the colors Spotify's UI would use for it. It accepts a Spotify image URI or an image URL, or a list of them, and resolves one preset per image. + +```ts +function extractColorPreset(image: string | string[]): Promise< + { + colorRaw: Color; + colorLight: Color; + colorDark: Color; + isFallback: boolean; + }[] +>; +``` + +| Parameter | Type | Description | +| --- | --- | --- | +| `image` | `string \| string[]` | A Spotify image URI or an image URL, or a list of them. | + +Each color is a [`Color`](/docs/development/api-wrapper/classes/color). `isFallback` is `true` when Spotify couldn't extract colors and returned its default ones. + +```ts +const [preset] = await Spicetify.extractColorPreset(imageUrl); +if (!preset.isFallback) { + header.style.background = preset.colorDark.toCSS(Spicetify.Color.CSSFormat.HEX); +} +``` + +For the color extractor service that works from an item URI, see [`colorExtractor`](/docs/development/api-wrapper/functions/color-extractor). diff --git a/src/content/docs/development/api-wrapper/methods/locale.md b/src/content/docs/development/api-wrapper/methods/locale.md new file mode 100644 index 0000000..809c33f --- /dev/null +++ b/src/content/docs/development/api-wrapper/methods/locale.md @@ -0,0 +1,33 @@ +--- +title: Locale +description: Spotify's localization library, for formatting and translated strings. +--- + +`Spicetify.Locale` wraps Spotify's localization library. It formats dates and numbers in the client's language and reads Spotify's translated strings. + +```ts +namespace Locale { + function formatDate(date: number | Date | undefined, options?: Intl.DateTimeFormatOptions): string; + function formatRelativeTime(date: number | Date | undefined, options?: Intl.DateTimeFormatOptions): string; + function formatNumber(number: number, options?: Intl.NumberFormatOptions): string; + function formatNumberCompact(number: number): string; + function get(key: string, ...children: React.ReactNode[]): string | React.ReactNode; + function getDictionary(): Record; + function getLocale(): string; + function getUrlLocale(): string; + function getSmartlingLocale(): string; + function getDateTimeFormat(options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat; + function getRelativeTimeFormat(): Intl.RelativeTimeFormat; + function getSeparator(): string; + function setLocale(locale: string): void; +} +``` + +`formatDate` and `formatRelativeTime` throw a `RangeError` for an invalid date. `get` looks up a key in Spotify's dictionary and fills its placeholders with `children`. `getDictionary` returns every translated string, which is how you find a key. + +```ts +const added = Spicetify.Locale.formatRelativeTime(track.addedAt); +const plays = Spicetify.Locale.formatNumberCompact(1234567); // "1.2M" in English +``` + +`Spicetify.Locale` exists once Spicetify has exposed Spotify's webpack modules. See [`Events.webpackLoaded`](/docs/development/api-wrapper/properties/events). diff --git a/src/content/docs/development/api-wrapper/properties/events.md b/src/content/docs/development/api-wrapper/properties/events.md new file mode 100644 index 0000000..de31971 --- /dev/null +++ b/src/content/docs/development/api-wrapper/properties/events.md @@ -0,0 +1,31 @@ +--- +title: Events +description: One-time events the Spicetify wrapper fires while Spotify starts. +--- + +`Spicetify.Events` holds two one-time events the wrapper fires while Spotify starts. Use them to wait for an API that the wrapper sets later in startup. + +```ts +namespace Events { + interface Event { + on(callback: () => void): void; + } + const platformLoaded: Event; + const webpackLoaded: Event; +} +``` + +| Event | Fires when | +| --- | --- | +| `platformLoaded` | Spotify's webpack modules have loaded, before Spicetify exposes them. | +| `webpackLoaded` | Spicetify has exposed the APIs it extracts from webpack, such as `React`, `ReactComponent`, `URI`, `Locale` and `Color`. | + +`on` runs `callback` when the event fires, or right away if it already fired, so a late listener never misses it. An error in one callback is logged and doesn't stop the others. + +```ts +Spicetify.Events.webpackLoaded.on(() => { + console.log(Spicetify.Locale.formatNumber(1234.5)); +}); +``` + +In a v3 module, the loader runs `load()` after the wrapper is ready, so you rarely need these. They're for code that runs earlier, such as a mixin.