Skip to content

Commit

Permalink
feat(StateDropdown): create component
Browse files Browse the repository at this point in the history
  • Loading branch information
DenisVorop committed Feb 27, 2024
1 parent f1f1fe3 commit 1cc1216
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions src/components/StateDropdown/StateDropdown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { State as StateType } from '@prisma/client';
import { ComponentProps, useCallback, useEffect } from 'react';
import { State } from '@taskany/bricks/harmony';
import { nullable } from '@taskany/bricks';

import { trpc } from '../../utils/trpcClient';
import { Dropdown, DropdownTrigger, DropdownPanel } from '../Dropdown/Dropdown';
import { StateWrapper } from '../StateWrapper';

interface StateDropdownProps {
error?: ComponentProps<typeof DropdownTrigger>['error'];
label?: ComponentProps<typeof DropdownTrigger>['label'];
disabled?: boolean;
value?: Partial<StateType>;
flowId?: string;

onChange?: (state: StateType) => void;
}

export const StateDropdown = ({ label, value, flowId, disabled, onChange, ...props }: StateDropdownProps) => {
const defaultFlowEnabled = !flowId && !disabled;

const onStateChange = useCallback(
(s: Partial<StateType>) => {
onChange?.(s as StateType);
},
[onChange],
);

const { data: flowById } = trpc.flow.getById.useQuery(flowId, {
enabled: !!flowId,
});

const { data: defaultFlow } = trpc.flow.recommedations.useQuery(undefined, {
enabled: defaultFlowEnabled,
refetchOnMount: 'always',
select([flow]) {
return flow;
},
});

const flow = defaultFlowEnabled ? defaultFlow : flowById;

useEffect(() => {
if (value) return;
const defaultState = flow?.states.find((state) => state.default === true);
defaultState && onStateChange(defaultState);
}, [flow, onStateChange, value]);

return (
<Dropdown>
<DropdownTrigger label={label} {...props} readOnly={disabled}>
{nullable(value, ({ hue, title }) => (
<StateWrapper hue={hue}>
<State color="var(--state-stroke)" title={title} />
</StateWrapper>
))}
</DropdownTrigger>
<DropdownPanel
width={160}
value={value}
items={flow?.states}
selectable
onChange={onStateChange}
renderItem={(props) => (
<StateWrapper hue={props.item?.hue}>
<State color="var(--state-stroke)" title={props.item?.title} />
</StateWrapper>
)}
/>
</Dropdown>
);
};

0 comments on commit 1cc1216

Please sign in to comment.