mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-27 18:09:10 +00:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a6a4d5d89e | |||
| 1ddfe8a969 |
Binary file not shown.
@@ -195,6 +195,25 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* =================== SOUND PROMPT ===================*/
|
||||
.sound-prompt {
|
||||
position: absolute;
|
||||
bottom: $view-block-padding;
|
||||
left: $view-inline-padding;
|
||||
padding: 0.5em 0.75em;
|
||||
border-radius: $element-border-radius;
|
||||
background-color: $viewer-card-bg-color;
|
||||
color: $viewer-secondary-color;
|
||||
font-size: $timer-label-size;
|
||||
text-transform: uppercase;
|
||||
pointer-events: none;
|
||||
transition: opacity $viewer-transition-time;
|
||||
|
||||
&--hidden {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* =================== LOGO ===================*/
|
||||
.logo {
|
||||
position: absolute;
|
||||
|
||||
@@ -8,6 +8,7 @@ import TitleCard from '../../common/components/title-card/TitleCard';
|
||||
import ViewLogo from '../../common/components/view-logo/ViewLogo';
|
||||
import ViewParamsEditor from '../../common/components/view-params-editor/ViewParamsEditor';
|
||||
import { useAutoTickingClock } from '../../common/hooks/useAutoTickingClock';
|
||||
import { useFadeOutOnInactivity } from '../../common/hooks/useFadeOutOnInactivity';
|
||||
import { useTimerSocket } from '../../common/hooks/useSocket';
|
||||
import { useWindowTitle } from '../../common/hooks/useWindowTitle';
|
||||
import { cx } from '../../common/utils/styleUtils';
|
||||
@@ -30,6 +31,7 @@ import {
|
||||
getTotalTime,
|
||||
} from './timer.utils';
|
||||
import { TimerData, useTimerData } from './useTimerData';
|
||||
import { useTimerSound } from './useTimerSound';
|
||||
|
||||
import './Timer.scss';
|
||||
|
||||
@@ -66,6 +68,7 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
|
||||
freezeOvertime,
|
||||
freezeMessage,
|
||||
hidePhase,
|
||||
endSound,
|
||||
font,
|
||||
keyColour,
|
||||
timerColour,
|
||||
@@ -75,6 +78,8 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
|
||||
const { getLocalizedString } = useTranslation();
|
||||
const localisedMinutes = getLocalizedString('common.minutes');
|
||||
|
||||
const { showPrompt } = useTimerSound(time.phase, endSound);
|
||||
|
||||
// gather modifiers
|
||||
const viewTimerType = timerType ?? timerTypeNow;
|
||||
const showOverlay = getShowMessage(message.timer);
|
||||
@@ -156,6 +161,8 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
|
||||
|
||||
<ViewParamsEditor target={OntimeView.Timer} viewOptions={timerOptions} />
|
||||
|
||||
{showPrompt && <EnableSoundPrompt />}
|
||||
|
||||
<div className={cx(['blackout', message.timer.blackout && 'blackout--active'])} />
|
||||
|
||||
{!hideMessage && (
|
||||
@@ -227,3 +234,19 @@ function TimerAutoTickingClock({ clockFormat }: { clockFormat: MaybeString }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nudges the user to interact with the screen so that the browser allows audio playback
|
||||
* Any interaction arms the sound, so this is a hint rather than a control
|
||||
* It is tied to mouse movement since that does not itself grant playback permission,
|
||||
* which keeps the hint off screen unless somebody is at the machine to act on it
|
||||
*/
|
||||
function EnableSoundPrompt() {
|
||||
const isUserActive = useFadeOutOnInactivity(true);
|
||||
|
||||
return (
|
||||
<div className={cx(['sound-prompt', !isUserActive && 'sound-prompt--hidden'])} aria-live='polite'>
|
||||
Tap the screen to enable sound
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { TimerPhase } from 'ontime-types';
|
||||
|
||||
import { shouldPlayEndSound } from '../timer.utils';
|
||||
|
||||
describe('shouldPlayEndSound()', () => {
|
||||
test.each([TimerPhase.Default, TimerPhase.Warning, TimerPhase.Danger])(
|
||||
'sounds when a running timer goes into overtime from %s',
|
||||
(previousPhase) => {
|
||||
expect(shouldPlayEndSound(previousPhase, TimerPhase.Overtime)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('stays silent on the first phase we see, a client could be joining mid-overtime', () => {
|
||||
expect(shouldPlayEndSound(null, TimerPhase.Overtime)).toBe(false);
|
||||
});
|
||||
|
||||
it('stays silent when the phase was reset, a reload during overtime starts from none', () => {
|
||||
expect(shouldPlayEndSound(TimerPhase.None, TimerPhase.Overtime)).toBe(false);
|
||||
});
|
||||
|
||||
it('stays silent for a roll timer waiting to start', () => {
|
||||
expect(shouldPlayEndSound(TimerPhase.Pending, TimerPhase.Overtime)).toBe(false);
|
||||
});
|
||||
|
||||
it('sounds once, not on every update while in overtime', () => {
|
||||
expect(shouldPlayEndSound(TimerPhase.Overtime, TimerPhase.Overtime)).toBe(false);
|
||||
});
|
||||
|
||||
it('stays silent on phases which are not the end of the timer', () => {
|
||||
expect(shouldPlayEndSound(TimerPhase.Default, TimerPhase.Warning)).toBe(false);
|
||||
expect(shouldPlayEndSound(TimerPhase.Warning, TimerPhase.Danger)).toBe(false);
|
||||
expect(shouldPlayEndSound(TimerPhase.Overtime, TimerPhase.None)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -76,6 +76,14 @@ export const getTimerOptions = (timeFormat: string, customFields: CustomFields):
|
||||
type: 'boolean',
|
||||
defaultValue: false,
|
||||
},
|
||||
{
|
||||
id: 'endSound',
|
||||
title: 'Play sound on timer end',
|
||||
description:
|
||||
'Plays a sound in this screen when the timer reaches zero. The screen must be interacted with once before it can play',
|
||||
type: 'boolean',
|
||||
defaultValue: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -193,6 +201,7 @@ type TimerOptions = {
|
||||
freezeOvertime: boolean;
|
||||
freezeMessage: string;
|
||||
hidePhase: boolean;
|
||||
endSound: boolean;
|
||||
font?: string;
|
||||
keyColour?: string;
|
||||
timerColour?: string;
|
||||
@@ -227,6 +236,7 @@ function getOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URL
|
||||
freezeOvertime: isStringBoolean(getValue('freezeOvertime')),
|
||||
freezeMessage: getValue('freezeMessage') ?? '',
|
||||
hidePhase: isStringBoolean(getValue('hidePhase')),
|
||||
endSound: isStringBoolean(getValue('endSound')),
|
||||
|
||||
font: getValue('font') ?? undefined,
|
||||
keyColour: makeColourString(getValue('keyColour')),
|
||||
|
||||
@@ -189,3 +189,18 @@ export function getCardData(
|
||||
nextSecondary,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the end of timer sound should play for a given phase transition
|
||||
* We only sound the transition into overtime from a phase that was already counting,
|
||||
* which keeps a client that connects or reloads mid-overtime silent
|
||||
*/
|
||||
export function shouldPlayEndSound(previousPhase: TimerPhase | null, phase: TimerPhase): boolean {
|
||||
if (phase !== TimerPhase.Overtime) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
previousPhase === TimerPhase.Default || previousPhase === TimerPhase.Warning || previousPhase === TimerPhase.Danger
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { TimerPhase } from 'ontime-types';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import buzzer from '../../assets/sounds/buzzer.mp3';
|
||||
import { shouldPlayEndSound } from './timer.utils';
|
||||
|
||||
/**
|
||||
* Plays a sound when the timer reaches its end
|
||||
*
|
||||
* Browsers reject playback until the document has been interacted with, and that permission
|
||||
* is lost on every page load. Since a timer screen is typically left unattended, we prime the
|
||||
* audio element on the first interaction and let the view prompt for one if it never comes.
|
||||
* Safari grants the permission per element, so priming has to call play() on this element from
|
||||
* inside the event handler, it is not enough to know that an interaction happened.
|
||||
*/
|
||||
export function useTimerSound(phase: TimerPhase, enabled: boolean): { showPrompt: boolean } {
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
const previousPhaseRef = useRef<TimerPhase | null>(null);
|
||||
const [isArmed, setIsArmed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
audioRef.current = new Audio(buzzer);
|
||||
|
||||
return () => {
|
||||
audioRef.current?.pause();
|
||||
audioRef.current = null;
|
||||
setIsArmed(false);
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || isArmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const prime = () => {
|
||||
audioRef.current
|
||||
?.play()
|
||||
.then(() => {
|
||||
if (!audioRef.current) return;
|
||||
audioRef.current.pause();
|
||||
audioRef.current.currentTime = 0;
|
||||
setIsArmed(true);
|
||||
})
|
||||
.catch(() => {
|
||||
// playback is still blocked, a later interaction will try again
|
||||
});
|
||||
};
|
||||
|
||||
document.addEventListener('pointerdown', prime, { capture: true, signal: controller.signal });
|
||||
document.addEventListener('keydown', prime, { capture: true, signal: controller.signal });
|
||||
|
||||
return () => {
|
||||
controller.abort();
|
||||
};
|
||||
}, [enabled, isArmed]);
|
||||
|
||||
useEffect(() => {
|
||||
const previousPhase = previousPhaseRef.current;
|
||||
previousPhaseRef.current = phase;
|
||||
|
||||
if (!enabled || !shouldPlayEndSound(previousPhase, phase)) {
|
||||
return;
|
||||
}
|
||||
|
||||
audioRef.current?.play().catch(() => {
|
||||
// the screen has not been interacted with, the view shows a prompt for it
|
||||
});
|
||||
}, [enabled, phase]);
|
||||
|
||||
return { showPrompt: enabled && !isArmed };
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { deepEqual } from 'fast-equals';
|
||||
import {
|
||||
EndAction,
|
||||
OntimeEntry,
|
||||
OntimeEvent,
|
||||
OntimeGroup,
|
||||
OntimeMilestone,
|
||||
@@ -10,21 +8,13 @@ import {
|
||||
TimerType,
|
||||
Trigger,
|
||||
} from 'ontime-types';
|
||||
import {
|
||||
MILLIS_PER_HOUR,
|
||||
MILLIS_PER_MINUTE,
|
||||
createDelay,
|
||||
createEvent,
|
||||
createGroup,
|
||||
createMilestone,
|
||||
} from 'ontime-utils';
|
||||
import { MILLIS_PER_HOUR, MILLIS_PER_MINUTE, createEvent } from 'ontime-utils';
|
||||
import { assertType } from 'vitest';
|
||||
|
||||
import { makeOntimeEvent, makeOntimeGroup, makeOntimeMilestone, makeRundown } from '../__mocks__/rundown.mocks.js';
|
||||
import { parseRundown } from '../rundown.parser.js';
|
||||
import {
|
||||
calculateDayOffset,
|
||||
cloneEntryData,
|
||||
deleteById,
|
||||
doesInvalidateMetadata,
|
||||
getIntegerAndFraction,
|
||||
@@ -725,68 +715,3 @@ describe('eventDurationMatchGroupTarget()', () => {
|
||||
expect(result).toStrictEqual(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cloneEntryData()', () => {
|
||||
const trigger: Trigger = {
|
||||
id: 'trigger-1',
|
||||
title: 'Go on air',
|
||||
trigger: TimerLifeCycle.onStart,
|
||||
automationId: 'automation-1',
|
||||
};
|
||||
|
||||
// the real factories, so these are complete entries exactly as the rundown holds them
|
||||
const entries: [string, OntimeEntry][] = [
|
||||
['event', createEvent({ custom: { sponsor: 'a value' }, triggers: [trigger] }, 'cue-1') as OntimeEvent],
|
||||
['group', createGroup({ id: 'group-1', entries: ['a', 'b'], custom: { sponsor: 'a value' } })],
|
||||
['milestone', createMilestone({ id: 'milestone-1', custom: { sponsor: 'a value' } })],
|
||||
['delay', createDelay({ id: 'delay-1', duration: 10 })],
|
||||
];
|
||||
|
||||
/**
|
||||
* Fails if any nested object or array in the clone is the same reference as the source,
|
||||
* so a field added later that needs a copy of its own is caught here without the clone
|
||||
* having to enumerate fields.
|
||||
*/
|
||||
function expectNoSharedReferences(clone: unknown, source: unknown, path: string) {
|
||||
if (typeof source !== 'object' || source === null) return;
|
||||
expect(clone, `${path} is shared with the source`).not.toBe(source);
|
||||
const cloneRecord = clone as Record<string, unknown>;
|
||||
const sourceRecord = source as Record<string, unknown>;
|
||||
for (const key of Object.keys(sourceRecord)) {
|
||||
expectNoSharedReferences(cloneRecord[key], sourceRecord[key], `${path}.${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** the two halves of the structuredClone contract: same value, no shared references */
|
||||
it.each(entries)('clones a %s to the same value structuredClone would produce', (_type, entry) => {
|
||||
expect(cloneEntryData(entry)).toStrictEqual(structuredClone(entry));
|
||||
});
|
||||
|
||||
it.each(entries)('shares no nested object or array with the source %s', (_type, entry) => {
|
||||
expectNoSharedReferences(cloneEntryData(entry), entry, 'entry');
|
||||
});
|
||||
|
||||
/**
|
||||
* Regression: normalising an absent container to an empty one makes deepEqual report a
|
||||
* change on every comparison, which would have the runtime re-broadcast and re-save the
|
||||
* restore point on every tick. See PR #2178.
|
||||
*/
|
||||
it.each([
|
||||
['event', makeOntimeEvent({ id: 'partial' })],
|
||||
['group', makeOntimeGroup({ id: 'partial', entries: undefined })],
|
||||
])('gives a partial %s exactly the keys structuredClone would, so it stays deep-equal', (_type, entry) => {
|
||||
const clone = cloneEntryData(entry);
|
||||
// asserting on keys, not values: `toBeUndefined()` cannot tell an absent key from an own
|
||||
// key holding undefined, and it is key presence that decides the deepEqual below
|
||||
expect(Object.keys(clone).sort()).toEqual(Object.keys(structuredClone(entry)).sort());
|
||||
// this is the comparison runtime.service.ts uses to decide whether to re-broadcast an
|
||||
// entry; if the clone gains a key, every tick looks like a change
|
||||
expect(deepEqual(clone, entry)).toBe(true);
|
||||
});
|
||||
|
||||
it('throws on an entry type it does not know how to clone', () => {
|
||||
expect(() => cloneEntryData({ id: 'x', type: 'unknown' } as unknown as OntimeEvent)).toThrow(
|
||||
'Unsupported entry type for cloning',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
isPlayableEvent,
|
||||
} from 'ontime-types';
|
||||
import { addToRundown, createGroup, customFieldLabelToKey, getInsertAfterId, insertAtIndex } from 'ontime-utils';
|
||||
import type { DeepReadonly } from 'ts-essentials';
|
||||
|
||||
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
|
||||
import { consoleError } from '../../utils/console.js';
|
||||
@@ -35,7 +34,6 @@ import { ProcessedRundownMetadata, makeRundownMetadata } from './rundown.parser.
|
||||
import type { RundownMetadata } from './rundown.types.js';
|
||||
import {
|
||||
applyPatchToEntry,
|
||||
cloneRundown,
|
||||
cloneSimpleRundownEntry,
|
||||
deleteById,
|
||||
doesInvalidateMetadata,
|
||||
@@ -45,14 +43,9 @@ import {
|
||||
} from './rundown.utils.js';
|
||||
|
||||
/**
|
||||
* The currently loaded rundown in cache.
|
||||
*
|
||||
* Reassigned - never mutated in place - when a different rundown is loaded: the persistence
|
||||
* layer stores this object by reference, so repurposing it for another rundown would rewrite
|
||||
* the previously loaded rundown's stored record. Mutating it in place while it represents the
|
||||
* same rundown (ie. from commit) is intended, and is what keeps the stored record current.
|
||||
* The currently loaded rundown in cache
|
||||
*/
|
||||
let cachedRundown: Rundown = {
|
||||
const cachedRundown: Rundown = {
|
||||
id: '',
|
||||
title: '',
|
||||
order: [],
|
||||
@@ -86,16 +79,9 @@ export const getRundownMetadata = (): Readonly<RundownMetadata> => rundownMetada
|
||||
export const getProjectCustomFields = (): Readonly<CustomFields> => projectCustomFields;
|
||||
export const getEntryWithId = (entryId: EntryId): OntimeEntry | undefined => cachedRundown.entries[entryId];
|
||||
|
||||
/**
|
||||
* @param R the type callers see for `rundown` - a plain, mutable `Rundown` when the
|
||||
* transaction was opened with `mutableRundown: true`, otherwise a `DeepReadonly<Rundown>`
|
||||
* so that accidentally mutating an entry (or an order array) on a non-mutable transaction
|
||||
* - which would silently corrupt the live cache without going through commit() - is a
|
||||
* compile-time error instead of a runtime bug.
|
||||
*/
|
||||
type Transaction<R> = {
|
||||
type Transaction = {
|
||||
customFields: CustomFields;
|
||||
rundown: R;
|
||||
rundown: Rundown;
|
||||
|
||||
commit: (shouldProcess?: boolean) => Promise<{
|
||||
rundown: Readonly<Rundown>;
|
||||
@@ -116,17 +102,11 @@ type TransactionOptions = {
|
||||
rundownId?: string;
|
||||
};
|
||||
|
||||
export function createTransaction(options: TransactionOptions & { mutableRundown: true }): Transaction<Rundown>;
|
||||
export function createTransaction(
|
||||
options: TransactionOptions & { mutableRundown?: false },
|
||||
): Transaction<DeepReadonly<Rundown>>;
|
||||
export function createTransaction(
|
||||
options: TransactionOptions,
|
||||
): Transaction<Rundown> | Transaction<DeepReadonly<Rundown>> {
|
||||
export function createTransaction(options: TransactionOptions): Transaction {
|
||||
const targetId = options.rundownId ?? cachedRundown.id;
|
||||
const isLoaded = targetId === cachedRundown.id;
|
||||
const sourceRundown: Rundown = isLoaded ? cachedRundown : (getDataProvider().getRundown(targetId) as Rundown);
|
||||
const rundown = options.mutableRundown ? cloneRundown(sourceRundown) : sourceRundown;
|
||||
const rundown = options.mutableRundown ? structuredClone(sourceRundown) : sourceRundown;
|
||||
const customFields = options.mutableCustomFields ? structuredClone(projectCustomFields) : projectCustomFields;
|
||||
|
||||
/**
|
||||
@@ -727,25 +707,21 @@ export const customFieldMutation = {
|
||||
* Expose function to add an initial rundown to the system
|
||||
*/
|
||||
export function init(initialRundown: Readonly<Rundown>, initialCustomFields: Readonly<CustomFields>) {
|
||||
const rundown = cloneRundown(initialRundown);
|
||||
const rundown = structuredClone(initialRundown);
|
||||
const customFields = structuredClone(initialCustomFields);
|
||||
const processedData = processRundown(rundown, customFields, { mutate: true });
|
||||
|
||||
// update the cache values
|
||||
cachedRundown.id = rundown.id;
|
||||
cachedRundown.title = rundown.title;
|
||||
projectCustomFields = customFields;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we are not interested in the iteration data
|
||||
const { previousEvent, latestEvent, previousEntry, entries, order, ...metadata } = processedData;
|
||||
|
||||
// a fresh object, so that the record already stored for a previously loaded rundown keeps
|
||||
// pointing at that rundown's data - see the note on cachedRundown
|
||||
cachedRundown = {
|
||||
id: rundown.id,
|
||||
title: rundown.title,
|
||||
entries,
|
||||
order,
|
||||
flatOrder: metadata.flatEntryOrder,
|
||||
revision: rundown.revision,
|
||||
};
|
||||
cachedRundown.entries = entries;
|
||||
cachedRundown.order = order;
|
||||
cachedRundown.flatOrder = metadata.flatEntryOrder;
|
||||
cachedRundown.revision = rundown.revision;
|
||||
rundownMetadata = metadata;
|
||||
|
||||
// defer writing to the database
|
||||
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
import { makeNewRundown } from '../../models/dataModel.js';
|
||||
import type { ErrorEmitter } from '../../utils/parserUtils.js';
|
||||
import { RundownMetadata } from './rundown.types.js';
|
||||
import { calculateDayOffset, cleanupCustomFields, cloneEntryData } from './rundown.utils.js';
|
||||
import { calculateDayOffset, cleanupCustomFields } from './rundown.utils.js';
|
||||
|
||||
/**
|
||||
* Parse a rundowns object along with the project custom fields
|
||||
@@ -234,7 +234,7 @@ export function makeRundownMetadata(customFields: CustomFields, options?: { muta
|
||||
};
|
||||
|
||||
function process<T extends OntimeEntry>(entry: T, childOfGroup: EntryId | null): T {
|
||||
return processEntry(rundownMeta, customFields, mutate ? entry : cloneEntryData(entry), childOfGroup);
|
||||
return processEntry(rundownMeta, customFields, mutate ? entry : structuredClone(entry), childOfGroup);
|
||||
}
|
||||
|
||||
function getMetadata(): ProcessedRundownMetadata {
|
||||
|
||||
@@ -39,7 +39,6 @@ import {
|
||||
import { parseRundown } from './rundown.parser.js';
|
||||
import type { RundownMetadata } from './rundown.types.js';
|
||||
import {
|
||||
cloneRundown,
|
||||
generateEvent,
|
||||
getFirstInsertId,
|
||||
getIntegerAndFraction,
|
||||
@@ -627,7 +626,7 @@ export async function editCustomField(
|
||||
// ... reassign references in the background rundowns
|
||||
for (const rundownId of Object.keys(projectRundowns)) {
|
||||
if (rundownId !== rundown.id) {
|
||||
const backgroundRundown = cloneRundown(projectRundowns[rundownId]);
|
||||
const backgroundRundown = structuredClone(projectRundowns[rundownId]);
|
||||
customFieldMutation.renameUsages(backgroundRundown, oldKey, newKey);
|
||||
await updateBackgroundRundown(rundownId, backgroundRundown);
|
||||
}
|
||||
@@ -667,7 +666,7 @@ export async function deleteCustomField(key: CustomFieldKey, projectRundowns: Pr
|
||||
// remove references in the background rundowns
|
||||
for (const rundownId of Object.keys(projectRundowns)) {
|
||||
if (rundownId !== rundown.id) {
|
||||
const backgroundRundown = cloneRundown(projectRundowns[rundownId]);
|
||||
const backgroundRundown = structuredClone(projectRundowns[rundownId]);
|
||||
customFieldMutation.removeUsages(backgroundRundown, key);
|
||||
await updateBackgroundRundown(rundownId, backgroundRundown);
|
||||
}
|
||||
@@ -847,7 +846,7 @@ export async function duplicateExistingRundown(id: string) {
|
||||
const dataProvider = getDataProvider();
|
||||
const rundown = dataProvider.getRundown(id);
|
||||
|
||||
const duplicatedRundown: Rundown = cloneRundown(rundown);
|
||||
const duplicatedRundown: Rundown = structuredClone(rundown);
|
||||
duplicatedRundown.id = generateId();
|
||||
duplicatedRundown.title = `Copy of ${rundown.title}`;
|
||||
duplicatedRundown.revision = 0;
|
||||
|
||||
@@ -329,7 +329,7 @@ export function mergeRundownPreservingFields(
|
||||
const structure = isOntimeGroup(incomingEntry)
|
||||
? { entries: incomingEntry.entries }
|
||||
: { parent: incomingEntry.parent };
|
||||
entries[id] = cloneEntryData({ ...merged, ...structure });
|
||||
entries[id] = structuredClone({ ...merged, ...structure });
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -499,61 +499,6 @@ export function cloneSimpleRundownEntry(entry: OntimeEntry, newId: EntryId): Ont
|
||||
throw new Error(`Unsupported entry type for cloning: ${entry}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fast, shape-aware clone of a single entry, preserving its identity (id, revision, etc).
|
||||
* Drop-in replacement for `structuredClone(entry)`
|
||||
*/
|
||||
export function cloneEntryData<T extends OntimeEntry>(entry: T): T {
|
||||
switch (entry.type) {
|
||||
case SupportedEntry.Event: {
|
||||
const clone: OntimeEvent = { ...entry };
|
||||
if (clone.custom) clone.custom = { ...clone.custom };
|
||||
if (clone.triggers) clone.triggers = clone.triggers.map((trigger) => ({ ...trigger }));
|
||||
return clone as T;
|
||||
}
|
||||
case SupportedEntry.Group: {
|
||||
const clone: OntimeGroup = { ...entry };
|
||||
if (clone.custom) clone.custom = { ...clone.custom };
|
||||
if (clone.entries) clone.entries = clone.entries.slice();
|
||||
return clone as T;
|
||||
}
|
||||
case SupportedEntry.Milestone: {
|
||||
const clone: OntimeMilestone = { ...entry };
|
||||
if (clone.custom) clone.custom = { ...clone.custom };
|
||||
return clone as T;
|
||||
}
|
||||
case SupportedEntry.Delay:
|
||||
return { ...entry } as T;
|
||||
default: {
|
||||
// exhaustiveness guard: a new member of `SupportedEntry` is named in the error here
|
||||
const unhandled: never = entry;
|
||||
throw new Error(`Unsupported entry type for cloning: ${(unhandled as OntimeEntry).type}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fast, shape-aware clone of a whole rundown.
|
||||
* Drop-in replacement for `structuredClone(rundown)`: every entry (and its nested
|
||||
* `custom` / `triggers` / `entries` containers) gets its own copy, so callers can mutate
|
||||
* the result freely without touching the source - same contract as structuredClone,
|
||||
* at a fraction of the cost since we skip the generic serialization algorithm.
|
||||
*/
|
||||
export function cloneRundown(rundown: Readonly<Rundown>): Rundown {
|
||||
const entries: RundownEntries = {};
|
||||
for (const id in rundown.entries) {
|
||||
entries[id] = cloneEntryData(rundown.entries[id]);
|
||||
}
|
||||
return {
|
||||
id: rundown.id,
|
||||
title: rundown.title,
|
||||
revision: rundown.revision,
|
||||
order: rundown.order.slice(),
|
||||
flatOrder: rundown.flatOrder.slice(),
|
||||
entries,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility for calculating if the current events should have a day offset
|
||||
* @param current the current event under test
|
||||
|
||||
@@ -464,8 +464,9 @@ export async function upload(sheetId: string, options: ImportMap) {
|
||||
sheetOrder.forEach((entryId, index) => {
|
||||
const isGroupEnd = entryId.startsWith('group-end-');
|
||||
const id = isGroupEnd ? entryId.split('group-end-')[1] : entryId;
|
||||
// cellRequestFromEvent only reads the entry to build a cell request, no clone is needed
|
||||
const entry = isGroupEnd ? ({ id: entryId, type: SupportedEntry.Group } as OntimeGroup) : rundown.entries[id];
|
||||
const entry = isGroupEnd
|
||||
? ({ id: entryId, type: SupportedEntry.Group } as OntimeGroup)
|
||||
: structuredClone(rundown.entries[id]);
|
||||
updateRundown.push(cellRequestFromEvent(entry, index, worksheetId, sheetMetadata));
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
@@ -101,16 +101,8 @@ function getCustomFields(): Readonly<CustomFields> {
|
||||
return db.data.customFields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a rundown, replacing any existing entry for the same key.
|
||||
* Takes ownership of `newData` and stores it by reference - the caller must not mutate it
|
||||
* afterward. Every call site either hands over a freshly-built object it never touches again,
|
||||
* or (for the loaded rundown) the cache's own long-lived object, which is already the single
|
||||
* source of truth for that data - aliasing it here costs nothing and avoids a second full
|
||||
* deep copy of the rundown on every commit.
|
||||
*/
|
||||
async function setRundown(rundownKey: string, newData: Rundown): ReadonlyPromise<ProjectRundowns> {
|
||||
db.data.rundowns[rundownKey] = newData;
|
||||
db.data.rundowns[rundownKey] = structuredClone(newData);
|
||||
await persist();
|
||||
return db.data.rundowns;
|
||||
}
|
||||
|
||||
@@ -4,17 +4,12 @@ import { DatabaseModel } from 'ontime-types';
|
||||
* Merges a partial ontime project into a given ontime project
|
||||
*/
|
||||
export function safeMerge(existing: DatabaseModel, newData: Partial<DatabaseModel>): DatabaseModel {
|
||||
// rundowns are merged separately below by reference (only the top-level map is copied,
|
||||
// same as the other properties here) - deep-cloning them here would be wasted work,
|
||||
// since a project's rundowns are by far the largest part of this object
|
||||
const { rundowns: existingRundowns, ...existingRest } = existing;
|
||||
const { rundowns: newRundowns = {}, ...newDataRest } = newData;
|
||||
|
||||
const deepExisting = structuredClone(existingRest);
|
||||
const deepNewData = structuredClone(newDataRest);
|
||||
const deepExisting = structuredClone(existing);
|
||||
const deepNewData = structuredClone(newData);
|
||||
|
||||
// destructure each property to simplify merging not provided ie: ...{} has no effect
|
||||
const {
|
||||
rundowns = {},
|
||||
project = {},
|
||||
settings = {},
|
||||
viewSettings = {},
|
||||
@@ -24,7 +19,7 @@ export function safeMerge(existing: DatabaseModel, newData: Partial<DatabaseMode
|
||||
} = deepNewData;
|
||||
|
||||
return {
|
||||
rundowns: { ...existingRundowns, ...newRundowns },
|
||||
rundowns: { ...existing.rundowns, ...rundowns },
|
||||
project: { ...deepExisting.project, ...project },
|
||||
settings: { ...deepExisting.settings, ...settings },
|
||||
viewSettings: { ...deepExisting.viewSettings, ...viewSettings },
|
||||
|
||||
@@ -1,226 +0,0 @@
|
||||
import { Offset, OffsetMode, Playback, TimerPhase, TimerState, TimerType } from 'ontime-types';
|
||||
|
||||
import { makeOntimeEvent, makeRundown } from '../../../api-data/rundown/__mocks__/rundown.mocks.js';
|
||||
import {
|
||||
findNextPlayableId,
|
||||
findNextPlayableWithCue,
|
||||
findPreviousPlayableId,
|
||||
getEventAtIndex,
|
||||
getShouldClockUpdate,
|
||||
getShouldOffsetUpdate,
|
||||
getShouldTimerUpdate,
|
||||
isNewSecond,
|
||||
} from '../runtime.utils.js';
|
||||
|
||||
describe('isNewSecond()', () => {
|
||||
it('is false while the value moves within the same second', () => {
|
||||
// count down rounds up, so both resolve to second 2
|
||||
expect(isNewSecond(1500, 1200)).toBe(false);
|
||||
});
|
||||
|
||||
it('is true once the value crosses a second boundary', () => {
|
||||
expect(isNewSecond(1001, 1000)).toBe(true);
|
||||
});
|
||||
|
||||
it('rounds according to the given direction', () => {
|
||||
// 1200 -> ceil 2 / floor 1, 1800 -> ceil 2 / floor 1
|
||||
expect(isNewSecond(1200, 1800, TimerType.CountDown)).toBe(false);
|
||||
expect(isNewSecond(1200, 1800, TimerType.CountUp)).toBe(false);
|
||||
// 1200 -> ceil 2 / floor 1, 2200 -> ceil 3 / floor 2
|
||||
expect(isNewSecond(1200, 2200, TimerType.CountDown)).toBe(true);
|
||||
expect(isNewSecond(1200, 2200, TimerType.CountUp)).toBe(true);
|
||||
});
|
||||
|
||||
it('treats null and undefined as second zero', () => {
|
||||
expect(isNewSecond(undefined, null)).toBe(false);
|
||||
expect(isNewSecond(null, 0)).toBe(false);
|
||||
expect(isNewSecond(undefined, 500)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getShouldClockUpdate()', () => {
|
||||
it('is false within the same second and true across the boundary', () => {
|
||||
expect(getShouldClockUpdate(1000, 1999)).toBe(false);
|
||||
expect(getShouldClockUpdate(1000, 2000)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getShouldTimerUpdate()', () => {
|
||||
const baseTimer: TimerState = {
|
||||
addedTime: 0,
|
||||
current: 10000,
|
||||
duration: 10000,
|
||||
elapsed: 0,
|
||||
expectedFinish: 10000,
|
||||
phase: TimerPhase.Default,
|
||||
playback: Playback.Play,
|
||||
secondaryTimer: null,
|
||||
startedAt: 0,
|
||||
};
|
||||
|
||||
it('always updates when there is no previous state', () => {
|
||||
expect(getShouldTimerUpdate(undefined, baseTimer)).toBe(true);
|
||||
});
|
||||
|
||||
it('does not update while the timer ticks within the same second', () => {
|
||||
expect(getShouldTimerUpdate(baseTimer, { ...baseTimer, current: 9500 })).toBe(false);
|
||||
});
|
||||
|
||||
it('updates when the timer crosses a second', () => {
|
||||
expect(getShouldTimerUpdate(baseTimer, { ...baseTimer, current: 8999 })).toBe(true);
|
||||
});
|
||||
|
||||
it('updates when the secondary timer crosses a second', () => {
|
||||
const previous = { ...baseTimer, secondaryTimer: 2000 };
|
||||
// counting down rounds up, so 1999 is still second 2
|
||||
expect(getShouldTimerUpdate(previous, { ...previous, secondaryTimer: 1999 })).toBe(false);
|
||||
expect(getShouldTimerUpdate(previous, { ...previous, secondaryTimer: 1000 })).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['addedTime', { addedTime: 1 }],
|
||||
['duration', { duration: 1 }],
|
||||
['phase', { phase: TimerPhase.Warning }],
|
||||
['playback', { playback: Playback.Pause }],
|
||||
['startedAt', { startedAt: 1 }],
|
||||
])('updates immediately when %s changes', (_label, patch) => {
|
||||
expect(getShouldTimerUpdate(baseTimer, { ...baseTimer, ...patch })).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['elapsed', { elapsed: 1 }],
|
||||
['expectedFinish', { expectedFinish: 1 }],
|
||||
])('does not update on %s alone, since it is derived', (_label, patch) => {
|
||||
expect(getShouldTimerUpdate(baseTimer, { ...baseTimer, ...patch })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getShouldOffsetUpdate()', () => {
|
||||
const baseOffset: Offset = {
|
||||
absolute: 0,
|
||||
relative: 0,
|
||||
mode: OffsetMode.Absolute,
|
||||
expectedGroupEnd: null,
|
||||
expectedRundownEnd: null,
|
||||
expectedFlagStart: null,
|
||||
};
|
||||
|
||||
it('always updates when there is no previous state', () => {
|
||||
expect(getShouldOffsetUpdate(undefined, baseOffset, false)).toBe(true);
|
||||
});
|
||||
|
||||
it('updates on a mode change even when no dependency ticked', () => {
|
||||
expect(getShouldOffsetUpdate(baseOffset, { ...baseOffset, mode: OffsetMode.Relative }, false)).toBe(true);
|
||||
});
|
||||
|
||||
it('holds back value changes until a dependency ticks', () => {
|
||||
const next = { ...baseOffset, absolute: 1000 };
|
||||
expect(getShouldOffsetUpdate(baseOffset, next, false)).toBe(false);
|
||||
expect(getShouldOffsetUpdate(baseOffset, next, true)).toBe(true);
|
||||
});
|
||||
|
||||
it('does not update when a dependency ticked but nothing changed', () => {
|
||||
expect(getShouldOffsetUpdate(baseOffset, { ...baseOffset }, true)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findPreviousPlayableId()', () => {
|
||||
const order = ['1', '2', '3'];
|
||||
|
||||
it('returns undefined when there is nothing to play', () => {
|
||||
expect(findPreviousPlayableId([])).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns the first event when nothing is loaded', () => {
|
||||
expect(findPreviousPlayableId(order)).toBe('1');
|
||||
});
|
||||
|
||||
it('returns the preceding event', () => {
|
||||
expect(findPreviousPlayableId(order, '3')).toBe('2');
|
||||
});
|
||||
|
||||
it('stays on the first event when already at the top', () => {
|
||||
expect(findPreviousPlayableId(order, '1')).toBe('1');
|
||||
});
|
||||
|
||||
it('falls back to the first event when the loaded id is unknown', () => {
|
||||
expect(findPreviousPlayableId(order, 'not-in-rundown')).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findNextPlayableId()', () => {
|
||||
const order = ['1', '2', '3'];
|
||||
|
||||
it('returns undefined when there is nothing to play', () => {
|
||||
expect(findNextPlayableId([])).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns the first event when nothing is loaded', () => {
|
||||
expect(findNextPlayableId(order)).toBe('1');
|
||||
});
|
||||
|
||||
it('returns the following event', () => {
|
||||
expect(findNextPlayableId(order, '1')).toBe('2');
|
||||
});
|
||||
|
||||
it('wraps to the first event from the last', () => {
|
||||
expect(findNextPlayableId(order, '3')).toBe('1');
|
||||
});
|
||||
|
||||
it('falls back to the first event when the loaded id is unknown', () => {
|
||||
expect(findNextPlayableId(order, 'not-in-rundown')).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findNextPlayableWithCue()', () => {
|
||||
const rundown = makeRundown({
|
||||
order: ['1', '2', '3', '4'],
|
||||
entries: {
|
||||
'1': makeOntimeEvent({ id: '1', cue: 'a' }),
|
||||
'2': makeOntimeEvent({ id: '2', cue: 'b' }),
|
||||
'3': makeOntimeEvent({ id: '3', cue: 'b', skip: true }),
|
||||
'4': makeOntimeEvent({ id: '4', cue: 'b' }),
|
||||
},
|
||||
});
|
||||
const order = ['1', '2', '3', '4'];
|
||||
|
||||
it('finds the next event with the given cue', () => {
|
||||
expect(findNextPlayableWithCue(rundown, order, 'b')?.id).toBe('2');
|
||||
});
|
||||
|
||||
it('skips events which are not playable', () => {
|
||||
expect(findNextPlayableWithCue(rundown, order, 'b', 2)?.id).toBe('4');
|
||||
});
|
||||
|
||||
it('wraps around to the start of the rundown', () => {
|
||||
expect(findNextPlayableWithCue(rundown, order, 'a', 2)?.id).toBe('1');
|
||||
});
|
||||
|
||||
it('excludes the current event unless allowCurrent is set', () => {
|
||||
expect(findNextPlayableWithCue(rundown, order, 'b', 1)?.id).toBe('4');
|
||||
expect(findNextPlayableWithCue(rundown, order, 'b', 1, true)?.id).toBe('2');
|
||||
});
|
||||
|
||||
it('returns undefined when no event carries the cue', () => {
|
||||
expect(findNextPlayableWithCue(rundown, order, 'missing')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEventAtIndex()', () => {
|
||||
const rundown = makeRundown({
|
||||
order: ['1', '2'],
|
||||
entries: {
|
||||
'1': makeOntimeEvent({ id: '1' }),
|
||||
'2': makeOntimeEvent({ id: '2' }),
|
||||
},
|
||||
});
|
||||
|
||||
it('returns the event at the given index', () => {
|
||||
expect(getEventAtIndex(rundown, ['1', '2'], 1)?.id).toBe('2');
|
||||
});
|
||||
|
||||
it('returns undefined when the index is out of range', () => {
|
||||
expect(getEventAtIndex(rundown, ['1', '2'], 5)).toBeUndefined();
|
||||
expect(getEventAtIndex(rundown, [], 0)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,6 @@ import { triggerAutomations } from '../../api-data/automation/automation.service
|
||||
import { triggerReportEntry } from '../../api-data/report/report.service.js';
|
||||
import { getCurrentRundown, getEntryWithId, getRundownMetadata } from '../../api-data/rundown/rundown.dao.js';
|
||||
import { RundownMetadata } from '../../api-data/rundown/rundown.types.js';
|
||||
import { cloneEntryData } from '../../api-data/rundown/rundown.utils.js';
|
||||
import { logger } from '../../classes/Logger.js';
|
||||
import { timerConfig } from '../../setup/config.js';
|
||||
import { eventStore } from '../../stores/EventStore.js';
|
||||
@@ -755,7 +754,7 @@ function broadcastResult(_target: any, _propertyKey: string, descriptor: Propert
|
||||
}
|
||||
// at this point we know that either the id or the contents has changed
|
||||
batch.add(key, currentEntry as RuntimeStore[K]); // we know that there is the necessary overlap in the types to cast this
|
||||
RuntimeService.previousState[key] = currentEntry ? cloneEntryData(currentEntry) : null;
|
||||
RuntimeService.previousState[key] = structuredClone(currentEntry);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user