Sync scene selection with URL
This commit is contained in:
34
src/main.js
34
src/main.js
@@ -14,6 +14,29 @@
|
||||
} = Matter;
|
||||
|
||||
const { scenes = [], defaultSceneId } = window.PhysilinksScenes || {};
|
||||
const getSceneById = (sceneId) =>
|
||||
scenes.find((candidate) => candidate.id === sceneId) || null;
|
||||
|
||||
const getSceneIdFromUrl = () => {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const urlScene = params.get("scene");
|
||||
return getSceneById(urlScene) ? urlScene : null;
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const setSceneIdInUrl = (sceneId) => {
|
||||
if (!sceneId) return;
|
||||
try {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set("scene", sceneId);
|
||||
history.replaceState({}, "", `${url.pathname}${url.search}${url.hash}`);
|
||||
} catch (err) {
|
||||
// ignore history failures (blocked or unsupported)
|
||||
}
|
||||
};
|
||||
|
||||
const config = {
|
||||
gravity: 1,
|
||||
@@ -80,8 +103,11 @@
|
||||
let boundaries = [];
|
||||
let rotators = [];
|
||||
let oscillators = [];
|
||||
let currentScene =
|
||||
scenes.find((s) => s.id === defaultSceneId) || scenes[0] || null;
|
||||
const initialSceneId =
|
||||
getSceneIdFromUrl() ||
|
||||
(getSceneById(defaultSceneId) ? defaultSceneId : null) ||
|
||||
scenes[0]?.id;
|
||||
let currentScene = getSceneById(initialSceneId) || scenes[0] || null;
|
||||
|
||||
if (currentScene && currentScene.config) {
|
||||
Object.assign(config, currentScene.config);
|
||||
@@ -131,9 +157,11 @@
|
||||
};
|
||||
|
||||
const applyScene = (sceneId) => {
|
||||
const next = scenes.find((s) => s.id === sceneId) || scenes[0];
|
||||
const next = getSceneById(sceneId) || scenes[0];
|
||||
if (!next) return;
|
||||
currentScene = next;
|
||||
ui.setSceneSelection(next.id);
|
||||
setSceneIdInUrl(next.id);
|
||||
const prevRadius = config.ballRadius;
|
||||
Object.assign(config, next.config);
|
||||
config.link = { ...next.config.link };
|
||||
|
||||
Reference in New Issue
Block a user