diff --git a/README.md b/README.md index bf95b84..c37831c 100644 --- a/README.md +++ b/README.md @@ -731,6 +731,107 @@ if (batch.changesTokenExpired) { } ``` +### React hooks + +Typed hooks wrap the imperative API. Each one fetches on mount, fetches again +whenever the app returns to the foreground (built on `pollOnForeground`), +refetches when its arguments change (compared by value, so inline arrays and +objects are fine), and drops results that arrive after unmount or for older +arguments. + +```tsx +import { + Permission, + RecordType, + timeRangeLastDays, + timeRangeToday, + useAggregate, + useHealthConnectAvailability, + useHealthConnectPermissions, + useMostRecentRecord, + useReadRecords, + type StepsRecord, + type WeightRecord, +} from '@solutionforest/android-health-connect'; + +function Dashboard() { + const availability = useHealthConnectAvailability(); + const [perms, request] = useHealthConnectPermissions([ + Permission.READ_STEPS, + Permission.READ_WEIGHT, + ]); + const ready = + availability.value === 'available' && perms.value?.allGranted === true; + + // Pass a function for "now"-relative ranges: it is re-evaluated on every + // fetch and does not restart the query on re-render. + const today = useAggregate(RecordType.STEPS, () => timeRangeToday(), { + enabled: ready, + }); + const week = useReadRecords(RecordType.STEPS, { + timeRangeFilter: () => timeRangeLastDays(7), + enabled: ready, + }); + const weight = useMostRecentRecord(RecordType.WEIGHT, { + enabled: ready, + }); + + if (availability.value !== 'available') return Install Health Connect; + if (!perms.value?.allGranted) return +
const steps = useAggregate(RecordType.STEPS, () => timeRangeToday(), {
+  ready: (r) => ((r.metrics['COUNT_TOTAL'] as number | null) ?? 0) > 0,
+  timeoutMs: 20_000,
+});
+// steps.satisfied === false → timed out; the value may be a real 0
+ +

Changelog sync with useChanges

+

+ useChanges(token, { onChanges }) drains the changelog with + pullChanges on mount and on every resume. After each pull it + continues from nextChangesToken, so persist that token in + onChanges. Pass null to pause until you have a + token. When changesTokenExpired is true, backfill and pass a + fresh token from getChangesToken; a new token + restarts from it. +

+
+
useStepsSync.ts
+
const [token, setToken] = useState<string | null>(storedToken);
+useChanges(token, {
+  onChanges: ({ upsertionChanges, deletionChanges, nextChangesToken, changesTokenExpired }) => {
+    if (changesTokenExpired) {
+      void backfill().then(() =>
+        getChangesToken({ recordTypes: [RecordType.STEPS] }).then(setToken),
+      );
+      return;
+    }
+    applyToLocalDb(upsertionChanges, deletionChanges);
+    saveToken(nextChangesToken);
+  },
+});
+
+ +
-

14Exercise routes#

+

15Exercise routes#

Writing a route with a session needs WRITE_EXERCISE_ROUTE; reading routes from other apps needs READ_EXERCISE_ROUTES. On @@ -728,7 +846,7 @@

14Exercise routes

-

15Planned exercise#

+

16Planned exercise#

Training plans need getFeatureStatus(Feature.PLANNED_EXERCISE) === FeatureStatus.AVAILABLE, plus READ_PLANNED_EXERCISE / @@ -789,7 +907,7 @@

15Planned exercise -

16Matchmaking & PHR#

+

17Matchmaking & PHR#

Newer Health Connect features are not on every device. Always check getFeatureStatus(Feature.*) first. It returns @@ -861,7 +979,7 @@

16Matchmaking & PHR -

17Upgrade reminders#

+

18Upgrade reminders#

checkLibraryUpdate compares the installed version with the latest GitHub Release, so you can show a banner in debug builds. @@ -881,7 +999,7 @@

17Upgrade reminders -

18Common mistakes#

+

19Common mistakes#

diff --git a/skills.md b/skills.md index 5ff5739..6b800f3 100644 --- a/skills.md +++ b/skills.md @@ -4,7 +4,7 @@ description: >- Integrate Solution Forest's React Native TurboModule for Android Health Connect (@solutionforest/android-health-connect). Use when adding HC permissions, reading/writing health records, aggregates, changelog sync, - Matchmaking, PHR, Expo plugin setup, or choosing npmjs vs GitHub Packages. + React hooks, Matchmaking, PHR, Expo plugin setup, or choosing npmjs vs GitHub Packages. --- # android-health-connect @@ -14,6 +14,7 @@ description: >- - Wiring Android Health Connect into a React Native / Expo app - Choosing install source: **npmjs.org (primary)** or **GitHub Packages (mirror)** - Implementing availability, permissions, records, aggregates, or resume polling +- Building React screens with the hooks (`useHealthConnectPermissions`, `useAggregate`, …) ## Do not @@ -23,6 +24,7 @@ description: >- - Hand-type permission strings when `Permission.*` exists - Hand-type record type strings when `RecordType.*` exists (`RecordType.STEPS`, not `'Steps'`) - Expect push/live updates from Health Connect — poll on resume +- Pass `timeRangeToday()` (a new object each render) to a hook — pass `() => timeRangeToday()` ## Install @@ -86,6 +88,27 @@ const { value, loading, refresh } = useForegroundPoll( Non-React: `pollOnForeground` / `pollUntil` / `waitUntil`. +**React components: prefer the typed hooks.** They fetch on mount, on every resume and when their arguments change, and ignore results after unmount. Data hooks return `{ value, satisfied, loading, error, refresh }` and accept `enabled`, `ready`, `timeoutMs`, `intervalMs`. + +| Hook | `value` | +|---|---| +| `useHealthConnectAvailability()` | `'available' \| 'notInstalled' \| 'notSupported'` | +| `useHealthConnectPermissions(perms)` | `[status, request]`; `status.value` = `{ granted, missing, allGranted }` | +| `useReadRecords(RecordType.X, opts)` | `ReadRecordsResponse` | +| `useMostRecentRecord(RecordType.X, opts?)` | `T \| null` | +| `useAggregate(RecordType.X, range, opts?)` | `AggregateResult` | +| `useChanges(token, { onChanges })` | `PullChangesResult`; continues from `nextChangesToken`, persist it in `onChanges` | + +```tsx +const [perms, request] = useHealthConnectPermissions([Permission.READ_STEPS]); +const today = useAggregate(RecordType.STEPS, () => timeRangeToday(), { + enabled: perms.value?.allGranted === true, + ready: (r) => ((r.metrics['COUNT_TOTAL'] as number | null) ?? 0) > 0, +}); +``` + +Pass "now"-relative ranges as a **function** (`() => timeRangeToday()`), not `timeRangeToday()`: a function is re-evaluated per fetch, while a fresh object each render changes the arguments and refetches every render. + 5. **Write / update** — `writeRecords([{ recordType: RecordType.STEPS, … }])`; `updateRecords` requires `metadata.id` from a prior read. 6. **Aggregates** — `aggregateRecord`, `aggregateGroupByDuration` (Instant buckets), `aggregateGroupByPeriod` (calendar). 7. **Changelog** — `getChangesToken` → `getChanges` / `pullChanges` (tokens ~30 days; prefer one record type per token). diff --git a/src/__tests__/hooks.test.tsx b/src/__tests__/hooks.test.tsx new file mode 100644 index 0000000..2a643b8 --- /dev/null +++ b/src/__tests__/hooks.test.tsx @@ -0,0 +1,544 @@ +import { act, create } from 'react-test-renderer'; +import type { ReactTestRenderer } from 'react-test-renderer'; +import { AppState, TurboModuleRegistry } from 'react-native'; +import { + useAggregate, + useChanges, + useHealthConnectAvailability, + useHealthConnectPermissions, + useMostRecentRecord, + useReadRecords, +} from '../index'; +import type { Spec } from '../NativeAndroidHealthConnect'; +import type { HealthPermission, RecordType, StepsRecord } from '../types'; + +jest.mock( + 'react-native', + () => { + const listeners = new Set(); + const native = { + isHealthConnectAvailable: jest.fn(), + checkPermissions: jest.fn(), + requestPermissions: jest.fn(), + readRecords: jest.fn(), + aggregateRecord: jest.fn(), + getChanges: jest.fn(), + }; + return { + TurboModuleRegistry: { getEnforcing: () => native }, + Platform: { OS: 'android' }, + AppState: { + addEventListener: jest.fn((_type: string, cb: Function) => { + listeners.add(cb); + return { remove: () => listeners.delete(cb) }; + }), + emit: (next: string) => listeners.forEach((cb) => cb(next)), + listenerCount: () => listeners.size, + }, + }; + }, + { virtual: true } +); + +const mockNative = TurboModuleRegistry.getEnforcing( + 'AndroidHealthConnect' +) as jest.Mocked; + +const appState = AppState as unknown as { + emit: (state: string) => void; + listenerCount: () => number; +}; + +const STEPS = 'Steps' as RecordType; +const WEIGHT = 'Weight' as RecordType; +const READ_STEPS = 'android.permission.health.READ_STEPS' as HealthPermission; +const READ_HR = 'android.permission.health.READ_HEART_RATE' as HealthPermission; + +const flush = async () => { + await act(async () => { + for (let i = 0; i < 10; i++) await Promise.resolve(); + }); +}; + +const mounted = new Set(); + +/** Renders `useHook` and exposes the latest return value. */ +function renderHook(useHook: (props: P) => R, initialProps: P) { + const result: { current: R } = { current: undefined as R }; + function Probe(props: { p: P }) { + result.current = useHook(props.p); + return null; + } + let renderer!: ReactTestRenderer; + act(() => { + renderer = create(); + }); + mounted.add(renderer); + return { + result, + rerender: (p: P) => act(() => renderer.update()), + unmount: () => { + mounted.delete(renderer); + act(() => renderer.unmount()); + }, + }; +} + +function deferred() { + let resolve!: (v: T) => void; + const promise = new Promise((r) => (resolve = r)); + return { promise, resolve }; +} + +const page = (records: unknown[], pageToken: string | null = null) => + JSON.stringify({ records, pageToken }); + +beforeEach(() => { + jest.clearAllMocks(); +}); + +afterEach(() => { + // Unmount anything a failed test left behind so failures don't cascade. + mounted.forEach((r) => { + act(() => { + r.unmount(); + }); + }); + mounted.clear(); + jest.useRealTimers(); + expect(appState.listenerCount()).toBe(0); +}); + +describe('useHealthConnectAvailability', () => { + it('loads on mount and re-checks on resume', async () => { + mockNative.isHealthConnectAvailable.mockResolvedValueOnce('notInstalled'); + const { result, unmount } = renderHook( + () => useHealthConnectAvailability(), + {} + ); + expect(result.current.loading).toBe(true); + await flush(); + expect(result.current.value).toBe('notInstalled'); + expect(result.current.loading).toBe(false); + expect(result.current.satisfied).toBe(true); + + mockNative.isHealthConnectAvailable.mockResolvedValueOnce('available'); + act(() => appState.emit('active')); + await flush(); + expect(result.current.value).toBe('available'); + expect(mockNative.isHealthConnectAvailable).toHaveBeenCalledTimes(2); + unmount(); + }); + + it('does not fetch while disabled', async () => { + const { result, unmount } = renderHook( + () => useHealthConnectAvailability({ enabled: false }), + {} + ); + await flush(); + expect(result.current.loading).toBe(false); + expect(result.current.value).toBeUndefined(); + expect(mockNative.isHealthConnectAvailable).not.toHaveBeenCalled(); + unmount(); + }); + + it('reports errors and keeps loading false', async () => { + const boom = new Error('boom'); + mockNative.isHealthConnectAvailable.mockRejectedValueOnce(boom); + const { result, unmount } = renderHook( + () => useHealthConnectAvailability(), + {} + ); + await flush(); + expect(result.current.error).toBe(boom); + expect(result.current.loading).toBe(false); + + mockNative.isHealthConnectAvailable.mockResolvedValueOnce('available'); + act(() => result.current.refresh()); + expect(result.current.loading).toBe(true); + expect(result.current.error).toBeUndefined(); + await flush(); + expect(result.current.value).toBe('available'); + unmount(); + }); + + it('drops a result that arrives after unmount', async () => { + const pending = deferred(); + mockNative.isHealthConnectAvailable.mockReturnValueOnce(pending.promise); + const { result, unmount } = renderHook( + () => useHealthConnectAvailability(), + {} + ); + const before = result.current; + unmount(); + pending.resolve('available'); + await flush(); + expect(result.current).toBe(before); + expect(result.current.value).toBeUndefined(); + }); +}); + +describe('useHealthConnectPermissions', () => { + it('reports granted and missing permissions', async () => { + mockNative.checkPermissions.mockResolvedValue([READ_STEPS]); + const { result, unmount } = renderHook( + () => useHealthConnectPermissions([READ_STEPS, READ_HR]), + {} + ); + await flush(); + const [status] = result.current; + expect(status.value).toEqual({ + granted: [READ_STEPS], + missing: [READ_HR], + allGranted: false, + }); + unmount(); + }); + + it('request asks only for missing permissions and refreshes the status', async () => { + mockNative.checkPermissions.mockResolvedValue([READ_STEPS]); + const { result, unmount } = renderHook( + () => useHealthConnectPermissions([READ_STEPS, READ_HR]), + {} + ); + await flush(); + + mockNative.requestPermissions.mockResolvedValue([READ_HR]); + mockNative.checkPermissions + .mockResolvedValueOnce([READ_STEPS]) + .mockResolvedValue([READ_STEPS, READ_HR]); + let outcome: unknown; + await act(async () => { + outcome = await result.current[1](); + }); + await flush(); + + expect(mockNative.requestPermissions).toHaveBeenCalledWith([READ_HR]); + expect(outcome).toEqual({ + granted: [READ_STEPS, READ_HR], + missing: [], + allGranted: true, + }); + expect(result.current[0].value?.allGranted).toBe(true); + unmount(); + }); + + it('request skips the dialog when everything is granted', async () => { + mockNative.checkPermissions.mockResolvedValue([READ_STEPS]); + const { result, unmount } = renderHook( + () => useHealthConnectPermissions([READ_STEPS]), + {} + ); + await flush(); + await act(async () => { + await result.current[1](); + }); + expect(mockNative.requestPermissions).not.toHaveBeenCalled(); + unmount(); + }); + + it('treats an empty list as granted without a native call', async () => { + const { result, unmount } = renderHook( + () => useHealthConnectPermissions([]), + {} + ); + await flush(); + expect(result.current[0].value?.allGranted).toBe(true); + expect(mockNative.checkPermissions).not.toHaveBeenCalled(); + unmount(); + }); + + it('does not refetch when an inline array keeps the same contents', async () => { + mockNative.checkPermissions.mockResolvedValue([READ_STEPS]); + const { rerender, unmount } = renderHook( + (perms: HealthPermission[]) => useHealthConnectPermissions(perms), + [READ_STEPS] + ); + await flush(); + rerender([READ_STEPS]); + await flush(); + expect(mockNative.checkPermissions).toHaveBeenCalledTimes(1); + unmount(); + }); +}); + +describe('useReadRecords', () => { + const range = { + startTime: '2026-01-01T00:00:00.000Z', + endTime: '2026-01-02T00:00:00.000Z', + }; + + it('reads a page with the given options', async () => { + const record = { recordType: 'Steps', count: 10 }; + mockNative.readRecords.mockResolvedValue(page([record])); + const { result, unmount } = renderHook( + () => + useReadRecords(STEPS, { + timeRangeFilter: range, + pageSize: 50, + }), + {} + ); + await flush(); + expect(result.current.value?.records).toEqual([record]); + expect(mockNative.readRecords).toHaveBeenCalledWith( + STEPS, + JSON.stringify({ pageSize: 50, timeRangeFilter: range }) + ); + unmount(); + }); + + it('evaluates a range factory on every fetch without restarting on re-render', async () => { + mockNative.readRecords.mockResolvedValue(page([])); + let n = 0; + const makeRange = () => { + n += 1; + return { startTime: `s${n}`, endTime: `e${n}` }; + }; + const { rerender, unmount } = renderHook( + () => useReadRecords(STEPS, { timeRangeFilter: makeRange }), + {} + ); + await flush(); + rerender({}); + await flush(); + expect(mockNative.readRecords).toHaveBeenCalledTimes(1); + + act(() => appState.emit('active')); + await flush(); + expect(mockNative.readRecords).toHaveBeenCalledTimes(2); + expect(mockNative.readRecords).toHaveBeenLastCalledWith( + STEPS, + JSON.stringify({ timeRangeFilter: { startTime: 's2', endTime: 'e2' } }) + ); + unmount(); + }); + + it('refetches when the record type changes and hides the old data', async () => { + mockNative.readRecords.mockResolvedValueOnce(page([{ count: 1 }])); + const { result, rerender, unmount } = renderHook( + (type: RecordType) => useReadRecords(type), + STEPS + ); + await flush(); + expect(result.current.value?.records).toHaveLength(1); + + const pending = deferred(); + mockNative.readRecords.mockReturnValueOnce(pending.promise); + rerender(WEIGHT); + expect(result.current.value).toBeUndefined(); + expect(result.current.loading).toBe(true); + + pending.resolve(page([])); + await flush(); + expect(result.current.value?.records).toEqual([]); + expect(mockNative.readRecords).toHaveBeenLastCalledWith(WEIGHT, '{}'); + unmount(); + }); + + it('ignores a slow result for the previous arguments', async () => { + const slow = deferred(); + mockNative.readRecords.mockReturnValueOnce(slow.promise); + const { result, rerender, unmount } = renderHook( + (type: RecordType) => useReadRecords(type), + STEPS + ); + mockNative.readRecords.mockResolvedValueOnce(page([{ kg: 70 }])); + rerender(WEIGHT); + await flush(); + slow.resolve(page([{ count: 999 }])); + await flush(); + expect(result.current.value?.records).toEqual([{ kg: 70 }]); + unmount(); + }); + + it('polls until ready, reporting satisfied', async () => { + jest.useFakeTimers(); + mockNative.readRecords + .mockResolvedValueOnce(page([])) + .mockResolvedValueOnce(page([{ count: 5 }])); + const { result, unmount } = renderHook( + () => + useReadRecords(STEPS, { + ready: (r) => r.records.length > 0, + intervalMs: 100, + timeoutMs: 1000, + }), + {} + ); + await flush(); + expect(result.current.loading).toBe(true); + await act(async () => { + jest.advanceTimersByTime(100); + }); + await flush(); + expect(result.current.value?.records).toHaveLength(1); + expect(result.current.satisfied).toBe(true); + unmount(); + jest.useRealTimers(); + }); +}); + +describe('useMostRecentRecord', () => { + it('reads one record in descending order', async () => { + const latest = { recordType: 'Weight', weight: { inKilograms: 70 } }; + mockNative.readRecords.mockResolvedValue(page([latest])); + const { result, unmount } = renderHook( + () => useMostRecentRecord(WEIGHT, { dataOriginFilter: ['com.x'] }), + {} + ); + await flush(); + expect(result.current.value).toEqual(latest); + expect(mockNative.readRecords).toHaveBeenCalledWith( + WEIGHT, + JSON.stringify({ + dataOriginFilter: ['com.x'], + ascendingOrder: false, + pageSize: 1, + }) + ); + unmount(); + }); + + it('returns null when there is no record', async () => { + mockNative.readRecords.mockResolvedValue(page([])); + const { result, unmount } = renderHook( + () => + useMostRecentRecord(WEIGHT, { + timeRangeFilter: () => ({ startTime: 'a', endTime: 'b' }), + }), + {} + ); + await flush(); + expect(result.current.value).toBeNull(); + expect(result.current.loading).toBe(false); + unmount(); + }); +}); + +describe('useAggregate', () => { + const result0 = { + recordType: 'Steps', + dataOrigins: [], + metrics: { COUNT_TOTAL: 1234 }, + }; + + it('aggregates over a static range with an origin filter', async () => { + mockNative.aggregateRecord.mockResolvedValue(JSON.stringify(result0)); + const range = { startTime: 'a', endTime: 'b' }; + const { result, unmount } = renderHook( + () => useAggregate('Steps', range, { dataOriginFilter: ['com.fit'] }), + {} + ); + await flush(); + expect(result.current.value).toEqual(result0); + expect(mockNative.aggregateRecord).toHaveBeenCalledWith( + JSON.stringify({ + recordType: 'Steps', + timeRangeFilter: range, + dataOriginFilter: ['com.fit'], + }) + ); + unmount(); + }); + + it('accepts a range factory', async () => { + mockNative.aggregateRecord.mockResolvedValue(JSON.stringify(result0)); + const { unmount } = renderHook( + () => useAggregate('Steps', () => ({ startTime: 'x', endTime: 'y' })), + {} + ); + await flush(); + expect(mockNative.aggregateRecord).toHaveBeenCalledWith( + JSON.stringify({ + recordType: 'Steps', + timeRangeFilter: { startTime: 'x', endTime: 'y' }, + }) + ); + unmount(); + }); +}); + +describe('useChanges', () => { + const changesPage = (next: string, extra: object = {}) => + JSON.stringify({ + upsertionChanges: [], + deletionChanges: [], + nextChangesToken: next, + hasMore: false, + changesTokenExpired: false, + ...extra, + }); + + it('pauses without a token', async () => { + const { result, unmount } = renderHook(() => useChanges(null), {}); + await flush(); + expect(result.current.loading).toBe(false); + expect(mockNative.getChanges).not.toHaveBeenCalled(); + unmount(); + }); + + it('pulls from the token, then continues from nextChangesToken on resume', async () => { + const onChanges = jest.fn(); + mockNative.getChanges + .mockResolvedValueOnce( + changesPage('t1', { deletionChanges: [{ recordId: 'r1' }] }) + ) + .mockResolvedValueOnce(changesPage('t2')); + const { result, unmount } = renderHook( + () => useChanges('t0', { onChanges, pageSize: 10 }), + {} + ); + await flush(); + expect(mockNative.getChanges).toHaveBeenLastCalledWith( + 't0', + JSON.stringify({ pageSize: 10 }) + ); + expect(result.current.value?.deletionChanges).toEqual([{ recordId: 'r1' }]); + expect(onChanges).toHaveBeenCalledTimes(1); + + act(() => appState.emit('active')); + await flush(); + expect(mockNative.getChanges).toHaveBeenLastCalledWith( + 't1', + JSON.stringify({ pageSize: 10 }) + ); + expect(result.current.value?.nextChangesToken).toBe('t2'); + expect(onChanges).toHaveBeenCalledTimes(2); + unmount(); + }); + + it('keeps the token when it has expired and restarts from a new token prop', async () => { + mockNative.getChanges.mockResolvedValueOnce( + changesPage('ignored', { changesTokenExpired: true }) + ); + const { result, rerender, unmount } = renderHook( + (token: string) => useChanges(token, { maxPages: 2 }), + 'old' as string + ); + await flush(); + expect(result.current.value?.changesTokenExpired).toBe(true); + + mockNative.getChanges.mockResolvedValueOnce(changesPage('t1')); + act(() => appState.emit('active')); + await flush(); + expect(mockNative.getChanges).toHaveBeenLastCalledWith('old', '{}'); + + mockNative.getChanges.mockResolvedValueOnce(changesPage('n1')); + rerender('fresh'); + await flush(); + expect(mockNative.getChanges).toHaveBeenLastCalledWith('fresh', '{}'); + unmount(); + }); + + it('does not call onChanges for a pull that finishes after unmount', async () => { + const onChanges = jest.fn(); + const pending = deferred(); + mockNative.getChanges.mockReturnValueOnce(pending.promise); + const { unmount } = renderHook(() => useChanges('t0', { onChanges }), {}); + unmount(); + pending.resolve(changesPage('t1')); + await flush(); + expect(onChanges).not.toHaveBeenCalled(); + }); +}); diff --git a/src/hooks.ts b/src/hooks.ts new file mode 100644 index 0000000..d13cf58 --- /dev/null +++ b/src/hooks.ts @@ -0,0 +1,426 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { + aggregateRecord, + checkPermissions, + isHealthConnectAvailable, + readRecords, + requestPermissions, +} from './index'; +import { pullChanges } from './helpers'; +import type { EnsurePermissionsResult, PullChangesResult } from './helpers'; +import { pollOnForeground } from './foreground'; +import type { + ForegroundPoller, + PollOnForegroundOptions, + UseForegroundPollState, +} from './foreground'; +import type { + AggregateRecordType, + AggregateRequest, + AggregateResult, + GetChangesOptions, + HealthConnectAvailability, + HealthPermission, + HealthRecord, + ReadRecordsOptions, + ReadRecordsResponse, + RecordType, + TimeRangeFilter, +} from './types'; + +// ─── Shared query plumbing ──────────────────────────────────────────────────── + +/** + * A time range, or a function that builds one. Pass a function (for example + * `() => timeRangeToday()`) when the range is relative to "now": it is + * re-evaluated on every fetch, including each foreground resume, and does not + * restart the query on re-render. + */ +export type TimeRangeInput = TimeRangeFilter | (() => TimeRangeFilter); + +/** Options shared by every data hook. */ +export type HealthQueryOptions = { + /** Set false to pause (e.g. until permissions are granted). Default: true. */ + enabled?: boolean; + /** + * Keep polling until this returns true, e.g. `(r) => r.records.length > 0` + * to wait out the "0 right after resume" sync gap. Default: accept the first + * result (one read per mount / resume / refresh). + */ + ready?: (value: T) => boolean; + /** Poll timeout when `ready` is set. Default: 15000. */ + timeoutMs?: number; + /** Poll interval when `ready` is set. Default: 500. */ + intervalMs?: number; +}; + +/** + * State returned by the data hooks. Same shape as {@link useForegroundPoll}: + * `value` is `undefined` until the first result for the current arguments. + */ +export type HealthQueryState = UseForegroundPollState; + +const acceptFirst = () => true; + +function resolveTimeRange(range: TimeRangeInput): TimeRangeFilter { + return typeof range === 'function' ? range() : range; +} + +type InternalState = Omit, 'refresh'> & { + key: string; +}; + +/** + * Runs `fetch` on mount, on every foreground resume and whenever `key` + * changes. Results for an older key, or after unmount, are dropped. + */ +function useHealthQuery( + key: string, + fetch: () => Promise, + options: HealthQueryOptions & { onResult?: (value: T) => void } +): HealthQueryState { + const { enabled = true, ready, timeoutMs, intervalMs, onResult } = options; + const fetchRef = useRef(fetch); + const readyRef = useRef(ready); + const onResultRef = useRef(onResult); + fetchRef.current = fetch; + readyRef.current = ready; + onResultRef.current = onResult; + + const pollerRef = useRef(undefined); + const [state, setState] = useState>({ + key, + value: undefined, + satisfied: false, + loading: enabled, + error: undefined, + }); + + useEffect(() => { + if (!enabled) return undefined; + + const pollOptions: PollOnForegroundOptions = { + ready: (v) => (readyRef.current ?? acceptFirst)(v), + onStart: () => + setState((s) => ({ + ...(s.key === key + ? s + : { key, value: undefined, satisfied: false, error: undefined }), + loading: true, + error: undefined, + })), + onResult: ({ value, satisfied }) => { + setState({ key, value, satisfied, loading: false, error: undefined }); + onResultRef.current?.(value); + }, + onError: (error) => + setState((s) => ({ + ...(s.key === key ? s : { key, value: undefined, satisfied: false }), + loading: false, + error, + })), + }; + if (timeoutMs !== undefined) pollOptions.timeoutMs = timeoutMs; + if (intervalMs !== undefined) pollOptions.intervalMs = intervalMs; + + const poller = pollOnForeground(() => fetchRef.current(), pollOptions); + pollerRef.current = poller; + + return () => { + poller.stop(); + pollerRef.current = undefined; + }; + }, [enabled, key, timeoutMs, intervalMs]); + + const refresh = useCallback(() => pollerRef.current?.refresh(), []); + + // Before the effect for a new key has run, don't show the old key's data. + if (state.key !== key) { + return { + value: undefined, + satisfied: false, + loading: enabled, + error: undefined, + refresh, + }; + } + return { + value: state.value, + satisfied: state.satisfied, + loading: state.loading, + error: state.error, + refresh, + }; +} + +// ─── Availability ───────────────────────────────────────────────────────────── + +/** + * Health Connect availability (`'available'`, `'notInstalled'`, + * `'notSupported'`). Re-checked on every resume, so the value updates after + * the user installs Health Connect from the Play Store and comes back. + */ +export function useHealthConnectAvailability( + options: Pick, 'enabled'> = {} +): HealthQueryState { + return useHealthQuery('availability', isHealthConnectAvailable, options); +} + +// ─── Permissions ────────────────────────────────────────────────────────────── + +export type HealthConnectPermissionsStatus = + HealthQueryState; + +/** Opens the HC permission dialog for missing permissions; resolves with the re-checked status. */ +export type RequestHealthConnectPermissions = + () => Promise; + +async function permissionStatus( + permissions: HealthPermission[] +): Promise { + if (permissions.length === 0) { + return { granted: [], missing: [], allGranted: true }; + } + const granted = await checkPermissions(permissions); + const grantedSet = new Set(granted); + const missing = permissions.filter((p) => !grantedSet.has(p)); + return { granted, missing, allGranted: missing.length === 0 }; +} + +/** + * Granted / missing state for `permissions`, plus a `request` function that + * shows the Health Connect dialog for the missing ones. The status is + * re-checked on every resume (the user may revoke access in Settings). + * + * @example + * ```tsx + * const [status, request] = useHealthConnectPermissions([ + * 'android.permission.health.READ_STEPS', + * ]); + * if (!status.value?.allGranted) return
SymptomCauseFix