Relative mode (#1764)

* feat: add group start time to state

* refactor: calculate expected times when offset mode changes

* feat: show relative data in ui

* fixup! feat: add group start time to state

* fixup! refactor: calculate expected times when offset mode changes

* fixup! feat: show relative data in ui

* try to handle multiday

* show planed/expected rundown end day offset values

* refactor: style tweaks to timers

* refactor: cleanup data use

* day offset

* update tests

* test getExpectedStart multiday

* write start epoch to restore file

* current day in relative mode

* remove todo

* move find day offset to utils

---------

Co-authored-by: arc-alex <ac@omnivox.dk>
This commit is contained in:
Carlos Valente
2025-09-17 11:20:14 +02:00
parent 313590905f
commit 8d2db7ffcd
24 changed files with 364 additions and 79 deletions
@@ -1,7 +1,8 @@
import { dayInMs, millisToString } from 'ontime-utils';
import { dayInMs, MILLIS_PER_HOUR, millisToString } from 'ontime-utils';
import { EndAction, Playback, TimeStrategy, TimerPhase, TimerType } from 'ontime-types';
import {
findDayOffset,
getCurrent,
getExpectedFinish,
getRuntimeOffset,
@@ -726,6 +727,7 @@ describe('getRuntimeOffset()', () => {
eventNow: {
id: '1',
timeStart: 100,
dayOffset: 0,
},
timer: {
startedAt: 150,
@@ -738,7 +740,10 @@ describe('getRuntimeOffset()', () => {
rundown: {
actualStart: 150,
plannedStart: 100,
currentDay: 0,
},
clock: 150,
_startDayOffset: 0,
} as RuntimeState;
const { absolute } = getRuntimeOffset(state);
@@ -750,6 +755,7 @@ describe('getRuntimeOffset()', () => {
eventNow: {
id: '1',
timeStart: 100,
dayOffset: 0,
},
timer: {
startedAt: 150, // we started 50ms delayed
@@ -762,7 +768,9 @@ describe('getRuntimeOffset()', () => {
rundown: {
actualStart: 150,
plannedStart: 100,
currentDay: 0,
},
_startDayOffset: 0,
} as RuntimeState;
const { absolute } = getRuntimeOffset(state);
@@ -775,6 +783,7 @@ describe('getRuntimeOffset()', () => {
id: '1',
timeStart: 100,
timeEnd: 140,
dayOffset: 0,
},
timer: {
startedAt: 100, // we started ontime
@@ -787,7 +796,9 @@ describe('getRuntimeOffset()', () => {
rundown: {
actualStart: 100,
plannedStart: 100,
currentDay: 0,
},
_startDayOffset: 0,
} as RuntimeState;
const { absolute } = getRuntimeOffset(state);
@@ -800,6 +811,7 @@ describe('getRuntimeOffset()', () => {
id: '1',
timeStart: 100,
timeEnd: 150,
dayOffset: 0,
},
clock: 150,
timer: {
@@ -813,7 +825,9 @@ describe('getRuntimeOffset()', () => {
rundown: {
actualStart: 100,
plannedStart: 100,
currentDay: 0,
},
_startDayOffset: 0,
} as RuntimeState;
const { absolute } = getRuntimeOffset(state);
@@ -830,6 +844,7 @@ describe('getRuntimeOffset()', () => {
duration: 3600000,
timeStrategy: 'lock-duration',
linkStart: false,
dayOffset: 0,
},
rundown: {
selectedEventIndex: 0,
@@ -837,6 +852,7 @@ describe('getRuntimeOffset()', () => {
plannedStart: 77400000,
plannedEnd: 84600000,
actualStart: null,
currentDay: 0,
},
offset: {
absolute: -77400000,
@@ -852,6 +868,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: null,
},
_startDayOffset: 0,
_timer: { pausedAt: null },
} as RuntimeState;
@@ -874,6 +891,7 @@ describe('getRuntimeOffset()', () => {
endAction: EndAction.None,
timerType: TimerType.CountDown,
countToEnd: true,
dayOffset: 0,
skip: false,
note: '',
colour: '',
@@ -890,6 +908,7 @@ describe('getRuntimeOffset()', () => {
plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00
actualStart: 78000000, // 21:40:00
currentDay: 0,
},
offset: {
absolute: 0,
@@ -905,6 +924,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: 78000000,
},
_startDayOffset: 0,
_timer: { pausedAt: null },
} as RuntimeState;
@@ -922,6 +942,7 @@ describe('getRuntimeOffset()', () => {
timeStart: 77400000, // 21:30:00
timeEnd: 81000000, // 22:30:00
duration: 3600000, // 01:00:00
dayOffset: 0,
timeStrategy: TimeStrategy.LockEnd,
linkStart: false,
endAction: EndAction.None,
@@ -943,6 +964,7 @@ describe('getRuntimeOffset()', () => {
plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00
actualStart: 78000000, // 21:40:00
currentDay: 0,
},
offset: {
absolute: 0,
@@ -958,6 +980,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: 78000000,
},
_startDayOffset: 0,
_timer: { pausedAt: null },
} as RuntimeState;
@@ -978,6 +1001,7 @@ describe('getRuntimeOffset()', () => {
endAction: EndAction.None,
timerType: TimerType.CountDown,
countToEnd: true,
dayOffset: 0,
},
rundown: {
selectedEventIndex: 0,
@@ -985,6 +1009,7 @@ describe('getRuntimeOffset()', () => {
plannedStart: 77400000, // 21:30:00
plannedEnd: 81000000, // 22:30:00
actualStart: 82000000, // 22:46:40 <--- started now
currentDay: 0,
},
offset: {
absolute: 0,
@@ -1000,6 +1025,7 @@ describe('getRuntimeOffset()', () => {
secondaryTimer: null,
startedAt: 82000000, // <--- started now
},
_startDayOffset: 0,
_timer: { pausedAt: null },
} as RuntimeState;
@@ -1017,6 +1043,7 @@ describe('getRuntimeOffset() relative', () => {
eventNow: {
id: '1',
timeStart: 150,
dayOffset: 0,
},
timer: {
startedAt: 150,
@@ -1029,7 +1056,9 @@ describe('getRuntimeOffset() relative', () => {
rundown: {
actualStart: 150,
plannedStart: 150,
currentDay: 0,
},
_startDayOffset: 0,
} as RuntimeState;
const { absolute, relative } = getRuntimeOffset(state);
@@ -1041,6 +1070,7 @@ describe('getRuntimeOffset() relative', () => {
eventNow: {
id: '1',
timeStart: 100,
dayOffset: 0,
},
timer: {
startedAt: 150,
@@ -1053,7 +1083,9 @@ describe('getRuntimeOffset() relative', () => {
rundown: {
actualStart: 150,
plannedStart: 100,
currentDay: 0,
},
_startDayOffset: 0,
} as RuntimeState;
const { absolute, relative } = getRuntimeOffset(state);
@@ -1065,6 +1097,7 @@ describe('getRuntimeOffset() relative', () => {
eventNow: {
id: '1',
timeStart: 150,
dayOffset: 0,
},
timer: {
startedAt: 100,
@@ -1077,7 +1110,9 @@ describe('getRuntimeOffset() relative', () => {
rundown: {
actualStart: 100,
plannedStart: 150,
currentDay: 0,
},
_startDayOffset: 0,
} as RuntimeState;
const { absolute, relative } = getRuntimeOffset(state);
@@ -1258,3 +1293,21 @@ describe('getTimerPhase()', () => {
expect(phase).toBe(TimerPhase.Pending);
});
});
describe('findDay()', () => {
test('finds dayOffset', () => {
//both have 1 hour offset but the clock are on different days
expect(findDayOffset(0, 23 * MILLIS_PER_HOUR)).toBe(-1); // -> 23
expect(findDayOffset(0, 13 * MILLIS_PER_HOUR)).toBe(-1); // -> 13
expect(findDayOffset(0, 12 * MILLIS_PER_HOUR)).toBe(-1); // -> 12
expect(findDayOffset(0, 11 * MILLIS_PER_HOUR)).toBe(0); // -> 11
expect(findDayOffset(1 * MILLIS_PER_HOUR, 0)).toBe(0); // -> -1
//both have 1 hour offset but the clock are on different days
expect(findDayOffset(23 * MILLIS_PER_HOUR, 0)).toBe(1); // -> -23
expect(findDayOffset(13 * MILLIS_PER_HOUR, 0)).toBe(1); // -> -13
expect(findDayOffset(12 * MILLIS_PER_HOUR, 0)).toBe(0); // -> -12
expect(findDayOffset(11 * MILLIS_PER_HOUR, 0)).toBe(0); // -> -11
expect(findDayOffset(22 * MILLIS_PER_HOUR, 23 * MILLIS_PER_HOUR)).toBe(0); // -> 1
});
});
@@ -12,6 +12,7 @@ describe('isRestorePoint()', () => {
addedTime: 2,
pausedAt: 3,
firstStart: 1,
startEpoch: 1,
};
expect(isRestorePoint(restorePoint)).toBe(true);
@@ -22,6 +23,7 @@ describe('isRestorePoint()', () => {
addedTime: 0,
pausedAt: null,
firstStart: 1,
startEpoch: 1,
};
expect(isRestorePoint(restorePoint)).toBe(true);
});
@@ -35,6 +37,7 @@ describe('isRestorePoint()', () => {
addedTime: 0,
pausedAt: null,
groupStartAt: 10,
startEpoch: 1,
};
expect(isRestorePoint(restorePoint)).toBe(false);
});
@@ -56,6 +59,7 @@ describe('isRestorePoint()', () => {
addedTime: 0,
pausedAt: null,
groupStartAt: 10,
startEpoch: 1,
};
expect(isRestorePoint(restorePoint)).toBe(false);
});
@@ -16,6 +16,7 @@ describe('restoreService', () => {
addedTime: 5678,
pausedAt: 9087,
firstStart: 1234,
startEpoch: 1234,
};
const mockRead = vi.fn().mockResolvedValue(expected);
@@ -33,6 +34,7 @@ describe('restoreService', () => {
addedTime: 0,
pausedAt: null,
firstStart: 1234,
startEpoch: 1234,
};
const mockRead = vi.fn().mockResolvedValue(expected);
@@ -79,6 +81,7 @@ describe('restoreService', () => {
addedTime: 1234,
pausedAt: 1234,
firstStart: 1234,
startEpoch: 1234,
};
const mockWrite = vi.fn().mockResolvedValue(undefined);
@@ -95,6 +98,7 @@ describe('restoreService', () => {
addedTime: 5678,
pausedAt: 5678,
firstStart: 5678,
startEpoch: 5678,
};
const mockWrite = vi.fn().mockRejectedValue(new Error('Write failed'));
@@ -20,6 +20,7 @@ export function isRestorePoint(restorePoint: unknown): restorePoint is RestorePo
'addedTime',
'pausedAt',
'firstStart',
'startEpoch',
])
) {
return false;
@@ -49,5 +50,9 @@ export function isRestorePoint(restorePoint: unknown): restorePoint is RestorePo
return false;
}
if (!is.number(restorePoint.startEpoch) && restorePoint.startEpoch !== null) {
return false;
}
return true;
}
@@ -7,4 +7,5 @@ export type RestorePoint = {
addedTime: number;
pausedAt: MaybeNumber;
firstStart: MaybeNumber;
startEpoch: MaybeNumber;
};
@@ -743,6 +743,7 @@ function broadcastResult(_target: any, _propertyKey: string, descriptor: Propert
addedTime: state.timer.addedTime,
pausedAt: state._timer.pausedAt,
firstStart: state.rundown.actualStart,
startEpoch: state._startEpoch,
})
.catch((_e) => {
//we don't do anything with the error here
+19 -8
View File
@@ -1,5 +1,5 @@
import { MaybeNumber, TimerPhase } from 'ontime-types';
import { dayInMs, isPlaybackActive } from 'ontime-utils';
import { dayInMs, isPlaybackActive, MILLIS_PER_HOUR } from 'ontime-utils';
import type { RuntimeState } from '../stores/runtimeState.js';
/**
@@ -113,14 +113,14 @@ export function skippedOutOfEvent(state: RuntimeState, previousTime: number, ski
* Negative offset is under time / ahead of schedule
*/
export function getRuntimeOffset(state: RuntimeState): { absolute: number; relative: number } {
const { eventNow, clock } = state;
const { eventNow, clock, _startDayOffset } = state;
const { addedTime, current, startedAt } = state.timer;
// nothing to calculate if there are no loaded events or if we havent started
if (eventNow === null || startedAt === null) {
if (eventNow === null || startedAt === null || _startDayOffset === null) {
return { absolute: 0, relative: 0 };
}
const { countToEnd, timeStart } = eventNow;
const { countToEnd, timeStart, dayOffset } = eventNow;
const { plannedStart, actualStart } = state.rundown;
// eslint-disable-next-line no-unused-labels -- dev code path
@@ -131,8 +131,8 @@ export function getRuntimeOffset(state: RuntimeState): { absolute: number; relat
if (actualStart === null) throw new Error('timerUtils.getRuntimeOffset: state.rundown.plannedStart must be set');
}
// difference between planned event start and actual event start (will be positive if we stared behind )
const eventStartOffset = startedAt - timeStart;
// difference between planned event start and actual event start (will be positive if we started behind )
const eventStartOffset = startedAt + _startDayOffset * dayInMs - (timeStart + dayOffset * dayInMs);
// how long has the event been running over (is a negative number when in over timer so inverted before adding to offset)
const overtime = Math.abs(Math.min(current, 0));
@@ -142,8 +142,8 @@ export function getRuntimeOffset(state: RuntimeState): { absolute: number; relat
const absolute = eventStartOffset + overtime + pausedTime + addedTime;
// the relative offset i the same as the absolute offset but adjusted relative to the actual start time
const relative = absolute + plannedStart - actualStart;
// the relative offset is the same as the absolute offset but adjusted relative to the actual start time
const relative = absolute + plannedStart - actualStart - _startDayOffset * dayInMs;
// in case of count to end, the absolute offset is just the overtime
return countToEnd ? { absolute: overtime, relative } : { absolute, relative };
@@ -180,3 +180,14 @@ export function getTimerPhase(state: RuntimeState): TimerPhase {
return TimerPhase.Default;
}
/**
* Finds the day offset relative to an event start
* used byt the runtimeState on first start to get correct offsets
*/
export function findDayOffset(plannedStart: number, clock: number): number {
const distance = clock - plannedStart;
if (distance >= 12 * MILLIS_PER_HOUR) return -1;
if (distance < -12 * MILLIS_PER_HOUR) return 1;
return 0;
}
@@ -14,6 +14,8 @@ const baseState: RuntimeState = {
plannedStart: 0,
plannedEnd: 0,
actualStart: null,
actualGroupStart: null,
currentDay: 0,
},
offset: {
absolute: 0,
@@ -46,6 +48,8 @@ const baseState: RuntimeState = {
_group: null,
_end: null,
_flag: null,
_startDayOffset: null,
_startEpoch: null,
};
export function makeRuntimeStateData(patch?: Partial<RuntimeState>): RuntimeState {
@@ -393,6 +393,7 @@ describe('loadGroupFlagAndEnd()', () => {
const state = {
groupNow: null,
eventNow: rundown.entries[11],
rundown: { actualGroupStart: null },
} as RuntimeState;
const metadata = { playableEventOrder: ['0', '11', '3'], flags: ['1'] } as RundownMetadata;
@@ -420,6 +421,7 @@ describe('loadGroupFlagAndEnd()', () => {
const state = {
groupNow: rundown.entries[1],
eventNow: rundown.entries[22],
rundown: { actualGroupStart: null },
} as RuntimeState;
const metadata = { playableEventOrder: ['0', '11', '22'], flags: ['1'] } as RundownMetadata;
@@ -447,6 +449,7 @@ describe('loadGroupFlagAndEnd()', () => {
const state = {
groupNow: rundown.entries[1],
eventNow: rundown.entries[0],
rundown: { actualGroupStart: null },
} as RuntimeState;
const metadata = { playableEventOrder: ['0', '11', '22'], flags: ['1'] } as RundownMetadata;
@@ -471,6 +474,7 @@ describe('loadGroupFlagAndEnd()', () => {
const state = {
groupNow: null,
eventNow: rundown.entries[0],
rundown: { actualGroupStart: null },
} as RuntimeState;
const metadata = { playableEventOrder: ['0', '1'], flags: ['1'] } as RundownMetadata;
+55 -12
View File
@@ -23,9 +23,15 @@ import {
isPlaybackActive,
} from 'ontime-utils';
import { timeNow } from '../utils/time.js';
import { getTimeObject, timeNow } from '../utils/time.js';
import type { RestorePoint } from '../services/restore-service/restore.type.js';
import { getCurrent, getExpectedFinish, getRuntimeOffset, getTimerPhase } from '../services/timerUtils.js';
import {
findDayOffset,
getCurrent,
getExpectedFinish,
getRuntimeOffset,
getTimerPhase,
} from '../services/timerUtils.js';
import { loadRoll, normaliseRollStart } from '../services/rollUtils.js';
import { timerConfig } from '../setup/config.js';
import { RundownMetadata } from '../api-data/rundown/rundown.types.js';
@@ -55,6 +61,8 @@ export type RuntimeState = {
_group: ExpectedMetadata;
_flag: ExpectedMetadata;
_end: ExpectedMetadata;
_startEpoch: MaybeNumber;
_startDayOffset: MaybeNumber;
};
const runtimeState: RuntimeState = {
@@ -78,6 +86,8 @@ const runtimeState: RuntimeState = {
_group: null,
_flag: null,
_end: null,
_startEpoch: null,
_startDayOffset: null,
};
export function getState(): Readonly<RuntimeState> {
@@ -152,6 +162,10 @@ export function clearState() {
runtimeState._timer.pausedAt = null;
runtimeState._timer.secondaryTarget = null;
runtimeState._timer.hasFinished = false;
runtimeState._startEpoch = null;
runtimeState._startDayOffset = null;
runtimeState.rundown.currentDay = null;
}
/**
@@ -190,7 +204,8 @@ export function updateRundownData(rundownData: {
runtimeState.rundown.plannedStart = rundownData.firstStart;
runtimeState.rundown.plannedEnd =
rundownData.firstStart === null ? null : rundownData.firstStart + rundownData.totalDuration;
getExpectedTimes();
if (isPlaybackActive(runtimeState.timer.playback)) getExpectedTimes();
}
/**
@@ -229,9 +244,14 @@ export function load(
// patch with potential provided data
if (initialData) {
patchTimer(initialData);
const startEpoch = initialData?.startEpoch;
const firstStart = initialData?.firstStart;
if (firstStart === null || typeof firstStart === 'number') {
if (
(firstStart === null || typeof firstStart === 'number') &&
(startEpoch === null || typeof startEpoch === 'number')
) {
runtimeState.rundown.actualStart = firstStart;
runtimeState._startEpoch = startEpoch;
const { absolute, relative } = getRuntimeOffset(runtimeState);
runtimeState.offset.absolute = absolute;
runtimeState.offset.relative = relative;
@@ -367,7 +387,8 @@ export function start(state: RuntimeState = runtimeState): boolean {
return false;
}
state.clock = timeNow();
const [epoch, now] = getTimeObject();
state.clock = now;
state.timer.secondaryTimer = null;
// add paused time if it exists
@@ -386,9 +407,16 @@ export function start(state: RuntimeState = runtimeState): boolean {
state.timer.elapsed = 0;
if (state.rundown.actualStart === null) {
state._startDayOffset = findDayOffset(state.eventNow.timeStart, state.clock);
state.rundown.currentDay = state._startDayOffset;
state._startEpoch = epoch;
state.rundown.actualStart = state.clock;
}
if (state.groupNow !== null && state.rundown.actualGroupStart === null) {
state.rundown.actualGroupStart = state.clock;
}
// update timer phase
runtimeState.timer.phase = getTimerPhase(runtimeState);
@@ -480,13 +508,20 @@ export type UpdateResult = {
export function update(): UpdateResult {
// 0. there are some things we always do
const previousClock = runtimeState.clock;
runtimeState.clock = timeNow(); // we update the clock on every update call
const [epoch, fromMidnight] = getTimeObject();
runtimeState.clock = fromMidnight; // we update the clock on every update call
// 1. is playback idle?
if (!isPlaybackActive(runtimeState.timer.playback)) {
return updateIfIdle();
}
// if we are playing and playback changes. we tick the current runtime day
if (runtimeState._startDayOffset !== null && runtimeState._startEpoch) {
runtimeState.rundown.currentDay =
runtimeState._startDayOffset + Math.floor((epoch - runtimeState._startEpoch) / dayInMs);
}
// 2. are we waiting to roll?
if (runtimeState.timer.playback === Playback.Roll && runtimeState.timer.secondaryTimer !== null) {
const hasCrossedMidnight = previousClock > runtimeState.clock;
@@ -704,7 +739,7 @@ function getExpectedTimes(state = runtimeState) {
if (_group !== null) {
const { event: lastEvent, accumulatedGap, isLinkedToLoaded } = _group;
const lastEventExpectedStart = getExpectedStart(lastEvent, {
currentDay: eventNow.dayOffset,
currentDay: state.rundown.currentDay!,
totalGap: accumulatedGap,
isLinkedToLoaded,
mode: offset.mode,
@@ -721,7 +756,7 @@ function getExpectedTimes(state = runtimeState) {
if (_flag) {
const { event, accumulatedGap, isLinkedToLoaded } = _flag;
const expectedStart = getExpectedStart(event, {
currentDay: eventNow.dayOffset,
currentDay: state.rundown.currentDay!,
totalGap: accumulatedGap,
isLinkedToLoaded,
mode: offset.mode,
@@ -736,7 +771,7 @@ function getExpectedTimes(state = runtimeState) {
if (state._end) {
const { event, accumulatedGap, isLinkedToLoaded } = state._end;
const expectedStart = getExpectedStart(event, {
currentDay: eventNow.dayOffset,
currentDay: state.rundown.currentDay!,
totalGap: accumulatedGap,
isLinkedToLoaded,
mode: offset.mode,
@@ -752,16 +787,19 @@ export function loadGroupFlagAndEnd(
rundown: Rundown,
metadata: RundownMetadata,
currentIndex: MaybeNumber,
state = runtimeState,
state = runtimeState, // used for testing
) {
const previousGroup = state.groupNow?.id;
state.groupNow = null;
state._group = null;
state.eventFlag = null;
state._flag = null;
state._end = null;
if (currentIndex == null) return;
if (state.eventNow === null) return;
if (currentIndex === null || state.eventNow === null) {
state.rundown.actualGroupStart = null;
return;
}
const currentGroupId = state.eventNow.parent;
const flagsPresent = metadata.flags.length !== 0;
@@ -773,6 +811,10 @@ export function loadGroupFlagAndEnd(
state.groupNow = currentGroupId ? (entries[currentGroupId] as OntimeGroup) : null;
const lastEventInGroup = orderInGroup ? getLastEventNormal(rundown.entries, orderInGroup).lastEvent : null;
if (previousGroup !== currentGroupId) {
state.rundown.actualGroupStart = null;
}
// if we don't have a any flags in the rundown then no need to look for it
let foundFlag = !flagsPresent;
// if we don't have a last event for the group there is no need to find its end time
@@ -814,4 +856,5 @@ export function loadGroupFlagAndEnd(
export function setOffsetMode(mode: OffsetMode) {
runtimeState.offset.mode = mode;
if (isPlaybackActive(runtimeState.timer.playback)) getExpectedTimes();
}
+15
View File
@@ -74,3 +74,18 @@ export function timeNow() {
elapsed += now.getMilliseconds();
return elapsed;
}
/**
* Get current time from system
* @returns [number, number] - [epoch time, milliseconds since midnight]
*/
export function getTimeObject(): [number, number] {
const now = new Date();
// extract milliseconds since midnight
let elapsed = now.getHours() * 3600000;
elapsed += now.getMinutes() * 60000;
elapsed += now.getSeconds() * 1000;
elapsed += now.getMilliseconds();
return [now.getTime(), elapsed];
}