refactor: extract rundown parsing

refactor: implement groups in editor
This commit is contained in:
Carlos Valente
2025-04-17 12:56:47 +02:00
committed by Carlos Valente
parent 166be66ce3
commit c616240db1
36 changed files with 1170 additions and 772 deletions
+180 -96
View File
@@ -1,13 +1,23 @@
import { Fragment, lazy, useCallback, useEffect, useRef, useState } from 'react';
import { closestCenter, DndContext, DragEndEvent, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import {
closestCenter,
DndContext,
DragEndEvent,
DragOverEvent,
DragStartEvent,
PointerSensor,
useSensor,
useSensors,
} from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useHotkeys } from '@mantine/hooks';
import { useHotkeys, useSessionStorage } from '@mantine/hooks';
import {
type EntryId,
type MaybeString,
type Rundown,
isOntimeBlock,
isOntimeEvent,
OntimeBlock,
OntimeEntry,
Playback,
SupportedEntry,
@@ -30,9 +40,9 @@ import { useEntryCopy } from '../../common/stores/entryCopyStore';
import { cloneEvent } from '../../common/utils/eventsManager';
import BlockBlock from './block-block/BlockBlock';
import BlockEnd from './block-block/BlockEnd';
import QuickAddBlock from './quick-add-block/QuickAddBlock';
import BlockEmpty from './BlockEmpty';
import { makeRundownMetadata } from './rundown.utils';
import { makeRundownMetadata, makeSortableList } from './rundown.utils';
import RundownEmpty from './RundownEmpty';
import { useEventSelection } from './useEventSelection';
@@ -45,10 +55,16 @@ interface RundownProps {
}
export default function Rundown({ data }: RundownProps) {
const { order, entries } = data;
const [statefulEntries, setStatefulEntries] = useState<EntryId[]>(order);
const { order, flatOrder, entries, id } = data;
// we create a copy of the rundown with a data structured aligned with what dnd-kit needs
const featureData = useRundownEditor();
const [sortableData, setSortableData] = useState<EntryId[]>(() => makeSortableList(flatOrder, entries));
const [collapsedGroups, setCollapsedGroups] = useSessionStorage<EntryId[]>({
// we ensure that this is unique to the rundown
key: `rundown.${id}-editor-collapsed-groups`,
defaultValue: [],
});
const { addEntry, reorderEntry, deleteEntry } = useEntryActions();
const { entryCopyId, setEntryCopyId } = useEntryCopy();
@@ -221,11 +237,11 @@ export default function Rundown({ data }: RundownProps) {
// we copy the state from the store here
// to workaround async updates on the drag mutations
useEffect(() => {
setStatefulEntries(order);
}, [order]);
setSortableData(makeSortableList(flatOrder, entries));
}, [flatOrder, entries]);
// in run mode, we follow selection
useEffect(() => {
// in run mode, we follow selection
if (appMode !== AppMode.Run || !featureData?.selectedEventId) {
return;
}
@@ -233,6 +249,36 @@ export default function Rundown({ data }: RundownProps) {
setSelectedEvents({ id: featureData.selectedEventId, selectMode: 'click', index });
}, [appMode, featureData.selectedEventId, order, setSelectedEvents]);
/**
* Checks whether a block is collapsed
*/
const getIsCollapsed = useCallback(
(blockId: EntryId): boolean => {
return Boolean(collapsedGroups.find((id) => id === blockId));
},
[collapsedGroups],
);
/**
* Handles logic for collapsing groups
*/
const handleCollapseGroup = useCallback(
(collapsed: boolean, groupId: EntryId) => {
setCollapsedGroups((prev) => {
const isCollapsed = getIsCollapsed(groupId);
if (collapsed && !isCollapsed) {
const newSet = new Set(prev).add(groupId);
return [...newSet];
}
if (!collapsed && isCollapsed) {
return [...prev].filter((id) => id !== groupId);
}
return prev;
});
},
[getIsCollapsed, setCollapsedGroups],
);
/**
* On drag end, we reorder the events
*/
@@ -245,7 +291,7 @@ export default function Rundown({ data }: RundownProps) {
const toIndex = over.data.current?.sortable.index;
// we keep a copy of the state as a hack to handle inconsistencies between dnd-kit and async store updates
setStatefulEntries((currentEntries) => {
setSortableData((currentEntries) => {
return reorderArray(currentEntries, fromIndex, toIndex);
});
reorderEntry(String(active.id), fromIndex, toIndex);
@@ -253,7 +299,36 @@ export default function Rundown({ data }: RundownProps) {
}
};
if (statefulEntries.length < 1) {
/**
* When we drag a block, we force collapse it
* This avoids strange scenarios like dropping a block inside itself
*/
const collapseDraggedBlocks = (event: DragStartEvent) => {
const isBlock = event.active.data.current?.type === 'block';
if (isBlock) {
handleCollapseGroup(true, event.active.id as EntryId);
}
};
/**
* When we drag over a block, we expand it if it is collapsed
*/
const expandOverBlock = (event: DragOverEvent) => {
// if we are dragging a block, the drop operation is invalid so we dont expand
if (event.active.data.current?.type === 'block') {
return;
}
if (event.over?.data.current?.type !== 'block') {
return;
}
const blockId = event.over?.id as EntryId;
const isCollapsed = getIsCollapsed(blockId);
if (isCollapsed) {
handleCollapseGroup(false, blockId);
}
};
if (sortableData.length < 1) {
return <RundownEmpty handleAddNew={() => insertAtId({ type: SupportedEntry.Event }, cursor)} />;
}
@@ -261,121 +336,130 @@ export default function Rundown({ data }: RundownProps) {
const isEditMode = appMode === AppMode.Edit;
// 2. initialise rundown metadata
const process = makeRundownMetadata(featureData?.selectedEventId);
const { metadata, process } = makeRundownMetadata(featureData?.selectedEventId);
// keep a single reference to the metadata which we override for every entry
let rundownMetadata = metadata;
return (
<div className={style.rundownContainer} ref={scrollRef} data-testid='rundown'>
<DndContext onDragEnd={handleOnDragEnd} sensors={sensors} collisionDetection={closestCenter}>
<SortableContext items={statefulEntries} strategy={verticalListSortingStrategy}>
<DndContext
onDragEnd={handleOnDragEnd}
onDragStart={collapseDraggedBlocks}
onDragOver={expandOverBlock}
sensors={sensors}
collisionDetection={closestCenter}
>
<SortableContext items={sortableData} strategy={verticalListSortingStrategy}>
<div className={style.list}>
{statefulEntries.map((entryId, index) => {
// we iterate through a stateful copy of order to make the operations smoother
{sortableData.map((entryId, index) => {
const isFirst = index === 0;
const isLast = index === sortableData.length - 1;
// the entry might be a pseudo block-end which does not generate metadata and should not be processed
if (entryId.startsWith('end-')) {
const parentId = entryId.split('end-')[1];
const isBlockCollapsed = getIsCollapsed(parentId);
if (isBlockCollapsed && isEditMode && isLast) {
return <QuickAddBlock key={entryId} previousEventId={parentId} parentBlock={null} />;
} else {
const parentColour = (entries[parentId] as OntimeBlock | undefined)?.colour;
// if the previous element is selected, it will have its own QuickAddBlock
// we use thisId instead of previousEntryId because the block end does not process
// and it does not cause the reassignment of the iteration id to the previous entry
const showPrependingQuickAdd = isEditMode && cursor !== rundownMetadata.thisId;
return (
<Fragment key={entryId}>
{showPrependingQuickAdd && (
<QuickAddBlock
previousEventId={rundownMetadata.previousEntryId}
parentBlock={parentId}
backgroundColor={parentColour}
/>
)}
<BlockEnd key={entryId} id={entryId} colour={parentColour} />
{isEditMode && isLast && <QuickAddBlock previousEventId={parentId} parentBlock={null} />}
</Fragment>
);
}
}
// we iterate through a stateful copy of order to make the dnd operations smoother
// this means that this can be out of sync with order until the useEffect runs
// instead of writing all the logic guards, we simply short circuit rendering here
const entry = entries[entryId];
if (!entry) {
if (!entry) return null;
rundownMetadata = process(entry);
// if the entry has a parent, and it is collapsed, render nothing
if (
entry.type !== SupportedEntry.Block &&
rundownMetadata.groupId !== null &&
getIsCollapsed(rundownMetadata.groupId)
) {
return null;
}
const rundownMeta = process(entry);
const isFirst = index === 0;
const isLast = index === order.length - 1;
const isNext = featureData?.nextEventId === entry.id;
const hasCursor = entry.id === cursor;
/**
* Outside a block, the value will be undefined
* If the colour is empty string ''
* ie: we are inside a block, but there is no defined colour
* we default to $gray-1050 #303030
*/
const blockColour = rundownMetadata.groupColour === '' ? '#303030' : rundownMetadata.groupColour;
return (
<Fragment key={entry.id}>
{isEditMode && (hasCursor || isFirst) && (
<QuickAddBlock previousEventId={rundownMeta.previousEntryId} parentBlock={null} />
<QuickAddBlock
previousEventId={rundownMetadata.previousEntryId}
parentBlock={isFirst ? null : rundownMetadata.groupId}
backgroundColor={isFirst ? undefined : blockColour}
/>
)}
{isOntimeBlock(entry) ? (
<BlockBlock data={entry} hasCursor={hasCursor}>
{entry.events.length === 0 && (
<BlockEmpty
handleAddNew={() => insertAtId({ type: SupportedEntry.Event, parent: entry.id }, entry.id)}
/>
)}
{entry.events.map((eventId, nestedIndex) => {
const nestedEntry = entries[eventId];
if (!nestedEntry) {
return null;
}
const nestedRundownMeta = process(nestedEntry);
const isFirstInGroup = nestedIndex === 0;
const isLastInGroup = nestedIndex === entry.events.length - 1;
const hasNestedCursor = nestedEntry.id === cursor;
if (!isOntimeEvent(nestedEntry)) {
return null;
}
return (
<Fragment key={nestedEntry.id}>
{isEditMode && (hasNestedCursor || isFirstInGroup) && (
<QuickAddBlock
parentBlock={entry.id}
previousEventId={nestedRundownMeta.previousEntryId}
/>
)}
<div
key={nestedEntry.id}
className={style.entryWrapper}
data-testid={`entry-${nestedRundownMeta.eventIndex}`}
>
<div className={style.entryIndex}>{nestedRundownMeta.eventIndex}</div>
<div className={style.entry} ref={hasNestedCursor ? cursorRef : undefined}>
<RundownEntry
key={nestedEntry.id}
type={nestedEntry.type}
isPast={nestedRundownMeta.isPast}
eventIndex={nestedRundownMeta.eventIndex}
data={nestedEntry}
loaded={nestedRundownMeta.isLoaded}
hasCursor={hasNestedCursor}
isNext={isNext}
previousEntryId={nestedRundownMeta.previousEntryId}
previousEventId={nestedRundownMeta.previousEvent?.id}
playback={nestedRundownMeta.isLoaded ? featureData.playback : undefined}
isRolling={featureData.playback === Playback.Roll}
isNextDay={nestedRundownMeta.isNextDay}
totalGap={nestedRundownMeta.totalGap}
isLinkedToLoaded={nestedRundownMeta.isLinkedToLoaded}
/>
</div>
</div>
{isEditMode && (hasNestedCursor || isLastInGroup) && (
<QuickAddBlock parentBlock={entry.id} previousEventId={nestedEntry.id} />
)}
</Fragment>
);
})}
</BlockBlock>
<BlockBlock
data={entry}
hasCursor={hasCursor}
collapsed={getIsCollapsed(entry.id)}
onCollapse={handleCollapseGroup}
/>
) : (
<div className={style.entryWrapper} data-testid={`entry-${rundownMeta.eventIndex}`}>
{isOntimeEvent(entry) && <div className={style.entryIndex}>{rundownMeta.eventIndex}</div>}
<div
className={style.entryWrapper}
data-testid={`entry-${rundownMetadata.eventIndex}`}
style={blockColour ? { '--user-bg': blockColour } : {}}
>
{isOntimeEvent(entry) && <div className={style.entryIndex}>{rundownMetadata.eventIndex}</div>}
<div className={style.entry} key={entry.id} ref={hasCursor ? cursorRef : undefined}>
<RundownEntry
type={entry.type}
isPast={rundownMeta.isPast}
eventIndex={rundownMeta.eventIndex}
isPast={rundownMetadata.isPast}
eventIndex={rundownMetadata.eventIndex}
data={entry}
loaded={rundownMeta.isLoaded}
loaded={rundownMetadata.isLoaded}
hasCursor={hasCursor}
isNext={isNext}
previousEntryId={rundownMeta.previousEntryId}
previousEventId={rundownMeta.previousEvent?.id}
playback={rundownMeta.isLoaded ? featureData.playback : undefined}
previousEntryId={rundownMetadata.previousEntryId}
previousEventId={rundownMetadata.previousEvent?.id}
playback={rundownMetadata.isLoaded ? featureData.playback : undefined}
isRolling={featureData.playback === Playback.Roll}
isNextDay={rundownMeta.isNextDay}
totalGap={rundownMeta.totalGap}
isLinkedToLoaded={rundownMeta.isLinkedToLoaded}
isNextDay={rundownMetadata.isNextDay}
totalGap={rundownMetadata.totalGap}
isLinkedToLoaded={rundownMetadata.isLinkedToLoaded}
/>
</div>
</div>
)}
{isEditMode && (hasCursor || isLast) && (
<QuickAddBlock previousEventId={entry.id} parentBlock={null} />
<QuickAddBlock
previousEventId={entry.id}
parentBlock={rundownMetadata.groupId}
backgroundColor={blockColour}
/>
)}
</Fragment>
);