adding food logging, phase 4

This commit is contained in:
Joren de Graaf
2026-10-03 21:07:30 +02:00
parent 03fcbcbafc
commit e7ddb0ea28
11 changed files with 245 additions and 4 deletions
+1
View File
@@ -1,3 +1,4 @@
.food-page{max-width:1180px;margin:0 auto;padding:1.5rem 0 4rem}.food-heading,.food-meal-heading{display:flex;justify-content:space-between;align-items:center;gap:1rem}.food-heading nav{display:flex;gap:.5rem;align-items:center}.food-heading nav a,.food-add-meal{display:inline-flex;align-items:center;justify-content:center;min-width:44px;min-height:44px;border:1px solid currentColor;border-radius:50%;text-decoration:none}.food-layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(290px,340px);gap:2rem;align-items:start}.food-sidebar{position:sticky;top:1rem}.food-card{background:var(--surface,#222);border:1px solid var(--border,#555);border-radius:1.2rem;padding:1.2rem;margin-bottom:1rem}.food-card h2,.food-card h3{margin:.1rem 0 .5rem}.food-remaining{font-size:1.45rem;font-weight:700}.food-progress{height:.65rem;background:#7776;border-radius:2rem;overflow:hidden}.food-progress span{display:block;height:100%;background:#62bd70;border-radius:inherit}.food-macros{display:grid;gap:.7rem}.food-macro{display:flex;align-items:center;gap:1rem}.food-macro p{margin:.15rem 0}.food-ring{--accent:#d45b8b;flex:none;width:74px;height:74px;border-radius:50%;display:grid;place-items:center;background:conic-gradient(var(--accent) var(--progress,0%),#7776 0)}.food-ring span{display:grid;place-items:center;width:60px;height:60px;background:var(--surface,#222);border-radius:50%;font-weight:700}.food-macro--blue{--accent:#53a9e7}.food-macro--orange{--accent:#e87952}.food-meal{margin-bottom:1.5rem}.food-meal-heading h2{margin:0}.food-meal-heading p{margin:.1rem 0;color:#62bd70}.food-add-meal{color:#62bd70;font-size:1.8rem}.food-entry-list,.food-product-list{list-style:none;margin:.8rem 0;padding:0}.food-entry,.food-product-list li{background:var(--surface,#222);border:1px solid var(--border,#555);padding:1rem;border-radius:1rem;margin:.4rem 0}.food-entry{display:flex;align-items:center;justify-content:space-between;gap:1rem}.food-entry-main{display:flex;align-items:center;gap:.8rem;min-width:0}.food-entry-main img{width:64px;height:64px;object-fit:contain;background:white;border-radius:.6rem}.food-entry-main strong,.food-entry-main span,.food-entry-main small{display:block}.food-entry-main small,.food-entry-main span,.food-empty{opacity:.75}.food-form-page{max-width:620px;margin:1.5rem auto 4rem}.food-form-page .food-card{margin-top:1rem}.food-search{display:flex;flex-wrap:wrap;gap:.6rem;align-items:center}.food-search input{min-width:180px;flex:1}.food-product-list a{display:block;min-height:44px;align-content:center}.food-form-page details dl{display:grid;grid-template-columns:1fr 1fr;gap:.4rem}.food-form-page details dd{margin:0;text-align:right}@media(max-width:760px){.food-layout{display:flex;flex-direction:column-reverse;gap:1rem}.food-sidebar{position:static;width:100%}.food-macros{grid-template-columns:repeat(3,minmax(0,1fr));gap:.4rem}.food-macro{display:block;padding:.65rem;text-align:center}.food-ring{margin:auto;width:58px;height:58px}.food-ring span{width:46px;height:46px;font-size:.8rem}.food-macro h3{font-size:.9rem;overflow-wrap:anywhere}.food-macro p{font-size:.8rem}.food-heading h1{font-size:1.5rem}.food-page{padding-top:.5rem}}@media(max-width:400px){.food-macros{grid-template-columns:1fr}.food-macro{display:flex;text-align:left}.food-ring{margin:0}}@media(prefers-reduced-motion:reduce){.food-page *{scroll-behavior:auto!important;animation:none!important;transition:none!important}}
.food-product-image{display:block;max-width:180px;max-height:180px;object-fit:contain;background:#fff;border-radius:1rem;margin:0 auto 1rem}
.food-tabs,.food-actions{display:flex;gap:.5rem;flex-wrap:wrap;margin:1rem 0}.food-tabs a{padding:.55rem .9rem;border-radius:2rem;border:1px solid currentColor;text-decoration:none}.food-tabs a[aria-current=page]{background:#62bd70;color:#111;border-color:#62bd70}.food-product-list a,.food-result-button{display:flex;align-items:center;gap:.8rem;width:100%;text-align:left}.food-product-list img{width:58px;height:58px;object-fit:contain;background:#fff;border-radius:.6rem}.food-product-list strong,.food-product-list small{display:block}.food-result-button{border:0;background:none;color:inherit;font:inherit;cursor:pointer;min-height:44px}.food-barcode-form{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;margin:1rem 0}.food-barcode-form input{min-width:130px;flex:1}.food-attribution{font-size:.85rem;opacity:.8}
.food-scanner{max-width:620px;margin:1.5rem auto 6rem}.food-scanner-header{display:flex;align-items:center;gap:1rem}.food-scanner-header a{display:grid;place-items:center;min-width:44px;min-height:44px;font-size:2rem;text-decoration:none}.food-camera-frame{position:relative;aspect-ratio:4/3;background:#111;border-radius:1rem;overflow:hidden}.food-camera-frame video{width:100%;height:100%;object-fit:cover}.food-scan-guide{position:absolute;inset:25% 10%;border:3px solid #62bd70;border-radius:.8rem;pointer-events:none}.food-mobile-switch{display:none}@media(max-width:760px){.food-mobile-switch{position:fixed;bottom:env(safe-area-inset-bottom,0px);left:50%;transform:translateX(-50%);display:flex;gap:.3rem;background:#222;color:#fff;padding:.35rem;border-radius:2rem;z-index:20;box-shadow:0 2px 15px #0008}.food-mobile-switch a,.food-mobile-switch span{display:grid;place-items:center;min-width:110px;min-height:44px;padding:.2rem 1rem;border-radius:2rem;color:inherit;text-decoration:none}.food-mobile-switch [aria-current=page]{background:#555}}
+144
View File
@@ -0,0 +1,144 @@
(() => {
const root = document.querySelector('[data-food-scanner]');
if (!root) return;
const video = root.querySelector('[data-scanner-video]');
const status = root.querySelector('[data-scanner-status]');
const startButton = root.querySelector('[data-scanner-start]');
const stopButton = root.querySelector('[data-scanner-stop]');
const form = root.querySelector('[data-scanner-form]');
const input = root.querySelector('[data-scanner-barcode]');
const formats = ['ean_13', 'ean_8', 'upc_a', 'upc_e', 'code_128'];
let stream = null;
let controls = null;
let frame = null;
let nativeTimeout = null;
let generation = 0;
let locked = false;
let opening = false;
let fallbackStarted = false;
const debug = (...args) => { if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') console.debug('[food:scanner]', ...args); };
const tell = (message) => { status.textContent = message; };
const stop = () => {
generation += 1;
if (frame !== null) cancelAnimationFrame(frame);
frame = null;
if (nativeTimeout !== null) clearTimeout(nativeTimeout);
nativeTimeout = null;
if (controls) controls.stop();
controls = null;
if (stream) { debug('stopping camera tracks'); stream.getTracks().forEach((track) => track.stop()); }
stream = null;
video.pause();
video.srcObject = null;
startButton.hidden = false;
stopButton.hidden = true;
opening = false;
};
const found = (value) => {
const code = String(value || '').trim();
if (locked || !/^[0-9]{6,64}$/.test(code)) return;
locked = true;
debug('detected', code);
tell('Barcode found. Looking up product…');
stop();
input.value = code;
form.requestSubmit();
};
const loadZXing = () => new Promise((resolve, reject) => {
if (window.ZXingBrowser) return resolve(window.ZXingBrowser);
const script = document.createElement('script');
script.src = root.dataset.zxingUrl;
script.onload = () => window.ZXingBrowser ? resolve(window.ZXingBrowser) : reject(new Error('Scanner library unavailable'));
script.onerror = () => reject(new Error('Scanner library unavailable'));
document.head.append(script);
});
const fallback = async (token) => {
if (token !== generation || !stream || fallbackStarted) return;
fallbackStarted = true;
if (frame !== null) cancelAnimationFrame(frame);
frame = null;
if (nativeTimeout !== null) clearTimeout(nativeTimeout);
nativeTimeout = null;
debug('using ZXing fallback');
tell('Scanning barcode…');
try {
const zxing = await loadZXing();
if (token !== generation || !stream) return;
const reader = new zxing.BrowserMultiFormatOneDReader();
const active = await reader.decodeFromStream(stream, video, (result, error, scanControls) => {
if (result) {
controls = scanControls;
found(result.getText());
}
});
if (token !== generation || !stream) active.stop();
else controls = active;
} catch (error) {
debug('fallback error', error);
stop();
tell('Scanner unavailable. Enter the barcode manually.');
input.focus();
}
};
const native = async (token) => {
if (!('BarcodeDetector' in window)) return false;
try {
const supported = await window.BarcodeDetector.getSupportedFormats();
const usable = formats.filter((format) => supported.includes(format));
if (!usable.length || token !== generation) return false;
debug('native BarcodeDetector available');
const detector = new window.BarcodeDetector({ formats: usable });
let failures = 0;
const scan = async () => {
if (token !== generation || locked || fallbackStarted) return;
try {
const hits = await detector.detect(video);
if (token !== generation || locked || fallbackStarted) return;
if (hits.length) { found(hits[0].rawValue); return; }
} catch (error) {
failures += 1;
if (failures >= 3) { fallback(token); return; }
}
if (!fallbackStarted) frame = requestAnimationFrame(scan);
};
nativeTimeout = setTimeout(() => { if (token === generation && !locked) fallback(token); }, 12000);
frame = requestAnimationFrame(scan);
return true;
} catch (error) { debug('native detector unavailable', error); return false; }
};
const open = async () => {
if (opening || stream) return;
locked = false;
fallbackStarted = false;
opening = true;
const token = ++generation;
startButton.hidden = true;
tell('Requesting camera…');
debug('requesting camera');
try {
if (!navigator.mediaDevices?.getUserMedia) throw new Error('Camera API unavailable');
const acquired = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } } });
if (token !== generation) { acquired.getTracks().forEach((track) => track.stop()); return; }
stream = acquired;
video.srcObject = stream;
await video.play();
if (token !== generation) return;
opening = false;
stopButton.hidden = false;
tell('Scanning barcode…');
if (!(await native(token))) await fallback(token);
} catch (error) {
debug('camera error', error);
stop();
tell('Camera unavailable or permission denied. Enter the barcode manually.');
input.focus();
}
};
startButton.addEventListener('click', open);
stopButton.addEventListener('click', () => { stop(); tell('Camera is off.'); startButton.focus(); });
form.addEventListener('submit', () => { locked = true; stop(); tell('Looking up product…'); });
root.querySelector('[data-scanner-close]').addEventListener('click', stop);
document.addEventListener('visibilitychange', () => { if (document.hidden) stop(); });
window.addEventListener('pagehide', stop);
})();
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 ZXing for JS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because one or more lines are too long