Fix live swipe paging and retain tilt preference on iOS
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 29s
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 29s
Replace the damped single-screen fade with live mobile panels on a shared composited rail, preserving per-tab scrolling and pausing offscreen physics. Center macro text and separate the saved tilt switch from session motion permission, resuming permission from a normal interaction. Validate live previews, interruption and multi-touch cancellation, relaunch, and permission races.
This commit is contained in:
parent
7288e56c02
commit
3c0d6560f1
15 changed files with 784 additions and 263 deletions
|
|
@ -11,7 +11,7 @@ A single-user, self-hosted nutrition journal. PWA first, with a responsive deskt
|
|||
- Independently enabled calorie, protein, carbohydrate, fat, fiber, sugar and sodium goals.
|
||||
- Weight journal in lb or kg; internally stored in kg. Multiple weigh-ins are retained, with the latest measurement per day used in charts.
|
||||
- Dedicated Weight tab on desktop and mobile, with its own logging, graph and journal. Nutrition trends live under Library → Trends. Both support 7 / 30 / 90 / 365 day periods. Nutrition averages exclude empty and likely incomplete days: the initial cutoff is half the calorie target, adjustable under Settings → Nutrition averages (0 includes all logged days). Every nutrient uses the same qualifying days; faded bars and exports retain actual totals. This is a logging heuristic, so adjust it for your own routine. Saving preferences stores the cutoff in kcal independently of later goal changes.
|
||||
- On phones, swipe left/right through Today → Library → Weight → Settings. Vertical scrolling, form controls, horizontal macro scrolling, and browser edge gestures remain independent. Pages and sheets animate with touch feedback; pull down from a sheet header to dismiss it. System Reduce Motion disables these transitions.
|
||||
- On phones, swipe left/right through Today → Library → Weight → Settings. Neighboring screens are already rendered and move together under your finger; settling uses a composited slide with no fade-to-blank delay. Every tab retains its own scroll position. Vertical scrolling, form controls, horizontal macro scrolling, and browser edge gestures remain independent. The calorie simulation pauses on other tabs. Pull down from a sheet header to dismiss it. System Reduce Motion disables these transitions.
|
||||
- Markdown, CSV and JSON export with date range, nutrient and weight selections. Markdown is designed for LLM analysis. Data is downloaded locally, never submitted to an LLM. Save preferences to remember the export format, range preset and selections.
|
||||
- Password authentication, IndexedDB offline journal/outbox, a precached app shell, automatic foreground/reconnect sync, and explicit PWA update prompts.
|
||||
|
||||
|
|
@ -77,7 +77,7 @@ To restore a database backup: stop Calio, preserve the current data directory, r
|
|||
|
||||
### Bubble motion
|
||||
|
||||
Enable **Settings → Look & feel → Tilt calorie bubbles** to allow device orientation. On iPhone, Safari asks for motion/orientation permission from that gesture; the public site must use HTTPS. The preference is stored only on this device, and iOS may require enabling it again after reopening the app. Sensor readings are never transmitted. Portrait, landscape and upside-down positions are mapped to the screen's gravity direction. Devices without sensors, or with permission denied, retain downward gravity.
|
||||
Enable **Settings → Look & feel → Tilt calorie bubbles** to allow device orientation. On iPhone, Safari asks for motion/orientation permission from that gesture; the public site must use HTTPS. The preference stays saved on this device across reopening, independently of browser permission. If iOS needs motion access again, Calio resumes it on your first normal interaction; Settings also provides **Allow motion** if needed. A denied request keeps the preference on and explains why tilt is unavailable. Sensor readings are never transmitted. Portrait, landscape and upside-down positions are mapped to the screen's gravity direction. Devices without sensors, or with permission denied, retain downward gravity.
|
||||
|
||||
The circle uses a bounded Matter.js simulation: bubbles collide with each other and the circular wall, new calorie bubbles drop from the top at 30 per second (50% faster than the original pace), and removing calories removes the corresponding particles. Bubbles draw smaller than their collision boundaries, creating a small visible gap between them. A full hexagonal packing defines the 100% capacity. The numeric readout always sits below the circle, leaving every dot visible. The particle count caps at the daily goal; over-goal calories still show the exact excess and a red ring. With the calorie goal disabled, the display uses a fixed 2,500 kcal visual scale. Macro bars animate when totals change, and rows with one or two tracked macros are centered. Motion honors the device's reduced-motion preference. The physics animation sleeps when settled and pauses in hidden tabs. The graphic is an approximate visual; the numeric calorie total is authoritative.
|
||||
|
||||
|
|
|
|||
262
src/App.tsx
262
src/App.tsx
|
|
@ -76,7 +76,40 @@ import { Trends } from "./Trends";
|
|||
import { Settings } from "./Settings";
|
||||
|
||||
import { Presence } from "./Presence";
|
||||
import { useNavigation } from "./useNavigation";
|
||||
import { useNavigation, type Page } from "./useNavigation";
|
||||
import { PageActivity } from "./PageActivity";
|
||||
import { useTiltResume } from "./useTilt";
|
||||
function PagePanel({
|
||||
name,
|
||||
page,
|
||||
mobile,
|
||||
header,
|
||||
children,
|
||||
}: {
|
||||
name: Page;
|
||||
page: Page;
|
||||
mobile: boolean;
|
||||
header?: ReactNode;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const active = page === name;
|
||||
return (
|
||||
<section
|
||||
className={"page-panel page-" + name}
|
||||
data-page={name}
|
||||
aria-hidden={!active}
|
||||
inert={!active}
|
||||
>
|
||||
<Activity mode={mobile || active ? "visible" : "hidden"}>
|
||||
<PageActivity value={active}>
|
||||
{header}
|
||||
<div className="page-body">{children}</div>
|
||||
</PageActivity>
|
||||
</Activity>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type Editor =
|
||||
| { kind: "log"; meal: Meal; record?: JournalRecord<Entry> }
|
||||
| { kind: "food"; record?: JournalRecord<Food> }
|
||||
|
|
@ -800,11 +833,10 @@ export function App() {
|
|||
const status = useSyncStatus();
|
||||
const [ready, setReady] = useState(false);
|
||||
const [fatal, setFatal] = useState("");
|
||||
const {
|
||||
page,
|
||||
navigate,
|
||||
ref: pageRef,
|
||||
} = useNavigation(ready && journal.unlocked);
|
||||
const { page, navigate, mobile, viewportRef, railRef } = useNavigation(
|
||||
ready && journal.unlocked,
|
||||
);
|
||||
useTiltResume(ready && journal.unlocked);
|
||||
const [date, setDate] = useState(today());
|
||||
const [editor, setEditor] = useState<Editor>(null);
|
||||
const [toast, setToast] = useState("");
|
||||
|
|
@ -965,8 +997,42 @@ export function App() {
|
|||
<span>{syncLabel}</span>
|
||||
</button>
|
||||
);
|
||||
const notices = (
|
||||
<>
|
||||
{status.needsLogin && (
|
||||
<div className="notice">
|
||||
<LockKeyhole size={17} />
|
||||
<span>Your session expired. Local logging is still available.</span>
|
||||
<button onClick={() => setReauth(true)}>Sign in</button>
|
||||
</div>
|
||||
)}
|
||||
{status.error && (
|
||||
<div className="notice">
|
||||
<CloudOff size={17} />
|
||||
<span>Saved on this device. {status.error}</span>
|
||||
<button onClick={() => void sync()}>Retry sync</button>
|
||||
</div>
|
||||
)}
|
||||
{waiting && (
|
||||
<div className="notice">
|
||||
<Sparkles size={17} />
|
||||
<span>A fresh version of Calio is ready.</span>
|
||||
<button onClick={() => void update()}>Update</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
const panelHeader = (
|
||||
<header className="topbar panel-topbar">
|
||||
<div className="mobile-brand brand">
|
||||
<img src="/icon.svg" alt="" />
|
||||
calio
|
||||
</div>
|
||||
{syncControl}
|
||||
</header>
|
||||
);
|
||||
return (
|
||||
<div className={"app-shell page-" + page}>
|
||||
<div className={"app-shell" + (mobile ? " mobile-pager" : "")}>
|
||||
<aside className="sidebar">
|
||||
<a
|
||||
className="brand"
|
||||
|
|
@ -996,7 +1062,7 @@ export function App() {
|
|||
</nav>
|
||||
</aside>
|
||||
<div className="main-wrap">
|
||||
<header className="topbar">
|
||||
<header className="topbar desktop-topbar">
|
||||
<span className="breadcrumb">
|
||||
Your journal <span>/</span> {nav.find((n) => n.key === page)?.label}
|
||||
</span>
|
||||
|
|
@ -1010,100 +1076,98 @@ export function App() {
|
|||
</span>
|
||||
</header>
|
||||
<main
|
||||
ref={pageRef}
|
||||
ref={viewportRef}
|
||||
tabIndex={-1}
|
||||
className="page-content"
|
||||
className="page-viewport"
|
||||
aria-label={nav.find((n) => n.key === page)?.label}
|
||||
>
|
||||
{status.needsLogin && (
|
||||
<div className="notice">
|
||||
<LockKeyhole size={17} />
|
||||
<span>
|
||||
Your session expired. Local logging is still available.
|
||||
</span>
|
||||
<button onClick={() => setReauth(true)}>Sign in</button>
|
||||
</div>
|
||||
)}
|
||||
{status.error && (
|
||||
<div className="notice">
|
||||
<CloudOff size={17} />
|
||||
<span>Saved on this device. {status.error}</span>
|
||||
<button onClick={() => void sync()}>Retry sync</button>
|
||||
</div>
|
||||
)}
|
||||
{waiting && (
|
||||
<div className="notice">
|
||||
<Sparkles size={17} />
|
||||
<span>A fresh version of Calio is ready.</span>
|
||||
<button onClick={() => void update()}>Update</button>
|
||||
</div>
|
||||
)}
|
||||
<Activity mode={page === "today" ? "visible" : "hidden"}>
|
||||
<Dashboard
|
||||
records={journal.records}
|
||||
settings={settings}
|
||||
date={date}
|
||||
setDate={setDate}
|
||||
add={(meal) => setEditor({ kind: "log", meal })}
|
||||
edit={(record) =>
|
||||
setEditor({ kind: "log", meal: record.data.meal, record })
|
||||
}
|
||||
remove={setDeleting}
|
||||
openLibrary={() => navigate("library")}
|
||||
syncControl={syncControl}
|
||||
/>
|
||||
</Activity>
|
||||
<Activity mode={page === "library" ? "visible" : "hidden"}>
|
||||
<Library
|
||||
foods={foods}
|
||||
plates={plates}
|
||||
newFood={() => setEditor({ kind: "food" })}
|
||||
newPlate={() => setEditor({ kind: "plate" })}
|
||||
editFood={(record) => setEditor({ kind: "food", record })}
|
||||
editPlate={(record) => setEditor({ kind: "plate", record })}
|
||||
log={() => setEditor({ kind: "log", meal: suggestedMeal() })}
|
||||
remove={setDeleting}
|
||||
trends={
|
||||
<Trends
|
||||
mode="nutrition"
|
||||
records={journal.records}
|
||||
settings={settings}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Activity>
|
||||
<Activity mode={page === "weight" ? "visible" : "hidden"}>
|
||||
<Trends
|
||||
mode="weight"
|
||||
records={journal.records}
|
||||
settings={settings}
|
||||
logWeight={() => setEditor({ kind: "weight" })}
|
||||
editWeight={(record) => setEditor({ kind: "weight", record })}
|
||||
remove={setDeleting}
|
||||
/>
|
||||
</Activity>
|
||||
<Activity mode={page === "settings" ? "visible" : "hidden"}>
|
||||
<Settings
|
||||
key={
|
||||
recordsOf<SettingsData>(journal.records, "settings")[0]
|
||||
?.updatedAt || "initial"
|
||||
}
|
||||
settings={settings}
|
||||
records={journal.records}
|
||||
pending={journal.outbox.length}
|
||||
lastSync={journal.lastSync}
|
||||
notify={notify}
|
||||
install={
|
||||
installEvent
|
||||
? () => {
|
||||
void installEvent.prompt();
|
||||
setInstallEvent(null);
|
||||
}
|
||||
: null
|
||||
}
|
||||
update={waiting ? () => void update() : null}
|
||||
/>
|
||||
</Activity>
|
||||
<div className="page-rail" ref={railRef}>
|
||||
<PagePanel name="today" page={page} mobile={mobile}>
|
||||
{notices}
|
||||
<Dashboard
|
||||
records={journal.records}
|
||||
settings={settings}
|
||||
date={date}
|
||||
setDate={setDate}
|
||||
add={(meal) => setEditor({ kind: "log", meal })}
|
||||
edit={(record) =>
|
||||
setEditor({ kind: "log", meal: record.data.meal, record })
|
||||
}
|
||||
remove={setDeleting}
|
||||
openLibrary={() => navigate("library")}
|
||||
syncControl={syncControl}
|
||||
/>
|
||||
</PagePanel>
|
||||
<PagePanel
|
||||
name="library"
|
||||
page={page}
|
||||
mobile={mobile}
|
||||
header={panelHeader}
|
||||
>
|
||||
{notices}
|
||||
<Library
|
||||
foods={foods}
|
||||
plates={plates}
|
||||
newFood={() => setEditor({ kind: "food" })}
|
||||
newPlate={() => setEditor({ kind: "plate" })}
|
||||
editFood={(record) => setEditor({ kind: "food", record })}
|
||||
editPlate={(record) => setEditor({ kind: "plate", record })}
|
||||
log={() => setEditor({ kind: "log", meal: suggestedMeal() })}
|
||||
remove={setDeleting}
|
||||
trends={
|
||||
<Trends
|
||||
mode="nutrition"
|
||||
records={journal.records}
|
||||
settings={settings}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</PagePanel>
|
||||
<PagePanel
|
||||
name="weight"
|
||||
page={page}
|
||||
mobile={mobile}
|
||||
header={panelHeader}
|
||||
>
|
||||
{notices}
|
||||
<Trends
|
||||
mode="weight"
|
||||
records={journal.records}
|
||||
settings={settings}
|
||||
logWeight={() => setEditor({ kind: "weight" })}
|
||||
editWeight={(record) => setEditor({ kind: "weight", record })}
|
||||
remove={setDeleting}
|
||||
/>
|
||||
</PagePanel>
|
||||
<PagePanel
|
||||
name="settings"
|
||||
page={page}
|
||||
mobile={mobile}
|
||||
header={panelHeader}
|
||||
>
|
||||
{notices}
|
||||
<Settings
|
||||
key={
|
||||
recordsOf<SettingsData>(journal.records, "settings")[0]
|
||||
?.updatedAt || "initial"
|
||||
}
|
||||
settings={settings}
|
||||
records={journal.records}
|
||||
pending={journal.outbox.length}
|
||||
lastSync={journal.lastSync}
|
||||
notify={notify}
|
||||
install={
|
||||
installEvent
|
||||
? () => {
|
||||
void installEvent.prompt();
|
||||
setInstallEvent(null);
|
||||
}
|
||||
: null
|
||||
}
|
||||
update={waiting ? () => void update() : null}
|
||||
/>
|
||||
</PagePanel>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<nav className="bottom-nav" aria-label="Mobile navigation">
|
||||
|
|
|
|||
4
src/PageActivity.ts
Normal file
4
src/PageActivity.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import { createContext } from "react";
|
||||
|
||||
// Offscreen pager panels retain their view, while expensive simulations pause.
|
||||
export const PageActivity = createContext(true);
|
||||
|
|
@ -215,7 +215,7 @@ export function Settings({
|
|||
</div>
|
||||
<div className="settings-section">
|
||||
<h3>Look & feel</h3>
|
||||
<div className="preference-row">
|
||||
<div className="preference-row" data-tilt-control>
|
||||
<label className="toggle-label">
|
||||
<input
|
||||
className="switch"
|
||||
|
|
@ -228,13 +228,24 @@ export function Settings({
|
|||
</div>
|
||||
<p className="small muted" role="status">
|
||||
{tilt.status === "denied"
|
||||
? "Motion permission was not granted. Check your browser’s website permissions."
|
||||
? "Tilt stays saved, but motion access was not granted. Allow motion or check your browser’s website permissions."
|
||||
: tilt.status === "unavailable"
|
||||
? "Orientation sensors are unavailable on this device. Bubbles still fall normally."
|
||||
: tilt.status === "permission"
|
||||
? "Enable tilt again to grant motion access for this session."
|
||||
: "Uses this device’s orientation. iPhone may request permission again after reopening. Reduced motion pauses the animation."}
|
||||
? "Tilt is saved. Motion access resumes on your next tap, or use Allow motion below."
|
||||
: "Saved on this device. If iOS asks for motion access after reopening, allow it to resume tilt. Reduced motion pauses the animation."}
|
||||
</p>
|
||||
{tilt.enabled &&
|
||||
(tilt.status === "permission" || tilt.status === "denied") && (
|
||||
<button
|
||||
className="secondary"
|
||||
type="button"
|
||||
data-tilt-control
|
||||
onClick={() => void tilt.requestTiltPermission()}
|
||||
>
|
||||
Allow motion
|
||||
</button>
|
||||
)}
|
||||
<div className="segmented theme-control">
|
||||
{(
|
||||
[
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { App } from "./App";
|
|||
import "./styles.css";
|
||||
import "./mobile.css";
|
||||
import "./motion.css";
|
||||
import "./pager.css";
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
|
|
|
|||
|
|
@ -198,7 +198,7 @@
|
|||
.page-today .topbar {
|
||||
display: none;
|
||||
}
|
||||
.page-today main {
|
||||
.page-today .page-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
|
|
@ -413,7 +413,7 @@
|
|||
color: var(--muted);
|
||||
font-size: 15px;
|
||||
}
|
||||
.page-today main > .notice {
|
||||
.page-today .page-body > .notice {
|
||||
flex: none;
|
||||
max-height: 100px;
|
||||
overflow-y: auto;
|
||||
|
|
@ -835,7 +835,7 @@
|
|||
}
|
||||
|
||||
@media (max-width: 365px) {
|
||||
.page-today main {
|
||||
.page-today .page-body {
|
||||
padding-inline: 16px;
|
||||
}
|
||||
main {
|
||||
|
|
@ -867,7 +867,7 @@
|
|||
}
|
||||
|
||||
@media (max-width: 760px) and (max-height: 680px) {
|
||||
.page-today main {
|
||||
.page-today .page-body {
|
||||
padding-top: 6px;
|
||||
padding-bottom: 6px;
|
||||
}
|
||||
|
|
@ -899,7 +899,7 @@
|
|||
}
|
||||
|
||||
@media (max-width: 1000px) and (max-height: 500px) {
|
||||
.page-today main {
|
||||
.page-today .page-body {
|
||||
padding: 6px 20px;
|
||||
}
|
||||
.today-heading {
|
||||
|
|
|
|||
|
|
@ -15,23 +15,6 @@ textarea {
|
|||
button {
|
||||
touch-action: manipulation;
|
||||
}
|
||||
.page-content {
|
||||
outline: none;
|
||||
transition:
|
||||
translate 180ms ease-out,
|
||||
transform 100ms ease-in,
|
||||
opacity 100ms ease-in;
|
||||
}
|
||||
.page-content.page-leaving {
|
||||
animation: none;
|
||||
transform: translateX(var(--exit-shift));
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.page-content.page-dragging {
|
||||
transition: none;
|
||||
user-select: none;
|
||||
}
|
||||
.sheet[open] {
|
||||
animation: sheet-arrive 260ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
|
||||
transition: translate 160ms ease-out;
|
||||
|
|
|
|||
87
src/pager.css
Normal file
87
src/pager.css
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
.page-viewport {
|
||||
outline: none;
|
||||
}
|
||||
.page-panel {
|
||||
min-width: 0;
|
||||
}
|
||||
.page-panel[aria-hidden="true"],
|
||||
.panel-topbar {
|
||||
display: none;
|
||||
}
|
||||
.macro {
|
||||
text-align: center;
|
||||
}
|
||||
.macro-label {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@media (max-width: 760px), (max-width: 1000px) and (max-height: 500px) {
|
||||
.mobile-pager {
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
}
|
||||
.mobile-pager .main-wrap {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.mobile-pager .desktop-topbar {
|
||||
display: none;
|
||||
}
|
||||
.mobile-pager .page-viewport {
|
||||
width: 100%;
|
||||
height: calc(100dvh - var(--mobile-nav-height));
|
||||
max-width: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
.page-rail {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
.page-rail.pager-dragging {
|
||||
user-select: none;
|
||||
}
|
||||
.mobile-pager .page-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 0 0 100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding-top: var(--safe-top);
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
overscroll-behavior-y: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
contain: layout paint;
|
||||
background: var(--bg);
|
||||
}
|
||||
.mobile-pager .page-panel.page-today {
|
||||
overflow: hidden;
|
||||
}
|
||||
.mobile-pager:has(dialog[open]) .page-panel {
|
||||
overflow-y: hidden;
|
||||
}
|
||||
.page-panel .panel-topbar {
|
||||
display: flex;
|
||||
flex: none;
|
||||
min-height: 60px;
|
||||
height: auto;
|
||||
padding: 8px 20px;
|
||||
}
|
||||
.page-body {
|
||||
flex: none;
|
||||
padding: 20px 20px 24px;
|
||||
}
|
||||
}
|
||||
@media (max-width: 365px) {
|
||||
.page-body {
|
||||
padding-inline: 16px;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { useEffect, useRef, useState } from "react";
|
||||
import { useContext, useEffect, useRef, useState } from "react";
|
||||
import { PageActivity } from "./PageActivity";
|
||||
import { useTilt } from "./useTilt";
|
||||
import {
|
||||
createBubbleWorld,
|
||||
|
|
@ -11,7 +12,11 @@ export function useBubblePhysics(count: number) {
|
|||
const world = useRef<ReturnType<typeof createBubbleWorld> | null>(null);
|
||||
const kick = useRef<() => void>(() => {});
|
||||
const redraw = useRef<() => void>(() => {});
|
||||
const { enabled } = useTilt();
|
||||
const pause = useRef<() => void>(() => {});
|
||||
const active = useContext(PageActivity);
|
||||
const activeRef = useRef(active);
|
||||
activeRef.current = active;
|
||||
const { enabled, status } = useTilt();
|
||||
const [reduced, setReduced] = useState(
|
||||
() => matchMedia("(prefers-reduced-motion: reduce)").matches,
|
||||
);
|
||||
|
|
@ -91,7 +96,7 @@ export function useBubblePhysics(count: number) {
|
|||
});
|
||||
function tick(now: number) {
|
||||
frame = 0;
|
||||
if (document.hidden || disposed) {
|
||||
if (document.hidden || disposed || !activeRef.current) {
|
||||
previous = 0;
|
||||
return;
|
||||
}
|
||||
|
|
@ -106,11 +111,23 @@ export function useBubblePhysics(count: number) {
|
|||
else previous = 0;
|
||||
}
|
||||
const start = () => {
|
||||
if (!frame && !document.hidden && !reduced && !disposed)
|
||||
if (
|
||||
!frame &&
|
||||
!document.hidden &&
|
||||
!reduced &&
|
||||
!disposed &&
|
||||
activeRef.current
|
||||
)
|
||||
frame = requestAnimationFrame(tick);
|
||||
};
|
||||
kick.current = start;
|
||||
redraw.current = draw;
|
||||
pause.current = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
previous = 0;
|
||||
accumulator = 0;
|
||||
};
|
||||
const visibility = () => {
|
||||
if (document.hidden) {
|
||||
cancelAnimationFrame(frame);
|
||||
|
|
@ -133,9 +150,15 @@ export function useBubblePhysics(count: number) {
|
|||
world.current = null;
|
||||
kick.current = () => {};
|
||||
redraw.current = () => {};
|
||||
pause.current = () => {};
|
||||
};
|
||||
}, [reduced]);
|
||||
|
||||
useEffect(() => {
|
||||
if (active) kick.current();
|
||||
else pause.current();
|
||||
}, [active]);
|
||||
|
||||
useEffect(() => {
|
||||
if (reduced) {
|
||||
world.current?.seed(count);
|
||||
|
|
@ -147,7 +170,13 @@ export function useBubblePhysics(count: number) {
|
|||
}, [count, reduced]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || reduced) {
|
||||
if (!active) return;
|
||||
if (
|
||||
!enabled ||
|
||||
reduced ||
|
||||
status === "denied" ||
|
||||
status === "unavailable"
|
||||
) {
|
||||
world.current?.gravity(0, 1);
|
||||
kick.current();
|
||||
return;
|
||||
|
|
@ -181,7 +210,7 @@ export function useBubblePhysics(count: number) {
|
|||
window.removeEventListener("deviceorientation", orientation);
|
||||
screen.orientation?.removeEventListener("change", apply);
|
||||
};
|
||||
}, [enabled, reduced]);
|
||||
}, [enabled, status, reduced, active]);
|
||||
|
||||
return { canvas };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,86 +9,164 @@ import { swipeStep } from "../shared/navigation.js";
|
|||
|
||||
export const pages = ["today", "library", "weight", "settings"] as const;
|
||||
export type Page = (typeof pages)[number];
|
||||
const mobile = () =>
|
||||
matchMedia("(max-width: 760px), (max-width: 1000px) and (max-height: 500px)")
|
||||
.matches;
|
||||
const mobileQuery =
|
||||
"(max-width: 760px), (max-width: 1000px) and (max-height: 500px)";
|
||||
const reduced = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
const transform = (x: number) => `translate3d(${x}px, 0, 0)`;
|
||||
|
||||
export function useNavigation(enabled: boolean) {
|
||||
const [page, setPage] = useState<Page>("today");
|
||||
const [direction, setDirection] = useState(1);
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const current = useRef<Page>(page);
|
||||
const [mobile, setMobile] = useState(() => matchMedia(mobileQuery).matches);
|
||||
const viewportRef = useRef<HTMLElement>(null);
|
||||
const railRef = useRef<HTMLDivElement>(null);
|
||||
const width = useRef(0);
|
||||
const position = useRef(0);
|
||||
const animation = useRef<Animation | null>(null);
|
||||
const frame = useRef(0);
|
||||
const scroll = useRef<Partial<Record<Page, number>>>({});
|
||||
const suppressClick = useRef(0);
|
||||
const navigate = useCallback(
|
||||
(next: Page) => {
|
||||
if (timer.current) {
|
||||
clearTimeout(timer.current);
|
||||
timer.current = null;
|
||||
}
|
||||
if (next === page) {
|
||||
ref.current?.classList.remove("page-leaving");
|
||||
const motionReduced = useRef(reduced());
|
||||
const gesture = useRef<{
|
||||
x: number;
|
||||
y: number;
|
||||
start: number;
|
||||
locked: boolean;
|
||||
dx: number;
|
||||
base: number;
|
||||
} | null>(null);
|
||||
const paint = useCallback((x: number) => {
|
||||
position.current = x;
|
||||
if (railRef.current) railRef.current.style.transform = transform(x);
|
||||
}, []);
|
||||
const stop = useCallback(() => {
|
||||
cancelAnimationFrame(frame.current);
|
||||
frame.current = 0;
|
||||
if (animation.current) {
|
||||
// Read once when interrupting a settle, never in the touch-move loop.
|
||||
const x = railRef.current
|
||||
? new DOMMatrixReadOnly(getComputedStyle(railRef.current).transform).m41
|
||||
: position.current;
|
||||
animation.current.cancel();
|
||||
animation.current = null;
|
||||
paint(x);
|
||||
}
|
||||
}, [paint]);
|
||||
const settle = useCallback(
|
||||
(index: number, animate = true) => {
|
||||
stop();
|
||||
const rail = railRef.current;
|
||||
const from = position.current;
|
||||
const to = -index * width.current;
|
||||
paint(to);
|
||||
if (!rail) return;
|
||||
rail.classList.remove("pager-dragging");
|
||||
if (!animate || reduced() || Math.abs(from - to) < 1) {
|
||||
rail.style.removeProperty("will-change");
|
||||
return;
|
||||
}
|
||||
const step = pages.indexOf(next) > pages.indexOf(page) ? 1 : -1;
|
||||
scroll.current[page] = window.scrollY;
|
||||
const commit = () => {
|
||||
timer.current = null;
|
||||
setDirection(step);
|
||||
setPage(next);
|
||||
rail.style.willChange = "transform";
|
||||
const next = rail.animate(
|
||||
[{ transform: transform(from) }, { transform: transform(to) }],
|
||||
{
|
||||
duration: Math.min(
|
||||
260,
|
||||
Math.max(
|
||||
140,
|
||||
(Math.abs(to - from) / Math.max(1, width.current)) * 260,
|
||||
),
|
||||
),
|
||||
easing: "cubic-bezier(.22,.75,.25,1)",
|
||||
},
|
||||
);
|
||||
animation.current = next;
|
||||
next.onfinish = () => {
|
||||
if (animation.current !== next) return;
|
||||
animation.current = null;
|
||||
rail.style.removeProperty("will-change");
|
||||
};
|
||||
if (reduced()) commit();
|
||||
else {
|
||||
ref.current?.style.setProperty("--exit-shift", `${step * -24}px`);
|
||||
ref.current?.classList.add("page-leaving");
|
||||
timer.current = setTimeout(commit, 100);
|
||||
}
|
||||
},
|
||||
[page, enabled],
|
||||
[paint, stop],
|
||||
);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
const navigate = useCallback(
|
||||
(next: Page) => {
|
||||
const previous = current.current;
|
||||
if (mobile)
|
||||
settle(
|
||||
pages.indexOf(next),
|
||||
Math.abs(pages.indexOf(next) - pages.indexOf(previous)) <= 1,
|
||||
);
|
||||
else scroll.current[previous] = window.scrollY;
|
||||
current.current = next;
|
||||
setPage(next);
|
||||
},
|
||||
[],
|
||||
[mobile, settle],
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
const element = ref.current;
|
||||
if (!element) return;
|
||||
element.classList.remove("page-leaving");
|
||||
const animation = !reduced()
|
||||
? element.animate(
|
||||
[
|
||||
{ opacity: 0, transform: `translateX(${direction * 24}px)` },
|
||||
{ opacity: 1, transform: "translateX(0)" },
|
||||
],
|
||||
{ duration: 240, easing: "cubic-bezier(.2,.75,.25,1)" },
|
||||
)
|
||||
: null;
|
||||
window.scrollTo({ top: scroll.current[page] || 0, behavior: "instant" });
|
||||
return () => animation?.cancel();
|
||||
}, [page, direction, enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = ref.current;
|
||||
if (!element) return;
|
||||
let gesture: {
|
||||
x: number;
|
||||
y: number;
|
||||
start: number;
|
||||
locked: boolean;
|
||||
} | null = null;
|
||||
const clear = () => {
|
||||
gesture = null;
|
||||
element.style.removeProperty("translate");
|
||||
element.classList.remove("page-dragging");
|
||||
const media = matchMedia(mobileQuery);
|
||||
const change = () => setMobile(media.matches);
|
||||
media.addEventListener("change", change);
|
||||
return () => media.removeEventListener("change", change);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const media = matchMedia("(prefers-reduced-motion: reduce)");
|
||||
const change = () => {
|
||||
motionReduced.current = media.matches;
|
||||
if (media.matches && mobile)
|
||||
settle(pages.indexOf(current.current), false);
|
||||
};
|
||||
change();
|
||||
media.addEventListener("change", change);
|
||||
return () => media.removeEventListener("change", change);
|
||||
}, [mobile, settle]);
|
||||
useLayoutEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
const rail = railRef.current;
|
||||
if (!viewport || !rail) return;
|
||||
if (!mobile) {
|
||||
stop();
|
||||
rail.style.removeProperty("transform");
|
||||
return;
|
||||
}
|
||||
const resize = () => {
|
||||
const nextWidth = viewport.getBoundingClientRect().width;
|
||||
if (nextWidth === width.current && width.current > 0) return;
|
||||
gesture.current = null;
|
||||
width.current = nextWidth;
|
||||
settle(pages.indexOf(current.current), false);
|
||||
};
|
||||
width.current = 0;
|
||||
resize();
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(viewport);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
stop();
|
||||
};
|
||||
}, [enabled, mobile, settle, stop]);
|
||||
useLayoutEffect(() => {
|
||||
if (!mobile && enabled)
|
||||
window.scrollTo({ top: scroll.current[page] || 0, behavior: "instant" });
|
||||
}, [page, mobile, enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
const rail = railRef.current;
|
||||
if (!viewport || !rail || !mobile) return;
|
||||
const cancel = () => {
|
||||
if (!gesture.current) return;
|
||||
gesture.current = null;
|
||||
settle(pages.indexOf(current.current));
|
||||
};
|
||||
const start = (event: TouchEvent) => {
|
||||
clear();
|
||||
suppressClick.current = 0;
|
||||
if (event.touches.length !== 1) {
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
if (gesture.current) cancel();
|
||||
if (
|
||||
!mobile() ||
|
||||
timer.current ||
|
||||
event.touches.length !== 1 ||
|
||||
document.querySelector("dialog[open]") ||
|
||||
window.getSelection()?.isCollapsed === false
|
||||
|
|
@ -101,67 +179,88 @@ export function useNavigation(enabled: boolean) {
|
|||
)
|
||||
)
|
||||
return;
|
||||
// Leave the browser's edge back gesture and horizontal carousels alone.
|
||||
const touch = event.touches[0];
|
||||
if (touch.clientX < 24 || touch.clientX > innerWidth - 24) return;
|
||||
for (
|
||||
let node: HTMLElement | null = target;
|
||||
node && node !== element;
|
||||
node && node !== viewport;
|
||||
node = node.parentElement
|
||||
) {
|
||||
)
|
||||
if (
|
||||
node.scrollWidth > node.clientWidth + 2 &&
|
||||
/auto|scroll/.test(getComputedStyle(node).overflowX)
|
||||
)
|
||||
return;
|
||||
}
|
||||
gesture = {
|
||||
stop();
|
||||
width.current = viewport.getBoundingClientRect().width;
|
||||
gesture.current = {
|
||||
x: touch.clientX,
|
||||
y: touch.clientY,
|
||||
start: performance.now(),
|
||||
locked: false,
|
||||
dx: 0,
|
||||
base: position.current,
|
||||
};
|
||||
};
|
||||
const dragPosition = (dx: number) => {
|
||||
const min = -(pages.length - 1) * width.current;
|
||||
const x =
|
||||
(gesture.current?.base ??
|
||||
-pages.indexOf(current.current) * width.current) +
|
||||
Math.max(-width.current, Math.min(width.current, dx));
|
||||
return x > 0 ? x * 0.15 : x < min ? min + (x - min) * 0.15 : x;
|
||||
};
|
||||
const move = (event: TouchEvent) => {
|
||||
if (!gesture) return;
|
||||
const drag = gesture.current;
|
||||
if (!drag) return;
|
||||
if (event.touches.length !== 1) {
|
||||
clear();
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
const dx = event.touches[0].clientX - gesture.x;
|
||||
const dy = event.touches[0].clientY - gesture.y;
|
||||
if (!gesture.locked) {
|
||||
const dx = event.touches[0].clientX - drag.x;
|
||||
const dy = event.touches[0].clientY - drag.y;
|
||||
if (!drag.locked) {
|
||||
if (Math.abs(dy) > 10 && Math.abs(dy) > Math.abs(dx) * 0.8) {
|
||||
clear();
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
if (Math.abs(dx) < 12 || Math.abs(dx) < Math.abs(dy) * 1.4) return;
|
||||
gesture.locked = true;
|
||||
drag.locked = true;
|
||||
rail.classList.add("pager-dragging");
|
||||
rail.style.willChange = "transform";
|
||||
}
|
||||
event.preventDefault();
|
||||
const index = pages.indexOf(page);
|
||||
const edge =
|
||||
(dx > 0 && index === 0) || (dx < 0 && index === pages.length - 1);
|
||||
element.classList.add("page-dragging");
|
||||
if (!reduced())
|
||||
element.style.translate = `${Math.max(-90, Math.min(90, dx * (edge ? 0.12 : 0.4)))}px 0`;
|
||||
drag.dx = dx;
|
||||
// Coalesce touch events: one composited transform per display frame, with
|
||||
// both live pages already laid out. No state updates or layout reads here.
|
||||
if (!frame.current && !motionReduced.current)
|
||||
frame.current = requestAnimationFrame(() => {
|
||||
frame.current = 0;
|
||||
if (gesture.current) paint(dragPosition(gesture.current.dx));
|
||||
});
|
||||
};
|
||||
const end = (event: TouchEvent) => {
|
||||
if (!gesture) return;
|
||||
const drag = gesture.current;
|
||||
if (!drag) return;
|
||||
const touch = event.changedTouches[0];
|
||||
const step =
|
||||
gesture.locked && touch
|
||||
drag.locked && touch
|
||||
? swipeStep(
|
||||
touch.clientX - gesture.x,
|
||||
touch.clientY - gesture.y,
|
||||
performance.now() - gesture.start,
|
||||
innerWidth,
|
||||
touch.clientX - drag.x,
|
||||
touch.clientY - drag.y,
|
||||
performance.now() - drag.start,
|
||||
width.current,
|
||||
)
|
||||
: 0;
|
||||
if (gesture.locked) suppressClick.current = performance.now() + 400;
|
||||
clear();
|
||||
const next = pages[pages.indexOf(page) + step];
|
||||
if (step && next) navigate(next);
|
||||
if (drag.locked) {
|
||||
suppressClick.current = performance.now() + 400;
|
||||
cancelAnimationFrame(frame.current);
|
||||
frame.current = 0;
|
||||
if (!reduced()) paint(dragPosition(drag.dx));
|
||||
}
|
||||
gesture.current = null;
|
||||
const next = pages[pages.indexOf(current.current) + step];
|
||||
navigate(step && next ? next : current.current);
|
||||
};
|
||||
const click = (event: MouseEvent) => {
|
||||
if (event.detail !== 0 && performance.now() < suppressClick.current) {
|
||||
|
|
@ -169,19 +268,27 @@ export function useNavigation(enabled: boolean) {
|
|||
event.stopPropagation();
|
||||
}
|
||||
};
|
||||
element.addEventListener("touchstart", start, { passive: true });
|
||||
element.addEventListener("touchmove", move, { passive: false });
|
||||
element.addEventListener("touchend", end);
|
||||
element.addEventListener("touchcancel", clear);
|
||||
element.addEventListener("click", click, true);
|
||||
return () => {
|
||||
clear();
|
||||
element.removeEventListener("touchstart", start);
|
||||
element.removeEventListener("touchmove", move);
|
||||
element.removeEventListener("touchend", end);
|
||||
element.removeEventListener("touchcancel", clear);
|
||||
element.removeEventListener("click", click, true);
|
||||
const hide = () => {
|
||||
if (!document.hidden) return;
|
||||
gesture.current = null;
|
||||
settle(pages.indexOf(current.current), false);
|
||||
};
|
||||
}, [page, navigate, enabled]);
|
||||
return { page, navigate, ref };
|
||||
viewport.addEventListener("touchstart", start, { passive: true });
|
||||
viewport.addEventListener("touchmove", move, { passive: false });
|
||||
viewport.addEventListener("touchend", end);
|
||||
viewport.addEventListener("touchcancel", cancel);
|
||||
viewport.addEventListener("click", click, true);
|
||||
document.addEventListener("visibilitychange", hide);
|
||||
return () => {
|
||||
gesture.current = null;
|
||||
stop();
|
||||
viewport.removeEventListener("touchstart", start);
|
||||
viewport.removeEventListener("touchmove", move);
|
||||
viewport.removeEventListener("touchend", end);
|
||||
viewport.removeEventListener("touchcancel", cancel);
|
||||
viewport.removeEventListener("click", click, true);
|
||||
document.removeEventListener("visibilitychange", hide);
|
||||
};
|
||||
}, [enabled, mobile, navigate, paint, settle, stop]);
|
||||
return { page, mobile, navigate, viewportRef, railRef };
|
||||
}
|
||||
|
|
|
|||
107
src/useTilt.ts
107
src/useTilt.ts
|
|
@ -1,4 +1,4 @@
|
|||
import { useSyncExternalStore } from "react";
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
|
||||
type Sensor = typeof DeviceOrientationEvent & {
|
||||
requestPermission?: () => Promise<string>;
|
||||
|
|
@ -15,10 +15,18 @@ try {
|
|||
wanted = localStorage.getItem("calio-tilt") === "true";
|
||||
} catch {}
|
||||
let state: TiltState = {
|
||||
enabled: wanted && !needsPermission(),
|
||||
status: wanted ? (needsPermission() ? "permission" : "enabled") : "off",
|
||||
enabled: wanted,
|
||||
status: wanted
|
||||
? typeof DeviceOrientationEvent === "undefined"
|
||||
? "unavailable"
|
||||
: needsPermission()
|
||||
? "permission"
|
||||
: "enabled"
|
||||
: "off",
|
||||
};
|
||||
const listeners = new Set<() => void>();
|
||||
let pending: Promise<void> | null = null;
|
||||
let revision = 0;
|
||||
function update(next: TiltState) {
|
||||
state = next;
|
||||
listeners.forEach((fn) => fn());
|
||||
|
|
@ -28,31 +36,82 @@ function remember(enabled: boolean) {
|
|||
localStorage.setItem("calio-tilt", String(enabled));
|
||||
} catch {}
|
||||
}
|
||||
async function toggleTilt() {
|
||||
if (state.enabled) {
|
||||
remember(false);
|
||||
update({ enabled: false, status: "off" });
|
||||
return;
|
||||
}
|
||||
function requestTiltPermission(): Promise<void> {
|
||||
if (!state.enabled) return Promise.resolve();
|
||||
if (pending) return pending;
|
||||
if (typeof DeviceOrientationEvent === "undefined") {
|
||||
update({ enabled: false, status: "unavailable" });
|
||||
return;
|
||||
update({ enabled: true, status: "unavailable" });
|
||||
return Promise.resolve();
|
||||
}
|
||||
const requestRevision = revision;
|
||||
const sensor = DeviceOrientationEvent as Sensor;
|
||||
// Call the iOS API in the original user gesture, before yielding to a promise.
|
||||
let permission: Promise<string>;
|
||||
try {
|
||||
const sensor = DeviceOrientationEvent as Sensor;
|
||||
// Invoke directly from the settings gesture, before any other async work (iOS).
|
||||
if (
|
||||
sensor.requestPermission &&
|
||||
(await sensor.requestPermission()) !== "granted"
|
||||
) {
|
||||
update({ enabled: false, status: "denied" });
|
||||
return;
|
||||
}
|
||||
remember(true);
|
||||
update({ enabled: true, status: "enabled" });
|
||||
permission = sensor.requestPermission
|
||||
? sensor.requestPermission()
|
||||
: Promise.resolve("granted");
|
||||
} catch {
|
||||
update({ enabled: false, status: "denied" });
|
||||
permission = Promise.resolve("denied");
|
||||
}
|
||||
pending = permission
|
||||
.then((result) => {
|
||||
if (state.enabled && revision === requestRevision)
|
||||
update({
|
||||
enabled: true,
|
||||
status: result === "granted" ? "enabled" : "denied",
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (state.enabled && revision === requestRevision)
|
||||
update({ enabled: true, status: "denied" });
|
||||
})
|
||||
.finally(() => {
|
||||
pending = null;
|
||||
});
|
||||
return pending;
|
||||
}
|
||||
async function toggleTilt() {
|
||||
revision++;
|
||||
const enabled = !state.enabled;
|
||||
remember(enabled);
|
||||
update({
|
||||
enabled,
|
||||
status: enabled ? (needsPermission() ? "permission" : "enabled") : "off",
|
||||
});
|
||||
if (enabled) await requestTiltPermission();
|
||||
}
|
||||
|
||||
// iOS may require fresh user activation after killing/reopening a PWA. Keep the
|
||||
// saved switch on and resume permission from the first normal app interaction.
|
||||
export function useTiltResume(available: boolean) {
|
||||
useEffect(() => {
|
||||
if (!available) return;
|
||||
const resume = (event: Event) => {
|
||||
if (
|
||||
event.type === "keydown" &&
|
||||
!["Enter", " "].includes((event as KeyboardEvent).key)
|
||||
)
|
||||
return;
|
||||
const target = event.target as Element | null;
|
||||
if (
|
||||
target &&
|
||||
typeof target.closest === "function" &&
|
||||
target.closest("[data-tilt-control]")
|
||||
)
|
||||
return;
|
||||
if (state.enabled && state.status === "permission")
|
||||
void requestTiltPermission();
|
||||
};
|
||||
document.addEventListener("pointerup", resume, true);
|
||||
document.addEventListener("touchend", resume, true);
|
||||
document.addEventListener("keydown", resume, true);
|
||||
return () => {
|
||||
document.removeEventListener("pointerup", resume, true);
|
||||
document.removeEventListener("touchend", resume, true);
|
||||
document.removeEventListener("keydown", resume, true);
|
||||
};
|
||||
}, [available]);
|
||||
}
|
||||
export function useTilt() {
|
||||
const snapshot = useSyncExternalStore(
|
||||
|
|
@ -64,5 +123,5 @@ export function useTilt() {
|
|||
},
|
||||
() => state,
|
||||
);
|
||||
return { ...snapshot, toggleTilt };
|
||||
return { ...snapshot, toggleTilt, requestTiltPermission };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
(() => {
|
||||
const checks = {};
|
||||
const font = (element) => getComputedStyle(element).fontSize.split('px')[0] * 1;
|
||||
const visible = (selector) => [...document.querySelectorAll(selector)].filter(e => e.getBoundingClientRect().width > 0);
|
||||
const visible = (selector) => [...document.querySelectorAll(selector)].filter(e => e.getBoundingClientRect().width > 0 && !e.closest('.page-panel[aria-hidden="true"]'));
|
||||
const dialog = document.querySelector('dialog[open]');
|
||||
checks.noHorizontalPageOverflow = document.documentElement.scrollWidth <= window.innerWidth + 1;
|
||||
if (!dialog && visible('.dashboard-grid').length) {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
(async () => {
|
||||
const checks = {};
|
||||
const pause = (ms = 380) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const visible = selector => [...document.querySelectorAll(selector)].filter(e => e.getBoundingClientRect().width > 0);
|
||||
const visible = selector => [...document.querySelectorAll(selector)].filter(e => e.getBoundingClientRect().width > 0 && !e.closest('.page-panel[aria-hidden="true"]'));
|
||||
const page = () => document.querySelector('main').getAttribute('aria-label');
|
||||
const nav = async label => {
|
||||
visible('.bottom-nav button').find(e => e.textContent.trim() === label).click();
|
||||
|
|
|
|||
65
tests/browser/swipe-preview.check.js
Normal file
65
tests/browser/swipe-preview.check.js
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
// Run on an unlocked phone-size localhost preview using Runtime.evaluate with
|
||||
// awaitPromise. Reproduces the visible adjacent screen and centered macro text.
|
||||
(async () => {
|
||||
const checks = {};
|
||||
const target = document.querySelector('.orb');
|
||||
const rect = target.getBoundingClientRect();
|
||||
const x = innerWidth / 2;
|
||||
const y = rect.y + rect.height / 2;
|
||||
const emit = (type, dx, ended = false) => {
|
||||
const touch = new Touch({ identifier: 21, target, clientX: x + dx, clientY: y });
|
||||
target.dispatchEvent(new TouchEvent(type, { bubbles: true, cancelable: true, touches: ended ? [] : [touch], changedTouches: [touch] }));
|
||||
};
|
||||
emit('touchstart', 0);
|
||||
emit('touchmove', -70);
|
||||
emit('touchmove', -140);
|
||||
await new Promise(requestAnimationFrame);
|
||||
await new Promise(requestAnimationFrame);
|
||||
const nextHeading = [...document.querySelectorAll('h1')].find(e => e.textContent.includes('Library'));
|
||||
const next = nextHeading?.getBoundingClientRect();
|
||||
checks.nextScreenVisibleDuringDrag = Boolean(next && next.width > 0 && next.left > 0 && next.left < innerWidth);
|
||||
const current = target.getBoundingClientRect();
|
||||
checks.followsFingerWithoutDamping = Math.abs((rect.left - current.left) - 140) < 3;
|
||||
emit('touchcancel', -140, true);
|
||||
await new Promise(resolve => setTimeout(resolve, 380));
|
||||
emit('touchstart', 0);
|
||||
emit('touchmove', -100);
|
||||
await new Promise(requestAnimationFrame);
|
||||
const first = new Touch({ identifier: 21, target, clientX: x - 100, clientY: y });
|
||||
const second = new Touch({ identifier: 22, target, clientX: x + 10, clientY: y });
|
||||
target.dispatchEvent(new TouchEvent('touchstart', { bubbles: true, touches: [first, second], changedTouches: [second] }));
|
||||
target.dispatchEvent(new TouchEvent('touchend', { bubbles: true, touches: [], changedTouches: [first, second] }));
|
||||
await new Promise(resolve => setTimeout(resolve, 380));
|
||||
checks.multitouchDoesNotLeavePartialPage = Math.abs(target.getBoundingClientRect().left - rect.left) < 2;
|
||||
const libraryButton = [...document.querySelectorAll('.bottom-nav button')].find(e => e.textContent.trim() === 'Library');
|
||||
libraryButton.click();
|
||||
await new Promise(requestAnimationFrame);
|
||||
const viewport = document.querySelector('main');
|
||||
const rail = document.querySelector('.page-rail');
|
||||
const before = new DOMMatrixReadOnly(getComputedStyle(rail).transform).m41;
|
||||
const resumeTouch = (type, dx) => {
|
||||
const touch = new Touch({ identifier: 23, target: viewport, clientX: x + dx, clientY: y });
|
||||
viewport.dispatchEvent(new TouchEvent(type, { bubbles: true, cancelable: true, touches: type === 'touchcancel' ? [] : [touch], changedTouches: [touch] }));
|
||||
};
|
||||
resumeTouch('touchstart', 0);
|
||||
resumeTouch('touchmove', 40);
|
||||
await new Promise(requestAnimationFrame);
|
||||
await new Promise(requestAnimationFrame);
|
||||
const after = new DOMMatrixReadOnly(getComputedStyle(rail).transform).m41;
|
||||
const desired = before + 40;
|
||||
const expected = desired > 0 ? desired * .15 : desired;
|
||||
checks.interruptedSettleContinuesWithoutJump = Math.abs(after - expected) < 5;
|
||||
resumeTouch('touchcancel', 40);
|
||||
await new Promise(resolve => setTimeout(resolve, 380));
|
||||
[...document.querySelectorAll('.bottom-nav button')].find(e => e.textContent.trim() === 'Today').click();
|
||||
await new Promise(resolve => setTimeout(resolve, 380));
|
||||
checks.macroNumbersCentered = [...document.querySelectorAll('.macro')].filter(e => e.getBoundingClientRect().width > 0).every(macro => {
|
||||
const value = macro.querySelector('div:not(.progress-track)');
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(value);
|
||||
const text = range.getBoundingClientRect();
|
||||
const track = macro.querySelector('.progress-track').getBoundingClientRect();
|
||||
return Math.abs(text.x + text.width / 2 - track.x - track.width / 2) < 2;
|
||||
});
|
||||
return { pass: Object.values(checks).every(Boolean), checks };
|
||||
})()
|
||||
111
tests/tilt.test.js
Normal file
111
tests/tilt.test.js
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import vm from "node:vm";
|
||||
import ts from "typescript";
|
||||
|
||||
// Reload the real hook module with an iOS-style permission API and the same
|
||||
// device storage. The hook snapshot is the value bound to the Settings switch.
|
||||
function launch(storage, permission = async () => "granted") {
|
||||
const exports = {};
|
||||
const effects = [];
|
||||
const document = new EventTarget();
|
||||
const context = {
|
||||
exports,
|
||||
require: () => ({
|
||||
useSyncExternalStore: (_subscribe, snapshot) => snapshot(),
|
||||
useEffect: (effect) => effects.push(effect),
|
||||
}),
|
||||
DeviceOrientationEvent: class {
|
||||
static requestPermission = permission;
|
||||
},
|
||||
localStorage: {
|
||||
getItem: (key) => storage.get(key) ?? null,
|
||||
setItem: (key, value) => storage.set(key, value),
|
||||
},
|
||||
document,
|
||||
};
|
||||
vm.runInNewContext(
|
||||
ts.transpileModule(
|
||||
readFileSync(new URL("../src/useTilt.ts", import.meta.url), "utf8"),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
},
|
||||
},
|
||||
).outputText,
|
||||
context,
|
||||
);
|
||||
return { api: exports, document, effects, snapshot: () => exports.useTilt() };
|
||||
}
|
||||
|
||||
test("saved tilt stays switched on when an iOS PWA is relaunched", async () => {
|
||||
const storage = new Map();
|
||||
const first = launch(storage);
|
||||
await first.snapshot().toggleTilt();
|
||||
assert.equal(first.snapshot().enabled, true);
|
||||
assert.equal(storage.get("calio-tilt"), "true");
|
||||
const reopened = launch(storage);
|
||||
assert.equal(
|
||||
reopened.snapshot().enabled,
|
||||
true,
|
||||
"A session permission check must not reset the saved switch",
|
||||
);
|
||||
});
|
||||
|
||||
test("explicitly switching tilt off stays off after reopening", async () => {
|
||||
const storage = new Map();
|
||||
const first = launch(storage);
|
||||
await first.snapshot().toggleTilt();
|
||||
await first.snapshot().toggleTilt();
|
||||
assert.equal(launch(storage).snapshot().enabled, false);
|
||||
});
|
||||
|
||||
test("the first app interaction resumes iOS motion without toggling the preference", async () => {
|
||||
let calls = 0;
|
||||
const reopened = launch(new Map([["calio-tilt", "true"]]), async () => {
|
||||
calls++;
|
||||
return "granted";
|
||||
});
|
||||
assert.equal(reopened.snapshot().status, "permission");
|
||||
reopened.api.useTiltResume(true);
|
||||
const cleanup = reopened.effects[0]();
|
||||
reopened.document.dispatchEvent(new Event("pointerup"));
|
||||
reopened.document.dispatchEvent(new Event("touchend"));
|
||||
await reopened.snapshot().requestTiltPermission();
|
||||
assert.equal(
|
||||
calls,
|
||||
1,
|
||||
"Overlapping pointer/touch events must share one request",
|
||||
);
|
||||
assert.equal(reopened.snapshot().enabled, true);
|
||||
assert.equal(reopened.snapshot().status, "enabled");
|
||||
cleanup();
|
||||
});
|
||||
|
||||
test("denial preserves the preference and a late permission grant cannot undo switching off", async () => {
|
||||
const denied = launch(
|
||||
new Map([["calio-tilt", "true"]]),
|
||||
async () => "denied",
|
||||
);
|
||||
await denied.snapshot().requestTiltPermission();
|
||||
assert.equal(denied.snapshot().enabled, true);
|
||||
assert.equal(denied.snapshot().status, "denied");
|
||||
let grant;
|
||||
const storage = new Map();
|
||||
const pending = launch(
|
||||
storage,
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
grant = resolve;
|
||||
}),
|
||||
);
|
||||
const enabling = pending.snapshot().toggleTilt();
|
||||
await pending.snapshot().toggleTilt();
|
||||
grant("granted");
|
||||
await enabling;
|
||||
assert.equal(pending.snapshot().enabled, false);
|
||||
assert.equal(pending.snapshot().status, "off");
|
||||
assert.equal(storage.get("calio-tilt"), "false");
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue