add entrance transition

This commit is contained in:
Timi
2026-08-24 16:16:43 +08:00
parent 2efce6de11
commit 05aad89706
54 changed files with 874 additions and 694 deletions
+105
View File
@@ -0,0 +1,105 @@
import type { ObjectDirective } from "vue";
const ENTRANCE_DURATION = 400;
const ACTIVE_CLASS = "entrance-fade-up-enter-active";
const FROM_CLASS = "entrance-fade-up-enter-from";
const TO_CLASS = "entrance-fade-up-enter-to";
const STATE_KEY = Symbol("entrance-transition-state");
type EntranceTransitionValue = number | string | { delay?: number | string } | undefined;
interface EntranceTransitionState {
frameId?: number;
timerId?: number;
delay: number;
}
type EntranceTransitionElement = HTMLElement & {
[STATE_KEY]?: EntranceTransitionState;
};
function getDelay(value: EntranceTransitionValue): number {
const rawDelay = typeof value === "object" && value !== null ? value.delay : value;
const delay = Number(rawDelay ?? 0);
return Number.isFinite(delay) ? Math.max(0, delay) : 0;
}
function setDelay(element: EntranceTransitionElement, delay: number): void {
element.style.setProperty("--entrance-delay", `${delay}ms`);
}
function cleanup(element: EntranceTransitionElement): void {
const state = element[STATE_KEY];
if (!state) {
return;
}
if (state.frameId !== undefined) {
window.cancelAnimationFrame(state.frameId);
}
if (state.timerId !== undefined) {
window.clearTimeout(state.timerId);
}
element.classList.remove(ACTIVE_CLASS, FROM_CLASS, TO_CLASS);
element.style.removeProperty("--entrance-delay");
delete element[STATE_KEY];
}
const vEntranceTransition: ObjectDirective<HTMLElement, EntranceTransitionValue> = {
beforeMount(element, binding) {
if (!(element instanceof HTMLElement)) {
return;
}
const target = element as EntranceTransitionElement;
const delay = getDelay(binding.value);
target[STATE_KEY] = { delay };
setDelay(target, delay);
target.classList.add(ACTIVE_CLASS, FROM_CLASS);
},
mounted(element) {
if (!(element instanceof HTMLElement)) {
return;
}
const target = element as EntranceTransitionElement;
const state = target[STATE_KEY];
if (!state) {
return;
}
state.frameId = window.requestAnimationFrame(() => {
state.frameId = window.requestAnimationFrame(() => {
state.frameId = undefined;
target.classList.remove(FROM_CLASS);
target.classList.add(TO_CLASS);
state.timerId = window.setTimeout(() => cleanup(target), ENTRANCE_DURATION + state.delay);
});
});
},
updated(element, binding) {
if (!(element instanceof HTMLElement) || binding.value === binding.oldValue) {
return;
}
const target = element as EntranceTransitionElement;
const state = target[STATE_KEY];
if (!state) {
return;
}
state.delay = getDelay(binding.value);
setDelay(target, state.delay);
},
beforeUnmount(element) {
if (element instanceof HTMLElement) {
cleanup(element as EntranceTransitionElement);
}
}
};
export default vEntranceTransition;