mirror of
https://github.com/cpvalente/ontime.git
synced 2026-07-26 10:38:55 +00:00
refactor(rundown): new entries are appended to rundown
This commit is contained in:
committed by
Carlos Valente
parent
8363f06a5c
commit
a8c611911d
@@ -1,7 +1,6 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
EntryId,
|
||||
InsertOptions,
|
||||
MaybeString,
|
||||
OntimeDelay,
|
||||
OntimeEntry,
|
||||
@@ -64,6 +63,11 @@ export type EventOptions = Partial<{
|
||||
lastEventId: MaybeString;
|
||||
}>;
|
||||
|
||||
type ClientInsertOptions = {
|
||||
after?: EntryId;
|
||||
before?: EntryId;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gather utilities for actions on entries in the loaded rundown.
|
||||
*/
|
||||
@@ -121,7 +125,7 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
|
||||
* @private
|
||||
*/
|
||||
const { mutateAsync: addEntryMutation } = useMutation({
|
||||
mutationFn: ([rundownId, entry]: [string, PatchWithId & InsertOptions]) => postAddEntry(rundownId, entry),
|
||||
mutationFn: ([rundownId, entry]: [string, PatchWithId & ClientInsertOptions]) => postAddEntry(rundownId, entry),
|
||||
onMutate: async ([_rundownId, entry]) => {
|
||||
const queryKey = resolveCurrentRundownQueryKey();
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
@@ -150,8 +154,9 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
|
||||
addToRundown(
|
||||
newRundown,
|
||||
optimisticEntry,
|
||||
afterId,
|
||||
parent ? (newRundown.entries[parent.id] as OntimeGroup) : null,
|
||||
afterId,
|
||||
entry.before ?? null,
|
||||
);
|
||||
|
||||
queryClient.setQueryData<Rundown>(queryKey, newRundown);
|
||||
@@ -194,7 +199,7 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
|
||||
throw new Error('Rundown not initialised');
|
||||
}
|
||||
|
||||
const newEntry: PatchWithId & InsertOptions = { ...entry, id: generateId() };
|
||||
const newEntry: PatchWithId & ClientInsertOptions = { ...entry, id: generateId() };
|
||||
|
||||
// handle adding options that concern all event types
|
||||
if (options?.after) {
|
||||
@@ -285,7 +290,7 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
|
||||
* Clone an entry
|
||||
*/
|
||||
const clone = useCallback(
|
||||
async (entryId: EntryId, options?: InsertOptions) => {
|
||||
async (entryId: EntryId, options?: ClientInsertOptions) => {
|
||||
try {
|
||||
const rundownId = getCurrentRundownData()?.id;
|
||||
if (!rundownId) {
|
||||
@@ -1058,7 +1063,7 @@ function optimisticDeleteEntries(entryIds: EntryId[], rundown: Rundown) {
|
||||
/**
|
||||
* Utility to create an optimistic entry for immediate cache insertion
|
||||
*/
|
||||
function createOptimisticEntry(payload: PatchWithId & InsertOptions): OntimeEntry {
|
||||
function createOptimisticEntry(payload: PatchWithId & ClientInsertOptions): OntimeEntry {
|
||||
const { after: _after, before: _before, ...entryData } = payload;
|
||||
const id = entryData.id;
|
||||
let parent: EntryId | null = null;
|
||||
|
||||
@@ -339,7 +339,9 @@ export default function Rundown({ order, flatOrder, entries, id, rundownMetadata
|
||||
increaseViewportBy={{ top: 200, bottom: 400 }}
|
||||
style={{ height: '100%' }}
|
||||
components={{
|
||||
Header: isEditMode ? () => <QuickAddButtons previousEventId={null} parentGroup={null} /> : undefined,
|
||||
Header: isEditMode
|
||||
? () => <QuickAddButtons previousEventId={null} nextEventId={order[0]} parentGroup={null} />
|
||||
: undefined,
|
||||
Footer: () => (
|
||||
<>
|
||||
{isEditMode && (
|
||||
|
||||
+9
-26
@@ -11,13 +11,17 @@ import style from './QuickAddButtons.module.scss';
|
||||
|
||||
interface QuickAddButtonsProps {
|
||||
previousEventId: MaybeString;
|
||||
nextEventId?: MaybeString;
|
||||
parentGroup: MaybeString;
|
||||
backgroundColor?: string;
|
||||
}
|
||||
|
||||
export default memo(QuickAddButtons);
|
||||
function QuickAddButtons({ previousEventId, parentGroup, backgroundColor }: QuickAddButtonsProps) {
|
||||
function QuickAddButtons({ previousEventId, nextEventId, parentGroup, backgroundColor }: QuickAddButtonsProps) {
|
||||
const { addEntry } = useEntryActionsContext();
|
||||
const appendOptions = previousEventId ? { after: previousEventId, lastEventId: previousEventId } : undefined;
|
||||
const prependOptions = nextEventId ? { before: nextEventId } : undefined;
|
||||
const insertionOptions = appendOptions ?? prependOptions;
|
||||
|
||||
const addEvent = () => {
|
||||
addEntry(
|
||||
@@ -25,44 +29,23 @@ function QuickAddButtons({ previousEventId, parentGroup, backgroundColor }: Quic
|
||||
type: SupportedEntry.Event,
|
||||
parent: parentGroup,
|
||||
},
|
||||
{
|
||||
after: previousEventId,
|
||||
lastEventId: previousEventId,
|
||||
},
|
||||
insertionOptions,
|
||||
);
|
||||
};
|
||||
|
||||
const addDelay = () => {
|
||||
addEntry(
|
||||
{ type: SupportedEntry.Delay, parent: parentGroup },
|
||||
{
|
||||
lastEventId: previousEventId,
|
||||
after: previousEventId,
|
||||
},
|
||||
);
|
||||
addEntry({ type: SupportedEntry.Delay, parent: parentGroup }, insertionOptions);
|
||||
};
|
||||
|
||||
const addMilestone = () => {
|
||||
addEntry(
|
||||
{ type: SupportedEntry.Milestone, parent: parentGroup },
|
||||
{
|
||||
lastEventId: previousEventId,
|
||||
after: previousEventId,
|
||||
},
|
||||
);
|
||||
addEntry({ type: SupportedEntry.Milestone, parent: parentGroup }, insertionOptions);
|
||||
};
|
||||
|
||||
const addGroup = () => {
|
||||
if (parentGroup !== null) {
|
||||
return;
|
||||
}
|
||||
addEntry(
|
||||
{ type: SupportedEntry.Group },
|
||||
{
|
||||
lastEventId: previousEventId,
|
||||
after: previousEventId,
|
||||
},
|
||||
);
|
||||
addEntry({ type: SupportedEntry.Group }, insertionOptions);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -714,17 +714,17 @@ describe('processRundown()', () => {
|
||||
});
|
||||
|
||||
describe('rundownMutation.add()', () => {
|
||||
test('adds an event an empty rundown', () => {
|
||||
test('adds an event to an empty rundown', () => {
|
||||
const mockEvent = makeOntimeEvent({ id: 'mock', cue: 'mock' });
|
||||
const rundown = makeRundown({});
|
||||
|
||||
rundownMutation.add(rundown, mockEvent, null, null);
|
||||
rundownMutation.add(rundown, mockEvent, null, null, null);
|
||||
|
||||
expect(rundown.order.length).toBe(1);
|
||||
expect(rundown.entries['mock']).toMatchObject(mockEvent);
|
||||
});
|
||||
|
||||
test('adds an event at the top if no afterId is given', () => {
|
||||
test('adds an event at the end if no afterId is given', () => {
|
||||
const mockEvent = makeOntimeEvent({ id: 'mock', cue: 'mock' });
|
||||
const rundown = makeRundown({
|
||||
flatOrder: ['1'],
|
||||
@@ -734,28 +734,28 @@ describe('rundownMutation.add()', () => {
|
||||
},
|
||||
});
|
||||
|
||||
rundownMutation.add(rundown, mockEvent, null, null);
|
||||
rundownMutation.add(rundown, mockEvent, null, null, null);
|
||||
|
||||
expect(rundown.order).toStrictEqual(['mock', '1']);
|
||||
expect(rundown.flatOrder).toStrictEqual(['mock', '1']);
|
||||
expect(rundown.order).toStrictEqual(['1', 'mock']);
|
||||
expect(rundown.flatOrder).toStrictEqual(['1', 'mock']);
|
||||
expect(rundown.entries['mock']).toMatchObject(mockEvent);
|
||||
});
|
||||
|
||||
test('adds an event at the top of the group if no after is given', () => {
|
||||
test('adds an event at the end of the group if parent is provided but no after', () => {
|
||||
const mockEvent = makeOntimeEvent({ id: 'mock', cue: 'mock' });
|
||||
const rundown = makeRundown({
|
||||
flatOrder: ['1', '1a'],
|
||||
order: ['1'],
|
||||
entries: {
|
||||
'1': makeOntimeGroup({ id: '1' }),
|
||||
'1': makeOntimeGroup({ id: '1', entries: ['1a'] }),
|
||||
'1a': makeOntimeEvent({ id: '1a', parent: '1' }),
|
||||
},
|
||||
});
|
||||
|
||||
rundownMutation.add(rundown, mockEvent, null, rundown.entries['1'] as OntimeGroup);
|
||||
rundownMutation.add(rundown, mockEvent, rundown.entries['1'] as OntimeGroup, null, null);
|
||||
|
||||
expect(rundown.order).toStrictEqual(['1']);
|
||||
expect(rundown.flatOrder).toStrictEqual(['1', 'mock', '1a']);
|
||||
expect(rundown.flatOrder).toStrictEqual(['1', '1a', 'mock']);
|
||||
expect(rundown.entries['mock']).toMatchObject(mockEvent);
|
||||
});
|
||||
|
||||
@@ -765,12 +765,12 @@ describe('rundownMutation.add()', () => {
|
||||
flatOrder: ['1', '1a'],
|
||||
order: ['1'],
|
||||
entries: {
|
||||
'1': makeOntimeGroup({ id: '1' }),
|
||||
'1': makeOntimeGroup({ id: '1', entries: ['1a'] }),
|
||||
'1a': makeOntimeEvent({ id: '1a', parent: '1' }),
|
||||
},
|
||||
});
|
||||
|
||||
rundownMutation.add(rundown, mockEvent, '1a', rundown.entries['1'] as OntimeGroup);
|
||||
rundownMutation.add(rundown, mockEvent, rundown.entries['1'] as OntimeGroup, '1a', null);
|
||||
|
||||
expect(rundown.order).toStrictEqual(['1']);
|
||||
expect(rundown.flatOrder).toStrictEqual(['1', '1a', 'mock']);
|
||||
@@ -1839,6 +1839,49 @@ describe('rundownMutation.clone()', () => {
|
||||
parent: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('clones an event and appends it with after true', () => {
|
||||
const testRundown = makeRundown({
|
||||
order: ['1', '2'],
|
||||
entries: {
|
||||
'1': makeOntimeEvent({ id: '1', cue: 'event1', parent: null }),
|
||||
'2': makeOntimeEvent({ id: '2', cue: 'event2', parent: null }),
|
||||
},
|
||||
});
|
||||
|
||||
const newEntry = rundownMutation.clone(testRundown, testRundown.entries['1'], { after: true });
|
||||
|
||||
expect(testRundown.order).toStrictEqual(['1', '2', newEntry.id]);
|
||||
});
|
||||
|
||||
it('clones an event and prepends it with before true', () => {
|
||||
const testRundown = makeRundown({
|
||||
order: ['1', '2'],
|
||||
entries: {
|
||||
'1': makeOntimeEvent({ id: '1', cue: 'event1', parent: null }),
|
||||
'2': makeOntimeEvent({ id: '2', cue: 'event2', parent: null }),
|
||||
},
|
||||
});
|
||||
|
||||
const newEntry = rundownMutation.clone(testRundown, testRundown.entries['2'], { before: true });
|
||||
|
||||
expect(testRundown.order).toStrictEqual([newEntry.id, '1', '2']);
|
||||
});
|
||||
|
||||
it('clones a group and appends it with after true', () => {
|
||||
const testRundown = makeRundown({
|
||||
order: ['1', '2'],
|
||||
entries: {
|
||||
'1': makeOntimeGroup({ id: '1', title: 'top', entries: ['1a'] }),
|
||||
'1a': makeOntimeEvent({ id: '1a', cue: 'nested', parent: '1' }),
|
||||
'2': makeOntimeEvent({ id: '2', cue: 'event2', parent: null }),
|
||||
},
|
||||
});
|
||||
|
||||
const newEntry = rundownMutation.clone(testRundown, testRundown.entries['1'], { after: true });
|
||||
|
||||
expect(testRundown.order).toStrictEqual(['1', '2', newEntry.id]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rundownMutation.group()', () => {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { OntimeGroup } from 'ontime-types';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
import { makeOntimeEvent, makeOntimeGroup, makeRundown } from '../__mocks__/rundown.mocks.js';
|
||||
import { assertInsertAnchorExists, assertInsertAnchorInOrder } from '../rundown.validation.js';
|
||||
|
||||
const rundown = makeRundown({
|
||||
order: ['top', 'group'],
|
||||
entries: {
|
||||
top: makeOntimeEvent({ id: 'top', parent: null }),
|
||||
group: makeOntimeGroup({ id: 'group', entries: ['nested'] }),
|
||||
nested: makeOntimeEvent({ id: 'nested', parent: 'group' }),
|
||||
},
|
||||
});
|
||||
|
||||
describe('insertion anchor validation', () => {
|
||||
test('rejects a missing anchor', () => {
|
||||
expect(() => assertInsertAnchorInOrder(rundown, null, { before: 'missing' })).toThrow(
|
||||
'Insertion anchor with ID missing does not exist',
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects an anchor from a different order', () => {
|
||||
expect(() => assertInsertAnchorInOrder(rundown, null, { after: 'nested' })).toThrow(
|
||||
'Insertion anchor with ID nested is not in the target order',
|
||||
);
|
||||
});
|
||||
|
||||
test('accepts a group-local anchor', () => {
|
||||
const group = rundown.entries.group as OntimeGroup;
|
||||
|
||||
expect(() => assertInsertAnchorInOrder(rundown, group, { before: 'nested' })).not.toThrow();
|
||||
});
|
||||
|
||||
test('checks clone anchors exist', () => {
|
||||
expect(() => assertInsertAnchorExists(rundown, { after: 'missing' })).toThrow(
|
||||
'Insertion anchor with ID missing does not exist',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -439,21 +439,27 @@ function clone(rundown: Rundown, entry: OntimeEntry, options?: InsertOptions): O
|
||||
rundown.entries[nestedEntry.id] = nestedEntry;
|
||||
}
|
||||
|
||||
// by default we insert after the cloned element
|
||||
let atIndex = rundown.order.indexOf(entry.id) + 1;
|
||||
|
||||
const referenceId = options?.after ?? options?.before;
|
||||
if (referenceId) {
|
||||
// trying to insert relatively to another entry
|
||||
const referenceEntry = rundown.entries[referenceId];
|
||||
if (referenceEntry) {
|
||||
if (options?.after) {
|
||||
atIndex = rundown.order.indexOf(referenceId) + 1;
|
||||
} else if (options?.before) {
|
||||
atIndex = rundown.order.indexOf(referenceId);
|
||||
}
|
||||
const position: { after: EntryId | null; before: EntryId | null } = (() => {
|
||||
if (options?.after === undefined && options?.before === undefined) {
|
||||
return { after: entry.id, before: null };
|
||||
}
|
||||
}
|
||||
|
||||
const after = getInsertAfterId(rundown, null, options.after, options.before);
|
||||
const before = options.before === true ? (after ?? null) : (options.before ?? null);
|
||||
return { after, before };
|
||||
})();
|
||||
|
||||
const atIndex = (() => {
|
||||
if (position.before !== null) {
|
||||
return rundown.order.indexOf(position.before);
|
||||
}
|
||||
|
||||
if (position.after !== null) {
|
||||
return rundown.order.indexOf(position.after) + 1;
|
||||
}
|
||||
|
||||
return rundown.order.length;
|
||||
})();
|
||||
|
||||
// we only need to insert the group, the nested entries will be resolved by the rundown engine
|
||||
rundown.order = insertAtIndex(atIndex, newGroup.id, rundown.order);
|
||||
@@ -461,41 +467,33 @@ function clone(rundown: Rundown, entry: OntimeEntry, options?: InsertOptions): O
|
||||
return newGroup;
|
||||
} else {
|
||||
const clonedEntry = cloneSimpleRundownEntry(entry, getUniqueId(rundown));
|
||||
const parent = (() => {
|
||||
const referenceId = (() => {
|
||||
if (typeof options?.after === 'string') return options.after;
|
||||
if (typeof options?.before === 'string') return options.before;
|
||||
return undefined;
|
||||
})();
|
||||
|
||||
let parent: OntimeGroup | null = null;
|
||||
const referenceEntry = referenceId ? rundown.entries[referenceId] : entry;
|
||||
const parentId = referenceEntry && !isOntimeGroup(referenceEntry) ? referenceEntry.parent : null;
|
||||
if (parentId === null) return null;
|
||||
|
||||
// trying to insert relatively to another entry, check that entries parent
|
||||
const referenceId = options?.after ?? options?.before;
|
||||
const maybeParent = rundown.entries[parentId];
|
||||
return isOntimeGroup(maybeParent) ? maybeParent : null;
|
||||
})();
|
||||
|
||||
/**
|
||||
* if we have a positioning reference, and that reference has a parent
|
||||
* we need to maintain the same parent for the cloned entry
|
||||
*/
|
||||
if (referenceId) {
|
||||
const referenceEntry = rundown.entries[referenceId];
|
||||
|
||||
if (referenceEntry && !isOntimeGroup(referenceEntry)) {
|
||||
if (referenceEntry.parent) {
|
||||
const maybeParent = rundown.entries[referenceEntry.parent];
|
||||
if (maybeParent && isOntimeGroup(maybeParent)) {
|
||||
parent = maybeParent;
|
||||
}
|
||||
}
|
||||
const position = (() => {
|
||||
// if no position is given, we add immediately after the element
|
||||
if (options?.after === undefined && options?.before === undefined) {
|
||||
return { after: entry.id, before: null };
|
||||
}
|
||||
} else if (entry.parent) {
|
||||
const maybeParent = rundown.entries[entry.parent];
|
||||
if (maybeParent && isOntimeGroup(maybeParent)) {
|
||||
parent = maybeParent;
|
||||
}
|
||||
}
|
||||
|
||||
// if we have resolved a parent, we add it to the cloned entry
|
||||
let after = getInsertAfterId(rundown, parent, options?.after, options?.before);
|
||||
if (!after) {
|
||||
after = entry.id;
|
||||
}
|
||||
const after = getInsertAfterId(rundown, parent, options.after, options.before);
|
||||
const before = options?.before === true ? after : (options.before ?? null);
|
||||
return { after, before };
|
||||
})();
|
||||
|
||||
return addToRundown(rundown, clonedEntry, after, parent);
|
||||
return addToRundown(rundown, clonedEntry, parent, position.after, position.before);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,11 +40,15 @@ import { parseRundown } from './rundown.parser.js';
|
||||
import type { RundownMetadata } from './rundown.types.js';
|
||||
import {
|
||||
generateEvent,
|
||||
getFirstInsertId,
|
||||
getIntegerAndFraction,
|
||||
getLastInsertId,
|
||||
getPreviousInsertId,
|
||||
hasChanges,
|
||||
mergeRundownPreservingFields,
|
||||
isLoadedPlayable,
|
||||
} from './rundown.utils.js';
|
||||
import { assertInsertAnchorExists, assertInsertAnchorInOrder, assertSingleInsertAnchor } from './rundown.validation.js';
|
||||
|
||||
/**
|
||||
* creates a new entry with given data
|
||||
@@ -52,6 +56,8 @@ import {
|
||||
export async function addEntry(rundownId: string, eventData: EventPostPayload): Promise<OntimeEntry> {
|
||||
const { rundown, commit } = createTransaction({ rundownId, mutableRundown: true });
|
||||
|
||||
assertSingleInsertAnchor(eventData);
|
||||
|
||||
// we allow the user to provide an ID, but make sure it is unique
|
||||
if (eventData?.id && Object.hasOwn(rundown.entries, eventData.id)) {
|
||||
throw new Error(`Event with ID ${eventData.id} already exists`);
|
||||
@@ -68,14 +74,29 @@ export async function addEntry(rundownId: string, eventData: EventPostPayload):
|
||||
parent = maybeParent;
|
||||
}
|
||||
|
||||
assertInsertAnchorInOrder(rundown, parent, eventData);
|
||||
|
||||
// normalise the position of the event in the rundown order
|
||||
const afterId = getInsertAfterId(rundown, parent, eventData?.after, eventData?.before);
|
||||
const insertPosition = (() => {
|
||||
if (eventData.before !== undefined) {
|
||||
const beforeId = getFirstInsertId(rundown, parent, eventData.before);
|
||||
return { afterId: null, beforeId, cueAfterId: getPreviousInsertId(rundown, parent, beforeId) };
|
||||
}
|
||||
|
||||
// if after is an ID, we will try and find the entry
|
||||
if (eventData.after !== undefined && eventData.after !== true) {
|
||||
const afterId = getInsertAfterId(rundown, parent, eventData.after);
|
||||
return { afterId, beforeId: null, cueAfterId: afterId };
|
||||
}
|
||||
|
||||
return { afterId: null, beforeId: null, cueAfterId: getLastInsertId(rundown, parent) };
|
||||
})();
|
||||
|
||||
// generate a fully formed entry from the patch
|
||||
const newEntry = generateEvent(rundown, eventData, afterId, parent?.id);
|
||||
const newEntry = generateEvent(rundown, eventData, insertPosition.cueAfterId, parent?.id);
|
||||
|
||||
// make mutations to rundown
|
||||
rundownMutation.add(rundown, newEntry, afterId, parent);
|
||||
rundownMutation.add(rundown, newEntry, parent, insertPosition.afterId, insertPosition.beforeId);
|
||||
|
||||
const { rundown: responseRundown, rundownMetadata, revision } = await commit();
|
||||
|
||||
@@ -395,7 +416,10 @@ export async function swapEvents(rundownId: string, fromId: EntryId, toId: Entry
|
||||
* @throws if the entry to clone does not exist
|
||||
*/
|
||||
export async function cloneEntry(rundownId: string, entryId: EntryId, options: InsertOptions): Promise<Rundown> {
|
||||
assertSingleInsertAnchor(options);
|
||||
|
||||
const { rundown, commit } = createTransaction({ rundownId, mutableRundown: true });
|
||||
assertInsertAnchorExists(rundown, options);
|
||||
const originalEntry = rundown.entries[entryId];
|
||||
|
||||
if (!originalEntry) {
|
||||
|
||||
@@ -70,6 +70,50 @@ export function generateEvent(
|
||||
throw new Error('Invalid event type');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the last valid insertion reference for a top-level rundown or group order.
|
||||
* Used when appending entries and when generating cues from the preceding entry.
|
||||
*/
|
||||
export function getLastInsertId(rundown: Rundown, parent: OntimeGroup | null): EntryId | null {
|
||||
const insertionList = parent ? parent.entries : rundown.order;
|
||||
return insertionList[insertionList.length - 1] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a `before` insertion option to the first entry in the relevant order when `true` is provided.
|
||||
* String values are already explicit anchors and are returned unchanged.
|
||||
*/
|
||||
export function getFirstInsertId(rundown: Rundown, parent: OntimeGroup | null, before: EntryId | true): EntryId | null {
|
||||
if (before !== true) {
|
||||
return before;
|
||||
}
|
||||
|
||||
const insertionList = parent ? parent.entries : rundown.order;
|
||||
return insertionList[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the sibling before a `before` insertion anchor in the top-level or group order.
|
||||
* Returns `null` when the new entry will be inserted at the start.
|
||||
*/
|
||||
export function getPreviousInsertId(
|
||||
rundown: Rundown,
|
||||
parent: OntimeGroup | null,
|
||||
beforeId: EntryId | null,
|
||||
): EntryId | null {
|
||||
if (beforeId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const insertionList = parent ? parent.entries : rundown.order;
|
||||
const beforeIndex = insertionList.indexOf(beforeId);
|
||||
if (beforeIndex < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return insertionList[beforeIndex - 1] ?? null;
|
||||
}
|
||||
|
||||
export function createEventPatch(originalEvent: OntimeEvent, patchEvent: Partial<OntimeEvent>): OntimeEvent {
|
||||
if (Object.keys(patchEvent).length === 0) {
|
||||
return originalEvent;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { body, param } from 'express-validator';
|
||||
import type { EntryId, InsertOptions, OntimeGroup, Rundown } from 'ontime-types';
|
||||
|
||||
import { requestValidationFunction } from '../validation-utils/validationFunction.js';
|
||||
|
||||
@@ -37,15 +38,27 @@ export const rundownImportValidator = [
|
||||
|
||||
export const entryPostValidator = [
|
||||
body('type').isString().isIn(['event', 'delay', 'group', 'milestone']),
|
||||
body('after').optional().isString(),
|
||||
body('before').optional().isString(),
|
||||
body('after')
|
||||
.optional()
|
||||
.custom((value) => value === true || typeof value === 'string')
|
||||
.withMessage('Allowed values for after are an ID or true.'),
|
||||
body('before')
|
||||
.optional()
|
||||
.custom((value) => value === true || typeof value === 'string')
|
||||
.withMessage('Allowed values for before are an ID or true.'),
|
||||
|
||||
requestValidationFunction,
|
||||
];
|
||||
|
||||
export const clonePostValidator = [
|
||||
body('after').optional().isString(),
|
||||
body('before').optional().isString(),
|
||||
body('after')
|
||||
.optional()
|
||||
.custom((value) => value === true || typeof value === 'string')
|
||||
.withMessage('Allowed values for after are an ID or true.'),
|
||||
body('before')
|
||||
.optional()
|
||||
.custom((value) => value === true || typeof value === 'string')
|
||||
.withMessage('Allowed values for before are an ID or true.'),
|
||||
|
||||
requestValidationFunction,
|
||||
];
|
||||
@@ -93,4 +106,44 @@ export const entryRenumberValidator = [
|
||||
requestValidationFunction,
|
||||
];
|
||||
|
||||
/**
|
||||
* Ensures callers use a single insertion anchor so placement is unambiguous.
|
||||
*/
|
||||
export function assertSingleInsertAnchor(options: InsertOptions) {
|
||||
if (options.after !== undefined && options.before !== undefined) {
|
||||
throw new Error('Use only one insertion anchor: after or before');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures an ID anchor exists and belongs to the order it is intended to position within.
|
||||
*/
|
||||
export function assertInsertAnchorInOrder(rundown: Rundown, parent: OntimeGroup | null, options: InsertOptions) {
|
||||
const anchor = getStringInsertAnchor(options);
|
||||
if (anchor === undefined) return;
|
||||
|
||||
if (!Object.hasOwn(rundown.entries, anchor)) {
|
||||
throw new Error(`Insertion anchor with ID ${anchor} does not exist`);
|
||||
}
|
||||
|
||||
const insertionList = parent ? parent.entries : rundown.order;
|
||||
if (!insertionList.includes(anchor)) {
|
||||
throw new Error(`Insertion anchor with ID ${anchor} is not in the target order`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Ensures an ID anchor refers to an entry in the rundown. */
|
||||
export function assertInsertAnchorExists(rundown: Rundown, options: InsertOptions) {
|
||||
const anchor = getStringInsertAnchor(options);
|
||||
if (anchor !== undefined && !Object.hasOwn(rundown.entries, anchor)) {
|
||||
throw new Error(`Insertion anchor with ID ${anchor} does not exist`);
|
||||
}
|
||||
}
|
||||
|
||||
function getStringInsertAnchor(options: InsertOptions): EntryId | undefined {
|
||||
if (typeof options.after === 'string') return options.after;
|
||||
if (typeof options.before === 'string') return options.before;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// #endregion operations on rundown entries =======================
|
||||
|
||||
@@ -153,6 +153,41 @@ describe('mcp.service', () => {
|
||||
expect(result.created.map((entry) => entry.id)).toEqual(['entry-1', 'entry-2', 'entry-3', 'entry-4']);
|
||||
});
|
||||
|
||||
it('omits insert anchors when creating an entry without a position', async () => {
|
||||
await createEntryForMcp({
|
||||
type: SupportedEntry.Milestone,
|
||||
title: 'End marker',
|
||||
});
|
||||
|
||||
expect(addEntryMock).toHaveBeenCalledWith(
|
||||
'loaded-rundown',
|
||||
expect.objectContaining({ type: SupportedEntry.Milestone, title: 'End marker' }),
|
||||
);
|
||||
expect(addEntryMock.mock.calls[0][1]).not.toHaveProperty('after');
|
||||
expect(addEntryMock.mock.calls[0][1]).not.toHaveProperty('before');
|
||||
});
|
||||
|
||||
it('uses before true for the first batch entry and chains the rest', async () => {
|
||||
await batchCreateEntriesForMcp({
|
||||
before: true,
|
||||
entries: [
|
||||
{ type: SupportedEntry.Event, title: 'First' },
|
||||
{ type: SupportedEntry.Event, title: 'Second' },
|
||||
],
|
||||
});
|
||||
|
||||
expect(addEntryMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'loaded-rundown',
|
||||
expect.objectContaining({ type: SupportedEntry.Event, title: 'First', before: true }),
|
||||
);
|
||||
expect(addEntryMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'loaded-rundown',
|
||||
expect.objectContaining({ type: SupportedEntry.Event, title: 'Second', after: 'entry-1' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects nested groups before creating entries', async () => {
|
||||
await expect(
|
||||
batchCreateEntriesForMcp({
|
||||
|
||||
@@ -71,10 +71,10 @@ Read the ontime://schema resource if you need a data model reference.
|
||||
|
||||
Steps:
|
||||
1. Call ontime_list_rundowns and identify the target rundown. If the user wants a background rundown, pass its \`rundownId\` in all entry read/write calls instead of loading it.
|
||||
2. Call ontime_get_rundown with the chosen \`rundownId\` to see current state and identify an \`after\` anchor if appending.
|
||||
2. Call ontime_get_rundown with the chosen \`rundownId\` to see current state and avoid duplicating existing entries.
|
||||
3. Call ontime_get_timer_state. If playback is not \`stop\` and the target is the loaded rundown, explain that MCP edits affect the live rundown and ask the user to confirm before changing it. If the target is a background rundown, it can be edited without interrupting playback.
|
||||
4. Build an array of entries in order and call ontime_batch_create_entries ONCE with all of them. This is much faster than calling ontime_create_entry per item.
|
||||
5. If the rundown already has events, pass \`after: <last event id>\` on the batch call so new events chain from the end.
|
||||
5. Omit \`after\` and \`before\` on the batch call to append the new entries to the end of the rundown. Use \`after: true\` for an explicit append request, or \`before: true\` for an explicit prepend request.
|
||||
|
||||
Entry type guidance:
|
||||
- Use \`event\` for anything with a scheduled time and duration (talks, panels, breaks, meals).
|
||||
|
||||
@@ -63,6 +63,11 @@ export type BatchCreateEntryArgs = CreateEntryArgs & { children?: BatchCreateEnt
|
||||
export type UpdateEntryArgs = EntryFieldArgs & TargetRundownArgs & { id: EntryId };
|
||||
export type GroupEntriesArgs = GroupFieldArgs & TargetRundownArgs & { ids: EntryId[] };
|
||||
export type UngroupEntryArgs = TargetRundownArgs & { id: EntryId };
|
||||
type BatchCreateEntriesArgs = TargetRundownArgs & {
|
||||
entries: BatchCreateEntryArgs[];
|
||||
after?: EntryId | true;
|
||||
before?: EntryId | true;
|
||||
};
|
||||
|
||||
export function resolveTargetRundownId(args: TargetRundownArgs): string {
|
||||
return args.rundownId ?? getCurrentRundownId();
|
||||
@@ -133,20 +138,24 @@ export function assertKnownCustomFields(...customValues: Array<EntryFieldArgs['c
|
||||
/** Translates tool arguments into the payload consumed by rundown.service addEntry */
|
||||
export function toEntryPayload(args: CreateEntryArgs): EventPostPayload {
|
||||
const { type = SupportedEntry.Event, after, before } = args;
|
||||
const insertOptions = {
|
||||
...(after !== undefined ? { after } : {}),
|
||||
...(before !== undefined ? { before } : {}),
|
||||
};
|
||||
|
||||
switch (type) {
|
||||
case SupportedEntry.Delay:
|
||||
return { type: SupportedEntry.Delay, duration: args.duration, after, before };
|
||||
return { type: SupportedEntry.Delay, duration: args.duration, ...insertOptions };
|
||||
case SupportedEntry.Milestone: {
|
||||
const { cue, title, note, colour, custom } = args;
|
||||
return { type: SupportedEntry.Milestone, cue, title, note, colour, custom, after, before };
|
||||
return { type: SupportedEntry.Milestone, cue, title, note, colour, custom, ...insertOptions };
|
||||
}
|
||||
case SupportedEntry.Group:
|
||||
// group creation currently only accepts a title, see generateEvent in rundown.utils.ts
|
||||
return { type: SupportedEntry.Group, title: args.title, after, before };
|
||||
return { type: SupportedEntry.Group, title: args.title, ...insertOptions };
|
||||
case SupportedEntry.Event: {
|
||||
const { type: _type, rundownId: _rundownId, ...eventFields } = args;
|
||||
return { type: SupportedEntry.Event, ...eventFields };
|
||||
const { type: _type, rundownId: _rundownId, after: _after, before: _before, ...eventFields } = args;
|
||||
return { type: SupportedEntry.Event, ...eventFields, ...insertOptions };
|
||||
}
|
||||
default:
|
||||
throw new Error(`Invalid entry type: ${String(type)}`);
|
||||
@@ -259,20 +268,25 @@ export async function ungroupEntryForMcp(args: UngroupEntryArgs) {
|
||||
return { target: getTargetMeta(rundownId), ungrouped: args.id, order: updatedRundown.order };
|
||||
}
|
||||
|
||||
export async function batchCreateEntriesForMcp(
|
||||
args: TargetRundownArgs & { entries: BatchCreateEntryArgs[]; after?: EntryId },
|
||||
) {
|
||||
const { entries = [], after } = args;
|
||||
export async function batchCreateEntriesForMcp(args: BatchCreateEntriesArgs) {
|
||||
const { entries = [], after, before } = args;
|
||||
validateBatchCreateEntries(entries);
|
||||
const allEntries = flattenBatchCreateEntries(entries);
|
||||
assertKnownCustomFields(...allEntries.map((entry) => entry.custom));
|
||||
const rundownId = resolveTargetRundownId(args);
|
||||
let previousId = after;
|
||||
let previousId: EntryId | undefined;
|
||||
const created: OntimeEntry[] = [];
|
||||
|
||||
for (const entryArgs of entries) {
|
||||
const firstInsertOptions =
|
||||
created.length === 0
|
||||
? {
|
||||
...(after !== undefined ? { after } : {}),
|
||||
...(before !== undefined ? { before } : {}),
|
||||
}
|
||||
: undefined;
|
||||
// eslint-disable-next-line no-await-in-loop -- top-level entries chain after the previously created one
|
||||
const entry = await createBatchEntry(rundownId, entryArgs, previousId);
|
||||
const entry = await createBatchEntry(rundownId, entryArgs, previousId, undefined, firstInsertOptions);
|
||||
created.push(...entry.created);
|
||||
previousId = entry.entry.id;
|
||||
}
|
||||
@@ -303,6 +317,7 @@ async function createBatchEntry(
|
||||
entryArgs: BatchCreateEntryArgs,
|
||||
previousId?: EntryId,
|
||||
parentId?: EntryId,
|
||||
firstInsertOptions?: InsertOptions,
|
||||
): Promise<{ entry: OntimeEntry; created: OntimeEntry[] }> {
|
||||
if (parentId && entryArgs.type === SupportedEntry.Group) {
|
||||
throw new Error('Cannot create a group inside another group.');
|
||||
@@ -311,8 +326,9 @@ async function createBatchEntry(
|
||||
const { children: _children, ...createArgs } = entryArgs;
|
||||
const payload = toEntryPayload(createArgs);
|
||||
const insertOptions = {
|
||||
...(previousId ? { after: previousId } : {}),
|
||||
...(parentId ? { parent: parentId } : {}),
|
||||
...(previousId !== undefined ? { after: previousId } : {}),
|
||||
...(parentId !== undefined ? { parent: parentId } : {}),
|
||||
...(previousId === undefined ? firstInsertOptions : {}),
|
||||
};
|
||||
|
||||
const createdEntry = await addEntry(rundownId, { ...payload, ...insertOptions } as EventPostPayload);
|
||||
|
||||
@@ -96,7 +96,7 @@ export const TOOL_DEFINITIONS = [
|
||||
{
|
||||
name: 'ontime_create_entry',
|
||||
description:
|
||||
'Create a new entry. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling. Omit after/before to append at the end. For type "event" provide title plus enough timing data for Ontime to infer a strategy: timeStart+duration calculates timeEnd, timeStart+timeEnd calculates duration and locks end, timeEnd+duration calculates timeStart, and all three prioritise duration. For "milestone" provide cue/title/note/colour and optional custom values using existing project custom field keys. For "delay" provide duration. For "group" provide title plus optional note/colour/custom/targetDuration.',
|
||||
'Create a new entry. Omit after/before to append at the end, use after: true to explicitly append, use before: true to prepend, or use before/after with an entry ID to position the entry. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling. For type "event" provide title plus enough timing data for Ontime to infer a strategy: timeStart+duration calculates timeEnd, timeStart+timeEnd calculates duration and locks end, timeEnd+duration calculates timeStart, and all three prioritise duration. For "milestone" provide cue/title/note/colour and optional custom values using existing project custom field keys. For "delay" provide duration. For "group" provide title plus optional note/colour/custom/targetDuration.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -114,8 +114,14 @@ export const TOOL_DEFINITIONS = [
|
||||
description: 'Duration in ms (events: should equal timeEnd - timeStart; delays: the schedule shift)',
|
||||
},
|
||||
targetDuration: { type: 'number', description: 'Groups only: planned length of the group in ms' },
|
||||
after: { type: 'string', description: 'Insert after this entry ID' },
|
||||
before: { type: 'string', description: 'Insert before this entry ID' },
|
||||
after: {
|
||||
type: ['string', 'boolean'],
|
||||
description: 'Insert after this entry ID, or true to append',
|
||||
},
|
||||
before: {
|
||||
type: ['string', 'boolean'],
|
||||
description: 'Insert before this entry ID, or true to prepend',
|
||||
},
|
||||
...EVENT_WRITABLE_FIELDS,
|
||||
},
|
||||
},
|
||||
@@ -218,13 +224,20 @@ export const TOOL_DEFINITIONS = [
|
||||
{
|
||||
name: 'ontime_batch_create_entries',
|
||||
description:
|
||||
'Create multiple entries, including groups with nested children. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling. Use this for "build from agenda" flows to avoid many round trips. Entries are inserted in array order; if `after` is provided it positions the first top-level entry, subsequent top-level entries chain from the previous. A group entry may include `children`; those entries are created inside the group in array order. Groups cannot be nested. For events, provide title plus enough timing data for Ontime to infer a strategy: timeStart+duration calculates timeEnd, timeStart+timeEnd calculates duration and locks end, timeEnd+duration calculates timeStart, and all three prioritise duration.',
|
||||
'Create multiple entries, including groups with nested children. Omit rundownId for the currently loaded live rundown, or provide a rundownId from ontime_list_rundowns to edit a background rundown without loading it. If playback is running and rundownId is omitted or matches the loaded rundown, confirm the user intends to change the live rundown before calling. Use this for "build from agenda" flows to avoid many round trips. Entries are inserted in array order; omit after/before to append the first entry at the end, use after: true to explicitly append, use before: true to prepend, or use after/before with an entry ID to position the first top-level entry. Subsequent top-level entries chain from the previous. A group entry may include `children`; those entries are created inside the group in array order. Groups cannot be nested. For events, provide title plus enough timing data for Ontime to infer a strategy: timeStart+duration calculates timeEnd, timeStart+timeEnd calculates duration and locks end, timeEnd+duration calculates timeStart, and all three prioritise duration.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
required: ['entries'],
|
||||
properties: {
|
||||
...RUNDOWN_TARGET_FIELD,
|
||||
after: { type: 'string', description: 'Insert the first entry after this entry ID' },
|
||||
after: {
|
||||
type: ['string', 'boolean'],
|
||||
description: 'Insert the first entry after this entry ID, or true to append',
|
||||
},
|
||||
before: {
|
||||
type: ['string', 'boolean'],
|
||||
description: 'Insert the first entry before this entry ID, or true to prepend',
|
||||
},
|
||||
entries: {
|
||||
type: 'array',
|
||||
description: 'Array of entries to create, in desired order',
|
||||
@@ -588,7 +601,13 @@ const TOOL_HANDLERS: Record<ToolName, (args: Record<string, unknown>) => Promise
|
||||
|
||||
ontime_batch_create_entries: async (args) => {
|
||||
return ok(
|
||||
await batchCreateEntriesForMcp(args as TargetRundownArgs & { entries: BatchCreateEntryArgs[]; after?: EntryId }),
|
||||
await batchCreateEntriesForMcp(
|
||||
args as TargetRundownArgs & {
|
||||
entries: BatchCreateEntryArgs[];
|
||||
after?: EntryId | true;
|
||||
before?: EntryId | true;
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user