Skip to content

Commit

Permalink
Make FE code formatting more clear (#395)
Browse files Browse the repository at this point in the history
* Clarify information about code style

* Update workflow with format check

* Fix formatting

* Update formatting settings & extension recommendations for VSCode workspace

* Add eslint to pre-commit check

---------

Co-authored-by: Michael Bunsen <[email protected]>
  • Loading branch information
annavik and mihow authored Jun 5, 2024
1 parent 696ba3f commit 936590f
Show file tree
Hide file tree
Showing 29 changed files with 419 additions and 328 deletions.
8 changes: 5 additions & 3 deletions .github/workflows/test.frontend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ on:
- "!./**"
- "ui/**"


push:
branches: ["master", "main"]
paths:
Expand Down Expand Up @@ -41,7 +40,10 @@ jobs:
- name: Install Dependencies
run: yarn install

- name: Run ESLint
- name: Check Format
run: yarn format --check

- name: Run Linter
run: yarn lint

test:
Expand All @@ -61,5 +63,5 @@ jobs:
- name: Install Dependencies
run: yarn install

- name: Run tests
- name: Run Tests
run: yarn test --watchAll=false
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ repos:
- id: djlint-reformat-django
- id: djlint-django

- repo: https://github.com/pre-commit/mirrors-eslint
rev: v9.4.0
hooks:
- id: eslint
args: ['--ext', '.js,.jsx,.ts,.tsx']


# sets up .pre-commit-ci.yaml to ensure pre-commit dependencies stay up to date
ci:
autoupdate_schedule: weekly
Expand Down
16 changes: 16 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"recommendations": [
"batisteo.vscode-django",
"ms-python.black-formatter",
"dbaeumer.vscode-eslint",
"ms-python.isort",
"esbenp.prettier-vscode",
"ms-python.python",
"foxundermoon.shell-format",
"ms-azuretools.vscode-docker"

],
"unwantedRecommendations": [

]
}
36 changes: 28 additions & 8 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,38 @@
{
"python.formatting.provider": "none",
"editor.formatOnSave": true,
"python.linting.enabled": true,
"python.linting.flake8Enabled": true,
"[python]": {
"editor.formatOnSave": true,
"diffEditor.codeLens": true,
"editor.defaultFormatter": "ms-python.black-formatter"
},
"diffEditor.codeLens": true,
"eslint.enable": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit",
"source.sortImports": "explicit",
"source.fixAll.markdownlint": "explicit",
"source.fixAll": "explicit"
},
"isort.args": [
"--profile",
"black"
],
"typescript.format.enable": true,
"prettier.requireConfig": true,
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"files.eol": "\n",
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true
}
11 changes: 7 additions & 4 deletions ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,17 @@ Now you can navigate to the following URL: http://localhost:3000

## Code style

We use [Prettier](https://prettier.io/) as a code formatter. You can setup your code editor to auto format the code you write, based on the project config. There is also an option to run the following command from terminal:
We use [Prettier](https://prettier.io/) as a code formatter. The project preferences are specified in `prettierrc.json`. If you are using Visual Stuido Code, the extension [Prettier - Code formatter](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) is recommended for auto formating in editor. There is also an option to run the following commands from terminal:

```bash
# Auto formats all code in folder src
yarn format
# Check format for all code in folder src
yarn format --check

# Auto format all code in folder src
yarn format --write
```

We use [ESLint](https://eslint.org/) to find issues in the code. You can setup your code editor to highlight such issues, based on the project config. There is also an option to run the following command from terminal:
We use [ESLint](https://eslint.org/) to find issues in the code. The project preferences are specified in `eslintrc.json`. If you are using Visual Stuido Code, the extension [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) is recommended for highlighting lint issues in editor. There is also an option to run the following command from terminal:

```bash
# Run linter for all code in folder src
Expand Down
2 changes: 1 addition & 1 deletion ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"build": "tsc && vite build",
"preview": "vite preview",
"test": "jest",
"format": "prettier --write \"src/**/*.{ts,tsx,css}\"",
"format": "prettier \"src/**/*.{ts,tsx,css}\"",
"lint": "eslint \"src/**/*.{ts,tsx}\"",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
Expand Down
22 changes: 15 additions & 7 deletions ui/src/data-services/hooks/captures/useStarCapture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,28 @@ import { API_ROUTES, API_URL } from 'data-services/constants'
import { getAuthHeader } from 'data-services/utils'
import { useUser } from 'utils/user/userContext'


export const useStarCapture = (id: string, isStarred: boolean, onSuccess?: () => void) => {
export const useStarCapture = (
id: string,
isStarred: boolean,
onSuccess?: () => void
) => {
const { user } = useUser()
const queryClient = useQueryClient()

const captureDetailUrl = `${API_URL}/${API_ROUTES.CAPTURES}/${id}`
const mutationUrl = isStarred ? `${captureDetailUrl}/unstar/` : `${captureDetailUrl}/star/`
const mutationUrl = isStarred
? `${captureDetailUrl}/unstar/`
: `${captureDetailUrl}/star/`

const { mutateAsync, isLoading, isSuccess, error } = useMutation({
mutationFn: () =>
axios.post(mutationUrl, {}, {
headers: getAuthHeader(user),
}),
axios.post(
mutationUrl,
{},
{
headers: getAuthHeader(user),
}
),
onSuccess: () => {
queryClient.invalidateQueries([API_ROUTES.CAPTURES])
onSuccess?.()
Expand All @@ -25,4 +34,3 @@ export const useStarCapture = (id: string, isStarred: boolean, onSuccess?: () =>

return { starCapture: mutateAsync, isLoading, isSuccess, error }
}

28 changes: 16 additions & 12 deletions ui/src/data-services/hooks/collections/usePopulateCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,22 @@ import { getAuthHeader } from 'data-services/utils'
import { useUser } from 'utils/user/userContext'

export const usePopulateCollection = () => {
const { user } = useUser()
const queryClient = useQueryClient()
const { user } = useUser()
const queryClient = useQueryClient()

const { mutateAsync, isLoading, isSuccess, error } = useMutation({
mutationFn: (id: string) =>
axios.post<{ id: number }>(`${API_URL}/${API_ROUTES.COLLECTIONS}/${id}/populate/`, undefined, {
headers: getAuthHeader(user),
}),
onSuccess: () => {
queryClient.invalidateQueries([API_ROUTES.COLLECTIONS])
},
})
const { mutateAsync, isLoading, isSuccess, error } = useMutation({
mutationFn: (id: string) =>
axios.post<{ id: number }>(
`${API_URL}/${API_ROUTES.COLLECTIONS}/${id}/populate/`,
undefined,
{
headers: getAuthHeader(user),
}
),
onSuccess: () => {
queryClient.invalidateQueries([API_ROUTES.COLLECTIONS])
},
})

return { populateCollection: mutateAsync, isLoading, isSuccess, error }
return { populateCollection: mutateAsync, isLoading, isSuccess, error }
}
10 changes: 7 additions & 3 deletions ui/src/data-services/hooks/jobs/useQueueJob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ export const useQueueJob = () => {

const { mutateAsync, isLoading, isSuccess, error } = useMutation({
mutationFn: (id: string) =>
axios.post<{ id: number }>(`${API_URL}/${API_ROUTES.JOBS}/${id}/run/`, undefined, {
headers: getAuthHeader(user),
}),
axios.post<{ id: number }>(
`${API_URL}/${API_ROUTES.JOBS}/${id}/run/`,
undefined,
{
headers: getAuthHeader(user),
}
),
onSuccess: () => {
queryClient.invalidateQueries([API_ROUTES.JOBS])
queryClient.invalidateQueries([API_ROUTES.CAPTURES])
Expand Down
2 changes: 1 addition & 1 deletion ui/src/data-services/hooks/species/useSpeciesDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const convertServerRecord = (record: ServerSpeciesDetails) =>

export const useSpeciesDetails = (
id: string,
projectId: string | undefined,
projectId: string | undefined
): {
species?: SpeciesDetails
isLoading: boolean
Expand Down
36 changes: 21 additions & 15 deletions ui/src/data-services/models/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,18 @@ export type CaptureDetection = {
}

const makeDetectionLabel = (detection: CaptureDetection) => {
const occurrence: DetectionOccurrence | undefined = detection.occurrence;
const occurrence: DetectionOccurrence | undefined = detection.occurrence
if (occurrence && occurrence.determination) {
if (occurrence.determination_score) {
const scorePercentage = Math.round(occurrence.determination_score * 100).toString();
return `${occurrence.determination.name} (${scorePercentage}%)`;
const scorePercentage = Math.round(
occurrence.determination_score * 100
).toString()
return `${occurrence.determination.name} (${scorePercentage}%)`
}
return occurrence.determination.name;
return occurrence.determination.name
}
return detection.id;
};
return detection.id
}

export class Capture {
protected readonly _capture: ServerCapture
Expand All @@ -40,15 +42,19 @@ export class Capture {
this._capture = capture

if (capture.detections?.length) {
this._detections = capture.detections.map((detection: CaptureDetection) => {
return {
bbox: detection.bbox,
id: `${detection.id}`,
label: makeDetectionLabel(detection),
score: detection.score,
occurrenceId: detection.occurrence ? `${detection.occurrence.id}` : undefined,
};
});
this._detections = capture.detections.map(
(detection: CaptureDetection) => {
return {
bbox: detection.bbox,
id: `${detection.id}`,
label: makeDetectionLabel(detection),
score: detection.score,
occurrenceId: detection.occurrence
? `${detection.occurrence.id}`
: undefined,
}
}
)
}
}

Expand Down
4 changes: 1 addition & 3 deletions ui/src/data-services/models/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { snakeCaseToSentenceCase } from 'utils/snakeCaseToSentenceCase'
import { Entity } from './entity'

export class Collection extends Entity {

public constructor(entity: ServerCollection) {
super(entity)
}
Expand All @@ -13,7 +12,7 @@ export class Collection extends Entity {
}

get kwargs(): object {
return this._data.kwargs || {};
return this._data.kwargs || {}
}

get methodNameDisplay(): string {
Expand All @@ -33,5 +32,4 @@ export class Collection extends Entity {
get numImages(): number | undefined {
return this._data.source_image_count
}

}
5 changes: 3 additions & 2 deletions ui/src/data-services/models/species-details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ export class SpeciesDetails extends Species {
width: occurrence.best_detection.width,
height: occurrence.best_detection.height,
},
label: `${occurrence.event.name}\n ${occurrence.determination.name
} (${_.round(occurrence.determination_score, 4)})`,
label: `${occurrence.event.name}\n ${
occurrence.determination.name
} (${_.round(occurrence.determination_score, 4)})`,
timeLabel: getCompactTimespanString({
date1: new Date(occurrence.first_appearance_timestamp),
date2: new Date(occurrence.last_appearance_timestamp),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import {
Identification
} from 'data-services/models/occurrence-details'
import { Identification } from 'data-services/models/occurrence-details'
import { Tooltip } from 'design-system/components/tooltip/tooltip'
import { ReactNode } from 'react'
import { getFormatedDateTimeString } from 'utils/date/getFormatedDateTimeString/getFormatedDateTimeString'
Expand All @@ -22,7 +20,9 @@ export const IdentificationSummary = ({
user,
identification,
}: IdentificationSummaryProps) => {
const formattedTime = getFormatedDateTimeString({ date: new Date(identification.createdAt) });
const formattedTime = getFormatedDateTimeString({
date: new Date(identification.createdAt),
})

return (
<div>
Expand Down Expand Up @@ -50,5 +50,5 @@ export const IdentificationSummary = ({
</div>
{children}
</div>
);
};
)
}
3 changes: 2 additions & 1 deletion ui/src/design-system/components/info-block/info-block.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ interface Field {
export const InfoBlock = ({ fields }: { fields: Field[] }) => (
<>
{fields.map((field, index) => {
const value = field.value !== undefined ? field.value : STRING.VALUE_NOT_AVAILABLE
const value =
field.value !== undefined ? field.value : STRING.VALUE_NOT_AVAILABLE

return (
<p className={styles.field} key={index}>
Expand Down
2 changes: 1 addition & 1 deletion ui/src/design-system/components/table/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export { CarouselTheme as ImageCellTheme } from '../image-carousel/types'
export enum CellTheme {
Default = 'default',
Primary = 'primary',
Bubble = 'bubble'
Bubble = 'bubble',
}

export enum TextAlign {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { bytesToMB } from 'utils/bytesToMB'
import { API_MAX_UPLOAD_SIZE } from 'utils/constants'
import { STRING, translate } from 'utils/language'


export const config: FormConfig = {
name: {
label: translate(STRING.FIELD_LABEL_NAME),
Expand Down
Loading

0 comments on commit 936590f

Please sign in to comment.