diff --git a/package-lock.json b/package-lock.json index a40f93f..0eff144 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.26", + "incyclist-services": "^1.9.27", "leaflet": "^1.9.4", "leaflet-geosearch": "^4.4.0", "react": "^19.2.6", @@ -7235,9 +7235,9 @@ } }, "node_modules/incyclist-services": { - "version": "1.9.26", - "resolved": "https://registry.npmjs.org/incyclist-services/-/incyclist-services-1.9.26.tgz", - "integrity": "sha512-hxSE5Vw3verEIzhw9qxkCDdKTiY+LlfELOVGryFSkAh7zCrLm3N1Eczs/hRZzPsZP9+UGxTaMAvMJjfycVc6mA==", + "version": "1.9.27", + "resolved": "https://registry.npmjs.org/incyclist-services/-/incyclist-services-1.9.27.tgz", + "integrity": "sha512-MTQbfiX95uHyahK8jR1Jn7+TrckHaUQ8cxJrxx1VU4Ogit7zmqhKqQXtYNAtRV+VVvwvtJyyTICI6xP5sQm9JQ==", "dependencies": { "@garmin/fitsdk": "^21.221.0", "axios": "^1.21.0", diff --git a/package.json b/package.json index bbbb306..bccf396 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.26", + "incyclist-services": "^1.9.27", "leaflet": "^1.9.4", "leaflet-geosearch": "^4.4.0", "react": "^19.2.6", diff --git a/public/images/intervals.png b/public/images/intervals.png deleted file mode 100644 index 4289e66..0000000 Binary files a/public/images/intervals.png and /dev/null differ diff --git a/public/images/velo-black.png b/public/images/velo-black.png deleted file mode 100644 index 984371d..0000000 Binary files a/public/images/velo-black.png and /dev/null differ diff --git a/src/components/modules/Settings/Apps/AppsSettings.jsx b/src/components/modules/Settings/Apps/AppsSettings.jsx index 43bb4b5..4642fb2 100644 --- a/src/components/modules/Settings/Apps/AppsSettings.jsx +++ b/src/components/modules/Settings/Apps/AppsSettings.jsx @@ -1,107 +1,96 @@ import { useAppsService } from "incyclist-services" -import React,{ useEffect, useState } from "react" -import styled from "styled-components"; -import { AppThemeProvider } from "../../../../theme"; -import { Row } from "../../../atoms"; -import { AppsItem } from "../../../molecules/Apps/AppsItem"; -import { StravaSettings } from "./Strava"; -import { KomootSettings } from "./Komoot/KomootSettings"; -import {IntervalsSettings} from './Intervals/IntervalsSettings' - +import React, { useCallback, useEffect, useRef, useState } from "react" +import styled from "styled-components" +import { EventLogger } from "gd-eventlog" +import { AppThemeProvider } from "../../../../theme" +import { AppsItem } from "../../../molecules/Apps/AppsItem" +import { KomootSettings } from "./Komoot/KomootSettings" +import { OAuthAppSettings } from "./OAuthAppSettings" export const ContentArea = styled.div` position:relative; width: ${props=> props.width || 'calc(100% - 2vw)'}; - // height: ${props=>props.height || 'calc(100% - 2vh)'}; text-align: left ; margin:auto; display: flex; flex-direction:column; - padding-left: 1vw; - padding-right: 1vw; - padding-top: 1vh; - padding-bottom: 1vh; padding:1vw; top:0; left:0; background: ${props => props.background || props.theme.dialogContent.background || 'white'}; `; -const getMapping = (service) => { - const mapping = { - strava: StravaSettings, - komoot: KomootSettings, - intervals: IntervalsSettings - } - const C = mapping[service] - return C -} +const Empty = styled.div` + padding: 1vh 1vw; +` -const SettingsPage = ( {service,onBack} ) => { - - const C = getMapping(service) - if (!C) - return null +// Apps that are connected through an image button instead of a text button +const CONNECT_IMAGES = { + strava: 'images/btn_strava_connectwith_orange.svg' +} - return +const renderApp = (app) => { + if (app.key === 'komoot') + return + return } - export const AppsSettings = ( ) => { const service = useAppsService() - const [state,setState] = useState(null) + const logger = useRef(new EventLogger('AppsSettings')).current - useEffect( ()=>{ - if (state?.initialized) - return; + const [apps, setApps] = useState(null) + const [expandedKey, setExpandedKey] = useState(null) - const apps = service.openSettings() - + // keeps the connection status of the entries up to date, whenever an app was (dis)connected + const refresh = useCallback( ()=>{ + setApps( service.openSettings() ) + },[service]) - setState({apps, initialized:true}) - },[service, state]) + useEffect( ()=>{ + refresh() + service.on('connected', refresh) + service.on('disconnected', refresh) - const onClick=(key) => { - setState( current=> ({...current, selected:key}) ) - } + return ()=>{ + service.off('connected', refresh) + service.off('disconnected', refresh) + } + },[service, refresh]) - const onBack=()=>{ - setState( current=> ({...current, selected:null}) ) + const onToggle = (key) => { + const expanded = expandedKey!==key + logger.logEvent({message:'app toggled', app:key, expanded, eventSource:'user'}) + setExpandedKey( expanded ? key : null) } - if (!state?.initialized ) - return null; - - if (state.selected && getMapping(state.selected)) - return - - return - - + if (!apps) + return null + return } -export const AppsSettingsView = ({apps,onClick}) => { +/** + * List of all apps (same UX as in the mobile app): every entry shows the name and the connection status + * and expands to the settings of the app. Only one entry is expanded at a time. + */ +export const AppsSettingsView = ({apps, expandedKey, onToggle, renderApp}) => { - const onClickHandler = (name) => { - if (onClick && typeof onClick==='function') { - onClick(name) - } - } - return ( - { apps?.length ? - apps.map( (app) => - onClickHandler(app.key)} /> - ) : - No Apps available + { apps?.length ? + apps.map( (app) => + onToggle?.(app.key)}> + {renderApp?.(app)} + + ) : + No Apps available } - ) - -} \ No newline at end of file +} diff --git a/src/components/modules/Settings/Apps/AppsSettings.stories.jsx b/src/components/modules/Settings/Apps/AppsSettings.stories.jsx index 8544d20..58097e0 100644 --- a/src/components/modules/Settings/Apps/AppsSettings.stories.jsx +++ b/src/components/modules/Settings/Apps/AppsSettings.stories.jsx @@ -1,33 +1,53 @@ -import styled from "styled-components"; -import { Row } from "../../../atoms"; -import { AppsSettingsView } from "./AppsSettings"; -import React from 'react' +import React, { useState } from 'react' +import styled from "styled-components" +import { Row } from "../../../atoms" +import { AppSettingsView } from "../../../molecules/Apps/AppSettingsView" +import { AppsSettingsView } from "./AppsSettings" -const View = styled(Row)` +const View = styled(Row)` width: 800px; height: 600px; overflow-y: hidden; -`; - +` export default { component: AppsSettingsView, - title: 'Modules/Settings/AppsSettings', - argTypes: { - onClick: { action: 'select' } , + title: 'Modules/Settings/AppsSettings', + argTypes: { + onToggle: { action: 'toggle' }, }, +} + +const apps = [ + { name: 'Strava', key: 'strava', isConnected: true }, + { name: 'Komoot', key: 'komoot', isConnected: false }, + { name: 'Intervals.icu', key: 'intervals', isConnected: false }, +] -}; +const operations = [ + { operation: 'ActivityUpload', enabled: true }, + { operation: 'RouteDownload', enabled: false }, +] -const Template = args => +const renderApp = (app) => -export const Default = Template.bind({}); -Default.args = { - apps: [ - { name:'Strava', key:'strava', iconUrl: 'https://static.cdnlogo.com/logos/s/42/strava-wordmark.svg' }, - { name:'VeloHero', key:'velohero', iconUrl: 'images/velo-white.png' }, - { name:'Komoot', key:'komoot', iconUrl:'https://www.komoot.com/assets/4d8ae313eec53e6e.svg' }, - ] +const Template = args => { + const [expandedKey, setExpandedKey] = useState(args.expandedKey) + const onToggle = (key) => setExpandedKey(current => current === key ? null : key) + + return + + } +export const Collapsed = Template.bind({}) +Collapsed.args = { apps } + +export const ConnectedExpanded = Template.bind({}) +ConnectedExpanded.args = { apps, expandedKey: 'strava' } + +export const NotConnectedExpanded = Template.bind({}) +NotConnectedExpanded.args = { apps, expandedKey: 'intervals' } +export const NoApps = Template.bind({}) +NoApps.args = { apps: [] } diff --git a/src/components/modules/Settings/Apps/AppsSettings.unit.test.jsx b/src/components/modules/Settings/Apps/AppsSettings.unit.test.jsx new file mode 100644 index 0000000..7e5468c --- /dev/null +++ b/src/components/modules/Settings/Apps/AppsSettings.unit.test.jsx @@ -0,0 +1,61 @@ +import React from 'react' +import { describe, test, expect, vi } from 'vitest' +import { render, screen, fireEvent } from '@testing-library/react' + +import { AppsSettingsView } from './AppsSettings' + +const apps = [ + { name: 'Strava', key: 'strava', isConnected: true }, + { name: 'Komoot', key: 'komoot', isConnected: false }, + { name: 'Intervals.icu', key: 'intervals', isConnected: false }, +] + +const renderApp = (app) =>
settings of {app.key}
+ +describe('AppsSettingsView', () => { + + test('lists all apps with their connection status', () => { + render() + + expect(screen.getByText('Strava')).toBeDefined() + expect(screen.getByText('Komoot')).toBeDefined() + expect(screen.getByText('Intervals.icu')).toBeDefined() + expect(screen.getAllByLabelText('Connected')).toHaveLength(1) + expect(screen.getAllByLabelText('Not connected')).toHaveLength(2) + }) + + test('shows the settings of the expanded app only', () => { + render() + + expect(screen.getByText('settings of komoot')).toBeDefined() + expect(screen.queryByText('settings of strava')).toBeNull() + expect(screen.queryByText('settings of intervals')).toBeNull() + }) + + test('shows no settings if nothing is expanded', () => { + render() + + expect(screen.queryByText(/settings of/)).toBeNull() + }) + + test('reports the key of the clicked app', () => { + const onToggle = vi.fn() + render() + + fireEvent.click(screen.getByText('Intervals.icu')) + + expect(onToggle).toHaveBeenCalledWith('intervals') + }) + + test('shows a hint if there are no apps', () => { + render() + + expect(screen.getByText('No Apps available')).toBeDefined() + }) + + test('handles missing apps', () => { + render() + + expect(screen.getByText('No Apps available')).toBeDefined() + }) +}) diff --git a/src/components/modules/Settings/Apps/Intervals/IntervalsSettings.jsx b/src/components/modules/Settings/Apps/Intervals/IntervalsSettings.jsx deleted file mode 100644 index e8ea428..0000000 --- a/src/components/modules/Settings/Apps/Intervals/IntervalsSettings.jsx +++ /dev/null @@ -1,138 +0,0 @@ -import React, { useState } from 'react' -import styled from "styled-components" -import { Button, Row, Text, View } from "../../../../atoms" -import { ArrowLeftIcon } from '@primer/octicons-react' -import { AppThemeProvider } from '../../../../../theme' -import { EventLogger } from 'gd-eventlog' -import { hasFeature } from '../../../../../utils/electron/integration' -import { OAuthBinding } from '../../../../../bindings' - -import { useAppsService } from 'incyclist-services' -import { OperationsSelector } from '../../../../molecules/Apps/OperationsSelector' - -export const IntervalsSettings = ({onBack})=> { - - const logger = new EventLogger('IntervalsSettings') - const [connecting,setConnecting] = useState(false) - const service = useAppsService() - - const [settings,setSettings] = useState( service.openAppSettings('intervals')) - - - const onConnect = async ()=>{ - - logger.logEvent({message:'onConnectIntervals'}) - if (hasFeature('oauth')) { - - setConnecting(true) - const res = await OAuthBinding.getInstance().authorize('intervals'); - - if (res.success) { - logger.logEvent({message:'onConnectIntervals succes', username:res.user.name}) - await service.connect('intervals', res.user?.auth?.intervals) - const settings = service.openAppSettings('intervals') - setSettings( current=> ({...current, ...settings}) ) - - - } - else { - logger.logEvent({message:'onConnectIntervals failed', reason:res.reason}) - } - setConnecting(false) - - } - } - - const onDisconnect = ()=>{ - service.disconnect('intervals') - setSettings( {isConnected:false}) - } - - const onOperationsChanged = (operation, enabled) => { - const operations = service.enableOperation('intervals',operation,enabled,true) - setSettings( current=> ({...current,operations} )) - } - - return - - -} - -const Container = styled(View)` - position: relative; -` - -const BackRow = styled(Row)` - position: absolute; - top: 0; - right: 0; - padding: 1vw - - color: ${props => props.theme.list.normal.text}; - background: ${props => props.theme.list.normal.background}; - - &:hover { - color: ${props => props.theme.list.hover.text}; - background: ${props => props.theme.list.hover.background}; - border-style: solid; - border-width: 1px; - border-color: white; - } - -` - -const Icon = styled(ArrowLeftIcon)` -` - -const Title = styled(Row)` - height: 32px; - font-size: 2.2vh; - padding: 1vw; - text-transform: uppercase; - - user-select: none; - pointer-events: none; - color: ${props => props.theme.title.text}; - background: ${props => props.theme.title.background}; - -` - -export const IntervalsSettingsView = ( {isConnected, isConnecting, operations, onBack, onConnect, onDisconnect,onOperationsChanged}) => { - - return - - - Intervals.icu Settings - - - - {isConnected ? -
- -
- : -
-
- } -
- - {isConnected ? - - - :null} - - - - - - -
-
- -} \ No newline at end of file diff --git a/src/components/modules/Settings/Apps/Intervals/IntervalsSettings.stories.jsx b/src/components/modules/Settings/Apps/Intervals/IntervalsSettings.stories.jsx deleted file mode 100644 index 0bc1602..0000000 --- a/src/components/modules/Settings/Apps/Intervals/IntervalsSettings.stories.jsx +++ /dev/null @@ -1,34 +0,0 @@ -import React from 'react' -import styled from "styled-components"; -import { IntervalsSettingsView } from "./IntervalsSettings"; -import { Row } from "../../../../atoms"; - -const View = styled(Row)` - width: 800px; - height: 600px; - overflow-y: hidden; -`; - - -export default { - component: IntervalsSettingsView, - title: 'Modules/Settings/Intervals.icu', - argTypes: { - onConnect: { action: 'connect' } , - onDisconnect: { action: 'discconnect' } , - onBack: {action:'back'} - }, - -}; - -const Template = args => - -export const Default = Template.bind({}); -Default.args = { - isConnected: false -} - -export const Connected = Template.bind({}); -Connected.args = { - isConnected: true -} \ No newline at end of file diff --git a/src/components/modules/Settings/Apps/Intervals/index.jsx b/src/components/modules/Settings/Apps/Intervals/index.jsx deleted file mode 100644 index bd9742e..0000000 --- a/src/components/modules/Settings/Apps/Intervals/index.jsx +++ /dev/null @@ -1 +0,0 @@ -export * from './IntervalsSettings' \ No newline at end of file diff --git a/src/components/modules/Settings/Apps/Komoot/KomootSettings.jsx b/src/components/modules/Settings/Apps/Komoot/KomootSettings.jsx index 701b0d9..23c5064 100644 --- a/src/components/modules/Settings/Apps/Komoot/KomootSettings.jsx +++ b/src/components/modules/Settings/Apps/Komoot/KomootSettings.jsx @@ -1,16 +1,37 @@ import React, { useRef, useState } from 'react' -import styled from "styled-components" -import { Button, Row, Text, View } from "../../../../atoms" -import { ArrowLeftIcon } from '@primer/octicons-react' -import { AppThemeProvider } from '../../../../../theme' -import { OperationsSelector } from '../../../../molecules/Apps/OperationsSelector' +import { AppSettingsView } from '../../../../molecules/Apps/AppSettingsView' import { DialogLauncher, KomootLoginDialog } from '../../../../molecules' import { useAppsService } from 'incyclist-services' import { useUnmountEffect } from '../../../../../hooks' const SERVICE = 'komoot' -export const KomootSettings = ({onBack})=> { +/** + * Reports the changes of the operations that were made while the settings were open (other services are interested in them). + * + * @param prev settings when the panel was opened + * @param current settings when the panel is closed + */ +const syncOperations = (service, prev, current) => { + const prevOperations = prev?.operations ?? [] + const currentOperations = current?.operations ?? [] + + if (prev?.isConnected && !current?.isConnected) { + prevOperations.forEach(op => { service.enableOperation(SERVICE, op.operation, false, true) }) + } + else if (!prev?.isConnected && current?.isConnected) { + currentOperations.filter(op => op.enabled).forEach(op => { service.enableOperation(SERVICE, op.operation, true, true) }) + } + else if (current?.isConnected) { + currentOperations.forEach((op, idx) => { + if (op.enabled !== prevOperations[idx]?.enabled) + service.enableOperation(SERVICE, op.operation, op.enabled, true) + }) + } + // not connected when opened and not connected when closed (e.g. connected and disconnected again): nothing has changed +} + +export const KomootSettings = ()=> { const [connecting,setConnecting] = useState(false) const service = useAppsService() @@ -57,7 +78,7 @@ export const KomootSettings = ({onBack})=> { const onDisconnect = ()=>{ service.disconnect(SERVICE) - setSettings( {isConnected:false}) + setSettings( current=> ({...current, isConnected:false})) } const onOperationsChanged = (operation, enabled) => { @@ -68,118 +89,14 @@ export const KomootSettings = ({onBack})=> { } useUnmountEffect( ()=>{ - - const prev = initialSettingsRef.current - const current = settings - - if (prev.isConnected && !current.isConnected) { - const {operations} = prev - operations.forEach( op=> { service.enableOperation(SERVICE,op.operation,false,true)}) - } - else if (!prev.isConnected && current.isConnected) { - const {operations} = current - operations.forEach( op=> { - if (op.enabled) - service.enableOperation(SERVICE,op.operation,true,true - )}) - } - else { - const {operations} = current - operations.forEach( (op,idx)=> { - const prevOp = prev.operations[idx] - if (op.enabled!==prevOp.enabled) - service.enableOperation(SERVICE,op.operation,op.enabled,true - )}) - - } - - + syncOperations(service, initialSettingsRef.current, settings) }) return <> - - - - - + } - -const Container = styled(View)` - position: relative; -` - -const BackRow = styled(Row)` - position: absolute; - top: 0; - right: 0; - padding: 1vw - - color: ${props => props.theme.list.normal.text}; - background: ${props => props.theme.list.normal.background}; - - &:hover { - color: ${props => props.theme.list.hover.text}; - background: ${props => props.theme.list.hover.background}; - border-style: solid; - border-width: 1px; - border-color: white; - } - -` - -const Icon = styled(ArrowLeftIcon)` -` - -const Title = styled(Row)` - height: 32px; - font-size: 2.2vh; - padding: 1vw; - text-transform: uppercase; - - user-select: none; - pointer-events: none; - color: ${props => props.theme.title.text}; - background: ${props => props.theme.title.background}; - -` - -export const VeloHeroSettingsView = ( {isConnected, isConnecting, operations, onBack, onConnect, onDisconnect,onOperationsChanged}) => { - - return - - - Komoot Settings - - - - {isConnected ? -
- -
- : -
-
- } -
- - {isConnected ? - - - :null} - - - - - - -
-
- -} \ No newline at end of file diff --git a/src/components/modules/Settings/Apps/Komoot/KomootSettings.unit.test.jsx b/src/components/modules/Settings/Apps/Komoot/KomootSettings.unit.test.jsx new file mode 100644 index 0000000..d991db9 --- /dev/null +++ b/src/components/modules/Settings/Apps/Komoot/KomootSettings.unit.test.jsx @@ -0,0 +1,134 @@ +import React from 'react' +import { describe, test, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, act } from '@testing-library/react' + +const { launched } = vi.hoisted(() => ({ launched: { props: null } })) + +let state +const operations = () => [{ operation: 'ActivityUpload', enabled: true }, { operation: 'RouteDownload', enabled: false }] + +const service = { + openAppSettings: vi.fn(() => state.settings), + connect: vi.fn(async () => { state.settings = { isConnected: true, operations: state.operations }; return true }), + disconnect: vi.fn(() => { state.settings = { isConnected: false, operations: state.operations } }), + enableOperation: vi.fn((_app, operation, enabled) => { + state.operations = state.operations.map(op => op.operation === operation ? { ...op, enabled } : op) + return state.operations + }), +} + +vi.mock('incyclist-services', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, useAppsService: () => service } +}) + +vi.mock('../../../../molecules', async () => { + const React = await import('react') + return { + DialogLauncher: React.forwardRef((_props, ref) => { + React.useImperativeHandle(ref, () => ({ + openDialog: (_Dialog, props) => { launched.props = props }, + closeDialog: () => { launched.props = null } + })) + return null + }), + KomootLoginDialog: () => null, + } +}) + +import { KomootSettings } from './KomootSettings' + +const setup = (isConnected) => { + state = { operations: operations(), settings: undefined } + state.settings = { isConnected, operations: state.operations } + service.enableOperation.mockClear() + return render() +} + +const login = async () => { + fireEvent.click(screen.getByText('Connect with Komoot')) + await act(async () => { launched.props.onOK({ username: 'user', password: 'pw' }, vi.fn()) }) +} + +describe('KomootSettings', () => { + + beforeEach(() => { + vi.clearAllMocks() + launched.props = null + }) + + describe('closing the panel (reports the changes of the operations)', () => { + + // review comment: connect, disconnect and collapse the row threw "forEach of undefined" + test('connected and disconnected again within one session: no error, nothing is reported', async () => { + const { unmount } = setup(false) + + await login() + expect(screen.getByText('Disconnect')).toBeDefined() + fireEvent.click(screen.getByText('Disconnect')) + + expect(() => unmount()).not.toThrow() + expect(service.enableOperation).not.toHaveBeenCalled() + }) + + test('the operations are kept when disconnecting (and shown again after connecting again)', async () => { + setup(false) + + await login() + expect(screen.getByLabelText('Activity Upload')).toBeDefined() + fireEvent.click(screen.getByText('Disconnect')) + expect(screen.queryByLabelText('Activity Upload')).toBeNull() + await login() + + expect(screen.getByLabelText('Activity Upload')).toBeDefined() + expect(screen.getByLabelText('Route Download')).toBeDefined() + }) + + test('disconnected while the panel was open: all operations are reported as disabled', () => { + const { unmount } = setup(true) + + fireEvent.click(screen.getByText('Disconnect')) + unmount() + + expect(service.enableOperation).toHaveBeenCalledTimes(2) + expect(service.enableOperation).toHaveBeenCalledWith('komoot', 'ActivityUpload', false, true) + expect(service.enableOperation).toHaveBeenCalledWith('komoot', 'RouteDownload', false, true) + }) + + test('connected while the panel was open: the enabled operations are reported', async () => { + const { unmount } = setup(false) + + await login() + unmount() + + expect(service.enableOperation).toHaveBeenCalledTimes(1) + expect(service.enableOperation).toHaveBeenCalledWith('komoot', 'ActivityUpload', true, true) + }) + + test('an operation was changed while connected: only the change is reported', () => { + const { unmount } = setup(true) + + fireEvent.click(screen.getByLabelText('Route Download')) + service.enableOperation.mockClear() + unmount() + + expect(service.enableOperation).toHaveBeenCalledTimes(1) + expect(service.enableOperation).toHaveBeenCalledWith('komoot', 'RouteDownload', true, true) + }) + + test('nothing was changed: nothing is reported', () => { + const { unmount } = setup(true) + + unmount() + + expect(service.enableOperation).not.toHaveBeenCalled() + }) + + test('never connected: nothing is reported', () => { + const { unmount } = setup(false) + + expect(() => unmount()).not.toThrow() + expect(service.enableOperation).not.toHaveBeenCalled() + }) + }) +}) diff --git a/src/components/modules/Settings/Apps/OAuthAppSettings.jsx b/src/components/modules/Settings/Apps/OAuthAppSettings.jsx new file mode 100644 index 0000000..e19d42c --- /dev/null +++ b/src/components/modules/Settings/Apps/OAuthAppSettings.jsx @@ -0,0 +1,75 @@ +import React, { useEffect, useRef, useState } from 'react' +import { EventLogger } from 'gd-eventlog' +import { useAppsService } from 'incyclist-services' +import { hasFeature } from '../../../../utils/electron/integration' +import { OAuthBinding } from '../../../../bindings' +import { AppSettingsView } from '../../../molecules/Apps/AppSettingsView' + +/** + * Settings of an app that is connected through the OAuth flow of the auth-server (Strava, Intervals.icu, ...) + */ +export const OAuthAppSettings = ({ appKey, name, connectImage }) => { + + const logger = useRef(new EventLogger('OAuthAppSettings')).current + const service = useAppsService() + + const [connecting, setConnecting] = useState(false) + const [settings, setSettings] = useState(() => service.openAppSettings(appKey)) + + // The panel is closed (and opened again) while a connection can still be in progress, so the state of the service + // has to be followed: otherwise a connection that finishes while the panel was closed is not shown + useEffect(() => { + const refresh = (app) => { + if (app === appKey) + setSettings(current => ({ ...current, ...service.openAppSettings(appKey) })) + } + + service.on('connected', refresh) + service.on('disconnected', refresh) + + return () => { + service.off('connected', refresh) + service.off('disconnected', refresh) + } + }, [service, appKey]) + + const onConnect = async () => { + if (!hasFeature('oauth')) + return + + try { + logger.logEvent({ message: 'connect', app: appKey }) + setConnecting(true) + + const res = await OAuthBinding.getInstance().authorize(appKey) + + if (res.success) { + logger.logEvent({ message: 'connect success', app: appKey }) + await service.connect(appKey, res.user?.auth?.[appKey]) + setSettings(current => ({ ...current, ...service.openAppSettings(appKey) })) + } + else { + logger.logEvent({ message: 'connect failed', app: appKey, reason: res.reason }) + } + } + catch (err) { + logger.logEvent({ message: 'error', fn: 'onConnect', app: appKey, error: err.message, stack: err.stack }) + } + finally { + setConnecting(false) + } + } + + const onDisconnect = () => { + service.disconnect(appKey) + setSettings(current => ({ ...current, isConnected: false })) + } + + const onOperationsChanged = (operation, enabled) => { + const operations = service.enableOperation(appKey, operation, enabled, true) + setSettings(current => ({ ...current, operations })) + } + + return +} diff --git a/src/components/modules/Settings/Apps/OAuthAppSettings.unit.test.jsx b/src/components/modules/Settings/Apps/OAuthAppSettings.unit.test.jsx new file mode 100644 index 0000000..b509224 --- /dev/null +++ b/src/components/modules/Settings/Apps/OAuthAppSettings.unit.test.jsx @@ -0,0 +1,205 @@ +import React from 'react' +import { describe, test, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, act } from '@testing-library/react' + +const { events, authorize, features } = vi.hoisted(() => ({ + events: { handlers: {} }, + authorize: { fn: null }, + features: { oauth: true } +})) + +let state +const operations = () => [{ operation: 'ActivityUpload', enabled: true }] + +const service = { + openAppSettings: vi.fn(() => state.settings), + connect: vi.fn(async (app) => { + state.settings = { isConnected: true, operations: state.operations } + service.emit('connected', app, true) + return true + }), + disconnect: vi.fn((app) => { + state.settings = { isConnected: false, operations: state.operations } + service.emit('disconnected', app) + }), + enableOperation: vi.fn(() => state.operations), + on: vi.fn((event, handler) => { (events.handlers[event] ??= []).push(handler) }), + off: vi.fn((event, handler) => { events.handlers[event] = (events.handlers[event] ?? []).filter(h => h !== handler) }), + emit: (event, ...args) => { [...(events.handlers[event] ?? [])].forEach(h => h(...args)) }, +} + +vi.mock('incyclist-services', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, useAppsService: () => service } +}) +vi.mock('../../../../utils/electron/integration', () => ({ hasFeature: (feature) => features[feature] })) +vi.mock('../../../../bindings', () => ({ + OAuthBinding: { getInstance: () => ({ authorize: (...args) => authorize.fn(...args) }) } +})) + +import { OAuthAppSettings } from './OAuthAppSettings' + +const setup = (isConnected, appKey = 'strava', name = 'Strava') => { + state = { operations: operations(), settings: { isConnected, operations: operations() } } + return render() +} + +/** the state of the service changes without any action in the panel (e.g. a connection that finishes after the row was collapsed) */ +const changeInBackground = (event, isConnected, app = 'strava') => { + state.settings = { isConnected, operations: state.operations } + act(() => { service.emit(event, app, true) }) +} + +describe('OAuthAppSettings', () => { + + beforeEach(() => { + vi.clearAllMocks() + events.handlers = {} + features.oauth = true + authorize.fn = vi.fn() + }) + + describe('follows the state of the service', () => { + + // review comment: reopen the row before OAuth finished -> the dot was green, but the button still said "Connect" + test('a connection that finishes while the panel is open is shown', () => { + setup(false) + expect(screen.getByText('Connect with Strava')).toBeDefined() + + changeInBackground('connected', true) + + expect(screen.queryByText('Connect with Strava')).toBeNull() + expect(screen.getByText('Disconnect')).toBeDefined() + expect(screen.getByLabelText('Activity Upload')).toBeDefined() + }) + + test('a disconnect from somewhere else is shown', () => { + setup(true) + expect(screen.getByText('Disconnect')).toBeDefined() + + changeInBackground('disconnected', false) + + expect(screen.getByText('Connect with Strava')).toBeDefined() + expect(screen.queryByText('Disconnect')).toBeNull() + }) + + test('events of other apps are ignored', () => { + setup(false) + + changeInBackground('connected', true, 'komoot') + + expect(screen.getByText('Connect with Strava')).toBeDefined() + }) + + test('stops following the service when the panel is closed', () => { + const { unmount } = setup(false) + expect(events.handlers.connected).toHaveLength(1) + expect(events.handlers.disconnected).toHaveLength(1) + + unmount() + + expect(events.handlers.connected).toHaveLength(0) + expect(events.handlers.disconnected).toHaveLength(0) + service.openAppSettings.mockClear() + service.emit('connected', 'strava', true) + expect(service.openAppSettings).not.toHaveBeenCalled() + }) + + test('a panel that is opened again shows the current state', () => { + const first = setup(false) + first.unmount() + state.settings = { isConnected: true, operations: state.operations } + + render() + + expect(screen.getByText('Disconnect')).toBeDefined() + }) + + test('the title of the app is used for the connect button (app provided by the service)', () => { + setup(false, 'trainingpeaks', 'TrainingPeaks') + + expect(screen.getByText('Connect with TrainingPeaks')).toBeDefined() + }) + }) + + describe('connect', () => { + + test('connects with the credentials of the auth-server', async () => { + setup(false) + const credentials = { id: 1, accesstoken: 'at', refreshtoken: 'rt', expiration: '1' } + authorize.fn.mockResolvedValue({ success: true, user: { auth: { strava: credentials } } }) + + await act(async () => { fireEvent.click(screen.getByText('Connect with Strava')) }) + + expect(authorize.fn).toHaveBeenCalledWith('strava') + expect(service.connect).toHaveBeenCalledWith('strava', credentials) + expect(screen.getByText('Disconnect')).toBeDefined() + }) + + test('shows the progress while the user authorizes', async () => { + setup(false) + let finish + authorize.fn.mockReturnValue(new Promise(resolve => { finish = resolve })) + + await act(async () => { fireEvent.click(screen.getByText('Connect with Strava')) }) + expect(screen.getByText('Connecting...')).toBeDefined() + + await act(async () => { finish({ success: false, reason: 'cancelled' }) }) + expect(screen.queryByText('Connecting...')).toBeNull() + expect(screen.getByText('Connect with Strava')).toBeDefined() + }) + + test('authorization failed: not connected', async () => { + setup(false) + authorize.fn.mockResolvedValue({ success: false, reason: 'denied' }) + + await act(async () => { fireEvent.click(screen.getByText('Connect with Strava')) }) + + expect(service.connect).not.toHaveBeenCalled() + expect(screen.getByText('Connect with Strava')).toBeDefined() + }) + + test('authorization throws: not connected, the panel is usable again', async () => { + setup(false) + authorize.fn.mockRejectedValue(new Error('ERROR')) + + await act(async () => { fireEvent.click(screen.getByText('Connect with Strava')) }) + + expect(service.connect).not.toHaveBeenCalled() + expect(screen.getByText('Connect with Strava')).toBeDefined() + }) + + test('not supported by this platform (feature oauth): nothing happens', async () => { + features.oauth = false + setup(false) + + await act(async () => { fireEvent.click(screen.getByText('Connect with Strava')) }) + + expect(authorize.fn).not.toHaveBeenCalled() + }) + }) + + describe('disconnect and operations', () => { + + test('disconnects and keeps the operations for the next connect', async () => { + setup(true) + + fireEvent.click(screen.getByText('Disconnect')) + + expect(service.disconnect).toHaveBeenCalledWith('strava') + expect(screen.getByText('Connect with Strava')).toBeDefined() + + authorize.fn.mockResolvedValue({ success: true, user: { auth: { strava: { accesstoken: 'a' } } } }) + await act(async () => { fireEvent.click(screen.getByText('Connect with Strava')) }) + expect(screen.getByLabelText('Activity Upload')).toBeDefined() + }) + + test('a changed operation is passed on to the service', () => { + setup(true) + + fireEvent.click(screen.getByLabelText('Activity Upload')) + + expect(service.enableOperation).toHaveBeenCalledWith('strava', 'ActivityUpload', false, true) + }) + }) +}) diff --git a/src/components/modules/Settings/Apps/Strava/StravaSettings.jsx b/src/components/modules/Settings/Apps/Strava/StravaSettings.jsx deleted file mode 100644 index c702e05..0000000 --- a/src/components/modules/Settings/Apps/Strava/StravaSettings.jsx +++ /dev/null @@ -1,145 +0,0 @@ -import React, { useState } from 'react' -import styled from "styled-components" -import { Button, Row, Text, View } from "../../../../atoms" -import { ArrowLeftIcon } from '@primer/octicons-react' -import { AppThemeProvider } from '../../../../../theme' -import { EventLogger } from 'gd-eventlog' -import { hasFeature } from '../../../../../utils/electron/integration' -import { OAuthBinding} from '../../../../../bindings' -import { useAppsService } from 'incyclist-services' -import { OperationsSelector } from '../../../../molecules/Apps/OperationsSelector' - -export const StravaSettings = ({onBack})=> { - - const logger = new EventLogger('StravaSettings') - const [connecting,setConnecting] = useState(false) - const service = useAppsService() - - const [settings,setSettings] = useState( service.openAppSettings('strava')) - - - const onConnect = async ()=>{ - - try { - logger.logEvent({message:'onConnectStrava'}) - if (hasFeature('oauth')) { - - setConnecting(true) - const res = await OAuthBinding.getInstance().authorize('strava'); - - if (res.success) { - logger.logEvent({message:'onConnectStrava succes', username:res.user.name}) - await service.connect('strava', res.user?.auth?.strava) - const settings = service.openAppSettings('strava') - setSettings( current=> ({...current, ...settings}) ) - - - } - else { - logger.logEvent({message:'onConnectStrava failed', reason:res.reason}) - } - setConnecting(false) - - } - } - catch(err) { - logger.logEvent({message:'error', fn:'onConnect', error:err.message, stack:err.stack}) - } - } - - const onDisconnect = ()=>{ - service.disconnect('strava') - setSettings( {isConnected:false}) - } - - const onOperationsChanged = (operation, enabled) => { - const operations = service.enableOperation('strava',operation,enabled,true ) - setSettings( current=> ({...current,operations} )) - } - - return - - -} - -const Container = styled(View)` - position: relative; -` - -const BackRow = styled(Row)` - position: absolute; - top: 0; - right: 0; - padding: 1vw - - color: ${props => props.theme.list.normal.text}; - background: ${props => props.theme.list.normal.background}; - - &:hover { - color: ${props => props.theme.list.hover.text}; - background: ${props => props.theme.list.hover.background}; - border-style: solid; - border-width: 1px; - border-color: white; - } - -` - -const Icon = styled(ArrowLeftIcon)` -` - -const Title = styled(Row)` - height: 32px; - font-size: 2.2vh; - padding: 1vw; - text-transform: uppercase; - - user-select: none; - pointer-events: none; - color: ${props => props.theme.title.text}; - background: ${props => props.theme.title.background}; - -` - -export const StravaSettingsView = ( {isConnected, isConnecting, operations, onBack, onConnect, onDisconnect,onOperationsChanged}) => { - - return - - - Strava Settings - - - - {isConnected ? -
- -
- : -
- -
- } -
- - {isConnected ? - - - :null} - - - - - - -
-
- -} \ No newline at end of file diff --git a/src/components/modules/Settings/Apps/Strava/StravaSettings.stories.jsx b/src/components/modules/Settings/Apps/Strava/StravaSettings.stories.jsx deleted file mode 100644 index c3e4bf3..0000000 --- a/src/components/modules/Settings/Apps/Strava/StravaSettings.stories.jsx +++ /dev/null @@ -1,34 +0,0 @@ -import React from 'react' -import styled from "styled-components"; -import { StravaSettingsView } from "./StravaSettings"; -import { Row } from "../../../../atoms"; - -const View = styled(Row)` - width: 800px; - height: 600px; - overflow-y: hidden; -`; - - -export default { - component: StravaSettingsView, - title: 'Modules/Settings/Strava', - argTypes: { - onConnect: { action: 'connect' } , - onDisconnect: { action: 'discconnect' } , - onBack: {action:'back'} - }, - -}; - -const Template = args => - -export const Default = Template.bind({}); -Default.args = { - isConnected: false -} - -export const Connected = Template.bind({}); -Connected.args = { - isConnected: true -} diff --git a/src/components/modules/Settings/Apps/Strava/index.jsx b/src/components/modules/Settings/Apps/Strava/index.jsx deleted file mode 100644 index 0da88cb..0000000 --- a/src/components/modules/Settings/Apps/Strava/index.jsx +++ /dev/null @@ -1 +0,0 @@ -export * from './StravaSettings' \ No newline at end of file diff --git a/src/components/molecules/Apps/AppSettingsView/AppSettingsView.jsx b/src/components/molecules/Apps/AppSettingsView/AppSettingsView.jsx new file mode 100644 index 0000000..16e80a0 --- /dev/null +++ b/src/components/molecules/Apps/AppSettingsView/AppSettingsView.jsx @@ -0,0 +1,50 @@ +import React from 'react' +import styled from 'styled-components' +import { Button, Text } from '../../../atoms' +import AppTheme, { AppThemeProvider } from '../../../../theme' +import { OperationsSelector } from '../OperationsSelector' + +const Content = styled.div` + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 1.6vh; +` + +const ConnectArea = styled.div` + display: flex; + align-items: center; + min-height: 4.4vh; +` + +/** + * Connect/disconnect and operation settings of a single app, shown inside the expanded + * entry of the Apps list. + * + * @param {string} name display name of the app + * @param {string} [connectImage] optional brand image (e.g. "Connect with Strava") that is used as connect button + */ +export const AppSettingsView = ({ name, isConnected, isConnecting, operations, connectImage, onConnect, onDisconnect, onOperationsChanged }) => { + + const renderConnect = () => { + if (isConnecting) + return + + if (isConnected) + return + + return