IntCyoaEnhancer

QoL improvements for CYOAs made in IntCyoaCreator

  1. // ==UserScript==
  2. // @name IntCyoaEnhancer
  3. // @namespace https://agregen.gitlab.io/
  4. // @version 0.5.3
  5. // @description QoL improvements for CYOAs made in IntCyoaCreator
  6. // @author agreg
  7. // @license MIT
  8. // @match https://*.neocities.org/*
  9. // @match https://intcyoacreator.onrender.com/*
  10. // @icon https://intcyoacreator.onrender.com/favicon.ico?
  11. // @run-at document-start
  12. // @require https://unpkg.com/mreframe/dist/mreframe.js
  13. // @require https://unpkg.com/lz-string/libs/lz-string.js
  14. // @require https://greasyfork.org/scripts/441035-json-edit/code/Json%20edit.js?version=1025094
  15. // @require https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/prism.min.js
  16. // @require https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/components/prism-json.min.js
  17. // @require https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/plugins/match-braces/prism-match-braces.min.js
  18. // @grant unsafeWindow
  19. // @grant GM_registerMenuCommand
  20. // @grant GM_addStyle
  21. // ==/UserScript==
  22.  
  23. (function() {
  24. 'use strict';
  25.  
  26. // overriding AJAX sender (before the page starts loading) to detect project.json download done at init time
  27. let init, enhance, ready, _XHR = unsafeWindow.XMLHttpRequest;
  28. unsafeWindow.XMLHttpRequest = class XHR extends _XHR {
  29. constructor () {
  30. super();
  31. let _open = this.open;
  32. this.open = (...args) => {
  33. if ((`${args[0]}`.toUpperCase() === "GET") && (`${args[1]}`.match(/^project.json$|^js\/app\.\w*\.js$/))) {
  34. init(() => this.addEventListener('loadend', () => ready.then(() => setTimeout(enhance))));
  35. // displaying loading indicator if not present already (as a mod)
  36. if (!document.getElementById('indicator')) {
  37. let _indicator = document.createElement('div'), NBSP = '\xA0';
  38. _indicator.style = `position: fixed; top: 0; left: 0; z-index: 1000`;
  39. _indicator.title = args[1];
  40. document.body.prepend(_indicator);
  41. this.addEventListener('progress', e => {
  42. _indicator.innerText = NBSP + "Loading data: " + (!e.total ? `${(e.loaded/1024**2).toFixed(1)} MB` :
  43. `${(100 * e.loaded / e.total).toFixed(2)}%`);
  44. });
  45. this.addEventListener('loadend', () => {_indicator.innerText = ""});
  46. }
  47. }
  48. return _open.apply(this, args);
  49. };
  50. }
  51. };
  52.  
  53. init = (thunk=enhance) => {!init.done && (console.log("IntCyoaEnhancer!"), init.done = true, thunk())};
  54. (ready = new Promise(resolve => document.addEventListener('readystatechange', () => (document.readyState == 'complete') && resolve())))
  55. .then(() => ['activated', 'rows', 'pointTypes'].every(k => k in app.__vue__.$store.state.app) && init());
  56.  
  57. enhance = () => {
  58. const CREATOR = (location.hostname == 'intcyoacreator.onrender.com');
  59. let {isArray} = Array, isJson = x => (typeof x === 'string') && x.trim().match(/^{.*}$/); // minimal check
  60. let {assign, keys, values, entries, fromEntries} = Object;
  61. let range = n => Array.from({length: n}, (_, i) => i);
  62. let times = (n, f) => range(n).forEach(f);
  63. let _lazy = assign(thunk => {let _ = () => (_lazy._cache.has(_) || _lazy._cache.set(_, thunk()), _lazy._cache.get(_));
  64. return _;}, {_cache: new Map()});
  65. let _try = (thunk, fallback, quiet=false) => {try {return thunk()} catch (e) {quiet||console.error(e); return fallback}};
  66. let _prompt = (message, value) => {let s = prompt(message, (typeof value == 'string' ? value : JSON.stringify(value)));
  67. return new Promise(resolve => (s != null) && resolve(s))};
  68. let _node = (tag, attr, ...children) => {
  69. let node = assign(document.createElement(tag), attr);
  70. children.forEach(child => {node.append(isArray(child) ? _node(...child) : document.createTextNode(`${child||""}`))});
  71. return node;
  72. };
  73. let _debounce = (thunk, msec) => function $debounce () {
  74. clearTimeout($debounce.delay);
  75. $debounce.delay = setTimeout(() => {
  76. $debounce.delay = null;
  77. thunk();
  78. }, msec);
  79. };
  80. let $editor = $jsonEdit.createEditorModal('PROMPT');
  81. document.body.append($editor);
  82. GM_addStyle(`#PROMPT button {width:auto; background:darkgray; padding:0 1ex; border-radius:1ex}
  83. #PROMPT .editor pre {padding:0 !important}`);
  84. let validator = s => !s || _decode(s);
  85. let _edit = (message, value, {json=false}={}) => $editor[json ? 'editAsJson' : 'editText'](value, {title: message, validator});
  86.  
  87. // title & savestate are stored in URL hash
  88. let _hash = _try(() => `["${decodeURIComponent( location.hash.slice(1) )}"]`); // it's a JSON array of 2 strings, without '["' & '"]' parts
  89. let $save = [], [$title="", $saved="", $snapshot=""] = _try(() => JSON.parse(CREATOR ? "[]" : _hash), []);
  90. let _encode = o => LZString.compressToBase64(isJson(o) ? o : JSON.stringify(o)),
  91. _decode = s => (isJson(s) ? JSON.parse(s) : JSON.parse(LZString.decompressFromBase64(s) || (_ => {throw Error("Invalid input")})()));
  92. let $updateUrl = ({title=$title, save=$save, snapshot=$snapshot}={}, url=new URL(location)) => CREATOR ||
  93. location.replace(assign(url, {hash: JSON.stringify([title, ...(!snapshot ? [$saved=save.join(",")] : ["", snapshot])]).slice(2, -2)}));
  94. // app state accessors
  95. let $store = () => app.__vue__.$store, $state = () => $store().state.app;
  96. let $pointTypes = () => $state().pointTypes, $rows = () => $state().rows;
  97. let $items = _lazy(() => [].concat( ...$rows().map(row => row.objects) ));
  98. let $hiddenActive = _lazy(() => $items().filter(item => item.isSelectableMultiple || item.isImageUpload));
  99. let $itemsMap = _lazy((m = new Map()) => ($items().forEach(item => m.set(item.id, item)), m)), $getItem = id => $itemsMap().get(id);
  100. let _fatKeys = x => ['backgroundImage', 'rowBackgroundImage', 'objectBackgroundImage'].concat(x.isImageUpload ? [] : ['image']);
  101. let _slim = x => x && (typeof x !== 'object' ? x : isArray(x) ? x.map(_slim) :
  102. assign({}, x, ..._fatKeys(x).map(k => ({[k]: void 0})),
  103. ...keys(x).filter(k => typeof x[k] === 'object').map(k => x[k] && ({[k]: _slim(x[k])}))));
  104. let $slimStateCopy = (state=$state()) => $clone( _slim(state) );
  105. try {$store()} catch (e) {console.error(e); throw Error("[IntCyoaEnhancer] Can't access app state!", {cause: e})}
  106.  
  107. let _bugfix = () => {
  108. $rows().forEach(row => {delete row.allowedChoicesChange}); // This is a runtime variable, why is it exported?! It breaks reset!
  109. [...document.querySelectorAll('*')].map(x => x.__vue__).filter(x => x && ('posOrNeg' in x))
  110. .forEach(x => {x.posOrNeg = (x.score.value < 0)}); // Score captions only calculate this when created
  111. };
  112.  
  113. // logic taken from IntCyoaCreator as it appears to be hardwired into a UI component
  114. let _selectedMulti = (item, num) => { // selecting a multi-value
  115. let counter = 0, sign = Math.sign(num);
  116. let _timesCmp = n => (sign < 0 ? item.numMultipleTimesMinus < n : item.numMultipleTimesPluss > n);
  117. let _useMulti = () => _timesCmp(counter) && (item.multipleUseVariable = counter += sign, true);
  118. let _addPoints = () => $pointTypes().filter(points => points.id == item.multipleScoreId).every(points =>
  119. _timesCmp(points.startingSum) && (item.multipleUseVariable = points.startingSum += sign, true));
  120. times(Math.abs(num), _ => {
  121. if ((item.isMultipleUseVariable ? _useMulti() : _addPoints()))
  122. item.scores.forEach(score => $pointTypes().filter(points => points.id == score.id)
  123. .forEach(points => {points.startingSum -= sign * parseInt(score.value)}));
  124. });
  125. };
  126. let _loadSave = save => { // applying a savestate
  127. let _isHidden = s => s.includes("/ON#") || s.includes("/IMG#");
  128. let tokens = save.split(','), activated = tokens.filter(s => s && !_isHidden(s)), hidden = tokens.filter(_isHidden);
  129. let _split = (sep, item, token, fn, [id, arg]=token.split(sep, 2)) => {(id == item.id) && fn(arg)};
  130. $store().commit({type: 'cleanActivated'}); // hopefully not broken…
  131. $items().forEach(item => {
  132. if (item.isSelectableMultiple)
  133. hidden.forEach(token => _split("/ON#", item, token, num => _selectedMulti(item, parseInt(num))));
  134. else if (item.isImageUpload)
  135. hidden.forEach(token => _split("/IMG#", item, token, img => {item.image = img.replaceAll("/CHAR#", ",")}));
  136. });
  137. //$store().commit({type: 'addNewActivatedArray', newActivated: activated}); // not all versions have this :-(
  138. let _activated = new Set(activated), _isActivated = id => _activated.has(id);
  139. $state().activated = activated;
  140. $rows().forEach(row => { // yes, four-level nested loop is how the app does everything
  141. row.isEditModeOn = false;
  142. delete row.allowedChoicesChange; // bugfix: cleanActivated is supposed to do this… but it doesn't
  143. row.objects.filter(item => _isActivated(item.id)).forEach(item => {
  144. item.isActive = true;
  145. row.currentChoices += 1;
  146. item.scores.forEach(score => $pointTypes().filter(points => points.id == score.id).forEach(points => {
  147. if (!score.requireds || (score.requireds.length <= 0) || $store().getters.checkRequireds(score)) {
  148. score.isActive = true;
  149. points.startingSum -= parseInt(score.value);
  150. }
  151. }));
  152. });
  153. });
  154. };
  155. // these are used for generating savestate
  156. let _isActive = item => item && (item.isActive || (item.isImageUpload && item.image) || (item.isSelectableMultiple && (item.multipleUseVariable !== 0)));
  157. let _activeId = item => (!_isActive(item) ? null : item.id + (item.isImageUpload ? `/IMG#${item.image.replaceAll(",", "/CHAR#")}` :
  158. item.isSelectableMultiple ? `/ON#${item.multipleUseVariable}` : ""));
  159. //let _activated = () => $items().map(_activeId).filter(Boolean); // this is how the app calculates it (selection order seems to be ignored)
  160.  
  161. let $hiddenActivated = () => $hiddenActive().filter(_isActive).map(item => item.id); // images and multi-vals are excluded from state
  162. $store().watch(state => state.app.activated.filter(Boolean).concat( $hiddenActivated() ), // activated is formed incorrectly and may contain ""
  163. ids => {$save = ids.map($getItem).filter(Boolean).map(_activeId), $updateUrl()}); // compared to the app """optimization""" this is blazing fast
  164.  
  165. let diff = initial => (current=$slimStateCopy(), cheat=$cheat.data) => {
  166. let _cheat = (function $slim (o) {
  167. if (!o || isArray(o) || (typeof o != 'object')) return o;
  168. let kvs = entries(o).filter(([k, v]) => $slim(v));
  169. return (kvs.length == 0 ? void 0 : fromEntries(kvs));
  170. })(cheat);
  171. return (function $diff (a, b/*, ...path*/) {
  172. if ((typeof a !== typeof b) || (isArray(a) !== isArray(b)) || (isArray(a) && (a.length !== b.length)))
  173. return b;
  174. else if (a && b && (typeof a === 'object')) {
  175. let res = entries(b).map(([k, v]) => [k, $diff(a[k], v/*, ...path, k*/)]).filter(([k, v]) => v !== void 0);
  176. if (res.length > 0) return fromEntries(res);
  177. } else if (a === a ? a !== b : b === b)
  178. return b;
  179. })(initial(), {_cheat, ...current}) || {};
  180. };
  181. let restoreSnapshot = initial => (snapshot=$snapshot) => _try(() => {
  182. let {reFrame: rf, util: {getIn, assoc, isArray, isDict, keys}} = require('mreframe');
  183. let {_cheat, ..._state} = (typeof snapshot !== 'string' ? snapshot : _decode(snapshot||"{}"));
  184. let newState = (function $deepMerge (a, b) {
  185. return (!isDict(b) ? a : keys(b).reduce((o, k) => ((o[k] = (!isDict(b[k]) ? b[k] : $deepMerge(a[k], b[k]))), o), a));
  186. })($clone(initial()), _state);
  187. (function $updState (a, x/*, ...path*/) {
  188. a && (typeof a == 'object') && keys(a).forEach(k => {
  189. isArray(a[k]) && (x[k] = (!isArray(x[k]) ? a[k] : x[k].slice(0, a[k].length).concat( a[k].slice(x[k].length) )));
  190. (!(k in x) || (typeof a[k] != 'object') ? x[k] = a[k] : $updState(a[k], x[k]/*, ...path, k*/));
  191. });
  192. isDict(x) && keys(x).filter(k => !(k in a) && !_fatKeys(x).includes(k)).forEach(k => {delete x[k]});
  193. })(newState, $state());
  194. (_cheat || $cheat.toggle) && ($cheat.toggle || $cheat(), rf.disp(['init-db', $cheat.data = _cheat]));
  195. _bugfix();
  196. $snapshot = _encode({_cheat, ..._state});
  197. $updateUrl();
  198. return true;
  199. }) || alert("State load failed. (Possible reason: invalid state snapshot.)");
  200.  
  201. // debug functions for console
  202. let $activated = () => $state().activated, $clone = x => JSON.parse(JSON.stringify(x));
  203. let $rowsActive = () => $rows().map(row => [row, row.objects.filter(_isActive)]).filter(([_, items]) => items.length > 0);
  204. let $dbg = {$store, $state, $pointTypes, $rows, $items, $getItem, $activated, $hiddenActivated, $rowsActive, $clone, $slimStateCopy};
  205. Object.assign(unsafeWindow, {$dbg}, $dbg);
  206.  
  207. // init && menu
  208. _bugfix();
  209. CREATOR || ["project.json", document.querySelector(`link[href^="js/app."][href$=".js"]`)?.href, `${location}`]
  210. .reduce((p, s) => p.catch(_ => fetch(s, {method: 'HEAD'})), Promise.reject()).then(x => x.headers.get('last-modified'))
  211. .then(s => {document.querySelector('.v-bottom-navigation').title = `Version: ${new Date(s || document.lastModified).toJSON()}`});
  212. let _title = document.title, _initial = _lazy($slimStateCopy), _restore = restoreSnapshot(_initial), _diff = diff(_initial);
  213. assign(unsafeWindow, {$initial: () => JSON.stringify(_initial()).length, $diff: _diff, $encode: _encode, $decode: _decode, $bugfix: _bugfix});
  214. $title && (document.title = $title);
  215. ($saved||$snapshot) && confirm("Load state from URL?") && setTimeout(() => !$snapshot ? _loadSave($saved) : _restore($snapshot));
  216. let _syncSnapshot = _debounce(() => {$snapshot = (CREATOR ? JSON.stringify : _encode)(_diff()), $updateUrl()}, 1000);
  217. let $watch = (snapshot=($snapshot ? "" : _encode( _diff() ))) => {
  218. document.body.classList[snapshot ? 'add' : 'remove']('-FULL-SCAN');
  219. $snapshot = snapshot;
  220. $watch.stop = $watch.stop && ($watch.stop(), null);
  221. snapshot && ($watch.stop = $store().watch(x => x, _syncSnapshot, {deep: true}));
  222. $updateUrl();
  223. };
  224. CREATOR && ($snapshot = "{}");
  225. $snapshot && $watch($snapshot);
  226. CREATOR || GM_registerMenuCommand("Change webpage title", () =>
  227. _prompt("Change webpage title (empty to default)", $title||document.title).then(s => {document.title = ($title = s) || _title; $updateUrl()}));
  228. GM_registerMenuCommand("Edit state", () => _edit("Edit state (empty to reset)", (!$snapshot ? $saved : _decode($snapshot)), {json: $snapshot})
  229. .then(!$snapshot ? _loadSave : _restore));
  230. if (CREATOR) {
  231. let reset$ = () => {console.warn("Enhancer cache reset!"); _lazy._cache.clear(); $snapshot = "{}"};
  232. $store().subscribe(console.debug);
  233. $store().subscribe(x => (x.type == 'loadApp') && reset$()); // when loading state from file
  234. new MutationObserver(function _ () { // when opening the View mode
  235. [_._old, _._screen] = [_._screen, app.__vue__.$children[0]?.$vnode.tag.replace(/.*-/, "")];
  236. document.getElementById('LIST-TOGGLE').style.display = (_._screen === 'appImageCyoaViewer' ? '' : 'none');
  237. (_._screen != _._old) && (_._screen === 'appImageCyoaViewer') && reset$();
  238. }).observe(app, {childList: true});
  239. } else {
  240. GM_registerMenuCommand("Toggle full scan mode", () => $watch());
  241. GM_registerMenuCommand("Download project data", () => assign(document.createElement('a'), {
  242. download: "project.json", href: `data:application/json,${encodeURIComponent(JSON.stringify($state()) + "\n")}`,
  243. }).click());
  244. ($state().backpack.length == 0) && GM_registerMenuCommand("Enable backpack", function $addBackpack(prefix) {
  245. _prompt([prefix, "How many choices should be displayed in a row? (1-4)"].filter(Boolean).join("\n"), "3").then(num =>
  246. (!["1", "2", "3", "4"].includes(num) ? setTimeout(() => $addBackpack(`Sorry, ${JSON.stringify(num)} is not a valid column number.`)) :
  247. ($state().backpack = [{title: "Selected choices", titleText: "", template: "1", isInfoRow: true, isResultRow: true,
  248. objectWidth: `col-md-${{1: 12, 2: 6, 3: 4, 4: 3}[num]}`}])));
  249. });
  250. }
  251.  
  252. let $overview = () => {
  253. if ($overview.toggle)
  254. $overview.toggle();
  255. else {
  256. const _ID = 'LIST', ID = '#'+_ID, _scroll = (s, bg='#2B2F35', thumb='grey', wk='::-webkit-scrollbar') =>
  257. `${s} {scrollbar-width:thin; scrollbar-color:${thumb} ${bg}} ${s}${wk} {width:6px; height:6px; background:${bg}} ${s}${wk}-thumb {background:${thumb}}`;
  258. GM_addStyle(`${ID} {position:fixed; top:0; left:0; height:100%; width:100%; background:#0008; z-index:1001}
  259. ${ID} img {position:fixed; top:0; max-height:40%; object-fit:contain; background:#000B}
  260. ${ID} .-nav .-row-name {cursor:pointer; padding:2px 1ex} ${ID} .-nav .-row-name:hover {background:var(--gray)}
  261. ${ID} .-item-name {font-weight:bold} ${ID} .-dialog :is(.-row-name, .-item):hover {cursor:help; text-shadow:0 0 10px}
  262. ${ID} .-roll :is(input, button) {width:2.5em; color:black; background:var(--light)}
  263. ${ID} .-roll button {border-radius:2ex} ${ID} input[type=number] {text-align:right} ${ID} input:invalid {background:var(--red)}` +
  264. [[" .-roll", "0", "20%", "#0008"], [" .-dialog", "20%", "60%", "var(--dark)"], [" .-nav", "80%", "20%", "#0008"]].map(([k, left, width, bg]) =>
  265. `${ID}${k} {position:fixed; top:40%; left:${left}; height:calc(60% - 56px); width:${width}; color:var(--light); background:${bg};
  266. padding:1em; overflow-y:auto} ${_scroll(ID+k)}`).join("\n"));
  267. document.body.append($overview.overlay = _node('div', {id: _ID, onclick: $overview}));
  268. $overview.overlay.append($overview.image = _node('img'));
  269. $overview.overlay.append($overview.activated = _node('div', {className: '-dialog', title: "Activated items", onclick: e => e.stopPropagation()}));
  270. $overview.overlay.append($overview.nav = _node('div', {className: '-nav', title: "Navigation (visible rows)", onclick: e => e.stopPropagation()}));
  271. $overview.overlay.append($overview.roll = _node('div', {className: '-roll', title: "Dice roll", onclick: e => e.stopPropagation()}));
  272. document.addEventListener('keydown', e => (e.key == 'Escape') && $overview.toggle(true));
  273. let _points = fromEntries( $pointTypes().map(points => [points.id, `[${points.id}] `+ (points.beforeText || `(${points.name})`)]) );
  274. let _ptReqOp = {1: ">", 2: "≥", 3: "=", 4: "≤", 5: "<"}, _ptReqCmpOp = {1: ">", 2: "=", 3: "≥"};
  275. let _req = score => x => (x.required ? "" : "NOT!") + ({id: x.reqId||"?", points: `${x.reqId||"?"} ${_ptReqOp[x.operator]} ${x.reqPoints}`,
  276. pointCompare: `${x.reqId||"?"} ${_ptReqCmpOp[x.operator]} ${x.reqId1||"?"}`})[x.type] || "???";
  277. let _cost = score => " " + (_points[score.id] || `"${score.beforeText}"`) + (score.value > 0 ? " " : " +") + (-parseInt(score.value||0)) +
  278. ((score.requireds||[]).length == 0 ? "" : "\t{" + score.requireds.map(_req(score)).join(" & ") + "}");
  279. let _showImg = ({image}) => () => ($overview.image.src = image) && ($overview.image.style.display = '');
  280. let _hideImg = () => {[$overview.image.src, $overview.image.style.display] = ["", 'none']};
  281. let _rowAttrs = row => ({className: '-row-name', title: `[${row.id}]\n\n${row.titleText}`.trim(), onmouseenter: _showImg(row), onmouseleave: _hideImg});
  282. let _nav = e => () => {$overview.toggle(true); e.scrollIntoView({block: 'start'})};
  283. let _dice = [1, 6, 0], _roll = (n, m, k) => (_dice = [n, m, k, range(n).reduce(res => res + Math.floor(1 + m*Math.random()), k)], _dice[3]);
  284. let _setDice = idx => function () {this.value = parseInt(this.value)||_dice[idx]; _dice.splice(idx, 1, this.valueAsNumber)};
  285. $overview.toggle = (visible = !$overview.overlay.style.display) => {
  286. if (!visible) {
  287. $overview.roll.innerHTML = "<h3>Roll</h3>";
  288. $overview.roll.append( _node('div', {},
  289. ['p', {}, ['input', {type: 'number', title: "N", min: 1, value: _dice[0], onchange: _setDice(0)}], " d ",
  290. ['input', {type: 'number', title: "M", min: 2, value: _dice[1], onchange: _setDice(1)}], " + ",
  291. ['input', {type: 'number', title: "K", value: _dice[2], onchange: _setDice(2)}], " = ",
  292. ['button', {title: "ROLL", onclick () {this.innerText = _roll(..._dice)}}, `${_dice.length < 4 ? "(roll)" : _dice[3]}`]],
  293. "(NdM+K means rolling an M-sided die N times and adding K to the total)") );
  294. $overview.nav.innerHTML = "<h3>Navigation</h3>";
  295. [...document.querySelectorAll(["* > .row", "*"].map(s => `.v-application--wrap > ${s} > :not(.v-bottom-navigation) > div:not(.col)`).join(", "))]
  296. .filter(e => !e.style.display).map(e => [e, e.__vue__._props.row])
  297. .forEach(([e, row]) => {$overview.nav.append( _node('div', {..._rowAttrs(row), onclick: _nav(e)}, row.title.trim() || ['i', {}, row.id]) )});
  298. $overview.activated.innerHTML = "<h3>Activated</h3>";
  299. $rowsActive().forEach(([row, items]) => {
  300. $overview.activated.append( _node('p', {className: '-row'},
  301. ['span', _rowAttrs(row), row.title.trim() || ['i', {}, row.id]],
  302. ": ",
  303. ...[].concat(...items.map(item => [
  304. ", ",
  305. ['span', {className: '-item', title: [`[${item.id}]`, item.text, item.scores.map(_cost).join("\n")].filter(Boolean).join("\n\n").trim(),
  306. onmouseenter: _showImg(item), onmouseleave: _hideImg},
  307. ['span', {className: '-item-name'}, item.title.trim() || ['i', {}, item.id]],
  308. !item.isActive && (item.isSelectableMultiple ? ` ${item.multipleUseVariable}}` : " {Image}")],
  309. ])).slice(1)));
  310. });
  311. }
  312. $overview.overlay.style.display = (visible ? 'none' : '');
  313. }
  314. $overview.toggle(false);
  315. }
  316. };
  317. GM_registerMenuCommand("Overview", $overview);
  318. GM_addStyle(`#LIST-TOGGLE {position:fixed; right:3px; bottom:3px; z-index:1001; color:var(--light); background:var(--gray);
  319. padding:1ex; width:auto; border-radius:1em}
  320. .-FULL-SCAN #LIST-TOGGLE {color:var(--gray); background:var(--light)}`);
  321. document.body.append( _node('button', {id: 'LIST-TOGGLE', className: "v-icon mdi mdi-table-of-contents", title: "Overview/dice roll", onclick: $overview}) );
  322.  
  323. function $cheat() {
  324. if (!$cheat.toggle) {
  325. const {reFrame: rf, reagent: r, util: {getIn, update, assocIn, merge, entries}} = require('mreframe');
  326. let updateIn = (o, path, f, ...args) => assocIn(o, path, f(getIn(o, path), ...args));
  327. const _ID = 'CHEAT', ID = '#'+_ID, _scroll = (s, bg='#2B2F35', thumb='grey', wk='::-webkit-scrollbar') =>
  328. `${s} {scrollbar-width:thin; scrollbar-color:${thumb} ${bg}} ${s}${wk} {width:6px; height:6px; background:${bg}} ${s}${wk}-thumb {background:${thumb}}`;
  329. GM_addStyle(`${ID} {position:fixed; bottom:0; left:0; z-index:1000; color:var(--light); background:var(--gray-dark); opacity:.75} ${ID}:hover {opacity:1}
  330. ${ID} .-frame {max-height:100vh; display:flex; flex-direction:column} ${ID} .-scrollbox {overflow-y:auto} ${_scroll(ID+" .-scrollbox")}
  331. ${ID} h3 {text-align:center} ${ID} table.-points td, ${ID} .-cheats {padding:.5ex} ${ID} .-row {display:flex; flex-direction:row}
  332. ${ID} button {background-color:var(--secondary); border-style:outset; border-radius:1em}
  333. ${ID} td.-minus button, ${ID} tr.-minus :is(.-point-name, .-point-value) {background-color:var(--danger)}
  334. ${ID} td.-plus button, ${ID} tr.-plus :is(.-point-name, .-point-value) {background-color:var(--purple)}
  335. ${ID} button.-cheats {background: var(--cyan)}`);
  336. document.body.append($cheat.UI = _node('div', {id: _ID}));
  337. $cheat.toggle = () => rf.disp(['toggle-ui']);
  338.  
  339. let _points = pointTypes => pointTypes.map(points => [points.id, points.name, points.beforeText, points.startingSum]);
  340. $store().watch(state => _points(state.app.pointTypes), points => rf.disp(['cache-points', points]));
  341. let _upd = rf.after(({show, cache, ...data}) => {$cheat.data = data});
  342.  
  343. rf.regEventDb('init-db', [_upd], (db, [_, {points={}}={}]) => ({
  344. show: false,
  345. points,
  346. cache: db.cache || {points: []},
  347. }));
  348. rf.regEventDb('toggle-ui', [_upd], db => update(db, 'show', x => !x));
  349. rf.regEventFx('point-add!', [_upd], ({db}, [_, id, n]) => ({db: updateIn(db, ['points', id], x => (x||0)+n),
  350. points: [{id, add: n}]}));
  351. rf.regEventFx('reset-cheats!', [_upd], ({db}) => ({db: merge(db, {points: {}}),
  352. points: entries(db.points).map(([id, n]) => ({id, add: -n}))}));
  353. rf.regEventDb('cache-points', [_upd], (db, [_, points]) => assocIn(db, ['cache', 'points'], points));
  354.  
  355. rf.regFx('points', changes => changes.forEach(({id, add}) => {$pointTypes().find(x => x.id == id).startingSum += add}));
  356.  
  357. rf.regSub('show', getIn);
  358. rf.regSub('points', getIn);
  359. rf.regSub('cache', getIn);
  360. rf.regSub('cheating?', db => true);
  361. rf.regSub('points*', ([_, id]) => rf.subscribe(['points', id]), n => n||0);
  362. let _change = n => (!n ? "" : `${n < 0 ? n : '+'+n}`);
  363. rf.regSub('point-show', ([_, id]) => rf.subscribe(['points', id]), _change);
  364. rf.regSub('point-changes', '<-', ['cache', 'points'], '<-', ['points'], ([points, o]) =>
  365. points.filter(([id]) => o[id]).map(([id, name, show]) => [`[${id}] ` + (show||`(${name})`), o[id]]));
  366. rf.regSub('tooltip', '<-', ['point-changes'], changes =>
  367. changes.map(([points, change]) => `${points} ${_change(change)}`).join("\n"));
  368. rf.regSub('cheating?', '<-', ['point-changes'], changes => changes.length > 0);
  369.  
  370. let PointAdd = id => n => ['button', {onclick: () => rf.disp(['point-add!', id, n])}, (n > 0) && '+', n];
  371. let Points = () => ['table.-points', ...rf.dsub(['cache', 'points']).map(([id, name, show, amount]) =>
  372. ['tr', {class: [{1: '-plus', '-1': '-minus'}[Math.sign(rf.dsub(['points*', id]))]],
  373. title: rf.dsub(['point-show', id])},
  374. ['td.-minus', ...[-100, -10, -1].map( PointAdd(id) )],
  375. ['td.-point-name', "[", ['tt', id], "]", ['br'], show||['em', "<untitled>"], ['br'], `(${name})`],
  376. ['td.-point-value', amount],
  377. ['td.-plus', ...[+100, +10, +1].map( PointAdd(id) )]])];
  378. let Frame = (...body) => ['.-frame',
  379. ['h3', {title: rf.dsub(['tooltip'])}, "Points"],
  380. ['.-scrollbox', ...body],
  381. ['div.-row', {title: rf.dsub(['tooltip'])},
  382. ['button', {onclick: $cheat}, (rf.dsub(['cheating?']) ? "< HIDE" : "× CLOSE")],
  383. rf.dsub(['cheating?']) && ['button', {onclick: () => rf.disp(['reset-cheats!'])}, "RESET"]]];
  384. let UI = () => (rf.dsub(['show']) ? [Frame, [Points]] :
  385. rf.dsub(['cheating?']) && ['button.-cheats', {onclick: $cheat, title: rf.dsub(['tooltip'])}, " Cheats: on "]);
  386.  
  387. rf.dispatchSync(['init-db']);
  388. rf.disp(['cache-points', _points( $pointTypes() )]);
  389. r.render([UI], $cheat.UI);
  390. }
  391. $cheat.toggle();
  392. }
  393. GM_registerMenuCommand("Cheat engine", $cheat);
  394. };
  395. })();