diff --git a/e2e/music.spec.ts b/e2e/music.spec.ts new file mode 100644 index 0000000..2fa7bdd --- /dev/null +++ b/e2e/music.spec.ts @@ -0,0 +1,132 @@ +import { test, expect } from "@playwright/test"; +function wave() { + const buffer = Buffer.alloc(44 + 160000); + buffer.write("RIFF", 0); + buffer.writeUInt32LE(buffer.length - 8, 4); + buffer.write("WAVEfmt ", 8); + buffer.writeUInt32LE(16, 16); + buffer.writeUInt16LE(1, 20); + buffer.writeUInt16LE(1, 22); + buffer.writeUInt32LE(8000, 24); + buffer.writeUInt32LE(16000, 28); + buffer.writeUInt16LE(2, 32); + buffer.writeUInt16LE(16, 34); + buffer.write("data", 36); + buffer.writeUInt32LE(160000, 40); + return buffer; +} +test("Music imports audio, plays it and persists playlists", async ({ + page, +}) => { + await page.goto("/"); + await expect(page.locator(".boot")).toHaveCount(0); + async function launch() { + await page.getByRole("button", { name: "Apps", exact: true }).click(); + await page + .locator(".startmenu") + .getByRole("button", { name: "Music", exact: true }) + .click(); + } + await launch(); + await page.getByLabel("Import audio", { exact: true }).setInputFiles({ + name: "sample.wav", + mimeType: "audio/wav", + buffer: wave(), + }); + await expect(page.getByRole("status")).toHaveText("Imported 1 track(s)."); + await page.getByRole("button", { name: "sample.wav", exact: true }).click(); + await expect( + page.getByRole("button", { name: "Pause", exact: true }), + ).toBeVisible(); + await page.getByRole("button", { name: "Home", exact: true }).click(); + expect( + await page + .locator(".music audio") + .evaluate((element: HTMLAudioElement) => element.paused), + ).toBe(false); + await launch(); + await page.getByRole("button", { name: "Pause", exact: true }).click(); + await page.getByLabel("Import audio", { exact: true }).setInputFiles({ + name: "second.wav", + mimeType: "audio/wav", + buffer: wave(), + }); + await expect(page.getByRole("status")).toHaveText("Imported 1 track(s)."); + async function openFirstFromExplorer() { + await page.evaluate(async () => { + const fsPath = "/src/stores/useFileSystemStore.ts"; + const openPath = "/src/lib/openNode.ts"; + const { useFileSystemStore } = await import(fsPath); + const { openFsNode } = await import(openPath); + const file = ( + Object.values(useFileSystemStore.getState().nodes) as { name: string }[] + ).find((node) => node.name === "sample.wav"); + openFsNode(file); + }); + } + await openFirstFromExplorer(); + await page.getByRole("button", { name: "second.wav", exact: true }).click(); + await expect(page.locator(".music__player > strong")).toHaveText( + "second.wav", + ); + await openFirstFromExplorer(); + await expect(page.locator(".music__player > strong")).toHaveText( + "sample.wav", + ); + await page.getByLabel("Playlist name", { exact: true }).fill("Favorites"); + await page + .getByRole("button", { name: "Create playlist", exact: true }) + .click(); + await page + .getByLabel("Add sample.wav to playlist", { exact: true }) + .selectOption({ label: "Favorites" }); + await page.reload(); + await expect(page.locator(".boot")).toHaveCount(0); + await launch(); + await page + .getByLabel("Music playlist", { exact: true }) + .selectOption({ label: "Favorites" }); + await expect( + page.getByRole("button", { name: "sample.wav", exact: true }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "Play", exact: true }), + ).toBeVisible(); + await page.getByRole("button", { name: "sample.wav", exact: true }).click(); + await expect( + page.getByRole("button", { name: "Pause", exact: true }), + ).toBeVisible(); + const player = await page.locator(".music audio").elementHandle(); + await page.evaluate(async () => { + const path = "/src/stores/useWindowStore.ts"; + const { useWindowStore } = await import(path); + const window = useWindowStore + .getState() + .windows.find((item: { appId: string }) => item.appId === "music"); + useWindowStore.getState().closeWindow(window.id); + }); + await expect(page.locator(".music")).toHaveCount(0); + expect( + await player!.evaluate((element: HTMLAudioElement) => element.paused), + ).toBe(true); + const media = await page.evaluate(async () => { + const path = "/src/stores/useFileSystemStore.ts"; + const { useFileSystemStore } = await import(path); + const fs = useFileSystemStore.getState(); + const file = ( + Object.values(fs.nodes) as { id: string; name: string; content: string }[] + ).find((node) => node.name === "sample.wav")!; + fs.deleteNode(file.id); + fs.permanentlyDelete(file.id); + return file.content.slice(12); + }); + await expect + .poll(async () => + page.evaluate(async (id) => { + const path = "/src/lib/audioStorage.ts"; + const { getAudio } = await import(path); + return !!(await getAudio(id)); + }, media), + ) + .toBe(false); +}); diff --git a/src/apps/Music/Music.css b/src/apps/Music/Music.css new file mode 100644 index 0000000..ec746c7 --- /dev/null +++ b/src/apps/Music/Music.css @@ -0,0 +1,59 @@ +.music { + height: 100%; + overflow: auto; + display: flex; + flex-direction: column; + background: var(--color-bg); + color: var(--color-text); + padding: 12px; + gap: 12px; +} +.music__toolbar { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; +} +.music button, +.music select, +.music input:not([type="range"]):not([type="checkbox"]) { + background: var(--color-surface); + color: inherit; + padding: 8px; + border: 1px solid var(--color-border); + border-radius: 6px; + max-width: 100%; +} +.music label { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} +.music__library { + flex: 1 0 120px; + overflow: auto; +} +.music__track { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 8px; +} +.music__track > button:first-child { + flex: 1; + text-align: left; + overflow-wrap: anywhere; +} +.music button[aria-pressed="true"] { + outline: 2px solid var(--color-accent); +} +.music__player { + display: flex; + flex-direction: column; + gap: 10px; +} +.music__player > label input { + flex: 1; + min-width: 100px; +} diff --git a/src/apps/Music/Music.tsx b/src/apps/Music/Music.tsx new file mode 100644 index 0000000..e43dfa2 --- /dev/null +++ b/src/apps/Music/Music.tsx @@ -0,0 +1,425 @@ +import { useEffect, useRef, useState } from "react"; +import type { AppProps } from "../../types"; +import { useFileSystemStore } from "../../stores/useFileSystemStore"; +import { useMusicStore } from "../../stores/useMusicStore"; +import { + audioEntries, + audioId, + deleteAudio, + getAudio, + putAudio, +} from "../../lib/audioStorage"; +import "./Music.css"; + +export function Music({ launchProps }: AppProps) { + const { nodes, rootId } = useFileSystemStore(); + const preferences = useMusicStore(); + const [selected, setSelected] = useState( + typeof launchProps?.fileId === "string" ? launchProps.fileId : null, + ); + const [playlist, setPlaylist] = useState("all"); + const [name, setName] = useState(""); + const [message, setMessage] = useState(""); + const [busy, setBusy] = useState(false); + const [muted, setMuted] = useState(false); + const [playing, setPlaying] = useState(false); + const [duration, setDuration] = useState(0); + const [position, setPosition] = useState(0); + const audio = useRef(null); + const autoplay = useRef(false); + const tracks = Object.values(nodes).filter( + (node) => node.type === "file" && audioId(node.content), + ); + const list = preferences.playlists.find((item) => item.id === playlist); + const queue = tracks.filter( + (track) => playlist === "all" || list?.files.includes(track.id), + ); + const current = nodes[selected ?? ""]; + const mediaId = audioId(current?.content); + + useEffect(() => { + if (typeof launchProps?.fileId === "string") { + autoplay.current = false; + setSelected(launchProps.fileId); + } + }, [launchProps]); + useEffect(() => { + const element = audio.current; + if (!element) return; + let disposed = false; + let url: string | null = null; + element.pause(); + element.removeAttribute("src"); + element.load(); + setDuration(0); + setPosition(0); + setPlaying(false); + if (mediaId) + getAudio(mediaId) + .then((blob) => { + if (disposed) return; + if (!blob) { + setMessage("This audio file is unavailable. Import it again."); + return; + } + url = URL.createObjectURL(blob); + element.src = url; + if (autoplay.current) + void element + .play() + .catch(() => setMessage("Press Play to start playback.")); + }) + .catch(() => { + if (!disposed) setMessage("Could not read audio storage."); + }); + return () => { + disposed = true; + element.pause(); + element.removeAttribute("src"); + element.load(); + if (url) URL.revokeObjectURL(url); + }; + }, [mediaId]); + useEffect(() => { + if (audio.current) { + audio.current.volume = preferences.volume; + audio.current.muted = muted; + } + }, [preferences.volume, muted]); + + function choose(id: string) { + setMessage(""); + autoplay.current = true; + if (id === selected) + void audio.current + ?.play() + .catch(() => setMessage("Unable to play this audio format.")); + else setSelected(id); + } + function advance(direction: number, ended = false) { + if (!queue.length) return; + const index = queue.findIndex((track) => track.id === selected); + if (ended && preferences.repeat === "one") { + if (audio.current) { + audio.current.currentTime = 0; + void audio.current + .play() + .catch(() => setMessage("Press Play to continue.")); + } + return; + } + if ( + ended && + preferences.repeat === "off" && + !preferences.shuffle && + index === queue.length - 1 + ) + return; + let next = + index < 0 ? 0 : (index + direction + queue.length) % queue.length; + if (preferences.shuffle && queue.length > 1) + next = + (Math.max(0, index) + + 1 + + Math.floor(Math.random() * (queue.length - 1))) % + queue.length; + choose(queue[next].id); + } + async function importFiles(files: FileList | null) { + if (!files) return; + const selectedFiles = Array.from(files); + setBusy(true); + setMessage(""); + let imported = 0; + try { + let total = (await audioEntries()).reduce( + (sum, entry) => sum + entry.blob.size, + 0, + ); + for (const file of selectedFiles) { + if ( + !/\.(mp3|wav|ogg|m4a|aac|webm|flac)$/i.test(file.name) || + file.size === 0 || + file.size > 20 * 1024 * 1024 + ) + throw new Error( + "Choose audio files up to 20 MB each (MP3, WAV, OGG, M4A, AAC, WebM or FLAC).", + ); + if (total + file.size > 128 * 1024 * 1024) + throw new Error( + "Audio storage limit is 128 MB. Remove unused tracks from the Recycle Bin to free space.", + ); + const fs = useFileSystemStore.getState(); + const folder = Object.values(fs.nodes).find( + (node) => + node.type === "folder" && + node.parentId === rootId && + node.name === "Music", + ); + const folderId = folder?.id ?? fs.createNode(rootId, "Music", "folder"); + if (!folderId) + throw new Error( + "A file named Music prevents creating the Music folder.", + ); + if ( + Object.values(fs.nodes).some( + (node) => node.parentId === folderId && node.name === file.name, + ) + ) + throw new Error(`“${file.name}” already exists in Music.`); + const id = crypto.randomUUID(); + await putAudio(id, file); + const before = useFileSystemStore.getState().nodes; + try { + const fileId = fs.createNode( + folderId, + file.name, + "file", + `webos-audio:${id}`, + ); + if (!fileId) throw new Error("A file with this name already exists."); + } catch (error) { + try { + useFileSystemStore.setState({ nodes: before }); + } catch { + /* Memory is restored even if persistence remains full. */ + } + await deleteAudio([id]); + throw error; + } + total += file.size; + imported++; + } + setMessage(`Imported ${imported} track(s).`); + } catch (error) { + setMessage( + `${imported ? `Imported ${imported} track(s). ` : ""}${error instanceof Error ? error.message : "Import failed. Storage may be full."}`, + ); + } finally { + setBusy(false); + } + } + return ( +
+
+ + +
+
+ setName(event.target.value)} + /> + + {list && ( + <> + + + + )} +
+
+ {!queue.length && ( +

No tracks here. Import audio or add tracks to this playlist.

+ )} + {queue.map((track) => ( +
+ + {list ? ( + + ) : ( + + )} +
+ ))} +
+
+ {current?.name ?? "Choose a track"} +
+ {message &&

{message}

} +
+ ); +} diff --git a/src/apps/Settings/Settings.tsx b/src/apps/Settings/Settings.tsx index 767b3d3..1542a03 100644 --- a/src/apps/Settings/Settings.tsx +++ b/src/apps/Settings/Settings.tsx @@ -57,20 +57,33 @@ export function Settings({}: AppProps) { } } - function handleResetFs() { + async function handleResetFs() { if (window.confirm("Reset the file system? All files will be deleted.")) { - useFileSystemStore.getState().resetFileSystem(); + try { + await useFileSystemStore.getState().resetFileSystem(); + } catch { + window.alert( + "Could not clear audio storage. Try again before reloading.", + ); + return; + } location.reload(); } } - function handleFactoryReset() { + async function handleFactoryReset() { if ( window.confirm( "Factory reset WebOS? All settings, files, and profile data will be erased.", ) ) { - factoryReset(); + try { + await factoryReset(); + } catch { + window.alert( + "Could not clear audio storage. Your saved workspace has been kept.", + ); + } } } diff --git a/src/apps/registry.tsx b/src/apps/registry.tsx index 14824c9..b983843 100644 --- a/src/apps/registry.tsx +++ b/src/apps/registry.tsx @@ -1,3 +1,4 @@ +import { Music } from "./Music/Music"; import { FocusTimer } from "./FocusTimer/FocusTimer"; import { Photos } from "./Photos/Photos"; import { OfficeHub } from "./Office/OfficeHub"; @@ -23,6 +24,17 @@ import { Calendar } from "./Calendar/Calendar"; import { RecycleBin } from "./RecycleBin/RecycleBin"; export const appRegistry: Record = { + music: { + id: "music", + name: "Music", + icon: "Music", + component: Music, + defaultWidth: 800, + defaultHeight: 600, + minWidth: 300, + minHeight: 300, + singleInstance: true, + }, "focus-timer": { id: "focus-timer", name: "Focus Timer", diff --git a/src/lib/__tests__/helpers.test.ts b/src/lib/__tests__/helpers.test.ts index 508984a..bbdd904 100644 --- a/src/lib/__tests__/helpers.test.ts +++ b/src/lib/__tests__/helpers.test.ts @@ -25,9 +25,13 @@ describe("cx", () => { it("supports conditional classes", () => { const focused = true; const maximized = false; - expect(cx("window", focused && "window--focused", maximized && "window--maximized")).toBe( - "window window--focused", - ); + expect( + cx( + "window", + focused && "window--focused", + maximized && "window--maximized", + ), + ).toBe("window window--focused"); }); it("returns an empty string when nothing is truthy", () => { expect(cx(false, null)).toBe(""); @@ -56,10 +60,13 @@ describe("formatClock", () => { describe("factoryReset", () => { const original = window.location; afterEach(() => { - Object.defineProperty(window, "location", { value: original, configurable: true }); + Object.defineProperty(window, "location", { + value: original, + configurable: true, + }); }); - it("removes all webos storage keys and reloads, leaving unrelated keys alone", () => { + it("removes all webos storage keys and reloads, leaving unrelated keys alone", async () => { const reload = vi.fn(); Object.defineProperty(window, "location", { value: { ...original, reload }, @@ -70,7 +77,7 @@ describe("factoryReset", () => { localStorage.setItem("webos-profile", "x"); localStorage.setItem("unrelated", "keep"); - factoryReset(); + await factoryReset(); expect(localStorage.getItem("webos-filesystem")).toBeNull(); expect(localStorage.getItem("webos-system")).toBeNull(); diff --git a/src/lib/__tests__/launchAndOpen.test.ts b/src/lib/__tests__/launchAndOpen.test.ts index 6dd88b2..588e7b6 100644 --- a/src/lib/__tests__/launchAndOpen.test.ts +++ b/src/lib/__tests__/launchAndOpen.test.ts @@ -139,3 +139,29 @@ describe("openFsNode", () => { expect(wins()).toHaveLength(1); }); }); + +describe("audio file opening", () => { + beforeEach(resetAllStores); + it("retargets the single Music window when another audio file opens", () => { + const fs = useFileSystemStore.getState(); + const first = fs.createNode( + fs.rootId, + "first.wav", + "file", + "webos-audio:first", + ); + const second = fs.createNode( + fs.rootId, + "second.wav", + "file", + "webos-audio:second", + ); + openFsNode(fs.getNode(first)!); + openFsNode(fs.getNode(second)!); + expect(wins()).toHaveLength(1); + expect(wins()[0]).toMatchObject({ + appId: "music", + launchProps: { fileId: second }, + }); + }); +}); diff --git a/src/lib/audioStorage.ts b/src/lib/audioStorage.ts new file mode 100644 index 0000000..f7824f2 --- /dev/null +++ b/src/lib/audioStorage.ts @@ -0,0 +1,80 @@ +export interface AudioEntry { + id: string; + blob: Blob; +} +const database = "webos-media"; +async function run( + mode: IDBTransactionMode, + operation: (store: IDBObjectStore) => IDBRequest | undefined, +): Promise { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open(database, 1); + request.onupgradeneeded = () => + request.result.createObjectStore("audio", { keyPath: "id" }); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + request.onblocked = () => + reject(new Error("Close other WebOS tabs to access audio storage.")); + }); + return new Promise((resolve, reject) => { + const transaction = db.transaction("audio", mode); + const request = operation(transaction.objectStore("audio")); + transaction.oncomplete = () => { + db.close(); + resolve(request?.result as T); + }; + transaction.onerror = transaction.onabort = () => { + db.close(); + reject(transaction.error ?? new Error("Audio storage failed.")); + }; + }); +} +interface StoredAudio { + id: string; + type: string; + data: ArrayBuffer; +} +export async function putAudio(id: string, blob: Blob) { + const data = await blob.arrayBuffer(); + await run("readwrite", (store) => store.put({ id, type: blob.type, data })); +} +export async function getAudio(id: string): Promise { + const entry = await run("readonly", (store) => + store.get(id), + ); + return entry ? new Blob([entry.data], { type: entry.type }) : undefined; +} +export async function audioEntries(): Promise { + const entries = await run("readonly", (store) => + store.getAll(), + ); + return entries.map((entry) => ({ + id: entry.id, + blob: new Blob([entry.data], { type: entry.type }), + })); +} +export async function deleteAudio(ids: string[]) { + if (typeof indexedDB === "undefined" || !ids.length) return; + await run("readwrite", (store) => { + for (const id of ids) store.delete(id); + return undefined; + }); +} +export async function replaceAudio(entries: AudioEntry[]) { + if (typeof indexedDB === "undefined") return; + const stored = await Promise.all( + entries.map(async (entry) => ({ + id: entry.id, + type: entry.blob.type, + data: await entry.blob.arrayBuffer(), + })), + ); + await run("readwrite", (store) => { + store.clear(); + for (const entry of stored) store.put(entry); + return undefined; + }); +} +export function audioId(content?: string): string | null { + return content?.startsWith("webos-audio:") ? content.slice(12) : null; +} diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts index 9e289b0..8e39f05 100644 --- a/src/lib/helpers.ts +++ b/src/lib/helpers.ts @@ -1,3 +1,4 @@ +import { replaceAudio } from "./audioStorage"; import { clearOfficeRecovery } from "../apps/Office/recovery"; export function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max); @@ -25,7 +26,9 @@ export function cx(...classes: (string | false | undefined | null)[]): string { return classes.filter(Boolean).join(" "); } -export function factoryReset() { +export async function factoryReset() { + await replaceAudio([]); + localStorage.removeItem("webos-music"); clearOfficeRecovery(); localStorage.removeItem("webos-widgets"); localStorage.removeItem("webos-focus"); diff --git a/src/lib/openNode.ts b/src/lib/openNode.ts index 212ac5a..1d6f1fa 100644 --- a/src/lib/openNode.ts +++ b/src/lib/openNode.ts @@ -55,19 +55,27 @@ export function openFsNode(node: FsNode) { if (!node.name.endsWith(".app")) useRecentFilesStore.getState().record(node.id); - const appId: AppId = node.name.toLowerCase().endsWith(".wsheet") - ? "sheets" - : node.name.toLowerCase().endsWith(".wslides") - ? "slides" - : node.name.toLowerCase().endsWith(".wdoc") - ? "writer" - : isImageFile(node.name) - ? "photos" - : "text-editor"; + const appId: AppId = /\.(mp3|wav|ogg|m4a|aac|webm|flac)$/i.test(node.name) + ? "music" + : node.name.toLowerCase().endsWith(".wsheet") + ? "sheets" + : node.name.toLowerCase().endsWith(".wslides") + ? "slides" + : node.name.toLowerCase().endsWith(".wdoc") + ? "writer" + : isImageFile(node.name) + ? "photos" + : "text-editor"; const existing = windows.find( - (w) => w.appId === appId && w.launchProps?.fileId === node.id, + (w) => + w.appId === appId && + (appId === "music" || w.launchProps?.fileId === node.id), ); if (existing) { + if (appId === "music") + useWindowStore + .getState() + .setLaunchProps(existing.id, { fileId: node.id }); focusWindow(existing.id); return; } diff --git a/src/stores/useFileSystemStore.test.ts b/src/stores/useFileSystemStore.test.ts index 7d6afef..51b0a39 100644 --- a/src/stores/useFileSystemStore.test.ts +++ b/src/stores/useFileSystemStore.test.ts @@ -27,7 +27,7 @@ describe("useFileSystemStore", () => { ]), ); const apps = fs().getChildren(byName("System Apps").id); - expect(apps).toHaveLength(22); + expect(apps).toHaveLength(23); expect(apps.every((a) => a.name.endsWith(".app") && a.content)).toBe( true, ); @@ -265,7 +265,7 @@ describe("useFileSystemStore", () => { const id = fs().createNode(byName("Desktop").id, "mine.txt", "file", ""); fs().resetFileSystem(); expect(fs().getNode(id)).toBeUndefined(); - expect(fs().getChildren(byName("System Apps").id)).toHaveLength(22); + expect(fs().getChildren(byName("System Apps").id)).toHaveLength(23); }); }); @@ -273,7 +273,7 @@ describe("useFileSystemStore", () => { it("persists nodes under the webos-filesystem key", () => { fs().createNode(byName("Desktop").id, "persisted.txt", "file", ""); const raw = JSON.parse(localStorage.getItem("webos-filesystem")!); - expect(raw.version).toBe(15); + expect(raw.version).toBe(16); const names = Object.values<{ name: string }>(raw.state.nodes).map( (n) => n.name, ); @@ -310,7 +310,7 @@ describe("useFileSystemStore", () => { }), ); await useFileSystemStore.persist.rehydrate(); - expect(fs().getChildren(byName("System Apps").id)).toHaveLength(22); + expect(fs().getChildren(byName("System Apps").id)).toHaveLength(23); expect(fs().getNode("mine")!.content).toBe("precious"); }); }); diff --git a/src/stores/useFileSystemStore.ts b/src/stores/useFileSystemStore.ts index 5f81213..45d20f0 100644 --- a/src/stores/useFileSystemStore.ts +++ b/src/stores/useFileSystemStore.ts @@ -1,3 +1,6 @@ +import { audioId, deleteAudio } from "../lib/audioStorage"; +import { useMusicStore } from "./useMusicStore"; +import { notify } from "../lib/notify"; import { useRecentFilesStore } from "./useRecentFilesStore"; import { create } from "zustand"; import { persist } from "zustand/middleware"; @@ -28,7 +31,7 @@ interface FsState { updateContent: (id: string, content: string) => void; moveNode: (id: string, newParentId: string) => void; getPath: (id: string) => string; - resetFileSystem: () => void; + resetFileSystem: () => Promise; restoreNode: (id: string) => void; permanentlyDelete: (id: string) => void; emptyRecycleBin: () => void; @@ -57,6 +60,7 @@ const SYSTEM_APP_FILES: [string, string][] = [ ["Writer.app", "writer"], ["Office.app", "office"], ["Photos.app", "photos"], + ["Music.app", "music"], ["Focus Timer.app", "focus-timer"], ["Slides.app", "slides"], ["Sheets.app", "sheets"], @@ -325,6 +329,17 @@ export const useFileSystemStore = create()( } } } + const media = toRemove + .map((rid) => audioId(nextDeleted[rid]?.node.content)) + .filter((id): id is string => !!id); + useMusicStore.getState().removeFiles(toRemove); + void deleteAudio(media).catch(() => + notify( + "Music", + "Could not clean up deleted audio storage.", + "Music", + ), + ); for (const rid of toRemove) { delete nextDeleted[rid]; } @@ -333,6 +348,17 @@ export const useFileSystemStore = create()( }, emptyRecycleBin: () => { + const deleted = Object.values(get().deletedNodes); + useMusicStore + .getState() + .removeFiles(deleted.map((entry) => entry.node.id)); + void deleteAudio( + deleted + .map((entry) => audioId(entry.node.content)) + .filter((id): id is string => !!id), + ).catch(() => + notify("Music", "Could not clean up deleted audio storage.", "Music"), + ); set({ deletedNodes: {} }); }, @@ -379,14 +405,25 @@ export const useFileSystemStore = create()( return "/" + parts.join("/"); }, - resetFileSystem: () => { + resetFileSystem: async () => { + const state = get(); + const files = [ + ...Object.values(state.nodes), + ...Object.values(state.deletedNodes).map((entry) => entry.node), + ]; + useMusicStore.getState().removeFiles(files.map((node) => node.id)); useRecentFilesStore.getState().clear(); set({ ...buildSeed(), deletedNodes: {} }); + await deleteAudio( + files + .map((node) => audioId(node.content)) + .filter((id): id is string => !!id), + ); }, }), { name: "webos-filesystem", - version: 15, + version: 16, partialize: (state) => ({ nodes: state.nodes, rootId: state.rootId, @@ -399,7 +436,7 @@ export const useFileSystemStore = create()( deletedNodes?: Record; }; if (!state.deletedNodes) state.deletedNodes = {}; - if (version < 15) { + if (version < 16) { // ensure the System Apps folder exists let sysFolder = Object.values(state.nodes).find( (n) => diff --git a/src/stores/useMusicStore.test.ts b/src/stores/useMusicStore.test.ts new file mode 100644 index 0000000..3337ad8 --- /dev/null +++ b/src/stores/useMusicStore.test.ts @@ -0,0 +1,16 @@ +import { beforeEach, expect, it } from "vitest"; +import { useMusicStore as store } from "./useMusicStore"; +beforeEach(() => store.setState(store.getInitialState(), true)); +it("keeps playlists unique by track and prunes permanently removed files", () => { + store.getState().create("Favorites"); + const id = store.getState().playlists[0].id; + store.getState().addTrack(id, "track"); + store.getState().addTrack(id, "track"); + expect(store.getState().playlists[0].files).toEqual(["track"]); + store.getState().rename(id, "Road trip"); + expect(store.getState().playlists[0].name).toBe("Road trip"); + store.getState().removeFiles(["track"]); + expect(store.getState().playlists[0].files).toEqual([]); + store.getState().remove(id); + expect(store.getState().playlists).toEqual([]); +}); diff --git a/src/stores/useMusicStore.ts b/src/stores/useMusicStore.ts new file mode 100644 index 0000000..7804646 --- /dev/null +++ b/src/stores/useMusicStore.ts @@ -0,0 +1,78 @@ +import { create } from "zustand"; +import { persist } from "zustand/middleware"; +interface Playlist { + id: string; + name: string; + files: string[]; +} +interface MusicState { + playlists: Playlist[]; + volume: number; + repeat: "off" | "all" | "one"; + shuffle: boolean; + create: (name: string) => void; + rename: (id: string, name: string) => void; + remove: (id: string) => void; + addTrack: (id: string, file: string) => void; + removeTrack: (id: string, file: string) => void; + removeFiles: (ids: string[]) => void; + settings: ( + updates: Partial>, + ) => void; +} +export const useMusicStore = create()( + persist( + (set) => ({ + playlists: [], + volume: 0.8, + repeat: "off", + shuffle: false, + create: (name) => { + if (!name.trim() || name.trim().length > 80) return; + set((state) => ({ + playlists: [ + ...state.playlists, + { id: crypto.randomUUID(), name: name.trim(), files: [] }, + ], + })); + }, + rename: (id, name) => { + if (!name.trim() || name.trim().length > 80) return; + set((state) => ({ + playlists: state.playlists.map((list) => + list.id === id ? { ...list, name: name.trim() } : list, + ), + })); + }, + remove: (id) => + set((state) => ({ + playlists: state.playlists.filter((list) => list.id !== id), + })), + addTrack: (id, file) => + set((state) => ({ + playlists: state.playlists.map((list) => + list.id === id + ? { ...list, files: [...new Set([...list.files, file])] } + : list, + ), + })), + removeTrack: (id, file) => + set((state) => ({ + playlists: state.playlists.map((list) => + list.id === id + ? { ...list, files: list.files.filter((value) => value !== file) } + : list, + ), + })), + removeFiles: (ids) => + set((state) => ({ + playlists: state.playlists.map((list) => ({ + ...list, + files: list.files.filter((id) => !ids.includes(id)), + })), + })), + settings: (updates) => set(updates), + }), + { name: "webos-music" }, + ), +); diff --git a/src/test/resetStores.ts b/src/test/resetStores.ts index 7a64770..220e0c2 100644 --- a/src/test/resetStores.ts +++ b/src/test/resetStores.ts @@ -1,3 +1,4 @@ +import { useMusicStore } from "../stores/useMusicStore"; import { useWidgetsStore } from "../stores/useWidgetsStore"; import { useFocusStore } from "../stores/useFocusStore"; import { useBookmarksStore } from "../stores/useBookmarksStore"; @@ -16,6 +17,7 @@ import { useNotificationStore } from "../stores/useNotificationStore"; import { useEditorSettingsStore } from "../stores/useEditorSettingsStore"; export function resetAllStores() { + useMusicStore.setState(useMusicStore.getInitialState(), true); useWidgetsStore.setState(useWidgetsStore.getInitialState(), true); useFocusStore.setState(useFocusStore.getInitialState(), true); useBookmarksStore.setState(useBookmarksStore.getInitialState(), true); diff --git a/src/types/index.ts b/src/types/index.ts index df7a0ee..34545a4 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -15,6 +15,7 @@ export interface FsNode { // ---------- Apps ---------- export type AppId = + | "music" | "focus-timer" | "photos" | "office"