-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.mjs
More file actions
411 lines (372 loc) · 10.3 KB
/
Copy pathutils.mjs
File metadata and controls
411 lines (372 loc) · 10.3 KB
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// @ts-check
/**
* @import { CreateElementOptions } from "./@types/utils"
*/
/**
* @param {any} any
* @returns {any}
*/
export function asAny(any) {
return any;
}
/**
* @param {URLSearchParams} urlParams
*/
export function replaceLocation(urlParams) {
const url = new URL(window.location.href);
const newLocation = `${url.origin}${url.pathname}?${urlParams}`;
history.replaceState(null, "", newLocation);
}
/**
* @param {URLSearchParams} urlParams
*/
export function changeLocation(urlParams) {
const url = new URL(window.location.href);
const newLocation = `${url.origin}${url.pathname}?${urlParams}`;
// @ts-ignore
window.location = newLocation;
}
/**
* @param {string} key
* @param {any} value
*/
export function exposeAsGlobal(key, value) {
console.log(key, value);
asAny(window)[key] = value;
}
/**
* Gets an element and throws if it doesn't exists. The className provided to specialize
* the type. Note the `any` coercion for the HTMLElement is working around an issue
* where TypeScript complains about the types. This workaround makes it so that the
* types are correctly inferred, and there are no runtime errors.
*
* @template {HTMLElement} T
*
* @param {string} id
* @param {{ new (): T }} className
* @returns {T}
*/
export function getElement(id, className = /** @type {any} */ (HTMLElement)) {
const element = document.getElementById(id);
if (!element) {
throw new Error("Could not find element by id: " + id);
}
if (!(element instanceof className)) {
throw new Error(
`Selected element #${id} was not an instance of ${className.name}`
);
}
return element;
}
/**
* Helper to create a table row, and add TD elements.
*
* @param {HTMLElement} tbody
* @param {Element?} [insertBefore]
*/
export function createTableRow(tbody, insertBefore) {
const tr = document.createElement("tr");
tbody.insertBefore(tr, insertBefore ?? null);
return {
tr,
/**
* @param {string | Element} [textOrEl]
* @returns {HTMLTableCellElement}
*/
createTD(textOrEl = "") {
const el = document.createElement("td");
if (typeof textOrEl === "string") {
el.innerText = textOrEl;
} else {
el.appendChild(textOrEl);
}
tr.appendChild(el);
return el;
},
};
}
/**
* Helper to create an <a href> tag.
*
* @param {string} text
* @param {string} [href]
*/
export function createLink(text, href) {
const a = document.createElement("a");
if (href) {
a.href = href;
}
a.innerText = text;
return a;
}
/**
* Helper to create a button with an action.
*
* @param {string | Element} textOrEl
* @param {(this: HTMLButtonElement, event: MouseEvent) => unknown} callback
*/
export function createButton(textOrEl, callback) {
const button = document.createElement("button");
button.addEventListener("click", callback);
if (typeof textOrEl === "string") {
button.innerText = textOrEl;
} else {
button.appendChild(textOrEl);
}
return button;
}
/**
* Formats a number of bytes into a human-readable string.
*
* @param {number} bytes
* @param {number} [decimals]
* @returns {string}
*/
export function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return "0 B";
const k = 1000;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}
/**
* @typedef {object} SearchFilters
* @property {string} key
* @property {string} value
* @property {boolean} negated
*/
/**
* AI-generated search query parser, manually tweaked.
*
* > Write a JS parser for the following search syntax:
* >
* > name:search-term date:>2025-01-02 -language:french
* >
* > term1 term2
* >
* > "quoted term"
* >
* > name:"quoted term" date:<2025-01-12
*
* @param {string} query
* @returns {{ filters: SearchFilters[], terms: string[] }}
*/
export function parseSearchQuery(query) {
const fieldPattern = /(?:^|\s)(-?)(\w+):(\"[^\"]+\"|[^\s]+)/g;
const unstructuredPattern = /(?:^|\s)(\"[^\"]+\"|\S+)/g;
let match;
/** @type {SearchFilters[]} */
const filters = [];
/** @type {string[]} */
const terms = [];
const seenIndices = new Set();
// Extract field-based filters
while ((match = fieldPattern.exec(query)) !== null) {
const [, negation, key, rawValue] = match;
const value = rawValue.replace(/^\"|\"$/g, "").trim();
if (value) {
filters.push({
key: key.toLowerCase(),
value: value.toLowerCase(),
negated: !!negation,
});
}
seenIndices.add(match.index);
}
// Extract unstructured search terms
while ((match = unstructuredPattern.exec(query)) !== null) {
if (!seenIndices.has(match.index)) {
const value = match[1].replace(/^\"|\"$/g, "");
if (value.trim()) {
terms.push(value.toLowerCase());
}
}
}
return { filters, terms };
}
/**
* @param {URLSearchParams} urlParams
*/
export function pushLocation(urlParams) {
const url = new URL(window.location.href);
const newLocation = `${url.origin}${url.pathname}?${urlParams}`;
history.pushState(null, "", newLocation);
}
/**
* @param {any} object
*/
export function jsonToYAML(object, indent = 0) {
const spaces = " ".repeat(indent);
let yaml = "";
for (const [key, value] of Object.entries(object)) {
const formattedKey = /^[a-zA-Z0-9_-]+$/.test(key) ? key : `'${key}'`;
if (value === null) {
yaml += `${spaces}${formattedKey}: null\n`;
} else if (typeof value === "boolean" || typeof value === "number") {
yaml += `${spaces}${formattedKey}: ${value}\n`;
} else if (typeof value === "string") {
yaml += `${spaces}${formattedKey}: ${
value.includes(":") || value.includes("\n")
? `|\n${spaces} ` + value.replace(/\n/g, `\n${spaces} `)
: value
}\n`;
} else if (Array.isArray(value)) {
if (value.length === 0) {
yaml += `${spaces}${formattedKey}: []\n`;
} else {
yaml += `${spaces}${formattedKey}:\n`;
for (const item of value) {
yaml += `${spaces} - ${
typeof item === "object"
? "\n" + jsonToYAML(item, indent + 2)
: item
}\n`;
}
}
} else if (typeof value === "object") {
yaml += `${spaces}${formattedKey}:\n` + jsonToYAML(value, indent + 1);
}
}
return yaml;
}
/**
* A type-only check that a type is "never"
* @param {never} never
*/
export function isNever(never) {}
/**
* A utility function to make it easier to create HTML elements declaratively.
*
* @template {keyof HTMLElementTagNameMap} T
*
* @param {T} tagName
* @param {Partial<CreateElementOptions>} [options]
*/
export function createElement(tagName, options) {
const element = document.createElement(tagName);
if (options) {
const { style, parent, children, href, className, title, attrs, onClick } =
options;
if (style) {
Object.assign(element.style, style);
}
if (attrs) {
for (const [key, value] of Object.entries(attrs)) {
if (value) {
element.setAttribute(key, String(value));
}
}
}
if (href !== undefined) {
if (element instanceof HTMLAnchorElement) {
element.href = href;
} else {
throw new Error("An href was provided for a non-anchor element.");
}
}
if (typeof children === "string") {
element.innerText = children;
} else if (typeof children === "number") {
element.innerText = String(children);
} else if (Array.isArray(children)) {
for (const child of children) {
if (typeof child === "string") {
element.appendChild(new Text(child));
} else if (typeof child === "number") {
element.appendChild(new Text(String(child)));
} else {
element.appendChild(child);
}
}
} else if (children instanceof Node) {
element.appendChild(children);
} else if (children) {
// Ensure we've handled all of the cases.
isNever(children);
}
if (className) {
element.className = className;
}
if (title) {
element.title = title;
}
if (onClick) {
if (element instanceof HTMLButtonElement) {
element.addEventListener("click", onClick);
} else {
throw new Error(
"The createElement util needs support for this onClick handler"
);
}
}
// Append it last to avoid unnecessary jank.
if (parent) {
parent.appendChild(element);
}
}
return element;
}
/**
* A subset of supported tag names, feel free to add more tag names.
*/
const tagNames = [
/** @type {const} */ ("a"),
/** @type {const} */ ("br"),
/** @type {const} */ ("button"),
/** @type {const} */ ("canvas"),
/** @type {const} */ ("div"),
/** @type {const} */ ("h1"),
/** @type {const} */ ("h2"),
/** @type {const} */ ("h3"),
/** @type {const} */ ("h4"),
/** @type {const} */ ("li"),
/** @type {const} */ ("p"),
/** @type {const} */ ("pre"),
/** @type {const} */ ("span"),
/** @type {const} */ ("table"),
/** @type {const} */ ("tbody"),
/** @type {const} */ ("thead"),
/** @type {const} */ ("th"),
/** @type {const} */ ("td"),
/** @type {const} */ ("tr"),
/** @type {const} */ ("ul"),
];
/**
* @typedef {(typeof tagNames)[number]} TagNames
*/
/**
* @typedef {typeof createElement} CreateElement
*/
/**
* Exports the createElement interface in a convenient partially applied interface that
* can autocomplete. To support additional tag names, add the tag to the tagNames list.
*
* The simplified type for the interface is (the HTMLElement is specialized to the specific type).
*
* (options?: Partial<CreateElementOptions>) => HTMLElement
*
* @see {CreateElementOptions}
*
* Instead of:
*
* const coolDiv = createElement("div", {
* className: "cool-div",
* });
*
* You can write:
*
* const coolDiv = create.div({
* className: "cool-div",
* });
*
* @type {{ [K in TagNames]: (options?: Partial<CreateElementOptions>) => HTMLElementTagNameMap[K]; }}
*/
export const create = /** @type {any} */ ({});
// Create the partially applied createElement functions.
for (const tagName of tagNames) {
/**
* @type {(options?: Partial<CreateElementOptions>) => any}
*/
create[tagName] = (options) => createElement(tagName, options);
}