Improve folder structure
This commit is contained in:
5
examples/preact/.prettierrc
Normal file
5
examples/preact/.prettierrc
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"arrowParens": "avoid",
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none"
|
||||
}
|
||||
1
examples/preact/build
Symbolic link
1
examples/preact/build
Symbolic link
@@ -0,0 +1 @@
|
||||
../../build
|
||||
56
examples/preact/capture-button.js
Normal file
56
examples/preact/capture-button.js
Normal file
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright 2021 Google LLC
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
*/
|
||||
|
||||
import { h, Component, Fragment } from 'preact';
|
||||
|
||||
/** @extends Component<{ getFile: () => Promise<File> }, { status: string }> */
|
||||
export class CaptureButton extends Component {
|
||||
state = { status: '📷' };
|
||||
|
||||
handleCapture = async () => {
|
||||
this.setState({ status: '⌛' });
|
||||
try {
|
||||
let file = await this.props.getFile();
|
||||
let url = URL.createObjectURL(file);
|
||||
Object.assign(document.createElement('a'), {
|
||||
download: file.name,
|
||||
href: url
|
||||
}).click();
|
||||
URL.revokeObjectURL(url);
|
||||
this.setState({ status: '📷' });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
this.setState({ status: '❌' });
|
||||
}
|
||||
};
|
||||
|
||||
render() {
|
||||
return h(
|
||||
Fragment,
|
||||
null,
|
||||
h('input', {
|
||||
type: 'button',
|
||||
id: 'capture',
|
||||
disabled: this.state.status !== '📷',
|
||||
class: 'pure-button',
|
||||
onclick: this.handleCapture,
|
||||
value: `${this.state.status} Capture image`
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
8
examples/preact/index-fallback.js
Normal file
8
examples/preact/index-fallback.js
Normal file
@@ -0,0 +1,8 @@
|
||||
document.body.innerHTML = `
|
||||
<div class="center-parent">
|
||||
<div class="center">
|
||||
<p>⚠ This browser is <a href="https://caniuse.com/webusb,import-maps">not supported</a>.
|
||||
<p>Don't know how you got here? Check out the <a href="https://web.dev/porting-libusb-to-webusb/">blog post</a> or the <a href="https://github.com/GoogleChromeLabs/web-gphoto2">repo</a>!
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
69
examples/preact/index.html
Normal file
69
examples/preact/index.html
Normal file
@@ -0,0 +1,69 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>gphoto2 on the Web</title>
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://unpkg.com/purecss@2.0.6/build/pure-min.css"
|
||||
crossorigin="anonymous"
|
||||
/>
|
||||
<style>
|
||||
.center-parent {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.center {
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#config {
|
||||
overflow-y: auto;
|
||||
max-height: 100vh;
|
||||
padding-left: 5px;
|
||||
box-sizing: border-box;
|
||||
border-left: 3px solid #777;
|
||||
}
|
||||
|
||||
#config .pure-button {
|
||||
margin: 1px;
|
||||
width: 20ch;
|
||||
}
|
||||
|
||||
#config label {
|
||||
width: 40%;
|
||||
}
|
||||
|
||||
#config input,
|
||||
#config select {
|
||||
width: 50%;
|
||||
}
|
||||
</style>
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports": {
|
||||
"preact": "https://unpkg.com/preact@10.6.4/dist/preact.module.js",
|
||||
"preact/debug": "https://unpkg.com/preact@10.6.4/debug/dist/debug.module.js",
|
||||
"preact/devtools": "https://unpkg.com/preact@10.6.4/devtools/dist/devtools.module.js",
|
||||
"stats.js": "https://unpkg.com/stats.js@0.17.0/src/Stats.js"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<script type="module">
|
||||
try {
|
||||
if (!('usb' in navigator)) {
|
||||
throw new Error('WebUSB is unsupported');
|
||||
}
|
||||
await import('./index.js');
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
await import('./index-fallback.js');
|
||||
}
|
||||
</script>
|
||||
<link
|
||||
rel="icon"
|
||||
href='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 0 110 100"><text y=".9em" font-size="90">📷</text></svg>'
|
||||
/>
|
||||
</head>
|
||||
</html>
|
||||
234
examples/preact/index.js
Normal file
234
examples/preact/index.js
Normal file
@@ -0,0 +1,234 @@
|
||||
/*
|
||||
* Copyright 2021 Google LLC
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
*/
|
||||
|
||||
import { h, render, Component } from 'preact';
|
||||
import { CaptureButton } from './capture-button.js';
|
||||
import { connect, rethrowIfCritical } from './ops.js';
|
||||
import { Preview } from './preview.js';
|
||||
import { Widget } from './widget.js';
|
||||
|
||||
/** @typedef {import('./build/libapi.mjs').Context} Context */
|
||||
/** @typedef {import('./build/libapi.mjs').Config} Config */
|
||||
/** @typedef {import('./ops.js').Connection} Connection */
|
||||
|
||||
export const isDebug = new URLSearchParams(location.search).has('debug');
|
||||
|
||||
if (isDebug) {
|
||||
await import('preact/debug');
|
||||
}
|
||||
|
||||
/** @typedef {{ type: 'CameraPicker' } | { type: 'Status', message: string } | { type: 'Config', config: Config }} AppState */
|
||||
|
||||
const INTERFACE_CLASS = 6; // PTP
|
||||
const INTERFACE_SUBCLASS = 1; // MTP
|
||||
|
||||
/** @extends Component<null, AppState> */
|
||||
class App extends Component {
|
||||
/** @type {Connection} */
|
||||
connection;
|
||||
|
||||
componentDidMount() {
|
||||
addEventListener('error', ({ message }) =>
|
||||
this.setState({
|
||||
type: 'Status',
|
||||
message: `⚠ ${message}`
|
||||
})
|
||||
);
|
||||
addEventListener(
|
||||
'beforeunload',
|
||||
() => {
|
||||
if (!this.connection) return;
|
||||
this.connection.disconnect();
|
||||
this.connection = undefined;
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
// Try to connect to camera at startup.
|
||||
// If none is found among saved connections, it will fallback to a picker.
|
||||
this.setState({ type: 'Status', message: '⌛ Loading...' });
|
||||
this.tryToConnectToCamera();
|
||||
}
|
||||
|
||||
selectDevice = async () => {
|
||||
// @ts-ignore
|
||||
await navigator.usb.requestDevice({
|
||||
filters: [
|
||||
{
|
||||
classCode: INTERFACE_CLASS,
|
||||
subclassCode: INTERFACE_SUBCLASS
|
||||
}
|
||||
]
|
||||
});
|
||||
this.setState({ type: 'Status', message: '⌛ Connecting...' });
|
||||
await this.tryToConnectToCamera();
|
||||
};
|
||||
|
||||
async tryToConnectToCamera() {
|
||||
try {
|
||||
this.connection = await connect();
|
||||
} catch (e) {
|
||||
console.warn(e);
|
||||
this.setState({ type: 'CameraPicker' });
|
||||
return;
|
||||
}
|
||||
// We should reach this only once.
|
||||
while (this.connection) {
|
||||
try {
|
||||
let config = await this.connection.schedule(context =>
|
||||
context.configToJS()
|
||||
);
|
||||
if (!isDebug) {
|
||||
delete config.children.actions;
|
||||
delete config.children.other;
|
||||
}
|
||||
this.setState({
|
||||
type: 'Config',
|
||||
config
|
||||
});
|
||||
} catch (err) {
|
||||
rethrowIfCritical(err);
|
||||
console.error('Could not refresh config:', err);
|
||||
}
|
||||
while (true) {
|
||||
await new Promise(resolve =>
|
||||
requestIdleCallback(resolve, { timeout: 500 })
|
||||
);
|
||||
try {
|
||||
let hadEvents = await this.connection.schedule(context =>
|
||||
context.consumeEvents()
|
||||
);
|
||||
if (hadEvents) {
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
rethrowIfCritical(err);
|
||||
console.error('Could not consume events:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the specified config value.
|
||||
* @param {string} name
|
||||
* @param {*} value
|
||||
*/
|
||||
setValue = async (name, value) => {
|
||||
/** @type {Promise<void>} */
|
||||
let uiTimeout;
|
||||
await this.connection.schedule(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(name, value);
|
||||
});
|
||||
await uiTimeout;
|
||||
};
|
||||
|
||||
capturePreview = () =>
|
||||
this.connection.schedule(context => context.capturePreviewAsBlob());
|
||||
|
||||
captureImage = () =>
|
||||
this.connection.schedule(context => context.captureImageAsFile());
|
||||
|
||||
render(/** @type {App['props']} */ props, /** @type {App['state']} */ state) {
|
||||
switch (state.type) {
|
||||
case 'CameraPicker':
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'center-parent' },
|
||||
h(
|
||||
'div',
|
||||
{
|
||||
class: 'center'
|
||||
},
|
||||
h('input', {
|
||||
type: 'button',
|
||||
onclick: this.selectDevice,
|
||||
value: '🔍 Select camera'
|
||||
}),
|
||||
h(
|
||||
'p',
|
||||
null,
|
||||
"Don't know how you got here? Check out the ",
|
||||
h(
|
||||
'a',
|
||||
{ href: 'https://web.dev/porting-libusb-to-webusb/' },
|
||||
'blog post'
|
||||
),
|
||||
' or the ',
|
||||
h(
|
||||
'a',
|
||||
{ href: 'https://github.com/GoogleChromeLabs/web-gphoto2' },
|
||||
'repo'
|
||||
),
|
||||
'!'
|
||||
)
|
||||
)
|
||||
);
|
||||
case 'Status':
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'center-parent' },
|
||||
h('div', { class: 'center' }, state.message)
|
||||
);
|
||||
case 'Config':
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'pure-g' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'pure-u-2-3' },
|
||||
h(Preview, {
|
||||
getPreview: this.connection.supportedOps.capturePreview
|
||||
? this.capturePreview
|
||||
: undefined
|
||||
})
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ id: 'config', class: 'pure-u-1-3' },
|
||||
h(
|
||||
'form',
|
||||
{ class: 'pure-form pure-form-aligned' },
|
||||
h(
|
||||
'fieldset',
|
||||
null,
|
||||
this.connection.supportedOps.triggerCapture
|
||||
? h(CaptureButton, { getFile: this.captureImage })
|
||||
: undefined,
|
||||
' ',
|
||||
h(
|
||||
'a',
|
||||
{
|
||||
class: 'pure-button',
|
||||
href: 'https://github.com/GoogleChromeLabs/web-gphoto2',
|
||||
target: '_blank'
|
||||
},
|
||||
'⭐ Star on Github'
|
||||
)
|
||||
),
|
||||
h(Widget, { config: state.config, setValue: this.setValue })
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render(h(App, null), document.body);
|
||||
64
examples/preact/ops.js
Normal file
64
examples/preact/ops.js
Normal file
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2021 Google LLC
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
*/
|
||||
|
||||
import initModule from './build/libapi.mjs';
|
||||
|
||||
/** @typedef {import('../libapi.mjs').Context} Context */
|
||||
|
||||
const ModulePromise = initModule();
|
||||
|
||||
export function rethrowIfCritical(err) {
|
||||
// If it's precisely Error, it's a custom error; anything else - SyntaxError,
|
||||
// WebAssembly.RuntimeError, TypeError, etc. - is treated as critical here.
|
||||
if (err.constructor !== Error)
|
||||
{
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function connect() {
|
||||
const Module = await ModulePromise;
|
||||
|
||||
let context = await new Module.Context();
|
||||
let supportedOps = await context.supportedOps();
|
||||
|
||||
/** @type {Promise<unknown>} */
|
||||
let queue = Promise.resolve();
|
||||
|
||||
/** Schedules an exclusive async operation on the global context.
|
||||
* @template T
|
||||
* @param {(ctx: Context) => Promise<T>} op
|
||||
* @returns {Promise<T>}
|
||||
*/
|
||||
function schedule(op)
|
||||
{
|
||||
let res = queue.then(() => op(context));
|
||||
queue = res.catch(rethrowIfCritical);
|
||||
return res;
|
||||
}
|
||||
|
||||
return {
|
||||
supportedOps,
|
||||
schedule,
|
||||
disconnect() {
|
||||
context.delete();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** @typedef {ReturnType<typeof connect> extends Promise<infer Connection> ? Connection : never} Connection */
|
||||
121
examples/preact/preview.js
Normal file
121
examples/preact/preview.js
Normal file
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* Copyright 2021 Google LLC
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
*/
|
||||
|
||||
import { h, Component, createRef } from 'preact';
|
||||
import { rethrowIfCritical } from './ops.js';
|
||||
|
||||
export const isDebug = new URLSearchParams(location.search).has('debug');
|
||||
|
||||
const Stats = isDebug
|
||||
? await import('stats.js').then(
|
||||
res => /** @type {typeof import('stats.js')} */ (res['default'])
|
||||
)
|
||||
: null;
|
||||
|
||||
/** @extends Component<{ getPreview?: () => Promise<Blob> }, { error?: string }> */
|
||||
export class Preview extends Component {
|
||||
canvasHolderRef = createRef();
|
||||
canvasRef = createRef();
|
||||
/** @type {ResizeObserver} */
|
||||
resizeObserver;
|
||||
stats = isDebug ? new Stats() : null;
|
||||
|
||||
render() {
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'center-parent', ref: this.canvasHolderRef },
|
||||
!this.props.getPreview
|
||||
? h('div', { class: 'center' }, `Preview is unsupported`)
|
||||
: h('canvas', { class: 'center', ref: this.canvasRef })
|
||||
);
|
||||
}
|
||||
|
||||
async componentDidMount() {
|
||||
if (!this.props.getPreview) return;
|
||||
|
||||
let canvas = /** @type {HTMLCanvasElement} */ (this.canvasRef.current);
|
||||
let canvasHolder = this.canvasHolderRef.current;
|
||||
|
||||
if (isDebug) {
|
||||
canvasHolder.appendChild(this.stats.dom);
|
||||
}
|
||||
|
||||
let canvasCtx = canvas.getContext('bitmaprenderer');
|
||||
|
||||
let ratio = 0;
|
||||
|
||||
let throttled = 0;
|
||||
function updateCanvasSize() {
|
||||
if (throttled) {
|
||||
cancelAnimationFrame(throttled);
|
||||
}
|
||||
throttled = requestAnimationFrame(() => {
|
||||
throttled = 0;
|
||||
|
||||
let width = canvasHolder.offsetWidth - 10;
|
||||
let height = canvasHolder.offsetHeight;
|
||||
|
||||
if (height * ratio > width) {
|
||||
height = width / ratio;
|
||||
} else {
|
||||
width = height * ratio;
|
||||
}
|
||||
|
||||
Object.assign(canvas, { width, height });
|
||||
});
|
||||
}
|
||||
(this.resizeObserver = new ResizeObserver(updateCanvasSize)).observe(
|
||||
canvasHolder
|
||||
);
|
||||
|
||||
// I have no idea why, but if we connect too soon, it just hangs...
|
||||
await new Promise(resolve => setTimeout(resolve, 1500));
|
||||
|
||||
while (this.canvasRef.current) {
|
||||
try {
|
||||
let blob = await this.props.getPreview();
|
||||
|
||||
// If ratio is known; decode resized image right away - it's a bit faster.
|
||||
// If it isn't known, retrieve entire image to calculate ratio from its dimensions.
|
||||
let img = await createImageBitmap(
|
||||
blob,
|
||||
ratio
|
||||
? {
|
||||
resizeWidth: canvas.width,
|
||||
resizeHeight: canvas.height
|
||||
}
|
||||
: {}
|
||||
);
|
||||
if (!ratio) {
|
||||
ratio = img.width / img.height;
|
||||
updateCanvasSize();
|
||||
}
|
||||
await new Promise(resolve => requestAnimationFrame(resolve));
|
||||
canvasCtx.transferFromImageBitmap(img);
|
||||
} catch (err) {
|
||||
rethrowIfCritical(err);
|
||||
console.error('Could not refresh preview:', err);
|
||||
}
|
||||
this.stats?.update();
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.resizeObserver?.disconnect();
|
||||
}
|
||||
}
|
||||
17
examples/preact/serve.json
Normal file
17
examples/preact/serve.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"headers": [
|
||||
{
|
||||
"source": "**/*",
|
||||
"headers": [
|
||||
{
|
||||
"key": "Cross-Origin-Embedder-Policy",
|
||||
"value": "require-corp"
|
||||
},
|
||||
{
|
||||
"key": "Cross-Origin-Opener-Policy",
|
||||
"value": "same-origin"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
191
examples/preact/widget.js
Normal file
191
examples/preact/widget.js
Normal file
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* Copyright 2021 Google LLC
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
*/
|
||||
|
||||
import { h, Component, createRef } from 'preact';
|
||||
|
||||
/** @typedef {import('./build/libapi.mjs').Config} Config */
|
||||
|
||||
/**
|
||||
* @param {Config} config
|
||||
*/
|
||||
function getValueForComparison(config) {
|
||||
if (config.type === 'window' || config.type === 'section') {
|
||||
// compare instances themselves
|
||||
return config;
|
||||
}
|
||||
return config.value;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @extends Component<{ config: Config, setValue: (name: string, value: any) => Promise<void> }>
|
||||
*/
|
||||
export class Widget extends Component {
|
||||
state = { inProgress: false };
|
||||
|
||||
shouldComponentUpdate(
|
||||
/** @type {Widget['props']} */ nextProps,
|
||||
/** @type {Widget['state']} */ nextState
|
||||
) {
|
||||
if (this.state.inProgress && nextState.inProgress) {
|
||||
return false;
|
||||
}
|
||||
if (this.state.inProgress || nextState.inProgress) {
|
||||
return true;
|
||||
}
|
||||
let prevConfig = this.props.config;
|
||||
let { config } = nextProps;
|
||||
if (config.type === 'toggle' && config.value === undefined) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
getValueForComparison(config) !== getValueForComparison(prevConfig) ||
|
||||
config.readonly !== prevConfig.readonly
|
||||
);
|
||||
}
|
||||
|
||||
getValueProp(out = false) {
|
||||
switch (this.props.config.type) {
|
||||
case 'toggle':
|
||||
return 'checked';
|
||||
case 'datetime':
|
||||
return 'valueAsNumber';
|
||||
case 'range':
|
||||
// Apparently can't render with `valueAsNumber` as preact property,
|
||||
// but can retrieve it back.
|
||||
return out ? 'valueAsNumber' : 'value';
|
||||
default:
|
||||
return 'value';
|
||||
}
|
||||
}
|
||||
|
||||
handleChange = async e => {
|
||||
this.setState({ inProgress: true });
|
||||
try {
|
||||
await this.props.setValue(
|
||||
this.props.config.name,
|
||||
e.target[this.getValueProp(true)]
|
||||
);
|
||||
} finally {
|
||||
this.setState({ inProgress: false });
|
||||
}
|
||||
};
|
||||
|
||||
render(
|
||||
/** @type {Widget['props']} */ { config, setValue },
|
||||
/** @type {Widget['state']} */ { inProgress }
|
||||
) {
|
||||
let { label, name } = config;
|
||||
let id = `config-${name}`;
|
||||
if (config.type === 'window' || config.type === 'section') {
|
||||
let children = Object.values(config.children);
|
||||
if (!children.length) return;
|
||||
return h(
|
||||
'fieldset',
|
||||
{ id },
|
||||
h('legend', {}, label),
|
||||
children.map(config =>
|
||||
h(Widget, { key: config.name, config, setValue })
|
||||
)
|
||||
);
|
||||
}
|
||||
let { value, readonly } = config;
|
||||
let valueProp = this.getValueProp();
|
||||
let attrs = {
|
||||
id,
|
||||
[valueProp]: value,
|
||||
readonly: readonly || inProgress,
|
||||
onChange: this.handleChange
|
||||
};
|
||||
let inputElem;
|
||||
switch (config.type) {
|
||||
case 'range': {
|
||||
let { min, max, step } = config;
|
||||
inputElem = h(EditableInput, {
|
||||
type: 'number',
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
...attrs
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'text':
|
||||
inputElem = h(EditableInput, attrs);
|
||||
break;
|
||||
case 'toggle': {
|
||||
inputElem = h('input', {
|
||||
type: 'checkbox',
|
||||
...attrs
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'menu':
|
||||
case 'radio': {
|
||||
let { choices } = config;
|
||||
inputElem = h(
|
||||
'select',
|
||||
attrs,
|
||||
choices.map(choice =>
|
||||
h(
|
||||
'option',
|
||||
{
|
||||
key: choice,
|
||||
disabled: attrs.readonly && value !== choice
|
||||
},
|
||||
choice
|
||||
)
|
||||
)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'datetime': {
|
||||
inputElem = h(EditableInput, {
|
||||
type: 'datetime-local',
|
||||
...attrs
|
||||
});
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
inputElem = '(unimplemented)';
|
||||
break;
|
||||
}
|
||||
}
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'pure-control-group' },
|
||||
h('label', { for: id }, (inProgress ? '⌛ ' : '') + label),
|
||||
inputElem
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper around <input /> that doesn't update it while it's in focus to allow editing.
|
||||
*/
|
||||
class EditableInput extends Component {
|
||||
ref = createRef();
|
||||
|
||||
shouldComponentUpdate() {
|
||||
return this.props.readonly || document.activeElement !== this.ref.current;
|
||||
}
|
||||
|
||||
render(props) {
|
||||
return h('input', Object.assign(props, { ref: this.ref }));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user