diff --git a/package-lock.json b/package-lock.json
index 0917aa1..105b24f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,7 +12,7 @@
"@floating-ui/react": "^0.27.19",
"@primer/octicons-react": "^19.27.0",
"gd-eventlog": "^0.1.27",
- "incyclist-services": "^1.9.28",
+ "incyclist-services": "^1.9.29",
"leaflet": "^1.9.4",
"leaflet-geosearch": "^4.4.0",
"react": "^19.2.6",
@@ -7235,9 +7235,9 @@
}
},
"node_modules/incyclist-services": {
- "version": "1.9.28",
- "resolved": "https://registry.npmjs.org/incyclist-services/-/incyclist-services-1.9.28.tgz",
- "integrity": "sha512-qySSSQm/WHSinnvo6sJVU5hMTTWcOofLLW0ZBg2aIGClZhFShOZl6b05tqGY9jmHeYkQ4WWUim0tDIX6L1VfsQ==",
+ "version": "1.9.29",
+ "resolved": "https://registry.npmjs.org/incyclist-services/-/incyclist-services-1.9.29.tgz",
+ "integrity": "sha512-hEtRjlbfz57v1lJk40mmTmKrzSd2a3arl7SFYIvdGT9Pk11pdFj/XayUNdgjppcOaPCJ3O2ADUas8tUePjJHoA==",
"dependencies": {
"@garmin/fitsdk": "^21.221.0",
"axios": "^1.21.1",
diff --git a/package.json b/package.json
index 4963b06..3d5bf78 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"@floating-ui/react": "^0.27.19",
"@primer/octicons-react": "^19.27.0",
"gd-eventlog": "^0.1.27",
- "incyclist-services": "^1.9.28",
+ "incyclist-services": "^1.9.29",
"leaflet": "^1.9.4",
"leaflet-geosearch": "^4.4.0",
"react": "^19.2.6",
diff --git a/src/components/modules/workout/WorkoutImport/WorkoutImportDialog.jsx b/src/components/modules/workout/WorkoutImport/WorkoutImportDialog.jsx
new file mode 100644
index 0000000..56d1d67
--- /dev/null
+++ b/src/components/modules/workout/WorkoutImport/WorkoutImportDialog.jsx
@@ -0,0 +1,78 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react'
+import { getWorkoutListPageService } from 'incyclist-services'
+import { EventLogger } from 'gd-eventlog'
+import { ErrorBoundary } from '../../../atoms'
+import { WorkoutImportDialogView } from './WorkoutImportDialogView'
+
+const logger = new EventLogger('WorkoutImportDialog')
+
+/**
+ * Smart import dialog. The phase and its data come from the workout list page service
+ * (`getImportDisplayProps()`, refreshed on every 'import-update'), the dialog only reports user actions.
+ *
+ * The parent owns the open/closed state: it mounts this component to open the dialog and
+ * unmounts it from `onClose`. Every way out (Done, Close, Cancel, Esc, outside click, unmount)
+ * ends the import flow in the service exactly once.
+ *
+ * props: `source` ('button' | 'page-drop', used for logging only), `onClose`
+ */
+export const WorkoutImportDialog = ({ source, onClose }) => {
+ const service = getWorkoutListPageService()
+ const [displayProps, setDisplayProps] = useState(() => service.getImportDisplayProps())
+
+ const refPhase = useRef(displayProps?.phase)
+ const refClosed = useRef(false)
+ refPhase.current = displayProps?.phase
+
+ useEffect(() => {
+ logger.logEvent({ message: 'dialog opened', source, phase: refPhase.current })
+ }, [source])
+
+ useEffect(() => {
+ const observer = service.getPageObserver()
+ const onUpdate = () => { setDisplayProps(service.getImportDisplayProps()) }
+
+ observer?.on('import-update', onUpdate)
+ return () => { observer?.off('import-update', onUpdate) }
+ }, [service])
+
+ const finish = useCallback((action) => {
+ if (refClosed.current)
+ return false
+ refClosed.current = true
+ logger.logEvent({ message: 'dialog closed', phase: refPhase.current, action })
+ service.onImportClose()
+ return true
+ }, [service])
+
+ // unmounted by the parent without a close action (e.g. navigation)
+ useEffect(() => () => { finish('unmount') }, [finish])
+
+ const handleClose = useCallback((action) => {
+ if (finish(action))
+ onClose?.()
+ }, [finish, onClose])
+
+ const onFiles = useCallback((files) => { service.onImportFiles(files, 'dialog') }, [service])
+ const onPickAnother = useCallback(() => { service.onImportOpen() }, [service])
+ const onSetGroup = useCallback((group) => {
+ const result = service.getImportDisplayProps()?.result ?? displayProps?.result
+ if (!result)
+ return
+ const isNew = !(displayProps?.knownGroups ?? []).includes(group)
+ logger.logEvent({ message: 'import group changed', group, isNew, eventSource: 'user' })
+ service.onImportSetGroup(result.id, group)
+ }, [service, displayProps])
+
+ return (
+
+
+
+ )
+}
diff --git a/src/components/modules/workout/WorkoutImport/WorkoutImportDialog.unit.test.jsx b/src/components/modules/workout/WorkoutImport/WorkoutImportDialog.unit.test.jsx
new file mode 100644
index 0000000..8755432
--- /dev/null
+++ b/src/components/modules/workout/WorkoutImport/WorkoutImportDialog.unit.test.jsx
@@ -0,0 +1,117 @@
+import React from 'react'
+import { describe, test, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent, act } from '@testing-library/react'
+import { WorkoutImportDialog } from './WorkoutImportDialog'
+
+const { service, observer, state } = vi.hoisted(() => {
+ const listeners = {}
+ return {
+ state: { props: { phase: 'landing', knownGroups: [] } },
+ observer: {
+ listeners,
+ on: vi.fn((evt, cb) => { (listeners[evt] ??= []).push(cb) }),
+ off: vi.fn((evt, cb) => { listeners[evt] = (listeners[evt] ?? []).filter(l => l !== cb) }),
+ },
+ service: {
+ getImportDisplayProps: vi.fn(),
+ getPageObserver: vi.fn(),
+ onImportFiles: vi.fn(),
+ onImportOpen: vi.fn(),
+ onImportSetGroup: vi.fn(),
+ onImportClose: vi.fn(),
+ },
+ }
+})
+
+vi.mock('incyclist-services', async (importOriginal) => {
+ const actual = await importOriginal()
+ return { ...actual, getWorkoutListPageService: () => service }
+})
+
+vi.mock('./WorkoutImportDialogView', () => ({
+ WorkoutImportDialogView: ({ displayProps, onClose, onFiles, onPickAnother, onSetGroup }) => (
+
+ phase:{displayProps.phase}
+
+
+
+
+
+
+ ),
+}))
+
+const emit = (evt) => act(() => { (observer.listeners[evt] ?? []).forEach(l => l()) })
+
+describe('WorkoutImportDialog', () => {
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ observer.listeners['import-update'] = []
+ state.props = { phase: 'landing', knownGroups: ['Sweet', 'VO2'] }
+ service.getImportDisplayProps.mockImplementation(() => state.props)
+ service.getPageObserver.mockReturnValue(observer)
+ })
+
+ test('renders the initial phase from the service', () => {
+ render()
+ expect(screen.getByText('phase:landing')).toBeTruthy()
+ })
+
+ test('renders the phase the service is already in (drop)', () => {
+ state.props = { phase: 'importing', knownGroups: [] }
+ render()
+ expect(screen.getByText('phase:importing')).toBeTruthy()
+ })
+
+ test('re-reads the display props on import-update', () => {
+ render()
+ state.props = { phase: 'result', result: { id: 'w1' }, knownGroups: ['Sweet'] }
+ emit('import-update')
+ expect(screen.getByText('phase:result')).toBeTruthy()
+ })
+
+ test('onFiles and onPickAnother go to the service', () => {
+ render()
+ fireEvent.click(screen.getByText('files'))
+ expect(service.onImportFiles).toHaveBeenCalledWith(['f'], 'dialog')
+ fireEvent.click(screen.getByText('another'))
+ expect(service.onImportOpen).toHaveBeenCalledTimes(1)
+ })
+
+ test('onSetGroup passes the result id and the group', () => {
+ state.props = { phase: 'result', result: { id: 'w1', group: 'VO2' }, knownGroups: ['Sweet', 'VO2'] }
+ render()
+ fireEvent.click(screen.getByText('group'))
+ expect(service.onImportSetGroup).toHaveBeenCalledWith('w1', 'Sweet')
+ })
+
+ test('close ends the import, then reports onClose; unmount does not close again', () => {
+ const onClose = vi.fn()
+ const order = []
+ service.onImportClose.mockImplementation(() => order.push('service'))
+ onClose.mockImplementation(() => order.push('parent'))
+
+ const { unmount } = render()
+ fireEvent.click(screen.getByText('done'))
+ expect(order).toEqual(['service', 'parent'])
+
+ unmount()
+ expect(service.onImportClose).toHaveBeenCalledTimes(1)
+ })
+
+ test('unmount without a close action closes the import once and does not call onClose', () => {
+ const onClose = vi.fn()
+ const { unmount } = render()
+ unmount()
+ expect(service.onImportClose).toHaveBeenCalledTimes(1)
+ expect(onClose).not.toHaveBeenCalled()
+ })
+
+ test('removes the import-update listener on unmount', () => {
+ const { unmount } = render()
+ const cb = observer.on.mock.calls.find(c => c[0] === 'import-update')[1]
+ unmount()
+ expect(observer.off).toHaveBeenCalledWith('import-update', cb)
+ })
+})
diff --git a/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.jsx b/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.jsx
new file mode 100644
index 0000000..b601e80
--- /dev/null
+++ b/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.jsx
@@ -0,0 +1,290 @@
+import React, { useCallback } from 'react'
+import styled from 'styled-components'
+import { Button, ButtonBar, ErrorText, ImportIcon, Loader } from '../../../atoms'
+import { Dialog, Dropzone, WorkoutGraph } from '../../../molecules'
+import { WorkoutCategorySelect } from '../selection/WorkoutCategorySelect'
+
+// Same fixed box as the Import Routes dialog: one box for every phase, only the content changes
+export const WORKOUT_IMPORT_DIALOG_WIDTH = 'min(980px, 70vw)'
+export const WORKOUT_IMPORT_DIALOG_HEIGHT = 'min(660px, 75vh)'
+
+export const WORKOUT_IMPORT_FILTERS = [
+ { name: 'Workouts', extensions: ['zwo', 'json'] },
+ { name: 'Zwift Workout', extensions: ['zwo'] },
+ { name: 'Incyclist Workout', extensions: ['json'] },
+]
+
+const TITLES = {
+ landing: 'Import Workout',
+ importing: 'Importing...',
+ result: 'Import Successful',
+ error: 'Import Failed',
+}
+
+const TileArea = styled.div`
+ display: flex;
+ align-items: stretch;
+ justify-content: center;
+ width: 100%;
+ height: calc(100% - 7.7vh);
+ padding: 3vh 2vw 0 2vw;
+ box-sizing: border-box;
+`
+
+const TileTitle = styled.div`
+ font-size: 2.2vh;
+ font-weight: bold;
+ color: white;
+`
+
+const TileSubline = styled.div`
+ font-size: 1.5vh;
+ color: white;
+ opacity: 0.8;
+`
+
+const TileContent = styled.div`
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 1vh;
+ padding: 2vh;
+ text-align: center;
+`
+
+const SUCCESS_COLOR = '#4CAF50'
+const ERROR_COLOR = '#D32F2F'
+const DEFAULT_GROUP = 'My Workouts'
+
+// centred panel (importing, error, result without graph)
+const Body = styled.div`
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ height: calc(100% - 7.7vh);
+ text-align: center;
+ padding: 2vh 2vw;
+ box-sizing: border-box;
+ gap: 2vh;
+ font-size: 2vh;
+`
+
+// result with graph: header, category, graph
+const ResultBody = styled.div`
+ display: flex;
+ flex-direction: column;
+ height: calc(100% - 7.7vh);
+ padding: 2vh 2vw;
+ box-sizing: border-box;
+ font-size: 2vh;
+`
+
+const HeaderRow = styled.div`
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ gap: 1.5vw;
+ margin-bottom: 1.5vh;
+ font-size: 2vh;
+ color: white;
+`
+
+const CategoryRow = styled.div`
+ align-self: ${props => props.$center ? 'center' : 'flex-start'};
+ margin-bottom: 1vh;
+ text-align: left;
+
+ /* keep the selected value readable regardless of the colour inherited from the dialog */
+ select, option {
+ color: #000;
+ background-color: #fff;
+ }
+`
+
+const GraphArea = styled.div`
+ flex: 1;
+ width: 100%;
+ min-height: 20vh;
+`
+
+const StatusCircle = styled.div`
+ flex: none;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ box-sizing: border-box;
+ width: ${props => props.$large ? '12vh' : '2.8vh'};
+ height: ${props => props.$large ? '12vh' : '2.8vh'};
+ border: ${props => props.$large ? '0.6vh' : '0.2vh'} solid ${props => props.$color};
+ border-radius: 50%;
+ color: ${props => props.$color};
+ font-weight: bold;
+ font-size: ${props => props.$large ? '7vh' : '1.6vh'};
+ line-height: 1;
+`
+
+const StatusText = styled.div`
+ font-size: 2vh;
+ color: white;
+`
+
+const SuccessCircle = ({ large }) => (
+
+
+
+)
+
+const ErrorCircle = () => (
+ !
+)
+
+const Landing = ({ onFiles, onCancel }) => {
+ const onDrop = useCallback((dropInfo) => {
+ const files = (Array.isArray(dropInfo) ? dropInfo : [dropInfo]).filter(Boolean)
+ if (files.length > 0)
+ onFiles?.(files)
+ }, [onFiles])
+
+ return (
+ <>
+
+
+ Choose Workout File
+ ZWO or JSON
+
+ }
+ />
+
+
+
+
+ >
+ )
+}
+
+const Importing = ({ fileName, onCancel }) => (
+ <>
+
+
+ {`Importing ${fileName ?? ''}…`}
+
+
+
+
+ >
+)
+
+const hasSteps = (workout) => Array.isArray(workout?.steps) && workout.steps.length > 0
+
+const Result = ({ result, knownGroups, onSetGroup, onPickAnother, onDone }) => {
+ const message = `"${result?.workoutName ?? ''}" has been added to your library`
+ const category = (
+
+ )
+ const buttons = (
+
+
+
+
+ )
+
+ if (!hasSteps(result?.workout)) {
+ return (
+ <>
+
+
+ {message}
+ {category}
+
+ {buttons}
+ >
+ )
+ }
+
+ return (
+ <>
+
+
+
+ {message}
+
+ {category}
+
+
+
+
+ {buttons}
+ >
+ )
+}
+
+const Failed = ({ error, onPickAnother, onClose }) => (
+ <>
+
+
+
+
+
+
+
+
+ >
+)
+
+/**
+ * Pure view of the workout import dialog. The phase and its data come in via `displayProps`
+ * (`phase`: landing | importing | result | error), all user actions are reported through
+ * callbacks - no service access.
+ *
+ * `onClose(action)` reports how the dialog was dismissed:
+ * 'done' | 'close' | 'cancel' | 'esc' | 'outside'.
+ */
+export const WorkoutImportDialogView = ({ displayProps, onClose, onFiles, onPickAnother, onSetGroup }) => {
+ const { phase = 'landing', importing, result, error, knownGroups } = displayProps ?? {}
+
+ const close = (action) => () => onClose?.(action)
+
+ let content
+ switch (phase) {
+ case 'importing':
+ content =
+ break
+ case 'result':
+ content =
+ break
+ case 'error':
+ content =
+ break
+ default:
+ content =
+ }
+
+ return (
+
+ )
+}
diff --git a/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.stories.jsx b/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.stories.jsx
new file mode 100644
index 0000000..6210b07
--- /dev/null
+++ b/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.stories.jsx
@@ -0,0 +1,72 @@
+import React from 'react'
+import { Workout } from 'incyclist-services'
+import { WorkoutImportDialogView } from './WorkoutImportDialogView'
+
+const workout = new Workout({
+ id: 'sweet-spot-3x12',
+ name: 'Sweet Spot 3x12',
+ type: 'workout',
+ steps: [
+ { type: 'step', duration: 600, power: { max: 55, type: 'pct of FTP' }, steady: true, work: false, cooldown: false, text: '' },
+ { type: 'step', duration: 720, power: { max: 90, type: 'pct of FTP' }, steady: true, work: true, cooldown: false, text: '' },
+ { type: 'step', duration: 300, power: { max: 55, type: 'pct of FTP' }, steady: true, work: false, cooldown: false, text: '' },
+ { type: 'step', duration: 720, power: { max: 90, type: 'pct of FTP' }, steady: true, work: true, cooldown: false, text: '' },
+ { type: 'step', duration: 300, power: { max: 55, type: 'pct of FTP' }, steady: true, work: false, cooldown: false, text: '' },
+ { type: 'step', duration: 720, power: { max: 90, type: 'pct of FTP' }, steady: true, work: true, cooldown: false, text: '' },
+ { type: 'step', duration: 600, power: { max: 50, type: 'pct of FTP' }, steady: true, work: false, cooldown: true, text: '' },
+ ],
+})
+
+export default {
+ component: WorkoutImportDialogView,
+ title: 'Modules/Workout/WorkoutImportDialogView',
+ argTypes: {
+ onClose: { action: 'close' },
+ onFiles: { action: 'files' },
+ onPickAnother: { action: 'pick another' },
+ onSetGroup: { action: 'set group' },
+ },
+}
+
+const Template = args =>
+
+export const Landing = Template.bind({})
+Landing.args = { displayProps: { phase: 'landing', knownGroups: [] } }
+
+export const Importing = Template.bind({})
+Importing.args = { displayProps: { phase: 'importing', knownGroups: [], importing: { fileName: 'sweet-spot.zwo' } } }
+
+// success header, category and the workout graph
+export const Result = Template.bind({})
+Result.args = {
+ displayProps: {
+ phase: 'result',
+ knownGroups: ['My Workouts', 'Intervals', 'Endurance'],
+ result: { id: 'w1', workoutName: 'Sweet Spot 3x12', group: 'My Workouts', workout, ftp: 250 },
+ },
+}
+
+// no workout in the props (older services): centred status panel
+export const ResultWithoutGraph = Template.bind({})
+ResultWithoutGraph.args = {
+ displayProps: {
+ phase: 'result',
+ knownGroups: ['My Workouts', 'Intervals', 'Endurance'],
+ result: { id: 'w1', workoutName: 'Sweet Spot 3x12', group: 'My Workouts' },
+ },
+}
+
+export const ResultCategoryPreselected = Template.bind({})
+ResultCategoryPreselected.args = {
+ displayProps: {
+ phase: 'result',
+ knownGroups: ['My Workouts', 'Intervals', 'Endurance'],
+ result: { id: 'w1', workoutName: 'Sweet Spot 3x12', group: 'Intervals', workout, ftp: 250 },
+ },
+}
+
+export const ErrorParse = Template.bind({})
+ErrorParse.args = { displayProps: { phase: 'error', knownGroups: [], error: 'invalid file format xml' } }
+
+export const ErrorMultipleFiles = Template.bind({})
+ErrorMultipleFiles.args = { displayProps: { phase: 'error', knownGroups: [], error: 'Only one workout file at a time' } }
diff --git a/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.unit.test.jsx b/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.unit.test.jsx
new file mode 100644
index 0000000..f006a51
--- /dev/null
+++ b/src/components/modules/workout/WorkoutImport/WorkoutImportDialogView.unit.test.jsx
@@ -0,0 +1,231 @@
+import React from 'react'
+import { describe, test, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent, act } from '@testing-library/react'
+
+const { rendered } = vi.hoisted(() => ({ rendered: { dropzoneProps: null } }))
+
+// Dropzone talks to the native file dialog and drag/drop events - neither works under jsdom.
+// Stubbed to capture the props the view passes, so a test can fire onDrop directly.
+vi.mock('../../../molecules', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ Dropzone: (props) => {
+ rendered.dropzoneProps = props
+ return {props.text}
+ },
+ }
+})
+
+vi.mock('../../../molecules/WorkoutGraph/WorkoutGraph', () => ({
+ WorkoutGraph: ({ workout, ftp }) => {workout?.name}
,
+}))
+
+import { WorkoutImportDialogView, WORKOUT_IMPORT_FILTERS } from './WorkoutImportDialogView'
+
+const outside = () => document.querySelector('.dialog').parentElement
+const pressEsc = () => fireEvent.keyUp(window, { key: 'Escape', keyCode: 27 })
+const nextTick = () => act(() => new Promise(done => process.nextTick(done)))
+const buttons = () => screen.queryAllByRole('button').map(b => b.textContent)
+
+describe('WorkoutImportDialogView', () => {
+
+ let handlers
+ beforeEach(() => {
+ vi.clearAllMocks()
+ rendered.dropzoneProps = null
+ handlers = { onClose: vi.fn(), onFiles: vi.fn(), onPickAnother: vi.fn(), onSetGroup: vi.fn() }
+ })
+
+ const renderView = (displayProps) => render()
+
+ describe('landing', () => {
+ test('shows the title, the file tile and a Cancel button', () => {
+ renderView({ phase: 'landing', knownGroups: [] })
+ expect(screen.getByText('Import Workout')).toBeTruthy()
+ expect(screen.getByText('Choose Workout File')).toBeTruthy()
+ expect(screen.getByText('ZWO or JSON')).toBeTruthy()
+ expect(buttons()).toEqual(['Cancel'])
+ })
+
+ test('Cancel reports cancel', () => {
+ renderView({ phase: 'landing', knownGroups: [] })
+ fireEvent.click(screen.getByText('Cancel'))
+ expect(handlers.onClose).toHaveBeenCalledWith('cancel')
+ })
+
+ test('tile accepts a single zwo/json file', () => {
+ renderView({ phase: 'landing', knownGroups: [] })
+ expect(rendered.dropzoneProps.multiple).toBe(false)
+ expect(rendered.dropzoneProps.filters).toEqual(WORKOUT_IMPORT_FILTERS)
+ expect(WORKOUT_IMPORT_FILTERS[0].extensions).toEqual(['zwo', 'json'])
+ })
+
+ test('dropping a file calls onFiles with the array', () => {
+ renderView({ phase: 'landing', knownGroups: [] })
+ const file = { type: 'url', name: 'a.zwo', ext: 'zwo' }
+ act(() => { rendered.dropzoneProps.onDrop([file]) })
+ expect(handlers.onFiles).toHaveBeenCalledWith([file])
+ })
+
+ test('a single (non-array) drop is wrapped, an empty one is ignored', () => {
+ renderView({ phase: 'landing', knownGroups: [] })
+ const file = { type: 'url', name: 'a.zwo', ext: 'zwo' }
+ act(() => { rendered.dropzoneProps.onDrop(file) })
+ expect(handlers.onFiles).toHaveBeenCalledWith([file])
+ handlers.onFiles.mockClear()
+ act(() => { rendered.dropzoneProps.onDrop([]) })
+ expect(handlers.onFiles).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('importing', () => {
+ const props = { phase: 'importing', knownGroups: [], importing: { fileName: 'ftp-test.zwo' } }
+
+ test('shows title, loader, file name and Cancel', () => {
+ renderView(props)
+ expect(screen.getByText('Importing...')).toBeTruthy()
+ expect(screen.getByText('Importing ftp-test.zwo…')).toBeTruthy()
+ expect(document.querySelector('.dialog-content span')).toBeTruthy() // react-spinners loader
+ expect(buttons()).toEqual(['Cancel'])
+ })
+
+ test('Cancel reports cancel', () => {
+ renderView(props)
+ fireEvent.click(screen.getByText('Cancel'))
+ expect(handlers.onClose).toHaveBeenCalledWith('cancel')
+ })
+ })
+
+ describe('result', () => {
+ const workout = { name: 'Sweet Spot', steps: [{ type: 'step', duration: 60 }] }
+ const props = {
+ phase: 'result', knownGroups: ['My Workouts', 'Intervals'],
+ result: { id: 'w1', workoutName: 'Sweet Spot', group: 'My Workouts', workout, ftp: 250 },
+ }
+ const noGraphProps = { ...props, result: { id: 'w1', workoutName: 'Sweet Spot', group: 'My Workouts' } }
+
+ test('shows title, success header, category, graph and both buttons', () => {
+ renderView(props)
+ expect(screen.getByText('Import Successful')).toBeTruthy()
+ expect(screen.getByText('"Sweet Spot" has been added to your library')).toBeTruthy()
+ expect(screen.getByText('Category')).toBeTruthy()
+ expect(screen.getByTestId('status-success')).toBeTruthy()
+ expect(screen.getByTestId('workout-graph')).toBeTruthy()
+ expect(buttons()).toEqual(['Import more', 'Done'])
+ })
+
+ test('graph uses the FTP from the props, 200 if missing', () => {
+ renderView(props)
+ expect(screen.getByTestId('workout-graph').getAttribute('data-ftp')).toBe('250')
+ })
+
+ test('graph defaults the FTP to 200', () => {
+ renderView({ ...props, result: { ...props.result, ftp: undefined } })
+ expect(screen.getByTestId('workout-graph').getAttribute('data-ftp')).toBe('200')
+ })
+
+ test('without workout: fallback panel without graph, still category and buttons', () => {
+ renderView(noGraphProps)
+ expect(screen.queryByTestId('workout-graph')).toBeNull()
+ expect(screen.getByTestId('status-success')).toBeTruthy()
+ expect(screen.getByText('"Sweet Spot" has been added to your library')).toBeTruthy()
+ expect(screen.getByRole('combobox')).toBeTruthy()
+ expect(buttons()).toEqual(['Import more', 'Done'])
+ })
+
+ test('a workout without steps uses the fallback as well', () => {
+ renderView({ ...props, result: { ...props.result, workout: { name: 'x', steps: [] } } })
+ expect(screen.queryByTestId('workout-graph')).toBeNull()
+ })
+
+ test('category select shows result.group', () => {
+ renderView(props)
+ expect(screen.getByRole('combobox').value).toBe('My Workouts')
+ })
+
+ test('category select shows a preselected group that is the last used one', () => {
+ renderView({ ...props, result: { ...props.result, group: 'Intervals' } })
+ expect(screen.getByRole('combobox').value).toBe('Intervals')
+ expect(screen.queryByText('Please select ..')).toBeNull()
+ })
+
+ test('category select never shows the placeholder, even without a group', () => {
+ renderView({ ...props, result: { ...props.result, group: undefined } })
+ expect(screen.getByRole('combobox').value).toBe('My Workouts')
+ expect(screen.queryByText('Please select ..')).toBeNull()
+ })
+
+ test('Done reports done', () => {
+ renderView(props)
+ fireEvent.click(screen.getByText('Done'))
+ expect(handlers.onClose).toHaveBeenCalledWith('done')
+ })
+
+ test('Import more calls onPickAnother and does not close', () => {
+ renderView(props)
+ fireEvent.click(screen.getByText('Import more'))
+ expect(handlers.onPickAnother).toHaveBeenCalledTimes(1)
+ expect(handlers.onClose).not.toHaveBeenCalled()
+ })
+
+ test('selecting an existing group calls onSetGroup(name)', () => {
+ renderView(props)
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Intervals' } })
+ expect(handlers.onSetGroup).toHaveBeenCalledWith('Intervals')
+ })
+
+ test('Add new Category shows a text field, committing it calls onSetGroup(newName)', () => {
+ renderView(props)
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Add new Category' } })
+ expect(handlers.onSetGroup).not.toHaveBeenCalled()
+
+ const input = screen.getByRole('textbox')
+ fireEvent.change(input, { target: { value: 'Climbing' } })
+ fireEvent.blur(input)
+ expect(handlers.onSetGroup).toHaveBeenCalledWith('Climbing')
+ })
+ })
+
+ describe('error', () => {
+ const props = { phase: 'error', knownGroups: [], error: 'Only one workout file at a time' }
+
+ test('shows title, reason and both buttons', () => {
+ renderView(props)
+ expect(screen.getByText('Import Failed')).toBeTruthy()
+ expect(screen.getByText('Only one workout file at a time')).toBeTruthy()
+ expect(screen.getByTestId('status-error').textContent).toBe('!')
+ expect(buttons()).toEqual(['Pick another file', 'Close'])
+ })
+
+ test('Pick another file calls onPickAnother, Close reports close', () => {
+ renderView(props)
+ fireEvent.click(screen.getByText('Pick another file'))
+ expect(handlers.onPickAnother).toHaveBeenCalledTimes(1)
+ expect(handlers.onClose).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByText('Close'))
+ expect(handlers.onClose).toHaveBeenCalledWith('close')
+ })
+ })
+
+ describe.each([
+ ['landing', { phase: 'landing', knownGroups: [] }],
+ ['importing', { phase: 'importing', knownGroups: [], importing: { fileName: 'a.zwo' } }],
+ ['result', { phase: 'result', knownGroups: [], result: { id: '1', workoutName: 'W', group: 'G' } }],
+ ['error', { phase: 'error', knownGroups: [], error: 'x' }],
+ ])('dismissal in phase %s', (_phase, props) => {
+ test('Esc reports esc', async () => {
+ renderView(props)
+ pressEsc()
+ await nextTick()
+ expect(handlers.onClose).toHaveBeenCalledWith('esc')
+ })
+
+ test('click outside reports outside', async () => {
+ renderView(props)
+ fireEvent.click(outside())
+ await nextTick()
+ expect(handlers.onClose).toHaveBeenCalledWith('outside')
+ })
+ })
+})
diff --git a/src/components/modules/workout/WorkoutImport/WorkoutImportDismiss.unit.test.jsx b/src/components/modules/workout/WorkoutImport/WorkoutImportDismiss.unit.test.jsx
new file mode 100644
index 0000000..dc74021
--- /dev/null
+++ b/src/components/modules/workout/WorkoutImport/WorkoutImportDismiss.unit.test.jsx
@@ -0,0 +1,85 @@
+import React from 'react'
+import { describe, test, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent, act } from '@testing-library/react'
+
+const { service, observer, state } = vi.hoisted(() => {
+ const listeners = {}
+ return {
+ state: { props: { phase: 'landing', knownGroups: [] } },
+ observer: {
+ listeners,
+ on: vi.fn((evt, cb) => { (listeners[evt] ??= []).push(cb) }),
+ off: vi.fn((evt, cb) => { listeners[evt] = (listeners[evt] ?? []).filter(l => l !== cb) }),
+ },
+ service: {
+ getImportDisplayProps: vi.fn(), getPageObserver: vi.fn(), onImportFiles: vi.fn(),
+ onImportOpen: vi.fn(), onImportSetGroup: vi.fn(), onImportClose: vi.fn(),
+ },
+ }
+})
+
+vi.mock('incyclist-services', async (importOriginal) => {
+ const actual = await importOriginal()
+ return { ...actual, getWorkoutListPageService: () => service }
+})
+vi.mock('../../../molecules/WorkoutGraph/WorkoutGraph', () => ({ WorkoutGraph: () => }))
+
+import { WorkoutImportDialog } from './WorkoutImportDialog'
+
+const emit = (props) => { state.props = props; act(() => { (observer.listeners['import-update'] ?? []).forEach(l => l()) }) }
+const outside = () => document.querySelector('.dialog').parentElement
+const pressEsc = () => fireEvent.keyUp(window, { key: 'Escape', keyCode: 27 })
+
+describe('WorkoutImportDialog dismissal (real view + Dialog)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ delete window.activeDialog
+ observer.listeners['import-update'] = []
+ state.props = { phase: 'landing', knownGroups: [] }
+ service.getImportDisplayProps.mockImplementation(() => state.props)
+ service.getPageObserver.mockReturnValue(observer)
+ })
+
+ const phases = {
+ landing: { phase: 'landing', knownGroups: [] },
+ importing: { phase: 'importing', knownGroups: [], importing: { fileName: 'a.zwo' } },
+ result: { phase: 'result', knownGroups: ['G'], result: { id: '1', workoutName: 'W', group: 'G' } },
+ error: { phase: 'error', knownGroups: [], error: 'x' },
+ }
+
+ test.each(Object.keys(phases))('Esc and outside click close in phase %s', (phase) => {
+ state.props = phases[phase]
+ const onClose = vi.fn()
+ const { unmount } = render()
+ pressEsc()
+ expect(onClose).toHaveBeenCalledTimes(1)
+ unmount()
+
+ const onClose2 = vi.fn()
+ render()
+ fireEvent.click(outside())
+ expect(onClose2).toHaveBeenCalledTimes(1)
+ })
+
+ test('Esc and outside click still work after phase changes and Import more', () => {
+ const onClose = vi.fn()
+ render()
+ emit(phases.importing)
+ emit(phases.result)
+ emit(phases.landing) // Import more
+ emit(phases.importing)
+ emit(phases.result)
+ pressEsc()
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ test('outside click works after phase changes', () => {
+ const onClose = vi.fn()
+ render()
+ emit(phases.importing)
+ emit(phases.result)
+ emit(phases.landing)
+ fireEvent.click(outside())
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/components/modules/workout/WorkoutImport/index.jsx b/src/components/modules/workout/WorkoutImport/index.jsx
new file mode 100644
index 0000000..c7e6cd3
--- /dev/null
+++ b/src/components/modules/workout/WorkoutImport/index.jsx
@@ -0,0 +1 @@
+export * from './WorkoutImportDialog'
diff --git a/src/components/modules/workout/index.jsx b/src/components/modules/workout/index.jsx
index 984671b..701012c 100644
--- a/src/components/modules/workout/index.jsx
+++ b/src/components/modules/workout/index.jsx
@@ -1,4 +1,5 @@
export * from './control'
export * from './dashboard'
export * from './selection'
-export * from './ScheduledWorkoutPrompt'
\ No newline at end of file
+export * from './ScheduledWorkoutPrompt'
+export * from './WorkoutImport'
diff --git a/src/components/modules/workout/selection/UploadCard/index.jsx b/src/components/modules/workout/selection/UploadCard/index.jsx
deleted file mode 100644
index b4d5825..0000000
--- a/src/components/modules/workout/selection/UploadCard/index.jsx
+++ /dev/null
@@ -1,7 +0,0 @@
-import React from 'react'
-import { UploadSummary } from './summary'
-import { Card } from '../base/Card'
-
-export const UploadCard = (props) => {
- return
-}
diff --git a/src/components/modules/workout/selection/UploadCard/stories.jsx b/src/components/modules/workout/selection/UploadCard/stories.jsx
deleted file mode 100644
index dfb24e0..0000000
--- a/src/components/modules/workout/selection/UploadCard/stories.jsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import React from 'react';
-
-import {UploadCard} from './index';
-
-
-//const routeData = route.decoded
-
-export default {
- component: UploadCard,
- title: 'Modules/WorkoutSelection/Upload',
- argTypes: { onClick: { action: 'clicked' } },
-};
-
-const Template = args => ;
-
-export const Default = Template.bind({});
-Default.args = {
- height: 500,
- loaded:true,
- visible:true,
- ready:true
-};
-
-
diff --git a/src/components/modules/workout/selection/UploadCard/summary.jsx b/src/components/modules/workout/selection/UploadCard/summary.jsx
deleted file mode 100644
index dfbdbcd..0000000
--- a/src/components/modules/workout/selection/UploadCard/summary.jsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import React from 'react';
-import { Container, ImageContainer, ButtonContainer, DataContainer, Title } from '../base/atoms';
-import { Button,Column,Row} from '../../../../atoms';
-import styled from 'styled-components';
-import { Dropzone } from '../../../../molecules';
-
-const DEFAULT_TITLE = 'Import Workout'
-const DEFAULT_FILTERS = [
- { name: 'Workouts', extensions: ['zwo'] }
-]
-
-
-const FileDrop = styled(Dropzone)`
- color: white;
- margin:10px;
-`
-
-export const UploadSummary = ( { id, title=DEFAULT_TITLE, filters=DEFAULT_FILTERS, ready,visible,
- width='20vw',height='30vh',onMoreInfo,onOK }) => {
-
-
- const onDrop = async (...args)=>{
- if (onOK) {
- await onOK(...args)
- return null;
- }
- return null;
- }
-
-
-
- return (
-
-
-
-
-
-
-
-
-
-
-
-
- {title}
-
-
-
-
-
-
-
-
-
- )
-}
\ No newline at end of file
diff --git a/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.jsx b/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.jsx
new file mode 100644
index 0000000..b140d88
--- /dev/null
+++ b/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.jsx
@@ -0,0 +1,42 @@
+import React, { useState } from "react"
+import { EditText, SingleSelect } from "../../../../atoms"
+
+export const ADD_CATEGORY = 'Add new Category'
+const DEFAULT_STYLING = { labelWidth: '12ch', labelPosition: 'before' }
+
+/**
+ * Pure category (group) selector: a select with the known groups plus an 'Add new Category'
+ * option, which switches to a text field for entering a new name.
+ * Reports the chosen/entered name through `onChange`.
+ */
+export const WorkoutCategorySelect = ({
+ value, groups, onChange,
+ labelWidth = DEFAULT_STYLING.labelWidth, labelPosition = DEFAULT_STYLING.labelPosition
+}) => {
+ const [showEdit, setShowEdit] = useState(false)
+ const styling = { labelWidth, labelPosition }
+
+ const onSelected = (selected) => {
+ if (selected === ADD_CATEGORY) {
+ setShowEdit(true)
+ return
+ }
+ onChange?.(selected)
+ }
+
+ const onNewGroup = (name) => {
+ setShowEdit(false)
+ if (name?.length)
+ onChange?.(name)
+ }
+
+ const options = [...(groups ?? [])]
+ if (value && !options.includes(value))
+ options.push(value)
+ options.push(ADD_CATEGORY)
+
+ if (showEdit)
+ return
+
+ return
+}
diff --git a/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.stories.jsx b/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.stories.jsx
new file mode 100644
index 0000000..f180a3a
--- /dev/null
+++ b/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.stories.jsx
@@ -0,0 +1,16 @@
+import React from 'react'
+import { WorkoutCategorySelect } from './WorkoutCategorySelect'
+
+export default {
+ component: WorkoutCategorySelect,
+ title: 'Modules/Workout/WorkoutCategorySelect',
+ argTypes: { onChange: { action: 'change' } },
+}
+
+const Template = args =>
+
+export const Default = Template.bind({})
+Default.args = { value: 'My Workouts', groups: ['My Workouts', 'Intervals', 'Endurance'] }
+
+export const UnknownValue = Template.bind({})
+UnknownValue.args = { value: 'Imported', groups: ['My Workouts'] }
diff --git a/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.unit.test.jsx b/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.unit.test.jsx
new file mode 100644
index 0000000..6bc7837
--- /dev/null
+++ b/src/components/modules/workout/selection/WorkoutCategorySelect/WorkoutCategorySelect.unit.test.jsx
@@ -0,0 +1,54 @@
+import React from 'react'
+import { describe, test, expect, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import { WorkoutCategorySelect } from './WorkoutCategorySelect'
+
+describe('WorkoutCategorySelect', () => {
+
+ test('shows the label and the current value', () => {
+ render()
+ expect(screen.getByText('Category')).toBeTruthy()
+ expect(screen.getByText('Intervals')).toBeTruthy()
+ })
+
+ test('selecting an existing group calls onChange', () => {
+ const onChange = vi.fn()
+ render()
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Intervals' } })
+ expect(onChange).toHaveBeenCalledWith('Intervals')
+ })
+
+ test('a current value missing from groups is offered as an option', () => {
+ render()
+ expect(screen.getByText('Custom')).toBeTruthy()
+ expect(screen.getByText('My Workouts')).toBeTruthy()
+ expect(screen.getByText('Add new Category')).toBeTruthy()
+ })
+
+ test('Add new Category switches to a text field without calling onChange', () => {
+ const onChange = vi.fn()
+ render()
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Add new Category' } })
+ expect(screen.getByRole('textbox')).toBeTruthy()
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ test('committing the new name calls onChange and returns to the select', () => {
+ const onChange = vi.fn()
+ render()
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Add new Category' } })
+ const input = screen.getByRole('textbox')
+ fireEvent.change(input, { target: { value: 'Climbing' } })
+ fireEvent.blur(input)
+ expect(onChange).toHaveBeenCalledWith('Climbing')
+ expect(screen.getByRole('combobox')).toBeTruthy()
+ })
+
+ test('committing an empty name does not call onChange', () => {
+ const onChange = vi.fn()
+ render()
+ fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Add new Category' } })
+ fireEvent.blur(screen.getByRole('textbox'))
+ expect(onChange).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/components/modules/workout/selection/WorkoutCategorySelect/index.jsx b/src/components/modules/workout/selection/WorkoutCategorySelect/index.jsx
new file mode 100644
index 0000000..874e588
--- /dev/null
+++ b/src/components/modules/workout/selection/WorkoutCategorySelect/index.jsx
@@ -0,0 +1 @@
+export * from './WorkoutCategorySelect'
diff --git a/src/components/modules/workout/selection/WorkoutDetails/WorkoutDetailsDialogView.jsx b/src/components/modules/workout/selection/WorkoutDetails/WorkoutDetailsDialogView.jsx
index e0d4a9e..c7034bf 100644
--- a/src/components/modules/workout/selection/WorkoutDetails/WorkoutDetailsDialogView.jsx
+++ b/src/components/modules/workout/selection/WorkoutDetails/WorkoutDetailsDialogView.jsx
@@ -1,7 +1,8 @@
import React, { useEffect, useState } from "react"
import styled from "styled-components"
-import { Button, ButtonBar, CheckBox, Column, Divider, EditNumber, EditText, Row, SingleSelect, Text } from "../../../../atoms"
+import { Button, ButtonBar, CheckBox, Column, Divider, EditNumber, Row, Text } from "../../../../atoms"
import { AttachmentChip, Dialog, MessageBox, WorkoutGraph } from "../../../../molecules"
+import { WorkoutCategorySelect } from "../WorkoutCategorySelect"
const ContentArea = styled(Column)`
height: calc(100% - 7.7vh);
@@ -10,7 +11,6 @@ const ContentArea = styled(Column)`
padding-right:0.4vw;
`
-const ADD_CATEGORY = 'Add new Category'
const styling = { labelWidth: '12ch', labelPosition: 'before' }
/**
@@ -26,7 +26,7 @@ export const WorkoutDetailsDialogView = ({
onFtpChange, onErgModeChange, onStepChangeAudioSignalChange, onGroupChange
}) => {
- const [state, setState] = useState({ ftp, useErgMode, stepChangeAudioSignal, showCategoryEdit: false, confirmDelete: false })
+ const [state, setState] = useState({ ftp, useErgMode, stepChangeAudioSignal, confirmDelete: false })
// keep local (optimistic) values in sync when the page service pushes new values
useEffect(() => { setState(c => ({ ...c, ftp })) }, [ftp])
@@ -48,19 +48,6 @@ export const WorkoutDetailsDialogView = ({
setState(c => ({ ...c, stepChangeAudioSignal: value }))
onStepChangeAudioSignalChange?.(value)
}
- const onGroupSelected = (value) => {
- if (value === ADD_CATEGORY) {
- setState(c => ({ ...c, showCategoryEdit: true }))
- return
- }
- onGroupChange?.(value)
- }
- const onNewGroup = (value) => {
- setState(c => ({ ...c, showCategoryEdit: false }))
- if (value?.length)
- onGroupChange?.(value)
- }
-
const onDeleteClicked = () => setState(c => ({ ...c, confirmDelete: true }))
const onDeleteNo = () => setState(c => ({ ...c, confirmDelete: false }))
const onDeleteYes = () => {
@@ -68,11 +55,6 @@ export const WorkoutDetailsDialogView = ({
onDelete?.()
}
- const groupList = [...(groups ?? [])]
- if (group && !groupList.includes(group))
- groupList.push(group)
- groupList.push(ADD_CATEGORY)
-
return (
<>
: null}
{isScheduledEntry ? :
- state.showCategoryEdit ?
-
- :
-
+
}
diff --git a/src/components/modules/workout/selection/index.jsx b/src/components/modules/workout/selection/index.jsx
index 96e4737..b9ae56f 100644
--- a/src/components/modules/workout/selection/index.jsx
+++ b/src/components/modules/workout/selection/index.jsx
@@ -1,5 +1,5 @@
export * from './CreateCard'
export * from './ScheduledWorkoutCard'
-export * from './UploadCard'
export * from './WorkoutCard'
+export * from './WorkoutCategorySelect'
export * from './WorkoutDetails'
\ No newline at end of file
diff --git a/src/components/molecules/Dialog/index.jsx b/src/components/molecules/Dialog/index.jsx
index 12575d8..372acc7 100644
--- a/src/components/molecules/Dialog/index.jsx
+++ b/src/components/molecules/Dialog/index.jsx
@@ -72,11 +72,26 @@ export function Title(props) {
const ESC=27
+// Open dialogs, topmost last. `window.activeDialog` always mirrors the topmost one (hooks like useKey
+// and useScheduledWorkoutPrompt read it). Tracking a stack - instead of every dialog restoring "the
+// value it saw" on each re-render - keeps a lower dialog from losing (or stealing back) the active
+// state when another dialog re-renders or closes.
+const dialogStack = []
+let dialogCounter = 0
+
+const updateActiveDialog = () => {
+ window.activeDialog = dialogStack.length>0 ? dialogStack[dialogStack.length-1] : undefined
+}
+
export const Dialog = (props) => {
const logger = new EventLogger('Incyclist')
- const key = `${props.id??props.title}${Date.now()}`
+ // stable for the lifetime of the dialog instance
+ const keyRef = useRef(null)
+ if (keyRef.current===null)
+ keyRef.current = `${props.id??props.title}${Date.now()}-${++dialogCounter}`
+ const key = keyRef.current
const mounted = useRef(false)
const onOutsideClicked = () => {
@@ -113,12 +128,15 @@ export const Dialog = (props) => {
})
useEffect( ()=>{
- const prev = window.activeDialog
- window.activeDialog = key
+ dialogStack.push(key)
+ updateActiveDialog()
return ()=> {
- window.activeDialog = prev
+ const idx = dialogStack.lastIndexOf(key)
+ if (idx!==-1)
+ dialogStack.splice(idx,1)
+ updateActiveDialog()
}
- })
+ },[key])
useUnmountEffect( ()=>{
diff --git a/src/components/molecules/Dialog/index.unit.test.jsx b/src/components/molecules/Dialog/index.unit.test.jsx
new file mode 100644
index 0000000..970e642
--- /dev/null
+++ b/src/components/molecules/Dialog/index.unit.test.jsx
@@ -0,0 +1,65 @@
+import React from 'react'
+import { describe, test, expect, vi, beforeEach } from 'vitest'
+import { render, fireEvent, act } from '@testing-library/react'
+import { Dialog } from './index'
+
+const pressEsc = () => fireEvent.keyUp(window, { key: 'Escape', keyCode: 27 })
+
+describe('Dialog', () => {
+ beforeEach(() => { delete window.activeDialog })
+
+ test('ESC and outside click are reported', () => {
+ const onESC = vi.fn(), onOutsideClicked = vi.fn()
+ render()
+ pressEsc()
+ expect(onESC).toHaveBeenCalledTimes(1)
+ fireEvent.click(document.querySelector('.dialog').parentElement)
+ expect(onOutsideClicked).toHaveBeenCalledTimes(1)
+ })
+
+ test('active dialog key stays stable across re-renders', () => {
+ const { rerender } = render()
+ const first = window.activeDialog
+ rerender()
+ expect(window.activeDialog).toBe(first)
+ })
+
+ test('active dialog is cleared when the last dialog unmounts', () => {
+ const { unmount } = render()
+ expect(window.activeDialog).toBeTruthy()
+ unmount()
+ expect(window.activeDialog).toBeUndefined()
+ })
+
+ // regression: a lower dialog re-rendering on its own while an upper dialog is open, and the upper one
+ // then closing, used to leave window.activeDialog on a stale key - ESC was ignored by the lower dialog
+ test('ESC still reaches the lower dialog after it re-rendered while an upper dialog was open', () => {
+ const escA = vi.fn(), escB = vi.fn()
+ let bumpA
+ const A = () => {
+ const [n, setN] = React.useState(0)
+ bumpA = () => setN(v => v + 1)
+ return
+ }
+ const ui = (showB) => (
+ <>
+
+ {showB ? : null}
+ >
+ )
+ const { rerender } = render(ui(false))
+ rerender(ui(true))
+ pressEsc()
+ expect(escB).toHaveBeenCalledTimes(1)
+ expect(escA).not.toHaveBeenCalled()
+
+ act(() => bumpA()) // A re-renders on its own while B is open
+ pressEsc()
+ expect(escB).toHaveBeenCalledTimes(2)
+ expect(escA).not.toHaveBeenCalled()
+
+ rerender(ui(false)) // B closes
+ pressEsc()
+ expect(escA).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/pages/workouts/page.jsx b/src/pages/workouts/page.jsx
index 1c02253..56d8513 100644
--- a/src/pages/workouts/page.jsx
+++ b/src/pages/workouts/page.jsx
@@ -9,6 +9,7 @@ import { getResponsiveHorizontal } from "./utils"
import { useWindowDimensions, usePageLogger } from "../../hooks"
import { usePageService } from "../../hooks/pages"
import { WorkoutDetailsDialog } from "../../components/modules/workout/selection/WorkoutDetails"
+import { WorkoutImportDialog } from "../../components/modules/workout/WorkoutImport"
import { ScheduledWorkoutPrompt } from "../../components/modules/workout/ScheduledWorkoutPrompt"
import { Button, CheckBox, Column, Row, Overlay } from "../../components/atoms"
@@ -38,7 +39,7 @@ const CreateInfoOverlay = ({ markAsSeenDefault, onClose }) => {
Click OK to open the ZwoFactory page
Within ZwoFactory, create or select a pre-defined workout
Within ZwoFactory, download the workout using the Download button
- Go back to Incyclist and import the workout using the Import Card
+ Go back to Incyclist and import the workout using the Import Workout button
@@ -63,6 +64,8 @@ export const WorkoutsPage = () => {
const [screenProps, setScreenProps] = useState(() => service.getScreenProps())
const [pageState, setPageState] = useState(null)
const refAutoOpened = useRef(null)
+ const [importOpen, setImportOpen] = useState(false)
+ const [importSource, setImportSource] = useState(null)
const [logger, closePageLogger] = usePageLogger(PAGE_ID, pageState)
@@ -121,9 +124,24 @@ export const WorkoutsPage = () => {
service.onCarouselUpdated(listId, e?.item, e?.itemsInSlide)
}, [service])
- const onOK = useCallback((id, files) => { service.onCardOK(id, files) }, [service])
+ const onOK = useCallback((id) => { service.onCardOK(id) }, [service])
const onDelete = useCallback((id) => { service.onDelete(id) }, [service])
- const onRetry = useCallback((id) => { service.onRetry(id) }, [service])
+
+ const onImportWorkout = useCallback(() => {
+ service.onImportOpen()
+ setImportSource('button')
+ setImportOpen(true)
+ }, [service])
+
+ // the service starts the import (or reports why it was rejected) before the dialog mounts,
+ // so the dialog opens directly in the importing/error phase
+ const onDropFiles = useCallback((files) => {
+ service.onImportFiles(files, 'page-drop')
+ setImportSource('page-drop')
+ setImportOpen(true)
+ }, [service])
+
+ const onImportClose = useCallback(() => { setImportOpen(false) }, [])
const { loading = true, lists = [], upcoming = null, displayType = 'tiles', detailWorkoutId, createInfo } = props ?? {}
@@ -132,12 +150,16 @@ export const WorkoutsPage = () => {
closePage={closePage}
onOK={onOK}
onDelete={onDelete}
- onRetry={onRetry}
+ onImportWorkout={onImportWorkout}
+ onDropFiles={onDropFiles}
+ dropEnabled={!importOpen}
onInitialized={onInitialized}
onSlideChanged={onSlideChanged} />
{detailWorkoutId ? : null}
+ {importOpen ? : null}
+
{createInfo ? ({
onOpenDetails: vi.fn(),
onCardOK: vi.fn(),
onDelete: vi.fn(),
- onRetry: vi.fn(),
+ onImportOpen: vi.fn(),
+ onImportFiles: vi.fn(),
onCarouselInitialized: vi.fn(),
onCarouselUpdated: vi.fn(),
onCreateInfoClosed: vi.fn(),
@@ -39,6 +40,10 @@ vi.mock('../../components/modules/workout/selection/WorkoutDetails', () => ({
WorkoutDetailsDialog: ({ id }) => details:{id}
,
}))
+vi.mock('../../components/modules/workout/WorkoutImport', () => ({
+ WorkoutImportDialog: ({ source, onClose }) => import-dialog:{source}
,
+}))
+
vi.mock('../../hooks', async (importOriginal) => {
const actual = await importOriginal()
return { ...actual, useWindowDimensions: () => ({ width: 1000, height: 800 }) }
@@ -96,14 +101,13 @@ describe('WorkoutsPage', () => {
test('card actions and carousel callbacks are forwarded by id', () => {
renderPage()
const p = screenCalls.at(-1)
- p.onOK('w1', ['f'])
+ p.onOK('w1')
p.onDelete('w1')
- p.onRetry('imp')
p.onInitialized('myWorkouts', { item: 1, itemsInSlide: 4 })
p.onSlideChanged('myWorkouts', { item: 2, itemsInSlide: 4 })
- expect(service.onCardOK).toHaveBeenCalledWith('w1', ['f'])
+ expect(service.onCardOK).toHaveBeenCalledWith('w1')
expect(service.onDelete).toHaveBeenCalledWith('w1')
- expect(service.onRetry).toHaveBeenCalledWith('imp')
+ expect(screenCalls.at(-1).onRetry).toBeUndefined()
expect(service.onCarouselInitialized).toHaveBeenCalledWith('myWorkouts', 1, 4)
expect(service.onCarouselUpdated).toHaveBeenCalledWith('myWorkouts', 2, 4)
})
@@ -152,4 +156,39 @@ describe('WorkoutsPage', () => {
renderPage()
expect(screen.queryByText(/steps to create a workout/)).toBeNull()
})
+
+ test('import button opens the import flow and mounts the dialog', () => {
+ renderPage()
+ expect(screen.queryByText(/import-dialog/)).toBeNull()
+ act(() => { screenCalls.at(-1).onImportWorkout() })
+ expect(service.onImportOpen).toHaveBeenCalledTimes(1)
+ expect(screen.getByText('import-dialog:button')).toBeTruthy()
+ expect(screenCalls.at(-1).dropEnabled).toBe(false)
+ })
+
+ test('a page drop hands the files to the service before the dialog mounts', () => {
+ renderPage()
+ expect(screenCalls.at(-1).dropEnabled).toBe(true)
+ service.onImportFiles.mockImplementation(() => {
+ expect(screen.queryByText(/import-dialog/)).toBeNull()
+ })
+ const files = [{ type: 'url', url: 'file:///a.zwo' }]
+ act(() => { screenCalls.at(-1).onDropFiles(files) })
+ expect(service.onImportFiles).toHaveBeenCalledWith(files, 'page-drop')
+ expect(screen.getByText('import-dialog:page-drop')).toBeTruthy()
+ })
+
+ test('closing the dialog unmounts it and re-enables the drop overlay', () => {
+ renderPage()
+ act(() => { screenCalls.at(-1).onImportWorkout() })
+ fireEvent.click(screen.getByText('close-import'))
+ expect(screen.queryByText(/import-dialog/)).toBeNull()
+ expect(screenCalls.at(-1).dropEnabled).toBe(true)
+ })
+
+ test('create-info step 4 points at the Import Workout button', () => {
+ service.getPageDisplayProperties.mockReturnValue(props({ createInfo: { markAsSeenDefault: true } }))
+ renderPage()
+ expect(screen.getByText(/Import Workout button/)).toBeTruthy()
+ })
})
diff --git a/src/pages/workouts/screen.jsx b/src/pages/workouts/screen.jsx
index 32e06c7..2a5428f 100644
--- a/src/pages/workouts/screen.jsx
+++ b/src/pages/workouts/screen.jsx
@@ -1,6 +1,9 @@
import React, {useEffect, useMemo, useRef, useState } from "react"
import MainPage from "../../components/molecules/MainPage"
-import { PageTitle,GroupTitle, Loader, Center } from "../../components/atoms"
+import { PageTitle,GroupTitle, Loader, Center, Button } from "../../components/atoms"
+import { ImportIcon } from "../../components/atoms/Icons/ImportIcon"
+import { Dropzone } from "../../components/molecules"
+import { WORKOUT_IMPORT_FILTERS } from "../../components/modules/workout/WorkoutImport/WorkoutImportDialogView"
import styled from "styled-components"
import { Column, Row } from "../../components/atoms/layout/View"
import { useKey } from "../../hooks/ui/useKey"
@@ -8,8 +11,6 @@ import { useMouseSwipe } from "../../hooks/ui/useMouseSwipe"
import { Carousel } from "../../components/atoms/Carousel"
import { NavigationBar } from "../../components/molecules/NavigationBar"
import { AppThemeProvider } from "../../theme"
-import { ActiveImportCard } from "../../components/modules/routeSelection/ActiveImportCard"
-import {UploadCard} from '../../components/modules/workout/selection/UploadCard'
import {WorkoutCard} from '../../components/modules/workout/selection/WorkoutCard'
import { WorkoutCreateCard } from "../../components/modules/workout/selection/CreateCard"
import { ScheduledWorkoutCard } from "../../components/modules/workout/selection/ScheduledWorkoutCard"
@@ -34,9 +35,67 @@ const ContentArea = styled(Column)`
padding-left:40px;
padding-right: 40px;
overflow-y: hidden;
+ position: relative;
+ box-sizing: border-box;
`
+// page-level drop overlay, only rendered while a file is dragged over the page
+const DropOverlay = styled(Dropzone)`
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ box-sizing: border-box;
+ margin: 0;
+ z-index: 20;
+ background-color: rgba(0,0,0,0.6);
+ border-width: 3px;
+ border-color: #dd9933;
+ border-radius: 8px;
+ color: white;
+`
+
+const DropOverlayTitle = styled.div`
+ font-size: 2.4vh;
+ font-weight: bold;
+`
+
+// title stays centred, the Import button sits on the right
+const HeaderLayout = styled.div`
+ display: grid;
+ grid-template-columns: 1fr auto 1fr;
+ align-items: center;
+ width: 100%;
+`
+
+const TitleCell = styled.div`
+ grid-column: 2;
+ white-space: nowrap;
+`
+
+const ImportSlot = styled.div`
+ grid-column: 3;
+ justify-self: end;
+ display: flex;
+`
+
+const HeaderButtonContent = styled.span`
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4em;
+ flex-shrink: 0;
+`
+
+export const WORKOUT_DROP_OVERLAY_TITLE = 'Drop a workout file (ZWO or JSON)'
+
+const ImportWorkoutButton = ({ onClick }) => (
+
+)
+
const CardView= styled(Row)`
justify-content:center;
user-select:none;
@@ -76,8 +135,6 @@ export const ListContainer = styled(View)`
`
const CARD_COMPONENTS = {
- WorkoutImport: UploadCard,
- ActiveWorkoutImport: ActiveImportCard,
WorkoutCreate: WorkoutCreateCard,
Workout: WorkoutCard,
ScheduledWorkout: ScheduledWorkoutCard
@@ -89,7 +146,7 @@ const callback = (fn, listId, e) => {
fn(listId, e)
}
-const WorkoutList = ({ list, cardSize, itemsFit, responsive, onOK, onDelete, onRetry,
+const WorkoutList = ({ list, cardSize, itemsFit, responsive, onOK, onDelete,
onInitialized, onUpdated, onSlideChange, onSlideChanged, setScrolling }) => {
const [cardData, setCardData] = useState(list.cards)
@@ -122,10 +179,9 @@ const WorkoutList = ({ list, cardSize, itemsFit, responsive, onOK, onDelete, onR
hidden={!content.visible}
onOK={onOK ? (...args) => { onOK(card.id, ...args) } : undefined}
onDelete={onDelete ? () => { onDelete(card.id) } : undefined}
- onRetry={onRetry ? () => { onRetry(card.id) } : undefined}
/>
- }).filter(Boolean), [cardData, cardSize, onOK, onDelete, onRetry])
+ }).filter(Boolean), [cardData, cardSize, onOK, onDelete])
const header = list.title
@@ -160,7 +216,7 @@ export const WorkoutsScreen =
({ loading, cardSize, offset = 0, responsive, itemsFit, width, height, lists, upcoming = null,
// eslint-disable-next-line no-unused-vars
displayType = 'tiles',
- onInitialized, onUpdated, onSlideChange, onSlideChanged, onOK, closePage, onDelete, onRetry }) => {
+ onInitialized, onUpdated, onSlideChange, onSlideChanged, onOK, closePage, onDelete, onImportWorkout, onDropFiles, dropEnabled = true }) => {
const swipeDisabled = useRef(false);
// upcoming (scheduled) workouts come first; keyed by list id so the section mounts/unmounts
@@ -168,6 +224,36 @@ export const WorkoutsScreen =
const allLists = useMemo(() => [...(upcoming ? [upcoming] : []), ...(lists ?? [])], [upcoming, lists])
const refDiv = useRef(null);
+ // --- page-level drop overlay (same mechanism as the Routes page) ---
+ const dragDepth = useRef(0)
+ const [dragActive, setDragActive] = useState(false)
+
+ const onContentDragEnterCapture = (e) => {
+ e.preventDefault()
+ dragDepth.current += 1
+ if (dragDepth.current === 1)
+ setDragActive(true)
+ }
+ const onContentDragOverCapture = (e) => { e.preventDefault() }
+ const onContentDragLeaveCapture = () => {
+ dragDepth.current = Math.max(0, dragDepth.current - 1)
+ if (dragDepth.current === 0)
+ setDragActive(false)
+ }
+ const onContentDropCapture = (e) => {
+ // an unhandled drop would navigate the window to the file. Hide the overlay only after the
+ // event is fully dispatched, otherwise it unmounts before its own drop handler runs.
+ e.preventDefault()
+ setTimeout(() => {
+ dragDepth.current = 0
+ setDragActive(false)
+ }, 0)
+ }
+ const onOverlayDrop = (dropInfo) => {
+ if (typeof onDropFiles === 'function')
+ onDropFiles(Array.isArray(dropInfo) ? dropInfo : [dropInfo])
+ }
+
const onScrollUp = (pixels)=> {
if (swipeDisabled.current===true)
@@ -259,14 +345,19 @@ export const WorkoutsScreen =
-
- Workouts
+
+
+ Workouts
+
+
{ !loading && cardSize && lists ?
allLists.map( list => )
:
@@ -276,6 +367,12 @@ export const WorkoutsScreen =
{ (loading || !cardSize ) ? :null }
+ {dragActive && dropEnabled ?
+ {WORKOUT_DROP_OVERLAY_TITLE}} />
+ : null}
+
diff --git a/src/pages/workouts/screen.stories.jsx b/src/pages/workouts/screen.stories.jsx
index 0db6dc4..5f89751 100644
--- a/src/pages/workouts/screen.stories.jsx
+++ b/src/pages/workouts/screen.stories.jsx
@@ -7,7 +7,8 @@ export default {
argTypes: {
onOK: { action: 'OK' },
onDelete: { action: 'delete' },
- onRetry: { action: 'retry' },
+ onImportWorkout: { action: 'import workout' },
+ onDropFiles: { action: 'drop files' },
},
}
@@ -30,7 +31,6 @@ const workout = (id, title, extra = {}) => ({
const myWorkouts = {
id: 'myWorkouts', title: 'My Workouts', observer: noObserver,
cards: [
- { id: 'Import', cardType: 'WorkoutImport', props: { title: 'Import Workout', filters: [], visible: true } },
{ id: 'Create', cardType: 'WorkoutCreate', props: { title: 'Create Workout', visible: true } },
workout('w1', 'Sweet Spot'),
]
diff --git a/src/pages/workouts/screen.unit.test.jsx b/src/pages/workouts/screen.unit.test.jsx
index 7ded5e6..d9411b3 100644
--- a/src/pages/workouts/screen.unit.test.jsx
+++ b/src/pages/workouts/screen.unit.test.jsx
@@ -1,6 +1,6 @@
import React from 'react'
import { describe, test, expect, vi } from 'vitest'
-import { render } from '@testing-library/react'
+import { render, screen, fireEvent } from '@testing-library/react'
import { WorkoutsScreen } from './screen'
vi.mock('../../components/molecules/MainPage', () => ({ default: ({ children }) => {children}
}))
@@ -9,6 +9,18 @@ vi.mock('../../hooks/ui/useKey', () => ({ useKey: () => {} }))
vi.mock('../../hooks/ui/useMouseSwipe', () => ({ useMouseSwipe: () => {} }))
vi.mock('../../components/atoms/Carousel', () => ({ Carousel: () => }))
+// Dropzone relies on native drag/drop internals that jsdom lacks - stubbed so a test can hand over a drop
+vi.mock('../../components/molecules', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ Dropzone: (props) => (
+ props.onDrop?.([{ type: 'url', url: 'file:///w/a.zwo' }])}>{props.text}
+ ),
+ }
+})
+
const cardSize = { width: 200, height: 300, padding: 0 }
const list = (id, title, observer) => ({ id, title, observer, cards: [] })
const renderScreen = (props) => render()
@@ -41,4 +53,38 @@ describe('WorkoutsScreen', () => {
rerender()
expect(observer.on).toHaveBeenCalledTimes(2)
})
+
+ test('renders the Import Workout button and reports clicks', () => {
+ const onImportWorkout = vi.fn()
+ renderScreen({ lists: [], onImportWorkout })
+ fireEvent.click(screen.getByText('Import Workout'))
+ expect(onImportWorkout).toHaveBeenCalledTimes(1)
+ })
+
+ test('dragging a file over the page shows the drop overlay', () => {
+ const { container } = renderScreen({ lists: [], dropEnabled: true })
+ expect(screen.queryByText('Drop a workout file (ZWO or JSON)')).toBeNull()
+ fireEvent.dragEnter(container.querySelector('.workouts-page'))
+ expect(screen.getByText('Drop a workout file (ZWO or JSON)')).toBeTruthy()
+ })
+
+ test('the overlay is not shown when drops are disabled', () => {
+ const { container } = renderScreen({ lists: [], dropEnabled: false })
+ fireEvent.dragEnter(container.querySelector('.workouts-page'))
+ expect(screen.queryByText('Drop a workout file (ZWO or JSON)')).toBeNull()
+ })
+
+ test('dropping on the overlay reports the files', () => {
+ const onDropFiles = vi.fn()
+ const { container } = renderScreen({ lists: [], dropEnabled: true, onDropFiles })
+ fireEvent.dragEnter(container.querySelector('.workouts-page'))
+ fireEvent.drop(container.querySelector('.workout-drop-overlay'))
+ expect(onDropFiles).toHaveBeenCalledWith([{ type: 'url', url: 'file:///w/a.zwo' }])
+ })
+
+ test('no Import card is rendered even if the service passes one', () => {
+ const l = { id: 'myWorkouts', title: 'My Workouts', cards: [{ id: 'Import', cardType: 'WorkoutImport', props: { title: 'Import Workout', visible: true } }] }
+ const { container } = renderScreen({ lists: [l] })
+ expect(container.querySelectorAll('.item').length).toBe(0)
+ })
})