Skip to content

Commit

Permalink
rework: remove any from type (#638)
Browse files Browse the repository at this point in the history
fix/clear any

Signed-off-by: capyq <[email protected]>
Co-authored-by: capyq <[email protected]>
Co-authored-by: Tristan Chuine <[email protected]>
  • Loading branch information
3 people authored Nov 25, 2024
1 parent 59e7c10 commit e1ca4ca
Show file tree
Hide file tree
Showing 14 changed files with 113 additions and 83 deletions.
13 changes: 10 additions & 3 deletions demo/src/equipment-search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ import { useState } from 'react';
import { Button, TextField } from '@mui/material';
import { Search } from '@mui/icons-material';
import { useIntl } from 'react-intl';
import { ElementSearchDialog, EquipmentItem, equipmentStyles, EquipmentType, useElementSearch } from '../../src/index';
import {
ElementSearchDialog,
EquipmentItem,
EquipmentItemProps,
equipmentStyles,
EquipmentType,
useElementSearch,
} from '../../src/index';

interface AnyElementInterface {
id: string;
Expand Down Expand Up @@ -56,11 +63,11 @@ export function EquipmentSearchDialog() {
open={isSearchOpen}
onClose={() => setIsSearchOpen(false)}
onSearchTermChange={updateSearchTerm}
onSelectionChange={(element: any) => {
onSelectionChange={(element: unknown) => {
console.log(element);
}}
elementsFound={elementsFound}
renderElement={(props: any) => (
renderElement={(props: EquipmentItemProps) => (
<EquipmentItem styles={equipmentStyles} {...props} key={props.element.key} />
)}
searchTerm={searchTerm}
Expand Down
6 changes: 3 additions & 3 deletions demo/src/inline-search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useState } from 'react';
import { TextField } from '@mui/material';
import { Search } from '@mui/icons-material';
import { useIntl } from 'react-intl';
import { ElementSearchInput, EquipmentItem, EquipmentType, equipmentStyles } from '../../src';
import { ElementSearchInput, EquipmentItem, EquipmentItemProps, EquipmentType, equipmentStyles } from '../../src';

export function InlineSearch() {
const [searchTerm, setSearchTerm] = useState('');
Expand All @@ -25,7 +25,7 @@ export function InlineSearch() {
return (
<ElementSearchInput
onSearchTermChange={updateSearchTerm}
onSelectionChange={(element: any) => {
onSelectionChange={(element: unknown) => {
console.log(element);
}}
elementsFound={
Expand All @@ -46,7 +46,7 @@ export function InlineSearch() {
]
: []
}
renderElement={(props: any) => (
renderElement={(props: EquipmentItemProps) => (
<EquipmentItem styles={equipmentStyles} {...props} key={props.element.key} />
)}
searchTerm={searchTerm}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
*/

import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
import { Checkbox, IconButton, ListItemIcon, ListItemText } from '@mui/material';
import { Checkbox, IconButton, ListItemIcon, ListItemText, Theme } from '@mui/material';
import { OverflowableText } from '../overflowableText';
import { DraggableClickableCheckBoxItemProps } from './checkBoxList.type';

const styles = {
dragIcon: (theme: any) => ({
dragIcon: (theme: Theme) => ({
padding: 'unset',
border: theme.spacing(0),
borderRadius: theme.spacing(0),
Expand Down
13 changes: 5 additions & 8 deletions src/components/checkBoxList/DraggableClickableRowItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
*/

import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
import { Checkbox, IconButton, ListItemButton, ListItemIcon, ListItemText } from '@mui/material';
import { Checkbox, IconButton, ListItemButton, ListItemIcon, ListItemText, SxProps, Theme } from '@mui/material';
import { OverflowableText } from '../overflowableText';
import { DraggableClickableRowItemProps } from './checkBoxList.type';
import { mergeSx } from '../../utils';

const styles = {
dragIcon: (theme: any) => ({
const styles: Record<string, SxProps<Theme>> = {
dragIcon: (theme) => ({
padding: 'unset',
border: theme.spacing(0),
borderRadius: theme.spacing(0),
Expand Down Expand Up @@ -45,11 +46,7 @@ export function DraggableClickableRowItem({
return (
<ListItemButton
disableTouchRipple={!isItemClickable}
sx={{
paddingLeft: 0,
...sx?.checkboxButton,
...(!isItemClickable && styles.unclickableItem),
}}
sx={mergeSx({ paddingLeft: 0 }, sx?.checkboxButton, !isItemClickable ? styles.unclickableItem : undefined)}
disabled={disabled}
onClick={handleItemClick}
>
Expand Down
26 changes: 14 additions & 12 deletions src/components/dialogs/customMuiDialog/CustomMuiDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import React, { useCallback, useState } from 'react';
import { FieldErrors, UseFormReturn } from 'react-hook-form';
import { FieldErrors, FieldValues, SubmitHandler, UseFormReturn } from 'react-hook-form';
import { FormattedMessage } from 'react-intl';
import { Dialog, DialogActions, DialogContent, DialogTitle, Grid, LinearProgress } from '@mui/material';
import * as yup from 'yup';
Expand All @@ -15,12 +15,12 @@ import { CancelButton } from '../../inputs/reactHookForm/utils/CancelButton';
import { CustomFormProvider, MergedFormContextProps } from '../../inputs/reactHookForm/provider/CustomFormProvider';
import { PopupConfirmationDialog } from '../popupConfirmationDialog/PopupConfirmationDialog';

export interface CustomMuiDialogProps {
export interface CustomMuiDialogProps<T extends FieldValues = FieldValues> {
open: boolean;
formSchema: yup.AnySchema;
formMethods: UseFormReturn<any> | MergedFormContextProps;
onClose: (event: React.MouseEvent) => void;
onSave: (data: any) => void;
formMethods: UseFormReturn<T> | MergedFormContextProps;
onClose: (event?: React.MouseEvent) => void;
onSave: SubmitHandler<T>;
onValidationError?: (errors: FieldErrors) => void;
titleId: string;
disabledSave?: boolean;
Expand Down Expand Up @@ -76,7 +76,7 @@ export const unscrollableDialogStyles = {
},
};

export function CustomMuiDialog({
export function CustomMuiDialog<T extends FieldValues = FieldValues>({
open,
formSchema,
formMethods,
Expand All @@ -92,9 +92,9 @@ export function CustomMuiDialog({
language,
confirmationMessageKey,
unscrollableFullHeight = false,
}: Readonly<CustomMuiDialogProps>) {
}: Readonly<CustomMuiDialogProps<T>>) {
const [openConfirmationPopup, setOpenConfirmationPopup] = useState(false);
const [validatedData, setValidatedData] = useState(undefined);
const [validatedData, setValidatedData] = useState<T>();
const { handleSubmit } = formMethods;

const handleCancel = useCallback(
Expand All @@ -113,15 +113,15 @@ export function CustomMuiDialog({
};

const validate = useCallback(
(data: any) => {
(data: T) => {
onSave(data);
onClose(data);
onClose();
},
[onClose, onSave]
);

const handleValidate = useCallback(
(data: any) => {
(data: T) => {
if (confirmationMessageKey) {
setValidatedData(data);
setOpenConfirmationPopup(true);
Expand All @@ -134,7 +134,9 @@ export function CustomMuiDialog({

const handlePopupConfirmation = useCallback(() => {
setOpenConfirmationPopup(false);
validate(validatedData);
if (validatedData) {
validate(validatedData);
}
}, [validate, validatedData]);

const handleValidationError = (errors: FieldErrors) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { useCallback } from 'react';
import { useForm } from 'react-hook-form';
import { SubmitHandler, useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { Box } from '@mui/material';
import yup from '../../../utils/yupConfig';
Expand All @@ -26,6 +26,7 @@ export interface DescriptionModificationDialogProps {
const schema = yup.object().shape({
[FieldConstants.DESCRIPTION]: yup.string().max(500, 'descriptionLimitError'),
});
type SchemaType = yup.InferType<typeof schema>;

export function DescriptionModificationDialog({
elementUuid,
Expand Down Expand Up @@ -54,15 +55,17 @@ export function DescriptionModificationDialog({
onClose();
};

const onSubmit = useCallback(
(data: { description: string }) => {
const onSubmit = useCallback<SubmitHandler<SchemaType>>(
(data) => {
updateElement(elementUuid, {
[FieldConstants.DESCRIPTION]: data[FieldConstants.DESCRIPTION].trim(),
}).catch((error: any) => {
snackError({
messageTxt: error.message,
headerId: 'descriptionModificationError',
});
[FieldConstants.DESCRIPTION]: data[FieldConstants.DESCRIPTION]?.trim() ?? '',
}).catch((error: unknown) => {
if (error instanceof Object && 'message' in error && typeof error.message === 'string') {
snackError({
messageTxt: error.message,
headerId: 'descriptionModificationError',
});
}
});
},
[elementUuid, updateElement, snackError]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { FieldConstants } from '../../../utils/constants/fieldConstants';
import { DirectoryItemSelector } from '../../directoryItemSelector/DirectoryItemSelector';
import { ElementType } from '../../../utils/types/elementType';
import { fetchDirectoryElementPath } from '../../../services';
import { ElementAttributes } from '../../../utils';

export interface ModifyElementSelectionProps {
elementType: ElementType;
Expand Down Expand Up @@ -46,8 +47,8 @@ export function ModifyElementSelection(props: ModifyElementSelectionProps) {

useEffect(() => {
if (directory) {
fetchDirectoryElementPath(directory).then((res: any) => {
setActiveDirectoryName(res.map((element: any) => element.elementName.trim()).join('/'));
fetchDirectoryElementPath(directory).then((res: ElementAttributes[]) => {
setActiveDirectoryName(res.map((element: ElementAttributes) => element.elementName.trim()).join('/'));
});
}
}, [directory]);
Expand Down
71 changes: 44 additions & 27 deletions src/components/directoryItemSelector/DirectoryItemSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ElementType } from '../../utils/types/elementType';
import { TreeViewFinder, TreeViewFinderNodeProps, TreeViewFinderProps } from '../treeViewFinder/TreeViewFinder';
import { useSnackMessage } from '../../hooks/useSnackMessage';
import { fetchDirectoryContent, fetchElementsInfos, fetchRootFolders } from '../../services';
import { ElementAttributes } from '../../utils';

const styles = {
icon: (theme: Theme) => ({
Expand All @@ -22,35 +23,49 @@ const styles = {
}),
};

function sameRights(a: any, b: any) {
if (!a && !b) {
// TODO: check avec Kevin / Sylvain
type ElementAttributesBase = {
elementUuid: ElementAttributes['elementUuid'] | null;
subdirectoriesCount: ElementAttributes['subdirectoriesCount'];
parentUuid: ElementAttributes['parentUuid'];
children: ElementAttributes['children'];
};

function sameRights(
sourceAccessRights: ElementAttributes['accessRights'],
accessRightsToCompare: ElementAttributes['accessRights']
) {
if (!sourceAccessRights && !accessRightsToCompare) {
return true;
}
if (!a || !b) {
if (!sourceAccessRights || !accessRightsToCompare) {
return false;
}
return a.isPrivate === b.isPrivate;
return sourceAccessRights.isPrivate === accessRightsToCompare.isPrivate;
}

function flattenDownNodes(n: any, cef: (n: any) => any[]): any[] {
function flattenDownNodes<T>(n: T, cef: (n: T) => T[]): T[] {
const subs = cef(n);
if (subs.length === 0) {
return [n];
}
return Array.prototype.concat([n], ...subs.map((sn: any) => flattenDownNodes(sn, cef)));
return Array.prototype.concat([n], ...subs.map((sn) => flattenDownNodes(sn, cef)));
}

function refreshedUpNodes(m: any[], nn: any): any[] {
if (!nn?.elementUuid) {
function refreshedUpNodes(
nodeMap: Record<UUID, ElementAttributesBase>,
newElement: ElementAttributesBase
): ElementAttributesBase[] {
if (!newElement?.elementUuid) {
return [];
}
if (nn.parentUuid === null) {
return [nn];
if (newElement.parentUuid === null) {
return [newElement];
}
const parent = m[nn.parentUuid];
const nextChildren = parent.children.map((c: any) => (c.elementUuid === nn.elementUuid ? nn : c));
const parent = nodeMap[newElement.parentUuid];
const nextChildren = parent.children.map((c) => (c.elementUuid === newElement.elementUuid ? newElement : c));
const nextParent = { ...parent, children: nextChildren };
return [nn, ...refreshedUpNodes(m, nextParent)];
return [newElement, ...refreshedUpNodes(nodeMap, nextParent)];
}

/**
Expand All @@ -60,10 +75,15 @@ function refreshedUpNodes(m: any[], nn: any): any[] {
* @param nodeId uuid of the node to update children, may be null or undefined (means root)
* @param children new value of the node children (shallow nodes)
*/
function updatedTree(prevRoots: any[], prevMap: any, nodeId: UUID | null, children: any[]) {
function updatedTree(
prevRoots: ElementAttributes[],
prevMap: Record<UUID, ElementAttributes>,
nodeId: UUID | null,
children: ElementAttributes[]
) {
const nextChildren = children
.sort((a, b) => a.elementName.localeCompare(b.elementName))
.map((n: any) => {
.map((n) => {
const pn = prevMap[n.elementUuid];
if (!pn) {
return { ...n, children: [], parentUuid: nodeId };
Expand All @@ -89,15 +109,12 @@ function updatedTree(prevRoots: any[], prevMap: any, nodeId: UUID | null, childr
});

const prevChildren = nodeId ? prevMap[nodeId]?.children : prevRoots;
if (
prevChildren?.length === nextChildren.length &&
prevChildren.every((e: any, i: number) => e === nextChildren[i])
) {
if (prevChildren?.length === nextChildren.length && prevChildren.every((e, i) => e === nextChildren[i])) {
return [prevRoots, prevMap];
}

const nextUuids = new Set(children ? children.map((n) => n.elementUuid) : []);
const prevUuids = prevChildren ? prevChildren.map((n: any) => n.elementUuid) : [];
const prevUuids = prevChildren ? prevChildren.map((n) => n.elementUuid) : [];
const mayNodeId = nodeId ? [nodeId] : [];

const nonCopyUuids = new Set([
Expand All @@ -117,7 +134,7 @@ function updatedTree(prevRoots: any[], prevMap: any, nodeId: UUID | null, childr
...prevNode,
children: nextChildren,
subdirectoriesCount: nextChildren.length,
};
} satisfies ElementAttributesBase;

const nextMap = Object.fromEntries([
...Object.entries(prevMap).filter(([k]) => !nonCopyUuids.has(k)),
Expand Down Expand Up @@ -169,12 +186,12 @@ export function DirectoryItemSelector({
...otherTreeViewFinderProps
}: Readonly<DirectoryItemSelectorProps>) {
const [data, setData] = useState<TreeViewFinderNodeProps[]>([]);
const [rootDirectories, setRootDirectories] = useState<any[]>([]);
const nodeMap = useRef<any>({});
const dataRef = useRef<any[]>([]);
const [rootDirectories, setRootDirectories] = useState<ElementAttributes[]>([]);
const nodeMap = useRef<Record<UUID, ElementAttributes>>({});
const dataRef = useRef<TreeViewFinderNodeProps[]>([]);
dataRef.current = data;

const rootsRef = useRef<any[]>([]);
const rootsRef = useRef<ElementAttributes[]>([]);
rootsRef.current = rootDirectories;
const { snackError } = useSnackMessage();
const contentFilter = useCallback(() => new Set([ElementType.DIRECTORY, ...types]), [types]);
Expand All @@ -193,7 +210,7 @@ export function DirectoryItemSelector({
}, []);

const convertRoots = useCallback(
(newRoots: any[]): any[] => {
(newRoots: ElementAttributes[]) => {
return newRoots.map((e) => {
return {
id: e.elementUuid,
Expand All @@ -211,7 +228,7 @@ export function DirectoryItemSelector({
);

const addToDirectory = useCallback(
(nodeId: UUID, content: any[]) => {
(nodeId: UUID, content: ElementAttributes[]) => {
const [nrs, mdr] = updatedTree(rootsRef.current, nodeMap.current, nodeId, content);
setRootDirectories(nrs);
nodeMap.current = mdr;
Expand Down
Loading

0 comments on commit e1ca4ca

Please sign in to comment.