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

Sidebar.motion.ts

294 lines10.9 KB

1const motionTiming = { duration: 150, easing: "ease-out" };
2const rowTravel = (height: number) => Math.min(height, 40);
3// Fades clone removed rows and animate clones and entries; intervening layout reads force reflows.
4const MAX_FADED_ROWS_PER_UPDATE = 40;
5​
6type RowPosition = { top: number; left: number; width: number; height: number };
7​
8function progress(animation: Animation) {
9 return animation.playState === "finished"
10 ? 1
11 : (animation.effect?.getComputedTiming().progress ?? 0);
13​
14/** Position the list so all direct children's offsetTop share an origin. */
15export function createSidebarListMotion(parent: HTMLUListElement) {
16 let positions: Map<HTMLElement, RowPosition> | null = null;
17 let disposed = false;
18 const reducedMotion = parent.ownerDocument.defaultView?.matchMedia(
19 "(prefers-reduced-motion: reduce)",
20 );
21 const running = new Map<HTMLElement, { animation: Animation; offset: number }>();
22 const entering = new Map<HTMLElement, { animation: Animation; travel: number }>();
23 const exiting = new Map<HTMLElement, Animation>();
24 let released: { tops: Map<HTMLElement, number>; scrollTop: number } | null = null;
25 const scroller = parent.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
26 const originalPaddingBottom = parent.style.paddingBottom;
27 let releasePadding = 0;
28 let scrollTop = scroller?.scrollTop ?? 0;
29 const setReleasePadding = (padding: number) => {
30 releasePadding = padding;
31 parent.style.paddingBottom = padding > 0 ? `${padding}px` : originalPaddingBottom;
32 };
33 const trimReleasePadding = () => {
34 if (!scroller || releasePadding === 0) return;
35 const spare = scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop;
36 if (spare > 0) setReleasePadding(Math.max(0, releasePadding - spare));
37 };
38 const trackScroll = () => {
39 const nextTop = scroller?.scrollTop ?? 0;
40 if (nextTop < scrollTop) trimReleasePadding();
41 scrollTop = nextTop;
42 };
43 scroller?.addEventListener("scroll", trackScroll, { passive: true });
44​
45 const remainingOffset = (node: HTMLElement) => {
46 const current = running.get(node);
47 const run = current ? current.offset * (1 - progress(current.animation)) : 0;
48 const entry = entering.get(node);
49 const enter = entry ? entry.travel * (1 - progress(entry.animation)) : 0;
50 return run + enter;
51 };
52 const clearFades = () => {
53 for (const entry of entering.values()) entry.animation.cancel();
54 for (const animation of exiting.values()) animation.cancel();
55 for (const node of exiting.keys()) node.remove();
56 entering.clear();
57 exiting.clear();
58 };
59 const fadeOut = (node: HTMLElement, position: RowPosition, travel: number, shift: number) => {
60 if (position.height === 0) return;
61 const clone = node.cloneNode(true) as HTMLElement;
62 for (const element of [clone, ...clone.querySelectorAll("*")]) {
63 for (const attribute of Array.from(element.attributes)) {
64 if (
65 (attribute.name === "id" && element.namespaceURI !== "http://www.w3.org/2000/svg") ||
66 attribute.name === "data-thread-item" ||
67 attribute.name === "data-thread-selection-safe" ||
68 attribute.name === "data-testid"
69 ) {
70 element.removeAttribute(attribute.name);
71 }
72 }
73 }
74 clone.setAttribute("aria-hidden", "true");
75 clone.inert = true;
76 Object.assign(clone.style, {
77 position: "absolute",
78 top: `${position.top + remainingOffset(node) + shift}px`,
79 left: `${position.left}px`,
80 width: `${position.width}px`,
81 height: `${position.height}px`,
82 margin: "0",
83 boxSizing: "border-box",
84 contentVisibility: "visible",
85 transform: "none",
86 transition: "none",
87 pointerEvents: "none",
88 });
89 parent.append(clone);
90 const entry = entering.get(node);
91 const entryProgress = entry ? progress(entry.animation) : 1;
92 const animation = clone.animate(
93 [
94 { opacity: entryProgress, transform: "translateY(0px)" },
95 { opacity: 0, transform: `translateY(${travel}px)` },
96 ],
97 motionTiming,
98 );
99 exiting.set(clone, animation);
100 animation.addEventListener(
101 "finish",
102 () => {
103 clone.remove();
104 exiting.delete(clone);
105 },
106 { once: true },
107 );
108 };
109​
110 const cancel = (node: HTMLElement) => {
111 running.get(node)?.animation.cancel();
112 running.delete(node);
113 };
114 const suspend = () => {
115 for (const node of running.keys()) cancel(node);
116 clearFades();
117 positions = null;
118 released = null;
119 };
120 const move = (node: HTMLElement, offset: number) => {
121 cancel(node);
122 const entry = entering.get(node);
123 if (entry) entry.travel = 0;
124 if (offset === 0 && !entry) return;
125 const animation = node.animate(
126 [{ transform: `translateY(${offset}px)` }, { transform: "translateY(0px)" }],
127 motionTiming,
128 );
129 running.set(node, { animation, offset });
130 animation.addEventListener(
131 "finish",
132 () => {
133 if (running.get(node)?.animation === animation) running.delete(node);
134 },
135 { once: true },
136 );
137 };
138​
139 return {
140 update(animate: boolean) {
141 if (disposed) return;
142 // A hidden list (the closed narrow sheet stays mounted) reports zero
143 // offsets, which would make the first pass after it opens animate every row.
144 if (parent.getClientRects().length === 0) {
145 suspend();
146 return;
147 }
148 if (released !== null && scroller !== null) {
149 // Removing drag-only overflow can clamp the viewport. Keep only the space the release
150 // position needs; scrolling back up removes it without moving any visible row.
151 const missing = released.scrollTop - (scroller.scrollHeight - scroller.clientHeight);
152 if (missing > 0) setReleasePadding(releasePadding + missing);
153 scroller.scrollTop = released.scrollTop;
154 } else trimReleasePadding();
155 const next = new Map(
156 Array.from(parent.children)
157 .filter((node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node))
158 .map((node) => [
159 node,
160 {
161 top: node.offsetTop,
162 left: node.offsetLeft,
163 width: node.offsetWidth,
164 height: node.offsetHeight,
165 },
166 ]),
167 );
168 let fadeCount = 0;
169 if (positions !== null) {
170 for (const [node, position] of positions) {
171 if (!next.has(node) && position.height > 0) fadeCount++;
172 }
173 for (const [node, position] of next) {
174 if (!positions.has(node) && position.height > 0) fadeCount++;
175 }
176 }
177 const shouldAnimate =
178 animate &&
179 positions !== null &&
180 !reducedMotion?.matches &&
181 fadeCount <= MAX_FADED_ROWS_PER_UPDATE;
182 // A removal near the bottom shrinks the list and the browser clamps scrollTop, moving
183 // every row on screen; offsets include that shift so those rows slide instead of jump.
184 let shift = 0;
185 if (scroller !== null) {
186 const max = scroller.scrollHeight - scroller.clientHeight;
187 if (scrollTop > max && scroller.scrollTop >= max - 1)
188 shift = scroller.scrollTop - scrollTop;
189 }
190 const movedDelta = new Map<HTMLElement, number>();
191 const nextOrder = [...next.keys()];
192 const oldOrder = positions === null ? [] : [...positions.keys()];
193 const ridingDelta = (
194 order: readonly HTMLElement[],
195 index: number,
196 retained: (node: HTMLElement) => boolean,
197 ) => {
198 for (let cursor = index - 1; cursor >= 0; cursor--) {
199 const node = order[cursor]!;
200 const delta = movedDelta.get(node);
201 if (delta !== undefined) return delta;
202 if (retained(node)) return remainingOffset(node);
203 }
204 return undefined;
205 };
206 if (!shouldAnimate) clearFades();
207 else {
208 for (const [node, position] of next) {
209 const previousTop = positions!.get(node)?.top;
210 if (previousTop === undefined || previousTop + shift === position.top) continue;
211 movedDelta.set(node, previousTop + remainingOffset(node) - position.top + shift);
212 }
213 for (const [node, position] of positions!) {
214 if (next.has(node)) continue;
215 const delta = ridingDelta(oldOrder, oldOrder.indexOf(node), (n) => next.has(n));
216 fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta, shift);
217 }
218 }
219 for (const [node, entry] of entering) {
220 if (!next.has(node)) {
221 entry.animation.cancel();
222 entering.delete(node);
223 }
224 }
225 for (const node of running.keys()) {
226 if (!shouldAnimate || !next.has(node)) cancel(node);
227 }
228 if (shouldAnimate) {
229 for (const [index, node] of nextOrder.entries()) {
230 const position = next.get(node)!;
231 const previousTop = positions!.get(node)?.top;
232 if (previousTop === undefined) {
233 if (position.height > 0) {
234 const delta = ridingDelta(nextOrder, index, (n) => positions!.has(n));
235 const travel = delta === undefined ? -rowTravel(position.height) : delta;
236 const animation = node.animate(
237 [
238 { opacity: 0, transform: `translateY(${travel}px)` },
239 { opacity: 1, transform: "translateY(0px)" },
240 ],
241 motionTiming,
242 );
243 entering.set(node, { animation, travel });
244 animation.addEventListener(
245 "finish",
246 () => {
247 if (entering.get(node)?.animation === animation) entering.delete(node);
248 },
249 { once: true },
250 );
251 }
252 continue;
253 }
254 const delta = movedDelta.get(node);
255 // Computed progress includes easing; carry forward only our translation, never dnd-kit's
256 // transforms.
257 if (delta !== undefined) move(node, delta);
258 }
259 }
260 if (released !== null) {
261 if (!reducedMotion?.matches) {
262 for (const [node, position] of next) {
263 const top = released.tops.get(node);
264 if (top !== undefined) move(node, top - position.top);
265 }
266 }
267 released = null;
268 }
269 positions = next;
270 if (scroller !== null) scrollTop = scroller.scrollTop;
271 },
272 release() {
273 suspend();
274 const origin = parent.getBoundingClientRect().top;
275 released = {
276 tops: new Map(
277 Array.from(parent.children)
278 .filter(
279 (node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node),
280 )
281 .map((node) => [node, node.getBoundingClientRect().top - origin]),
282 ),
283 scrollTop: scroller?.scrollTop ?? 0,
284 };
285 },
286 suspend,
287 dispose() {
288 suspend();
289 scroller?.removeEventListener("scroll", trackScroll);
290 parent.style.paddingBottom = originalPaddingBottom;
291 disposed = true;
292 },
293 };