Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sidebar.motion.ts

249 lines8.7 KB

1const motionTiming = { duration: 150, easing: "ease-out" };
2const rowTravel = (height: number) => Math.min(height, 40);
3// Fades are the expensive part: every removed row gets a deep clone and every
4// clone and entering row gets its own animation, and the layout reads in
5// between force synchronous reflows.
6const MAX_FADED_ROWS_PER_UPDATE = 40;
7​
8type RowPosition = { top: number; left: number; width: number; height: number };
9​
10function progress(animation: Animation) {
11 return animation.playState === "finished"
12 ? 1
13 : (animation.effect?.getComputedTiming().progress ?? 0);
15​
16/** The list must be
17 * positioned so every direct child's offsetTop has the same origin. */
18export function createSidebarListMotion(parent: HTMLUListElement) {
19 let positions: Map<HTMLElement, RowPosition> | null = null;
20 let disposed = false;
21 const reducedMotion = parent.ownerDocument.defaultView?.matchMedia(
22 "(prefers-reduced-motion: reduce)",
23 );
24 const running = new Map<HTMLElement, { animation: Animation; offset: number }>();
25 const entering = new Map<HTMLElement, { animation: Animation; travel: number }>();
26 const exiting = new Map<HTMLElement, Animation>();
27 let released: Map<HTMLElement, number> | null = null;
28​
29 const remainingOffset = (node: HTMLElement) => {
30 const current = running.get(node);
31 const run = current ? current.offset * (1 - progress(current.animation)) : 0;
32 const entry = entering.get(node);
33 const enter = entry ? entry.travel * (1 - progress(entry.animation)) : 0;
34 return run + enter;
35 };
36 const clearFades = () => {
37 for (const entry of entering.values()) entry.animation.cancel();
38 for (const animation of exiting.values()) animation.cancel();
39 for (const node of exiting.keys()) node.remove();
40 entering.clear();
41 exiting.clear();
42 };
43 const fadeOut = (node: HTMLElement, position: RowPosition, travel: number) => {
44 if (position.height === 0) return;
45 const clone = node.cloneNode(true) as HTMLElement;
46 for (const element of [clone, ...clone.querySelectorAll("*")]) {
47 for (const attribute of Array.from(element.attributes)) {
48 if (
49 (attribute.name === "id" && element.namespaceURI !== "http://www.w3.org/2000/svg") ||
50 attribute.name === "data-thread-item" ||
51 attribute.name === "data-thread-selection-safe" ||
52 attribute.name === "data-testid"
53 ) {
54 element.removeAttribute(attribute.name);
55 }
56 }
57 }
58 clone.setAttribute("aria-hidden", "true");
59 clone.inert = true;
60 Object.assign(clone.style, {
61 position: "absolute",
62 top: `${position.top + remainingOffset(node)}px`,
63 left: `${position.left}px`,
64 width: `${position.width}px`,
65 height: `${position.height}px`,
66 margin: "0",
67 boxSizing: "border-box",
68 contentVisibility: "visible",
69 transform: "none",
70 transition: "none",
71 pointerEvents: "none",
72 });
73 parent.append(clone);
74 const entry = entering.get(node);
75 const entryProgress = entry ? progress(entry.animation) : 1;
76 const animation = clone.animate(
77 [
78 { opacity: entryProgress, transform: "translateY(0px)" },
79 { opacity: 0, transform: `translateY(${travel}px)` },
80 ],
81 motionTiming,
82 );
83 exiting.set(clone, animation);
84 animation.addEventListener(
85 "finish",
86 () => {
87 clone.remove();
88 exiting.delete(clone);
89 },
90 { once: true },
91 );
92 };
93​
94 const cancel = (node: HTMLElement) => {
95 running.get(node)?.animation.cancel();
96 running.delete(node);
97 };
98 const suspend = () => {
99 for (const node of running.keys()) cancel(node);
100 clearFades();
101 positions = null;
102 released = null;
103 };
104 const move = (node: HTMLElement, offset: number) => {
105 cancel(node);
106 const entry = entering.get(node);
107 if (entry) entry.travel = 0;
108 if (offset === 0 && !entry) return;
109 const animation = node.animate(
110 [{ transform: `translateY(${offset}px)` }, { transform: "translateY(0px)" }],
111 motionTiming,
112 );
113 running.set(node, { animation, offset });
114 animation.addEventListener(
115 "finish",
116 () => {
117 if (running.get(node)?.animation === animation) running.delete(node);
118 },
119 { once: true },
120 );
121 };
122​
123 return {
124 update(animate: boolean) {
125 if (disposed) return;
126 const next = new Map(
127 Array.from(parent.children)
128 .filter((node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node))
129 .map((node) => [
130 node,
131 {
132 top: node.offsetTop,
133 left: node.offsetLeft,
134 width: node.offsetWidth,
135 height: node.offsetHeight,
136 },
137 ]),
138 );
139 let fadeCount = 0;
140 if (positions !== null) {
141 for (const [node, position] of positions) {
142 if (!next.has(node) && position.height > 0) fadeCount++;
143 }
144 for (const [node, position] of next) {
145 if (!positions.has(node) && position.height > 0) fadeCount++;
146 }
147 }
148 const shouldAnimate =
149 animate &&
150 positions !== null &&
151 !reducedMotion?.matches &&
152 fadeCount <= MAX_FADED_ROWS_PER_UPDATE;
153 const movedDelta = new Map<HTMLElement, number>();
154 const nextOrder = [...next.keys()];
155 const oldOrder = positions === null ? [] : [...positions.keys()];
156 const ridingDelta = (
157 order: readonly HTMLElement[],
158 index: number,
159 retained: (node: HTMLElement) => boolean,
160 ) => {
161 for (let cursor = index - 1; cursor >= 0; cursor--) {
162 const node = order[cursor]!;
163 const delta = movedDelta.get(node);
164 if (delta !== undefined) return delta;
165 if (retained(node)) return remainingOffset(node);
166 }
167 return undefined;
168 };
169 if (!shouldAnimate) clearFades();
170 else {
171 for (const [node, position] of next) {
172 const previousTop = positions!.get(node)?.top;
173 if (previousTop === undefined || previousTop === position.top) continue;
174 movedDelta.set(node, previousTop + remainingOffset(node) - position.top);
175 }
176 for (const [node, position] of positions!) {
177 if (next.has(node)) continue;
178 const delta = ridingDelta(oldOrder, oldOrder.indexOf(node), (n) => next.has(n));
179 fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta);
180 }
181 }
182 for (const [node, entry] of entering) {
183 if (!next.has(node)) {
184 entry.animation.cancel();
185 entering.delete(node);
186 }
187 }
188 for (const node of running.keys()) {
189 if (!shouldAnimate || !next.has(node)) cancel(node);
190 }
191 if (shouldAnimate) {
192 for (const [index, node] of nextOrder.entries()) {
193 const position = next.get(node)!;
194 const previousTop = positions!.get(node)?.top;
195 if (previousTop === undefined) {
196 if (position.height > 0) {
197 const delta = ridingDelta(nextOrder, index, (n) => positions!.has(n));
198 const travel = delta === undefined ? -rowTravel(position.height) : delta;
199 const animation = node.animate(
200 [
201 { opacity: 0, transform: `translateY(${travel}px)` },
202 { opacity: 1, transform: "translateY(0px)" },
203 ],
204 motionTiming,
205 );
206 entering.set(node, { animation, travel });
207 animation.addEventListener(
208 "finish",
209 () => {
210 if (entering.get(node)?.animation === animation) entering.delete(node);
211 },
212 { once: true },
213 );
214 }
215 continue;
216 }
217 const delta = movedDelta.get(node);
218 // Computed progress includes the effect's easing. Only our own
219 // translate is carried forward; dnd-kit's transforms are never read.
220 if (delta !== undefined) move(node, delta);
221 }
222 }
223 if (released !== null) {
224 if (!reducedMotion?.matches) {
225 for (const [node, position] of next) {
226 const top = released.get(node);
227 if (top !== undefined) move(node, top - position.top);
228 }
229 }
230 released = null;
231 }
232 positions = next;
233 },
234 release() {
235 suspend();
236 const origin = parent.getBoundingClientRect().top;
237 released = new Map(
238 Array.from(parent.children)
239 .filter((node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node))
240 .map((node) => [node, node.getBoundingClientRect().top - origin]),
241 );
242 },
243 suspend,
244 dispose() {
245 suspend();
246 disposed = true;
247 },
248 };