-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.ts
More file actions
203 lines (177 loc) · 4.88 KB
/
helpers.ts
File metadata and controls
203 lines (177 loc) · 4.88 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
import type {
Logger,
ScrollContainer,
ScrollPosition,
ScrollState,
Target,
} from "./defs.js";
import { finder } from "@medv/finder";
/** The logger and event prefix for the debug mode */
export const prefix = "restore-scroll";
/** Create a minimal logger with a prefix */
export function createLogger() {
const style = [
"background: linear-gradient(to right, #a960ee, #f78ed4)",
"color: white",
"padding-inline: 4px",
"border-radius: 2px",
"font-family: monospace",
].join(";");
return {
log: (...args: any[]) => console.log(`%c${prefix}`, style, ...args),
warn: (...args: any[]) => console.warn(`%c${prefix}`, style, ...args),
error: (...args: any[]) => console.error(`%c${prefix}`, style, ...args),
};
}
/** Return a Promise that resolves after the next event loop. */
export const nextTick = (): Promise<void> => {
return new Promise((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
});
};
/**
* Minimal debounce function.
* @see https://www.joshwcomeau.com/snippets/javascript/debounce/
*/
export function debounce<F extends (...args: unknown[]) => unknown>(
callback: F,
wait = 0,
): (...args: Parameters<F>) => void {
let timeout: ReturnType<typeof setTimeout>;
return (...args: Parameters<F>) => {
clearTimeout(timeout);
timeout = setTimeout(() => callback(...args), wait);
};
}
/**
* Check if an unknown value is a non-empty object
*/
export function isRecord(value: unknown): boolean {
return !!value && typeof value === "object" && !Array.isArray(value);
}
/**
* Check if an unknown value has the shape of the ScrollPosition type
*/
export function isScrollPosition(value: unknown): value is ScrollPosition {
return (
isRecord(value) &&
typeof (value as Record<string, unknown>).top === "number" &&
typeof (value as Record<string, unknown>).left === "number"
);
}
/**
* Check if an unknown value has the shape of the restoreScroll type
*/
export function isScrollState(value: unknown): value is ScrollState {
return (
isRecord(value) &&
Object.entries(value as Record<string, unknown>).every(
([key, value]) => typeof key === "string" && isScrollPosition(value),
)
);
}
/**
* Create a unique CSS selector for a given DOM element.
* Uses @medv/finder library for robust selector generation.
*/
function createUniqueSelector(el: Element): string {
// Use finder library to generate an optimal unique selector
return finder(el, {
root: document.body,
});
}
/**
* Get the container selector for an element
*/
export function createContainerSelector(
element: Element,
logger?: Logger,
): string {
if (!isRootElement(element) && !element.id) {
logger?.log(
"💡 for best results, add an [id] to elements you want to restore",
{ element },
);
}
return element.matches("body *") ? createUniqueSelector(element) : ":root";
}
/**
* Check if an element is a root element (<html> or <body>)
*/
export function isRootElement(element: unknown): boolean {
return (
element instanceof HTMLHtmlElement || element instanceof HTMLBodyElement
);
}
/**
* Read the container selector, log if none exists
*/
export function readContainerSelector(
element: ScrollContainer,
logger?: Logger,
): string | undefined {
const { selector } = element.__restore_scroll || {};
if (typeof selector !== "string") {
logger?.error("Invalid selector", { selector, element });
return;
}
if (!selector) {
logger?.error("No selector available", { element });
return;
}
return selector;
}
/**
* Read the scroll state from the current history
*/
export function readScrollState(): ScrollState {
const state = window.history.state?.restoreScroll;
return isScrollState(state) ? state : {};
}
/**
* Commit the provided scroll state to the history
*/
export function commitScrollState(state: ScrollState) {
if (!isScrollState(state)) {
return console.error("Invalid scroll state", state);
}
window.history.replaceState(
{
...(window.history.state ?? {}),
restoreScroll: state,
},
"",
);
}
/**
* Resolve a target
*/
export function resolveTarget(target: Target | null): Element | null {
if (!target) return null;
if (target === window || isRootElement(target)) {
return document.scrollingElement ?? document.documentElement;
}
return target instanceof Element ? target : null;
}
/**
* Check if two objects contain equal values
*/
export function deepEqual(a: any, b: any): boolean {
if (a === b) return true;
if (
typeof a !== "object" ||
typeof b !== "object" ||
a == null ||
b == null
) {
return false;
}
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (const key of keysA) {
if (!keysB.includes(key)) return false;
if (!deepEqual(a[key], b[key])) return false;
}
return true;
}