Compare commits

...

13 Commits

Author SHA1 Message Date
Claude e9de1ec19f fix: prevent white background flash and overscroll on Safari iOS
- Set background-color: #101010 on html/body/.App so the Safari iOS
  rubber-band overscroll area is dark instead of white
- Always render body background style in ViewLoader (not just during
  Suspense fallback) so keyColour param and --background-color-override
  propagate to the body for the overscroll region
- Add viewport-fit=cover, apple-mobile-web-app meta tags for proper
  iOS notch/safe-area handling
- Fix manifest.json background_color from #ffffff to #101010
- Align theme_color across both manifests to #101010

https://claude.ai/code/session_016z5vU45pexTdkQV2eHJqh4
2026-05-09 16:35:53 +00:00
Joel Wetzell fe44b33da2 Merge pull request #2078 from cpvalente/macos-icon
refactor: icon compatibility with macos tahoe
2026-05-09 08:15:08 -05:00
Joel Wetzell 22e392ba9d change macOS runner version in build workflow 2026-05-08 09:22:31 -05:00
Joel Wetzell 4997602e9b refactor: icon compatibility with macos tahoe 2026-05-07 20:23:26 -05:00
Joel Wetzell bdb8d4d89a Merge pull request #2077 from cpvalente/update-electron-builder
update electron-builder to v26.9.1
2026-05-07 16:24:39 -05:00
Joel Wetzell b1d5ee12e4 update electron-builder to v26.9.1 2026-05-07 07:50:49 -05:00
Alex Christoffer Rasmussen a5e733246d fix: format clock from preset (#2066)
* fix: format clock from preset

* fix: add to all views

* chore: format

* refactor: return flat value from common.options.ts
2026-05-03 18:43:58 +02:00
Alex Christoffer Rasmussen 1a08b39b8b feat: auto cue re-numbering (#2016)
* feat: update auto cue numbering

* feat: renumber from ui

* refactor: patchEntries is not used

* chore: format

* fix: correct cue at top of group

* fix: handle precision

* refactor dialog

* bump limit for performance time test

* extract type

* add class name to lable

* fix rebase

* refator: extract renumering logic

* chore: comments for getIntegerAndFraction function

* chore: add the for renumber mutation

* fix: fraction match precision

* refactor: small cleanup

* refactor: use more narrow validator

---------

Co-authored-by: alex-Arc <omnivox@LAPTOP-RC5SNBVV.localdomain>
2026-05-03 18:39:00 +02:00
Carlos Valente ba1c3235b3 refactor: improve gsheet import UX 2026-05-03 18:17:17 +02:00
Alex Christoffer Rasmussen 7c1d2f4554 refactor: small cleanups (#2059)
* refactor: remove unneeded async

* chore: add express Router type to all routes

* refactor: don't use index in react key

* refactor: correctly get error message in excel route

* refactor: avoid exporting muteable values
2026-04-26 17:32:50 +02:00
Alex Christoffer Rasmussen 23a44b2f04 refactor: improve the amount of GET requests for translation assets (#2058)
* refactor: replace traslation hook refetch time with stale time

* refactor: make it the service responsebillety to send refetch keys for asset changes
2026-04-14 09:30:27 +02:00
Carlos Valente 2d3c8e7eb2 chore: update CI actions 2026-04-09 21:30:27 +02:00
Carlos Valente 2f138acad7 fix: extracted rundown entry editor shows correct colour 2026-04-09 06:51:18 +02:00
85 changed files with 1159 additions and 851 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
# This step is only needed to setup the permissions to update npm as pnpm will setup the correct node version
- uses: actions/setup-node@v6
+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
CI: ''
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
+12 -12
View File
@@ -7,10 +7,10 @@ on:
jobs:
build_macos:
runs-on: macOS-latest
runs-on: macOS-26
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
@@ -44,7 +44,7 @@ jobs:
timeout-minutes: 60
- name: Upload macOS build artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
if: always()
with:
name: ontime-macos-build
@@ -54,7 +54,7 @@ jobs:
retention-days: 1
- name: Release
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
if: github.ref_type == 'tag'
with:
files: |
@@ -67,14 +67,14 @@ jobs:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
- name: Setup pnpm
uses: pnpm/action-setup@v3
uses: pnpm/action-setup@v4
- name: Install dependencies
run: pnpm install --frozen-lockfile
@@ -83,7 +83,7 @@ jobs:
run: pnpm dist-win
- name: Upload Windows build artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
if: always()
with:
name: ontime-windows-build
@@ -93,7 +93,7 @@ jobs:
retention-days: 1
- name: Release
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
if: github.ref_type == 'tag'
with:
files: './apps/electron/dist/ontime-win64.exe'
@@ -104,14 +104,14 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
- name: Setup pnpm
uses: pnpm/action-setup@v3
uses: pnpm/action-setup@v4
- name: Install dependencies
run: pnpm install --frozen-lockfile
@@ -120,7 +120,7 @@ jobs:
run: pnpm dist-linux
- name: Upload Linux build artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
if: always()
with:
name: ontime-linux-build
@@ -131,7 +131,7 @@ jobs:
retention-days: 1
- name: Release
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
if: github.ref_type == 'tag'
with:
files: |
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
# This step is only needed to setup the permissions to update npm as pnpm will setup the correct node version
- uses: actions/setup-node@v6
+4 -4
View File
@@ -13,7 +13,7 @@ jobs:
CI: ''
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
@@ -52,7 +52,7 @@ jobs:
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
@@ -90,14 +90,14 @@ jobs:
- name: Run Playwright tests
run: pnpm e2e
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v6
if: always()
with:
name: playwright-report
path: playwright-report/
retention-days: 30
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v6
with:
name: automated-screenshots
path: automated-screenshots/
+3 -1
View File
@@ -4,8 +4,10 @@
<meta charset="utf-8" />
<base href="/" />
<link rel="icon" href="favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#101010" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="ontime" content="ontime - time keeping for live events" />
<link rel="apple-touch-icon" href="ontime-logo.png" />
<link rel="icon" type="image/png" href="ontime-logo.png" />
+2 -2
View File
@@ -14,6 +14,6 @@
"scope": "./",
"start_url": "./",
"display": "",
"theme_color": "#121212",
"background_color": "#ffffff"
"theme_color": "#101010",
"background_color": "#101010"
}
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "",
"short_name": "",
"icons": [{ "src": "ontime-logo.png", "sizes": "295x295", "type": "image/png" }],
"theme_color": "#2B5ABC",
"theme_color": "#101010",
"background_color": "#101010",
"display": "standalone"
}
+16 -1
View File
@@ -1,5 +1,13 @@
import axios, { AxiosResponse } from 'axios';
import { EntryId, OntimeEntry, OntimeEvent, ProjectRundownsList, Rundown, TransientEventPayload } from 'ontime-types';
import {
EntryId,
OntimeEntry,
OntimeEvent,
ProjectRundownsList,
RenumberCues,
Rundown,
TransientEventPayload,
} from 'ontime-types';
import { apiEntryUrl } from './constants';
import type { RequestOptions } from './requestOptions';
@@ -111,6 +119,13 @@ export async function putBatchEditEvents(rundownId: RundownId, data: BatchEditEn
return axios.put(`${rundownPath}/${rundownId}/batch`, data);
}
/**
* HTTP request to renumber cues for multiple events
*/
export function patchRenumberCues(rundownId: RundownId, data: RenumberCues): Promise<AxiosResponse<Rundown>> {
return axios.patch(`${rundownPath}/${rundownId}/renumber`, data);
}
export type ReorderEntry = {
entryId: EntryId;
destinationId: EntryId;
@@ -1,10 +1,9 @@
// skipcq: JS-C1003 - sentry does not expose itself as an ES Module.
import * as Sentry from '@sentry/react';
/* eslint-disable react/destructuring-assignment */
import React from 'react';
import { hasConnected, reconnectAttempts } from '../../../common/utils/socket';
import { runtimeStore } from '../../stores/runtime';
import { getConnectionState, getReconnectAttempts } from '../../utils/socket';
import style from './ErrorBoundary.module.scss';
@@ -37,7 +36,7 @@ class ErrorBoundary extends React.Component {
scope.setExtras({
error,
store: appState,
hasSocket: { hasConnected, reconnectAttempts },
hasSocket: { hasConnected: getConnectionState(), reconnectAttempts: getReconnectAttempts() },
});
const eventId = Sentry.captureException(error);
this.setState({ eventId, info });
@@ -64,8 +64,8 @@ function SectionContents({ options, collapsed }: SectionContentsProps) {
function HiddenContents({ options }: { options: ParamField[] }) {
return (
<>
{options.map((option, index) => {
return <ParamInput key={option.title + index} paramField={option} />;
{options.map((option) => {
return <ParamInput key={option.id} paramField={option} />;
})}
</>
);
@@ -26,3 +26,14 @@ export const showLeadingZeros: ParamField = {
type: 'boolean',
defaultValue: false,
};
export type TimeOptions = {
timeformat: string | null;
};
/**
* Helper to get value of 'timeformat' from either source, prioritizing defaultValues
*/
export function getTimeOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URLSearchParams) {
return defaultValues?.get('timeformat') ?? searchParams.get('timeformat');
}
@@ -1,16 +1,16 @@
import { useQuery } from '@tanstack/react-query';
import { langEn } from 'ontime-types';
import { MILLIS_PER_HOUR } from 'ontime-utils';
import { getUserTranslation } from '../../common/api/assets';
import { TRANSLATION } from '../../common/api/constants';
import { queryRefetchIntervalSlow } from '../../ontimeConfig';
export function useCustomTranslation() {
const { data, status, refetch } = useQuery({
queryKey: TRANSLATION,
queryFn: ({ signal }) => getUserTranslation({ signal }),
placeholderData: (previousData, _previousQuery) => previousData,
refetchInterval: queryRefetchIntervalSlow,
staleTime: MILLIS_PER_HOUR,
});
return { data: data ?? langEn, status, refetch };
}
@@ -41,6 +41,7 @@ import {
patchReorderEntry,
postAddEntry,
postCloneEntry,
patchRenumberCues,
putBatchEditEvents,
putEditEntry,
requestApplyDelay,
@@ -523,6 +524,39 @@ export const useEntryActions = () => {
[batchUpdateEventsMutation, getCurrentRundownData],
);
const { mutateAsync: renumberCuesMutation } = useMutation({
mutationFn: ([rundownId, body]: Parameters<typeof patchRenumberCues>) => patchRenumberCues(rundownId, body),
onMutate: async () => {
const queryKey = resolveCurrentRundownQueryKey();
await queryClient.cancelQueries({ queryKey });
const previousRundown = queryClient.getQueryData<Rundown>(queryKey);
return { previousRundown, queryKey };
},
onSuccess: (response, _variables, context) => {
if (!response.data || !context?.queryKey) return;
const updatedRundown = response.data;
queryClient.setQueryData<Rundown>(context.queryKey, updatedRundown);
},
onError: (_error, _vars, context) => {
if (context?.previousRundown) queryClient.setQueryData<Rundown>(context.queryKey, context.previousRundown);
},
});
const renumberCues = useCallback(
async (eventIds: EntryId[], prefix: string, start: string, increment: string) => {
const rundown = getCurrentRundownData();
const rundownId = rundown?.id;
if (!rundownId) throw new Error('Rundown not initialized');
try {
await renumberCuesMutation([rundownId, { ids: eventIds, prefix, start, increment }]);
} catch (error) {
logAxiosError('Error renumbering cues', error);
throw error;
}
},
[getCurrentRundownData, renumberCuesMutation],
);
/**
* Calls mutation to delete an entry
* @private
@@ -947,6 +981,7 @@ export const useEntryActions = () => {
groupEntries,
move,
reorderEntry,
renumberCues,
swapEvents,
updateEntry,
updateTimer,
@@ -963,6 +998,7 @@ export const useEntryActions = () => {
groupEntries,
move,
reorderEntry,
renumberCues,
swapEvents,
updateEntry,
updateTimer,
+4 -2
View File
@@ -51,8 +51,10 @@ const socketConfig = {
offlineAttemptsThreshold: 2, // when we consider the client disconnected
} as const;
export let hasConnected = false;
export let reconnectAttempts = 0;
export const getConnectionState = () => hasConnected;
export const getReconnectAttempts = () => reconnectAttempts;
let hasConnected = false;
let reconnectAttempts = 0;
export const connectSocket = () => {
websocket = new WebSocket(websocketUrl);
+5 -4
View File
@@ -1,4 +1,4 @@
import { MaybeNumber, OntimeEvent, Settings, TimeFormat } from 'ontime-types';
import { MaybeNumber, MaybeString, OntimeEvent, Settings, TimeFormat } from 'ontime-types';
import {
MILLIS_PER_HOUR,
MILLIS_PER_MINUTE,
@@ -75,8 +75,9 @@ function resolveTimeFormat(fallback12: string, fallback24: string): string {
}
type FormatOptions = {
format12: string;
format24: string;
format12?: string;
format24?: string;
override?: MaybeString;
};
/**
@@ -97,7 +98,7 @@ export const formatTime = (
return '...';
}
const timeFormat = resolver(options?.format12 ?? FORMAT_12, options?.format24 ?? FORMAT_24);
const timeFormat = options?.override ?? resolver(options?.format12 ?? FORMAT_12, options?.format24 ?? FORMAT_24);
const display = formatFromMillis(Math.abs(milliseconds), timeFormat);
const isNegative = milliseconds < 0;
@@ -15,23 +15,25 @@ import Input from '../../../../../common/components/input/input/Input';
import Tag from '../../../../../common/components/tag/Tag';
import { openLink } from '../../../../../common/utils/linkUtils';
import * as Panel from '../../../panel-utils/PanelUtils';
import { extractSheetId, getPersistedSheetId, persistSheetId } from './gsheetUtils';
import style from './SourcesPanel.module.scss';
interface GSheetSetupProps {
onCancel: () => void;
onSheetLoaded: (sheetId: string, options: SpreadsheetWorksheetOptions) => void;
closedByUser: boolean;
}
export default function GSheetSetup(props: GSheetSetupProps) {
const { onCancel, onSheetLoaded } = props;
const { onCancel, onSheetLoaded, closedByUser } = props;
const [file, setFile] = useState<File | null>(null);
const [sheetId, setSheetId] = useState('');
const [sheetId, setSheetId] = useState(getPersistedSheetId);
const [authenticationStatus, setAuthenticationStatus] = useState<AuthenticationStatus>('not_authenticated');
const [authKey, setAuthKey] = useState<string | null>(null);
const [loading, setLoading] = useState<'' | 'cancel' | 'connect' | 'authenticate' | 'load-sheet'>('');
const [authLink, setAuthLink] = useState('');
const [loading, setLoading] = useState<'' | 'cancel' | 'connect' | 'authenticate' | 'load-sheet'>('');
const [authError, setAuthError] = useState('');
const [worksheetError, setWorksheetError] = useState('');
const pollTimeoutRef = useRef<number | null>(null);
@@ -62,6 +64,7 @@ export default function GSheetSetup(props: GSheetSetupProps) {
const loadWorksheetOptions = useCallback(
async (nextSheetId: string) => {
const worksheetOptions = await getWorksheetOptions(nextSheetId);
persistSheetId(nextSheetId);
onSheetLoaded(nextSheetId, worksheetOptions);
setWorksheetError('');
},
@@ -71,6 +74,7 @@ export default function GSheetSetup(props: GSheetSetupProps) {
const pollUntilAuthenticated = useCallback(
async (attempts: number = 0) => {
clearPollTimeout();
if (closedByUser) return;
try {
const result = await verifyAuthenticationStatus();
@@ -82,13 +86,16 @@ export default function GSheetSetup(props: GSheetSetupProps) {
pollTimeoutRef.current = window.setTimeout(() => {
pollUntilAuthenticated(attempts + 1);
}, 2000);
} else {
setLoading('');
return; // Keep authKey for next poll
}
// Polling timed out
setAuthKey(null);
setLoading('');
return;
}
if (result.authenticated === 'authenticated') {
if (result.authenticated === 'authenticated' && result.sheetId) {
setLoading('load-sheet');
try {
await loadWorksheetOptions(result.sheetId);
} catch (error) {
@@ -96,13 +103,15 @@ export default function GSheetSetup(props: GSheetSetupProps) {
}
}
setAuthKey(null);
setLoading('');
} catch (error) {
setAuthError(maybeAxiosError(error));
setAuthKey(null);
setLoading('');
}
},
[clearPollTimeout, loadWorksheetOptions],
[clearPollTimeout, loadWorksheetOptions, closedByUser],
);
/** check if the current session has been authenticated */
@@ -150,7 +159,7 @@ export default function GSheetSetup(props: GSheetSetupProps) {
};
/**
* Requests connection to google auth
* Requests a device code from Google. The user can copy it before opening the browser.
*/
const handleConnect = async () => {
if (!file) return;
@@ -171,7 +180,7 @@ export default function GSheetSetup(props: GSheetSetupProps) {
};
/**
* Open google auth
* Opens the Google verification page and starts polling for completion.
*/
const handleAuthenticate = () => {
setLoading('authenticate');
@@ -180,7 +189,6 @@ export default function GSheetSetup(props: GSheetSetupProps) {
clearPollTimeout();
clearAuthFallbackTimeout();
// open link and schedule a check for when the user focuses again
openLink(authLink);
authFallbackTimeoutRef.current = window.setTimeout(() => {
if (document.hasFocus()) {
@@ -269,18 +277,19 @@ export default function GSheetSetup(props: GSheetSetupProps) {
</Panel.ListGroup>
)}
<Panel.ListGroup className={style.setupBlock}>
<Panel.Description>Enter ID of sheet to synchronise</Panel.Description>
<Panel.Description>Enter ID of sheet to synchronize</Panel.Description>
<Panel.Error>{worksheetError}</Panel.Error>
<Input
fluid
value={sheetId}
placeholder='Sheet ID'
placeholder='Sheet ID or Google Sheets URL'
onChange={(event) => {
setWorksheetError('');
setSheetId(event.target.value);
setSheetId(extractSheetId(event.target.value));
}}
disabled={isLoading || canAuthenticate}
/>
<div className={style.setupHint}>Paste a Google Sheets URL or the sheet ID from the URL bar.</div>
</Panel.ListGroup>
{isAuthenticated ? (
<Panel.ListGroup className={style.setupBlock}>
@@ -304,18 +313,16 @@ export default function GSheetSetup(props: GSheetSetupProps) {
</Panel.ListGroup>
) : (
<Panel.ListGroup className={style.setupBlock}>
<Panel.Description>Authenticate this Ontime session with Google</Panel.Description>
<Panel.Description>Copy the device code, then authenticate with Google</Panel.Description>
<Panel.InlineElements wrap='wrap' className={style.setupActions}>
{isAuthenticating && <span>Authenticating...</span>}
<CopyTag copyValue={authKey ?? ''} disabled={!canAuthenticate}>
{authKey ? authKey : 'Upload files to generate Auth Key'}
</CopyTag>
<Button onClick={handleAuthenticate} disabled={!canAuthenticate}>
<CopyTag copyValue={authKey ?? ''}>{authKey}</CopyTag>
<Button onClick={handleAuthenticate} disabled={isLoading} loading={loading === 'authenticate'}>
<IoShieldCheckmarkOutline />
Authenticate
</Button>
</Panel.InlineElements>
<div className={style.setupHint}>Open the browser prompt, complete the code flow, then come back here.</div>
<div className={style.setupHint}>Copy the code, then open the browser prompt to complete the flow.</div>
</Panel.ListGroup>
)}
</Panel.Section>
@@ -37,12 +37,15 @@ type ActiveSource =
kind: 'excel';
worksheetNames: string[];
initialWorksheetMetadata: SpreadsheetWorksheetMetadata | null;
closedByUser: boolean;
}
| {
kind: 'gsheet';
sheetId: string;
worksheetNames: string[];
initialWorksheetMetadata: SpreadsheetWorksheetMetadata | null;
title: string;
closedByUser: boolean;
};
export default function SourcesPanel() {
@@ -73,6 +76,7 @@ export default function SourcesPanel() {
kind: 'excel',
worksheetNames: worksheetOptions.worksheets,
initialWorksheetMetadata: worksheetOptions.metadata,
closedByUser: false,
});
setImportFlow('excel');
setHasFile('done');
@@ -106,7 +110,13 @@ export default function SourcesPanel() {
};
const cancelImportFlow = () => {
resetFlow();
if (activeSource && activeSource.kind === 'gsheet') {
// Return to GSheetSetup so the user can change the sheet ID or revoke auth
setActiveSource({ ...activeSource, closedByUser: true });
setError('');
} else {
resetFlow();
}
};
const handleFinished = () => {
@@ -177,15 +187,22 @@ export default function SourcesPanel() {
sheetId,
worksheetNames: worksheetOptions.worksheets,
initialWorksheetMetadata: worksheetOptions.metadata,
title: worksheetOptions.title ?? '',
closedByUser: false,
});
}, []);
const closedByUser = activeSource?.closedByUser ?? false;
const isGSheetFlow = importFlow === 'gsheet';
const showInput = importFlow === 'none';
const showCompleted = importFlow === 'finished';
const showAuth = isGSheetFlow && activeSource === null;
const showImportWorkspace = activeSource !== null;
const importModalTitle = activeSource?.kind === 'excel' ? 'Import spreadsheet' : 'Synchronise with Google Sheet';
const showImportWorkspace = activeSource !== null && !closedByUser;
const importModalTitle = (() => {
if (!activeSource) return '';
if (activeSource.kind === 'excel') return 'Import spreadsheet';
return activeSource.title ? `Sync: ${activeSource.title}` : 'Synchronize with Google Sheet';
})();
const sourceKey = (() => {
if (!activeSource) return null;
if (activeSource.kind === 'excel') return 'excel';
@@ -195,7 +212,7 @@ export default function SourcesPanel() {
return (
<Panel.Section>
<Panel.Card>
<Panel.SubHeader>Synchronise your rundown with an external source</Panel.SubHeader>
<Panel.SubHeader>Synchronize your rundown with an external source</Panel.SubHeader>
{error && <Panel.Error>{error}</Panel.Error>}
{showInput && (
<div className={style.introStack}>
@@ -233,7 +250,7 @@ export default function SourcesPanel() {
</section>
<section className={style.sourceCard}>
<div className={style.sourceHeader}>
<h4 className={style.sourceTitle}>Synchronise with Google</h4>
<h4 className={style.sourceTitle}>Synchronize with Google</h4>
</div>
<p className={style.sourceDescription}>
Connect a Google account once, then load any sheet by ID and keep the import flow inside Ontime.
@@ -241,7 +258,7 @@ export default function SourcesPanel() {
<div className={style.sourceMeta}>Requires Google OAuth client credentials</div>
<Button variant='primary' size='large' fluid onClick={openGSheetFlow} disabled={hasFile !== 'none'}>
<IoCloudOutline />
Synchronise with Google
Synchronize with Google
</Button>
</section>
</div>
@@ -257,7 +274,9 @@ export default function SourcesPanel() {
</Button>
</div>
)}
{showAuth && <GSheetSetup onCancel={cancelGSheetFlow} onSheetLoaded={handleSheetLoaded} />}
{isGSheetFlow && (
<GSheetSetup onCancel={cancelGSheetFlow} onSheetLoaded={handleSheetLoaded} closedByUser={closedByUser} />
)}
<Modal
isOpen={showImportWorkspace}
title={importModalTitle}
@@ -0,0 +1,45 @@
import { describe, expect, it } from 'vitest';
import { extractSheetId } from '../gsheetUtils';
describe('extractSheetId()', () => {
it('extracts the ID from a full Google Sheets URL', () => {
const url = 'https://docs.google.com/spreadsheets/d/1aBcDeFgHiJkLmNoPqRsTuVwXyZ/edit#gid=0';
expect(extractSheetId(url)).toBe('1aBcDeFgHiJkLmNoPqRsTuVwXyZ');
});
it('extracts the ID when the URL has no trailing path', () => {
expect(extractSheetId('https://docs.google.com/spreadsheets/d/abc123')).toBe('abc123');
});
it('handles IDs with hyphens and underscores', () => {
const url = 'https://docs.google.com/spreadsheets/d/1a-B_c2/edit';
expect(extractSheetId(url)).toBe('1a-B_c2');
});
it('returns a raw sheet ID unchanged', () => {
expect(extractSheetId('1aBcDeFgHiJkLmNoPqRsTuVwXyZ')).toBe('1aBcDeFgHiJkLmNoPqRsTuVwXyZ');
});
it('trims whitespace from the input', () => {
expect(extractSheetId(' 1aBcDeFg ')).toBe('1aBcDeFg');
});
it('trims whitespace from a pasted URL', () => {
const url = ' https://docs.google.com/spreadsheets/d/1aBcDeFg/edit ';
expect(extractSheetId(url)).toBe('1aBcDeFg');
});
it('strips query params from a raw ID', () => {
expect(extractSheetId('1aBcDeFgHiJkLmNoPqRsTuVwXyZ?edit=1')).toBe('1aBcDeFgHiJkLmNoPqRsTuVwXyZ');
});
it('strips fragment from a raw ID', () => {
expect(extractSheetId('1aBcDeFg#gid=0')).toBe('1aBcDeFg');
});
it('returns empty string for empty input', () => {
expect(extractSheetId('')).toBe('');
expect(extractSheetId(' ')).toBe('');
});
});
@@ -0,0 +1,29 @@
import { makeStageKey } from '../../../../../common/utils/localStorage';
// Matches the document ID segment from a Google Sheets URL:
// https://docs.google.com/spreadsheets/d/{ID}/edit#gid=0
// ^^^^ captured group
// IDs consist of alphanumeric chars, hyphens, and underscores.
const sheetIdPattern = /\/spreadsheets\/d\/([a-zA-Z0-9_-]+)/;
const lastSheetIdKey = makeStageKey('gsheet:lastSheetId');
/**
* Extracts a Google Sheet ID from a full URL, or returns the raw input if it doesn't match.
*/
export function extractSheetId(input: string): string {
const trimmed = input.trim();
const match = trimmed.match(sheetIdPattern);
if (match) return match[1];
// Strip query params (?...) and fragments (#...) in case the user
// pasted a partial URL or an ID with trailing junk like "abc123?edit=1"
return trimmed.split(/[?#]/)[0];
}
export function getPersistedSheetId(): string {
return localStorage.getItem(lastSheetIdKey) ?? '';
}
export function persistSheetId(sheetId: string) {
localStorage.setItem(lastSheetIdKey, sheetId);
}
@@ -16,7 +16,7 @@ export function getWarningText(warning: MappingWarning): string {
case 'invalid-name':
return 'Column cannot be converted into an Ontime field name';
case 'name-collision':
return 'Column name resolves to a duplicate column';
return 'Column name resolves to a duplicate Ontime field';
default:
return '';
}
@@ -50,7 +50,7 @@ export default function SheetImportMappingPane({
return (
<section className={style.mappingPane}>
<Panel.InlineElements align='apart' className={style.mappingPaneHeader}>
<span className={style.mappingPaneTitle}>Fields</span>
<span className={style.mappingPaneTitle}>Column mapping</span>
<Panel.InlineElements relation='inner' className={style.mappingPaneActions}>
<Button className={style.addColumnTrigger} onClick={handleAddCustomField} disabled={isBusy}>
<IoAdd />
@@ -58,7 +58,7 @@ describe('getImportWarnings()', () => {
expect(warnings['custom.0.importName']).toStrictEqual({ kind: 'invalid-name' });
});
it('warns when a custom header resolves to an existing Ontime field name', () => {
it('warns when a custom header resolves to a built-in or duplicate imported field name', () => {
const values = createDefaultFormValues();
values.custom = [
{ ontimeName: '', importName: 'Artist-1' },
@@ -67,12 +67,20 @@ describe('getImportWarnings()', () => {
{ ontimeName: '', importName: 'Presenter-1' },
];
const warnings = getImportWarnings(values, ['Artist-1', 'Artist/1', 'Title!', 'Presenter-1'], ['Presenter 1']);
const warnings = getImportWarnings(values, ['Artist-1', 'Artist/1', 'Title!', 'Presenter-1']);
expect(warnings['custom.0.importName']).toBeUndefined();
expect(warnings['custom.1.importName']).toStrictEqual({ kind: 'name-collision' });
expect(warnings['custom.2.importName']).toStrictEqual({ kind: 'name-collision' });
expect(warnings['custom.3.importName']).toStrictEqual({ kind: 'name-collision' });
expect(warnings['custom.3.importName']).toBeUndefined();
});
it('does not give false warnings for pre-existing custom fields', () => {
const values = createDefaultFormValues();
values.custom = [{ ontimeName: '', importName: 'Video Info' }];
const warnings = getImportWarnings(values, ['Video Info']);
expect(warnings['custom.0.importName']).toBeUndefined();
});
});
@@ -127,26 +127,26 @@ function isPersistedFormValues(obj: unknown): obj is ImportFormValues {
);
}
export function getPersistedImportState(sourceKey: string): ImportFormValues {
export function getPersistedImportState(sourceKey: string): { values: ImportFormValues; isPersisted: boolean } {
const storageKey = getImportMapKey(sourceKey);
try {
const raw = localStorage.getItem(storageKey);
if (!raw) {
return createDefaultFormValues();
return { values: createDefaultFormValues(), isPersisted: false };
}
const parsed: unknown = JSON.parse(raw);
if (isPersistedFormValues(parsed)) {
return parsed;
return { values: parsed, isPersisted: true };
}
// Invalid schema - delete malformed data
localStorage.removeItem(storageKey);
return createDefaultFormValues();
return { values: createDefaultFormValues(), isPersisted: false };
} catch {
// Parse error - delete corrupted data
localStorage.removeItem(storageKey);
return createDefaultFormValues();
return { values: createDefaultFormValues(), isPersisted: false };
}
}
@@ -156,11 +156,9 @@ export function getPersistedImportState(sourceKey: string): ImportFormValues {
export function getImportWarnings(
values: ImportFormValues,
detectedSpreadsheetColumns: string[],
existingCustomFieldLabels: string[] = [],
): Record<string, MappingWarning | undefined> {
const normalisedHeaders = new Set(detectedSpreadsheetColumns.map(normaliseColumnName).filter(Boolean));
const builtInLabels = new Set(builtInFieldDefs.map((def) => def.label.toLowerCase()));
const existingLabels = new Set(existingCustomFieldLabels.map((label) => label.trim().toLowerCase()).filter(Boolean));
const seenColumns = new Set<string>();
const seenDerivedLabels = new Set<string>();
const warnings: Record<string, MappingWarning | undefined> = {};
@@ -200,11 +198,7 @@ export function getImportWarnings(
warnings[key] = { kind: 'missing' };
} else {
const normalisedDerivedLabel = sanitisedLabel.toLowerCase();
if (
builtInLabels.has(normalisedDerivedLabel) ||
existingLabels.has(normalisedDerivedLabel) ||
seenDerivedLabels.has(normalisedDerivedLabel)
) {
if (builtInLabels.has(normalisedDerivedLabel) || seenDerivedLabels.has(normalisedDerivedLabel)) {
warnings[key] = { kind: 'name-collision' };
}
}
@@ -5,7 +5,6 @@ import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react';
import { useFieldArray, useForm } from 'react-hook-form';
import { maybeAxiosError } from '../../../../../../common/api/utils';
import useCustomFields from '../../../../../../common/hooks-query/useCustomFields';
import { formatDuration } from '../../../../../../common/utils/time';
import {
type ImportFormValues,
@@ -118,10 +117,15 @@ export function useSheetImportForm({
onApply,
onExport,
}: UseSheetImportFormProps) {
const initialFormValues = useMemo(() => {
const persisted = getPersistedImportState(sourceKey);
const worksheet = getPreferredWorksheet(worksheetNames, persisted.worksheet, initialMetadata?.worksheet ?? '');
return { ...persisted, worksheet };
const { initialFormValues, skipAutoPreview } = useMemo(() => {
const { values, isPersisted } = getPersistedImportState(sourceKey);
const worksheet = getPreferredWorksheet(worksheetNames, values.worksheet, initialMetadata?.worksheet ?? '');
// Skip auto-preview when restoring a persisted mapping that was saved for a different worksheet.
const hasWorksheetChanged = values.worksheet !== worksheet;
return {
initialFormValues: { ...values, worksheet },
skipAutoPreview: isPersisted && hasWorksheetChanged,
};
}, [initialMetadata?.worksheet, sourceKey, worksheetNames]);
const {
@@ -139,7 +143,6 @@ export function useSheetImportForm({
const { fields, append, remove } = useFieldArray({ control, name: 'custom' });
const values = watch();
const { data: existingCustomFields } = useCustomFields();
// --- Worksheet metadata via react-query ---
const queryClient = useQueryClient();
@@ -167,16 +170,14 @@ export function useSheetImportForm({
const columnLabels = buildColumnLabels(values);
const [state, dispatch] = useReducer(importReducer, initialImportState);
const existingCustomFieldLabels = useMemo(
() => Object.values(existingCustomFields).map((field) => field.label),
[existingCustomFields],
);
const warnings = getImportWarnings(values, headers, existingCustomFieldLabels);
const warnings = getImportWarnings(values, headers);
const warningCount = Object.values(warnings).filter(Boolean).length;
const previewRef = useRef<SpreadsheetPreviewResponse | null>(null);
const autoPreviewFiredRef = useRef(false);
// Rehydrate the form from persisted/default state whenever the source context changes.
useEffect(() => {
autoPreviewFiredRef.current = false;
reset(initialFormValues);
dispatch({ type: 'reset' });
}, [initialFormValues, reset]);
@@ -225,6 +226,16 @@ export function useSheetImportForm({
[previewImport],
);
// Auto-preview on mount once metadata is ready.
useEffect(() => {
if (autoPreviewFiredRef.current) return;
if (skipAutoPreview) return;
if (!isValid || headers.length === 0) return;
autoPreviewFiredRef.current = true;
handleSubmit(handlePreview)();
}, [skipAutoPreview, isValid, headers, handleSubmit, handlePreview]);
const handleApply = useCallback(async () => {
if (!state.preview) return;
@@ -16,6 +16,7 @@ import EntryEditModal from '../../views/cuesheet/cuesheet-edit-modal/EntryEditMo
import { EditorLayoutMode, useEditorLayout } from '../../views/editor/useEditorLayout';
import RundownEntryEditor from './entry-editor/RundownEntryEditor';
import FinderPlacement from './placements/FinderPlacement';
import RenumberCuesDialog from './renumber-cues-dialog/RenumberCuesDialog';
import { RundownContextMenu } from './rundown-context-menu/RundownContextMenu';
import RundownHeader from './rundown-header/RundownHeader';
import RundownHeaderMobile from './rundown-header/RundownHeaderMobile';
@@ -112,6 +113,7 @@ function RundownRoot({ isSmallDevice, isExtracted, viewMode, setViewMode }: Rund
)}
{viewMode === RundownViewMode.List ? <RundownList /> : <RundownTable />}
{viewMode === RundownViewMode.Table && <EntryEditModal />}
<RenumberCuesDialog />
</div>
);
}
@@ -104,6 +104,7 @@
/* approximating the style of a disabled input */
.textLikeInput {
color: $gray-200;
background: transparent;
justify-content: start;
width: 7.5em;
@@ -1,4 +1,3 @@
import { sanitiseCue } from 'ontime-utils';
import { memo } from 'react';
import * as Editor from '../../../../common/components/editor-utils/EditorUtils';
@@ -24,10 +23,6 @@ export default memo(EventEditorTitles);
function EventEditorTitles({ eventId, cue, flag, title, note, colour }: EventEditorTitlesProps) {
const { updateEntry } = useEntryActionsContext();
const cueSubmitHandler = (_field: string, newValue: string) => {
updateEntry({ id: eventId, cue: sanitiseCue(newValue) });
};
const flagSubmitHandler = (newValue: boolean) => {
updateEntry({ id: eventId, flag: newValue });
};
@@ -48,7 +43,7 @@ function EventEditorTitles({ eventId, cue, flag, title, note, colour }: EventEdi
field='cue'
label='Cue'
initialValue={cue}
submitHandler={cueSubmitHandler}
submitHandler={textSubmitHandler}
maxLength={10}
/>
<div>
@@ -0,0 +1,22 @@
@use '../../../theme/ontimeColours' as *;
@use '../../../theme/ontimeStyles' as *;
.fields {
display: flex;
flex-direction: column;
gap: 1rem;
padding-inline: 0.5rem;
margin-bottom: 0.5rem;
}
.label {
font-size: $inner-section-text-size;
color: $label-gray;
}
.error {
padding-inline: 0.5rem;
font-size: $inner-section-text-size;
color: $error-red;
margin: 0;
}
@@ -0,0 +1,131 @@
import { RenumberCues } from 'ontime-types';
import { useForm } from 'react-hook-form';
import { create } from 'zustand';
import { maybeAxiosError } from '../../../common/api/utils';
import Button from '../../../common/components/buttons/Button';
import Dialog from '../../../common/components/dialog/Dialog';
import Input from '../../../common/components/input/input/Input';
import { useEntryActionsContext } from '../../../common/context/EntryActionsContext';
import useRundown from '../../../common/hooks-query/useRundown';
import { orderEntries } from '../rundown.utils';
import { useEventSelection } from '../useEventSelection';
import style from './RenumberCuesDialog.module.scss';
type RenumberCueData = Pick<RenumberCues, 'increment' | 'prefix' | 'start'>;
export default function RenumberCuesDialog() {
'use memo';
const { data } = useRundown();
const { flatOrder } = data;
const { onClose, isOpen } = useRenumberCuesDialogStore();
const { renumberCues } = useEntryActionsContext();
const selectedEvents = useEventSelection((state) => state.selectedEvents);
const {
register,
handleSubmit,
setError,
clearErrors,
formState: { errors, isSubmitting },
} = useForm<RenumberCueData>();
const onSubmit = async (data: RenumberCueData) => {
clearErrors();
try {
const { prefix, start, increment } = data;
const orderedEvents = orderEntries(Array.from(selectedEvents), flatOrder);
await renumberCues(orderedEvents, prefix, start, increment);
onClose();
} catch (error) {
const message = maybeAxiosError(error);
setError('root', { message });
}
};
return (
<Dialog
isOpen={isOpen}
onClose={onClose}
title='Renumber cues'
showCloseButton
showBackdrop
bodyElements={
<form id='renumber-cues-form' onSubmit={handleSubmit(onSubmit)} className={style.fields}>
<div className={style.field}>
<label className={style.label}>
Prefix
<Input
{...register('prefix')}
type='text'
maxLength={8}
height='large'
fluid
autoComplete='off'
placeholder='A'
/>
</label>
</div>
<div className={style.field}>
<label className={style.label}>
Start
<Input
{...register('start')}
type='number'
required
step={0.001}
height='large'
fluid
autoComplete='off'
placeholder='10'
/>
</label>
</div>
<div className={style.field}>
<label className={style.label}>
Increment
<Input
{...register('increment')}
type='number'
required
step={0.001}
height='large'
fluid
autoComplete='off'
placeholder='0.1'
/>
</label>
</div>
{errors.root && <p className={style.error}>{errors.root.message}</p>}
</form>
}
footerElements={
<>
<Button type='button' variant='subtle-white' onClick={onClose} disabled={isSubmitting}>
Cancel
</Button>
<Button type='submit' variant='primary' form='renumber-cues-form' loading={isSubmitting}>
Renumber
</Button>
</>
}
/>
);
}
interface RenumberCuesDialogState {
isOpen: boolean;
onClose: () => void;
onOpen: () => void;
}
export const useRenumberCuesDialogStore = create<RenumberCuesDialogState>()((set) => ({
isOpen: false,
onClose: () => {
set({ isOpen: false });
},
onOpen: () => {
set({ isOpen: true });
},
}));
@@ -13,13 +13,14 @@ import {
IoTrash,
IoUnlink,
} from 'react-icons/io5';
import { TbFlagFilled } from 'react-icons/tb';
import { TbFlagFilled, TbListNumbers } from 'react-icons/tb';
import { useEntryActionsContext } from '../../../common/context/EntryActionsContext';
import { useContextMenu } from '../../../common/hooks/useContextMenu';
import { useEntryCopy } from '../../../common/stores/entryCopyStore';
import { deviceMod } from '../../../common/utils/deviceUtils';
import { cx, getAccessibleColour } from '../../../common/utils/styleUtils';
import { useRenumberCuesDialogStore } from '../renumber-cues-dialog/RenumberCuesDialog';
import { useEventIdSwapping } from '../useEventIdSwapping';
import { getSelectionMode, useEventSelection } from '../useEventSelection';
import RundownEventInner from './RundownEventInner';
@@ -99,6 +100,7 @@ export default function RundownEvent({
const selectedEventId = useEventIdSwapping((state) => state.selectedEventId);
const setSelectedEventId = useEventIdSwapping((state) => state.setSelectedEventId);
const clearSelectedEventId = useEventIdSwapping((state) => state.clearSelectedEventId);
const openRenumberDialog = useRenumberCuesDialogStore((state) => state.onOpen);
const { updateEntry, batchUpdateEvents, clone, deleteEntry, groupEntries, swapEvents } = useEntryActionsContext();
@@ -143,6 +145,13 @@ export default function RundownEvent({
disabled: parent !== null,
},
{ type: 'divider' },
{
type: 'item',
label: 'Renumber cues',
icon: TbListNumbers,
onClick: openRenumberDialog,
},
{ type: 'divider' },
{
type: 'item',
label: 'Delete',
+2
View File
@@ -81,6 +81,8 @@ html,
user-select: none;
-webkit-app-region: drag;
isolation: isolate;
// prevents Safari iOS from showing white in the overscroll (rubber-band) area
background-color: $ui-black;
}
// reset button styles
+5 -1
View File
@@ -23,15 +23,19 @@ export default function ViewLoader({ children }: PropsWithChildren) {
const searchParams = new URLSearchParams(window.location.search);
const colourFromParams = searchParams.get('keyColour') ?? '#101010';
// always keep body background in sync so Safari iOS overscroll area matches the view
const bodyBgStyle = `body { background-color: var(--background-color-override, ${colourFromParams}); }`;
return (
<Suspense
fallback={
<>
<style>{`body { background: var(--background-color-override, ${colourFromParams}); }`}</style>
<style>{bodyBgStyle}</style>
<Loader />
</>
}
>
<style>{bodyBgStyle}</style>
<OverrideStyles />
{children}
</Suspense>
+13 -8
View File
@@ -43,7 +43,7 @@ export default function BackstageLoader() {
function Backstage({ events, customFields, projectData, isMirrored, settings }: BackstageData) {
const { getLocalizedString } = useTranslation();
const { mainSource, secondarySource, extraInfo } = useBackstageOptions();
const { mainSource, secondarySource, extraInfo, timeformat } = useBackstageOptions();
const { eventNext, eventNow, rundown, selectedEventId, time } = useBackstageSocket();
const [blinkClass, setBlinkClass] = useState(false);
const { height: screenHeight } = useViewportSize();
@@ -71,18 +71,20 @@ function Backstage({ events, customFields, projectData, isMirrored, settings }:
// gather timer data
const isPendingStart = getIsPendingStart(time.playback, time.phase);
const startedAt = isPendingStart ? formatTime(time.secondaryTimer) : formatTime(time.startedAt);
const startedAt = isPendingStart
? formatTime(time.secondaryTimer, { override: timeformat })
: formatTime(time.startedAt, { override: timeformat });
const scheduledStart = (() => {
if (showNow) return undefined;
if (!hasEvents) return undefined;
return formatTime(rundown.plannedStart, { format12: 'h:mm a', format24: 'HH:mm' });
return formatTime(rundown.plannedStart, { format12: 'h:mm a', format24: 'HH:mm', override: timeformat });
})();
const scheduledEnd = (() => {
if (showNow) return undefined;
if (!hasEvents) return undefined;
return formatTime(rundown.plannedEnd, { format12: 'h:mm a', format24: 'HH:mm' });
return formatTime(rundown.plannedEnd, { format12: 'h:mm a', format24: 'HH:mm', override: timeformat });
})();
let displayTimer = millisToString(time.current, { fallback: timerPlaceholderMin });
@@ -107,7 +109,7 @@ function Backstage({ events, customFields, projectData, isMirrored, settings }:
<div className='project-header'>
{projectData?.logo && <ViewLogo name={projectData.logo} className='logo' />}
<div className='title'>{projectData.title}</div>
<BackstageClock />
<BackstageClock timeformat={timeformat} />
</div>
{showProgress && <ProgressBar className='progress-container' current={time.current} duration={time.duration} />}
@@ -131,7 +133,10 @@ function Backstage({ events, customFields, projectData, isMirrored, settings }:
{isOvertime(time.current) ? (
<div className='time-entry__value'>{getLocalizedString('countdown.overtime')}</div>
) : (
<SuperscriptTime time={formatTime(time.expectedFinish)} className='time-entry__value' />
<SuperscriptTime
time={formatTime(time.expectedFinish, { override: timeformat })}
className='time-entry__value'
/>
)}
</div>
<div className='timer-gap' />
@@ -213,12 +218,12 @@ function ExtraInfo({ projectData, size, source }: ExtraInfoProps) {
);
}
function BackstageClock() {
function BackstageClock({ timeformat }: { timeformat: string | null }) {
const { getLocalizedString } = useTranslation();
const clock = useAutoTickingClock();
// gather timer data
const formattedClock = formatTime(clock);
const formattedClock = formatTime(clock, { override: timeformat });
return (
<div className='clock-container'>
@@ -2,7 +2,11 @@ import { CustomFields, OntimeEvent, ProjectData } from 'ontime-types';
import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router';
import { getTimeOption } from '../../common/components/view-params-editor/common.options';
import {
getTimeOption,
getTimeOptionsFromParams,
TimeOptions,
} from '../../common/components/view-params-editor/common.options';
import { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import {
@@ -71,7 +75,7 @@ type BackstageOptions = {
mainSource: keyof OntimeEvent | null;
secondarySource: keyof OntimeEvent | null;
extraInfo: string | null;
};
} & TimeOptions;
/**
* Utility extract the view options from URL Params
@@ -85,6 +89,7 @@ function getOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URL
mainSource: getValue('main') as keyof OntimeEvent | null,
secondarySource: getValue('secondary-src') as keyof OntimeEvent | null,
extraInfo: getValue('extra-info'),
timeformat: getTimeOptionsFromParams(searchParams, defaultValues),
};
}
+2 -1
View File
@@ -101,6 +101,7 @@ export function getPropertyValue(
type FormattingOptions = {
removeSeconds: boolean;
removeLeadingZero: boolean;
clockFormat?: MaybeString;
};
export function getFormattedTimer(
@@ -114,7 +115,7 @@ export function getFormattedTimer(
}
if (timerType === TimerType.Clock) {
return formatTime(timer);
return formatTime(timer, { override: options?.clockFormat });
}
let timeToParse = timer;
@@ -139,11 +139,12 @@ function CountdownContents({ playableEvents, subscriptions, goToEditMode }: Coun
}
function CountdownClock() {
const { timeformat } = useCountdownOptions();
const { getLocalizedString } = useTranslation();
const clock = useAutoTickingClock();
// gather timer data
const formattedClock = formatTime(clock);
const formattedClock = formatTime(clock, { override: timeformat });
return (
<div className='clock-container'>
@@ -2,7 +2,11 @@ import { CustomFields, EntryId, OntimeEvent } from 'ontime-types';
import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router';
import { getTimeOption } from '../../common/components/view-params-editor/common.options';
import {
getTimeOption,
getTimeOptionsFromParams,
TimeOptions,
} from '../../common/components/view-params-editor/common.options';
import { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils';
@@ -91,7 +95,7 @@ type CountdownOptions = {
secondarySource: keyof OntimeEvent | null;
showExpected: boolean;
hidePast: boolean;
};
} & TimeOptions;
/**
* Utility extract the view options from URL Params
@@ -115,6 +119,7 @@ function getOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URL
secondarySource: getValue('secondary-src') as keyof OntimeEvent | null,
showExpected: isStringBoolean(getValue('showExpected')),
hidePast: isStringBoolean(getValue('hidePast')),
timeformat: getTimeOptionsFromParams(searchParams, defaultValues),
};
}
@@ -80,6 +80,7 @@ function ProjectInfo({ projectData, isMirrored }: ProjectInfoData) {
{projectData.custom.map((info, idx) => {
const hasUrl = Boolean(info.url);
return (
// oxlint-disable-next-line react/no-array-index-key - we only have the index to go of here
<div key={`${info.title}-${idx}`} className='info__custom'>
{hasUrl && (
<div className='info__image-container'>
+7 -4
View File
@@ -6,6 +6,7 @@ import { useStudioClockSocket } from '../../common/hooks/useSocket';
import { cx } from '../../common/utils/styleUtils';
import { formatTime } from '../../common/utils/time';
import SuperscriptTime from '../common/superscript-time/SuperscriptTime';
import { useStudioOptions } from './studio.options';
import { getLargeClockData } from './studioClock.utils';
import './StudioClock.scss';
@@ -18,6 +19,7 @@ interface StudioClockProps {
}
export default function StudioClock({ hideCards }: StudioClockProps) {
const { timeformat } = useStudioOptions();
const isSmallScreen = useIsSmallScreen();
const clock = useAutoTickingClock();
const { playback } = useStudioClockSocket();
@@ -25,10 +27,10 @@ export default function StudioClock({ hideCards }: StudioClockProps) {
// if we are on mobile and have to show the cards
if (isSmallScreen && !hideCards) {
return <StudioClockMobile clock={clock} onAir={onAir} />;
return <StudioClockMobile clock={clock} onAir={onAir} timeformat={timeformat} />;
}
const { seconds, display, meridian } = getLargeClockData(clock);
const { seconds, display, meridian } = getLargeClockData(clock, timeformat);
return (
<div className='studio__clock'>
@@ -62,10 +64,11 @@ export default function StudioClock({ hideCards }: StudioClockProps) {
interface StudioClockMobileProps {
clock: number;
onAir: boolean;
timeformat: string | null;
}
function StudioClockMobile({ clock, onAir }: StudioClockMobileProps) {
const displayClock = formatTime(clock);
function StudioClockMobile({ clock, onAir, timeformat }: StudioClockMobileProps) {
const displayClock = formatTime(clock, { override: timeformat });
return (
<div className='studio__clock studio__clock--small'>
@@ -2,7 +2,11 @@ import { CustomFields, OntimeEvent } from 'ontime-types';
import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router';
import { getTimeOption } from '../../common/components/view-params-editor/common.options';
import {
getTimeOption,
getTimeOptionsFromParams,
TimeOptions,
} from '../../common/components/view-params-editor/common.options';
import { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils';
@@ -47,7 +51,7 @@ export const getStudioOptions = (timeFormat: string, customFields: CustomFields)
type StudioOptions = {
mainSource: keyof OntimeEvent | null;
hideCards: boolean;
};
} & TimeOptions;
/**
* Utility extract the view options from URL Params
@@ -60,6 +64,7 @@ function getOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URL
return {
mainSource: getValue('main') as keyof OntimeEvent | null,
hideCards: isStringBoolean(getValue('hideCards')),
timeformat: getTimeOptionsFromParams(searchParams, defaultValues),
};
}
@@ -5,9 +5,9 @@ import { formatTime } from '../../common/utils/time';
/**
* Gathers display elements for the large studio clock
*/
export function getLargeClockData(clock: number) {
export function getLargeClockData(clock: number, timeformat: string | null) {
const [display, meridian] = (() => {
const formatted = formatTime(clock);
const formatted = formatTime(clock, { override: timeformat });
if (formatted.endsWith('AM')) {
return [formatted.slice(0, -2), 'AM'];
}
@@ -37,7 +37,7 @@ export default function TimelinePageLoader() {
function TimelinePage({ events, customFields, projectData, settings }: TimelineData) {
const selectedEventId = useSelectedEventId();
const { mainSource } = useTimelineOptions();
const { mainSource, timeformat } = useTimelineOptions();
// holds copy of the rundown with only relevant events
const { scopedRundown, firstStart, totalDuration } = useScopedRundown(events, selectedEventId);
@@ -56,7 +56,7 @@ function TimelinePage({ events, customFields, projectData, settings }: TimelineD
<div className='project-header'>
{projectData?.logo && <ViewLogo name={projectData.logo} className='logo' />}
<div className='title'>{projectData.title}</div>
<TimelineClock />
<TimelineClock timeformat={timeformat} />
</div>
<TimelineSections now={now} next={next} followedBy={followedBy} mainSource={mainSource} />
@@ -71,12 +71,12 @@ function TimelinePage({ events, customFields, projectData, settings }: TimelineD
);
}
function TimelineClock() {
function TimelineClock({ timeformat }: { timeformat: string | null }) {
const { getLocalizedString } = useTranslation();
const clock = useAutoTickingClock();
// gather timer data
const formattedClock = formatTime(clock);
const formattedClock = formatTime(clock, { override: timeformat });
return (
<div className='clock-container'>
@@ -2,7 +2,11 @@ import { CustomFields, OntimeEvent } from 'ontime-types';
import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router';
import { getTimeOption } from '../../common/components/view-params-editor/common.options';
import {
getTimeOption,
getTimeOptionsFromParams,
TimeOptions,
} from '../../common/components/view-params-editor/common.options';
import { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils';
@@ -55,7 +59,7 @@ type TimelineOptions = {
mainSource: keyof OntimeEvent | null;
hidePast: boolean;
fixedSize: boolean;
};
} & TimeOptions;
/**
* Utility extract the view options from URL Params
@@ -69,6 +73,7 @@ function getOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URL
mainSource: getValue('main') as keyof OntimeEvent | null,
hidePast: isStringBoolean(getValue('hidePast')),
fixedSize: isStringBoolean(getValue('fixedSize')),
timeformat: getTimeOptionsFromParams(searchParams, defaultValues),
};
}
+6 -4
View File
@@ -1,4 +1,4 @@
import { OntimeView, TimerType } from 'ontime-types';
import { MaybeString, OntimeView, TimerType } from 'ontime-types';
import { useMemo } from 'react';
import { FitText } from '../../common/components/fit-text/FitText';
@@ -69,6 +69,7 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
font,
keyColour,
timerColour,
timeformat,
} = useTimerOptions();
const { getLocalizedString } = useTranslation();
@@ -106,6 +107,7 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
const display = getFormattedTimer(stageTimer, viewTimerType, localisedMinutes, {
removeSeconds: hideTimerSeconds,
removeLeadingZero: removeLeadingZeros,
clockFormat: timeformat,
});
const currentAux = (() => {
@@ -164,7 +166,7 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
</div>
)}
{showClock && <TimerAutoTickingClock />}
{showClock && <TimerAutoTickingClock clockFormat={timeformat} />}
<div className={cx(['timer-container', message.timer.blink && !showOverlay && 'blink'])}>
{showEndMessage ? (
@@ -212,9 +214,9 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
);
}
function TimerAutoTickingClock() {
function TimerAutoTickingClock({ clockFormat }: { clockFormat: MaybeString }) {
const autoTickingClock = useAutoTickingClock();
const formattedClock = formatTime(autoTickingClock);
const formattedClock = formatTime(autoTickingClock, { override: clockFormat });
const { getLocalizedString } = useTranslation();
return (
+4 -1
View File
@@ -6,8 +6,10 @@ import { useSearchParams } from 'react-router';
import type { SelectOption } from '../../common/components/select/Select';
import {
getTimeOption,
getTimeOptionsFromParams,
hideTimerSeconds,
showLeadingZeros,
TimeOptions,
} from '../../common/components/view-params-editor/common.options';
import { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
@@ -194,7 +196,7 @@ type TimerOptions = {
font?: string;
keyColour?: string;
timerColour?: string;
};
} & TimeOptions;
/**
* Utility extract the view options from URL Params
@@ -229,6 +231,7 @@ function getOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URL
font: getValue('font') ?? undefined,
keyColour: makeColourString(getValue('keyColour')),
timerColour: makeColourString(getValue('timerColour')),
timeformat: getTimeOptionsFromParams(searchParams, defaultValues),
};
}
+3 -4
View File
@@ -14,7 +14,7 @@
"main": "src/main.js",
"devDependencies": {
"electron": "38.2.1",
"electron-builder": "26.0.18",
"electron-builder": "26.9.1",
"wait-on": "^7.2.0"
},
"scripts": {
@@ -29,8 +29,7 @@
"appId": "no.lightdev.ontime",
"asar": true,
"dmg": {
"artifactName": "ontime-macOS-${arch}.dmg",
"icon": "icon.icns"
"artifactName": "ontime-macOS-${arch}.dmg"
},
"mac": {
"notarize": true,
@@ -46,7 +45,7 @@
]
},
"category": "public.app-category.productivity",
"icon": "icon.icns"
"icon": "ontime.icon"
},
"win": {
"target": "nsis"
Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

@@ -0,0 +1,62 @@
{
"fill-specializations" : [
{
"value" : "system-dark"
},
{
"appearance" : "dark",
"value" : "system-dark"
}
],
"groups" : [
{
"layers" : [
{
"blend-mode-specializations" : [
{
"appearance" : "dark",
"value" : "normal"
}
],
"glass-specializations" : [
{
"value" : false
},
{
"appearance" : "dark",
"value" : false
},
{
"appearance" : "tinted",
"value" : false
}
],
"hidden" : false,
"image-name" : "ontime-icon.png",
"name" : "ontime-icon",
"position" : {
"scale" : 1,
"translation-in-points" : [
-0.5,
-113
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.5
},
"translucency" : {
"enabled" : true,
"value" : 0.5
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}
@@ -1,5 +1,5 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import { type ErrorResponse, RefetchKey } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
@@ -8,7 +8,7 @@ import { defaultCss } from '../../bundle/bundledCss.js';
import { readCssFile, writeCssFile, writeUserTranslation } from './assets.service.js';
import { validatePostCss, validatePostTranslation } from './assets.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/css', async (_req: Request, res: Response<string | ErrorResponse>) => {
try {
@@ -24,7 +24,6 @@ router.post('/css', validatePostCss, async (req: Request, res: Response<never |
const { css } = req.body;
try {
await writeCssFile(css);
sendRefetch(RefetchKey.CssOverride);
res.status(204).send();
} catch (error) {
const message = getErrorMessage(error);
@@ -53,7 +52,6 @@ router.post('/translations', validatePostTranslation, async (req: Request, res:
try {
await writeUserTranslation(translation);
sendRefetch(RefetchKey.Translation);
res.status(204).send();
} catch (error) {
const message = getErrorMessage(error);
@@ -1,8 +1,9 @@
import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
import type { TranslationObject } from 'ontime-types';
import { RefetchKey, type TranslationObject } from 'ontime-types';
import { sendRefetch } from '../../adapters/WebsocketAdapter.js';
import { defaultCss } from '../../bundle/bundledCss.js';
import { publicFiles } from '../../setup/index.js';
@@ -33,6 +34,9 @@ export async function writeCssFile(css: string) {
}
await writeFile(path, css, { encoding: 'utf8' });
setImmediate(() => {
sendRefetch(RefetchKey.CssOverride);
});
}
/**
@@ -43,4 +47,7 @@ export async function writeUserTranslation(translations: TranslationObject) {
const path = publicFiles.translationsFile;
const translationsString = JSON.stringify(translations, null, 2);
await writeFile(path, translationsString, { encoding: 'utf8' });
setImmediate(() => {
sendRefetch(RefetchKey.Translation);
});
}
@@ -1,4 +1,4 @@
import express from 'express';
import express, { Router } from 'express';
import { paramsWithId } from '../validation-utils/validationFunction.js';
import {
@@ -21,7 +21,7 @@ import {
validateTriggerPatch,
} from './automation.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/', getAutomationSettings);
router.post('/', validateAutomationSettings, postAutomationSettings);
@@ -1,5 +1,5 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import { CustomField, CustomFields, ErrorResponse } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
@@ -8,12 +8,12 @@ import { getProjectCustomFields } from '../rundown/rundown.dao.js';
import { createCustomField, deleteCustomField, editCustomField } from '../rundown/rundown.service.js';
import { validateCustomField, validateDeleteCustomField, validateEditCustomField } from './customFields.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
/**
* Gets all the custom fields for the project
*/
router.get('/', async (_req: Request, res: Response<CustomFields>) => {
router.get('/', (_req: Request, res: Response<CustomFields>) => {
const customFields = getProjectCustomFields();
res.status(200).json(customFields);
});
@@ -1,5 +1,5 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import { type CustomViewsListResponse, type ErrorResponse, type MessageResponse } from 'ontime-types';
import { handleCustomViewsError } from './customViews.errors.js';
@@ -13,7 +13,7 @@ import {
} from './customViews.service.js';
import { validateCustomViewSlugParam } from './customViews.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/', async (_req: Request, res: Response<CustomViewsListResponse | ErrorResponse>) => {
try {
+2 -2
View File
@@ -1,4 +1,4 @@
import express from 'express';
import express, { Router } from 'express';
import {
createProjectFile,
@@ -24,7 +24,7 @@ import {
validateQuickProject,
} from './db.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/', currentProjectDownload);
router.post('/download', validateFilenameBody, projectDownload);
+10 -6
View File
@@ -1,11 +1,12 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import type {
ErrorResponse,
SpreadsheetPreviewResponse,
SpreadsheetWorksheetMetadata,
SpreadsheetWorksheetOptions,
} from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
import { getProjectCustomFields } from '../rundown/rundown.dao.js';
@@ -19,7 +20,7 @@ import {
validateWorksheetMetadataRequest,
} from './excel.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.post(
'/upload',
@@ -32,7 +33,8 @@ router.post(
const worksheetOptions = await readExcelFile(filePath);
res.status(200).send(worksheetOptions);
} catch (error) {
res.status(500).send({ message: String(error) });
const message = getErrorMessage(error);
res.status(500).send({ message });
}
},
);
@@ -46,7 +48,8 @@ router.post(
const data = generateRundownPreview(options);
res.status(200).send(data);
} catch (error) {
res.status(500).send({ message: String(error) });
const message = getErrorMessage(error);
res.status(500).send({ message });
}
},
);
@@ -60,7 +63,8 @@ router.post(
const data = getWorksheetMetadata(worksheet);
res.status(200).send(data);
} catch (error) {
res.status(500).send({ message: String(error) });
const message = getErrorMessage(error);
res.status(500).send({ message });
}
},
);
@@ -75,7 +79,7 @@ router.get('/:rundownId/export', validateRundownExport, (req: Request, res: Resp
res.setHeader('Content-Type', EXCEL_MIME);
res.setHeader('Content-Length', buffer.length.toString());
res.status(200).send(buffer);
} catch (error) {
} catch (_error) {
res.status(500).send({ message: 'Failed to generate Excel file' });
}
});
+2 -2
View File
@@ -1,4 +1,4 @@
import express from 'express';
import express, { Router } from 'express';
import { router as assetsRouter } from './assets/assets.router.js';
import { router as automationsRouter } from './automation/automation.router.js';
@@ -15,7 +15,7 @@ import { router as sheetsRouter } from './sheets/sheets.router.js';
import { router as urlPresetsRouter } from './url-presets/urlPresets.router.js';
import { router as viewSettingsRouter } from './view-settings/viewSettings.router.js';
export const appRouter = express.Router();
export const appRouter: Router = express.Router();
appRouter.use('/automations', automationsRouter);
appRouter.use('/custom-fields', customFieldsRouter);
@@ -1,5 +1,5 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import type { ErrorResponse, ProjectData } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
@@ -9,7 +9,7 @@ import { uploadImageFile } from '../db/db.middleware.js';
import * as projectDao from './projectData.dao.js';
import { projectSanitiser } from './projectData.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/', (_req: Request, res: Response<ProjectData>) => {
res.status(200).json(projectDao.getProjectData());
@@ -1,10 +1,10 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import { paramsWithId } from '../validation-utils/validationFunction.js';
import * as report from './report.service.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/', (_req: Request, res: Response) => {
res.status(200).json(report.generate());
@@ -98,7 +98,7 @@ describe('processRundown()', () => {
Object.keys(result?.entries ?? {}).length,
'events',
);
expect(t2 - t1).lessThan(100);
expect(t2 - t1).lessThan(120);
});
it('generates metadata from given rundown', () => {
@@ -851,6 +851,98 @@ describe('rundownMutation.removeAll()', () => {
});
});
describe('rundownMutation.renumber()', () => {
it('sets cues from integer start and increment with no fractional part', () => {
const rundown = makeRundown({
order: ['a', 'b', 'c'],
entries: {
a: makeOntimeEvent({ id: 'a', cue: 'old-a' }),
b: makeOntimeEvent({ id: 'b', cue: 'old-b' }),
c: makeOntimeEvent({ id: 'c', cue: 'old-c' }),
},
});
rundownMutation.renumber(
rundown,
['a', 'b', 'c'],
'Q',
{ integer: 10, faction: 0, precision: 0 },
{ integer: 2, faction: 0, precision: 0 },
);
expect((rundown.entries['a'] as OntimeEvent).cue).toBe('Q10');
expect((rundown.entries['b'] as OntimeEvent).cue).toBe('Q12');
expect((rundown.entries['c'] as OntimeEvent).cue).toBe('Q14');
});
it('pads fractional segment to maxPrecision and steps faction by increment', () => {
const rundown = makeRundown({
order: ['a', 'b', 'c', 'd'],
entries: {
a: makeOntimeEvent({ id: 'a' }),
b: makeOntimeEvent({ id: 'b' }),
c: makeOntimeEvent({ id: 'c' }),
d: makeOntimeEvent({ id: 'd' }),
},
});
rundownMutation.renumber(
rundown,
['a', 'b', 'c', 'd'],
'',
{ integer: 1, faction: 0, precision: 2 },
{ integer: 0, faction: 25, precision: 2 },
);
expect((rundown.entries['a'] as OntimeEvent).cue).toBe('1.00');
expect((rundown.entries['b'] as OntimeEvent).cue).toBe('1.25');
expect((rundown.entries['c'] as OntimeEvent).cue).toBe('1.50');
expect((rundown.entries['d'] as OntimeEvent).cue).toBe('1.75');
});
it('throws when an id is not an event', () => {
const rundown = makeRundown({
order: ['e', 'd'],
entries: {
e: makeOntimeEvent({ id: 'e' }),
d: makeOntimeDelay({ id: 'd' }),
},
});
expect(() =>
rundownMutation.renumber(
rundown,
['e', 'd'],
'X',
{ integer: 1, faction: 0, precision: 0 },
{ integer: 1, faction: 0, precision: 0 },
),
).toThrowError('A given id was not an event');
});
it('handles mixed precision', () => {
const rundown = makeRundown({
order: ['a', 'b', 'c', 'd'],
entries: {
a: makeOntimeEvent({ id: 'a' }),
b: makeOntimeEvent({ id: 'b' }),
c: makeOntimeEvent({ id: 'c' }),
d: makeOntimeEvent({ id: 'd' }),
},
});
const inc = { integer: 0, faction: 5, precision: 1 }; // 0.5
const start = { integer: 1, faction: 5, precision: 2 }; // 1.05
rundownMutation.renumber(rundown, ['a', 'b', 'c', 'd'], 'X', start, inc);
expect((rundown.entries['a'] as OntimeEvent).cue).toBe('X1.05');
expect((rundown.entries['b'] as OntimeEvent).cue).toBe('X1.55');
expect((rundown.entries['c'] as OntimeEvent).cue).toBe('X1.105');
expect((rundown.entries['d'] as OntimeEvent).cue).toBe('X1.155');
});
});
describe('rundownMutation.reorder()', () => {
it('moves an event into a group', () => {
const rundown = makeRundown({
@@ -9,6 +9,7 @@ import {
deleteById,
doesInvalidateMetadata,
duplicateRundown,
getIntegerAndFraction,
hasChanges,
makeDeepClone,
} from '../rundown.utils.js';
@@ -281,3 +282,29 @@ describe('makeDeepClone()', () => {
]);
});
});
describe('getIntegerAndFraction()', () => {
test('integer without fraction', () => {
expect(getIntegerAndFraction('123')).toStrictEqual({ integer: 123, faction: 0, precision: 0 });
});
test('integer and fraction', () => {
expect(getIntegerAndFraction('123.456')).toStrictEqual({ integer: 123, faction: 456, precision: 3 });
});
test('invalid integer', () => {
expect(() => getIntegerAndFraction('abc.456')).toThrowError('input can not be converted to a number');
});
test('indicate precision just with zeros', () => {
expect(getIntegerAndFraction('123.000')).toStrictEqual({ integer: 123, faction: 0, precision: 3 });
});
test('invalid fraction', () => {
expect(() => getIntegerAndFraction('123.abc')).toThrowError('input can not be converted to a number');
});
test('floating separator', () => {
expect(getIntegerAndFraction('123.')).toStrictEqual({ integer: 123, faction: 0, precision: 0 });
});
});
@@ -38,6 +38,7 @@ import {
deleteById,
doesInvalidateMetadata,
getUniqueId,
IncrementNumber,
makeDeepClone,
} from './rundown.utils.js';
@@ -531,6 +532,40 @@ function ungroup(rundown: Rundown, group: OntimeGroup) {
}
}
/**
* Renumbers a range of events
*/
function renumber(
rundown: Rundown,
ids: EntryId[],
prefix: string,
start: IncrementNumber,
increment: IncrementNumber,
) {
const maxPrecision = Math.max(increment.precision, start.precision);
//scale both factions so they have matching precision
increment.faction = increment.faction * Math.pow(10, maxPrecision - increment.precision);
start.faction = start.faction * Math.pow(10, maxPrecision - start.precision);
for (let i = 0; i < ids.length; i++) {
const currentId = ids[i];
const currentEntry = rundown.entries[currentId];
if (!currentEntry || !isOntimeEvent(currentEntry)) throw new Error('A given id was not an event');
//note: we know this dose not handle role over from the fraction into the integer
const integer = String(start.integer + increment.integer * i);
const fraction = maxPrecision
? '.' + String(start.faction + increment.faction * i).padStart(maxPrecision, '0')
: '';
rundownMutation.edit(rundown, {
id: currentId,
cue: `${prefix}${integer}${fraction}`,
});
}
}
export const rundownMutation = {
add: addToRundown,
edit,
@@ -542,6 +577,7 @@ export const rundownMutation = {
clone,
group,
ungroup,
renumber,
};
/**
@@ -1,6 +1,7 @@
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import express from 'express';
import { ErrorResponse, OntimeEntry, ProjectRundownsList, Rundown } from 'ontime-types';
import { matchedData } from 'express-validator';
import { ErrorResponse, OntimeEntry, ProjectRundownsList, RenumberCues, Rundown } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
@@ -18,6 +19,7 @@ import {
groupEntries,
initRundown,
loadRundown,
renumberEntries,
reorderEntry,
swapEvents,
ungroupEntries,
@@ -28,6 +30,7 @@ import {
entryBatchPutValidator,
entryPostValidator,
entryPutValidator,
entryRenumberValidator,
entryReorderValidator,
entrySwapValidator,
rundownArrayOfIds,
@@ -35,7 +38,7 @@ import {
validateRundownMutation,
} from './rundown.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
// #region operations on project rundowns =========================
@@ -373,4 +376,23 @@ router.delete(
},
);
/**
* Reorders two entries in a rundown
*/
router.patch(
'/:rundownId/renumber',
entryRenumberValidator,
validateRundownMutation,
(req: Request, res: Response<Rundown | ErrorResponse>) => {
try {
const { ids, prefix, start, increment } = matchedData<RenumberCues>(req);
const rundown = renumberEntries(ids, prefix, start, increment);
res.status(200).send(rundown);
} catch (error) {
const message = getErrorMessage(error);
res.status(400).send({ message });
}
},
);
// #endregion operations on rundown entries =======================
@@ -33,7 +33,7 @@ import {
updateBackgroundRundown,
} from './rundown.dao.js';
import type { RundownMetadata } from './rundown.types.js';
import { generateEvent, hasChanges } from './rundown.utils.js';
import { generateEvent, getIntegerAndFraction, hasChanges } from './rundown.utils.js';
/**
* creates a new entry with given data
@@ -61,7 +61,7 @@ export async function addEntry(eventData: EventPostPayload): Promise<OntimeEntry
const afterId = getInsertAfterId(rundown, parent, eventData?.after, eventData?.before);
// generate a fully formed entry from the patch
const newEntry = generateEvent(rundown, eventData, afterId);
const newEntry = generateEvent(rundown, eventData, afterId, parent?.id);
// make mutations to rundown
rundownMutation.add(rundown, newEntry, afterId, parent);
@@ -140,7 +140,7 @@ export async function batchEditEntries(ids: EntryId[], patch: Partial<OntimeEntr
let batchDidInvalidate = false;
const changedIds: EntryId[] = [];
const patchedEntries: OntimeEntry[] = [];
for (let i = 0; i < ids.length; i++) {
const currentId = ids[i];
const currentEntry = rundown.entries[currentId];
@@ -165,10 +165,9 @@ export async function batchEditEntries(ids: EntryId[], patch: Partial<OntimeEntr
continue;
}
const { entry, didInvalidate } = rundownMutation.edit(rundown, { ...patch, id: currentId });
const { didInvalidate } = rundownMutation.edit(rundown, { ...patch, id: currentId });
changedIds.push(currentId);
patchedEntries.push(entry);
if (didInvalidate) {
batchDidInvalidate = true;
@@ -270,6 +269,30 @@ export async function reorderEntry(entryId: EntryId, destinationId: EntryId, ord
return rundownResult;
}
/**
* @throws if an id is missing or not an Ontime event
*/
export function renumberEntries(ids: EntryId[], prefix: string, start: string, increment: string): Rundown {
const startNumber = getIntegerAndFraction(start);
const incrementNumber = getIntegerAndFraction(increment);
// if the prefix doesn't already include a separator or is empty, then insert a separator
if (prefix !== '' && !prefix.endsWith('-') && !prefix.endsWith(' ')) prefix += ' ';
const { rundown, commit } = createTransaction({ mutableRundown: true, mutableCustomFields: false });
rundownMutation.renumber(rundown, ids, prefix, startNumber, incrementNumber);
const { rundown: rundownResult, rundownMetadata, revision } = commit(false);
setImmediate(() => {
updateRuntimeOnChange(rundownMetadata);
notifyChanges(rundownMetadata, revision, { timer: ids, external: true });
});
return rundownResult;
}
/**
* Applies a delay into the rundown effectively changing the schedule
* The applied delay is deleted
@@ -50,9 +50,12 @@ type CompleteEntry<T> =
*/
export function generateEvent<
T extends Partial<OntimeEvent> | Partial<OntimeDelay> | Partial<OntimeGroup> | Partial<OntimeMilestone>,
>(rundown: Rundown, eventData: T, afterId: EntryId | null): CompleteEntry<T> {
>(rundown: Rundown, eventData: T, afterId: EntryId | null, parent?: EntryId): CompleteEntry<T> {
if (isOntimeEvent(eventData)) {
return createEvent(eventData, getCueCandidate(rundown.entries, rundown.order, afterId)) as CompleteEntry<T>;
return createEvent(
eventData,
getCueCandidate(rundown.entries, rundown.flatOrder, afterId, parent),
) as CompleteEntry<T>;
}
const id = eventData.id || getUniqueId(rundown);
@@ -470,3 +473,30 @@ export function duplicateRundown(rundown: Rundown, newTitle: string): Rundown {
return newRundown;
}
export type IncrementNumber = {
integer: number;
faction: number;
precision: number;
};
/**
* Parses a decimal string into integer part, fractional digits as an integer, and fractional digit count.
* Splits on the first `.` only
*
* @param value - Numeric string, e.g. `"123"` or `"123.456"`.
* @returns `integer` whole part, `faction` digits after the point as a number (0 when no fraction), `precision` digit count after `.`.
* @throws {Error} When the integer or fractional segment is not parseable as number
*/
export function getIntegerAndFraction(value: string): IncrementNumber {
const [integerStr, factionStr] = value.split('.', 2);
const integer = parseInt(integerStr);
const precision = (factionStr ?? '').length;
const faction = precision === 0 ? 0 : parseInt(factionStr);
if (isNaN(integer) || isNaN(faction)) throw new Error('input can not be converted to a number');
return {
integer,
faction,
precision,
};
}
@@ -83,4 +83,13 @@ export const rundownArrayOfIds = [
requestValidationFunction,
];
export const entryRenumberValidator = [
body('ids').isArray().notEmpty(),
body('ids.*').isString(),
body('prefix').isString(),
body('start').isDecimal(),
body('increment').isDecimal(),
requestValidationFunction,
];
// #endregion operations on rundown entries =======================
@@ -1,12 +1,12 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import type { ErrorResponse, GetInfo, GetUrl, SessionStats } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
import * as sessionService from './session.service.js';
import { validateGenerateUrl } from './session.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/', async (_req: Request, res: Response<SessionStats | ErrorResponse>) => {
try {
@@ -18,9 +18,9 @@ router.get('/', async (_req: Request, res: Response<SessionStats | ErrorResponse
}
});
router.get('/info', async (_req: Request, res: Response<GetInfo | ErrorResponse>) => {
router.get('/info', (_req: Request, res: Response<GetInfo | ErrorResponse>) => {
try {
const info = await sessionService.getInfo();
const info = sessionService.getInfo();
res.status(200).send(info);
} catch (error) {
const message = getErrorMessage(error);
@@ -37,7 +37,7 @@ export async function getSessionStats(): Promise<SessionStats> {
/**
* Adds business logic to gathering data for the info endpoint
*/
export async function getInfo(): Promise<GetInfo> {
export function getInfo(): GetInfo {
const { version } = getDataProvider().getSettings();
const { port } = portManager.getPort();
@@ -1,5 +1,5 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import { matchedData } from 'express-validator';
import { deepEqual } from 'fast-equals';
import { ErrorResponse, PortInfo, RefetchKey, Settings } from 'ontime-types';
@@ -11,7 +11,7 @@ import { portManager } from '../../classes/port-manager/PortManager.js';
import * as appState from '../../services/app-state-service/AppStateService.js';
import { validateSettings, validateWelcomeDialog, validateServerPort } from './settings.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.post('/welcomedialog', validateWelcomeDialog, async (req: Request, res: Response) => {
const show = await appState.setShowWelcomeDialog(req.body.show);
@@ -56,7 +56,7 @@ export async function requestConnection(
/**
* Returns the current Google Sheets authentication status for this server session.
*/
export async function verifyAuthentication(
export function verifyAuthentication(
_req: Request,
res: Response<{ authenticated: AuthenticationStatus } | ErrorResponse>,
) {
@@ -72,7 +72,7 @@ export async function verifyAuthentication(
/**
* Clears the current Google Sheets authentication session.
*/
export async function revokeAuthentication(
export function revokeAuthentication(
_req: Request,
res: Response<{ authenticated: AuthenticationStatus } | ErrorResponse>,
) {
@@ -2,7 +2,7 @@
* This is a feature specific router for integration with google sheets
*/
import express from 'express';
import express, { Router } from 'express';
import {
getWorksheetMetadataFromSheet,
@@ -21,7 +21,7 @@ import {
validateWorksheetMetadata,
} from './sheets.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/connect', verifyAuthentication);
router.post('/:sheetId/connect', uploadClientSecret, validateRequestConnection, requestConnection);
@@ -223,10 +223,15 @@ export function hasAuth(): { authenticated: AuthenticationStatus; sheetId: strin
return { authenticated: currentAuthClient ? 'authenticated' : 'not_authenticated', sheetId: currentSheetId };
}
type VerifySheetResult = {
worksheets: string[];
title: string;
};
/**
* Validates that a spreadsheet exists and returns its worksheet titles without reading cell data.
*/
async function verifySheet(sheetId = currentSheetId, authClient = currentAuthClient): Promise<string[]> {
async function verifySheet(sheetId = currentSheetId, authClient = currentAuthClient): Promise<VerifySheetResult> {
if (!sheetId || !authClient) {
throw new Error('Missing sheet ID or authentication');
}
@@ -247,7 +252,9 @@ async function verifySheet(sheetId = currentSheetId, authClient = currentAuthCli
if (worksheets.length === 0) {
throw new Error('No worksheets found');
}
return worksheets;
const title = spreadsheets.data.properties?.title ?? '';
return { worksheets, title };
} catch (error) {
// attempt to catch errors caused by importing xlsx
catchCommonImportXlsxError(error);
@@ -287,17 +294,18 @@ export async function handleInitialConnection(
*/
export async function getWorksheetOptions(
sheetId: string,
): Promise<{ worksheets: string[]; metadata: SpreadsheetWorksheetMetadata | null }> {
): Promise<{ worksheets: string[]; metadata: SpreadsheetWorksheetMetadata | null; title: string }> {
if (!currentAuthClient) {
throw new Error('Not authenticated');
}
currentSheetId = sheetId;
const worksheets = await verifySheet(sheetId);
const { worksheets, title } = await verifySheet(sheetId);
return {
worksheets,
metadata: null,
title,
};
}
@@ -1,5 +1,5 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import { type ErrorResponse, RefetchKey, type URLPreset } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
@@ -7,7 +7,7 @@ import { sendRefetch } from '../../adapters/WebsocketAdapter.js';
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
import { validateNewPreset, validatePresetParam, validateUpdatePreset } from './urlPresets.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/', (_req: Request, res: Response<URLPreset[]>) => {
const presets = getDataProvider().getUrlPresets();
@@ -1,5 +1,5 @@
import express from 'express';
import type { Request, Response } from 'express';
import type { Request, Response, Router } from 'express';
import { type ErrorResponse, RefetchKey, type ViewSettings } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
@@ -7,7 +7,7 @@ import { sendRefetch } from '../../adapters/WebsocketAdapter.js';
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
import { validateViewSettings } from './viewSettings.validation.js';
export const router = express.Router();
export const router: Router = express.Router();
router.get('/', (_req: Request, res: Response<ViewSettings>) => {
const views = getDataProvider().getViewSettings();
@@ -5,7 +5,7 @@
*
*/
import express, { type Request, type Response } from 'express';
import express, { Router, type Request, type Response } from 'express';
import { ErrorResponse, LogOrigin } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils';
@@ -14,7 +14,7 @@ import { logger } from '../classes/Logger.js';
import { isEmptyObject } from '../utils/parserUtils.js';
import { dispatchFromAdapter } from './integration.controller.js';
export const integrationRouter = express.Router();
export const integrationRouter: Router = express.Router();
const helloMessage = 'You have reached Ontime API server';
+2 -2
View File
@@ -1,7 +1,7 @@
import type { IncomingMessage } from 'node:http';
import { parse as parseCookie } from 'cookie';
import express, { type NextFunction, type Request, type Response } from 'express';
import express, { Router, type NextFunction, type Request, type Response } from 'express';
import type { WebSocket } from 'ws';
import { hasPassword, hashedPassword } from '../api-data/session/session.service.js';
@@ -40,7 +40,7 @@ export function isPublicAssetRequest(originalUrl: string, prefix: string): boole
* @param {string} prefix - Prefix is used for the client hashes in Ontime Cloud
*/
export function makeLoginRouter(prefix: string) {
const router = express.Router();
const router: Router = express.Router();
// serve static files at root
router.use('/', express.static(srcFiles.login));
@@ -191,7 +191,7 @@ test('Add event', async ({ page }) => {
// add event above
await page.getByTestId('rundown-event').locator('div').filter({ hasText: '1' }).press('Alt+Shift+E');
await expect(page.getByTestId('rundown-event')).toHaveCount(3);
await expect(page.getByTestId('entry-1').getByTestId('rundown-event')).toContainText('0.1');
await expect(page.getByTestId('entry-1').getByTestId('rundown-event')).toContainText('1');
});
test('Delete event', async ({ page }) => {
@@ -16,7 +16,7 @@ test('imports spreadsheet and applies imported rundown to editor', async ({ page
await page.getByRole('button', { name: 'Toggle settings' }).click();
await page.getByRole('button', { name: 'Project settings' }).click();
await page.getByRole('button', { name: 'Import spreadsheet' }).first().click();
await expect(page.getByText('Synchronise your rundown with an external source')).toBeVisible();
await expect(page.getByText('Synchronize your rundown with an external source')).toBeVisible();
// upload the spreadsheet
const fileChooserPromise = page.waitForEvent('filechooser');
@@ -29,3 +29,10 @@ export type RundownSummary = {
start: MaybeNumber;
end: MaybeNumber;
};
export type RenumberCues = {
ids: EntryId[];
prefix: string;
start: string;
increment: string;
};
@@ -10,6 +10,7 @@ export type SpreadsheetWorksheetMetadata = {
export type SpreadsheetWorksheetOptions = {
worksheets: string[];
metadata: SpreadsheetWorksheetMetadata | null;
title?: string;
};
export type SpreadsheetPreviewResponse = {
+1
View File
@@ -89,6 +89,7 @@ export type {
ProjectRundownsList,
TransientEventPayload,
RundownSummary,
RenumberCues,
} from './api/rundown-controller/BackendResponse.type.js';
export type { LinkOptions } from './api/session-controller/BackendResponse.type.js';
export type { CustomViewSummary, CustomViewsListResponse } from './api/custom-views/customViews.type.js';
-1
View File
@@ -4,7 +4,6 @@ export { isKnownTimerType, validateTimeStrategy } from './src/validate-events/va
export { calculateDuration, getLinkedTimes, validateTimes } from './src/validate-times/validateTimes.js';
// rundown utils
export { sanitiseCue } from './src/cue-utils/cueUtils.js';
export { getCueCandidate } from './src/cue-utils/cueUtils.js';
export { generateId } from './src/generate-id/generateId.js';
export {
+45 -49
View File
@@ -1,7 +1,7 @@
import type { OntimeDelay, OntimeEntry, OntimeEvent, RundownEntries } from 'ontime-types';
import type { OntimeDelay, OntimeEntry, OntimeEvent, OntimeGroup, OntimeMilestone, RundownEntries } from 'ontime-types';
import { SupportedEntry } from 'ontime-types';
import { getCueCandidate, getIncrement, sanitiseCue } from './cueUtils.js';
import { getCueCandidate, getIncrement } from './cueUtils.js';
describe('getIncrement()', () => {
it('increments number', () => {
@@ -12,24 +12,30 @@ describe('getIncrement()', () => {
});
it('increments decimal number', () => {
expect(getIncrement('1.1')).toBe('1.2');
expect(getIncrement('1.9')).toBe('1.10');
expect(getIncrement('10.10')).toBe('10.11');
expect(getIncrement('99.99')).toBe('99.100');
expect(getIncrement('101.101')).toBe('101.102');
// NOTE: we know the below would fail, handling this amount of decimals is outside of scope
// expect(getIncrement('101.999')).toBe('101.1000');
expect(getIncrement('101.999')).toBe('101.1000');
});
// NOTE: we also know the following fails since we only handle one decimal
//it('handles multiple decimals', () => {
// expect(getIncrement('2.1.1')).toBe('2.1.2');
//});
it('finds last digit in string', () => {
it.fails('handles multiple decimals', () => {
expect(getIncrement('2.1.1')).toBe('2.1.2');
});
it('finds last digit in string without separator', () => {
expect(getIncrement('Presenter1')).toBe('Presenter2');
expect(getIncrement('Presenter10')).toBe('Presenter11');
expect(getIncrement('Presenter99')).toBe('Presenter100');
expect(getIncrement('Presenter101')).toBe('Presenter102');
});
it('finds last digit in string with space separator', () => {
expect(getIncrement('Presenter 1')).toBe('Presenter 2');
expect(getIncrement('Presenter 10')).toBe('Presenter 11');
expect(getIncrement('Presenter 99')).toBe('Presenter 100');
expect(getIncrement('Presenter 101')).toBe('Presenter 102');
});
it('adds a 2 if none is found', () => {
expect(getIncrement('Presenter')).toBe('Presenter2');
expect(getIncrement('Presenter')).toBe('Presenter-2');
});
});
@@ -43,15 +49,6 @@ describe('getCueCandidate()', () => {
const cue = getCueCandidate(entries, ['1', '2'], null);
expect(cue).toBe('1');
});
it('creates decimal stem if next cue is 1', () => {
const entries: RundownEntries = {
'1': { id: '1', cue: '1', type: SupportedEntry.Event } as OntimeEvent,
'2': { id: '2', cue: '10', type: SupportedEntry.Event } as OntimeEvent,
};
const cue = getCueCandidate(entries, ['1', '2'], null);
expect(cue).toBe('0.1');
});
});
describe('in the middle of the rundown', () => {
@@ -74,10 +71,10 @@ describe('getCueCandidate()', () => {
} as OntimeEntry,
};
const cue = getCueCandidate(entries, ['1', '2'], '1');
expect(cue).toBe('Presenter2');
expect(cue).toBe('Presenter-2');
});
it('creates decimal stem if next cue has same stem (case of numbers)', () => {
it.fails('creates decimal stem if next cue has same stem (case of numbers)', () => {
const entries: RundownEntries = {
'1': { id: '1', cue: '1', type: SupportedEntry.Event } as OntimeEvent,
'2': { id: '2', cue: '2', type: SupportedEntry.Event } as OntimeEvent,
@@ -86,7 +83,7 @@ describe('getCueCandidate()', () => {
expect(cue).toBe('1.1');
});
it('creates decimal stem if next cue has same stem (case of letters)', () => {
it.fails('creates decimal stem if next cue has same stem (case of letters)', () => {
const entries: RundownEntries = {
'1': { id: '1', cue: 'Presenter1', type: SupportedEntry.Event } as OntimeEvent,
'2': { id: '2', cue: 'Presenter2', type: SupportedEntry.Event } as OntimeEvent,
@@ -99,22 +96,33 @@ describe('getCueCandidate()', () => {
describe('considers edge cases', () => {
it('previousEvent might not be a cue', () => {
const entries: RundownEntries = {
'1': { id: '1', cue: '10', type: SupportedEntry.Event } as OntimeEvent,
'0': { id: '0', cue: '10', type: SupportedEntry.Event } as OntimeEvent,
'1': { id: '1', type: SupportedEntry.Milestone } as OntimeMilestone,
'2': { id: '2', type: SupportedEntry.Delay } as OntimeDelay,
};
const cue = getCueCandidate(entries, ['0', '1', '2'], '2');
expect(cue).toBe('11');
});
it('previousEvent might not be a group', () => {
const entries: RundownEntries = {
'0': { id: '0', cue: '10', type: SupportedEntry.Event } as OntimeEvent,
'1': { id: '1', type: SupportedEntry.Milestone } as OntimeMilestone,
'2': { id: '2', type: SupportedEntry.Group } as OntimeGroup,
};
const cue = getCueCandidate(entries, ['0', '1', '2'], null, '2');
expect(cue).toBe('11');
});
it('there might not be events before', () => {
const entries: RundownEntries = {
'1': { id: '1', type: SupportedEntry.Delay } as OntimeDelay,
'2': { id: '2', type: SupportedEntry.Delay } as OntimeDelay,
};
const cue = getCueCandidate(entries, ['1', '2'], '2');
expect(cue).toBe('11');
expect(cue).toBe('1');
});
});
it('there might not be events before', () => {
const entries: RundownEntries = {
'1': { id: '1', type: SupportedEntry.Delay } as OntimeDelay,
'2': { id: '2', type: SupportedEntry.Delay } as OntimeDelay,
};
const cue = getCueCandidate(entries, ['1', '2'], '2');
expect(cue).toBe('1');
});
});
describe('findCueName() with mixed events', () => {
@@ -128,7 +136,8 @@ describe('findCueName() with mixed events', () => {
expect(cue).toBe('1');
});
it('creates decimal stem if next cue is 1', () => {
// we let this fail to reduced complexity
it.fails('creates decimal stem if next cue is 1', () => {
const entries: RundownEntries = {
'1': { id: '1', cue: '1', type: SupportedEntry.Event } as OntimeEvent,
'2': { id: '2', cue: '10', type: SupportedEntry.Event } as OntimeEvent,
@@ -154,10 +163,10 @@ describe('findCueName() with mixed events', () => {
'2': { id: '2', cue: 'Interval', type: SupportedEntry.Event } as OntimeEvent,
};
const cue = getCueCandidate(entries, ['1', '2'], '1');
expect(cue).toBe('Presenter2');
expect(cue).toBe('Presenter-2');
});
it('creates decimal stem if next cue has same stem (case of numbers)', () => {
it.fails('creates decimal stem if next cue has same stem (case of numbers)', () => {
const entries: RundownEntries = {
'1': { id: '1', cue: '1', type: SupportedEntry.Event } as OntimeEvent,
'2': { id: '2', cue: '2', type: SupportedEntry.Event } as OntimeEvent,
@@ -166,7 +175,7 @@ describe('findCueName() with mixed events', () => {
expect(cue).toBe('1.1');
});
it('creates decimal stem if next cue has same stem (case of letters)', () => {
it.fails('creates decimal stem if next cue has same stem (case of letters)', () => {
const entries: RundownEntries = {
'1': { id: '1', cue: 'Presenter1', type: SupportedEntry.Event } as OntimeEvent,
'2': { id: '2', cue: 'Presenter2', type: SupportedEntry.Event } as OntimeEvent,
@@ -176,16 +185,3 @@ describe('findCueName() with mixed events', () => {
});
});
});
describe('sanitiseCue()', () => {
it('removes spaces', () => {
expect(sanitiseCue(' test')).toBe('test');
expect(sanitiseCue(' test ')).toBe('test');
expect(sanitiseCue('test')).toBe('test');
expect(sanitiseCue('t e s t ')).toBe('test');
});
it('enforces . as decimals', () => {
expect(sanitiseCue('1,2')).toBe('1.2');
expect(sanitiseCue('1,2,3')).toBe('1.2.3');
});
});
+34 -76
View File
@@ -1,13 +1,10 @@
import type { EntryId, OntimeEntry, RundownEntries } from 'ontime-types';
import { isOntimeEvent } from 'ontime-types';
import { getFirstEventNormal, getNextEventNormal, getPreviousEventNormal } from '../rundown-utils/rundownUtils.js';
import { isNumeric } from '../types/types.js';
import { getPreviousEventNormal } from '../rundown-utils/rundownUtils.js';
// Zero or more non-digit characters at the beginning ((\D*)).
// One or more digits ((\d+)).
// Optionally, a decimal part starting with a dot ((\.\d+)?).
const regex = /^(\D*)(\d+)(\.\d+)?$/;
// Groups: 1=prefix, 2=separator(optional dash or space), 3=integer, 4='.', 5=fraction
const regex = /^(\D*?)(?:([ -]))?(\d+)(?:(\.)(\d+))?$/;
/**
* Finds if last characters in input are a number and increments
@@ -15,84 +12,45 @@ const regex = /^(\D*)(\d+)(\.\d+)?$/;
export function getIncrement(input: string): string {
// Check if the input string contains a number at the end
const match = regex.exec(input);
if (match) {
// If a number is found, extract the non-numeric prefix, integer part, and decimal part
// eslint-disable-next-line prefer-const -- some items in the destructuring are modified
let [, prefix, integerPart, decimalPart] = match;
if (decimalPart) {
if (decimalPart === '.99') {
decimalPart = '.100';
} else {
const addDecimal = `${'0'.repeat(decimalPart.length - 2)}1`;
const incrementedDecimal = (Number(decimalPart) + Number(`0.${addDecimal}`)).toFixed(decimalPart.length - 1);
decimalPart = incrementedDecimal.toString().replace('0.', '.');
}
return `${prefix}${integerPart}${decimalPart}`;
}
const incrementedInteger = Number(integerPart) + 1;
integerPart = incrementedInteger.toString();
return `${prefix}${integerPart}`;
}
// If no number is found, append "2" to the string and return the updated string
return `${input}2`;
if (match === null) return `${input}-2`;
const [, prefix, separator, integerPart, _decimalSeparator, decimalPart] = match;
if (decimalPart === undefined) return incrementInteger(prefix, integerPart, separator);
return incrementDecimal(prefix, integerPart, decimalPart, separator);
}
const incrementDecimal = (prefix: string, integerPart: string, decimalPart: string, separator = '') => {
const decimalInteger = parseInt(decimalPart);
const incrementedDecimal = (decimalInteger + 1).toString();
const newDecimalPart = incrementedDecimal.padStart(decimalPart.length, '0');
return `${prefix}${separator ?? ''}${integerPart}.${newDecimalPart}`;
};
const incrementInteger = (prefix: string, integerPart: string, separator = '') => {
const incrementedInteger = parseInt(integerPart) + 1;
const newIntegerPart = incrementedInteger.toString();
return `${prefix}${separator}${newIntegerPart}`;
};
/**
* Gets suitable name for a new event cue
*/
export function getCueCandidate(entries: RundownEntries, order: EntryId[], insertAfterId: EntryId | null): string {
// we did not provide a element to go after, we attempt to go first so only need to check for a cue with value 1
if (insertAfterId === null || order.length === 0) {
return addAtTop();
}
export function getCueCandidate(
entries: RundownEntries,
flatOrder: EntryId[],
insertAfterId: EntryId | null,
parent?: EntryId,
): string {
// we might not get a insertAfterId if we are inserting at the top of a group
// in that case we need to get the id of the group so we can find the proceeding event
const prevId = insertAfterId ? insertAfterId : (parent ?? null);
if (flatOrder.length === 0 || prevId === null) return '1';
// get the given event, or any before that
let previousEvent: OntimeEntry | null | undefined = entries[insertAfterId];
let previousEvent: OntimeEntry | null | undefined = entries[prevId];
if (!isOntimeEvent(previousEvent)) {
previousEvent = getPreviousEventNormal(entries, order, insertAfterId).previousEvent;
if (!isOntimeEvent(previousEvent)) {
return addAtTop();
}
previousEvent = getPreviousEventNormal(entries, flatOrder, prevId).previousEvent;
if (!isOntimeEvent(previousEvent)) return '1';
}
// the cue is based on the previous event cue
const cue = getIncrement(previousEvent.cue);
const { nextEvent } = getNextEventNormal(entries, order, insertAfterId);
// if increment is clashing with next, we add a decimal instead
if (cue !== nextEvent?.cue) {
return cue;
}
// there is a clash, bt the cue is a pure number
if (isNumeric(cue)) {
return incrementDecimal(previousEvent.cue);
}
/**
* at this point, we know the cue is not numeric
* but the increment failed, so we have a numeric ending
* eg. Presenter 1 .... Presenter 2 -> Presenter1.1
* eg. Presenter 1.1 .... Presenter 1.2 -> Presenter1.1.1
*/
return `${previousEvent.cue}.1`;
function incrementDecimal(cue: string) {
const n = Number(cue);
return (n + 0.1).toString();
}
function addAtTop() {
const firstEventCue = getFirstEventNormal(entries, order).firstEvent?.cue;
if (firstEventCue === '1') {
return '0.1';
}
return '1';
}
}
export function sanitiseCue(cue: string) {
return cue.replaceAll(' ', '').replaceAll(',', '.');
return getIncrement(previousEvent.cue);
}
+174 -526
View File
File diff suppressed because it is too large Load Diff