157 lines
6.1 KiB
TypeScript
157 lines
6.1 KiB
TypeScript
"use client";
|
|
|
|
import { Pause, Play, Timer as TimerIcon } from "lucide-react";
|
|
import { useTranslations } from "next-intl";
|
|
import { useEffect, useState } from "react";
|
|
import { Button } from "@/components/ui/button";
|
|
import { labelFor } from "@/lib/ingredient-name";
|
|
import type { Section } from "@/lib/recipe-style";
|
|
import { timerFromText } from "@/lib/timer";
|
|
import { type BaseUnit, type DisplayUnit } from "@/lib/units";
|
|
import { useKitchenAmount } from "@/lib/use-kitchen-amount";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
// Gemeinsames von Kochmodus und Präsentation (26.11.28): Display an lassen,
|
|
// Timer gegen die Uhr, Mengen in der Portionszahl.
|
|
|
|
export type Ingredient = {
|
|
ingredientId: string;
|
|
name: string;
|
|
forms: { one: string; other: string } | null;
|
|
qtyPerPortion: number;
|
|
unit: BaseUnit;
|
|
note: string | null;
|
|
displayUnit?: DisplayUnit | null;
|
|
packSize?: number | null;
|
|
};
|
|
export type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
|
|
export type Running = { step: number; endsAt: number | null; left: number; done: boolean };
|
|
|
|
export const mmss = (s: number) => `${Math.floor(s / 60)}:${String(Math.max(0, Math.round(s % 60))).padStart(2, "0")}`;
|
|
|
|
function beep() {
|
|
try {
|
|
const ctx = new AudioContext();
|
|
for (const [i, f] of [880, 660, 880].entries()) {
|
|
const o = ctx.createOscillator();
|
|
const g = ctx.createGain();
|
|
o.frequency.value = f;
|
|
o.connect(g).connect(ctx.destination);
|
|
g.gain.setValueAtTime(0.2, ctx.currentTime + i * 0.35);
|
|
o.start(ctx.currentTime + i * 0.35);
|
|
o.stop(ctx.currentTime + i * 0.35 + 0.25);
|
|
}
|
|
} catch {}
|
|
}
|
|
|
|
/** Display an lassen, solange die Ansicht offen ist (Screen Wake Lock). */
|
|
export function useWakeLock(): boolean {
|
|
const [awake, setAwake] = useState(false);
|
|
useEffect(() => {
|
|
let lock: WakeLockSentinel | null = null;
|
|
const request = async () => {
|
|
try {
|
|
lock = (await navigator.wakeLock?.request("screen")) ?? null;
|
|
setAwake(!!lock);
|
|
} catch {
|
|
setAwake(false);
|
|
}
|
|
};
|
|
void request();
|
|
const again = () => document.visibilityState === "visible" && void request();
|
|
document.addEventListener("visibilitychange", again);
|
|
return () => {
|
|
document.removeEventListener("visibilitychange", again);
|
|
void lock?.release().catch(() => undefined);
|
|
};
|
|
}, []);
|
|
return awake;
|
|
}
|
|
|
|
/** Timer je Schritt; laufen weiter beim Blättern, gerechnet gegen die Uhr, nicht gegen Intervalle. */
|
|
export function useStepTimers() {
|
|
const t = useTranslations("cooking");
|
|
const [timers, setTimers] = useState<Running[]>([]);
|
|
const [alarm, setAlarm] = useState<string | null>(null);
|
|
useEffect(() => {
|
|
const tick = setInterval(() => {
|
|
setTimers((list) =>
|
|
list.map((r) => {
|
|
if (r.done || r.endsAt === null) return r;
|
|
const left = (r.endsAt - Date.now()) / 1000;
|
|
if (left > 0) return { ...r, left };
|
|
if ("vibrate" in navigator) navigator.vibrate?.([300, 150, 300]);
|
|
beep();
|
|
setAlarm(t("alarm", { n: r.step + 1 }));
|
|
return { ...r, left: 0, done: true, endsAt: null };
|
|
}),
|
|
);
|
|
}, 500);
|
|
return () => clearInterval(tick);
|
|
}, [t]);
|
|
|
|
function toggle(step: number, seconds: number) {
|
|
setAlarm(null);
|
|
setTimers((list) => {
|
|
const r = list.find((x) => x.step === step);
|
|
if (!r || r.done) return [...list.filter((x) => x.step !== step), { step, endsAt: Date.now() + seconds * 1000, left: seconds, done: false }];
|
|
if (r.endsAt === null) return list.map((x) => (x.step === step ? { ...x, endsAt: Date.now() + x.left * 1000 } : x)); // weiter
|
|
return list.map((x) => (x.step === step ? { ...x, endsAt: null } : x)); // Pause
|
|
});
|
|
}
|
|
|
|
return { timers, alarm, toggle, running: timers.filter((r) => !r.done || r.left === 0) };
|
|
}
|
|
|
|
/** Kein hinterlegter Timer? Dann die Zeit aus dem Text („30 Minuten köcheln“). */
|
|
export const withTextTimer = (s: Step): Step => ({ ...s, timerSeconds: s.timerSeconds ?? timerFromText(s.text) });
|
|
|
|
/** „250 g“ in der Portionszahl, und der passende Name (Einzahl/Mehrzahl). */
|
|
export function useAmount(portions: number) {
|
|
const kitchen = useKitchenAmount();
|
|
return {
|
|
// „2 EL (30 ml)“, „400 g (1 Dose)“ — lib/units.ts formatKitchen (26.11.39).
|
|
amount: (i: Ingredient) => kitchen.text(i, i.qtyPerPortion * portions),
|
|
label: (i: Ingredient) => labelFor(i, i.qtyPerPortion * portions),
|
|
};
|
|
}
|
|
|
|
export function AlarmNotice({ alarm }: { alarm: string | null }) {
|
|
return (
|
|
<p role="alert" aria-live="assertive" className={cn(alarm ? "rounded-xl border border-accent bg-accent/10 px-4 py-3 font-semibold" : "sr-only")}>
|
|
{alarm}
|
|
</p>
|
|
);
|
|
}
|
|
|
|
export function TimerChips({ running, onPick, className }: { running: Running[]; onPick: (step: number) => void; className?: string }) {
|
|
const t = useTranslations("cooking");
|
|
if (!running.length) return null;
|
|
return (
|
|
<ul className={cn("flex flex-wrap gap-2", className)} aria-label={t("timers")}>
|
|
{running.map((r) => (
|
|
<li key={r.step}>
|
|
<Button type="button" variant="outline" onClick={() => onPick(r.step)}>
|
|
<TimerIcon aria-hidden />
|
|
{t("timerChip", { n: r.step + 1, time: mmss(r.left) })}
|
|
</Button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
);
|
|
}
|
|
|
|
export function TimerButton({ running, seconds, onToggle, className }: { running: Running | undefined; seconds: number; onToggle: () => void; className?: string }) {
|
|
const t = useTranslations("cooking");
|
|
const active = running && !running.done && running.endsAt !== null;
|
|
const paused = running && !running.done && running.endsAt === null;
|
|
const left = running && !running.done ? running.left : seconds;
|
|
return (
|
|
<Button type="button" variant={active ? "default" : "outline"} size="lg" className={cn("h-16 self-start px-6 text-2xl tabular-nums", className)} onClick={onToggle}>
|
|
{active ? <Pause aria-hidden /> : <Play aria-hidden />}
|
|
<span>{mmss(left)}</span>
|
|
<span className="sr-only">{active ? t("pause") : paused ? t("resume") : t("startTimer")}</span>
|
|
</Button>
|
|
);
|
|
}
|