Fixing universe save/load logic

This commit is contained in:
2023-11-14 14:35:18 +01:00
parent 31f5afe64b
commit 04d4450555
9 changed files with 90 additions and 108 deletions

View File

@ -21,9 +21,9 @@ if (!self.define) {
const singleRequire = (uri, parentUri) => { const singleRequire = (uri, parentUri) => {
uri = new URL(uri + ".js", parentUri).href; uri = new URL(uri + ".js", parentUri).href;
return ( return registry[uri] || (
registry[uri] ||
new Promise((resolve) => { new Promise(resolve => {
if ("document" in self) { if ("document" in self) {
const script = document.createElement("script"); const script = document.createElement("script");
script.src = uri; script.src = uri;
@ -34,7 +34,9 @@ if (!self.define) {
importScripts(uri); importScripts(uri);
resolve(); resolve();
} }
}).then(() => { })
.then(() => {
let promise = registry[uri]; let promise = registry[uri];
if (!promise) { if (!promise) {
throw new Error(`Module ${uri} didnt register its module`); throw new Error(`Module ${uri} didnt register its module`);
@ -45,31 +47,27 @@ if (!self.define) {
}; };
self.define = (depsNames, factory) => { self.define = (depsNames, factory) => {
const uri = const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href;
nextDefineUri ||
("document" in self ? document.currentScript.src : "") ||
location.href;
if (registry[uri]) { if (registry[uri]) {
// Module is already loading or loaded. // Module is already loading or loaded.
return; return;
} }
let exports = {}; let exports = {};
const require = (depUri) => singleRequire(depUri, uri); const require = depUri => singleRequire(depUri, uri);
const specialDeps = { const specialDeps = {
module: { uri }, module: { uri },
exports, exports,
require, require
}; };
registry[uri] = Promise.all( registry[uri] = Promise.all(depsNames.map(
depsNames.map((depName) => specialDeps[depName] || require(depName)) depName => specialDeps[depName] || require(depName)
).then((deps) => { )).then(deps => {
factory(...deps); factory(...deps);
return exports; return exports;
}); });
}; };
} }
define(["./workbox-b7fccfec"], function (workbox) { define(['./workbox-b7fccfec'], (function (workbox) { 'use strict';
"use strict";
self.skipWaiting(); self.skipWaiting();
workbox.clientsClaim(); workbox.clientsClaim();
@ -79,44 +77,28 @@ define(["./workbox-b7fccfec"], function (workbox) {
* requests for URLs in the manifest. * requests for URLs in the manifest.
* See https://goo.gl/S9QRab * See https://goo.gl/S9QRab
*/ */
workbox.precacheAndRoute( workbox.precacheAndRoute([{
[ "url": "registerSW.js",
{ "revision": "3ca0b8505b4bec776b69afdba2768812"
url: "registerSW.js", }, {
revision: "3ca0b8505b4bec776b69afdba2768812", "url": "index.html",
}, "revision": "0.fnf2e5c80tg"
{ }], {});
url: "index.html",
revision: "0.0ufj7f4tmog",
},
],
{}
);
workbox.cleanupOutdatedCaches(); workbox.cleanupOutdatedCaches();
workbox.registerRoute( workbox.registerRoute(new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), {
new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), { allowlist: [/^\/$/]
allowlist: [/^\/$/], }));
}) workbox.registerRoute(({
); url
workbox.registerRoute( }) => [/^https:\/\/raw\.githubusercontent\.com\/.*/i, /^https:\/\/shabda\.ndre\.gr\/.*/i].some(regex => regex.test(url)), new workbox.CacheFirst({
({ url }) => "cacheName": "external-samples",
[ plugins: [new workbox.ExpirationPlugin({
/^https:\/\/raw\.githubusercontent\.com\/.*/i,
/^https:\/\/shabda\.ndre\.gr\/.*/i,
].some((regex) => regex.test(url)),
new workbox.CacheFirst({
cacheName: "external-samples",
plugins: [
new workbox.ExpirationPlugin({
maxEntries: 5000, maxEntries: 5000,
maxAgeSeconds: 2592000, maxAgeSeconds: 2592000
}), }), new workbox.CacheableResponsePlugin({
new workbox.CacheableResponsePlugin({ statuses: [0, 200]
statuses: [0, 200], })]
}), }), 'GET');
],
}), }));
"GET"
);
});
//# sourceMappingURL=sw.js.map //# sourceMappingURL=sw.js.map

File diff suppressed because one or more lines are too long

View File

@ -78,12 +78,18 @@ export class UserAPI {
} }
_loadUniverseFromInterface = (universe: string) => { _loadUniverseFromInterface = (universe: string) => {
this.app.selected_universe = universe.trim();
this.app.settings.selected_universe = universe.trim();
loadUniverse(this.app, universe as string); loadUniverse(this.app, universe as string);
openUniverseModal(); openUniverseModal();
}; };
_deleteUniverseFromInterface = (universe: string) => { _deleteUniverseFromInterface = (universe: string) => {
delete this.app.universes[universe]; delete this.app.universes[universe];
if (this.app.settings.selected_universe === universe) {
this.app.settings.selected_universe = "Welcome";
this.app.selected_universe = "Welcome";
}
this.app.settings.saveApplicationToLocalStorage( this.app.settings.saveApplicationToLocalStorage(
this.app.universes, this.app.universes,
this.app.settings this.app.settings

View File

@ -1,4 +1,4 @@
import { tutorial_universe } from "./universes/tutorial"; // import { tutorial_universe } from "./universes/tutorial";
import { gzipSync, decompressSync, strFromU8 } from "fflate"; import { gzipSync, decompressSync, strFromU8 } from "fflate";
import { examples } from "./examples/excerpts"; import { examples } from "./examples/excerpts";
import { type Editor } from "./main"; import { type Editor } from "./main";
@ -109,7 +109,7 @@ export const template_universes = {
example: { candidate: "", committed: "", evaluations: 0 }, example: { candidate: "", committed: "", evaluations: 0 },
notes: { candidate: "" }, notes: { candidate: "" },
}, },
Help: tutorial_universe, //Help: tutorial_universe,
}; };
export class AppSettings { export class AppSettings {
@ -247,14 +247,22 @@ export const initializeSelectedUniverse = (app: Editor): void => {
*/ */
if (app.settings.load_demo_songs) { if (app.settings.load_demo_songs) {
let random_example = examples[Math.floor(Math.random() * examples.length)]; let random_example = examples[Math.floor(Math.random() * examples.length)];
app.selected_universe = "Welcome"; app.selected_universe = "Demo";
app.universes[app.selected_universe] = structuredClone(template_universe);
app.universes[app.selected_universe].global.committed = random_example; app.universes[app.selected_universe].global.committed = random_example;
app.universes[app.selected_universe].global.candidate = random_example; app.universes[app.selected_universe].global.candidate = random_example;
} else { } else {
try {
app.selected_universe = app.settings.selected_universe; app.selected_universe = app.settings.selected_universe;
if (app.universes[app.selected_universe] === undefined) if (app.universes[app.selected_universe] === undefined)
app.universes[app.selected_universe] =
structuredClone(template_universe);
} catch (error) {
app.settings.selected_universe = "Welcome";
app.selected_universe = app.settings.selected_universe;
app.universes[app.selected_universe] = structuredClone(template_universe); app.universes[app.selected_universe] = structuredClone(template_universe);
} }
}
app.interface.universe_viewer.innerHTML = `Topos: ${app.selected_universe}`; app.interface.universe_viewer.innerHTML = `Topos: ${app.selected_universe}`;
}; };
@ -315,22 +323,20 @@ export const loadUniverse = (
universeName: string, universeName: string,
universe: Universe = template_universe universe: Universe = template_universe
): void => { ): void => {
console.log(universeName, universe);
app.currentFile().candidate = app.view.state.doc.toString();
// Getting the new universe name and moving on
let selectedUniverse = universeName.trim(); let selectedUniverse = universeName.trim();
if (app.universes[selectedUniverse] === undefined) { if (app.universes[selectedUniverse] === undefined) {
app.settings.universes[selectedUniverse] = universe; // Pushing a freshly cloned template universe to:
app.universes[selectedUniverse] = universe; // 1) the current session 2) the settings
const freshUniverse = structuredClone(universe);
app.universes[selectedUniverse] = freshUniverse;
app.settings.universes[selectedUniverse] = freshUniverse;
} }
// Updating references to the currently selected universe
app.settings.selected_universe = selectedUniverse;
app.selected_universe = selectedUniverse; app.selected_universe = selectedUniverse;
app.settings.selected_universe = app.selected_universe;
app.interface.universe_viewer.innerHTML = `Topos: ${selectedUniverse}`; app.interface.universe_viewer.innerHTML = `Topos: ${selectedUniverse}`;
// Updating the editor View to reflect the selected universe // Updating the editor View to reflect the selected universe
app.updateEditorView(); app.updateEditorView();
// Evaluating the initialisation script for the selected universe // Evaluating the initialisation script for the selected universe
tryEvaluate(app, app.universes[app.selected_universe.toString()].init); tryEvaluate(app, app.universes[app.selected_universe.toString()].init);
}; };

View File

@ -23,6 +23,7 @@ import { inlineHoveringTips } from "./documentation/inlineHelp";
import { lineNumbers } from "@codemirror/view"; import { lineNumbers } from "@codemirror/view";
import { jsCompletions } from "./EditorSetup"; import { jsCompletions } from "./EditorSetup";
import { createDocumentationStyle } from "./DomElements"; import { createDocumentationStyle } from "./DomElements";
import { saveState } from "./WindowBehavior";
export const installInterfaceLogic = (app: Editor) => { export const installInterfaceLogic = (app: Editor) => {
// Initialize style // Initialize style
@ -184,8 +185,8 @@ export const installInterfaceLogic = (app: Editor) => {
app.interface.load_universe_button.addEventListener("click", () => { app.interface.load_universe_button.addEventListener("click", () => {
let query = (app.interface.buffer_search as HTMLInputElement).value; let query = (app.interface.buffer_search as HTMLInputElement).value;
if (query.length > 2 && query.length < 20 && !query.includes(" ")) { if (query.length > 2 && query.length < 20 && !query.includes(" ")) {
loadUniverse(app, query);
app.settings.selected_universe = query; app.settings.selected_universe = query;
loadUniverse(app, query);
(app.interface.buffer_search as HTMLInputElement).value = ""; (app.interface.buffer_search as HTMLInputElement).value = "";
closeUniverseModal(); closeUniverseModal();
app.view.focus(); app.view.focus();
@ -336,6 +337,7 @@ export const installInterfaceLogic = (app: Editor) => {
}); });
app.interface.close_universes_button.addEventListener("click", () => { app.interface.close_universes_button.addEventListener("click", () => {
saveState(app);
openUniverseModal(); openUniverseModal();
}); });
@ -443,8 +445,10 @@ export const installInterfaceLogic = (app: Editor) => {
if (universeName) { if (universeName) {
if (universeName.length > 2 && universeName.length < 20) { if (universeName.length > 2 && universeName.length < 20) {
loadUniverse(app, universeName); universeName = universeName.trim();
app.settings.selected_universe = universeName; app.settings.selected_universe = universeName;
app.selected_universe = universeName;
loadUniverse(app, universeName);
(app.interface.buffer_search as HTMLInputElement).value = ""; (app.interface.buffer_search as HTMLInputElement).value = "";
closeUniverseModal(); closeUniverseModal();
app.view.focus(); app.view.focus();

View File

@ -68,22 +68,4 @@ export const installWindowBehaviors = (
false false
); );
} }
window.addEventListener(
"error",
(e) => {
console.log("Je suis bien installé !");
console.log(
e.message,
"\n",
e.filename,
":",
e.lineno,
e.colno ? ":" + e.colno : "",
e.error && e.error.stack ? "\n" : "",
e.error ? e.error.stack : undefined
);
},
false
);
}; };

View File

@ -20,7 +20,7 @@ import * as oeis from "jisg";
import * as zpatterns from "zifferjs/src/patterns.ts"; import * as zpatterns from "zifferjs/src/patterns.ts";
import { makeArrayExtensions } from "./extensions/ArrayExtensions"; import { makeArrayExtensions } from "./extensions/ArrayExtensions";
import "./style.css"; import "./style.css";
import { Universes, File, template_universes } from "./FileManagement"; import { Universes, File } from "./FileManagement";
import { tryEvaluate } from "./Evaluator"; import { tryEvaluate } from "./Evaluator";
// @ts-ignore // @ts-ignore
import showdown from "showdown"; import showdown from "showdown";
@ -39,7 +39,7 @@ if ("serviceWorker" in navigator) {
export class Editor { export class Editor {
// Universes and settings // Universes and settings
settings: AppSettings = new AppSettings(); settings: AppSettings = new AppSettings();
universes: Universes = template_universes; universes: Universes = {};
selected_universe: string = "Welcome"; selected_universe: string = "Welcome";
fill: boolean = false; fill: boolean = false;
@ -115,7 +115,7 @@ export class Editor {
this.universes = { this.universes = {
...this.settings.universes, ...this.settings.universes,
...template_universes, //...template_universes,
}; };
initializeSelectedUniverse(this); initializeSelectedUniverse(this);
@ -237,7 +237,7 @@ export class Editor {
list.append( list.append(
...Object.keys(this.universes).map((it) => { ...Object.keys(this.universes).map((it) => {
let item = itemTemplate.content.cloneNode(true) as DocumentFragment; let item = itemTemplate.content.cloneNode(true) as DocumentFragment;
let api = window as unknown as UserAPI; // It's dirty but okey let api = window as unknown as UserAPI;
item.querySelector(".universe-name")!.textContent = it; item.querySelector(".universe-name")!.textContent = it;
item item
.querySelector(".load-universe") .querySelector(".load-universe")

View File

@ -61,7 +61,7 @@ const init_buffer = `// ,,
// be available from the start. It is only executed once, so if you want to change something, you need to // be available from the start. It is only executed once, so if you want to change something, you need to
// reload the universe or force the reloading: Ctrl+Shift+Enter. // reload the universe or force the reloading: Ctrl+Shift+Enter.
bpm(140) // set the bpm to 140 tempo(140) // set the bpm to 140
`; `;
const note_buffer = `# Notes const note_buffer = `# Notes

View File

@ -28,9 +28,11 @@ const vitePWAconfiguration = {
enabled: true, enabled: true,
}, },
workbox: { workbox: {
sourcemap: true, sourcemap: false,
cleanupOutdatedCaches: true, cleanupOutdatedCaches: true,
globPatterns: ["**/*.{js,css,html,gif,png,json,woff,json,ogg,wav,mp3,ico,png,svg}"], globPatterns: [
"**/*.{js,css,html,gif,png,json,woff,json,ogg,wav,mp3,ico,png,svg}",
],
// Thanks Froos :) // Thanks Froos :)
runtimeCaching: [ runtimeCaching: [
{ {
@ -39,9 +41,9 @@ const vitePWAconfiguration = {
/^https:\/\/raw\.githubusercontent\.com\/.*/i, /^https:\/\/raw\.githubusercontent\.com\/.*/i,
/^https:\/\/shabda\.ndre\.gr\/.*/i, /^https:\/\/shabda\.ndre\.gr\/.*/i,
].some((regex) => regex.test(url)), ].some((regex) => regex.test(url)),
handler: 'CacheFirst', handler: "CacheFirst",
options: { options: {
cacheName: 'external-samples', cacheName: "external-samples",
expiration: { expiration: {
maxEntries: 5000, maxEntries: 5000,
maxAgeSeconds: 60 * 60 * 24 * 30, // <== 14 days maxAgeSeconds: 60 * 60 * 24 * 30, // <== 14 days