Skip to content

Commit

Permalink
Merge pull request #50 from skorphil/update-institution-scenario
Browse files Browse the repository at this point in the history
Implemented update institution scenario
  • Loading branch information
skorphil authored Feb 24, 2024
2 parents 1e1796d + 243aed4 commit b466174
Show file tree
Hide file tree
Showing 10 changed files with 277 additions and 99 deletions.
16 changes: 13 additions & 3 deletions components/AssetContainer/AssetContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,28 @@ export function AssetContainer({
isCompact = false,
onDeleteAsset,
}) {
const { register } = useFormContext();
const { register, setValue, getFieldState, formState } = useFormContext();
// const { isDirty } = getFieldState(`${assetName}`, formState);

const amountInput = (
<HStack align="end" spacing={1} flex={1}>
{/* <p>{`fieldState: ${isDirty}`}</p> */}
<FormControl>
{isCompact || <FormLabel>Amount</FormLabel>}
<NumberInput>
<NumberInputField {...register(`${assetName}.amount`)} px={2} />
<NumberInputField
{...register(`${assetName}.amount`, { valueAsNumber: true })}
px={2}
/>
</NumberInput>
</FormControl>
<Input
{...register(`${assetName}.currency`)}
{...register(`${assetName}.currency`, {
onChange: (e) => {
const upperCaseValue = e.target.value.toUpperCase();
setValue(`${assetName}.currency`, upperCaseValue);
},
})}
placeholder="USD"
flexShrink={0}
w={14}
Expand Down
4 changes: 4 additions & 0 deletions components/AssetContainer/helperFunctions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const formatCurrency = (assetName, event) => {
const modifiedValue = event.target.value.toUpperCase();
setValue(`${assetName}.currency`, modifiedValue);
};
21 changes: 19 additions & 2 deletions components/InstitutionContainer/InstitutionContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,14 @@ const AssetsList = ({ isInstitutionOpen, institutionName }) => {
} = useFieldArray({
name: arrayName,
});
const { resetField } = useFormContext();
const {
resetField,
getValues,
formState: { isDirty, dirtyFields, defaultValues },
} = useFormContext();
// const { fields: institutionFields } = useFieldArray({
// name: "institutions.0.assets.0",
// });

return (
<VStack
Expand All @@ -134,6 +141,14 @@ const AssetsList = ({ isInstitutionOpen, institutionName }) => {
isCompact={!isInstitutionOpen}
/>
))}
{/* TEST HERE */}
<Button onClick={() => console.log("assets:", assets)}>Log assets</Button>
<Button onClick={() => console.log("dirtyFields:", dirtyFields)}>
Log dirty
</Button>
<Button onClick={() => console.log(defaultValues.institutions[0])}>
getValues
</Button>

{isInstitutionOpen && (
<>
Expand Down Expand Up @@ -169,7 +184,9 @@ const InstitutionNameInput = ({ institutionName }) => {
<FormLabel>Institution Name</FormLabel>
<Input
disabled={true}
{...register(`${institutionName}.name`, {})}
{...register(`${institutionName}.name`, {
// disabled: true, // Not showing it inside header with `getValues` or `watch`.
})}
px={2}
w="100%"
/>
Expand Down
48 changes: 34 additions & 14 deletions components/InstitutionTab/InstitutionTab.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,38 @@

import { IconButton, Tab, forwardRef, Box } from "@chakra-ui/react";
import { CgUndo } from "react-icons/cg";
import { useFormContext, useWatch } from "react-hook-form";
import classes from "./InstitutionTab.module.css";

export const InstitutionTab = forwardRef(
(
{ name = "Unnamed institution", isDeleted = false, state = null, ...props },
ref
) => (
<Tab
isDisabled={isDeleted}
className={`${classes.tab} ${isDeleted && classes.deleted}`}
ref={ref}
{...props}
>
<Box className={classes.tabName}>{name}</Box>
<TabRightSection state={state} isDeleted={isDeleted} />
</Tab>
)
({ isDeleted = false, institutionName, ...props }, ref) => {
const { formState, getValues, control } = useFormContext();
const institutionDefaultValues =
formState.defaultValues.institutions[
getInstitutionIndex(institutionName)
];
const institutionCurrentValues = getValues(institutionName);
const isChanged =
JSON.stringify(institutionDefaultValues) !==
JSON.stringify(institutionCurrentValues);
const state = isChanged ? "updated" : null;
const name = useWatch({
control,
name: `${institutionName}.name`,
});

return (
<Tab
isDisabled={isDeleted}
className={`${classes.tab} ${isDeleted && classes.deleted}`}
ref={ref}
{...props}
>
<Box className={classes.tabName}>{name}</Box>
<TabRightSection state={state} isDeleted={isDeleted} />
</Tab>
);
}
);

function TabRightSection({ state, isDeleted }) {
Expand All @@ -39,3 +54,8 @@ function TabRightSection({ state, isDeleted }) {
);
} else return false;
}

function getInstitutionIndex(institutionName) {
const index = parseInt(institutionName.split(".")[1]);
return index;
}
129 changes: 49 additions & 80 deletions components/InstitutionTab/docs.md
Original file line number Diff line number Diff line change
@@ -1,89 +1,58 @@
## Altering components style in chakra ui
[Build your own design system with chakraui | Youtube](https://youtu.be/epJuxo8FKFA?si=UEmVtkfPLerimLkN&t=1210)

The fundamental approach:
1. Create components style file, according to Chakra style API
2. Use methods `definePartsStyle`, `defineMultiStyleConfig`
3. extend chacra's `theme` appending component styles with `extendTheme` ([theme.js](app/ChakraTheme.js))
4. pass `theme` as prop to `ChakraProvider`


Tabs is a multipart component - [chackra docs | styling-multipart-components](https://chakra-ui.com/docs/styled-system/component-style#styling-multipart-components) and require `definePartsStyle`, `defineMultiStyleConfig` methods


- [ ] How to use props do be passed to styles?

Chakra tab custom styles
```js
import { createMultiStyleConfigHelpers, defineStyle } from "@chakra-ui/react";
const { definePartsStyle, defineMultiStyleConfig } =
createMultiStyleConfigHelpers(["tablist", "tab"]);

export const tabsTheme = defineMultiStyleConfig({
variants: {
grid: {
tab: {
borderRadius: "base",
_selected: {
bg: "black",
},
## InstitutionTab
### Props
```diff
//Props
- isNew
- isDeleted
- isUpdated
- text
+ insitutionName (string)
onRestore

//Context
+ fields from useFieldArray()
+ getValue
+ getFieldState
```

justifyContent: "flex-start",
},
tablist: {
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(100px,1fr))",
gap: "3",
w: "100%",
},
},
},
});
### Listeners
- restoreButton click

### States
```mermaid
---
title: InstitutionTab
---
stateDiagram-v2
direction LR
[*] --> existing
existing --> updated : prop changed
updated --> existing : prop changed
updated --> deleted : prop changed
existing --> deleted : prop changed
deleted --> updated : BUTTON_PRESS <br/> Do / setState
deleted --> existing : BUTTON_PRESS <br/> Do / setState
[*] --> new
```

## Worklog
### Deriving the states
I want to minimize states number. By somehow derive from existing use-hook-form states

ChakraTheme.js
```js
import { tabsTheme } from "../components/InstitutionTab/Tabs.chakra";
...
const theme = extendTheme({
config,
components: {
Tabs: tabsTheme,
},
});
#### New state
Probably can be known via comparison between institution value and defaultValues(which are retrieved)
For this scenario probably the simplest reliable way is to generate unique ID for institution and store it in db.

export default theme;
```
*defaultValues* can be retrieved from `fields` https://react-hook-form.com/docs/usefieldarray#:~:text=Description-,fields,-object%20%26%20%7B%20id

if `institutions.ID.name` from `fields` === '' than institution is new

## ForwardRef to extend component
`forwardRef` https://chakra-ui.com/community/recipes/as-prop#option-1-using-forwardref-from-chakra-uireact
#### Deleted state
can be set by disabling institution fields

Seems to work

```js
const IntitutionTab = forwardRef((props, ref) => (
<Tab px="4" py="5" rounded="sm" shadow="lg" ref={ref} {...props}>
Custom Tab
</Tab>
));
...
<IntitutionTab bg="red" />
```
#### Updated state
can be retrived from `isDirty`

```js
const IntitutionTab = forwardRef(
(
{ name = "Unnamed institution", isDeleted = false, state = null, ...props },
ref
) => {
...
<Tab
isDisabled={isDeleted}
paddingRight={rightSection && 1}
className={`${classes.tab} ${isDeleted && classes.deleted}`}
ref={ref}
{...props}
>
```
### Text prop
`text`(`InstitutionName`) can be retrieved by `getValues()`, **but there is problem of retreiving value from disabled inputs**(which i planned to use for deleted state) https://github.com/orgs/react-hook-form/discussions/11533
89 changes: 89 additions & 0 deletions components/InstitutionTab/learned.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
## Altering components style in chakra ui
[Build your own design system with chakraui | Youtube](https://youtu.be/epJuxo8FKFA?si=UEmVtkfPLerimLkN&t=1210)

The fundamental approach:
1. Create components style file, according to Chakra style API
2. Use methods `definePartsStyle`, `defineMultiStyleConfig`
3. extend chacra's `theme` appending component styles with `extendTheme` ([theme.js](app/ChakraTheme.js))
4. pass `theme` as prop to `ChakraProvider`


Tabs is a multipart component - [chackra docs | styling-multipart-components](https://chakra-ui.com/docs/styled-system/component-style#styling-multipart-components) and require `definePartsStyle`, `defineMultiStyleConfig` methods


- [ ] How to use props do be passed to styles?

Chakra tab custom styles
```js
import { createMultiStyleConfigHelpers, defineStyle } from "@chakra-ui/react";
const { definePartsStyle, defineMultiStyleConfig } =
createMultiStyleConfigHelpers(["tablist", "tab"]);

export const tabsTheme = defineMultiStyleConfig({
variants: {
grid: {
tab: {
borderRadius: "base",
_selected: {
bg: "black",
},

justifyContent: "flex-start",
},
tablist: {
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(100px,1fr))",
gap: "3",
w: "100%",
},
},
},
});
```


ChakraTheme.js
```js
import { tabsTheme } from "../components/InstitutionTab/Tabs.chakra";
...
const theme = extendTheme({
config,
components: {
Tabs: tabsTheme,
},
});

export default theme;
```


## ForwardRef to extend component
`forwardRef` https://chakra-ui.com/community/recipes/as-prop#option-1-using-forwardref-from-chakra-uireact

Seems to work

```js
const IntitutionTab = forwardRef((props, ref) => (
<Tab px="4" py="5" rounded="sm" shadow="lg" ref={ref} {...props}>
Custom Tab
</Tab>
));
...
<IntitutionTab bg="red" />
```

```js
const IntitutionTab = forwardRef(
(
{ name = "Unnamed institution", isDeleted = false, state = null, ...props },
ref
) => {
...
<Tab
isDisabled={isDeleted}
paddingRight={rightSection && 1}
className={`${classes.tab} ${isDeleted && classes.deleted}`}
ref={ref}
{...props}
>
```
1 change: 1 addition & 0 deletions components/InstitutionsTabsList/InstitutionsTabsList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export function InstitutionsTabsList({
// as={motion.div}
// layout="position"
width={isKeyboardOpened && "180px"}
institutionName={`institutions.${id}`}
key={`institutionTab-${id}`}
name={institution.name}
state="new"
Expand Down
2 changes: 2 additions & 0 deletions components/RecordForm/RecordForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { CgMinimizeAlt } from "react-icons/cg";

import { InstitutionsList } from "../InstitutionsList";
import { FormHeader } from "~/FormHeader";
import { DevTool } from "@hookform/devtools";

const prevRecord = {
institutions: [
Expand Down Expand Up @@ -142,6 +143,7 @@ export function RecordForm({ onSubmit }) {
// institutions={prevRecord.institutions}
/>
</form>
<DevTool control={formMethods.control} />
</FormProvider>
);
}
Loading

0 comments on commit b466174

Please sign in to comment.