Files
Grinch-AP/WebHostLib/static/assets/weightedOptions.js
Chris Wilson 5e3c5dedf3 WebHost: Massive overhaul of options pages (#2614)
* Implement support for option groups. WebHost options pages still need to be updated.

* Remove debug output

* In-progress conversion of player-options to Jinja rendering

* Support "Randomize" button without JS, transpile SCSS to CSS, include map file for later editors

* Un-alphabetize options, add default group name for item/location Option classes, implement more option types

* Re-flow UI generation to avoid printing rows with unsupported or invalid option types, add support for TextChoice options

* Support all remaining option types

* Rendering improvements and CSS fixes for prettiness

* Wrap options in a form, update button styles, fix labels, disable inputs where the default is random, nuke the JS

* Minor CSS tweaks, as recommended by the designer

* Hide JS-required elements in noscript tag. Add JS reactivity to range, named-range, and randomize buttons.

* Fix labels, add JS handling for TextChoice

* Make option groups collapsable

* PEP8 current option_groups progress (#2604)

* Make the python more PEP8 and remove unneeded imports

* remove LocationSet from `Item & Location Options` group

* It's ugly, but YAML generation is working

* Stop generating JSON files for player-options pages

* Do not include ItemDict entries whose values are zero

* Properly format yaml output

* Save options when form is submitted, load options on page load

* Fix options being omitted from the page if a group has an even number of options

* Implement generate-game, escape option descriptions

* Fix "randomize" checkboxes not properly setting YAML options to "random"

* Add a separator between item/location groups and items/locations in their respective lists

* Implement option presets

* Fix docs to detail what actually ended up happening

* implement option groups on webworld to allow dev sorting (#2616)

* Force extremely long item/location/option names with no spaces to text-wrap

* Fix "randomize" button being too wide in single-column display, change page header to include game name

* Update preset select to read "custom" when updating form inputs. Show error message if the user doesn't input a name

* Un-break weighted-options, add option group names to weighted options

* Nuke weighted-options. Set up framework to rebuild it in Jinja.

* Generate styles with scss, remove styles which will be replaced, add placeholders for worlds

* Support Toggle, DefaultOnToggle, and Choice options in weighted-options

* Implement expand/collapse without JS for worlds and option groups

* Properly style set options

* Implement Range and NamedRange. Also, CSS is hard.

* Add support for remaining option types. JS and backend still forthcoming.

* Add JS functionality for collapsing game divs, populating span values on range updates. Add <noscript> tag to warn users with JS disabled.

* Support showing/hiding game divs based on range value for game

* Add support for adding/deleting range rows

* Save settings to localStorage on form submission

* Save deleted options on form submission

* Break weighted-options into a per-game page.

- Break weighted-options into a per-game page
- Add "advanced options" links to supported games page
- Use details/summary tags on supported games, player-options, and weighted-options
- Fix bug preventing previously deleted rows from being removed on page load if JS is enabled
- Move route handling for options pages to options.py
- Remove world handling from weighted-options

* Implement loading previous settings from localStorage on page load if JS is enabled

* Weighted options can now generate YAML files and single-player games

* options pages now respect option visibility settings for simple and complex pages

* Remove `/weighted-settings` redirect, fix weighted-options link on player-options page

* Fix instance of AutoWorld not having access to proper `random`

* Catch instances of frozenset along with set

* Restore word-wrap in tooltips

* Fix word wrap in player-options labels

* Add `dedent` filter to help with formatting tooltips in player-options

* Do not change the ordering of keys when printing yaml files

* Move necessary import out of conditional statement

* Expand only the first option group by default on both options pages

* Respect option visibility when generating yaml template files

* Swap to double quotes

* Replace instances of `/weighted-settings` with `/weighted-options`, swap out incomplete links

* Strip newlines and spaces after applying dedent filter

* Fix documentation for option groups

* Update site map

* Update various docs

* Sort OptionSet lists alphabetically

* Minor style tweak

* Fix extremely long text overflowing tooltips

* Convert player-options to use CSS grid instead of tables

* Do not display link to weighted-options page on supported games if the options page is an external link

* Update worlds/AutoWorld.py

Bugfix by @alwaysintreble

Co-authored-by: Aaron Wagener <mmmcheese158@gmail.com>

* Fix NamedRange options not being properly set if a preset it loaded

* Move option-presets route into options.py

* Include preset name in YAML if not "default" and not "custom"

* Removed macros for PlandoBosses and DefaultOnToggle, as they were handled by their parent classes

* Fix not disabling custom inputs when the randomize button is clicked

* Only sort OptionList and OptionSet valid_keys if they are unordered

* Quick style fixes for player-settings to give `select` elements `text-overflow: ellipsis` and increase base size of left-column

* Prevent showing a horizontal scroll bar on player-options if the browser width was beneath a certain threshold

* Fix a bug in weighted-options which prevented inputting a negative value for new range inputs

---------

Co-authored-by: Aaron Wagener <mmmcheese158@gmail.com>
2024-05-18 00:11:57 -04:00

224 lines
8.4 KiB
JavaScript

let deletedOptions = {};
window.addEventListener('load', () => {
const worldName = document.querySelector('#weighted-options').getAttribute('data-game');
// Generic change listener. Detecting unique qualities and acting on them here reduces initial JS initialisation time
// and handles dynamically created elements
document.addEventListener('change', (evt) => {
// Handle updates to range inputs
if (evt.target.type === 'range') {
// Update span containing range value. All ranges have a corresponding `{rangeId}-value` span
document.getElementById(`${evt.target.id}-value`).innerText = evt.target.value;
// If the changed option was the name of a game, determine whether to show or hide that game's div
if (evt.target.id.startsWith('game||')) {
const gameName = evt.target.id.split('||')[1];
const gameDiv = document.getElementById(`${gameName}-container`);
if (evt.target.value > 0) {
gameDiv.classList.remove('hidden');
} else {
gameDiv.classList.add('hidden');
}
}
}
});
// Generic click listener
document.addEventListener('click', (evt) => {
// Handle creating new rows for Range options
if (evt.target.classList.contains('add-range-option-button')) {
const optionName = evt.target.getAttribute('data-option');
addRangeRow(optionName);
}
// Handle deleting range rows
if (evt.target.classList.contains('range-option-delete')) {
const targetRow = document.querySelector(`tr[data-row="${evt.target.getAttribute('data-target')}"]`);
setDeletedOption(
targetRow.getAttribute('data-option-name'),
targetRow.getAttribute('data-value'),
);
targetRow.parentElement.removeChild(targetRow);
}
});
// Listen for enter presses on inputs intended to add range rows
document.addEventListener('keydown', (evt) => {
if (evt.key === 'Enter') {
evt.preventDefault();
}
if (evt.key === 'Enter' && evt.target.classList.contains('range-option-value')) {
const optionName = evt.target.getAttribute('data-option');
addRangeRow(optionName);
}
});
// Detect form submission
document.getElementById('weighted-options-form').addEventListener('submit', (evt) => {
// Save data to localStorage
const weightedOptions = {};
document.querySelectorAll('input[name]').forEach((input) => {
const keys = input.getAttribute('name').split('||');
// Determine keys
const optionName = keys[0] ?? null;
const subOption = keys[1] ?? null;
// Ensure keys exist
if (!weightedOptions[optionName]) { weightedOptions[optionName] = {}; }
if (subOption && !weightedOptions[optionName][subOption]) {
weightedOptions[optionName][subOption] = null;
}
if (subOption) { return weightedOptions[optionName][subOption] = determineValue(input); }
if (optionName) { return weightedOptions[optionName] = determineValue(input); }
});
localStorage.setItem(`${worldName}-weights`, JSON.stringify(weightedOptions));
localStorage.setItem(`${worldName}-deletedOptions`, JSON.stringify(deletedOptions));
});
// Remove all deleted values as specified by localStorage
deletedOptions = JSON.parse(localStorage.getItem(`${worldName}-deletedOptions`) || '{}');
Object.keys(deletedOptions).forEach((optionName) => {
deletedOptions[optionName].forEach((value) => {
const targetRow = document.querySelector(`tr[data-row="${value}-row"]`);
targetRow.parentElement.removeChild(targetRow);
});
});
// Populate all settings from localStorage on page initialisation
const previousSettingsJson = localStorage.getItem(`${worldName}-weights`);
if (previousSettingsJson) {
const previousSettings = JSON.parse(previousSettingsJson);
Object.keys(previousSettings).forEach((option) => {
if (typeof previousSettings[option] === 'string') {
return document.querySelector(`input[name="${option}"]`).value = previousSettings[option];
}
Object.keys(previousSettings[option]).forEach((value) => {
const input = document.querySelector(`input[name="${option}||${value}"]`);
if (!input?.type) {
return console.error(`Unable to populate option with name ${option}||${value}.`);
}
switch (input.type) {
case 'checkbox':
input.checked = (parseInt(previousSettings[option][value], 10) === 1);
break;
case 'range':
input.value = parseInt(previousSettings[option][value], 10);
break;
case 'number':
input.value = previousSettings[option][value].toString();
break;
default:
console.error(`Found unsupported input type: ${input.type}`);
}
});
});
}
});
const addRangeRow = (optionName) => {
const inputQuery = `input[type=number][data-option="${optionName}"].range-option-value`;
const inputTarget = document.querySelector(inputQuery);
const newValue = inputTarget.value;
if (!/^-?\d+$/.test(newValue)) {
alert('Range values must be a positive or negative integer!');
return;
}
inputTarget.value = '';
const tBody = document.querySelector(`table[data-option="${optionName}"].range-rows tbody`);
const tr = document.createElement('tr');
tr.setAttribute('data-row', `${optionName}-${newValue}-row`);
tr.setAttribute('data-option-name', optionName);
tr.setAttribute('data-value', newValue);
const tdLeft = document.createElement('td');
tdLeft.classList.add('td-left');
const label = document.createElement('label');
label.setAttribute('for', `${optionName}||${newValue}`);
label.innerText = newValue.toString();
tdLeft.appendChild(label);
tr.appendChild(tdLeft);
const tdMiddle = document.createElement('td');
tdMiddle.classList.add('td-middle');
const range = document.createElement('input');
range.setAttribute('type', 'range');
range.setAttribute('min', '0');
range.setAttribute('max', '50');
range.setAttribute('value', '0');
range.setAttribute('id', `${optionName}||${newValue}`);
range.setAttribute('name', `${optionName}||${newValue}`);
tdMiddle.appendChild(range);
tr.appendChild(tdMiddle);
const tdRight = document.createElement('td');
tdRight.classList.add('td-right');
const valueSpan = document.createElement('span');
valueSpan.setAttribute('id', `${optionName}||${newValue}-value`);
valueSpan.innerText = '0';
tdRight.appendChild(valueSpan);
tr.appendChild(tdRight);
const tdDelete = document.createElement('td');
const deleteSpan = document.createElement('span');
deleteSpan.classList.add('range-option-delete');
deleteSpan.classList.add('js-required');
deleteSpan.setAttribute('data-target', `${optionName}-${newValue}-row`);
deleteSpan.innerText = '❌';
tdDelete.appendChild(deleteSpan);
tr.appendChild(tdDelete);
tBody.appendChild(tr);
// Remove this option from the set of deleted options if it exists
unsetDeletedOption(optionName, newValue);
};
/**
* Determines the value of an input element, or returns a 1 or 0 if the element is a checkbox
*
* @param {object} input - The input element.
* @returns {number} The value of the input element.
*/
const determineValue = (input) => {
switch (input.type) {
case 'checkbox':
return (input.checked ? 1 : 0);
case 'range':
return parseInt(input.value, 10);
default:
return input.value;
}
};
/**
* Sets the deleted option value for a given world and option name.
* If the world or option does not exist, it creates the necessary entries.
*
* @param {string} optionName - The name of the option.
* @param {*} value - The value to be set for the deleted option.
* @returns {void}
*/
const setDeletedOption = (optionName, value) => {
deletedOptions[optionName] = deletedOptions[optionName] || [];
deletedOptions[optionName].push(`${optionName}-${value}`);
};
/**
* Removes a specific value from the deletedOptions object.
*
* @param {string} optionName - The name of the option.
* @param {*} value - The value to be removed
* @returns {void}
*/
const unsetDeletedOption = (optionName, value) => {
if (!deletedOptions.hasOwnProperty(optionName)) { return; }
if (deletedOptions[optionName].includes(`${optionName}-${value}`)) {
deletedOptions[optionName].splice(deletedOptions[optionName].indexOf(`${optionName}-${value}`), 1);
}
if (deletedOptions[optionName].length === 0) {
delete deletedOptions[optionName];
}
};