Add unified data sources and stage debug
This commit is contained in:
1 parent
3fae670e6b
commit
5b300dee0d
18 files changed
+940
-72
No files matched your search
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "@dev-screen-starter/data",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc --noEmit",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.1.16",
|
||||
"typescript": "^5.9.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './usePollingData'
|
||||
export * from './useScreenDataSources'
|
||||
export * from './request'
|
||||
export * from './sources'
|
||||
export * from './types'
|
||||
@@ -0,0 +1,9 @@
|
||||
export async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(url, init)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Request failed: ${response.status}`)
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type {
|
||||
DataSource,
|
||||
HttpDataSource,
|
||||
MockDataSource,
|
||||
MqttDataSource,
|
||||
SignalRDataSource,
|
||||
WebSocketDataSource
|
||||
} from './types'
|
||||
|
||||
export function mockSource<Result>(source: Omit<MockDataSource<Result>, 'type'>): MockDataSource<Result> {
|
||||
return { type: 'mock', ...source }
|
||||
}
|
||||
|
||||
export function httpSource<Result, Raw = Result>(source: Omit<HttpDataSource<Result, Raw>, 'type'>): HttpDataSource<Result, Raw> {
|
||||
return { type: 'http', ...source }
|
||||
}
|
||||
|
||||
export function websocketSource<Result, Raw = Result>(
|
||||
source: Omit<WebSocketDataSource<Result, Raw>, 'type'>
|
||||
): WebSocketDataSource<Result, Raw> {
|
||||
return { type: 'websocket', ...source }
|
||||
}
|
||||
|
||||
export function signalrSource<Result, Raw = Result>(
|
||||
source: Omit<SignalRDataSource<Result, Raw>, 'type'>
|
||||
): SignalRDataSource<Result, Raw> {
|
||||
return { type: 'signalr', ...source }
|
||||
}
|
||||
|
||||
export function mqttSource<Result, Raw = Result>(source: Omit<MqttDataSource<Result, Raw>, 'type'>): MqttDataSource<Result, Raw> {
|
||||
return { type: 'mqtt', ...source }
|
||||
}
|
||||
|
||||
export function defineDataSources<TSources extends Record<string, DataSource<any, any>>>(sources: TSources): TSources {
|
||||
return sources
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
export type DataSourceType = 'mock' | 'http' | 'websocket' | 'signalr' | 'mqtt'
|
||||
|
||||
export type DataConnectionStatus = 'idle' | 'connecting' | 'open' | 'closed' | 'error'
|
||||
|
||||
export type RealtimeUpdateMode = 'replace' | 'append'
|
||||
|
||||
export type DataState<T> = {
|
||||
data: T | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
status: DataConnectionStatus
|
||||
lastUpdated?: number
|
||||
sourceType?: DataSourceType
|
||||
}
|
||||
|
||||
export type DataTransform<Raw, Result> = (raw: Raw, previous: Result | null) => Result
|
||||
|
||||
type BaseDataSource<Result, Raw = unknown> = {
|
||||
enabled?: boolean
|
||||
transform?: DataTransform<Raw, Result>
|
||||
}
|
||||
|
||||
export type MockDataSource<Result> = BaseDataSource<Result, Result> & {
|
||||
type: 'mock'
|
||||
data: Result | (() => Result)
|
||||
intervalMs?: number
|
||||
}
|
||||
|
||||
export type HttpDataSource<Result, Raw = unknown> = BaseDataSource<Result, Raw> & {
|
||||
type: 'http'
|
||||
url: string
|
||||
init?: RequestInit
|
||||
intervalMs?: number
|
||||
immediate?: boolean
|
||||
}
|
||||
|
||||
export type WebSocketDataSource<Result, Raw = unknown> = BaseDataSource<Result, Raw> & {
|
||||
type: 'websocket'
|
||||
url: string
|
||||
protocols?: string | string[]
|
||||
mode?: RealtimeUpdateMode
|
||||
maxItems?: number
|
||||
}
|
||||
|
||||
export type SignalRDataSource<Result, Raw = unknown> = BaseDataSource<Result, Raw> & {
|
||||
type: 'signalr'
|
||||
url: string
|
||||
method: string
|
||||
mode?: RealtimeUpdateMode
|
||||
maxItems?: number
|
||||
}
|
||||
|
||||
export type MqttDataSource<Result, Raw = unknown> = BaseDataSource<Result, Raw> & {
|
||||
type: 'mqtt'
|
||||
url: string
|
||||
topic: string
|
||||
mode?: RealtimeUpdateMode
|
||||
maxItems?: number
|
||||
}
|
||||
|
||||
export type DataSource<Result = unknown, Raw = unknown> =
|
||||
| MockDataSource<Result>
|
||||
| HttpDataSource<Result, Raw>
|
||||
| WebSocketDataSource<Result, Raw>
|
||||
| SignalRDataSource<Result, Raw>
|
||||
| MqttDataSource<Result, Raw>
|
||||
|
||||
export type DataSourceMap = Record<string, DataSource<any, any>>
|
||||
|
||||
export type InferDataSourceResult<TSource> = TSource extends DataSource<infer Result, any> ? Result : never
|
||||
|
||||
export type DataStates<TSources extends DataSourceMap> = {
|
||||
[Key in keyof TSources]: DataState<InferDataSourceResult<TSources[Key]>>
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
type PollingState<T> = {
|
||||
data?: T
|
||||
loading: boolean
|
||||
error?: string
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
export function usePollingData<T>(loader: () => Promise<T>, intervalMs = 30000): PollingState<T> {
|
||||
const [state, setState] = useState<PollingState<T>>({ loading: true })
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
|
||||
const run = async () => {
|
||||
try {
|
||||
const data = await loader()
|
||||
if (active) {
|
||||
setState({ data, loading: false, updatedAt: new Date().toISOString() })
|
||||
}
|
||||
} catch (error) {
|
||||
if (active) {
|
||||
setState((current) => ({
|
||||
...current,
|
||||
loading: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void run()
|
||||
const timer = window.setInterval(run, intervalMs)
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
window.clearInterval(timer)
|
||||
}
|
||||
}, [intervalMs, loader])
|
||||
|
||||
return state
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { requestJson } from './request'
|
||||
import type { DataSource, DataSourceMap, DataState, DataStates, RealtimeUpdateMode } from './types'
|
||||
|
||||
function createInitialState(source: DataSource<unknown, unknown>): DataState<unknown> {
|
||||
return {
|
||||
data: null,
|
||||
loading: source.enabled === false ? false : true,
|
||||
error: null,
|
||||
status: source.enabled === false ? 'idle' : 'connecting',
|
||||
sourceType: source.type
|
||||
}
|
||||
}
|
||||
|
||||
function readMockValue<T>(value: T | (() => T)): T {
|
||||
return typeof value === 'function' ? (value as () => T)() : value
|
||||
}
|
||||
|
||||
function parsePayload(payload: unknown): unknown {
|
||||
if (typeof payload !== 'string') {
|
||||
return payload
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(payload) as unknown
|
||||
} catch {
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
function applyTransform(
|
||||
source: DataSource<unknown, unknown>,
|
||||
raw: unknown,
|
||||
previous: unknown
|
||||
): unknown {
|
||||
return source.transform ? source.transform(raw, previous) : raw
|
||||
}
|
||||
|
||||
function mergeRealtimeData(
|
||||
current: unknown,
|
||||
next: unknown,
|
||||
mode: RealtimeUpdateMode = 'replace',
|
||||
maxItems = 100
|
||||
): unknown {
|
||||
if (mode !== 'append') {
|
||||
return next
|
||||
}
|
||||
|
||||
const currentItems = Array.isArray(current) ? current : []
|
||||
const nextItems = Array.isArray(next) ? next : [next]
|
||||
|
||||
return [...nextItems, ...currentItems].slice(0, maxItems)
|
||||
}
|
||||
|
||||
function toErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
||||
export function useScreenDataSources<TSources extends DataSourceMap>(sources: TSources): DataStates<TSources> {
|
||||
const sourceEntries = useMemo(() => Object.entries(sources), [sources])
|
||||
|
||||
const [states, setStates] = useState<Record<string, DataState<unknown>>>(() =>
|
||||
Object.fromEntries(sourceEntries.map(([key, source]) => [key, createInitialState(source)]))
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
setStates(Object.fromEntries(sourceEntries.map(([key, source]) => [key, createInitialState(source)])))
|
||||
|
||||
const cleanups: Array<() => void> = []
|
||||
|
||||
for (const [key, source] of sourceEntries) {
|
||||
if (source.enabled === false) {
|
||||
continue
|
||||
}
|
||||
|
||||
const updateState = (patch: Partial<DataState<unknown>>) => {
|
||||
setStates((current) => ({
|
||||
...current,
|
||||
[key]: {
|
||||
...current[key],
|
||||
...patch,
|
||||
sourceType: source.type
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
const commitData = (raw: unknown, mode?: RealtimeUpdateMode, maxItems?: number) => {
|
||||
setStates((current) => {
|
||||
const previous = current[key]?.data ?? null
|
||||
const transformed = applyTransform(source, raw, previous)
|
||||
const data = source.type === 'websocket' || source.type === 'signalr' || source.type === 'mqtt'
|
||||
? mergeRealtimeData(previous, transformed, mode, maxItems)
|
||||
: transformed
|
||||
|
||||
return {
|
||||
...current,
|
||||
[key]: {
|
||||
data,
|
||||
loading: false,
|
||||
error: null,
|
||||
status: 'open',
|
||||
lastUpdated: Date.now(),
|
||||
sourceType: source.type
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (source.type === 'mock') {
|
||||
const run = () => commitData(readMockValue(source.data))
|
||||
run()
|
||||
|
||||
if (source.intervalMs) {
|
||||
const timer = window.setInterval(run, source.intervalMs)
|
||||
cleanups.push(() => window.clearInterval(timer))
|
||||
}
|
||||
}
|
||||
|
||||
if (source.type === 'http') {
|
||||
let active = true
|
||||
let abortController: AbortController | null = null
|
||||
|
||||
const run = async () => {
|
||||
abortController?.abort()
|
||||
abortController = new AbortController()
|
||||
updateState({ loading: true, error: null, status: 'connecting' })
|
||||
|
||||
try {
|
||||
const raw = await requestJson<unknown>(source.url, {
|
||||
...source.init,
|
||||
signal: abortController.signal
|
||||
})
|
||||
|
||||
if (active) {
|
||||
commitData(raw)
|
||||
}
|
||||
} catch (error) {
|
||||
if (active && !(error instanceof DOMException && error.name === 'AbortError')) {
|
||||
updateState({ loading: false, error: toErrorMessage(error), status: 'error' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (source.immediate !== false) {
|
||||
void run()
|
||||
}
|
||||
|
||||
if (source.intervalMs) {
|
||||
const timer = window.setInterval(run, source.intervalMs)
|
||||
cleanups.push(() => window.clearInterval(timer))
|
||||
}
|
||||
|
||||
cleanups.push(() => {
|
||||
active = false
|
||||
abortController?.abort()
|
||||
})
|
||||
}
|
||||
|
||||
if (source.type === 'websocket') {
|
||||
if (typeof WebSocket === 'undefined') {
|
||||
updateState({ loading: false, error: 'WebSocket is not available in this runtime.', status: 'error' })
|
||||
continue
|
||||
}
|
||||
|
||||
updateState({ status: 'connecting', error: null })
|
||||
const socket = new WebSocket(source.url, source.protocols)
|
||||
|
||||
socket.addEventListener('open', () => updateState({ loading: false, status: 'open', error: null }))
|
||||
socket.addEventListener('message', (event) => {
|
||||
commitData(parsePayload(event.data), source.mode, source.maxItems)
|
||||
})
|
||||
socket.addEventListener('close', () => updateState({ loading: false, status: 'closed' }))
|
||||
socket.addEventListener('error', () => updateState({ loading: false, status: 'error', error: 'WebSocket connection error.' }))
|
||||
|
||||
cleanups.push(() => socket.close())
|
||||
}
|
||||
|
||||
if (source.type === 'signalr' || source.type === 'mqtt') {
|
||||
updateState({
|
||||
loading: false,
|
||||
status: 'idle',
|
||||
error: `${source.type} adapter is declared but not installed yet.`
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
cleanups.forEach((cleanup) => cleanup())
|
||||
}
|
||||
}, [sourceEntries])
|
||||
|
||||
return states as DataStates<TSources>
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -1,16 +1,31 @@
|
||||
import { type CSSProperties, type ReactNode, useEffect, useMemo, useState } from 'react'
|
||||
import { calculateStageScale, type ScaleMode } from './scale'
|
||||
import { calculateStageScale, type ScaleMode, type StageMetrics } from './scale'
|
||||
|
||||
type ScreenStageProps = {
|
||||
width?: number
|
||||
height?: number
|
||||
scaleMode?: ScaleMode
|
||||
background?: string
|
||||
className?: string
|
||||
debug?: boolean
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function ScreenStage({ width = 1920, height = 1080, scaleMode = 'fit', background = '#061826', children }: ScreenStageProps) {
|
||||
const [viewport, setViewport] = useState({ width: window.innerWidth, height: window.innerHeight })
|
||||
const defaultViewport = () => ({
|
||||
width: typeof window === 'undefined' ? 1920 : window.innerWidth,
|
||||
height: typeof window === 'undefined' ? 1080 : window.innerHeight
|
||||
})
|
||||
|
||||
export function ScreenStage({
|
||||
width = 1920,
|
||||
height = 1080,
|
||||
scaleMode = 'fit',
|
||||
background = '#061826',
|
||||
className = '',
|
||||
debug = false,
|
||||
children
|
||||
}: ScreenStageProps) {
|
||||
const [viewport, setViewport] = useState(defaultViewport)
|
||||
|
||||
useEffect(() => {
|
||||
const onResize = () => setViewport({ width: window.innerWidth, height: window.innerHeight })
|
||||
@@ -20,6 +35,19 @@ export function ScreenStage({ width = 1920, height = 1080, scaleMode = 'fit', ba
|
||||
|
||||
const scale = useMemo(() => calculateStageScale({ width, height, scaleMode }, viewport.width, viewport.height), [height, scaleMode, viewport.height, viewport.width, width])
|
||||
|
||||
const metrics: StageMetrics = useMemo(
|
||||
() => ({
|
||||
designWidth: width,
|
||||
designHeight: height,
|
||||
viewportWidth: viewport.width,
|
||||
viewportHeight: viewport.height,
|
||||
scaleMode,
|
||||
scaleX: scale.scaleX,
|
||||
scaleY: scale.scaleY
|
||||
}),
|
||||
[height, scale.scaleX, scale.scaleY, scaleMode, viewport.height, viewport.width, width]
|
||||
)
|
||||
|
||||
const stageStyle: CSSProperties = {
|
||||
width,
|
||||
height,
|
||||
@@ -29,9 +57,21 @@ export function ScreenStage({ width = 1920, height = 1080, scaleMode = 'fit', ba
|
||||
|
||||
return (
|
||||
<main className="screen-viewport">
|
||||
<section className="screen-stage" style={stageStyle}>
|
||||
<section className={`screen-stage ${className}`} style={stageStyle}>
|
||||
{children}
|
||||
</section>
|
||||
{debug ? <StageDebug metrics={metrics} /> : null}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
function StageDebug({ metrics }: { metrics: StageMetrics }) {
|
||||
return (
|
||||
<aside className="screen-stage-debug">
|
||||
<span>design {metrics.designWidth}x{metrics.designHeight}</span>
|
||||
<span>viewport {metrics.viewportWidth}x{metrics.viewportHeight}</span>
|
||||
<span>mode {metrics.scaleMode}</span>
|
||||
<span>scale {metrics.scaleX.toFixed(3)} / {metrics.scaleY.toFixed(3)}</span>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -11,6 +11,16 @@ export type StageScale = {
|
||||
scaleY: number
|
||||
}
|
||||
|
||||
export type StageMetrics = {
|
||||
designWidth: number
|
||||
designHeight: number
|
||||
viewportWidth: number
|
||||
viewportHeight: number
|
||||
scaleMode: ScaleMode
|
||||
scaleX: number
|
||||
scaleY: number
|
||||
}
|
||||
|
||||
export function calculateStageScale(screen: ScreenSize, viewportWidth: number, viewportHeight: number): StageScale {
|
||||
const scaleMode = screen.scaleMode ?? 'fit'
|
||||
|
||||
|
||||
Reference in new issue
Block a user