diff --git a/src/components/Challenge/AvailableChallengeDetailsView.tsx b/src/components/Challenge/AvailableChallengeDetailsView.tsx index e9f1a0d43cf5d274fa46136218ff4ab694140134..52e13af773348070e42e1baf886c7c63c3f41751 100644 --- a/src/components/Challenge/AvailableChallengeDetailsView.tsx +++ b/src/components/Challenge/AvailableChallengeDetailsView.tsx @@ -1,7 +1,7 @@ import React, { useState, useEffect, useCallback } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { Redirect } from 'react-router-dom' -import { Client, withClient } from 'cozy-client' import { useRecoilState, useRecoilValue } from 'recoil' import { DateTime } from 'luxon' import { Location } from 'history' @@ -26,15 +26,14 @@ import AvailableChallengeIcon from 'assets/png/badges/available-big.png' interface AvailableChallengeDetailsViewProps { location: Location<ChallengeType> - client: Client - t: Function } const AvailableChallengeDetailsView: React.FC<AvailableChallengeDetailsViewProps> = ({ location, - client, - t, }: AvailableChallengeDetailsViewProps) => { + const { t } = useI18n() + const client = useClient() + const screenType = useRecoilValue(screenTypeState) const fluidTypes = useRecoilValue(fluidTypeState) const [userProfile, setUserProfile] = useRecoilState<UserProfile>( @@ -214,4 +213,4 @@ const AvailableChallengeDetailsView: React.FC<AvailableChallengeDetailsViewProps ) } -export default translate()(withClient(AvailableChallengeDetailsView)) +export default AvailableChallengeDetailsView diff --git a/src/components/Challenge/ChallengeCardLink.tsx b/src/components/Challenge/ChallengeCardLink.tsx index fb3aa21b359ba0f354535340b0d4c1938a9e7126..7dada7a8073276c6bd52252fb67e76a628740b5c 100644 --- a/src/components/Challenge/ChallengeCardLink.tsx +++ b/src/components/Challenge/ChallengeCardLink.tsx @@ -1,18 +1,11 @@ import React from 'react' -import { Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { useRecoilValue } from 'recoil' import { currentChallengeState } from 'atoms/challenge.state' import ChallengeCardLinkItem from 'components/Challenge/ChallengeCardLinkItem' -interface ChallengeCardLinkProps { - t: Function - client: Client -} - -const ChallengeCardLink: React.FC<ChallengeCardLinkProps> = ({ - t, -}: ChallengeCardLinkProps) => { +const ChallengeCardLink: React.FC = () => { + const { t } = useI18n() const currentChallenge = useRecoilValue(currentChallengeState) return ( <> @@ -30,4 +23,4 @@ const ChallengeCardLink: React.FC<ChallengeCardLinkProps> = ({ ) } -export default translate()(ChallengeCardLink) +export default ChallengeCardLink diff --git a/src/components/Challenge/ChallengeCardLinkItem.tsx b/src/components/Challenge/ChallengeCardLinkItem.tsx index 2a5c53309ce226581b67d3295011b2d5e798687f..650ab10de2098122e4d2b1aecc2f94e210d17ca9 100644 --- a/src/components/Challenge/ChallengeCardLinkItem.tsx +++ b/src/components/Challenge/ChallengeCardLinkItem.tsx @@ -1,5 +1,4 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' import { NavLink } from 'react-router-dom' import { useRecoilValue } from 'recoil' @@ -80,4 +79,4 @@ const ChallengeCardLinkItem: React.FC<ChallengeCardLinkItemProps> = ({ ) } -export default translate()(ChallengeCardLinkItem) +export default ChallengeCardLinkItem diff --git a/src/components/Challenge/ChallengeList.tsx b/src/components/Challenge/ChallengeList.tsx index 095c044d250e60820a567e28003375bfd5ec96e0..87fa86592402ff5c71f7c0507bc9810c64ce8d52 100644 --- a/src/components/Challenge/ChallengeList.tsx +++ b/src/components/Challenge/ChallengeList.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { withClient, Client } from 'cozy-client' +import { useClient } from 'cozy-client' import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil' import { ChallengeState } from 'enum/challenge.enum' @@ -15,13 +15,8 @@ import StyledChallengeSpinner from 'components/CommonKit/Spinner/StyledChallenge import ChallengeListItem from 'components/Challenge/ChallengeListItem' import ChallengeModal from 'components/Challenge/ChallengeModal' -interface ChallengeListProps { - client: Client -} - -const ChallengeList: React.FC<ChallengeListProps> = ({ - client, -}: ChallengeListProps) => { +const ChallengeList: React.FC = () => { + const client = useClient() const screenType = useRecoilValue(screenTypeState) const fluidTypes = useRecoilValue(fluidTypeState) const [challengeNotification, setChallengeNotification] = useRecoilState( @@ -186,29 +181,25 @@ const ChallengeList: React.FC<ChallengeListProps> = ({ ) )} {userChallenges && - userChallenges.map((challenge, index) => - challenge && challenge.state === 0 ? ( - <ChallengeListItem - key={index} - challenge={challenge.challengeType} - userChallenge={challenge} - challengeState="ongoing" - /> - ) : ( - <ChallengeListItem - key={index} - challenge={challenge.challengeType} - userChallenge={challenge} - challengeState="finished" - badgeStatus={challenge.badge} - /> - ) - )} + userChallenges.map((challenge, index) => ( + <ChallengeListItem + key={index} + challenge={ + challenge.challengeType + ? challenge.challengeType + : undefined + } + userChallenge={challenge} + challengeState={ + challenge.state === 0 ? 'ongoing' : 'finished' + } + /> + ))} </div> </div> </div> )} - {openChallengeModal && ( + {openChallengeModal && ongoingChallengeModal && ( <ChallengeModal opened={openChallengeModal} challenge={ongoingChallengeModal} @@ -220,4 +211,4 @@ const ChallengeList: React.FC<ChallengeListProps> = ({ ) } -export default withClient(ChallengeList) +export default ChallengeList diff --git a/src/components/Challenge/ChallengeListItem.tsx b/src/components/Challenge/ChallengeListItem.tsx index 492744223286b21767ce8b2f238a92d4f432ce2f..3052184a9432ad7c9817b1d1242e9613ec7b5653 100644 --- a/src/components/Challenge/ChallengeListItem.tsx +++ b/src/components/Challenge/ChallengeListItem.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { NavLink } from 'react-router-dom' import { ChallengeType, Ecogesture, UserChallenge } from 'models' @@ -14,10 +14,9 @@ import OngoingChallengeIcon from 'assets/png/badges/ongoing.png' import DefaultChallengeIcon from 'assets/png/badges/default.png' interface ChallengeListItemProps { - challenge: ChallengeType + challenge?: ChallengeType userChallenge?: UserChallenge handleClick?: (challenge: ChallengeType) => void - t: Function challengeState?: string ecogestures?: Ecogesture[] } @@ -25,9 +24,9 @@ interface ChallengeListItemProps { const ChallengeListItem: React.FC<ChallengeListItemProps> = ({ challenge, userChallenge, - t, challengeState, }: ChallengeListItemProps) => { + const { t } = useI18n() const [badgeIcon, setBadgeIcon] = useState<string | undefined>() async function importRightBadge(id: string, badgeStatus: number) { @@ -100,9 +99,9 @@ const ChallengeListItem: React.FC<ChallengeListItemProps> = ({ </div> )} <div className={`title-${challengeState} text-18-bold`}> - {!challenge.title - ? t('CHALLENGE.NO_CHALLENGE') - : challenge.title} + {challenge && challenge.title + ? challenge.title + : t('CHALLENGE.NO_CHALLENGE')} </div> </div> </div> @@ -121,4 +120,4 @@ const ChallengeListItem: React.FC<ChallengeListItemProps> = ({ ) } -export default translate()(ChallengeListItem) +export default ChallengeListItem diff --git a/src/components/Challenge/ChallengeModal.tsx b/src/components/Challenge/ChallengeModal.tsx index 6e8c3e61b963bf614afc2fcb9ae42eab824189cd..2183f93578eb9c2c0a295704e4124ef57dcebdce 100644 --- a/src/components/Challenge/ChallengeModal.tsx +++ b/src/components/Challenge/ChallengeModal.tsx @@ -1,5 +1,5 @@ import React, { useState } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { useRecoilValue } from 'recoil' import { ScreenType } from 'enum/screen.enum' @@ -16,7 +16,6 @@ import StyledIcon from 'components/CommonKit/Icon/StyledIcon' interface ChallengeModalProps { opened: boolean challenge: UserChallenge - t: Function handleCloseClick: () => void badgeStatus: number | null } @@ -24,14 +23,14 @@ interface ChallengeModalProps { const ChallengeModal: React.FC<ChallengeModalProps> = ({ opened, challenge, - t, handleCloseClick, badgeStatus, }: ChallengeModalProps) => { + const { t } = useI18n() const screenType = useRecoilValue(screenTypeState) const [badgeIcon, setBadgeIcon] = useState<string | null>(null) - async function importRightBadge(id: string, badgeStatus: number) { + async function importRightBadge(id: string, _badgeStatus: number) { // Les png doivent être au format idchallenge-badgestate.png const importedBadge = id === 'CHA00000001' @@ -39,12 +38,12 @@ const ChallengeModal: React.FC<ChallengeModalProps> = ({ /* webpackMode: "eager" */ `assets/png/badges/${id}-1.png` ) : await import( - /* webpackMode: "eager" */ `assets/png/badges/${id}-${badgeStatus}.png` + /* webpackMode: "eager" */ `assets/png/badges/${id}-${_badgeStatus}.png` ) setBadgeIcon(importedBadge.default) } - const showTheRightBadge = (badgeStatus: number | null) => { + const showTheRightBadge = (_badgeStatus: number | null) => { const result = challenge && formatNumberValues( @@ -56,7 +55,7 @@ const ChallengeModal: React.FC<ChallengeModalProps> = ({ const badge = challenge.badge ? challenge.badge : 0 importRightBadge(challengeId, badge) if (badgeIcon) { - if (badgeStatus === 1) { + if (_badgeStatus === 1) { return ( <> <div className="cm-title win text-24-bold "> @@ -161,4 +160,4 @@ const ChallengeModal: React.FC<ChallengeModalProps> = ({ ) } -export default translate()(ChallengeModal) +export default ChallengeModal diff --git a/src/components/Challenge/ChallengePile.tsx b/src/components/Challenge/ChallengePile.tsx index 8da4a4ef7e765a00d8a1ead84befb52fe49019a3..47eaa7d6622af76fc0f28ec39765381d44a3e934 100644 --- a/src/components/Challenge/ChallengePile.tsx +++ b/src/components/Challenge/ChallengePile.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { UserChallenge } from 'models' import { formatNumberValues } from 'utils/utils' @@ -10,14 +10,13 @@ import StyledIcon from 'components/CommonKit/Icon/StyledIcon' interface ChallengePileProps { challenge: UserChallenge small?: boolean - t: Function } const ChallengePile: React.FC<ChallengePileProps> = ({ challenge, small = false, - t, }: ChallengePileProps) => { + const { t } = useI18n() const [pilePercent, setPilePercent] = useState<number>(0) const sizePile = small ? 100 : 150 const textFont = small ? 'text-17-bold' : 'text-20-bold' @@ -77,4 +76,4 @@ const ChallengePile: React.FC<ChallengePileProps> = ({ ) } -export default translate()(ChallengePile) +export default ChallengePile diff --git a/src/components/Challenge/ChallengeTimeline.tsx b/src/components/Challenge/ChallengeTimeline.tsx index d9a33bd68362f1b950776f500acfd0b4af5f5f7a..55e41e7ef637deb523258fdaf47c00159c3e7caf 100644 --- a/src/components/Challenge/ChallengeTimeline.tsx +++ b/src/components/Challenge/ChallengeTimeline.tsx @@ -1,6 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' -import { Client } from 'cozy-client' +import { useClient } from 'cozy-client' import { DateTime, Interval } from 'luxon' import { UserChallenge } from 'models' @@ -8,13 +7,12 @@ import ChallengeService from 'services/challenge.service' interface ChallengeTimelineViewProps { challenge: UserChallenge - client: Client } const ChallengeTimeline: React.FC<ChallengeTimelineViewProps> = ({ challenge, - client, }: ChallengeTimelineViewProps) => { + const client = useClient() const challengeService = new ChallengeService(client) const viewingDate = () => { @@ -170,4 +168,4 @@ const ChallengeTimeline: React.FC<ChallengeTimelineViewProps> = ({ ) } -export default translate()(ChallengeTimeline) +export default ChallengeTimeline diff --git a/src/components/Challenge/ChallengeViewingDate.tsx b/src/components/Challenge/ChallengeViewingDate.tsx index a310001d2e7684792663134d7e6720f09c2e71de..4e206b3d13e6ed1f42066dba6bdbadc8dff71749 100644 --- a/src/components/Challenge/ChallengeViewingDate.tsx +++ b/src/components/Challenge/ChallengeViewingDate.tsx @@ -1,6 +1,6 @@ import React, { useState, useEffect } from 'react' -import { translate } from 'cozy-ui/react/I18n' -import { Client, withClient } from 'cozy-client' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { DateTime } from 'luxon' import { UserChallenge } from 'models' @@ -8,15 +8,13 @@ import ChallengeService from 'services/challenge.service' interface ChallengeViewingDateProps { challenge: UserChallenge - client: Client - t: Function } const ChallengeViewingDate: React.FC<ChallengeViewingDateProps> = ({ challenge, - client, - t, }: ChallengeViewingDateProps) => { + const { t } = useI18n() + const client = useClient() const challengeService = new ChallengeService(client) const [firstDateWithData, setFirstDateWithData] = useState<DateTime | null>( null @@ -48,6 +46,7 @@ const ChallengeViewingDate: React.FC<ChallengeViewingDateProps> = ({ <React.Fragment> {firstDateWithData && firstDateWithData > DateTime.local() && + diffDays && diffDays > 0 ? ( <div className="view-start-date"> {t('CHALLENGE.VIEW_START', { @@ -65,4 +64,4 @@ const ChallengeViewingDate: React.FC<ChallengeViewingDateProps> = ({ ) } -export default translate()(withClient(ChallengeViewingDate)) +export default ChallengeViewingDate diff --git a/src/components/Challenge/FinishedChallengeDetailsView.tsx b/src/components/Challenge/FinishedChallengeDetailsView.tsx index 0bc37f30ac7b5971f1f3764354e407fcc974fbe0..cda865df439ee7363d7ba1c283186045059057aa 100644 --- a/src/components/Challenge/FinishedChallengeDetailsView.tsx +++ b/src/components/Challenge/FinishedChallengeDetailsView.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { Redirect } from 'react-router-dom' import { useRecoilValue } from 'recoil' import { Location } from 'history' @@ -20,14 +20,12 @@ import EcogestureCard from 'components/Ecogesture/EcogestureCard' interface FinishedChallengeDetailsViewProps { location: Location<UserChallenge> - props: object - t: Function } const FinishedChallengeDetailsView: React.FC<FinishedChallengeDetailsViewProps> = ({ location, - t, }: FinishedChallengeDetailsViewProps) => { + const { t } = useI18n() const userChallengeState = location.state const screenType = useRecoilValue(screenTypeState) const [challengeEcogesture, setChallengeEcogesture] = useState<number>(0) @@ -177,4 +175,4 @@ const FinishedChallengeDetailsView: React.FC<FinishedChallengeDetailsViewProps> ) } -export default translate()(FinishedChallengeDetailsView) +export default FinishedChallengeDetailsView diff --git a/src/components/Challenge/LockedChallengeDetailsViewContainer.tsx b/src/components/Challenge/LockedChallengeDetailsViewContainer.tsx index d975065c7bf49d6f21f5d6a10ec24196e9cec63e..858e0161db84fccacb812c5802f1955ee755f3e0 100644 --- a/src/components/Challenge/LockedChallengeDetailsViewContainer.tsx +++ b/src/components/Challenge/LockedChallengeDetailsViewContainer.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { Redirect } from 'react-router-dom' import { useRecoilValue } from 'recoil' import { Location } from 'history' @@ -18,13 +18,12 @@ import LockedChallengeIcon from 'assets/png/badges/locked-big.png' interface LockedChallengeDetailsViewProps { location: Location<ChallengeType> - t: Function } const LockedChallengeDetailsViewContainer: React.FC<LockedChallengeDetailsViewProps> = ({ location, - t, }: LockedChallengeDetailsViewProps) => { + const { t } = useI18n() const screenType = useRecoilValue(screenTypeState) const [challenge, setChallenge] = useState<ChallengeType | null>(null) const [headerHeight, setHeaderHeight] = useState<number>(0) @@ -89,4 +88,4 @@ const LockedChallengeDetailsViewContainer: React.FC<LockedChallengeDetailsViewPr ) } -export default translate()(LockedChallengeDetailsViewContainer) +export default LockedChallengeDetailsViewContainer diff --git a/src/components/Challenge/OngoingChallengeDetailsView.tsx b/src/components/Challenge/OngoingChallengeDetailsView.tsx index 33145cb986499eea3f6c8ad97e5ec4f94b3e0fd6..75bc9ffab2206fae14d0938b94ecef2d4ee4b9c5 100644 --- a/src/components/Challenge/OngoingChallengeDetailsView.tsx +++ b/src/components/Challenge/OngoingChallengeDetailsView.tsx @@ -1,7 +1,7 @@ import React, { useState, useEffect, useCallback } from 'react' import { Redirect } from 'react-router-dom' -import { translate } from 'cozy-ui/react/I18n' -import { Client, withClient } from 'cozy-client' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil' import { Location } from 'history' @@ -30,15 +30,13 @@ import AvailableChallengeIcon from 'assets/png/badges/available.png' interface OngoingChallengeDetailsViewProps { location: Location<UserChallenge> - client: Client - t: Function } const OngoingChallengeDetailsView: React.FC<OngoingChallengeDetailsViewProps> = ({ location, - client, - t, }: OngoingChallengeDetailsViewProps) => { + const { t } = useI18n() + const client = useClient() const screenType = useRecoilValue(screenTypeState) const [userProfile, setUserProfile] = useRecoilState<UserProfile>( userProfileState @@ -76,16 +74,13 @@ const OngoingChallengeDetailsView: React.FC<OngoingChallengeDetailsViewProps> = _challenge.id, ChallengeState.ABANDONED ) - userProfile.notificationEcogesture = userProfile.notificationEcogesture.filter( (x: string) => x !== _challenge.selectedEcogestures[0].id && x !== _challenge.selectedEcogestures[1].id ) await updateUserProfileNotification(userProfile.notificationEcogesture) - setCurrentChallenge(null) - history.goBack() } } @@ -145,7 +140,6 @@ const OngoingChallengeDetailsView: React.FC<OngoingChallengeDetailsViewProps> = <ChallengeTimeline challenge={challenge} /> </div> )} - <div className="cp-description text-16-bold"> {challenge.challengeType && challenge.challengeType.description} @@ -201,4 +195,4 @@ const OngoingChallengeDetailsView: React.FC<OngoingChallengeDetailsViewProps> = ) } -export default translate()(withClient(OngoingChallengeDetailsView)) +export default OngoingChallengeDetailsView diff --git a/src/components/Charts/AxisRight.tsx b/src/components/Charts/AxisRight.tsx index ac48b6a18ef1452442885774fb8b2918394d134b..9d4a1781b5f528dcc9b7d727e0b09dbe4c000490 100644 --- a/src/components/Charts/AxisRight.tsx +++ b/src/components/Charts/AxisRight.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useRef } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { select, selectAll } from 'd3-selection' import { axisRight } from 'd3-axis' import { ScaleLinear } from 'd3-scale' @@ -11,11 +11,16 @@ interface AxisRightProps { width: number marginRight: number marginTop: number - t: Function // translation service } -const AxisRight = (props: AxisRightProps) => { - const { yScale, fluidTypes, width, marginRight, marginTop, t } = props +const AxisRight = ({ + yScale, + fluidTypes, + width, + marginRight, + marginTop, +}: AxisRightProps) => { + const { t } = useI18n() const isHome: boolean = !window.location.hash.split('/')[2] ? true : false const fluidStyle = fluidTypes.length > 1 || isHome ? 'MULTIFLUID' : FluidType[fluidTypes[0]] @@ -47,4 +52,4 @@ const AxisRight = (props: AxisRightProps) => { ) } -export default translate()(AxisRight) +export default AxisRight diff --git a/src/components/Charts/Bar.tsx b/src/components/Charts/Bar.tsx index f815d2deedeeddc27d72a199ed223280bb8932ee..fbb7a306d8bc98ee28fa2af669490e16770d7c45 100644 --- a/src/components/Charts/Bar.tsx +++ b/src/components/Charts/Bar.tsx @@ -27,23 +27,21 @@ interface BarProps { isSwitching: boolean } -const Bar = (props: BarProps) => { - const { - index, - dataload, - compareDataload, - fluidTypes, - timeStep, - multiFluid, - selectedDate, - showCompare, - handleClickData, - xScale, - yScale, - height, - isSwitching, - } = props - +const Bar = ({ + index, + dataload, + compareDataload, + fluidTypes, + timeStep, + multiFluid, + selectedDate, + showCompare, + handleClickData, + xScale, + yScale, + height, + isSwitching, +}: BarProps) => { const [clicked, setClicked] = useState(false) const [animationEnded, setAnimationEnded] = useState(false) const [compareAnimationEnded, setCompareAnimationEnded] = useState(false) diff --git a/src/components/Charts/BarChart.tsx b/src/components/Charts/BarChart.tsx index 21fa13e41d5aa1a367003e14075692a5c95254cb..45f1ec10d4874413736f09106962645b82265510 100644 --- a/src/components/Charts/BarChart.tsx +++ b/src/components/Charts/BarChart.tsx @@ -88,10 +88,11 @@ const BarChart: React.FC<BarChartProps> = (props: BarChartProps) => { if (DateTime.local() < selectedDate && !maxLoads[key]) { maxLoads[key] = 15 } + const maxLoad = maxLoads[key] || 0 if (showCompare) { - return Math.max(maxLoads[key], maxCompare) + return Math.max(maxLoad, maxCompare) } - return maxLoads[key] > 0 ? maxLoads[key] : 15 + return maxLoad > 0 ? maxLoad : 15 } else { let max = chartData.actualData ? Math.max(...chartData.actualData.map(d => d.value)) diff --git a/src/components/Connection/ConnectionForm.tsx b/src/components/Connection/ConnectionForm.tsx index 7ff0ea1e7cb642af9e49995c0926ca0ecd9f03a1..36f9e62a732ed5f01ec92a48b28c093794951a97 100644 --- a/src/components/Connection/ConnectionForm.tsx +++ b/src/components/Connection/ConnectionForm.tsx @@ -1,5 +1,5 @@ import React, { useCallback } from 'react' -import { Client, withClient } from 'cozy-client' +import { useClient } from 'cozy-client' import { useSetRecoilState } from 'recoil' import { userProfileState } from 'atoms/userProfile.state' @@ -15,7 +15,6 @@ interface ConnectionFormProps { account: Account | null trigger: Trigger | null handleSuccessForm: Function - client: Client } const ConnectionForm: React.FC<ConnectionFormProps> = ({ @@ -24,8 +23,8 @@ const ConnectionForm: React.FC<ConnectionFormProps> = ({ account, trigger, handleSuccessForm, - client, }: ConnectionFormProps) => { + const client = useClient() const setUserProfile = useSetRecoilState(userProfileState) const oAuth: boolean = fluidConfig.konnectorConfig.oauth @@ -64,4 +63,4 @@ const ConnectionForm: React.FC<ConnectionFormProps> = ({ ) } -export default withClient(ConnectionForm) +export default ConnectionForm diff --git a/src/components/Connection/ConnectionLaunch.tsx b/src/components/Connection/ConnectionLaunch.tsx index a9de3c590c520e11b547109c7cb6a408d4d0af58..7f0ff3b7f64cf848dea702f094daf9251e90ae82 100644 --- a/src/components/Connection/ConnectionLaunch.tsx +++ b/src/components/Connection/ConnectionLaunch.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useState } from 'react' -import { withClient, Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { Konnector, Trigger } from 'models' import { isKonnectorRunning } from 'cozy-harvest-lib/dist/helpers/triggers' @@ -32,8 +32,6 @@ interface ConnectionLaunchProps { konnector: Konnector type: string handleConnectionLaunch: Function - client: Client - t: Function } const ConnectionLaunch: React.FC<ConnectionLaunchProps> = ({ @@ -41,9 +39,9 @@ const ConnectionLaunch: React.FC<ConnectionLaunchProps> = ({ konnector, type, handleConnectionLaunch, - client, - t, }: ConnectionLaunchProps) => { + const { t } = useI18n() + const client = useClient() const [state, setState] = useState<string | null>(null) const [openModal, setOpenModal] = useState(false) const callbackResponse = (_state: string) => { @@ -128,4 +126,4 @@ const ConnectionLaunch: React.FC<ConnectionLaunchProps> = ({ ) } -export default translate()(withClient(ConnectionLaunch)) +export default ConnectionLaunch diff --git a/src/components/Connection/ConnectionLoginForm.tsx b/src/components/Connection/ConnectionLoginForm.tsx index bb864602e3602040e4cfe10da145df17bacf5519..a93b11c747921eac78230a6fe6a50c1a2fe7647c 100644 --- a/src/components/Connection/ConnectionLoginForm.tsx +++ b/src/components/Connection/ConnectionLoginForm.tsx @@ -1,6 +1,6 @@ import React, { useState, useEffect } from 'react' -import { withClient, Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { Account, AccountAuthData, Trigger, FluidConfig } from 'models' import AccountService from 'services/account.service' @@ -20,8 +20,6 @@ interface ConnectionLoginFormProps { onSuccess: Function account: Account trigger: Trigger - client: Client - t: Function } const ConnectionLoginForm: React.FC<ConnectionLoginFormProps> = ({ @@ -29,9 +27,9 @@ const ConnectionLoginForm: React.FC<ConnectionLoginFormProps> = ({ onSuccess, account, trigger, - client, - t, }: ConnectionLoginFormProps) => { + const { t } = useI18n() + const client = useClient() const konnectorSlug: string = fluidConfig.konnectorConfig.slug const konnectorType: string = fluidConfig.konnectorConfig.type const siteLink: string = fluidConfig.siteLink @@ -251,4 +249,4 @@ const ConnectionLoginForm: React.FC<ConnectionLoginFormProps> = ({ ) } -export default translate()(withClient(ConnectionLoginForm)) +export default ConnectionLoginForm diff --git a/src/components/Connection/ConnectionNotFound.tsx b/src/components/Connection/ConnectionNotFound.tsx index 3afcac462b234136103c225a92e4f7c2bcfe809c..bf8fa68d3afe163c7de190333a3297fe31be19c1 100644 --- a/src/components/Connection/ConnectionNotFound.tsx +++ b/src/components/Connection/ConnectionNotFound.tsx @@ -1,17 +1,17 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import StyledButton from 'components/CommonKit/Button/StyledButton' interface ConnectionNotFoundProps { konnectorSlug: string - t: Function } const ConnectionNotFound: React.FC<ConnectionNotFoundProps> = ({ konnectorSlug, - t, }: ConnectionNotFoundProps) => { + const { t } = useI18n() + const openKonnectorURL = () => { // TODO - Use getstoreinstallationurl from client - https://docs.cozy.io/en/cozy-client/api/cozy-client/#getstoreinstallationurl-string const hostname = window.location.origin.replace('ecolyo', 'store') @@ -34,4 +34,4 @@ const ConnectionNotFound: React.FC<ConnectionNotFoundProps> = ({ ) } -export default translate()(ConnectionNotFound) +export default ConnectionNotFound diff --git a/src/components/Connection/ConnectionOAuthForm.tsx b/src/components/Connection/ConnectionOAuthForm.tsx index 73a27332ea74d0ba21d4052947c566f30d78ea7b..7e15a20d0df2a3522ef7c2bc8a1739cb53bd551c 100644 --- a/src/components/Connection/ConnectionOAuthForm.tsx +++ b/src/components/Connection/ConnectionOAuthForm.tsx @@ -1,6 +1,6 @@ import React from 'react' -import { Client, withClient } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { Konnector, Trigger, FluidConfig } from 'models' import OAuthForm from 'components/Connection/OAuthForm' @@ -14,8 +14,6 @@ interface ConnectionOAuthFormProps { siteLink: string onSuccess: Function loading: boolean - client: Client - t: Function } const ConnectionOAuthForm: React.FC<ConnectionOAuthFormProps> = ({ @@ -24,9 +22,9 @@ const ConnectionOAuthForm: React.FC<ConnectionOAuthFormProps> = ({ siteLink, onSuccess, loading, - client, - t, }: ConnectionOAuthFormProps) => { + const { t } = useI18n() + const client = useClient() const konnectorSlug: string = fluidConfig.konnectorConfig.slug const handleSuccess = async (accountId: string) => { @@ -73,4 +71,4 @@ const ConnectionOAuthForm: React.FC<ConnectionOAuthFormProps> = ({ ) } -export default translate()(withClient(ConnectionOAuthForm)) +export default ConnectionOAuthForm diff --git a/src/components/Connection/ConnectionResult.tsx b/src/components/Connection/ConnectionResult.tsx index 4f475ad6c0f0a76ebd001d8d4455eff42a3ebf42..33df1db8bbe36962237fbc561f50581d79a23db8 100644 --- a/src/components/Connection/ConnectionResult.tsx +++ b/src/components/Connection/ConnectionResult.tsx @@ -1,6 +1,6 @@ import React, { useState, useEffect, useCallback } from 'react' -import { withClient, Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { useRecoilValue, useSetRecoilState } from 'recoil' import { isKonnectorRunning } from 'cozy-harvest-lib/dist/helpers/triggers' @@ -28,17 +28,15 @@ interface ConnectionResultProps { account: Account konnector: Konnector handleJobState: Function - client: Client - t: Function } const ConnectionResult: React.FC<ConnectionResultProps> = ({ account, konnector, handleJobState, - client, - t, }: ConnectionResultProps) => { + const { t } = useI18n() + const client = useClient() const [trigger, setTrigger] = useState<Trigger | null>(null) const [updating, setUpdating] = useState<boolean>(false) const [lastExecutionDate, setLastExecutionDate] = useState<string>('-') @@ -207,4 +205,4 @@ const ConnectionResult: React.FC<ConnectionResultProps> = ({ ) } -export default translate()(withClient(ConnectionResult)) +export default ConnectionResult diff --git a/src/components/Connection/OAuthForm.tsx b/src/components/Connection/OAuthForm.tsx index beecbb3748ed2ea9733486f07addd727f111d4ef..2a6820a823fad0d1459a6453d4ba7794d3614e8f 100644 --- a/src/components/Connection/OAuthForm.tsx +++ b/src/components/Connection/OAuthForm.tsx @@ -1,6 +1,6 @@ import React, { useState } from 'react' -import { Client, withClient } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { Konnector } from 'models' import { OAuthWindow } from 'cozy-harvest-lib/dist/components/OAuthWindow' @@ -14,19 +14,17 @@ interface OAuthFormProps { konnector: Konnector onSuccess: Function loginFailed: boolean - client: Client - t: Function } const OAuthForm: React.FC<OAuthFormProps> = ({ konnector, onSuccess, - client, - t, }: OAuthFormProps) => { const IDLE = 'idle' const WAITING = 'waiting' + const { t } = useI18n() + const client = useClient() const [status, setStatus] = useState<string>(IDLE) function endOAuth() { @@ -82,4 +80,4 @@ const OAuthForm: React.FC<OAuthFormProps> = ({ ) } -export default translate()(withClient(OAuthForm)) +export default OAuthForm diff --git a/src/components/ConsumptionNavigator/ActivateHalfHourLoad.tsx b/src/components/ConsumptionNavigator/ActivateHalfHourLoad.tsx index 4e1a8bb95e4d6c8851a68568bda9e135975fdec2..13f0577650b976de5306bad6fdc6b8a0d5c6cc91 100644 --- a/src/components/ConsumptionNavigator/ActivateHalfHourLoad.tsx +++ b/src/components/ConsumptionNavigator/ActivateHalfHourLoad.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import ConfigService from 'services/fluidConfig.service' @@ -7,10 +7,8 @@ import StyledAuthButton from 'components/CommonKit/Button/StyledAuthButton' import StyledIcon from 'components/CommonKit/Icon/StyledIcon' import iconEnedisLogo from 'assets/icons/visu/enedis-logo.svg' -interface ActivateHalfHourLoadProps { - t: Function // translation service -} -const ActivateHalfHourLoad = ({ t }: ActivateHalfHourLoadProps) => { +const ActivateHalfHourLoad = () => { + const { t } = useI18n() const fluidConfig = new ConfigService().getFluidConfig() return ( <div className="cta-box"> @@ -36,4 +34,4 @@ const ActivateHalfHourLoad = ({ t }: ActivateHalfHourLoadProps) => { ) } -export default translate()(ActivateHalfHourLoad) +export default ActivateHalfHourLoad diff --git a/src/components/ConsumptionNavigator/ConsumptionNavigator.tsx b/src/components/ConsumptionNavigator/ConsumptionNavigator.tsx index 04b98824f40959bdfcdd926f3c8512c312f34253..78af1a14a87e9a34a761e223c019883e0071fc62 100644 --- a/src/components/ConsumptionNavigator/ConsumptionNavigator.tsx +++ b/src/components/ConsumptionNavigator/ConsumptionNavigator.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { FluidType } from 'enum/fluid.enum' import { TimeStep } from 'enum/timeStep.enum' @@ -12,7 +12,6 @@ interface ConsumptionNavigatorProps { multiFluid: boolean timeStep: TimeStep handleClickTimeStep(timeStep: TimeStep): void - t: Function } const ConsumptionNavigator: React.FC<ConsumptionNavigatorProps> = ({ @@ -20,8 +19,8 @@ const ConsumptionNavigator: React.FC<ConsumptionNavigatorProps> = ({ multiFluid, timeStep, handleClickTimeStep, - t, }: ConsumptionNavigatorProps) => { + const { t } = useI18n() const fluidStyle = multiFluid ? 'MULTIFLUID' : fluidTypes.length === 0 @@ -93,4 +92,4 @@ const ConsumptionNavigator: React.FC<ConsumptionNavigatorProps> = ({ ) } -export default translate()(ConsumptionNavigator) +export default ConsumptionNavigator diff --git a/src/components/ConsumptionVisualizer/ConsumptionVisualizer.tsx b/src/components/ConsumptionVisualizer/ConsumptionVisualizer.tsx index b9095cf34b70b91ced327fef391b8828e9fc4d16..b395e25695006f9331c3def39da28729355d616b 100644 --- a/src/components/ConsumptionVisualizer/ConsumptionVisualizer.tsx +++ b/src/components/ConsumptionVisualizer/ConsumptionVisualizer.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { FluidType } from 'enum/fluid.enum' import { DateTime } from 'luxon' @@ -49,6 +49,7 @@ const ConsumptionVisualizer = ({ handleClickDetails, handleChangeIndex, }: ConsumptionVisualizerProps) => { + const { t } = useI18n() const dateChartService = new DateChartService() return ( <div className="cv"> @@ -110,4 +111,4 @@ const ConsumptionVisualizer = ({ ) } -export default translate()(ConsumptionVisualizer) +export default ConsumptionVisualizer diff --git a/src/components/ConsumptionVisualizer/DataloadConsumptionVisualizer.tsx b/src/components/ConsumptionVisualizer/DataloadConsumptionVisualizer.tsx index 260ab8ba00f5986472634b5ab7f9db3d852eae08..8be307fa6c98daf94885c3150f3aeeebebb90ae5 100644 --- a/src/components/ConsumptionVisualizer/DataloadConsumptionVisualizer.tsx +++ b/src/components/ConsumptionVisualizer/DataloadConsumptionVisualizer.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { NavLink } from 'react-router-dom' import { DateTime } from 'luxon' @@ -22,7 +22,6 @@ interface DataloadConsumptionVisualizerProps { isLoaded: boolean handleClickMove: (increment: number) => void handleClickDetails: () => void - t: Function // translation service } const DataloadConsumptionVisualizer = ({ fluidTypes, @@ -32,8 +31,8 @@ const DataloadConsumptionVisualizer = ({ multiFluid, lastDataDate, isLoaded, - t, }: DataloadConsumptionVisualizerProps) => { + const { t } = useI18n() const converterService = new ConverterService() const [hasData, setHasData] = useState(false) const [hasCompareData, setHasCompareData] = useState(false) @@ -210,4 +209,4 @@ const DataloadConsumptionVisualizer = ({ ) } -export default translate()(DataloadConsumptionVisualizer) +export default DataloadConsumptionVisualizer diff --git a/src/components/ConsumptionVisualizer/DetailedConsumptionVisualizer.tsx b/src/components/ConsumptionVisualizer/DetailedConsumptionVisualizer.tsx index 4eb83b0ea3008888153f4933b7cd9a84bedb4e4d..aa15c3f199af6e663dd7f5f6063fbd357aa56515 100644 --- a/src/components/ConsumptionVisualizer/DetailedConsumptionVisualizer.tsx +++ b/src/components/ConsumptionVisualizer/DetailedConsumptionVisualizer.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { FluidType } from 'enum/fluid.enum' import { TimeStep } from 'enum/timeStep.enum' @@ -8,15 +8,14 @@ interface DetailedConsumptionVisualizerProps { timeStep: TimeStep multiFluid: boolean handleClickDetails: () => void - t: Function // translation service } const DetailedConsumptionVisualizer = ({ fluidTypes, timeStep, multiFluid, handleClickDetails, - t, }: DetailedConsumptionVisualizerProps) => { + const { t } = useI18n() const isDetailDisplayed = () => { if (multiFluid) { return false @@ -60,4 +59,4 @@ const DetailedConsumptionVisualizer = ({ ) } -export default translate()(DetailedConsumptionVisualizer) +export default DetailedConsumptionVisualizer diff --git a/src/components/ConsumptionVisualizer/ErrorDataConsumptionVisualizer.tsx b/src/components/ConsumptionVisualizer/ErrorDataConsumptionVisualizer.tsx index d3714333ff530ebf5e5543183c5e5aa4a61abfc0..c763ab1beb662b35609baa794b15784be483d883 100644 --- a/src/components/ConsumptionVisualizer/ErrorDataConsumptionVisualizer.tsx +++ b/src/components/ConsumptionVisualizer/ErrorDataConsumptionVisualizer.tsx @@ -1,12 +1,11 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { DateTime, Interval } from 'luxon' import warning from 'assets/icons/ico/warning.svg' import StyledIcon from 'components/CommonKit/Icon/StyledIcon' interface ErrorDataConsumptionVisualizerProps { lastDateWithAllData: DateTime - t: Function // translation service handleChangeIndex: (index: number) => void indexDisplayed: number setSelectedDate: Function @@ -15,12 +14,12 @@ interface ErrorDataConsumptionVisualizerProps { } const ErrorDataConsumptionVisualizer = ({ lastDateWithAllData, - t, date, indexDisplayed, setIndexDisplayed, setSelectedDate, }: ErrorDataConsumptionVisualizerProps) => { + const { t } = useI18n() const setDateAndMoveToindex = () => { let indexToMove = 0 if (date < lastDateWithAllData) { @@ -49,4 +48,4 @@ const ErrorDataConsumptionVisualizer = ({ ) } -export default translate()(ErrorDataConsumptionVisualizer) +export default ErrorDataConsumptionVisualizer diff --git a/src/components/ConsumptionVisualizer/LastDataConsumptionVisualizer.tsx b/src/components/ConsumptionVisualizer/LastDataConsumptionVisualizer.tsx index e295b1fbd847a99a28a840a62bbd15db6d435365..c11f1f1ad942f5291637b671e461eae7d3273e49 100644 --- a/src/components/ConsumptionVisualizer/LastDataConsumptionVisualizer.tsx +++ b/src/components/ConsumptionVisualizer/LastDataConsumptionVisualizer.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { FluidType } from 'enum/fluid.enum' import { TimeStep } from 'enum/timeStep.enum' @@ -8,12 +8,11 @@ interface LastDataConsumptionVisualizerProps { timeStep: TimeStep multiFluid: boolean handleChangeIndex: (index: number) => void - t: Function // translation service } const LastDataConsumptionVisualizer = ({ handleChangeIndex, - t, }: LastDataConsumptionVisualizerProps) => { + const { t } = useI18n() return ( <div> <button className="cv-button" onClick={() => handleChangeIndex(0)}> @@ -23,4 +22,4 @@ const LastDataConsumptionVisualizer = ({ ) } -export default translate()(LastDataConsumptionVisualizer) +export default LastDataConsumptionVisualizer diff --git a/src/components/Ecogesture/EcogestureList.tsx b/src/components/Ecogesture/EcogestureList.tsx index 025f215da22b98bb31dfdbaf414ba31e40115f80..e1defba0441a13ee2d6658320b425d4d1f55fc59 100644 --- a/src/components/Ecogesture/EcogestureList.tsx +++ b/src/components/Ecogesture/EcogestureList.tsx @@ -1,6 +1,6 @@ import React, { useState, useEffect } from 'react' -import { withClient, Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { Ecogesture } from 'models' import ChallengeService from 'services/challenge.service' @@ -11,15 +11,9 @@ import EcogestureCard from 'components/Ecogesture/EcogestureCard' import EcogestureModal from 'components/Ecogesture/EcogestureModal' import NegaWattModal from 'components/Ecogesture/NegaWattModal' -interface EcogesturesListProps { - t: Function - client: Client -} - -const EcogesturesList: React.FC<EcogesturesListProps> = ({ - t, - client, -}: EcogesturesListProps) => { +const EcogesturesList: React.FC = () => { + const { t } = useI18n() + const client = useClient() const [ selectedEcogesture, setSelectedEcogesture, @@ -112,4 +106,4 @@ const EcogesturesList: React.FC<EcogesturesListProps> = ({ ) } -export default translate()(withClient(EcogesturesList)) +export default EcogesturesList diff --git a/src/components/Ecogesture/EcogestureModal.tsx b/src/components/Ecogesture/EcogestureModal.tsx index 738f6ee5969eefffa9e57e6943f6e92bc65712cb..e2244fba4ecd620397df14a334ae66bd926f79a6 100644 --- a/src/components/Ecogesture/EcogestureModal.tsx +++ b/src/components/Ecogesture/EcogestureModal.tsx @@ -1,6 +1,6 @@ import React, { useState, useEffect, useCallback } from 'react' import { useClient } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { useRecoilState } from 'recoil' import { getPicto } from 'utils/picto' @@ -16,7 +16,6 @@ interface EcogestureModalProps { open: boolean ecogesture: Ecogesture unlockedEcogesture: boolean - t: Function handleCloseClick: () => void } @@ -24,9 +23,9 @@ const EcogestureModal: React.FC<EcogestureModalProps> = ({ open, ecogesture, unlockedEcogesture, - t, handleCloseClick, }: EcogestureModalProps) => { + const { t } = useI18n() const [ecogestureIcon, setEcogestureIcon] = useState(def) const [userProfile, setUserProfile] = useRecoilState(userProfileState) const client = useClient() @@ -130,4 +129,4 @@ const EcogestureModal: React.FC<EcogestureModalProps> = ({ ) } -export default translate()(EcogestureModal) +export default EcogestureModal diff --git a/src/components/Ecogesture/NegaWattModal.tsx b/src/components/Ecogesture/NegaWattModal.tsx index 6e014f70d00b6c25252f0f2407bf14ace6fa4f64..2507e141012cc47a5cc2a271d221b5f99363d8d5 100644 --- a/src/components/Ecogesture/NegaWattModal.tsx +++ b/src/components/Ecogesture/NegaWattModal.tsx @@ -1,18 +1,17 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import Modal from 'components/CommonKit/Modal/Modal' interface NegaWattModalProps { open: boolean - t: Function handleCloseClick: () => void } const NegaWattModal: React.FC<NegaWattModalProps> = ({ open, - t, handleCloseClick, }: NegaWattModalProps) => { + const { t } = useI18n() return ( <> <Modal open={open} handleCloseClick={handleCloseClick}> @@ -45,4 +44,4 @@ const NegaWattModal: React.FC<NegaWattModalProps> = ({ ) } -export default translate()(NegaWattModal) +export default NegaWattModal diff --git a/src/components/FAQ/FAQLink.tsx b/src/components/FAQ/FAQLink.tsx index 22f5947d8804285d5ca56ba54e0f5e7e245b6ea1..0d2853502e38057c3c26f61fa08d3dcc838f00a1 100644 --- a/src/components/FAQ/FAQLink.tsx +++ b/src/components/FAQ/FAQLink.tsx @@ -1,16 +1,13 @@ import React from 'react' import { NavLink } from 'react-router-dom' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import StyledCard from 'components/CommonKit/Card/StyledCard' import StyledIcon from 'components/CommonKit/Icon/StyledIcon' import QuestionMarkIcon from 'assets/icons/ico/question-mark.svg' -interface FAQLinkProps { - t: Function -} - -const FAQLink: React.FC<FAQLinkProps> = ({ t }: FAQLinkProps) => { +const FAQLink: React.FC = () => { + const { t } = useI18n() return ( <div className="faq-root"> <div className="faq-content"> @@ -38,4 +35,4 @@ const FAQLink: React.FC<FAQLinkProps> = ({ t }: FAQLinkProps) => { ) } -export default translate()(FAQLink) +export default FAQLink diff --git a/src/components/Feedback/FeedbackModal.tsx b/src/components/Feedback/FeedbackModal.tsx index 1e9b47bbd80cd664824cb6478d48c5b4bb3e6a2d..12d5a33fc85740d259152cdb175212db20434ff6 100644 --- a/src/components/Feedback/FeedbackModal.tsx +++ b/src/components/Feedback/FeedbackModal.tsx @@ -1,6 +1,6 @@ import React, { useState } from 'react' -import { withClient, Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { detect } from 'detect-browser' import Modal from 'components/CommonKit/Modal/Modal' @@ -23,16 +23,14 @@ const browser = detect() interface FeedbackModalProps { open: boolean handleCloseClick: () => void - t: Function - client: Client } const FeedbackModal: React.FC<FeedbackModalProps> = ({ open, handleCloseClick, - t, - client, }: FeedbackModalProps) => { + const { t } = useI18n() + const client = useClient() const [type, setType] = useState<string>('bug') const [description, setDescription] = useState<string>('') const [email, setEmail] = useState<string>('') @@ -89,6 +87,7 @@ const FeedbackModal: React.FC<FeedbackModalProps> = ({ } try { const jobCollection = client.collection('io.cozy.jobs') + console.log(jobCollection) await jobCollection.create('sendmail', mailData) } catch (e) { // eslint-disable-next-line no-console @@ -240,4 +239,4 @@ const FeedbackModal: React.FC<FeedbackModalProps> = ({ ) } -export default translate()(withClient(FeedbackModal)) +export default FeedbackModal diff --git a/src/components/FluidChart/FluidChart.tsx b/src/components/FluidChart/FluidChart.tsx index b2f56f553df12b406c930c7ac9ff77e3b05c2a58..da12a0672b7e8dacda0ee5d8b0c1e557f0a5d639 100644 --- a/src/components/FluidChart/FluidChart.tsx +++ b/src/components/FluidChart/FluidChart.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { withClient, Client } from 'cozy-client' +import { useClient } from 'cozy-client' import { useRecoilValue } from 'recoil' import { DateTime } from 'luxon' @@ -20,7 +20,6 @@ interface FluidChartProps { multiFluid: boolean handleClickTimeStep(_timeStep: TimeStep): void setChartLoaded(): void - client: Client } const FluidChart: React.FC<FluidChartProps> = ({ @@ -30,8 +29,8 @@ const FluidChart: React.FC<FluidChartProps> = ({ multiFluid, handleClickTimeStep, setChartLoaded, - client, }: FluidChartProps) => { + const client = useClient() const currentChallenge = useRecoilValue(currentChallengeState) const [lastDataDate, setLastDataDate] = useState<DateTime>(DateTime.local()) const [lastDateWithAllData, setLastDateWithAllData] = useState<DateTime>( @@ -142,4 +141,4 @@ const FluidChart: React.FC<FluidChartProps> = ({ ) } -export default withClient(FluidChart) +export default FluidChart diff --git a/src/components/FluidChart/FluidChartContent.tsx b/src/components/FluidChart/FluidChartContent.tsx index bbf9a68bcc1ad9ccce2420156a2f49127521b52b..a12ca65df3e0b0c3824d783c513879b60ef28fb9 100644 --- a/src/components/FluidChart/FluidChartContent.tsx +++ b/src/components/FluidChart/FluidChartContent.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { DateTime } from 'luxon' import { NavLink } from 'react-router-dom' import { useRecoilValue } from 'recoil' @@ -26,7 +26,6 @@ interface FluidChartContentProps { currentChallenge: UserChallenge | null isDataLoaded: boolean handleDetailedDate(date: DateTime, timeStep: TimeStep): void - t: Function } const FluidChartContent: React.FC<FluidChartContentProps> = ({ @@ -39,8 +38,8 @@ const FluidChartContent: React.FC<FluidChartContentProps> = ({ currentChallenge, isDataLoaded, handleDetailedDate, - t, }: FluidChartContentProps) => { + const { t } = useI18n() const challengeNotification = useRecoilValue(challengeNotificationState) const [indexDisplayed, setIndexDisplayed] = useState<number>(0) const [selectedDate, setSelectedDate] = useState<DateTime>(referenceDate) @@ -201,4 +200,4 @@ const FluidChartContent: React.FC<FluidChartContentProps> = ({ ) } -export default translate()(FluidChartContent) +export default FluidChartContent diff --git a/src/components/FluidChart/FluidChartSlide.tsx b/src/components/FluidChart/FluidChartSlide.tsx index 333d107e04283b935439190bcafb81b1ac4a9000..0fcef191a450843652ad11cadd9a791125a071a5 100644 --- a/src/components/FluidChart/FluidChartSlide.tsx +++ b/src/components/FluidChart/FluidChartSlide.tsx @@ -1,6 +1,6 @@ import React, { useState, useEffect } from 'react' -import { withClient, Client } from 'cozy-client' -import { useRecoilState, useRecoilValue } from 'recoil' +import { useClient } from 'cozy-client' +import { useRecoilValue } from 'recoil' import { DateTime } from 'luxon' import { FluidType } from 'enum/fluid.enum' @@ -29,7 +29,6 @@ interface FluidChartSlideProps { compareDataload: Dataload | null ) => void isSwitching: boolean - client: Client } const FluidChartSlide: React.FC<FluidChartSlideProps> = ({ @@ -45,8 +44,8 @@ const FluidChartSlide: React.FC<FluidChartSlideProps> = ({ challengePeriod, handleClickData, isSwitching, - client, }: FluidChartSlideProps) => { + const client = useClient() const [chartData, setChartData] = useState<Datachart>({ actualData: [], comparisonData: null, @@ -165,4 +164,4 @@ const FluidChartSlide: React.FC<FluidChartSlideProps> = ({ ) } -export default withClient(FluidChartSlide) +export default FluidChartSlide diff --git a/src/components/Header/CozyBar.tsx b/src/components/Header/CozyBar.tsx index 0254fcc3bf251308a3cbb1aa23e079ad5f2b7f7c..06dacf74c22549331c66a67895009198e3a2f6d5 100644 --- a/src/components/Header/CozyBar.tsx +++ b/src/components/Header/CozyBar.tsx @@ -1,7 +1,7 @@ import React from 'react' -import { history } from 'components/App' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { useRecoilValue, useSetRecoilState } from 'recoil' +import { history } from 'components/App' import { ScreenType } from 'enum/screen.enum' import { ModalState } from 'models' @@ -15,14 +15,13 @@ import StyledIconButton from 'components/CommonKit/IconButton/StyledIconButton' interface CozyBarProps { titleKey?: string displayBackArrow?: boolean - t: Function } const CozyBar = ({ titleKey = 'COMMON.APP_TITLE', displayBackArrow = false, - t, }: CozyBarProps) => { + const { t } = useI18n() const { BarLeft, BarCenter, BarRight } = cozy.bar const screenType = useRecoilValue(screenTypeState) const setModalState = useSetRecoilState(modalState) @@ -70,4 +69,4 @@ const CozyBar = ({ return cozyBarCustom(screenType) } -export default translate()(CozyBar) +export default CozyBar diff --git a/src/components/Header/Header.tsx b/src/components/Header/Header.tsx index c157becb8e3e0bc886b2c85c95aade23c758c0bc..7a409634967a4ecff21c89250836082a6472c366 100644 --- a/src/components/Header/Header.tsx +++ b/src/components/Header/Header.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useRef } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { useRecoilValue, useSetRecoilState } from 'recoil' import { history } from 'components/App' @@ -18,7 +18,6 @@ interface HeaderProps { displayBackArrow?: boolean children?: React.ReactNode setHeaderHeight(height: number): void - t: Function } const Header: React.FC<HeaderProps> = ({ @@ -27,8 +26,8 @@ const Header: React.FC<HeaderProps> = ({ displayBackArrow, children, setHeaderHeight, - t, }: HeaderProps) => { + const { t } = useI18n() const header = useRef(null) const screenType = useRecoilValue(screenTypeState) const setModalState = useSetRecoilState(modalState) @@ -117,4 +116,4 @@ const Header: React.FC<HeaderProps> = ({ ) } -export default translate()(Header) +export default Header diff --git a/src/components/Home/HomeIndicators.tsx b/src/components/Home/HomeIndicators.tsx index fd0b009e1e4927798cad39545242e288dc0b27b5..c82b4a07b06fd4751afc4ff16101736a8672a0e8 100644 --- a/src/components/Home/HomeIndicators.tsx +++ b/src/components/Home/HomeIndicators.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useState } from 'react' -import { withClient, Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { useRecoilValue } from 'recoil' import { TimeStep } from 'enum/timeStep.enum' @@ -19,16 +19,14 @@ import KonnectorViewerListItem from 'components/Konnector/KonnectorViewerListIte interface HomeIndicatorsProps { timeStep: TimeStep setIndicatorsLoaded(): void - client: Client - t: Function } const HomeIndicators: React.FC<HomeIndicatorsProps> = ({ timeStep, setIndicatorsLoaded, - client, - t, }: HomeIndicatorsProps) => { + const { t } = useI18n() + const client = useClient() const fluidTypes = useRecoilValue(fluidTypeState) const [performanceIndicators, setPerformanceIndicators] = useState< PerformanceIndicator[] @@ -130,4 +128,4 @@ const HomeIndicators: React.FC<HomeIndicatorsProps> = ({ ) } -export default translate()(withClient(HomeIndicators)) +export default HomeIndicators diff --git a/src/components/Home/OldFluidDataModal.tsx b/src/components/Home/OldFluidDataModal.tsx index ee0a7ae9f54e1b4df57284b63b241d900ec4e846..78d3798830ce041d30c94770ac33a6846daf7592 100644 --- a/src/components/Home/OldFluidDataModal.tsx +++ b/src/components/Home/OldFluidDataModal.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import Modal from 'components/CommonKit/Modal/Modal' import WarnCross from 'assets/icons/ico/warn-cross.svg' import StyledIcon from 'components/CommonKit/Icon/StyledIcon' @@ -12,7 +12,6 @@ import { FluidStatus } from 'models' interface OldFluidDataModalProps { open: boolean - t: Function fluidStatus: FluidStatus[] fluidOldData: FluidType[] handleCloseClick: () => void @@ -20,11 +19,11 @@ interface OldFluidDataModalProps { const OldFluidDataModal: React.FC<OldFluidDataModalProps> = ({ open, - t, fluidStatus, fluidOldData, handleCloseClick, }: OldFluidDataModalProps) => { + const { t } = useI18n() const [konnectorError, setkonnectorError] = useState<boolean>(false) const [erroredKonnectors] = useState<FluidType[]>([]) const [redirect, setRedirect] = useState(false) @@ -114,4 +113,4 @@ const OldFluidDataModal: React.FC<OldFluidDataModalProps> = ({ ) } -export default translate()(OldFluidDataModal) +export default OldFluidDataModal diff --git a/src/components/Hooks/userInstanceSettings.tsx b/src/components/Hooks/userInstanceSettings.tsx index eb05ff8b973ea275f12537a16fe28ea3c88122d1..91d22c9801cd5079e38b0e7d46dc7e6877ffaaf4 100644 --- a/src/components/Hooks/userInstanceSettings.tsx +++ b/src/components/Hooks/userInstanceSettings.tsx @@ -1,8 +1,9 @@ import { useState, useEffect } from 'react' import get from 'lodash/get' -import { Client } from 'cozy-client' +import { useClient } from 'cozy-client' -const userInstanceSettings = (client: Client) => { +const userInstanceSettings = () => { + const client = useClient() const [settings, setSettings] = useState({}) const [fetchStatus, setFetchStatus] = useState('idle') @@ -12,7 +13,7 @@ const userInstanceSettings = (client: Client) => { const response = await client .getStackClient() .fetchJSON('GET', '/settings/instance') - setSettings(get(response, 'data.attributes'), {}) + setSettings(get(response, 'data.attributes')) setFetchStatus('loaded') } catch (error) { setFetchStatus('failed') diff --git a/src/components/Konnector/KonnectorViewerCard.tsx b/src/components/Konnector/KonnectorViewerCard.tsx index 4f017024552efe7654af5832e79a479bd0dca3a1..91d320838e53887d0bd0db2ce50e2c764ba989b1 100644 --- a/src/components/Konnector/KonnectorViewerCard.tsx +++ b/src/components/Konnector/KonnectorViewerCard.tsx @@ -1,45 +1,39 @@ import React, { useState, useEffect, useRef } from 'react' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { FluidType } from 'enum/fluid.enum' - -import { withClient, Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' - +import { JobState } from 'enum/jobState.enum' +import { Konnector, Trigger, TriggerState, FluidConfig } from 'models' +import AccountService from 'services/account.service' +import TriggerService from 'services/triggers.service' import { getPicto, getAddPicto, getParamPicto } from 'utils/picto' import { getFluidType } from 'utils/utils' + import chevronDown from 'assets/icons/ico/chevron-down.svg' import chevronUp from 'assets/icons/ico/chevron-up.svg' - import StyledIcon from 'components/CommonKit/Icon/StyledIcon' import StyledIconButton from 'components/CommonKit/IconButton/StyledIconButton' - import failurePicto from 'assets/png/picto/picto-failure.png' - import ConnectionNotFound from 'components/Connection/ConnectionNotFound' import ConnectionForm from 'components/Connection/ConnectionForm' import ConnectionResult from 'components/Connection/ConnectionResult' import ConnectionLaunch from 'components/Connection/ConnectionLaunch' -import { Konnector, Trigger, TriggerState, FluidConfig } from 'models' -import AccountService from 'services/account.service' -import TriggerService from 'services/triggers.service' -import { JobState } from 'enum/jobState.enum' - interface KonnectorViewerCardProps { fluidConfig: FluidConfig konnector: Konnector - client: Client + isParam: boolean - t: Function } const KonnectorViewerCard: React.FC<KonnectorViewerCardProps> = ({ fluidConfig, konnector, - client, isParam, - t, }: KonnectorViewerCardProps) => { + const { t } = useI18n() + const client = useClient() const [account, setAccount] = useState<Account | null>(null) const [trigger, setTrigger] = useState<Trigger | null>(null) const [triggerState, setTriggerState] = useState<TriggerState | null>(null) @@ -204,4 +198,4 @@ const KonnectorViewerCard: React.FC<KonnectorViewerCardProps> = ({ </> ) } -export default translate()(withClient(KonnectorViewerCard)) +export default KonnectorViewerCard diff --git a/src/components/Konnector/KonnectorViewerList.tsx b/src/components/Konnector/KonnectorViewerList.tsx index 543c8fee40e8a1cbc0ff3f27544f4c6614084ebd..715b89b47e373543e08423ac58b1349b2624f662 100644 --- a/src/components/Konnector/KonnectorViewerList.tsx +++ b/src/components/Konnector/KonnectorViewerList.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { useRecoilValue } from 'recoil' import { FluidConfig } from 'models' @@ -10,13 +10,12 @@ import KonnectorViewerListItem from 'components/Konnector/KonnectorViewerListIte interface KonnectorViewerListProps { isParam: boolean - t: Function } const KonnectorViewerList: React.FC<KonnectorViewerListProps> = ({ isParam = false, - t, }: KonnectorViewerListProps) => { + const { t } = useI18n() const fluidConfigs: FluidConfig[] = new ConfigService().getFluidConfig() const fluidTypes = useRecoilValue(fluidTypeState) return ( @@ -50,4 +49,4 @@ const KonnectorViewerList: React.FC<KonnectorViewerListProps> = ({ ) } -export default translate()(KonnectorViewerList) +export default KonnectorViewerList diff --git a/src/components/Konnector/KonnectorViewerListItem.tsx b/src/components/Konnector/KonnectorViewerListItem.tsx index ea4dceca801ecf97bbbc0a471c37131f1b7b7f51..3cb48f4d33583262448e91622f93cd876a288690 100644 --- a/src/components/Konnector/KonnectorViewerListItem.tsx +++ b/src/components/Konnector/KonnectorViewerListItem.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react' -import { withClient, Client } from 'cozy-client' +import { useClient } from 'cozy-client' import { Konnector, FluidConfig } from 'models' import KonnectorService from 'services/konnector.service' @@ -8,15 +8,14 @@ import KonnectorViewerCard from 'components/Konnector/KonnectorViewerCard' export interface KonnectorViewerListItemProps { fluidConfig: FluidConfig - client: Client isParam: boolean } const KonnectorViewerListItem: React.FC<KonnectorViewerListItemProps> = ({ fluidConfig, - client, isParam = false, }: KonnectorViewerListItemProps) => { + const client = useClient() const [konnector, setKonnector] = useState<Konnector | null>(null) const [loaded, setLoaded] = useState<boolean>(false) @@ -53,4 +52,4 @@ const KonnectorViewerListItem: React.FC<KonnectorViewerListItemProps> = ({ ) } -export default withClient(KonnectorViewerListItem) +export default KonnectorViewerListItem diff --git a/src/components/LegalNotice/LegalNoticeLink.tsx b/src/components/LegalNotice/LegalNoticeLink.tsx index 50d18bb203fadb6dded7fcacfd494c75c6247e07..9118ef5f425c3c7289e8b8750ab67a9970400dd7 100644 --- a/src/components/LegalNotice/LegalNoticeLink.tsx +++ b/src/components/LegalNotice/LegalNoticeLink.tsx @@ -1,18 +1,13 @@ import React from 'react' import { NavLink } from 'react-router-dom' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import StyledCard from 'components/CommonKit/Card/StyledCard' import StyledIcon from 'components/CommonKit/Icon/StyledIcon' import LegalNoticeIcon from 'assets/icons/ico/legal-notice.svg' -interface LegalNoticeLinkProps { - t: Function -} - -const LegalNoticeLink: React.FC<LegalNoticeLinkProps> = ({ - t, -}: LegalNoticeLinkProps) => { +const LegalNoticeLink: React.FC = () => { + const { t } = useI18n() return ( <div className="legal-notice-root"> <div className="legal-notice-content"> @@ -40,4 +35,4 @@ const LegalNoticeLink: React.FC<LegalNoticeLinkProps> = ({ ) } -export default translate()(LegalNoticeLink) +export default LegalNoticeLink diff --git a/src/components/Navbar/Navbar.tsx b/src/components/Navbar/Navbar.tsx index 929a1c5d2f5edc20b4ff0ad9561e6f18eb0a0a73..0b617b9b22b7610edcf78765ce37710e498bc8dc 100644 --- a/src/components/Navbar/Navbar.tsx +++ b/src/components/Navbar/Navbar.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { NavLink } from 'react-router-dom' import ConsoIconOn from 'assets/icons/tabbar/conso/conso-on.svg' @@ -15,11 +15,8 @@ import StyledIcon from 'components/CommonKit/Icon/StyledIcon' import { useRecoilValue } from 'recoil' import { challengeNotificationState } from 'atoms/notification.state' -interface NavbarProps { - t: Function -} - -export const Navbar = ({ t }: NavbarProps) => { +export const Navbar = () => { + const { t } = useI18n() const challengeNotification = useRecoilValue(challengeNotificationState) return ( @@ -80,5 +77,4 @@ export const Navbar = ({ t }: NavbarProps) => { ) } -// translate() provide t() to use translations (ex: locales/en.json) -export default translate()(Navbar) +export default Navbar diff --git a/src/components/Options/ReportOptions.tsx b/src/components/Options/ReportOptions.tsx index f1b3f0dd60beffefd69e9a6b7966a682f03e2acc..4ba49f8528cfa5886b6ae2c15c96ed373c81d841 100644 --- a/src/components/Options/ReportOptions.tsx +++ b/src/components/Options/ReportOptions.tsx @@ -1,20 +1,14 @@ import React, { useCallback } from 'react' -import { Client, withClient } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { useRecoilState } from 'recoil' import UserProfileService from 'services/userProfile.service' import { userProfileState } from 'atoms/userProfile.state' import { UserProfile } from 'models' -interface ReportOptionsProps { - t: Function - client: Client -} - -const ReportOptions: React.FC<ReportOptionsProps> = ({ - t, - client, -}: ReportOptionsProps) => { +const ReportOptions: React.FC = () => { + const { t } = useI18n() + const client = useClient() const [userProfile, setUserProfile] = useRecoilState<UserProfile>( userProfileState ) @@ -76,4 +70,4 @@ const ReportOptions: React.FC<ReportOptionsProps> = ({ ) } -export default translate()(withClient(ReportOptions)) +export default ReportOptions diff --git a/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx b/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx index 915c82fe2c1ad7acaf22fe7f5a6eec7d36244fa0..284cd666a1f06cc01de6375a0761451a3a936364 100644 --- a/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx +++ b/src/components/PerformanceIndicator/FluidPerformanceIndicator.tsx @@ -1,6 +1,6 @@ import React from 'react' import { NavLink } from 'react-router-dom' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { FluidType } from 'enum/fluid.enum' import { PerformanceIndicator } from 'models' @@ -15,15 +15,14 @@ interface FluidPerformanceIndicatorProps { performanceIndicator: PerformanceIndicator timePeriodText: string fluidType: FluidType - t: Function } const FluidPerformanceIndicator: React.FC<FluidPerformanceIndicatorProps> = ({ performanceIndicator, timePeriodText, fluidType, - t, }: FluidPerformanceIndicatorProps) => { + const { t } = useI18n() const iconType = getPicto(fluidType) let displayedValue: string @@ -104,4 +103,4 @@ const FluidPerformanceIndicator: React.FC<FluidPerformanceIndicatorProps> = ({ ) } -export default translate()(FluidPerformanceIndicator) +export default FluidPerformanceIndicator diff --git a/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx b/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx index da149d1fd25d9dd55233c0dabc367b79cd6dc6ce..4f91d2f4d20403708403beb9e6251c2ecaee7113 100644 --- a/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx +++ b/src/components/PerformanceIndicator/PerformanceIndicatorContent.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { TimeStep } from 'enum/timeStep.enum' import { PerformanceIndicator } from 'models' @@ -15,18 +15,17 @@ import ErrorIndicatorIcon from 'assets/icons/visu/indicator/error.svg' import NodataIndicatorIcon from 'assets/icons/visu/indicator/nodata.svg' interface PerformanceIndicatorContentProps { - t: Function performanceIndicator: PerformanceIndicator timePeriodText: string timeStep: TimeStep } const PerformanceIndicatorContent: React.FC<PerformanceIndicatorContentProps> = ({ - t, performanceIndicator, timePeriodText, timeStep, }: PerformanceIndicatorContentProps) => { + const { t } = useI18n() let displayedValue: string if (performanceIndicator && performanceIndicator.value) displayedValue = formatNumberValues(performanceIndicator.value).toString() @@ -133,4 +132,4 @@ const PerformanceIndicatorContent: React.FC<PerformanceIndicatorContentProps> = ) } -export default translate()(PerformanceIndicatorContent) +export default PerformanceIndicatorContent diff --git a/src/components/SingleFluid/SingleFluidIndicators.tsx b/src/components/SingleFluid/SingleFluidIndicators.tsx index f9979895a67d61bc9e03d4191c3417ac27b889ee..cbb60c5f445e2d30ae21641a22d1eda28c424a40 100644 --- a/src/components/SingleFluid/SingleFluidIndicators.tsx +++ b/src/components/SingleFluid/SingleFluidIndicators.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useState } from 'react' -import { withClient, Client } from 'cozy-client' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' +import { useClient } from 'cozy-client' import { useRecoilValue } from 'recoil' import { TimeStep } from 'enum/timeStep.enum' @@ -18,18 +18,16 @@ import SingleFluidRedirect from 'components/SingleFluid/SingleFluidRedirect' interface SingleFluidIndicatorsProps { timeStep: TimeStep setIndicatorsLoaded(): void - client: Client fluidTypes: FluidType[] - t: Function } const SingleFluidIndicators: React.FC<SingleFluidIndicatorsProps> = ({ timeStep, setIndicatorsLoaded, - client, fluidTypes, - t, }: SingleFluidIndicatorsProps) => { + const { t } = useI18n() + const client = useClient() const allConfiguredFluidTypes = useRecoilValue(fluidTypeState) const [performanceIndicators, setPerformanceIndicators] = useState< @@ -108,10 +106,7 @@ const SingleFluidIndicators: React.FC<SingleFluidIndicatorsProps> = ({ {t('COMMON.MINI_CARDS_LABEL')} </div> <div className="sfi-redirect"> - <SingleFluidRedirect - fluidTypes={filteredFluidTypes} - timeStep={timeStep} - /> + <SingleFluidRedirect fluidTypes={filteredFluidTypes} /> </div> </> )} @@ -122,4 +117,4 @@ const SingleFluidIndicators: React.FC<SingleFluidIndicatorsProps> = ({ ) } -export default translate()(withClient(SingleFluidIndicators)) +export default SingleFluidIndicators diff --git a/src/components/SingleFluid/SingleFluidRedirect.tsx b/src/components/SingleFluid/SingleFluidRedirect.tsx index f2e469de9c8e55ec021d5f7570e15bf8a682836a..e0cfdd09efb033c596464ce4f53f553a4faf7585 100644 --- a/src/components/SingleFluid/SingleFluidRedirect.tsx +++ b/src/components/SingleFluid/SingleFluidRedirect.tsx @@ -1,18 +1,17 @@ import React from 'react' -import { translate } from 'cozy-ui/react/I18n' +import { useI18n } from 'cozy-ui/transpiled/react' import { FluidType } from 'enum/fluid.enum' import StyledIconCard from 'components/CommonKit/Card/StyledIconCard' import { NavLink } from 'react-router-dom' export interface SingleFluidRedirectProps { fluidTypes: FluidType[] - t: Function } const SingleFluidRedirect: React.FC<SingleFluidRedirectProps> = ({ fluidTypes, - t, }: SingleFluidRedirectProps) => { + const { t } = useI18n() return ( <> {fluidTypes.map(fluidType => ( @@ -36,4 +35,4 @@ const SingleFluidRedirect: React.FC<SingleFluidRedirectProps> = ({ ) } -export default translate()(SingleFluidRedirect) +export default SingleFluidRedirect diff --git a/src/components/SingleFluid/SingleFluidView.tsx b/src/components/SingleFluid/SingleFluidView.tsx index 96955c84b656d2e06f9755123d6ca178ab46ded4..53d5d42e7832e5a28518d53ab6afa659b360b961 100644 --- a/src/components/SingleFluid/SingleFluidView.tsx +++ b/src/components/SingleFluid/SingleFluidView.tsx @@ -23,7 +23,7 @@ const SingleFluidView: React.FC<SingleFluidViewProps> = ({ previousTimeStepState ) - const [timeStep, setTimeStep] = useState<TimeStep | null>( + const [timeStep, setTimeStep] = useState<TimeStep>( previousTimeStep !== TimeStep.HALF_AN_HOUR ? previousTimeStep : TimeStep.DAY ) const [resetRefenceDate, setResetReferenceDate] = useState<boolean>(false) diff --git a/src/components/Splash/SplashScreenError.tsx b/src/components/Splash/SplashScreenError.tsx index e3b1e2b3d8433ad64058514bff0825495f937cb3..0ba708c157a512dfabf1a64b1dd40ff1f2e9b171 100644 --- a/src/components/Splash/SplashScreenError.tsx +++ b/src/components/Splash/SplashScreenError.tsx @@ -1,6 +1,6 @@ import React from 'react' +import { useI18n } from 'cozy-ui/transpiled/react' import Lottie from 'react-lottie' -import { translate } from 'cozy-ui/react/I18n' import StyledButton from 'components/CommonKit/Button/StyledButton' import * as loadingData from 'assets/anims/splash.json' @@ -14,13 +14,8 @@ const loadingOptions = { }, } -interface SplashScreenErrorProps { - t: Function -} - -const SplashScreenError: React.FC<SplashScreenErrorProps> = ({ - t, -}: SplashScreenErrorProps) => { +const SplashScreenError: React.FC = () => { + const { t } = useI18n() return ( <> <div className="splash-content"> @@ -41,4 +36,4 @@ const SplashScreenError: React.FC<SplashScreenErrorProps> = ({ ) } -export default translate()(SplashScreenError) +export default SplashScreenError diff --git a/src/components/Welcome/WelcomeModal.tsx b/src/components/Welcome/WelcomeModal.tsx index 7196a53c8bb539669a5d2ddc3e38e947ea2b225c..a68cb78cb1dc2f460283e8e54ce49f25762bfafd 100644 --- a/src/components/Welcome/WelcomeModal.tsx +++ b/src/components/Welcome/WelcomeModal.tsx @@ -1,24 +1,20 @@ import React from 'react' -import { withClient, Client } from 'cozy-client' +import { useI18n } from 'cozy-ui/transpiled/react' import Modal from 'components/CommonKit/Modal/Modal' import StyledButton from 'components/CommonKit/Button/StyledButton' -import { translate } from 'cozy-ui/react/I18n' import userInstanceSettings from 'components/Hooks/userInstanceSettings' interface WelcomeModalContainerProps { open: boolean handleCloseClick: () => void - t: Function - client: Client } const WelcomeModalContainer: React.FC<WelcomeModalContainerProps> = ({ open, handleCloseClick, - t, - client, }: WelcomeModalContainerProps) => { - const { data: instanceSettings } = userInstanceSettings(client) + const { t } = useI18n() + const { data: instanceSettings } = userInstanceSettings() return ( <React.Fragment> @@ -50,4 +46,4 @@ const WelcomeModalContainer: React.FC<WelcomeModalContainerProps> = ({ ) } -export default translate()(withClient(WelcomeModalContainer)) +export default WelcomeModalContainer diff --git a/src/cozy-bar.d.ts b/src/cozy-bar.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b4af830ad6af6a7e9853d2138abb32b13732612 --- /dev/null +++ b/src/cozy-bar.d.ts @@ -0,0 +1,34 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +declare module 'cozy-bar' { + type TcozyBarInitOpts = { + appName: string + appNamePrefix: string + appSlug?: string + lang: string + iconPath: string + cozyClient: Client + cozyURL?: string + ssl?: boolean + token?: string + replaceTitleOnMobile: boolean + isPublic?: boolean + onLogOut?: () => any + } + + declare global { + const cozy: { + bar: { + BarCenter: () => any + BarLeft: () => any + BarRight: () => any + init: (opt: TcozyBarInitOpts) => any + setBarCenter: (e: string) => any + setBarLeft: (e: string) => any + setBarRight: (e: string) => any + setLocale: (e: any) => any + setTheme: (theme: string, opts?: any) => any + updateAccessToken: (e: any) => any + } + } + } +} diff --git a/src/cozy-client.d.ts b/src/cozy-client.d.ts index 9259f339a8958061ff6137eff3899e9fe86b6e35..d14548709e101fdbefd8b510a5f111553f9bd903 100644 --- a/src/cozy-client.d.ts +++ b/src/cozy-client.d.ts @@ -1,78 +1,762 @@ -declare module 'cozy-client' - -type QueryDefinition = { - doctype: string - id: string - ids: Array - selector: object - fields: Array - indexedFields: Array - sort: Array - includes: string - referenced: string - limit: null | number - skip: null | number - cursor: unknown -} +/* eslint-disable @typescript-eslint/interface-name-prefix */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { TRealtimePlugin, RealtimePlugin } from 'cozy-realtime' +import { TDoctype } from 'doctypes' -type AppMetaData = { - slug: string - version: string -} +declare module 'cozy-client' { + type QueryDefinition = { + where(selector: any) + include(relations: string[]) + } -type Offline = { - getDatabase: unknown -} -export type Client = { - find(doctype: string): typeof QueryDefinition - query(doctype: string): typeof QueryDefinition - destroy(document: any): typeof QueryDefinition - save(document: any): typeof QueryDefinition - create( - doctype: string, - entry: object, - relationships?: object - ): typeof QueryDefinition - collection(doctype: string): function - offline: typeof Offline - getStackClient: function - appMetadata: AppMetaData -} + type QueryResult = { + data: any + included?: any + } -export type QueryId = string + type AllCollections = + | FileCollection + | PermissionsCollection + | TriggerCollection + | JobCollection + | KonnectorCollection + | TaskCollection + | ObjectiveCollection + | AppointmentCollection -export type QueryDefinitionBuilder = (client: Client) => QueryDefinition + interface IClientInstanceOpts { + cozyAppEditor: string + cozyAppName: string + cozyAppNamePrefix: string + cozyAppSlug: string + cozyDomain: string + cozyIconPath: string + cozyLocale: string + cozyToken: string + } + interface IClientStackClient { + jobs: JobCollection + konnectors: KonnectorCollection + fetchJSON: Function + options: any + token: { token: string } + uri: string + _events: any + } + interface IClientToJSON { + uri: string + } + interface IClientLogin { + token: string + uri: string + } + interface IClientSchema { + byDoctype: any + client: Client + } -export type QueryOptions = { - doc?: unknown - query?: QueryDefinition | QueryDefinitionBuilder - as?: QueryId -} + export type Client = { + appMetadata: any + options: IClientLogin + idCounter: number + isLogged: boolean + instanceOptions: IClientInstanceOpts + links: any + chain: any + schema: any + plugins: { realtime: TRealtimePlugin; [key: string]: any } -export type QueryOptionsBuilder<P> = (props: P) => QueryOptions + /** + * A plugin is a class whose constructor receives the client as first argument. + * The main mean of interaction with the client should be with events + * like "login"/"logout". + * + * The plugin system is meant to encourage separation of concerns, modularity + * and testability : instead of registering events at module level, please + * create a plugin that subscribes to events. + * + * Plugin instances are stored internally in the `plugins` attribute of the client + * and can be accessed via this mean. A plugin class must have the attribute + * `pluginName` that will be use as the key in the `plugins` object. + * + * Two plugins with the same `pluginName` cannot co-exist. + * + * @example + * ``` + * class AlertPlugin { + * constructor(client, options) { + * this.client = client + * this.options = options + * this.handleLogin = this.handleLogin.bind(this) + * this.handleLogout = this.handleLogout.bind(this) + * this.client.on("login", this.handleLogin) + * this.client.on("logout", this.handleLogout) + * } + * + * handleLogin() { + * alert(this.options.onLoginAlert) + * } + * + * handleLogout() { + * alert(this.options.onLogoutAlert) + * } + * } + * + * AlertPlugin.pluginName = 'alerts' + * + * client.registerPlugin(AlertPlugin, { + * onLoginAlert: 'client has logged in !', + * onLogoutAlert: 'client has logged out !' + * }) + * + * // the instance of the plugin is accessible via + * client.plugins.alerts + * ``` + */ + registerPlugin(Plugin: RealtimePlugin | any, options?: any) -export type QuerySpecs<P> = { - [k in string]: QueryOptions | QueryOptionsBuilder<P> -} + /** + * Notify the links that they can start and set isLogged to true. + * + * On mobile, where url/token are set after instantiation, use this method + * to set the token and uri via options. + * + * Emits + * + * - "beforeLogin" at the beginning, before links have been set up + * - "login" when the client is fully logged in and links have been set up + * + * @param {object} options - Options + * @param {string} options.token - If passed, the token is set on the client + * @param {string} options.uri - If passed, the uri is set on the client + * @returns {Promise} - Resolves when all links have been setup and client is fully logged in + * + */ + login(options: IClientLogin): Promise<any> -export function queryConnect<C extends React.ElementType>( - querySpecs: QuerySpecs<React.ComponentPropsWithoutRef<C>> -): (wrappedElement: C) => void - -export function withClient<C extends React.ElementType>( - component: React.ComponentPropsWithoutRef<C> -): (wrappedElement: C) => void - -export type QueryState<D> = { - id: unknown - definition: unknown - fetchStatus: 'pending' | 'loading' | 'loaded' | 'failed' - lastFetch: null | number - lastUpdate: null | number - lastError: null | number - hasMore: boolean - count: number - data: D[] -} + /** + * Logs out the client and reset all the links + * + * Emits + * + * - "beforeLogout" at the beginning, before links have been reset + * - "login" when the client is fully logged out and links have been reset + * + * @returns {Promise} - Resolves when all links have been reset and client is fully logged out + */ + logout(): Promise<any> + + /** + * Forwards to a stack client instance and returns + * a [DocumentCollection]{@link https://docs.cozy.io/en/cozy-client/api/cozy-stack-client/#DocumentCollection} instance. + * + * @param {string} doctype The collection doctype. + * @returns {DocumentCollection} Collection corresponding to the doctype + */ + collection(doctype: TDoctype): AllCollections + fetch(method: string, path: string, body: any, options?: any): Promise<any> + find(doctype: string, selector?: any): QueryDefinition + get(doctype: TDoctype, id: string): any + validate(document: any): any + save( + documentType: { _type: TDoctype; [key: string]: any }, + mutationOptions?: any + ): Promise<QueryResult> + + /** + * Creates a list of mutations to execute to create a document and its relationships. + * + * ```js + * const baseDoc = { _type: 'io.cozy.todo', label: 'Go hiking' } + * // relations can be arrays or single objects + * const relationships = { + * attachments: [{ _id: 12345, _type: 'io.cozy.files' }, { _id: 6789, _type: 'io.cozy.files' }], + * bills: { _id: 9999, _type: 'io.cozy.bills' } + * } + * client.getDocumentSavePlan(baseDoc, relationships) + * ``` + * + * @param {object} document The base document to create + * @param {object} relationships The list of relationships to add, as a dictionnary. Keys should be relationship names and values the documents to link. + * @returns {Mutation[]} One or more mutation to execute + */ + getDocumentSavePlan(document: any, relationships: any) + triggerHook(name: string, document: any): any + + /** + * Destroys a document. {before,after}:destroy hooks will be fired. + * + * @param {Document} document - Document to be deleted + * @returns {Document} The document that has been deleted + */ + destroy(document: any): typeof QueryDefinition + upload(file: any, dirPath: string, mutationOptions?: any) + ensureQueryExists(queryId: string, queryDefinition: any): any + + /** + * Executes a query and returns its results. + * + * Results from the query will be saved internally and can be retrieved via + * `getQueryFromState` or directly using `<Query />`. `<Query />` automatically + * executes its query when mounted if no fetch policy has been indicated. + * + * @param {QueryDefinition} queryDefinition - Definition that will be executed + * @param {string} options - Options + * @param {string} options.as - Names the query so it can be reused (by multiple components for example) + * @param {string} options.fetchPolicy - Fetch policy to bypass fetching based on what's already inside the state. See "Fetch policies" + * @returns {QueryResult} + */ + query( + queryDefinition: QueryDefinition, + { update, ...options }?: any + ): Promise<QueryResult> + + /** + * Will fetch all documents for a `queryDefinition`, automatically fetching more + * documents if the total of documents is superior to the pagination limit. Can + * result in a lot of network requests. + * + * @param {QueryDefinition} queryDefinition - Definition to be executed + * @param {object} options - Options to the query + * @returns {Array} All documents matching the query + */ + queryAll(queryDefinition: QueryDefinition, options): Promise<QueryResult> + makeObservableQuery(queryDefinition: QueryDefinition, options?: any): any + create( + doctype: TDoctype, + entry: any, + relationships?: any, + options?: any + ): Promise<QueryResult> + getStackClient(): IClientStackClient + getInstanceOptions(): IClientInstanceOpts + toJSON(): IClientToJSON + } + + export const CozyProvider: any + + export class DocumentCollection { + doctype: TDoctype + stackClient: IClientStackClient + indexes: any + endpoint: string + + /** + * Lists all documents of the collection, without filters. + * + * The returned documents are paginated by the stack. + * + * @param {{limit, skip, bookmark, keys}} options The fetch options: pagination & fetch of specific docs. + * @returns {{data, meta, skip, bookmark, next}} The JSON API conformant response. + * @throws {FetchError} + */ + all(options?: any): Promise<any> + + /** + * Returns a filtered list of documents using a Mango selector. + * + * The returned documents are paginated by the stack. + * + * @param {object} selector The Mango selector. + * @param {{sort, fields, limit, skip, bookmark, indexId}} options The query options. + * @returns {{data, skip, bookmark, next}} The JSON API conformant response. + * @throws {FetchError} + */ + find(selector: any, options?: any): Promise<any> + + /** + * Get a document by id + * + * @param {string} id The document id. + * @returns {object} JsonAPI response containing normalized document as data attribute + */ + get(id: string): Promise<any> + + /** + * Get many documents by id + */ + getAll(ids: string[]): Promise<any> + + /** + * Creates a document + * + * @param {object} doc - Document to create. Optional: you can force the id with the _id attribute + */ + create(doc: any): Promise<any> + + /** + * Updates a document + * + * @param {object} document - Document to update. Do not forget the _id attribute + */ + update(document: any): Promise<any> + + /** + * Destroys a document + * + * @param {object} doc - Document to destroy. Do not forget _id and _rev attributes + */ + destroy(doc: any): Promise<any> + + /** + * Updates several documents in one batch + * + * @param {Document[]} docs Documents to be updated + */ + updateAll(docs: any[]): Promise<any> + + /** + * Deletes several documents in one batch + * + * @param {Document[]} docs - Documents to delete + */ + destroyAll(docs: any[]): Promise<any> + + toMangoOptions(selector: any, options?: any): Promise<any> + checkUniquenessOf(property: any, value: any): Promise<any> + getUniqueIndexId(property: any): Promise<any> + getIndexId(fields: any, indexName: string[]): Promise<any> + createIndex(fields: any): Promise<any> + getIndexNameFromFields(fields: string[]): Promise<any> + + /** + * Compute fields that should be indexed for a mango + * query to work + * + * @private + * @param {object} options - Mango query options + * @returns {Array} - Fields to index + */ + getIndexFields(options: any): Promise<any> + + /** + * Use Couch _changes API + * + * @param {object} couchOptions Couch options for changes https://kutt.it/5r7MNQ + * @param {object} options { includeDesign: false, includeDeleted: false } + */ + fetchChanges(couchOptions: any, options?: any): Promise<any> + } + + export interface FileCollection extends DocumentCollection { + specialDirectories: any + + /** + * Fetches the file's data + */ + get(id: string): Promise<any> + + /** + * Returns a filtered list of documents using a Mango selector. + * + * The returned documents are paginated by the stack. + */ + find(selector: any, options?: any): Promise<any> + + /** + * Returns the list of files referenced by a document -- see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/ + */ + findReferencedBy(document: any, options?: any): Promise<any> + + /** + * Add referenced_by documents to a file — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/#post-filesfile-idrelationshipsreferenced_by + + * For example, to have an album referenced by a file: + * ``` + * addReferencedBy({_id: 123, _type: "io.cozy.files", name: "cozy.jpg"}, [{_id: 456, _type: "io.cozy.photos.albums", name: "Happy Cloud"}]) + * ``` + */ + addReferencedBy(document: any, documents: any[]): Promise<any> + + /** + * Remove referenced_by documents from a file — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/#delete-filesfile-idrelationshipsreferenced_by + * + * For example, to remove an album reference from a file: + * ``` + * removeReferencedBy({_id: 123, _type: "io.cozy.files", name: "cozy.jpg"}, [{_id: 456, _type: "io.cozy.photos.albums", name: "Happy Cloud"}]) + * ``` + */ + removeReferencedBy(document: any, documents: any[]): Promise<any> + + /** + * Add files references to a document — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/#post-datatypedoc-idrelationshipsreferences + * + * For example, to add a photo to an album: + * ``` + * addReferencesTo({_id: 456, _type: "io.cozy.photos.albums", name: "Happy Cloud"}, [{_id: 123, _type: "io.cozy.files", name: "cozy.jpg"}]) + * ``` + */ + addReferencesTo(document: any, documents: any[]): Promise<any> + + /** + * Remove files references to a document — see https://docs.cozy.io/en/cozy-stack/references-docs-in-vfs/#delete-datatypedoc-idrelationshipsreferences + * + * For example, to remove a photo from an album: + * ``` + * removeReferencesTo({_id: 456, _type: "io.cozy.photos.albums", name: "Happy Cloud"}, [{_id: 123, _type: "io.cozy.files", name: "cozy.jpg"}]) + * ``` + */ + removeReferencesTo(document: any, documents: any[]): Promise<any> + destroy(any: any, options?: any): Promise<any> + + /** + * Empty the Trash + */ + emptyTrash(): Promise<any> + + /** + * Restores a trashed file. + */ + restore(id: string): Promise<any> + + /** + * Definitely delete a file + */ + deleteFilePermanently(id: string): Promise<any> + + /** + * Upload a file + */ + upload(data: File, dirPath: string): Promise<any> + + /** + * Creates directory or file. + * + * - Used by StackLink to support CozyClient.create('io.cozy.files', options) + */ + create(attributes: any): Promise<any> -export function fromEnv(env: NodeJS.ProcessEnv, schema: object): () => Client + /** + * Creates a file + */ + createFile(data: File, {}: any) + + /*** + * updateFile - Updates a file's data + */ + updateFile(data: File, params?: any): Promise<any> + getDownloadLinkById(id: string): Promise<string> + getDownloadLinkByRevision(versionId: string, filename: string): Promise<any> + getDownloadLinkByPath(path: string): Promise<any> + + /** + * Download a file or a specific version of the file + */ + download(file: any, versionId?: string, filename?: string): Promise<any> + + /** + * Fetch the binary of a file or a specific version of a file + * Useful for instance when you can't download the file directly + * (via a content-disposition attachement header) and need to store + * it before doing an operation. + */ + fetchFileContent(id: string): Promise<any> + + /** + * Get a beautified size for a given file + * + * 1024B => 1KB + * + * 102404500404B => 95.37 GB + */ + getBeautifulSize(file: any, decimal: number): Promise<any> + + downloadArchive(fileIds: string[], notSecureFilename?: string): Promise<any> + getArchiveLinkByIds(ids: string[], name?: string): Promise<any> + + /** + * Checks if the file belongs to the parent's hierarchy. + */ + isChildOf(child: any | string, parent: any | string): Promise<any> + + /** + * statById - Fetches the metadata about a document. For folders, the results include the list of child files and folders. + */ + statById(id: string, options?: any): Promise<any> + statByPath(path: string): Promise<any> + createDirectory(attributes: any): Promise<any> + ensureDirectoryExists(path: string): Promise<any> + getDirectoryOrCreate(name: string, parentDirectory: any): Promise<any> + + /** + * Creates one or more folders until the given path exists + */ + createDirectoryByPath(path: string): Promise<any> + + /** + * + * async updateAttributes - Updates a file / folder's attributes except + * the metadata attribute. If you want to update its metadata attribute, + * then use `updateFileMetadataAttribute` since `metadata` is a specific + * doctype. + * + * For instance, if you want to update the name of a file, you can pass + * attributes = { name: 'newName'} + * + * You can see the attributes for both Folder and File (as they share the + * same doctype they have a few in common) here : + * https://docs.cozy.io/en/cozy-doctypes/docs/io.cozy.files/#iocozyfiles + */ + updateAttributes(id: string, attributes: any): Promise<any> + updateFileMetadata(id: string, attributes: any): Promise<any> + + /** + * Send a metadata object that can be associated to a file uploaded after that, + * via the MetadataID query parameter. + * See https://github.com/cozy/cozy-stack/blob/master/docs/files.md#post-filesuploadmetadata + */ + createFileMetadata(attributes: any): Promise<any> + + /** + * + * Updates the metadata attribute of a io.cozy.files + * Creates a new version of the file without having + * to upload again the file's content + * + * To see available content of the metadata attribute + * see : https://docs.cozy.io/en/cozy-doctypes/docs/io.cozy.files_metadata/ + */ + updateMetadataAttribute(id: string, metadata: any): Promise<any> + + /** + * + * This method should not be called directly to upload a file. + * + * You should use `createFile` + */ + doUpload( + data: File, + path: string, + options?: any, + method: 'POST' | 'PUT' | 'PATCH' + ): Promise<any> + } + + export interface ContactCollection extends DocumentCollection { + find(selector: any, options?: any): Promise<any> + findMyself(): Promise<any> + } + + export interface PermissionsCollection extends DocumentCollection { + get(id: string): Promise<any> + + /** + * Create a new set of permissions + * It can also associates one or more codes to it, via the codes parameter + * + * @param {object} permission + * @param {string} permission.codes A comma separed list of values (defaulted to code) + * @param {string} permission.ttl Make the codes expire after a delay (bigduration format) + * + * bigduration format: https://github.com/justincampbell/bigduration/blob/master/README.md + * @see https://docs.cozy.io/en/cozy-stack/permissions/#post-permissions + * + */ + create(attributes: any): Promise<any> + + /** + * Adds a permission to the given document. Document type must be + * `io.cozy.apps`, `io.cozy.konnectors` or `io.cozy.permissions` + * + * @param {object} document - Document which receives the permission + * @param {object} permission - Describes the permission + * @returns {Promise} + * + * @example + * ``` + * const permissions = await client + * .collection('io.cozy.permissions') + * .add(konnector, { + * folder: { + * type: 'io.cozy.files', + * verbs: ['GET', 'PUT'], + * values: [`io.cozy.files.bc57b60eb2954537b0dcdc6ebd8e9d23`] + * } + * }) + * ``` + */ + add(document, permission): Promise<any> + destroy(permission): Promise<any> + findLinksByDoctype(doctype): Promise<any> + findApps(): Promise<any> + + /** + * Create a share link + * + * @param {{_id, _type}} document - cozy document + * @param {object} options - options + * @param {string[]} options.verbs - explicit permissions to use + */ + createSharingLink(document, options?) + + /** + * Follow the next link to fetch the next permissions + * + * @param {object} permissions JSON-API based permissions document + */ + fetchPermissionsByLink(permissions: any) + + /** + * + * @param {object} document Cozy doc + * @returns {object} with all the permissions + */ + fetchAllLinks(document: any) + + /** + * Destroy a sharing link and the related permissions + * + * @param {object} document + */ + revokeSharingLink(document) + + /** + * async getOwnPermissions - Gets the permission for the current token + * + * @returns {object} + */ + getOwnPermissions() + } + + export interface TriggerCollection extends DocumentCollection { + /** + * Get the list of triggers. + * + * @see https://docs.cozy.io/en/cozy-stack/jobs/#get-jobstriggers + * @param {{Worker}} options The fetch options: Worker allow to filter only triggers associated with a specific worker. + * @returns {{data}} The JSON API conformant response. + * @throws {FetchError} + */ + all(options: any): Promise<any> + + /** + * Creates a Trigger document + * + * @see https://docs.cozy.io/en/cozy-stack/jobs/#post-jobstriggers + * @param {object} attributes Trigger's attributes + * @returns {object} Stack response, containing trigger document under `data` attribute. + */ + create(attributes: any): Promise<any> + + /** + * Deletes a trigger + * + * @see https://docs.cozy.io/en/cozy-stack/jobs/#delete-jobstriggerstrigger-id + * @param {object} document The trigger to delete — must have an _id field + * @returns {object} The deleted document + */ + destroy(document: any): Promise<any> + + /** + * + * Be warned, ATM /jobs/triggers does not return the same informations + * than /data/io.cozy.triggers (used by the super.find method). + * + * See https://github.com/cozy/cozy-stack/pull/2010 + * + * @param {object} selector - Which kind of worker {konnector,service} + * @param {object} options - Options + * @returns {{data, meta, skip, next}} The JSON API conformant response. + * @throws {FetchError} + */ + find(selector = {}, options = {}): Promise<any> + get(id: string): Promise<any> + + /** + * Force given trigger execution. + * + * @see https://docs.cozy.io/en/cozy-stack/jobs/#post-jobstriggerstrigger-idlaunch + * @param {object} trigger Trigger to launch + * @returns {object} Stack response, containing job launched by trigger, under `data` attribute. + */ + launch(trigger: any): Promise<any> + + update(): Promise<any> + } + + export interface JobCollection extends DocumentCollection { + /** + * Enqueue programmatically a new job. + * + * @see https://docs.cozy.io/en/cozy-stack/jobs/#post-jobsqueueworker-type + * @param {object} workerType Job's attributes + * @param {object} args Job's attributes + * @param {object} options Job's attributes + * @returns {object} Stack response, containing job document under `data` attribute. + */ + create(workerType: any, args: any, options?: any): Promise<any> + + get() + queued(workerType: any) + waitFor(argument: any) + } + + export interface AppCollection extends DocumentCollection { + endpoint: string + + /** + * Lists all apps, without filters. + * + * The returned documents are not paginated by the stack. + * + * @returns {{data, meta, skip, next}} The JSON API conformant response. + * @throws {FetchError} + */ + all(): Promise<any> + create(): Promise<any> + update(): Promise<any> + destroy(): Promise<any> + } + + export interface KonnectorCollection extends AppCollection { + doctype: TDoctype + endpoint: string + + create(): Promise<any> + destroy(): Promise<any> + + /** + * Find triggers for a particular konnector + * + * @param {string} slug of the konnector + */ + findTriggersBySlug(slug: string): Promise<any> + + /** + * Launch a trigger for a given konnector. + * + * @param {string} slug + * @param {object} options + * @param {object} options.accountId - Pinpoint the account that should be used, useful if the user + * has more than 1 account for 1 konnector + */ + launch(slug: string, options: { accountId: string }) + + /** + * Updates a konnector + * + * @param {string} slug + * @param {object} options + * @param {object} options.source - Specify the source (ex: registry://slug/stable) + * @param {boolean} options.sync - Wait for konnector to be updated, otherwise the job + * is just scheduled + */ + update(slug: string, options: { source: any; sync: boolean }): Promise<any> + } + + export type GroupCollection = DocumentCollection + export type TaskCollection = DocumentCollection + export type ObjectiveCollection = DocumentCollection + export type AppointmentCollection = DocumentCollection + export type JobCollection = DocumentCollection + + export function useClient(): Client + + class CCozyClient { + constructor(n: any): Client + } + const CozyClient: { + new (n: any): Client + } = CCozyClient + export default CozyClient +} diff --git a/src/cozy-ui.d.ts b/src/cozy-ui.d.ts index bf96cf6b8ec1363b57a004b9ed9bfe1f4b72b70d..65c1da052d48e22be47d77b27e9a1be6582dbbae 100644 --- a/src/cozy-ui.d.ts +++ b/src/cozy-ui.d.ts @@ -1,4 +1,38 @@ -declare module 'cozy-ui/react/I18n' +/* eslint-disable @typescript-eslint/interface-name-prefix */ +/* eslint-disable @typescript-eslint/no-explicit-any */ declare module 'cozy-ui/transpiled/react/Icon' declare module 'cozy-ui/transpiled/react/Spinner' declare module 'cozy-ui/transpiled/react/Layout' + +declare module 'cozy-ui/transpiled/react' { + interface IPropsIcon { + icon?: string + width?: string | number + height?: string | number + color?: string + className?: string + preserveColor?: string + rotate?: string + size?: string | number + spin?: any + [key: string]: any + } + interface IuseI18n { + t: (key: string, opt?: any) => string + f: (date: Date, format: string) => string + lang: string + } + + export function useI18n(): IuseI18n + export function Icon( + props: IPropsIcon + ): React.CElement<any, React.Component<any, any, any>> + export const I18n: any +} + +declare module 'cozy-ui/transpiled/react/I18n' { + export function initTranslation( + userLocal: string, + cb: (lang: string) => string + ) +} diff --git a/src/targets/browser/index.tsx b/src/targets/browser/index.tsx index acfe5941e44d07fb740a69b4f4f80b48d68d04c6..3dce2390d30aae46bc085737d1505e27128ee666 100644 --- a/src/targets/browser/index.tsx +++ b/src/targets/browser/index.tsx @@ -2,76 +2,77 @@ import '../../styles/index.scss' import React from 'react' -import CozyClient, { CozyProvider } from 'cozy-client' -import { render } from 'react-dom' -import { I18n } from 'cozy-ui/react/I18n' +import CozyClient, { CozyProvider, Client } from 'cozy-client' +import ReactDOM, { render } from 'react-dom' +import { Document } from 'cozy-doctypes' +import { I18n } from 'cozy-ui/transpiled/react' +import { initTranslation } from 'cozy-ui/transpiled/react/I18n' import schema from 'doctypes' +import { getDataset, getDataOrDefault } from 'utils/initFromDom' const manifest = require('../../../manifest.webapp') -let appLocale: string -const renderApp = function(client) { +const renderApp = (polyglot: any, lang: string, client: Client) => { const App = require('components/App').default + render( - <I18n - lang={appLocale} - dictRequire={appLocale => require(`locales/${appLocale}`)} - > - <CozyProvider client={client}> + <CozyProvider client={client}> + <I18n lang={lang} polyglot={polyglot}> <App /> - </CozyProvider> - </I18n>, + </I18n> + </CozyProvider>, document.querySelector('[role=application]') ) } -// return a defaultData if the template hasn't been replaced by cozy-stack -const getDataOrDefault = function(toTest: string, defaultData: string) { - const templateRegex = /^\{\{\.[a-zA-Z]*\}\}$/ // {{.Example}} - return templateRegex.test(toTest) ? defaultData : toTest -} +const initApp = () => { + const supportedLocales = ['fr', 'en'] + const data = getDataset() -// initial rendering of the application -document.addEventListener('DOMContentLoaded', () => { - const root = document.querySelector('[role=application]') - const data = root.dataset - const appIcon = getDataOrDefault( + const iconPath = getDataOrDefault( data.cozyIconPath, require('../vendor/assets/icon.svg') ) - const appNamePrefix = getDataOrDefault( data.cozyAppNamePrefix || manifest.name_prefix, '' ) const appName = getDataOrDefault(data.cozyAppName, manifest.name) const appSlug = getDataOrDefault(data.cozyAppSlug, manifest.slug) - // const appVersion = getDataOrDefault(data.cozyAppVersion, manifest.version) - const appVersion = manifest.version - - // appLocale = getDataOrDefault(data.cozyLocale, 'fr') - appLocale = 'fr' + const appVersion = getDataOrDefault(data.cozyAppVersion, manifest.version) + // FIX cozyLocal + const userLocale = 'fr' // getDataOrDefault(data.cozyLocale, 'fr') + const polyglot = initTranslation(userLocale, lang => + require(`locales/${lang}`) + ) + const lang = supportedLocales.includes(userLocale) ? userLocale : 'fr' const protocol = window.location ? window.location.protocol : 'https:' - // initialize the client to interact with the cozy stack + const token = data.cozyToken + + // initialize the client const client = new CozyClient({ uri: `${protocol}//${data.cozyDomain}`, - token: data.cozyToken, - schema, + token, appMetadata: { slug: appSlug, version: appVersion, }, + schema, }) + if (!Document.cozyClient) { + Document.registerClient(client) + } - // initialize the bar, common of all applications, it allows - // platform features like apps navigation without doing anything + // necessary to initialize the bar with the correct React instance + window.React = React + window.ReactDOM = ReactDOM cozy.bar.init({ - appName: appName, - appNamePrefix: appNamePrefix, - iconPath: appIcon, - lang: appLocale, + appName, + appNamePrefix, + iconPath, + lang, replaceTitleOnMobile: true, cozyClient: client, }) @@ -79,5 +80,8 @@ document.addEventListener('DOMContentLoaded', () => { const { setTheme } = cozy.bar setTheme('primary', { primaryColor: 'transparent' }) - renderApp(client) -}) + renderApp(polyglot, lang, client) +} + +// initial rendering of the application +document.addEventListener('DOMContentLoaded', initApp) diff --git a/src/utils/initFromDom.ts b/src/utils/initFromDom.ts new file mode 100644 index 0000000000000000000000000000000000000000..470975ca1da14686780b0d4a150bfaf782e49c07 --- /dev/null +++ b/src/utils/initFromDom.ts @@ -0,0 +1,15 @@ +export const getDataset = () => { + const root: any = document.querySelector('[role=application]') + return root.dataset +} + +// return a defaultData if the template hasn't been replaced by cozy-stack +export const getDataOrDefault = (toTest: string, defaultData: string) => { + const templateRegex = /^\{\{\.[a-zA-Z]*\}\}$/ // {{.Example}} + return templateRegex.test(toTest) ? defaultData : toTest +} + +export const getPublicSharecode = () => { + const search = new URLSearchParams(window.location.search) + return search.get('sharecode') +}