-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
272 lines (247 loc) · 7.39 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
export type Palette = Record<
| "background"
| "f_high"
| "f_med"
| "f_low"
| "f_inv"
| "b_high"
| "b_med"
| "b_low"
| "b_inv",
HexColor
>;
export type HexColor = `#${string}`;
export type LoadCallback = (palette: Palette) => unknown;
export type Options = Partial<{
host: Document;
onload: LoadCallback;
defaultTheme: Palette;
parser: DOMParser;
quiet: boolean;
}>;
/**
* Fork of 100r's {@link https://github.com/hundredrabbits/Themes|theme framework}, rewritten using ts + esm.
*
* Quick start:
* ```typescript
* const theme = new Theme();
* theme.install(); // see {@link install}
* theme.start(); // see {@link start}
* ```
*/
export default class Theme {
readonly defaultTheme: Palette;
#el: HTMLElement;
active?: Palette | undefined;
host: Document;
#parser: DOMParser;
readonly #quiet: boolean;
onLoad?: LoadCallback | undefined;
/**
* Adds drag and drop listeners and appends the style element the to the {@link host}.
*/
install = (): void => {
this.host.addEventListener("dragover", this.drag);
this.host.addEventListener("drop", this.drop);
this.host.body.appendChild(this.#el);
};
/**
* Try to load an existing theme in `localStorage`, or load the {@link defaultTheme|default theme}.
*
* @see {@link load}
*/
start = (): void => {
this.#log("Starting..");
try {
this.#log("Loading theme in localStorage...");
this.load(localStorage["theme"]);
} catch {
this.#log("Loading failed, falling back to default...");
this.load(this.defaultTheme);
}
};
/**
* Opens a dialog for the user to choose the theme file to {@link load}.
*
* @deprecated current non-functional.
*/
open = (): void => {
this.#log("Open theme..");
const input = this.host.createElement("input");
input.type = "file";
input.onchange = (e) => {
if (!e.target) return;
this.#log(e.target);
// this.read(e.target.files[0], this.load);
};
input.click();
};
/**
* Parse and load the provided theme.
*
* @param data an object or a string containing valid `application/json` or `image/svg+xml`.
*/
load = (data: Palette | string): void => {
const theme = this.parse(data);
this.#el.innerHTML = `:root {${
Object.entries(theme).map(([key, val]) => `--${key}: ${val};`).join(" ")
}}`;
this.#log("Loaded theme.");
localStorage.setItem("theme", JSON.stringify(theme));
this.active = theme;
this.#log("Saved theme.");
if (this.onLoad) this.onLoad(theme);
};
/**
* Loads the default theme.
*/
reset = (): void => {
this.load(this.defaultTheme);
};
/**
* Sets a color by the key to the current {@link active|active theme}.
*
* @param key the color key of the {@link Palette}
* @param val a {@link HexColor} formatted color string
*/
set = (key: keyof Palette, val: string): void => {
if (!this.isColor(val)) {
throw new Error("Theme: invalid color provided.");
}
if (!this.active) {
throw new Error("Theme: theme have not been started yet.");
}
this.active[key] = val as HexColor; // check on above
};
/**
* Gets a color by the key in the current {@link active|active palette}.
*
* @param key color key in a {@link Palette}
* @returns a {@link HexColor} formatted string that represents the selected color
*/
get = (key: keyof Palette): string => {
if (!this.active) {
throw new Error("Theme: theme have not been started yet.");
}
return this.active[key];
};
/**
* Transforms the provided data into a parsed theme as an object.
*
* @param data an object or a string containing valid `application/json` or `image/svg+xml`
* @returns an object representing the provided theme
* @see {@link load}
*/
parse = (data: unknown): Palette => {
switch (typeof data) {
case "string":
if (this.isJson(data)) return this.parse(JSON.parse(data));
if (this.isSvg(data)) return this.extract(data);
break;
case "object":
if (this.isValid(data)) return data as Palette;
throw new Error("Theme: invalid palette provided.");
}
throw new Error("Theme: Unrecognized data format.");
};
drag = (e: DragEvent) => {
e.stopPropagation();
e.preventDefault();
if (!e.dataTransfer) return;
e.dataTransfer.dropEffect = "copy";
};
drop = (e: DragEvent) => {
e.preventDefault();
if (!e.dataTransfer) return;
const file = e.dataTransfer.files[0];
if (!file) return;
if (file.name.indexOf(".svg") > -1) {
this.read(file, this.load);
}
e.stopPropagation();
};
read = (file: File, callback: typeof this.load): void => {
const reader = new FileReader();
reader.onload = (event) => {
if (typeof event.target?.result !== "string") return;
callback(event.target.result);
};
reader.readAsText(file, "UTF-8");
};
isColor = (hex: string): boolean => /^#([0-9A-F]{3}){1,2}$/i.test(hex);
isJson = (text: string): boolean => {
try {
JSON.parse(text);
} catch {
return false;
}
return true;
};
isSvg = (text: string): boolean => {
try {
this.#parser.parseFromString(text, "image/svg+xml");
} catch {
return false;
}
return true;
};
/**
* Checks if the provided object is a valid theme.
*
* @param palette an object containing possible valid {@link Palette}.
* @returns true if provided palette is not undefined or null, contains all colors, and all colors are valid {@link HexColor}.
*/
isValid = (palette?: object | null): boolean =>
palette !== undefined &&
palette !== null &&
Object.keys(palette).length > 0 &&
Object.keys(palette).sort().every((el, i) =>
el === Object.keys(this.defaultTheme).sort()[i] // probably not a very efficient check
) &&
Object.values(palette).map(this.isColor).every((el) => el === true);
/**
* Transforms the provided xml into a valid {@link Palette} object.
*
* @param xml a string containing valid `image/svg+xml`.
* @returns
*/
extract = (xml: string): Palette => {
const svg = this.#parser.parseFromString(xml, "image/svg+xml");
const theme = (Object.keys(this.defaultTheme) as (keyof Palette)[])
.reduce((palette, key) => {
const color = svg.getElementById(key)?.getAttribute("fill");
if (!color) throw new Error("Theme: Incomplete SVG theme.");
if (!this.isColor(color)) {
throw new Error("Theme: Invalid color provided in SVG.");
}
palette[key] = color as HexColor;
return palette;
}, {} as Palette);
return theme;
};
#log = (...data: unknown[]) => {
if (!this.#quiet) console.log("Theme:", ...data);
};
constructor(opts?: Options) {
if (opts?.defaultTheme && !this.isValid(opts?.defaultTheme)) {
throw new Error("Theme: invalid defaultTheme supplied.");
}
this.defaultTheme = opts?.defaultTheme || {
background: "#eeeeee",
f_high: "#0a0a0a",
f_med: "#4a4a4a",
f_low: "#6a6a6a",
f_inv: "#111111",
b_high: "#a1a1a1",
b_med: "#c1c1c1",
b_low: "#ffffff",
b_inv: "#ffb545",
};
this.host = opts?.host || globalThis.document;
this.onLoad = opts?.onload;
this.#el = this.host.createElement("style");
this.#el.id = "theme-framework";
this.#parser = opts?.parser || new globalThis.DOMParser();
this.#quiet = opts?.quiet || false;
}
}