Skip to content

Commit

Permalink
fast forward animations by swap time
Browse files Browse the repository at this point in the history
  • Loading branch information
martrapp committed Sep 7, 2024
1 parent e4528d4 commit 1f87c9b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/large-mangos-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vtbag/element-crossing': patch
---

Animation playback time now does a fast forward to take swap time into account
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,6 @@ export type Spec = {
};
export type ElementSpec = {
id: string;
timestamp: number;
specs: Spec[];
};
34 changes: 20 additions & 14 deletions src/vanilla.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ElementSpec, Spec } from './types';

const DEBUG = false;
const DEBUG = true;

const crossing = top!.__vtbag?.elementCrossing;
init();
Expand Down Expand Up @@ -29,13 +29,16 @@ function pageSwap() {
}
}

function pageReveal() {
function pageReveal(event: Event) {
let values;
if (self.crossingStorage) {
values = self.crossingStorage.getItem('@vtbag/element-crossing') ?? [];
let storage;
if (storage = self.crossingStorage) {
values = storage.getItem('@vtbag/element-crossing') ?? [];
} else {
values = JSON.parse(top!.sessionStorage.getItem('@vtbag/element-crossing') ?? '[]');
storage = top!.sessionStorage;
values = JSON.parse(storage.getItem('@vtbag/element-crossing') ?? '[]');
}
!("viewTransition" in event && event.viewTransition) && storage.removeItem('@vtbag/element-crossing');
restore(values);
}

Expand Down Expand Up @@ -162,20 +165,20 @@ function elementSpec(element: HTMLElement) {
}
});
if (!id) console.error('[crossing]', 'missing id in', element);
else return { id, specs };
else return { id, timestamp: new Date().getTime(), specs };
}

function restore(values: ElementSpec[]) {
DEBUG && console.log('[crossing]', 'restore', values);
values.forEach((elementSpec: ElementSpec) => {
let element = document.querySelector<HTMLElement>(
'#' +
elementSpec.id +
",[data-vtbag-x*='#" +
elementSpec.id +
"'],[data-vtbag-x*='id:" +
elementSpec.id +
"']"
elementSpec.id +
",[data-vtbag-x*='#" +
elementSpec.id +
"'],[data-vtbag-x*='id:" +
elementSpec.id +
"']"
);
if (element) {
elementSpec.specs.forEach((s) => {
Expand Down Expand Up @@ -216,8 +219,11 @@ function restore(values: ElementSpec[]) {
element
);
}
animations.forEach((a) => (a.currentTime = ~~(s.value ?? '0')));
element!.setAttribute(s.key, s.value ?? '');
animations.forEach(
(a) =>
(a.currentTime =
~~(s.value ?? '0') + (new Date().getTime() - elementSpec.timestamp))
);
break;
case 'elem':
const crossing = top?.__vtbag?.elementCrossing;
Expand Down

0 comments on commit 1f87c9b

Please sign in to comment.