Skip to content

Commit

Permalink
feat: made List more extensible
Browse files Browse the repository at this point in the history
  • Loading branch information
doprz committed Mar 6, 2024
1 parent b800c58 commit cd34601
Show file tree
Hide file tree
Showing 6 changed files with 152 additions and 81 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
"react-devtools-core": "^5.0.0",
"react-dom": "^18.2.0",
"react-window": "^1.8.10",
"sass": "^1.69.5",
"sql.js": "1.9.0",
"sass": "^1.70.0",
"sql.js": "1.10.2",
"uuid": "^9.0.1"
},
"devDependencies": {
Expand Down
16 changes: 16 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

119 changes: 77 additions & 42 deletions src/stories/components/List.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,43 +1,76 @@
import React from 'react';
import { Meta, StoryObj } from '@storybook/react';
import { Course, Status } from 'src/shared/types/Course';
import { CourseMeeting, DAY_MAP } from 'src/shared/types/CourseMeeting';
import { CourseSchedule } from 'src/shared/types/CourseSchedule';
import Instructor from 'src/shared/types/Instructor';
import List from 'src/views/components/common/List/List';
import CalendarCourseMeeting from 'src/views/components/common/CalendarCourseBlock/CalendarCourseMeeting';
import { Course, Status } from '@shared/types/Course';
import { CourseMeeting } from '@shared/types/CourseMeeting';
import Instructor from '@shared/types/Instructor';
import List from '@views/components/common/List/List';
import PopupCourseBlock from '@views/components/common/PopupCourseBlock/PopupCourseBlock';
import { getCourseColors } from 'src/shared/util/colors';
import { test_colors } from './PopupCourseBlock.stories';

const placeholderCourse: Course = new Course({
uniqueId: 123,
number: '311C',
fullName: "311C - Bevo's Default Course",
courseName: "Bevo's Default Course",
department: 'BVO',
creditHours: 3,
status: Status.OPEN,
instructors: [new Instructor({ firstName: '', lastName: 'Bevo', fullName: 'Bevo' })],
isReserved: false,
url: '',
flags: [],
schedule: new CourseSchedule({
meetings: [

const numberOfCourses = 5;

const generateCourses = (count) => {
const courses = [];

for (let i = 0; i < count; i++) {
const course = new Course({
courseName: 'ELEMS OF COMPTRS/PROGRAMMNG-WB',
creditHours: 3,
department: 'C S',
description: [
'Problem solving and fundamental algorithms for various applications in science, business, and on the World Wide Web, and introductory programming in a modern object-oriented programming language.',
'Only one of the following may be counted: Computer Science 303E, 312, 312H. Credit for Computer Science 303E may not be earned after a student has received credit for Computer Science 314, or 314H. May not be counted toward a degree in computer science.',
'May be counted toward the Quantitative Reasoning flag requirement.',
'Designed to accommodate 100 or more students.',
'Taught as a Web-based course.',
],
flags: ['Quantitative Reasoning'],
fullName: 'C S 303E ELEMS OF COMPTRS/PROGRAMMNG-WB',
instructionMode: 'Online',
instructors: [
new Instructor({
firstName: 'Bevo',
lastName: 'Bevo',
fullName: 'Bevo Bevo',
}),
],
isReserved: false,
number: '303E',
schedule: {
meetings: [
new CourseMeeting({
days: [DAY_MAP.M, DAY_MAP.W, DAY_MAP.F],
startTime: 480,
endTime: 570,
location: {
building: 'UTC',
room: '123',
},
days: ['Tuesday', 'Thursday'],
endTime: 660,
startTime: 570,
}),
],
}),
instructionMode: 'In Person',
semester: {
year: 2024,
season: 'Spring',
},
});
],
},
semester: {
code: '12345',
season: 'Spring',
year: 2024,
},
status: Status.WAITLISTED,
uniqueId: 12345 + i, // Make uniqueId different for each course
url: 'https://utdirect.utexas.edu/apps/registrar/course_schedule/20242/12345/',
});

courses.push(course);
}

return courses;
};

const exampleCourses = generateCourses(numberOfCourses);
const generateCourseBlocks = (exampleCourses, colors) => {
return exampleCourses.map((course, i) => (
<PopupCourseBlock key={course.uniqueId} course={course} colors={colors[i]} />
))
}
const exampleCourseBlocks = generateCourseBlocks(exampleCourses, test_colors);


const meta = {
title: 'Components/Common/List',
Expand All @@ -48,6 +81,10 @@ const meta = {
tags: ['autodocs'],
argTypes: {
draggableElements: { control: 'object' },
itemHeight: { control: 'number' },
listHeight: { control: 'number' },
listWidth: { control: 'number' },
gap: { control: 'number' },
},
} satisfies Meta<typeof List>;
export default meta;
Expand All @@ -56,12 +93,10 @@ type Story = StoryObj<typeof meta>;

export const Default: Story = {
args: {
draggableElements: [
<CalendarCourseMeeting key="1" course={placeholderCourse} meetingIdx={0} color="lightblue" />,
<CalendarCourseMeeting key="2" course={placeholderCourse} meetingIdx={0} color="lightgreen" />,
<CalendarCourseMeeting key="3" course={placeholderCourse} meetingIdx={0} color="lightcoral" />,
<CalendarCourseMeeting key="4" course={placeholderCourse} meetingIdx={0} color="lightgoldenrodyellow" />,
<CalendarCourseMeeting key="5" course={placeholderCourse} meetingIdx={0} color="lightpink" />
],
draggableElements: exampleCourseBlocks,
itemHeight: 55,
listHeight: 300,
listWidth: 300,
gap: 8,
},
};
4 changes: 2 additions & 2 deletions src/stories/components/PopupCourseBlock.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export const Variants: Story = {
),
};

const colors = Object.keys(theme.colors)
export const test_colors = Object.keys(theme.colors)
// check that the color is a colorway (is an object)
.filter(color => typeof theme.colors[color] === 'object')
.slice(0, 17)
Expand All @@ -104,7 +104,7 @@ const colors = Object.keys(theme.colors)
export const AllColors: Story = {
render: props => (
<div className='grid grid-rows-9 grid-cols-2 grid-flow-col max-w-2xl w-90vw gap-x-4 gap-y-2'>
{colors.map((color, i) => (
{test_colors.map((color, i) => (
<PopupCourseBlock key={color.primaryColor} course={exampleCourse} colors={color} />
))}
</div>
Expand Down
86 changes: 52 additions & 34 deletions src/views/components/common/List/List.tsx
Original file line number Diff line number Diff line change
@@ -1,73 +1,79 @@
import React from 'react';
import { useState } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import { FixedSizeList, areEqual } from "react-window";
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { FixedSizeList, areEqual } from 'react-window';
import { ReactElement } from 'react';

/*Ctrl + f dragHandleProps on PopupCourseBlock.tsx for example implementation of drag handle (two lines of code)
*
*/

/**
* Props for the List component.
*/
export interface ListProps {
draggableElements: any[]; //Will later define draggableElements based on what types
//of components are draggable.
itemHeight: number;
listHeight: number;
listWidth: number;
gap: number; //Impacts the spacing between items in the list

}

function initial(draggableElements: any[] = []) {
return draggableElements.map((element, index) => ({
id: `id:${index}`,
content: element
content: element as ReactElement,
}));
}

function reorder(list, startIndex: number, endIndex: number) {
function reorder(list: { id: string, content: ReactElement }[], startIndex: number, endIndex: number) {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
}

function getStyle({ provided, style, isDragging }) {
function getStyle({ provided, style, isDragging, gap }) {
const combined = {
...style,
...provided.draggableProps.style
};

const marginBottom = 8;
const withSpacing = {
...combined,
height: isDragging ? combined.height : combined.height - marginBottom,
marginBottom
};
return withSpacing;
//return style;

return combined;
}

function Item({ provided, item, style, isDragging }) {
function Item({ provided, item, style, isDragging, gap }) {
return (
<div
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
style={getStyle({ provided, style, isDragging })}
style={getStyle({ provided, style, isDragging, gap })}
className={`item ${isDragging ? "is-dragging" : ""}`}
>
{item.content}
{React.cloneElement(item.content, {dragHandleProps: provided.dragHandleProps})}
</div>
);
}

interface RowProps {
data: any, //DraggableElements[]; Need to define DraggableElements interface once those components are ready
index: number,
style: any
style: React.CSSProperties,
}

const Row: React.FC<RowProps> = React.memo(({ data: items, index, style }) => {
const Row: React.FC<RowProps> = React.memo(({ data: { items, gap }, index, style }) => {
const item = items[index];
const adjustedStyle = {
...style,
height: `calc(${style.height}px - ${gap}px)`, // Reduce the height by gap to accommodate the margin
marginBottom: `${gap}px` // Add gap as bottom margin
};
return (
<Draggable draggableId={item.id} index={index} key={item.id}>
{/*@ts-ignore*/}
{provided => <Item provided={provided} item={item} style={style} />}
{provided => <Item provided={provided} item={item} style={adjustedStyle} gap={gap}/>}
</Draggable>
);
}, areEqual);
Expand All @@ -78,15 +84,14 @@ const Row: React.FC<RowProps> = React.memo(({ data: items, index, style }) => {
* @example
* <List draggableElements={elements} />
*/
const List: React.FC<ListProps> = ({
draggableElements
}: ListProps) => {
const List: React.FC<ListProps> = ( { draggableElements, itemHeight, listHeight, listWidth, gap=8 }: ListProps) => {
const [items, setItems] = useState(() => initial(draggableElements));

function onDragEnd(result) {
if (!result.destination) {
return;
}

if (result.source.index === result.destination.index) {
return;
}
Expand All @@ -96,10 +101,11 @@ const List: React.FC<ListProps> = ({
result.source.index,
result.destination.index
);
setItems(newItems as {id: string, content: any}[]);
setItems(newItems as {id: string, content: ReactElement}[]);
}

return (
<div style={{ overflow: 'hidden', width: listWidth, height: listHeight }}>
<DragDropContext onDragEnd = {onDragEnd}>
<div style = {{
display: "flex",
Expand All @@ -121,11 +127,21 @@ const List: React.FC<ListProps> = ({
.split(',')
.map((v) => parseInt(v, 10));

style.transform = `translate(0px, ${y}px)`;
}

style.fontFamily = "Inter";
const minTranslateY = -1 * rubric.source.index * itemHeight;
const maxTranslateY = (items.length - rubric.source.index - 1) * itemHeight;
if (y < minTranslateY) {

}
else if (y > maxTranslateY) {

}
else {

}

style.transform = `translate(0px, ${y}px)`; // Apply constrained y value
}

return (
<Item
provided={provided}
Expand All @@ -134,26 +150,28 @@ const List: React.FC<ListProps> = ({
style = {{
style
}}
gap = {gap}
/>
)}
}
>
{provided => (
<FixedSizeList
height={500}
height={listHeight}
itemCount={items.length}
itemSize={80}
width={300}
itemSize={itemHeight}
width={listWidth}
outerRef={provided.innerRef}
itemData={items}
itemData={{ items, gap }}
>
{Row}
</FixedSizeList>
)}
</Droppable>
</div>
</DragDropContext>
</div>
);
};

export default List;
export default List;
Loading

0 comments on commit cd34601

Please sign in to comment.