A music player that connects to your cloud/distributed storage.
1import { queryOptional } from "~/common/element.js";
2import * as Output from "~/common/output.js";
3
4/**
5 * @import {DiffuseElement} from "~/common/element.js"
6 * @import {OutputElement} from "~/components/output/types.d.ts"
7 */
8
9/**
10 * Read a stored session value from output settings when an output is configured,
11 * otherwise falls back to localStorage.
12 *
13 * @param {DiffuseElement} element
14 * @param {string} key
15 * @returns {Promise<string | null>}
16 */
17export async function readSession(element, key) {
18 /** @type {OutputElement | null} */
19 const output = queryOptional(element, "output-selector");
20
21 if (output) {
22 const settings = await Output.data(output.settings);
23 const existing = settings.find((s) => s.key === key);
24 if (existing) return existing.value;
25 }
26
27 return localStorage.getItem(key);
28}
29
30/**
31 * Save a session value to output settings when an output is configured,
32 * otherwise falls back to localStorage.
33 *
34 * @param {DiffuseElement} element
35 * @param {string} key
36 * @param {string} value
37 */
38export async function saveSession(element, key, value) {
39 /** @type {OutputElement | null} */
40 const output = queryOptional(element, "output-selector");
41
42 if (output) {
43 const settings = await Output.data(output.settings);
44 const existing = settings.find((s) => s.key === key);
45
46 const updated = existing
47 ? settings.map((s) => s.key === key ? { ...s, value } : s)
48 : [
49 ...settings,
50 {
51 $type: /** @type {"sh.diffuse.output.setting"} */ (
52 "sh.diffuse.output.setting"
53 ),
54 id: crypto.randomUUID(),
55 key,
56 value,
57 },
58 ];
59
60 await output.settings.save(updated);
61 } else {
62 localStorage.setItem(key, value);
63 }
64}
65
66/**
67 * Remove a stored session value from output settings when an output is configured,
68 * otherwise falls back to localStorage.
69 *
70 * @param {DiffuseElement} element
71 * @param {string} key
72 */
73export async function clearSession(element, key) {
74 /** @type {OutputElement | null} */
75 const output = queryOptional(element, "output-selector");
76
77 if (output) {
78 const settings = await Output.data(output.settings);
79 const updated = settings.filter((s) => s.key !== key);
80 if (updated.length !== settings.length) {
81 await output.settings.save(updated);
82 }
83 } else {
84 localStorage.removeItem(key);
85 }
86}