/* eslint-disable @typescript-eslint/no-unsafe-member-access */ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ /** * @packageDocumentation * @module utils */ import assert from 'assert'; import { Warnings, getByID } from './utils'; import { Settings } from './dataset'; /** * Possible HTML attributes to attach to a setting */ // this is mostly to catch typo early. Feel free to add more! type Attribute = 'value' | 'checked' | 'innerText' | 'multival'; /// Type mapping for options interface OptionsTypeMap { // I would really like to use `'string': string` here as the mapping, but // this is forbidden by the typescript compiler (for reasons unclear to me, // it thinks that `OptionsTypeMap[T extends keyof OptionsTypeMap]` is // `never`). https://github.com/microsoft/TypeScript/issues/33014 seems to // be related. // // Using a tuple/array type (`[string]`) seems to trick the compiler/improve // the way it performs type inference. string: [string]; int: [number]; number: [number]; boolean: [boolean]; } type OptionsType = keyof OptionsTypeMap; type OptionsValue = OptionsTypeMap[T][0]; function parse(type: T, value: string): OptionsValue { if (type === 'string') { return value; } else if (type === 'int') { const result = Number(value); if (value.trim() === '' || Number.isNaN(result) || !Number.isInteger(result)) { throw Error(`invalid value for int: ${value}`); } return result; } else if (type === 'number') { // accept any capitalisation of NaN (e.g. a stringified numpy `nan` in an // externally-created file); for min/max settings NaN means "autoscale" if (value.toLowerCase() === 'nan') { return NaN; } const result = Number(value); if (value.trim() === '' || Number.isNaN(result)) { throw Error(`invalid value for number: ${value}`); } return result; } else if (type === 'boolean') { if (value === 'false') { return false; } else if (value === 'true') { return true; } else { throw Error(`invalid value for boolean: ${value}`); } } throw Error(`unknown type '${type}' passed to parse`); } /** Possible origins of a option change: from JS code, or from DOM interaction */ export type OptionModificationOrigin = 'JS' | 'DOM'; /** A single DOM element that will be synchronized with the javascript value of a setting */ interface HTMLOptionElement { /** The DOM element that we should check for changes */ element: HTMLElement; /** Which attribute of the element should we check */ attribute: Attribute; /** Store the function used to listen on the element to be able to remove it */ listener: (e: Event) => void; } /** * Creates a validating function that checks value against a list of valid * entries. This is intended to be used as a `validate` callback on an * {@link HTMLOption}. * * @param valid list of valid values for the setting * @param name name of the setting for better error messages * @return a function that can be used to validate a new setting value */ export function optionValidator(valid: string[], name = ''): (value: string) => void { return (value: string) => { if (valid.includes(value)) { return; } throw Error(`invalid value '${value}' for ${name}, expected one of [${valid.join(', ')}]`); }; } /** * Simple two-way data binding implementation to store settings in chemiscope. * * This class manages a setting single value, and bind it to HTML elements. * Whenever the value is changed from javascript code, or updated in any of the * linked HTML element, it is automatically updated everywhere. */ export class HTMLOption { /** the type of the value stored by this setting */ public readonly type: T; /** Callback to validate the new value before propagating changes. */ public validate: (value: OptionsValue) => void; /** Additional callbacks to run whenever the setting value changes */ public onchange: Array<(value: OptionsValue, origin: OptionModificationOrigin) => void>; // storage of the actual value, this is separated from this.value to allow // intercepting set private _value: OptionsValue; // list of bound HTML elements: any update to the setting `value` or any of // the element will change both the setting value and all of the linked // elements private _boundList: HTMLOptionElement[]; private _previous_value: OptionsValue; /** * Create a new {@link HTMLOption} containing a value of the given type. * Possible type/values combinations are described in the {@link OptionsTypeMap} * interface. * * @param type type of the setting * @param value initial value of the setting */ constructor(type: T, value: OptionsValue) { this.type = type; this._value = value; this._previous_value = value; this._boundList = []; this.validate = () => {}; this.onchange = []; Object.preventExtensions(this); } /** Get the value of this setting */ public get value(): OptionsValue { return this._value; } /** Set a new value for this setting */ public set value(v: OptionsValue) { this._update(v.toString(), 'JS'); } /** * Call all onchange callbacks & update the DOM representation after a * change. This function is called automatically when using `.value = ...` */ public changed(origin: OptionModificationOrigin) { for (const bound of this._boundList) { if (bound.attribute === 'multival') { // options take a list of comma-separated values to allow multiple settings const values = (this._value as string).split(','); const element = bound.element as HTMLSelectElement; for (const option of element.options) { option.selected = values.includes(option.value); } } else { let value = this._value; // Special handling for NaN in number inputs to avoid browser warnings if (typeof value === 'number' && Number.isNaN(value)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any value = '' as any; } // eslint-disable-next-line @typescript-eslint/no-explicit-any (bound.element as any)[bound.attribute] = value; } } for (const callback of this.onchange) { callback(this._value, origin); } } /** Reset to a previous value for this setting */ public reset(): void { this.value = this._previous_value; } /** * Add a new HTML element to the list of synchronized element. * `element.attribute` will be set to the setting value, and the setting * value will be updated every time the 'change' event is sent. * * @param element HTML DOM element to watch for updates, or string id * of such element * @param attribute attribute of the HTML element to use as value */ public bind(element: HTMLElement | string, attribute: Attribute): void { if (typeof element === 'string') { element = getByID(element); } element = element as HTMLElement; let listener: (event: Event) => void; if (attribute === 'multival') { listener = (event: Event) => { // we need a special handler for multi-select options assert(event.target !== null); const element = event.target as HTMLSelectElement; const values: string[] = Array.from(element.options) .filter((option) => option.selected) .map((option) => option.value); this._update(values.toString(), 'DOM'); }; // also initializes the state of the option list const values = (this._value as string).split(','); // eslint-disable-next-line @typescript-eslint/no-explicit-any for (const option of (element as any).options) { option.selected = values.includes(option.value as string); } } else { listener = (event: Event) => { assert(event.target !== null); // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument this._update((event.target as any)[attribute].toString(), 'DOM'); }; let value = this._value; // Special handling for NaN in number inputs to avoid browser warnings if (typeof value === 'number' && Number.isNaN(value)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any value = '' as any; } // eslint-disable-next-line @typescript-eslint/no-explicit-any (element as any)[attribute] = value; } element.addEventListener('change', listener); this._boundList.push({ element, attribute, listener }); } /** * Disable all HTML elements linked to this by setting the `disabled` * attribute to `true` if it exists on the element. This should only * disable HTMLInputElement. */ public disable(): void { for (const bound of this._boundList) { const element = bound.element as unknown as Record; if ('disabled' in element) { element.disabled = true; } } } /** * Enable all HTML elements linked to this by setting the `disabled` * attribute to `false` if it exists on the element. This should only * enable HTMLInputElement. */ public enable(): void { for (const bound of this._boundList) { const element = bound.element as unknown as Record; if ('disabled' in element) { element.disabled = false; } } } /** * Remove all HTML elements bound to this setting, and the associated event * listeners. */ public unbindAll(): void { for (const bound of this._boundList) { bound.element.removeEventListener('change', bound.listener); } this._boundList = []; } // Actually perform the update of the value and all linked elements. The // value is passed around as a string, since that's the easiest way to merge // different data types coming from the DOM. private _update(value: string, origin: OptionModificationOrigin) { const updated = parse(this.type, value); if (this._value === updated) { // nothing to update return; } this.validate(updated); this._previous_value = this.value; this._value = updated; this.changed(origin); } } /** * A setting option that is not bound to any HTML element, but can be saved and * loaded with the rest of the settings. */ export class JSOption { /** Callback to validate the new value before propagating changes. */ public validate: (value: T) => void; /** Additional callbacks to run whenever the setting value changes */ public onchange: Array<(value: T, origin: OptionModificationOrigin) => void>; /** Check if two values are equal. Default to strict equality */ public equals: (a: T, b: T) => boolean; private _value: T; constructor(value: T) { this._value = value; this.validate = () => {}; this.onchange = []; this.equals = (a, b) => a === b; Object.preventExtensions(this); } public get value(): T { return this._value; } public set value(v: T) { this.setValue(v, 'JS'); } public setValue(v: T, origin: OptionModificationOrigin) { // We can not check for equality here since T can be an object/array this.validate(v); if (this.equals(this._value, v)) { return; } this._value = v; for (const callback of this.onchange) { callback(this._value, origin); } } } /** * Callback function to use with {@link OptionsGroup.foreachSetting} */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export type OptionsCallback = (keys: string[], setting: HTMLOption | JSOption) => void; /** * Abstract base class to use for a group of settings. * * This class implement saving current settings as {@link SavedSettings}; and * applying saved settings to the setting group. * * # Example * * ```typescript * class MyOptions extends OptionsGroup { * public cats: HTMLOption<'int'>; * public dogs: { * husky: HTMLOption<'string'>; * labrador: HTMLOption<'string'>; * }; * * constructor() { * super(); * this.cats = new HTMLOption('int', 3); * this.dogs = { * husky: new HTMLOption('string', 'a cold dog'), * labrador: new HTMLOption('string', 'a long dog'), * }; * } * } * * const settings = new MyOptions(); * * settings.saveSettings(); * // {cats: 3, dogs: {husky: 'a cold dog', labrador: 'a long dog'}} * * settings.applySettings({cats: 66, dogs: {husky: 'a good dog'}}); * settings.saveSettings(); * // {cats: 66, dogs: {husky: 'a good dog', labrador: 'a long dog'}} * ``` */ export abstract class OptionsGroup { /** * Save the current values of all HTMLOption properties of the class, * including nested ones. * * Properties which name starts with an underscore are ignored. * * @return An object with the same structure as this class containing the * values of all settings. */ public warnings: Warnings; constructor(warnings: Warnings) { this.warnings = warnings; } public saveSettings(): Settings { const settings: Settings = {}; this.foreachOption((keys, option) => { assert(keys.length >= 1); const value = option.value; // Save property value if valid if (value !== undefined || value !== null || !Number.isNaN(value)) { let root = settings; for (const key of keys.slice(0, keys.length - 1)) { if (!(key in root)) { root[key] = {}; } root = root[key] as unknown as Settings; } const lastKey = keys[keys.length - 1]; root[lastKey] = value; } }); return settings; } /** * Set values from `settings` to the {@link HTMLOption} properties of this class, * matching the properties names. * * Properties starting with an underscore are ignored. */ public applySettings(settings: Settings): void { // make a copy of the settings since we will be changing it below const copy = JSON.parse(JSON.stringify(settings)) as Settings; this.foreachOption((keys, option) => { assert(keys.length >= 1); let root = copy; // keep track of the chain of objects to be able to remove empty // sub-objects (e.g. settings.map.color.select) const objectChain = [root]; for (const key of keys.slice(0, keys.length - 1)) { if (!(key in root)) { // this key is missing from the settings return; } root = root[key] as unknown as Settings; objectChain.push(root); } const lastKey = keys[keys.length - 1]; if (lastKey in root) { let value = root[lastKey]; // convert null values for numeric options to NaN (useful for axis range) if (typeof option.value === 'number' && value === null) { value = NaN; } // send warning if the value is invalid and omit applying it if (value === undefined || value === null) { this.warnings.sendMessage( `ignored setting '${lastKey}' with invalid value '${value}'` ); return; } option.value = value; // remove used keys from the settings to be able to warn on // unused keys // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete root[lastKey]; // cleanup empty objects up the chain for (let i = objectChain.length - 1; i > 0; i--) { const obj = objectChain[i]; if (Object.keys(obj).length === 0) { const parent = objectChain[i - 1]; // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete parent[keys[i - 1]]; } else { break; } } } }); if (Object.keys(copy).length !== 0) { this.warnings.sendMessage(`ignored unknown settings '${JSON.stringify(copy)}'`); } } /** * Add the given `callback` to be called whenever a setting changes. The * callback will be given the path to the settings as a list of keys; and * the new value of the setting. * * There is currently no way to remove a callback. */ public onSettingChange(callback: (keys: string[], value: unknown) => void): void { this.foreachOption((keys, option) => { option.onchange.push((value) => callback(keys, value)); }); } /** * Call the given callback on each setting inside the given SettingGroup. * * Keys starting with an underscore character are ignored. * * @param settings group of settings * @param callback callback operating on a single setting */ protected foreachOption(callback: OptionsCallback): void { foreachOptionImpl(this as Record, callback, []); } } /** * Recursive implementation of foreachOption * * This function looks through all properties of `options`, ignoring the ones * starting with an underscore. If the property is an instance of * {@link HTMLOption}, the `callback` is called on the option, together with the * keys used to access the property from the root object. * * @param options object containing the options * @param callback function to call on each HTMLOption * @param keys current keys to access the `settings` object from the root */ function foreachOptionImpl( options: Record, callback: OptionsCallback, keys: string[] = [] ): void { if (keys.length > 10) { throw Error('setting object is too deep'); } for (const key in options) { if (key.startsWith('_')) { continue; } const currentKeys = keys.concat([key]); const element = options[key]; if (element instanceof HTMLOption || element instanceof JSOption) { callback(currentKeys, element); } else if (typeof element === 'object' && element !== null) { foreachOptionImpl(element as Record, callback, currentKeys); } } }