Various UI improvements for config

This commit is contained in:
Ingvar Stepanyan
2021-07-14 16:40:27 +00:00
parent 37017f6c3f
commit 86a271cf9f

173
ui.js
View File

@@ -1,4 +1,4 @@
import { h, render, Component } from 'preact'; import { h, render, Component, createRef } from 'preact';
import initModule from './libapi.mjs'; import initModule from './libapi.mjs';
/** @typedef {InstanceType<import('./libapi.mjs').Module['Context']>} Context */ /** @typedef {InstanceType<import('./libapi.mjs').Module['Context']>} Context */
@@ -47,13 +47,55 @@ const scheduleOp = (() => {
/** /**
* *
* @param {{ * @extends Component<{ config: Config }>
* config: Config,
* inProgress: boolean,
* }} params
* @returns {import('preact').VNode<any>}
*/ */
function Config({ config, inProgress }) { class ConfigComponent extends Component {
state = { inProgress: false };
shouldComponentUpdate(
/** @type {ConfigComponent['props']} */ nextProps,
/** @type {ConfigComponent['state']} */ nextState
) {
return !(this.state.inProgress && nextState.inProgress);
}
getValueProp() {
switch (this.props.config.type) {
case 'toggle':
return 'checked';
case 'datetime':
return 'valueAsNumber';
default:
return 'value';
}
}
handleChange = async e => {
this.setState({ inProgress: true });
let value = e.target[this.getValueProp()];
try {
/** @type {Promise<void>} */
let uiTimeout;
await scheduleOp(context => {
// This is terrible, yes... but some configs return too quickly before they're actually updated.
// We want to wait some time before updating the UI in that case, but not block subsequent ops.
uiTimeout = new Promise(resolve => setTimeout(resolve, 800));
return context.setConfigValue(this.props.config.name, value);
});
await uiTimeout;
} catch (e) {
console.error(e);
}
this.setState({ inProgress: false });
};
render(
/** @type {ConfigComponent['props']} */ { config },
/** @type {ConfigComponent['state']} */ { inProgress }
) {
let { label, name } = config; let { label, name } = config;
let id = `config-${name}`; let id = `config-${name}`;
if (config.type === 'window' || config.type === 'section') { if (config.type === 'window' || config.type === 'section') {
@@ -62,43 +104,33 @@ function Config({ config, inProgress }) {
{ id }, { id },
h('legend', {}, label), h('legend', {}, label),
Object.values(config.children).map(config => Object.values(config.children).map(config =>
h(Config, { key: config.name, config, inProgress }) h(ConfigComponent, { key: config.name, config })
) )
); );
} }
let { value, readonly } = config; let { value, readonly } = config;
let valueProp; let valueProp = this.getValueProp();
switch (config.type) {
case 'toggle':
valueProp = 'checked';
break;
case 'range':
case 'datetime':
valueProp = 'valueAsNumber';
break;
default:
valueProp = 'value';
}
// We don't want to override current input's value while user is editing it.
if (document.activeElement?.id === id) {
// @ts-ignore
value = document.activeElement?.[valueProp];
}
let attrs = { let attrs = {
id, id,
[valueProp]: value, [valueProp]: value,
readonly, readonly: readonly || inProgress,
disabled: inProgress onChange: this.handleChange
}; };
let inputElem; let inputElem;
switch (config.type) { switch (config.type) {
case 'range': { case 'range': {
let { min, max, step } = config; let { min, max, step } = config;
inputElem = h('input', { type: 'number', min, max, step, ...attrs }); inputElem = h(EditableInput, {
type: 'number',
min,
max,
step,
...attrs
});
break; break;
} }
case 'text': case 'text':
inputElem = readonly ? value : h('input', attrs); inputElem = readonly ? value : h(EditableInput, attrs);
break; break;
case 'toggle': { case 'toggle': {
inputElem = h('input', { inputElem = h('input', {
@@ -114,21 +146,17 @@ function Config({ config, inProgress }) {
'select', 'select',
attrs, attrs,
choices.map(choice => choices.map(choice =>
h( h(Option, {
'option',
{
key: choice, key: choice,
value: choice, value: choice,
disabled: attrs.readonly && value !== choice disabled: attrs.readonly && value !== choice
}, })
choice
)
) )
); );
break; break;
} }
case 'datetime': { case 'datetime': {
inputElem = h('input', { inputElem = h(EditableInput, {
type: 'datetime-local', type: 'datetime-local',
...attrs ...attrs
}); });
@@ -142,13 +170,43 @@ function Config({ config, inProgress }) {
return h( return h(
'div', 'div',
{ class: 'pure-control-group' }, { class: 'pure-control-group' },
h('label', { for: id }, label), h('label', { for: id }, (inProgress ? '⌛ ' : '') + label),
inputElem inputElem
); );
} }
}
/**
* Special memoized option to work around https://github.com/preactjs/preact/issues/3171.
* @extends Component<{ value: string, disabled?: boolean }>
*/
class Option extends Component {
shouldComponentUpdate(/** @type {Option['props']} */ nextProps) {
return nextProps.value !== this.props.value;
}
render() {
return h('option', this.props, this.props.value);
}
}
/**
* Wrapper around <input /> that doesn't update it while it's in focus to allow editing.
*/
class EditableInput extends Component {
ref = createRef();
shouldComponentUpdate() {
return document.activeElement !== this.ref.current;
}
render(props) {
return h('input', Object.assign(props, { ref: this.ref }));
}
}
class Settings extends Component { class Settings extends Component {
state = { inProgress: false, config: 'Connecting...' }; state = { config: 'Connecting...' };
constructor() { constructor() {
super(); super();
@@ -160,38 +218,6 @@ class Settings extends Component {
})(); })();
} }
handleChange = async e => {
let name = e.target.id;
if (!name.startsWith('config-')) {
throw new Error('Unhandled input');
}
name = name.slice('config-'.length);
let value;
switch (e.target.type) {
case 'checkbox':
value = e.target.checked;
break;
case 'number':
case 'datetime-local':
value = e.target.valueAsNumber;
break;
default:
value = e.target.value;
break;
}
this.setState({ inProgress: true });
try {
await scheduleOp(context => context.setConfigValue(name, value));
} catch (e) {
console.error(e);
}
await this.refreshConfig();
this.setState({ inProgress: false });
};
async refreshConfig() { async refreshConfig() {
let config; let config;
try { try {
@@ -218,16 +244,13 @@ class Settings extends Component {
? state.config ? state.config
: h( : h(
'form', 'form',
{ { class: 'pure-form pure-form-aligned' },
class: 'pure-form pure-form-aligned',
onchange: this.handleChange
},
h('input', { h('input', {
type: 'button', type: 'button',
value: 'Capture image', value: 'Capture image',
onclick: this.handleCapture onclick: this.handleCapture
}), }),
h(Config, state) h(ConfigComponent, state)
); );
} }
} }