Compare commits

..

7 Commits

Author SHA1 Message Date
Claude b59dc796cf feat: collapsible aux timers section, fix icon button variants
- Add a collapse toggle next to the aux timers settings shortcut,
  mirroring the chevron pattern already used for rundown groups. State
  persists in localStorage via the existing editorSettings store, so
  it's a durable per-user preference rather than resetting on reload.
  This matters most on small viewports, where the aux timer controls
  (3 rows) are a disproportionate cost relative to their usage.
- When collapsed, a small active-indicator dot appears next to the
  "Aux timers" label if any aux timer is currently running, so a
  running timer never goes silently invisible.
- Switch both header icon buttons (settings shortcut, collapse toggle)
  from the 'subtle' variant (blue, reserved for actions) to
  'subtle-white', matching how utility/navigation icon buttons are
  styled elsewhere (eg. the rundown group collapse chevron).

Verified in the browser: collapsing reclaims the three-row control
block, the indicator dot appears while a timer runs and the panel is
collapsed, and both icon buttons render white/gray instead of blue.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WCZejVTzuAY3tHTE6nB3JH
2026-08-01 07:53:20 +00:00
Claude d70d7f2fd8 fix: prevent aux timer names from breaking the playback control layout
The aux timer label sits inside a 3 column CSS grid. Grid items default
to min-width: auto, so their minimum width is set by their content -
with white-space: nowrap forcing that to the full unbroken name, the
column would grow to fit it instead of the ellipsis ever kicking in,
breaking the equal column layout for long names.

Set min-width: 0 on the label so it can shrink to its grid column, and
swap the native title attribute for the app's shared Tooltip component
so the full name is still available on hover, consistent with how
truncated text is handled elsewhere in the app.

Verified in the browser: a long name now truncates with an ellipsis
without disturbing the three-column layout, and hovering shows the
full name in a tooltip.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WCZejVTzuAY3tHTE6nB3JH
2026-08-01 07:32:02 +00:00
Claude 469d83dc0b fix: keep editor identifying timers by index, revert secondary-source labels
- AuxTimer.tsx (editor playback control) now always shows the timer's
  index alongside its custom name, eg. "Aux 1: Speaker", instead of
  replacing the index entirely. Truncates to a single line with an
  ellipsis (and a title tooltip) so long names don't wrap and break the
  compact three-column layout.
- Revert the secondary-source select and its preview label
  (TimerViewControl.tsx, TimerPreview.tsx) back to plain "Aux 1/2/3" -
  these identify a fixed technical source, not the timer's identity, so
  they should stay stable regardless of naming.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WCZejVTzuAY3tHTE6nB3JH
2026-08-01 07:25:18 +00:00
Claude 59bff62f76 refactor: address review feedback on aux timer naming
- Revert the automation action labels back to "Aux N: action" (no
  functional reason to change this wording).
- Simplify the aux timers header in the playback control: the flex
  container now only handles layout, and the label text reuses the
  same font-size/color as the per-timer labels below it, instead of a
  bespoke style block duplicating those values.
- Replace the generic, length-driven normaliser with an explicit
  sanitiseAuxTimerNames() that always deals with exactly three timers,
  and rename it away from "normalise" (which didn't convey that it
  trims, caps length and fills in missing entries). Static defaults
  now use a plain ['', '', ''] literal instead of calling the
  sanitiser with no input to sanitise.
- Settings.type.ts and AuxTimerSettings.tsx no longer generate their
  three fields from a loop; the form mirrors the same explicit,
  one-field-per-row style already used by GeneralSettings.tsx.
- Trim comments that only restated what the following line already
  says, keeping the ones that explain non-obvious behaviour (why
  AuxTimerService needs to be resynced separately from the data
  provider, why SimpleTimer.reset() preserves the name).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WCZejVTzuAY3tHTE6nB3JH
2026-08-01 07:15:12 +00:00
Claude 38e3ab979d fix: resync aux timer names on project load, consolidate name handling
Addresses the review findings on the aux timer naming feature.

- Aux timer names are project data, but they were only applied at
  bootstrap and on a settings POST. Loading another project left the
  previous project's names in the runtime store, so the controls and
  views disagreed with the settings panel until a restart. The names are
  now applied when a project is loaded, and patching the current project
  settings applies them and sends a settings refetch to the clients
  (loading a project already triggers a full refetch via the rundown).
- Consolidate the name handling into a single normaliser in ontime-utils,
  used by the project file parser, the API validation and to build the
  default value. This creates the property when importing project files
  saved before the feature existed, and enforces the name length limit
  server side rather than only in the form.
- loadNames normalises its input, so the runtime state is consistent
  regardless of the shape of the stored settings.
- Clarify that auxTimerNames is ordered (index 0 is aux timer 1), and
  derive the settings form from the shared aux timer count.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WCZejVTzuAY3tHTE6nB3JH
2026-07-30 17:31:27 +00:00
Claude 2f29060fa4 refactor: expose aux timer names via runtime store, index in automations
Addresses review feedback on the aux timer naming feature:

- Automation action labels now reference the timers by index
  ("Aux timer 1: start") rather than the custom names, keeping the
  automation config stable regardless of naming.
- Expose the custom names through the consumer-facing runtime interface:
  the aux timer objects broadcast over the websocket now carry a `name`
  field. Names are seeded from the persisted settings at bootstrap and
  kept in sync whenever the settings change, so every consumer (views and
  integrations) reads them from the same runtime data.
- The client control and view consumers now read the name from the
  runtime store instead of querying settings directly; the settings form
  remains the persisted editing source.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WCZejVTzuAY3tHTE6nB3JH
2026-07-25 08:49:51 +00:00
Claude 2f7909ccc3 feat: allow naming aux timers
Adds custom, persisted names for the three aux timers, editable in the
editor settings and surfaced everywhere an aux title is shown.

- Persist `auxTimerNames` on the Settings object (default empty, falls
  back to the stock "Aux N" label when unset). Reuses the existing
  settings pipeline: validation sanitises to a fixed-length trimmed
  array, the parser normalises loaded/legacy data, and migrations carry
  the field forward.
- New "Aux timers" settings section to name each timer, plus a shortcut
  button next to the aux timers in the playback control that jumps
  straight to it.
- Resolve names via a shared getAuxTimerLabel helper in the aux timer
  control, Studio view, secondary-source selector and preview, and the
  automation action labels.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WCZejVTzuAY3tHTE6nB3JH
2026-07-23 15:48:09 +00:00
63 changed files with 713 additions and 886 deletions
+7 -13
View File
@@ -1,6 +1,7 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
EntryId,
InsertOptions,
MaybeString,
OntimeDelay,
OntimeEntry,
@@ -59,15 +60,9 @@ export type EventOptions = Partial<{
before: MaybeString;
// options of entries of type OntimeEvent
linkPrevious: boolean;
/** the timing reference for the new entry, usually the same as after */
lastEventId: MaybeString;
}>;
type ClientInsertOptions = {
after?: EntryId;
before?: EntryId;
};
/**
* Gather utilities for actions on entries in the loaded rundown.
*/
@@ -125,7 +120,7 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
* @private
*/
const { mutateAsync: addEntryMutation } = useMutation({
mutationFn: ([rundownId, entry]: [string, PatchWithId & ClientInsertOptions]) => postAddEntry(rundownId, entry),
mutationFn: ([rundownId, entry]: [string, PatchWithId & InsertOptions]) => postAddEntry(rundownId, entry),
onMutate: async ([_rundownId, entry]) => {
const queryKey = resolveCurrentRundownQueryKey();
await queryClient.cancelQueries({ queryKey });
@@ -154,9 +149,8 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
addToRundown(
newRundown,
optimisticEntry,
parent ? (newRundown.entries[parent.id] as OntimeGroup) : null,
afterId,
entry.before ?? null,
parent ? (newRundown.entries[parent.id] as OntimeGroup) : null,
);
queryClient.setQueryData<Rundown>(queryKey, newRundown);
@@ -199,7 +193,7 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
throw new Error('Rundown not initialised');
}
const newEntry: PatchWithId & ClientInsertOptions = { ...entry, id: generateId() };
const newEntry: PatchWithId & InsertOptions = { ...entry, id: generateId() };
// handle adding options that concern all event types
if (options?.after) {
@@ -211,8 +205,8 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
// ************* CHECK OPTIONS specific to events
if (isOntimeEvent(newEntry)) {
// last event id is the timing reference of the previous OntimeEvent in rundown
if (options?.lastEventId) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- we know this is a value
const previousEvent = rundownData.entries[options?.lastEventId];
if (isOntimeEvent(previousEvent)) {
newEntry.timeStart = previousEvent.timeEnd;
@@ -290,7 +284,7 @@ function useEntryActionsForRundown(scopedRundownId: string | undefined) {
* Clone an entry
*/
const clone = useCallback(
async (entryId: EntryId, options?: ClientInsertOptions) => {
async (entryId: EntryId, options?: InsertOptions) => {
try {
const rundownId = getCurrentRundownData()?.id;
if (!rundownId) {
@@ -1063,7 +1057,7 @@ function optimisticDeleteEntries(entryIds: EntryId[], rundown: Rundown) {
/**
* Utility to create an optimistic entry for immediate cache insertion
*/
function createOptimisticEntry(payload: PatchWithId & ClientInsertOptions): OntimeEntry {
function createOptimisticEntry(payload: PatchWithId & InsertOptions): OntimeEntry {
const { after: _after, before: _before, ...entryData } = payload;
const id = entryData.id;
let parent: EntryId | null = null;
+19
View File
@@ -95,6 +95,22 @@ export const useAuxTimersTime = createSelector((state: RuntimeStore) => {
};
});
export const useAuxTimersName = createSelector((state: RuntimeStore) => {
return {
aux1: state.auxtimer1.name,
aux2: state.auxtimer2.name,
aux3: state.auxtimer3.name,
};
});
export const useAuxTimersActive = createSelector((state: RuntimeStore) => {
return (
state.auxtimer1.playback === SimplePlayback.Start ||
state.auxtimer2.playback === SimplePlayback.Start ||
state.auxtimer3.playback === SimplePlayback.Start
);
});
export const useAuxTimerTime = (index: number) =>
createSelector((state: RuntimeStore) => {
if (index === 1) return state.auxtimer1.current;
@@ -108,15 +124,18 @@ export const useAuxTimerControl = (index: number) =>
return {
playback: state.auxtimer1.playback,
direction: state.auxtimer1.direction,
name: state.auxtimer1.name,
};
if (index === 2)
return {
playback: state.auxtimer2.playback,
direction: state.auxtimer2.direction,
name: state.auxtimer2.name,
};
return {
playback: state.auxtimer3.playback,
direction: state.auxtimer3.direction,
name: state.auxtimer3.name,
};
})();
@@ -6,4 +6,5 @@ export const ontimePlaceholderSettings: Settings = {
operatorKey: null,
timeFormat: '24',
language: 'en',
auxTimerNames: ['', '', ''],
};
@@ -13,6 +13,7 @@ type EditorSettingsStore = {
defaultTimerType: TimerType;
defaultEndAction: EndAction;
inheritGroupColour: boolean;
auxTimersCollapsed: boolean;
setDefaultDuration: (defaultDuration: string) => void;
setLinkPrevious: (linkPrevious: boolean) => void;
setInheritGroupColour: (inheritGroupColour: boolean) => void;
@@ -21,6 +22,7 @@ type EditorSettingsStore = {
setDangerTime: (dangerTime: string) => void;
setDefaultTimerType: (defaultTimerType: TimerType) => void;
setDefaultEndAction: (defaultEndAction: EndAction) => void;
setAuxTimersCollapsed: (auxTimersCollapsed: boolean) => void;
};
export const editorSettingsDefaults = {
@@ -32,6 +34,7 @@ export const editorSettingsDefaults = {
timerType: TimerType.CountDown,
endAction: EndAction.None,
inheritGroupColour: false,
auxTimersCollapsed: false,
};
enum EditorSettingsKeys {
@@ -43,6 +46,7 @@ enum EditorSettingsKeys {
DefaultTimerType = 'ontime-default-timer-type',
DefaultEndAction = 'ontime-default-end-action',
InheritGroupColour = 'ontime-inherit-group-colour',
AuxTimersCollapsed = 'ontime-aux-timers-collapsed',
}
export const useEditorSettings = create<EditorSettingsStore>((set) => {
@@ -67,6 +71,10 @@ export const useEditorSettings = create<EditorSettingsStore>((set) => {
EditorSettingsKeys.InheritGroupColour,
editorSettingsDefaults.inheritGroupColour,
),
auxTimersCollapsed: booleanFromLocalStorage(
EditorSettingsKeys.AuxTimersCollapsed,
editorSettingsDefaults.auxTimersCollapsed,
),
setDefaultDuration: (defaultDuration) =>
set(() => {
@@ -110,5 +118,10 @@ export const useEditorSettings = create<EditorSettingsStore>((set) => {
localStorage.setItem(EditorSettingsKeys.InheritGroupColour, String(inheritGroupColour));
return { inheritGroupColour };
}),
setAuxTimersCollapsed: (auxTimersCollapsed) =>
set(() => {
localStorage.setItem(EditorSettingsKeys.AuxTimersCollapsed, String(auxTimersCollapsed));
return { auxTimersCollapsed };
}),
};
});
@@ -0,0 +1,10 @@
export function getAuxTimerLabel(name: string | undefined, fallback: string): string {
const custom = name?.trim();
return custom ? custom : fallback;
}
/** Combines the aux timer's index with its custom name, eg. "Aux 1: Speaker" */
export function getAuxTimerIndexedLabel(name: string | undefined, index: number): string {
const custom = name?.trim();
return custom ? `Aux ${index}: ${custom}` : `Aux ${index}`;
}
+4 -3
View File
@@ -5,7 +5,6 @@ import {
MILLIS_PER_SECOND,
dayInMs,
formatFromMillis,
getExpectedEnd,
getExpectedStart,
} from 'ontime-utils';
@@ -187,13 +186,15 @@ export function getExpectedTimesFromExtendedEvent(
...state,
},
);
const expectedEnd = getExpectedEnd(event, expectedStart, state.currentDay);
const plannedEnd = event.timeStart + event.duration + event.delay;
return {
expectedStart,
timeToStart: expectedStart - state.clock,
expectedEnd,
expectedEnd: event.countToEnd
? Math.max(expectedStart + event.duration, plannedEnd)
: expectedStart + event.duration,
plannedEnd,
};
}
@@ -0,0 +1,95 @@
import { Settings } from 'ontime-types';
import { auxTimerNameMaxLength } from 'ontime-utils';
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { postSettings } from '../../../../common/api/settings';
import { maybeAxiosError } from '../../../../common/api/utils';
import Button from '../../../../common/components/buttons/Button';
import Info from '../../../../common/components/info/Info';
import Input from '../../../../common/components/input/input/Input';
import useSettings from '../../../../common/hooks-query/useSettings';
import { preventEscape } from '../../../../common/utils/keyEvent';
import * as Panel from '../../panel-utils/PanelUtils';
export default function AuxTimerSettings() {
const { data, status, refetch } = useSettings();
const {
handleSubmit,
register,
reset,
setError,
formState: { isSubmitting, isDirty, errors },
} = useForm<Settings>({
defaultValues: data,
resetOptions: {
keepDirtyValues: true,
},
});
useEffect(() => {
if (data) {
reset(data);
}
}, [data, reset]);
const onSubmit = async (formData: Settings) => {
try {
await postSettings(formData);
} catch (error) {
const message = maybeAxiosError(error);
setError('root', { message });
} finally {
await refetch();
}
};
const onReset = () => {
reset(data);
};
const isLoading = status === 'pending';
return (
<Panel.Section
as='form'
onSubmit={handleSubmit(onSubmit)}
onKeyDown={(event) => preventEscape(event, onReset)}
id='aux-timer-settings'
>
<Panel.Card>
<Panel.SubHeader>
Aux timers
<Panel.InlineElements>
<Button disabled={!isDirty || isSubmitting} variant='ghosted' onClick={onReset}>
Revert to saved
</Button>
<Button type='submit' loading={isSubmitting} disabled={!isDirty} variant='primary'>
Save
</Button>
</Panel.InlineElements>
</Panel.SubHeader>
<Panel.Divider />
<Panel.Section>
<Info>Give the aux timers custom names. Names are shown across the editor controls and views.</Info>
<Panel.Loader isLoading={isLoading} />
<Panel.Error>{errors.root?.message}</Panel.Error>
<Panel.ListGroup>
<Panel.ListItem>
<Panel.Field title='Aux timer 1' description='Custom name for aux timer 1' />
<Input maxLength={auxTimerNameMaxLength} placeholder='Aux 1' {...register('auxTimerNames.0')} />
</Panel.ListItem>
<Panel.ListItem>
<Panel.Field title='Aux timer 2' description='Custom name for aux timer 2' />
<Input maxLength={auxTimerNameMaxLength} placeholder='Aux 2' {...register('auxTimerNames.1')} />
</Panel.ListItem>
<Panel.ListItem>
<Panel.Field title='Aux timer 3' description='Custom name for aux timer 3' />
<Input maxLength={auxTimerNameMaxLength} placeholder='Aux 3' {...register('auxTimerNames.2')} />
</Panel.ListItem>
</Panel.ListGroup>
</Panel.Section>
</Panel.Card>
</Panel.Section>
);
}
@@ -3,6 +3,7 @@ import { isDocker } from '../../../../externals';
import type { PanelBaseProps } from '../../panel-list/PanelList';
import * as Panel from '../../panel-utils/PanelUtils';
import CustomViews from '../manage-panel/CustomViews';
import AuxTimerSettings from './AuxTimerSettings';
import GeneralSettings from './GeneralSettings';
import McpSection from './McpSection';
import ProjectData from './ProjectData';
@@ -12,6 +13,7 @@ import ViewSettings from './ViewSettings';
export default function SettingsPanel({ location }: PanelBaseProps) {
const dataRef = useScrollIntoView<HTMLDivElement>('data', location);
const generalRef = useScrollIntoView<HTMLDivElement>('general', location);
const auxTimersRef = useScrollIntoView<HTMLDivElement>('aux-timers', location);
const viewRef = useScrollIntoView<HTMLDivElement>('view', location);
const customViewsRef = useScrollIntoView<HTMLDivElement>('custom-views', location);
const mcpRef = useScrollIntoView<HTMLDivElement>('mcp', location);
@@ -26,6 +28,9 @@ export default function SettingsPanel({ location }: PanelBaseProps) {
<div ref={generalRef}>
<GeneralSettings />
</div>
<div ref={auxTimersRef}>
<AuxTimerSettings />
</div>
<div ref={viewRef}>
<ViewSettings />
</div>
@@ -17,6 +17,7 @@ const staticOptions = [
secondary: [
{ id: 'settings__data', label: 'Project data' },
{ id: 'settings__general', label: 'General settings' },
{ id: 'settings__aux-timers', label: 'Aux timers' },
{ id: 'settings__view', label: 'View settings' },
{ id: 'settings__custom-views', label: 'Custom views' },
{ id: 'settings__mcp', label: 'MCP Server' },
@@ -3,6 +3,34 @@
margin: 0 auto;
}
.auxHeader {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 1rem;
}
.label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: $inner-section-text-size;
color: $label-gray;
}
.auxHeaderButtons {
display: flex;
align-items: center;
gap: 0.25rem;
}
.activeIndicator {
width: 0.5rem;
height: 0.5rem;
border-radius: 50%;
background-color: $active-indicator;
}
.auxTimers {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
@@ -1,4 +1,10 @@
import { usePlaybackControl } from '../../../common/hooks/useSocket';
import { IoChevronDown, IoChevronUp, IoSettingsOutline } from 'react-icons/io5';
import IconButton from '../../../common/components/buttons/IconButton';
import Tooltip from '../../../common/components/tooltip/Tooltip';
import { useAuxTimersActive, usePlaybackControl } from '../../../common/hooks/useSocket';
import { useEditorSettings } from '../../../common/stores/editorSettings';
import useAppSettingsNavigation from '../../app-settings/useAppSettingsNavigation';
import AddTime from './add-time/AddTime';
import { AuxTimer } from './aux-timer/AuxTimer';
import PlaybackButtons from './playback-buttons/PlaybackButtons';
@@ -8,6 +14,9 @@ import style from './PlaybackControl.module.scss';
export default function PlaybackControl() {
const data = usePlaybackControl();
const { setLocation } = useAppSettingsNavigation();
const { auxTimersCollapsed, setAuxTimersCollapsed } = useEditorSettings();
const isAuxTimerActive = useAuxTimersActive();
return (
<div className={style.mainContainer}>
@@ -20,11 +29,42 @@ export default function PlaybackControl() {
selectedEventIndex={data.selectedEventIndex}
timerPhase={data.timerPhase}
/>
<div className={style.auxTimers}>
<AuxTimer index={1} />
<AuxTimer index={2} />
<AuxTimer index={3} />
<div className={style.auxHeader}>
<span className={style.label}>
Aux timers
{auxTimersCollapsed && isAuxTimerActive && <span className={style.activeIndicator} />}
</span>
<div className={style.auxHeaderButtons}>
<Tooltip
text='Name aux timers'
render={
<IconButton
size='small'
variant='subtle-white'
aria-label='Name aux timers'
onClick={() => setLocation('settings__aux-timers')}
/>
}
>
<IoSettingsOutline />
</Tooltip>
<IconButton
size='small'
variant='subtle-white'
aria-label={auxTimersCollapsed ? 'Expand aux timers' : 'Collapse aux timers'}
onClick={() => setAuxTimersCollapsed(!auxTimersCollapsed)}
>
{auxTimersCollapsed ? <IoChevronUp /> : <IoChevronDown />}
</IconButton>
</div>
</div>
{!auxTimersCollapsed && (
<div className={style.auxTimers}>
<AuxTimer index={1} />
<AuxTimer index={2} />
<AuxTimer index={3} />
</div>
)}
</div>
);
}
@@ -1,8 +1,18 @@
.label {
display: block;
margin-top: 1rem;
// aux timers sit in a 3 column grid, without this a long name would grow its column
// instead of shrinking to it, breaking the equal column layout
min-width: 0;
}
.labelText {
display: block;
font-size: $inner-section-text-size;
color: $label-gray;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.controls {
@@ -3,7 +3,9 @@ import { millisToString, parseUserTime } from 'ontime-utils';
import { IoArrowDown, IoArrowUp, IoPause, IoPlay, IoStop } from 'react-icons/io5';
import TimeInput from '../../../../common/components/input/time-input/TimeInput';
import Tooltip from '../../../../common/components/tooltip/Tooltip';
import { setAuxTimer, useAuxTimerControl, useAuxTimerTime } from '../../../../common/hooks/useSocket';
import { getAuxTimerIndexedLabel } from '../../../../common/utils/auxTimerUtils';
import TapButton from '../tap-button/TapButton';
import style from './AuxTimer.module.scss';
@@ -13,10 +15,12 @@ interface AuxTimerProps {
}
export function AuxTimer({ index }: AuxTimerProps) {
const { playback, direction } = useAuxTimerControl(index);
const { playback, direction, name } = useAuxTimerControl(index);
const { stop, setDirection } = setAuxTimer;
const label = getAuxTimerIndexedLabel(name, index);
const toggleDirection = () => {
const newDirection = direction === SimpleDirection.CountDown ? SimpleDirection.CountUp : SimpleDirection.CountDown;
setDirection(index, newDirection);
@@ -27,10 +31,12 @@ export function AuxTimer({ index }: AuxTimerProps) {
return (
<label className={style.label}>
Aux Timer {index}
<Tooltip text={label} render={<span />} className={style.labelText}>
{label}
</Tooltip>
<div className={style.controls}>
<div className={style.input}>
<AuxTimerInput index={index} isActive={isActive} />
<AuxTimerInput index={index} isActive={isActive} placeholder={`Aux ${index}`} />
<TapButton onClick={toggleDirection} aspect='tight' disabled={isActive}>
{direction === SimpleDirection.CountDown && <IoArrowDown data-testid={`aux-timer-direction-${index}`} />}
{direction === SimpleDirection.CountUp && <IoArrowUp data-testid={`aux-timer-direction-${index}`} />}
@@ -50,9 +56,10 @@ export function AuxTimer({ index }: AuxTimerProps) {
interface AuxTimerInputProps {
index: number;
isActive: boolean;
placeholder: string;
}
function AuxTimerInput({ index, isActive }: AuxTimerInputProps) {
function AuxTimerInput({ index, isActive, placeholder }: AuxTimerInputProps) {
const newTimeInMs = useAuxTimerTime(index);
const { setDuration } = setAuxTimer;
@@ -70,7 +77,7 @@ function AuxTimerInput({ index, isActive }: AuxTimerInputProps) {
}
return (
<TimeInput submitHandler={handleTimeUpdate} name={`aux${index}`} time={newTimeInMs} placeholder={`Aux ${index}`} />
<TimeInput submitHandler={handleTimeUpdate} name={`aux${index}`} time={newTimeInMs} placeholder={placeholder} />
);
}
+1 -3
View File
@@ -339,9 +339,7 @@ export default function Rundown({ order, flatOrder, entries, id, rundownMetadata
increaseViewportBy={{ top: 200, bottom: 400 }}
style={{ height: '100%' }}
components={{
Header: isEditMode
? () => <QuickAddButtons previousEventId={null} nextEventId={order[0]} parentGroup={null} />
: undefined,
Header: isEditMode ? () => <QuickAddButtons previousEventId={null} parentGroup={null} /> : undefined,
Footer: () => (
<>
{isEditMode && (
@@ -11,17 +11,13 @@ import style from './QuickAddButtons.module.scss';
interface QuickAddButtonsProps {
previousEventId: MaybeString;
nextEventId?: MaybeString;
parentGroup: MaybeString;
backgroundColor?: string;
}
export default memo(QuickAddButtons);
function QuickAddButtons({ previousEventId, nextEventId, parentGroup, backgroundColor }: QuickAddButtonsProps) {
function QuickAddButtons({ previousEventId, 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(
@@ -29,23 +25,44 @@ function QuickAddButtons({ previousEventId, nextEventId, parentGroup, background
type: SupportedEntry.Event,
parent: parentGroup,
},
insertionOptions,
{
after: previousEventId,
lastEventId: previousEventId,
},
);
};
const addDelay = () => {
addEntry({ type: SupportedEntry.Delay, parent: parentGroup }, insertionOptions);
addEntry(
{ type: SupportedEntry.Delay, parent: parentGroup },
{
lastEventId: previousEventId,
after: previousEventId,
},
);
};
const addMilestone = () => {
addEntry({ type: SupportedEntry.Milestone, parent: parentGroup }, insertionOptions);
addEntry(
{ type: SupportedEntry.Milestone, parent: parentGroup },
{
lastEventId: previousEventId,
after: previousEventId,
},
);
};
const addGroup = () => {
if (parentGroup !== null) {
return;
}
addEntry({ type: SupportedEntry.Group }, insertionOptions);
addEntry(
{ type: SupportedEntry.Group },
{
lastEventId: previousEventId,
after: previousEventId,
},
);
};
/**
@@ -96,7 +96,7 @@ export function useRundownCommands({
addEntry(patch, {
after: id && !above ? id : undefined,
before: id && above ? id : undefined,
lastEventId: id && !above ? id : undefined,
lastEventId: !above && id ? id : undefined,
});
},
[addEntry],
@@ -153,7 +153,7 @@ type ScheduleTimeProps = {
//TODO: consider relative mode
export function ScheduleTime(props: ScheduleTimeProps) {
const { event, showExpected } = props;
const { timeStart, duration, delay, expectedStart, expectedEnd } = event;
const { timeStart, duration, delay, expectedStart, countToEnd } = event;
const plannedStart = timeStart + delay + event.dayOffset * dayInMs;
@@ -164,6 +164,7 @@ export function ScheduleTime(props: ScheduleTimeProps) {
const expectedStateClass = `sub__schedule--${getOffsetState(expectedStart - plannedStart)}`;
const plannedEnd = plannedStart + duration + delay;
const expectedEnd = countToEnd ? Math.max(expectedStart + duration, plannedEnd) : expectedStart + duration;
const expectedEndClass = `sub__schedule--${getOffsetState(expectedEnd - plannedEnd)}`;
return (
@@ -1,15 +1,17 @@
import { getExpectedEnd, getExpectedStart } from 'ontime-utils';
import { MaybeNumber, OntimeEvent } from 'ontime-types';
import { getExpectedStart } from 'ontime-utils';
import { IoPencil } from 'react-icons/io5';
import Button from '../../common/components/buttons/Button';
import useReport from '../../common/hooks-query/useReport';
import { useFadeOutOnInactivity } from '../../common/hooks/useFadeOutOnInactivity';
import { useExpectedStartData } from '../../common/hooks/useSocket';
import { ExtendedEntry } from '../../common/utils/rundownMetadata';
import { cx } from '../../common/utils/styleUtils';
import SuperscriptTime from '../common/superscript-time/SuperscriptTime';
import { getPropertyValue } from '../common/viewUtils';
import { useCountdownOptions } from './countdown.options';
import { CountdownEvent, CountdownTarget, useSubscriptionDisplayData } from './countdown.utils';
import { CountdownTarget, useSubscriptionDisplayData } from './countdown.utils';
import { ScheduleTime } from './CountdownSubscriptions';
import './SingleEventCountdown.scss';
@@ -36,10 +38,8 @@ export default function SingleEventCountdown({ subscribedEvent, goToEditMode }:
mode,
});
const expectedEnd = getExpectedEnd(subscribedEvent, expectedStart, currentDay);
const { endedAt } = reportData[subscribedEvent.reportId ?? subscribedEvent.id] ?? { endedAt: null };
const countdownEvent = { ...subscribedEvent, expectedStart, endedAt, expectedEnd };
const countdownEvent = { ...subscribedEvent, expectedStart, endedAt };
const titleTmp = getPropertyValue(subscribedEvent, mainSource ?? 'title');
const title = titleTmp?.length ? titleTmp : ' '; // insert utf-8 empty space to avoid the line collapsing;
// while a group is live, surface the running event's title as the secondary line
@@ -64,7 +64,7 @@ export default function SingleEventCountdown({ subscribedEvent, goToEditMode }:
}
interface SubscriptionStatusProps {
event: CountdownEvent;
event: ExtendedEntry<OntimeEvent> & { endedAt: MaybeNumber; expectedStart: number };
}
function SubscriptionStatus({ event }: SubscriptionStatusProps) {
@@ -12,7 +12,7 @@ import {
isOntimeGroup,
isPlayableEvent,
} from 'ontime-types';
import { MILLIS_PER_MINUTE, getExpectedEnd, getExpectedStart, millisToString, removeLeadingZero } from 'ontime-utils';
import { MILLIS_PER_MINUTE, getExpectedStart, millisToString, removeLeadingZero } from 'ontime-utils';
import { useCountdownSocket } from '../../common/hooks/useSocket';
import { ExtendedEntry } from '../../common/utils/rundownMetadata';
@@ -197,7 +197,7 @@ export type CountdownTarget = ExtendedEntry<OntimeEvent> & {
liveEntry?: ExtendedEntry<OntimeEvent> | null; // the running child while a group is live
};
export type CountdownEvent = CountdownTarget & { expectedStart: number; endedAt: MaybeNumber; expectedEnd: number };
export type CountdownEvent = CountdownTarget & { expectedStart: number; endedAt: MaybeNumber };
/**
* Resolves a subscription (event or group) into an event-shaped countdown target.
@@ -271,7 +271,6 @@ export function extendEventData(
offset,
mode,
});
const expectedEnd = getExpectedEnd(event, expectedStart, currentDay);
const { endedAt } = reportData[event.reportId ?? event.id] ?? { endedAt: null };
return { ...event, expectedStart, endedAt, expectedEnd };
return { ...event, expectedStart, endedAt };
}
@@ -1,7 +1,8 @@
import { Playback, TimerPhase, ViewSettings } from 'ontime-types';
import { millisToString } from 'ontime-utils';
import { useAuxTimersTime, useStudioTimersSocket } from '../../common/hooks/useSocket';
import { useAuxTimersName, useAuxTimersTime, useStudioTimersSocket } from '../../common/hooks/useSocket';
import { getAuxTimerLabel } from '../../common/utils/auxTimerUtils';
import { getOffsetState } from '../../common/utils/offset';
import { cx } from '../../common/utils/styleUtils';
import { useTranslation } from '../../translation/TranslationProvider';
@@ -121,22 +122,23 @@ export default function StudioTimers({ viewSettings }: StudioTimersProps) {
function StudioTimersAux() {
const auxTimer = useAuxTimersTime();
const auxName = useAuxTimersName();
return (
<div className='card' id='card-aux'>
<div className='card__row'>
<div>
<div className='label'>Aux 1</div>
<div className='label'>{getAuxTimerLabel(auxName.aux1, 'Aux 1')}</div>
<div className='extra'>{millisToString(auxTimer.aux1)}</div>
</div>
<div>
<div className='label center'>Aux 2</div>
<div className='label center'>{getAuxTimerLabel(auxName.aux2, 'Aux 2')}</div>
<div className='extra center'>{millisToString(auxTimer.aux2)}</div>
</div>
<div>
<div className='label right'>Aux 3</div>
<div className='label right'>{getAuxTimerLabel(auxName.aux3, 'Aux 3')}</div>
<div className='extra right'>{millisToString(auxTimer.aux3)}</div>
</div>
</div>
@@ -90,4 +90,14 @@ describe('test parseDatabaseModel() edge cases', () => {
// @ts-expect-error -- we know this is wrong, testing imports outside domain
expect(() => parseDatabaseModel('some random dataset')).toThrow();
});
it('creates the aux timer names when importing a project file which predates the feature', () => {
const oldProject = structuredClone(demoDb);
// @ts-expect-error -- simulating a project file saved before aux timer naming existed
delete oldProject.settings.auxTimerNames;
const { data } = parseDatabaseModel(oldProject);
expect(data.settings.auxTimerNames).toStrictEqual(['', '', '']);
});
});
@@ -74,7 +74,15 @@ export function migrateSettings(jsonData: object): (Settings & { serverPort: num
const { serverPort, editorKey, operatorKey, timeFormat, language } = structuredClone(
jsonData.settings,
) as old_Settings;
return { version: '4.0.0', serverPort, editorKey, operatorKey, timeFormat, language };
return {
version: '4.0.0',
serverPort,
editorKey,
operatorKey,
timeFormat,
language,
auxTimerNames: ['', '', ''],
};
}
}
@@ -1,4 +1,5 @@
import { DatabaseModel, Settings } from 'ontime-types';
import { sanitiseAuxTimerNames } from 'ontime-utils';
import { is } from '../../../utils/is.js';
@@ -23,6 +24,7 @@ export function migrateServerPort(jsonData: Partial<DatabaseModel>): {
const operatorKey = settings?.operatorKey;
const timeFormat = settings?.timeFormat;
const language = settings?.language;
const auxTimerNames = sanitiseAuxTimerNames(settings?.auxTimerNames);
const version = '4.5.0';
db.settings = {
version,
@@ -30,6 +32,7 @@ export function migrateServerPort(jsonData: Partial<DatabaseModel>): {
operatorKey,
timeFormat,
language,
auxTimerNames,
app: 'ontime',
} as Settings;
return { db, serverPort: settings?.serverPort };
@@ -184,6 +184,7 @@ describe('v3 to v4', () => {
operatorKey: null,
timeFormat: '24',
language: 'en',
auxTimerNames: ['', '', ''],
};
const newSettings = v3.migrateSettings(oldDb);
expect(newSettings).toEqual(expectSettings);
@@ -714,17 +714,17 @@ describe('processRundown()', () => {
});
describe('rundownMutation.add()', () => {
test('adds an event to an empty rundown', () => {
test('adds an event an empty rundown', () => {
const mockEvent = makeOntimeEvent({ id: 'mock', cue: 'mock' });
const rundown = makeRundown({});
rundownMutation.add(rundown, mockEvent, null, null, null);
rundownMutation.add(rundown, mockEvent, null, null);
expect(rundown.order.length).toBe(1);
expect(rundown.entries['mock']).toMatchObject(mockEvent);
});
test('adds an event at the end if no afterId is given', () => {
test('adds an event at the top 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, null);
rundownMutation.add(rundown, mockEvent, null, null);
expect(rundown.order).toStrictEqual(['1', 'mock']);
expect(rundown.flatOrder).toStrictEqual(['1', 'mock']);
expect(rundown.order).toStrictEqual(['mock', '1']);
expect(rundown.flatOrder).toStrictEqual(['mock', '1']);
expect(rundown.entries['mock']).toMatchObject(mockEvent);
});
test('adds an event at the end of the group if parent is provided but no after', () => {
test('adds an event at the top of the group if no after is given', () => {
const mockEvent = makeOntimeEvent({ id: 'mock', cue: 'mock' });
const rundown = makeRundown({
flatOrder: ['1', '1a'],
order: ['1'],
entries: {
'1': makeOntimeGroup({ id: '1', entries: ['1a'] }),
'1': makeOntimeGroup({ id: '1' }),
'1a': makeOntimeEvent({ id: '1a', parent: '1' }),
},
});
rundownMutation.add(rundown, mockEvent, rundown.entries['1'] as OntimeGroup, null, null);
rundownMutation.add(rundown, mockEvent, null, rundown.entries['1'] as OntimeGroup);
expect(rundown.order).toStrictEqual(['1']);
expect(rundown.flatOrder).toStrictEqual(['1', '1a', 'mock']);
expect(rundown.flatOrder).toStrictEqual(['1', 'mock', '1a']);
expect(rundown.entries['mock']).toMatchObject(mockEvent);
});
@@ -765,12 +765,12 @@ describe('rundownMutation.add()', () => {
flatOrder: ['1', '1a'],
order: ['1'],
entries: {
'1': makeOntimeGroup({ id: '1', entries: ['1a'] }),
'1': makeOntimeGroup({ id: '1' }),
'1a': makeOntimeEvent({ id: '1a', parent: '1' }),
},
});
rundownMutation.add(rundown, mockEvent, rundown.entries['1'] as OntimeGroup, '1a', null);
rundownMutation.add(rundown, mockEvent, '1a', rundown.entries['1'] as OntimeGroup);
expect(rundown.order).toStrictEqual(['1']);
expect(rundown.flatOrder).toStrictEqual(['1', '1a', 'mock']);
@@ -1839,49 +1839,6 @@ 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()', () => {
@@ -1,40 +0,0 @@
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',
);
});
});
+43 -41
View File
@@ -439,27 +439,21 @@ function clone(rundown: Rundown, entry: OntimeEntry, options?: InsertOptions): O
rundown.entries[nestedEntry.id] = nestedEntry;
}
const position: { after: EntryId | null; before: EntryId | null } = (() => {
if (options?.after === undefined && options?.before === undefined) {
return { after: entry.id, before: null };
// 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 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);
@@ -467,33 +461,41 @@ 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;
})();
const referenceEntry = referenceId ? rundown.entries[referenceId] : entry;
const parentId = referenceEntry && !isOntimeGroup(referenceEntry) ? referenceEntry.parent : null;
if (parentId === null) return null;
let parent: OntimeGroup | null = null;
const maybeParent = rundown.entries[parentId];
return isOntimeGroup(maybeParent) ? maybeParent : null;
})();
// trying to insert relatively to another entry, check that entries parent
const referenceId = options?.after ?? options?.before;
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 };
/**
* 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;
}
}
}
} else if (entry.parent) {
const maybeParent = rundown.entries[entry.parent];
if (maybeParent && isOntimeGroup(maybeParent)) {
parent = maybeParent;
}
}
const after = getInsertAfterId(rundown, parent, options.after, options.before);
const before = options?.before === true ? after : (options.before ?? null);
return { after, before };
})();
// 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;
}
return addToRundown(rundown, clonedEntry, parent, position.after, position.before);
return addToRundown(rundown, clonedEntry, after, parent);
}
}
@@ -40,15 +40,11 @@ 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
@@ -56,8 +52,6 @@ import { assertInsertAnchorExists, assertInsertAnchorInOrder, assertSingleInsert
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`);
@@ -74,29 +68,14 @@ 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 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) };
})();
const afterId = getInsertAfterId(rundown, parent, eventData?.after, eventData?.before);
// generate a fully formed entry from the patch
const newEntry = generateEvent(rundown, eventData, insertPosition.cueAfterId, parent?.id);
const newEntry = generateEvent(rundown, eventData, afterId, parent?.id);
// make mutations to rundown
rundownMutation.add(rundown, newEntry, parent, insertPosition.afterId, insertPosition.beforeId);
rundownMutation.add(rundown, newEntry, afterId, parent);
const { rundown: responseRundown, rundownMetadata, revision } = await commit();
@@ -416,10 +395,7 @@ 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,50 +70,6 @@ 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,5 +1,4 @@
import { body, param } from 'express-validator';
import type { EntryId, InsertOptions, OntimeGroup, Rundown } from 'ontime-types';
import { requestValidationFunction } from '../validation-utils/validationFunction.js';
@@ -38,27 +37,15 @@ export const rundownImportValidator = [
export const entryPostValidator = [
body('type').isString().isIn(['event', 'delay', 'group', 'milestone']),
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.'),
body('after').optional().isString(),
body('before').optional().isString(),
requestValidationFunction,
];
export const clonePostValidator = [
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.'),
body('after').optional().isString(),
body('before').optional().isString(),
requestValidationFunction,
];
@@ -106,44 +93,4 @@ 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 =======================
@@ -16,6 +16,36 @@ describe('parseSettings()', () => {
operatorKey: null,
timeFormat: '24',
language: 'en',
auxTimerNames: ['', '', ''],
});
});
it('carries custom aux timer names through and pads to a length-3 array', () => {
const result = parseSettings({
settings: { version: '1', auxTimerNames: ['Speaker'] } as unknown as Settings,
});
expect(result.auxTimerNames).toStrictEqual(['Speaker', '', '']);
});
it('falls back to defaults when aux timer names are missing or malformed', () => {
const result = parseSettings({
settings: { version: '1', auxTimerNames: 'not-an-array' } as unknown as Settings,
});
expect(result.auxTimerNames).toStrictEqual(['', '', '']);
});
it('creates the aux timer names for project files made before the feature existed', () => {
const oldSettings = {
version: '4.5.0',
editorKey: null,
operatorKey: null,
timeFormat: '24',
language: 'en',
};
const result = parseSettings({ settings: oldSettings as Settings });
expect(result.auxTimerNames).toStrictEqual(['', '', '']);
expect(result).toMatchObject({ timeFormat: '24', language: 'en' });
});
});
@@ -1,4 +1,5 @@
import { DatabaseModel, Settings } from 'ontime-types';
import { sanitiseAuxTimerNames } from 'ontime-utils';
import { getPartialProject } from '../../models/dataModel.js';
@@ -22,5 +23,7 @@ export function parseSettings(data: Partial<DatabaseModel>): Settings {
operatorKey: data.settings.operatorKey ?? defaultSettings.operatorKey,
timeFormat: data.settings.timeFormat ?? defaultSettings.timeFormat,
language: data.settings.language ?? defaultSettings.language,
// older project files predate this property
auxTimerNames: sanitiseAuxTimerNames(data.settings.auxTimerNames),
};
}
@@ -9,6 +9,7 @@ import { sendRefetch } from '../../adapters/WebsocketAdapter.js';
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
import { portManager } from '../../classes/port-manager/PortManager.js';
import * as appState from '../../services/app-state-service/AppStateService.js';
import { auxTimerService } from '../../services/aux-timer-service/AuxTimerService.js';
import { validateSettings, validateWelcomeDialog, validateServerPort } from './settings.validation.js';
export const router: Router = express.Router();
@@ -41,6 +42,10 @@ router.post('/', validateSettings, async (req: Request, res: Response<Settings |
if (!deepEqual(data, settings)) {
await getDataProvider().setSettings(data);
// keep the runtime aux timers in sync so consumers get the new names live
if (!deepEqual(data.auxTimerNames, settings.auxTimerNames)) {
auxTimerService.loadNames(data.auxTimerNames);
}
sendRefetch(RefetchKey.Settings);
}
@@ -1,4 +1,5 @@
import { body } from 'express-validator';
import { sanitiseAuxTimerNames } from 'ontime-utils';
import { requestValidationFunction } from '../validation-utils/validationFunction.js';
@@ -27,6 +28,7 @@ export const validateSettings = [
pinValidator('operatorKey'),
body('timeFormat').isString().isIn(['12', '24']).withMessage('Time format can only be "12" or "24"'),
body('language').isString().trim().notEmpty(),
body('auxTimerNames').isArray().withMessage('auxTimerNames must be an array').customSanitizer(sanitiseAuxTimerNames),
requestValidationFunction,
];
@@ -153,41 +153,6 @@ 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({
+2 -2
View File
@@ -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 avoid duplicating existing entries.
2. Call ontime_get_rundown with the chosen \`rundownId\` to see current state and identify an \`after\` anchor if appending.
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. 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.
5. If the rundown already has events, pass \`after: <last event id>\` on the batch call so new events chain from the end.
Entry type guidance:
- Use \`event\` for anything with a scheduled time and duration (talks, panels, breaks, meals).
+13 -29
View File
@@ -63,11 +63,6 @@ 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();
@@ -138,24 +133,20 @@ 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, ...insertOptions };
return { type: SupportedEntry.Delay, duration: args.duration, after, before };
case SupportedEntry.Milestone: {
const { cue, title, note, colour, custom } = args;
return { type: SupportedEntry.Milestone, cue, title, note, colour, custom, ...insertOptions };
return { type: SupportedEntry.Milestone, cue, title, note, colour, custom, after, before };
}
case SupportedEntry.Group:
// group creation currently only accepts a title, see generateEvent in rundown.utils.ts
return { type: SupportedEntry.Group, title: args.title, ...insertOptions };
return { type: SupportedEntry.Group, title: args.title, after, before };
case SupportedEntry.Event: {
const { type: _type, rundownId: _rundownId, after: _after, before: _before, ...eventFields } = args;
return { type: SupportedEntry.Event, ...eventFields, ...insertOptions };
const { type: _type, rundownId: _rundownId, ...eventFields } = args;
return { type: SupportedEntry.Event, ...eventFields };
}
default:
throw new Error(`Invalid entry type: ${String(type)}`);
@@ -268,25 +259,20 @@ export async function ungroupEntryForMcp(args: UngroupEntryArgs) {
return { target: getTargetMeta(rundownId), ungrouped: args.id, order: updatedRundown.order };
}
export async function batchCreateEntriesForMcp(args: BatchCreateEntriesArgs) {
const { entries = [], after, before } = args;
export async function batchCreateEntriesForMcp(
args: TargetRundownArgs & { entries: BatchCreateEntryArgs[]; after?: EntryId },
) {
const { entries = [], after } = args;
validateBatchCreateEntries(entries);
const allEntries = flattenBatchCreateEntries(entries);
assertKnownCustomFields(...allEntries.map((entry) => entry.custom));
const rundownId = resolveTargetRundownId(args);
let previousId: EntryId | undefined;
let previousId = after;
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, undefined, firstInsertOptions);
const entry = await createBatchEntry(rundownId, entryArgs, previousId);
created.push(...entry.created);
previousId = entry.entry.id;
}
@@ -317,7 +303,6 @@ 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.');
@@ -326,9 +311,8 @@ async function createBatchEntry(
const { children: _children, ...createArgs } = entryArgs;
const payload = toEntryPayload(createArgs);
const insertOptions = {
...(previousId !== undefined ? { after: previousId } : {}),
...(parentId !== undefined ? { parent: parentId } : {}),
...(previousId === undefined ? firstInsertOptions : {}),
...(previousId ? { after: previousId } : {}),
...(parentId ? { parent: parentId } : {}),
};
const createdEntry = await addEntry(rundownId, { ...payload, ...insertOptions } as EventPostPayload);
+6 -25
View File
@@ -96,7 +96,7 @@ export const TOOL_DEFINITIONS = [
{
name: 'ontime_create_entry',
description:
'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.',
'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.',
inputSchema: {
type: 'object',
properties: {
@@ -114,14 +114,8 @@ 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', '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',
},
after: { type: 'string', description: 'Insert after this entry ID' },
before: { type: 'string', description: 'Insert before this entry ID' },
...EVENT_WRITABLE_FIELDS,
},
},
@@ -224,20 +218,13 @@ 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; 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.',
'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.',
inputSchema: {
type: 'object',
required: ['entries'],
properties: {
...RUNDOWN_TARGET_FIELD,
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',
},
after: { type: 'string', description: 'Insert the first entry after this entry ID' },
entries: {
type: 'array',
description: 'Array of entries to create, in desired order',
@@ -601,13 +588,7 @@ 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 | true;
before?: EntryId | true;
},
),
await batchCreateEntriesForMcp(args as TargetRundownArgs & { entries: BatchCreateEntryArgs[]; after?: EntryId }),
);
},
+9
View File
@@ -5,6 +5,7 @@ import cookieParser from 'cookie-parser';
import cors from 'cors';
import express from 'express';
import { LogOrigin, SimpleDirection, SimplePlayback, runtimeStorePlaceholder } from 'ontime-types';
import { sanitiseAuxTimerNames } from 'ontime-utils';
import serverTiming from 'server-timing';
import { oscServer } from './adapters/OscAdapter.js';
@@ -26,6 +27,7 @@ import { bodyParser } from './middleware/bodyParser.js';
import { compressedStatic } from './middleware/staticGZip.js';
import { ONTIME_VERSION } from './ONTIME_VERSION.js';
import { getShowWelcomeDialog } from './services/app-state-service/AppStateService.js';
import { auxTimerService } from './services/aux-timer-service/AuxTimerService.js';
import * as messageService from './services/message-service/message.service.js';
import { initialiseProject } from './services/project-service/ProjectService.js';
import { restoreService } from './services/restore-service/restore.service.js';
@@ -204,6 +206,7 @@ export const startServer = async (): Promise<{ message: string; serverPort: numb
* Module initialises the services and provides initial payload for the store
*/
const state = getState();
const [auxName1, auxName2, auxName3] = sanitiseAuxTimerNames(getDataProvider().getSettings().auxTimerNames);
eventStore.init({
clock: state.clock,
timer: state.timer,
@@ -219,22 +222,28 @@ export const startServer = async (): Promise<{ message: string; serverPort: numb
current: timerConfig.auxTimerDefault,
playback: SimplePlayback.Stop,
direction: SimpleDirection.CountDown,
name: auxName1,
},
auxtimer2: {
duration: timerConfig.auxTimerDefault,
current: timerConfig.auxTimerDefault,
playback: SimplePlayback.Stop,
direction: SimpleDirection.CountDown,
name: auxName2,
},
auxtimer3: {
duration: timerConfig.auxTimerDefault,
current: timerConfig.auxTimerDefault,
playback: SimplePlayback.Stop,
direction: SimpleDirection.CountDown,
name: auxName3,
},
ping: 1,
});
// AuxTimerService owns its own SimpleTimer instances, so the store above doesn't update them
auxTimerService.loadNames(getDataProvider().getSettings().auxTimerNames);
// initialise message service
messageService.init(eventStore.set, eventStore.get);
@@ -81,6 +81,7 @@ describe('safeMerge', () => {
editorKey: null,
timeFormat: baseDb.settings.timeFormat,
language: 'pt',
auxTimerNames: baseDb.settings.auxTimerNames,
});
});
@@ -6,6 +6,7 @@ export class SimpleTimer {
current: 0,
playback: SimplePlayback.Stop,
direction: SimpleDirection.CountDown,
name: '',
};
private startedAt: number | null = null;
private pausedAt: number | null = null;
@@ -23,9 +24,16 @@ export class SimpleTimer {
current: 0,
playback: SimplePlayback.Stop,
direction: SimpleDirection.CountDown,
// the name is a persisted configuration, independent of the timer runtime
name: this.state.name,
};
}
public setName(name: string): SimpleTimerState {
this.state.name = name;
return this.state;
}
/**
* Sets the duration of the timer
* @param time - time in milliseconds
@@ -16,6 +16,7 @@ describe('SimpleTimer count-down', () => {
current: initialTime,
direction: SimpleDirection.CountDown,
playback: SimplePlayback.Stop,
name: '',
};
expect(newState).toStrictEqual(expected);
});
@@ -27,6 +28,7 @@ describe('SimpleTimer count-down', () => {
current: initialTime,
direction: SimpleDirection.CountDown,
playback: SimplePlayback.Start,
name: '',
};
expect(newState).toStrictEqual(expected);
});
@@ -38,6 +40,7 @@ describe('SimpleTimer count-down', () => {
current: initialTime - 100,
direction: SimpleDirection.CountDown,
playback: SimplePlayback.Start,
name: '',
};
expect(newState).toStrictEqual(expected);
@@ -58,6 +61,7 @@ describe('SimpleTimer count-down', () => {
current: initialTime - 1500,
direction: SimpleDirection.CountDown,
playback: SimplePlayback.Pause,
name: '',
};
expect(newState).toStrictEqual(expected);
@@ -83,6 +87,7 @@ describe('SimpleTimer count-down', () => {
current: initialTime,
direction: SimpleDirection.CountDown,
playback: SimplePlayback.Stop,
name: '',
};
expect(newState).toStrictEqual(expected);
});
@@ -97,6 +102,7 @@ describe('SimpleTimer count-down', () => {
current: initialTime,
direction: SimpleDirection.CountUp,
playback: SimplePlayback.Start,
name: '',
};
newState = timer.update(100);
@@ -127,6 +133,7 @@ describe('SimpleTimer count-down', () => {
current: 1000,
direction: SimpleDirection.CountUp,
playback: SimplePlayback.Start,
name: '',
});
newState = timer.update(100);
@@ -135,6 +142,7 @@ describe('SimpleTimer count-down', () => {
current: initialTime + 100,
direction: SimpleDirection.CountUp,
playback: SimplePlayback.Start,
name: '',
});
newState = timer.update(500);
@@ -143,6 +151,7 @@ describe('SimpleTimer count-down', () => {
current: 1500,
direction: SimpleDirection.CountUp,
playback: SimplePlayback.Start,
name: '',
});
newState = timer.setDirection(SimpleDirection.CountDown, 600);
@@ -151,6 +160,7 @@ describe('SimpleTimer count-down', () => {
current: 1500,
direction: SimpleDirection.CountDown,
playback: SimplePlayback.Start,
name: '',
});
newState = timer.update(700);
@@ -159,6 +169,7 @@ describe('SimpleTimer count-down', () => {
current: 1400,
direction: SimpleDirection.CountDown,
playback: SimplePlayback.Start,
name: '',
});
newState = timer.setDirection(SimpleDirection.CountUp, 700);
@@ -167,6 +178,7 @@ describe('SimpleTimer count-down', () => {
current: 1400,
direction: SimpleDirection.CountUp,
playback: SimplePlayback.Start,
name: '',
});
newState = timer.update(800);
@@ -175,6 +187,7 @@ describe('SimpleTimer count-down', () => {
current: 1500,
direction: SimpleDirection.CountUp,
playback: SimplePlayback.Start,
name: '',
});
});
+1
View File
@@ -30,6 +30,7 @@ const dbModel: DatabaseModel = {
operatorKey: null,
timeFormat: '24',
language: 'en',
auxTimerNames: ['', '', ''],
},
viewSettings: {
overrideStyles: false,
+1
View File
@@ -29,6 +29,7 @@ export const demoDb: DatabaseModel = {
operatorKey: null,
timeFormat: '24',
language: 'en',
auxTimerNames: ['', '', ''],
},
viewSettings: {
dangerColor: '#ff7300',
@@ -1126,7 +1126,7 @@ describe('getRuntimeOffset()', () => {
} as RuntimeState;
const { absolute } = getRuntimeOffset(state);
expect(absolute).toBe(400000 - 200000); // <--- offset is always the overtime + added time
expect(absolute).toBe(400000); // <--- offset is always the overtime
});
it('handles time-to-end started after the end time', () => {
@@ -1,4 +1,5 @@
import { RuntimeStore, SimpleDirection, SimplePlayback } from 'ontime-types';
import { sanitiseAuxTimerNames } from 'ontime-utils';
import { SimpleTimer } from '../../classes/simple-timer/SimpleTimer.js';
import { timerConfig } from '../../setup/config.js';
@@ -24,6 +25,20 @@ export class AuxTimerService {
this.getTime = getTime;
}
/**
* Called at bootstrap and whenever the loaded project's settings change,
* so the running timers reflect the current project's aux timer names.
*/
loadNames(names?: string[]) {
const [name1, name2, name3] = sanitiseAuxTimerNames(names);
const patch: AuxTimerStateUpdate = {
auxtimer1: this.aux1.setName(name1),
auxtimer2: this.aux2.setName(name2),
auxtimer3: this.aux3.setName(name3),
};
this.emit(patch);
}
/**
* Whether any of the aux timers are currently running
*/
@@ -0,0 +1,53 @@
import { RuntimeStore } from 'ontime-types';
import { AuxTimerService } from '../AuxTimerService.js';
describe('AuxTimerService', () => {
describe('loadNames()', () => {
it('applies the names to each aux timer and broadcasts them', () => {
const emit = vi.fn();
const service = new AuxTimerService(emit, () => 0);
service.loadNames(['Speaker', 'Break', 'Q&A']);
const patch = emit.mock.calls.at(-1)?.[0] as Partial<RuntimeStore>;
expect(patch.auxtimer1?.name).toBe('Speaker');
expect(patch.auxtimer2?.name).toBe('Break');
expect(patch.auxtimer3?.name).toBe('Q&A');
});
it('defaults missing names to an empty string', () => {
const emit = vi.fn();
const service = new AuxTimerService(emit, () => 0);
service.loadNames(['only-one']);
const patch = emit.mock.calls.at(-1)?.[0] as Partial<RuntimeStore>;
expect(patch.auxtimer1?.name).toBe('only-one');
expect(patch.auxtimer2?.name).toBe('');
expect(patch.auxtimer3?.name).toBe('');
});
it('handles names missing from a project file', () => {
const emit = vi.fn();
const service = new AuxTimerService(emit, () => 0);
expect(() => service.loadNames(undefined)).not.toThrow();
const patch = emit.mock.calls.at(-1)?.[0] as Partial<RuntimeStore>;
expect(patch.auxtimer1?.name).toBe('');
expect(patch.auxtimer2?.name).toBe('');
expect(patch.auxtimer3?.name).toBe('');
});
it('keeps the name on the timer through subsequent commands', () => {
const emit = vi.fn();
const service = new AuxTimerService(emit, () => 0);
service.loadNames(['Speaker', '', '']);
const started = service.start(1);
expect(started.name).toBe('Speaker');
});
});
});
@@ -1,9 +1,10 @@
import { copyFile } from 'fs/promises';
import { join } from 'path';
import { DatabaseModel, LogOrigin, ProjectFileListResponse } from 'ontime-types';
import { DatabaseModel, LogOrigin, ProjectFileListResponse, RefetchKey } from 'ontime-types';
import { getErrorMessage, getFirstRundown } from 'ontime-utils';
import { sendRefetch } from '../../adapters/WebsocketAdapter.js';
import { parseCustomFields } from '../../api-data/custom-fields/customFields.parser.js';
import { parseDatabaseModel } from '../../api-data/db/db.parser.js';
import { getCurrentRundown } from '../../api-data/rundown/rundown.dao.js';
@@ -28,6 +29,7 @@ import {
removeFileExtension,
} from '../../utils/fileManagement.js';
import { getLastLoaded, isLastLoadedProject, setLastLoaded } from '../app-state-service/AppStateService.js';
import { auxTimerService } from '../aux-timer-service/AuxTimerService.js';
import { runtimeService } from '../runtime-service/runtime.service.js';
import {
doesProjectExist,
@@ -88,12 +90,16 @@ async function loadProject(projectData: DatabaseModel, fileName: string, rundown
// stop the runtime service
runtimeService.stop();
// AuxTimerService holds its own state, independent of the loaded project, so it needs to be updated explicitly
auxTimerService.loadNames(projectData.settings.auxTimerNames);
// load the rundown given by key otherwise load the first in the project
const rundown =
rundownId && rundownId in projectData.rundowns
? projectData.rundowns[rundownId]
: getFirstRundown(projectData.rundowns);
// initialising the rundown with reload sends a refetch to the clients
await initRundown(rundown, projectData.customFields, true);
// persist the project selection
@@ -346,6 +352,12 @@ export async function patchCurrentProject(data: Partial<DatabaseModel>) {
// we can pass some stuff straight to the data provider
await getDataProvider().mergeIntoData(rest);
// AuxTimerService holds its own state, so a settings patch needs to be applied to it explicitly
if (rest.settings) {
auxTimerService.loadNames(getDataProvider().getSettings().auxTimerNames);
sendRefetch(RefetchKey.Settings);
}
// the rundown depends on custom fields
// so custom fields needs to be checked first
if (customFields) {
+3 -3
View File
@@ -180,13 +180,13 @@ export function getRuntimeOffset(state: RuntimeState): { absolute: number; relat
const pausedTime = state._timer.pausedAt === null ? 0 : clock - state._timer.pausedAt;
// absolute offset is difference between schedule and playback time
// in case of count to end, the absolute offset is overtime and added time
const absolute = countToEnd ? overtime + addedTime : eventStartOffset + overtime + pausedTime + addedTime;
const absolute = eventStartOffset + overtime + pausedTime + addedTime;
// the relative offset is the same as the absolute but adjusted relative to the actual start time
const relative = absolute + plannedStart - actualStart - _startDayOffset * dayInMs;
return { absolute, relative };
// in case of count to end, the absolute offset is just the overtime
return countToEnd ? { absolute: overtime, relative } : { absolute, relative };
}
/**
@@ -1036,167 +1036,4 @@ describe('loadGroupFlagAndEnd()', () => {
eventNow: rundown.entries[0],
});
});
test('countToEnd entries decouple the link chain for subsequent events', () => {
// Event 0 (loaded): no countToEnd, linkStart=true
// Event 1: countToEnd=true → breaks the link chain
// Event 2: linkStart=true → unlinked (chain broken by event 1)
// Event 3: flag event → also unlinked
const rundown = makeRundown({
entries: {
group: makeOntimeGroup({ id: 'group', entries: ['0', '1', '2'] }),
0: makeOntimeEvent({
id: '0',
parent: 'group',
timeStart: 0,
duration: 3600000,
countToEnd: false,
linkStart: true,
gap: 0,
} as any),
1: makeOntimeEvent({
id: '1',
parent: 'group',
timeStart: 3600000,
duration: 3600000,
countToEnd: true,
linkStart: true,
gap: 0,
} as any),
2: makeOntimeEvent({
id: '2',
parent: 'group',
timeStart: 7200000,
duration: 3600000,
linkStart: true,
gap: 0,
} as any),
3: makeOntimeEvent({
id: '3',
parent: null,
timeStart: 10800000,
duration: 3600000,
linkStart: true,
gap: 0,
} as any),
},
order: ['group', '0', '1', '2', '3'],
});
const state = {
groupNow: null,
eventNow: rundown.entries[0],
rundown: { actualGroupStart: null },
} as RuntimeState;
const metadata = { playableEventOrder: ['0', '1', '2', '3'], flags: ['3'] } as RundownMetadata;
loadGroupFlagAndEnd(rundown, metadata, 0, state);
// _group is the last event in the group (event 2)
// isLinkedToLoaded is false because event 1 (between loaded and group end) has countToEnd=true
// accumulatedGap includes event 1's duration carried forward to event 2
// (the countToEnd duration is applied to the next event, not the countToEnd event itself)
expect(state._group).toMatchObject({
event: rundown.entries[2],
isLinkedToLoaded: false,
accumulatedGap: 3600000,
});
// _flag (event 3): isLinkedToLoaded is false because chain was broken by event 1
// accumulatedGap is still 3600000 because event 2 is not countToEnd,
// so previousWasCountToEnd is null and no further duration is carried forward
expect(state._flag).toMatchObject({
event: rundown.entries[3],
isLinkedToLoaded: false,
accumulatedGap: 3600000,
});
// _end (event 3): also unlinked because the chain was broken at event 1
expect(state._end).toMatchObject({
event: rundown.entries[3],
isLinkedToLoaded: false,
});
});
test('countToEnd in the middle of the chain breaks links for downstream events', () => {
// Event 0 (loaded): no countToEnd, linkStart=true
// Event 1: linkStart=true → linked to loaded
// Event 2: countToEnd=true → breaks the chain (also last in group)
// Event 3: linkStart=true → unlinked (chain broken by event 2)
const rundown = makeRundown({
entries: {
group: makeOntimeGroup({ id: 'group', entries: ['0', '1', '2'] }),
0: makeOntimeEvent({
id: '0',
parent: 'group',
timeStart: 0,
duration: 3600000,
countToEnd: false,
linkStart: true,
gap: 0,
} as any),
1: makeOntimeEvent({
id: '1',
parent: 'group',
timeStart: 3600000,
duration: 3600000,
linkStart: true,
gap: 0,
} as any),
2: makeOntimeEvent({
id: '2',
parent: 'group',
timeStart: 7200000,
duration: 3600000,
countToEnd: true,
linkStart: true,
gap: 0,
} as any),
3: makeOntimeEvent({
id: '3',
parent: null,
timeStart: 10800000,
duration: 3600000,
linkStart: true,
gap: 0,
} as any),
},
order: ['group', '0', '1', '2', '3'],
});
const state = {
groupNow: null,
eventNow: rundown.entries[0],
rundown: { actualGroupStart: null },
} as RuntimeState;
const metadata = { playableEventOrder: ['0', '1', '2', '3'], flags: ['3'] } as RundownMetadata;
loadGroupFlagAndEnd(rundown, metadata, 0, state);
// _group is the last event in the group (event 2)
// isLinkedToLoaded is true because no preceding event had countToEnd
// accumulatedGap is 0 because no preceding event was countToEnd
// (the countToEnd duration is carried forward to the next event, not added to the countToEnd event itself)
expect(state._group).toMatchObject({
event: rundown.entries[2],
isLinkedToLoaded: true,
accumulatedGap: 0,
});
// _flag (event 3): isLinkedToLoaded is false because chain was broken by count-to-end event 2
// accumulatedGap includes event 2's duration carried forward
expect(state._flag).toMatchObject({
event: rundown.entries[3],
isLinkedToLoaded: false,
accumulatedGap: 3600000,
});
// _end (event 3): unlinked because event 2 has countToEnd=true
expect(state._end).toMatchObject({
event: rundown.entries[3],
isLinkedToLoaded: false,
});
});
});
+5 -21
View File
@@ -23,7 +23,6 @@ import {
calculateDuration,
checkIsNow,
dayInMs,
getExpectedEnd,
getExpectedStart,
getLastEventNormal,
isPlaybackActive,
@@ -832,6 +831,7 @@ function getExpectedTimes(state = runtimeState) {
state.offset.expectedRundownEnd = null;
state.offset.expectedGroupEnd = null;
state.offset.expectedFlagStart = null;
state.offset.expectedRundownEnd = null;
const { offset } = state;
const { plannedStart, actualStart } = state.rundown;
@@ -852,7 +852,7 @@ function getExpectedTimes(state = runtimeState) {
plannedStart,
actualStart,
});
state.offset.expectedGroupEnd = getExpectedEnd(lastEvent, lastEventExpectedStart, state.rundown.currentDay!);
state.offset.expectedGroupEnd = lastEventExpectedStart + lastEvent.duration;
}
}
@@ -884,7 +884,7 @@ function getExpectedTimes(state = runtimeState) {
plannedStart,
actualStart,
});
state.offset.expectedRundownEnd = getExpectedEnd(event, expectedStart, state.rundown.currentDay!);
state.offset.expectedRundownEnd = expectedStart + event.duration;
}
}
@@ -927,7 +927,6 @@ export function loadGroupFlagAndEnd(
let accumulatedGap = 0;
let isLinkedToLoaded = true;
let previousWasCountToEnd: Maybe<number> = null;
for (let idx = currentIndex; idx < playableEventOrder.length; idx++) {
const entry = entries[playableEventOrder[idx]];
@@ -935,23 +934,8 @@ export function loadGroupFlagAndEnd(
if (isOntimeEvent(entry)) {
if (idx !== currentIndex) {
// we only accumulate data after the loaded event
if (previousWasCountToEnd !== null) {
/** previous event was countToEnd: add its duration as a positive gap (it "gives back" time downstream)
* and break the link to the loaded event since countToEnd events reset the schedule
*/
accumulatedGap += entry.gap + previousWasCountToEnd;
isLinkedToLoaded = false;
} else {
accumulatedGap += entry.gap;
isLinkedToLoaded = isLinkedToLoaded && entry.linkStart;
}
if (entry.countToEnd) {
previousWasCountToEnd = entry.duration;
} else {
previousWasCountToEnd = null;
}
accumulatedGap += entry.gap;
isLinkedToLoaded = isLinkedToLoaded && entry.linkStart;
// and the loaded event is not allowed to be the next flag
if (!foundFlag && metadata.flags.includes(entry.id)) {
@@ -4,8 +4,8 @@ import type { MaybeNumber } from '../../utils/utils.type.js';
export type PatchWithId<T extends OntimeEntry = OntimeEntry> = Partial<T> & { id: EntryId };
export type InsertOptions = {
after?: EntryId | true;
before?: EntryId | true;
after?: EntryId;
before?: EntryId;
};
export type EventPostPayload = Partial<OntimeEntry> & InsertOptions;
@@ -6,4 +6,9 @@ export type Settings = {
operatorKey: null | string;
timeFormat: TimeFormat;
language: string;
/**
* Custom names for the aux timers, one entry per aux timer in order (index 0 is aux timer 1).
* An empty string means the timer is unnamed and consumers show the default label
*/
auxTimerNames: string[];
};
@@ -14,4 +14,6 @@ export type SimpleTimerState = {
current: number;
playback: SimplePlayback;
direction: SimpleDirection;
/** Custom name for the aux timer. Empty string when unnamed */
name: string;
};
@@ -53,18 +53,21 @@ export const runtimeStorePlaceholder: Readonly<RuntimeStore> = {
direction: SimpleDirection.CountUp,
duration: 0,
playback: SimplePlayback.Stop,
name: '',
},
auxtimer2: {
current: 0,
direction: SimpleDirection.CountUp,
duration: 0,
playback: SimplePlayback.Stop,
name: '',
},
auxtimer3: {
current: 0,
direction: SimpleDirection.CountUp,
duration: 0,
playback: SimplePlayback.Stop,
name: '',
},
ping: 1,
};
+4 -1
View File
@@ -80,7 +80,7 @@ export { validateEndAction, validateTimerType } from './src/validate-events/vali
// feature business logic
export { getExpectedStart, getExpectedEnd } from './src/date-utils/getExpected.js';
export { getExpectedStart } from './src/date-utils/getExpectedStart.js';
// feature business logic - rundown
export { checkIsNow } from './src/date-utils/checkIsNow.js';
@@ -99,6 +99,9 @@ export {
export { isPlaybackActive } from './src/playback-utils/playbackstate.js';
// aux timers
export { auxTimerNameMaxLength, sanitiseAuxTimerNames } from './src/aux-timer-utils/auxTimerUtils.js';
//Colour
export {
colourToHex,
@@ -0,0 +1,30 @@
import { auxTimerNameMaxLength, sanitiseAuxTimerNames } from './auxTimerUtils.js';
describe('sanitiseAuxTimerNames()', () => {
it('generates the default value when given nothing', () => {
expect(sanitiseAuxTimerNames()).toStrictEqual(['', '', '']);
});
it('always returns exactly three entries', () => {
expect(sanitiseAuxTimerNames(['a', 'b', 'c', 'extra'])).toStrictEqual(['a', 'b', 'c']);
});
it('pads missing entries with an empty string', () => {
expect(sanitiseAuxTimerNames(['Speaker'])).toStrictEqual(['Speaker', '', '']);
});
it('trims whitespace', () => {
expect(sanitiseAuxTimerNames([' Speaker ', '', ''])).toStrictEqual(['Speaker', '', '']);
});
it('caps the name length', () => {
const tooLong = 'a'.repeat(auxTimerNameMaxLength + 10);
expect(sanitiseAuxTimerNames([tooLong])[0]).toHaveLength(auxTimerNameMaxLength);
});
it('falls back to defaults for malformed data', () => {
expect(sanitiseAuxTimerNames('not-an-array')).toStrictEqual(['', '', '']);
expect(sanitiseAuxTimerNames(null)).toStrictEqual(['', '', '']);
expect(sanitiseAuxTimerNames([42, {}, undefined])).toStrictEqual(['', '', '']);
});
});
@@ -0,0 +1,16 @@
/** Maximum length of a user given aux timer name */
export const auxTimerNameMaxLength = 30;
function sanitiseAuxTimerName(value: unknown): string {
return typeof value === 'string' ? value.trim().slice(0, auxTimerNameMaxLength) : '';
}
/**
* Ontime has three aux timers. Given whatever was found on disk or in a request body,
* returns a name for each of them, so callers never need to deal with a missing
* or malformed auxTimerNames (eg. a project file saved before this feature existed).
*/
export function sanitiseAuxTimerNames(names?: unknown): [string, string, string] {
const source = Array.isArray(names) ? names : [];
return [sanitiseAuxTimerName(source[0]), sanitiseAuxTimerName(source[1]), sanitiseAuxTimerName(source[2])];
}
@@ -1,7 +1,7 @@
import { Day, OffsetMode } from 'ontime-types';
import { MILLIS_PER_HOUR, dayInMs } from './conversionUtils';
import { getExpectedEnd, getExpectedStart } from './getExpected';
import { getExpectedStart } from './getExpectedStart';
describe('getExpectedStart()', () => {
describe('Absolute offset mode', () => {
@@ -315,144 +315,3 @@ describe('getExpectedStart()', () => {
expect(getExpectedStart(testEvent, { ...testState, currentDay: 0 })).toBe(23 * MILLIS_PER_HOUR + 5);
});
});
describe('getExpectedEnd()', () => {
const baseState = {
currentDay: 0,
totalGap: 0,
mode: OffsetMode.Absolute,
actualStart: null,
plannedStart: null,
isLinkedToLoaded: true,
};
test('a regular event ends at its expected start plus duration', () => {
const testEvent = {
timeStart: 100,
duration: 50,
delay: 0,
dayOffset: 0 as Day,
countToEnd: false,
};
// on schedule
const expectedStart0 = getExpectedStart(testEvent, { ...baseState, offset: 0 });
expect(getExpectedEnd(testEvent, expectedStart0, baseState.currentDay)).toBe(150);
// running 20 behind pushes the end out
const expectedStart20 = getExpectedStart(testEvent, { ...baseState, offset: 20 });
expect(getExpectedEnd(testEvent, expectedStart20, baseState.currentDay)).toBe(170);
});
test('a countToEnd event pins to the planned end while in overtime', () => {
const testEvent = {
timeStart: 100,
duration: 50,
delay: 0,
dayOffset: 0 as Day,
countToEnd: true,
};
// overtime would otherwise push the end to 170, but countToEnd absorbs it and pins to 150
const expectedStart = getExpectedStart(testEvent, { ...baseState, offset: 20 });
expect(getExpectedEnd(testEvent, expectedStart, baseState.currentDay)).toBe(150);
});
test('an overnight countToEnd event returns a normalised end', () => {
// event starts at 23:00 and counts to 01:00 the next day -> duration spans midnight
const timeStart = 23 * MILLIS_PER_HOUR;
const duration = 2 * MILLIS_PER_HOUR;
const testEvent = {
timeStart,
duration,
delay: 0,
dayOffset: 0 as Day,
countToEnd: true,
};
const expectedStart = getExpectedStart(testEvent, { ...baseState, offset: 0 });
expect(getExpectedEnd(testEvent, expectedStart, baseState.currentDay)).toBe(timeStart + duration);
});
test('a countToEnd event ignores upstream delays and stays pinned to its fixed end', () => {
const testEvent = {
timeStart: 100,
duration: 50,
delay: 20,
dayOffset: 0 as Day,
};
// events shift their schedule based on delay...
const expectedStart = getExpectedStart({ ...testEvent }, { ...baseState, offset: 0 });
expect(getExpectedEnd({ ...testEvent, countToEnd: false }, expectedStart, baseState.currentDay)).toBe(170);
// ... but count to end events stay pinned to the scheduled end
const expectedStartCountToEnd = getExpectedStart({ ...testEvent }, { ...baseState, offset: 0 });
expect(getExpectedEnd({ ...testEvent, countToEnd: true }, expectedStartCountToEnd, baseState.currentDay)).toBe(150);
});
test('a countToEnd event drifts when a delay pushes its start past the fixed end', () => {
const testEvent = {
timeStart: 100,
duration: 50,
delay: 60,
dayOffset: 0 as Day,
countToEnd: true,
};
// the delayed start (160) is past the fixed end (150), so the event can no longer
// finish on time and the end follows the compromised start
const expectedStart = getExpectedStart(testEvent, { ...baseState, offset: 0 });
expect(getExpectedEnd(testEvent, expectedStart, baseState.currentDay)).toBe(160);
});
test('a countToEnd event on a later day keeps the day offset on the end', () => {
const testEvent = {
timeStart: 100,
duration: 50,
delay: 0,
dayOffset: 1 as Day,
countToEnd: true,
};
// the scheduled end must include the day offset (timeStart + dayInMs + duration),
// not collapse to the day-shifted start
const expectedStart = getExpectedStart(testEvent, { ...baseState, currentDay: 0, offset: 0 });
expect(getExpectedEnd(testEvent, expectedStart, baseState.currentDay)).toBe(150 + dayInMs);
// when the running event is already on the same day, no extra day is added
const expectedStartSameDay = getExpectedStart(
{ ...testEvent, dayOffset: 0 as Day },
{ ...baseState, currentDay: 0, offset: 0 },
);
expect(getExpectedEnd({ ...testEvent, dayOffset: 0 as Day }, expectedStartSameDay, baseState.currentDay)).toBe(150);
});
test('a countToEnd event is anchored to its wall-clock end in relative mode', () => {
const testEvent = {
timeStart: 100,
duration: 50,
delay: 0,
dayOffset: 0 as Day,
countToEnd: true,
};
const relativeState = {
...baseState,
mode: OffsetMode.Relative,
actualStart: 30,
plannedStart: 0,
offset: 0,
};
// a regular event in the same state is shifted by the relative-start offset to 180
const expectedStartRegular = getExpectedStart({ ...testEvent }, relativeState);
expect(getExpectedEnd({ ...testEvent, countToEnd: false }, expectedStartRegular, relativeState.currentDay)).toBe(
180,
);
// the countToEnd event stays pinned to its wall-clock end (150), not shifted
const expectedStartCountToEnd = getExpectedStart(testEvent, relativeState);
expect(getExpectedEnd(testEvent, expectedStartCountToEnd, relativeState.currentDay)).toBe(150);
});
});
@@ -3,6 +3,15 @@ import { OffsetMode } from 'ontime-types';
import { dayInMs } from './conversionUtils.js';
/**
* @param event the event that we are counting to
* @param currentDay the day offset of the currently running event
* @param totalGap accumulated gap from the current event
* @param isLinkedToLoaded is this event part of a chain linking back to the current loaded event
* @param clock
* @param offset
* @returns
*/
export function getExpectedStart(
event: Pick<OntimeEvent, 'timeStart' | 'dayOffset' | 'delay'>,
state: {
@@ -51,25 +60,3 @@ export function getExpectedStart(
const offsetStartTimeBufferedByGaps = offsetStartTime - totalGap;
return offsetStartTimeBufferedByGaps;
}
export function getExpectedEnd(
event: Pick<OntimeEvent, 'timeStart' | 'dayOffset' | 'duration' | 'countToEnd'>,
expectedStart: number,
currentRuntimeDay: number,
): number {
/**
* Count to end events are a special case
* - the end time is always the wall clock
*/
if (event.countToEnd) {
// account for day offset
const relativeDayOffset = event.dayOffset - currentRuntimeDay;
const plannedEnd = event.timeStart + event.duration + relativeDayOffset * dayInMs;
// count to end should finish on the planned time or on start
return Math.max(expectedStart, plannedEnd);
}
// for normal events, the expected end is when we would start + its duration
return expectedStart + event.duration;
}
@@ -342,6 +342,7 @@ export const demoDb: DatabaseModel = {
operatorKey: null,
timeFormat: '24',
language: 'en',
auxTimerNames: ['', '', ''],
},
viewSettings: {
dangerColor: '#ff7300',
@@ -248,30 +248,28 @@ describe('getInsertAfterId()', () => {
revision: 1,
} as Rundown;
it('returns the provided after id', () => {
it('returns afterId if provided', () => {
expect(getInsertAfterId(rundown, null, 'b')).toBe('b');
});
it('returns null if no anchors are provided', () => {
it('returns null if neither afterId nor beforeId is provided', () => {
expect(getInsertAfterId(rundown, null)).toBeNull();
});
it('returns null if after is true', () => {
expect(getInsertAfterId(rundown, null, true)).toBeNull();
it('returns null if beforeId is not found', () => {
expect(getInsertAfterId(rundown, null, undefined, 'z')).toBeNull();
expect(getInsertAfterId(rundown, null, undefined, '1')).toBeNull();
});
it('returns the before id if provided', () => {
expect(getInsertAfterId(rundown, null, undefined, '2')).toBe('2');
expect(getInsertAfterId(rundown, null, undefined, '4')).toBe('4');
expect(getInsertAfterId(rundown, null, undefined, 'group')).toBe('group');
it('returns the previous id of an entry in the rundown', () => {
expect(getInsertAfterId(rundown, null, undefined, '2')).toBe('1');
expect(getInsertAfterId(rundown, null, undefined, '4')).toBe('group');
expect(getInsertAfterId(rundown, null, undefined, 'group')).toBe('2');
});
it('returns the first top-level id if before is true', () => {
expect(getInsertAfterId(rundown, null, undefined, true)).toBe('1');
});
it('returns the first group entry if before is true inside a group', () => {
expect(getInsertAfterId(rundown, rundown.entries.group as OntimeGroup, undefined, true)).toBe('31');
it('returns the previous id of an event in a group', () => {
expect(getInsertAfterId(rundown, rundown.entries.group as OntimeGroup, undefined, '31')).toBeNull();
expect(getInsertAfterId(rundown, rundown.entries.group as OntimeGroup, undefined, '32')).toBe('31');
});
});
@@ -333,22 +331,22 @@ describe('addToRundown()', () => {
const rundown = { id: 'test', title: '', entries: {}, order: [], flatOrder: [], revision: 0 } as Rundown;
const newEntry = { id: 'new', type: SupportedEntry.Event } as OntimeEvent;
addToRundown(rundown, newEntry, null, null, null);
addToRundown(rundown, newEntry, null, null);
expect(rundown.order).toEqual(['new']);
expect(rundown.flatOrder).toEqual(['new']);
expect(rundown.entries['new']).toBe(newEntry);
});
// case 2c: insert at the end of the rundown
it('adds at the end of order and flatOrder when afterId is null', () => {
// case 2b: insert at the beginning of the rundown
it('adds at the beginning of order and flatOrder when afterId is null', () => {
const rundown = makeTestRundown();
const newEntry = { id: 'new', type: SupportedEntry.Event } as OntimeEvent;
addToRundown(rundown, newEntry, null, null, null);
addToRundown(rundown, newEntry, null, null);
expect(rundown.order).toEqual(['1', '2', 'group', 'new']);
expect(rundown.flatOrder).toEqual(['1', '2', 'group', '31', '32', 'new']);
expect(rundown.order).toEqual(['new', '1', '2', 'group']);
expect(rundown.flatOrder).toEqual(['new', '1', '2', 'group', '31', '32']);
});
// case 2a: insert after a given entry at top level
@@ -356,55 +354,19 @@ describe('addToRundown()', () => {
const rundown = makeTestRundown();
const newEntry = { id: 'new', type: SupportedEntry.Event } as OntimeEvent;
addToRundown(rundown, newEntry, null, '1', null);
addToRundown(rundown, newEntry, '1', null);
expect(rundown.order).toEqual(['1', 'new', '2', 'group']);
expect(rundown.flatOrder).toEqual(['1', 'new', '2', 'group', '31', '32']);
});
it('prepends to the rundown when before is true', () => {
const rundown = makeTestRundown();
const newEntry = { id: 'new', type: SupportedEntry.Event } as OntimeEvent;
const afterId = getInsertAfterId(rundown, null, undefined, true);
addToRundown(rundown, newEntry, null, afterId, afterId);
expect(rundown.order).toEqual(['new', '1', '2', 'group']);
expect(rundown.flatOrder).toEqual(['new', '1', '2', 'group', '31', '32']);
});
it('inserts after a top-level group and its children in flatOrder', () => {
const rundown = makeTestRundown();
const newEntry = { id: 'new', type: SupportedEntry.Event } as OntimeEvent;
addToRundown(rundown, newEntry, null, 'group', null);
expect(rundown.order).toEqual(['1', '2', 'group', 'new']);
expect(rundown.flatOrder).toEqual(['1', '2', 'group', '31', '32', 'new']);
});
// case 1c: insert at the end of a group
it('inserts at the end of a group and sets parent', () => {
// case 1b: insert at the beginning of a group
it('inserts right after the group header in flatOrder and sets parent', () => {
const rundown = makeTestRundown();
const parent = rundown.entries['group'] as OntimeGroup;
const newEntry = { id: 'new', type: SupportedEntry.Event, parent: null } as OntimeEvent;
addToRundown(rundown, newEntry, parent, null, null);
expect(parent.entries).toEqual(['31', '32', 'new']);
expect(newEntry.parent).toBe('group');
expect(rundown.flatOrder).toEqual(['1', '2', 'group', '31', '32', 'new']);
// top-level order must not change when inserting into a group
expect(rundown.order).toEqual(['1', '2', 'group']);
});
it('prepends to a group when before is true', () => {
const rundown = makeTestRundown();
const parent = rundown.entries['group'] as OntimeGroup;
const newEntry = { id: 'new', type: SupportedEntry.Event, parent: null } as OntimeEvent;
const afterId = getInsertAfterId(rundown, parent, undefined, true);
addToRundown(rundown, newEntry, parent, afterId, afterId);
addToRundown(rundown, newEntry, null, parent);
expect(parent.entries).toEqual(['new', '31', '32']);
expect(newEntry.parent).toBe('group');
@@ -419,7 +381,7 @@ describe('addToRundown()', () => {
const parent = rundown.entries['group'] as OntimeGroup;
const newEntry = { id: 'new', type: SupportedEntry.Event, parent: null } as OntimeEvent;
addToRundown(rundown, newEntry, parent, '31', null);
addToRundown(rundown, newEntry, '31', parent);
expect(parent.entries).toEqual(['31', 'new', '32']);
expect(newEntry.parent).toBe('group');
@@ -361,26 +361,31 @@ export function getNextGroupNormal(
return { entry: null, index: null };
}
/**
* Receives an insertion order and returns the reference to an entry ID
* after which we will insert the new entry
*/
export function getInsertAfterId(
rundown: Rundown,
parent: OntimeGroup | null,
afterId?: EntryId | true,
beforeId?: EntryId | true,
afterId?: EntryId,
beforeId?: EntryId,
): EntryId | null {
if (beforeId) {
const insertionList = parent ? parent.entries : rundown.order;
return beforeId === true ? (insertionList[0] ?? null) : beforeId;
}
if (afterId) return afterId;
if (!beforeId) return null;
if (afterId) return afterId === true ? null : afterId;
const insertionList = parent ? parent.entries : rundown.order;
if (!insertionList || insertionList.length === 0) return null;
return null;
const atIndex = insertionList.findIndex((id) => id === beforeId);
if (atIndex < 1) return null;
return insertionList[atIndex - 1];
}
type ResolveInsertParentOptions = {
parent?: EntryId | null;
after?: EntryId | true;
before?: EntryId | true;
after?: EntryId;
before?: EntryId;
};
/**
@@ -388,21 +393,15 @@ type ResolveInsertParentOptions = {
* Uses explicit parent first, then infers from sibling references.
*/
export function resolveInsertParent(rundown: Rundown, options: ResolveInsertParentOptions): EntryId | null {
// 1. if we have a parent reference we return that
if (options.parent !== undefined && options.parent !== null) {
if (options.parent) {
return options.parent;
}
// 2. ... otherwise we look for a sibling and get their parent
const referenceId = (() => {
if (typeof options.after === 'string') return options.after;
if (typeof options.before === 'string') return options.before;
return undefined;
})();
if (referenceId === undefined) return null;
const referenceId = options.after ?? options.before;
if (!referenceId) return null;
const maybeSibling = rundown.entries[referenceId];
if (maybeSibling !== undefined && 'parent' in maybeSibling && maybeSibling.parent !== null) {
if (maybeSibling && 'parent' in maybeSibling && maybeSibling.parent) {
return maybeSibling.parent;
}
@@ -411,57 +410,52 @@ export function resolveInsertParent(rundown: Rundown, options: ResolveInsertPare
/**
* Add entry to rundown, mutates the rundown in place.
* if afterId and beforeId are not provided, we add at the end of the rundown
* Handles the following cases:
* - 1a. add entry in group, after a given entry
* - 1b. add entry in group, at the beginning (right after the group header)
* - 2a. add entry to the rundown, after a given entry
* - 2b. add entry to the rundown, at the beginning
*/
export function addToRundown(
rundown: Rundown,
entry: OntimeEntry,
parent: OntimeGroup | null,
afterId: EntryId | null,
beforeId: EntryId | null,
parent: OntimeGroup | null,
): OntimeEntry {
// which list to use, the top level or a group order
const insertionList = parent ? parent.entries : rundown.order;
if (parent) {
// 1. inserting an entry inside a group
// the index inside the list
const insertionIndex = (() => {
if (beforeId) return insertionList.indexOf(beforeId);
if (afterId) return insertionList.indexOf(afterId) + 1;
return insertionList.length;
})();
// the index inside the flat order
const flatIndex = (() => {
if (beforeId) return rundown.flatOrder.indexOf(beforeId);
// assign the parent reference on the entry
if ('parent' in entry) {
entry.parent = parent.id;
}
if (afterId) {
const afterEntry = rundown.entries[afterId];
const flatReferenceId =
!parent && isOntimeGroup(afterEntry) && afterEntry.entries?.length > 0
? afterEntry.entries[afterEntry.entries.length - 1]
: afterId;
return rundown.flatOrder.indexOf(flatReferenceId) + 1;
// 1a. insert after a given entry within the group
const atEventsIndex = parent.entries.indexOf(afterId) + 1;
const atFlatIndex = rundown.flatOrder.indexOf(afterId) + 1;
parent.entries = insertAtIndex(atEventsIndex, entry.id, parent.entries);
rundown.flatOrder = insertAtIndex(atFlatIndex, entry.id, rundown.flatOrder);
} else {
// 1b. insert at the beginning of the group (right after the group header in flatOrder)
parent.entries = insertAtIndex(0, entry.id, parent.entries);
const atFlatIndex = rundown.flatOrder.indexOf(parent.id) + 1;
rundown.flatOrder = insertAtIndex(atFlatIndex, entry.id, rundown.flatOrder);
}
if (parent) {
const previousId = insertionList[insertionIndex - 1] ?? parent.id;
return rundown.flatOrder.indexOf(previousId) + 1;
}
return rundown.flatOrder.length;
})();
if (parent) {
if (isOntimeGroup(entry)) {
throw new Error('Cannot add a group to another group');
}
entry.parent = parent.id;
parent.entries = insertAtIndex(insertionIndex, entry.id, parent.entries);
} else {
rundown.order = insertAtIndex(insertionIndex, entry.id, rundown.order);
// 2. inserting an entry at top level
if (afterId) {
// 2a. insert after a given entry
const atOrderIndex = rundown.order.indexOf(afterId) + 1;
const atFlatIndex = rundown.flatOrder.indexOf(afterId) + 1;
rundown.order = insertAtIndex(atOrderIndex, entry.id, rundown.order);
rundown.flatOrder = insertAtIndex(atFlatIndex, entry.id, rundown.flatOrder);
} else {
// 2b. insert at the beginning
rundown.order = insertAtIndex(0, entry.id, rundown.order);
rundown.flatOrder = insertAtIndex(0, entry.id, rundown.flatOrder);
}
}
rundown.flatOrder = insertAtIndex(flatIndex, entry.id, rundown.flatOrder);
// either way, we register the entry in the entries map
rundown.entries[entry.id] = entry;