feat: initial make-space full-stack release with weighted multi-provider LLM and Dockerfile
This commit is contained in:
commit
37b323c9ac
55 files changed
+17087
No files matched your search
+787
@@ -0,0 +1,787 @@
|
||||
import * as THREE from "three";
|
||||
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
||||
|
||||
const FLOOR_HEIGHT = 3.6;
|
||||
const WALL_HEIGHT = 2.6;
|
||||
const WALL_THICK = 0.16;
|
||||
|
||||
// sRGB equivalents of the Aurora light canvas and blue action palette.
|
||||
const SCENE_COLORS = {
|
||||
background: 0xeff0f2,
|
||||
gridMajor: 0xd6d9df,
|
||||
gridMinor: 0xe3e5e9,
|
||||
accent: 0x235cc7,
|
||||
};
|
||||
|
||||
const ZONE_COLORS = {
|
||||
seating: 0xe8dfd1,
|
||||
counter: 0xd4a373,
|
||||
bar: 0xc89f81,
|
||||
kitchen: 0xb7b7a4,
|
||||
restroom: 0xa8dadc,
|
||||
terrace: 0xccd5ae,
|
||||
entrance: 0xf4e285,
|
||||
other: 0xdedbd2,
|
||||
};
|
||||
|
||||
const scenes = new Map();
|
||||
let nextId = 1;
|
||||
|
||||
function floorIndex(floors, level) {
|
||||
const sorted = [...floors].sort((a, b) => a.level - b.level);
|
||||
const idx = sorted.findIndex((f) => f.level === level);
|
||||
return idx >= 0 ? idx : 0;
|
||||
}
|
||||
|
||||
function createScene(canvas, layoutJson, onZoneSelect, cleanup) {
|
||||
const layout = JSON.parse(layoutJson);
|
||||
if (!layout || !Array.isArray(layout.floors)) throw new Error("Invalid floor layout");
|
||||
const coarsePointer = window.matchMedia("(pointer: coarse)");
|
||||
const originalTouchAction = canvas.style.touchAction;
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });
|
||||
cleanup.push(() => renderer.dispose());
|
||||
renderer.shadowMap.enabled = true;
|
||||
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
||||
renderer.setClearColor(SCENE_COLORS.background, 1);
|
||||
|
||||
const scene = new THREE.Scene();
|
||||
cleanup.push(() => disposeSceneObjects(scene));
|
||||
scene.fog = new THREE.FogExp2(SCENE_COLORS.background, 0.015);
|
||||
|
||||
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200);
|
||||
const controls = new OrbitControls(camera, canvas);
|
||||
cleanup.push(() => { controls.dispose(); canvas.style.touchAction = originalTouchAction; });
|
||||
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
controls.enableDamping = !reducedMotion.matches;
|
||||
controls.dampingFactor = 0.08;
|
||||
controls.maxPolarAngle = Math.PI * 0.48;
|
||||
|
||||
const hemi = new THREE.HemisphereLight(0xffffff, 0xaab0ba, 1.05);
|
||||
scene.add(hemi);
|
||||
|
||||
const dir = new THREE.DirectionalLight(0xffffff, 1.25);
|
||||
dir.position.set(16, 28, 18);
|
||||
dir.castShadow = true;
|
||||
dir.shadow.mapSize.set(2048, 2048);
|
||||
dir.shadow.camera.near = 1;
|
||||
dir.shadow.camera.far = 90;
|
||||
const d = 24;
|
||||
dir.shadow.camera.left = -d;
|
||||
dir.shadow.camera.right = d;
|
||||
dir.shadow.camera.top = d;
|
||||
dir.shadow.camera.bottom = -d;
|
||||
scene.add(dir);
|
||||
|
||||
const groundGrid = new THREE.GridHelper(60, 60, SCENE_COLORS.gridMajor, SCENE_COLORS.gridMinor);
|
||||
groundGrid.position.y = -0.08;
|
||||
scene.add(groundGrid);
|
||||
|
||||
const floorGroups = new Map();
|
||||
const pinMeshes = [];
|
||||
const floors = layout.floors || [];
|
||||
|
||||
floors.forEach((floor) => {
|
||||
const idx = floorIndex(floors, floor.level);
|
||||
const yBase = idx * FLOOR_HEIGHT;
|
||||
const group = buildFloorGroup(floor, yBase, pinMeshes);
|
||||
scene.add(group);
|
||||
floorGroups.set(floor.level, { group, yBase, floor });
|
||||
});
|
||||
|
||||
const maxW = Math.max(10, ...floors.map((f) => f.width_m || 10));
|
||||
const maxD = Math.max(10, ...floors.map((f) => f.depth_m || 10));
|
||||
const span = Math.max(maxW, maxD);
|
||||
camera.position.set(span * 1.15, span * 1.05, span * 1.25);
|
||||
controls.target.set(0, (floors.length - 1) * FLOOR_HEIGHT * 0.35, 0);
|
||||
controls.update();
|
||||
|
||||
let hasSize = false;
|
||||
let visible = true;
|
||||
let contextLost = false;
|
||||
let disposed = false;
|
||||
let raf = 0;
|
||||
let st;
|
||||
const requestFrame = () => {
|
||||
if (!disposed && !contextLost && !document.hidden && visible && hasSize && !raf) {
|
||||
raf = requestAnimationFrame(animate);
|
||||
}
|
||||
};
|
||||
let pixelRatio = 0;
|
||||
const resize = () => {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const w = rect.width;
|
||||
const h = rect.height;
|
||||
hasSize = w > 0 && h > 0;
|
||||
if (!hasSize) return;
|
||||
const nextPixelRatio = Math.min(window.devicePixelRatio || 1, coarsePointer.matches ? 1.5 : 2);
|
||||
if (nextPixelRatio !== pixelRatio) {
|
||||
renderer.setPixelRatio(nextPixelRatio);
|
||||
pixelRatio = nextPixelRatio;
|
||||
}
|
||||
renderer.setSize(w, h, false);
|
||||
camera.aspect = w / h;
|
||||
// Leave room around the model on portrait and near-square phone viewports.
|
||||
camera.fov = (2 * Math.atan(Math.tan((42 * Math.PI) / 360) / Math.min(1, camera.aspect / 1.15)) * 180) / Math.PI;
|
||||
camera.updateProjectionMatrix();
|
||||
requestFrame();
|
||||
};
|
||||
resize();
|
||||
const ro = new ResizeObserver(resize);
|
||||
cleanup.push(() => ro.disconnect());
|
||||
ro.observe(canvas);
|
||||
window.addEventListener("resize", resize);
|
||||
cleanup.push(() => window.removeEventListener("resize", resize));
|
||||
|
||||
const raycaster = new THREE.Raycaster();
|
||||
const pointer = new THREE.Vector2();
|
||||
const activePointers = new Set();
|
||||
let downPos = null;
|
||||
|
||||
const syncInteraction = () => {
|
||||
downPos = null;
|
||||
controls.enabled = !coarsePointer.matches || canvas.dataset.interactive === "true";
|
||||
// OrbitControls sets this to "none" in its constructor, so apply the page-scroll mode afterward.
|
||||
canvas.style.touchAction = controls.enabled ? "none" : "pan-y";
|
||||
};
|
||||
syncInteraction();
|
||||
const interactionObserver = new MutationObserver(syncInteraction);
|
||||
cleanup.push(() => interactionObserver.disconnect());
|
||||
interactionObserver.observe(canvas, { attributes: true, attributeFilter: ["data-interactive"] });
|
||||
const onPointerModeChange = () => {
|
||||
syncInteraction();
|
||||
resize();
|
||||
};
|
||||
coarsePointer.addEventListener("change", onPointerModeChange);
|
||||
cleanup.push(() => coarsePointer.removeEventListener("change", onPointerModeChange));
|
||||
|
||||
const onActivePointerDown = (e) => {
|
||||
activePointers.add(e.pointerId);
|
||||
if (activePointers.size > 1) downPos = null;
|
||||
};
|
||||
const onPointerDown = (e) => {
|
||||
activePointers.add(e.pointerId);
|
||||
// Pins remain tappable in page-scroll mode; only orbit gestures require opt-in.
|
||||
if (activePointers.size !== 1 || e.isPrimary === false || e.button !== 0) {
|
||||
downPos = null;
|
||||
return;
|
||||
}
|
||||
downPos = { pointerId: e.pointerId, x: e.clientX, y: e.clientY, at: performance.now() };
|
||||
};
|
||||
const onPointerMove = (e) => {
|
||||
if (downPos?.pointerId === e.pointerId && Math.hypot(e.clientX - downPos.x, e.clientY - downPos.y) > 6) {
|
||||
downPos = null;
|
||||
}
|
||||
};
|
||||
const onPointerUp = (e) => {
|
||||
const wasOnlyPointer = activePointers.size === 1 && activePointers.has(e.pointerId);
|
||||
activePointers.delete(e.pointerId);
|
||||
const tap = downPos;
|
||||
downPos = null;
|
||||
if (!wasOnlyPointer || tap?.pointerId !== e.pointerId || performance.now() - tap.at > 800) return;
|
||||
if (Math.hypot(e.clientX - tap.x, e.clientY - tap.y) > 6) return;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
if (rect.width <= 0 || rect.height <= 0) return;
|
||||
if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;
|
||||
pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
|
||||
pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
|
||||
raycaster.setFromCamera(pointer, camera);
|
||||
const selectablePins = pinMeshes.filter((pin) => {
|
||||
if (st.activeLevel !== 0 && pin.userData.floorLevel !== st.activeLevel) return false;
|
||||
for (let parent = pin; parent; parent = parent.parent) {
|
||||
if (!parent.visible) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const hits = raycaster.intersectObjects(selectablePins, true);
|
||||
let obj = hits[0]?.object;
|
||||
// The decorative pin is small; use a 44px minimum tap target around its visible center.
|
||||
if (!obj) {
|
||||
let distance = 22;
|
||||
const projected = new THREE.Vector3();
|
||||
for (const pin of selectablePins) {
|
||||
pin.getWorldPosition(projected);
|
||||
projected.project(camera);
|
||||
if (projected.z < -1 || projected.z > 1) continue;
|
||||
const x = rect.left + (projected.x + 1) * rect.width / 2;
|
||||
const y = rect.top + (1 - projected.y) * rect.height / 2;
|
||||
const candidateDistance = Math.hypot(e.clientX - x, e.clientY - y);
|
||||
if (candidateDistance < distance) {
|
||||
distance = candidateDistance;
|
||||
obj = pin;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (obj) {
|
||||
while (obj && !obj.userData?.photoIds) {
|
||||
obj = obj.parent;
|
||||
}
|
||||
if (obj && obj.userData?.photoIds && typeof onZoneSelect === "function") {
|
||||
highlightZone(st.id, obj.userData.zoneLabel, JSON.stringify(obj.userData.photoIds));
|
||||
onZoneSelect(obj.userData.zoneLabel || "구역", JSON.stringify(obj.userData.photoIds));
|
||||
}
|
||||
}
|
||||
};
|
||||
const onPointerCancel = (e) => {
|
||||
activePointers.delete(e.pointerId);
|
||||
downPos = null;
|
||||
};
|
||||
canvas.addEventListener("pointerdown", onPointerDown);
|
||||
window.addEventListener("pointerdown", onActivePointerDown, true);
|
||||
window.addEventListener("pointermove", onPointerMove, true);
|
||||
canvas.addEventListener("lostpointercapture", onPointerCancel);
|
||||
// Capture release/cancel even when a scrolling or dragged pointer leaves the canvas.
|
||||
window.addEventListener("pointerup", onPointerUp, true);
|
||||
window.addEventListener("pointercancel", onPointerCancel, true);
|
||||
cleanup.push(() => {
|
||||
canvas.removeEventListener("pointerdown", onPointerDown);
|
||||
window.removeEventListener("pointerdown", onActivePointerDown, true);
|
||||
window.removeEventListener("pointermove", onPointerMove, true);
|
||||
canvas.removeEventListener("lostpointercapture", onPointerCancel);
|
||||
window.removeEventListener("pointerup", onPointerUp, true);
|
||||
window.removeEventListener("pointercancel", onPointerCancel, true);
|
||||
});
|
||||
|
||||
function animate() {
|
||||
raf = 0;
|
||||
if (disposed || contextLost || document.hidden || !visible || !hasSize) return;
|
||||
const t = performance.now() / 1000;
|
||||
pinMeshes.forEach((pin, i) => {
|
||||
pin.position.y = pin.userData.baseY + (reducedMotion.matches ? 0 : Math.sin(t * 2.6 + i) * 0.08);
|
||||
pin.rotation.y = reducedMotion.matches ? 0 : t * 1.1 + i;
|
||||
});
|
||||
controls.update();
|
||||
renderer.render(scene, camera);
|
||||
if (!reducedMotion.matches) requestFrame();
|
||||
}
|
||||
const stopFrame = () => {
|
||||
cancelAnimationFrame(raf);
|
||||
raf = 0;
|
||||
};
|
||||
const onVisibilityChange = () => document.hidden ? stopFrame() : requestFrame();
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
cleanup.push(() => { disposed = true; stopFrame(); document.removeEventListener("visibilitychange", onVisibilityChange); });
|
||||
const intersectionObserver = new IntersectionObserver(([entry]) => {
|
||||
visible = entry.isIntersecting;
|
||||
visible ? requestFrame() : stopFrame();
|
||||
});
|
||||
intersectionObserver.observe(canvas);
|
||||
cleanup.push(() => intersectionObserver.disconnect());
|
||||
const onMotionChange = () => {
|
||||
controls.enableDamping = !reducedMotion.matches;
|
||||
requestFrame();
|
||||
};
|
||||
reducedMotion.addEventListener("change", onMotionChange);
|
||||
controls.addEventListener("change", requestFrame);
|
||||
cleanup.push(() => { reducedMotion.removeEventListener("change", onMotionChange); controls.removeEventListener("change", requestFrame); });
|
||||
const onContextLost = (event) => {
|
||||
event.preventDefault();
|
||||
contextLost = true;
|
||||
stopFrame();
|
||||
reportSceneState(canvas, "공간 화면이 중단됐습니다. 잠시 후 다시 시도해 주세요.");
|
||||
};
|
||||
const onContextRestored = () => {
|
||||
contextLost = false;
|
||||
resize();
|
||||
requestFrame();
|
||||
reportSceneState(canvas, null);
|
||||
};
|
||||
canvas.addEventListener("webglcontextlost", onContextLost);
|
||||
canvas.addEventListener("webglcontextrestored", onContextRestored);
|
||||
cleanup.push(() => { canvas.removeEventListener("webglcontextlost", onContextLost); canvas.removeEventListener("webglcontextrestored", onContextRestored); });
|
||||
|
||||
const id = nextId++;
|
||||
st = {
|
||||
id,
|
||||
renderer,
|
||||
scene,
|
||||
camera,
|
||||
controls,
|
||||
floorGroups,
|
||||
pinMeshes,
|
||||
ro,
|
||||
interactionObserver,
|
||||
coarsePointer,
|
||||
onPointerModeChange,
|
||||
resize,
|
||||
requestFrame,
|
||||
reducedMotion,
|
||||
onMotionChange,
|
||||
intersectionObserver,
|
||||
onVisibilityChange,
|
||||
onContextLost,
|
||||
onContextRestored,
|
||||
stopAnimation: () => {
|
||||
disposed = true;
|
||||
stopFrame();
|
||||
},
|
||||
canvas,
|
||||
originalTouchAction,
|
||||
onPointerDown,
|
||||
onActivePointerDown,
|
||||
onPointerMove,
|
||||
onPointerUp,
|
||||
onPointerCancel,
|
||||
span,
|
||||
activeLevel: 0,
|
||||
viewMode: "3d",
|
||||
};
|
||||
scenes.set(id, st);
|
||||
resetScene(id);
|
||||
reportSceneState(canvas, null);
|
||||
requestFrame();
|
||||
return id;
|
||||
}
|
||||
|
||||
function reportSceneState(canvas, message) {
|
||||
canvas.dataset.sceneError = message || "";
|
||||
canvas.dispatchEvent(new Event(message ? "scene-error" : "scene-ready", { bubbles: true }));
|
||||
}
|
||||
|
||||
export function mountScene(canvas, layoutJson, onZoneSelect) {
|
||||
const cleanup = [];
|
||||
try {
|
||||
return createScene(canvas, layoutJson, onZoneSelect, cleanup);
|
||||
} catch (error) {
|
||||
cleanup.reverse().forEach((dispose) => { try { dispose(); } catch { /* Finish the remaining cleanup. */ } });
|
||||
console.warn("Space viewer could not start", error?.message);
|
||||
reportSceneState(canvas, "공간 화면을 열 수 없습니다. 아래 정보와 사진을 확인하거나 다시 시도해 주세요.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export function setFloor(handle, level) {
|
||||
const st = scenes.get(handle);
|
||||
if (!st) return;
|
||||
if (level !== 0 && !st.floorGroups.has(level)) return;
|
||||
const previousY = floorTarget(st);
|
||||
st.activeLevel = level;
|
||||
const offsetY = floorTarget(st) - previousY;
|
||||
st.camera.position.y += offsetY;
|
||||
st.controls.target.y += offsetY;
|
||||
st.floorGroups.forEach(({ group, yBase }, fLevel) => {
|
||||
if (level === 0) {
|
||||
group.visible = true;
|
||||
setGroupOpacity(group, 1.0);
|
||||
} else if (fLevel === level) {
|
||||
group.visible = true;
|
||||
setGroupOpacity(group, 1.0);
|
||||
} else if (fLevel < level) {
|
||||
group.visible = st.viewMode !== "plan";
|
||||
setGroupOpacity(group, 0.18);
|
||||
} else {
|
||||
group.visible = false;
|
||||
}
|
||||
});
|
||||
st.controls.update();
|
||||
st.requestFrame();
|
||||
}
|
||||
|
||||
function floorTarget(st) {
|
||||
return st.floorGroups.get(st.activeLevel)?.yBase ?? Math.max(0, st.floorGroups.size - 1) * FLOOR_HEIGHT * 0.35;
|
||||
}
|
||||
|
||||
export function setViewMode(handle, mode) {
|
||||
const st = scenes.get(handle);
|
||||
if (!st) return;
|
||||
st.viewMode = mode === "plan" ? "plan" : "3d";
|
||||
const plan = st.viewMode === "plan";
|
||||
st.controls.enableRotate = !plan;
|
||||
st.controls.minPolarAngle = 0;
|
||||
st.controls.maxPolarAngle = plan ? 0 : Math.PI * 0.48;
|
||||
st.controls.screenSpacePanning = true;
|
||||
st.controls.mouseButtons.LEFT = plan ? THREE.MOUSE.PAN : THREE.MOUSE.ROTATE;
|
||||
st.controls.touches.ONE = plan ? THREE.TOUCH.PAN : THREE.TOUCH.ROTATE;
|
||||
st.controls.touches.TWO = THREE.TOUCH.DOLLY_PAN;
|
||||
setFloor(handle, st.activeLevel);
|
||||
resetScene(handle);
|
||||
}
|
||||
|
||||
export function resetScene(handle) {
|
||||
const st = scenes.get(handle);
|
||||
if (!st) return;
|
||||
const yTarget = floorTarget(st);
|
||||
const s = st.span;
|
||||
// Flush accumulated damping so reset and view changes do not inherit a prior gesture.
|
||||
const damping = st.controls.enableDamping;
|
||||
st.controls.enableDamping = false;
|
||||
st.controls.update();
|
||||
st.controls.enableDamping = damping;
|
||||
st.controls.minDistance = Math.max(2, s * 0.18);
|
||||
st.controls.maxDistance = s * 5;
|
||||
if (st.viewMode === "plan") {
|
||||
st.camera.position.set(0, yTarget + s * 1.65, 0.01);
|
||||
st.controls.target.set(0, yTarget, 0);
|
||||
} else {
|
||||
st.camera.position.set(s * 1.15, yTarget + s * 1.0, s * 1.25);
|
||||
st.controls.target.set(0, yTarget + 0.4, 0);
|
||||
}
|
||||
st.controls.update();
|
||||
st.requestFrame();
|
||||
}
|
||||
|
||||
export function zoomScene(handle, delta) {
|
||||
const st = scenes.get(handle);
|
||||
if (!st || !Number.isFinite(delta)) return;
|
||||
const offset = st.camera.position.clone().sub(st.controls.target);
|
||||
const distance = THREE.MathUtils.clamp(offset.length() * Math.exp(-delta * 0.18), st.controls.minDistance, st.controls.maxDistance);
|
||||
st.camera.position.copy(st.controls.target).add(offset.setLength(distance));
|
||||
st.controls.update();
|
||||
st.requestFrame();
|
||||
}
|
||||
|
||||
export function highlightZone(handle, label, photoIdsJson) {
|
||||
const st = scenes.get(handle);
|
||||
if (!st) return;
|
||||
let photoIds = [];
|
||||
try { photoIds = JSON.parse(photoIdsJson); } catch { /* An empty selection simply clears emphasis. */ }
|
||||
st.scene.traverse((obj) => {
|
||||
if (!obj.userData.zoneSurface) return;
|
||||
const selected = Boolean(label) && obj.userData.zoneLabel === label &&
|
||||
(!photoIds.length || obj.userData.photoIds.some((id) => photoIds.includes(id)));
|
||||
obj.material.emissive.setHex(selected ? SCENE_COLORS.accent : 0x000000);
|
||||
obj.material.emissiveIntensity = selected ? 0.23 : 0;
|
||||
});
|
||||
st.pinMeshes.forEach((pin) => {
|
||||
const selected = Boolean(label) && pin.userData.zoneLabel === label &&
|
||||
(!photoIds.length || pin.userData.photoIds.some((id) => photoIds.includes(id)));
|
||||
pin.scale.setScalar(selected ? 1.4 : 1);
|
||||
});
|
||||
st.requestFrame();
|
||||
}
|
||||
|
||||
export function disposeScene(handle) {
|
||||
const st = scenes.get(handle);
|
||||
if (!st) return;
|
||||
st.stopAnimation();
|
||||
st.ro.disconnect();
|
||||
st.intersectionObserver.disconnect();
|
||||
st.interactionObserver.disconnect();
|
||||
st.coarsePointer.removeEventListener("change", st.onPointerModeChange);
|
||||
st.reducedMotion.removeEventListener("change", st.onMotionChange);
|
||||
document.removeEventListener("visibilitychange", st.onVisibilityChange);
|
||||
window.removeEventListener("resize", st.resize);
|
||||
st.canvas.removeEventListener("pointerdown", st.onPointerDown);
|
||||
window.removeEventListener("pointerdown", st.onActivePointerDown, true);
|
||||
window.removeEventListener("pointermove", st.onPointerMove, true);
|
||||
st.canvas.removeEventListener("lostpointercapture", st.onPointerCancel);
|
||||
window.removeEventListener("pointerup", st.onPointerUp, true);
|
||||
window.removeEventListener("pointercancel", st.onPointerCancel, true);
|
||||
st.canvas.removeEventListener("webglcontextlost", st.onContextLost);
|
||||
st.canvas.removeEventListener("webglcontextrestored", st.onContextRestored);
|
||||
st.controls.removeEventListener("change", st.requestFrame);
|
||||
st.controls.dispose();
|
||||
st.canvas.style.touchAction = st.originalTouchAction;
|
||||
disposeSceneObjects(st.scene);
|
||||
st.renderer.dispose();
|
||||
scenes.delete(handle);
|
||||
}
|
||||
|
||||
function disposeSceneObjects(scene) {
|
||||
const geometries = new Set();
|
||||
const materials = new Set();
|
||||
scene.traverse((obj) => {
|
||||
if (obj.geometry) geometries.add(obj.geometry);
|
||||
if (obj.material) (Array.isArray(obj.material) ? obj.material : [obj.material]).forEach((m) => materials.add(m));
|
||||
if (obj.shadow) obj.shadow.dispose();
|
||||
});
|
||||
geometries.forEach((geometry) => geometry.dispose());
|
||||
materials.forEach((material) => material.dispose());
|
||||
}
|
||||
|
||||
function setGroupOpacity(group, opacity) {
|
||||
group.traverse((obj) => {
|
||||
if (obj.isMesh && obj.material) {
|
||||
const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
|
||||
mats.forEach((m) => {
|
||||
if (m.userData.baseOpacity === undefined) {
|
||||
m.userData.baseOpacity = m.opacity ?? 1.0;
|
||||
m.userData.wasTransparent = m.transparent ?? false;
|
||||
}
|
||||
if (opacity < 0.99) {
|
||||
m.transparent = true;
|
||||
m.opacity = m.userData.baseOpacity * opacity;
|
||||
} else {
|
||||
m.transparent = m.userData.wasTransparent;
|
||||
m.opacity = m.userData.baseOpacity;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Convert floor local (x east 0..W, y north 0..D) into Three.js world (x east -W/2..W/2, z south -D/2..D/2)
|
||||
// Note: local y=0 is SOUTH (front/entrance), which maps to z = +D/2 in Three.js so south faces the viewer.
|
||||
function toWorldXZ(floor, lx, ly) {
|
||||
return [lx - floor.width_m / 2, floor.depth_m / 2 - ly];
|
||||
}
|
||||
|
||||
function buildFloorGroup(floor, yBase, pinMeshes) {
|
||||
const group = new THREE.Group();
|
||||
group.position.y = yBase;
|
||||
const W = floor.width_m || 10;
|
||||
const D = floor.depth_m || 10;
|
||||
|
||||
// Floor slab
|
||||
const slabGeo = new THREE.BoxGeometry(W, 0.14, D);
|
||||
const slabMat = new THREE.MeshStandardMaterial({ color: 0xf3ede2, roughness: 0.85 });
|
||||
const slab = new THREE.Mesh(slabGeo, slabMat);
|
||||
slab.position.y = -0.07;
|
||||
slab.receiveShadow = true;
|
||||
group.add(slab);
|
||||
|
||||
// Subtle perimeter walls (low cutaway height on South/East so interior is easy to see)
|
||||
buildWalls(group, floor);
|
||||
|
||||
// Zones + furniture + pins
|
||||
(floor.zones || []).forEach((zone) => {
|
||||
const zg = buildZone(floor, zone, pinMeshes);
|
||||
group.add(zg);
|
||||
});
|
||||
|
||||
// Verticals (stairs / elevator)
|
||||
(floor.verticals || []).forEach((v) => {
|
||||
group.add(buildVertical(floor, v));
|
||||
});
|
||||
|
||||
return group;
|
||||
}
|
||||
|
||||
function buildWalls(group, floor) {
|
||||
const W = floor.width_m;
|
||||
const D = floor.depth_m;
|
||||
const wallMat = new THREE.MeshStandardMaterial({ color: 0xd8d2c5, roughness: 0.75 });
|
||||
const glassMat = new THREE.MeshStandardMaterial({
|
||||
color: 0x8ecae6,
|
||||
transparent: true,
|
||||
opacity: 0.32,
|
||||
roughness: 0.2,
|
||||
});
|
||||
const doorMat = new THREE.MeshStandardMaterial({ color: 0xe76f51, roughness: 0.6 });
|
||||
|
||||
// Back walls (North & West) full height; front walls (South & East) cutaway 0.9m so camera sees inside
|
||||
const north = new THREE.Mesh(new THREE.BoxGeometry(W, WALL_HEIGHT, WALL_THICK), wallMat.clone());
|
||||
north.position.set(0, WALL_HEIGHT / 2, -D / 2);
|
||||
north.castShadow = true;
|
||||
group.add(north);
|
||||
|
||||
const west = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, WALL_HEIGHT, D), wallMat.clone());
|
||||
west.position.set(-W / 2, WALL_HEIGHT / 2, 0);
|
||||
west.castShadow = true;
|
||||
group.add(west);
|
||||
|
||||
const lowH = 0.65;
|
||||
const south = new THREE.Mesh(new THREE.BoxGeometry(W, lowH, WALL_THICK), wallMat.clone());
|
||||
south.position.set(0, lowH / 2, D / 2);
|
||||
group.add(south);
|
||||
|
||||
const east = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, lowH, D), wallMat.clone());
|
||||
east.position.set(W / 2, lowH / 2, 0);
|
||||
group.add(east);
|
||||
|
||||
// Render openings (windows as glass panels, entrances as welcome mats + arch)
|
||||
(floor.openings || []).forEach((op) => {
|
||||
const len = Math.max(0.9, op.length_m || 1.5);
|
||||
const off = op.offset_m || 1.0;
|
||||
const isWindow = op.kind === "window";
|
||||
const h = isWindow ? 1.5 : 2.1;
|
||||
const yCenter = isWindow ? 1.3 : h / 2;
|
||||
const mat = isWindow ? glassMat.clone() : doorMat.clone();
|
||||
|
||||
let mesh;
|
||||
if (op.wall === "south" || op.wall === "north") {
|
||||
mesh = new THREE.Mesh(new THREE.BoxGeometry(len, h, WALL_THICK * 1.3), mat);
|
||||
const x = -W / 2 + off + len / 2;
|
||||
const z = op.wall === "south" ? D / 2 : -D / 2;
|
||||
mesh.position.set(x, yCenter, z);
|
||||
} else {
|
||||
mesh = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK * 1.3, h, len), mat);
|
||||
const z = D / 2 - (off + len / 2);
|
||||
const x = op.wall === "east" ? W / 2 : -W / 2;
|
||||
mesh.position.set(x, yCenter, z);
|
||||
}
|
||||
group.add(mesh);
|
||||
});
|
||||
}
|
||||
|
||||
function buildZone(floor, zone, pinMeshes) {
|
||||
const g = new THREE.Group();
|
||||
const [wx, wz] = toWorldXZ(floor, zone.x + zone.w / 2, zone.y + zone.d / 2);
|
||||
g.position.set(wx, 0.02, wz);
|
||||
|
||||
const color = ZONE_COLORS[zone.kind] || ZONE_COLORS.other;
|
||||
const pad = new THREE.Mesh(
|
||||
new THREE.BoxGeometry(Math.max(0.8, zone.w - 0.12), 0.04, Math.max(0.8, zone.d - 0.12)),
|
||||
new THREE.MeshStandardMaterial({ color, roughness: 0.9 })
|
||||
);
|
||||
pad.receiveShadow = true;
|
||||
pad.userData = { zoneSurface: true, zoneLabel: zone.label || zone.kind, photoIds: zone.evidence_photos || [] };
|
||||
g.add(pad);
|
||||
|
||||
// Place furniture groups inside the zone
|
||||
(zone.furniture || []).forEach((fg) => {
|
||||
populateFurniture(g, zone.w, zone.d, fg);
|
||||
});
|
||||
|
||||
// If this zone has evidence photos, place a glowing interactive pin above it
|
||||
if (zone.evidence_photos && zone.evidence_photos.length > 0) {
|
||||
const pin = buildPin(zone.label || zone.kind, zone.evidence_photos);
|
||||
pin.position.set(0, 1.65, 0);
|
||||
pin.userData.baseY = 1.65;
|
||||
pin.userData.floorLevel = floor.level;
|
||||
g.add(pin);
|
||||
pinMeshes.push(pin);
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
function populateFurniture(zoneGroup, zw, zd, fg) {
|
||||
const count = Math.min(24, Math.max(1, fg.count || 1));
|
||||
const cols = Math.max(1, Math.ceil(Math.sqrt(count * (zw / Math.max(1, zd)))));
|
||||
const rows = Math.max(1, Math.ceil(count / cols));
|
||||
const cellW = (zw * 0.82) / cols;
|
||||
const cellD = (zd * 0.82) / rows;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const r = Math.floor(i / cols);
|
||||
const c = i % cols;
|
||||
const x = -zw * 0.41 + (c + 0.5) * cellW;
|
||||
const z = -zd * 0.41 + (r + 0.5) * cellD;
|
||||
const item = buildFurnitureMesh(fg.kind, cellW, cellD);
|
||||
item.position.set(x, 0.02, z);
|
||||
zoneGroup.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
function buildFurnitureMesh(kind, cellW, cellD) {
|
||||
const g = new THREE.Group();
|
||||
const wood = new THREE.MeshStandardMaterial({ color: 0x8b5e3c, roughness: 0.7 });
|
||||
const darkWood = new THREE.MeshStandardMaterial({ color: 0x5c3d28, roughness: 0.75 });
|
||||
const chairMat = new THREE.MeshStandardMaterial({ color: 0x3d405b, roughness: 0.8 });
|
||||
const sofaMat = new THREE.MeshStandardMaterial({ color: 0x6b705c, roughness: 0.85 });
|
||||
const metal = new THREE.MeshStandardMaterial({ color: 0xadb5bd, metalness: 0.5, roughness: 0.4 });
|
||||
const leaf = new THREE.MeshStandardMaterial({ color: 0x52b788, roughness: 0.8 });
|
||||
|
||||
if (kind === "counter_bar") {
|
||||
const w = Math.min(2.6, Math.max(1.2, cellW * 0.9));
|
||||
const d = Math.min(1.0, Math.max(0.65, cellD * 0.6));
|
||||
const body = new THREE.Mesh(new THREE.BoxGeometry(w, 0.95, d), darkWood);
|
||||
body.position.y = 0.475;
|
||||
body.castShadow = true;
|
||||
g.add(body);
|
||||
const machine = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.35, 0.35), metal);
|
||||
machine.position.set(-w * 0.2, 1.12, 0);
|
||||
g.add(machine);
|
||||
return g;
|
||||
}
|
||||
|
||||
if (kind === "bar_seat") {
|
||||
const stool = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 0.68, 12), chairMat);
|
||||
stool.position.y = 0.34;
|
||||
stool.castShadow = true;
|
||||
g.add(stool);
|
||||
return g;
|
||||
}
|
||||
|
||||
if (kind === "sofa") {
|
||||
const seat = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.42, 0.65), sofaMat);
|
||||
seat.position.y = 0.21;
|
||||
seat.castShadow = true;
|
||||
const back = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.45, 0.16), sofaMat);
|
||||
back.position.set(0, 0.55, -0.24);
|
||||
g.add(seat, back);
|
||||
return g;
|
||||
}
|
||||
|
||||
if (kind === "plant") {
|
||||
const pot = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.16, 0.36, 12), darkWood);
|
||||
pot.position.y = 0.18;
|
||||
const crown = new THREE.Mesh(new THREE.SphereGeometry(0.36, 12, 10), leaf);
|
||||
crown.position.y = 0.62;
|
||||
crown.castShadow = true;
|
||||
g.add(pot, crown);
|
||||
return g;
|
||||
}
|
||||
|
||||
// Tables (table2, table4, table6, communal_table)
|
||||
const isLarge = kind === "table6" || kind === "communal_table";
|
||||
const isFour = kind === "table4";
|
||||
const tw = isLarge ? 1.5 : isFour ? 0.95 : 0.68;
|
||||
const td = isLarge ? 0.8 : 0.68;
|
||||
const top = new THREE.Mesh(new THREE.BoxGeometry(tw, 0.06, td), wood);
|
||||
top.position.y = 0.72;
|
||||
top.castShadow = true;
|
||||
const leg = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.08, 0.7, 10), metal);
|
||||
leg.position.y = 0.35;
|
||||
g.add(top, leg);
|
||||
|
||||
const chairOffsets = isLarge
|
||||
? [
|
||||
[-0.45, -0.52],
|
||||
[0, -0.52],
|
||||
[0.45, -0.52],
|
||||
[-0.45, 0.52],
|
||||
[0, 0.52],
|
||||
[0.45, 0.52],
|
||||
]
|
||||
: isFour
|
||||
? [
|
||||
[-0.24, -0.48],
|
||||
[0.24, -0.48],
|
||||
[-0.24, 0.48],
|
||||
[0.24, 0.48],
|
||||
]
|
||||
: [
|
||||
[0, -0.46],
|
||||
[0, 0.46],
|
||||
];
|
||||
|
||||
chairOffsets.forEach(([cx, cz]) => {
|
||||
const ch = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.44, 0.32), chairMat);
|
||||
ch.position.set(cx, 0.22, cz);
|
||||
ch.castShadow = true;
|
||||
g.add(ch);
|
||||
});
|
||||
return g;
|
||||
}
|
||||
|
||||
function buildVertical(floor, v) {
|
||||
const g = new THREE.Group();
|
||||
const [wx, wz] = toWorldXZ(floor, v.x + v.w / 2, v.y + v.d / 2);
|
||||
g.position.set(wx, 0, wz);
|
||||
const mat = new THREE.MeshStandardMaterial({ color: 0xadb5bd, roughness: 0.6 });
|
||||
|
||||
if (v.kind === "elevator") {
|
||||
const box = new THREE.Mesh(new THREE.BoxGeometry(v.w, WALL_HEIGHT, v.d), mat);
|
||||
box.position.y = WALL_HEIGHT / 2;
|
||||
g.add(box);
|
||||
} else {
|
||||
const steps = 8;
|
||||
for (let i = 0; i < steps; i++) {
|
||||
const sh = ((i + 1) / steps) * (WALL_HEIGHT * 0.85);
|
||||
const step = new THREE.Mesh(new THREE.BoxGeometry(v.w, sh, v.d / steps), mat);
|
||||
step.position.set(0, sh / 2, -v.d / 2 + ((i + 0.5) * v.d) / steps);
|
||||
step.castShadow = true;
|
||||
g.add(step);
|
||||
}
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
function buildPin(zoneLabel, photoIds) {
|
||||
const g = new THREE.Group();
|
||||
g.userData = { zoneLabel, photoIds };
|
||||
const headMat = new THREE.MeshStandardMaterial({
|
||||
color: SCENE_COLORS.accent,
|
||||
emissive: SCENE_COLORS.accent,
|
||||
emissiveIntensity: 0.18,
|
||||
roughness: 0.3,
|
||||
});
|
||||
const head = new THREE.Mesh(new THREE.OctahedronGeometry(0.24, 0), headMat);
|
||||
head.position.y = 0.2;
|
||||
const stem = new THREE.Mesh(
|
||||
new THREE.CylinderGeometry(0.03, 0.03, 0.35, 8),
|
||||
new THREE.MeshBasicMaterial({ color: SCENE_COLORS.accent })
|
||||
);
|
||||
g.add(head, stem);
|
||||
return g;
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import vm from "node:vm";
|
||||
import { test } from "node:test";
|
||||
import * as Three from "../../public/vendor/three/three.module.js";
|
||||
|
||||
// Exercise real scene geometry/camera math with a minimal rendering boundary. No DOM or GPU
|
||||
// is required: these tests cover gesture arbitration and view state, not WebGL rendering.
|
||||
const source = (await readFile(new URL("./scene.js", import.meta.url), "utf8"))
|
||||
.replace(/^import .*;\r?\n/gm, "")
|
||||
.replace(/^export /gm, "");
|
||||
|
||||
class Surface extends EventTarget {
|
||||
style = { touchAction: "" };
|
||||
dataset = {};
|
||||
hidden = false;
|
||||
getBoundingClientRect() { return { left: 0, top: 0, right: 390, bottom: 460, width: 390, height: 460 }; }
|
||||
}
|
||||
|
||||
function setup({ reduced = false } = {}) {
|
||||
const window = new Surface();
|
||||
const document = new Surface();
|
||||
const canvas = new Surface();
|
||||
const frames = new Map();
|
||||
let nextFrame = 1;
|
||||
let failRenderer = false;
|
||||
class Renderer {
|
||||
shadowMap = {};
|
||||
setClearColor() {}
|
||||
setPixelRatio() {}
|
||||
setSize() {}
|
||||
constructor() { if (failRenderer) throw new Error("GPU unavailable"); }
|
||||
render(scene, camera) { scene.updateMatrixWorld(true); camera.updateMatrixWorld(true); }
|
||||
dispose() { this.disposed = true; }
|
||||
}
|
||||
class Controls extends Three.EventDispatcher {
|
||||
target = new Three.Vector3();
|
||||
mouseButtons = {};
|
||||
touches = {};
|
||||
minDistance = 0;
|
||||
maxDistance = Infinity;
|
||||
update() {}
|
||||
dispose() { this.disposed = true; }
|
||||
}
|
||||
class Observer { observe() {} disconnect() { this.disconnected = true; } }
|
||||
window.matchMedia = (query) => Object.assign(new Surface(), {
|
||||
matches: query === "(pointer: coarse)" || (query.includes("reduced-motion") && reduced),
|
||||
});
|
||||
window.devicePixelRatio = 1;
|
||||
const context = vm.createContext({
|
||||
THREE: { ...Three, WebGLRenderer: Renderer }, OrbitControls: Controls,
|
||||
window, document, Event, performance, console: { warn() {} },
|
||||
ResizeObserver: Observer, MutationObserver: Observer, IntersectionObserver: Observer,
|
||||
requestAnimationFrame(callback) { const id = nextFrame++; frames.set(id, callback); return id; },
|
||||
cancelAnimationFrame(id) { frames.delete(id); },
|
||||
});
|
||||
vm.runInContext(`${source}\nthis.api = {mountScene,setFloor,setViewMode,resetScene,zoomScene,highlightZone,disposeScene,scenes};`, context);
|
||||
const api = context.api;
|
||||
const selected = [];
|
||||
const layout = JSON.stringify({ floors: [1, 2].map((level) => ({
|
||||
level, width_m: 10, depth_m: 10, openings: [], verticals: [],
|
||||
zones: [{ label: `층${level}`, kind: "seating", x: 1, y: 1, w: 4, d: 4, furniture: [], evidence_photos: [`p${level}`] }],
|
||||
})) });
|
||||
const mount = () => api.mountScene(canvas, layout, (label) => selected.push(label));
|
||||
const handle = mount();
|
||||
const st = api.scenes.get(handle);
|
||||
const frame = () => {
|
||||
const batch = [...frames.values()];
|
||||
frames.clear();
|
||||
batch.forEach((callback) => callback());
|
||||
};
|
||||
frame();
|
||||
function point(pin = st.pinMeshes[0]) {
|
||||
st.scene.updateMatrixWorld(true);
|
||||
st.camera.lookAt(st.controls.target);
|
||||
st.camera.updateMatrixWorld(true);
|
||||
const v = pin.getWorldPosition(new Three.Vector3()).project(st.camera);
|
||||
return { x: (v.x + 1) * 195, y: (1 - v.y) * 230 };
|
||||
}
|
||||
function pointer(target, type, { id = 1, x, y, primary = true } = {}) {
|
||||
const event = new Event(type, { cancelable: true });
|
||||
Object.assign(event, { pointerId: id, clientX: x, clientY: y, isPrimary: primary, button: 0 });
|
||||
target.dispatchEvent(event);
|
||||
}
|
||||
return { api, canvas, window, document, selected, handle, st, frame, point, pointer, frames, mount, fail: () => { failRenderer = true; } };
|
||||
}
|
||||
|
||||
test("photo pins work while page scrolling is enabled", () => {
|
||||
const t = setup();
|
||||
assert.equal(t.canvas.style.touchAction, "pan-y");
|
||||
assert.equal(t.st.controls.enabled, false);
|
||||
t.api.setFloor(t.handle, 1);
|
||||
const p = t.point();
|
||||
t.pointer(t.canvas, "pointerdown", p);
|
||||
t.pointer(t.window, "pointerup", p);
|
||||
assert.deepEqual(t.selected, ["층1"]);
|
||||
t.api.disposeScene(t.handle);
|
||||
});
|
||||
|
||||
test("scroll, cancelled, and multi-touch gestures cannot select a pin", () => {
|
||||
const t = setup();
|
||||
const p = t.point();
|
||||
t.pointer(t.canvas, "pointerdown", p);
|
||||
t.pointer(t.window, "pointermove", { x: p.x, y: p.y + 12 });
|
||||
t.pointer(t.window, "pointerup", p);
|
||||
t.pointer(t.canvas, "pointerdown", p);
|
||||
t.pointer(t.window, "pointercancel", p);
|
||||
t.pointer(t.window, "pointerup", p);
|
||||
t.pointer(t.canvas, "pointerdown", p);
|
||||
t.pointer(t.canvas, "pointerdown", { ...p, id: 2, primary: false });
|
||||
t.pointer(t.window, "pointerup", { ...p, id: 2, primary: false });
|
||||
t.pointer(t.window, "pointerup", p);
|
||||
t.pointer(t.canvas, "pointerdown", p);
|
||||
t.pointer(t.window, "pointerdown", { ...p, id: 2, primary: false });
|
||||
t.pointer(t.window, "pointerup", p);
|
||||
t.pointer(t.window, "pointerup", { ...p, id: 2, primary: false });
|
||||
assert.deepEqual(t.selected, []);
|
||||
t.api.disposeScene(t.handle);
|
||||
});
|
||||
|
||||
test("plan mode locks rotation and floor changes preserve its zoom and orientation", () => {
|
||||
const t = setup();
|
||||
t.api.setFloor(t.handle, 1);
|
||||
t.api.setViewMode(t.handle, "plan");
|
||||
assert.equal(t.st.controls.enableRotate, false);
|
||||
assert.equal(t.st.controls.maxPolarAngle, 0);
|
||||
assert.equal(t.st.controls.touches.ONE, Three.TOUCH.PAN);
|
||||
t.api.zoomScene(t.handle, 1);
|
||||
const offset = t.st.camera.position.clone().sub(t.st.controls.target);
|
||||
t.api.setFloor(t.handle, 2);
|
||||
assert.ok(offset.distanceTo(t.st.camera.position.clone().sub(t.st.controls.target)) < 1e-10);
|
||||
assert.equal(t.st.floorGroups.get(1).group.visible, false);
|
||||
t.api.setViewMode(t.handle, "3d");
|
||||
assert.equal(t.st.controls.enableRotate, true);
|
||||
assert.equal(t.st.floorGroups.get(1).group.visible, true);
|
||||
assert.equal(t.st.activeLevel, 2);
|
||||
t.api.disposeScene(t.handle);
|
||||
});
|
||||
|
||||
test("reduced motion renders on demand and freezes decorative pins", () => {
|
||||
const t = setup({ reduced: true });
|
||||
assert.equal(t.st.controls.enableDamping, false);
|
||||
assert.equal(t.frames.size, 0);
|
||||
assert.ok(t.st.pinMeshes.every((pin) => pin.rotation.y === 0 && pin.position.y === pin.userData.baseY));
|
||||
t.api.zoomScene(t.handle, 1);
|
||||
assert.equal(t.frames.size, 1);
|
||||
t.frame();
|
||||
assert.equal(t.frames.size, 0);
|
||||
t.api.disposeScene(t.handle);
|
||||
});
|
||||
|
||||
test("context loss reports a recoverable state and disposal cancels work", () => {
|
||||
const t = setup();
|
||||
let errors = 0;
|
||||
let ready = 0;
|
||||
t.canvas.addEventListener("scene-error", () => errors++);
|
||||
t.canvas.addEventListener("scene-ready", () => ready++);
|
||||
const lost = new Event("webglcontextlost", { cancelable: true });
|
||||
t.canvas.dispatchEvent(lost);
|
||||
assert.equal(lost.defaultPrevented, true);
|
||||
assert.equal(errors, 1);
|
||||
assert.ok(t.canvas.dataset.sceneError);
|
||||
assert.equal(t.frames.size, 0);
|
||||
t.canvas.dispatchEvent(new Event("webglcontextrestored"));
|
||||
assert.equal(ready, 1);
|
||||
assert.equal(t.canvas.dataset.sceneError, "");
|
||||
t.api.disposeScene(t.handle);
|
||||
assert.equal(t.api.scenes.size, 0);
|
||||
assert.equal(t.frames.size, 0);
|
||||
assert.equal(t.st.renderer.disposed, true);
|
||||
assert.equal(t.st.controls.disposed, true);
|
||||
assert.equal(t.canvas.style.touchAction, "");
|
||||
t.canvas.dispatchEvent(new Event("webglcontextlost", { cancelable: true }));
|
||||
assert.equal(errors, 1);
|
||||
});
|
||||
|
||||
test("unavailable WebGL returns an explicit failure handle instead of throwing", () => {
|
||||
const t = setup();
|
||||
t.api.disposeScene(t.handle);
|
||||
t.fail();
|
||||
assert.equal(t.mount(), 0);
|
||||
assert.ok(t.canvas.dataset.sceneError);
|
||||
assert.equal(t.api.scenes.size, 0);
|
||||
});
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
// Small browser-only interactions shared by the hydrated views.
|
||||
const scrollPositions = new Map();
|
||||
const dialogs = new Map();
|
||||
const watchers = new Map();
|
||||
let nextHandle = 1;
|
||||
let scrollLock = null;
|
||||
let restoreGeneration = 0;
|
||||
|
||||
export function saveScroll(key) {
|
||||
restoreGeneration += 1;
|
||||
scrollPositions.set(key, window.scrollY);
|
||||
}
|
||||
export function restoreScroll(destination) {
|
||||
const target = new URL(destination, location.href);
|
||||
const top = scrollPositions.get(target.pathname) || 0;
|
||||
const route = target.pathname + target.search;
|
||||
const previousRoute = location.pathname + location.search;
|
||||
const generation = ++restoreGeneration;
|
||||
let attempts = 0;
|
||||
const afterCommit = () => {
|
||||
if (generation !== restoreGeneration) return;
|
||||
const currentRoute = location.pathname + location.search;
|
||||
// Leptos constructs the destination before committing the browser URL.
|
||||
// Wait for that commit, but abandon a canceled or superseded navigation.
|
||||
if (currentRoute !== route) {
|
||||
if (currentRoute === previousRoute && ++attempts < 60) requestAnimationFrame(afterCommit);
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(() => {
|
||||
if (generation === restoreGeneration && location.pathname + location.search === route) {
|
||||
window.scrollTo({ top, behavior: "instant" });
|
||||
}
|
||||
});
|
||||
};
|
||||
requestAnimationFrame(afterCommit);
|
||||
}
|
||||
export function focusSearch() {
|
||||
document.querySelector('input[name="q"]')?.focus({ preventScroll: true });
|
||||
}
|
||||
export function blurActive() {
|
||||
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
|
||||
}
|
||||
export function closeMenu(id) { document.getElementById(id)?.removeAttribute("open"); }
|
||||
export function clearJobQuery() {
|
||||
const url = new URL(location.href);
|
||||
if (url.searchParams.has("job")) {
|
||||
url.searchParams.delete("job");
|
||||
history.replaceState(history.state, "", url);
|
||||
}
|
||||
}
|
||||
export function revealSelectedPhoto() {
|
||||
requestAnimationFrame(() => {
|
||||
if (isCompact() || document.querySelector('dialog:modal')) return;
|
||||
const panel = document.getElementById('info-panel');
|
||||
if (panel) panel.scrollTop = 0;
|
||||
panel?.querySelector('.selected-zone-panel')?.scrollIntoView({ block: 'nearest', behavior: 'instant' });
|
||||
});
|
||||
}
|
||||
export function isCompact() {
|
||||
return matchMedia("(max-width: 639px), (max-height: 499px)").matches;
|
||||
}
|
||||
export function watchCompact(onChange) {
|
||||
const handle = nextHandle++;
|
||||
const media = matchMedia("(max-width: 639px), (max-height: 499px)");
|
||||
const listener = () => onChange(media.matches);
|
||||
media.addEventListener("change", listener);
|
||||
watchers.set(handle, { media, listener });
|
||||
listener();
|
||||
return handle;
|
||||
}
|
||||
export function releaseWatch(handle) {
|
||||
const watcher = watchers.get(handle);
|
||||
if (watcher) watcher.media.removeEventListener("change", watcher.listener);
|
||||
watchers.delete(handle);
|
||||
}
|
||||
|
||||
function unlockScroll() {
|
||||
if (scrollLock && ![...dialogs.values()].some(record => !record.finished)) {
|
||||
document.documentElement.style.overflow = scrollLock.html;
|
||||
document.body.style.overflow = scrollLock.body;
|
||||
scrollLock = null;
|
||||
}
|
||||
}
|
||||
function finishDialog(record, notify = true) {
|
||||
if (record.finished) return;
|
||||
record.finished = true;
|
||||
record.dialog.removeEventListener("cancel", record.cancel);
|
||||
record.dialog.removeEventListener("close", record.closed);
|
||||
record.dialog.removeEventListener("click", record.backdrop);
|
||||
record.dialog.removeAttribute("aria-modal");
|
||||
if (record.dialog.open) record.dialog.close();
|
||||
if (record.inline && record.dialog.isConnected) record.dialog.show();
|
||||
unlockScroll();
|
||||
if (location.pathname + location.search === record.route) {
|
||||
window.scrollTo({ top: record.scrollY, behavior: "instant" });
|
||||
if (record.focus?.isConnected) record.focus.focus({ preventScroll: true });
|
||||
}
|
||||
if (notify) queueMicrotask(() => {
|
||||
if (dialogs.get(record.handle) === record) record.onClose();
|
||||
});
|
||||
}
|
||||
|
||||
function requestClose(record) {
|
||||
if (record.finished || record.pending) return;
|
||||
if (history.state?.spaceOverlay === record.token) {
|
||||
record.pending = true;
|
||||
history.back();
|
||||
} else {
|
||||
finishDialog(record);
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("popstate", () => {
|
||||
for (const record of [...dialogs.values()].reverse()) {
|
||||
if (!record.finished && history.state?.spaceOverlay !== record.token) finishDialog(record);
|
||||
else if (!record.finished) break;
|
||||
}
|
||||
});
|
||||
|
||||
export function openDialog(id, onClose) {
|
||||
const dialog = document.getElementById(id);
|
||||
if (!(dialog instanceof HTMLDialogElement)) return 0;
|
||||
const existing = [...dialogs.values()].find(record => record.dialog === dialog && !record.finished);
|
||||
if (existing) {
|
||||
// The Rust bridge replaces its stored Closure for a reused handle.
|
||||
existing.onClose = onClose;
|
||||
return existing.handle;
|
||||
}
|
||||
const handle = nextHandle++;
|
||||
const record = {
|
||||
handle, dialog, onClose, token: `space-${handle}-${Date.now()}`,
|
||||
focus: document.activeElement instanceof HTMLElement ? document.activeElement : null,
|
||||
inline: dialog.hasAttribute("data-inline-dialog"),
|
||||
scrollY: window.scrollY, route: location.pathname + location.search,
|
||||
finished: false, pending: false,
|
||||
};
|
||||
record.cancel = event => { event.preventDefault(); requestClose(record); };
|
||||
record.closed = () => {
|
||||
// close() before showModal() queues an event; ignore it while the new modal is open.
|
||||
if (!dialog.open && !record.finished) requestClose(record);
|
||||
};
|
||||
record.backdrop = event => {
|
||||
if (event.target !== dialog) return;
|
||||
const rect = dialog.getBoundingClientRect();
|
||||
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) requestClose(record);
|
||||
};
|
||||
if (!scrollLock) {
|
||||
scrollLock = { html: document.documentElement.style.overflow, body: document.body.style.overflow };
|
||||
document.documentElement.style.overflow = "hidden";
|
||||
document.body.style.overflow = "hidden";
|
||||
}
|
||||
dialogs.set(handle, record);
|
||||
if (dialog.open) dialog.close();
|
||||
try {
|
||||
dialog.showModal();
|
||||
} catch {
|
||||
dialogs.delete(handle);
|
||||
if (record.inline && dialog.isConnected) dialog.show();
|
||||
unlockScroll();
|
||||
return 0;
|
||||
}
|
||||
dialog.setAttribute("aria-modal", "true");
|
||||
dialog.addEventListener("cancel", record.cancel);
|
||||
dialog.addEventListener("close", record.closed);
|
||||
dialog.addEventListener("click", record.backdrop);
|
||||
history.pushState({ ...history.state, spaceOverlay: record.token }, "");
|
||||
const focusTarget = dialog.querySelector("[autofocus], button:not([disabled]), [href], [tabindex='0']");
|
||||
focusTarget?.focus({ preventScroll: true });
|
||||
return handle;
|
||||
}
|
||||
export function closeDialog(id) {
|
||||
const record = [...dialogs.values()].reverse().find(entry => entry.dialog.id === id && !entry.finished);
|
||||
if (record) requestClose(record);
|
||||
}
|
||||
export function releaseDialog(handle) {
|
||||
const record = dialogs.get(handle);
|
||||
if (!record) return;
|
||||
// Route disposal must not initiate a second navigation. Explicit close consumes history.
|
||||
finishDialog(record, false);
|
||||
dialogs.delete(handle);
|
||||
}
|
||||
|
||||
export function copyText(value, onResult) {
|
||||
if (!navigator.clipboard?.writeText) { onResult(false); return; }
|
||||
navigator.clipboard.writeText(value).then(() => onResult(true), () => onResult(false));
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import vm from "node:vm";
|
||||
|
||||
const source = readFileSync(new URL("./ui.js", import.meta.url), "utf8");
|
||||
|
||||
// The fake environment models asynchronous close/popstate delivery deliberately:
|
||||
// it catches lifetime mistakes hidden by a synchronous history.back() stub.
|
||||
function setup() {
|
||||
const tasks = [];
|
||||
const microtasks = [];
|
||||
const frames = [];
|
||||
const elements = new Map();
|
||||
const scrollCalls = [];
|
||||
const document = {
|
||||
activeElement: null,
|
||||
documentElement: { style: { overflow: "auto" } },
|
||||
body: { style: { overflow: "" } },
|
||||
getElementById: id => elements.get(id),
|
||||
querySelector: () => null,
|
||||
};
|
||||
class Element extends EventTarget {
|
||||
isConnected = true;
|
||||
focusCount = 0;
|
||||
focus() { this.focusCount += 1; document.activeElement = this; }
|
||||
blur() { if (document.activeElement === this) document.activeElement = null; }
|
||||
}
|
||||
class Dialog extends Element {
|
||||
constructor(id, { inline = false } = {}) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.open = inline;
|
||||
this.modal = false;
|
||||
this.attributes = new Map(inline ? [["data-inline-dialog", "true"]] : []);
|
||||
this.firstButton = new Element();
|
||||
elements.set(id, this);
|
||||
}
|
||||
hasAttribute(name) { return this.attributes.has(name); }
|
||||
setAttribute(name, value) { this.attributes.set(name, value); }
|
||||
removeAttribute(name) { this.attributes.delete(name); }
|
||||
querySelector() { return this.firstButton; }
|
||||
show() { this.open = true; this.modal = false; }
|
||||
showModal() {
|
||||
if (this.open) throw new Error("A nonmodal dialog must be closed first");
|
||||
this.open = true;
|
||||
this.modal = true;
|
||||
}
|
||||
close() {
|
||||
if (!this.open) return;
|
||||
this.open = false;
|
||||
this.modal = false;
|
||||
tasks.push(() => this.dispatchEvent(new Event("close")));
|
||||
}
|
||||
getBoundingClientRect() { return { left: 10, top: 10, right: 300, bottom: 500 }; }
|
||||
}
|
||||
const window = new EventTarget();
|
||||
window.scrollY = 340;
|
||||
window.scrollTo = options => {
|
||||
window.scrollY = options.top;
|
||||
scrollCalls.push(options.top);
|
||||
};
|
||||
const location = new URL("http://localhost/place/kakao:123?from=%2Frecent");
|
||||
const entries = [{ router: "base" }];
|
||||
let historyIndex = 0;
|
||||
const history = {
|
||||
backCalls: 0,
|
||||
get state() { return entries[historyIndex]; },
|
||||
pushState(state) {
|
||||
entries.splice(historyIndex + 1);
|
||||
entries.push(state);
|
||||
historyIndex += 1;
|
||||
},
|
||||
replaceState(state) { entries[historyIndex] = state; },
|
||||
back() {
|
||||
this.backCalls += 1;
|
||||
tasks.push(() => {
|
||||
if (historyIndex === 0) return;
|
||||
historyIndex -= 1;
|
||||
window.dispatchEvent(new Event("popstate"));
|
||||
});
|
||||
},
|
||||
};
|
||||
const context = {
|
||||
window, document, location, history, URL, Event,
|
||||
HTMLElement: Element, HTMLDialogElement: Dialog,
|
||||
navigator: {},
|
||||
queueMicrotask: callback => microtasks.push(callback),
|
||||
requestAnimationFrame: callback => frames.push(callback),
|
||||
matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
|
||||
};
|
||||
const exports = ["saveScroll", "restoreScroll", "openDialog", "closeDialog", "releaseDialog"];
|
||||
const api = vm.runInNewContext(
|
||||
`${source.replace(/^export /gm, "")}\n({ ${exports.join(", ")} })`,
|
||||
context,
|
||||
{ filename: "ui.js" },
|
||||
);
|
||||
function flush() {
|
||||
while (tasks.length || microtasks.length) {
|
||||
while (microtasks.length) microtasks.shift()();
|
||||
if (tasks.length) tasks.shift()();
|
||||
}
|
||||
}
|
||||
function flushFrames() {
|
||||
while (frames.length) frames.shift()();
|
||||
}
|
||||
function nextFrame() { frames.shift()?.(); }
|
||||
return { api, Dialog, Element, document, window, location, history, entries, scrollCalls, flush, flushFrames, nextFrame };
|
||||
}
|
||||
|
||||
test("nested modal close consumes only the inner history entry and retains the outer scroll lock", () => {
|
||||
const env = setup();
|
||||
const { api, document, history, flush } = env;
|
||||
const opener = new env.Element();
|
||||
opener.focus();
|
||||
const scene = new env.Dialog("scene", { inline: true });
|
||||
const photo = new env.Dialog("photo");
|
||||
let sceneClosed = 0;
|
||||
let photoClosed = 0;
|
||||
api.openDialog("scene", () => sceneClosed++);
|
||||
const innerOpener = new env.Element();
|
||||
innerOpener.focus();
|
||||
api.openDialog("photo", () => photoClosed++);
|
||||
|
||||
api.closeDialog("photo");
|
||||
assert.equal(photo.open, true, "close is pending its history traversal");
|
||||
flush();
|
||||
assert.equal(photo.open, false);
|
||||
assert.equal(photoClosed, 1);
|
||||
assert.equal(sceneClosed, 0);
|
||||
assert.equal(scene.open, true);
|
||||
assert.equal(scene.modal, true);
|
||||
assert.equal(document.body.style.overflow, "hidden");
|
||||
assert.equal(document.activeElement, innerOpener);
|
||||
assert.equal(history.state.spaceOverlay, env.entries[1].spaceOverlay);
|
||||
|
||||
api.closeDialog("scene");
|
||||
flush();
|
||||
assert.equal(sceneClosed, 1);
|
||||
assert.equal(scene.open, true, "the inline canvas remains rendered");
|
||||
assert.equal(scene.modal, false);
|
||||
assert.equal(document.body.style.overflow, "");
|
||||
assert.equal(document.documentElement.style.overflow, "auto");
|
||||
assert.equal(document.activeElement, opener);
|
||||
assert.equal(history.backCalls, 2);
|
||||
});
|
||||
|
||||
test("the queued close event from promoting an inline dialog does not dismiss its modal", () => {
|
||||
const env = setup();
|
||||
const dialog = new env.Dialog("scene", { inline: true });
|
||||
let closed = 0;
|
||||
env.api.openDialog("scene", () => closed++);
|
||||
env.flush();
|
||||
assert.equal(dialog.modal, true);
|
||||
assert.equal(dialog.open, true);
|
||||
assert.equal(closed, 0);
|
||||
assert.equal(env.history.backCalls, 0);
|
||||
|
||||
const cancel = new Event("cancel", { cancelable: true });
|
||||
dialog.dispatchEvent(cancel);
|
||||
assert.equal(cancel.defaultPrevented, true);
|
||||
env.flush();
|
||||
assert.equal(dialog.open, true);
|
||||
assert.equal(dialog.modal, false);
|
||||
assert.equal(closed, 1);
|
||||
});
|
||||
|
||||
test("reopening an already open dialog replaces the callback without adding history", () => {
|
||||
const env = setup();
|
||||
new env.Dialog("photo");
|
||||
let oldCalls = 0;
|
||||
let newCalls = 0;
|
||||
const first = env.api.openDialog("photo", () => oldCalls++);
|
||||
const second = env.api.openDialog("photo", () => newCalls++);
|
||||
assert.equal(second, first);
|
||||
assert.equal(env.entries.length, 2);
|
||||
env.api.closeDialog("photo");
|
||||
env.flush();
|
||||
assert.equal(oldCalls, 0, "the old Rust Closure can safely be dropped");
|
||||
assert.equal(newCalls, 1);
|
||||
});
|
||||
|
||||
test("component release restores inline content without navigating history or notifying disposed state", () => {
|
||||
const env = setup();
|
||||
const scene = new env.Dialog("scene", { inline: true });
|
||||
let closed = 0;
|
||||
const handle = env.api.openDialog("scene", () => closed++);
|
||||
// The URL can still be the old route while a router disposes its component.
|
||||
env.api.releaseDialog(handle);
|
||||
env.flush();
|
||||
assert.equal(env.history.backCalls, 0);
|
||||
assert.equal(scene.open, true);
|
||||
assert.equal(scene.modal, false);
|
||||
assert.equal(env.document.body.style.overflow, "");
|
||||
assert.equal(closed, 0);
|
||||
});
|
||||
|
||||
test("close followed by immediate release cannot call a dropped callback after popstate", () => {
|
||||
const env = setup();
|
||||
const photo = new env.Dialog("photo");
|
||||
const handle = env.api.openDialog("photo", () => assert.fail("disposed callback invoked"));
|
||||
env.api.closeDialog("photo");
|
||||
env.api.releaseDialog(handle);
|
||||
env.flush();
|
||||
assert.equal(env.history.backCalls, 1);
|
||||
assert.equal(photo.open, false);
|
||||
assert.equal(env.document.body.style.overflow, "");
|
||||
});
|
||||
|
||||
test("browser back closes nested dialogs from top to bottom", () => {
|
||||
const env = setup();
|
||||
const scene = new env.Dialog("scene", { inline: true });
|
||||
const photo = new env.Dialog("photo");
|
||||
const notifications = [];
|
||||
env.api.openDialog("scene", () => notifications.push("scene"));
|
||||
env.api.openDialog("photo", () => notifications.push("photo"));
|
||||
env.history.back();
|
||||
env.flush();
|
||||
assert.deepEqual(notifications, ["photo"]);
|
||||
assert.equal(photo.open, false);
|
||||
assert.equal(scene.modal, true);
|
||||
env.history.back();
|
||||
env.flush();
|
||||
assert.deepEqual(notifications, ["photo", "scene"]);
|
||||
assert.equal(scene.open, true);
|
||||
assert.equal(scene.modal, false);
|
||||
});
|
||||
|
||||
test("native dialog close still consumes overlay history once", () => {
|
||||
const env = setup();
|
||||
const photo = new env.Dialog("photo");
|
||||
let closed = 0;
|
||||
env.api.openDialog("photo", () => closed++);
|
||||
photo.close();
|
||||
env.flush();
|
||||
assert.equal(env.history.backCalls, 1);
|
||||
assert.equal(closed, 1);
|
||||
assert.equal(env.document.body.style.overflow, "");
|
||||
});
|
||||
|
||||
test("a deferred search scroll restore cannot affect a different query on the same route", () => {
|
||||
const env = setup();
|
||||
env.location.pathname = "/";
|
||||
env.location.search = "?q=first";
|
||||
env.window.scrollY = 620;
|
||||
env.api.saveScroll("/");
|
||||
env.window.scrollY = 0;
|
||||
env.api.restoreScroll("/?q=first");
|
||||
env.location.search = "?q=second";
|
||||
env.flushFrames();
|
||||
assert.deepEqual(env.scrollCalls, []);
|
||||
|
||||
env.location.search = "?q=first";
|
||||
env.api.restoreScroll("/?q=first");
|
||||
env.flushFrames();
|
||||
assert.deepEqual(env.scrollCalls, [620]);
|
||||
});
|
||||
|
||||
test("search restoration waits for the router's destination URL commit", () => {
|
||||
const env = setup();
|
||||
env.location.pathname = "/";
|
||||
env.location.search = "?q=first";
|
||||
env.window.scrollY = 89;
|
||||
env.api.saveScroll("/");
|
||||
env.location.pathname = "/recent";
|
||||
env.location.search = "";
|
||||
env.window.scrollY = 0;
|
||||
// The new Home component exists while browser location still says /recent.
|
||||
env.api.restoreScroll("/?q=first");
|
||||
env.nextFrame();
|
||||
assert.deepEqual(env.scrollCalls, []);
|
||||
env.location.pathname = "/";
|
||||
env.location.search = "?q=first";
|
||||
env.flushFrames();
|
||||
assert.deepEqual(env.scrollCalls, [89]);
|
||||
});
|
||||
|
||||
test("a newer navigation cancels a pending restoration before its URL commits", () => {
|
||||
const env = setup();
|
||||
env.window.scrollY = 89;
|
||||
env.api.saveScroll("/");
|
||||
env.location.pathname = "/recent";
|
||||
env.location.search = "";
|
||||
env.api.restoreScroll("/?q=first");
|
||||
env.nextFrame();
|
||||
env.api.saveScroll("/recent");
|
||||
env.location.pathname = "/";
|
||||
env.location.search = "?q=first";
|
||||
env.flushFrames();
|
||||
assert.deepEqual(env.scrollCalls, []);
|
||||
});
|
||||
|
||||
test("releasing a dialog after route change does not restore focus or scroll into the old page", () => {
|
||||
const env = setup();
|
||||
const opener = new env.Element();
|
||||
opener.focus();
|
||||
new env.Dialog("photo");
|
||||
const handle = env.api.openDialog("photo", () => assert.fail("disposed callback invoked"));
|
||||
env.location.pathname = "/recent";
|
||||
env.location.search = "";
|
||||
env.api.releaseDialog(handle);
|
||||
env.flush();
|
||||
assert.equal(opener.focusCount, 1);
|
||||
assert.deepEqual(env.scrollCalls, []);
|
||||
assert.equal(env.history.backCalls, 0);
|
||||
});
|
||||
Reference in new issue
Block a user