Debian Codegraph @

html_renderer/src/lib/utils.ts

raw symbols SCIP
1
2 export class UnreachableCaseError extends Error {
3 constructor(value: never) {
4 super(`Unreachable case: ${value}`)
5 }
6 }
7
8 export function sampleGradient(gradient: number[][], location: number) {
9 const index = location * (gradient.length - 1)
10 const lowerIndex = Math.floor(index)
11 const upperIndex = Math.ceil(index)
12 const lowerColor = gradient[lowerIndex]
13 const upperColor = gradient[upperIndex]
14 const ratio = index - lowerIndex
15 return mapRGBColor(ratio, { to: [lowerColor, upperColor] })
16 }
17
18 export function clamp(value: number, min: number, max: number): number {
19 if (value === Infinity) {
20 console.warn('clamp: value is Infinity, returning `max`', value);
21 return max;
22 }
23 if (value === -Infinity) {
24 console.warn('clamp: value is -Infinity, returning `min`', value);
25 return min;
26 }
27 if (!Number.isFinite(value)) {
28 console.warn('clamp: value isn\'t finite, returning `min`', value);
29 return min
30 }
31
32 if (value < min) return min;
33 if (value > max) return max;
34 return value;
35 }
36
37 export function map(x: number, options: {
38 from?: [number, number],
39 to?: [number, number],
40 clamp?: boolean
41 }): number {
42 const { from = [0, 1], to = [0, 1] } = options;
43 const shouldClamp = options.clamp || false;
44
45 let result = (x - from[0]) / (from[1] - from[0]) * (to[1] - to[0]) + to[0]
46 if (shouldClamp) {
47 result = clamp(result, Math.min(to[0], to[1]), Math.max(to[0], to[1]));
48 }
49
50 return result;
51 }
52
53 export function mapRGBColor(x: number, options: {
54 from?: [number, number],
55 to: [number[], number[]],
56 clamp?: boolean
57 }): string {
58 return `rgb(
59 ${map(x, { from: options.from, to: [options.to[0][0], options.to[1][0]], clamp: options.clamp })},
60 ${map(x, { from: options.from, to: [options.to[0][1], options.to[1][1]], clamp: options.clamp })},
61 ${map(x, { from: options.from, to: [options.to[0][2], options.to[1][2]], clamp: options.clamp })}
62 )`
63 }
64
65 export function mapColor(x: number, options: {
66 from?: [number, number],
67 to: [string, string],
68 clamp?: boolean
69 }): string {
70 return mapRGBColor(x, {
71 from: options.from,
72 to: [parseColor(options.to[0]), parseColor(options.to[1])],
73 clamp: options.clamp
74 })
75 }
76
77 /**
78 * @returns A color string in the format "rgb(r, g, b)", where r, g, and b
79 * are integers in the range [0, 255].
80 */
81 export function parseColor(input: string) {
82 if (input.substr(0, 1) == "#") {
83 var collen = (input.length - 1) / 3;
84 var fact = [17, 1, 0.062272][collen - 1];
85 return [
86 Math.round(parseInt(input.substr(1, collen), 16) * fact),
87 Math.round(parseInt(input.substr(1 + collen, collen), 16) * fact),
88 Math.round(parseInt(input.substr(1 + 2 * collen, collen), 16) * fact)
89 ];
90 }
91 else return input.split("(")[1].split(")")[0].split(",").map(x => +x);
92 }
93
94 /**
95 * returns a hash of the string, as an integer with 2^53 possible values.
96 */
97 export function cyrb53(str: string, seed: number = 0) {
98 let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
99 for(let i = 0, ch; i < str.length; i++) {
100 ch = str.charCodeAt(i);
101 h1 = Math.imul(h1 ^ ch, 2654435761);
102 h2 = Math.imul(h2 ^ ch, 1597334677);
103 }
104 h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
105 h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
106 h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
107 h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
108
109 return 4294967296 * (2097151 & h2) + (h1 >>> 0);
110 };
111
112 export function hash(str: string) {
113 return cyrb53(str, 21) / 2**53;
114 }
115
116 interface OnClickOutsideOptions {
117 ignore?: (HTMLElement | string)[];
118 capture?: boolean;
119 }
120
121 type OnClickOutsideHandler = (evt: MouseEvent) => void;
122
123 /**
124 * Listen for clicks outside of an element.
125 *
126 * Translated from
127 * https://github.com/vueuse/vueuse/blob/798077d678a2a8cd50cc3c3b85a722befb6087d4/packages/core/onClickOutside/index.ts
128 * License: MIT
129 * https://github.com/vueuse/vueuse/blob/798077d678a2a8cd50cc3c3b85a722befb6087d4/LICENSE
130 *
131 * @param target - The target element to watch for outside clicks.
132 * @param handler - The function to call when a click outside the target is detected.
133 * @param options - Optional configurations.
134 * @returns A cleanup function that removes the event listeners.
135 */
136 export function onClickOutside(
137 target: HTMLElement,
138 handler: OnClickOutsideHandler,
139 options: OnClickOutsideOptions = {}
140 ) {
141 const { ignore = [], capture = true } = options;
142 const windowObj = window;
143
144 if (!windowObj) return () => {};
145
146 let shouldListen = true;
147 let isProcessingClick = false;
148
149 const shouldIgnore = (event: MouseEvent) => {
150 return ignore.some((target) => {
151 if (typeof target === "string") {
152 return Array.from(document.querySelectorAll(target)).some(
153 (el) => el === event.target || event.composedPath().includes(el)
154 );
155 } else {
156 return target && (event.target === target || event.composedPath().includes(target));
157 }
158 });
159 };
160
161 const listener = (event: MouseEvent) => {
162 if (!target || target === event.target || event.composedPath().includes(target)) return;
163
164 if (event.detail === 0) shouldListen = !shouldIgnore(event);
165
166 if (!shouldListen) {
167 shouldListen = true;
168 return;
169 }
170
171 handler(event);
172 };
173
174 const clickListener = (event: MouseEvent) => {
175 if (!isProcessingClick) {
176 isProcessingClick = true;
177 setTimeout(() => {
178 isProcessingClick = false;
179 }, 0);
180 listener(event);
181 }
182 };
183
184 const pointerDownListener = (event: PointerEvent) => {
185 shouldListen = !shouldIgnore(event) && !!(target && !event.composedPath().includes(target));
186 };
187
188 windowObj.addEventListener("click", clickListener, { passive: true, capture });
189 windowObj.addEventListener("pointerdown", pointerDownListener, { passive: true });
190
191 const stop = () => {
192 windowObj.removeEventListener("click", clickListener, { capture });
193 windowObj.removeEventListener("pointerdown", pointerDownListener);
194 };
195
196 return stop;
197 }
198
199 export function escapeForHtml(str: string) {
200 const div = document.createElement('div');
201 div.appendChild(document.createTextNode(str));
202 return div.innerHTML;
203 }
204
205 export function htmlForStringWithWBRAtSlashes(str: string) {
206 let result = escapeForHtml(str);
207 return result.replace(/(\/|\\)/g, s => `${s}<wbr>`);
208 }
209
210 export function maxBy<T>(list: readonly T[], keyFunc: (a:T) => number): T|null {
211 if (list.length == 0) return null
212
213 let maxResult = list[0]
214 let maxResultScore = keyFunc(maxResult)
215
216 for (const el of list) {
217 const elScore = keyFunc(el)
218 if (elScore > maxResultScore) {
219 maxResult = el
220 maxResultScore = elScore
221 }
222 }
223
224 return maxResult
225 }
226
227 /**
228 * Provides 56 bits of randomness as a neat 11-character string.
229 */
230 export function randomId() {
231 return Math.random().toString(36).substring(2);
232 }