Repository Public
1// « La porte de la maison s'ouvre » — la transition signature d'Immo-Ka.2//3// Mise en scène (niveau signature, 1 360 ms effacement compris) :4// 1. la MAISON du logo émerge de la photographie choisie (façade complète :5// toit aux avant-toits retroussés, cheminée, murs, porte rouge) et vient6// au centre ; la page d'origine s'efface derrière elle ;7// 2. on s'approche de la façade : la porte grandit jusqu'à occuper l'écran ;8// la béquille s'abaisse, le battant pivote lentement sur ses charnières ;9// la lumière chaude de l'intérieur sort, se répand au sol, et la vraie10// photo de la propriété se dévoile par l'embrasure ;11// 3. on entre : l'embrasure s'élargit et devient la photo principale de la12// fiche ; la façade et le chambranle s'effacent ;13// 4. la scène disparaît dès que la photo de la fiche est affichée.14//15// Règles : jamais bloquante (un clic, Échap ou un retour l'interrompt), la16// navigation n'attend pas la fin de l'animation, les données et le code de la17// fiche sont préchargés dès le clic, et rien ne se joue sur un lien direct.1819import { useEffect } from "react";20import { useNavigate, type NavigateFunction } from "react-router";21import { useQueryClient, type QueryClient } from "@tanstack/react-query";22import { fetchListing, thumb } from "@/lib/api";23import {24 DOOR_TIMINGS,25 DoorEngine,26 EASE_DOOR,27 EASE_OUT,28 resolveLevel,29 revealStart,30 slowFactor,31 type MotionLevel,32} from "./engine";33import { HOUSE, HOUSE_PATHS } from "./geometry";3435export type DoorContext = "card" | "marker" | "favorite";3637interface OpenArgs {38 uid: string;39 /** photographie affichée sur l'élément d'origine (la même image sera révélée) */40 image: string | null;41 /** élément d'où part la porte (photo de la carte, aperçu, pastille) */42 from: Element | null;43 context?: DoorContext;44 /** niveau imposé (laboratoire) ; sinon choisi selon le contexte et la fréquence */45 level?: MotionLevel;46}4748let nav: NavigateFunction | null = null;49let qc: QueryClient | null = null;50let active: { finish: () => void } | null = null;5152/** Chemin d'une propriété : la seule source de vérité. */53export const listingPath = (uid: string) => `/propriete/${encodeURIComponent(uid)}`;5455/** Précharge le code et les données de la fiche (au survol ou au clic). */56export function preloadListing(uid: string) {57 void import("@/pages/Property");58 void qc?.prefetchQuery({ queryKey: ["listing", uid], queryFn: () => fetchListing(uid), staleTime: 3e5 });59}6061/** Rectangle d'arrivée : la photo principale de la fiche, sinon une estimation. */62function targetRect(): DOMRect {63 const el = document.querySelector<HTMLElement>("[data-door-target]");64 if (el) {65 const r = el.getBoundingClientRect();66 if (r.width > 40 && r.height > 40) return r;67 }68 const vw = window.innerWidth;69 const vh = window.innerHeight;70 if (vw < 1024) return new DOMRect(0, 64, vw, Math.round(vw * 0.75));71 const w = Math.min(1280, vw) - 2 * Math.max(16, Math.min(40, vw * 0.04));72 return new DOMRect((vw - w) / 2, 132, w * 0.5, Math.min(560, vh * 0.62));73}7475/** On avance encore un peu en franchissant le seuil. */76const PUSH = 1.06;77/** Rapport largeur / hauteur de l'embrasure du symbole (18 × 30). */78const DOOR_RATIO = (HOUSE.opening.right - HOUSE.opening.left) / (HOUSE.opening.bottom - HOUSE.opening.top);7980/** La façade : le symbole dessiné en élévation (grille 64), à l'échelle de la porte. */81function facadeSvg(): string {82 const clins: string[] = [];83 for (let y = 13.2; y < 57.5; y += 2.05) clins.push(`M0 ${y.toFixed(2)}H64`);84 return `<svg class="ikd-facade" viewBox="0 0 64 64" aria-hidden="true">85<defs><clipPath id="ikd-clip-mur"><path d="${HOUSE_PATHS.silhouette}"/></clipPath></defs>86<path class="ikd-f-ground" d="M-60 58.15H124"/>87<path class="ikd-f-wall" d="${HOUSE_PATHS.silhouette}"/>88<path class="ikd-f-siding" clip-path="url(#ikd-clip-mur)" d="${clins.join("")}"/>89<path class="ikd-f-under" clip-path="url(#ikd-clip-mur)" d="M9 31.5 32 10.2 55 31.5V32.9L32 11.6 9 32.9Z"/>90<path class="ikd-f-roof" d="${HOUSE_PATHS.roof}"/>91<path class="ikd-f-roof" d="${HOUSE_PATHS.chimney}M40.9 8.700h6.700v1.300h-6.700Z"/>92<rect class="ikd-f-trim" x="29.3" y="17.8" width="5.4" height="6.8" rx="0.25"/>93<rect class="ikd-f-glass" x="29.95" y="18.45" width="4.1" height="5.5"/>94<path class="ikd-f-mullion" d="M32 18.450v5.500M29.95 21.200h4.1"/>95</svg>`;96}9798const wait = (ms: number) => new Promise<void>((r) => window.setTimeout(r, ms));99const frame = () => new Promise<void>((r) => requestAnimationFrame(() => r()));100const div = (className: string) => {101 const d = document.createElement("div");102 d.className = className;103 return d;104};105106/** Ouvre une propriété en jouant la transition adaptée. */107export function openListing({ uid, image, from, context = "card", level }: OpenArgs) {108 const to = listingPath(uid);109 if (!nav) {110 window.location.assign(to);111 return;112 }113 active?.finish();114 preloadListing(uid);115116 const lvl = level ?? resolveLevel(context);117 const src = from?.getBoundingClientRect();118 const visible = src && src.width > 24 && src.height > 24 && src.bottom > 0 && src.top < window.innerHeight;119 if (lvl === "none" || !visible) {120 nav(to, { state: { door: lvl } });121 return;122 }123124 const k = slowFactor();125 const base = DOOR_TIMINGS[lvl];126 const t = { ...base, emerge: base.emerge * k, swingDelay: base.swingDelay * k, swing: base.swing * k, reveal: base.reveal * k, settle: base.settle * k };127 const withDoor = lvl === "signature" || lvl === "standard";128 const navigate = nav;129 let navigated = false;130 let done = false;131 const go = () => {132 if (navigated) return;133 navigated = true;134 navigate(to, { state: { door: lvl } });135 };136137 // --- géométrie ----------------------------------------------------------------138 const vw = window.innerWidth;139 const vh = window.innerHeight;140 // la porte, au centre de l'écran, aux proportions de l'embrasure du symbole141 const H = Math.round(Math.max(280, Math.min(560, vh * 0.62)));142 const W = Math.round(H * DOOR_RATIO);143 const door = withDoor144 ? { left: Math.round((vw - W) / 2), top: Math.round((vh - H) / 2 - vh * 0.015), width: W, height: H }145 : { left: src.left, top: src.top, width: src.width, height: src.height };146 // une unité de la grille 64 du symbole, en pixels : la façade entoure la porte147 const u = W / (HOUSE.opening.right - HOUSE.opening.left);148 const houseSize = u * HOUSE.box;149 // échelle « maison entière » : toute la façade tient à l'écran (sur mobile, les avant-toits peuvent dépasser)150 const z0 = Math.max(0.42, Math.min(0.7, (vh * 0.8) / houseSize, (vw * 0.9) / houseSize));151 // à cette échelle, la maison (et non la porte) est centrée : la porte est 10 unités sous le centre du symbole152 const lift = 10 * u * z0;153 // au départ, la maison tient dans la photo d'origine154 const s0 = withDoor ? Math.min(1, (src.height * 0.92) / (houseSize * z0)) : 1;155 const dx = src.left + src.width / 2 - (door.left + door.width / 2);156 const dy = src.top + src.height / 2 - (door.top + door.height / 2);157 const ft = Math.max(8, Math.round(W * 0.05));158159 // --- scène ------------------------------------------------------------------------160 const root = div("ikd-root");161 root.setAttribute("aria-hidden", "true");162 const veil = div("ikd-veil");163 const rig = div("ikd-rig");164 rig.style.cssText = `left:${door.left}px;top:${door.top}px;width:${door.width}px;height:${door.height}px;`;165 const stage = div("ikd-stage");166 stage.style.setProperty("--ft", withDoor ? `${ft}px` : "0px");167 stage.style.setProperty("--u", `${u.toFixed(3)}px`);168 const opening = div("ikd-opening");169 if (image) {170 const img = document.createElement("img");171 img.decoding = "sync";172 img.referrerPolicy = "no-referrer";173 // l'image déjà affichée par l'élément d'origine (en cache, quelle que soit sa largeur) ; sinon la miniature174 const shown = from?.querySelector<HTMLImageElement>("img")?.currentSrc;175 img.src = shown || thumb(image, 480);176 img.onerror = () => {177 if (img.src !== image) img.src = image;178 };179 opening.appendChild(img);180 }181 stage.appendChild(opening);182183 let panel: HTMLDivElement | null = null;184 let frameEl: HTMLDivElement | null = null;185 let lever: HTMLDivElement | null = null;186 const fading: HTMLElement[] = [];187 if (withDoor) {188 const spill = div("ikd-spill");189 opening.append(div("ikd-bloom"), div("ikd-depth"));190 panel = div("ikd-panel");191 const face = div("ikd-face");192 lever = div("ikd-lever");193 face.append(div("ikd-mold ikd-mold--top"), div("ikd-mold ikd-mold--bottom"), div("ikd-rose"), lever);194 panel.append(face, div("ikd-edge"));195 const clip = div("ikd-clip");196 // perspective proportionnelle à la porte : le battant fuit nettement en pivotant197 clip.style.perspective = `${Math.round(W * 2.5)}px`;198 clip.appendChild(panel);199 frameEl = div("ikd-frame");200 const sill = div("ikd-sill");201 stage.insertAdjacentHTML("afterbegin", facadeSvg());202 const facade = stage.firstElementChild as HTMLElement;203 facade.after(sill, spill);204 stage.append(clip, frameEl);205 fading.push(facade, spill, frameEl, sill, clip);206 }207 rig.appendChild(stage);208 root.append(veil, rig);209 document.body.appendChild(root);210211 const engine = new DoorEngine("closed", 0);212 engine.attach(stage);213 const anims: Animation[] = [];214 const run = (el: Element, kf: Keyframe[], duration: number, easing = EASE_OUT, delay = 0) => {215 const a = el.animate(kf, { duration: Math.max(1, duration), easing, fill: "both", delay });216 anims.push(a);217 return a.finished.catch(() => undefined);218 };219220 const cleanup = () => {221 if (done) return;222 done = true;223 window.clearTimeout(guard);224 window.removeEventListener("pointerdown", interrupt, true);225 window.removeEventListener("keydown", onKey, true);226 window.removeEventListener("popstate", interrupt);227 anims.forEach((a) => a.cancel());228 engine.attach(null);229 root.remove();230 if (active === handleRef) active = null;231 };232 // interruption : on arrive tout de suite sur la fiche, sans état intermédiaire233 function interrupt() {234 if (done) return;235 engine.interrupt();236 go();237 cleanup();238 }239 function onKey(e: KeyboardEvent) {240 if (e.key === "Escape" || e.key === "Enter" || e.key === "Tab") interrupt();241 }242 const handleRef = { finish: interrupt };243 active = handleRef;244 window.addEventListener("pointerdown", interrupt, true);245 window.addEventListener("keydown", onKey, true);246 window.addEventListener("popstate", interrupt);247 const morphAt = revealStart(t);248 // délai de garde : quoi qu'il arrive, la scène disparaît249 const guard = window.setTimeout(interrupt, morphAt + t.reveal + t.settle + 900 * k);250251 void (async () => {252 try {253 // retour tactile immédiat sur l'élément d'origine254 from?.animate([{ transform: "scale(1)" }, { transform: "scale(0.975)" }, { transform: "scale(1)" }], { duration: 180, easing: EASE_OUT });255256 if (withDoor && panel && lever) {257 // 1 — la maison émerge de la photographie et vient au centre258 const approachAt = t.emerge * 0.5;259 const approachFor = morphAt - approachAt;260 stage.style.transform = `translate(0px, ${lift}px) scale(${z0})`;261 void run(veil, [{ opacity: 0 }, { opacity: 1 }], t.emerge * 1.15, "ease-out");262 void run(263 rig,264 [265 { transform: `translate(${dx}px, ${dy}px) scale(${s0})`, opacity: 0 },266 { opacity: 1, offset: 0.28 },267 { transform: "translate(0px, 0px) scale(1)", opacity: 1 },268 ],269 t.emerge,270 "cubic-bezier(0.22, 0.9, 0.24, 1)",271 );272 // 2 — on s'approche de la façade, d'un seul mouvement continu jusqu'au seuil273 void run(274 stage,275 [276 { transform: `translate(0px, ${lift}px) scale(${z0})` },277 { transform: `translate(0px, 0px) scale(${PUSH})` },278 ],279 approachFor,280 "cubic-bezier(0.5, 0, 0.22, 1)",281 approachAt,282 );283 // la béquille s'abaisse, puis le battant pivote avec son poids284 void run(lever, [{ transform: "rotate(0deg)" }, { transform: "rotate(-26deg)" }, { transform: "rotate(0deg)" }], 200 * k, "ease-in-out", Math.max(0, t.swingDelay - 80 * k));285 await wait(t.swingDelay);286 if (done) return;287 void engine.open(t.swing, t.angle);288 // 3 — le passage du seuil commence juste avant la fin du pivotement289 await wait(Math.max(0, morphAt - t.swingDelay));290 if (done) return;291 } else if (lvl === "compact") {292 await run(veil, [{ opacity: 0 }, { opacity: 1 }], 70 * k);293 }294 if (done) return;295296 // la navigation part maintenant : la fiche se monte sous la scène297 veil.style.opacity = "1";298 engine.reveal();299 go();300 engine.navigate();301 await frame();302 await frame();303 if (done) return;304 const dst = targetRect();305306 if (lvl === "reduced") {307 rig.style.display = "none";308 await run(veil, [{ opacity: 0 }, { opacity: 1 }], 60);309 } else {310 // l'embrasure s'élargit jusqu'à la photo de la fiche ; l'encadrement s'efface311 for (const el of fading) void run(el, [{ opacity: 1 }, { opacity: 0 }], t.reveal * 0.55, "ease-out");312 if (withDoor) {313 void run(opening, [{ inset: `${ft}px ${ft}px 0px ${ft}px` }, { inset: "0px 0px 0px 0px" }], t.reveal * 0.7, EASE_DOOR);314 }315 if (withDoor) void run(stage, [{ transform: `scale(${PUSH})` }, { transform: "scale(1)" }], t.reveal * 0.8, EASE_DOOR);316 await run(317 rig,318 [319 { left: `${door.left}px`, top: `${door.top}px`, width: `${door.width}px`, height: `${door.height}px` },320 { left: `${dst.left}px`, top: `${dst.top}px`, width: `${dst.width}px`, height: `${dst.height}px` },321 ],322 t.reveal,323 "cubic-bezier(0.6, 0, 0.16, 1)",324 );325 }326 if (done) return;327328 // 4 — la scène ne s'efface que lorsque la photo de la fiche est affichée329 // (aucun flash gris), sans jamais attendre plus de 700 ms330 root.style.pointerEvents = "none";331 const until = performance.now() + 700;332 while (!done && performance.now() < until) {333 const img = document.querySelector<HTMLImageElement>("[data-door-target] img");334 if (img?.complete && img.naturalWidth > 0) break;335 await wait(30);336 }337 if (done) return;338 await run(root, [{ opacity: 1 }, { opacity: 0 }], t.settle, "ease-out");339 engine.complete();340 } finally {341 go();342 cleanup();343 }344 })();345}346347/** À monter une fois dans l'ossature : donne au moteur l'accès au routeur. */348export function ImmokaDoorTransition() {349 const navigate = useNavigate();350 const client = useQueryClient();351 useEffect(() => {352 nav = navigate;353 qc = client;354 return () => {355 nav = null;356 qc = null;357 };358 }, [navigate, client]);359 return null;360}361362/**363 * Gestionnaire de clic pour un lien de propriété : laisse le navigateur gérer364 * les ouvertures dans un nouvel onglet, sinon joue la transition.365 */366export function doorClick(367 e: React.MouseEvent,368 args: Omit<OpenArgs, "from"> & { from?: Element | null },369) {370 if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;371 e.preventDefault();372 const from =373 args.from ?? (e.currentTarget as Element).querySelector("[data-door-source]") ?? (e.currentTarget as Element);374 openListing({ ...args, from });375}376