diff --git a/src/common/constituents/default.js b/src/common/constituents/default.js index eddf9919..956569d3 100644 --- a/src/common/constituents/default.js +++ b/src/common/constituents/default.js @@ -61,4 +61,32 @@ export function config() { if (!trigger) queue.shift(); }); }); + + // Return elements + return { + GROUP, + + configurator: { + input, + }, + engine: { + queue, + }, + input: { + openSubsonic, + s3, + }, + orchestrator: { + queueTracks: oqt, + }, + output: { + indexedDB: idb, + }, + transformer: { + jsonStringOutput: json, + refiner: { + default: refiner, + }, + }, + }; } diff --git a/src/components/engine/audio/element.js b/src/components/engine/audio/element.js index 744193f7..ffc1e0df 100644 --- a/src/components/engine/audio/element.js +++ b/src/components/engine/audio/element.js @@ -1,9 +1,10 @@ import { BroadcastableDiffuseElement } from "@common/element.js"; -import { signal } from "@common/signal.js"; +import { computed, signal } from "@common/signal.js"; /** - * @import {Actions, Audio, AudioState, State} from "./types.d.ts" + * @import {Actions, Audio, AudioState, AudioStateReadOnly, LoadingState} from "./types.d.ts" * @import {RenderArg} from "@common/element.d.ts" + * @import {SignalReader} from "@common/signal.d.ts" */ //////////////////////////////////////////// @@ -112,7 +113,7 @@ class AudioEngine extends BroadcastableDiffuseElement { */ adjustVolume(args) { if (args.audioId) { - this.withAudioNode(args.audioId, (audio) => { + this.#withAudioNode(args.audioId, (audio) => { audio.volume = args.volume; }); } else { @@ -124,14 +125,14 @@ class AudioEngine extends BroadcastableDiffuseElement { * @type {Actions["pause"]} */ pause({ audioId }) { - this.withAudioNode(audioId, (audio) => audio.pause()); + this.#withAudioNode(audioId, (audio) => audio.pause()); } /** * @type {Actions["play"]} */ play({ audioId, volume }) { - this.withAudioNode(audioId, (audio, item) => { + this.#withAudioNode(audioId, (audio, item) => { audio.volume = volume ?? this.volume(); audio.muted = false; @@ -139,7 +140,7 @@ class AudioEngine extends BroadcastableDiffuseElement { if (!audio.isConnected) return; const promise = audio.play() || Promise.resolve(); - item.state({ isPlaying: true }); + item.$state.isPlaying.set(true); promise.catch((e) => { if (!audio.isConnected) { @@ -148,7 +149,7 @@ class AudioEngine extends BroadcastableDiffuseElement { const err = "Couldn't play audio automatically. Please resume playback manually."; console.error(err, e); - item.state({ isPlaying: false }); + item.$state.isPlaying.set(false); }); }); } @@ -157,7 +158,7 @@ class AudioEngine extends BroadcastableDiffuseElement { * @type {Actions["reload"]} */ reload(args) { - this.withAudioNode(args.audioId, (audio, item) => { + this.#withAudioNode(args.audioId, (audio, item) => { if (audio.readyState === 0 || audio.error?.code === 2) { audio.load(); @@ -179,7 +180,7 @@ class AudioEngine extends BroadcastableDiffuseElement { * @type {Actions["seek"]} */ seek({ audioId, percentage }) { - this.withAudioNode(audioId, (audio) => { + this.#withAudioNode(audioId, (audio) => { if (!isNaN(audio.duration)) { audio.currentTime = audio.duration * percentage; } @@ -236,20 +237,53 @@ class AudioEngine extends BroadcastableDiffuseElement { // 🛠️ + /** + * Get the state of a single audio item. + * + * @param {string} audioId + * @returns {SignalReader} + */ + _state(audioId) { + return computed(() => { + const _trigger = this.#items.value; + + const s = this.#itemElement(audioId)?.state; + return s ? { ...s } : undefined; + }); + } + + /** + * Get the state of a single audio item. + * + * @param {string} audioId + * @returns {AudioStateReadOnly | undefined} + */ + state(audioId) { + return this._state(audioId)(); + } + /** * @param {string} audioId - * @param {(audio: HTMLAudioElement, item: AudioEngineItem) => void} fn */ - withAudioNode(audioId, fn) { + #itemElement(audioId) { const node = this.querySelector( `de-audio-item[id="${audioId}"]:not([preload])`, ); if (node) { const item = /** @type {AudioEngineItem} */ (node); - if (item) fn(item.audio, item); + return item; } } + + /** + * @param {string} audioId + * @param {(audio: HTMLAudioElement, item: AudioEngineItem) => void} fn + */ + #withAudioNode(audioId, fn) { + const item = this.#itemElement(audioId); + if (item) fn(item.audio, item); + } } export default AudioEngine; @@ -259,26 +293,21 @@ export default AudioEngine; //////////////////////////////////////////// class AudioEngineItem extends HTMLElement { - /** - * @type {AudioState} - */ - #state; - constructor() { super(); const ip = this.getAttribute("initial-progress"); - this.#state = { - duration: 0, - hasEnded: false, - id: this.id, - isPlaying: true, - isPreload: this.hasAttribute("preload"), - loadingState: "loading", - mimeType: this.getAttribute("mime-type") ?? undefined, - progress: ip ? parseFloat(ip) : 0, - url: this.getAttribute("url") ?? "", + /** + * @type {AudioState} + */ + this.$state = { + duration: signal(0), + hasEnded: signal(false), + isPlaying: signal(true), + isPreload: signal(this.hasAttribute("preload")), + loadingState: signal(/** @type {LoadingState} */ ("loading")), + progress: signal(ip ? parseFloat(ip) : 0), }; const audio = this.audio; @@ -294,6 +323,31 @@ class AudioEngineItem extends HTMLElement { audio.addEventListener("waiting", this.waitingEvent); } + // LIFECYCLE + + connectedCallback() { + } + + // STATE + + /** + * @type {AudioStateReadOnly} + */ + get state() { + return { + id: this.id, + mimeType: (this.getAttribute("mime-type") ?? undefined), + url: (this.getAttribute("url") ?? ""), + + duration: this.$state.duration.get, + hasEnded: this.$state.hasEnded.get, + isPlaying: this.$state.isPlaying.get, + isPreload: this.$state.isPreload.get, + loadingState: this.$state.loadingState.get, + progress: this.$state.progress.get, + }; + } + // RELATED ELEMENTS get audio() { @@ -308,16 +362,6 @@ class AudioEngineItem extends HTMLElement { else return null; } - // STATE - - /** - * @param {Partial | undefined} [s] - */ - state(s) { - if (s) this.#state = { ...this.#state, ...s }; - else return { ...this.#state }; - } - // EVENTS /** @@ -349,7 +393,7 @@ class AudioEngineItem extends HTMLElement { const audio = /** @type {HTMLAudioElement} */ (event.target); if (!isNaN(audio.duration)) { - engineItem(audio)?.state({ duration: audio.duration }); + engineItem(audio)?.$state.duration.set(audio.duration); } } @@ -360,7 +404,7 @@ class AudioEngineItem extends HTMLElement { const audio = /** @type {HTMLAudioElement} */ (event.target); audio.currentTime = 0; - engineItem(audio)?.state({ hasEnded: true }); + engineItem(audio)?.$state.hasEnded.set(true); engineItem(audio)?.engine?.$hasEnded.set(true); } @@ -371,7 +415,7 @@ class AudioEngineItem extends HTMLElement { const audio = /** @type {HTMLAudioElement} */ (event.target); const code = audio.error?.code || 0; - engineItem(audio)?.state({ loadingState: { error: { code } } }); + engineItem(audio)?.$state.loadingState.set({ error: { code } }); } /** @@ -381,12 +425,12 @@ class AudioEngineItem extends HTMLElement { const audio = /** @type {HTMLAudioElement} */ (event.target); const item = engineItem(audio); - const itemState = item?.state(); + const itemState = item?.$state; const ended = itemState - ? itemState.hasEnded || itemState.progress === 1 + ? itemState.hasEnded.value || itemState.progress.value === 1 : false; - item?.state({ isPlaying: false }); + item?.$state.isPlaying.set(false); item?.engine?.$isPlaying.set(ended); } @@ -396,7 +440,7 @@ class AudioEngineItem extends HTMLElement { playEvent(event) { const audio = /** @type {HTMLAudioElement} */ (event.target); - engineItem(audio)?.state({ isPlaying: true }); + engineItem(audio)?.$state.isPlaying.set(true); engineItem(audio)?.engine?.$isPlaying.set(true); // In case audio was preloaded: @@ -416,11 +460,11 @@ class AudioEngineItem extends HTMLElement { timeupdateEvent(event) { const audio = /** @type {HTMLAudioElement} */ (event.target); - engineItem(audio)?.state({ - progress: isNaN(audio.duration) || audio.duration === 0 + engineItem(audio)?.$state.progress.set( + isNaN(audio.duration) || audio.duration === 0 ? 0 : audio.currentTime / audio.duration, - }); + ); } /** @@ -451,7 +495,7 @@ function engineItem(audio) { */ function finishedLoading(event) { const audio = /** @type {HTMLAudioElement} */ (event.target); - engineItem(audio)?.state({ loadingState: "loaded" }); + engineItem(audio)?.$state.loadingState.set("loaded"); } /** @@ -460,7 +504,7 @@ function finishedLoading(event) { function initiateLoading(event) { const audio = /** @type {HTMLAudioElement} */ (event.target); if (audio.readyState < 4) { - engineItem(audio)?.state({ loadingState: "loading" }); + engineItem(audio)?.$state.loadingState.set("loading"); } } diff --git a/src/components/engine/audio/types.d.ts b/src/components/engine/audio/types.d.ts index 68199adb..1b01eaee 100644 --- a/src/components/engine/audio/types.d.ts +++ b/src/components/engine/audio/types.d.ts @@ -1,4 +1,4 @@ -import type { SignalReader } from "@common/signal.d.ts"; +import type { Signal, SignalReader } from "@common/signal.d.ts"; export type Actions = { adjustVolume: (_: { audioId?: string; volume: number }) => void; @@ -15,28 +15,41 @@ export type Audio = { id: string; isPreload: boolean; mimeType?: string; + // NOTE: Initial progress progress?: number; url: string; }; export type AudioState = { - duration: number; + duration: Signal; + hasEnded: Signal; + isPlaying: Signal; + isPreload: Signal; + loadingState: Signal; + progress: Signal; +}; + +export type AudioStateReadOnly = { id: string; - hasEnded: boolean; - loadingState: - | "initialisation" - | "loading" - | "loaded" - | { - error: { code: number }; - }; - isPlaying: boolean; - isPreload: boolean; - mimeType?: string; - progress: number; url: string; + mimeType: string | undefined; + + duration: SignalReader; + hasEnded: SignalReader; + isPlaying: SignalReader; + isPreload: SignalReader; + loadingState: SignalReader; + progress: SignalReader; }; +export type LoadingState = + | "initialisation" + | "loading" + | "loaded" + | { + error: { code: number }; + }; + export type State = { isPlaying: SignalReader; items: SignalReader; diff --git a/src/themes/blur/artwork-controller/element.js b/src/themes/blur/artwork-controller/element.js index d5739cff..2befb110 100644 --- a/src/themes/blur/artwork-controller/element.js +++ b/src/themes/blur/artwork-controller/element.js @@ -10,6 +10,7 @@ import { signal } from "@common/signal.js"; /** * @import {RenderArg} from "@common/element.d.ts" * @import {Track} from "@definitions/types.d.ts" + * @import {AudioStateReadOnly} from "@components/engine/audio/types.d.ts" * @import {InputElement} from "@components/input/types.d.ts" * @import {Artwork} from "@components/processor/artwork/types.d.ts" */ @@ -22,7 +23,7 @@ class ArtworkController extends DiffuseElement { // SIGNALS - // activeTrack = signal(/** @type {Track | undefined} */ (undefined)); + // #audio = signal(/** @type {AudioStateReadOnly | undefined} */ (undefined)); #artwork = signal(/** @type {Artwork[]} */ ([])); #artworkColor = signal(/** @type {string | undefined} */ (undefined)); #artworkLightMode = signal(false); @@ -62,31 +63,126 @@ class ArtworkController extends DiffuseElement { // Changed artwork based on active queue item. const debouncedChangeArtwork = debounce( 1000, - this.#changeArtwork.bind(this), + this.#setArtwork.bind(this), ); this.effect(() => { debouncedChangeArtwork(queue.now()); }); - // Force render when elements are defined + this.effect(() => { + const curr = queue.now(); + const aud = curr ? audio.state(curr.id) : undefined; + + console.log("NOW", curr, aud); + }); - // this.effect(() => { - // this.forceRender(); - // }); + this.effect(() => this.#changeArtworkInDOM()); + this.effect(() => this.#formatTimestamps()); + this.effect(() => this.#lightOrDark()); }); + } + + //////////////////////////////////////////// + // ✨ EFFECTS + // 🖼️ Artwork + //////////////////////////////////////////// + + /** @type {Record>} */ + #timeouts = {}; + + #changeArtworkInDOM() { + const art = this.#artwork.value; + + // No artwork, fade out existing. + if (art.length === 0) { + this.root().querySelectorAll(".artwork img").forEach((el) => { + const element = /** @type {HTMLElement} */ (el); + element.style.opacity = "0"; + const hash = element.getAttribute("data-hash"); + if (hash) { + this.#timeouts[hash] = setTimeout(() => element.remove(), 1000); + } + }); + return; + } + + // Determine if the current artwork needs to be replaced. + const hash = xxh32r(art[0].bytes).toString(); - this.#artworkEffects(); + /** @type {HTMLImageElement | null} */ + const existingArtwork = this.root().querySelector( + `.artwork img[data-hash="${hash}"]`, + ); + + // If the artwork is the same, stop here. + if (existingArtwork) { + const timeoutId = this.#timeouts[hash]; + if (timeoutId) clearTimeout(timeoutId); + existingArtwork.style.opacity = "1"; + return; + } + + // Add new artwork + const blob = new Blob( + [/** @type {ArrayBuffer} */ (art[0].bytes.buffer)], + { type: art[0].mime }, + ); + const url = URL.createObjectURL(blob); + + /** @type {HTMLImageElement} */ + const img = document.createElement("img"); + img.setAttribute("data-hash", hash); + img.src = url; + + // Extract average color + img.onload = () => { + const fac = new FastAverageColor(); + const color = fac.getColor(img); + const rgb = color.value; + const o = Math.round( + (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000, + ); + + this.#artworkColor.value = color.rgba; + this.#artworkLightMode.value = o > 165; + + /** @type {HTMLElement | null} */ + const bg = this.root().querySelector(".controller__background"); + if (bg) bg.style.backgroundColor = color.rgba; + + /** @type {HTMLElement | null} */ + const main = this.root().querySelector("main"); + if (main) main.style.backgroundColor = color.rgba; + + img.style.opacity = "1"; + + this.root().querySelectorAll(".artwork img").forEach((el) => { + if (el === img) return; + + const element = /** @type {HTMLElement} */ (el); + element.style.opacity = "0"; + this.#timeouts[hash] = setTimeout(() => element.remove(), 1000); + }); + }; + + // Insert new artwork + this.root().querySelector(".artwork")?.appendChild(img); } - // EFFECTS + #lightOrDark() { + const controller = this.root().querySelector(".controller__inner"); + if (!controller) return; + + if (this.#artworkLightMode.value) { + controller.classList.add("controller__inner--light-mode"); + } else controller.classList.remove("controller__inner--light-mode"); + } /** * @param {Track | null} track */ - async #changeArtwork(track) { - console.log("QUEUE NOW", track); - + async #setArtwork(track) { if (!track) { this.#artwork.value = []; return; @@ -100,8 +196,6 @@ class ArtworkController extends DiffuseElement { uri: track.uri, }); - console.log(resGet, this.input); - if (!resGet) return; const request = "stream" in resGet @@ -121,101 +215,72 @@ class ArtworkController extends DiffuseElement { const art = await this.artwork?.artwork(request) ?? []; - console.log(art); + console.log("ART", art); const currCacheId = track ? await trackArtworkCacheId(track) : undefined; if (cacheId === currCacheId) this.#artwork.set(art); } - #artworkEffects() { - /** @type {Record>} */ - const timeouts = {}; - - this.effect(() => { - const art = this.#artwork.value; + //////////////////////////////////////////// + // ✨ EFFECTS + // ⌚️ Time + //////////////////////////////////////////// + #formatTimestamps() { + const curr = this.queue?.now?.() ?? undefined; + const audio = curr ? this.audio?.state(curr.id) : undefined; + const prog = audio?.progress() ?? 0; + const dur = curr?.stats?.duration ?? audio?.duration(); + + if (audio && dur != undefined && !isNaN(dur)) { + const p = Temporal.Duration.from({ + milliseconds: Math.round(dur * prog * 1000), + }).round({ + largestUnit: "hours", + }); - // No artwork, fade out existing. - if (art.length === 0) { - this.root().querySelectorAll(".artwork img").forEach((el) => { - const element = /** @type {HTMLElement} */ (el); - element.style.opacity = "0"; - const hash = element.getAttribute("data-hash"); - if (hash) timeouts[hash] = setTimeout(() => element.remove(), 1000); + const d = Temporal.Duration.from({ milliseconds: Math.round(dur * 1000) }) + .round({ + largestUnit: "hours", }); - return; - } - - // Determine if the current artwork needs to be replaced. - const hash = xxh32r(art[0].bytes).toString(); - - /** @type {HTMLImageElement | null} */ - const existingArtwork = this.root().querySelector( - `.artwork img[data-hash="${hash}"]`, - ); - - // If the artwork is the same, stop here. - if (existingArtwork) { - const timeoutId = timeouts[hash]; - if (timeoutId) clearTimeout(timeoutId); - existingArtwork.style.opacity = "1"; - return; - } - - // Add new artwork - const blob = new Blob( - [/** @type {ArrayBuffer} */ (art[0].bytes.buffer)], - { type: art[0].mime }, - ); - const url = URL.createObjectURL(blob); - - /** @type {HTMLImageElement} */ - const img = document.createElement("img"); - img.setAttribute("data-hash", hash); - img.src = url; - - // Extract average color - img.onload = () => { - const fac = new FastAverageColor(); - const color = fac.getColor(img); - const rgb = color.value; - const o = Math.round( - (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000, - ); - - this.#artworkColor.value = color.rgba; - this.#artworkLightMode.value = o > 165; - - /** @type {HTMLElement | null} */ - const bg = this.root().querySelector(".controller__background"); - if (bg) bg.style.backgroundColor = color.rgba; - - /** @type {HTMLElement | null} */ - const main = this.root().querySelector("main"); - if (main) main.style.backgroundColor = color.rgba; - img.style.opacity = "1"; - - this.root().querySelectorAll(".artwork img").forEach((el) => { - if (el === img) return; - - const element = /** @type {HTMLElement} */ (el); - element.style.opacity = "0"; - timeouts[hash] = setTimeout(() => element.remove(), 1000); - }); - }; + this.#time.value = this.#formatTime(p); + this.#duration.value = this.#formatTime(d); + } else { + this.#time.value = "0:00"; + this.#duration.value = "0:00"; + } + } - // Insert new artwork - this.root().querySelector(".artwork")?.appendChild(img); - }); + /** + * @param {Temporal.Duration} duration + */ + #formatTime(duration) { + return `${duration.hours > 0 ? duration.hours.toFixed(0) + ":" : ""}${ + duration.hours > 0 + ? (duration.minutes > 9 + ? duration.minutes.toFixed(0) + : "0" + duration.minutes.toFixed(0)) + : duration.minutes.toFixed(0) + }:${ + duration.seconds > 9 + ? duration.seconds.toFixed(0) + : "0" + duration.seconds.toFixed(0) + }`; + } - this.effect(() => { - const controller = this.root().querySelector(".controller__inner"); - if (!controller) return; + // EVENTS - if (this.#artworkLightMode.value) { - controller.classList.add("controller__inner--light-mode"); - } else controller.classList.remove("controller__inner--light-mode"); - }); + /** + * @param {MouseEvent} event + */ + seek(event) { + const target = event.target + ? /** @type {HTMLProgressElement} */ (event.target) + : null; + const percentage = target ? event.offsetX / target.clientWidth : 0; + const audioId = this.queue?.now()?.id; + + if (audioId) this.audio?.seek({ audioId, percentage }); } // RENDER @@ -247,8 +312,26 @@ class ArtworkController extends DiffuseElement {
- -
+
+ + + Diffuse +
+ +
+ + +
+ +
+ + +
+
+ + +
`; diff --git a/src/themes/blur/artwork-controller/index.vto b/src/themes/blur/artwork-controller/index.vto index c3fd782b..9d2be916 100644 --- a/src/themes/blur/artwork-controller/index.vto +++ b/src/themes/blur/artwork-controller/index.vto @@ -23,13 +23,24 @@ styles: