Create professional demos and 3D mockups in seconds, directly in your browser
feat: add 3D iPhone Duo device mockups
Efrain Chiri Ninac5037645c755
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsxindex b8c974d..397f687 100644--- a/app/[locale]/(editor)/editor/page.tsx+++ b/app/[locale]/(editor)/editor/page.tsx@@ -1,5 +1,6 @@"use client";+import { EDITOR_WITHOUT_AUTH } from "@/app/config/editor";import { useState, useRef, useEffect, useCallback, lazy, Suspense, useMemo } from "react";import { Icon } from "@iconify/react";import { motion, AnimatePresence } from "framer-motion";@@ -1036,7 +1037,7 @@ export default function Editor() {const router = useRouter();const handleExport = useCallback((quality: ExportQuality) => {- if (!authUser) {+ if (!EDITOR_WITHOUT_AUTH && !authUser) {savePendingExport(quality);router.replace({pathname: "/login",diff --git a/app/[locale]/(editor)/layout.tsx b/app/[locale]/(editor)/layout.tsxindex a04fc05..7a28c39 100644--- a/app/[locale]/(editor)/layout.tsx+++ b/app/[locale]/(editor)/layout.tsx@@ -1,3 +1,4 @@+import { EDITOR_WITHOUT_AUTH } from "@/app/config/editor";import { AuthProvider } from "@/app/contexts/useAuth";import RecordingOverlay from "../../components/ui/RecordingOverlay";import { Mockup3dProvider } from "@/app/contexts/Mockup3dContext";@@ -5,7 +6,7 @@ import { RecordingProvider } from "@/app/contexts/RecordingContext";export default async function EditorLayout({ children }: { children: React.ReactNode }) {return (- <AuthProvider>+ <AuthProvider disabled={EDITOR_WITHOUT_AUTH}><RecordingProvider><Mockup3dProvider><div id="editor-root" className="min-h-screen bg-background">diff --git a/app/[locale]/layout.tsx b/app/[locale]/layout.tsxindex 960d1ad..7a78502 100644--- a/app/[locale]/layout.tsx+++ b/app/[locale]/layout.tsx@@ -18,22 +18,6 @@ import {} from "@/lib/seo";import "../globals.css";-const THEME_INLINE_SCRIPT = `-(function () {- try {- var get = function (name) {- var m = document.cookie.match(new RegExp("(?:^|;\\s*)" + name + "=([^;]*)"));- return m ? decodeURIComponent(m[1]) : null;- };- var pref = get("openvid_theme_pref") || get("openvid_theme") || "system";- var dark = pref === "system"- ? window.matchMedia("(prefers-color-scheme: dark)").matches- : pref === "dark";- document.documentElement.classList.toggle("dark", dark);- } catch (e) {}-})();-`;-const inter = Inter({subsets: ["latin"],variable: "--font-inter",@@ -186,11 +170,7 @@ export default async function LocaleLayout({return (<html lang={locale || defaultLocale} suppressHydrationWarning><head>- <Script- id="openvid-theme"- strategy="beforeInteractive"- dangerouslySetInnerHTML={{ __html: THEME_INLINE_SCRIPT }}- />+ <Script id="openvid-theme" src="/openvid-theme.js" strategy="beforeInteractive" /></head><bodyclassName={`${inter.variable} ${roboto.variable} ${inter.className} antialiased`}diff --git a/app/components/ui/editor/DuoMotionCard.tsx b/app/components/ui/editor/DuoMotionCard.tsxnew file mode 100644index 0000000..79f8e33--- /dev/null+++ b/app/components/ui/editor/DuoMotionCard.tsx@@ -0,0 +1,48 @@+"use client";++import Image from "next/image";+import { Icon } from "@iconify/react";+import { useTranslations } from "next-intl";+import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";++export function DuoMotionCard() {+ const t = useTranslations("motionMenu");+ const device = useMockup3dContext();+ const active = device.imagePhoneActive && device.imagePhoneDevice === "iphone-duo";++ function addDuo() {+ device.setImagePhoneDevice("iphone-duo");+ device.setImagePhoneActive(true);+ device.setImagePhoneX(0);+ device.setImagePhoneY(0);+ device.setImagePhoneScale(0.7);+ device.setImagePhoneRotX(6);+ device.setImagePhoneRotY(-12);+ device.setImagePhoneRotZ(0);+ device.setImagePhoneOpening(1);+ device.setImagePhonePresetId("custom");+ device.setViewer3DAutoRotate(false);+ }++ return (+ <div className="overflow-hidden rounded-2xl border border-border bg-card">+ <div className="relative h-36 overflow-hidden bg-[#101116]">+ <Image width={800} height={480} src="/images/mockups-3d/iphone-duo/preview.webp" alt="iPhone Duo" className="h-full w-full object-cover" />+ <span className="absolute left-3 top-3 rounded-full border border-white/15 bg-black/35 px-2 py-1 text-[9px] font-medium uppercase tracking-widest text-white/80">3D · iPhone Duo</span>+ </div>+ <div className="space-y-3 p-3">+ <div>+ <p className="text-xs font-medium text-foreground">{t("duoEyebrow")}</p>+ <p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">{t(active ? "duoHint" : "duoDescription")}</p>+ </div>+ {active ? (+ <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground"><Icon icon="lucide:check" width={13} />{t("duoActive")}</div>+ ) : (+ <button type="button" onClick={addDuo} className="flex w-full items-center justify-center gap-2 rounded-lg bg-foreground px-3 py-2 text-xs font-medium text-background transition-opacity hover:opacity-80 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">+ <Icon icon="lucide:plus" width={14} />{t("duoAdd")}+ </button>+ )}+ </div>+ </div>+ );+}diff --git a/app/components/ui/editor/EditorTopBar.tsx b/app/components/ui/editor/EditorTopBar.tsxindex cfef003..b3bfa21 100644--- a/app/components/ui/editor/EditorTopBar.tsx+++ b/app/components/ui/editor/EditorTopBar.tsx@@ -1,5 +1,6 @@"use client";+import { EDITOR_WITHOUT_AUTH } from "@/app/config/editor";import { Icon } from "@iconify/react";import { ExportDropdown } from "../ExportDropdown";import { ExportImageDropdown } from "../ExportImageDropdown";@@ -142,7 +143,7 @@ export function EditorTopBar({</TooltipAction></div>- {loading ? (+ {EDITOR_WITHOUT_AUTH ? null : loading ? (<div className="flex items-center gap-2 pl-3 border-l border-border ml-1"><div className="hidden sm:flex flex-col items-end gap-1.5"><div className="w-16 h-2.5 bg-muted rounded-sm animate-pulse"></div>diff --git a/app/components/ui/editor/Mockup3dMenu.tsx b/app/components/ui/editor/Mockup3dMenu.tsxindex 2e6ff39..898476a 100644--- a/app/components/ui/editor/Mockup3dMenu.tsx+++ b/app/components/ui/editor/Mockup3dMenu.tsx@@ -240,7 +240,13 @@ export function Mockup3dMenu({setImagePhoneRotY(defaultRotY);setImagePhoneRotZ(0);- if (imagePhoneDevice === "laptop") {+ if (imagePhoneDevice === "iphone-duo") {+ setImagePhoneScale(0.7);+ setImagePhoneRotX(6);+ setImagePhoneRotY(-12);+ setImagePhoneOpening(1);+ setImagePhoneShadow(0.4);+ } else if (imagePhoneDevice === "laptop") {setImagePhoneOpening(1);setImagePhoneShadow(0.7);} else if (imagePhoneDevice === "double_iphone_13_pro") {@@ -351,10 +357,10 @@ export function Mockup3dMenu({{t("modelProperties") || "Propiedades del Modelo"}</span>- {isLaptop && (+ {(isLaptop || imagePhoneDevice === "iphone-duo") && (<SliderControl- icon="material-symbols:laptop-chromebook-outline"- label={t("laptopOpening")}+ icon={imagePhoneDevice === "iphone-duo" ? "lucide:book-open" : "material-symbols:laptop-chromebook-outline"}+ label={t(imagePhoneDevice === "iphone-duo" ? "foldOpening" : "laptopOpening")}value={Math.round(imagePhoneOpening * 100)}min={0}max={100}diff --git a/app/components/ui/editor/MockupMenu.tsx b/app/components/ui/editor/MockupMenu.tsxindex 144f152..2e4c43b 100644--- a/app/components/ui/editor/MockupMenu.tsx+++ b/app/components/ui/editor/MockupMenu.tsx@@ -147,7 +147,14 @@ export function MockupMenu({setImagePhoneY(0);setImagePhoneScale(0.9);- if (id === "iphone-13-pro-max") {+ if (id === "iphone-duo") {+ setImagePhoneRotX(6);+ setImagePhoneRotY(-12);+ setImagePhoneRotZ(0);+ setImagePhoneOpening(1);+ setImagePhoneScale(0.7);+ setImagePhonePresetId("custom");+ } else if (id === "iphone-13-pro-max") {setImagePhoneRotX(-58.23);setImagePhoneRotY(-29.82);setImagePhoneScale(1.6);@@ -171,7 +178,7 @@ export function MockupMenu({}, [imagePhoneDevice, imagePhoneRotX, imagePhoneRotY, setImagePhoneDevice,setImagePhoneX, setImagePhoneY, setImagePhoneScale, setImagePhoneRotX,- setImagePhoneRotY, setImagePhoneOpening, setImagePhoneActive, mockupId, onMockupChange+ setImagePhoneRotY, setImagePhoneRotZ, setImagePhonePresetId, setImagePhoneOpening, setImagePhoneActive, mockupId, onMockupChange]);const handleRemoveAll = useCallback(() => {diff --git a/app/components/ui/editor/MotionGlobalConfig.tsx b/app/components/ui/editor/MotionGlobalConfig.tsxindex 519097c..fe7837b 100644--- a/app/components/ui/editor/MotionGlobalConfig.tsx+++ b/app/components/ui/editor/MotionGlobalConfig.tsx@@ -1,8 +1,10 @@"use client";import { Icon } from "@iconify/react";import { useTranslations } from "next-intl";-import { MOCKUP_MOTION_PRESETS, type MockupMotionPresetId, type MockupMotionMode, MockupMotionFragment, getMotionPresetMode } from "@/lib/mockup-motion";+import { MOCKUP_MOTION_PRESETS, type MockupMotionPresetId, type MockupMotionMode, MockupMotionFragment } from "@/lib/mockup-motion";import { MotionPresetIcon, MotionPresetIconStyles } from "../../../../components/ui/MotionPresetIcon";+import { supports3DMotionPreset } from "@/lib/mockup-motion-3d";+import { useMockup3dContext } from "@/app/contexts/Mockup3dContext";import { Toggle } from "@/components/ui/toggle";interface MotionGlobalConfigProps {@@ -24,6 +26,7 @@ export function MotionGlobalConfig({onToggleGlobalMotion,}: MotionGlobalConfigProps) {const t = useTranslations("motionMenu");+ const { imagePhoneDevice } = useMockup3dContext();// Derive which motion mode is active: 3D takes priority when a 3D mockup// is present, otherwise fall back to 2D. When neither is present we show@@ -58,7 +61,7 @@ export function MotionGlobalConfig({);}- const presetsForMode = MOCKUP_MOTION_PRESETS.filter((p) => p.mode === activeMode);+ const presetsForMode = MOCKUP_MOTION_PRESETS.filter((p) => p.mode === activeMode && supports3DMotionPreset(p.id, imagePhoneDevice));return (<div className="p-4 flex flex-col gap-4 h-full relative min-h-0">diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsxindex 2211be2..34cf517 100644--- a/app/components/ui/editor/VideoCanvas.tsx+++ b/app/components/ui/editor/VideoCanvas.tsx@@ -1,5 +1,6 @@"use client";+import { supports3DMotionPreset } from "@/lib/mockup-motion-3d";import { useRef, useEffect, useImperativeHandle, useMemo, useState, useCallback, memo, lazy, Suspense } from "react";import type * as THREE from "three";import type { VideoCanvasHandle, VideoCanvasProps, VideoThumbnail } from "@/types";@@ -246,7 +247,7 @@ function VideoCanvasInner({// Root THREE.Group ref for applying 3D motion during export rendering.const imagePhoneRootRef = useRef<THREE.Group | null>(null);const imagePhoneApiRef = useRef<{- renderAt: (w: number, h: number) => void;+ renderAt: (w: number, h: number, motion?: Mockup3DMotionTransform) => void;restorePreview: () => void;hasBuiltInShadow?: boolean;getVisualSize?: () => { width: number; height: number; offsetY?: number } | null; // ← offsetY@@ -762,16 +763,16 @@ function VideoCanvasInner({);// 3D motion: sample fragments that belong to 3D presets only.- const hasMockup3DMotion = imagePhoneActive && mockupMotionFragments.some((f) => MOTION_PRESET_3D_IDS.has(f.presetId));+ const hasMockup3DMotion = imagePhoneActive && mockupMotionFragments.some((f) => MOTION_PRESET_3D_IDS.has(f.presetId) && supports3DMotionPreset(f.presetId, imagePhoneDevice));const mockup3DMotionPreview = useMemo<Mockup3DMotionTransform>(() => {if (!hasMockup3DMotion) return REST_MOCKUP_3D_MOTION;- const fragments3D = mockupMotionFragments.filter((f) => MOTION_PRESET_3D_IDS.has(f.presetId));+ const fragments3D = mockupMotionFragments.filter((f) => MOTION_PRESET_3D_IDS.has(f.presetId) && supports3DMotionPreset(f.presetId, imagePhoneDevice));if (fragments3D.length === 0) return REST_MOCKUP_3D_MOTION;return sampleCombined3DMotion(fragments3D as unknown as Parameters<typeof sampleCombined3DMotion>[0], currentTime);},- [hasMockup3DMotion, mockupMotionFragments, currentTime]+ [hasMockup3DMotion, mockupMotionFragments, currentTime, imagePhoneDevice]);// Effective aspect ratio for the "none" mockup contain-box, adjusted for@@ -1372,7 +1373,7 @@ function VideoCanvasInner({// 3D motion sampled at this export frame's time.const motion3DForFrame: Mockup3DMotionTransform = hasMockup3DMotion? (() => {- const fragments3D = mockupMotionFragments.filter((f) => MOTION_PRESET_3D_IDS.has(f.presetId));+ const fragments3D = mockupMotionFragments.filter((f) => MOTION_PRESET_3D_IDS.has(f.presetId) && supports3DMotionPreset(f.presetId, imagePhoneDevice));return fragments3D.length > 0? sampleCombined3DMotion(fragments3D as unknown as Parameters<typeof sampleCombined3DMotion>[0], frameTime): REST_MOCKUP_3D_MOTION;@@ -1553,7 +1554,7 @@ function VideoCanvasInner({motionRoot.position.z = basePz + m3d.posZ;}if (highQuality) {- imagePhoneApiRef.current?.renderAt(drawW, drawH);+ imagePhoneApiRef.current?.renderAt(drawW, drawH, m3d);drawMaskedImage(ctx, phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH, effectivePhoneMaskConfig, maskCompositeCanvasRef);imagePhoneApiRef.current?.restorePreview();} else {@@ -2548,7 +2549,7 @@ function VideoCanvasInner({rootRef={imagePhoneRootRef}imageUrl={imageUrl}videoElement={activeVideoElement ?? undefined}- openingProgress={imagePhoneDevice === "laptop" ? imagePhoneOpening : undefined}+ openingProgress={imagePhoneOpening}modelUrl={imagePhoneDevice === "phone" || imagePhoneDevice === "iphone" ? imagePhoneModelUrl : undefined}imageMaskConfig={effectivePhoneMaskConfig}cropArea={cropArea}diff --git a/app/components/ui/editor/mockups-3d/Device3DBoundary.tsx b/app/components/ui/editor/mockups-3d/Device3DBoundary.tsxnew file mode 100644index 0000000..a32ff36--- /dev/null+++ b/app/components/ui/editor/mockups-3d/Device3DBoundary.tsx@@ -0,0 +1,28 @@+"use client";++import { Component, type ReactNode } from "react";+import { useTranslations } from "next-intl";+import { useGLTF } from "@react-three/drei";++class Boundary extends Component<{ children: ReactNode; fallback: (retry: () => void) => ReactNode }, { failed: boolean }> {+ state = { failed: false };+ static getDerivedStateFromError() { return { failed: true }; }+ render() {+ return this.state.failed ? this.props.fallback(() => {+ useGLTF.clear("/models/iphone-duo.glb");+ this.setState({ failed: false });+ }) : this.props.children;+ }+}++export function Device3DBoundary({ children }: { children: ReactNode }) {+ const t = useTranslations("mockupMenu");+ return (+ <Boundary fallback={(retry) => (+ <div role="alert" className="flex h-full min-h-40 flex-col items-center justify-center gap-3 rounded-xl border border-border bg-card p-6 text-center text-sm text-foreground">+ <p>{t("deviceLoadError")}</p>+ <button type="button" onClick={retry} className="rounded-lg border border-border px-4 py-2 hover:bg-muted">{t("retry")}</button>+ </div>+ )}>{children}</Boundary>+ );+}diff --git a/app/components/ui/editor/mockups-3d/IPhoneDuo3DViewer.tsx b/app/components/ui/editor/mockups-3d/IPhoneDuo3DViewer.tsxnew file mode 100644index 0000000..e8f7f5c--- /dev/null+++ b/app/components/ui/editor/mockups-3d/IPhoneDuo3DViewer.tsx@@ -0,0 +1,235 @@+"use client";++import { useFrame, useThree } from "@react-three/fiber";+import { Environment, OrbitControls, PerspectiveCamera, useGLTF } from "@react-three/drei";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";+import * as THREE from "three";+import type { OrbitControls as OrbitControlsType } from "three-stdlib";+import { createScreenMaterial } from "@/lib/iphone-duo/screen-material";+import { foldChoreography } from "@/lib/iphone-duo/fold-choreography";+import { applyTextureCover } from "@/lib/phone3d.utils";+import { HDRI_FILES, sphericalCameraPos } from "@/lib/viewer-controls3d";+import type { Mockup3DStageProps } from "./Mockup3DStage";+import type { Phone3DApi } from "@/lib/phone3d-composite-draw.utils";+import type { Mockup3DMotionTransform } from "@/lib/mockup-motion-3d";++const DEG = Math.PI / 180;+const MODEL_SCALE = 0.04;+const CAMERA_RADIUS = 1.7;++export function IPhoneDuoScene({+ imageUrl, videoElement, cropArea, openingProgress = 1,+ initialRotationX = 6, initialRotationY = -12, initialRotationZ = 0,+ zoom = 1, autoRotate = false, rotationSpeed = 3.5,+ environment = "studio", glow = 1.2, shadowIntensity = 0,+ motionTransform, onRotationChange, onApi, onLoaded, rootRef, cameraRef,+}: Mockup3DStageProps & {+ rootRef: React.MutableRefObject<THREE.Group | null>;+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;+ onLoaded?: () => void;+}) {+ const { scene: source } = useGLTF("/models/iphone-duo.glb");+ const { gl, scene, invalidate } = useThree();+ const orbitRef = useRef<OrbitControlsType | null>(null);+ const textureRef = useRef<THREE.Texture[]>([]);+ const callbacks = useRef({ onLoaded, onApi });+ const pose = useRef({ openingProgress, motionTransform });+ useLayoutEffect(() => {+ callbacks.current = { onLoaded, onApi };+ pose.current = { openingProgress, motionTransform };+ });++ const model = useMemo(() => {+ const body = source.clone(true);+ const hinge = body.getObjectByName("folding-half");+ if (!hinge) throw new Error("iPhone Duo: missing folding-half");+ const inner = createScreenMaterial(false);+ const cover = createScreenMaterial(true);+ const owned = new Set<THREE.Material>([inner, cover]);+ body.traverse((object) => {+ if (!(object instanceof THREE.Mesh)) return;+ const replace = (material: THREE.Material) => {+ if (material.name === "inner-screen") return inner;+ if (material.name === "cover-screen") return cover;+ const clone = material.clone();+ owned.add(clone);+ return clone;+ };+ object.material = Array.isArray(object.material)+ ? object.material.map(replace) : replace(object.material);+ });+ return { body, hinge, inner, cover, owned };+ }, [source]);++ useEffect(() => () => {+ // GLTF geometry/textures belong to useGLTF's cache; only dispose our materials.+ model.owned.forEach((material) => material.dispose());+ }, [model]);++ const modelRef = useRef(model);+ useLayoutEffect(() => { modelRef.current = model; }, [model]);++ const applyOpening = useCallback((motion?: Mockup3DMotionTransform) => {+ const model = modelRef.current;+ const p = THREE.MathUtils.clamp(motion?.openingProgress ?? pose.current.openingProgress, 0, 1);+ const fold = foldChoreography(p);+ model.hinge.rotation.y = fold.angle;+ model.body.position.x = -4.12 * (1 - Math.max(0, Math.cos(fold.angle)));+ model.inner.uniforms.defocus.value = fold.innerDefocus;+ model.cover.uniforms.focusEdge.value = fold.coverFocusEdge;+ for (const material of [model.inner, model.cover]) {+ material.uniforms.progress.value = p;+ material.uniforms.blur.value = 28;+ material.uniforms.parallax.value = 1;+ }+ // Preserve the source shader's model-space screen projection after scaling/rotation.+ model.body.updateWorldMatrix(true, true);+ for (const material of [model.inner, model.cover]) {+ material.uniforms.bodyInverse.value.copy(model.body.matrixWorld).invert();+ }+ }, []);++ useFrame(() => applyOpening(pose.current.motionTransform));+ useEffect(() => { invalidate(); }, [openingProgress, motionTransform, invalidate]);++ useEffect(() => {+ let cancelled = false;+ const textures: THREE.Texture[] = [];+ const materials = [model.inner, model.cover];+ const targets = [[15.798708, 11.10349], [7.739354, 11.251288]];+ const updateScreen = (texture: THREE.Texture, index: number, width: number, height: number) => {+ const material = materials[index];+ const transform = new THREE.Texture();+ transform.flipY = texture.flipY;+ applyTextureCover(transform, width, height, targets[index][0], targets[index][1], imageUrl || videoElement ? cropArea : null);+ transform.updateMatrix();+ material.uniforms.screenTransform.value.copy(transform.matrix);+ transform.dispose();+ material.uniforms.screenMap.value = texture;+ material.uniforms.isVideo.value = texture instanceof THREE.VideoTexture ? 1 : 0;+ // Bind valid samplers for unused optional layers as well.+ material.uniforms.overlayMap.value = texture;+ material.uniforms.revealMap.value = texture;+ material.uniforms.resolution.value.set(width, height);+ material.needsUpdate = true;+ invalidate();+ };+ const setup = (texture: THREE.Texture) => {+ texture.colorSpace = THREE.SRGBColorSpace;+ texture.anisotropy = Math.min(8, gl.capabilities.getMaxAnisotropy());+ textures.push(texture);+ return texture;+ };+ const updateVideo = () => {+ if (cancelled || !videoElement || !videoElement.videoWidth) return;+ textures.forEach((texture, index) => updateScreen(texture, index, videoElement.videoWidth, videoElement.videoHeight));+ callbacks.current.onLoaded?.();+ };+ if (videoElement) {+ // Independent UV transforms for the wide inner screen and narrow cover.+ for (let index = 0; index < 2; index++) setup(new THREE.VideoTexture(videoElement));+ textureRef.current = textures;+ updateVideo();+ videoElement.addEventListener("loadeddata", updateVideo);+ videoElement.addEventListener("resize", updateVideo);+ } else {+ const urls = imageUrl ? [imageUrl, imageUrl] : [+ "/images/mockups-3d/iphone-duo/apple-desert.avif",+ "/images/mockups-3d/iphone-duo/apple-desert-cover.avif",+ ];+ Promise.all(urls.map(async (url, index) => {+ const texture = await new THREE.TextureLoader().loadAsync(url);+ if (cancelled) { texture.dispose(); return; }+ setup(texture);+ updateScreen(texture, index, texture.image.width, texture.image.height);+ })).then(() => {+ if (!cancelled) callbacks.current.onLoaded?.();+ }).catch((error) => {+ if (!cancelled) {+ console.error("iPhone Duo screen could not load", error);+ // The device remains usable even when an external image is unavailable.+ callbacks.current.onLoaded?.();+ }+ });+ textureRef.current = textures;+ }+ return () => {+ cancelled = true;+ videoElement?.removeEventListener("loadeddata", updateVideo);+ videoElement?.removeEventListener("resize", updateVideo);+ textureRef.current = [];+ textures.forEach((texture) => texture.dispose());+ };+ }, [model, imageUrl, videoElement, cropArea, gl, invalidate]);++ useEffect(() => {+ const cam = cameraRef.current;+ if (!cam) return;+ cam.position.set(...sphericalCameraPos(initialRotationX, initialRotationY, CAMERA_RADIUS / zoom));+ cam.lookAt(0, 0, 0);+ orbitRef.current?.update();+ invalidate();+ }, [initialRotationX, initialRotationY, zoom, cameraRef, invalidate]);++ useEffect(() => {+ const callback = callbacks.current.onApi;+ let previewPixelRatio = gl.getPixelRatio();+ const api = {+ renderAt(width: number, height: number, motion?: Mockup3DMotionTransform) {+ const cam = cameraRef.current;+ if (!cam) return;+ previewPixelRatio = gl.getPixelRatio();+ const ratio = Math.min(2, gl.capabilities.maxTextureSize / Math.max(1, width, height));+ const w = Math.max(1, Math.round(width));+ const h = Math.max(1, Math.round(height));+ cam.aspect = w / h;+ cam.updateProjectionMatrix();+ gl.setPixelRatio(ratio);+ gl.setSize(w, h, false);+ applyOpening(motion ?? pose.current.motionTransform);+ textureRef.current.forEach((texture) => {+ if (texture instanceof THREE.VideoTexture) texture.needsUpdate = true;+ });+ gl.render(scene, cam);+ },+ restorePreview() {+ const cam = cameraRef.current;+ if (!cam) return;+ const w = Math.max(1, gl.domElement.clientWidth);+ const h = Math.max(1, gl.domElement.clientHeight);+ cam.aspect = w / h;+ cam.updateProjectionMatrix();+ gl.setPixelRatio(previewPixelRatio);+ gl.setSize(w, h, false);+ applyOpening(pose.current.motionTransform);+ invalidate();+ },+ hasBuiltInShadow: false,+ getVisualSize: () => ({ width: 1100, height: 900, offsetY: -(shadowIntensity ** 2 * 60 * 0.8) / 2 }),+ } satisfies Phone3DApi;+ callback?.(api);+ return () => callback?.(null);+ }, [gl, scene, cameraRef, applyOpening, shadowIntensity, invalidate]);++ return (+ <>+ <PerspectiveCamera ref={cameraRef} makeDefault fov={30} near={0.01} far={100}+ position={sphericalCameraPos(initialRotationX, initialRotationY, CAMERA_RADIUS / zoom)} />+ <OrbitControls ref={orbitRef} enableZoom={false} enablePan={false} enableDamping+ autoRotate={autoRotate} autoRotateSpeed={rotationSpeed}+ onEnd={() => {+ const orbit = orbitRef.current;+ if (orbit) onRotationChange?.(90 - orbit.getPolarAngle() / DEG, orbit.getAzimuthalAngle() / DEG);+ }} />+ <Environment files={HDRI_FILES[environment]} environmentIntensity={glow} />+ <ambientLight intensity={1.5} />+ <directionalLight position={[-0.8, 1.2, 2]} intensity={3} />+ <directionalLight position={[1, -0.5, 1]} intensity={0.7} color="#b7ccff" />+ <group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>+ <group scale={MODEL_SCALE}>+ <primitive object={model.body} dispose={null} />+ </group>+ </group>+ </>+ );+}diff --git a/app/components/ui/editor/mockups-3d/Mockup3DFrame.tsx b/app/components/ui/editor/mockups-3d/Mockup3DFrame.tsxindex c3341ed..ac68ff3 100644--- a/app/components/ui/editor/mockups-3d/Mockup3DFrame.tsx+++ b/app/components/ui/editor/mockups-3d/Mockup3DFrame.tsx@@ -24,6 +24,11 @@ interface DeviceLayout {}const DEVICE_LAYOUT: Record<ImageDeviceId, DeviceLayout> = {+ "iphone-duo": {+ width: 1100, height: 900,+ overlay: { kind: "fixed", pointerEvents: "auto" },+ maskInset: 0,+ },"iphone-13-pro-max": {width: 480, height: 1000,marginTop: "100px", marginRight: "0",diff --git a/app/components/ui/editor/mockups-3d/Mockup3DStage.tsx b/app/components/ui/editor/mockups-3d/Mockup3DStage.tsxindex 8916e0d..9302d1d 100644--- a/app/components/ui/editor/mockups-3d/Mockup3DStage.tsx+++ b/app/components/ui/editor/mockups-3d/Mockup3DStage.tsx@@ -1,4 +1,6 @@"use client";+import { Device3DBoundary } from "./Device3DBoundary";+import { IPhoneDuoScene } from "./IPhoneDuo3DViewer";import { Canvas } from "@react-three/fiber";import { Suspense, useCallback, useEffect, useRef, useState } from "react";import * as THREE from "three";@@ -29,7 +31,7 @@ export interface Mockup3DStageProps {initialRotationX?: number;initialRotationY?: number;initialRotationZ?: number;- openingProgress?: number; // solo laptop+ openingProgress?: number; // laptop / foldable phonemodelUrl?: string; // solo devices genéricos (phone/iphone)onRotationChange?: (rx: number, ry: number) => void;onMount?: (canvas: HTMLCanvasElement) => void;@@ -136,7 +138,11 @@ function Motion3DApplicator({return null;}-export function Mockup3DStage({ device, rootRef: externalRootRef, cameraRef: externalCameraRef, onLoadedChange, ...props }: StageProps) {+export function Mockup3DStage(props: StageProps) {+ return <Device3DBoundary key={props.device}><StageContent {...props} /></Device3DBoundary>;+}++function StageContent({ device, rootRef: externalRootRef, cameraRef: externalCameraRef, onLoadedChange, ...props }: StageProps) {const internalRootRef = useRef<THREE.Group | null>(null);const internalCameraRef = useRef<THREE.PerspectiveCamera | null>(null);const rootRef = externalRootRef ?? internalRootRef;@@ -174,9 +180,9 @@ export function Mockup3DStage({ device, rootRef: externalRootRef, cameraRef: extpowerPreference: "high-performance",failIfMajorPerformanceCaveat: false,}}- dpr={3}- frameloop={props.videoElement || hasMotion ? "always" : "demand"}- resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}+ dpr={device === "iphone-duo" ? [1, 2] : 3}+ frameloop={props.videoElement || props.autoRotate || hasMotion ? "always" : "demand"}+ resize={{ scroll: false, offsetSize: device === "iphone-duo", debounce: { scroll: 0, resize: 0 } }}onCreated={({ gl, scene }) => {gl.outputColorSpace = THREE.SRGBColorSpace;gl.toneMapping = THREE.NeutralToneMapping;@@ -196,6 +202,9 @@ export function Mockup3DStage({ device, rootRef: externalRootRef, cameraRef: ext{device === "iphone-17-pro-max" && (<IPhone17ProMaxScene {...props} rootRef={rootRef} cameraRef={cameraRef} onLoaded={markLoaded} />)}+ {device === "iphone-duo" && (+ <IPhoneDuoScene {...props} rootRef={rootRef} cameraRef={cameraRef} onLoaded={markLoaded} />+ )}{device === "laptop" && (<LaptopScene {...props} rootRef={rootRef} cameraRef={cameraRef} onLoaded={markLoaded} />)}diff --git a/app/config/editor.ts b/app/config/editor.tsnew file mode 100644index 0000000..7f1488f--- /dev/null+++ b/app/config/editor.ts@@ -0,0 +1,2 @@+// Temporary editor development mode. Set to false to restore authentication.+export const EDITOR_WITHOUT_AUTH = true;diff --git a/app/contexts/Mockup3dContext.tsx b/app/contexts/Mockup3dContext.tsxindex f80bd65..488349e 100644--- a/app/contexts/Mockup3dContext.tsx+++ b/app/contexts/Mockup3dContext.tsx@@ -1,5 +1,6 @@"use client";+import type { ImageDeviceId } from "@/types/mockup.types";import { createContext, useContext, useState, useEffect, useRef, useMemo, type ReactNode } from "react";import { DEVICE_VIEWER_DEFAULTS } from "@/lib/phone3d.utils";import type { EnvironmentPreset } from "@/lib/viewer-controls3d";@@ -37,12 +38,12 @@ interface Mockup3dState {/** Perspective (px) for the 3D transform on the phone mockup */imagePhonePerspective: number;setImagePhonePerspective: (v: number) => void;- /** Which 3D device model is active: the default phone JSON, iPhone 15 Pro Max, or single macOS laptop */- imagePhoneDevice: 'phone' | 'iphone' | 'iphone-13-pro-max' | 'iphone-17-pro-max' | 'double_iphone_13_pro' | 'laptop' | 'ipad_mini_6_2021';- setImagePhoneDevice: (d: 'phone' | 'iphone' | 'iphone-13-pro-max' | 'iphone-17-pro-max' | 'double_iphone_13_pro' | 'laptop' | 'ipad_mini_6_2021') => void;+ /** Active device from the shared 3D catalogue */+ imagePhoneDevice: ImageDeviceId;+ setImagePhoneDevice: (d: ImageDeviceId) => void;imagePhonePresetId: string;setImagePhonePresetId: (id: string) => void;- /** Laptop opening animation progress (0 = closed, 1 = fully open) */+ /** Laptop lid or foldable phone opening progress (0 = closed, 1 = fully open) */imagePhoneOpening: number;setImagePhoneOpening: (v: number) => void;/** Drop-shadow intensity for the active device mockup (0 = no shadow, 1 = full) */@@ -78,7 +79,7 @@ export function Mockup3dProvider({ children }: { children: ReactNode }) {const [imagePhoneRotY, setImagePhoneRotY] = useState(0);const [imagePhoneRotZ, setImagePhoneRotZ] = useState(0);const [imagePhonePerspective, setImagePhonePerspective] = useState(600);- const [imagePhoneDevice, setImagePhoneDevice] = useState<'phone' | 'iphone' | 'iphone-13-pro-max' | 'iphone-17-pro-max' | 'double_iphone_13_pro' | 'laptop' | 'ipad_mini_6_2021'>('phone');+ const [imagePhoneDevice, setImagePhoneDevice] = useState<ImageDeviceId>('phone');const [imagePhonePresetId, setImagePhonePresetId] = useState('custom');const [imagePhoneOpening, setImagePhoneOpening] = useState(1);const [imagePhoneShadow, setImagePhoneShadow] = useState(0.6);diff --git a/app/contexts/useAuth.tsx b/app/contexts/useAuth.tsxindex bd134ff..ad58750 100644--- a/app/contexts/useAuth.tsx+++ b/app/contexts/useAuth.tsx@@ -42,7 +42,26 @@ const PROFILE_REFRESH_EVENTS = new Set<AuthChangeEvent>(["PASSWORD_RECOVERY",]);-export function AuthProvider({ children }: { children: React.ReactNode }) {+const guestAuth: AuthContextType = {+ user: null,+ profile: null,+ session: null,+ loading: false,+ signOut: async () => {},+ refreshProfile: async () => {},+};++export function AuthProvider({ children, disabled = false }: {+ children: React.ReactNode;+ disabled?: boolean;+}) {+ if (disabled) {+ return <AuthContext.Provider value={guestAuth}>{children}</AuthContext.Provider>;+ }+ return <SessionAuthProvider>{children}</SessionAuthProvider>;+}++function SessionAuthProvider({ children }: { children: React.ReactNode }) {const [user, setUser] = useState<User | null>(null);const [profile, setProfile] = useState<UserProfile | null>(null);const [session, setSession] = useState<Session | null>(null);diff --git a/components/ui/DeviceCard.tsx b/components/ui/DeviceCard.tsxindex b0fa629..bd9455c 100644--- a/components/ui/DeviceCard.tsx+++ b/components/ui/DeviceCard.tsx@@ -1,3 +1,4 @@+import Image from "next/image";import { useEffect, useRef, useState } from "react";import { Icon } from "@iconify/react";import { IMAGE_DEVICE_TEMPLATES } from "@/types";@@ -61,15 +62,17 @@ export function DeviceCard({: `linear-gradient(135deg, ${tpl.accentColor}10 0%, transparent 70%)`,}}/>- <img+ <Image+ fill+ sizes="160px"src={tpl.posterUrl}alt={tpl.title}draggable={false}className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${- isHovering ? "scale-105 opacity-0" : "scale-100 opacity-100"+ isHovering && videoReady && tpl.videoUrl ? "scale-105 opacity-0" : "scale-100 opacity-100"}`}/>- <video+ {tpl.videoUrl && <videoref={videoRef}src={tpl.videoUrl}poster={tpl.posterUrl}@@ -81,7 +84,7 @@ export function DeviceCard({className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${isHovering && videoReady ? "scale-105 opacity-100" : "scale-100 opacity-0"}`}- />+ />}<divclassName={`absolute inset-0 z-20 bg-black/20 transition-opacity duration-300 ${isHovering ? "opacity-100" : "opacity-0"diff --git a/components/ui/MotionPresetIcon.tsx b/components/ui/MotionPresetIcon.tsxindex dfd3241..3925c2a 100644--- a/components/ui/MotionPresetIcon.tsx+++ b/components/ui/MotionPresetIcon.tsx@@ -47,7 +47,9 @@ export function MotionPresetIcon({<div className="mp-grid pointer-events-none absolute inset-0" /><div className="pointer-events-none absolute inset-0 bg-gradient-to-b from-white/[0.06] to-transparent" /><div className="mp-perspective absolute inset-0 flex items-center justify-center">- <span className={`mp-card mp-card--${presetId}`} />+ {presetId.startsWith("duo-") ? (+ <span className={`mp-duo mp-duo--${presetId}`}><span className="mp-duo-half mp-duo-left" /><span className="mp-duo-half mp-duo-right" /></span>+ ) : <span className={`mp-card mp-card--${presetId}`} />}</div></div>);@@ -56,6 +58,17 @@ export function MotionPresetIcon({export function MotionPresetIconStyles() {return (<style jsx global>{`+ .mp-duo { width: 48%; height: 58%; position: relative; transform-style: preserve-3d; transform: rotateX(10deg) rotateY(-15deg); }+ .mp-duo-half { position: absolute; top: 0; height: 100%; width: 50%; border: 2px solid #a8adba; background: linear-gradient(145deg, #252d59, #b7a1ec 55%, #e9c7ac); box-shadow: inset 0 0 0 2px #15161b, 0 8px 18px #0006; backface-visibility: visible; }+ .mp-duo-left { left: 0; border-radius: 7px 1px 1px 7px; transform-origin: right center; }+ .mp-duo-right { right: 0; border-radius: 1px 7px 7px 1px; }+ .mp-duo--duo-unfold .mp-duo-left { transform: rotateY(145deg); }+ @media (prefers-reduced-motion: no-preference) {+ .group:hover .mp-duo-left, .force-animate .mp-duo-left { animation: mp-duo-open 2.4s ease-in-out infinite alternate; }+ .group:hover .mp-duo--duo-fold .mp-duo-left, .force-animate .mp-duo--duo-fold .mp-duo-left { animation-direction: alternate-reverse; }+ .group:hover .mp-duo--duo-cycle .mp-duo-left, .force-animate .mp-duo--duo-cycle .mp-duo-left { animation-duration: 1.8s; }+ }+ @keyframes mp-duo-open { 0%, 12% { transform: rotateY(175deg); } 85%, 100% { transform: rotateY(0deg); } }.mp-grid {opacity: 0.05;background-image: linear-gradient(diff --git a/eslint.config.mjs b/eslint.config.mjsindex 4ca170d..2eaf4c9 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -18,6 +18,7 @@ const eslintConfig = defineConfig([// Independent backend and desktop projects have their own toolchains."openvid-back/**","openvid-autozoom/**",+ "iphone-duo-main/**",]),]);diff --git a/hooks/useImageProjects.ts b/hooks/useImageProjects.tsindex a62e059..9d0c1ec 100644--- a/hooks/useImageProjects.ts+++ b/hooks/useImageProjects.ts@@ -1,5 +1,6 @@"use client";+import type { ImageDeviceId } from "@/types/mockup.types";import { useState, useCallback, useEffect } from "react";import type { ImageProject, ImageProjectPreview } from "@/types/image-project.types";import {@@ -50,7 +51,7 @@ interface ImageProjectState {imagePhoneRotY: number;imagePhoneRotZ: number;imagePhonePerspective: number;- imagePhoneDevice: 'phone' | 'iphone' | 'iphone-13-pro-max' | 'iphone-17-pro-max' | 'double_iphone_13_pro' | 'laptop' | 'ipad_mini_6_2021';+ imagePhoneDevice: ImageDeviceId;imagePhonePresetId: string;imagePhoneOpening: number;imagePhoneShadow: number;diff --git a/lib/iphone-duo/LICENSE b/lib/iphone-duo/LICENSEnew file mode 100644index 0000000..160c159--- /dev/null+++ b/lib/iphone-duo/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Justin Levine++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/lib/iphone-duo/README.md b/lib/iphone-duo/README.mdnew file mode 100644index 0000000..c933292--- /dev/null+++ b/lib/iphone-duo/README.md@@ -0,0 +1,5 @@+# iPhone Duo integration++Adapted from `iphone-duo-main` by Justin Levine, MIT (see LICENSE). The source project credits Apple for the model and desert wallpapers.++Openvid uses its own React Three Fiber scene and timeline. No DialKit, standalone demo styles, or additional animation dependency is needed. The opening is sampled from the timeline and passed to the same renderer during export.diff --git a/lib/iphone-duo/fold-choreography.ts b/lib/iphone-duo/fold-choreography.tsnew file mode 100644index 0000000..4e6e942--- /dev/null+++ b/lib/iphone-duo/fold-choreography.ts@@ -0,0 +1,11 @@+export const FOLD_DURATION = 2++export function foldChoreography(progress: number) {+ const p = Math.max(0, Math.min(1, progress))+ const hinge = Math.min(1, p / 0.96)+ return {+ angle: (1 - hinge) * Math.PI,+ coverFocusEdge: 1.25 - Math.min(1, p / 0.45) * 1.1,+ innerDefocus: (1 - p) ** 0.65,+ }+}diff --git a/lib/iphone-duo/screen-material.ts b/lib/iphone-duo/screen-material.tsnew file mode 100644index 0000000..6def937--- /dev/null+++ b/lib/iphone-duo/screen-material.ts@@ -0,0 +1,104 @@+// Adapted from iphone-duo by Justin Levine (MIT). See ./LICENSE.+import { Matrix3, Matrix4, ShaderMaterial, Vector2 } from 'three'++export function createScreenMaterial(cover: boolean) {+ return new ShaderMaterial({+ uniforms: { isVideo: { value: 0 }, screenTransform: { value: new Matrix3() }, bodyInverse: { value: new Matrix4() }, screenMap: { value: undefined }, overlayMap: { value: undefined }, hasOverlay: { value: 0 }, revealMap: { value: undefined }, hasReveal: { value: 0 }, resolution: { value: new Vector2(1600, 1200) }, progress: { value: 0 }, focusEdge: { value: cover ? 1.25 : 0.5 }, defocus: { value: 1 }, blur: { value: 28 }, parallax: { value: 1 }, cover: { value: cover ? 1 : 0 } },+ vertexShader: `+ uniform mat4 bodyInverse;+ varying vec2 screenUv;+ varying vec3 displayPosition;+ varying vec3 displayCamera;+ varying vec3 coverStart;+ varying vec3 coverEnd;+ void main() {+ displayPosition = (bodyInverse * modelMatrix * vec4(position, 1.0)).xyz;+ displayCamera = (bodyInverse * vec4(cameraPosition, 1.0)).xyz;+ coverStart = (bodyInverse * modelMatrix * vec4(-0.233961, 0.0, -0.524105, 1.0)).xyz;+ coverEnd = (bodyInverse * modelMatrix * vec4(-7.973315, 0.0, -0.524105, 1.0)).xyz;+ screenUv = uv;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+ }+ `,+ fragmentShader: `+ uniform sampler2D screenMap;+ uniform mat3 screenTransform;+ uniform float isVideo;+ uniform sampler2D overlayMap;+ uniform float hasOverlay;+ uniform sampler2D revealMap;+ uniform float hasReveal;+ uniform float parallax;+ uniform vec2 resolution;+ uniform float progress;+ uniform float focusEdge;+ uniform float defocus;+ uniform float blur;+ uniform float cover;+ varying vec2 screenUv;+ varying vec3 displayPosition;+ varying vec3 displayCamera;+ varying vec3 coverStart;+ varying vec3 coverEnd;+ vec4 sampleLayer(sampler2D layer, vec2 uv, float lod) {+ return mix(texture2D(layer, uv), textureLod(layer, uv, lod), smoothstep(0.0, 1.0, lod));+ }+ vec4 sampleScreen(vec2 uv, float lod) {+ vec2 backgroundUv = clamp((uv - 0.5) * 0.97 + 0.5, vec2(0.001), vec2(0.999));+ vec4 background = sampleLayer(screenMap, (screenTransform * vec3(backgroundUv, 1.0)).xy, lod);+ if (isVideo > 0.5) background = sRGBTransferEOTF(background);+ vec2 revealUv = uv;+ vec4 reveal = sampleLayer(revealMap, clamp(revealUv, vec2(0.001), vec2(0.999)), lod);+ float revealInside = step(0.0, revealUv.x) * step(revealUv.x, 1.0) * step(0.0, revealUv.y) * step(revealUv.y, 1.0);+ background.rgb = mix(background.rgb, reveal.rgb, reveal.a * hasReveal * revealInside);+ vec2 contentUv = uv;+ vec4 content = sampleLayer(overlayMap, clamp(contentUv, vec2(0.001), vec2(0.999)), lod);+ float inside = step(0.0, contentUv.x) * step(contentUv.x, 1.0) * step(0.0, contentUv.y) * step(contentUv.y, 1.0);+ return vec4(mix(background.rgb, content.rgb, content.a * hasOverlay * inside), 1.0);+ }+ void main() {+ vec3 ray = displayPosition - displayCamera;+ float rayDepth = min(ray.z, -0.001);+ vec3 intersection = displayCamera + ray * (-displayCamera.z / rayDepth);+ vec2 planeUv = vec2(intersection.x / mix(15.798708, 7.739354, cover) + 0.5 * (1.0 - cover), intersection.y / mix(11.10349, 11.251288, cover) + 0.5);+ vec3 startRay = coverStart - displayCamera;+ vec3 endRay = coverEnd - displayCamera;+ float startX = displayCamera.x - startRay.x * displayCamera.z / min(startRay.z, -0.001);+ float endX = displayCamera.x - endRay.x * displayCamera.z / min(endRay.z, -0.001);+ if (cover > 0.5) {+ float span = endX - startX;+ planeUv.x = abs(span) > 0.001 ? (intersection.x - startX) / span : screenUv.x;+ }+ float projection = mix((1.0 - smoothstep(0.18, 0.5, screenUv.x)) * (1.0 - smoothstep(0.9, 1.0, progress)), smoothstep(0.0, 0.08, progress), cover);+ vec2 projectedUv = mix(screenUv, planeUv, clamp(parallax, 0.0, 1.0) * projection);+ float coverage = smoothstep(-0.01, 0.018, projectedUv.x) * (1.0 - smoothstep(0.982, 1.01, projectedUv.x));+ coverage = mix(coverage, 1.0, cover);+ coverage *= smoothstep(-0.035, 0.015, projectedUv.y) * (1.0 - smoothstep(0.985, 1.035, projectedUv.y));+ float coverWave = smoothstep(focusEdge - 0.2, focusEdge + 0.18, screenUv.x);+ float innerWave = defocus * (1.0 - smoothstep(0.2, 0.49, screenUv.x));+ float amount = mix(innerWave, coverWave, cover);+ float radius = blur * amount * mix(3.5, 1.8, cover);+ float lod = max(0.0, log2(max(1.0, radius / 3.0)));+ vec4 color = sampleScreen(projectedUv, lod);+ float weight = 1.0;+ for (int i = 1; i <= 4; i++) {+ float f = float(i);+ float distance = sqrt(f / 4.0);+ float angle = f * 2.399963;+ vec2 offset = vec2(cos(angle), sin(angle)) * distance * radius * 0.35 / resolution;+ float w = exp(-distance * distance * 2.0);+ color += sampleScreen(clamp(projectedUv + offset, vec2(0.001), vec2(0.999)), lod) * w;+ weight += w;+ }+ color /= weight;+ float foldShade = sin(progress * 3.14159265);+ float innerShade = foldShade * 0.18 * (1.0 - smoothstep(0.3, 0.5, screenUv.x));+ float coverShade = foldShade * 0.52 * smoothstep(0.05, 0.95, screenUv.x);+ color.rgb *= mix(1.0, coverage, projection) * (1.0 - mix(innerShade, coverShade, cover));+ gl_FragColor = color;+ #include <colorspace_fragment>+ }+ `,+ toneMapped: false,+ })+}diff --git a/lib/mockup-motion-3d.ts b/lib/mockup-motion-3d.tsindex 597401a..e4e3d70 100644--- a/lib/mockup-motion-3d.ts+++ b/lib/mockup-motion-3d.ts@@ -6,11 +6,17 @@ export type Mockup3DMotionPresetId =| "macro-pan"| "screen-glide"| "float-hold"- | "spiral-drop";+ | "spiral-drop"+ | "duo-unfold"+ | "duo-fold"+ | "duo-cycle";export const MOCKUP_3D_MOTION_PRESETS: {id: Mockup3DMotionPresetId;category: "Entrance" | "Continue" | "Exit";}[] = [+ { id: "duo-unfold", category: "Entrance" },+ { id: "duo-cycle", category: "Continue" },+ { id: "duo-fold", category: "Exit" },{ id: "orbit-entrance", category: "Entrance" },{ id: "hero-reveal", category: "Entrance" },@@ -22,6 +28,11 @@ export const MOCKUP_3D_MOTION_PRESETS: {{ id: "spiral-drop", category: "Exit" },];+/** Fold presets are only meaningful on a device with the Duo hinge. */+export function supports3DMotionPreset(presetId: string, device: string): boolean {+ return !presetId.startsWith("duo-") || device === "iphone-duo";+}+export interface Mockup3DMotionConfig {presetId: Mockup3DMotionPresetId;intensity: number;@@ -53,6 +64,8 @@ export interface Mockup3DMotionTransform {scale: number;/** Opacity [0..1] — applied to materials when < 1. */opacity: number;+ /** Absolute hinge progress for foldable devices; undefined uses the manual pose. */+ openingProgress?: number;}export const REST_MOCKUP_3D_MOTION: Mockup3DMotionTransform = {@@ -103,6 +116,29 @@ export function sampleMockup3DMotion(if (presetId === "none" || clipDurationSec <= 0) return REST_MOCKUP_3D_MOTION;switch (presetId) {+ case "duo-unfold":+ case "duo-fold":+ case "duo-cycle": {+ const p = clamp01(currentTime / clipDurationSec);+ // Speed shapes the transition within the fragment, preserving its endpoints.+ const duration = lerp(1, 0.35, clamp01(speed / 100));+ const t = presetId === "duo-fold"+ ? clamp01((p - (1 - duration)) / duration)+ : clamp01(p / duration);+ const eased = easeInOutCubic(t);+ const cycle = easeInOutCubic(clamp01(p < 0.5 ? p * 2 / duration : (1 - p) * 2 / duration));+ const openingProgress = presetId === "duo-unfold" ? eased+ : presetId === "duo-fold" ? 1 - eased : 1 - cycle;+ const tilt = Math.sin(openingProgress * Math.PI) * i;+ return {+ ...REST_MOCKUP_3D_MOTION,+ openingProgress,+ rotY: tilt * -12 * DEG,+ rotX: tilt * 4 * DEG,+ scale: 1 + tilt * 0.06,+ };+ }+/*** ORBIT ENTRANCE — the model sweeps in from a dramatic three-quarter* angle while rising on the Y axis, then settles into its resting pose.@@ -316,6 +352,8 @@ export function getDefault3DFragmentDuration(presetId: Mockup3DMotionPresetId,speed: number): number {+ if (presetId.startsWith("duo-")) return presetId === "duo-cycle" ? 4 : 2;+if (LONG_DURATION_PRESETS_3D.has(presetId)) {return lerp(10, 6.0, clamp01(speed / 100));}@@ -369,6 +407,8 @@ function apply3DMotionCustomOffsets(return {...base,+ openingProgress: base.openingProgress === undefined ? undefined+ : custom.reverse ? 1 - base.openingProgress : base.openingProgress,scale: base.scale * custom.zoomMultiplier,posX: base.posX * sign + custom.positionX,posY: base.posY * sign + custom.positionY,@@ -413,7 +453,15 @@ export function sampleCombined3DMotion((f) => currentTime >= f.startTime && currentTime <= f.endTime);- if (active.length === 0) return REST_MOCKUP_3D_MOTION;+ // Keep the most recent completed fold pose while the timeline continues.+ // Sampling by time (not frame history) makes scrubbing and export identical.+ const lastFold = fragments.filter((f) => f.presetId.startsWith("duo-") && f.endTime < currentTime)+ .sort((a, b) => b.endTime - a.endTime)[0];+ const rest = lastFold ? {+ ...REST_MOCKUP_3D_MOTION,+ openingProgress: sample3DFragmentMotion(lastFold, lastFold.endTime).openingProgress,+ } : REST_MOCKUP_3D_MOTION;+ if (active.length === 0) return rest;return active.reduce<Mockup3DMotionTransform>((acc, fragment) => {@@ -427,9 +475,10 @@ export function sampleCombined3DMotion(posZ: acc.posZ + t.posZ,scale: acc.scale * t.scale,opacity: acc.opacity * t.opacity,+ openingProgress: t.openingProgress ?? acc.openingProgress,};},- { ...REST_MOCKUP_3D_MOTION }+ { ...rest });}diff --git a/lib/mockup-motion.ts b/lib/mockup-motion.tsindex 699527c..76feec7 100644--- a/lib/mockup-motion.ts+++ b/lib/mockup-motion.ts@@ -20,7 +20,10 @@ export type MockupMotionPresetId =| "macro-pan"| "screen-glide"| "float-hold"- | "spiral-drop";+ | "spiral-drop"+ | "duo-unfold"+ | "duo-fold"+ | "duo-cycle";export type MockupMotionMode = "2d" | "3d";@@ -43,6 +46,9 @@ export const MOCKUP_MOTION_PRESETS: MockupMotionPresetDef[] = [{ id: "rise-crash", category: "Continue", mode: "2d" },{ id: "exit-fade-down", category: "Exit", mode: "2d" },{ id: "exit-scale-blur", category: "Exit", mode: "2d" },+ { id: "duo-unfold", category: "Entrance", mode: "3d" },+ { id: "duo-cycle", category: "Continue", mode: "3d" },+ { id: "duo-fold", category: "Exit", mode: "3d" },{ id: "orbit-entrance", category: "Entrance", mode: "3d" },{ id: "flick-exit", category: "Exit", mode: "3d" },{ id: "hero-reveal", category: "Entrance", mode: "3d" },diff --git a/lib/phone3d-composite-draw.utils.ts b/lib/phone3d-composite-draw.utils.tsindex d97ab4f..791fff0 100644--- a/lib/phone3d-composite-draw.utils.ts+++ b/lib/phone3d-composite-draw.utils.ts@@ -6,7 +6,7 @@ import { REST_MOCKUP_3D_MOTION } from "@/lib/mockup-motion-3d";import * as THREE from "three";export interface Phone3DApi {- renderAt: (w: number, h: number) => void;+ renderAt: (w: number, h: number, motion?: Mockup3DMotionTransform) => void;restorePreview: () => void;hasBuiltInShadow?: boolean;getVisualSize?: () => { width: number; height: number; offsetY?: number } | null;@@ -96,7 +96,7 @@ export function drawPhone3DCompositeWithZoom(}if (highQuality) {- imagePhoneApiRef.current?.renderAt(baseW, baseH);+ imagePhoneApiRef.current?.renderAt(baseW, baseH, motion);}c.save();diff --git a/lib/phone3d.utils.ts b/lib/phone3d.utils.tsindex aec1b1d..8a267f7 100644--- a/lib/phone3d.utils.ts+++ b/lib/phone3d.utils.ts@@ -29,6 +29,7 @@ export const RENDER_W = PHONE_W * RENDER_MULTIPLIER;export const RENDER_H = PHONE_H * RENDER_MULTIPLIER;export const DEVICE_3D_DIMENSIONS: Record<string, { width: number; height: number }> = {+ 'iphone-duo': { width: 1100, height: 900 },'phone': { width: PHONE_W, height: PHONE_H },'iphone': { width: PHONE_W, height: PHONE_H },'iphone-13-pro-max': { width: 480, height: 1000 },@@ -39,6 +40,7 @@ export const DEVICE_3D_DIMENSIONS: Record<string, { width: number; height: numbe};export const PHONE_DEVICE_URLS: Record<string, string | undefined> = {+ 'iphone-duo': '/models/iphone-duo.glb',phone: '/models/phone-gltf.glb',iphone: '/models/iphone-15-pro-max.glb','iphone-13-pro-max': '/models/apple_iphone_13_pro_max.glb',@@ -78,6 +80,7 @@ export const deviceConfigs: Record<DeviceKey, DeviceConfig> = {};export const DEVICE_VIEWER_DEFAULTS: Record<string, { environment: EnvironmentPreset; glow: number }> = {+ "iphone-duo": { environment: "studio", glow: 1.2 },double_iphone_13_pro: { environment: "studio", glow: 3.0 },"iphone-13-pro-max": { environment: "sunset", glow: 2.0 },"iphone-17-pro-max": { environment: "studio", glow: 1.0 },diff --git a/messages/en.json b/messages/en.jsonindex 6c1b9ee..675a010 100644--- a/messages/en.json+++ b/messages/en.json@@ -637,6 +637,9 @@"reset": "Reset","scale": "Scale","laptopOpening": "Laptop opening",+ "foldOpening": "Fold opening",+ "deviceLoadError": "Unable to load the 3D device.",+ "retry": "Try again","shadow": "Shadow","position": "Position","removeFrame": "Remove frame",@@ -689,6 +692,7 @@},"devices": {"iphone-13-pro-max": "iPhone 13 Pro",+ "iphone-duo": "iPhone Duo","double_iphone_13_pro": "Double iPhone 13 Pro","iphone-17-pro-max": "iPhone 17 Pro","iphone": "iPhone 15 Pro",@@ -1360,6 +1364,11 @@},"motionMenu": {"title": "Motion",+ "duoEyebrow": "Foldable device",+ "duoDescription": "Two screens. One continuous motion.",+ "duoAdd": "Add iPhone Duo",+ "duoActive": "Ready to animate",+ "duoHint": "Choose an opening or closing motion below.","globalMotionLabel": "Animate all","empty2D": {"title": "Requires 2D Mockup",@@ -1384,6 +1393,9 @@"rise-crash": "Rise and Crash","crane-sweep": "Crane Sweep","orbit-entrance": "Orbit Entrance",+ "duo-unfold": "Unfold",+ "duo-fold": "Fold",+ "duo-cycle": "Fold & unfold","flick-exit": "Flick Exit","hero-reveal": "Hero Reveal","macro-pan": "Macro Pan",diff --git a/messages/es.json b/messages/es.jsonindex 2a72f88..4f68878 100644--- a/messages/es.json+++ b/messages/es.json@@ -593,6 +593,9 @@"reset": "Restablecer","scale": "Escala","laptopOpening": "Apertura del portátil",+ "foldOpening": "Apertura del plegado",+ "deviceLoadError": "No se pudo cargar el dispositivo 3D.",+ "retry": "Reintentar","shadow": "Sombra","position": "Posición","removeFrame": "Quitar marco",@@ -645,6 +648,7 @@},"devices": {"iphone-13-pro-max": "iPhone 13 Pro",+ "iphone-duo": "iPhone Duo","double_iphone_13_pro": "Doble iPhone 13 Pro","iphone-17-pro-max": "iPhone 17 Pro","iphone": "iPhone 15 Pro",@@ -1338,6 +1342,11 @@},"motionMenu": {"title": "Motion",+ "duoEyebrow": "Dispositivo plegable",+ "duoDescription": "Dos pantallas. Un movimiento continuo.",+ "duoAdd": "Añadir iPhone Duo",+ "duoActive": "Listo para animar",+ "duoHint": "Elige abajo un movimiento de apertura o cierre.","globalMotionLabel": "Animar todo","empty2D": {"title": "Requiere Mockup 2D",@@ -1362,6 +1371,9 @@"rise-crash": "Elevación y Caída Rápida","crane-sweep": "Barrido de Grúa","orbit-entrance": "Entrada en órbita",+ "duo-unfold": "Desplegar",+ "duo-fold": "Plegar",+ "duo-cycle": "Plegar y desplegar","flick-exit": "Salida rápida","hero-reveal": "Revelación Hero","macro-pan": "Paneo Macro",diff --git a/messages/ko.json b/messages/ko.jsonindex c296bf1..3121f7b 100644--- a/messages/ko.json+++ b/messages/ko.json@@ -637,6 +637,9 @@"reset": "초기화","scale": "크기","laptopOpening": "노트북 열림 정도",+ "foldOpening": "펼침 정도",+ "deviceLoadError": "3D 기기를 불러올 수 없습니다.",+ "retry": "다시 시도","shadow": "그림자","position": "위치","removeFrame": "프레임 제거",@@ -689,6 +692,7 @@},"devices": {"iphone-13-pro-max": "iPhone 13 Pro",+ "iphone-duo": "iPhone Duo","double_iphone_13_pro": "iPhone 13 Pro (2대)","iphone-17-pro-max": "iPhone 17 Pro","iphone": "iPhone 15 Pro",@@ -1360,6 +1364,11 @@},"motionMenu": {"title": "모션",+ "duoEyebrow": "폴더블 기기",+ "duoDescription": "두 화면, 하나의 부드러운 모션.",+ "duoAdd": "iPhone Duo 추가",+ "duoActive": "애니메이션 준비 완료",+ "duoHint": "아래에서 펼치기 또는 접기 모션을 선택하세요.","globalMotionLabel": "모두 애니메이션","empty2D": {"title": "2D 목업 필요",@@ -1384,6 +1393,9 @@"rise-crash": "상승 및 추락","crane-sweep": "크레인 스윕","orbit-entrance": "오빗 입장",+ "duo-unfold": "펼치기",+ "duo-fold": "접기",+ "duo-cycle": "접고 펼치기","flick-exit": "플릭 퇴장","hero-reveal": "히어로 리빌","macro-pan": "매크로 팬",diff --git a/messages/ru.json b/messages/ru.jsonindex 8797531..aacce3b 100644--- a/messages/ru.json+++ b/messages/ru.json@@ -604,6 +604,9 @@"reset": "Сбросить","scale": "Масштаб","laptopOpening": "Открытие ноутбука",+ "foldOpening": "Раскрытие",+ "deviceLoadError": "Не удалось загрузить 3D-устройство.",+ "retry": "Повторить","shadow": "Тень","position": "Позиция","removeFrame": "Удалить рамку",@@ -656,6 +659,7 @@},"devices": {"iphone-13-pro-max": "iPhone 13 Pro",+ "iphone-duo": "iPhone Duo","double_iphone_13_pro": "Два iPhone 13 Pro","iphone-17-pro-max": "iPhone 17 Pro","iphone": "iPhone 15 Pro",@@ -1360,6 +1364,11 @@},"motionMenu": {"title": "Анимация",+ "duoEyebrow": "Складное устройство",+ "duoDescription": "Два экрана. Одно плавное движение.",+ "duoAdd": "Добавить iPhone Duo",+ "duoActive": "Готово к анимации",+ "duoHint": "Выберите анимацию открытия или закрытия ниже.","globalMotionLabel": "Анимировать всё","empty2D": {"title": "Требуется 2D-макет",@@ -1384,6 +1393,9 @@"rise-crash": "Взлет и Падение","crane-sweep": "Панорама Кран-Стрелы","orbit-entrance": "Орбитальный вход",+ "duo-unfold": "Раскрыть",+ "duo-fold": "Сложить",+ "duo-cycle": "Сложить и раскрыть","flick-exit": "Быстрый выход","hero-reveal": "Эффектный показ","macro-pan": "Макро-панорама",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b673532..b8f8e24 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -6,6 +6,9 @@ importers:.:configDependencies: {}packageManagerDependencies:+ '@pnpm/exe':+ specifier: 12.3.4+ version: 12.3.4pnpm:specifier: 12.3.4version: 12.3.4@@ -56,6 +59,11 @@ packages:cpu: [x64]os: [win32]+ '@pnpm/[email protected]':+ resolution: {integrity: sha512-Rq7JokWAyYF9IFfn8zofB/q2AgnZlmoMuH5fMHB2+Ta61I9aD7sNm+woZpx6iH+5vb38chdSoYRvOtSqlH72YQ==}+ engines: {node: '>=18.*'}+ hasBin: true+resolution: {integrity: sha512-lhqkH7B32joEpEHZ+OFevAyW2o73ELLrZ7+e58sGEOq9SPH9hfUc/+c4RnhfoPh8VqOocqHYk/hEZ0G1zORUVw==}engines: {node: '>=18.*'}@@ -87,6 +95,17 @@ snapshots:'@pnpm/[email protected]':optional: true+ '@pnpm/[email protected]':+ optionalDependencies:+ '@pnpm/exe.darwin-arm64': 12.3.4+ '@pnpm/exe.darwin-x64': 12.3.4+ '@pnpm/exe.linux-arm64': 12.3.4+ '@pnpm/exe.linux-arm64-musl': 12.3.4+ '@pnpm/exe.linux-x64': 12.3.4+ '@pnpm/exe.linux-x64-musl': 12.3.4+ '@pnpm/exe.win32-arm64': 12.3.4+ '@pnpm/exe.win32-x64': 12.3.4+optionalDependencies:'@pnpm/exe.darwin-arm64': 12.3.4diff --git a/proxy.ts b/proxy.tsindex 30568e1..5637bfe 100644--- a/proxy.ts+++ b/proxy.ts@@ -1,3 +1,4 @@+import { EDITOR_WITHOUT_AUTH } from "@/app/config/editor";import { type NextRequest, NextResponse } from "next/server";import createIntlMiddleware from "next-intl/middleware";import { locales, defaultLocale } from "./i18n";@@ -17,7 +18,9 @@ const intlMiddleware = createIntlMiddleware({export default async function proxy(request: NextRequest) {const country = request.headers.get("x-vercel-ip-country") || "UNKNOWN";- const needsAuth = shouldRefreshSession(request);+ const pathname = request.nextUrl.pathname.replace(/\/$/, "");+ const isEditor = pathname === "/editor" || locales.some((locale) => pathname === `/${locale}/editor`);+ const needsAuth = !(EDITOR_WITHOUT_AUTH && isEditor) && shouldRefreshSession(request);if (!needsAuth) {const intlResponse = intlMiddleware(request);diff --git a/public/images/devices-positions/iphone-duo/flat-front-subtle-turn.webp b/public/images/devices-positions/iphone-duo/flat-front-subtle-turn.webpnew file mode 100644index 0000000..47b940dBinary files /dev/null and b/public/images/devices-positions/iphone-duo/flat-front-subtle-turn.webp differdiff --git a/public/images/devices-positions/iphone-duo/high-angle-right-shifted.webp b/public/images/devices-positions/iphone-duo/high-angle-right-shifted.webpnew file mode 100644index 0000000..1dd0ce2Binary files /dev/null and b/public/images/devices-positions/iphone-duo/high-angle-right-shifted.webp differdiff --git a/public/images/devices-positions/iphone-duo/isometric-forward-twist.webp b/public/images/devices-positions/iphone-duo/isometric-forward-twist.webpnew file mode 100644index 0000000..748f006Binary files /dev/null and b/public/images/devices-positions/iphone-duo/isometric-forward-twist.webp differdiff --git a/public/images/devices-positions/iphone-duo/isometric-left-tilt.webp b/public/images/devices-positions/iphone-duo/isometric-left-tilt.webpnew file mode 100644index 0000000..16c4845Binary files /dev/null and b/public/images/devices-positions/iphone-duo/isometric-left-tilt.webp differdiff --git a/public/images/devices-positions/iphone-duo/slanted-forward-view.webp b/public/images/devices-positions/iphone-duo/slanted-forward-view.webpnew file mode 100644index 0000000..f110b12Binary files /dev/null and b/public/images/devices-positions/iphone-duo/slanted-forward-view.webp differdiff --git a/public/images/devices-positions/iphone-duo/steep-isometric-front.webp b/public/images/devices-positions/iphone-duo/steep-isometric-front.webpnew file mode 100644index 0000000..5343092Binary files /dev/null and b/public/images/devices-positions/iphone-duo/steep-isometric-front.webp differdiff --git a/public/images/devices-positions/iphone-duo/subtle-low-angle-left.webp b/public/images/devices-positions/iphone-duo/subtle-low-angle-left.webpnew file mode 100644index 0000000..c265f28Binary files /dev/null and b/public/images/devices-positions/iphone-duo/subtle-low-angle-left.webp differdiff --git a/public/images/mockups-3d/apple-desert-cover_duo.avif b/public/images/mockups-3d/apple-desert-cover_duo.avifnew file mode 100644index 0000000..ca1925bBinary files /dev/null and b/public/images/mockups-3d/apple-desert-cover_duo.avif differdiff --git a/public/images/mockups-3d/apple-desert_duo.avif b/public/images/mockups-3d/apple-desert_duo.avifnew file mode 100644index 0000000..b04875fBinary files /dev/null and b/public/images/mockups-3d/apple-desert_duo.avif differdiff --git a/public/images/mockups-3d/iphone-duo.png b/public/images/mockups-3d/iphone-duo.pngnew file mode 100644index 0000000..261f601Binary files /dev/null and b/public/images/mockups-3d/iphone-duo.png differdiff --git a/public/models/iphone-duo.glb b/public/models/iphone-duo.glbnew file mode 100644index 0000000..38ca5f8Binary files /dev/null and b/public/models/iphone-duo.glb differdiff --git a/public/openvid-theme.js b/public/openvid-theme.jsnew file mode 100644index 0000000..489efc6--- /dev/null+++ b/public/openvid-theme.js@@ -0,0 +1,15 @@+(function () {+ try {+ var get = function (name) {+ var match = document.cookie.match(new RegExp("(?:^|;\\s*)" + name + "=([^;]*)"));+ return match ? decodeURIComponent(match[1]) : null;+ };+ var preference = get("openvid_theme_pref") || get("openvid_theme") || "system";+ var isDark = preference === "system"+ ? window.matchMedia("(prefers-color-scheme: dark)").matches+ : preference === "dark";+ document.documentElement.classList.toggle("dark", isDark);+ } catch {+ // Theme setup must never prevent the page from loading.+ }+})();diff --git a/public/videos/mockups-3d/iphone-duo.mp4 b/public/videos/mockups-3d/iphone-duo.mp4new file mode 100644index 0000000..792b3dcBinary files /dev/null and b/public/videos/mockups-3d/iphone-duo.mp4 differdiff --git a/tests/iphone-duo-motion.test.mjs b/tests/iphone-duo-motion.test.mjsnew file mode 100644index 0000000..64d2abf--- /dev/null+++ b/tests/iphone-duo-motion.test.mjs@@ -0,0 +1,83 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { supports3DMotionPreset, sampleMockup3DMotion, sampleCombined3DMotion, sample3DFragmentMotion, DEFAULT_3D_MOTION_CUSTOM_OFFSETS, getDefault3DFragmentDuration } from '../lib/mockup-motion-3d.ts';+import { foldChoreography } from '../lib/iphone-duo/fold-choreography.ts';++const fragment = (presetId, startTime = 0, endTime = 2) => ({ id: presetId, presetId, startTime, endTime, intensity: 50, speed: 50 });++test('fold choreography clamps both endpoints and keeps the hinge in range', () => {+ assert.equal(foldChoreography(-1).angle, Math.PI);+ assert.equal(foldChoreography(2).angle, 0);+ for (let p = 0; p <= 1; p += 0.01) {+ const { angle } = foldChoreography(p);+ assert.ok(angle >= 0 && angle <= Math.PI);+ }+});++test('unfold and fold finish at their intended endpoints at every speed', () => {+ for (const speed of [0, 50, 100]) {+ for (const intensity of [0, 50, 100]) {+ for (const [presetId, from, to] of [['duo-unfold', 0, 1], ['duo-fold', 1, 0]]) {+ const config = { presetId, speed, intensity };+ assert.equal(sampleMockup3DMotion(config, 0, 2).openingProgress, from);+ assert.equal(sampleMockup3DMotion(config, 2, 2).openingProgress, to);+ let previous = from;+ for (let frame = 0; frame <= 60; frame++) {+ const pose = sampleMockup3DMotion(config, frame / 30, 2);+ assert.ok(pose.openingProgress >= 0 && pose.openingProgress <= 1);+ assert.ok(to > from ? pose.openingProgress >= previous : pose.openingProgress <= previous);+ assert.ok(Object.values(pose).every(Number.isFinite));+ previous = pose.openingProgress;+ }+ }+ }+ }+});++test('cycle starts open, closes at the middle, and ends open', () => {+ const f = fragment('duo-cycle', 0, 4);+ assert.equal(sample3DFragmentMotion(f, 0).openingProgress, 1);+ assert.equal(sample3DFragmentMotion(f, 2).openingProgress, 0);+ assert.equal(sample3DFragmentMotion(f, 4).openingProgress, 1);+});++test('folded pose is retained through gaps and unrelated motion', () => {+ const fragments = [fragment('duo-fold'), fragment('float-hold', 3, 6), fragment('duo-unfold', 7, 9)];+ assert.equal(sampleCombined3DMotion(fragments, 2.5).openingProgress, 0);+ assert.equal(sampleCombined3DMotion(fragments, 4).openingProgress, 0);+ assert.equal(sampleCombined3DMotion(fragments, 10).openingProgress, 1);+ assert.equal(sampleCombined3DMotion(fragments, -1).openingProgress, undefined);+});++test('random scrubbing and serialized project restore match sequential export sampling', () => {+ const fragments = [fragment('duo-fold'), fragment('duo-unfold', 3, 5)];+ const restored = JSON.parse(JSON.stringify(fragments));+ const frames = Array.from({ length: 181 }, (_, i) => sampleCombined3DMotion(fragments, i / 30));+ for (const i of [180, 0, 110, 60, 89, 32, 150, 20]) {+ assert.deepEqual(sampleCombined3DMotion(restored, i / 30), frames[i]);+ }+});++test('reverse flips the fold direction and remains held after the fragment', () => {+ const f = { ...fragment('duo-unfold'), custom3D: { ...DEFAULT_3D_MOTION_CUSTOM_OFFSETS, reverse: true } };+ assert.equal(sample3DFragmentMotion(f, 0).openingProgress, 1);+ assert.equal(sample3DFragmentMotion(f, 2).openingProgress, 0);+ assert.equal(sampleCombined3DMotion([f], 3).openingProgress, 0);+});++test('ordinary devices and empty timelines keep manual opening untouched', () => {+ assert.equal(sampleCombined3DMotion([], 3).openingProgress, undefined);+ assert.equal(sampleCombined3DMotion([fragment('orbit-entrance')], 1).openingProgress, undefined);+ assert.equal(sampleMockup3DMotion(fragment('duo-unfold'), 0, 0).openingProgress, undefined);+ assert.equal(getDefault3DFragmentDuration('duo-unfold', 50), 2);+ assert.equal(getDefault3DFragmentDuration('duo-cycle', 50), 4);+});++test('fold presets cannot animate a different device', () => {+ for (const preset of ['duo-unfold', 'duo-fold', 'duo-cycle']) {+ assert.equal(supports3DMotionPreset(preset, 'iphone-duo'), true);+ assert.equal(supports3DMotionPreset(preset, 'laptop'), false);+ assert.equal(supports3DMotionPreset(preset, 'iphone-13-pro-max'), false);+ }+ assert.equal(supports3DMotionPreset('orbit-entrance', 'iphone-duo'), true);+});diff --git a/tsconfig.json b/tsconfig.jsonindex e54580e..3f1233d 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -30,5 +30,5 @@".next/dev/types/**/*.ts","**/*.mts"],- "exclude": ["node_modules", "openvid-back"]+ "exclude": ["node_modules", "openvid-back", "iphone-duo-main"]}diff --git a/types/editor-state.types.ts b/types/editor-state.types.tsindex 5334a0a..a3b9082 100644--- a/types/editor-state.types.ts+++ b/types/editor-state.types.ts@@ -1,3 +1,4 @@+import type { ImageDeviceId } from "@/types/mockup.types";import type { BackgroundTab, AspectRatio, BackgroundColorConfig, CropArea, ZoomFragment, AudioTrack, ZoomMovement } from "@/types";import type { TrimRange } from "@/types/timeline.types";import type { MockupConfig } from "@/types/mockup.types";@@ -47,7 +48,7 @@ export interface EditorState {imagePhoneRotY: number;imagePhoneRotZ: number;imagePhonePerspective: number;- imagePhoneDevice: 'phone' | 'iphone' | 'iphone-13-pro-max' | 'iphone-17-pro-max' | 'double_iphone_13_pro' | 'laptop' | 'ipad_mini_6_2021';+ imagePhoneDevice: ImageDeviceId;imagePhonePresetId: string;imagePhoneOpening: number;imagePhoneShadow: number;diff --git a/types/image-project.types.ts b/types/image-project.types.tsindex 5f12bad..5d603b4 100644--- a/types/image-project.types.ts+++ b/types/image-project.types.ts@@ -1,3 +1,4 @@+import type { ImageDeviceId } from "@/types/mockup.types";import type { BackgroundTab, BackgroundColorConfig, AspectRatio, CropArea } from "@/types";import type { MockupConfig } from "@/types/mockup.types";import { CanvasElement } from "./canvas-elements.types";@@ -50,7 +51,7 @@ export interface ImageProject {imagePhoneRotY: number;imagePhoneRotZ: number;imagePhonePerspective: number;- imagePhoneDevice: 'phone' | 'iphone' | 'iphone-13-pro-max' | 'double_iphone_13_pro' | 'laptop' | 'iphone-17-pro-max' | 'ipad_mini_6_2021';+ imagePhoneDevice: ImageDeviceId;imagePhonePresetId: string;imagePhoneOpening: number;imagePhoneShadow: number;diff --git a/types/mockup.types.ts b/types/mockup.types.tsindex ba520fd..a0a9f34 100644--- a/types/mockup.types.ts+++ b/types/mockup.types.ts@@ -92,6 +92,15 @@ export const HANDLE_R = 9;export type MenuPage = "home" | "detail-2d" | "detail-3d";export const IMAGE_DEVICE_TEMPLATES = [+ {+ id: "iphone-duo",+ title: "iPhone Duo",+ accentColor: "#A9BDF4",+ icon: "simple-icons:apple",+ modelUrl: "/models/iphone-duo.glb",+ posterUrl: encodeURI("/images/mockups-3d/iphone-duo.png"),+ videoUrl: encodeURI("/videos/mockups-3d/iphone-duo.mp4"),+ },{id: "iphone-13-pro-max",title: "iPhone 13 Pro",diff --git a/types/photo.types.ts b/types/photo.types.tsindex 7f73441..2cd37b5 100644--- a/types/photo.types.ts+++ b/types/photo.types.ts@@ -91,6 +91,16 @@ export const PHONE_IMAGE_PREVIEWS_DEFAULT: PhoneImagePreviewConfig[] = buildPhonexport function getPhoneImagePreviews(device: string): PhoneImagePreviewConfig[] {switch (device) {+ case "iphone-duo":+ return buildPhonePresets([+ { x: 0, y: 0, scale: 0.7, rotateX: 12, rotateY: -25, rotateZ: -6 },+ { x: 0, y: 0, scale: 0.7, rotateX: -6, rotateY: -15, rotateZ: 0 },+ { x: 0, y: 0, scale: 0.7, rotateX: 15, rotateY: 22, rotateZ: -10 },+ { x: 0, y: 0, scale: 0.7, rotateX: 28, rotateY: 25, rotateZ: 0 },+ { x: 0, y: 0, scale: 0.7, rotateX: 35, rotateY: 0, rotateZ: 0 },+ { x: 0, y: 0, scale: 0.7, rotateX: 20, rotateY: -12, rotateZ: 8 },+ { x: 0, y: 0, scale: 0.7, rotateX: 0, rotateY: 0, rotateZ: 0 },+ ]).map((preset) => ({ ...preset, imageUrl: `/images/devices-positions/iphone-duo/${preset.id}.webp` }));case "iphone-13-pro-max":return PHONE_IMAGE_PREVIEWS_IPHONE13;case "double_iphone_13_pro":diff --git a/utils/supabase/client.ts b/utils/supabase/client.tsindex 6a36ca7..11fe2b2 100644--- a/utils/supabase/client.ts+++ b/utils/supabase/client.ts@@ -1,11 +1,12 @@import { createBrowserClient } from "@supabase/ssr";-const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;-const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;+export const createClient = () => {+ const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;+ const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;-if (!supabaseUrl || !supabaseKey) {- throw new Error("Missing Supabase environment variables");-}+ if (!supabaseUrl || !supabaseKey) {+ throw new Error("Missing Supabase environment variables");+ }-export const createClient = () =>- createBrowserClient(supabaseUrl, supabaseKey);+ return createBrowserClient(supabaseUrl, supabaseKey);+};diff --git a/utils/supabase/middleware.ts b/utils/supabase/middleware.tsindex 6cc537a..c12d5be 100644--- a/utils/supabase/middleware.ts+++ b/utils/supabase/middleware.ts@@ -5,10 +5,6 @@ import { type NextRequest, NextResponse } from "next/server";const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;-if (!supabaseUrl || !supabaseKey) {- throw new Error("Missing Supabase environment variables");-}-type CookieToSet = {name: string;value: string;@@ -56,6 +52,10 @@ export function getSafeInternalPath(export async function updateSession(request: NextRequest,): Promise<SessionUpdateResult> {+ if (!supabaseUrl || !supabaseKey) {+ throw new Error("Missing Supabase environment variables");+ }+const cookiesToApply: CookieToSet[] = [];const supabase = createServerClient(supabaseUrl!, supabaseKey!, {