diff --git a/package-lock.json b/package-lock.json
index b7d60b0e..af27544e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -24,7 +24,7 @@
"axios": "^1.17.0",
"events": "^3.3.0",
"gd-eventlog": "^0.1.27",
- "incyclist-services": "^1.9.21",
+ "incyclist-services": "^1.9.22",
"mqtt": "^5.15.2",
"path-browserify": "^1.0.1",
"process": "^0.11.10",
@@ -2118,9 +2118,10 @@
}
},
"node_modules/@emnapi/runtime": {
- "version": "1.11.3",
- "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
- "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
+ "version": "1.9.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz",
+ "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==",
+ "dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
@@ -3385,6 +3386,16 @@
"url": "https://opencollective.com/libvips"
}
},
+ "node_modules/@img/sharp-wasm32/node_modules/@emnapi/runtime": {
+ "version": "1.11.3",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@img/sharp-webcontainers-wasm32": {
"version": "0.35.5",
"resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
@@ -4083,9 +4094,9 @@
}
},
"node_modules/@napi-rs/wasm-runtime": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.5.tgz",
- "integrity": "sha512-HshSvXzmBxNzqejd3k/KemgQ3hdREUYFRRrgxOZ+gPljDIsO2SDZrVZMd4Z/HsxudQbE62OVyVFE8z9BCurfjA==",
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz",
+ "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -4100,8 +4111,8 @@
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
- "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4",
- "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4"
+ "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3",
+ "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3"
}
},
"node_modules/@nicolo-ribaudo/eslint-scope-5-internals": {
@@ -4464,17 +4475,6 @@
"node": "^20.19.0 || >=22.12.0"
}
},
- "node_modules/@oxc-parser/binding-wasm32-wasi/node_modules/@emnapi/runtime": {
- "version": "1.9.2",
- "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz",
- "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
"node_modules/@oxc-parser/binding-win32-arm64-msvc": {
"version": "0.127.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.127.0.tgz",
@@ -5758,6 +5758,9 @@
"arm"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5772,6 +5775,9 @@
"arm"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5786,6 +5792,9 @@
"arm64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5800,6 +5809,9 @@
"arm64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5814,6 +5826,9 @@
"loong64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5828,6 +5843,9 @@
"loong64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5842,6 +5860,9 @@
"ppc64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5856,6 +5877,9 @@
"ppc64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5870,6 +5894,9 @@
"riscv64"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5884,6 +5911,9 @@
"riscv64"
],
"dev": true,
+ "libc": [
+ "musl"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -5898,6 +5928,9 @@
"s390x"
],
"dev": true,
+ "libc": [
+ "glibc"
+ ],
"license": "MIT",
"optional": true,
"os": [
@@ -12856,9 +12889,9 @@
}
},
"node_modules/incyclist-devices": {
- "version": "3.0.45",
- "resolved": "https://registry.npmjs.org/incyclist-devices/-/incyclist-devices-3.0.45.tgz",
- "integrity": "sha512-F4i4Ntpcd7zJkcvQho1y/xpPsgTBZ0pcU7lxKCHp6f2I/PES3Qq8XMNIdOu5i9kuUxxaNyDbIJFBXVWtrc2eqQ==",
+ "version": "3.0.46",
+ "resolved": "https://registry.npmjs.org/incyclist-devices/-/incyclist-devices-3.0.46.tgz",
+ "integrity": "sha512-dtaXjm3LfcJaHG6/Bg7jhTWAtN8LKsXJtSifTQqTyFkn2XyGm+rQKOLUAsN795hIp0YDN/JR56of6t1wAi7Tbg==",
"dependencies": {
"@protobuf-ts/runtime": "^2.11.1",
"@serialport/bindings-interface": "^1.2.2",
@@ -12874,13 +12907,13 @@
}
},
"node_modules/incyclist-services": {
- "version": "1.9.21",
- "resolved": "https://registry.npmjs.org/incyclist-services/-/incyclist-services-1.9.21.tgz",
- "integrity": "sha512-kWj0Xfa2nA/E15uRy1i6X1CrAat2AYsqsTsYVowyy/CPDzvu5Xzgcu8n63yIiyQ4WP0e7X4GfaYqQiUC0mUXlw==",
+ "version": "1.9.22",
+ "resolved": "https://registry.npmjs.org/incyclist-services/-/incyclist-services-1.9.22.tgz",
+ "integrity": "sha512-YAndkOZyrTesh2cT7KkCncoauNSB8WttXoFEdSAO9mm3TxfSdeVHKQPCAlATIVkwAtgsj57lpt3EE7WtQb+MDA==",
"dependencies": {
"@garmin/fitsdk": "^21.221.0",
"axios": "^1.21.0",
- "incyclist-devices": "^3.0.45",
+ "incyclist-devices": "^3.0.46",
"promise.any": "^2.0.6",
"semver": "^7.7.4",
"tcx-builder": "^1.1.1",
diff --git a/package.json b/package.json
index 1b95cd67..ca90daa4 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,7 @@
"axios": "^1.17.0",
"events": "^3.3.0",
"gd-eventlog": "^0.1.27",
- "incyclist-services": "^1.9.21",
+ "incyclist-services": "^1.9.22",
"mqtt": "^5.15.2",
"path-browserify": "^1.0.1",
"process": "^0.11.10",
diff --git a/src/components/ButtonBar/ButtonBar.test.tsx b/src/components/ButtonBar/ButtonBar.test.tsx
index f619dff1..ce0c11c6 100644
--- a/src/components/ButtonBar/ButtonBar.test.tsx
+++ b/src/components/ButtonBar/ButtonBar.test.tsx
@@ -42,6 +42,17 @@ describe('Button', () => {
expect(touchable?.props.hitSlop.right).toBeLessThan(8);
});
+ // The compact button is about 34 high (14 text plus 8 padding above and below): with the
+ // vertical hitSlop, its touch target reaches the 48 dp minimum.
+ it('in compact layout, its touch target is at least 48 high', () => {
+ (useScreenLayout as jest.Mock).mockReturnValue('compact');
+
+ const { getByText } = render();
+ const { top, bottom } = getByText('OK').parent?.parent?.props.hitSlop;
+
+ expect(34 + top + bottom).toBeGreaterThanOrEqual(48);
+ });
+
it('still fires onClick when compact', () => {
(useScreenLayout as jest.Mock).mockReturnValue('compact');
const onClick = jest.fn();
diff --git a/src/components/ButtonBar/ButtonBar.tsx b/src/components/ButtonBar/ButtonBar.tsx
index e95a88e5..5a22862c 100644
--- a/src/components/ButtonBar/ButtonBar.tsx
+++ b/src/components/ButtonBar/ButtonBar.tsx
@@ -4,12 +4,13 @@ import { colors } from '../../theme'
import { ButtonBarProps, ButtonProps } from './types'
import { useLogging, useScreenLayout } from '../../hooks'
-// Compact mode's ~34px visible button is under the 44px touch-target guideline, but its small
+// Compact mode's ~34px visible button is under the 48dp touch-target guideline, but its small
// footprint is intentional (saves vertical space in landscape on phones as short as ~320px tall)
-// - expand the tappable region via hitSlop instead of growing the button. Horizontal slop must
-// stay under btnCompact's 8px marginHorizontal (styles.btn) so adjacent buttons' hit-slop
-// regions can't overlap and turn near-misses into taps on the wrong button.
-const COMPACT_HIT_SLOP = { top: 5, bottom: 5, left: 6, right: 6 }
+// - expand the tappable region via hitSlop instead of growing the button: 8 above and below takes
+// it to ~50. That stays inside the bar's 12px vertical margin. Horizontal slop must stay under
+// btnCompact's 8px marginHorizontal (styles.btn) so adjacent buttons' hit-slop regions can't
+// overlap and turn near-misses into taps on the wrong button.
+const COMPACT_HIT_SLOP = { top: 8, bottom: 8, left: 6, right: 6 }
export const Button = ({ id,label, primary,attention, disabled, onClick }:ButtonProps) => {
const {logEvent} = useLogging('Incyclist')
diff --git a/src/components/CapabilityStatusBars/CapabilityStatusBars.mock.ts b/src/components/CapabilityStatusBars/CapabilityStatusBars.mock.ts
index 60036c81..8cd5b0f6 100644
--- a/src/components/CapabilityStatusBars/CapabilityStatusBars.mock.ts
+++ b/src/components/CapabilityStatusBars/CapabilityStatusBars.mock.ts
@@ -94,6 +94,39 @@ export const MOCK_CAPABILITIES_TRAINER_UNAVAILABLE: Capabilities = {
rowLabels: { top: { text: 'TO RIDE', subtext: 'waiting for your trainer' }, bottom: OPTIONAL_LABEL },
}
+const dimmedTrainerIn = (title: string, capability: CapabilityDisplayProps['capability']): CapabilityDisplayProps => ({
+ ...trainerIn(title, capability, 'failed'),
+ trainerRole: 'via-trainer',
+ footerText: { full: 'Not used', short: 'Not used' },
+ dimmed: true,
+ awaited: false,
+})
+
+/**
+ * The trainer can't be reached and the rider chose to ride on a separate power meter: Resistance and
+ * the other tile still holding the trainer are dimmed, and a tap on Resistance takes the trainer back.
+ */
+export const MOCK_CAPABILITIES_FALLBACK: Capabilities = {
+ top: [
+ {
+ ...trainerIn('Resistance', 'control', 'failed'),
+ trainerRole: 'trainer',
+ roleLabel: 'Your trainer',
+ footerText: { full: 'Tap to use again', short: 'Tap to use again' },
+ dimmed: true,
+ awaited: false,
+ },
+ { title: 'Power', capability: 'power', deviceName: 'Stages Power', interface: 'ble', role: 'required', value: '154', unit: 'W', connectState: 'connected', awaited: false, onClick: noop, onUnselect: noop },
+ dimmedTrainerIn('Speed', 'speed'),
+ ],
+ bottom: [
+ OPTIONAL_ROW[0],
+ { ...dimmedTrainerIn('Cadence', 'cadence'), role: 'optional' },
+ OPTIONAL_ROW[2],
+ ],
+ rowLabels: { top: { text: '✓ READY TO RIDE' }, bottom: OPTIONAL_LABEL },
+}
+
/** Ready: a power meter connected, Resistance switched off with its trainer remembered. */
export const MOCK_CAPABILITIES_SWITCHED_OFF: Capabilities = {
top: [
diff --git a/src/components/CapabilityStatusBars/CapabilityStatusBars.stories.tsx b/src/components/CapabilityStatusBars/CapabilityStatusBars.stories.tsx
index c3147f0b..eba89e9f 100644
--- a/src/components/CapabilityStatusBars/CapabilityStatusBars.stories.tsx
+++ b/src/components/CapabilityStatusBars/CapabilityStatusBars.stories.tsx
@@ -4,7 +4,7 @@ import type { Meta, StoryObj } from '@storybook/react-native-web-vite';
import { CapabilityStatusBars } from './CapabilityStatusBars'
import { colors } from '../../theme'
import {
- MOCK_CAPABILITIES_HEARTRATE_ONLY, MOCK_CAPABILITIES_SEARCHING, MOCK_CAPABILITIES_SWITCHED_OFF,
+ MOCK_CAPABILITIES_FALLBACK, MOCK_CAPABILITIES_HEARTRATE_ONLY, MOCK_CAPABILITIES_SEARCHING, MOCK_CAPABILITIES_SWITCHED_OFF,
MOCK_CAPABILITIES_TRAINER_CONNECTING, MOCK_CAPABILITIES_TRAINER_UNAVAILABLE,
} from './CapabilityStatusBars.mock'
@@ -44,6 +44,10 @@ export const SwitchedOff: Story = {
args: { capabilities: MOCK_CAPABILITIES_SWITCHED_OFF },
}
+export const Fallback: Story = {
+ args: { capabilities: MOCK_CAPABILITIES_FALLBACK },
+}
+
// the space left beside the helper panel on a 667 x 375 phone
const styles = StyleSheet.create({
decorator: {
diff --git a/src/components/CapabilityStatusBars/CapabilityStatusBars.test.tsx b/src/components/CapabilityStatusBars/CapabilityStatusBars.test.tsx
index 2d43c96c..fc3d7607 100644
--- a/src/components/CapabilityStatusBars/CapabilityStatusBars.test.tsx
+++ b/src/components/CapabilityStatusBars/CapabilityStatusBars.test.tsx
@@ -1,7 +1,7 @@
import React from 'react'
import { render, fireEvent } from '@testing-library/react-native'
import { CapabilityStatusBars } from './CapabilityStatusBars'
-import { MOCK_CAPABILITIES_HEARTRATE_ONLY, MOCK_CAPABILITIES_TRAINER_UNAVAILABLE } from './CapabilityStatusBars.mock'
+import { MOCK_CAPABILITIES_FALLBACK, MOCK_CAPABILITIES_HEARTRATE_ONLY, MOCK_CAPABILITIES_TRAINER_UNAVAILABLE } from './CapabilityStatusBars.mock'
describe('CapabilityStatusBars', () => {
it('renders the required row as bars and the optional row as one line', () => {
@@ -34,6 +34,23 @@ describe('CapabilityStatusBars', () => {
expect(getAllByText('Tacx Flux · via your trainer · Via trainer')).toHaveLength(2)
})
+ it('while the ride falls back to another device, the dimmed bars show the copy as given', () => {
+ const { getByText } = render()
+ expect(getByText('Tacx Flux · Your trainer · Tap to use again')).toBeTruthy()
+ expect(getByText('154 W · Stages Power · CONNECTED')).toBeTruthy()
+ expect(getByText('Tacx Flux · Not used')).toBeTruthy()
+ // the dimmed Cadence tile isn't marked connected in the optional line
+ expect(getByText('OPTIONAL: HEARTRATE · CADENCE · CONTROLLER')).toBeTruthy()
+ })
+
+ it('a tap on a dimmed bar calls its onClick, as the tile does', () => {
+ const onClick = jest.fn()
+ const tiles = MOCK_CAPABILITIES_FALLBACK.top.map(t => (t.capability === 'control' ? { ...t, onClick } : t))
+ const { getByText } = render()
+ fireEvent.press(getByText('RESISTANCE'))
+ expect(onClick).toHaveBeenCalledTimes(1)
+ })
+
it('renders nothing without capabilities', () => {
const { toJSON } = render()
expect(toJSON()).toBeNull()
diff --git a/src/components/CapabilityStatusBars/utils.test.ts b/src/components/CapabilityStatusBars/utils.test.ts
index 0d0504c3..84398700 100644
--- a/src/components/CapabilityStatusBars/utils.test.ts
+++ b/src/components/CapabilityStatusBars/utils.test.ts
@@ -50,6 +50,27 @@ describe('getBarStateLine', () => {
})
expect(getBarStateLine(t)).toBe('Tacx Flux · via your trainer · Via trainer')
})
+
+ it('a dimmed Resistance tile: the trainer, its role and the footer copy as given, without a connect state', () => {
+ const t = tile({
+ title: 'Resistance', capability: 'control', deviceName: 'Tacx Flux', connectState: 'failed', dimmed: true,
+ trainerRole: 'trainer', roleLabel: 'Your trainer', footerText: { full: 'Tap to use again', short: 'Tap again' },
+ })
+ expect(getBarStateLine(t)).toBe('Tacx Flux · Your trainer · Tap again')
+ })
+
+ it('a dimmed tile the trainer still holds shows no value, even if one is reported', () => {
+ const t = tile({
+ deviceName: 'Tacx Flux', value: '120', unit: 'W', connectState: 'connected', dimmed: true,
+ trainerRole: 'via-trainer', footerText: { full: 'Not used', short: 'Not used' },
+ })
+ expect(getBarStateLine(t)).toBe('Tacx Flux · Not used')
+ })
+
+ it('a dimmed tile without footer copy falls back to its empty footer, never to the connect state', () => {
+ const t = tile({ deviceName: 'Tacx Flux', connectState: 'failed', dimmed: true, emptyFooter: 'Searching…' })
+ expect(getBarStateLine(t)).toBe('Tacx Flux · Searching…')
+ })
})
describe('getBarLook', () => {
@@ -61,6 +82,12 @@ describe('getBarLook', () => {
expect(getBarLook(tile({ deviceName: 'Tacx Flux', connectState: 'connecting' }))).toBe('idle')
})
+ it('a dimmed tile gets the same muted look as a switched-off one, even if its device reports connected', () => {
+ expect(getBarLook(tile({ deviceName: 'Tacx Flux', connectState: 'failed', dimmed: true }))).toBe('dimmed')
+ expect(getBarLook(tile({ deviceName: 'Tacx Flux', connectState: 'connected', dimmed: true }))).toBe('dimmed')
+ expect(getBarLook(tile({ deviceName: 'Tacx Flux', connectState: 'failed', dimmed: true, awaited: true }))).toBe('dimmed')
+ })
+
it('the amber outline follows whether the page waits for the tile', () => {
expect(getBarLook(tile({ deviceName: 'Tacx Flux', connectState: 'failed', awaited: true }))).toBe('waiting')
expect(getBarLook(tile({ deviceName: 'Tacx Flux', connectState: 'failed', awaited: false }))).toBe('idle')
@@ -85,4 +112,9 @@ describe('getOptionalSummary', () => {
const tiles = [tile({ title: 'Heartrate', capability: 'heartrate', deviceName: 'HRM', connectState: 'connected', disabled: true })]
expect(getOptionalSummary(tiles)).toEqual([{ title: 'Heartrate', connected: false }])
})
+
+ it('a dimmed tile is never marked connected', () => {
+ const tiles = [tile({ title: 'Cadence', capability: 'cadence', deviceName: 'Tacx Flux', connectState: 'connected', dimmed: true })]
+ expect(getOptionalSummary(tiles)).toEqual([{ title: 'Cadence', connected: false }])
+ })
})
diff --git a/src/components/CapabilityStatusBars/utils.ts b/src/components/CapabilityStatusBars/utils.ts
index 9100d5bd..bb10ae60 100644
--- a/src/components/CapabilityStatusBars/utils.ts
+++ b/src/components/CapabilityStatusBars/utils.ts
@@ -9,8 +9,15 @@ export interface OptionalSummaryItem {
export const isSwitchedOff = (tile: CapabilityDisplayProps): boolean => Boolean(tile.deviceName) && Boolean(tile.disabled)
+/**
+ * A device is there but deliberately not used right now (the ride falls back to another device while
+ * the trainer isn't available). It looks like a switched-off tile, but it isn't switched off: it has
+ * no switch, and a tap does whatever the page service set as the tile's `onClick`.
+ */
+export const isDimmed = (tile: CapabilityDisplayProps): boolean => Boolean(tile.deviceName) && Boolean(tile.dimmed)
+
export const isConnected =(tile: CapabilityDisplayProps): boolean =>
- Boolean(tile.deviceName) && !tile.disabled && tile.connectState === 'connected'
+ Boolean(tile.deviceName) && !tile.disabled && !tile.dimmed && tile.connectState === 'connected'
/**
* The one state line of a status bar, from the same props the tile shows: the value, the device (or
@@ -23,6 +30,10 @@ export const getBarStateLine = (tile: CapabilityDisplayProps): string => {
if (isSwitchedOff(tile))
return [tile.deviceName, footer ?? tile.emptyFooter ?? 'Not used'].join(' · ')
+ // no value and no connect state: the device isn't used, the footer copy says what a tap does
+ if (isDimmed(tile))
+ return [tile.deviceName, tile.roleLabel, footer ?? tile.emptyFooter].filter(Boolean).join(' · ')
+
if (!tile.deviceName)
return [tile.helpText?.short, footer ?? tile.emptyFooter].filter(Boolean).join(' · ')
@@ -32,11 +43,12 @@ export const getBarStateLine = (tile: CapabilityDisplayProps): string => {
}
/**
- * The bar's look, in the tile colour language: green when connected, dimmed when switched off, the
- * amber outline while the page waits for it, grey otherwise.
+ * The bar's look, in the tile colour language: green when connected, dimmed when switched off or not
+ * used while the ride falls back to another device, the amber outline while the page waits for it,
+ * grey otherwise.
*/
export const getBarLook = (tile: CapabilityDisplayProps): BarLook => {
- if (isSwitchedOff(tile))
+ if (isSwitchedOff(tile) || isDimmed(tile))
return 'dimmed'
if (isConnected(tile))
return 'connected'
diff --git a/src/components/CapabilityTile/CapabilityTile.stories.tsx b/src/components/CapabilityTile/CapabilityTile.stories.tsx
index b3f0c856..7856c942 100644
--- a/src/components/CapabilityTile/CapabilityTile.stories.tsx
+++ b/src/components/CapabilityTile/CapabilityTile.stories.tsx
@@ -96,6 +96,43 @@ export const PhoneWithToggle: Story= {
}
};
+// The ride falls back to a separate power meter while the trainer isn't available: the Resistance
+// tile is dimmed, without a switch, and a tap takes the trainer back into use
+export const DimmedResistance: Story= {
+ args: {
+ height:160,
+ title:'resistance',
+ capability:'control',
+ deviceName:'Tacx Flux',
+ interface:'ble',
+ connectState:'failed',
+ trainerRole:'trainer',
+ roleLabel:'Your trainer',
+ footerText:{ full:'Tap to use again', short:'Tap to use again' },
+ dimmed:true,
+ awaited:false,
+ onClick:fn()
+ }
+};
+
+// Another tile the trainer still holds while the ride falls back to another device
+export const DimmedViaTrainerPhone: Story= {
+ args: {
+ height:90,
+ title:'speed',
+ capability:'speed',
+ deviceName:'Tacx Flux',
+ interface:'ble',
+ connectState:'failed',
+ trainerRole:'via-trainer',
+ footerText:{ full:'Not used', short:'Not used' },
+ dimmed:true,
+ awaited:false,
+ variant:'short',
+ onClick:fn()
+ }
+};
+
export const UndefinedUnits: Story= {
args: {
height:160,
diff --git a/src/components/CapabilityTile/CapabilityTile.test.tsx b/src/components/CapabilityTile/CapabilityTile.test.tsx
index ee0bc691..b1c1ecdc 100644
--- a/src/components/CapabilityTile/CapabilityTile.test.tsx
+++ b/src/components/CapabilityTile/CapabilityTile.test.tsx
@@ -215,6 +215,109 @@ describe('CapabilityTile T16 (switched off, device remembered)', () => {
});
});
+describe('CapabilityTile dimmed (the ride falls back to another device)', () => {
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ // the shape the page service sends for a dimmed tile: a device, not disabled, no switch handlers
+ const buildDimmedTile = (props: Partial = {}) => buildTile({
+ title: 'Resistance', capability: 'control', deviceName: 'Tacx Flux', connectState: 'failed',
+ value: undefined, unit: undefined, onUnselect: undefined, onUse: undefined,
+ dimmed: true, trainerRole: 'trainer', roleLabel: 'Your trainer',
+ footerText: { full: 'Tap to use again', short: 'Tap again' },
+ ...props,
+ });
+
+ const fillOf = (root: ReturnType['UNSAFE_root']) =>
+ StyleSheet.flatten(root.findByType(TouchableOpacity).props.style).backgroundColor;
+
+ it('shows the device, its role and the footer copy as given, with no value and no connect state', () => {
+ const { getByText, queryByText } = render();
+
+ expect(getByText('Tacx Flux')).toBeTruthy();
+ expect(getByText('Your trainer')).toBeTruthy();
+ expect(getByText('Tap to use again')).toBeTruthy();
+ expect(queryByText('120')).toBeNull();
+ expect(queryByText('FAILED')).toBeNull();
+ });
+
+ it('uses the phone footer copy on a phone', () => {
+ const { getByText, queryByText } = render();
+
+ expect(getByText('Tap again')).toBeTruthy();
+ expect(queryByText('Tap to use again')).toBeNull();
+ });
+
+ it('has no on/off switch', () => {
+ const { queryByLabelText } = render();
+
+ expect(queryByLabelText('Use Resistance')).toBeNull();
+ });
+
+ it('gets the muted fill of a switched-off tile, even if its device reports connected', () => {
+ const { UNSAFE_root } = render();
+
+ expect(fillOf(UNSAFE_root)).toBe(colors.tileEmpty);
+ });
+
+ it('a tap on the tile calls its onClick, once, with the tile', () => {
+ const tile = buildDimmedTile();
+ const { getByText } = render();
+
+ fireEvent.press(getByText('Tacx Flux'));
+
+ expect(tile.onClick).toHaveBeenCalledTimes(1);
+ expect(tile.onClick).toHaveBeenCalledWith(expect.objectContaining({ capability: 'control', dimmed: true }));
+ });
+
+ it('another tile the trainer still holds is dimmed the same way', () => {
+ const { getByText, queryByText, queryByLabelText, UNSAFE_root } = render();
+
+ expect(getByText('Not used')).toBeTruthy();
+ expect(queryByText('0')).toBeNull();
+ expect(queryByLabelText('Use Power')).toBeNull();
+ expect(fillOf(UNSAFE_root)).toBe(colors.tileEmpty);
+ });
+});
+
+describe('CapabilityTile Resistance switch while the trainer connects or cannot be reached', () => {
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ const buildTrainerTile = (connectState: CapabilityDisplayProps['connectState']) => buildTile({
+ title: 'Resistance', capability: 'control', deviceName: 'Tacx Flux', value: undefined, unit: undefined,
+ connectState, trainerRole: 'trainer', roleLabel: 'Your trainer', awaited: true,
+ footerText: { full: 'Not connected · waiting', short: 'Waiting…' },
+ });
+
+ it.each(['connecting', 'failed'])('switching it off (%s) calls onUnselect exactly once, and nothing else', (connectState) => {
+ const tile = buildTrainerTile(connectState as CapabilityDisplayProps['connectState']);
+ const { getByLabelText } = render();
+
+ fireEvent.press(getByLabelText('Use Resistance'));
+
+ expect(tile.onUnselect).toHaveBeenCalledTimes(1);
+ expect(tile.onUnselect).toHaveBeenCalledWith();
+ expect(tile.onClick).not.toHaveBeenCalled();
+ });
+
+ it('the switch stays as the page service draws it: still on after the tap, until the next props arrive', () => {
+ const tile = buildTrainerTile('connecting');
+ const { getByLabelText } = render();
+
+ fireEvent.press(getByLabelText('Use Resistance'));
+
+ expect(getByLabelText('Use Resistance').props.accessibilityState).toEqual({ checked: true });
+ });
+});
+
describe('CapabilityTile waiting outline', () => {
const borderColorOf = (root: ReturnType['UNSAFE_root']) =>
diff --git a/src/components/CapabilityTile/CapabilityTile.tsx b/src/components/CapabilityTile/CapabilityTile.tsx
index 17b1979f..b8530241 100644
--- a/src/components/CapabilityTile/CapabilityTile.tsx
+++ b/src/components/CapabilityTile/CapabilityTile.tsx
@@ -47,8 +47,9 @@ export const CapabilityTile = ( props:PropsWithChildren) =>
const hasDevice = Boolean(props.deviceName)
const switchedOff = isSwitchedOff(props)
// only a connected device gets the in-use colour - the same rule as the status bars, so the grid
- // and the bars always agree. A device that is still connecting or can't be reached, and a
- // switched-off tile (T16), use the same muted look as an empty tile.
+ // and the bars always agree. A device that is still connecting or can't be reached, a
+ // switched-off tile, and a dimmed tile (not used while the ride falls back to another
+ // device) use the same muted look as an empty tile.
const backgroundColor = isConnected(props) ? colors.tileActive : colors.tileEmpty
// the page service decides which tiles the page waits for; the tile only renders the outline
const waitingBorder = props.awaited ? { borderWidth: 3, borderColor: colors.pairingWaiting } : undefined
@@ -252,6 +253,7 @@ const CapabilityTileView = React.memo ( (props: ComponentProps) => {
stateText,
value,
disabled,
+ dimmed,
unit,
interface:ifName,
size,
@@ -303,7 +305,7 @@ const CapabilityTileView = React.memo ( (props: ComponentProps) => {
return capabilityIconSize === undefined ? undefined : { width: capabilityIconSize, height: capabilityIconSize }
}
- if ( deviceName && !disabled) {
+ if ( deviceName && !disabled && !dimmed) {
const activeFooter = getActiveFooter(footer, stateText, connectState)
// a connected tile keeps its value column even before the first value arrives, so the icon
// doesn't jump; any other tile has no value, and its icon has the row to itself, centred
@@ -360,9 +362,11 @@ const CapabilityTileView = React.memo ( (props: ComponentProps) => {
)
}
- // T16: switched off, but a device is remembered - shown dimmed (muted tile colour, set by the
- // parent), with the device name and no value, and the toggle to turn it straight back on
- if ( deviceName && disabled) {
+ // switched off, but a device is remembered - shown dimmed (muted tile colour, set by the
+ // parent), with the device name and no value, and the toggle to turn it straight back on.
+ // A dimmed tile (not used while the ride falls back to another device) looks the same; the page
+ // service sends it without switch handlers, so it gets no toggle, and its footer copy as given.
+ if ( deviceName && (disabled || dimmed)) {
return (
{
+ const { logEvent } = useLogging('ConflictStepRows')
+
+ const onPress = useCallback(() => {
+ logEvent({ message: 'button clicked', button: 'conflict choice', capability, choice, eventSource: 'user' })
+ onChoice(capability, choice)
+ }, [logEvent, onChoice, capability, choice])
+
+ return (
+
+
+ {selected && }
+
+ {label}
+
+ )
+}
+
+const styles = StyleSheet.create({
+ option: {
+ minHeight: MIN_ROW_HEIGHT,
+ flexDirection: 'row',
+ alignItems: 'center',
+ paddingHorizontal: 10,
+ paddingVertical: 6,
+ marginBottom: 6,
+ borderRadius: 6,
+ borderWidth: 1,
+ borderColor: colors.disabled,
+ },
+ // on one line with the other choice: the row's own spacing separates it from the next row
+ optionFill: {
+ flex: 1,
+ flexBasis: 0,
+ marginBottom: 0,
+ },
+ optionSelected: {
+ borderColor: colors.pairingWaiting,
+ },
+ radio: {
+ width: 16,
+ height: 16,
+ borderRadius: 8,
+ borderWidth: 2,
+ borderColor: colors.text,
+ alignItems: 'center',
+ justifyContent: 'center',
+ marginRight: 10,
+ },
+ radioSelected: {
+ borderColor: colors.pairingWaiting,
+ },
+ radioDot: {
+ width: 8,
+ height: 8,
+ borderRadius: 4,
+ backgroundColor: colors.pairingWaiting,
+ },
+ label: {
+ flex: 1,
+ color: colors.text,
+ fontSize: textSizes.subtitle,
+ },
+})
diff --git a/src/components/ConflictStepRows/ConflictStepBody.test.tsx b/src/components/ConflictStepRows/ConflictStepBody.test.tsx
new file mode 100644
index 00000000..37cf5e7b
--- /dev/null
+++ b/src/components/ConflictStepRows/ConflictStepBody.test.tsx
@@ -0,0 +1,121 @@
+import React from 'react'
+import { act, render, fireEvent } from '@testing-library/react-native'
+import { ScrollView, StyleProp, StyleSheet, ViewStyle } from 'react-native'
+import { ConflictStepBody } from './ConflictStepBody'
+import { buildManualConflict, buildQueuedDetectionConflict } from './ConflictStepRows.mock'
+
+jest.mock('../../hooks', () => ({
+ useLogging: () => ({ logEvent: jest.fn() }),
+}))
+
+const mockDimensions = { width: 800, height: 360 }
+jest.mock('react-native/Libraries/Utilities/useWindowDimensions', () => ({
+ default: jest.fn(() => mockDimensions),
+}))
+
+const setDimensions = (width: number, height: number) => {
+ mockDimensions.width = width
+ mockDimensions.height = height
+}
+
+const directionOf = (node: { props: { style?: StyleProp } }) => StyleSheet.flatten(node.props.style)?.flexDirection
+
+const resize = (scroll: ReturnType['UNSAFE_root'], viewHeight: number, contentHeight: number) => {
+ const view = scroll.findByType(ScrollView)
+ act(() => {
+ fireEvent(view, 'layout', { nativeEvent: { layout: { x: 0, y: 0, width: 400, height: viewHeight } } })
+ fireEvent(view, 'contentSizeChange', 400, contentHeight)
+ })
+}
+const scrollTo = (root: ReturnType['UNSAFE_root'], y: number) => {
+ act(() => {
+ fireEvent.scroll(root.findByType(ScrollView), { nativeEvent: { contentOffset: { x: 0, y } } })
+ })
+}
+
+describe('ConflictStepBody', () => {
+ beforeEach(() => {
+ setDimensions(800, 360)
+ })
+
+ it('shows the subline and the rows, the short subline when compact', () => {
+ const step = { ...buildManualConflict(), subline: { full: 'The full line', short: 'The short line' } }
+ const { getByText, queryByText } = render()
+
+ expect(getByText('The short line')).toBeTruthy()
+ expect(queryByText('The full line')).toBeNull()
+ expect(getByText('Keep Wahoo Speed')).toBeTruthy()
+ })
+
+ it('leaves the count of waiting conflicts to the dialog\'s footer', () => {
+ const step = buildQueuedDetectionConflict()
+ const { queryByText } = render()
+
+ expect(queryByText('2 more')).toBeNull()
+ expect(queryByText(/to check/)).toBeNull()
+ })
+
+ it('scrolls the rows itself, in one ScrollView', () => {
+ const step = buildManualConflict()
+ const { UNSAFE_root } = render()
+
+ expect(UNSAFE_root.findAllByType(ScrollView)).toHaveLength(1)
+ })
+
+ it('on a phone, puts each row on one line: the slot\'s name on the left, then Keep and Use', () => {
+ const step = buildManualConflict()
+ const { getByTestId } = render()
+
+ expect(directionOf(getByTestId('conflict-row-power'))).toBe('row')
+ expect(directionOf(getByTestId('conflict-choices-power'))).toBe('row')
+ })
+
+ it('on a tablet in landscape, puts Keep and Use side by side under the slot\'s name', () => {
+ setDimensions(1280, 800)
+ const step = buildManualConflict()
+ const { getByTestId } = render()
+
+ expect(directionOf(getByTestId('conflict-row-power'))).not.toBe('row')
+ expect(directionOf(getByTestId('conflict-choices-power'))).toBe('row')
+ })
+
+ it('in portrait, stacks them', () => {
+ setDimensions(800, 1280)
+ const step = buildManualConflict()
+ const { getByTestId } = render()
+
+ expect(directionOf(getByTestId('conflict-choices-power'))).not.toBe('row')
+ })
+})
+
+describe('ConflictStepBody "more below" hint', () => {
+ it('shows while rows are hidden below, and goes once the rider scrolled to the end', () => {
+ const step = buildManualConflict()
+ const { UNSAFE_root, queryByTestId } = render()
+
+ resize(UNSAFE_root, 150, 230)
+ expect(queryByTestId('conflict-more-below')).toBeTruthy()
+
+ scrollTo(UNSAFE_root, 80)
+ expect(queryByTestId('conflict-more-below')).toBeNull()
+
+ scrollTo(UNSAFE_root, 10)
+ expect(queryByTestId('conflict-more-below')).toBeTruthy()
+ })
+
+ it('is not shown when every row fits', () => {
+ const step = buildManualConflict()
+ const { UNSAFE_root, queryByTestId } = render()
+
+ resize(UNSAFE_root, 300, 230)
+ expect(queryByTestId('conflict-more-below')).toBeNull()
+ })
+
+ it('never takes the taps meant for the row under it', () => {
+ const step = buildManualConflict()
+ const { UNSAFE_root, getByTestId } = render()
+
+ resize(UNSAFE_root, 150, 230)
+ expect(StyleSheet.flatten(getByTestId('conflict-more-below').props.style).pointerEvents).toBe('none')
+ })
+})
diff --git a/src/components/ConflictStepRows/ConflictStepBody.tsx b/src/components/ConflictStepRows/ConflictStepBody.tsx
new file mode 100644
index 00000000..bb7150f0
--- /dev/null
+++ b/src/components/ConflictStepRows/ConflictStepBody.tsx
@@ -0,0 +1,110 @@
+import React, { useCallback, useRef, useState } from 'react'
+import {
+ View, Text, ScrollView, StyleSheet, useWindowDimensions,
+ LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent,
+} from 'react-native'
+
+import { colors, textSizes } from '../../theme'
+import { ConflictStepRows } from './ConflictStepRows'
+import { ConflictRowsLayout, ConflictStepBodyProps } from './types'
+import { hasMoreBelow, ScrollSizes } from './utils'
+
+const MORE_BELOW = 'More below ▾'
+
+/**
+ * The body of a conflict dialog, under its title: the subline, and the rows in a scroll view of
+ * their own, so the subline stays in view. While rows are hidden below, a hint at the bottom says
+ * so. A phone's rows use the label-column layout; a tablet falls back to side-by-side (landscape)
+ * or stacked (portrait). Both the device list's second step and the dialog for a device found by
+ * the search show it, so the two look and read the same; the dialog using it must not scroll its
+ * own content (`scrollable={false}`).
+ */
+export const ConflictStepBody = ({ step, compact, onChoice }: ConflictStepBodyProps) => {
+ const { width, height } = useWindowDimensions()
+ // a phone's rows always use the label column - it's the layout the scroll-drag area needs,
+ // regardless of orientation; a tablet falls back to the existing side-by-side/stacked choice
+ const tabletLayout: ConflictRowsLayout = width > height ? 'side-by-side' : 'stacked'
+ const layout: ConflictRowsLayout = compact ? 'label-column' : tabletLayout
+
+ const refSizes = useRef({ viewHeight: 0, contentHeight: 0, offset: 0 })
+ const [moreBelow, setMoreBelow] = useState(false)
+
+ const update = useCallback((changed: Partial) => {
+ refSizes.current = { ...refSizes.current, ...changed }
+ setMoreBelow(hasMoreBelow(refSizes.current))
+ }, [])
+
+ const onLayout = useCallback((e: LayoutChangeEvent) => {
+ update({ viewHeight: e.nativeEvent.layout.height })
+ }, [update])
+
+ const onContentSizeChange = useCallback((_width: number, contentHeight: number) => {
+ update({ contentHeight })
+ }, [update])
+
+ const onScroll = useCallback((e: NativeSyntheticEvent) => {
+ update({ offset: e.nativeEvent.contentOffset.y })
+ }, [update])
+
+ return (
+
+ {compact ? step.subline.short : step.subline.full}
+
+
+
+
+ {moreBelow ? (
+
+ {MORE_BELOW}
+
+ ) : null}
+
+
+ )
+}
+
+const styles = StyleSheet.create({
+ body: {
+ flex: 1,
+ paddingHorizontal: 8,
+ paddingTop: 4,
+ },
+ subline: {
+ color: colors.text,
+ fontSize: textSizes.smallText,
+ marginBottom: 8,
+ },
+ rowsArea: {
+ flex: 1,
+ minHeight: 0,
+ },
+ rows: {
+ flex: 1,
+ },
+ moreBelow: {
+ position: 'absolute',
+ left: 0,
+ right: 0,
+ bottom: 0,
+ alignItems: 'center',
+ paddingVertical: 3,
+ backgroundColor: colors.dialogBackground.at(-1),
+ borderTopWidth: StyleSheet.hairlineWidth,
+ borderTopColor: colors.buttonPrimary,
+ // a hint only: taps go to the row under it
+ pointerEvents: 'none',
+ },
+ moreBelowText: {
+ color: colors.buttonPrimary,
+ fontSize: textSizes.smallText,
+ fontWeight: '700',
+ },
+})
diff --git a/src/components/ConflictStepRows/ConflictStepRows.mock.ts b/src/components/ConflictStepRows/ConflictStepRows.mock.ts
new file mode 100644
index 00000000..a6ecf164
--- /dev/null
+++ b/src/components/ConflictStepRows/ConflictStepRows.mock.ts
@@ -0,0 +1,92 @@
+import type { ConflictChoice, ConflictStepProps, ConflictStepRowProps, TIncyclistCapability } from 'incyclist-services'
+
+// Fixtures with the page service's copy, for tests and stories. Callbacks default to no-ops; pass
+// spies (jest.fn() in tests, fn() in stories) to observe them.
+
+type Noop = () => void
+const noop: Noop = () => {}
+
+export interface MockConflictHandlers {
+ onChoice?: (capability: TIncyclistCapability, choice: ConflictChoice) => void
+ onDone?: Noop
+ onDismiss?: Noop
+}
+
+const NEW_DEVICE = 'Tacx Neo 2T'
+
+// the page service's copy for two conflicts waiting
+const QUEUED_TWO = { full: '2 more devices to check', short: '2 more to check' }
+
+const row = (capability: TIncyclistCapability, capabilityTitle: string, currentName: string, choice: ConflictChoice = 'keep'): ConflictStepRowProps => ({
+ capability,
+ capabilityTitle,
+ currentName,
+ choice,
+ keepLabel: `Keep ${currentName}`,
+ replaceLabel: `Use ${NEW_DEVICE}`,
+})
+
+/** A trainer found by the search wants Power and Cadence, which other devices already hold. */
+export const buildDetectionConflict = (h: MockConflictHandlers = {}, choices: Partial> = {}): ConflictStepProps => ({
+ id: 'conflict-1',
+ origin: 'detection',
+ deviceName: NEW_DEVICE,
+ title: `${NEW_DEVICE} can also measure more`,
+ subline: {
+ full: `We just found your ${NEW_DEVICE}. Nothing changes until you choose. Resistance was free and now uses ${NEW_DEVICE}.`,
+ short: `Just found ${NEW_DEVICE}. Nothing changes until you choose.`,
+ },
+ rows: [
+ row('power', 'Power', 'Stages Power', choices.power),
+ row('cadence', 'Cadence', 'Wahoo RPM', choices.cadence),
+ ],
+ queued: 0,
+ onChoice: h.onChoice ?? noop,
+ onDone: h.onDone ?? noop,
+ onDismiss: h.onDismiss ?? noop,
+})
+
+/** A power meter found by the search wants Cadence only, which another device already holds. */
+export const buildSingleRowDetectionConflict = (h: MockConflictHandlers = {}): ConflictStepProps => {
+ const conflict = buildDetectionConflict(h)
+ return { ...conflict, rows: conflict.rows.filter(r => r.capability === 'cadence') }
+}
+
+/** A trainer found by the search wants Power, Speed and Cadence, all held by other devices, with two more conflicts waiting. */
+export const buildThreeRowDetectionConflict = (h: MockConflictHandlers = {}): ConflictStepProps => {
+ const conflict = buildDetectionConflict(h)
+ return {
+ ...conflict,
+ rows: [conflict.rows[0], row('speed', 'Speed', 'Wahoo Speed'), conflict.rows[1]],
+ queued: 2,
+ queuedText: QUEUED_TWO,
+ }
+}
+
+/** The same conflict, with two more waiting behind it. */
+export const buildQueuedDetectionConflict = (h: MockConflictHandlers = {}): ConflictStepProps => ({
+ ...buildDetectionConflict(h),
+ queued: 2,
+ queuedText: QUEUED_TWO,
+})
+
+/** The rider picked a trainer in the Resistance list, and it would take Power, Speed and Cadence from other devices. */
+export const buildManualConflict = (h: MockConflictHandlers = {}, choices: Partial> = {}): ConflictStepProps => ({
+ id: 'conflict-2',
+ origin: 'manual',
+ deviceName: NEW_DEVICE,
+ title: `${NEW_DEVICE} can also measure more`,
+ subline: {
+ full: 'Choose which device to use for each.',
+ short: 'Choose which device to use for each.',
+ },
+ rows: [
+ row('power', 'Power', 'Stages Power', choices.power),
+ row('speed', 'Speed', 'Wahoo Speed', choices.speed),
+ row('cadence', 'Cadence', 'Wahoo RPM', choices.cadence),
+ ],
+ queued: 0,
+ onChoice: h.onChoice ?? noop,
+ onDone: h.onDone ?? noop,
+ onDismiss: h.onDismiss ?? noop,
+})
diff --git a/src/components/ConflictStepRows/ConflictStepRows.stories.tsx b/src/components/ConflictStepRows/ConflictStepRows.stories.tsx
new file mode 100644
index 00000000..b943be1a
--- /dev/null
+++ b/src/components/ConflictStepRows/ConflictStepRows.stories.tsx
@@ -0,0 +1,54 @@
+import React from 'react'
+import { View, StyleSheet } from 'react-native'
+import type { Meta, StoryObj } from '@storybook/react-native-web-vite';
+import { fn } from 'storybook/test';
+import { ConflictStepRows } from './ConflictStepRows'
+import { colors } from '../../theme'
+import { buildDetectionConflict, buildManualConflict } from './ConflictStepRows.mock'
+
+const meta: Meta = {
+ title: 'Components/ConflictStepRows',
+ component: ConflictStepRows,
+ args: {
+ onChoice: fn(),
+ layout: 'side-by-side',
+ },
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+}
+
+export default meta
+
+type Story = StoryObj
+
+export const KeepEverything: Story = {
+ args: { rows: buildDetectionConflict().rows },
+}
+
+export const OneReplaced: Story = {
+ args: { rows: buildManualConflict({}, { speed: 'replace' }).rows },
+}
+
+// where the dialog is too narrow for the two choices on one line
+export const Stacked: Story = {
+ args: { rows: buildDetectionConflict().rows, layout: 'stacked' },
+}
+
+// a phone's layout: the capability's name in a column on the left, the choices to its right
+export const LabelColumn: Story = {
+ args: { rows: buildDetectionConflict().rows, layout: 'label-column' },
+}
+
+// about the width of the rows in the conflict dialog on a phone
+const styles = StyleSheet.create({
+ decorator: {
+ width: 440,
+ padding: 12,
+ backgroundColor: colors.helperPanelBackground,
+ },
+})
diff --git a/src/components/ConflictStepRows/ConflictStepRows.test.tsx b/src/components/ConflictStepRows/ConflictStepRows.test.tsx
new file mode 100644
index 00000000..9e607c8d
--- /dev/null
+++ b/src/components/ConflictStepRows/ConflictStepRows.test.tsx
@@ -0,0 +1,116 @@
+import React from 'react'
+import { StyleSheet } from 'react-native'
+import { render, fireEvent, within } from '@testing-library/react-native'
+import { ConflictStepRows } from './ConflictStepRows'
+import { buildDetectionConflict, buildManualConflict } from './ConflictStepRows.mock'
+
+const mockLogEvent = jest.fn()
+jest.mock('../../hooks', () => ({
+ useLogging: () => ({ logEvent: mockLogEvent }),
+}))
+
+describe('ConflictStepRows', () => {
+
+ afterEach(() => {
+ jest.clearAllMocks()
+ })
+
+ it('shows one row per slot, each with its title and both choices', () => {
+ const { rows, onChoice } = buildManualConflict()
+ const { getByText, getAllByText } = render()
+
+ expect(getByText('POWER')).toBeTruthy()
+ expect(getByText('SPEED')).toBeTruthy()
+ expect(getByText('CADENCE')).toBeTruthy()
+ expect(getByText('Keep Stages Power')).toBeTruthy()
+ expect(getByText('Keep Wahoo Speed')).toBeTruthy()
+ expect(getAllByText('Use Tacx Neo 2T')).toHaveLength(3)
+ })
+
+ it('marks the choice each row has, keep by default', () => {
+ const { rows, onChoice } = buildDetectionConflict({}, { cadence: 'replace' })
+ const { getByLabelText } = render()
+
+ expect(getByLabelText('Power: Keep Stages Power').props.accessibilityState).toEqual({ selected: true })
+ expect(getByLabelText('Power: Use Tacx Neo 2T').props.accessibilityState).toEqual({ selected: false })
+ expect(getByLabelText('Cadence: Keep Wahoo RPM').props.accessibilityState).toEqual({ selected: false })
+ expect(getByLabelText('Cadence: Use Tacx Neo 2T').props.accessibilityState).toEqual({ selected: true })
+ })
+
+ it('a tap on a choice reports the slot and the choice, and logs it', () => {
+ const onChoice = jest.fn()
+ const { rows } = buildDetectionConflict({ onChoice })
+ const { getByLabelText } = render()
+
+ fireEvent.press(getByLabelText('Cadence: Use Tacx Neo 2T'))
+ expect(onChoice).toHaveBeenCalledWith('cadence', 'replace')
+
+ fireEvent.press(getByLabelText('Power: Keep Stages Power'))
+ expect(onChoice).toHaveBeenCalledWith('power', 'keep')
+
+ expect(onChoice).toHaveBeenCalledTimes(2)
+ expect(mockLogEvent).toHaveBeenCalledWith(expect.objectContaining({ message: 'button clicked', button: 'conflict choice', capability: 'cadence', choice: 'replace' }))
+ })
+
+ it('side by side: each row\'s Keep and Use share one line, Keep first, under the row\'s title', () => {
+ const { rows, onChoice } = buildManualConflict()
+ const { getByTestId } = render()
+
+ rows.forEach(row => {
+ const choices = getByTestId(`conflict-choices-${row.capability}`)
+ expect(StyleSheet.flatten(choices.props.style).flexDirection).toBe('row')
+ const labels = within(choices).getAllByRole('radio').map(r => r.props.accessibilityLabel)
+ expect(labels).toEqual([`${row.capabilityTitle}: ${row.keepLabel}`, `${row.capabilityTitle}: ${row.replaceLabel}`])
+ expect(StyleSheet.flatten(getByTestId(`conflict-row-${row.capability}`).props.style)?.flexDirection).not.toBe('row')
+ })
+ })
+
+ it('stacked: Keep above Use', () => {
+ const { rows, onChoice } = buildManualConflict()
+ const { getByTestId } = render()
+
+ expect(StyleSheet.flatten(getByTestId('conflict-choices-power').props.style)?.flexDirection).not.toBe('row')
+ })
+
+ it('stacked unless told otherwise', () => {
+ const { rows, onChoice } = buildManualConflict()
+ const { getByTestId } = render()
+
+ expect(StyleSheet.flatten(getByTestId('conflict-choices-power').props.style)?.flexDirection).not.toBe('row')
+ })
+
+ it('label column: each row is one line - the slot\'s name on the left, then Keep and Use', () => {
+ const { rows, onChoice } = buildManualConflict()
+ const { getByTestId } = render()
+
+ rows.forEach(row => {
+ const line = getByTestId(`conflict-row-${row.capability}`)
+ expect(StyleSheet.flatten(line.props.style).flexDirection).toBe('row')
+
+ const texts = within(line).getAllByText(/./).map(t => t.props.children)
+ expect(texts).toEqual([row.capabilityTitle.toUpperCase(), row.keepLabel, row.replaceLabel])
+
+ const choices = getByTestId(`conflict-choices-${row.capability}`)
+ expect(StyleSheet.flatten(choices.props.style).flexDirection).toBe('row')
+ })
+ })
+
+ it('label column: the name may wrap, its column has a fixed width so every row lines up', () => {
+ const { rows, onChoice } = buildManualConflict()
+ const { getByText } = render()
+
+ const label = getByText('POWER')
+ expect(label.props.numberOfLines).toBeUndefined()
+ const widths = ['POWER', 'SPEED', 'CADENCE'].map(t => StyleSheet.flatten(getByText(t).props.style).width)
+ expect(new Set(widths).size).toBe(1)
+ expect(widths[0]).toEqual(expect.any(Number))
+ })
+
+ it('renders no buttons of its own beyond the two choices per row', () => {
+ const { rows, onChoice } = buildManualConflict()
+ const { getAllByRole, queryAllByRole } = render()
+
+ expect(getAllByRole('radio')).toHaveLength(rows.length * 2)
+ expect(queryAllByRole('button')).toHaveLength(0)
+ })
+})
diff --git a/src/components/ConflictStepRows/ConflictStepRows.tsx b/src/components/ConflictStepRows/ConflictStepRows.tsx
new file mode 100644
index 00000000..4d87210b
--- /dev/null
+++ b/src/components/ConflictStepRows/ConflictStepRows.tsx
@@ -0,0 +1,88 @@
+import React from 'react'
+import { View, Text, StyleSheet } from 'react-native'
+
+import { colors, textSizes } from '../../theme'
+import { ConflictChoiceOption } from './ConflictChoiceOption'
+import { ConflictRowsLayout, ConflictStepRowsProps } from './types'
+
+// wide enough for "HEARTRATE"; a longer name wraps to a second line
+const LABEL_WIDTH = 90
+
+const choicesStyleOf = (layout: ConflictRowsLayout) => {
+ if (layout === 'label-column')
+ return styles.choicesBesideLabel
+ if (layout === 'side-by-side')
+ return styles.choicesSideBySide
+ return styles.choicesStacked
+}
+
+/**
+ * The rows of a device-selection conflict: one per slot that already holds a different device, each
+ * with the slot's name and the two choices (keep the current device, or use the new one):
+ * - `label-column` (phone): one line per row, the name in a column on the left, then the two choices.
+ * The column holds no buttons, so every row has room to start a scroll from;
+ * - `side-by-side`: the name above, the two choices on one line under it;
+ * - `stacked`: the name above, the two choices under each other.
+ * The same rows show in the dialog for a device found by the search and in the Resistance list's second step.
+ */
+export const ConflictStepRows = ({ rows, onChoice, layout = 'stacked' }: ConflictStepRowsProps) => {
+ const labelColumn = layout === 'label-column'
+ const fill = layout !== 'stacked'
+ const choicesStyle = choicesStyleOf(layout)
+
+ return (
+
+ {rows.map(row => (
+
+ {row.capabilityTitle.toUpperCase()}
+
+
+
+
+
+ ))}
+
+ )
+}
+
+const styles = StyleSheet.create({
+ row: {
+ marginBottom: 8,
+ },
+ rowLine: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 8,
+ marginBottom: 8,
+ },
+ rowTitle: {
+ color: colors.text,
+ fontSize: textSizes.smallText,
+ fontWeight: '700',
+ marginBottom: 4,
+ },
+ label: {
+ width: LABEL_WIDTH,
+ color: colors.text,
+ fontSize: textSizes.smallText,
+ fontWeight: '700',
+ },
+ choicesStacked: {
+ flexDirection: 'column',
+ },
+ choicesSideBySide: {
+ flexDirection: 'row',
+ gap: 8,
+ },
+ choicesBesideLabel: {
+ flex: 1,
+ flexDirection: 'row',
+ gap: 8,
+ },
+})
diff --git a/src/components/ConflictStepRows/index.ts b/src/components/ConflictStepRows/index.ts
new file mode 100644
index 00000000..b6e22dbd
--- /dev/null
+++ b/src/components/ConflictStepRows/index.ts
@@ -0,0 +1,4 @@
+export * from './ConflictStepRows'
+export * from './ConflictStepBody'
+export * from './types'
+export * from './utils'
diff --git a/src/components/ConflictStepRows/types.ts b/src/components/ConflictStepRows/types.ts
new file mode 100644
index 00000000..cb2d8821
--- /dev/null
+++ b/src/components/ConflictStepRows/types.ts
@@ -0,0 +1,24 @@
+import type { ConflictStepProps, ConflictStepRowProps } from 'incyclist-services'
+
+/**
+ * How a conflict's rows are laid out: the slot's name in a column left of Keep and Use (phone),
+ * Keep and Use side by side under the name (tablet, landscape), or stacked under the name.
+ */
+export type ConflictRowsLayout = 'label-column' | 'side-by-side' | 'stacked'
+
+export interface ConflictStepRowsProps {
+ /** one row per slot, as the page service gives them */
+ rows: ReadonlyArray
+ onChoice: ConflictStepProps['onChoice']
+ /** `stacked` if not given */
+ layout?: ConflictRowsLayout
+}
+
+export interface ConflictStepBodyProps {
+ /** the conflict as the page service gives it */
+ step: ConflictStepProps
+ /** the phone's short subline instead of the full one */
+ compact: boolean
+ /** what a tap on a row's choice calls: the step's own `onChoice`, or a guarded wrapper of it */
+ onChoice: ConflictStepProps['onChoice']
+}
diff --git a/src/components/ConflictStepRows/utils.test.ts b/src/components/ConflictStepRows/utils.test.ts
new file mode 100644
index 00000000..36ba9cb2
--- /dev/null
+++ b/src/components/ConflictStepRows/utils.test.ts
@@ -0,0 +1,21 @@
+import { hasMoreBelow } from './utils'
+
+describe('hasMoreBelow', () => {
+ it('is false while the content fits', () => {
+ expect(hasMoreBelow({ viewHeight: 200, contentHeight: 180, offset: 0 })).toBe(false)
+ })
+
+ it('is true while some content is below the visible part', () => {
+ expect(hasMoreBelow({ viewHeight: 200, contentHeight: 260, offset: 0 })).toBe(true)
+ expect(hasMoreBelow({ viewHeight: 200, contentHeight: 260, offset: 40 })).toBe(true)
+ })
+
+ it('is false once scrolled to the end, allowing for rounding', () => {
+ expect(hasMoreBelow({ viewHeight: 200, contentHeight: 260, offset: 60 })).toBe(false)
+ expect(hasMoreBelow({ viewHeight: 200, contentHeight: 260, offset: 58.5 })).toBe(false)
+ })
+
+ it('is false before the sizes are known', () => {
+ expect(hasMoreBelow({ viewHeight: 0, contentHeight: 0, offset: 0 })).toBe(false)
+ })
+})
diff --git a/src/components/ConflictStepRows/utils.ts b/src/components/ConflictStepRows/utils.ts
new file mode 100644
index 00000000..918bfc10
--- /dev/null
+++ b/src/components/ConflictStepRows/utils.ts
@@ -0,0 +1,15 @@
+// how close to the end of the rows still counts as "at the end", for rounding in scroll offsets
+const END_TOLERANCE = 2
+
+export interface ScrollSizes {
+ /** the visible height of the scroll view */
+ viewHeight: number
+ /** the height of everything in it */
+ contentHeight: number
+ /** how far it is scrolled down */
+ offset: number
+}
+
+/** Whether some of the rows are hidden below the visible part of their scroll view. */
+export const hasMoreBelow = ({ viewHeight, contentHeight, offset }: ScrollSizes): boolean =>
+ viewHeight > 0 && contentHeight - (offset + viewHeight) > END_TOLERANCE
diff --git a/src/components/DeviceSelector/DeviceSelector.stories.tsx b/src/components/DeviceSelector/DeviceSelector.stories.tsx
index a7223878..a72447d8 100644
--- a/src/components/DeviceSelector/DeviceSelector.stories.tsx
+++ b/src/components/DeviceSelector/DeviceSelector.stories.tsx
@@ -4,6 +4,7 @@ import { View } from 'react-native';
import { DeviceSelector } from './DeviceSelector';
import { DeviceSelectionProps, TIncyclistCapability } from 'incyclist-services';
import { fn } from 'storybook/test';
+import { buildManualConflict } from '../ConflictStepRows/ConflictStepRows.mock';
export const defaultArgs: DeviceSelectionProps = {
capability: 'control' as TIncyclistCapability,
@@ -62,8 +63,7 @@ export const Disabled: Story = {
};
// Regression case for the scroll/overlap bug: with enough entries to overflow the list's
-// maxHeight, the last entries must remain reachable by scrolling and must not render hidden
-// underneath the "For all capabilities" / "Disable All" footer bar.
+// maxHeight, the last entries must remain reachable by scrolling.
export const LongList: Story = {
args: {
...Default.args,
@@ -76,4 +76,19 @@ export const LongList: Story = {
onDelete: () => {},
})),
},
+};
+
+// The second step after a pick in the Resistance list that would take slots held by other devices
+export const ConflictStep: Story = {
+ args: {
+ ...Default.args,
+ conflictStep: buildManualConflict({ onChoice: fn(), onDone: fn(), onDismiss: fn() }),
+ },
+};
+
+export const ConflictStepOneReplaced: Story = {
+ args: {
+ ...Default.args,
+ conflictStep: buildManualConflict({ onChoice: fn(), onDone: fn(), onDismiss: fn() }, { power: 'replace' }),
+ },
};
\ No newline at end of file
diff --git a/src/components/DeviceSelector/DeviceSelector.test.tsx b/src/components/DeviceSelector/DeviceSelector.test.tsx
index 47eda8af..77a694a6 100644
--- a/src/components/DeviceSelector/DeviceSelector.test.tsx
+++ b/src/components/DeviceSelector/DeviceSelector.test.tsx
@@ -1,8 +1,29 @@
import React from 'react';
-import { render } from '@testing-library/react-native';
-import { ScrollView } from 'react-native';
+import { render, fireEvent, within } from '@testing-library/react-native';
+import { Modal, ScrollView, StyleSheet } from 'react-native';
import { DeviceSelector } from './DeviceSelector';
import { DeviceSelectionItemProps, DeviceSelectionProps, TIncyclistCapability } from 'incyclist-services';
+import { buildManualConflict } from '../ConflictStepRows/ConflictStepRows.mock';
+
+const mockDimensions = { width: 800, height: 360 };
+jest.mock('react-native/Libraries/Utilities/useWindowDimensions', () => ({
+ default: jest.fn(() => mockDimensions),
+}));
+
+const setDimensions = (width: number, height: number) => {
+ mockDimensions.width = width;
+ mockDimensions.height = height;
+};
+const PHONE: [number, number] = [800, 360];
+const TABLET: [number, number] = [1280, 800];
+
+// the dialog's own surface, sized to the whole window with square corners
+const fillsScreen = (root: ReturnType['UNSAFE_root']) => root.findAll(node => {
+ if (typeof node.type !== 'string')
+ return false;
+ const style = StyleSheet.flatten(node.props.style);
+ return style?.width === '100%' && style?.height === '100%' && style?.borderRadius === 0;
+}).length > 0;
const buildDevice = (i: number): DeviceSelectionItemProps => ({
deviceName: `Device ${i}`,
@@ -13,7 +34,7 @@ const buildDevice = (i: number): DeviceSelectionItemProps => ({
onDelete: jest.fn(),
});
-const buildProps = (deviceCount: number): DeviceSelectionProps => ({
+const buildProps = (deviceCount: number, extra: Partial = {}): DeviceSelectionProps => ({
capability: 'control' as TIncyclistCapability,
devices: Array.from({ length: deviceCount }, (_, i) => buildDevice(i)),
isScanning: false,
@@ -21,9 +42,14 @@ const buildProps = (deviceCount: number): DeviceSelectionProps => ({
changeForAll: true,
canSelectAll: true,
onClose: jest.fn(),
+ ...extra,
});
describe('DeviceSelector', () => {
+ beforeEach(() => {
+ setDimensions(...PHONE);
+ });
+
it('renders without crashing for a short device list', () => {
const { getByText } = render();
expect(getByText('Device 0')).toBeTruthy();
@@ -38,23 +64,139 @@ describe('DeviceSelector', () => {
expect(getByText('Device 29')).toBeTruthy();
});
- it('gives the device list ScrollView bottom padding matching the footer height, so the last entries clear it', () => {
+ it('lists the devices in a single ScrollView of its own - Dialog\'s is disabled', () => {
const { UNSAFE_root } = render();
- const scrollViews = UNSAFE_root.findAllByType(ScrollView);
- expect(scrollViews.length).toBe(1); // only DeviceSelector's own list ScrollView - Dialog's is disabled
+ expect(UNSAFE_root.findAllByType(ScrollView).length).toBe(1);
+ });
- const contentContainerStyle = scrollViews[0].props.contentContainerStyle;
- const flatStyle = Array.isArray(contentContainerStyle)
- ? Object.assign({}, ...contentContainerStyle)
- : contentContainerStyle;
+ it('has no "For all capabilities" switch and no "Don\'t use" tick, even where the deprecated props still ask for one', () => {
+ const { queryByText, queryByRole } = render();
+ expect(queryByText(/for all/i)).toBeNull();
+ expect(queryByText(/Don't use/)).toBeNull();
+ expect(queryByRole('checkbox')).toBeNull();
+ expect(queryByRole('switch')).toBeNull();
+ });
+
+ it('a tap on a device picks it, without any "for all" argument', () => {
+ const props = buildProps(3, { canSelectAll: true, changeForAll: true });
+ const { getByText } = render();
+
+ fireEvent.press(getByText('Device 1'));
- expect(flatStyle.paddingBottom).toBeGreaterThanOrEqual(60);
+ expect(props.devices[1].onClick).toHaveBeenCalledTimes(1);
+ expect(props.devices[1].onClick).toHaveBeenCalledWith();
});
- it('renders "For all capabilities" and no "Don\'t use" tick, since unselecting is done from the tile', () => {
- const { getByText, queryByText } = render();
- expect(getByText('For all capabilities')).toBeTruthy();
- expect(queryByText(/Don't use/)).toBeNull();
+ it('a tap outside closes the list', () => {
+ const props = buildProps(3);
+ const { UNSAFE_root } = render();
+
+ UNSAFE_root.findByType(Modal).props.onRequestClose();
+
+ expect(props.onClose).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('DeviceSelector conflict step', () => {
+ beforeEach(() => {
+ setDimensions(...PHONE);
+ });
+
+ it('replaces the list with the step: title, rows and Done', () => {
+ const conflictStep = buildManualConflict();
+ const { getByText, queryByText, getAllByText } = render();
+
+ expect(getByText('Tacx Neo 2T can also measure more')).toBeTruthy();
+ expect(getByText('Keep Stages Power')).toBeTruthy();
+ expect(getByText('Keep Wahoo Speed')).toBeTruthy();
+ expect(getAllByText('Use Tacx Neo 2T')).toHaveLength(3);
+ expect(getByText('Done')).toBeTruthy();
+ expect(queryByText('Device 0')).toBeNull();
+ expect(queryByText('Select Device')).toBeNull();
+ });
+
+ it('shows the phone subline on a phone, the full one on a tablet', () => {
+ const conflictStep = { ...buildManualConflict(), subline: { full: 'The full line', short: 'The short line' } };
+
+ const phone = render();
+ expect(phone.getByText('The short line')).toBeTruthy();
+ expect(phone.queryByText('The full line')).toBeNull();
+
+ setDimensions(...TABLET);
+ const tablet = render();
+ expect(tablet.getByText('The full line')).toBeTruthy();
+ });
+
+ it('a choice is passed on as given', () => {
+ const onChoice = jest.fn();
+ const { getByLabelText } = render();
+
+ fireEvent.press(getByLabelText('Speed: Use Tacx Neo 2T'));
+
+ expect(onChoice).toHaveBeenCalledWith('speed', 'replace');
+ });
+
+ it('Done commits the choices', () => {
+ const onDone = jest.fn();
+ const onDismiss = jest.fn();
+ const props = buildProps(3, { conflictStep: buildManualConflict({ onDone, onDismiss }) });
+ const { getByText } = render();
+
+ fireEvent.press(getByText('Done'));
+
+ expect(onDone).toHaveBeenCalledTimes(1);
+ expect(onDismiss).not.toHaveBeenCalled();
+ expect(props.onClose).not.toHaveBeenCalled();
+ });
+
+ it('a tap outside or the back button applies the choices made so far, through the step', () => {
+ const onDone = jest.fn();
+ const onDismiss = jest.fn();
+ const props = buildProps(3, { conflictStep: buildManualConflict({ onDone, onDismiss }) });
+ const { UNSAFE_root } = render();
+
+ UNSAFE_root.findByType(Modal).props.onRequestClose();
+
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ expect(onDone).not.toHaveBeenCalled();
+ expect(props.onClose).not.toHaveBeenCalled();
+ });
+
+ it('on a phone, the step fills the screen; the list before it keeps its size', () => {
+ const list = render();
+ expect(fillsScreen(list.UNSAFE_root)).toBe(false);
+ list.unmount();
+
+ const step = render();
+ expect(fillsScreen(step.UNSAFE_root)).toBe(true);
+ });
+
+ it('on a tablet, the step keeps the list\'s size', () => {
+ setDimensions(...TABLET);
+ const { UNSAFE_root } = render();
+ expect(fillsScreen(UNSAFE_root)).toBe(false);
+ });
+
+ it('scrolls the rows in the step\'s own ScrollView, not the dialog\'s', () => {
+ const { UNSAFE_root } = render();
+
+ expect(UNSAFE_root.findAllByType(ScrollView).length).toBe(1);
+ });
+
+ it('says how many more wait in the footer, the same way as the dialog for a device found by the search', () => {
+ const conflictStep = { ...buildManualConflict(), queued: 1, queuedText: { full: 'The full queued line', short: 'The short queued line' } };
+ const { getByTestId, queryByText } = render();
+
+ expect(within(getByTestId('dialog-footer')).getByText('The short queued line')).toBeTruthy();
+ expect(queryByText('The full queued line')).toBeNull();
+ });
+
+ it('has Done as its only button', () => {
+ const { getAllByRole, getAllByText } = render();
+
+ // the dialog's buttons are plain touchables; Done is the only text that isn't a row or the copy
+ expect(getAllByText('Done')).toHaveLength(1);
+ expect(getAllByRole('radio')).toHaveLength(6);
});
});
diff --git a/src/components/DeviceSelector/DeviceSelector.tsx b/src/components/DeviceSelector/DeviceSelector.tsx
index e5a0b95c..094448bd 100644
--- a/src/components/DeviceSelector/DeviceSelector.tsx
+++ b/src/components/DeviceSelector/DeviceSelector.tsx
@@ -1,77 +1,89 @@
-import React, { FC, useState } from 'react';
+import React, { FC, useCallback, useMemo } from 'react';
import { View, StyleSheet, ScrollView, useWindowDimensions } from 'react-native';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
import DeviceEntry from '../DeviceEntry';
import { DeviceSelectionItemProps, DeviceSelectionProps } from 'incyclist-services';
import { textSizes } from '../../theme';
+import { useScreenLayout } from '../../hooks';
import { Dialog } from '../Dialog';
-import { BinarySelect } from '../BinarySelect';
+import { ButtonProps } from '../ButtonBar/types';
+import { ConflictStepBody } from '../ConflictStepRows';
+import { getConflictDialogStyle, getDeviceDialogWidth } from './utils';
+const DONE_LABEL = 'Done';
+
+/**
+ * The device list of one capability. After a pick in the Resistance list that would take slots held
+ * by a different device, the page service sends a conflict step: it replaces the list in the same
+ * dialog until Done, or a tap outside / the back button, which both apply the choices made so far.
+ * On a phone, the dialog fills the screen while it shows the step.
+ */
export const DeviceSelector: FC = ({
devices,
isScanning,
- changeForAll,
- canSelectAll,
+ conflictStep,
onClose,
}) => {
const { width: screenWidth, height: screenHeight } = useWindowDimensions();
+ const compact = useScreenLayout() === 'compact';
+ const insets = useSafeAreaInsets();
- const targetWidth = textSizes.listEntry * 0.6 * 40; // ~288dp
- const dialogWidth = Math.min(0.9 * screenWidth, targetWidth);
+ const dialogWidth = getDeviceDialogWidth(screenWidth);
const minHeightLeft = screenHeight - (textSizes.dialogTitle + 100 + 80 + 8);
const deviceListMinHeight = Math.min(380, minHeightLeft);
- const [all, setAll] = useState(canSelectAll && changeForAll);
-
const onDeviceClicked = (device: DeviceSelectionItemProps) => {
- if (device.onClick) {
- device.onClick(all);
- }
+ device.onClick?.();
};
- const onDialogClosed = () => {
- onClose();
- };
+ const onOutsideClick = useCallback(() => {
+ if (conflictStep)
+ conflictStep.onDismiss();
+ else
+ onClose();
+ }, [conflictStep, onClose]);
- const dialogStyle = [styles.dialog, { width: dialogWidth }];
+ const stepButtons = useMemo(() => conflictStep
+ ? [{ id: 'conflict-done', label: DONE_LABEL, primary: true, onClick: conflictStep.onDone }]
+ : undefined
+ , [conflictStep]);
+
+ const dialogStyle = [styles.dialog, conflictStep ? getConflictDialogStyle(screenWidth, compact, insets) : { width: dialogWidth }];
const deviceListStyle = [styles.deviceList, { minHeight: deviceListMinHeight }];
+ let title = isScanning ? 'Searching ...' : 'Select Device';
+ if (conflictStep)
+ title = conflictStep.title;
+
return (
);
};
-const FOOTER_HEIGHT = 60;
-
const styles = StyleSheet.create({
dialog: {
// Dynamic width applied via inline style
@@ -89,27 +101,4 @@ const styles = StyleSheet.create({
maxHeight: 380,
// Dynamic minHeight applied via inline style
},
- // Reserves space at the bottom of the scrollable content so the last device entries clear
- // the footer bar, which is absolutely positioned over the bottom of `modalView`.
- deviceListContent: {
- paddingBottom: FOOTER_HEIGHT,
- },
- footer: {
- flexDirection: 'row',
- height: FOOTER_HEIGHT,
- width: '100%',
- position: 'absolute',
- left: 0,
- bottom: 0,
- paddingHorizontal: 15,
- borderTopWidth: 1,
- borderTopColor: '#553388',
- alignItems: 'center',
- },
- checkboxContainer: {
- flex: 1,
- flexDirection: 'row',
- alignItems: 'center',
- marginRight: 4,
- },
-});
\ No newline at end of file
+});
diff --git a/src/components/DeviceSelector/utils.test.ts b/src/components/DeviceSelector/utils.test.ts
new file mode 100644
index 00000000..9f6e3cd5
--- /dev/null
+++ b/src/components/DeviceSelector/utils.test.ts
@@ -0,0 +1,30 @@
+import { getConflictDialogStyle, getDeviceDialogWidth } from './utils'
+
+describe('getDeviceDialogWidth', () => {
+ it('is about 480 wide, but never more than 90% of the window', () => {
+ expect(getDeviceDialogWidth(1280)).toBe(480)
+ expect(getDeviceDialogWidth(500)).toBe(450)
+ })
+})
+
+describe('getConflictDialogStyle', () => {
+ it('on a phone, the conflict step fills the screen, without rounded corners', () => {
+ expect(getConflictDialogStyle(667, true)).toEqual(expect.objectContaining({
+ width: '100%', height: '100%', maxHeight: '100%', borderRadius: 0,
+ }))
+ })
+
+ it('on a phone, keeps its content clear of a notch on either side, by the larger inset', () => {
+ expect(getConflictDialogStyle(667, true, { left: 0, right: 32 })).toEqual(expect.objectContaining({
+ paddingLeft: 32, paddingRight: 32,
+ }))
+ expect(getConflictDialogStyle(667, true)).toEqual(expect.objectContaining({
+ paddingLeft: 0, paddingRight: 0,
+ }))
+ })
+
+ it('on a tablet, keeps the device list\'s size', () => {
+ expect(getConflictDialogStyle(1024, false)).toEqual({ width: 480 })
+ expect(getConflictDialogStyle(1024, false, { left: 32, right: 0 })).toEqual({ width: 480 })
+ })
+})
diff --git a/src/components/DeviceSelector/utils.ts b/src/components/DeviceSelector/utils.ts
new file mode 100644
index 00000000..90fa3cf7
--- /dev/null
+++ b/src/components/DeviceSelector/utils.ts
@@ -0,0 +1,44 @@
+import type { ViewStyle } from 'react-native'
+import { textSizes } from '../../theme'
+
+// about 480: wide enough for a device name at list-entry size
+const TARGET_WIDTH = textSizes.listEntry * 0.6 * 40
+
+export interface SideInsets {
+ left: number
+ right: number
+}
+
+const NO_INSETS: SideInsets = { left: 0, right: 0 }
+
+/**
+ * The width of the device list's dialog, which the dialog for a device found by the search shares.
+ *
+ * @param screenWidth the window's width
+ */
+export const getDeviceDialogWidth = (screenWidth: number): number => Math.min(0.9 * screenWidth, TARGET_WIDTH)
+
+/**
+ * The size of a dialog asking about a conflict. On a phone it fills the screen: a phone in landscape
+ * is too short for more than two rows in the device list's box, and the full width lets each row's
+ * two choices sit on one line without wrapping. Its content keeps clear of a notch on either side.
+ * On a tablet it keeps the device list's size.
+ *
+ * @param screenWidth the window's width
+ * @param compact a phone's layout
+ * @param insets the safe-area insets left and right (the app is landscape-locked, so the notch is on a side)
+ */
+export const getConflictDialogStyle = (screenWidth: number, compact: boolean, insets: SideInsets = NO_INSETS): ViewStyle => {
+ if (!compact)
+ return { width: getDeviceDialogWidth(screenWidth) }
+
+ const sidePad = Math.max(insets.left, insets.right)
+ return {
+ width: '100%',
+ height: '100%',
+ maxHeight: '100%',
+ borderRadius: 0,
+ paddingLeft: sidePad,
+ paddingRight: sidePad,
+ }
+}
diff --git a/src/components/Dialog/Dialog.test.tsx b/src/components/Dialog/Dialog.test.tsx
index 6746ec07..c8603bdd 100644
--- a/src/components/Dialog/Dialog.test.tsx
+++ b/src/components/Dialog/Dialog.test.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { render } from '@testing-library/react-native';
+import { render, within } from '@testing-library/react-native';
import { Modal, ScrollView, StyleSheet, Text, View } from 'react-native';
import * as SafeAreaContext from 'react-native-safe-area-context';
import { EventLogger } from 'gd-eventlog';
@@ -31,6 +31,18 @@ describe('Dialog', () => {
expect(UNSAFE_root.findAllByType(ScrollView).length).toBe(0);
});
+ it('when scrollable=false, lets the content shrink to the space between header and footer, so a child that scrolls itself is bounded', () => {
+ const { getByTestId } = render(
+
+ );
+
+ const style = StyleSheet.flatten(getByTestId('dialog-content').props.style);
+ expect(style.flexShrink).toBe(1);
+ expect(style.minHeight).toBe(0);
+ });
+
it('still renders the children content when scrollable=false', () => {
const { getByText } = render(