-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.js
337 lines (311 loc) · 8.84 KB
/
util.js
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
let ERROR_ELEMENT = document.getElementById("error-msg");
/**
* Show the error messages associated with the given template.
* @param {...(Error | string)} errors
*/
export function render_error_messages(...errors) {
let message = "";
for (let error of errors) {
if (error instanceof Error) {
message += recursively_to_string(error);
} else {
message += error;
}
message += "\n\n";
}
if (ERROR_ELEMENT != null) {
ERROR_ELEMENT.innerText = message.trimEnd();
} else {
console.log("error-msg element is missing!");
}
}
/**
* Transform an error to a string, recursing into the `causes` field if available.
* @param {Error} err
* @return {string}
*/
export function recursively_to_string(err) {
let string = err.message;
if (err.cause) {
// @ts-ignore
string += recursively_to_string(err.cause);
}
return string;
}
/**
* Yields pairs of (index, item) from an array.
* @param {Array<T>} items An array of items
* @returns {Generator<[number, T]>} a tuple of (index, item)
* @template T
*/
export function* enumerate(items) {
let i = 0;
for (const item of items) {
yield [i, item];
i += 1;
}
}
/**
* Attempts to get an object from localStorage and parse it as JSON, falling back to a default value
* if this fails.
* @template T
* @param {string} key the key in localStorage to look up
* @param {T} fallback the fallback item to fall back to.
* @returns {any | T} The parsed object from localStorage, or the fallback if that fails
*/
export function localStorageOrDefault(key, fallback) {
let obj = localStorage.getItem(key);
if (obj == null) {
return fallback;
}
try {
return JSON.parse(obj);
} catch (err) {
console.warn(err);
return fallback;
}
}
/** Constructs HTML elements
* @param {string} tag - The tag of the HTML element
* @param {object} attrs -A dictionary of the attributes of the element
* whose keys are the attribute names and the values are the attribute values.
* Note that the "value" key (a key whose name is literally "value") is
* special--this sets the `node.value` property instead of setting an attribute.
* @param {string | HTMLElement | Array<string | HTMLElement>} [body] - The body of the HTML element.
* @returns {HTMLElement} - The constructed HTML element
* You can recursively call `h` to achieve nested objects.
* Example:
* ```javascript
* h("div", { class: "foo" }, [
* h("h1", { id: "bar" }, "Hello!"),
* h("p", {}, "World!"),
* ])
* ```
* This produces the following HTML
* ```html
* <div class="foo">
* <h1 id="bar">Hello!</h1>
* <p>World!<p>
* </div>
* ```
*/
export function h(tag, attrs, body = []) {
const element = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
// Special-case the value and have it set the actual node value
if (k == "value") {
// @ts-ignore
element["value"] = v;
} else {
element.setAttribute(k, v);
}
}
if (Array.isArray(body)) {
element.append(...body);
} else {
element.append(body);
}
return element;
}
/**
* @param {any} value
* @param {string} msg
*/
export function assert(value, msg) {
if (!value) {
throw new Error(`Assert failed: ${msg}`);
}
}
/**
* @template ElementType
* @param {any} object
* @param {Constructor<ElementType>} type The HTML element name to check for
* @returns {asserts object is ElementType}
*/
export function assert_html_node(object, type) {
if (!(object instanceof type)) {
throw new Error(`expected ${object} to be HTML node of type ${type.name}. Got ${object.constructor.name} instead.`);
}
}
/**
* @template T
* @typedef {new (...args: any[]) => T} Constructor
*/
/**
* @template ElementType
* @param {Constructor<ElementType>} ty
* @param {any} value
* @returns {asserts value is ElementType}
*/
export function assertType(value, ty) {
if (ty.name == "Number") {
console.warn(`Warning: using assertType() with ${ty.name} will not work for primative numbers! Use assertNumber() instead.`);
} else if (ty.name == "Boolean") {
console.warn(`Warning: using assertType() with ${ty.name} will not work for primative booleans! Use assertBoolean() instead.`);
}
if (!(value instanceof ty)) {
throw new Error(`Assert failed: Expected value (${value}) to be type ${ty.name}, but got ${value.constructor.name} instead.`);
}
}
/**
* @param {any} value
* @returns {asserts value is number}
*/
export function assertNumber(value) {
if (typeof value != "number") {
throw new Error(`Assert failed: Expected typeof value (${value}) to be number, but got ${value.constructor.name} instead.`);
}
}
/**
* @param {any} value
* @returns {asserts value is boolean}
*/
export function assertBoolean(value) {
if (typeof value != "boolean") {
throw new Error(`Assert failed: Expected typeof value (${value}) to be boolean, but got ${value.constructor.name} instead.`);
}
}
/**
* @template ElementType
* @param {Constructor<ElementType>} ty
* @param {string} id
* @returns {ElementType}
*/
export function getTypedElementById(ty, id) {
let element = document.getElementById(id);
if (element == null) { throw new Error(`Element with id ${id} not found!`); }
if (!(element instanceof ty)) {
throw new Error(`Element with id ${id} is type ${element.constructor.name}, wanted ${ty}`);
}
return element;
}
export class RGBColor {
/**
*
* @param {number} r red channel, 0x00 to 0xFF range inclusive
* @param {number} g green channel, 0x00 to 0xFF range inclusive
* @param {number} b blue channel, 0x00 to 0xFF range inclusive
*/
constructor(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
}
/**
*
* @param {string} hex_code
* @returns {RGBColor | null}
*/
static fromHexCode(hex_code) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex_code);
if (result) {
return new RGBColor(parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16));
} else {
return null;
}
}
/**
* Convert HSV to RGB
* from https://stackoverflow.com/questions/17242144/javascript-convert-hsb-hsv-color-to-rgb-accurately
* @param {number} h
* @param {number} s
* @param {number} v
* @returns {RGBColor}
*/
static fromHSV(h, s, v) {
var r, g, b, i, f, p, q, t;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
default:
case 5: r = v, g = p, b = q; break;
}
return new RGBColor(
Math.round(r * 0xFF),
Math.round(g * 0xFF),
Math.round(b * 0xFF),
);
}
/**
* Turns an RGBColor into [0.0 - 1.0] float triple.
* @returns {[number, number, number]}
*/
toFloat() {
return [this.r / 0xFF, this.g / 0xFF, this.b / 0xFF];
}
/**
* Turn a RGBColor into a hex string. Does not include the #.
* @returns {string}
*/
toHexString() {
return `${toHex(this.r)}${toHex(this.g)}${toHex(this.b)}`;
/**
* @param {number} c
*/
function toHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
}
}
/**
* @template T
* @param {T | null} x
* @return {T}
*/
export function unwrap(x) {
if (x == null) {
throw new Error("Unwrapped a null value!");
}
return x;
}
/**
* @param {number} n
* @param {number} modulus
*/
export function rem_euclid(n, modulus) {
let out = n % modulus;
return out < 0 ? out + Math.abs(modulus) : out;
}
/**
* @param {string} str
* @returns {boolean}
*/
export function isNumber(str) {
if (typeof str != "string") return false // we only process strings!
// could also coerce to string: str = ""+str
return !isNaN(+str) && !isNaN(parseFloat(str))
}
/**
* @param {any[]} array
* @returns {string}
*/
export function array_to_string(array) {
let out = "";
for (let i = 0; i < array.length; i += 1) {
out += array[i].toString();
if (i != array.length - 1) {
out += " ";
}
}
return out + "";
}
/**
* @template T
* @param {T[]} values
* @returns {T}
*/
export function choose(...values) {
let value = values[Math.floor(Math.random() * values.length)];
return value;
}