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

feat: import config #55

Merged
merged 33 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
9d4662b
Sets up basics for device naming screen. Still needs api call to work.
cimigree Dec 3, 2024
1ebb36c
Removes console logs.
cimigree Dec 4, 2024
0ed4682
Adds the next screen create join project screen to check that the dev…
cimigree Dec 4, 2024
45e02b5
Adds segmenter count and byte count to limit device name length.
cimigree Dec 4, 2024
5441dda
Makes reusable onboarding layout component. Makes create join project…
cimigree Dec 4, 2024
b3747c2
Merges with main for device naming grapheme count logic.
cimigree Dec 4, 2024
8b2414b
Updates grapheme count methods
cimigree Dec 4, 2024
527f4c8
Moves files into various folders and updates imports. Fixes height is…
cimigree Dec 5, 2024
087c785
Adjustments to device naming screen.
cimigree Dec 5, 2024
5465d5f
Fixes height of screens. Finishes basic UI for create a project screen.
cimigree Dec 5, 2024
2e0ffca
Allows button to take className prop. Sets up top menu so user cannot…
cimigree Dec 5, 2024
856bf01
Adds join project screen.
cimigree Dec 9, 2024
35e5687
Adds bigger icons
cimigree Dec 9, 2024
ce4e810
Fixes styling and responsiveness of first screen.
cimigree Dec 9, 2024
586d2d3
Makes the layout and menu component just styles and less logic. Moves…
cimigree Dec 10, 2024
e99e409
CHanges spacing to 12 and 20 to reflect design decision.
cimigree Dec 11, 2024
3434ed7
Adds ability to import a config file while creating a project.
cimigree Dec 11, 2024
f3d6c8b
Merges with main.
cimigree Dec 12, 2024
ca1c0fc
Some tweaks to file after merge conflicts.
cimigree Dec 12, 2024
5ea8957
Adds a test for the config file importer test.
cimigree Dec 12, 2024
f52ab4b
Adds a test for the config file importer test.
cimigree Dec 12, 2024
29a1e64
Merge branch 'main' into feat/import-config
cimigree Dec 13, 2024
5a0c1bd
Merges with main.
cimigree Dec 16, 2024
1d4d7da
Merges with main.
cimigree Jan 6, 2025
ab532c5
Merge branch 'main' into feat/import-config
cimigree Jan 6, 2025
9de7aac
Replaces html file input with hook that uses electron import dialog. …
cimigree Jan 6, 2025
f105668
Fixes import. Fixes test.
cimigree Jan 6, 2025
d0ce621
Merge branch 'main' into feat/import-config
cimigree Jan 7, 2025
36101ed
Fixes project creation error message. Fixes test. Displays file name …
cimigree Jan 7, 2025
00a3a47
Removes unnecessary prop from test.
cimigree Jan 7, 2025
1d2958b
Merge branch 'main' into feat/import-config
cimigree Jan 7, 2025
768cff9
Updates config importer to use new select file. Updates test.
cimigree Jan 7, 2025
924c8f7
Updates test to include throwing an error.
cimigree Jan 8, 2025
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
6 changes: 3 additions & 3 deletions messages/renderer/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -212,15 +212,15 @@
"screens.PrivacyPolicy.whyCollectedDescription": {
"message": "Crash data and app errors together with the device and app info provide Awana Digital with the information we need to fix errors and bugs in the app. The performance data helps us improve the responsiveness of the app and identify errors. User counts, including total users, users per country, and users per project, help justify ongoing investment in the development of CoMapeo."
},
"screens.ProjectCreationScreen.addName": {
"message": "Create Project"
},
"screens.ProjectCreationScreen.advancedProjectSettings": {
"message": "Advanced Project Settings"
},
"screens.ProjectCreationScreen.characterCount": {
"message": "{count}/{maxLength}"
},
"screens.ProjectCreationScreen.createProject": {
"message": "Create Project"
},
"screens.ProjectCreationScreen.enterNameLabel": {
"message": "Name your project"
},
Expand Down
10 changes: 8 additions & 2 deletions src/renderer/src/hooks/mutations/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,14 @@ export function useCreateProject() {

return useMutation({
mutationKey: [CREATE_PROJECT_KEY],
mutationFn: (name?: string) => {
return api.createProject({ name })
mutationFn: (opts?: Parameters<typeof api.createProject>[0]) => {
if (opts) {
return api.createProject(opts)
} else {
// Have to avoid passing `undefined` explicitly
// See https://github.com/digidem/comapeo-mobile/issues/392
return api.createProject()
}
},
onSuccess: () => {
queryClient.invalidateQueries({
Expand Down
70 changes: 70 additions & 0 deletions src/renderer/src/hooks/useConfigFileImporter.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'

import { useSelectProjectConfigFile } from './mutations/file-system'

describe('useSelectProjectConfigFile', () => {
Copy link
Member

Choose a reason for hiding this comment

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

non-blocking but would be good to add a test here for when the payload from window.runtime.selectFile() is invalid e.g. the path or name are not strings

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Just FYI, to get it to "throw" the error, I have to mock the selectFile as a rejected promise... because otherwise I would actually have to spin up Electron or the preload script with an integration test or an E2E test. Hope that is ok. Is this useful? Not sure...

Copy link
Member

@achou11 achou11 Jan 8, 2025

Choose a reason for hiding this comment

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

I have to mock the selectFile as a rejected promise

yeah this is what I figured you would do for now. think that's fine 👍

EDIT: re-reading it and yeah, my initial suggestion was something that can't be done easily (i.e. stub the ipc call to electron). there's probably a way to do it but not worth figuring it out. Given that, maybe not as useful as I initially thought

beforeEach(() => {
window.runtime = {
init: vi.fn(),
getLocale: vi.fn().mockResolvedValue('en'),
updateLocale: vi.fn(),
selectFile: vi.fn(),
}
})

it('returns file path from window.runtime.selectFile', async () => {
vi.spyOn(window.runtime, 'selectFile').mockResolvedValue(
'/some/path.comapeocat',
)

const queryClient = new QueryClient()

const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)

const { result } = renderHook(() => useSelectProjectConfigFile(), {
wrapper,
})

let selectedPath: string | undefined

await act(async () => {
await result.current.mutateAsync(undefined, {
onSuccess: (val) => {
selectedPath = val
},
})
cimigree marked this conversation as resolved.
Show resolved Hide resolved
})

expect(selectedPath).toBe('/some/path.comapeocat')
})

it('returns undefined if user cancels', async () => {
vi.spyOn(window.runtime, 'selectFile').mockResolvedValue(undefined)

const queryClient = new QueryClient()

const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)

const { result } = renderHook(() => useSelectProjectConfigFile(), {
wrapper,
})

let selectedPath: string | undefined

await act(async () => {
await result.current.mutateAsync(undefined, {
onSuccess: (val) => {
selectedPath = val
},
})
cimigree marked this conversation as resolved.
Show resolved Hide resolved
})

expect(selectedPath).toBeUndefined()
})
})
104 changes: 54 additions & 50 deletions src/renderer/src/routes/Onboarding/CreateProjectScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
import { Text } from '../../components/Text'
import { PROJECT_NAME_MAX_LENGTH_GRAPHEMES } from '../../constants'
import { useActiveProjectIdStoreActions } from '../../contexts/ActiveProjectIdProvider'
import { useSelectProjectConfigFile } from '../../hooks/mutations/file-system'
import { useCreateProject } from '../../hooks/mutations/projects'
import ProjectImage from '../../images/add_square.png'

Expand All @@ -37,8 +38,8 @@ export const m = defineMessages({
id: 'screens.ProjectCreationScreen.placeholder',
defaultMessage: 'Project Name',
},
addName: {
id: 'screens.ProjectCreationScreen.addName',
createProject: {
id: 'screens.ProjectCreationScreen.createProject',
defaultMessage: 'Create Project',
},
characterCount: {
Expand Down Expand Up @@ -107,52 +108,64 @@ const HorizontalLine = styled('div')({
function CreateProjectScreenComponent() {
const navigate = useNavigate()
const { formatMessage } = useIntl()

const [projectName, setProjectName] = useState('')
const [error, setError] = useState(false)
const [hasNameError, setHasNameError] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const setProjectNameMutation = useCreateProject()
const [configPath, setConfigPath] = useState<string | null>(null)

const createProjectMutation = useCreateProject()
const selectConfigFile = useSelectProjectConfigFile()
const { setActiveProjectId } = useActiveProjectIdStoreActions()

const [configFileName, setConfigFileName] = useState<string | null>(null)
function handleImportConfig() {
selectConfigFile.mutate(undefined, {
onSuccess: (filePath) => {
if (filePath) {
setConfigPath(filePath)
}
},
onError: (err) => {
console.error('Error selecting file', err)
},
})
}

const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const value = event.target.value
setProjectName(value)

const localError: boolean = checkForError(
value.trim(),
PROJECT_NAME_MAX_LENGTH_GRAPHEMES,
)
setProjectName(value)
if (localError !== error) {
setError(localError)
}
setError(localError)
setHasNameError(localError)
}

const graphemeCount = countGraphemes(projectName.trim())

const handleAddName = () => {
const handleCreateProject = () => {
if (checkForError(projectName, PROJECT_NAME_MAX_LENGTH_GRAPHEMES)) {
setError(true)
setHasNameError(true)
return
}
setProjectNameMutation.mutate(projectName, {
onSuccess: (projectId) => {
setActiveProjectId(projectId)
navigate({ to: '/tab1' })
},
onError: (error) => {
console.error('Error setting project name:', error)
setErrorMessage(formatMessage(m.errorSavingProjectName))
},
})
}

function importConfigFile() {
// Placeholder for file import logic
setConfigFileName('myProjectConfig.comapeocat')
createProjectMutation.mutate(
{ name: projectName.trim(), configPath: configPath ?? undefined },
cimigree marked this conversation as resolved.
Show resolved Hide resolved
{
onSuccess: (projectId) => {
setActiveProjectId(projectId)
navigate({ to: '/tab1' })
},
onError: (error) => {
console.error('Error saving project:', error)
setErrorMessage(formatMessage(m.errorSavingProjectName))
cimigree marked this conversation as resolved.
Show resolved Hide resolved
},
},
)
}

const backPressHandler = setProjectNameMutation.isPending
const backPressHandler = createProjectMutation.isPending
? undefined
: () => navigate({ to: '/Onboarding/CreateJoinProjectScreen' })

Expand All @@ -177,7 +190,7 @@ function CreateProjectScreenComponent() {
value={projectName}
onChange={handleChange}
variant="outlined"
error={error}
error={hasNameError}
sx={{
'& .MuiFormLabel-asterisk': {
color: 'red',
Expand All @@ -197,7 +210,7 @@ function CreateProjectScreenComponent() {
},
}}
/>
<CharacterCount error={error}>
<CharacterCount error={hasNameError}>
{formatMessage(m.characterCount, {
count: graphemeCount,
maxLength: PROJECT_NAME_MAX_LENGTH_GRAPHEMES,
Expand Down Expand Up @@ -243,41 +256,32 @@ function CreateProjectScreenComponent() {
maxWidth: 350,
padding: '12px 20px',
}}
onClick={importConfigFile}
onClick={handleImportConfig}
>
{formatMessage(m.importConfig)}
</Button>
{configFileName && (
{configPath && (
<Text style={{ textAlign: 'center', marginTop: 12 }}>
{configFileName}
{configPath}
achou11 marked this conversation as resolved.
Show resolved Hide resolved
</Text>
)}
</AccordionDetails>
</Accordion>
</div>
</div>
<div
<Button
onClick={handleCreateProject}
style={{
marginTop: 12,
width: '100%',
display: 'flex',
justifyContent: 'center',
maxWidth: 350,
padding: '12px 20px',
}}
disabled={createProjectMutation.isPending}
>
<Button
onClick={handleAddName}
style={{
width: '100%',
maxWidth: 350,
padding: '12px 20px',
}}
disabled={setProjectNameMutation.isPending}
>
{setProjectNameMutation.isPending
? formatMessage(m.saving)
: formatMessage(m.addName)}
</Button>
</div>
{createProjectMutation.isPending
? formatMessage(m.saving)
: formatMessage(m.createProject)}
cimigree marked this conversation as resolved.
Show resolved Hide resolved
</Button>
</OnboardingScreenLayout>
)
}
4 changes: 0 additions & 4 deletions src/renderer/src/routes/Onboarding/DeviceNamingScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,3 @@ export function DeviceNamingScreenComponent() {
</OnboardingScreenLayout>
)
}

export function getUtf8ByteLength(text: string): number {
return new TextEncoder().encode(text).length
}
Loading