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: Add components required for estimates #4690

Merged
merged 10 commits into from
Jun 4, 2024
4 changes: 3 additions & 1 deletion packages/ui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ export * from "./loader";
export * from "./control-link";
export * from "./toast";
export * from "./drag-handle";
export * from "./drop-indicator";
export * from "./drop-indicator";
export * from "./radio-input";
export * from "./sortable";
1 change: 1 addition & 0 deletions packages/ui/src/radio-input/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./radio-input";
36 changes: 36 additions & 0 deletions packages/ui/src/radio-input/radio-input.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { Meta, StoryObj } from "@storybook/react";
import { fn } from "@storybook/test";
import { RadioInput } from "./radio-input";

const meta: Meta<typeof RadioInput> = {
title: "RadioInput",
component: RadioInput,
};

export default meta;
type Story = StoryObj<typeof RadioInput>;

const options = [
{ label: "Option 1", value: "option1" },
{
label:
"A very very long label, lets add some lipsum text and see what happens? May be we don't have to. This is long enough",
value: "option2",
},
{ label: "Option 3", value: "option3" },
];

export const Default: Story = {
args: {
options,
label: "Horizontal Radio Input",
},
};

export const vertical: Story = {
args: {
options,
label: "Vertical Radio Input",
vertical: true,
},
};
72 changes: 72 additions & 0 deletions packages/ui/src/radio-input/radio-input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import React from "react";
import { Field, Label, Radio, RadioGroup } from "@headlessui/react";
import { cn } from "../../helpers";
// helpers

type RadioInputProps = {
label: string | React.ReactNode | undefined;
wrapperClassName?: string;
fieldClassName?: string;
buttonClassName?: string;
labelClassName?: string;
ariaLabel?: string;
options: { label: string | React.ReactNode; value: string; disabled?: boolean }[];
vertical?: boolean;
selected: string;
onChange: (value: string) => void;
className?: string;
};

export const RadioInput = ({
label: inputLabel,
labelClassName: inputLabelClassName = "",
wrapperClassName: inputWrapperClassName = "",
fieldClassName: inputFieldClassName = "",
buttonClassName: inputButtonClassName = "",
options,
vertical,
selected,
ariaLabel,
onChange,
className,
}: RadioInputProps) => {
const wrapperClass = vertical ? "flex flex-col gap-1" : "flex gap-2";

const setSelected = (value: string) => {
onChange(value);
};

let aria = ariaLabel ? ariaLabel.toLowerCase().replace(" ", "-") : "";
if (!aria && typeof inputLabel === "string") {
aria = inputLabel.toLowerCase().replace(" ", "-");
} else {
aria = "radio-input";
}

// return <h1>Hello</h1>;
SatishGandham marked this conversation as resolved.
Show resolved Hide resolved

return (
<RadioGroup value={selected} onChange={setSelected} aria-label={aria} className={className}>
<Label className={cn(`mb-2`, inputLabelClassName)}>{inputLabel}</Label>
<div className={cn(`${wrapperClass}`, inputWrapperClassName)}>
{options.map(({ value, label, disabled }, index) => (
<Field key={index} className={cn("flex items-center gap-2", inputFieldClassName)}>
<Radio
value={value}
className={cn(
"group flex size-5 items-center justify-center rounded-full border border-custom-border-400 bg-custom-background-500 data-[checked]:bg-custom-primary-200 data-[checked]:border-custom-primary-100 cursor-pointer data-[disabled]:bg-custom-background-200 data-[disabled]:border-custom-border-200 data-[disabled]:cursor-not-allowed",
inputButtonClassName
)}
disabled={disabled}
>
<span className="invisible size-2 rounded-full bg-white group-data-[checked]:visible" />
</Radio>
<Label className="text-base cursor-pointer">{label}</Label>
</Field>
))}
</div>
</RadioGroup>
);
};

export default RadioInput;
62 changes: 62 additions & 0 deletions packages/ui/src/sortable/draggable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import React, { useEffect, useRef, useState } from "react";
import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";
import { draggable, dropTargetForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
import { isEqual } from "lodash";
import { cn } from "../../helpers";
import { attachClosestEdge, extractClosestEdge } from "@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge";
import { DropIndicator } from "../drop-indicator";

type Props = {
children: React.ReactNode;
data: any; //@todo make this generic
className?: string;
};
const Draggable = ({ children, data, className }: Props) => {
const ref = useRef<HTMLDivElement>(null);
const [dragging, setDragging] = useState<boolean>(false); // NEW
const [isDraggedOver, setIsDraggedOver] = useState(false);

const [closestEdge, setClosestEdge] = useState<string | null>(null);
useEffect(() => {
const el = ref.current;

if (el) {
combine(
draggable({
element: el,
onDragStart: () => setDragging(true), // NEW
onDrop: () => setDragging(false), // NEW
getInitialData: () => data,
}),
dropTargetForElements({
element: el,
onDragEnter: (args) => {
setIsDraggedOver(true);
setClosestEdge(extractClosestEdge(args.self.data));
SatishGandham marked this conversation as resolved.
Show resolved Hide resolved
},
onDragLeave: () => setIsDraggedOver(false),
onDrop: () => {
setIsDraggedOver(false);
},
canDrop: ({ source }) => !isEqual(source.data, data) && source.data.__uuid__ === data.__uuid__,
getData: ({ input, element }) =>
attachClosestEdge(data, {
input,
element,
allowedEdges: ["top", "bottom"],
}),
})
);
}
}, [data]);

return (
<div ref={ref} className={cn(dragging && "opacity-25", className)}>
{<DropIndicator isVisible={isDraggedOver && closestEdge === "top"} />}
{children}
{<DropIndicator isVisible={isDraggedOver && closestEdge === "bottom"} />}
</div>
);
};

export { Draggable };
2 changes: 2 additions & 0 deletions packages/ui/src/sortable/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./sortable";
export * from "./draggable";
32 changes: 32 additions & 0 deletions packages/ui/src/sortable/sortable.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { Meta, StoryObj } from "@storybook/react";
import React from "react";
import { Draggable } from "./draggable";
import { Sortable } from "./sortable";

const meta: Meta<typeof Sortable> = {
title: "Sortable",
component: Sortable,
};

export default meta;
type Story = StoryObj<typeof Sortable>;

const data = [
{ id: "1", name: "John Doe" },
{ id: "2", name: "Jane Doe 2" },
{ id: "3", name: "Alice" },
{ id: "4", name: "Bob" },
{ id: "5", name: "Charlie" },
];
export const Default: Story = {
args: {
data,
render: (item: any) => (
// <Draggable data={item} className="rounded-lg">
<div className="border ">{item.name}</div>
// </Draggable>
),
onChange: (data) => console.log(data.map(({ id }) => id)),
keyExtractor: (item: any) => item.id,
},
};
79 changes: 79 additions & 0 deletions packages/ui/src/sortable/sortable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import React, { Fragment, useEffect, useMemo } from "react";
import { monitorForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
import { Draggable } from "./draggable";

type Props<T> = {
data: T[];
render: (item: T, index: number) => React.ReactNode;
onChange: (data: T[]) => void;
keyExtractor: (item: T, index: number) => string;
containerClassName?: string;
id: string;
};

const moveItem = <T,>(
data: T[],
source: T,
destination: T & Record<symbol, string>,
keyExtractor: (item: T, index: number) => string
) => {
const sourceIndex = data.indexOf(source);
if (sourceIndex === -1) return data;

const destinationIndex = data.findIndex((item, index) => keyExtractor(item, index) === keyExtractor(destination, 0));

if (destinationIndex === -1) return data;

const symbolKey = Reflect.ownKeys(destination).find((key) => key.toString() === "Symbol(closestEdge)");
const position = symbolKey ? destination[symbolKey as symbol] : "bottom"; // Add 'as symbol' to cast symbolKey to symbol
const newData = [...data];
const [movedItem] = newData.splice(sourceIndex, 1);

let adjustedDestinationIndex = destinationIndex;
if (position === "bottom") {
adjustedDestinationIndex++;
}

// Prevent moving item out of bounds
if (adjustedDestinationIndex > newData.length) {
adjustedDestinationIndex = newData.length;
}

newData.splice(adjustedDestinationIndex, 0, movedItem);

return newData;
};

export const Sortable = <T,>({ data, render, onChange, keyExtractor, containerClassName, id }: Props<T>) => {
useEffect(() => {
const unsubscribe = monitorForElements({
onDrop({ source, location }) {
const destination = location?.current?.dropTargets[0];
if (!destination) return;
onChange(moveItem(data, source.data as T, destination.data as T & { closestEdge: string }, keyExtractor));
},
});

// Clean up the subscription on unmount
return () => {
if (unsubscribe) unsubscribe();
};
}, [data, keyExtractor, onChange]);

const enhancedData = useMemo(() => {
const uuid = id ? id : Math.random().toString(36).substring(7);
Dismissed Show dismissed Hide dismissed
return data.map((item) => ({ ...item, __uuid__: uuid }));
}, [data]);

Check warning on line 66 in packages/ui/src/sortable/sortable.tsx

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

packages/ui/src/sortable/sortable.tsx#L66

React Hook useMemo has a missing dependency: 'id'. Either include it or remove the dependency array.

return (
<>
{enhancedData.map((item, index) => (
<Draggable key={keyExtractor(item, index)} data={item} className={containerClassName}>
<Fragment>{render(item, index)} </Fragment>
</Draggable>
))}
</>
);
};

export default Sortable;
1 change: 1 addition & 0 deletions packages/ui/src/typography/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./sub-heading";
15 changes: 15 additions & 0 deletions packages/ui/src/typography/sub-heading.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from "react";
import { cn } from "../../helpers";

type Props = {
children: React.ReactNode;
className?: string;
noMargin?: boolean;
};
const SubHeading = ({ children, className, noMargin }: Props) => (
<h3 className={cn("text-xl font-medium text-custom-text-200 block leading-7", !noMargin && "mb-2", className)}>
{children}
</h3>
);

export { SubHeading };
Loading