- axe is clean across every screen in both themes, phone and desktop. Fixed: the hidden file inputs (aria-hidden + tabIndex -1 — they are opened by labelled buttons, so they should not be in the accessibility tree), the heading order (deck/homework/smart-review cards are h2 under the page h1; LearningSection takes a level so it stays h2 on the library and h3 inside the settings dialog) and landmarks around the study and review feeds. - tests/contrast.mjs (new diagnostic): samples rendered pixels, because axe cannot judge text on blurred glass — it reports those nodes as incomplete. It skips disabled controls (1.4.3 exempts them) and content behind an open sheet. Result: no below-minimum text on any scanned screen. - The report control exists in the homework guide too: under each "Try it yourself" exercise, labelled "Report exercise", without a skip (there is no queue to skip). lib/question-reports now takes deckId/deckTitle directly. - The rail's two creation actions are buttons now (.nav-action) rather than quiet nav rows — once the library is full they were the only way to start something on desktop and read as just more navigation. "Make my homework" is "New homework" wherever it is an action (rail, empty state, share chooser, manifest shortcut); the page title and mode switch keep their wording. Version 0.1.6 (three task bumps), SW -> freezmo-v52.
218 lines
7.6 KiB
TypeScript
218 lines
7.6 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState, useSyncExternalStore } from "react";
|
|
|
|
import { Button } from "@/components/ui";
|
|
import { haptic } from "@/lib/haptics";
|
|
import { localeHeader, useI18n } from "@/lib/i18n";
|
|
import { authHeaders, saveSettings, settingsStore } from "@/lib/settings";
|
|
|
|
const GOALS = [10, 20, 30, 50];
|
|
|
|
type PushStatus = { enabled: boolean; publicKey?: string };
|
|
|
|
function urlBase64ToUint8Array(base64: string): Uint8Array {
|
|
const padding = "=".repeat((4 - (base64.length % 4)) % 4);
|
|
const normalized = (base64 + padding).replace(/-/g, "+").replace(/_/g, "/");
|
|
const raw = atob(normalized);
|
|
const bytes = new Uint8Array(raw.length);
|
|
for (let index = 0; index < raw.length; index++) bytes[index] = raw.charCodeAt(index);
|
|
return bytes;
|
|
}
|
|
|
|
/**
|
|
* Settings → Learning: the daily goal, plus push reminders — but only when
|
|
* the server has VAPID keys configured. Without them the reminder block is
|
|
* hidden completely, exactly as if the feature did not exist.
|
|
*/
|
|
/**
|
|
* `level` keeps the heading order right in both places it is used: h2 on the
|
|
* library page (under its h1) and h3 inside the settings dialog (under its h2
|
|
* title).
|
|
*/
|
|
export function LearningSection({ level = 2 }: { level?: 2 | 3 } = {}) {
|
|
const { t } = useI18n();
|
|
const dailyGoal = useSyncExternalStore(
|
|
settingsStore.subscribe,
|
|
() => settingsStore.getSnapshot().dailyGoal,
|
|
() => 20,
|
|
);
|
|
const [status, setStatus] = useState<PushStatus | null>(null);
|
|
const [subscribed, setSubscribed] = useState(false);
|
|
const [endpoint, setEndpoint] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const [notice, setNotice] = useState<string | null>(null);
|
|
|
|
const pushSupported =
|
|
typeof window !== "undefined" &&
|
|
"serviceWorker" in navigator &&
|
|
"PushManager" in window &&
|
|
"Notification" in window;
|
|
|
|
useEffect(() => {
|
|
if (!pushSupported) return;
|
|
let cancelled = false;
|
|
void (async () => {
|
|
try {
|
|
const response = await fetch("/api/push", {
|
|
headers: { ...authHeaders(), ...localeHeader() },
|
|
cache: "no-store",
|
|
});
|
|
const body = (await response.json()) as PushStatus;
|
|
if (cancelled) return;
|
|
setStatus(body);
|
|
if (body.enabled) {
|
|
const registration = await navigator.serviceWorker.ready.catch(() => null);
|
|
const subscription = await registration?.pushManager.getSubscription();
|
|
if (!cancelled && subscription) {
|
|
setSubscribed(true);
|
|
setEndpoint(subscription.endpoint);
|
|
}
|
|
}
|
|
} catch {
|
|
if (!cancelled) setStatus({ enabled: false });
|
|
}
|
|
})();
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [pushSupported]);
|
|
|
|
const enable = async () => {
|
|
if (!status?.publicKey) return;
|
|
setBusy(true);
|
|
setNotice(null);
|
|
try {
|
|
const permission = await Notification.requestPermission();
|
|
if (permission !== "granted") {
|
|
setNotice(t("settings.reminderDenied"));
|
|
return;
|
|
}
|
|
const registration = await navigator.serviceWorker.ready;
|
|
const subscription = await registration.pushManager.subscribe({
|
|
userVisibleOnly: true,
|
|
applicationServerKey: urlBase64ToUint8Array(status.publicKey) as unknown as BufferSource,
|
|
});
|
|
const response = await fetch("/api/push", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", ...authHeaders(), ...localeHeader() },
|
|
body: JSON.stringify(subscription.toJSON()),
|
|
});
|
|
if (!response.ok) throw new Error("subscribe failed");
|
|
setSubscribed(true);
|
|
setEndpoint(subscription.endpoint);
|
|
setNotice(t("settings.reminderOn"));
|
|
haptic("toggle");
|
|
} catch {
|
|
setNotice(t("settings.reminderError"));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const disable = async () => {
|
|
setBusy(true);
|
|
setNotice(null);
|
|
try {
|
|
const registration = await navigator.serviceWorker.ready.catch(() => null);
|
|
const subscription = await registration?.pushManager.getSubscription();
|
|
if (subscription) {
|
|
await fetch(`/api/push?endpoint=${encodeURIComponent(subscription.endpoint)}`, {
|
|
method: "DELETE",
|
|
headers: { ...authHeaders(), ...localeHeader() },
|
|
});
|
|
await subscription.unsubscribe();
|
|
}
|
|
setSubscribed(false);
|
|
setEndpoint(null);
|
|
setNotice(t("settings.reminderOff"));
|
|
} catch {
|
|
setNotice(t("settings.reminderError"));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const test = async () => {
|
|
if (!endpoint) return;
|
|
setBusy(true);
|
|
setNotice(null);
|
|
try {
|
|
const response = await fetch("/api/push/test", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", ...authHeaders(), ...localeHeader() },
|
|
body: JSON.stringify({ endpoint }),
|
|
});
|
|
if (!response.ok) throw new Error("test failed");
|
|
setNotice(t("settings.reminderOn"));
|
|
} catch {
|
|
setNotice(t("settings.reminderError"));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const iosNeedsInstall =
|
|
typeof navigator !== "undefined" &&
|
|
/iPhone|iPad|iPod/.test(navigator.userAgent) &&
|
|
!(navigator as Navigator & { standalone?: boolean }).standalone;
|
|
|
|
return (
|
|
<section className="mb-4 space-y-3 rounded-2xl border border-[var(--hairline)] bg-[var(--surface-sunken)] p-3">
|
|
{level === 3 ? (
|
|
<h3 className="text-sm font-semibold text-frost-950 dark:text-frost-50">{t("settings.learning")}</h3>
|
|
) : (
|
|
<h2 className="text-sm font-semibold text-frost-950 dark:text-frost-50">{t("settings.learning")}</h2>
|
|
)}
|
|
|
|
<div className="space-y-1.5">
|
|
<p className="text-[12px] font-semibold text-[var(--text)]">{t("settings.dailyGoal")}</p>
|
|
<p className="text-[11px] leading-snug text-[var(--text-subtle)]">{t("settings.dailyGoalNote")}</p>
|
|
<div className="segmented" role="group" aria-label={t("settings.dailyGoal")}>
|
|
{GOALS.map((goal) => (
|
|
<button
|
|
key={goal}
|
|
type="button"
|
|
aria-pressed={dailyGoal === goal}
|
|
onClick={() => {
|
|
haptic("toggle");
|
|
saveSettings({ dailyGoal: goal });
|
|
}}
|
|
>
|
|
<span className="seg-label">{goal}</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
{pushSupported && status?.enabled ? (
|
|
<div className="space-y-2 border-t border-[var(--hairline-soft)] pt-2.5">
|
|
<p className="text-[12px] font-semibold text-[var(--text)]">{t("settings.reminders")}</p>
|
|
<p className="text-[11px] leading-snug text-[var(--text-subtle)]">{t("settings.remindersNote")}</p>
|
|
{iosNeedsInstall ? (
|
|
<p className="text-[11px] font-medium leading-snug text-amber-700 dark:text-amber-300">
|
|
{t("settings.remindersIos")}
|
|
</p>
|
|
) : null}
|
|
<div className="flex flex-wrap gap-2">
|
|
{subscribed ? (
|
|
<>
|
|
<Button size="sm" variant="secondary" loading={busy} onClick={() => void test()}>
|
|
{t("settings.reminderTest")}
|
|
</Button>
|
|
<Button size="sm" variant="ghost" loading={busy} onClick={() => void disable()}>
|
|
{t("settings.reminderDisable")}
|
|
</Button>
|
|
</>
|
|
) : (
|
|
<Button size="sm" loading={busy} onClick={() => void enable()}>
|
|
{t("settings.reminderEnable")}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
{notice ? <p className="text-[12px] font-medium text-[var(--text-muted)]">{notice}</p> : null}
|
|
</div>
|
|
) : null}
|
|
</section>
|
|
);
|
|
}
|