Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Preact scanner frontend
import { h } from 'preact';
import { useEffect, useState } from 'preact/hooks';
import style from './style.css';
let socket;
const HOSTNAME = `paperless.local:8081`;
const Progress = () => {
return (
<div class={style.progress}>
<progress />
</div>
)
};
const LastScan = ({ fileName = null }) => {
if (!fileName) { return null; }
fileName = fileName.trim();
let src = `http://${HOSTNAME}/${fileName}`;
let scan;
if (fileName.endsWith('pdf')) {
scan = (<a href={src}>Download PDF</a>);
} else {
scan = (<img src={src} />);
}
return (
<div class={style.lastScan}>{scan}</div>
);
};
const LastOutput = ({ output = null }) => {
if (!output) { return null; }
return (
<div class={style.lastOutput}>
<pre>{output}</pre>
</div>
);
}
const Home = () => {
const [disabled, setDisabled] = useState(true);
const [output, setOutput] = useState('');
const [lastScan, setLastScan] = useState(null);
let handleButtonClick = (event) => {
let id = event.target.id;
socket.send(`SCAN:${id}`);
};
let handleResult = (data) => {
let output = data.replace(/^RESULT:/, '');
setOutput(output);
if (output.startsWith('/')) {
// Assume it's a path to the most recent scan.
let parts = output.split('/');
let fileName = parts.pop();
setLastScan(fileName);
}
}
useEffect(() => {
socket = new WebSocket(`ws://${HOSTNAME}`);
socket.addEventListener('open', () => {
socket.send('OK?');
});
socket.addEventListener('message', (event) => {
if (event.data === 'OK') {
setDisabled(false);
} else if (event.data === 'WAIT') {
setDisabled(true);
}
if (event.data.startsWith('RESULT:')) {
handleResult(event.data);
}
console.debug('Message from server:', event.data);
});
}, []);
return (
<div class={style.home}>
<div class={style.buttons} onClick={handleButtonClick}>
<fieldset>
<legend>Scan to Image</legend>
<div class={style.fieldsetGroup}>
<button id="image-scan-from-bed" disabled={disabled}>From Bed</button>
<button id="image-scan-from-adf" disabled={disabled}>From ADF</button>
</div>
</fieldset>
<fieldset>
<legend>Scan to Paperless</legend>
<div class={style.fieldsetGroup}>
<button id="paperless-scan-from-bed" disabled={disabled}>From Bed</button>
<button id="paperless-scan-from-adf" disabled={disabled}>From ADF</button>
</div>
</fieldset>
</div>
{disabled && <Progress />}
<LastScan fileName={lastScan} />
<LastOutput output={output} />
</div>
);
}
export default Home;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment