Compare commits

..

1 Commits

Author SHA1 Message Date
Claude 4c29756abe test: cover runtime update gating and colour parsing
Adds unit tests for two pure modules which had no coverage:

- `runtime.utils.ts` gates every websocket broadcast and the
  `onUpdate` / `onClock` automation triggers. The tests pin the
  second-boundary rounding, the documented cases where a field is
  deliberately *not* broadcast (`elapsed`, `expectedFinish`), and the
  wrap-around behaviour of the load-next / load-previous / go-to-cue
  lookups.

- `colour.utils.ts` parses user supplied colour strings for both the
  Google Sheets export and the cuesheet rows. The tests cover the
  hex/CSS-name parsing, the null returns for invalid input, and the
  hexToColour <-> colourToHex round trip.

Both files are pure, so neither test uses a mock.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAH21unBqSzEH9HMwqfa5Q
2026-08-17 11:38:27 +00:00
39 changed files with 425 additions and 3110 deletions
+2 -24
View File
@@ -20,7 +20,6 @@ const Backstage = lazy(() => import('./views/backstage/Backstage'));
const StudioClock = lazy(() => import('./views/studio/Studio'));
const Timeline = lazy(() => import('./views/timeline/TimelinePage'));
const ProjectInfo = lazy(() => import('./views/project-info/ProjectInfo'));
const Teleprompter = lazy(() => import('./views/teleprompter/Teleprompter'));
const Editor = lazy(() => import('./views/editor/ProtectedEditor'));
const Cuesheet = lazy(() => import('./views/cuesheet/ProtectedCuesheet'));
@@ -96,15 +95,6 @@ export default function AppRouter() {
</ViewLoader>
}
/>
<Route
path='teleprompter'
element={
<ViewLoader>
<ViewNavigationMenu isNavigationLocked={getIsNavigationLocked()} suppressSpaceHotkey />
<Teleprompter />
</ViewLoader>
}
/>
{/*/!* Protected Routes *!/*/}
<Route path='editor' element={<Editor />} />
<Route path='cuesheet' element={<Cuesheet />} />
@@ -175,7 +165,6 @@ const PresetViewMap: Record<OntimeViewPresettable, ComponentType> = {
[OntimeView.StudioClock]: StudioClock,
[OntimeView.Countdown]: Countdown,
[OntimeView.ProjectInfo]: ProjectInfo,
[OntimeView.Teleprompter]: Teleprompter,
};
/**
@@ -225,19 +214,8 @@ function PresetView() {
const Component = PresetViewMap[preset.target as OntimeViewPresettable];
return (
<PresetContext value={preset}>
{/*
Presets render the same views as the direct routes and need the same
wrapper: ViewLoader is what injects the project's CSS override
stylesheet. Without it a preset silently ignores configured styling.
*/}
<ViewLoader>
<ViewNavigationMenu
isNavigationLocked={getIsNavigationLocked()}
suppressSettings
suppressSpaceHotkey={preset.target === OntimeView.Teleprompter}
/>
{Component ? <Component /> : <NotFound />}
</ViewLoader>
<ViewNavigationMenu isNavigationLocked={getIsNavigationLocked()} suppressSettings />
{Component ? <Component /> : <NotFound />}
</PresetContext>
);
}
@@ -1,75 +0,0 @@
/**
* Layout for a list of keyboard shortcuts, shared by the rundown editor and the
* teleprompter help.
*
* Colour is left to whoever renders it: the editor and the viewer palettes have
* no tokens in common, and the only thing the two lists actually share is the
* shape. The three custom properties below are the seams for that.
*/
.groups {
display: grid;
gap: 0.875rem;
}
.group {
h3 {
margin: 0 0 0.375rem;
color: var(--shortcut-title-color, currentColor);
font-size: calc(1rem - 3px);
font-weight: 600;
text-transform: uppercase;
}
}
.list {
display: grid;
gap: 0.25rem;
}
.row {
min-height: 1.625rem;
display: grid;
grid-template-columns: minmax(10rem, 1fr) minmax(0, auto);
align-items: center;
gap: 0.75rem;
font-size: calc(1rem - 3px);
}
.label {
min-width: 0;
line-height: 1.2;
color: var(--shortcut-label-color, currentColor);
}
.keys {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
justify-content: flex-end;
gap: 0.25rem 0.5rem;
min-width: 0;
}
.combo {
display: inline-flex;
align-items: center;
flex-wrap: nowrap;
gap: 0.25rem 0;
}
.separator {
color: var(--shortcut-separator-color, currentColor);
font-size: calc(1rem - 5px);
}
/* the label column cannot hold a sentence and a key combo side by side on a phone */
@media (max-width: 680px) {
.row {
grid-template-columns: 1fr;
gap: 0.25rem;
}
.keys {
justify-content: flex-start;
}
}
@@ -1,52 +0,0 @@
import type { PropsWithChildren } from 'react';
import { cx } from '../../utils/styleUtils';
import Kbd from '../kbd/Kbd';
import style from './KeyboardShortcuts.module.scss';
/**
* The pieces a list of keyboard shortcuts is built from.
*
* Both the rundown editor's empty state and the teleprompter's help answer the
* same question, so they are laid out by the same components: a reader who has
* learned one list can read the other. Only the palette is left to the host,
* through the --shortcut-*-color properties, since the editor and the viewer
* themes share no tokens.
*/
export function ShortcutGroups({ className, children }: PropsWithChildren<{ className?: string }>) {
return <div className={cx([style.groups, className])}>{children}</div>;
}
export function ShortcutGroup({ title, children }: PropsWithChildren<{ title: string }>) {
return (
<section className={style.group}>
<h3>{title}</h3>
<div className={style.list}>{children}</div>
</section>
);
}
export function Shortcut({ label, children }: PropsWithChildren<{ label: string }>) {
return (
<div className={style.row}>
<span className={style.label}>{label}</span>
<span className={style.keys}>{children}</span>
</div>
);
}
/** One chord, rendered as keycaps. Several in a row read as alternatives */
export function Combo({ keys }: { keys: string[] }) {
return (
<span className={style.combo}>
{keys.map((key) => (
<Kbd key={key}>{key}</Kbd>
))}
</span>
);
}
export function Separator() {
return <span className={style.separator}>/</span>;
}
@@ -1,4 +1,4 @@
import { type HotkeyItem, useDisclosure, useHotkeys } from '@mantine/hooks';
import { useDisclosure, useHotkeys } from '@mantine/hooks';
import { memo } from 'react';
import { useSearchParams } from 'react-router';
@@ -13,38 +13,24 @@ interface ViewNavigationMenuProps {
isNavigationLocked?: boolean;
/** prevent showing settings */
suppressSettings?: boolean;
/** leave Space to the view, for views which need the key themselves */
suppressSpaceHotkey?: boolean;
}
export default memo(ViewNavigationMenu);
function ViewNavigationMenu({ isNavigationLocked, suppressSettings, suppressSpaceHotkey }: ViewNavigationMenuProps) {
function ViewNavigationMenu({ isNavigationLocked, suppressSettings }: ViewNavigationMenuProps) {
const [isMenuOpen, menuHandler] = useDisclosure();
const { open: showEditFormDrawer } = useViewParamsEditorStore();
const [searchParams] = useSearchParams();
const hasSavedChanges = hasCustomParams(searchParams);
/**
* The Space binding is left out entirely rather than made a no-op, because
* useHotkeys calls preventDefault before it reaches the handler. A handler
* which returns early still swallows the key, which would stop Space
* activating whichever button the user has focused.
*/
const spaceHotkey: HotkeyItem[] = suppressSpaceHotkey
? []
: [
[
'Space',
() => {
if (isNavigationLocked) return;
menuHandler.toggle();
},
{ preventDefault: true },
],
];
useHotkeys([
...spaceHotkey,
[
'Space',
() => {
if (isNavigationLocked) return;
menuHandler.toggle();
},
{ preventDefault: true },
],
[
'mod + ,',
() => {
@@ -49,20 +49,7 @@ export default function ParamInput({ paramField }: ParamInputProps) {
}
if (type === 'boolean') {
/**
* isStringBoolean answers false for an absent param rather than nothing, so
* it cannot be used to fall through to the default: a ?? here would never
* fire and every switch would open off, whatever the option declares. That
* only shows on options which default to true, where the editor would then
* disagree with the view it is meant to be editing.
*/
const paramValue = searchParams.get(id);
return (
<ControlledSwitch
id={id}
initialValue={paramValue === null ? Boolean(defaultValue) : isStringBoolean(paramValue)}
/>
);
return <ControlledSwitch id={id} initialValue={isStringBoolean(searchParams.get(id)) ?? defaultValue} />;
}
if (type === 'number') {
@@ -227,45 +227,12 @@ describe('getURLSearchParamsFromObj()', () => {
],
},
];
// a switch which is off sends nothing at all, it is not present and false
const params = {
bool1: 'off',
bool2: 'on',
};
const result = getURLSearchParamsFromObj(params, mockOptionsWithBooleans);
expect(result.get('bool1')).toBe('false');
expect(result.get('bool2')).toBe('true');
});
it('omits booleans which match their default', () => {
const mockOptionsWithBooleans: ViewOption[] = [
{
title: OptionTitle.StyleOverride,
options: [
{
id: 'onByDefault',
title: 'onByDefault',
description: 'On by default',
type: 'boolean',
defaultValue: true,
},
{
id: 'offByDefault',
title: 'offByDefault',
description: 'Off by default',
type: 'boolean',
defaultValue: false,
},
],
},
];
// both switches left as they were: the URL stays clean
const untouched = getURLSearchParamsFromObj({ onByDefault: 'on' }, mockOptionsWithBooleans);
expect(untouched.toString()).toBe('');
// both switches flipped: each one has to be written to survive a reload
const flipped = getURLSearchParamsFromObj({ offByDefault: 'on' }, mockOptionsWithBooleans);
expect(flipped.get('onByDefault')).toBe('false');
expect(flipped.get('offByDefault')).toBe('true');
});
});
@@ -155,20 +155,6 @@ export function getURLSearchParamsFromObj(paramsObj: ViewParamsObj, paramFields:
});
});
/**
* An unchecked checkbox is absent from the form data rather than present and
* false, so a boolean can only be read by looking for the ones which did not
* arrive. Without this an option defaulting to true could never be turned off:
* the switch would send nothing, no param would be written, and the parser
* would fall back to the default the user was trying to leave.
*/
metadata.booleanFields.forEach((id) => {
if (id in paramsObj) return;
if (metadata.defaultValues[id] !== 'false') {
addUniqueParam(id, 'false');
}
});
// Then process user-provided values
Object.entries(paramsObj).forEach(([id, value]) => {
if (typeof value === 'string' && value.length) {
@@ -26,7 +26,6 @@ const targetOptions: SelectOption<OntimeViewPresettable>[] = [
{ value: OntimeView.StudioClock, label: 'Studio Clock' },
{ value: OntimeView.Countdown, label: 'Countdown' },
{ value: OntimeView.ProjectInfo, label: 'Project Info' },
{ value: OntimeView.Teleprompter, label: 'Teleprompter' },
];
const formId = 'url-preset-form';
@@ -17,10 +17,59 @@
}
.shortcuts {
display: grid;
gap: 0.875rem;
margin-top: 0.875rem;
}
--shortcut-title-color: #{$ui-white};
--shortcut-separator-color: #{$gray-500};
.shortcutGroup {
h3 {
margin: 0 0 0.375rem;
color: $ui-white;
font-size: calc(1rem - 3px);
font-weight: 600;
text-transform: uppercase;
}
}
.shortcutList {
display: grid;
gap: 0.25rem;
}
.shortcutRow {
min-height: 1.625rem;
display: grid;
grid-template-columns: minmax(10rem, 1fr) minmax(0, auto);
align-items: center;
gap: 0.75rem;
font-size: calc(1rem - 3px);
}
.shortcutLabel {
min-width: 0;
line-height: 1.2;
}
.shortcutKeys {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
justify-content: flex-end;
gap: 0.25rem 0.5rem;
min-width: 0;
}
.keyCombo {
display: inline-flex;
align-items: center;
flex-wrap: nowrap;
gap: 0.25rem 0;
}
.separator {
color: $gray-500;
font-size: calc(1rem - 5px);
}
.prompt {
@@ -35,4 +84,13 @@
.shortcutSection {
margin-top: 1rem;
}
.shortcutRow {
grid-template-columns: 1fr;
gap: 0.25rem;
}
.shortcutKeys {
justify-content: flex-start;
}
}
@@ -1,13 +1,7 @@
import { memo } from 'react';
import { PropsWithChildren, memo } from 'react';
import * as Editor from '../../../common/components/editor-utils/EditorUtils';
import {
Combo,
Separator,
Shortcut,
ShortcutGroup,
ShortcutGroups,
} from '../../../common/components/keyboard-shortcuts/KeyboardShortcuts';
import Kbd from '../../../common/components/kbd/Kbd';
import { deviceAlt, deviceMod } from '../../../common/utils/deviceUtils';
import style from './EventEditorEmpty.module.scss';
@@ -19,7 +13,7 @@ function EventEditorEmpty() {
<div className={style.entryEditor} data-testid='editor-container'>
<div className={style.shortcutSection}>
<Editor.Title className={style.prompt}>Rundown shortcuts</Editor.Title>
<ShortcutGroups className={style.shortcuts}>
<div className={style.shortcuts}>
<ShortcutGroup title='Search'>
<Shortcut label='Find in rundown'>
<Combo keys={[deviceMod, 'F']} />
@@ -106,8 +100,40 @@ function EventEditorEmpty() {
<Combo keys={[deviceAlt, 'Shift', 'D']} />
</Shortcut>
</ShortcutGroup>
</ShortcutGroups>
</div>
</div>
</div>
);
}
function ShortcutGroup({ title, children }: PropsWithChildren<{ title: string }>) {
return (
<section className={style.shortcutGroup}>
<h3>{title}</h3>
<div className={style.shortcutList}>{children}</div>
</section>
);
}
function Shortcut({ label, children }: PropsWithChildren<{ label: string }>) {
return (
<div className={style.shortcutRow}>
<span className={style.shortcutLabel}>{label}</span>
<span className={style.shortcutKeys}>{children}</span>
</div>
);
}
function Combo({ keys }: { keys: string[] }) {
return (
<span className={style.keyCombo}>
{keys.map((key) => (
<Kbd key={key}>{key}</Kbd>
))}
</span>
);
}
function Separator() {
return <span className={style.separator}>/</span>;
}
@@ -35,7 +35,6 @@ export default function GenerateLinkFormExport({ lockedPath }: GenerateLinkFormE
{ value: OntimeView.Timer, label: 'Timer' },
{ value: OntimeView.Cuesheet, label: 'Cuesheet' },
{ value: OntimeView.Operator, label: 'Operator' },
{ value: OntimeView.Teleprompter, label: 'Teleprompter' },
{ value: '<<companion>>', label: 'Companion' },
...urlPresetData.map((preset) => ({
value: `preset-${preset.alias}`,
-1
View File
@@ -4,7 +4,6 @@ export const navigatorConstants = [
{ url: 'timeline', label: 'Timeline' },
{ url: 'studio', label: 'Studio Clock' },
{ url: 'countdown', label: 'Countdown' },
{ url: 'teleprompter', label: 'Teleprompter' },
{ url: 'info', label: 'Project Info' },
];
@@ -1,294 +0,0 @@
@use '@/theme/viewerDefs' as *;
/**
* The --tp-* custom properties come from Teleprompter.tsx, set from the parsed
* view options, so they carry no fallbacks here. A fallback would be a second
* copy of a default that nothing reaches and nothing keeps in step. The one
* exception is --tp-font-size, derived below from the size the view was given.
*/
.teleprompter {
--tp-flip-x: 1;
--tp-flip-y: 1;
/**
* The configured size is a ceiling rather than a fixed value. A prompter set
* up on a stage screen keeps its size in the link it is shared as, and the
* same link opened on a phone would otherwise leave three words to a line.
* The cap only bites below about 650px of viewport, so a rig set up on
* anything laptop sized or larger reads exactly what it was given.
*/
--tp-font-size: min(var(--tp-configured-font-size), 8vw);
position: relative;
height: 100dvh;
width: 100%;
overflow: hidden;
font-family: var(--font-family-override, $viewer-font-family);
/**
* White on black is the prompter default and there is no option to change it.
* Anyone needing another palette has the project's CSS override stylesheet,
* which ViewLoader injects into this view and which can restyle anything.
*/
background: var(--background-color-override, #000000);
color: var(--color-override, #ffffff);
/**
* The flip is applied to the whole view rather than to the text alone.
* A beam splitter reflects everything, so inverting only the text would leave
* the scroll direction reading backwards against the words.
* No transition: a flip mid show has to be instant.
*/
transform: scale(var(--tp-flip-x), var(--tp-flip-y));
transform-origin: center center;
&--flip-h {
--tp-flip-x: -1;
}
&--flip-v {
--tp-flip-y: -1;
}
}
.teleprompter__scroller {
height: 100%;
overflow-y: auto;
overscroll-behavior: contain;
/**
* Chrome's scroll anchoring silently adjusts scrollTop when content above the
* viewport changes height, and the rundown refetches on a timer while a show
* is running. It would be a second writer of scrollTop, fighting our loop.
*/
overflow-anchor: none;
/* the animation frame loop owns scrollTop: never let CSS animate our writes */
scroll-behavior: auto;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
}
.teleprompter__content {
width: var(--tp-text-width);
margin-inline: auto;
font-size: var(--tp-font-size);
line-height: var(--tp-line-height);
/**
* The first line has to be able to reach the reading line, and the last line
* has to be able to scroll all the way up to it. Without the bottom padding
* the script simply cannot be read to the end.
*
* These are expressed against the viewport height rather than as a percentage:
* percentage padding resolves against the containing block's *width*, which
* would put the first line nowhere near the reading line.
*/
padding-top: calc(var(--tp-reading-line) * 1dvh);
padding-bottom: calc(100dvh - var(--tp-reading-line) * 1dvh);
}
.teleprompter__block {
margin-bottom: 1em;
&[data-loaded] .teleprompter__heading {
color: $accent-color;
}
}
/**
* Headings and group names are signposts for the operator, not lines to be read
* aloud, so they stay small and stay on the same left rail as the script. Given
* their own alignment they would become a second thing for the eye to find on
* every segment change, which is the opposite of what a prompter is for.
*/
.teleprompter__group {
font-size: 0.34em;
text-transform: uppercase;
letter-spacing: 0.1em;
color: $viewer-label-color;
margin-bottom: 0.35em;
}
.teleprompter__heading {
font-size: 0.38em;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: $viewer-secondary-color;
margin-bottom: 0.3em;
}
.teleprompter__body {
/* operators write their own line breaks, they are part of the read */
white-space: pre-wrap;
overflow-wrap: break-word;
}
/* ---------------------------------------------------------------- overlays */
/**
* All overlays are absolutely positioned, never fixed: the flip transform on the
* view root makes it the containing block for fixed descendants.
*/
.teleprompter__dim {
position: absolute;
inset: 0 0 auto 0;
height: calc(var(--tp-reading-line) * 1%);
pointer-events: none;
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0));
}
/**
* The marker aligns to the text column rather than the viewport, so it tracks
* the text width option instead of drifting away from the words as the column
* narrows. The content padding puts the top of the read line exactly at the
* reading position, which is why this is not centred on it.
*/
.teleprompter__reading-line {
position: absolute;
top: calc(var(--tp-reading-line) * 1%);
left: 0;
right: 0;
width: var(--tp-text-width);
margin-inline: auto;
height: calc(var(--tp-font-size) * var(--tp-line-height));
pointer-events: none;
}
/**
* A triangle pointing in at the line, which is the shape prompter cue
* indicators have settled on: it names one line without touching the words,
* and it reads as a pointer from the edge rather than as punctuation in the
* script. Clipped from a filled box rather than built from borders so its
* height stays tied to the parent's single line.
*/
.teleprompter__reading-marker {
position: absolute;
top: 0;
bottom: 0;
background: $accent-color;
clip-path: polygon(0 0, 100% 50%, 0 100%);
/* em here is the script's own size, so the arrow grows with the text */
font-size: var(--tp-font-size);
/**
* The text width option leaves a gutter on each side, and the arrow is sized
* against it rather than against the viewport: it fills a good part of the
* space it has, and it cannot land on the words when the column is widened.
* A column at the full width leaves no gutter and no arrow, which is the
* honest outcome, since there is nowhere for it to go.
*/
--tp-gutter: max(0px, calc((100vw - 100%) / 2));
width: min(1.2em, calc(var(--tp-gutter) * 0.6));
right: calc(100% + var(--tp-gutter) * 0.2);
}
.teleprompter__controls {
position: absolute;
bottom: min(2vh, 16px);
left: 50%;
/**
* Applying the view's own flip a second time cancels it, which keeps the
* transport the right way round on a mirrored rig. The flip exists to
* pre-compensate for a beam splitter, so it belongs to the script; the
* operator reads these buttons off the screen itself, and mirrored icons in
* a mirrored order are unusable. The navigation menu and the help dialog are
* already outside the flip for the same reason, this is the odd one in.
*/
transform: translateX(-50%) scale(var(--tp-flip-x), var(--tp-flip-y));
display: flex;
align-items: center;
gap: min(1vh, 8px);
padding: min(1vh, 8px) clamp(8px, 1vw, 16px);
background: rgba(white, 8%);
border-radius: $element-border-radius;
backdrop-filter: blur(6px);
opacity: 1;
transition: opacity $viewer-transition-time;
/**
* useFadeOutOnInactivity drives this, as it does the floating navigation, and
* the same rule applies: once faded the controls stop taking clicks. Leaving
* them live would put an invisible transport across the foot of the script,
* where a stray tap pauses the read.
*/
&--idle {
opacity: 0;
pointer-events: none;
}
}
.teleprompter__speed {
display: flex;
align-items: baseline;
gap: 0.2em;
min-width: 4em;
justify-content: center;
font-size: clamp(14px, 1.4vw, 22px);
font-variant-numeric: tabular-nums;
}
.teleprompter__speed-unit {
font-size: 0.6em;
color: $viewer-label-color;
}
/**
* The help dialog is portalled to the body, so unlike the other overlays it sits
* outside the view root: fixed positioning is correct here, and it is not caught
* by the flip, which keeps it readable on a mirrored rig. Being outside also
* means it inherits nothing from the view and states its own colours.
*/
.teleprompter__help {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.75);
}
.teleprompter__help-card {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(92vw, 32rem);
max-height: 85dvh;
overflow-y: auto;
padding: 1.5rem;
background: $viewer-background-color;
color: $viewer-color;
border-radius: $element-border-radius;
/* the card is chrome, not script: it keeps the UI scale, not the prompter's */
font-size: 1rem;
}
.teleprompter__help-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1.25rem;
}
.teleprompter__help-title {
font-size: 1.25rem;
font-weight: 600;
}
/* the shared shortcut list owns its layout, the view supplies the palette */
.teleprompter__help-groups {
--shortcut-title-color: #{$viewer-label-color};
--shortcut-label-color: #{$viewer-secondary-color};
--shortcut-separator-color: #{$viewer-label-color};
}
@@ -1,203 +0,0 @@
import { OntimeView } from 'ontime-types';
import { type CSSProperties, useState } from 'react';
import EmptyPage from '../../common/components/state/EmptyPage';
import ViewParamsEditor from '../../common/components/view-params-editor/ViewParamsEditor';
import { useSelectedEventId } from '../../common/hooks/useSocket';
import { useWindowTitle } from '../../common/hooks/useWindowTitle';
import { useViewOptionsStore } from '../../common/stores/viewOptions';
import { cx } from '../../common/utils/styleUtils';
import Loader from '../common/loader/Loader';
import ControlOverlay from './control-overlay/ControlOverlay';
import HelpOverlay from './help-overlay/HelpOverlay';
import ReadingLine from './reading-line/ReadingLine';
import ScriptBlockView from './script-block/ScriptBlock';
import { defaults, getTeleprompterOptions, useTeleprompterOptions } from './teleprompter.options';
import { stepFontSize } from './teleprompter.scroll';
import { buildScript, composeFlip } from './teleprompter.utils';
import { useMirrorLiveParams } from './useMirrorLiveParams';
import { useTeleprompterControls } from './useTeleprompterControls';
import { type TeleprompterData, useTeleprompterData } from './useTeleprompterData';
import { useTeleprompterScroll } from './useTeleprompterScroll';
import './Teleprompter.scss';
export default function TeleprompterLoader() {
const { data, status } = useTeleprompterData();
useWindowTitle('Teleprompter');
if (status === 'pending') {
return <Loader />;
}
if (status === 'error') {
return <EmptyPage variant='error' text='There was an error fetching data, please refresh the page.' />;
}
return <Teleprompter {...data} />;
}
function Teleprompter({ rundown, rundownMetadata, customFields }: TeleprompterData) {
'use memo';
const options = useTeleprompterOptions();
const selectedEventId = useSelectedEventId();
// the shared "Flip Screen" toggle from the navigation menu
const isMirrored = useViewOptionsStore((state) => state.mirror);
const [showHelp, setShowHelp] = useState(false);
/**
* The params seed the live controls, which the keys then own until the params
* change again. Without that the params would only apply on mount, so editing
* them in the view options, or redirecting this client to the same view with a
* different query, would silently do nothing.
*
* The reset happens during render rather than in an effect so React can throw
* the stale render away before it reaches the screen. An effect would let a
* frame of the previous orientation paint first, which on a prompter reads as
* a flash. The speed option is kept live the same way, in useTeleprompterScroll.
*/
const fromParams = { flipH: options.flipH, flipV: options.flipV, fontSize: options.fontSize };
const paramsKey = `${fromParams.flipH}|${fromParams.flipV}|${fromParams.fontSize}`;
const [live, setLive] = useState(fromParams);
const [seededFrom, setSeededFrom] = useState(paramsKey);
if (seededFrom !== paramsKey) {
setSeededFrom(paramsKey);
setLive(fromParams);
}
const viewOptions = getTeleprompterOptions(customFields);
const blocks = buildScript(rundown, rundownMetadata, customFields, {
scriptSource: options.scriptSource,
heading: options.heading,
hideEmpty: options.hideEmpty,
showGroups: options.showGroups,
});
const {
scrollerRef,
contentRef,
registerBlock,
handleUserScroll,
controller,
isRunning,
speed,
followLocked,
atEnd,
} = useTeleprompterScroll({
initialSpeed: options.speed,
followLoaded: options.followLoaded,
selectedEventId,
readingLinePos: options.readingLinePos,
blocks,
});
const handleFlip = (axis: 'h' | 'v') =>
setLive((current) => {
const key = axis === 'h' ? 'flipH' : 'flipV';
return { ...current, [key]: !current[key] };
});
const handleFontSize = (steps: number) =>
setLive((current) => ({ ...current, fontSize: stepFontSize(current.fontSize, steps) }));
/**
* Back to the view's default rather than to the size this client happened to
* open at. Now that the keys write the size into the query there is no longer
* a separate configured value to return to, and remembering one privately
* would mean two people on the same link getting different results from the
* same key.
*/
const handleResetFontSize = () => setLive((current) => ({ ...current, fontSize: defaults.fontSize }));
const handleToggleHelp = () => setShowHelp((current) => !current);
/**
* Everything the operator can change from the prompter itself is a view
* setting, and view settings live in the query. Recording them there is what
* makes a tuned prompter shareable, and what makes a reload keep the setup.
*/
useMirrorLiveParams({
speed: speed === defaults.speed ? null : String(speed),
fontSize: live.fontSize === defaults.fontSize ? null : String(live.fontSize),
flipH: live.flipH === defaults.flipH ? null : String(live.flipH),
flipV: live.flipV === defaults.flipV ? null : String(live.flipV),
});
useTeleprompterControls({
controller,
isHelpOpen: showHelp,
onFlip: handleFlip,
onFontSize: handleFontSize,
onResetFontSize: handleResetFontSize,
onToggleHelp: handleToggleHelp,
});
const hasScriptSource = options.scriptSource !== 'none';
// Flip Screen is a flip on both axes, so it folds into the per view flips
const effectiveFlip = composeFlip(live.flipH, live.flipV, isMirrored);
const viewStyles = {
'--tp-configured-font-size': `${live.fontSize}px`,
'--tp-line-height': options.lineHeight,
'--tp-text-width': `${options.textWidth}%`,
// unitless, so the stylesheet can scale it by 1% against the view height for
// the overlays and by 1dvh for the content padding. Percentage padding would
// resolve against width and put the first line nowhere near the reading line
'--tp-reading-line': options.readingLinePos,
} as CSSProperties;
return (
<div
className={cx([
'teleprompter',
effectiveFlip.flipH && 'teleprompter--flip-h',
effectiveFlip.flipV && 'teleprompter--flip-v',
])}
style={viewStyles}
data-testid='teleprompter-view'
>
<ViewParamsEditor target={OntimeView.Teleprompter} viewOptions={viewOptions} />
{!hasScriptSource ? (
<EmptyPage text='Select which field holds the script in the view options' />
) : blocks.length === 0 ? (
<EmptyPage text='There is no script text in the selected field' />
) : (
<>
<div
className='teleprompter__scroller'
data-testid='teleprompter-scroller'
ref={scrollerRef}
onWheel={handleUserScroll}
onTouchMove={handleUserScroll}
onPointerDown={handleUserScroll}
>
<div className='teleprompter__content' ref={contentRef}>
{blocks.map((block) => (
<ScriptBlockView key={block.id} block={block} registerRef={registerBlock} />
))}
</div>
</div>
<ReadingLine showReadingLine={options.readingLine} />
<ControlOverlay
isRunning={isRunning}
speed={speed}
canReengageFollow={followLocked && options.followLoaded}
atEnd={atEnd}
controller={controller}
onToggleHelp={handleToggleHelp}
/>
</>
)}
<HelpOverlay isOpen={showHelp} onClose={handleToggleHelp} />
</div>
);
}
@@ -1,104 +0,0 @@
import { resolveTeleprompterAction, type TeleprompterKeyEvent } from '../teleprompter.keymap';
import { SPEED_STEP, SPEED_STEP_COARSE } from '../teleprompter.scroll';
function makeEvent(overrides: Partial<TeleprompterKeyEvent>): TeleprompterKeyEvent {
return {
code: '',
key: '',
shiftKey: false,
ctrlKey: false,
metaKey: false,
altKey: false,
repeat: false,
...overrides,
};
}
describe('resolveTeleprompterAction()', () => {
test('space toggles playback', () => {
expect(resolveTeleprompterAction(makeEvent({ code: 'Space' }))).toEqual({ type: 'togglePlay' });
});
test('ignores a repeating space', () => {
// a held key, or a pressed foot pedal, otherwise toggles playback dozens of times
expect(resolveTeleprompterAction(makeEvent({ code: 'Space', repeat: true }))).toBeNull();
});
test('vertical arrows nudge by a line', () => {
expect(resolveTeleprompterAction(makeEvent({ code: 'ArrowDown' }))).toEqual({ type: 'nudge', lines: 1 });
expect(resolveTeleprompterAction(makeEvent({ code: 'ArrowUp' }))).toEqual({ type: 'nudge', lines: -1 });
});
test('a repeating arrow still nudges, so the key can be held', () => {
expect(resolveTeleprompterAction(makeEvent({ code: 'ArrowDown', repeat: true }))).toEqual({
type: 'nudge',
lines: 1,
});
});
test('page keys jump a screen', () => {
expect(resolveTeleprompterAction(makeEvent({ code: 'PageDown' }))).toEqual({ type: 'page', direction: 1 });
expect(resolveTeleprompterAction(makeEvent({ code: 'PageUp' }))).toEqual({ type: 'page', direction: -1 });
});
test('horizontal arrows change speed', () => {
expect(resolveTeleprompterAction(makeEvent({ code: 'ArrowRight' }))).toEqual({ type: 'speed', delta: SPEED_STEP });
expect(resolveTeleprompterAction(makeEvent({ code: 'ArrowLeft' }))).toEqual({ type: 'speed', delta: -SPEED_STEP });
});
test('shift makes the speed step coarse', () => {
expect(resolveTeleprompterAction(makeEvent({ code: 'ArrowRight', shiftKey: true }))).toEqual({
type: 'speed',
delta: SPEED_STEP_COARSE,
});
expect(resolveTeleprompterAction(makeEvent({ code: 'ArrowLeft', shiftKey: true }))).toEqual({
type: 'speed',
delta: -SPEED_STEP_COARSE,
});
});
test('home rewinds and escape rewinds and stops', () => {
expect(resolveTeleprompterAction(makeEvent({ code: 'Home' }))).toEqual({ type: 'rewind' });
expect(resolveTeleprompterAction(makeEvent({ code: 'Escape' }))).toEqual({ type: 'rewindAndPause' });
expect(resolveTeleprompterAction(makeEvent({ code: 'End' }))).toEqual({ type: 'jumpToEnd' });
});
test('f flips, shift+f flips the other axis', () => {
expect(resolveTeleprompterAction(makeEvent({ key: 'f' }))).toEqual({ type: 'flip', axis: 'h' });
expect(resolveTeleprompterAction(makeEvent({ key: 'F', shiftKey: true }))).toEqual({ type: 'flip', axis: 'v' });
});
test('font size is resolved by key so it survives other layouts', () => {
expect(resolveTeleprompterAction(makeEvent({ key: '+' }))).toMatchObject({ type: 'fontSize' });
expect(resolveTeleprompterAction(makeEvent({ key: '=' }))).toMatchObject({ type: 'fontSize' });
expect(resolveTeleprompterAction(makeEvent({ key: '-' }))?.type).toBe('fontSize');
expect(resolveTeleprompterAction(makeEvent({ key: '0' }))).toEqual({ type: 'resetFontSize' });
});
test('plus increases and minus decreases', () => {
expect(resolveTeleprompterAction(makeEvent({ key: '+' }))).toEqual({ type: 'fontSize', steps: 1 });
expect(resolveTeleprompterAction(makeEvent({ key: '-' }))).toEqual({ type: 'fontSize', steps: -1 });
});
test('l re-engages the follow and ? shows the help', () => {
expect(resolveTeleprompterAction(makeEvent({ key: 'l' }))).toEqual({ type: 'reengageFollow' });
expect(resolveTeleprompterAction(makeEvent({ key: '?', shiftKey: true }))).toEqual({ type: 'toggleHelp' });
});
test('never shadows a shortcut which carries a modifier', () => {
// mod+, opens the view params and must keep working
expect(resolveTeleprompterAction(makeEvent({ key: ',', metaKey: true }))).toBeNull();
expect(resolveTeleprompterAction(makeEvent({ code: 'Space', ctrlKey: true }))).toBeNull();
expect(resolveTeleprompterAction(makeEvent({ code: 'ArrowRight', altKey: true }))).toBeNull();
});
test('ignores keys it does not bind', () => {
expect(resolveTeleprompterAction(makeEvent({ code: 'KeyQ', key: 'q' }))).toBeNull();
});
test('leaves Enter alone, so a focused transport button can still be pressed', () => {
// Space belongs to the prompter wherever focus is, which leaves Enter as the
// only way to work the overlay from the keyboard
expect(resolveTeleprompterAction(makeEvent({ code: 'Enter', key: 'Enter' }))).toBeNull();
});
});
@@ -1,121 +0,0 @@
import { getOptionsFromParams, getTeleprompterOptions } from '../teleprompter.options';
import { DEFAULT_SPEED, MAX_SPEED, MIN_SPEED } from '../teleprompter.scroll';
describe('getOptionsFromParams()', () => {
test('provides sensible defaults with no params', () => {
const options = getOptionsFromParams(new URLSearchParams());
expect(options).toMatchObject({
scriptSource: 'none',
heading: 'title',
hideEmpty: true,
showGroups: true,
speed: DEFAULT_SPEED,
followLoaded: true,
fontSize: 52,
lineHeight: 1.3,
textWidth: 80,
readingLine: true,
readingLinePos: 25,
flipH: false,
flipV: false,
});
});
test('reads the script source verbatim so it can be handed to getPropertyValue', () => {
const options = getOptionsFromParams(new URLSearchParams('script=custom-prompter'));
expect(options.scriptSource).toBe('custom-prompter');
});
test('booleans which default to true can be turned off', () => {
const options = getOptionsFromParams(
new URLSearchParams('hideEmpty=false&showGroups=false&followLoaded=false&readingLine=false'),
);
expect(options).toMatchObject({
hideEmpty: false,
showGroups: false,
followLoaded: false,
readingLine: false,
});
});
test('booleans which default to false can be turned on', () => {
const options = getOptionsFromParams(new URLSearchParams('flipH=true&flipV=true'));
expect(options).toMatchObject({
flipH: true,
flipV: true,
});
});
test('clamps the speed to the usable range', () => {
expect(getOptionsFromParams(new URLSearchParams('speed=1000')).speed).toBe(MAX_SPEED);
expect(getOptionsFromParams(new URLSearchParams('speed=0')).speed).toBe(MIN_SPEED);
});
test('falls back to the default for a non numeric value', () => {
// Number(null) is 0, so a naive parse would silently produce a speed of zero
expect(getOptionsFromParams(new URLSearchParams('speed=fast')).speed).toBe(DEFAULT_SPEED);
expect(getOptionsFromParams(new URLSearchParams('speed=')).speed).toBe(DEFAULT_SPEED);
expect(getOptionsFromParams(new URLSearchParams('fontSize=huge')).fontSize).toBe(52);
});
test('rejects an unknown value for an enumerated option', () => {
expect(getOptionsFromParams(new URLSearchParams('heading=banana')).heading).toBe('title');
});
test('preset values take precedence over the search params', () => {
const options = getOptionsFromParams(
new URLSearchParams('speed=10&script=custom-a'),
new URLSearchParams('speed=20&script=custom-b'),
);
expect(options.speed).toBe(20);
expect(options.scriptSource).toBe('custom-b');
});
});
describe('getTeleprompterOptions()', () => {
/**
* The params editor renders the declared defaults while the view runs the
* parsed ones. If they drift the editor shows a value the view is not using,
* and nothing else would notice.
*/
test('every declared default is what parsing an empty query produces', () => {
const parsed = getOptionsFromParams(new URLSearchParams()) as Record<string, unknown>;
// the parser exposes the script source under a different name to its param
const parsedByParamId: Record<string, unknown> = { ...parsed, script: parsed.scriptSource };
const declared = getTeleprompterOptions({}).flatMap((section) => section.options);
expect(declared.length).toBeGreaterThan(0);
for (const field of declared) {
if (!('defaultValue' in field) || field.defaultValue === undefined) continue;
const expected = field.defaultValue;
expect({ id: field.id, value: parsedByParamId[field.id] }).toEqual({ id: field.id, value: expected });
}
});
});
describe('option value round trip', () => {
/**
* The editor offers a set of values and the parser accepts a set of values.
* If they part company the editor happily writes a value which the parser
* throws away for the default, and the view just ignores the choice.
*/
test('every value the editor offers survives parsing', () => {
const selects = getTeleprompterOptions({})
.flatMap((section) => section.options)
.filter((field) => field.type === 'option' && field.id !== 'script');
expect(selects.length).toBeGreaterThan(0);
for (const field of selects) {
for (const { value } of field.values) {
const parsed = getOptionsFromParams(new URLSearchParams(`${field.id}=${value}`)) as Record<string, unknown>;
expect({ id: field.id, value, parsed: parsed[field.id] }).toEqual({ id: field.id, value, parsed: value });
}
}
});
});
@@ -1,139 +0,0 @@
import {
advance,
clampSpeed,
easeCatchUp,
frameDeltaSeconds,
linesPerMinuteToPxPerSecond,
MAX_FONT_SIZE,
MAX_FRAME_DELTA_MS,
MAX_SPEED,
MIN_FONT_SIZE,
MIN_SPEED,
stepFontSize,
} from '../teleprompter.scroll';
describe('linesPerMinuteToPxPerSecond()', () => {
test('converts a read rate into a pixel rate', () => {
// 30 lines a minute over a 64px line is half a line a second
expect(linesPerMinuteToPxPerSecond(30, 64)).toBe(32);
});
});
describe('stepFontSize()', () => {
test('steps by a ratio, so a press is the same visual change at any size', () => {
// a fixed pixel step would be a big jump at 20px and imperceptible at 200px
expect(stepFontSize(100, 1)).toBe(110);
expect(stepFontSize(20, 1)).toBe(22);
});
test('shrinking undoes growing', () => {
expect(stepFontSize(stepFontSize(50, 1), -1)).toBe(50);
});
test('stays inside the range the option accepts', () => {
expect(stepFontSize(MAX_FONT_SIZE, 5)).toBe(MAX_FONT_SIZE);
expect(stepFontSize(MIN_FONT_SIZE, -5)).toBe(MIN_FONT_SIZE);
});
});
describe('clampSpeed()', () => {
test('bounds the speed to the usable range', () => {
expect(clampSpeed(MIN_SPEED - 10)).toBe(MIN_SPEED);
expect(clampSpeed(MAX_SPEED + 10)).toBe(MAX_SPEED);
expect(clampSpeed(30)).toBe(30);
});
test('falls back to the minimum for a non number, rather than stalling at zero', () => {
expect(clampSpeed(Number.NaN)).toBe(MIN_SPEED);
});
});
describe('frameDeltaSeconds()', () => {
test('clamps a long gap so returning to a background tab cannot teleport the script', () => {
// requestAnimationFrame is suspended while hidden, so the first timestamp
// back can be minutes stale
expect(frameDeltaSeconds(1000 / 60)).toBeCloseTo(1 / 60, 6);
expect(frameDeltaSeconds(60_000)).toBe(MAX_FRAME_DELTA_MS / 1000);
});
test('ignores nonsense deltas', () => {
expect(frameDeltaSeconds(-5)).toBe(0);
expect(frameDeltaSeconds(Number.NaN)).toBe(0);
});
});
describe('advance()', () => {
test('accumulates sub-pixel movement without losing any to rounding', () => {
// 32px/s sampled at 60fps is 0.53px a frame: rounding each frame would stall
const pxPerSecond = 32;
const frame = 1 / 60;
let position = 0;
for (let i = 0; i < 100; i += 1) {
position = advance(position, pxPerSecond, frame, 10_000).position;
}
expect(position).toBeCloseTo((pxPerSecond * 100) / 60, 5);
});
test('reports the end of the script once the bottom is reached', () => {
expect(advance(499, 100, 1, 500).atEnd).toBe(true);
expect(advance(100, 100, 1, 500).atEnd).toBe(false);
});
test('reports the end without bounding the position, which the caller owns', () => {
// the loop has to bound the position anyway, for nudges and for a document
// which shrank, so this does not do it a second time
expect(advance(490, 100, 1, 500)).toEqual({ position: 590, atEnd: true });
});
test('never reports the end for a document which does not overflow', () => {
// it may simply not have been measured yet, and stopping playback on an
// unmeasured document would look like the prompter refusing to run
expect(advance(0, 100, 1, 0).atEnd).toBe(false);
});
});
describe('easeCatchUp()', () => {
test('approaches the target monotonically from either side', () => {
let fromAbove = 500;
let fromBelow = 0;
let previousAbove = 501;
let previousBelow = -1;
for (let i = 0; i < 20; i += 1) {
fromBelow = easeCatchUp(fromBelow, 500, 1 / 60);
fromAbove = easeCatchUp(fromAbove, 0, 1 / 60);
expect(fromBelow).toBeGreaterThan(previousBelow);
expect(fromBelow).toBeLessThanOrEqual(500);
expect(fromAbove).toBeLessThan(previousAbove);
expect(fromAbove).toBeGreaterThanOrEqual(0);
previousBelow = fromBelow;
previousAbove = fromAbove;
}
});
test('settles exactly on the target instead of creeping forever', () => {
let position = 0;
for (let i = 0; i < 300; i += 1) {
position = easeCatchUp(position, 500, 1 / 60);
}
expect(position).toBe(500);
});
test('is framerate independent, so a jump takes the same time on any display', () => {
let atSixty = 0;
for (let i = 0; i < 60; i += 1) {
atSixty = easeCatchUp(atSixty, 1000, 1 / 60);
}
let atThirty = 0;
for (let i = 0; i < 30; i += 1) {
atThirty = easeCatchUp(atThirty, 1000, 1 / 30);
}
expect(atSixty).toBeCloseTo(atThirty, 3);
});
});
@@ -1,218 +0,0 @@
import { type CustomFields, type OntimeEntry, type Rundown, SupportedEntry } from 'ontime-types';
import type { RundownMetadata, RundownMetadataObject } from '../../../common/utils/rundownMetadata';
import { buildScript, composeFlip } from '../teleprompter.utils';
function makeEvent(id: string, overrides: Partial<OntimeEntry> = {}): OntimeEntry {
return {
type: SupportedEntry.Event,
id,
cue: id.toUpperCase(),
title: `Title ${id}`,
note: `Note ${id}`,
skip: false,
custom: { script: `Script ${id}` },
parent: null,
...overrides,
} as OntimeEntry;
}
function makeGroup(id: string, title: string, entries: string[]): OntimeEntry {
return { type: SupportedEntry.Group, id, title, entries } as OntimeEntry;
}
function makeMetadata(overrides: Partial<RundownMetadata> = {}): RundownMetadata {
return { isPast: false, isLoaded: false, groupId: null, ...overrides } as RundownMetadata;
}
function makeRundown(entries: OntimeEntry[], flatOrder?: string[]): Rundown {
return {
id: 'default',
title: 'test',
order: flatOrder ?? entries.map((entry) => entry.id),
flatOrder: flatOrder ?? entries.map((entry) => entry.id),
entries: Object.fromEntries(entries.map((entry) => [entry.id, entry])),
revision: 1,
};
}
const customFields: CustomFields = {
script: { type: 'text', colour: '', label: 'Script' },
poster: { type: 'image', colour: '', label: 'Poster' },
};
const defaultOptions = {
scriptSource: 'custom-script',
heading: 'title' as const,
hideEmpty: true,
showGroups: true,
};
function metadataFor(ids: string[], overrides: Record<string, Partial<RundownMetadata>> = {}): RundownMetadataObject {
return Object.fromEntries(ids.map((id) => [id, makeMetadata(overrides[id])]));
}
describe('buildScript()', () => {
test('resolves the script from the selected custom field, in rundown order', () => {
const rundown = makeRundown([makeEvent('a'), makeEvent('b')]);
const blocks = buildScript(rundown, metadataFor(['a', 'b']), customFields, defaultOptions);
expect(blocks).toHaveLength(2);
expect(blocks.map((block) => block.id)).toEqual(['a', 'b']);
expect(blocks[0].text).toBe('Script a');
});
test('returns nothing when no script source is selected', () => {
const rundown = makeRundown([makeEvent('a')]);
expect(buildScript(rundown, metadataFor(['a']), customFields, { ...defaultOptions, scriptSource: 'none' })).toEqual(
[],
);
});
test('refuses an image custom field, which the select filters but the URL does not', () => {
const rundown = makeRundown([makeEvent('a', { custom: { poster: 'https://example.com/a.png' } })]);
const blocks = buildScript(rundown, metadataFor(['a']), customFields, {
...defaultOptions,
scriptSource: 'custom-poster',
});
expect(blocks).toEqual([]);
});
test('reads the note and the title as script sources', () => {
const rundown = makeRundown([makeEvent('a')]);
expect(
buildScript(rundown, metadataFor(['a']), customFields, { ...defaultOptions, scriptSource: 'note' })[0].text,
).toBe('Note a');
expect(
buildScript(rundown, metadataFor(['a']), customFields, { ...defaultOptions, scriptSource: 'title' })[0].text,
).toBe('Title a');
});
test('skips entries which are not events', () => {
const rundown = makeRundown([
makeEvent('a'),
{ type: SupportedEntry.Delay, id: 'd', duration: 10 } as OntimeEntry,
{ type: SupportedEntry.Milestone, id: 'm', title: 'milestone' } as OntimeEntry,
]);
const blocks = buildScript(rundown, metadataFor(['a', 'd', 'm']), customFields, defaultOptions);
expect(blocks.map((block) => block.id)).toEqual(['a']);
});
test('skips events flagged as skipped', () => {
const rundown = makeRundown([makeEvent('a', { skip: true }), makeEvent('b')]);
const blocks = buildScript(rundown, metadataFor(['a', 'b']), customFields, defaultOptions);
expect(blocks.map((block) => block.id)).toEqual(['b']);
});
test('hideEmpty drops events with no script text', () => {
const rundown = makeRundown([makeEvent('a', { custom: { script: ' ' } }), makeEvent('b')]);
expect(buildScript(rundown, metadataFor(['a', 'b']), customFields, defaultOptions).map((b) => b.id)).toEqual(['b']);
expect(
buildScript(rundown, metadataFor(['a', 'b']), customFields, { ...defaultOptions, hideEmpty: false }).map(
(b) => b.id,
),
).toEqual(['a', 'b']);
});
test('marks the block belonging to the loaded event', () => {
const rundown = makeRundown([makeEvent('a'), makeEvent('b')]);
const metadata = metadataFor(['a', 'b'], { b: { isLoaded: true } });
const blocks = buildScript(rundown, metadata, customFields, defaultOptions);
expect(blocks.map((block) => block.isLoaded)).toEqual([false, true]);
});
test('emits a group title once, on the first block of the group', () => {
const rundown = makeRundown(
[makeGroup('g', 'Morning session', ['a', 'b']), makeEvent('a'), makeEvent('b')],
['g', 'a', 'b'],
);
const metadata = metadataFor(['g', 'a', 'b'], { a: { groupId: 'g' }, b: { groupId: 'g' } });
const blocks = buildScript(rundown, metadata, customFields, defaultOptions);
expect(blocks.map((block) => block.groupTitle)).toEqual(['Morning session', null]);
});
test('emits each group title as the script moves between groups', () => {
const rundown = makeRundown(
[
makeGroup('g1', 'Morning session', ['a']),
makeEvent('a'),
makeGroup('g2', 'Afternoon session', ['b']),
makeEvent('b'),
],
['g1', 'a', 'g2', 'b'],
);
const metadata = metadataFor(['g1', 'a', 'g2', 'b'], { a: { groupId: 'g1' }, b: { groupId: 'g2' } });
const blocks = buildScript(rundown, metadata, customFields, defaultOptions);
expect(blocks.map((block) => block.groupTitle)).toEqual(['Morning session', 'Afternoon session']);
});
test('repeats a group title when the script returns to it after an ungrouped event', () => {
// the reader has lost the context by then, so naming the group again is right
const rundown = makeRundown(
[makeGroup('g', 'Morning session', ['a', 'c']), makeEvent('a'), makeEvent('b'), makeEvent('c')],
['g', 'a', 'b', 'c'],
);
const metadata = metadataFor(['g', 'a', 'b', 'c'], { a: { groupId: 'g' }, c: { groupId: 'g' } });
const blocks = buildScript(rundown, metadata, customFields, defaultOptions);
expect(blocks.map((block) => block.groupTitle)).toEqual(['Morning session', null, 'Morning session']);
});
test('does not emit group titles when they are turned off', () => {
const rundown = makeRundown([makeGroup('g', 'Morning session', ['a']), makeEvent('a')], ['g', 'a']);
const metadata = metadataFor(['g', 'a'], { a: { groupId: 'g' } });
const blocks = buildScript(rundown, metadata, customFields, { ...defaultOptions, showGroups: false });
expect(blocks[0].groupTitle).toBeNull();
});
describe('headings', () => {
const rundown = makeRundown([makeEvent('a')]);
const metadata = metadataFor(['a']);
test('shows the title, the cue, both, or nothing', () => {
expect(buildScript(rundown, metadata, customFields, { ...defaultOptions, heading: 'title' })[0].heading).toBe(
'Title a',
);
expect(buildScript(rundown, metadata, customFields, { ...defaultOptions, heading: 'cue' })[0].heading).toBe('A');
expect(buildScript(rundown, metadata, customFields, { ...defaultOptions, heading: 'both' })[0].heading).toBe(
'A · Title a',
);
expect(buildScript(rundown, metadata, customFields, { ...defaultOptions, heading: 'none' })[0].heading).toBe('');
});
test('leaves no dangling separator when an event has no cue', () => {
const noCue = makeRundown([makeEvent('a', { cue: '' })]);
expect(buildScript(noCue, metadata, customFields, { ...defaultOptions, heading: 'both' })[0].heading).toBe(
'Title a',
);
});
});
});
describe('composeFlip()', () => {
test('passes the per view flips through when Flip Screen is off', () => {
expect(composeFlip(false, false, false)).toEqual({ flipH: false, flipV: false });
expect(composeFlip(true, false, false)).toEqual({ flipH: true, flipV: false });
expect(composeFlip(false, true, false)).toEqual({ flipH: false, flipV: true });
});
test('Flip Screen alone flips both axes, matching rotate(180deg) in every other view', () => {
expect(composeFlip(false, false, true)).toEqual({ flipH: true, flipV: true });
});
test('a horizontal flip and Flip Screen leave only the vertical axis flipped', () => {
// scale(-1, 1) composed with scale(-1, -1) is scale(1, -1)
expect(composeFlip(true, false, true)).toEqual({ flipH: false, flipV: true });
});
test('both flips cancel Flip Screen out', () => {
expect(composeFlip(true, true, true)).toEqual({ flipH: false, flipV: false });
});
});
@@ -1,161 +0,0 @@
import type { MouseEvent } from 'react';
import { IoAdd, IoArrowUp, IoHelpCircleOutline, IoLocate, IoPause, IoPlay, IoRemove } from 'react-icons/io5';
import IconButton from '../../../common/components/buttons/IconButton';
import Tooltip from '../../../common/components/tooltip/Tooltip';
import { useFadeOutOnInactivity } from '../../../common/hooks/useFadeOutOnInactivity';
import { cx } from '../../../common/utils/styleUtils';
import { SPEED_STEP } from '../teleprompter.scroll';
import type { TeleprompterController } from '../teleprompter.types';
interface ControlOverlayProps {
isRunning: boolean;
speed: number;
/** whether the follow can be re-engaged: it is off while already following */
canReengageFollow: boolean;
atEnd: boolean;
controller: TeleprompterController;
onToggleHelp: () => void;
}
/**
* Transport for whoever is not at a keyboard, which on a tablet prompter is
* everyone. The keys remain the primary interface, and the way pedals reach it.
*
* Visibility follows the same rule as the rest of Ontime's floating chrome: it
* fades once the operator stops moving, so it leaves the talent's eyeline
* without needing to know whether the script happens to be rolling.
*
* Every control is present for the life of the view and goes disabled when it
* has nothing to do. A control which comes and goes moves every control after
* it, so the operator reaches for pause during a show and presses whatever slid
* under their finger instead.
*/
export default function ControlOverlay({
isRunning,
speed,
canReengageFollow,
atEnd,
controller,
onToggleHelp,
}: ControlOverlayProps) {
const isActive = useFadeOutOnInactivity(true);
/**
* A pointer press leaves focus on the button, where it would swallow the next
* Space: the operator taps pause, reaches for the pedal, and the script does
* not move. Space belongs to the transport, so the button hands focus back.
* A keyboard activation reports detail 0 and keeps its focus ring, since
* tabbing to a control only to have it drop out from under you is worse.
*/
const press = (action: () => void) => (event: MouseEvent<HTMLButtonElement>) => {
if (event.detail > 0) {
event.currentTarget.blur();
}
action();
};
return (
<div className={cx(['teleprompter__controls', !isActive && 'teleprompter__controls--idle'])}>
<Tooltip
text={isRunning ? 'Pause (Space)' : 'Play (Space)'}
render={
<IconButton
variant='subtle-white'
size='large'
onClick={press(controller.togglePlay)}
data-testid='teleprompter-play'
aria-label={isRunning ? 'Pause' : 'Play'}
/>
}
>
{isRunning ? <IoPause /> : <IoPlay />}
</Tooltip>
<Tooltip
text='Slow down (Left arrow)'
render={
<IconButton
variant='subtle-white'
size='large'
onClick={press(() => controller.changeSpeed(-SPEED_STEP))}
aria-label='Slow down'
/>
}
>
<IoRemove />
</Tooltip>
<div className='teleprompter__speed' data-testid='teleprompter-speed'>
{speed}
<span className='teleprompter__speed-unit'>lpm</span>
</div>
<Tooltip
text='Speed up (Right arrow)'
render={
<IconButton
variant='subtle-white'
size='large'
onClick={press(() => controller.changeSpeed(SPEED_STEP))}
aria-label='Speed up'
/>
}
>
<IoAdd />
</Tooltip>
<Tooltip
text='Rewind to the top (Home)'
render={
<IconButton
variant={atEnd ? 'primary' : 'subtle-white'}
size='large'
onClick={press(() => controller.rewind())}
aria-label='Rewind to top'
/>
}
>
<IoArrowUp />
</Tooltip>
{/*
The operator view solves this with its own FollowButton, a labelled pill
fixed to the bottom centre. That is exactly where this group sits, so the
two would land on top of each other. Same icon and same job, folded into
the transport rather than floating separately.
*/}
<Tooltip
text={
canReengageFollow ? 'Jump back to the loaded event and follow it again (L)' : 'Following the loaded event'
}
render={
<IconButton
variant={canReengageFollow ? 'primary' : 'subtle-white'}
size='large'
disabled={!canReengageFollow}
onClick={press(controller.reengageFollow)}
data-testid='teleprompter-follow'
aria-label='Follow the loaded event'
/>
}
>
<IoLocate />
</Tooltip>
<Tooltip
text='Keyboard shortcuts (?)'
render={
<IconButton
variant='subtle-white'
size='large'
onClick={press(onToggleHelp)}
aria-label='Keyboard shortcuts'
/>
}
>
<IoHelpCircleOutline />
</Tooltip>
</div>
);
}
@@ -1,111 +0,0 @@
import { Dialog } from '@base-ui/react/dialog';
import { IoClose } from 'react-icons/io5';
import IconButton from '../../../common/components/buttons/IconButton';
import {
Combo,
Separator,
Shortcut,
ShortcutGroup,
ShortcutGroups,
} from '../../../common/components/keyboard-shortcuts/KeyboardShortcuts';
interface HelpOverlayProps {
isOpen: boolean;
onClose: () => void;
}
/**
* Built on the shared Dialog rather than a bare overlay so it behaves as a
* modal: focus moves into it, stays inside it, and returns to where it came
* from. Escape closes the dialog instead of rewinding the script, and the
* prompter keymap stands down for as long as it is open.
*
* Built from the same components as the rundown editor's shortcut list, because
* it answers the same question and should not have to be learned twice.
*/
export default function HelpOverlay({ isOpen, onClose }: HelpOverlayProps) {
return (
<Dialog.Root
open={isOpen}
onOpenChange={(open) => {
if (!open) {
onClose();
}
}}
>
<Dialog.Portal>
<Dialog.Backdrop className='teleprompter__help' />
<Dialog.Popup className='teleprompter__help-card'>
<div className='teleprompter__help-header'>
<Dialog.Title className='teleprompter__help-title'>Prompter shortcuts</Dialog.Title>
<IconButton variant='subtle-white' size='large' onClick={onClose} aria-label='Close'>
<IoClose />
</IconButton>
</div>
<ShortcutGroups className='teleprompter__help-groups'>
<ShortcutGroup title='Transport'>
<Shortcut label='Start / stop scrolling'>
<Combo keys={['Space']} />
</Shortcut>
<Shortcut label='Slower / faster'>
<Combo keys={['←']} />
<Separator />
<Combo keys={['→']} />
</Shortcut>
<Shortcut label='Larger speed steps'>
<Combo keys={['Shift', '←']} />
<Separator />
<Combo keys={['Shift', '→']} />
</Shortcut>
</ShortcutGroup>
<ShortcutGroup title='Navigation'>
<Shortcut label='Nudge one line'>
<Combo keys={['↑']} />
<Separator />
<Combo keys={['↓']} />
</Shortcut>
<Shortcut label='Jump a screen'>
<Combo keys={['PgUp']} />
<Separator />
<Combo keys={['PgDn']} />
</Shortcut>
<Shortcut label='Jump to top / end'>
<Combo keys={['Home']} />
<Separator />
<Combo keys={['End']} />
</Shortcut>
<Shortcut label='Rewind and stop'>
<Combo keys={['Esc']} />
</Shortcut>
<Shortcut label='Follow the loaded event again'>
<Combo keys={['L']} />
</Shortcut>
</ShortcutGroup>
<ShortcutGroup title='Display'>
<Shortcut label='Font size'>
<Combo keys={['+']} />
<Separator />
<Combo keys={['-']} />
</Shortcut>
<Shortcut label='Reset font size'>
<Combo keys={['0']} />
</Shortcut>
<Shortcut label='Flip horizontally / vertically'>
<Combo keys={['F']} />
<Separator />
<Combo keys={['Shift', 'F']} />
</Shortcut>
<Shortcut label='Show this list'>
<Combo keys={['?']} />
</Shortcut>
</ShortcutGroup>
</ShortcutGroups>
</Dialog.Popup>
</Dialog.Portal>
</Dialog.Root>
);
}
@@ -1,31 +0,0 @@
interface ReadingLineProps {
showReadingLine: boolean;
}
/**
* The eye-line indicator: it marks where on the screen the talent should read,
* which keeps their eyeline near the lens instead of tracking down the page.
*
* It is a marker beside the text rather than a rule across it. A full width line
* cuts through the words at the one place the eye is trying to rest, and every
* prompter which ships a cue indicator keeps it out of the reading path for the
* same reason. One line tall, so it frames the line being read rather than
* pointing at a position between two of them.
*
* The fade over what has already been read is not optional. Prompter software
* treats the marker and the shading as two halves of one reading guide, and a
* shade which can be switched off is a setting nobody has a reason to change on
* a black on white script.
*/
export default function ReadingLine({ showReadingLine }: ReadingLineProps) {
return (
<>
<div className='teleprompter__dim' />
{showReadingLine && (
<div className='teleprompter__reading-line'>
<span className='teleprompter__reading-marker' />
</div>
)}
</>
);
}
@@ -1,26 +0,0 @@
import type { ScriptBlock } from '../teleprompter.types';
interface ScriptBlockProps {
block: ScriptBlock;
registerRef: (id: string, element: HTMLElement | null) => void;
}
export default function ScriptBlockView({ block, registerRef }: ScriptBlockProps) {
'use memo';
return (
// the id is bound here rather than by the parent so the compiler can keep
// the callback stable: React re-runs a ref callback whenever its identity
// changes, which would unregister every block on every parent render
<section
className='teleprompter__block'
ref={(element) => registerRef(block.id, element)}
data-loaded={block.isLoaded || undefined}
>
{block.groupTitle && <div className='teleprompter__group'>{block.groupTitle}</div>}
{block.heading && <h2 className='teleprompter__heading'>{block.heading}</h2>}
{/* the script is user data, it is rendered as text and never as markup */}
<p className='teleprompter__body'>{block.text}</p>
</section>
);
}
@@ -1,88 +0,0 @@
import { SPEED_STEP, SPEED_STEP_COARSE } from './teleprompter.scroll';
import type { TeleprompterAction } from './teleprompter.types';
/**
* The subset of a KeyboardEvent the keymap needs.
* Declaring it structurally keeps `resolveTeleprompterAction` testable with plain objects.
*/
export type TeleprompterKeyEvent = {
code: string;
key: string;
shiftKey: boolean;
ctrlKey: boolean;
metaKey: boolean;
altKey: boolean;
repeat: boolean;
};
/**
* Maps a keyboard event onto a teleprompter action.
*
* The mapping deliberately matches the convention shared by prompter software
* (space to run, arrows for speed, home to rewind). That convention is also the
* hardware protocol: foot pedals and hand controllers are USB HID devices which
* emit these very keystrokes, so matching it is what makes them work here.
*
* Enter is deliberately left unbound. Space is the run/stop pedal and has to
* reach the prompter wherever focus happens to be, so the transport overlay
* needs one key which still activates whichever control is focused, and Enter
* is it. Binding it here would take the overlay's keyboard operation away.
*
* @returns the action to run, or null when the view should ignore the event
*/
export function resolveTeleprompterAction(event: TeleprompterKeyEvent): TeleprompterAction | null {
// never shadow browser or Ontime shortcuts, notably mod+, which opens the view params
if (event.ctrlKey || event.metaKey || event.altKey) {
return null;
}
switch (event.code) {
case 'Space':
// a held key or a pressed foot pedal repeats: without this guard a single
// press toggles playback dozens of times
return event.repeat ? null : { type: 'togglePlay' };
case 'ArrowDown':
return { type: 'nudge', lines: 1 };
case 'ArrowUp':
return { type: 'nudge', lines: -1 };
case 'PageDown':
return { type: 'page', direction: 1 };
case 'PageUp':
return { type: 'page', direction: -1 };
case 'ArrowRight':
return { type: 'speed', delta: event.shiftKey ? SPEED_STEP_COARSE : SPEED_STEP };
case 'ArrowLeft':
return { type: 'speed', delta: event.shiftKey ? -SPEED_STEP_COARSE : -SPEED_STEP };
case 'Home':
return { type: 'rewind' };
case 'End':
return { type: 'jumpToEnd' };
case 'Escape':
return { type: 'rewindAndPause' };
}
// the remaining bindings are resolved by key rather than code so that they
// survive non-QWERTY layouts
switch (event.key) {
case '?':
return { type: 'toggleHelp' };
case '+':
case '=':
return { type: 'fontSize', steps: 1 };
case '-':
case '_':
return { type: 'fontSize', steps: -1 };
case '0':
return { type: 'resetFontSize' };
}
const lowerKey = event.key.toLowerCase();
if (lowerKey === 'f') {
return { type: 'flip', axis: event.shiftKey ? 'v' : 'h' };
}
if (lowerKey === 'l') {
return { type: 'reengageFollow' };
}
return null;
}
@@ -1,249 +0,0 @@
import type { CustomFields } from 'ontime-types';
import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router';
import { OptionTitle } from '../../common/components/view-params-editor/constants';
import type { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils';
import { PresetContext } from '../../common/context/PresetContext';
import { isStringBoolean } from '../common/viewUtils';
import { DEFAULT_SPEED, MAX_FONT_SIZE, MAX_SPEED, MIN_FONT_SIZE, MIN_SPEED } from './teleprompter.scroll';
import type { HeadingSource, TeleprompterOptions } from './teleprompter.types';
/**
* The values the editor offers are also the values the parser accepts, so the
* allow lists are derived rather than written out again. Listed twice, adding a
* value to the select would leave the parser rejecting it and quietly falling
* back to the default.
*/
const headingOptions: { value: HeadingSource; label: string }[] = [
{ value: 'title', label: 'Title' },
{ value: 'cue', label: 'Cue' },
{ value: 'both', label: 'Cue and title' },
{ value: 'none', label: 'None' },
];
const headingSources = headingOptions.map((option) => option.value);
/**
* Defaults and bounds for every option, in one place.
*
* The params editor renders these and the parser falls back to them, so they
* have to agree. Kept apart, they drift silently: the editor would show one
* value while the view used another, with nothing failing to say so.
*/
export const defaults = {
script: 'none',
heading: 'title' as HeadingSource,
hideEmpty: true,
showGroups: true,
speed: DEFAULT_SPEED,
followLoaded: true,
fontSize: 52,
lineHeight: 1.3,
textWidth: 80,
readingLine: true,
readingLinePos: 25,
flipH: false,
flipV: false,
};
/** ranges for the numeric options, applied when parsing */
const bounds = {
speed: [MIN_SPEED, MAX_SPEED],
fontSize: [MIN_FONT_SIZE, MAX_FONT_SIZE],
lineHeight: [1, 4],
textWidth: [20, 100],
readingLinePos: [0, 100],
} as const;
export const getTeleprompterOptions = (customFields: CustomFields): ViewOption[] => {
const scriptOptions = makeOptionsFromCustomFields(customFields, [
{ value: 'none', label: 'None' },
{ value: 'note', label: 'Note' },
{ value: 'title', label: 'Title' },
]);
return [
{
title: OptionTitle.DataSources,
collapsible: true,
options: [
{
id: 'script',
title: 'Script',
description: 'Select the data source which holds the script to read',
type: 'option',
values: scriptOptions,
defaultValue: defaults.script,
},
{
id: 'heading',
title: 'Segment heading',
description: 'What to show above each segment of the script',
type: 'option',
values: headingOptions,
defaultValue: defaults.heading,
},
],
},
{
title: OptionTitle.BehaviourOptions,
collapsible: true,
options: [
{
id: 'speed',
title: 'Speed',
description: `Scroll speed in lines per minute (${MIN_SPEED}-${MAX_SPEED}). Adjustable live with the arrow keys`,
type: 'number',
defaultValue: defaults.speed,
},
{
id: 'followLoaded',
title: 'Follow loaded event',
description: 'Scroll to the segment of the loaded event. Scrolling by hand releases the follow',
type: 'boolean',
defaultValue: defaults.followLoaded,
},
],
},
{
title: OptionTitle.ElementVisibility,
collapsible: true,
options: [
{
id: 'hideEmpty',
title: 'Hide events without a script',
description: 'Prevents showing headings for events which have no script text',
type: 'boolean',
defaultValue: defaults.hideEmpty,
},
{
id: 'showGroups',
title: 'Show group names',
description: 'Shows the group name when the script moves into a new group',
type: 'boolean',
defaultValue: defaults.showGroups,
},
],
},
{
title: OptionTitle.StyleOverride,
collapsible: true,
options: [
{
id: 'fontSize',
title: 'Font size',
description: 'Base font size in pixels. Adjustable live with the + and - keys',
type: 'number',
defaultValue: defaults.fontSize,
},
{
id: 'lineHeight',
title: 'Line height',
description: 'Spacing between lines, as a multiple of the font size',
type: 'number',
defaultValue: defaults.lineHeight,
},
{
id: 'textWidth',
title: 'Text width',
description: 'Width of the text column as a percentage of the screen. Narrower means less eye movement',
type: 'number',
defaultValue: defaults.textWidth,
},
{
id: 'readingLine',
title: 'Reading line',
description: 'Shows a marker beside the line which should be read',
type: 'boolean',
defaultValue: defaults.readingLine,
},
{
id: 'readingLinePos',
title: 'Reading line position',
description: 'Position of the reading line as a percentage from the top of the screen',
type: 'number',
defaultValue: defaults.readingLinePos,
},
{
id: 'flipH',
title: 'Flip horizontally',
description:
'Mirrors the view horizontally, which is what a beam splitter rig needs. Toggled live with F. Flip Screen in the navigation menu flips both axes at once, which is a rotation rather than a mirror',
type: 'boolean',
defaultValue: defaults.flipH,
},
{
id: 'flipV',
title: 'Flip vertically',
description: 'Mirrors the view vertically. Note this also moves the reading line. Toggled live with Shift+F',
type: 'boolean',
defaultValue: defaults.flipV,
},
],
},
];
};
/**
* Parses a numeric param, guarding against the Number(null) === 0 trap.
*/
function toNumber(value: string | null, [min, max]: readonly [number, number], fallback: number): number {
if (value === null || value === '') return fallback;
const parsed = Number(value);
if (!Number.isFinite(parsed)) return fallback;
return Math.min(Math.max(parsed, min), max);
}
/** an absent param takes the default, which for some options is true */
function toBoolean(value: string | null, fallback: boolean): boolean {
return value === null ? fallback : isStringBoolean(value);
}
function toEnum<T extends string>(value: string | null, allowed: readonly T[], fallback: T): T {
return allowed.includes(value as T) ? (value as T) : fallback;
}
/**
* Utility extract the view options from URL Params
* the names and fallbacks are manually matched with getTeleprompterOptions
*/
export function getOptionsFromParams(
searchParams: URLSearchParams,
defaultValues?: URLSearchParams,
): TeleprompterOptions {
// Helper to get value from either source, prioritizing defaultValues
const getValue = (key: string) => defaultValues?.get(key) ?? searchParams.get(key);
return {
scriptSource: getValue('script') ?? defaults.script,
heading: toEnum(getValue('heading'), headingSources, defaults.heading),
hideEmpty: toBoolean(getValue('hideEmpty'), defaults.hideEmpty),
showGroups: toBoolean(getValue('showGroups'), defaults.showGroups),
speed: toNumber(getValue('speed'), bounds.speed, defaults.speed),
followLoaded: toBoolean(getValue('followLoaded'), defaults.followLoaded),
fontSize: toNumber(getValue('fontSize'), bounds.fontSize, defaults.fontSize),
lineHeight: toNumber(getValue('lineHeight'), bounds.lineHeight, defaults.lineHeight),
textWidth: toNumber(getValue('textWidth'), bounds.textWidth, defaults.textWidth),
readingLine: toBoolean(getValue('readingLine'), defaults.readingLine),
readingLinePos: toNumber(getValue('readingLinePos'), bounds.readingLinePos, defaults.readingLinePos),
flipH: toBoolean(getValue('flipH'), defaults.flipH),
flipV: toBoolean(getValue('flipV'), defaults.flipV),
};
}
/**
* Hook exposes the teleprompter view options
*/
export function useTeleprompterOptions(): TeleprompterOptions {
const [searchParams] = useSearchParams();
const maybePreset = use(PresetContext);
return useMemo(() => {
const defaultValues = maybePreset ? new URLSearchParams(maybePreset.search) : undefined;
return getOptionsFromParams(searchParams, defaultValues);
}, [maybePreset, searchParams]);
}
@@ -1,121 +0,0 @@
/**
* Pure scroll arithmetic for the teleprompter.
*
* Everything here is side effect free so it can be unit tested without a DOM.
* The hook that owns the requestAnimationFrame loop is the only caller.
*/
/**
* Lines per minute.
*
* The default is calibrated against the reading rate rather than picked for
* feel: broadcast presenters read at 140-160 words per minute and conference
* talent slower still, and at the default size a line carries around ten words.
* Fourteen lines per minute measures at 136 wpm, a presenter's pace rather than
* a news reader's. The ceiling is set where the text stops being readable at
* all, not at the fastest the loop can physically scroll, so the arrow keys
* stay useful across their whole range.
*/
export const MIN_SPEED = 1;
export const MAX_SPEED = 40;
export const DEFAULT_SPEED = 14;
/** how much one speed adjustment moves, shared by the keymap and the overlay */
export const SPEED_STEP = 1;
export const SPEED_STEP_COARSE = 5;
/**
* Font size in pixels, the same range the view option accepts.
*
* The +/- keys move it by a ratio rather than a fixed number of pixels, so a
* press is the same visual step whether the talent is reading at 30px on a
* laptop or 200px through a beam splitter.
*/
export const MIN_FONT_SIZE = 12;
export const MAX_FONT_SIZE = 400;
const FONT_SIZE_STEP_RATIO = 1.1;
/** @param steps how many presses to apply, negative to shrink */
export function stepFontSize(current: number, steps: number): number {
return clamp(Math.round(current * FONT_SIZE_STEP_RATIO ** steps), MIN_FONT_SIZE, MAX_FONT_SIZE);
}
/**
* requestAnimationFrame is suspended in background tabs, so the timestamp can
* jump by minutes when the view becomes visible again.
* We clamp the frame delta so a resume can never teleport the script.
*/
export const MAX_FRAME_DELTA_MS = 100;
/** how aggressively an eased jump converges on its target, per second */
const CATCH_UP_RATE = 8;
/** below this distance an eased jump is considered arrived */
const CATCH_UP_EPSILON = 0.5;
export function clamp(value: number, min: number, max: number): number {
if (Number.isNaN(value)) return min;
return Math.min(Math.max(value, min), max);
}
export function clampSpeed(value: number): number {
return clamp(value, MIN_SPEED, MAX_SPEED);
}
/**
* Converts a speed in lines per minute into pixels per second.
* Lines per minute is the unit prompter operators think in, and it is
* independent of font size, which is why it is what we persist.
*/
export function linesPerMinuteToPxPerSecond(linesPerMinute: number, lineHeightPx: number): number {
return (linesPerMinute / 60) * lineHeightPx;
}
/**
* Clamps a raw frame delta and converts it to seconds.
* @param deltaMs milliseconds since the previous frame
*/
export function frameDeltaSeconds(deltaMs: number): number {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return 0;
return Math.min(deltaMs, MAX_FRAME_DELTA_MS) / 1000;
}
/**
* Advances the scroll position at a constant rate, and reports having reached
* the bottom.
*
* The position is kept as a float by the caller: at readable prompter speeds the
* per frame delta is well under a pixel, so rounding on every frame would stall
* the scroll entirely. We return the exact float and let the DOM round on write.
*
* Deliberately does not bound the result. The caller has to bound the position
* anyway, because a nudge or a shrinking document can put it out of range on
* frames this never runs on, and one clamp in one place is easier to trust than
* the same rule applied twice on one of the paths.
*/
export function advance(
position: number,
pxPerSecond: number,
deltaSeconds: number,
maxScroll: number,
): { position: number; atEnd: boolean } {
const next = position + pxPerSecond * deltaSeconds;
// a document which does not overflow is never "at the end": it may simply not
// have been measured yet, and stopping playback on that would be wrong
return { position: next, atEnd: maxScroll > 0 && next >= maxScroll };
}
/**
* Moves `current` towards `target` with an exponential ease.
*
* Framerate independent: the same wall clock duration produces the same curve
* regardless of how many frames it was sampled over.
*
* Snaps to the target once it is close enough rather than approaching it
* forever, so the caller can treat equality with the target as arrival.
*/
export function easeCatchUp(current: number, target: number, deltaSeconds: number): number {
if (deltaSeconds <= 0) return current;
const next = target + (current - target) * Math.exp(-CATCH_UP_RATE * deltaSeconds);
return Math.abs(next - target) < CATCH_UP_EPSILON ? target : next;
}
@@ -1,65 +0,0 @@
import type { MaybeString } from 'ontime-types';
/** What the per-event heading shows above each script block */
export type HeadingSource = 'none' | 'title' | 'cue' | 'both';
/** A single readable segment of the prompter document */
export type ScriptBlock = {
/** entry id, used as the follow target and the react key */
id: string;
/** heading text, already resolved from the heading option. Empty string when suppressed */
heading: string;
/** the script itself */
text: string;
/** group title, present only on the first block of a new group */
groupTitle: MaybeString;
/** the block belongs to the currently loaded event */
isLoaded: boolean;
};
export type TeleprompterOptions = {
/** 'custom-<key>' | 'note' | 'title', or 'none' when nothing is selected */
scriptSource: string;
heading: HeadingSource;
hideEmpty: boolean;
showGroups: boolean;
/** lines per minute */
speed: number;
followLoaded: boolean;
fontSize: number;
lineHeight: number;
textWidth: number;
readingLine: boolean;
readingLinePos: number;
flipH: boolean;
flipV: boolean;
};
/**
* A discrete intent resolved from a keyboard event.
* Kept as data so the keymap can be unit tested without a DOM.
*/
export type TeleprompterAction =
| { type: 'togglePlay' }
| { type: 'nudge'; lines: number }
| { type: 'page'; direction: 1 | -1 }
| { type: 'speed'; delta: number }
| { type: 'rewind' }
| { type: 'rewindAndPause' }
| { type: 'jumpToEnd' }
| { type: 'flip'; axis: 'h' | 'v' }
| { type: 'fontSize'; steps: number }
| { type: 'resetFontSize' }
| { type: 'reengageFollow' }
| { type: 'toggleHelp' };
/** The imperative surface the overlay and the key handler drive */
export type TeleprompterController = {
togglePlay: () => void;
nudge: (lines: number) => void;
page: (direction: 1 | -1) => void;
changeSpeed: (delta: number) => void;
rewind: (alsoPause?: boolean) => void;
jumpToEnd: () => void;
reengageFollow: () => void;
};
@@ -1,106 +0,0 @@
import { type CustomFields, isOntimeEvent, isOntimeGroup, type MaybeString, type Rundown } from 'ontime-types';
import type { RundownMetadataObject } from '../../common/utils/rundownMetadata';
import { getPropertyValue } from '../common/viewUtils';
import type { HeadingSource, ScriptBlock, TeleprompterOptions } from './teleprompter.types';
type BuildScriptOptions = Pick<TeleprompterOptions, 'scriptSource' | 'heading' | 'hideEmpty' | 'showGroups'>;
/**
* Resolves the heading shown above a script block.
*/
function makeHeading(source: HeadingSource, cue: string, title: string): string {
switch (source) {
case 'cue':
return cue;
case 'title':
return title;
case 'both':
return [cue, title].filter(Boolean).join(' · ');
case 'none':
return '';
}
}
/**
* An image custom field holds a URL, which is meaningless to read aloud.
* The params editor filters these out of the select, but the URL can be hand typed.
*/
function isReadableSource(scriptSource: string, customFields: CustomFields): boolean {
if (!scriptSource.startsWith('custom-')) {
return true;
}
const key = scriptSource.slice('custom-'.length);
return customFields[key]?.type === 'text';
}
/**
* Flattens the rundown into the continuous document the prompter scrolls through.
*
* We iterate flatOrder so that events nested in groups arrive in reading order
* without a second pass.
*/
export function buildScript(
rundown: Rundown,
rundownMetadata: RundownMetadataObject,
customFields: CustomFields,
options: BuildScriptOptions,
): ScriptBlock[] {
const { scriptSource, heading, hideEmpty, showGroups } = options;
if (scriptSource === 'none' || !isReadableSource(scriptSource, customFields)) {
return [];
}
const blocks: ScriptBlock[] = [];
let lastGroupId: MaybeString = null;
for (const id of rundown.flatOrder) {
const entry = rundown.entries[id];
if (!isOntimeEvent(entry) || entry.skip) {
continue;
}
const metadata = rundownMetadata[id];
const text = getPropertyValue(entry, scriptSource, rundown.entries)?.trim() ?? '';
if (hideEmpty && !text) {
continue;
}
// a group title is emitted once, on the first block that belongs to it
const groupId = metadata?.groupId ?? null;
let groupTitle: MaybeString = null;
if (showGroups && groupId && groupId !== lastGroupId) {
const group = rundown.entries[groupId];
groupTitle = isOntimeGroup(group) ? group.title : null;
}
lastGroupId = groupId;
blocks.push({
id,
heading: makeHeading(heading, entry.cue, entry.title),
text,
groupTitle,
isLoaded: Boolean(metadata?.isLoaded),
});
}
return blocks;
}
/**
* Folds Ontime's global "Flip Screen" toggle into the per view flips.
*
* The shared `.mirror` class is `rotate(180deg)`, which is the same matrix as
* `scale(-1, -1)`: a flip on both axes at once. So the global toggle is exactly
* the pair of flips this view already has, and composing them with XOR keeps the
* teleprompter behaving like every other view without two transforms competing
* for the same property.
*
* It cannot replace the per view flips, though. A rotation preserves handedness,
* so it never yields the mirror image a beam splitter reflection needs; only a
* single axis flip does. That is why both exist.
*/
export function composeFlip(flipH: boolean, flipV: boolean, isMirrored: boolean): { flipH: boolean; flipV: boolean } {
return { flipH: flipH !== isMirrored, flipV: flipV !== isMirrored };
}
@@ -1,82 +0,0 @@
import { use, useEffect, useRef } from 'react';
import { useSearchParams } from 'react-router';
import { PresetContext } from '../../common/context/PresetContext';
/**
* How long the controls have to settle before the URL is rewritten.
*
* The arrow keys repeat while held, and a foot pedal held down repeats too, so
* writing on every change would rewrite the URL dozens of times a second for a
* single gesture. The controls keep their own state and stay instant; this only
* records where they came to rest.
*/
const SETTLE_MS = 400;
/**
* Mirrors the live controls into the URL.
*
* Speed, font size and the flips can each be set in two places: the view params
* editor, which writes the query, and the prompter's own keys and buttons, which
* did not. The URL therefore described how the view was opened rather than how
* it had been tuned, so a link copied after setting the prompter up handed the
* next person a differently configured prompter. Reloading lost the setup for
* the same reason.
*
* Writing the same query the params editor writes means the existing features
* built on it — sharing a link, saving a URL preset, redirecting a client — all
* describe what is actually on screen, with no changes of their own.
*
* @param live values to record, keyed by param name. A null value means the
* control is at its default and the param is dropped, which keeps a shared link
* down to the settings which were actually changed.
*/
export function useMirrorLiveParams(live: Record<string, string | null>) {
const [, setSearchParams] = useSearchParams();
const isPreset = Boolean(use(PresetContext));
/**
* The caller passes a fresh object every render, so the effect keys off the
* values instead. Depending on the object itself would restart the timer on
* every unrelated re-render, and the view re-renders on socket traffic, so the
* write would keep being postponed and never land.
*
* The values are then read through a ref rather than closed over, which keeps
* the timeout reading the latest of them and keeps the dependency honest.
*/
const serialised = JSON.stringify(live);
const liveRef = useRef(live);
useEffect(() => {
liveRef.current = live;
});
useEffect(() => {
/**
* A preset's own search string wins over the query when the options are
* read, so a mirrored param would show a value the next load would ignore.
* Better to leave the address bar alone than to write a link which lies.
*/
if (isPreset) return;
const timeout = setTimeout(() => {
setSearchParams(
(current) => {
const next = new URLSearchParams(current);
for (const [key, value] of Object.entries(liveRef.current)) {
if (value === null) {
next.delete(key);
} else {
next.set(key, value);
}
}
return next;
},
// a speed nudge is not a navigation: pushing would bury the operator's
// back button under one entry per keypress
{ replace: true },
);
}, SETTLE_MS);
return () => clearTimeout(timeout);
}, [serialised, isPreset, setSearchParams]);
}
@@ -1,89 +0,0 @@
import { useEffect, useRef } from 'react';
import { useViewParamsEditorStore } from '../../common/components/view-params-editor/viewParamsEditor.store';
import { resolveTeleprompterAction } from './teleprompter.keymap';
import type { TeleprompterAction, TeleprompterController } from './teleprompter.types';
interface UseTeleprompterControlsArgs {
controller: TeleprompterController;
/** the help dialog is modal, so the keymap stands down while it is open */
isHelpOpen: boolean;
onFlip: (axis: 'h' | 'v') => void;
onFontSize: (steps: number) => void;
onResetFontSize: () => void;
onToggleHelp: () => void;
}
const ignoredTags = new Set(['INPUT', 'TEXTAREA', 'SELECT']);
/**
* Binds the prompter keymap.
*
* Space is the universal run/stop key on prompter software and the centre pedal
* of every three pedal controller, so this view cannot leave it to the
* navigation menu. The routes which render the teleprompter pass
* suppressSpaceHotkey to ViewNavigationMenu so the menu stands down.
*/
export function useTeleprompterControls(args: UseTeleprompterControlsArgs) {
// the listener is installed once and reads the current handlers through a ref.
// Updated in an effect rather than during render, which would be a side effect
// in a place React is free to run more than once or throw away
const argsRef = useRef(args);
useEffect(() => {
argsRef.current = args;
});
useEffect(() => {
function applyAction(action: TeleprompterAction) {
const { controller, onFlip, onFontSize, onResetFontSize, onToggleHelp } = argsRef.current;
switch (action.type) {
case 'togglePlay':
return controller.togglePlay();
case 'nudge':
return controller.nudge(action.lines);
case 'page':
return controller.page(action.direction);
case 'speed':
return controller.changeSpeed(action.delta);
case 'rewind':
return controller.rewind();
case 'rewindAndPause':
return controller.rewind(true);
case 'jumpToEnd':
return controller.jumpToEnd();
case 'reengageFollow':
return controller.reengageFollow();
case 'flip':
return onFlip(action.axis);
case 'fontSize':
return onFontSize(action.steps);
case 'resetFontSize':
return onResetFontSize();
case 'toggleHelp':
return onToggleHelp();
}
}
function handleKeyDown(event: KeyboardEvent) {
const target = event.target as HTMLElement | null;
if (target && (ignoredTags.has(target.tagName) || target.isContentEditable)) {
return;
}
// the params editor and the help dialog are modal, they own the keyboard
if (useViewParamsEditorStore.getState().isOpen || argsRef.current.isHelpOpen) {
return;
}
const action = resolveTeleprompterAction(event);
if (!action) return;
// without this the browser also scrolls the container natively and the
// movement is applied twice
event.preventDefault();
applyAction(action);
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
}
@@ -1,26 +0,0 @@
import type { CustomFields, Rundown } from 'ontime-types';
import useCustomFields from '../../common/hooks-query/useCustomFields';
import { useRundownWithMetadata } from '../../common/hooks-query/useRundown';
import type { RundownMetadataObject } from '../../common/utils/rundownMetadata';
import { type ViewData, aggregateQueryStatus } from '../utils/viewLoader.utils';
export interface TeleprompterData {
rundown: Rundown;
rundownMetadata: RundownMetadataObject;
customFields: CustomFields;
}
export function useTeleprompterData(): ViewData<TeleprompterData> {
const { data: rundown, rundownMetadata, status: rundownStatus } = useRundownWithMetadata();
const { data: customFields, status: customFieldStatus } = useCustomFields();
return {
data: {
rundown,
rundownMetadata,
customFields,
},
status: aggregateQueryStatus([rundownStatus, customFieldStatus]),
};
}
@@ -1,364 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { throttle } from '../../common/utils/throttle';
import {
advance,
clamp,
clampSpeed,
easeCatchUp,
frameDeltaSeconds,
linesPerMinuteToPxPerSecond,
} from './teleprompter.scroll';
import type { ScriptBlock, TeleprompterController } from './teleprompter.types';
/** how much of a screen a page jump moves */
const PAGE_FRACTION = 0.85;
/** how long the user has to stop scrolling before we consider the gesture over */
const FOLLOW_LOCK_THROTTLE = 1000;
/**
* How far the scroller may sit from where we left it before we treat the move as
* somebody else's. Comfortably above the rounding the browser applies to the
* fractional value we write, and well below a line.
*/
const EXTERNAL_SCROLL_EPSILON = 2;
interface UseTeleprompterScrollArgs {
initialSpeed: number;
followLoaded: boolean;
selectedEventId: string | null;
/** percentage from the top of the screen */
readingLinePos: number;
/** the rendered document, watched so a follow can retarget once its block exists */
blocks: ScriptBlock[];
}
/**
* Owns the scroll position of the teleprompter.
*
* The single most important rule here is that this hook is the *only* writer of
* scrollTop. Everything else (nudges, page jumps, rewinds, following the loaded
* event) writes a target or a delta into a ref, and the animation frame applies
* it. Mixing in a second writer, such as scrollTo({ behavior: 'smooth' }), makes
* the two fight each other and the scroll visibly stutters. That is also why we
* reuse the arithmetic of useFollowComponent rather than the hook itself.
*
* The position is deliberately held in a ref rather than in state: at readable
* prompter speeds the per frame movement is a fraction of a pixel, so this runs
* every animation frame, and re-rendering a long script that often is not viable.
*/
export function useTeleprompterScroll({
initialSpeed,
followLoaded,
selectedEventId,
readingLinePos,
blocks,
}: UseTeleprompterScrollArgs) {
const scrollerRef = useRef<HTMLDivElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const blockRefs = useRef(new Map<string, HTMLElement>());
/**
* The view renders an empty state instead of the scroller until a script is
* chosen, so these elements can arrive long after mount. Tracking that in
* state is what lets the measuring effect run when they do: keyed only on the
* refs it would have run once, against nothing, and playback would sit dead
* until the page was reloaded.
*/
const [isScrollerMounted, setIsScrollerMounted] = useState(false);
const attachScroller = useCallback((element: HTMLDivElement | null) => {
scrollerRef.current = element;
setIsScrollerMounted(Boolean(element && contentRef.current));
}, []);
const attachContent = useCallback((element: HTMLDivElement | null) => {
contentRef.current = element;
setIsScrollerMounted(Boolean(element && scrollerRef.current));
}, []);
// authoritative, sub-pixel scroll position
const posRef = useRef(0);
const lastTsRef = useRef(0);
const runningRef = useRef(false);
const speedRef = useRef(initialSpeed);
const lineHeightRef = useRef(0);
/** never negative: measure() is the only writer and floors it at zero */
const maxScrollRef = useRef(0);
const catchUpTargetRef = useRef<number | null>(null);
const pendingDeltaRef = useRef(0);
const [isRunning, setIsRunning] = useState(false);
const [speed, setSpeed] = useState(initialSpeed);
const [followLocked, setFollowLocked] = useState(false);
const [atEnd, setAtEnd] = useState(false);
/**
* Advances the scroll by one frame.
*
* Runs on every frame for the lifetime of the view rather than being started
* and stopped around each action. Waking a sleeping loop meant every path that
* could move the script had to remember to do so, and forgetting simply lost
* the action with no error. A frame that has nothing to do costs one pass of
* arithmetic, and the browser suspends the whole loop while the tab is hidden.
*
* Reads and writes only refs, so it never needs rebuilding.
*/
const tick = useCallback((timestamp: number) => {
const el = scrollerRef.current;
// no scroller while the view is showing an empty state
if (!el) return;
/**
* The scroller is no longer where this loop left it, so something else moved
* it: a wheel, a touch drag, a scrollbar, find in page, or the browser
* clamping us because the document got shorter. Whatever the cause, the DOM
* is now the truth and an eased jump in flight is stale.
*
* Detecting divergence covers every one of those without each having to
* announce itself, which is why there is no adopt flag for handlers to set.
*/
if (Math.abs(el.scrollTop - posRef.current) > EXTERNAL_SCROLL_EPSILON) {
posRef.current = el.scrollTop;
catchUpTargetRef.current = null;
}
const deltaSeconds = frameDeltaSeconds(timestamp - lastTsRef.current);
lastTsRef.current = timestamp;
let next = posRef.current;
if (pendingDeltaRef.current !== 0) {
next += pendingDeltaRef.current;
pendingDeltaRef.current = 0;
// an explicit nudge overrides an eased jump in progress
catchUpTargetRef.current = null;
}
if (catchUpTargetRef.current !== null) {
next = easeCatchUp(next, catchUpTargetRef.current, deltaSeconds);
// easeCatchUp snaps to the target once it is close enough, so landing on it
// exactly is the arrival signal and needs no second distance test
if (next === catchUpTargetRef.current) {
catchUpTargetRef.current = null;
}
} else if (runningRef.current) {
const pxPerSecond = linesPerMinuteToPxPerSecond(speedRef.current, lineHeightRef.current);
const result = advance(next, pxPerSecond, deltaSeconds, maxScrollRef.current);
next = result.position;
if (result.atEnd) {
runningRef.current = false;
setIsRunning(false);
setAtEnd(true);
}
}
// the one place the position is bounded, whichever branch produced it
const clamped = clamp(next, 0, maxScrollRef.current);
// touch the DOM only when the position actually moved, so a paused prompter
// costs arithmetic rather than a scroll write on every frame
if (clamped !== posRef.current) {
posRef.current = clamped;
// a fractional value is intentional, the browser rounds it for us while we
// keep the remainder, which is what makes slow speeds move at all
el.scrollTop = clamped;
}
}, []);
useEffect(() => {
lastTsRef.current = performance.now();
let frame = requestAnimationFrame(function loop(timestamp) {
tick(timestamp);
frame = requestAnimationFrame(loop);
});
return () => cancelAnimationFrame(frame);
}, [tick]);
/** recomputes the scroll bounds and the line height the speed is derived from */
const measure = useCallback(() => {
const scroller = scrollerRef.current;
const content = contentRef.current;
if (!scroller || !content) return;
maxScrollRef.current = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
/**
* The line height is read from the content element itself, which is where
* the stylesheet sets it and which the blocks inherit. Sampling a block
* instead would mean finding one, and a lookup that quietly finds nothing
* would leave the speed wrong rather than raise anything.
*/
const computed = getComputedStyle(content);
const parsedLineHeight = Number.parseFloat(computed.lineHeight);
if (Number.isFinite(parsedLineHeight) && parsedLineHeight > 0) {
lineHeightRef.current = parsedLineHeight;
} else {
// line-height computes to the keyword 'normal' when it resolves to nothing
const parsedFontSize = Number.parseFloat(computed.fontSize);
lineHeightRef.current = Number.isFinite(parsedFontSize) ? parsedFontSize * 1.2 : 0;
}
}, []);
// the loop cannot read state, so the live speed is mirrored into a ref
useEffect(() => {
speedRef.current = speed;
}, [speed]);
// the configured speed seeds the live one, and reclaims it whenever the option
// changes. Adjusted during render rather than in an effect so the readout never
// commits the stale value first. It arrives already bounded by the option parser,
// so only the keys and buttons, which add deltas, have to clamp
const [speedFromOption, setSpeedFromOption] = useState(initialSpeed);
if (speedFromOption !== initialSpeed) {
setSpeedFromOption(initialSpeed);
setSpeed(initialSpeed);
}
// the observer covers every reflow that matters, script edits included, so
// nothing else needs to ask for a remeasure
useEffect(() => {
measure();
const scroller = scrollerRef.current;
const content = contentRef.current;
if (!scroller || !content) return;
const observer = new ResizeObserver(() => measure());
observer.observe(scroller);
observer.observe(content);
return () => observer.disconnect();
}, [measure, isScrollerMounted]);
// webfonts land after first paint and reflow the whole document
useEffect(() => {
let cancelled = false;
void document.fonts?.ready.then(() => {
if (!cancelled) measure();
});
return () => {
cancelled = true;
};
}, [measure]);
// requestAnimationFrame is suspended while the tab is hidden, so the first
// timestamp on return is stale. Reset the baseline rather than jump.
useEffect(() => {
const onVisibilityChange = () => {
lastTsRef.current = performance.now();
};
document.addEventListener('visibilitychange', onVisibilityChange);
return () => document.removeEventListener('visibilitychange', onVisibilityChange);
}, []);
/**
* Whether the loaded event currently has a block to scroll to.
*
* The follow watches this rather than the blocks array, because memoisation is
* a performance hint that React is free to discard: keying off array identity
* would let a rebuilt but otherwise identical list re-fire the jump and yank
* the script back while it is being read.
*/
const hasSelectedBlock = selectedEventId !== null && blocks.some((block) => block.id === selectedEventId);
// follow the loaded event
useEffect(() => {
if (!followLoaded || followLocked || !selectedEventId) return;
const scroller = scrollerRef.current;
const target = blockRefs.current.get(selectedEventId);
if (!scroller || !target) return;
// same arithmetic as useFollowComponent, but we hand the result to our own
// loop instead of calling scrollTo
const offset = (scroller.clientHeight * readingLinePos) / 100;
const top = target.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop - offset;
catchUpTargetRef.current = clamp(top, 0, maxScrollRef.current);
setAtEnd(false);
}, [selectedEventId, followLoaded, followLocked, readingLinePos, hasSelectedBlock]);
const lockFollow = useMemo(() => throttle(() => setFollowLocked(true), FOLLOW_LOCK_THROTTLE), []);
/**
* Releases the follow when the operator takes over by hand.
*
* Only deliberate gestures count, which is why this listens for wheel and
* touch rather than the scroll event: scroll also fires for the loop's own
* writes, and following the loaded event would switch itself off on its way
* there. Adopting the resulting position is the tick's job, not this one's.
*/
const handleUserScroll = useCallback(() => {
if (followLoaded) {
lockFollow();
}
}, [followLoaded, lockFollow]);
// entry ids are not guaranteed to be valid CSS selectors, so the follow target
// is looked up through this map rather than with querySelector
const registerBlock = useCallback((id: string, element: HTMLElement | null) => {
if (element) {
blockRefs.current.set(id, element);
} else {
blockRefs.current.delete(id);
}
}, []);
const controller: TeleprompterController = useMemo(() => {
const play = () => {
if (maxScrollRef.current > 0 && posRef.current >= maxScrollRef.current) {
// nothing left to read, rewinding is the only sensible way to resume
return;
}
runningRef.current = true;
setIsRunning(true);
setAtEnd(false);
};
const pause = () => {
runningRef.current = false;
setIsRunning(false);
};
return {
togglePlay: () => (runningRef.current ? pause() : play()),
nudge: (lines: number) => {
pendingDeltaRef.current += lines * lineHeightRef.current;
setAtEnd(false);
},
page: (direction: 1 | -1) => {
const scroller = scrollerRef.current;
if (!scroller) return;
const distance = scroller.clientHeight * PAGE_FRACTION * direction;
catchUpTargetRef.current = clamp(posRef.current + distance, 0, maxScrollRef.current);
setAtEnd(false);
},
changeSpeed: (delta: number) => setSpeed((current) => clampSpeed(current + delta)),
rewind: (alsoPause = false) => {
catchUpTargetRef.current = 0;
if (alsoPause) pause();
setAtEnd(false);
},
jumpToEnd: () => {
catchUpTargetRef.current = maxScrollRef.current;
// the eased branch never reports the end, only the playing one does
if (maxScrollRef.current > 0) {
runningRef.current = false;
setIsRunning(false);
setAtEnd(true);
}
},
reengageFollow: () => setFollowLocked(false),
};
}, []);
return {
scrollerRef: attachScroller,
contentRef: attachContent,
registerBlock,
handleUserScroll,
controller,
isRunning,
speed,
followLocked,
atEnd,
};
}
@@ -151,7 +151,6 @@ function makeViewMenu(clientUrl) {
makeItemOpenInBrowser('Editor', `${clientUrl}/editor`),
makeItemOpenInBrowser('Cuesheet', `${clientUrl}/cuesheet`),
makeItemOpenInBrowser('Operator', `${clientUrl}/op`),
makeItemOpenInBrowser('Teleprompter', `${clientUrl}/teleprompter`),
{ type: 'separator' },
makeItemOpenInBrowser('Timer', `${clientUrl}/timer`),
makeItemOpenInBrowser('Backstage', `${clientUrl}/backstage`),
@@ -0,0 +1,226 @@
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();
});
});
-10
View File
@@ -48,16 +48,6 @@ test.describe('test view navigation feature', () => {
await expect(page).toHaveURL('/timer');
});
test('Teleprompter', async ({ page }) => {
// note: openNavigationMenu presses Space, which the teleprompter claims for
// playback. Every test starts from the timer view, so reaching it is fine,
// but a test which navigates *away* from it must click the nav button.
await openNavigationMenu(page);
await page.getByRole('button', { name: 'Teleprompter' }).click();
page.locator('data-testid=teleprompter-view');
await expect(page).toHaveURL('/teleprompter');
});
test('not-found', async ({ page }) => {
await page.goto('/not-found');
@@ -1,7 +1,5 @@
import { expect, test } from '@playwright/test';
import { seedScript } from '../utils/seedScript';
test('View params configures timer view', async ({ page }) => {
await page.goto('/timer');
@@ -15,29 +13,3 @@ test('View params configures timer view', async ({ page }) => {
await expect(page.getByText('TIME NOW', { exact: true })).not.toBeInViewport();
await expect(page).toHaveURL(/.*hideClock=true/);
});
/**
* An option which defaults to true is the case which breaks: the switch has to
* open on, and switching it off has to reach the URL. A checkbox which is off
* sends nothing at all, so an option in that state is only representable by
* writing it out explicitly.
*/
test('View params can switch off an option which defaults to on', async ({ page }) => {
await seedScript(page);
await page.goto('/teleprompter?script=note');
const readingMarker = page.locator('.teleprompter__reading-marker');
await expect(readingMarker).toBeVisible();
await page.mouse.move(Math.random() * 100, Math.random() * 100);
await page.getByTestId('navigation__toggle-settings').click();
const readingLineSwitch = page.locator('label:has(input[name="readingLine"]) [role="switch"]');
await expect(readingLineSwitch).toHaveAttribute('aria-checked', 'true');
await readingLineSwitch.click();
await page.getByTestId('apply-view-params').click();
await expect(page).toHaveURL(/.*readingLine=false/);
await expect(readingMarker).toHaveCount(0);
});
-196
View File
@@ -1,196 +0,0 @@
import { type Page, expect, test } from '@playwright/test';
import { scriptMarker, seedScript } from '../utils/seedScript';
/**
* The note field is the script source throughout, so that these tests do not
* depend on how custom field keys happen to be spelled.
*/
const teleprompterUrl = '/teleprompter?script=note';
function scroller(page: Page) {
return page.getByTestId('teleprompter-scroller');
}
function scrollTop(page: Page) {
return scroller(page).evaluate((element) => element.scrollTop);
}
test.describe('teleprompter', () => {
test.beforeEach(async ({ page }) => {
await seedScript(page);
});
test('shows the script from the selected source', async ({ page }) => {
await page.goto(teleprompterUrl);
await expect(page.getByTestId('teleprompter-view')).toBeVisible();
await expect(scroller(page)).toBeVisible();
await expect(page.getByText(scriptMarker).first()).toBeVisible();
});
test('asks for a script source when none is selected', async ({ page }) => {
await page.goto('/teleprompter');
await expect(page.getByTestId('teleprompter-view')).toBeVisible();
await expect(page.getByText('Select which field holds the script in the view options')).toBeVisible();
});
test('space starts and stops the scroll', async ({ page }) => {
await page.goto(teleprompterUrl);
await expect(scroller(page)).toBeVisible();
expect(await scrollTop(page)).toBe(0);
await page.keyboard.press('Space');
await expect.poll(() => scrollTop(page)).toBeGreaterThan(0);
await page.keyboard.press('Space');
await page.waitForTimeout(200);
const afterPause = await scrollTop(page);
await page.waitForTimeout(500);
expect(await scrollTop(page)).toBe(afterPause);
});
test('space drives playback instead of opening the navigation menu', async ({ page }) => {
// the navigation menu binds Space globally, the teleprompter claims it back
await page.goto('/timer');
await expect(page.locator('data-testid=timer-view')).toBeVisible();
await page.keyboard.press('Space');
await expect(page.getByRole('dialog')).toBeVisible();
await page.goto(teleprompterUrl);
await expect(scroller(page)).toBeVisible();
await page.keyboard.press('Space');
await expect(page.getByRole('dialog')).toHaveCount(0);
// and the claim is released once the view goes away
await page.goto('/timer');
await expect(page.locator('data-testid=timer-view')).toBeVisible();
await page.keyboard.press('Space');
await expect(page.getByRole('dialog')).toBeVisible();
});
test('arrow keys nudge and home rewinds', async ({ page }) => {
await page.goto(teleprompterUrl);
await expect(scroller(page)).toBeVisible();
await page.keyboard.press('ArrowDown');
await page.keyboard.press('ArrowDown');
await expect.poll(() => scrollTop(page)).toBeGreaterThan(0);
// the rewind eases rather than snapping, so poll rather than guess a duration
await page.keyboard.press('Home');
await expect.poll(() => scrollTop(page)).toBe(0);
});
test('keeps a scroll it did not make itself', async ({ page }) => {
// the animation frame loop runs for the lifetime of the view, so it has to
// notice when something else moves the scroller, otherwise a scrollbar drag
// or find in page would be snapped back on the next frame
await page.goto(teleprompterUrl);
await expect(scroller(page)).toBeVisible();
await scroller(page).evaluate((element) => {
element.scrollTop = 400;
});
await page.waitForTimeout(500);
expect(await scrollTop(page)).toBe(400);
});
test('arrow keys change the speed', async ({ page }) => {
await page.goto(teleprompterUrl);
await expect(scroller(page)).toBeVisible();
const readout = page.getByTestId('teleprompter-speed');
const before = Number(await readout.innerText().then((text) => text.replace(/\D/g, '')));
await page.keyboard.press('ArrowRight');
const faster = Number(await readout.innerText().then((text) => text.replace(/\D/g, '')));
expect(faster).toBeGreaterThan(before);
await page.keyboard.press('ArrowLeft');
const slower = Number(await readout.innerText().then((text) => text.replace(/\D/g, '')));
expect(slower).toBe(before);
});
test('keeps every transport control in place', async ({ page }) => {
// a control which appears mid show moves the ones after it, and the operator
// reaches for pause and presses whatever slid under their finger instead
await page.goto(teleprompterUrl);
await expect(scroller(page)).toBeVisible();
const controls = page.locator('.teleprompter__controls button');
const follow = page.getByTestId('teleprompter-follow');
await expect(controls).toHaveCount(6);
await expect(follow).toBeVisible();
await expect(follow).toBeDisabled();
// taking over by hand offers the follow back, without restacking the row
await page.mouse.move(640, 300);
await page.mouse.wheel(0, 200);
await expect(controls).toHaveCount(6);
await expect(follow).toBeVisible();
});
test('records the live controls in the url so a tuned view can be shared', async ({ page }) => {
await page.goto(teleprompterUrl);
await expect(scroller(page)).toBeVisible();
// a view left at its defaults should not litter the query
await expect(page).toHaveURL(/\?script=note$/);
await page.keyboard.press('ArrowRight');
await page.keyboard.press('f');
await expect(page).toHaveURL(/speed=/);
await expect(page).toHaveURL(/flipH=true/);
// the tuned url has to reproduce the prompter, which is the point of writing it
const shared = page.url();
const readSpeed = () =>
page
.getByTestId('teleprompter-speed')
.innerText()
.then((text) => text.replace(/\D/g, ''));
const tunedSpeed = await readSpeed();
await page.goto('/teleprompter');
await page.goto(shared);
await expect(scroller(page)).toBeVisible();
expect(await readSpeed()).toBe(tunedSpeed);
// and returning the controls to their defaults clears the query again
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('f');
await expect(page).toHaveURL(/\?script=note$/);
});
test('f mirrors the view for a beam splitter rig', async ({ page }) => {
await page.goto(teleprompterUrl);
await expect(scroller(page)).toBeVisible();
const view = page.getByTestId('teleprompter-view');
await page.keyboard.press('f');
// a horizontal flip is a negative x scale in the computed matrix
const transform = await view.evaluate((element) => getComputedStyle(element).transform);
expect(transform.startsWith('matrix(-1')).toBe(true);
});
test('honours the flip and reading line params', async ({ page }) => {
await page.goto('/teleprompter?script=note&flipV=true&readingLine=false');
const view = page.getByTestId('teleprompter-view');
const transform = await view.evaluate((element) => getComputedStyle(element).transform);
// a vertical flip leaves x positive and makes the y scale negative
expect(transform).toMatch(/^matrix\(1, 0, 0, -1/);
// a boolean which defaults to true has to be switchable off from the url
await expect(page.locator('.teleprompter__reading-marker')).toHaveCount(0);
});
});
-24
View File
@@ -1,24 +0,0 @@
import type { Page } from '@playwright/test';
export const scriptMarker = 'E2E prompter script';
/** long enough that the document scrolls well past a screen */
export const scriptText = `${scriptMarker}. `.repeat(40);
/**
* Puts a known script into whichever rundown happens to be loaded.
*
* Specs which read the rundown cannot rely on the uploaded fixture surviving:
* the suite runs serially and earlier specs add, edit and delete entries, while
* 214 creates a fresh rundown and leaves it loaded. Seeding is idempotent, so
* the rundown gains one event no matter how many tests have run before.
*/
export async function seedScript(page: Page) {
const rundown = await (await page.request.get('/data/rundowns/current')).json();
const alreadySeeded = rundown.flatOrder.some((id: string) => rundown.entries[id]?.note?.startsWith(scriptMarker));
if (alreadySeeded) return;
await page.request.post(`/data/rundowns/${rundown.id}/entry`, {
data: { type: 'event', title: 'Teleprompter e2e', note: scriptText },
});
}
@@ -11,7 +11,6 @@ export enum OntimeView {
StudioClock = 'studio',
Countdown = 'countdown',
ProjectInfo = 'info',
Teleprompter = 'teleprompter',
}
export type OntimeViewPresettable = Exclude<OntimeView, OntimeView.Editor>;
@@ -0,0 +1,89 @@
import { colourToHex, cssOrHexToColour, hexToColour, isLightColour, mixColours } from './colour.utils';
describe('hexToColour()', () => {
it('parses a full length hex', () => {
expect(hexToColour('#ff8800')).toStrictEqual({ red: 255, green: 136, blue: 0, alpha: 1 });
});
it('parses a compressed hex by duplicating each digit', () => {
expect(hexToColour('#f80')).toStrictEqual(hexToColour('#ff8800'));
});
it('parses the alpha channel of a full length hex', () => {
expect(hexToColour('#ff880000')).toStrictEqual({ red: 255, green: 136, blue: 0, alpha: 0 });
expect(hexToColour('#ff8800ff')).toStrictEqual({ red: 255, green: 136, blue: 0, alpha: 1 });
});
it('parses the alpha channel of a compressed hex', () => {
expect(hexToColour('#f800')).toStrictEqual(hexToColour('#ff880000'));
});
it('is case insensitive', () => {
expect(hexToColour('#FF8800')).toStrictEqual(hexToColour('#ff8800'));
});
it('returns null for values which are not a hex colour', () => {
// these are the values which reach us from user input
for (const invalid of ['', 'red', '#', '#ff', '#fffff', '#ffg', 'ff8800']) {
expect(hexToColour(invalid)).toBeNull();
}
});
});
describe('colourToHex()', () => {
it('pads single digit channels', () => {
expect(colourToHex({ red: 0, green: 1, blue: 2, alpha: 1 })).toBe('#000102ff');
});
it('round trips with hexToColour', () => {
for (const hex of ['#000000ff', '#ff8800ff', '#ffffffff', '#12345600']) {
expect(colourToHex(hexToColour(hex)!)).toBe(hex);
}
});
});
describe('cssOrHexToColour()', () => {
it('resolves named css colours', () => {
expect(cssOrHexToColour('red')).toStrictEqual({ red: 255, green: 0, blue: 0, alpha: 1 });
});
it('resolves named css colours regardless of casing', () => {
expect(cssOrHexToColour('CornflowerBlue')).toStrictEqual(cssOrHexToColour('cornflowerblue'));
});
it('delegates hex values to the hex parser', () => {
expect(cssOrHexToColour('#f80')).toStrictEqual(hexToColour('#f80'));
});
it('returns null for an unknown colour name', () => {
expect(cssOrHexToColour('not-a-colour')).toBeNull();
expect(cssOrHexToColour('')).toBeNull();
});
});
describe('mixColours()', () => {
const black = { red: 0, green: 0, blue: 0, alpha: 1 };
const white = { red: 255, green: 255, blue: 255, alpha: 1 };
it('defaults to an even mix', () => {
expect(mixColours(black, white)).toStrictEqual({ red: 128, green: 128, blue: 128, alpha: 1 });
});
it('weights the first colour by the given proportion', () => {
expect(mixColours(black, white, 1)).toStrictEqual({ ...black, alpha: 1 });
expect(mixColours(black, white, 0)).toStrictEqual({ ...white, alpha: 1 });
});
});
describe('isLightColour()', () => {
it('detects light and dark colours', () => {
expect(isLightColour({ red: 255, green: 255, blue: 255, alpha: 1 })).toBe(true);
expect(isLightColour({ red: 0, green: 0, blue: 0, alpha: 1 })).toBe(false);
});
it('weights green most heavily, as per the YIQ calculation', () => {
// pure green is considered light, pure blue is not
expect(isLightColour({ red: 0, green: 255, blue: 0, alpha: 1 })).toBe(true);
expect(isLightColour({ red: 0, green: 0, blue: 255, alpha: 1 })).toBe(false);
});
});