Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor multiple old files to TypeScript #1010

Merged
merged 8 commits into from
Nov 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { getClient } from '/libs/client'
import { getColors } from '/ui/colors'
import { localMethods } from '/libs/intents/localMethods'
import { persistor, store } from '/redux/store'
import { useAppBootstrap } from '/hooks/useAppBootstrap.js'
import { useAppBootstrap } from '/hooks/useAppBootstrap'
import { useGlobalAppState } from '/hooks/useGlobalAppState'
import { useCookieResyncOnResume } from '/hooks/useCookieResyncOnResume'
import { useCozyEnvironmentOverride } from '/hooks/useCozyEnvironmentOverride'
Expand Down
3 changes: 3 additions & 0 deletions src/app/domain/backup/services/getMedias.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export const formatMediasFromPhotoIdentifier = (
if (subTypes.includes('PhotoLive')) {
return [
{
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
id,
name: getPathWithoutExtension(filename) + '.MOV',
uri: uri,
Expand All @@ -113,6 +114,7 @@ export const formatMediasFromPhotoIdentifier = (
fileSize: null
},
{
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
id,
name: filename,
uri: uri,
Expand All @@ -130,6 +132,7 @@ export const formatMediasFromPhotoIdentifier = (

return [
{
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
id,
name: filename,
uri: uri,
Expand Down
29 changes: 0 additions & 29 deletions src/app/domain/geolocation/helpers/index.js

This file was deleted.

31 changes: 31 additions & 0 deletions src/app/domain/geolocation/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import BackgroundGeolocation from 'react-native-background-geolocation'

import Minilog from 'cozy-minilog'

const log = Minilog('📍 Geolocation')

export const getTs = (location: { timestamp: string }): number => {
return parseISOString(location.timestamp).getTime() / 1000
}

export const parseISOString = (ISOString: string): Date => {
const b = ISOString.split(/\D+/)
// @ts-expect-error - Date.UTC() expects number arguments, not stringed numbers
// But at the time of this refactoring, not feeling safe enough to change this
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]))
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@paultranvan is it okay for you?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what it means for CozyGPSMemory: will it require some extra ts config?
I'm a bit worried that it may introduce more harm than good

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what it means for CozyGPSMemory: will it require some extra ts config? I'm a bit worried that it may introduce more harm than good

I don't think it should impact CozyGPSMemory, I think the issue here could be an unexpected behaviour at runtime with the casting to Number explicitly (this was required for stronger type inference).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the issue here could be an unexpected behaviour at runtime with the casting to Number explicitly

I'm not sure what you imply here: do you mean an issue could arise if the variable is actually not a number (which is normal), or that this issue could arise anyway?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed runtime modifications


const Logger = BackgroundGeolocation.logger

export const Log = (message: string): void => {
log.debug(message)
Logger.debug(message)
}

export const getAllLogs = async (): Promise<string> => {
return Logger.getLog()
}

export const sendLogFile = (): Promise<boolean> => {
return Logger.emailLog('')
}
2 changes: 1 addition & 1 deletion src/app/view/Loading/RemountProgress.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const RemountProgress = (): JSX.Element => {
}

const progressBarConfig = {
width: null,
width: undefined,
indeterminate: true,
unfilledColor: palette.Grey[200],
color: palette.Primary[600],
Expand Down
87 changes: 68 additions & 19 deletions src/components/Bar.js → src/components/Bar.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,50 @@
// This was taken from https://github.com/oblador/react-native-progress because hacks were needed
// At this time the fastest was just to copy the file, it has no dependencies

import React, { Component } from 'react'
import { Animated, Easing, View, I18nManager } from 'react-native'
import React, { Component, ReactElement } from 'react'
import {
Animated,
Easing,
View,
I18nManager,
ViewStyle,
StyleProp
} from 'react-native'

const INDETERMINATE_WIDTH_FACTOR = 0.6 // 0.3 to 0.6
const BAR_WIDTH_ZERO_POSITION =
INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR)

export default class ProgressBar extends Component {
interface ProgressBarProps {
animated?: boolean
borderRadius?: number
borderWidth?: number
color?: string
height?: number
indeterminate?: boolean
indeterminateAnimationDuration?: number
progress?: number
width?: number
useNativeDriver?: boolean
animationConfig?: { bounciness: number }
animationType?: string
onLayout?: (event: unknown) => void
unfilledColor?: string
borderColor?: string
style?: StyleProp<ViewStyle>
children?: ReactElement
}

interface ProgressBarState {
width: number
progress: Animated.Value
animationValue: Animated.Value
}

export default class ProgressBar extends Component<
ProgressBarProps,
ProgressBarState
> {
static defaultProps = {
animated: true,
borderRadius: 4,
Expand All @@ -24,9 +60,9 @@ export default class ProgressBar extends Component {
animationType: 'spring'
}

constructor(props) {
constructor(props: ProgressBarProps) {
super(props)
const progress = Math.min(Math.max(props.progress, 0), 1)
const progress = Math.min(Math.max(props.progress ?? 0, 0), 1)
this.state = {
width: 0,
progress: new Animated.Value(
Expand All @@ -36,20 +72,20 @@ export default class ProgressBar extends Component {
}
}

componentDidMount() {
componentDidMount(): void {
if (this.props.indeterminate) {
this.animate()
}
}

componentDidUpdate(prevProps) {
componentDidUpdate(prevProps: ProgressBarProps): void {
if (prevProps.indeterminate !== this.props.indeterminate) {
if (this.props.indeterminate) {
this.animate()
} else {
Animated.spring(this.state.animationValue, {
toValue: BAR_WIDTH_ZERO_POSITION,
useNativeDriver: this.props.useNativeDriver
useNativeDriver: this.props.useNativeDriver ?? false
}).start()
}
}
Expand All @@ -59,22 +95,34 @@ export default class ProgressBar extends Component {
) {
const progress = this.props.indeterminate
? INDETERMINATE_WIDTH_FACTOR
: Math.min(Math.max(this.props.progress, 0), 1)
: Math.min(Math.max(this.props.progress ?? 0, 0), 1)

if (this.props.animated) {
const { animationType, animationConfig } = this.props
Animated[animationType](this.state.progress, {
const animationFunction = Animated[
animationType as keyof typeof Animated
] as (
value: Animated.Value,
config: Animated.SpringAnimationConfig
) => Animated.CompositeAnimation
animationFunction(this.state.progress, {
...animationConfig,
toValue: progress,
useNativeDriver: this.props.useNativeDriver
}).start()
useNativeDriver: this.props.useNativeDriver ?? false
}).start((endState: { finished: boolean }) => {
if (endState.finished && this.props.indeterminate) {
this.animate()
}
})
} else {
this.state.progress.setValue(progress)
}
}
}

handleLayout = event => {
handleLayout = (event: {
nativeEvent: { layout: { width: number } }
}): void => {
if (!this.props.width) {
this.setState({ width: event.nativeEvent.layout.width })
}
Expand All @@ -83,22 +131,22 @@ export default class ProgressBar extends Component {
}
}

animate() {
animate(): void {
this.state.animationValue.setValue(0)
Animated.timing(this.state.animationValue, {
toValue: 1,
duration: this.props.indeterminateAnimationDuration,
easing: Easing.linear,
isInteraction: false,
useNativeDriver: this.props.useNativeDriver
useNativeDriver: this.props.useNativeDriver ?? false
}).start(endState => {
if (endState.finished) {
this.animate()
}
})
}

render() {
render(): JSX.Element {
const {
borderColor,
borderRadius,
Expand All @@ -112,15 +160,16 @@ export default class ProgressBar extends Component {
...restProps
} = this.props

const innerWidth = Math.max(0, width || this.state.width) - borderWidth * 2
const innerWidth =
Math.max(0, width ?? this.state.width) - (borderWidth ?? 1) * 2
const containerStyle = {
width,
borderWidth,
borderColor: borderColor || color,
borderColor: borderColor ?? color,
borderRadius,
overflow: 'hidden',
backgroundColor: unfilledColor
}
} as ViewStyle
const progressStyle = {
backgroundColor: color,
borderRadius: 100, // Added
Expand Down
2 changes: 1 addition & 1 deletion src/components/ProgressContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { styles } from '/components/ProgressContainer.styles'
const colors = getColors()

const progressBarConfig = {
width: null,
width: undefined,
indeterminate: false,
unfilledColor: palette.Grey[200],
color: colors.primaryColor,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ const colors = getColors()
const body = `
<div class="d-flex flex-grow-1 flex-column justify-content-center text-center">
<div class="mb-4">
${getLogoSvg({ backgroundColor: colors.primaryColor })}
${getLogoSvg({
backgroundColor: colors.primaryColor,
foregroundColor: colors.paperBackgroundColor
})}
</div>

<div class="h2 mb-3">${t('screens.welcome.title')}</div>
Expand Down
12 changes: 9 additions & 3 deletions src/components/makeHTML.js → src/components/makeHTML.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import { themeCss } from '/screens/login/components/assets/common/css/cssTheme'

import { getLocalFonts } from './getLocalFonts'

const makeDOM = ({ body, isInverted }) => {
const makeDOM = ({
body,
isInverted
}: {
body: string
isInverted: boolean
}): string => {
const { navbarHeight, statusBarHeight } = getDimensions()

const theme = isInverted ? 'theme-inverted' : ''
Expand All @@ -32,10 +38,10 @@ const makeDOM = ({ body, isInverted }) => {
`
}

export const makeHTML = body => {
export const makeHTML = (body: string): string => {
return makeDOM({ body, isInverted: false })
}

export const makeInvertedHTML = body => {
export const makeInvertedHTML = (body: string): string => {
return makeDOM({ body, isInverted: true })
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ const xml = `
</svg>
`

class SVG extends React.Component {
render() {
class SVG extends React.Component<{
width: number
height: number
color: string
}> {
render(): JSX.Element {
return (
<SvgXml
xml={xml}
Expand Down
4 changes: 2 additions & 2 deletions src/components/webviews/CozyWebview.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jest.mock('react-native-file-viewer', () => ({
jest.mock('@react-native-cookies/cookies', () => ({
set: jest.fn()
}))
jest.mock('/libs/RootNavigation.js', () => ({
jest.mock('/libs/RootNavigation', () => ({
navigationRef: {
getCurrentRoute: jest.fn().mockReturnValue({ name: 'home' })
}
Expand Down Expand Up @@ -65,7 +65,7 @@ jest.mock('@react-navigation/native', () => ({
useIsFocused: () => mockUseIsFocused()
}))

jest.mock('../../hooks/useSession.js', () => ({
jest.mock('../../hooks/useSession', () => ({
useSession: () => ({
shouldInterceptAuth: false,
handleInterceptAuth: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
/* eslint-disable no-console */
/* eslint-disable no-console */ // we're mocking console
import { tryConsole } from './jsLogInterception'

const logId = 'logId'
const logger = {
log: jest.fn(),
debug: jest.fn()
} as unknown as MiniLogger

type MakePayload = ({ type, args }: { type: string; args?: string[] }) => {
nativeEvent: {
data: string
}
}
const makePayload = ({ type, args }) => ({

const makePayload: MakePayload = ({ type, args }) => ({
nativeEvent: {
data: JSON.stringify({
type: 'Console',
data: { type, log: ['one', 'two', 'three', ...(args || [])] }
data: { type, log: ['one', 'two', 'three', ...(args ?? [])] }
})
}
})
Expand Down Expand Up @@ -66,6 +73,7 @@ it('handles post-me case', () => {
it('recovers when erroring', () => {
console.error = jest.fn()

// @ts-expect-error - we're testing error handling
tryConsole()

expect(console.error).toHaveBeenCalledTimes(1)
Expand Down
Loading