1import { computed } from "@common/signal.js";
2import { OutputTransformer } from "../../base.js";
3
4/**
5 * @import { OutputManagerDeputy } from "@components/output/types.d.ts"
6 */
7
8/**
9 * @extends {OutputTransformer<string>}
10 */
11class JsonStringOutputTransformer extends OutputTransformer {
12 constructor() {
13 super();
14
15 const base = this.base();
16
17 /** @type {OutputManagerDeputy} */
18 const manager = {
19 facets: {
20 ...base.facets,
21 collection: computed(() => {
22 const json = base.facets.collection();
23 return typeof json === "string" ? parseArray(json) : [];
24 }),
25 save: async (newFacets) => {
26 const json = JSON.stringify(newFacets);
27 await base.facets.save(json);
28 },
29 },
30 playlists: {
31 ...base.playlists,
32 collection: computed(() => {
33 const json = base.playlists.collection();
34 return typeof json === "string" ? parseArray(json) : [];
35 }),
36 save: async (newPlaylists) => {
37 const json = JSON.stringify(newPlaylists);
38 await base.playlists.save(json);
39 },
40 },
41 themes: {
42 ...base.themes,
43 collection: computed(() => {
44 const json = base.themes.collection();
45 return typeof json === "string" ? parseArray(json) : [];
46 }),
47 save: async (newThemes) => {
48 const json = JSON.stringify(newThemes);
49 await base.themes.save(json);
50 },
51 },
52 tracks: {
53 ...base.tracks,
54 collection: computed(() => {
55 const json = base.tracks.collection();
56 return typeof json === "string" ? parseArray(json) : [];
57 }),
58 save: async (newTracks) => {
59 const json = JSON.stringify(newTracks);
60 await base.tracks.save(json);
61 },
62 },
63 };
64
65 // Assign manager properties to class
66 this.facets = manager.facets;
67 this.playlists = manager.playlists;
68 this.themes = manager.themes;
69 this.tracks = manager.tracks;
70 }
71}
72
73/**
74 * @param {string} json
75 */
76function parseArray(json) {
77 try {
78 return JSON.parse(json);
79 } catch (err) {
80 console.error(err);
81 return [];
82 }
83}
84
85export default JsonStringOutputTransformer;
86
87////////////////////////////////////////////
88// REGISTER
89////////////////////////////////////////////
90
91export const CLASS = JsonStringOutputTransformer;
92export const NAME = "dtos-json";
93
94customElements.define(NAME, CLASS);