Compare commits

...

27 Commits

Author SHA1 Message Date
Claude 767b567bba Improve editor settings navigation, UX, and visual design
- Unsaved changes guard: confirm dialog when navigating away from dirty forms (GeneralSettings, ProjectData, ViewSettings, ServerPortSettings, AutomationSettingsForm)
- Sticky breadcrumb header: replaces floating close button with a sticky top bar showing current panel › section context
- Scroll-to-sidebar sync: IntersectionObserver in useScrollIntoView feeds active scroll section back into sidebar secondary item highlights
- Rich empty states: ClientList now shows friendly messages for empty Ontime/Other client tables
- Sidebar styling: distinct background, right border, left-accent active indicator (VS Code style)
- Card elevation: raised opacity + box-shadow for visible depth hierarchy
- Border radius: 8px cards and 6px sidebar items using existing theme variable

https://claude.ai/code/session_017jeJF78B4eXcpXAj7KGmnF
2026-05-28 06:51:24 +00:00
Alex Christoffer Rasmussen 9ae49a7175 chore: pnpm 11 + dependency cleanup (#2089)
* core: upgrade to pnpm 11 and nodejs to 22.22.2

* chore: allow builds

* chore: remove unused

* chore: update actions

* chore: add stub for vitest

* reafactor: small optimization
2026-05-17 21:01:16 +02:00
Carlos Valente d30d9cfd4e refactor: account for tick size on translate 2026-05-13 20:26:15 +02:00
Carlos Valente a0e7b9b665 refactor: simplify spacing between help menu items 2026-05-13 20:26:15 +02:00
Carlos Valente 1dcb7fb08d refactor: fix Info text flow 2026-05-13 20:26:15 +02:00
Carlos Valente a7e84b9903 refactor: fixed css editor size 2026-05-13 20:26:15 +02:00
Carlos Valente 3bebbf9ce9 refactor: invalidate changed rundown 2026-05-11 21:25:15 +02:00
Carlos Valente ab8da07518 refactor: improve memoisation on table rows 2026-05-11 21:25:15 +02:00
Carlos Valente c8bae76121 refactor: add empty state for autoamtion form 2026-05-11 20:59:50 +02:00
Carlos Valente 2873698959 bump version to 4.8.0 2026-05-11 19:55:33 +02:00
Cameron Slipp 741ebef90e refactor: improve automation UX 2026-05-11 19:55:01 +02:00
Claude 0741f46aca feat: add self-contained legacy timer viewer for old browsers
Adds timer-legacy.html — a zero-dependency static page that connects
to the Ontime WebSocket and displays the live countdown for browsers
that cannot parse the Vite-built React bundle (Safari < 14, Chrome < 85).

Also adds a synchronous pre-React guard in index.html that redirects
/timer visitors to the legacy page when Promise.any is unavailable,
matching the Vite build target floor of Safari 14 / Chrome 85.

https://claude.ai/code/session_013MfdwdjdDUnr3akpGSGXa4
2026-05-09 22:33:34 +02:00
Carlos Valente 5a33ffad92 refactor: improve background colour inheritance in safari 2026-05-09 22:32:04 +02:00
Claude 562f00dc7e fix: add legacy plugin to support iOS 14 2026-05-09 22:31:30 +02:00
Carlos Valente e50ab0150e docs: add link to youtube 2026-05-09 22:25:32 +02: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
139 changed files with 3172 additions and 1777 deletions
+3 -3
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: 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 # 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 - uses: actions/setup-node@v6
@@ -20,13 +20,13 @@ jobs:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
- name: Setup pnpm - name: Setup pnpm
uses: pnpm/action-setup@v4 uses: pnpm/action-setup@v6
- name: Get pnpm store directory - name: Get pnpm store directory
run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache - name: Setup pnpm cache
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: ${{ env.PNPM_STORE_PATH }} path: ${{ env.PNPM_STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }}
+3 -3
View File
@@ -12,16 +12,16 @@ jobs:
CI: '' CI: ''
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- name: Setup pnpm - name: Setup pnpm
uses: pnpm/action-setup@v4 uses: pnpm/action-setup@v6
- name: Get pnpm store directory - name: Get pnpm store directory
run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache - name: Setup pnpm cache
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: ${{ env.PNPM_STORE_PATH }} path: ${{ env.PNPM_STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }}
+14 -14
View File
@@ -7,23 +7,23 @@ on:
jobs: jobs:
build_macos: build_macos:
runs-on: macOS-latest runs-on: macOS-26
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- uses: actions/setup-node@v6 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
- name: Setup pnpm - name: Setup pnpm
uses: pnpm/action-setup@v4 uses: pnpm/action-setup@v6
- name: Get pnpm store directory - name: Get pnpm store directory
run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache - name: Setup pnpm cache
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: ${{ env.PNPM_STORE_PATH }} path: ${{ env.PNPM_STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }}
@@ -44,7 +44,7 @@ jobs:
timeout-minutes: 60 timeout-minutes: 60
- name: Upload macOS build artifacts - name: Upload macOS build artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v6
if: always() if: always()
with: with:
name: ontime-macos-build name: ontime-macos-build
@@ -54,7 +54,7 @@ jobs:
retention-days: 1 retention-days: 1
- name: Release - name: Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v2
if: github.ref_type == 'tag' if: github.ref_type == 'tag'
with: with:
files: | files: |
@@ -67,14 +67,14 @@ jobs:
runs-on: windows-latest runs-on: windows-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- uses: actions/setup-node@v6 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
- name: Setup pnpm - name: Setup pnpm
uses: pnpm/action-setup@v3 uses: pnpm/action-setup@v6
- name: Install dependencies - name: Install dependencies
run: pnpm install --frozen-lockfile run: pnpm install --frozen-lockfile
@@ -83,7 +83,7 @@ jobs:
run: pnpm dist-win run: pnpm dist-win
- name: Upload Windows build artifacts - name: Upload Windows build artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v6
if: always() if: always()
with: with:
name: ontime-windows-build name: ontime-windows-build
@@ -93,7 +93,7 @@ jobs:
retention-days: 1 retention-days: 1
- name: Release - name: Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v2
if: github.ref_type == 'tag' if: github.ref_type == 'tag'
with: with:
files: './apps/electron/dist/ontime-win64.exe' files: './apps/electron/dist/ontime-win64.exe'
@@ -104,14 +104,14 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- uses: actions/setup-node@v6 - uses: actions/setup-node@v6
with: with:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
- name: Setup pnpm - name: Setup pnpm
uses: pnpm/action-setup@v3 uses: pnpm/action-setup@v6
- name: Install dependencies - name: Install dependencies
run: pnpm install --frozen-lockfile run: pnpm install --frozen-lockfile
@@ -120,7 +120,7 @@ jobs:
run: pnpm dist-linux run: pnpm dist-linux
- name: Upload Linux build artifacts - name: Upload Linux build artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v6
if: always() if: always()
with: with:
name: ontime-linux-build name: ontime-linux-build
@@ -131,7 +131,7 @@ jobs:
retention-days: 1 retention-days: 1
- name: Release - name: Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v2
if: github.ref_type == 'tag' if: github.ref_type == 'tag'
with: with:
files: | files: |
+3 -3
View File
@@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: 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 # 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 - uses: actions/setup-node@v6
@@ -18,13 +18,13 @@ jobs:
node-version-file: '.nvmrc' node-version-file: '.nvmrc'
- name: Setup pnpm - name: Setup pnpm
uses: pnpm/action-setup@v4 uses: pnpm/action-setup@v6
- name: Get pnpm store directory - name: Get pnpm store directory
run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache - name: Setup pnpm cache
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: ${{ env.PNPM_STORE_PATH }} path: ${{ env.PNPM_STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }}
+9 -9
View File
@@ -13,16 +13,16 @@ jobs:
CI: '' CI: ''
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- name: Setup pnpm - name: Setup pnpm
uses: pnpm/action-setup@v4 uses: pnpm/action-setup@v6
- name: Get pnpm store directory - name: Get pnpm store directory
run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache - name: Setup pnpm cache
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: ${{ env.PNPM_STORE_PATH }} path: ${{ env.PNPM_STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }}
@@ -52,16 +52,16 @@ jobs:
timeout-minutes: 20 timeout-minutes: 20
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- name: Setup pnpm - name: Setup pnpm
uses: pnpm/action-setup@v4 uses: pnpm/action-setup@v6
- name: Get pnpm store directory - name: Get pnpm store directory
run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV run: echo "PNPM_STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache - name: Setup pnpm cache
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: ${{ env.PNPM_STORE_PATH }} path: ${{ env.PNPM_STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('pnpm-lock.yaml') }}
@@ -74,7 +74,7 @@ jobs:
- name: Get installed Playwright version - name: Get installed Playwright version
run: echo "PLAYWRIGHT_VERSION=$(pnpm ls @playwright/test --parseable | cut -s -d '@' -f3 | cut -d '/' -f1)" >> $GITHUB_ENV run: echo "PLAYWRIGHT_VERSION=$(pnpm ls @playwright/test --parseable | cut -s -d '@' -f3 | cut -d '/' -f1)" >> $GITHUB_ENV
- name: Cache playwright binaries - name: Cache playwright binaries
uses: actions/cache@v4 uses: actions/cache@v5
with: with:
path: | path: |
~/.cache/ms-playwright ~/.cache/ms-playwright
@@ -90,14 +90,14 @@ jobs:
- name: Run Playwright tests - name: Run Playwright tests
run: pnpm e2e run: pnpm e2e
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v6
if: always() if: always()
with: with:
name: playwright-report name: playwright-report
path: playwright-report/ path: playwright-report/
retention-days: 30 retention-days: 30
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v6
with: with:
name: automated-screenshots name: automated-screenshots
path: automated-screenshots/ path: automated-screenshots/
+1 -1
View File
@@ -1 +1 @@
v22.15.1 v22.22.2
+1 -1
View File
@@ -1,4 +1,4 @@
ARG NODE_VERSION=22.15.1 ARG NODE_VERSION=22.22.2
FROM node:${NODE_VERSION}-alpine FROM node:${NODE_VERSION}-alpine
# Set environment variables # Set environment variables
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@getontime/cli", "name": "@getontime/cli",
"version": "4.7.0", "version": "4.8.0",
"author": "Carlos Valente", "author": "Carlos Valente",
"description": "Time keeping for live events", "description": "Time keeping for live events",
"repository": "https://github.com/cpvalente/ontime", "repository": "https://github.com/cpvalente/ontime",
+9 -1
View File
@@ -4,9 +4,10 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<base href="/" /> <base href="/" />
<link rel="icon" href="favicon.ico" /> <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="theme-color" content="#101010" />
<meta name="ontime" content="ontime - time keeping for live events" /> <meta name="ontime" content="ontime - time keeping for live events" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<link rel="apple-touch-icon" href="ontime-logo.png" /> <link rel="apple-touch-icon" href="ontime-logo.png" />
<link rel="icon" type="image/png" href="ontime-logo.png" /> <link rel="icon" type="image/png" href="ontime-logo.png" />
<link rel="manifest" href="site.webmanifest" /> <link rel="manifest" href="site.webmanifest" />
@@ -17,6 +18,13 @@
<body> <body>
<noscript>You need to enable JavaScript to run this app.</noscript> <noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div> <div id="root"></div>
<script>
if (/\/timer\/?$/.test(window.location.pathname) && typeof Promise.any !== 'function') {
var b = document.querySelector('base');
var base = b ? (b.getAttribute('href') || '').replace(/\/$/, '') : '';
window.location.replace(base + '/timer-legacy' + window.location.search);
}
</script>
<script type="module" src="/src/index.tsx"></script> <script type="module" src="/src/index.tsx"></script>
</body> </body>
</html> </html>
+5 -4
View File
@@ -1,6 +1,6 @@
{ {
"name": "ontime-ui", "name": "ontime-ui",
"version": "4.7.0", "version": "4.8.0",
"private": true, "private": true,
"type": "module", "type": "module",
"dependencies": { "dependencies": {
@@ -32,7 +32,6 @@
"react-icons": "5.5.0", "react-icons": "5.5.0",
"react-router": "^7.11.0", "react-router": "^7.11.0",
"react-virtuoso": "^4.17.0", "react-virtuoso": "^4.17.0",
"web-vitals": "^5.1.0",
"zustand": "^5.0.9" "zustand": "^5.0.9"
}, },
"scripts": { "scripts": {
@@ -51,7 +50,8 @@
"production": [ "production": [
">0.2%", ">0.2%",
"not dead", "not dead",
"not op_mini all" "not op_mini all",
"safari >= 14.1"
], ],
"development": [ "development": [
"last 1 chrome version", "last 1 chrome version",
@@ -64,8 +64,10 @@
"@types/qrcode": "^1.5.6", "@types/qrcode": "^1.5.6",
"@types/react": "^19.1.12", "@types/react": "^19.1.12",
"@types/react-dom": "^19.1.9", "@types/react-dom": "^19.1.9",
"@vitejs/plugin-legacy": "^8.0.1",
"@vitejs/plugin-react": "5.2.0", "@vitejs/plugin-react": "5.2.0",
"babel-plugin-react-compiler": "1.0.0", "babel-plugin-react-compiler": "1.0.0",
"happy-dom": "^20.9.0",
"ontime-types": "workspace:*", "ontime-types": "workspace:*",
"ontime-utils": "workspace:*", "ontime-utils": "workspace:*",
"sass": "^1.57.1", "sass": "^1.57.1",
@@ -73,7 +75,6 @@
"vite": "8.0.1", "vite": "8.0.1",
"vite-plugin-compression2": "2.5.1", "vite-plugin-compression2": "2.5.1",
"vite-plugin-svgr": "4.5.0", "vite-plugin-svgr": "4.5.0",
"vite-tsconfig-paths": "6.1.1",
"vitest": "catalog:" "vitest": "catalog:"
} }
} }
+1 -1
View File
@@ -15,5 +15,5 @@
"start_url": "./", "start_url": "./",
"display": "", "display": "",
"theme_color": "#121212", "theme_color": "#121212",
"background_color": "#ffffff" "background_color": "#101010"
} }
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "", "name": "",
"short_name": "", "short_name": "",
"icons": [{ "src": "ontime-logo.png", "sizes": "295x295", "type": "image/png" }], "icons": [{ "src": "ontime-logo.png", "sizes": "295x295", "type": "image/png" }],
"theme_color": "#2B5ABC", "theme_color": "#121212",
"background_color": "#101010", "background_color": "#101010",
"display": "standalone" "display": "standalone"
} }
+16 -1
View File
@@ -1,5 +1,13 @@
import axios, { AxiosResponse } from 'axios'; 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 { apiEntryUrl } from './constants';
import type { RequestOptions } from './requestOptions'; import type { RequestOptions } from './requestOptions';
@@ -111,6 +119,13 @@ export async function putBatchEditEvents(rundownId: RundownId, data: BatchEditEn
return axios.put(`${rundownPath}/${rundownId}/batch`, data); 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 = { export type ReorderEntry = {
entryId: EntryId; entryId: EntryId;
destinationId: EntryId; destinationId: EntryId;
@@ -1,10 +1,9 @@
// skipcq: JS-C1003 - sentry does not expose itself as an ES Module. // skipcq: JS-C1003 - sentry does not expose itself as an ES Module.
import * as Sentry from '@sentry/react'; import * as Sentry from '@sentry/react';
/* eslint-disable react/destructuring-assignment */
import React from 'react'; import React from 'react';
import { hasConnected, reconnectAttempts } from '../../../common/utils/socket';
import { runtimeStore } from '../../stores/runtime'; import { runtimeStore } from '../../stores/runtime';
import { getConnectionState, getReconnectAttempts } from '../../utils/socket';
import style from './ErrorBoundary.module.scss'; import style from './ErrorBoundary.module.scss';
@@ -37,7 +36,7 @@ class ErrorBoundary extends React.Component {
scope.setExtras({ scope.setExtras({
error, error,
store: appState, store: appState,
hasSocket: { hasConnected, reconnectAttempts }, hasSocket: { hasConnected: getConnectionState(), reconnectAttempts: getReconnectAttempts() },
}); });
const eventId = Sentry.captureException(error); const eventId = Sentry.captureException(error);
this.setState({ eventId, info }); this.setState({ eventId, info });
@@ -64,8 +64,8 @@ function SectionContents({ options, collapsed }: SectionContentsProps) {
function HiddenContents({ options }: { options: ParamField[] }) { function HiddenContents({ options }: { options: ParamField[] }) {
return ( return (
<> <>
{options.map((option, index) => { {options.map((option) => {
return <ParamInput key={option.title + index} paramField={option} />; return <ParamInput key={option.id} paramField={option} />;
})} })}
</> </>
); );
@@ -26,3 +26,14 @@ export const showLeadingZeros: ParamField = {
type: 'boolean', type: 'boolean',
defaultValue: false, 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 { useQuery } from '@tanstack/react-query';
import { langEn } from 'ontime-types'; import { langEn } from 'ontime-types';
import { MILLIS_PER_HOUR } from 'ontime-utils';
import { getUserTranslation } from '../../common/api/assets'; import { getUserTranslation } from '../../common/api/assets';
import { TRANSLATION } from '../../common/api/constants'; import { TRANSLATION } from '../../common/api/constants';
import { queryRefetchIntervalSlow } from '../../ontimeConfig';
export function useCustomTranslation() { export function useCustomTranslation() {
const { data, status, refetch } = useQuery({ const { data, status, refetch } = useQuery({
queryKey: TRANSLATION, queryKey: TRANSLATION,
queryFn: ({ signal }) => getUserTranslation({ signal }), queryFn: ({ signal }) => getUserTranslation({ signal }),
placeholderData: (previousData, _previousQuery) => previousData, placeholderData: (previousData, _previousQuery) => previousData,
refetchInterval: queryRefetchIntervalSlow, staleTime: MILLIS_PER_HOUR,
}); });
return { data: data ?? langEn, status, refetch }; return { data: data ?? langEn, status, refetch };
} }
@@ -40,6 +40,7 @@ export default function useRundown() {
queryClient.setQueryData(getRundownQueryKey(data.id), data); queryClient.setQueryData(getRundownQueryKey(data.id), data);
}, [data, loadedRundownId, queryClient]); }, [data, loadedRundownId, queryClient]);
// Once we have the ID, drop the temporary current cache
useEffect(() => { useEffect(() => {
if (!loadedRundownId) return; if (!loadedRundownId) return;
queryClient.removeQueries({ queryKey: CURRENT_RUNDOWN_QUERY_KEY, exact: true }); queryClient.removeQueries({ queryKey: CURRENT_RUNDOWN_QUERY_KEY, exact: true });
@@ -41,6 +41,7 @@ import {
patchReorderEntry, patchReorderEntry,
postAddEntry, postAddEntry,
postCloneEntry, postCloneEntry,
patchRenumberCues,
putBatchEditEvents, putBatchEditEvents,
putEditEntry, putEditEntry,
requestApplyDelay, requestApplyDelay,
@@ -523,6 +524,39 @@ export const useEntryActions = () => {
[batchUpdateEventsMutation, getCurrentRundownData], [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 * Calls mutation to delete an entry
* @private * @private
@@ -947,6 +981,7 @@ export const useEntryActions = () => {
groupEntries, groupEntries,
move, move,
reorderEntry, reorderEntry,
renumberCues,
swapEvents, swapEvents,
updateEntry, updateEntry,
updateTimer, updateTimer,
@@ -963,6 +998,7 @@ export const useEntryActions = () => {
groupEntries, groupEntries,
move, move,
reorderEntry, reorderEntry,
renumberCues,
swapEvents, swapEvents,
updateEntry, updateEntry,
updateTimer, updateTimer,
@@ -1,6 +1,10 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
export default function useScrollIntoView<T extends HTMLElement>(name: string, location?: string) { export default function useScrollIntoView<T extends HTMLElement>(
name: string,
location?: string,
onVisible?: (name: string) => void,
) {
const ref = useRef<T>(null); const ref = useRef<T>(null);
useEffect(() => { useEffect(() => {
@@ -11,5 +15,17 @@ export default function useScrollIntoView<T extends HTMLElement>(name: string, l
} }
}, [location, name]); }, [location, name]);
useEffect(() => {
if (!ref.current || !onVisible) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) onVisible(name);
},
{ threshold: 0.3, rootMargin: '0px 0px -40% 0px' },
);
observer.observe(ref.current);
return () => observer.disconnect();
}, [name, onVisible]);
return ref; return ref;
} }
@@ -47,6 +47,11 @@ describe('getRouteFromPreset()', () => {
expect(getRouteFromPreset(location, presets)).toStrictEqual('timer?user=guest&alias=demopage'); expect(getRouteFromPreset(location, presets)).toStrictEqual('timer?user=guest&alias=demopage');
}); });
it('returns null when already on a preset path', () => {
const location = resolvePath('/preset/demopage');
expect(getRouteFromPreset(location, presets)).toBeNull();
});
it('returns null if the current location is the exact match of an unwrapped alias', () => { it('returns null if the current location is the exact match of an unwrapped alias', () => {
// we make the current location be the alias // we make the current location be the alias
const location = resolvePath('/timer?user=guest&alias=demopage'); const location = resolvePath('/timer?user=guest&alias=demopage');
+26 -31
View File
@@ -3,9 +3,7 @@ import {
Log, Log,
MaybeNumber, MaybeNumber,
MessageTag, MessageTag,
ProjectRundownsList,
RefetchKey, RefetchKey,
Rundown,
RuntimeStore, RuntimeStore,
WsPacketToClient, WsPacketToClient,
WsPacketToServer, WsPacketToServer,
@@ -17,15 +15,16 @@ import {
CLIENT_LIST, CLIENT_LIST,
CSS_OVERRIDE, CSS_OVERRIDE,
CUSTOM_FIELDS, CUSTOM_FIELDS,
PROJECT_DATA,
CURRENT_RUNDOWN_QUERY_KEY, CURRENT_RUNDOWN_QUERY_KEY,
PROJECT_RUNDOWNS, PROJECT_DATA,
REPORT, REPORT,
RUNDOWN,
RUNTIME, RUNTIME,
TRANSLATION, TRANSLATION,
URL_PRESETS, URL_PRESETS,
VIEW_SETTINGS, VIEW_SETTINGS,
getRundownQueryKey, getRundownQueryKey,
PROJECT_RUNDOWNS,
} from '../api/constants'; } from '../api/constants';
import { invalidateAllCaches } from '../api/utils'; import { invalidateAllCaches } from '../api/utils';
import { ontimeQueryClient } from '../queryClient'; import { ontimeQueryClient } from '../queryClient';
@@ -51,8 +50,10 @@ const socketConfig = {
offlineAttemptsThreshold: 2, // when we consider the client disconnected offlineAttemptsThreshold: 2, // when we consider the client disconnected
} as const; } as const;
export let hasConnected = false; export const getConnectionState = () => hasConnected;
export let reconnectAttempts = 0; export const getReconnectAttempts = () => reconnectAttempts;
let hasConnected = false;
let reconnectAttempts = 0;
export const connectSocket = () => { export const connectSocket = () => {
websocket = new WebSocket(websocketUrl); websocket = new WebSocket(websocketUrl);
@@ -179,7 +180,7 @@ export const connectSocket = () => {
} }
case MessageTag.Refetch: { case MessageTag.Refetch: {
// the refetch message signals that the rundown has changed in the server side // the refetch message signals that the rundown has changed in the server side
const { target, revision } = payload; const { target, revision, rundownId } = payload;
switch (target) { switch (target) {
case RefetchKey.All: case RefetchKey.All:
invalidateAllCaches(); invalidateAllCaches();
@@ -194,7 +195,7 @@ export const connectSocket = () => {
ontimeQueryClient.invalidateQueries({ queryKey: REPORT }); ontimeQueryClient.invalidateQueries({ queryKey: REPORT });
break; break;
case RefetchKey.Rundown: { case RefetchKey.Rundown: {
maybeInvalidateRundownCache(revision); maybeInvalidateRundownCache(revision, rundownId);
break; break;
} }
case RefetchKey.UrlPresets: case RefetchKey.UrlPresets:
@@ -230,34 +231,28 @@ export const connectSocket = () => {
}; };
}; };
/** export function maybeInvalidateRundownCache(revision: MaybeNumber, rundownId?: string) {
* When we receive a refetch message for the rundown if (!rundownId) {
* check which rundown needs to be invalidated // we omit rundownId to signify invalidate all rundowns
*/ ontimeQueryClient.invalidateQueries({ queryKey: RUNDOWN });
export function maybeInvalidateRundownCache(revision: MaybeNumber) { ontimeQueryClient.invalidateQueries({ queryKey: CURRENT_RUNDOWN_QUERY_KEY, exact: true });
const loadedRundownId: string | undefined = (ontimeQueryClient.getQueryData(PROJECT_RUNDOWNS) as ProjectRundownsList)
?.loaded;
const activeRundownQueryKey = loadedRundownId ? getRundownQueryKey(loadedRundownId) : CURRENT_RUNDOWN_QUERY_KEY;
const cachedRundown = ontimeQueryClient.getQueryData<Rundown>(activeRundownQueryKey);
if (revision === cachedRundown?.revision) {
return; return;
} }
ontimeQueryClient.invalidateQueries({ queryKey: activeRundownQueryKey, exact: true }); // skip if we dont recognise the ID the revision is lower
const queryKey = getRundownQueryKey(rundownId);
if (loadedRundownId) { const cachedRundown = ontimeQueryClient.getQueryData<{ revision: number }>(queryKey);
// Keep bootstrap alias in sync with the ID-based cache if (revision !== null && revision === cachedRundown?.revision) {
ontimeQueryClient.invalidateQueries({ queryKey: CURRENT_RUNDOWN_QUERY_KEY, exact: true }); return;
} else {
// During bootstrap, loadedRundownId is not yet known.
// Invalidate any ID-based rundown caches that may have been seeded early.
ontimeQueryClient.invalidateQueries({
predicate: (query) => query.queryKey[0] === 'rundown' && query.queryKey[1] !== 'current',
});
} }
ontimeQueryClient.invalidateQueries({ queryKey: CUSTOM_FIELDS }); ontimeQueryClient.invalidateQueries({ queryKey, exact: true });
// keep current alias in sync with the ID-based cache
const loadedRundownId = ontimeQueryClient.getQueryData<{ loaded: string }>(PROJECT_RUNDOWNS)?.loaded;
if (!loadedRundownId || loadedRundownId === rundownId) {
ontimeQueryClient.invalidateQueries({ queryKey: CURRENT_RUNDOWN_QUERY_KEY, exact: true });
}
} }
export function sendSocket<T extends MessageTag | ApiActionTag>( export function sendSocket<T extends MessageTag | ApiActionTag>(
+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 { import {
MILLIS_PER_HOUR, MILLIS_PER_HOUR,
MILLIS_PER_MINUTE, MILLIS_PER_MINUTE,
@@ -75,8 +75,9 @@ function resolveTimeFormat(fallback12: string, fallback24: string): string {
} }
type FormatOptions = { type FormatOptions = {
format12: string; format12?: string;
format24: string; format24?: string;
override?: MaybeString;
}; };
/** /**
@@ -97,7 +98,7 @@ export const formatTime = (
return '...'; 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 display = formatFromMillis(Math.abs(milliseconds), timeFormat);
const isNegative = milliseconds < 0; const isNegative = milliseconds < 0;
+3 -3
View File
@@ -204,7 +204,7 @@ function isPresettableView(view: string): view is OntimeViewPresettable {
/** /**
* Check if current location is a preset path * Check if current location is a preset path
*/ */
export function isPresetPath(location: Path): boolean { function isPresetPath(location: Path): boolean {
const segments = location.pathname.split('/').filter(Boolean); const firstSegment = location.pathname.split('/').find(Boolean);
return segments[0] === 'preset'; return firstSegment === 'preset';
} }
+1
View File
@@ -9,6 +9,7 @@ export const apiRepoLatest = 'https://api.github.com/repos/cpvalente/ontime/rele
export const websiteUrl = 'https://www.getontime.no'; export const websiteUrl = 'https://www.getontime.no';
export const discordUrl = 'https://discord.com/invite/eje3CSUEXm'; export const discordUrl = 'https://discord.com/invite/eje3CSUEXm';
export const subredditUrl = 'https://www.reddit.com/r/ontimeapp/'; export const subredditUrl = 'https://www.reddit.com/r/ontimeapp/';
export const youtubeUrl = 'https://www.youtube.com/@ontimeapp';
export const documentationUrl = 'https://docs.getontime.no'; export const documentationUrl = 'https://docs.getontime.no';
export const customFieldsDocsUrl = 'https://docs.getontime.no/features/custom-fields/'; export const customFieldsDocsUrl = 'https://docs.getontime.no/features/custom-fields/';
@@ -4,7 +4,7 @@
width: 100%; width: 100%;
padding: 1rem; padding: 1rem;
display: flex; display: flex;
gap: 0.25rem; gap: 0;
overflow: hidden; overflow: hidden;
background-color: $ui-black; background-color: $ui-black;
@@ -1,6 +1,7 @@
import { ErrorBoundary } from '@sentry/react'; import { ErrorBoundary } from '@sentry/react';
import { useKeyDown } from '../../common/hooks/useKeyDown'; import { useKeyDown } from '../../common/hooks/useKeyDown';
import { AppSettingsScrollContext, useScrollContextState } from './AppSettingsScrollContext';
import PanelContent from './panel-content/PanelContent'; import PanelContent from './panel-content/PanelContent';
import PanelList from './panel-list/PanelList'; import PanelList from './panel-list/PanelList';
import AboutPanel from './panel/about-panel/AboutPanel'; import AboutPanel from './panel/about-panel/AboutPanel';
@@ -17,13 +18,15 @@ import style from './AppSettings.module.scss';
export default function AppSettings() { export default function AppSettings() {
const { close, panel, location, setLocation } = useAppSettingsNavigation(); const { close, panel, location, setLocation } = useAppSettingsNavigation();
const scrollContext = useScrollContextState(panel);
useKeyDown(close, 'Escape'); useKeyDown(close, 'Escape');
return ( return (
<div className={style.container}> <div className={style.container}>
<ErrorBoundary> <ErrorBoundary>
<AppSettingsScrollContext.Provider value={scrollContext}>
<PanelList selectedPanel={panel} location={location} /> <PanelList selectedPanel={panel} location={location} />
<PanelContent onClose={close}> <PanelContent onClose={close} panel={panel} location={location}>
{panel === 'settings' && <SettingsPanel location={location} />} {panel === 'settings' && <SettingsPanel location={location} />}
{panel === 'project' && <ProjectPanel location={location} setLocation={setLocation} />} {panel === 'project' && <ProjectPanel location={location} setLocation={setLocation} />}
{panel === 'manage' && <ManagePanel location={location} />} {panel === 'manage' && <ManagePanel location={location} />}
@@ -33,6 +36,7 @@ export default function AppSettings() {
{panel === 'about' && <AboutPanel />} {panel === 'about' && <AboutPanel />}
{panel === 'shutdown' && <ShutdownPanel />} {panel === 'shutdown' && <ShutdownPanel />}
</PanelContent> </PanelContent>
</AppSettingsScrollContext.Provider>
</ErrorBoundary> </ErrorBoundary>
</div> </div>
); );
@@ -0,0 +1,31 @@
import { createContext, useCallback, useContext, useState } from 'react';
interface ScrollContextValue {
activeSection: string | undefined;
setActiveSection: (name: string) => void;
}
export const AppSettingsScrollContext = createContext<ScrollContextValue>({
activeSection: undefined,
setActiveSection: () => {},
});
export function useAppSettingsScroll() {
return useContext(AppSettingsScrollContext);
}
export function useScrollContextState(panel: string) {
const [activeSection, setActiveSectionRaw] = useState<string | undefined>(undefined);
const [trackedPanel, setTrackedPanel] = useState(panel);
if (panel !== trackedPanel) {
setTrackedPanel(panel);
setActiveSectionRaw(undefined);
}
const setActiveSection = useCallback((name: string) => {
setActiveSectionRaw(name);
}, []);
return { activeSection, setActiveSection };
}
@@ -0,0 +1,11 @@
let _isDirty = false;
export const markDirty = () => {
_isDirty = true;
};
export const markClean = () => {
_isDirty = false;
};
export const getIsDirty = () => _isDirty;
@@ -1,8 +1,19 @@
.corner { .stickyHeader {
position: fixed; position: sticky;
top: 6rem; top: 0;
right: 4rem; z-index: $zindex-nav;
z-index: $zindex-floating; display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5rem 1rem;
background-color: $gray-1250;
border-bottom: 1px solid $white-10;
flex-shrink: 0;
}
.breadcrumb {
font-size: calc(1rem - 1px);
color: $gray-400;
} }
.contentWrapper { .contentWrapper {
@@ -12,6 +23,7 @@
flex: 1 1 auto; flex: 1 1 auto;
min-width: 0; min-width: 0;
position: relative; position: relative;
overflow: hidden;
} }
.content { .content {
@@ -2,22 +2,31 @@ import { PropsWithChildren } from 'react';
import { IoClose } from 'react-icons/io5'; import { IoClose } from 'react-icons/io5';
import Button from '../../../common/components/buttons/Button'; import Button from '../../../common/components/buttons/Button';
import { getPanelLabel } from '../useAppSettingsMenu';
import style from './PanelContent.module.scss'; import style from './PanelContent.module.scss';
interface PanelContentProps { interface PanelContentProps {
onClose: () => void; onClose: () => void;
panel: string;
location?: string;
} }
export default function PanelContent({ onClose, children }: PropsWithChildren<PanelContentProps>) { export default function PanelContent({ onClose, panel, location, children }: PropsWithChildren<PanelContentProps>) {
const { panelLabel, sectionLabel } = getPanelLabel(panel, location);
return ( return (
<div className={style.contentWrapper}> <div className={style.contentWrapper}>
<div className={style.content}>{children}</div> <div className={style.stickyHeader}>
<div className={style.corner}> <span className={style.breadcrumb}>
{panelLabel}
{sectionLabel ? <> {sectionLabel}</> : null}
</span>
<Button size='large' onClick={onClose}> <Button size='large' onClick={onClose}>
Close settings <IoClose /> Close settings <IoClose />
</Button> </Button>
</div> </div>
<div className={style.content}>{children}</div>
</div> </div>
); );
} }
@@ -12,6 +12,9 @@ ul {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow-y: auto; overflow-y: auto;
background-color: $gray-1250;
border-right: 1px solid $white-10;
padding: 0.5rem 0;
} }
.primary, .primary,
@@ -32,14 +35,16 @@ ul {
.primary { .primary {
font-size: 1rem; font-size: 1rem;
border-radius: 2px; border-radius: 6px;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.5rem;
&.active { &.active {
color: $blue-400; color: $blue-400;
background-color: $gray-1100; border-left: 3px solid $blue-400;
padding-left: calc(1rem - 3px);
border-radius: 0 6px 6px 0;
} }
&.highlight { &.highlight {
@@ -53,10 +58,6 @@ ul {
background-color: $red-400; background-color: $red-400;
} }
} }
&.split {
margin-top: 1rem;
}
} }
.secondary { .secondary {
@@ -67,5 +68,7 @@ ul {
&.active { &.active {
color: $blue-400; color: $blue-400;
border-left-color: $blue-400;
border-left-width: 2px;
} }
} }
@@ -3,6 +3,8 @@ import { Fragment } from 'react';
import Tooltip from '../../../common/components/tooltip/Tooltip'; import Tooltip from '../../../common/components/tooltip/Tooltip';
import { isKeyEnter } from '../../../common/utils/keyEvent'; import { isKeyEnter } from '../../../common/utils/keyEvent';
import { cx } from '../../../common/utils/styleUtils'; import { cx } from '../../../common/utils/styleUtils';
import { getIsDirty, markClean } from '../appSettingsDirtyState';
import { useAppSettingsScroll } from '../AppSettingsScrollContext';
import { SettingsOption, SettingsOptionId, useAppSettingsMenu } from '../useAppSettingsMenu'; import { SettingsOption, SettingsOptionId, useAppSettingsMenu } from '../useAppSettingsMenu';
import useAppSettingsNavigation from '../useAppSettingsNavigation'; import useAppSettingsNavigation from '../useAppSettingsNavigation';
@@ -42,25 +44,27 @@ interface PanelListItemProps {
location?: string; location?: string;
} }
function PanelListItem(props: PanelListItemProps) { function navigateWithGuard(navigate: (id: SettingsOptionId) => void, id: SettingsOptionId) {
const { panel, isSelected, location } = props; if (getIsDirty()) {
const { setLocation } = useAppSettingsNavigation(); if (!window.confirm('You have unsaved changes. Leave without saving?')) return;
markClean();
}
navigate(id);
}
const classes = cx([ function PanelListItem({ panel, isSelected, location }: PanelListItemProps) {
style.primary, const { setLocation } = useAppSettingsNavigation();
isSelected && style.active, const { activeSection } = useAppSettingsScroll();
panel.split && style.split, const classes = cx([style.primary, isSelected && style.active, panel.highlight && style.highlight]);
panel.highlight && style.highlight,
]);
return ( return (
<Fragment key={panel.id}> <Fragment key={panel.id}>
<li <li
key={panel.id} key={panel.id}
onClick={() => setLocation(panel.id as SettingsOptionId)} onClick={() => navigateWithGuard(setLocation, panel.id as SettingsOptionId)}
onKeyDown={(event) => { onKeyDown={(event) => {
if (isKeyEnter(event)) { if (isKeyEnter(event)) {
setLocation(panel.id as SettingsOptionId); navigateWithGuard(setLocation, panel.id as SettingsOptionId);
} }
}} }}
className={classes} className={classes}
@@ -71,14 +75,15 @@ function PanelListItem(props: PanelListItemProps) {
</li> </li>
{panel.secondary?.map((secondary, index) => { {panel.secondary?.map((secondary, index) => {
const id = secondary.id.split('__')[1]; const id = secondary.id.split('__')[1];
const secondaryClasses = cx([style.secondary, isSelected && location === id ? style.active : null]); const effectiveSection = isSelected ? (activeSection ?? location) : undefined;
const secondaryClasses = cx([style.secondary, effectiveSection === id ? style.active : null]);
return ( return (
<li <li
key={secondary.id + index} key={secondary.id + index}
onClick={() => setLocation(secondary.id as SettingsOptionId)} onClick={() => navigateWithGuard(setLocation, secondary.id as SettingsOptionId)}
onKeyDown={(event) => { onKeyDown={(event) => {
if (isKeyEnter(event)) { if (isKeyEnter(event)) {
setLocation(secondary.id as SettingsOptionId); navigateWithGuard(setLocation, secondary.id as SettingsOptionId);
} }
}} }}
className={secondaryClasses} className={secondaryClasses}
@@ -53,9 +53,10 @@ $inner-padding: 1rem;
.card { .card {
position: relative; position: relative;
padding: 2rem; padding: 2rem;
background-color: $white-3; background-color: $white-5;
border: 1px solid $gray-1100; border: 1px solid $gray-1100;
border-radius: 3px; border-radius: 8px;
box-shadow: $box-shadow-l1;
} }
.highlight { .highlight {
@@ -7,6 +7,7 @@ import {
githubUrl, githubUrl,
subredditUrl, subredditUrl,
websiteUrl, websiteUrl,
youtubeUrl,
} from '../../../../externals'; } from '../../../../externals';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import AppVersion from './AppVersion'; import AppVersion from './AppVersion';
@@ -38,6 +39,7 @@ export default function AboutPanel() {
<ExternalLink href={documentationUrl}>Read the docs</ExternalLink> <ExternalLink href={documentationUrl}>Read the docs</ExternalLink>
<ExternalLink href={githubUrl}>Follow the project on GitHub</ExternalLink> <ExternalLink href={githubUrl}>Follow the project on GitHub</ExternalLink>
<ExternalLink href={discordUrl}>Discord server</ExternalLink> <ExternalLink href={discordUrl}>Discord server</ExternalLink>
<ExternalLink href={youtubeUrl}>YouTube channel</ExternalLink>
<ExternalLink href={subredditUrl}>Subreddit</ExternalLink> <ExternalLink href={subredditUrl}>Subreddit</ExternalLink>
</Panel.Section> </Panel.Section>
</> </>
@@ -1,5 +1,6 @@
import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings'; import useAutomationSettings from '../../../../common/hooks-query/useAutomationSettings';
import useScrollIntoView from '../../../../common/hooks/useScrollIntoView'; import useScrollIntoView from '../../../../common/hooks/useScrollIntoView';
import { useAppSettingsScroll } from '../../AppSettingsScrollContext';
import type { PanelBaseProps } from '../../panel-list/PanelList'; import type { PanelBaseProps } from '../../panel-list/PanelList';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import AutomationSettingsForm from './AutomationSettingsForm'; import AutomationSettingsForm from './AutomationSettingsForm';
@@ -8,9 +9,10 @@ import TriggersList from './TriggersList';
export default function AutomationPanel({ location }: PanelBaseProps) { export default function AutomationPanel({ location }: PanelBaseProps) {
const { data, status } = useAutomationSettings(); const { data, status } = useAutomationSettings();
const settingsRef = useScrollIntoView<HTMLDivElement>('settings', location); const { setActiveSection } = useAppSettingsScroll();
const triggersRef = useScrollIntoView<HTMLDivElement>('triggers', location); const settingsRef = useScrollIntoView<HTMLDivElement>('settings', location, setActiveSection);
const automationsRef = useScrollIntoView<HTMLDivElement>('automations', location); const triggersRef = useScrollIntoView<HTMLDivElement>('triggers', location, setActiveSection);
const automationsRef = useScrollIntoView<HTMLDivElement>('automations', location, setActiveSection);
const isLoading = status === 'pending'; const isLoading = status === 'pending';
const automationState = isLoading ? undefined : data.enabledAutomations; const automationState = isLoading ? undefined : data.enabledAutomations;
@@ -12,6 +12,7 @@ import { preventEscape } from '../../../../common/utils/keyEvent';
import { isOnlyNumbers } from '../../../../common/utils/regex'; import { isOnlyNumbers } from '../../../../common/utils/regex';
import { isOntimeCloud } from '../../../../externals'; import { isOntimeCloud } from '../../../../externals';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import { useSettingsDirty } from '../../useSettingsDirty';
const oscApiDocsUrl = 'https://docs.getontime.no/api/protocols/osc/'; const oscApiDocsUrl = 'https://docs.getontime.no/api/protocols/osc/';
@@ -45,6 +46,7 @@ export default function AutomationSettingsForm({
keepDirtyValues: false, keepDirtyValues: false,
}, },
}); });
useSettingsDirty(isDirty);
const onSubmit = async (formData: AutomationSettingsProps) => { const onSubmit = async (formData: AutomationSettingsProps) => {
try { try {
@@ -89,10 +91,9 @@ export default function AutomationSettingsForm({
<Panel.Section> <Panel.Section>
<Info> <Info>
<p>Control Ontime and share its data with external systems in your workflow.</p> <span>Control Ontime and share its data with external systems in your workflow.</span>
<p>- Automations allow Ontime to send its data on lifecycle triggers.</p> <span>- Automations allow Ontime to send its data on lifecycle triggers.</span>
<p>- OSC Input tells Ontime to listen to messages on the specific port.</p> <span>- OSC Input tells Ontime to listen to messages on the specific port.</span>
<br />
<ExternalLink href={oscApiDocsUrl}>See the docs</ExternalLink> <ExternalLink href={oscApiDocsUrl}>See the docs</ExternalLink>
</Info> </Info>
</Panel.Section> </Panel.Section>
@@ -1,5 +1,6 @@
import useScrollIntoView from '../../../../common/hooks/useScrollIntoView'; import useScrollIntoView from '../../../../common/hooks/useScrollIntoView';
import { isOntimeCloud } from '../../../../externals'; import { isOntimeCloud } from '../../../../externals';
import { useAppSettingsScroll } from '../../AppSettingsScrollContext';
import GenerateLinkFormExport from '../../../sharing/GenerateLinkFormExport'; import GenerateLinkFormExport from '../../../sharing/GenerateLinkFormExport';
import type { PanelBaseProps } from '../../panel-list/PanelList'; import type { PanelBaseProps } from '../../panel-list/PanelList';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
@@ -8,9 +9,10 @@ import ReportSettings from './ReportSettings';
import URLPresets from './URLPresets'; import URLPresets from './URLPresets';
export default function FeaturePanel({ location }: PanelBaseProps) { export default function FeaturePanel({ location }: PanelBaseProps) {
const presetsRef = useScrollIntoView<HTMLDivElement>('presets', location); const { setActiveSection } = useAppSettingsScroll();
const linkRef = useScrollIntoView<HTMLDivElement>('link', location); const presetsRef = useScrollIntoView<HTMLDivElement>('presets', location, setActiveSection);
const reportRef = useScrollIntoView<HTMLDivElement>('report', location); const linkRef = useScrollIntoView<HTMLDivElement>('link', location, setActiveSection);
const reportRef = useScrollIntoView<HTMLDivElement>('report', location, setActiveSection);
return ( return (
<> <>
@@ -57,11 +57,11 @@ export default function CustomFieldSettings() {
<Panel.Divider /> <Panel.Divider />
<Panel.Section> <Panel.Section>
<Info> <Info>
Custom fields allow for additional information to be added to an event. <span>Custom fields allow for additional information to be added to an event.</span>
<br /> <span>
<br /> To use custom fields as a data source in an{' '}
To use custom fields as a data source in an{' '} <AppLink search='settings=automation__automations'>Automation</AppLink>, please note the generated key.
<AppLink search='settings=automation__automations'>Automation</AppLink>, please note the generated key. </span>
<ExternalLink href={customFieldsDocsUrl}>See the docs</ExternalLink> <ExternalLink href={customFieldsDocsUrl}>See the docs</ExternalLink>
</Info> </Info>
</Panel.Section> </Panel.Section>
@@ -52,8 +52,9 @@ export default function CustomViews() {
<Panel.Section> <Panel.Section>
<Info> <Info>
Upload one <strong>index.html</strong> per view to <strong>/external/&lt;name&gt;/</strong>. <span>
<br /> Upload one <strong>index.html</strong> per view to <strong>/external/&lt;name&gt;/</strong>.
</span>
External imports are not allowed, include all assets inside the html file. External imports are not allowed, include all assets inside the html file.
<ExternalLink href={customViewsDocs}>See the docs</ExternalLink> <ExternalLink href={customViewsDocs}>See the docs</ExternalLink>
</Info> </Info>
@@ -1,4 +1,5 @@
import useScrollIntoView from '../../../../common/hooks/useScrollIntoView'; import useScrollIntoView from '../../../../common/hooks/useScrollIntoView';
import { useAppSettingsScroll } from '../../AppSettingsScrollContext';
import type { PanelBaseProps } from '../../panel-list/PanelList'; import type { PanelBaseProps } from '../../panel-list/PanelList';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import CustomFieldSettings from './CustomFields'; import CustomFieldSettings from './CustomFields';
@@ -7,10 +8,11 @@ import RundownDefaultSettings from './RundownDefaultSettings';
import SourcesPanel from './sources-panel/SourcesPanel'; import SourcesPanel from './sources-panel/SourcesPanel';
export default function ManagePanel({ location }: PanelBaseProps) { export default function ManagePanel({ location }: PanelBaseProps) {
const defaultsRef = useScrollIntoView<HTMLDivElement>('defaults', location); const { setActiveSection } = useAppSettingsScroll();
const customRef = useScrollIntoView<HTMLDivElement>('custom', location); const defaultsRef = useScrollIntoView<HTMLDivElement>('defaults', location, setActiveSection);
const rundownsRef = useScrollIntoView<HTMLDivElement>('rundowns', location); const customRef = useScrollIntoView<HTMLDivElement>('custom', location, setActiveSection);
const sheetsRef = useScrollIntoView<HTMLDivElement>('sheets', location); const rundownsRef = useScrollIntoView<HTMLDivElement>('rundowns', location, setActiveSection);
const sheetsRef = useScrollIntoView<HTMLDivElement>('sheets', location, setActiveSection);
return ( return (
<> <>
@@ -15,23 +15,25 @@ import Input from '../../../../../common/components/input/input/Input';
import Tag from '../../../../../common/components/tag/Tag'; import Tag from '../../../../../common/components/tag/Tag';
import { openLink } from '../../../../../common/utils/linkUtils'; import { openLink } from '../../../../../common/utils/linkUtils';
import * as Panel from '../../../panel-utils/PanelUtils'; import * as Panel from '../../../panel-utils/PanelUtils';
import { extractSheetId, getPersistedSheetId, persistSheetId } from './gsheetUtils';
import style from './SourcesPanel.module.scss'; import style from './SourcesPanel.module.scss';
interface GSheetSetupProps { interface GSheetSetupProps {
onCancel: () => void; onCancel: () => void;
onSheetLoaded: (sheetId: string, options: SpreadsheetWorksheetOptions) => void; onSheetLoaded: (sheetId: string, options: SpreadsheetWorksheetOptions) => void;
closedByUser: boolean;
} }
export default function GSheetSetup(props: GSheetSetupProps) { export default function GSheetSetup(props: GSheetSetupProps) {
const { onCancel, onSheetLoaded } = props; const { onCancel, onSheetLoaded, closedByUser } = props;
const [file, setFile] = useState<File | null>(null); const [file, setFile] = useState<File | null>(null);
const [sheetId, setSheetId] = useState(''); const [sheetId, setSheetId] = useState(getPersistedSheetId);
const [authenticationStatus, setAuthenticationStatus] = useState<AuthenticationStatus>('not_authenticated'); const [authenticationStatus, setAuthenticationStatus] = useState<AuthenticationStatus>('not_authenticated');
const [authKey, setAuthKey] = useState<string | null>(null); const [authKey, setAuthKey] = useState<string | null>(null);
const [loading, setLoading] = useState<'' | 'cancel' | 'connect' | 'authenticate' | 'load-sheet'>('');
const [authLink, setAuthLink] = useState(''); const [authLink, setAuthLink] = useState('');
const [loading, setLoading] = useState<'' | 'cancel' | 'connect' | 'authenticate' | 'load-sheet'>('');
const [authError, setAuthError] = useState(''); const [authError, setAuthError] = useState('');
const [worksheetError, setWorksheetError] = useState(''); const [worksheetError, setWorksheetError] = useState('');
const pollTimeoutRef = useRef<number | null>(null); const pollTimeoutRef = useRef<number | null>(null);
@@ -62,6 +64,7 @@ export default function GSheetSetup(props: GSheetSetupProps) {
const loadWorksheetOptions = useCallback( const loadWorksheetOptions = useCallback(
async (nextSheetId: string) => { async (nextSheetId: string) => {
const worksheetOptions = await getWorksheetOptions(nextSheetId); const worksheetOptions = await getWorksheetOptions(nextSheetId);
persistSheetId(nextSheetId);
onSheetLoaded(nextSheetId, worksheetOptions); onSheetLoaded(nextSheetId, worksheetOptions);
setWorksheetError(''); setWorksheetError('');
}, },
@@ -71,6 +74,7 @@ export default function GSheetSetup(props: GSheetSetupProps) {
const pollUntilAuthenticated = useCallback( const pollUntilAuthenticated = useCallback(
async (attempts: number = 0) => { async (attempts: number = 0) => {
clearPollTimeout(); clearPollTimeout();
if (closedByUser) return;
try { try {
const result = await verifyAuthenticationStatus(); const result = await verifyAuthenticationStatus();
@@ -82,13 +86,16 @@ export default function GSheetSetup(props: GSheetSetupProps) {
pollTimeoutRef.current = window.setTimeout(() => { pollTimeoutRef.current = window.setTimeout(() => {
pollUntilAuthenticated(attempts + 1); pollUntilAuthenticated(attempts + 1);
}, 2000); }, 2000);
} else { return; // Keep authKey for next poll
setLoading('');
} }
// Polling timed out
setAuthKey(null);
setLoading('');
return; return;
} }
if (result.authenticated === 'authenticated') { if (result.authenticated === 'authenticated' && result.sheetId) {
setLoading('load-sheet');
try { try {
await loadWorksheetOptions(result.sheetId); await loadWorksheetOptions(result.sheetId);
} catch (error) { } catch (error) {
@@ -96,13 +103,15 @@ export default function GSheetSetup(props: GSheetSetupProps) {
} }
} }
setAuthKey(null);
setLoading(''); setLoading('');
} catch (error) { } catch (error) {
setAuthError(maybeAxiosError(error)); setAuthError(maybeAxiosError(error));
setAuthKey(null);
setLoading(''); setLoading('');
} }
}, },
[clearPollTimeout, loadWorksheetOptions], [clearPollTimeout, loadWorksheetOptions, closedByUser],
); );
/** check if the current session has been authenticated */ /** 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 () => { const handleConnect = async () => {
if (!file) return; 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 = () => { const handleAuthenticate = () => {
setLoading('authenticate'); setLoading('authenticate');
@@ -180,7 +189,6 @@ export default function GSheetSetup(props: GSheetSetupProps) {
clearPollTimeout(); clearPollTimeout();
clearAuthFallbackTimeout(); clearAuthFallbackTimeout();
// open link and schedule a check for when the user focuses again
openLink(authLink); openLink(authLink);
authFallbackTimeoutRef.current = window.setTimeout(() => { authFallbackTimeoutRef.current = window.setTimeout(() => {
if (document.hasFocus()) { if (document.hasFocus()) {
@@ -269,18 +277,19 @@ export default function GSheetSetup(props: GSheetSetupProps) {
</Panel.ListGroup> </Panel.ListGroup>
)} )}
<Panel.ListGroup className={style.setupBlock}> <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> <Panel.Error>{worksheetError}</Panel.Error>
<Input <Input
fluid fluid
value={sheetId} value={sheetId}
placeholder='Sheet ID' placeholder='Sheet ID or Google Sheets URL'
onChange={(event) => { onChange={(event) => {
setWorksheetError(''); setWorksheetError('');
setSheetId(event.target.value); setSheetId(extractSheetId(event.target.value));
}} }}
disabled={isLoading || canAuthenticate} disabled={isLoading || canAuthenticate}
/> />
<div className={style.setupHint}>Paste a Google Sheets URL or the sheet ID from the URL bar.</div>
</Panel.ListGroup> </Panel.ListGroup>
{isAuthenticated ? ( {isAuthenticated ? (
<Panel.ListGroup className={style.setupBlock}> <Panel.ListGroup className={style.setupBlock}>
@@ -304,18 +313,16 @@ export default function GSheetSetup(props: GSheetSetupProps) {
</Panel.ListGroup> </Panel.ListGroup>
) : ( ) : (
<Panel.ListGroup className={style.setupBlock}> <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}> <Panel.InlineElements wrap='wrap' className={style.setupActions}>
{isAuthenticating && <span>Authenticating...</span>} {isAuthenticating && <span>Authenticating...</span>}
<CopyTag copyValue={authKey ?? ''} disabled={!canAuthenticate}> <CopyTag copyValue={authKey ?? ''}>{authKey}</CopyTag>
{authKey ? authKey : 'Upload files to generate Auth Key'} <Button onClick={handleAuthenticate} disabled={isLoading} loading={loading === 'authenticate'}>
</CopyTag>
<Button onClick={handleAuthenticate} disabled={!canAuthenticate}>
<IoShieldCheckmarkOutline /> <IoShieldCheckmarkOutline />
Authenticate Authenticate
</Button> </Button>
</Panel.InlineElements> </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.ListGroup>
)} )}
</Panel.Section> </Panel.Section>
@@ -37,12 +37,15 @@ type ActiveSource =
kind: 'excel'; kind: 'excel';
worksheetNames: string[]; worksheetNames: string[];
initialWorksheetMetadata: SpreadsheetWorksheetMetadata | null; initialWorksheetMetadata: SpreadsheetWorksheetMetadata | null;
closedByUser: boolean;
} }
| { | {
kind: 'gsheet'; kind: 'gsheet';
sheetId: string; sheetId: string;
worksheetNames: string[]; worksheetNames: string[];
initialWorksheetMetadata: SpreadsheetWorksheetMetadata | null; initialWorksheetMetadata: SpreadsheetWorksheetMetadata | null;
title: string;
closedByUser: boolean;
}; };
export default function SourcesPanel() { export default function SourcesPanel() {
@@ -73,6 +76,7 @@ export default function SourcesPanel() {
kind: 'excel', kind: 'excel',
worksheetNames: worksheetOptions.worksheets, worksheetNames: worksheetOptions.worksheets,
initialWorksheetMetadata: worksheetOptions.metadata, initialWorksheetMetadata: worksheetOptions.metadata,
closedByUser: false,
}); });
setImportFlow('excel'); setImportFlow('excel');
setHasFile('done'); setHasFile('done');
@@ -106,7 +110,13 @@ export default function SourcesPanel() {
}; };
const cancelImportFlow = () => { 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 = () => { const handleFinished = () => {
@@ -177,15 +187,22 @@ export default function SourcesPanel() {
sheetId, sheetId,
worksheetNames: worksheetOptions.worksheets, worksheetNames: worksheetOptions.worksheets,
initialWorksheetMetadata: worksheetOptions.metadata, initialWorksheetMetadata: worksheetOptions.metadata,
title: worksheetOptions.title ?? '',
closedByUser: false,
}); });
}, []); }, []);
const closedByUser = activeSource?.closedByUser ?? false;
const isGSheetFlow = importFlow === 'gsheet'; const isGSheetFlow = importFlow === 'gsheet';
const showInput = importFlow === 'none'; const showInput = importFlow === 'none';
const showCompleted = importFlow === 'finished'; const showCompleted = importFlow === 'finished';
const showAuth = isGSheetFlow && activeSource === null;
const showImportWorkspace = activeSource !== null; const showImportWorkspace = activeSource !== null && !closedByUser;
const importModalTitle = activeSource?.kind === 'excel' ? 'Import spreadsheet' : 'Synchronise with Google Sheet'; const importModalTitle = (() => {
if (!activeSource) return '';
if (activeSource.kind === 'excel') return 'Import spreadsheet';
return activeSource.title ? `Sync: ${activeSource.title}` : 'Synchronize with Google Sheet';
})();
const sourceKey = (() => { const sourceKey = (() => {
if (!activeSource) return null; if (!activeSource) return null;
if (activeSource.kind === 'excel') return 'excel'; if (activeSource.kind === 'excel') return 'excel';
@@ -195,7 +212,7 @@ export default function SourcesPanel() {
return ( return (
<Panel.Section> <Panel.Section>
<Panel.Card> <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>} {error && <Panel.Error>{error}</Panel.Error>}
{showInput && ( {showInput && (
<div className={style.introStack}> <div className={style.introStack}>
@@ -233,7 +250,7 @@ export default function SourcesPanel() {
</section> </section>
<section className={style.sourceCard}> <section className={style.sourceCard}>
<div className={style.sourceHeader}> <div className={style.sourceHeader}>
<h4 className={style.sourceTitle}>Synchronise with Google</h4> <h4 className={style.sourceTitle}>Synchronize with Google</h4>
</div> </div>
<p className={style.sourceDescription}> <p className={style.sourceDescription}>
Connect a Google account once, then load any sheet by ID and keep the import flow inside Ontime. 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> <div className={style.sourceMeta}>Requires Google OAuth client credentials</div>
<Button variant='primary' size='large' fluid onClick={openGSheetFlow} disabled={hasFile !== 'none'}> <Button variant='primary' size='large' fluid onClick={openGSheetFlow} disabled={hasFile !== 'none'}>
<IoCloudOutline /> <IoCloudOutline />
Synchronise with Google Synchronize with Google
</Button> </Button>
</section> </section>
</div> </div>
@@ -257,7 +274,9 @@ export default function SourcesPanel() {
</Button> </Button>
</div> </div>
)} )}
{showAuth && <GSheetSetup onCancel={cancelGSheetFlow} onSheetLoaded={handleSheetLoaded} />} {isGSheetFlow && (
<GSheetSetup onCancel={cancelGSheetFlow} onSheetLoaded={handleSheetLoaded} closedByUser={closedByUser} />
)}
<Modal <Modal
isOpen={showImportWorkspace} isOpen={showImportWorkspace}
title={importModalTitle} 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': case 'invalid-name':
return 'Column cannot be converted into an Ontime field name'; return 'Column cannot be converted into an Ontime field name';
case 'name-collision': case 'name-collision':
return 'Column name resolves to a duplicate column'; return 'Column name resolves to a duplicate Ontime field';
default: default:
return ''; return '';
} }
@@ -50,7 +50,7 @@ export default function SheetImportMappingPane({
return ( return (
<section className={style.mappingPane}> <section className={style.mappingPane}>
<Panel.InlineElements align='apart' className={style.mappingPaneHeader}> <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}> <Panel.InlineElements relation='inner' className={style.mappingPaneActions}>
<Button className={style.addColumnTrigger} onClick={handleAddCustomField} disabled={isBusy}> <Button className={style.addColumnTrigger} onClick={handleAddCustomField} disabled={isBusy}>
<IoAdd /> <IoAdd />
@@ -58,7 +58,7 @@ describe('getImportWarnings()', () => {
expect(warnings['custom.0.importName']).toStrictEqual({ kind: 'invalid-name' }); 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(); const values = createDefaultFormValues();
values.custom = [ values.custom = [
{ ontimeName: '', importName: 'Artist-1' }, { ontimeName: '', importName: 'Artist-1' },
@@ -67,12 +67,20 @@ describe('getImportWarnings()', () => {
{ ontimeName: '', importName: 'Presenter-1' }, { 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.0.importName']).toBeUndefined();
expect(warnings['custom.1.importName']).toStrictEqual({ kind: 'name-collision' }); expect(warnings['custom.1.importName']).toStrictEqual({ kind: 'name-collision' });
expect(warnings['custom.2.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); const storageKey = getImportMapKey(sourceKey);
try { try {
const raw = localStorage.getItem(storageKey); const raw = localStorage.getItem(storageKey);
if (!raw) { if (!raw) {
return createDefaultFormValues(); return { values: createDefaultFormValues(), isPersisted: false };
} }
const parsed: unknown = JSON.parse(raw); const parsed: unknown = JSON.parse(raw);
if (isPersistedFormValues(parsed)) { if (isPersistedFormValues(parsed)) {
return parsed; return { values: parsed, isPersisted: true };
} }
// Invalid schema - delete malformed data // Invalid schema - delete malformed data
localStorage.removeItem(storageKey); localStorage.removeItem(storageKey);
return createDefaultFormValues(); return { values: createDefaultFormValues(), isPersisted: false };
} catch { } catch {
// Parse error - delete corrupted data // Parse error - delete corrupted data
localStorage.removeItem(storageKey); localStorage.removeItem(storageKey);
return createDefaultFormValues(); return { values: createDefaultFormValues(), isPersisted: false };
} }
} }
@@ -156,11 +156,9 @@ export function getPersistedImportState(sourceKey: string): ImportFormValues {
export function getImportWarnings( export function getImportWarnings(
values: ImportFormValues, values: ImportFormValues,
detectedSpreadsheetColumns: string[], detectedSpreadsheetColumns: string[],
existingCustomFieldLabels: string[] = [],
): Record<string, MappingWarning | undefined> { ): Record<string, MappingWarning | undefined> {
const normalisedHeaders = new Set(detectedSpreadsheetColumns.map(normaliseColumnName).filter(Boolean)); const normalisedHeaders = new Set(detectedSpreadsheetColumns.map(normaliseColumnName).filter(Boolean));
const builtInLabels = new Set(builtInFieldDefs.map((def) => def.label.toLowerCase())); 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 seenColumns = new Set<string>();
const seenDerivedLabels = new Set<string>(); const seenDerivedLabels = new Set<string>();
const warnings: Record<string, MappingWarning | undefined> = {}; const warnings: Record<string, MappingWarning | undefined> = {};
@@ -200,11 +198,7 @@ export function getImportWarnings(
warnings[key] = { kind: 'missing' }; warnings[key] = { kind: 'missing' };
} else { } else {
const normalisedDerivedLabel = sanitisedLabel.toLowerCase(); const normalisedDerivedLabel = sanitisedLabel.toLowerCase();
if ( if (builtInLabels.has(normalisedDerivedLabel) || seenDerivedLabels.has(normalisedDerivedLabel)) {
builtInLabels.has(normalisedDerivedLabel) ||
existingLabels.has(normalisedDerivedLabel) ||
seenDerivedLabels.has(normalisedDerivedLabel)
) {
warnings[key] = { kind: 'name-collision' }; 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 { useFieldArray, useForm } from 'react-hook-form';
import { maybeAxiosError } from '../../../../../../common/api/utils'; import { maybeAxiosError } from '../../../../../../common/api/utils';
import useCustomFields from '../../../../../../common/hooks-query/useCustomFields';
import { formatDuration } from '../../../../../../common/utils/time'; import { formatDuration } from '../../../../../../common/utils/time';
import { import {
type ImportFormValues, type ImportFormValues,
@@ -118,10 +117,15 @@ export function useSheetImportForm({
onApply, onApply,
onExport, onExport,
}: UseSheetImportFormProps) { }: UseSheetImportFormProps) {
const initialFormValues = useMemo(() => { const { initialFormValues, skipAutoPreview } = useMemo(() => {
const persisted = getPersistedImportState(sourceKey); const { values, isPersisted } = getPersistedImportState(sourceKey);
const worksheet = getPreferredWorksheet(worksheetNames, persisted.worksheet, initialMetadata?.worksheet ?? ''); const worksheet = getPreferredWorksheet(worksheetNames, values.worksheet, initialMetadata?.worksheet ?? '');
return { ...persisted, 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]); }, [initialMetadata?.worksheet, sourceKey, worksheetNames]);
const { const {
@@ -139,7 +143,6 @@ export function useSheetImportForm({
const { fields, append, remove } = useFieldArray({ control, name: 'custom' }); const { fields, append, remove } = useFieldArray({ control, name: 'custom' });
const values = watch(); const values = watch();
const { data: existingCustomFields } = useCustomFields();
// --- Worksheet metadata via react-query --- // --- Worksheet metadata via react-query ---
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@@ -167,16 +170,14 @@ export function useSheetImportForm({
const columnLabels = buildColumnLabels(values); const columnLabels = buildColumnLabels(values);
const [state, dispatch] = useReducer(importReducer, initialImportState); const [state, dispatch] = useReducer(importReducer, initialImportState);
const existingCustomFieldLabels = useMemo( const warnings = getImportWarnings(values, headers);
() => Object.values(existingCustomFields).map((field) => field.label),
[existingCustomFields],
);
const warnings = getImportWarnings(values, headers, existingCustomFieldLabels);
const warningCount = Object.values(warnings).filter(Boolean).length; const warningCount = Object.values(warnings).filter(Boolean).length;
const previewRef = useRef<SpreadsheetPreviewResponse | null>(null); const previewRef = useRef<SpreadsheetPreviewResponse | null>(null);
const autoPreviewFiredRef = useRef(false);
// Rehydrate the form from persisted/default state whenever the source context changes. // Rehydrate the form from persisted/default state whenever the source context changes.
useEffect(() => { useEffect(() => {
autoPreviewFiredRef.current = false;
reset(initialFormValues); reset(initialFormValues);
dispatch({ type: 'reset' }); dispatch({ type: 'reset' });
}, [initialFormValues, reset]); }, [initialFormValues, reset]);
@@ -225,6 +226,16 @@ export function useSheetImportForm({
[previewImport], [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 () => { const handleApply = useCallback(async () => {
if (!state.preview) return; if (!state.preview) return;
@@ -5,14 +5,16 @@ import useScrollIntoView from '../../../../common/hooks/useScrollIntoView';
import { usePing } from '../../../../common/hooks/useSocket'; import { usePing } from '../../../../common/hooks/useSocket';
import { sendSocket } from '../../../../common/utils/socket'; import { sendSocket } from '../../../../common/utils/socket';
import { isDocker } from '../../../../externals'; import { isDocker } from '../../../../externals';
import { useAppSettingsScroll } from '../../AppSettingsScrollContext';
import type { PanelBaseProps } from '../../panel-list/PanelList'; import type { PanelBaseProps } from '../../panel-list/PanelList';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import ClientControlPanel from './client-control/ClientControlPanel'; import ClientControlPanel from './client-control/ClientControlPanel';
import LogExport from './NetworkLogExport'; import LogExport from './NetworkLogExport';
export default function NetworkLogPanel({ location }: PanelBaseProps) { export default function NetworkLogPanel({ location }: PanelBaseProps) {
const clientsRef = useScrollIntoView<HTMLDivElement>('clients', location); const { setActiveSection } = useAppSettingsScroll();
const logRef = useScrollIntoView<HTMLDivElement>('log', location); const clientsRef = useScrollIntoView<HTMLDivElement>('clients', location, setActiveSection);
const logRef = useScrollIntoView<HTMLDivElement>('log', location, setActiveSection);
return ( return (
<> <>
@@ -68,6 +68,7 @@ export default function ClientList() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{ontimeClients.length === 0 && <Panel.TableEmpty label='No clients connected' />}
{ontimeClients.map(([key, client]) => { {ontimeClients.map(([key, client]) => {
const { identify, name, path } = client; const { identify, name, path } = client;
const isCurrent = id === key; const isCurrent = id === key;
@@ -125,6 +126,7 @@ export default function ClientList() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{otherClients.length === 0 && <Panel.TableEmpty label='No other clients' />}
{otherClients.map(([key, client]) => { {otherClients.map(([key, client]) => {
const { name, type } = client; const { name, type } = client;
@@ -1,4 +1,5 @@
import useScrollIntoView from '../../../../common/hooks/useScrollIntoView'; import useScrollIntoView from '../../../../common/hooks/useScrollIntoView';
import { useAppSettingsScroll } from '../../AppSettingsScrollContext';
import type { PanelBaseProps } from '../../panel-list/PanelList'; import type { PanelBaseProps } from '../../panel-list/PanelList';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import QuickStart from '../../quick-start/QuickStart'; import QuickStart from '../../quick-start/QuickStart';
@@ -10,7 +11,8 @@ interface ProjectPanelProps extends PanelBaseProps {
} }
export default function ProjectPanel({ location, setLocation }: ProjectPanelProps) { export default function ProjectPanel({ location, setLocation }: ProjectPanelProps) {
const manageProjectsRef = useScrollIntoView<HTMLDivElement>('list', location); const { setActiveSection } = useAppSettingsScroll();
const manageProjectsRef = useScrollIntoView<HTMLDivElement>('list', location, setActiveSection);
const handleQuickClose = () => { const handleQuickClose = () => {
setLocation('project'); setLocation('project');
@@ -11,6 +11,7 @@ import Select from '../../../../common/components/select/Select';
import useSettings from '../../../../common/hooks-query/useSettings'; import useSettings from '../../../../common/hooks-query/useSettings';
import { preventEscape } from '../../../../common/utils/keyEvent'; import { preventEscape } from '../../../../common/utils/keyEvent';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import { useSettingsDirty } from '../../useSettingsDirty';
import GeneralPinInput from './composite/GeneralPinInput'; import GeneralPinInput from './composite/GeneralPinInput';
const TranslationModal = lazy(() => import('./composite/CustomTranslationModal')); const TranslationModal = lazy(() => import('./composite/CustomTranslationModal'));
@@ -32,6 +33,7 @@ export default function GeneralSettings() {
keepDirtyValues: true, keepDirtyValues: true,
}, },
}); });
useSettingsDirty(isDirty);
const [isOpen, handler] = useDisclosure(); const [isOpen, handler] = useDisclosure();
@@ -14,6 +14,7 @@ import { preventEscape } from '../../../../common/utils/keyEvent';
import { validateLogo } from '../../../../common/utils/uploadUtils'; import { validateLogo } from '../../../../common/utils/uploadUtils';
import { documentationUrl } from '../../../../externals'; import { documentationUrl } from '../../../../externals';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import { useSettingsDirty } from '../../useSettingsDirty';
import style from './SettingsPanel.module.scss'; import style from './SettingsPanel.module.scss';
@@ -38,6 +39,7 @@ export default function ProjectData() {
}, },
mode: 'onChange', mode: 'onChange',
}); });
useSettingsDirty(isDirty);
const { fields, append, remove } = useFieldArray({ const { fields, append, remove } = useFieldArray({
control, control,
@@ -9,6 +9,7 @@ import useServerPort from '../../../../common/hooks-query/useServerPort';
import { preventEscape } from '../../../../common/utils/keyEvent'; import { preventEscape } from '../../../../common/utils/keyEvent';
import { isOnlyNumbers } from '../../../../common/utils/regex'; import { isOnlyNumbers } from '../../../../common/utils/regex';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import { useSettingsDirty } from '../../useSettingsDirty';
interface ServerPortForm { interface ServerPortForm {
serverPort: number; serverPort: number;
@@ -27,6 +28,7 @@ export default function ServerPortSettings() {
mode: 'onChange', mode: 'onChange',
defaultValues: { serverPort: 4001 }, defaultValues: { serverPort: 4001 },
}); });
useSettingsDirty(isDirty);
useEffect(() => { useEffect(() => {
reset({ serverPort: data.port }); reset({ serverPort: data.port });
@@ -1,5 +1,6 @@
import useScrollIntoView from '../../../../common/hooks/useScrollIntoView'; import useScrollIntoView from '../../../../common/hooks/useScrollIntoView';
import { isDocker } from '../../../../externals'; import { isDocker } from '../../../../externals';
import { useAppSettingsScroll } from '../../AppSettingsScrollContext';
import type { PanelBaseProps } from '../../panel-list/PanelList'; import type { PanelBaseProps } from '../../panel-list/PanelList';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import CustomViews from '../manage-panel/CustomViews'; import CustomViews from '../manage-panel/CustomViews';
@@ -9,11 +10,12 @@ import ServerPortSettings from './ServerPortSettings';
import ViewSettings from './ViewSettings'; import ViewSettings from './ViewSettings';
export default function SettingsPanel({ location }: PanelBaseProps) { export default function SettingsPanel({ location }: PanelBaseProps) {
const dataRef = useScrollIntoView<HTMLDivElement>('data', location); const { setActiveSection } = useAppSettingsScroll();
const generalRef = useScrollIntoView<HTMLDivElement>('general', location); const dataRef = useScrollIntoView<HTMLDivElement>('data', location, setActiveSection);
const viewRef = useScrollIntoView<HTMLDivElement>('view', location); const generalRef = useScrollIntoView<HTMLDivElement>('general', location, setActiveSection);
const customViewsRef = useScrollIntoView<HTMLDivElement>('custom-views', location); const viewRef = useScrollIntoView<HTMLDivElement>('view', location, setActiveSection);
const portRef = useScrollIntoView<HTMLDivElement>('port', location); const customViewsRef = useScrollIntoView<HTMLDivElement>('custom-views', location, setActiveSection);
const portRef = useScrollIntoView<HTMLDivElement>('port', location, setActiveSection);
return ( return (
<> <>
@@ -13,6 +13,7 @@ import Tag from '../../../../common/components/tag/Tag';
import useViewSettings from '../../../../common/hooks-query/useViewSettings'; import useViewSettings from '../../../../common/hooks-query/useViewSettings';
import { preventEscape } from '../../../../common/utils/keyEvent'; import { preventEscape } from '../../../../common/utils/keyEvent';
import * as Panel from '../../panel-utils/PanelUtils'; import * as Panel from '../../panel-utils/PanelUtils';
import { useSettingsDirty } from '../../useSettingsDirty';
import CodeEditorModal from './composite/StyleEditorModal'; import CodeEditorModal from './composite/StyleEditorModal';
const cssOverrideDocsUrl = 'https://docs.getontime.no/features/custom-styling/'; const cssOverrideDocsUrl = 'https://docs.getontime.no/features/custom-styling/';
@@ -35,6 +36,7 @@ export default function ViewSettings() {
keepDirtyValues: true, keepDirtyValues: true,
}, },
}); });
useSettingsDirty(isDirty);
// update form if we get new data from server // update form if we get new data from server
useEffect(() => { useEffect(() => {
@@ -20,4 +20,5 @@
border: 1px solid $gray-1100; border: 1px solid $gray-1100;
border-radius: 3px; border-radius: 3px;
overflow: hidden; overflow: hidden;
height: 100%;
} }
@@ -7,7 +7,6 @@ export type SettingsOption = {
id: string; id: string;
label: string; label: string;
secondary?: Readonly<SettingsOption[]>; secondary?: Readonly<SettingsOption[]>;
split?: boolean;
highlight?: string; highlight?: string;
}; };
@@ -26,7 +25,6 @@ const staticOptions = [
{ {
id: 'project', id: 'project',
label: 'Project', label: 'Project',
split: true,
secondary: [ secondary: [
{ id: 'project__create', label: 'Create...' }, { id: 'project__create', label: 'Create...' },
{ id: 'project__list', label: 'Manage projects' }, { id: 'project__list', label: 'Manage projects' },
@@ -46,7 +44,6 @@ const staticOptions = [
{ {
id: 'automation', id: 'automation',
label: 'Automation', label: 'Automation',
split: true,
secondary: [ secondary: [
{ id: 'automation__settings', label: 'Automation settings' }, { id: 'automation__settings', label: 'Automation settings' },
{ id: 'automation__automations', label: 'Manage automations' }, { id: 'automation__automations', label: 'Manage automations' },
@@ -56,7 +53,6 @@ const staticOptions = [
{ {
id: 'sharing', id: 'sharing',
label: 'Sharing and reporting', label: 'Sharing and reporting',
split: true,
secondary: [ secondary: [
{ id: 'sharing__presets', label: 'URL Presets' }, { id: 'sharing__presets', label: 'URL Presets' },
{ {
@@ -69,7 +65,6 @@ const staticOptions = [
{ {
id: 'network', id: 'network',
label: 'Network', label: 'Network',
split: true,
secondary: [ secondary: [
{ {
id: 'network__log', id: 'network__log',
@@ -84,15 +79,22 @@ const staticOptions = [
{ {
id: 'about', id: 'about',
label: 'About', label: 'About',
split: true,
}, },
{ {
id: 'shutdown', id: 'shutdown',
label: 'Shutdown', label: 'Shutdown',
split: true,
}, },
] as const; ] as const;
export function getPanelLabel(panel: string, location?: string): { panelLabel: string; sectionLabel?: string } {
const panelOption = staticOptions.find((o) => o.id === panel);
if (!panelOption) return { panelLabel: panel };
const panelLabel = panelOption.label;
if (!location || !('secondary' in panelOption)) return { panelLabel };
const match = panelOption.secondary.find((s) => s.id.split('__')[1] === location);
return { panelLabel, sectionLabel: match?.label };
}
// a child of navigation or a child of secondary navigation // a child of navigation or a child of secondary navigation
export type SettingsOptionId = export type SettingsOptionId =
| (typeof staticOptions)[number]['id'] | (typeof staticOptions)[number]['id']
@@ -0,0 +1,14 @@
import { useEffect } from 'react';
import { markClean, markDirty } from './appSettingsDirtyState';
export function useSettingsDirty(isDirty: boolean) {
useEffect(() => {
if (isDirty) {
markDirty();
} else {
markClean();
}
return () => markClean();
}, [isDirty]);
}
@@ -16,6 +16,7 @@ import EntryEditModal from '../../views/cuesheet/cuesheet-edit-modal/EntryEditMo
import { EditorLayoutMode, useEditorLayout } from '../../views/editor/useEditorLayout'; import { EditorLayoutMode, useEditorLayout } from '../../views/editor/useEditorLayout';
import RundownEntryEditor from './entry-editor/RundownEntryEditor'; import RundownEntryEditor from './entry-editor/RundownEntryEditor';
import FinderPlacement from './placements/FinderPlacement'; import FinderPlacement from './placements/FinderPlacement';
import RenumberCuesDialog from './renumber-cues-dialog/RenumberCuesDialog';
import { RundownContextMenu } from './rundown-context-menu/RundownContextMenu'; import { RundownContextMenu } from './rundown-context-menu/RundownContextMenu';
import RundownHeader from './rundown-header/RundownHeader'; import RundownHeader from './rundown-header/RundownHeader';
import RundownHeaderMobile from './rundown-header/RundownHeaderMobile'; import RundownHeaderMobile from './rundown-header/RundownHeaderMobile';
@@ -112,6 +113,7 @@ function RundownRoot({ isSmallDevice, isExtracted, viewMode, setViewMode }: Rund
)} )}
{viewMode === RundownViewMode.List ? <RundownList /> : <RundownTable />} {viewMode === RundownViewMode.List ? <RundownList /> : <RundownTable />}
{viewMode === RundownViewMode.Table && <EntryEditModal />} {viewMode === RundownViewMode.Table && <EntryEditModal />}
<RenumberCuesDialog />
</div> </div>
); );
} }
@@ -104,6 +104,7 @@
/* approximating the style of a disabled input */ /* approximating the style of a disabled input */
.textLikeInput { .textLikeInput {
color: $gray-200;
background: transparent; background: transparent;
justify-content: start; justify-content: start;
width: 7.5em; width: 7.5em;
@@ -1,4 +1,3 @@
import { sanitiseCue } from 'ontime-utils';
import { memo } from 'react'; import { memo } from 'react';
import * as Editor from '../../../../common/components/editor-utils/EditorUtils'; 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) { function EventEditorTitles({ eventId, cue, flag, title, note, colour }: EventEditorTitlesProps) {
const { updateEntry } = useEntryActionsContext(); const { updateEntry } = useEntryActionsContext();
const cueSubmitHandler = (_field: string, newValue: string) => {
updateEntry({ id: eventId, cue: sanitiseCue(newValue) });
};
const flagSubmitHandler = (newValue: boolean) => { const flagSubmitHandler = (newValue: boolean) => {
updateEntry({ id: eventId, flag: newValue }); updateEntry({ id: eventId, flag: newValue });
}; };
@@ -48,7 +43,7 @@ function EventEditorTitles({ eventId, cue, flag, title, note, colour }: EventEdi
field='cue' field='cue'
label='Cue' label='Cue'
initialValue={cue} initialValue={cue}
submitHandler={cueSubmitHandler} submitHandler={textSubmitHandler}
maxLength={10} maxLength={10}
/> />
<div> <div>
@@ -4,18 +4,6 @@
gap: 0.75rem; gap: 0.75rem;
} }
.section,
.formSection {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.sectionTitle {
font-size: $aux-text-size;
color: $label-gray;
}
.triggerList { .triggerList {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -25,25 +13,13 @@
overflow: hidden; overflow: hidden;
} }
.triggerForm { .triggerHeader {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.formFields {
display: grid; display: grid;
grid-template-columns: 8rem 1fr; grid-template-columns: 8rem 1fr 2rem;
gap: 0.75rem; gap: 0.5rem;
align-items: end; padding: 0.375rem 0.75rem;
} font-size: $aux-text-size;
color: $label-gray;
.formActions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.75rem;
min-height: 2rem;
} }
.trigger { .trigger {
@@ -51,40 +27,22 @@
display: grid; display: grid;
grid-template-columns: 8rem 1fr 2rem; grid-template-columns: 8rem 1fr 2rem;
align-items: center; align-items: center;
gap: 0.5rem;
min-height: 2.5rem; min-height: 2.5rem;
&:not(:first-child) { &:not(:first-child) {
border-top: 1px solid $white-10; border-top: 1px solid $white-10;
} }
&[data-duplicate] {
> button:not(:last-child) {
border-color: $orange-500;
}
}
} }
.triggerMeta { .duplicateMessage {
min-width: 0; padding-left: 0.75rem;
}
.metaLabel {
color: $label-gray;
font-size: $aux-text-size; font-size: $aux-text-size;
line-height: 1.2; color: $orange-500;
margin-bottom: 0.125rem;
}
.automationTitle {
overflow-wrap: anywhere;
}
.validationError,
.validationSuccess {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: $aux-text-size;
}
.validationError {
color: $red-500;
}
.validationSuccess {
color: $green-500;
} }
@@ -1,11 +1,9 @@
import { NormalisedAutomation, TimerLifeCycle, Trigger, timerLifecycleValues } from 'ontime-types'; import { Trigger } from 'ontime-types';
import { generateId } from 'ontime-utils'; import { generateId } from 'ontime-utils';
import { Fragment, useCallback, useMemo, useState } from 'react'; import { IoAdd, IoTrash } from 'react-icons/io5';
import { IoAlertCircle, IoCheckmarkCircle, IoTrash } from 'react-icons/io5';
import Button from '../../../../common/components/buttons/Button'; import Button from '../../../../common/components/buttons/Button';
import IconButton from '../../../../common/components/buttons/IconButton'; import IconButton from '../../../../common/components/buttons/IconButton';
import * as Editor from '../../../../common/components/editor-utils/EditorUtils';
import Info from '../../../../common/components/info/Info'; import Info from '../../../../common/components/info/Info';
import Select from '../../../../common/components/select/Select'; import Select from '../../../../common/components/select/Select';
import { useEntryActionsContext } from '../../../../common/context/EntryActionsContext'; import { useEntryActionsContext } from '../../../../common/context/EntryActionsContext';
@@ -21,174 +19,108 @@ interface EventEditorTriggersProps {
export default function EventEditorTriggers({ triggers, eventId }: EventEditorTriggersProps) { export default function EventEditorTriggers({ triggers, eventId }: EventEditorTriggersProps) {
const { data: automationSettings, status: automationStatus } = useAutomationSettings(); const { data: automationSettings, status: automationStatus } = useAutomationSettings();
const { updateEntry } = useEntryActionsContext();
const automationsEnabled = automationStatus === 'pending' ? undefined : automationSettings.enabledAutomations; const automationsEnabled = automationStatus === 'pending' ? undefined : automationSettings.enabledAutomations;
const showTriggers = triggers.length > 0;
const allAutomationOptions = Object.values(automationSettings.automations).map(({ id, title }) => ({
value: id,
label: title,
}));
const hasAutomationOptions = allAutomationOptions.length > 0;
const triggerOptions = eventTriggerOptions.map((cycle) => ({ value: cycle, label: cycle }));
const duplicateIds = new Set<string>();
const seen = new Map<string, string>();
for (const trigger of triggers) {
const key = `${trigger.trigger}:${trigger.automationId}`;
if (seen.has(key)) {
duplicateIds.add(trigger.id);
} else {
seen.set(key, trigger.id);
}
}
const handleAdd = () => {
if (!hasAutomationOptions) return;
updateEntry({
id: eventId,
triggers: [
...triggers,
{ id: generateId(), title: '', trigger: eventTriggerOptions[0], automationId: allAutomationOptions[0].value },
],
});
};
const handleDelete = (triggerId: string) => {
updateEntry({ id: eventId, triggers: triggers.filter((t) => t.id !== triggerId) });
};
const handleChange = (triggerId: string, field: 'trigger' | 'automationId', value: string) => {
const newTriggers = triggers.map((t) => (t.id !== triggerId ? t : { ...t, [field]: value }));
updateEntry({ id: eventId, triggers: newTriggers });
};
return ( return (
<div className={style.triggers}> <div className={style.triggers}>
{automationsEnabled === false && ( {automationsEnabled === false && (
<Info>Automations are disabled. Event triggers stay configured, but they will not run until enabled.</Info> <Info>Automations are disabled. Event triggers stay configured, but they will not run until enabled.</Info>
)} )}
{showTriggers && ( {automationsEnabled && !hasAutomationOptions && (
<div className={style.section}> <Info>
<div className={style.sectionTitle}>Applied automations</div> <Info.Title>No automations available</Info.Title>
<ExistingEventTriggers triggers={triggers} eventId={eventId} automations={automationSettings.automations} /> <Info.Body>Create an automation before attaching it to this event.</Info.Body>
</div> </Info>
)} )}
<Editor.Panel className={style.formSection}> {triggers.length > 0 && (
<div className={style.sectionTitle}>Add automation</div> <div className={style.triggerList}>
<EventTriggerForm triggers={triggers} eventId={eventId} automations={automationSettings.automations} /> <div className={style.triggerHeader}>
</Editor.Panel> <span>Lifecycle</span>
</div> <span>Automation</span>
); </div>
} {triggers.map((trigger) => {
const isDuplicate = duplicateIds.has(trigger.id);
interface EventTriggerFormProps { const lifecycleOptions = isDuplicate
eventId: string; ? triggerOptions.map((opt) => (opt.value === trigger.trigger ? { ...opt, label: `${opt.label} *` } : opt))
triggers?: Trigger[]; : triggerOptions;
automations: NormalisedAutomation; const automationOptions = isDuplicate
} ? allAutomationOptions.map((opt) =>
opt.value === trigger.automationId ? { ...opt, label: `${opt.label} *` } : opt,
function EventTriggerForm({ eventId, triggers, automations }: EventTriggerFormProps) { )
const { updateEntry } = useEntryActionsContext(); : allAutomationOptions;
const [automationId, setAutomationId] = useState<string | undefined>(undefined);
const [cycleValue, setCycleValue] = useState(TimerLifeCycle.onStart);
const handleSubmit = (triggerLifeCycle: TimerLifeCycle, automationId: string) => {
const newTriggers = triggers ?? new Array<Trigger>();
const id = generateId();
newTriggers.push({ id, title: '', trigger: triggerLifeCycle, automationId });
updateEntry({ id: eventId, triggers: newTriggers });
};
const getValidationError = (cycle: TimerLifeCycle, automationId?: string): string | undefined => {
if (automationId === undefined) {
return 'Select an automation';
}
if (!Object.keys(automations).includes(automationId)) {
return 'This automation does not exist';
}
if (triggers === undefined) {
return;
}
return Object.values(triggers).some((t) => t.automationId === automationId && t.trigger === cycle)
? 'Automation can only be used once'
: undefined;
};
const validationError = getValidationError(cycleValue, automationId);
const validationLabel = validationError ?? 'Ready to add automation';
const triggerOptions = useMemo(
() => [
{ value: null, label: 'Select lifecycle' },
...eventTriggerOptions.map((cycle) => ({ value: cycle, label: cycle })),
],
[], // eventTriggerOptions is a constant, no need for dependency
);
const automationOptions = useMemo(
() => [
{ value: null, label: 'Select Automation' },
...Object.values(automations).map(({ id, title }) => ({ value: id, label: title })),
],
[automations], // This needs to be a dependency as it can change
);
return (
<div className={style.triggerForm}>
<div className={style.formFields}>
<div>
<Editor.Label>Lifecycle</Editor.Label>
<Select
value={cycleValue}
onValueChange={(value) => {
if (value !== null) setCycleValue(value);
}}
options={triggerOptions}
/>
</div>
<div>
<Editor.Label>Automation</Editor.Label>
<Select
value={automationId ?? null}
onValueChange={(value) => {
if (value !== null) setAutomationId(value);
}}
options={automationOptions}
/>
</div>
</div>
<div className={style.formActions}>
<div className={validationError ? style.validationError : style.validationSuccess}>
{validationError ? <IoAlertCircle /> : <IoCheckmarkCircle />}
<span>{validationLabel}</span>
</div>
<Button
disabled={validationError !== undefined}
onClick={() => automationId && handleSubmit(cycleValue, automationId)}
>
Add automation
</Button>
</div>
</div>
);
}
interface ExistingEventTriggersProps {
eventId: string;
triggers: Trigger[];
automations: NormalisedAutomation;
}
function ExistingEventTriggers({ eventId, triggers, automations }: ExistingEventTriggersProps) {
const { updateEntry } = useEntryActionsContext();
const handleDelete = useCallback(
(triggerId: string) => {
const newTriggers = triggers.filter((trigger) => trigger.id !== triggerId);
updateEntry({ id: eventId, triggers: newTriggers });
},
[eventId, triggers, updateEntry],
);
const filteredTriggers: Record<string, Trigger[]> = {};
// sort triggers out into groups by the Lifecycle they are on
timerLifecycleValues.forEach((triggerType) => {
const thisTriggerType = triggers.filter((trigger) => trigger.trigger === triggerType);
if (thisTriggerType.length) {
Object.assign(filteredTriggers, { [triggerType]: thisTriggerType });
}
});
return (
<div className={style.triggerList}>
{Object.entries(filteredTriggers).map(([triggerLifeCycle, triggerGroup]) => (
<Fragment key={triggerLifeCycle}>
{triggerGroup.map((trigger) => {
const { id, automationId } = trigger;
const automationTitle = automations[automationId]?.title ?? '<MISSING AUTOMATION>';
return ( return (
<div key={id} className={style.trigger}> <div key={trigger.id} className={style.trigger} data-duplicate={isDuplicate || undefined}>
<div className={style.triggerMeta}> <Select
<div className={style.metaLabel}>Lifecycle</div> value={trigger.trigger}
<div>{triggerLifeCycle}</div> onValueChange={(value) => {
</div> if (value !== null) handleChange(trigger.id, 'trigger', value);
<div className={style.triggerMeta}> }}
<div className={style.metaLabel}>Automation</div> options={lifecycleOptions}
<div className={style.automationTitle}>{automationTitle}</div> />
</div> <Select
<IconButton variant='ghosted-destructive' onClick={() => handleDelete(id)}> value={trigger.automationId}
onValueChange={(value) => {
if (value !== null) handleChange(trigger.id, 'automationId', value);
}}
options={automationOptions}
/>
<IconButton variant='ghosted-destructive' onClick={() => handleDelete(trigger.id)}>
<IoTrash /> <IoTrash />
</IconButton> </IconButton>
</div> </div>
); );
})} })}
</Fragment> </div>
))} )}
{duplicateIds.size > 0 && (
<span className={style.duplicateMessage}>
* Duplicate combinations will only fire once per lifecycle event.
</span>
)}
{hasAutomationOptions && (
<Button variant='ghosted' onClick={handleAdd}>
<IoAdd /> Add automation
</Button>
)}
</div> </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, IoTrash,
IoUnlink, IoUnlink,
} from 'react-icons/io5'; } from 'react-icons/io5';
import { TbFlagFilled } from 'react-icons/tb'; import { TbFlagFilled, TbListNumbers } from 'react-icons/tb';
import { useEntryActionsContext } from '../../../common/context/EntryActionsContext'; import { useEntryActionsContext } from '../../../common/context/EntryActionsContext';
import { useContextMenu } from '../../../common/hooks/useContextMenu'; import { useContextMenu } from '../../../common/hooks/useContextMenu';
import { useEntryCopy } from '../../../common/stores/entryCopyStore'; import { useEntryCopy } from '../../../common/stores/entryCopyStore';
import { deviceMod } from '../../../common/utils/deviceUtils'; import { deviceMod } from '../../../common/utils/deviceUtils';
import { cx, getAccessibleColour } from '../../../common/utils/styleUtils'; import { cx, getAccessibleColour } from '../../../common/utils/styleUtils';
import { useRenumberCuesDialogStore } from '../renumber-cues-dialog/RenumberCuesDialog';
import { useEventIdSwapping } from '../useEventIdSwapping'; import { useEventIdSwapping } from '../useEventIdSwapping';
import { getSelectionMode, useEventSelection } from '../useEventSelection'; import { getSelectionMode, useEventSelection } from '../useEventSelection';
import RundownEventInner from './RundownEventInner'; import RundownEventInner from './RundownEventInner';
@@ -99,6 +100,7 @@ export default function RundownEvent({
const selectedEventId = useEventIdSwapping((state) => state.selectedEventId); const selectedEventId = useEventIdSwapping((state) => state.selectedEventId);
const setSelectedEventId = useEventIdSwapping((state) => state.setSelectedEventId); const setSelectedEventId = useEventIdSwapping((state) => state.setSelectedEventId);
const clearSelectedEventId = useEventIdSwapping((state) => state.clearSelectedEventId); const clearSelectedEventId = useEventIdSwapping((state) => state.clearSelectedEventId);
const openRenumberDialog = useRenumberCuesDialogStore((state) => state.onOpen);
const { updateEntry, batchUpdateEvents, clone, deleteEntry, groupEntries, swapEvents } = useEntryActionsContext(); const { updateEntry, batchUpdateEvents, clone, deleteEntry, groupEntries, swapEvents } = useEntryActionsContext();
@@ -143,6 +145,13 @@ export default function RundownEvent({
disabled: parent !== null, disabled: parent !== null,
}, },
{ type: 'divider' }, { type: 'divider' },
{
type: 'item',
label: 'Renumber cues',
icon: TbListNumbers,
onClick: openRenumberDialog,
},
{ type: 'divider' },
{ {
type: 'item', type: 'item',
label: 'Delete', label: 'Delete',
+1
View File
@@ -81,6 +81,7 @@ html,
user-select: none; user-select: none;
-webkit-app-region: drag; -webkit-app-region: drag;
isolation: isolate; isolation: isolate;
background-color: $ui-black; // prevent the safari from showing white background
} }
// reset button styles // reset button styles
+13 -11
View File
@@ -24,16 +24,18 @@ export default function ViewLoader({ children }: PropsWithChildren) {
const colourFromParams = searchParams.get('keyColour') ?? '#101010'; const colourFromParams = searchParams.get('keyColour') ?? '#101010';
return ( return (
<Suspense <>
fallback={ <style>{`body { background: var(--background-color-override, ${colourFromParams}); }`}</style>
<> <Suspense
<style>{`body { background: var(--background-color-override, ${colourFromParams}); }`}</style> fallback={
<Loader /> <>
</> <Loader />
} </>
> }
<OverrideStyles /> >
{children} <OverrideStyles />
</Suspense> {children}
</Suspense>
</>
); );
} }
+13 -8
View File
@@ -43,7 +43,7 @@ export default function BackstageLoader() {
function Backstage({ events, customFields, projectData, isMirrored, settings }: BackstageData) { function Backstage({ events, customFields, projectData, isMirrored, settings }: BackstageData) {
const { getLocalizedString } = useTranslation(); const { getLocalizedString } = useTranslation();
const { mainSource, secondarySource, extraInfo } = useBackstageOptions(); const { mainSource, secondarySource, extraInfo, timeformat } = useBackstageOptions();
const { eventNext, eventNow, rundown, selectedEventId, time } = useBackstageSocket(); const { eventNext, eventNow, rundown, selectedEventId, time } = useBackstageSocket();
const [blinkClass, setBlinkClass] = useState(false); const [blinkClass, setBlinkClass] = useState(false);
const { height: screenHeight } = useViewportSize(); const { height: screenHeight } = useViewportSize();
@@ -71,18 +71,20 @@ function Backstage({ events, customFields, projectData, isMirrored, settings }:
// gather timer data // gather timer data
const isPendingStart = getIsPendingStart(time.playback, time.phase); 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 = (() => { const scheduledStart = (() => {
if (showNow) return undefined; if (showNow) return undefined;
if (!hasEvents) 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 = (() => { const scheduledEnd = (() => {
if (showNow) return undefined; if (showNow) return undefined;
if (!hasEvents) 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 }); let displayTimer = millisToString(time.current, { fallback: timerPlaceholderMin });
@@ -107,7 +109,7 @@ function Backstage({ events, customFields, projectData, isMirrored, settings }:
<div className='project-header'> <div className='project-header'>
{projectData?.logo && <ViewLogo name={projectData.logo} className='logo' />} {projectData?.logo && <ViewLogo name={projectData.logo} className='logo' />}
<div className='title'>{projectData.title}</div> <div className='title'>{projectData.title}</div>
<BackstageClock /> <BackstageClock timeformat={timeformat} />
</div> </div>
{showProgress && <ProgressBar className='progress-container' current={time.current} duration={time.duration} />} {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) ? ( {isOvertime(time.current) ? (
<div className='time-entry__value'>{getLocalizedString('countdown.overtime')}</div> <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>
<div className='timer-gap' /> <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 { getLocalizedString } = useTranslation();
const clock = useAutoTickingClock(); const clock = useAutoTickingClock();
// gather timer data // gather timer data
const formattedClock = formatTime(clock); const formattedClock = formatTime(clock, { override: timeformat });
return ( return (
<div className='clock-container'> <div className='clock-container'>
@@ -2,7 +2,11 @@ import { CustomFields, OntimeEvent, ProjectData } from 'ontime-types';
import { use, useMemo } from 'react'; import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router'; 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 { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types'; import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import { import {
@@ -71,7 +75,7 @@ type BackstageOptions = {
mainSource: keyof OntimeEvent | null; mainSource: keyof OntimeEvent | null;
secondarySource: keyof OntimeEvent | null; secondarySource: keyof OntimeEvent | null;
extraInfo: string | null; extraInfo: string | null;
}; } & TimeOptions;
/** /**
* Utility extract the view options from URL Params * 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, mainSource: getValue('main') as keyof OntimeEvent | null,
secondarySource: getValue('secondary-src') as keyof OntimeEvent | null, secondarySource: getValue('secondary-src') as keyof OntimeEvent | null,
extraInfo: getValue('extra-info'), extraInfo: getValue('extra-info'),
timeformat: getTimeOptionsFromParams(searchParams, defaultValues),
}; };
} }
+2 -1
View File
@@ -101,6 +101,7 @@ export function getPropertyValue(
type FormattingOptions = { type FormattingOptions = {
removeSeconds: boolean; removeSeconds: boolean;
removeLeadingZero: boolean; removeLeadingZero: boolean;
clockFormat?: MaybeString;
}; };
export function getFormattedTimer( export function getFormattedTimer(
@@ -114,7 +115,7 @@ export function getFormattedTimer(
} }
if (timerType === TimerType.Clock) { if (timerType === TimerType.Clock) {
return formatTime(timer); return formatTime(timer, { override: options?.clockFormat });
} }
let timeToParse = timer; let timeToParse = timer;
@@ -139,11 +139,12 @@ function CountdownContents({ playableEvents, subscriptions, goToEditMode }: Coun
} }
function CountdownClock() { function CountdownClock() {
const { timeformat } = useCountdownOptions();
const { getLocalizedString } = useTranslation(); const { getLocalizedString } = useTranslation();
const clock = useAutoTickingClock(); const clock = useAutoTickingClock();
// gather timer data // gather timer data
const formattedClock = formatTime(clock); const formattedClock = formatTime(clock, { override: timeformat });
return ( return (
<div className='clock-container'> <div className='clock-container'>
@@ -2,7 +2,11 @@ import { CustomFields, EntryId, OntimeEvent } from 'ontime-types';
import { use, useMemo } from 'react'; import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router'; 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 { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types'; import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils'; import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils';
@@ -91,7 +95,7 @@ type CountdownOptions = {
secondarySource: keyof OntimeEvent | null; secondarySource: keyof OntimeEvent | null;
showExpected: boolean; showExpected: boolean;
hidePast: boolean; hidePast: boolean;
}; } & TimeOptions;
/** /**
* Utility extract the view options from URL Params * 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, secondarySource: getValue('secondary-src') as keyof OntimeEvent | null,
showExpected: isStringBoolean(getValue('showExpected')), showExpected: isStringBoolean(getValue('showExpected')),
hidePast: isStringBoolean(getValue('hidePast')), hidePast: isStringBoolean(getValue('hidePast')),
timeformat: getTimeOptionsFromParams(searchParams, defaultValues),
}; };
} }
@@ -1,7 +1,7 @@
import { Table, flexRender } from '@tanstack/react-table'; import { Table, flexRender } from '@tanstack/react-table';
import { EntryId, OntimeEntry, RGBColour, SupportedEntry } from 'ontime-types'; import { EntryId, OntimeEntry, RGBColour, SupportedEntry } from 'ontime-types';
import { colourToHex, cssOrHexToColour } from 'ontime-utils'; import { colourToHex, cssOrHexToColour } from 'ontime-utils';
import { CSSProperties, useMemo } from 'react'; import { CSSProperties, memo, useMemo } from 'react';
import { IoEllipsisHorizontal } from 'react-icons/io5'; import { IoEllipsisHorizontal } from 'react-icons/io5';
import IconButton from '../../../../common/components/buttons/IconButton'; import IconButton from '../../../../common/components/buttons/IconButton';
@@ -30,7 +30,8 @@ interface EventRowProps {
hasCursor?: boolean; hasCursor?: boolean;
} }
export default function EventRow({ export default memo(EventRow);
function EventRow({
rowId, rowId,
id, id,
eventIndex, eventIndex,
@@ -55,24 +56,25 @@ export default function EventRow({
const openMenu = useCuesheetTableMenu((store) => store.openMenu); const openMenu = useCuesheetTableMenu((store) => store.openMenu);
const { color, backgroundColor } = getAccessibleColour(colour); const { rowBgColour, backgroundColor, mutedText } = useMemo(() => {
const tmpColour = cssOrHexToColour(color) as RGBColour; // we know this to be a correct colour const accessible = getAccessibleColour(colour);
const mutedText = colourToHex({ ...tmpColour, alpha: tmpColour.alpha * 0.8 }); const tmpColour = cssOrHexToColour(accessible.color) as RGBColour;
const rowBgColour: string | undefined = useMemo(() => { let rowBgColour: string | undefined;
if (isLoaded) { if (isLoaded) {
return '#087A27'; // $active-green rowBgColour = '#087A27'; // $active-green
} else if (colour) { } else if (colour) {
// the colour is user defined and might be invalid const accessibleBg = cssOrHexToColour(accessible.backgroundColor);
const accessibleBackgroundColor = cssOrHexToColour(getAccessibleColour(colour).backgroundColor); if (accessibleBg !== null) {
if (accessibleBackgroundColor !== null) { rowBgColour = colourToHex({ ...accessibleBg, alpha: accessibleBg.alpha * 0.25 });
return colourToHex({
...accessibleBackgroundColor,
alpha: accessibleBackgroundColor.alpha * 0.25,
});
} }
} }
return;
return {
rowBgColour,
backgroundColor: accessible.backgroundColor,
mutedText: colourToHex({ ...tmpColour, alpha: tmpColour.alpha * 0.8 }),
};
}, [colour, isLoaded]); }, [colour, isLoaded]);
return ( return (
@@ -1,6 +1,6 @@
import { Table, flexRender } from '@tanstack/react-table'; import { Table, flexRender } from '@tanstack/react-table';
import { EntryId, SupportedEntry } from 'ontime-types'; import { EntryId, SupportedEntry } from 'ontime-types';
import { CSSProperties } from 'react'; import { CSSProperties, memo } from 'react';
import { IoEllipsisHorizontal } from 'react-icons/io5'; import { IoEllipsisHorizontal } from 'react-icons/io5';
import IconButton from '../../../../common/components/buttons/IconButton'; import IconButton from '../../../../common/components/buttons/IconButton';
@@ -20,7 +20,8 @@ interface GroupRowProps {
hasCursor?: boolean; hasCursor?: boolean;
} }
export default function GroupRow({ export default memo(GroupRow);
function GroupRow({
groupId, groupId,
colour, colour,
rowId, rowId,
@@ -1,7 +1,7 @@
import { Table, flexRender } from '@tanstack/react-table'; import { Table, flexRender } from '@tanstack/react-table';
import { EntryId, SupportedEntry } from 'ontime-types'; import { EntryId, SupportedEntry } from 'ontime-types';
import { colourToHex, cssOrHexToColour } from 'ontime-utils'; import { colourToHex, cssOrHexToColour } from 'ontime-utils';
import { CSSProperties } from 'react'; import { CSSProperties, memo, useMemo } from 'react';
import { IoEllipsisHorizontal } from 'react-icons/io5'; import { IoEllipsisHorizontal } from 'react-icons/io5';
import IconButton from '../../../../common/components/buttons/IconButton'; import IconButton from '../../../../common/components/buttons/IconButton';
@@ -25,7 +25,8 @@ interface MilestoneRowProps {
hasCursor?: boolean; hasCursor?: boolean;
} }
export default function MilestoneRow({ export default memo(MilestoneRow);
function MilestoneRow({
entryId, entryId,
isPast, isPast,
parentBgColour, parentBgColour,
@@ -45,17 +46,12 @@ export default function MilestoneRow({
const openMenu = useCuesheetTableMenu((store) => store.openMenu); const openMenu = useCuesheetTableMenu((store) => store.openMenu);
let rowBgColour: string | undefined; const rowBgColour = useMemo(() => {
if (colour) { if (!colour) return undefined;
// the colour is user defined and might be invalid const accessibleBg = cssOrHexToColour(getAccessibleColour(colour).backgroundColor);
const accessibleBackgroundColor = cssOrHexToColour(getAccessibleColour(colour).backgroundColor); if (accessibleBg === null) return undefined;
if (accessibleBackgroundColor !== null) { return colourToHex({ ...accessibleBg, alpha: accessibleBg.alpha * 0.25 });
rowBgColour = colourToHex({ }, [colour]);
...accessibleBackgroundColor,
alpha: accessibleBackgroundColor.alpha * 0.25,
});
}
}
return ( return (
<tr <tr
@@ -80,6 +80,7 @@ function ProjectInfo({ projectData, isMirrored }: ProjectInfoData) {
{projectData.custom.map((info, idx) => { {projectData.custom.map((info, idx) => {
const hasUrl = Boolean(info.url); const hasUrl = Boolean(info.url);
return ( 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'> <div key={`${info.title}-${idx}`} className='info__custom'>
{hasUrl && ( {hasUrl && (
<div className='info__image-container'> <div className='info__image-container'>
@@ -45,6 +45,9 @@ $studio-idle: $red-1300;
top: 0; top: 0;
top: 50%; top: 50%;
left: 50%; left: 50%;
margin-top: -0.5rem;
margin-left: -0.5rem;
} }
.tick--active { .tick--active {
+7 -4
View File
@@ -6,6 +6,7 @@ import { useStudioClockSocket } from '../../common/hooks/useSocket';
import { cx } from '../../common/utils/styleUtils'; import { cx } from '../../common/utils/styleUtils';
import { formatTime } from '../../common/utils/time'; import { formatTime } from '../../common/utils/time';
import SuperscriptTime from '../common/superscript-time/SuperscriptTime'; import SuperscriptTime from '../common/superscript-time/SuperscriptTime';
import { useStudioOptions } from './studio.options';
import { getLargeClockData } from './studioClock.utils'; import { getLargeClockData } from './studioClock.utils';
import './StudioClock.scss'; import './StudioClock.scss';
@@ -18,6 +19,7 @@ interface StudioClockProps {
} }
export default function StudioClock({ hideCards }: StudioClockProps) { export default function StudioClock({ hideCards }: StudioClockProps) {
const { timeformat } = useStudioOptions();
const isSmallScreen = useIsSmallScreen(); const isSmallScreen = useIsSmallScreen();
const clock = useAutoTickingClock(); const clock = useAutoTickingClock();
const { playback } = useStudioClockSocket(); 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 we are on mobile and have to show the cards
if (isSmallScreen && !hideCards) { 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 ( return (
<div className='studio__clock'> <div className='studio__clock'>
@@ -62,10 +64,11 @@ export default function StudioClock({ hideCards }: StudioClockProps) {
interface StudioClockMobileProps { interface StudioClockMobileProps {
clock: number; clock: number;
onAir: boolean; onAir: boolean;
timeformat: string | null;
} }
function StudioClockMobile({ clock, onAir }: StudioClockMobileProps) { function StudioClockMobile({ clock, onAir, timeformat }: StudioClockMobileProps) {
const displayClock = formatTime(clock); const displayClock = formatTime(clock, { override: timeformat });
return ( return (
<div className='studio__clock studio__clock--small'> <div className='studio__clock studio__clock--small'>
@@ -2,7 +2,11 @@ import { CustomFields, OntimeEvent } from 'ontime-types';
import { use, useMemo } from 'react'; import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router'; 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 { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types'; import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils'; import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils';
@@ -47,7 +51,7 @@ export const getStudioOptions = (timeFormat: string, customFields: CustomFields)
type StudioOptions = { type StudioOptions = {
mainSource: keyof OntimeEvent | null; mainSource: keyof OntimeEvent | null;
hideCards: boolean; hideCards: boolean;
}; } & TimeOptions;
/** /**
* Utility extract the view options from URL Params * Utility extract the view options from URL Params
@@ -60,6 +64,7 @@ function getOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URL
return { return {
mainSource: getValue('main') as keyof OntimeEvent | null, mainSource: getValue('main') as keyof OntimeEvent | null,
hideCards: isStringBoolean(getValue('hideCards')), 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 * 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 [display, meridian] = (() => {
const formatted = formatTime(clock); const formatted = formatTime(clock, { override: timeformat });
if (formatted.endsWith('AM')) { if (formatted.endsWith('AM')) {
return [formatted.slice(0, -2), 'AM']; return [formatted.slice(0, -2), 'AM'];
} }
@@ -37,7 +37,7 @@ export default function TimelinePageLoader() {
function TimelinePage({ events, customFields, projectData, settings }: TimelineData) { function TimelinePage({ events, customFields, projectData, settings }: TimelineData) {
const selectedEventId = useSelectedEventId(); const selectedEventId = useSelectedEventId();
const { mainSource } = useTimelineOptions(); const { mainSource, timeformat } = useTimelineOptions();
// holds copy of the rundown with only relevant events // holds copy of the rundown with only relevant events
const { scopedRundown, firstStart, totalDuration } = useScopedRundown(events, selectedEventId); const { scopedRundown, firstStart, totalDuration } = useScopedRundown(events, selectedEventId);
@@ -56,7 +56,7 @@ function TimelinePage({ events, customFields, projectData, settings }: TimelineD
<div className='project-header'> <div className='project-header'>
{projectData?.logo && <ViewLogo name={projectData.logo} className='logo' />} {projectData?.logo && <ViewLogo name={projectData.logo} className='logo' />}
<div className='title'>{projectData.title}</div> <div className='title'>{projectData.title}</div>
<TimelineClock /> <TimelineClock timeformat={timeformat} />
</div> </div>
<TimelineSections now={now} next={next} followedBy={followedBy} mainSource={mainSource} /> <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 { getLocalizedString } = useTranslation();
const clock = useAutoTickingClock(); const clock = useAutoTickingClock();
// gather timer data // gather timer data
const formattedClock = formatTime(clock); const formattedClock = formatTime(clock, { override: timeformat });
return ( return (
<div className='clock-container'> <div className='clock-container'>
@@ -2,7 +2,11 @@ import { CustomFields, OntimeEvent } from 'ontime-types';
import { use, useMemo } from 'react'; import { use, useMemo } from 'react';
import { useSearchParams } from 'react-router'; 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 { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types'; import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils'; import { makeOptionsFromCustomFields } from '../../common/components/view-params-editor/viewParams.utils';
@@ -55,7 +59,7 @@ type TimelineOptions = {
mainSource: keyof OntimeEvent | null; mainSource: keyof OntimeEvent | null;
hidePast: boolean; hidePast: boolean;
fixedSize: boolean; fixedSize: boolean;
}; } & TimeOptions;
/** /**
* Utility extract the view options from URL Params * 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, mainSource: getValue('main') as keyof OntimeEvent | null,
hidePast: isStringBoolean(getValue('hidePast')), hidePast: isStringBoolean(getValue('hidePast')),
fixedSize: isStringBoolean(getValue('fixedSize')), 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 { useMemo } from 'react';
import { FitText } from '../../common/components/fit-text/FitText'; import { FitText } from '../../common/components/fit-text/FitText';
@@ -69,6 +69,7 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
font, font,
keyColour, keyColour,
timerColour, timerColour,
timeformat,
} = useTimerOptions(); } = useTimerOptions();
const { getLocalizedString } = useTranslation(); const { getLocalizedString } = useTranslation();
@@ -106,6 +107,7 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
const display = getFormattedTimer(stageTimer, viewTimerType, localisedMinutes, { const display = getFormattedTimer(stageTimer, viewTimerType, localisedMinutes, {
removeSeconds: hideTimerSeconds, removeSeconds: hideTimerSeconds,
removeLeadingZero: removeLeadingZeros, removeLeadingZero: removeLeadingZeros,
clockFormat: timeformat,
}); });
const currentAux = (() => { const currentAux = (() => {
@@ -164,7 +166,7 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
</div> </div>
)} )}
{showClock && <TimerAutoTickingClock />} {showClock && <TimerAutoTickingClock clockFormat={timeformat} />}
<div className={cx(['timer-container', message.timer.blink && !showOverlay && 'blink'])}> <div className={cx(['timer-container', message.timer.blink && !showOverlay && 'blink'])}>
{showEndMessage ? ( {showEndMessage ? (
@@ -212,9 +214,9 @@ function Timer({ customFields, projectData, isMirrored, settings, viewSettings,
); );
} }
function TimerAutoTickingClock() { function TimerAutoTickingClock({ clockFormat }: { clockFormat: MaybeString }) {
const autoTickingClock = useAutoTickingClock(); const autoTickingClock = useAutoTickingClock();
const formattedClock = formatTime(autoTickingClock); const formattedClock = formatTime(autoTickingClock, { override: clockFormat });
const { getLocalizedString } = useTranslation(); const { getLocalizedString } = useTranslation();
return ( return (
+4 -1
View File
@@ -6,8 +6,10 @@ import { useSearchParams } from 'react-router';
import type { SelectOption } from '../../common/components/select/Select'; import type { SelectOption } from '../../common/components/select/Select';
import { import {
getTimeOption, getTimeOption,
getTimeOptionsFromParams,
hideTimerSeconds, hideTimerSeconds,
showLeadingZeros, showLeadingZeros,
TimeOptions,
} from '../../common/components/view-params-editor/common.options'; } from '../../common/components/view-params-editor/common.options';
import { OptionTitle } from '../../common/components/view-params-editor/constants'; import { OptionTitle } from '../../common/components/view-params-editor/constants';
import { ViewOption } from '../../common/components/view-params-editor/viewParams.types'; import { ViewOption } from '../../common/components/view-params-editor/viewParams.types';
@@ -194,7 +196,7 @@ type TimerOptions = {
font?: string; font?: string;
keyColour?: string; keyColour?: string;
timerColour?: string; timerColour?: string;
}; } & TimeOptions;
/** /**
* Utility extract the view options from URL Params * Utility extract the view options from URL Params
@@ -229,6 +231,7 @@ function getOptionsFromParams(searchParams: URLSearchParams, defaultValues?: URL
font: getValue('font') ?? undefined, font: getValue('font') ?? undefined,
keyColour: makeColourString(getValue('keyColour')), keyColour: makeColourString(getValue('keyColour')),
timerColour: makeColourString(getValue('timerColour')), timerColour: makeColourString(getValue('timerColour')),
timeformat: getTimeOptionsFromParams(searchParams, defaultValues),
}; };
} }
+5 -1
View File
@@ -1,6 +1,7 @@
import path from 'path'; import path from 'path';
import { sentryVitePlugin } from '@sentry/vite-plugin'; import { sentryVitePlugin } from '@sentry/vite-plugin';
import legacy from '@vitejs/plugin-legacy';
import react from '@vitejs/plugin-react'; import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
import { compression } from 'vite-plugin-compression2'; import { compression } from 'vite-plugin-compression2';
@@ -21,6 +22,9 @@ export default defineConfig({
'import.meta.env.IS_DOCKER': process.env.NODE_ENV === 'docker', 'import.meta.env.IS_DOCKER': process.env.NODE_ENV === 'docker',
}, },
plugins: [ plugins: [
legacy({
targets: ['safari >= 14.1'],
}),
react({ react({
babel: { babel: {
plugins: [['babel-plugin-react-compiler', ReactCompilerConfig]], plugins: [['babel-plugin-react-compiler', ReactCompilerConfig]],
@@ -83,7 +87,7 @@ export default defineConfig({
}, },
test: { test: {
globals: true, globals: true,
environment: 'jsdom', dom: true,
}, },
build: { build: {
outDir: './build', outDir: './build',
+4 -5
View File
@@ -1,6 +1,6 @@
{ {
"name": "ontime-electron", "name": "ontime-electron",
"version": "4.7.0", "version": "4.8.0",
"author": "Carlos Valente", "author": "Carlos Valente",
"description": "Time keeping for live events", "description": "Time keeping for live events",
"repository": "https://github.com/cpvalente/ontime", "repository": "https://github.com/cpvalente/ontime",
@@ -14,7 +14,7 @@
"main": "src/main.js", "main": "src/main.js",
"devDependencies": { "devDependencies": {
"electron": "38.2.1", "electron": "38.2.1",
"electron-builder": "26.0.18", "electron-builder": "26.9.1",
"wait-on": "^7.2.0" "wait-on": "^7.2.0"
}, },
"scripts": { "scripts": {
@@ -29,8 +29,7 @@
"appId": "no.lightdev.ontime", "appId": "no.lightdev.ontime",
"asar": true, "asar": true,
"dmg": { "dmg": {
"artifactName": "ontime-macOS-${arch}.dmg", "artifactName": "ontime-macOS-${arch}.dmg"
"icon": "icon.icns"
}, },
"mac": { "mac": {
"notarize": true, "notarize": true,
@@ -46,7 +45,7 @@
] ]
}, },
"category": "public.app-category.productivity", "category": "public.app-category.productivity",
"icon": "icon.icns" "icon": "ontime.icon"
}, },
"win": { "win": {
"target": "nsis" "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 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@getontime/resolver", "name": "@getontime/resolver",
"version": "4.7.0", "version": "4.8.0",
"type": "module", "type": "module",
"repository": "https://github.com/cpvalente/ontime", "repository": "https://github.com/cpvalente/ontime",
"types": "./dist/main.d.ts", "types": "./dist/main.d.ts",
+1 -3
View File
@@ -2,7 +2,7 @@
"name": "ontime-server", "name": "ontime-server",
"type": "module", "type": "module",
"main": "src/index.ts", "main": "src/index.ts",
"version": "4.7.0", "version": "4.8.0",
"exports": "./src/index.js", "exports": "./src/index.js",
"dependencies": { "dependencies": {
"@googleapis/sheets": "^5.0.5", "@googleapis/sheets": "^5.0.5",
@@ -29,12 +29,10 @@
"@types/express": "5.0.3", "@types/express": "5.0.3",
"@types/multer": "2.1.0", "@types/multer": "2.1.0",
"@types/node": "catalog:", "@types/node": "catalog:",
"@types/websocket": "^1.0.5",
"@types/ws": "^8.5.10", "@types/ws": "^8.5.10",
"esbuild": "^0.24.0", "esbuild": "^0.24.0",
"ontime-types": "workspace:*", "ontime-types": "workspace:*",
"server-timing": "^3.3.3", "server-timing": "^3.3.3",
"shx": "^0.3.4",
"ts-essentials": "catalog:", "ts-essentials": "catalog:",
"tsx": "^4.19.2", "tsx": "^4.19.2",
"typescript": "catalog:", "typescript": "catalog:",
+2 -2
View File
@@ -262,6 +262,6 @@ export const socket = new SocketServer();
/** /**
* Utility function to notify clients that the REST data is stale * Utility function to notify clients that the REST data is stale
*/ */
export function sendRefetch(target: RefetchKey, revision: MaybeNumber = null) { export function sendRefetch(target: RefetchKey, revision: MaybeNumber = null, rundownId?: string) {
socket.sendAsJson(MessageTag.Refetch, { target, revision }); socket.sendAsJson(MessageTag.Refetch, { target, revision, rundownId });
} }
@@ -1,5 +1,5 @@
import express from 'express'; 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 { type ErrorResponse, RefetchKey } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils'; import { getErrorMessage } from 'ontime-utils';
@@ -8,7 +8,7 @@ import { defaultCss } from '../../bundle/bundledCss.js';
import { readCssFile, writeCssFile, writeUserTranslation } from './assets.service.js'; import { readCssFile, writeCssFile, writeUserTranslation } from './assets.service.js';
import { validatePostCss, validatePostTranslation } from './assets.validation.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>) => { router.get('/css', async (_req: Request, res: Response<string | ErrorResponse>) => {
try { try {
@@ -24,7 +24,6 @@ router.post('/css', validatePostCss, async (req: Request, res: Response<never |
const { css } = req.body; const { css } = req.body;
try { try {
await writeCssFile(css); await writeCssFile(css);
sendRefetch(RefetchKey.CssOverride);
res.status(204).send(); res.status(204).send();
} catch (error) { } catch (error) {
const message = getErrorMessage(error); const message = getErrorMessage(error);
@@ -53,7 +52,6 @@ router.post('/translations', validatePostTranslation, async (req: Request, res:
try { try {
await writeUserTranslation(translation); await writeUserTranslation(translation);
sendRefetch(RefetchKey.Translation);
res.status(204).send(); res.status(204).send();
} catch (error) { } catch (error) {
const message = getErrorMessage(error); const message = getErrorMessage(error);
@@ -1,8 +1,9 @@
import { existsSync } from 'node:fs'; import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises'; 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 { defaultCss } from '../../bundle/bundledCss.js';
import { publicFiles } from '../../setup/index.js'; import { publicFiles } from '../../setup/index.js';
@@ -33,6 +34,9 @@ export async function writeCssFile(css: string) {
} }
await writeFile(path, css, { encoding: 'utf8' }); 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 path = publicFiles.translationsFile;
const translationsString = JSON.stringify(translations, null, 2); const translationsString = JSON.stringify(translations, null, 2);
await writeFile(path, translationsString, { encoding: 'utf8' }); 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 { paramsWithId } from '../validation-utils/validationFunction.js';
import { import {
@@ -21,7 +21,7 @@ import {
validateTriggerPatch, validateTriggerPatch,
} from './automation.validation.js'; } from './automation.validation.js';
export const router = express.Router(); export const router: Router = express.Router();
router.get('/', getAutomationSettings); router.get('/', getAutomationSettings);
router.post('/', validateAutomationSettings, postAutomationSettings); router.post('/', validateAutomationSettings, postAutomationSettings);
@@ -47,7 +47,15 @@ export function triggerAutomations(cycle: TimerLifeCycle) {
return; return;
} }
filteredTrigger.forEach((trigger) => { // deduplicate — if the same automation appears multiple times on one lifecycle, fire it once
const seen = new Set<string>();
const uniqueTriggers = filteredTrigger.filter((t) => {
if (seen.has(t.automationId)) return false;
seen.add(t.automationId);
return true;
});
uniqueTriggers.forEach((trigger) => {
const automation = automations[trigger.automationId]; const automation = automations[trigger.automationId];
if (!automation || automation.outputs.length === 0) { if (!automation || automation.outputs.length === 0) {
return; return;
@@ -1,5 +1,5 @@
import express from 'express'; 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 { CustomField, CustomFields, ErrorResponse } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils'; 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 { createCustomField, deleteCustomField, editCustomField } from '../rundown/rundown.service.js';
import { validateCustomField, validateDeleteCustomField, validateEditCustomField } from './customFields.validation.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 * 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(); const customFields = getProjectCustomFields();
res.status(200).json(customFields); res.status(200).json(customFields);
}); });

Some files were not shown because too many files have changed in this diff Show More