@wix/himalaya-cli 0.1257.0 → 0.1258.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/motion/src/index.d.ts +45 -5
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/sdk-types/src/capabilities.generated.d.ts +1 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/audio-record.mjs +1 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/calendar.mjs +1 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/calls.mjs +1 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/contacts.mjs +1 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/location.mjs +1 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/motion.mjs +18 -2
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/photos.mjs +1 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdk-types.mjs +1 -1
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/tasks.mjs +1 -1
- package/dist/cli.mjs +47 -23
- package/dist/preview-assets.generated.bin +0 -0
- package/guides/sdk-reference.json +15 -3
- package/package.json +2 -2
- package/templates/beauty-salon/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/beauty-salon/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/beauty-salon/tier5-src/himi-booking-bookings/index.ts +41 -4
- package/templates/beauty-salon/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/beauty-salon-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/branded-lite/config.ts +14 -1
- package/templates/branded-lite/dev/index.ts +845 -2
- package/templates/branded-lite/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/branded-lite/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/branded-lite/tier5-src/himi-booking-bookings/index.ts +41 -4
- package/templates/branded-lite/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/branded-lite/tier5-src/himi-branded-lite-steps/index.ts +524 -0
- package/templates/community-club/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/community-club/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/community-club/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/community-club-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/events-meetups/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/events-meetups/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/events-meetups/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/events-meetups-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/gym-fitness/config.ts +14 -1
- package/templates/gym-fitness/dev/index.ts +844 -1
- package/templates/gym-fitness/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/gym-fitness/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/gym-fitness/tier5-src/himi-booking-bookings/index.ts +41 -4
- package/templates/gym-fitness/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/gym-fitness/tier5-src/himi-branded-lite-steps/index.ts +524 -0
- package/templates/gym-fitness-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/nonprofit-cause/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/nonprofit-cause/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/nonprofit-cause/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/nonprofit-cause-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/owner-lite/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/podcast-creator/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/podcast-creator/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/podcast-creator/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/podcast-creator-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/portfolio-creative/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/portfolio-creative/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/portfolio-creative/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/portfolio-creative-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/restaurant/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/restaurant/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/restaurant/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/restaurant-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/retail-store/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/retail-store/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/retail-store/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/retail-store-owner/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/yoga-studio/dev/index.ts +90 -1
- package/templates/yoga-studio/tier5-src/_shared/collection-service.ts +7 -0
- package/templates/yoga-studio/tier5-src/_shared/weekly-goal.ts +107 -0
- package/templates/yoga-studio/tier5-src/himi-booking-bookings/index.ts +41 -4
- package/templates/yoga-studio/tier5-src/himi-branded-lite-home/index.ts +31 -7
- package/templates/yoga-studio-owner/tier5-src/_shared/collection-service.ts +7 -0
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import { defineService, type PollDirective } from "@himalaya/state";
|
|
2
|
+
import {
|
|
3
|
+
availability,
|
|
4
|
+
getPermissionStatus,
|
|
5
|
+
getStepCount,
|
|
6
|
+
openStepHistorySetup,
|
|
7
|
+
requestPermission,
|
|
8
|
+
watch,
|
|
9
|
+
type StepHistoryStatus,
|
|
10
|
+
type StepSample,
|
|
11
|
+
} from "@himalaya/motion";
|
|
12
|
+
import { copyParam, copyTemplate, stashCopy } from "../_shared/himi-copy.js";
|
|
13
|
+
|
|
14
|
+
// The Steps screen worker (himi_steps): today's steps against the provisioned daily goal
|
|
15
|
+
// (`provisioning.goals.dailySteps`, forwarded as the onAppear `goal` param).
|
|
16
|
+
//
|
|
17
|
+
// WHERE THE NUMBER COMES FROM, best first:
|
|
18
|
+
// today `getStepCount(startOfDay, now)` — CoreMotion on iOS; on Android a step store that
|
|
19
|
+
// records on its own (Google's Recording API) when `availability().stepHistory` is
|
|
20
|
+
// "available". A real daily total, the
|
|
21
|
+
// steps taken while the app was closed included.
|
|
22
|
+
// live otherwise (no store, a phone without Play services, or a store holding no record
|
|
23
|
+
// yet — the day its recording began):
|
|
24
|
+
// accumulate `watch({ sensor: "steps" })` deltas into a per-DAY total in
|
|
25
|
+
// himalaya.storage, so reopening the screen continues the count instead of resetting.
|
|
26
|
+
// On Android the stream also carries the step counter's running total since restart;
|
|
27
|
+
// saving it lets the next visit add the steps taken while the screen was CLOSED (same
|
|
28
|
+
// day, same boot) — labelled "Since you first opened the app today". Without it (older
|
|
29
|
+
// binaries), "Since you opened this screen". Never presented as the day's total.
|
|
30
|
+
// When both exist, the shown total is the LARGER of the two: a store can lag (the Recording API
|
|
31
|
+
// writes in batches, and its history starts at the first grant), and the live count is a real
|
|
32
|
+
// lower bound.
|
|
33
|
+
// A device that can do neither never shows a number: a confident "0 steps" is the one wrong
|
|
34
|
+
// answer this screen must not give. A motion bridge that FAILS (a throw, not a "no") is the
|
|
35
|
+
// `error` phase with a retry — never folded into "unsupported" or a count of 0.
|
|
36
|
+
//
|
|
37
|
+
// DETERMINISM: the boot state reads no clock and no sensor (the build hashes initial state into
|
|
38
|
+
// the release). Every Date / storage / sensor read happens inside an action.
|
|
39
|
+
|
|
40
|
+
export const DEFAULT_DAILY_GOAL = 8000;
|
|
41
|
+
const MAX_DAILY_GOAL = 100_000;
|
|
42
|
+
/** How often a live sample may trigger a re-read of the day total. */
|
|
43
|
+
const HISTORY_REREAD_MS = 30_000;
|
|
44
|
+
const STORAGE_PREFIX = "himi.steps.";
|
|
45
|
+
const COUNTER_KEY = "himi.steps.counter";
|
|
46
|
+
/** Two boot-time readings closer than this are the same boot (the wall clock drifts a little). */
|
|
47
|
+
const SAME_BOOT_TOLERANCE_MS = 60_000;
|
|
48
|
+
|
|
49
|
+
type Phase = "loading" | "connect" | "denied" | "unsupported" | "counting" | "error";
|
|
50
|
+
type Source = "today" | "live" | "";
|
|
51
|
+
|
|
52
|
+
export interface State {
|
|
53
|
+
phase: Phase;
|
|
54
|
+
goal: number;
|
|
55
|
+
steps: number;
|
|
56
|
+
/** 0..1 — the gauge fill. */
|
|
57
|
+
pct: number;
|
|
58
|
+
goalMet: boolean;
|
|
59
|
+
source: Source;
|
|
60
|
+
stepHistory: StepHistoryStatus;
|
|
61
|
+
stepsLabel: string;
|
|
62
|
+
goalLabel: string;
|
|
63
|
+
remainingLabel: string;
|
|
64
|
+
sourceLabel: string;
|
|
65
|
+
accessibilityValue: string;
|
|
66
|
+
/** The live count bridges the gaps between visits (Android counter samples), so it covers the
|
|
67
|
+
* day since the app was first opened — not just this screen visit. */
|
|
68
|
+
liveSinceFirstOpen: boolean;
|
|
69
|
+
/** Set in the `error` phase: what failed, in the user's words. */
|
|
70
|
+
errorText: string;
|
|
71
|
+
/** The day (dayKey) the shown count belongs to — "" until counting. A later day means the count
|
|
72
|
+
* is yesterday's: `tick` and `sample` switch over instead of carrying it. */
|
|
73
|
+
day: string;
|
|
74
|
+
/** The step store answered "available" but its read FAILED, so the live count stands in — not
|
|
75
|
+
* the same as an empty store, and never announced as "whole-day counting is on". */
|
|
76
|
+
historyReadFailed: boolean;
|
|
77
|
+
// hiddenPath gates (a node hides while its flag is TRUE).
|
|
78
|
+
hideLoading: boolean;
|
|
79
|
+
hideError: boolean;
|
|
80
|
+
hideConnect: boolean;
|
|
81
|
+
hideDenied: boolean;
|
|
82
|
+
hideUnsupported: boolean;
|
|
83
|
+
hideCounting: boolean;
|
|
84
|
+
/** The gauge + numbers — hidden in `counting` until a source exists (a store needing setup on
|
|
85
|
+
* a device with no live sensor), so nothing renders a number it does not have. */
|
|
86
|
+
hideProgress: boolean;
|
|
87
|
+
hideSetup: boolean;
|
|
88
|
+
/** Step history works but holds no record for today, and there is no live sensor to count
|
|
89
|
+
* with — say so (and how to fix it) instead of showing a bare title or a confident 0. */
|
|
90
|
+
hideNoData: boolean;
|
|
91
|
+
/** The store works but holds nothing for today while the phone counts live (the day its
|
|
92
|
+
* recording began): say whole-day counting is on from now. */
|
|
93
|
+
hideHistoryHint: boolean;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const INITIAL: State = derive({
|
|
97
|
+
phase: "loading",
|
|
98
|
+
goal: DEFAULT_DAILY_GOAL,
|
|
99
|
+
steps: 0,
|
|
100
|
+
pct: 0,
|
|
101
|
+
goalMet: false,
|
|
102
|
+
source: "",
|
|
103
|
+
stepHistory: "unsupported",
|
|
104
|
+
stepsLabel: "",
|
|
105
|
+
goalLabel: "",
|
|
106
|
+
remainingLabel: "",
|
|
107
|
+
sourceLabel: "",
|
|
108
|
+
accessibilityValue: "",
|
|
109
|
+
liveSinceFirstOpen: false,
|
|
110
|
+
errorText: "",
|
|
111
|
+
day: "",
|
|
112
|
+
historyReadFailed: false,
|
|
113
|
+
hideLoading: false,
|
|
114
|
+
hideError: true,
|
|
115
|
+
hideConnect: true,
|
|
116
|
+
hideDenied: true,
|
|
117
|
+
hideUnsupported: true,
|
|
118
|
+
hideCounting: true,
|
|
119
|
+
hideProgress: true,
|
|
120
|
+
hideSetup: true,
|
|
121
|
+
hideNoData: true,
|
|
122
|
+
hideHistoryHint: true,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// ── pure helpers (exported for the unit test) ───────────────────────────────
|
|
126
|
+
|
|
127
|
+
/** "12,345" — locale-neutral grouping, so the label is stable across devices. */
|
|
128
|
+
export function groupDigits(n: number): string {
|
|
129
|
+
return String(Math.max(0, Math.round(n))).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The onAppear `goal` param → a positive integer goal; anything else → the default. */
|
|
133
|
+
/** Whether the onAppear params carry a `goal` at all (absent ≠ malformed). */
|
|
134
|
+
function hasGoalParam(arg: unknown): boolean {
|
|
135
|
+
return !!arg && typeof arg === "object" && "goal" in (arg as Record<string, unknown>);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function parseGoal(arg: unknown): number {
|
|
139
|
+
const raw = (arg as Record<string, unknown> | undefined)?.goal;
|
|
140
|
+
const n = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw) : NaN;
|
|
141
|
+
return Number.isFinite(n) && n >= 1 ? Math.min(Math.round(n), MAX_DAILY_GOAL) : DEFAULT_DAILY_GOAL;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Local midnight of `now`'s day, epoch ms. */
|
|
145
|
+
export function startOfDayMs(now: number): number {
|
|
146
|
+
const d = new Date(now);
|
|
147
|
+
d.setHours(0, 0, 0, 0);
|
|
148
|
+
return d.getTime();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The per-day storage key for the live total — the local calendar date, so the count rolls
|
|
152
|
+
* over at the user's midnight. */
|
|
153
|
+
export function dayKey(now: number): string {
|
|
154
|
+
const d = new Date(now);
|
|
155
|
+
return `${STORAGE_PREFIX}${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function derive(s: State): State {
|
|
159
|
+
const counting = s.phase === "counting";
|
|
160
|
+
const hasNumber = counting && s.source !== "";
|
|
161
|
+
const pct = s.goal > 0 ? Math.min(Math.max(s.steps / s.goal, 0), 1) : 0;
|
|
162
|
+
const goalMet = hasNumber && s.steps >= s.goal;
|
|
163
|
+
const remaining = Math.max(s.goal - s.steps, 0);
|
|
164
|
+
const needsSetup = s.stepHistory === "needs_setup" || s.stepHistory === "needs_permission";
|
|
165
|
+
return {
|
|
166
|
+
...s,
|
|
167
|
+
pct: hasNumber ? pct : 0,
|
|
168
|
+
goalMet,
|
|
169
|
+
stepsLabel: hasNumber ? groupDigits(s.steps) : "",
|
|
170
|
+
goalLabel: hasNumber ? copyTemplate("steps.goalLabel", "of {goal} steps", { goal: groupDigits(s.goal) }) : "",
|
|
171
|
+
remainingLabel: !hasNumber ? "" : goalMet
|
|
172
|
+
? copyParam("steps.goalMet", "Daily goal reached. Nice work.")
|
|
173
|
+
: copyTemplate("steps.remaining", "{count} steps to your daily goal", { count: groupDigits(remaining) }),
|
|
174
|
+
sourceLabel: s.source === "today"
|
|
175
|
+
? copyParam("steps.sourceToday", "Today")
|
|
176
|
+
: s.source !== "live" ? ""
|
|
177
|
+
: s.liveSinceFirstOpen
|
|
178
|
+
? copyParam("steps.sourceLiveDay", "Since you first opened the app today")
|
|
179
|
+
: copyParam("steps.sourceLive", "Since you opened this screen"),
|
|
180
|
+
accessibilityValue: hasNumber
|
|
181
|
+
? copyTemplate("steps.a11yValue", "{steps} of {goal} steps", { steps: groupDigits(s.steps), goal: groupDigits(s.goal) })
|
|
182
|
+
: "",
|
|
183
|
+
errorText: s.phase === "error" ? copyParam("steps.errorText", "Your step data could not be read. Try again.") : "",
|
|
184
|
+
hideLoading: s.phase !== "loading",
|
|
185
|
+
hideError: s.phase !== "error",
|
|
186
|
+
hideConnect: s.phase !== "connect",
|
|
187
|
+
hideDenied: s.phase !== "denied",
|
|
188
|
+
hideUnsupported: s.phase !== "unsupported",
|
|
189
|
+
hideCounting: !counting,
|
|
190
|
+
hideProgress: !hasNumber,
|
|
191
|
+
// Only once the user has said yes to step data: before that, the connect card is the one ask.
|
|
192
|
+
hideSetup: !(counting && needsSetup),
|
|
193
|
+
hideNoData: !(counting && !hasNumber && s.stepHistory === "available"),
|
|
194
|
+
hideHistoryHint: !(counting && s.source === "live" && s.stepHistory === "available" && !s.historyReadFailed),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ── storage (live accumulation) ─────────────────────────────────────────────
|
|
199
|
+
|
|
200
|
+
interface StorageLike { getItem(k: string): string | null; setItem(k: string, v: string): void }
|
|
201
|
+
function storage(): StorageLike | undefined {
|
|
202
|
+
const host = globalThis as { himalaya?: { storage?: StorageLike }; localStorage?: StorageLike };
|
|
203
|
+
return host.himalaya?.storage ?? host.localStorage;
|
|
204
|
+
}
|
|
205
|
+
/** The live total survives a reopen through storage; when storage fails it is kept HERE for
|
|
206
|
+
* this session instead — the count keeps going, it just does not outlive the worker. */
|
|
207
|
+
const memoryTotals = new Map<string, number>();
|
|
208
|
+
function readLiveTotal(now: number): number {
|
|
209
|
+
const key = dayKey(now);
|
|
210
|
+
let raw: string | null | undefined;
|
|
211
|
+
try {
|
|
212
|
+
raw = storage()?.getItem(key);
|
|
213
|
+
} catch {
|
|
214
|
+
raw = undefined; // storage unavailable → the session's in-memory total below
|
|
215
|
+
}
|
|
216
|
+
const n = Number(raw ?? memoryTotals.get(key) ?? 0);
|
|
217
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
|
|
218
|
+
}
|
|
219
|
+
function writeLiveTotal(now: number, steps: number): void {
|
|
220
|
+
const key = dayKey(now);
|
|
221
|
+
const value = Math.max(0, Math.round(steps));
|
|
222
|
+
memoryTotals.set(key, value);
|
|
223
|
+
try { storage()?.setItem(key, String(value)); } catch { /* kept in memoryTotals */ }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The last step-counter reading this app saw: which day, the running total, which boot. */
|
|
227
|
+
/** The step counter at the last sample, and the day total SHOWN with it — so a reopen can put the
|
|
228
|
+
* steps walked in between on top of what was shown, not only on top of a store that may lag. */
|
|
229
|
+
export interface CounterMark { day: string; counter: number; bootTimeMs: number; shown?: number }
|
|
230
|
+
let memoryMark: CounterMark | null = null;
|
|
231
|
+
function readMark(): CounterMark | null {
|
|
232
|
+
let raw: string | null | undefined;
|
|
233
|
+
try {
|
|
234
|
+
raw = storage()?.getItem(COUNTER_KEY);
|
|
235
|
+
} catch {
|
|
236
|
+
raw = undefined; // storage unavailable → this session's in-memory mark
|
|
237
|
+
}
|
|
238
|
+
if (!raw) return memoryMark;
|
|
239
|
+
try {
|
|
240
|
+
const m = JSON.parse(raw) as Partial<CounterMark>;
|
|
241
|
+
return typeof m.day === "string" && typeof m.counter === "number" && typeof m.bootTimeMs === "number"
|
|
242
|
+
? { day: m.day, counter: m.counter, bootTimeMs: m.bootTimeMs, ...(typeof m.shown === "number" ? { shown: m.shown } : {}) }
|
|
243
|
+
: memoryMark;
|
|
244
|
+
} catch {
|
|
245
|
+
return memoryMark; // a corrupt mark bridges nothing rather than inventing steps
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function writeMark(mark: CounterMark): void {
|
|
249
|
+
memoryMark = mark;
|
|
250
|
+
try { storage()?.setItem(COUNTER_KEY, JSON.stringify(mark)); } catch { /* kept in memoryMark */ }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Steps taken while nothing was listening: the counter's growth since the saved mark — but
|
|
254
|
+
* ONLY for the same day (steps before midnight are yesterday's) and the same boot (a restart
|
|
255
|
+
* resets the counter, so the difference means nothing). Anything else bridges 0 steps. */
|
|
256
|
+
export function stepsWhileAway(mark: CounterMark | null, day: string, counter: number, bootTimeMs: number): number {
|
|
257
|
+
if (!mark || mark.day !== day) return 0;
|
|
258
|
+
if (Math.abs(mark.bootTimeMs - bootTimeMs) > SAME_BOOT_TOLERANCE_MS) return 0;
|
|
259
|
+
if (!Number.isFinite(counter) || counter < mark.counter) return 0;
|
|
260
|
+
return Math.round(counter - mark.counter);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ── sensors ─────────────────────────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
let canLive = false; // a live pedometer stream is possible (motion granted + sensor)
|
|
266
|
+
let watching = false; // one live loop per worker
|
|
267
|
+
let counterAnchored = false; // this stream's first counter sample has bridged the gap
|
|
268
|
+
let lastLiveDay = ""; // the day of this stream's previous sample ("" before its first)
|
|
269
|
+
let lastHistoryRead = 0; // throttles sample-driven re-reads of the day total
|
|
270
|
+
/** The last day total history answered, WITH its day (after midnight yesterday's total must
|
|
271
|
+
* never be shown as today's, even while a re-read is throttled or failing) and the live total at
|
|
272
|
+
* the moment it was read — live steps since then count ON TOP of it, so the number keeps moving
|
|
273
|
+
* while the store lags its own recording. */
|
|
274
|
+
let lastHistory: { day: string; steps: number; liveAtRead: number } | null = null;
|
|
275
|
+
/** Every `resolve` (load, tick, connect, setup, refresh, a midnight sample) takes a number when it
|
|
276
|
+
* STARTS, and `lastResolved` keeps the result of the newest one that has COMPLETED — an older
|
|
277
|
+
* resolve finishing late never replaces it. A `sample` whose store read was overtaken by a
|
|
278
|
+
* completed resolve commits that state instead of its own stale snapshot; one still in flight
|
|
279
|
+
* will commit after the sample anyway. */
|
|
280
|
+
let resolveStarted = 0;
|
|
281
|
+
let lastResolved: { gen: number; state: State } | null = null;
|
|
282
|
+
|
|
283
|
+
/** `ok: false` = the read FAILED (a bridge/native error), distinct from `steps: null` = this
|
|
284
|
+
* device holds no history for today. */
|
|
285
|
+
type TodayRead = { ok: true; day: string; steps: number | null } | { ok: false };
|
|
286
|
+
async function readToday(): Promise<TodayRead> {
|
|
287
|
+
const now = Date.now();
|
|
288
|
+
try {
|
|
289
|
+
return { ok: true, day: dayKey(now), steps: await getStepCount(startOfDayMs(now), now) };
|
|
290
|
+
} catch {
|
|
291
|
+
return { ok: false };
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** History's total for [day] plus the live steps counted since it was read, or 0 when the last
|
|
296
|
+
* answer was for another day. */
|
|
297
|
+
function historyNow(day: string, live: number): number {
|
|
298
|
+
if (lastHistory?.day !== day) return 0;
|
|
299
|
+
return lastHistory.steps + Math.max(0, live - lastHistory.liveAtRead);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function ensureWatch(): void {
|
|
303
|
+
if (watching || !canLive) return;
|
|
304
|
+
watching = true;
|
|
305
|
+
counterAnchored = false; // a new native stream re-anchors, and its first sample bridges the gap
|
|
306
|
+
lastLiveDay = "";
|
|
307
|
+
void (async () => {
|
|
308
|
+
try {
|
|
309
|
+
for await (const sample of watch<StepSample>({ sensor: "steps", intervalMs: 5000 })) {
|
|
310
|
+
if (sample && typeof sample.steps === "number") await svc.sample(sample);
|
|
311
|
+
}
|
|
312
|
+
} catch { /* the stream died; Refresh re-opens it */ }
|
|
313
|
+
watching = false;
|
|
314
|
+
})();
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Resolve the number for the `counting` phase from the best available source. */
|
|
318
|
+
async function counted(input: State): Promise<State> {
|
|
319
|
+
const base: State = { ...input, day: dayKey(Date.now()), historyReadFailed: false };
|
|
320
|
+
let historyFailed = false;
|
|
321
|
+
if (base.stepHistory === "available") {
|
|
322
|
+
const today = await readToday();
|
|
323
|
+
lastHistoryRead = Date.now();
|
|
324
|
+
if (today.ok && today.steps !== null) {
|
|
325
|
+
const live = readLiveTotal(Date.now());
|
|
326
|
+
// The same rule as a sample's re-read: rebase only on a store that has caught up with the
|
|
327
|
+
// current estimate, so a refresh against a lagging store never moves the number backwards.
|
|
328
|
+
const estimate = historyNow(today.day, live);
|
|
329
|
+
if (today.steps >= estimate) lastHistory = { day: today.day, steps: today.steps, liveAtRead: live };
|
|
330
|
+
ensureWatch(); // the live count keeps going: it is the floor when history lags its writers
|
|
331
|
+
return derive({ ...base, phase: "counting", source: "today", steps: Math.max(today.steps, estimate, live) });
|
|
332
|
+
}
|
|
333
|
+
historyFailed = !today.ok;
|
|
334
|
+
}
|
|
335
|
+
// A failed history read with no live sensor to fall back on is an error, not "no number".
|
|
336
|
+
if (historyFailed && !canLive) return derive({ ...base, phase: "error", source: "", steps: 0 });
|
|
337
|
+
if (canLive) {
|
|
338
|
+
ensureWatch();
|
|
339
|
+
return derive({ ...base, phase: "counting", source: "live", steps: readLiveTotal(Date.now()), historyReadFailed: historyFailed });
|
|
340
|
+
}
|
|
341
|
+
return derive({ ...base, phase: "counting", source: "", steps: 0 });
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Read permission + availability and land on the right phase. `afterAsk`: the user just
|
|
345
|
+
* answered a prompt, so "not granted" now means refused rather than not-yet-asked (Android
|
|
346
|
+
* reports both as "denied"). */
|
|
347
|
+
async function resolve(state: State, afterAsk: boolean, permission?: string): Promise<State> {
|
|
348
|
+
const gen = ++resolveStarted;
|
|
349
|
+
const next = await resolvePhase(state, afterAsk, permission);
|
|
350
|
+
if (!lastResolved || gen >= lastResolved.gen) lastResolved = { gen, state: next };
|
|
351
|
+
return next;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async function resolvePhase(state: State, afterAsk: boolean, permission?: string): Promise<State> {
|
|
355
|
+
let status: string;
|
|
356
|
+
let avail: Awaited<ReturnType<typeof availability>>;
|
|
357
|
+
try {
|
|
358
|
+
status = permission ?? await getPermissionStatus();
|
|
359
|
+
avail = await availability();
|
|
360
|
+
} catch {
|
|
361
|
+
// The motion bridge itself failed — say so and offer a retry rather than guessing a phase.
|
|
362
|
+
canLive = false;
|
|
363
|
+
return derive({ ...state, phase: "error", source: "", steps: 0 });
|
|
364
|
+
}
|
|
365
|
+
const stepHistory: StepHistoryStatus = avail.stepHistory;
|
|
366
|
+
const base: State = { ...state, stepHistory };
|
|
367
|
+
if (status !== "granted") {
|
|
368
|
+
canLive = false;
|
|
369
|
+
// No sensor and no history: nothing on this device could ever be counted, so it is
|
|
370
|
+
// "unsupported" — not a refusal to send to Settings, and not a prompt worth showing.
|
|
371
|
+
// - "undetermined" says so at once, before any ask: an iPad, the Simulator, a Mac, a browser
|
|
372
|
+
// (iOS Safari's orientation prompt would count no steps either way). Android never reports
|
|
373
|
+
// "undetermined" — a never-asked grant reads "denied" and its `steps` needs the grant — so
|
|
374
|
+
// a first open on a real phone still shows the connect card.
|
|
375
|
+
// - after an ask, anything but a real refusal ("denied") lands here too.
|
|
376
|
+
const nothingToCount = avail.steps !== true && stepHistory === "unsupported";
|
|
377
|
+
if (nothingToCount && (status === "undetermined" || (afterAsk && status !== "denied"))) {
|
|
378
|
+
return derive({ ...base, phase: "unsupported", source: "", steps: 0 });
|
|
379
|
+
}
|
|
380
|
+
return derive({ ...base, phase: afterAsk ? "denied" : "connect", source: "", steps: 0 });
|
|
381
|
+
}
|
|
382
|
+
canLive = avail.steps === true;
|
|
383
|
+
if (!canLive && stepHistory === "unsupported") {
|
|
384
|
+
return derive({ ...base, phase: "unsupported", source: "", steps: 0 });
|
|
385
|
+
}
|
|
386
|
+
return counted(base);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** The worker has no clock, so a screen left open across midnight would keep yesterday's count.
|
|
390
|
+
* A `tick` every 15 s notices the new day (a no-op otherwise); the host also fires it at once when the app comes
|
|
391
|
+
* back to the foreground (and suspends it in the background). */
|
|
392
|
+
const DAY_WATCH: PollDirective = {
|
|
393
|
+
id: "himi-steps-day",
|
|
394
|
+
intervalMs: 15_000,
|
|
395
|
+
action: "himiBrandedSteps.tick",
|
|
396
|
+
immediate: false,
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
const svc = defineService<State, {
|
|
400
|
+
load: (state: State, arg?: unknown) => Promise<State & { _poll: PollDirective }>;
|
|
401
|
+
tick: (state: State) => Promise<State>;
|
|
402
|
+
connect: (state: State) => Promise<State>;
|
|
403
|
+
setup: (state: State) => Promise<State>;
|
|
404
|
+
refresh: (state: State) => Promise<State>;
|
|
405
|
+
sample: (state: State, sample?: unknown) => Promise<State> | State;
|
|
406
|
+
}>("himiBrandedSteps", {
|
|
407
|
+
state: INITIAL,
|
|
408
|
+
// Every key but the goal is a READING: a cold boot on a later day must not paint yesterday's
|
|
409
|
+
// persisted count as "Today" while `load` re-reads — it starts from the loading state instead.
|
|
410
|
+
notHydrated: (Object.keys(INITIAL) as Array<keyof State>).filter((key) => key !== "goal"),
|
|
411
|
+
actions: {
|
|
412
|
+
// Runs on every entry (onAppear), so it is also what arms the day watch.
|
|
413
|
+
load: async (state, arg) => {
|
|
414
|
+
stashCopy(arg);
|
|
415
|
+
// A re-run without the onAppear params (iOS re-runs every service's `load` with none when a
|
|
416
|
+
// pooled worker is reclaimed) keeps the provisioned goal instead of falling back to 8,000.
|
|
417
|
+
const goal = hasGoalParam(arg) ? parseGoal(arg) : state.goal;
|
|
418
|
+
return { ...(await resolve({ ...state, goal }, false)), _poll: DAY_WATCH };
|
|
419
|
+
},
|
|
420
|
+
// The day watch: a count that belongs to an earlier day is re-resolved for today.
|
|
421
|
+
tick: async (state) =>
|
|
422
|
+
state.phase === "counting" && state.day !== "" && state.day !== dayKey(Date.now()) ? resolve(state, false) : state,
|
|
423
|
+
// "Count my steps": the motion prompt (and, on Android, a store's own grant right after it
|
|
424
|
+
// when it needs one — see MotionCapability.StepHistory).
|
|
425
|
+
connect: async (state) => {
|
|
426
|
+
let permission: string;
|
|
427
|
+
try {
|
|
428
|
+
permission = await requestPermission();
|
|
429
|
+
} catch {
|
|
430
|
+
return derive({ ...state, phase: "error", source: "", steps: 0 }); // the prompt never ran
|
|
431
|
+
}
|
|
432
|
+
return resolve(state, true, permission);
|
|
433
|
+
},
|
|
434
|
+
// Setup: leaves the app to update / install the store or grant access, then re-reads
|
|
435
|
+
// everything — opening the store is not the same as installing.
|
|
436
|
+
setup: async (state) => {
|
|
437
|
+
await openStepHistorySetup().catch(() => false);
|
|
438
|
+
return resolve(state, false);
|
|
439
|
+
},
|
|
440
|
+
refresh: async (state) => (state.phase === "loading" ? state : resolve(state, false)),
|
|
441
|
+
// A live pedometer sample (internal — the watch loop dispatches it): `steps` is the delta;
|
|
442
|
+
// on Android `stepsSinceBoot` + `bootTimeMs` carry the counter's running total.
|
|
443
|
+
sample: async (state, arg) => {
|
|
444
|
+
const sample = (typeof arg === "number" ? { steps: arg } : (arg ?? {})) as Partial<StepSample>;
|
|
445
|
+
const delta = Number(sample.steps);
|
|
446
|
+
if (state.phase !== "counting" || !Number.isFinite(delta) || delta < 0) return state;
|
|
447
|
+
const now = Date.now();
|
|
448
|
+
const day = dayKey(now);
|
|
449
|
+
let add = Math.round(delta);
|
|
450
|
+
const hasCounter = typeof sample.stepsSinceBoot === "number" && typeof sample.bootTimeMs === "number";
|
|
451
|
+
// A delta whose stream last reported on an EARLIER day — or that arrives after the shown
|
|
452
|
+
// count's day — was (at least partly) walked before midnight: an app back from the
|
|
453
|
+
// background delivers the whole gap at once, and the foreground `tick` may already have
|
|
454
|
+
// switched the day. Credit none of it to today: the store has today's real total, and the
|
|
455
|
+
// next sample counts on from here.
|
|
456
|
+
const spansMidnight = (lastLiveDay !== "" && lastLiveDay !== day) || (state.day !== "" && state.day !== day);
|
|
457
|
+
lastLiveDay = day;
|
|
458
|
+
if (spansMidnight) {
|
|
459
|
+
if (hasCounter) {
|
|
460
|
+
counterAnchored = true;
|
|
461
|
+
writeMark({ day, counter: sample.stepsSinceBoot as number, bootTimeMs: sample.bootTimeMs as number });
|
|
462
|
+
}
|
|
463
|
+
return state.day !== day ? resolve(state, false) : state;
|
|
464
|
+
}
|
|
465
|
+
let bridged = 0;
|
|
466
|
+
let markBefore: CounterMark | null = null;
|
|
467
|
+
if (hasCounter && !counterAnchored) {
|
|
468
|
+
// The first reading of this stream: add what the counter grew by while nobody listened.
|
|
469
|
+
counterAnchored = true;
|
|
470
|
+
markBefore = readMark();
|
|
471
|
+
bridged = stepsWhileAway(markBefore, day, sample.stepsSinceBoot as number, sample.bootTimeMs as number);
|
|
472
|
+
add += bridged;
|
|
473
|
+
}
|
|
474
|
+
// The mark is written on EVERY return below, with the total shown at that moment.
|
|
475
|
+
const remember = (shown: number): void => {
|
|
476
|
+
if (hasCounter) writeMark({ day, counter: sample.stepsSinceBoot as number, bootTimeMs: sample.bootTimeMs as number, shown });
|
|
477
|
+
};
|
|
478
|
+
// Add to the STORED total for today, not to state.steps: across midnight the key changes
|
|
479
|
+
// and the count restarts from the new day's (empty) total instead of carrying yesterday's.
|
|
480
|
+
const live = readLiveTotal(now) + add;
|
|
481
|
+
if (add > 0) writeLiveTotal(now, live);
|
|
482
|
+
// The bridged gap was walked before the store's last read. A store that recorded it already
|
|
483
|
+
// holds it; one still waiting on its batch does not. So take the LARGER of the two views,
|
|
484
|
+
// never both: the store's (the gap inside its total) and "shown at the mark + the gap".
|
|
485
|
+
if (bridged > 0 && lastHistory?.day === day) {
|
|
486
|
+
const storeView = { ...lastHistory, liveAtRead: lastHistory.liveAtRead + bridged };
|
|
487
|
+
const storeEstimate = storeView.steps + Math.max(0, live - storeView.liveAtRead);
|
|
488
|
+
const withGap = (markBefore?.shown ?? 0) + bridged;
|
|
489
|
+
lastHistory = withGap > storeEstimate ? { day, steps: withGap, liveAtRead: live } : storeView;
|
|
490
|
+
}
|
|
491
|
+
const liveSinceFirstOpen = state.liveSinceFirstOpen || hasCounter;
|
|
492
|
+
if (state.source === "today") {
|
|
493
|
+
// A new day re-reads at once: the throttle must not keep yesterday's total on screen.
|
|
494
|
+
if (add > 0 && (now - lastHistoryRead >= HISTORY_REREAD_MS || lastHistory?.day !== day)) {
|
|
495
|
+
lastHistoryRead = now;
|
|
496
|
+
const completedBefore = lastResolved?.gen ?? 0;
|
|
497
|
+
const today = await readToday();
|
|
498
|
+
// Rebase only on a store that has caught up with what is shown: a lagging answer must not
|
|
499
|
+
// move the number backwards (it lacks the steps the live stream already counted).
|
|
500
|
+
if (today.ok && today.steps !== null && today.steps >= historyNow(today.day, live)) {
|
|
501
|
+
lastHistory = { day: today.day, steps: today.steps, liveAtRead: live };
|
|
502
|
+
}
|
|
503
|
+
// A resolve ran during the read (a tick at midnight, a re-entry): its state is newer than
|
|
504
|
+
// this snapshot, so commit that. The live total is already stored, so nothing is lost.
|
|
505
|
+
if (lastResolved && lastResolved.gen !== completedBefore) {
|
|
506
|
+
remember(lastResolved.state.day === day ? lastResolved.state.steps : live);
|
|
507
|
+
return lastResolved.state;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
const steps = Math.max(historyNow(day, live), live);
|
|
511
|
+
remember(steps);
|
|
512
|
+
return derive({ ...state, liveSinceFirstOpen, steps });
|
|
513
|
+
}
|
|
514
|
+
if (state.source !== "live") {
|
|
515
|
+
remember(live);
|
|
516
|
+
return state;
|
|
517
|
+
}
|
|
518
|
+
remember(live);
|
|
519
|
+
return derive({ ...state, liveSinceFirstOpen, steps: live });
|
|
520
|
+
},
|
|
521
|
+
},
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
export { svc };
|
|
@@ -11,6 +11,8 @@ export interface CollectionSaving {
|
|
|
11
11
|
type State = Record<string, unknown>;
|
|
12
12
|
interface BackendCollection {
|
|
13
13
|
restorePagesOnLoad?: boolean;
|
|
14
|
+
/** Sees the load action's argument (the screen's onAppear params) BEFORE the query runs. */
|
|
15
|
+
onLoad?(arg: unknown): void;
|
|
14
16
|
controller: ReturnType<typeof createCollectionQuery<CollectionRow>>;
|
|
15
17
|
apply(state: State, page: CollectionQueryState<CollectionRow>): State;
|
|
16
18
|
}
|
|
@@ -294,6 +296,7 @@ export function decorateCollection(name: string, def: { state: State; actions?:
|
|
|
294
296
|
actions.collectionDataChanged = s => derive(backend.apply(s, backend.controller.getState()));
|
|
295
297
|
actions.load = (_s, arg) => {
|
|
296
298
|
stashCopy(arg); syncSaved(); applyNavigationCriteria(arg, _s);
|
|
299
|
+
backend.onLoad?.(arg);
|
|
297
300
|
return backend.controller.query(criteria(), backend.restorePagesOnLoad).then(() => undefined);
|
|
298
301
|
};
|
|
299
302
|
actions.refresh = (_s, arg) => {
|
|
@@ -320,6 +323,9 @@ export function decorateCollection(name: string, def: { state: State; actions?:
|
|
|
320
323
|
export function defineBackendCollection<S extends object, Row extends object>(name: string, options: {
|
|
321
324
|
/** Revalidate already opened pages on navigation return; explicit refresh resets. */
|
|
322
325
|
restorePagesOnLoad?: boolean;
|
|
326
|
+
/** The load action's argument (onAppear params beyond `copy`), before the query runs — for a
|
|
327
|
+
* domain setting that rides the descriptor, e.g. My Bookings' `weeklyGoal`. */
|
|
328
|
+
onLoad?(arg: unknown): void;
|
|
323
329
|
state: S;
|
|
324
330
|
source: CollectionQuerySource<Row>;
|
|
325
331
|
apply(state: S, page: CollectionQueryState<Row>): S;
|
|
@@ -330,6 +336,7 @@ export function defineBackendCollection<S extends object, Row extends object>(na
|
|
|
330
336
|
const controller = createCollectionQuery(options.source, () => { publish?.(); });
|
|
331
337
|
const definition = decorateCollection(name, { state: options.state as State, actions: options.actions as Record<string, Reducer> | undefined }, options.saving, {
|
|
332
338
|
restorePagesOnLoad: options.restorePagesOnLoad,
|
|
339
|
+
onLoad: options.onLoad,
|
|
333
340
|
controller: controller as unknown as BackendCollection['controller'],
|
|
334
341
|
apply: (state, page) => options.apply(state as S, page as unknown as CollectionQueryState<Row>) as State,
|
|
335
342
|
});
|
|
@@ -11,6 +11,8 @@ export interface CollectionSaving {
|
|
|
11
11
|
type State = Record<string, unknown>;
|
|
12
12
|
interface BackendCollection {
|
|
13
13
|
restorePagesOnLoad?: boolean;
|
|
14
|
+
/** Sees the load action's argument (the screen's onAppear params) BEFORE the query runs. */
|
|
15
|
+
onLoad?(arg: unknown): void;
|
|
14
16
|
controller: ReturnType<typeof createCollectionQuery<CollectionRow>>;
|
|
15
17
|
apply(state: State, page: CollectionQueryState<CollectionRow>): State;
|
|
16
18
|
}
|
|
@@ -294,6 +296,7 @@ export function decorateCollection(name: string, def: { state: State; actions?:
|
|
|
294
296
|
actions.collectionDataChanged = s => derive(backend.apply(s, backend.controller.getState()));
|
|
295
297
|
actions.load = (_s, arg) => {
|
|
296
298
|
stashCopy(arg); syncSaved(); applyNavigationCriteria(arg, _s);
|
|
299
|
+
backend.onLoad?.(arg);
|
|
297
300
|
return backend.controller.query(criteria(), backend.restorePagesOnLoad).then(() => undefined);
|
|
298
301
|
};
|
|
299
302
|
actions.refresh = (_s, arg) => {
|
|
@@ -320,6 +323,9 @@ export function decorateCollection(name: string, def: { state: State; actions?:
|
|
|
320
323
|
export function defineBackendCollection<S extends object, Row extends object>(name: string, options: {
|
|
321
324
|
/** Revalidate already opened pages on navigation return; explicit refresh resets. */
|
|
322
325
|
restorePagesOnLoad?: boolean;
|
|
326
|
+
/** The load action's argument (onAppear params beyond `copy`), before the query runs — for a
|
|
327
|
+
* domain setting that rides the descriptor, e.g. My Bookings' `weeklyGoal`. */
|
|
328
|
+
onLoad?(arg: unknown): void;
|
|
323
329
|
state: S;
|
|
324
330
|
source: CollectionQuerySource<Row>;
|
|
325
331
|
apply(state: S, page: CollectionQueryState<Row>): S;
|
|
@@ -330,6 +336,7 @@ export function defineBackendCollection<S extends object, Row extends object>(na
|
|
|
330
336
|
const controller = createCollectionQuery(options.source, () => { publish?.(); });
|
|
331
337
|
const definition = decorateCollection(name, { state: options.state as State, actions: options.actions as Record<string, Reducer> | undefined }, options.saving, {
|
|
332
338
|
restorePagesOnLoad: options.restorePagesOnLoad,
|
|
339
|
+
onLoad: options.onLoad,
|
|
333
340
|
controller: controller as unknown as BackendCollection['controller'],
|
|
334
341
|
apply: (state, page) => options.apply(state as S, page as unknown as CollectionQueryState<Row>) as State,
|
|
335
342
|
});
|