Skip to content

Instantly share code, notes, and snippets.

@yiwenl
Last active March 16, 2022 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yiwenl/334b929dc32aead20d48036bb649946a to your computer and use it in GitHub Desktop.
Save yiwenl/334b929dc32aead20d48036bb649946a to your computer and use it in GitHub Desktop.
// add any configs you like
export default {
value:0.5,
autoSave: false,
};
import * as dat from "dat.gui";
import Config from "../Config";
import Settings from "../Settings";
import { saveJson } from "./";
export default () => {
const { refresh, reload } = Settings;
const oControl = {
save: () => {
saveJson(Config, "Settings");
},
};
const gui = new dat.GUI({ width: 300 });
gui.add(Config, 'value', 0, 1).onFinishChange(refresh);
gui.add(Config, "autoSave").onFinishChange(reload);
gui.add(oControl, "save").name("Save Settings");
gui.add(Settings, "reset").name("Reset Default");
};
// saveJson.js
const saveJson = (obj, mName = "data", mPretty = true) => {
var str = mPretty ? JSON.stringify(obj, null, 4) : JSON.stringify(obj);
var data = encode(str);
var blob = new Blob([data], {
type: "application/octet-stream",
});
var url = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", `${mName}.json`);
var event = document.createEvent("MouseEvents");
event.initMouseEvent(
"click",
true,
true,
window,
1,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null
);
link.dispatchEvent(event);
};
const encode = (s) => {
var out = [];
for (var i = 0; i < s.length; i++) {
out[i] = s.charCodeAt(i);
}
return new Uint8Array(out);
};
export { saveJson };
// Settings.js
import Config from "./Config";
import parse from "url-parse";
let enabled = true;
const reload = () => {
if (!enabled) {
return;
}
window.location.href =
window.location.origin +
window.location.pathname +
"?config=" +
JSON.stringify(Config);
};
const refresh = () => {
if (!enabled) {
return;
}
window.history.pushState(
"experiment",
"Title",
window.location.origin +
window.location.pathname +
"?config=" +
JSON.stringify(Config)
);
};
const reset = () => {
window.location.href = window.location.origin + window.location.pathname;
};
let delayIndex = -1;
const delayReload = () => {
if (!enabled) {
return;
}
window.clearTimeout(delayIndex);
delayIndex = window.setTimeout(() => {
window.location.href =
window.location.origin +
window.location.pathname +
"?config=" +
JSON.stringify(Config);
}, 500);
};
const init = (mEnabled = true) => {
enabled = mEnabled;
const parsed = parse(window.location.search, true);
let parsedJson = {};
if (parsed.query.config) {
parsedJson = JSON.parse(parsed.query.config);
}
Object.assign(Config, parsedJson);
refresh();
};
export default {
enabled,
reload,
reset,
refresh,
delayReload,
init,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment