@glivion/square-screen-js-sdk 0.1.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +874 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +522 -0
- package/dist/index.d.mts +522 -0
- package/dist/index.mjs +870 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +8 -1
- package/.github/workflows/build-js-sdk.yml +0 -70
- package/eslint.config.js +0 -3
- package/examples/react-app/README.md +0 -73
- package/examples/react-app/eslint.config.js +0 -22
- package/examples/react-app/index.html +0 -13
- package/examples/react-app/package-lock.json +0 -2239
- package/examples/react-app/package.json +0 -31
- package/examples/react-app/public/favicon.svg +0 -1
- package/examples/react-app/public/icons.svg +0 -24
- package/examples/react-app/src/App.css +0 -184
- package/examples/react-app/src/App.tsx +0 -157
- package/examples/react-app/src/EmergencyTicker.tsx +0 -25
- package/examples/react-app/src/HeadlessExample.tsx +0 -66
- package/examples/react-app/src/RendererExample.tsx +0 -70
- package/examples/react-app/src/assets/hero.png +0 -0
- package/examples/react-app/src/assets/react.svg +0 -1
- package/examples/react-app/src/assets/vite.svg +0 -1
- package/examples/react-app/src/index.css +0 -183
- package/examples/react-app/src/main.tsx +0 -10
- package/examples/react-app/src/mockNetworkDataSource.ts +0 -116
- package/examples/react-app/src/usePlayer.ts +0 -71
- package/examples/react-app/tsconfig.app.json +0 -25
- package/examples/react-app/tsconfig.json +0 -7
- package/examples/react-app/tsconfig.node.json +0 -24
- package/examples/react-app/vite.config.ts +0 -7
- package/examples/react-app/yarn.lock +0 -1089
- package/src/__tests__/cache/SquareScreenCache.test.ts +0 -375
- package/src/__tests__/network/NetworkClient.test.ts +0 -217
- package/src/__tests__/network/mappers.test.ts +0 -163
- package/src/__tests__/player/SquareScreenPlayer.test.ts +0 -840
- package/src/cache/SquareScreenCache.ts +0 -154
- package/src/constants.ts +0 -9
- package/src/core/types.ts +0 -251
- package/src/env.d.ts +0 -4
- package/src/index.ts +0 -34
- package/src/network/NetworkClient.ts +0 -234
- package/src/network/apiTypes.ts +0 -89
- package/src/network/mappers.ts +0 -106
- package/src/player/SquareScreenPlayer.ts +0 -414
- package/src/renderer/SquareScreenRenderer.ts +0 -282
- package/tsconfig.json +0 -12
- package/tsdown.config.ts +0 -23
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,874 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let idb = require("idb");
|
|
3
|
+
//#region src/constants.ts
|
|
4
|
+
/**
|
|
5
|
+
* Production root URL for the SquareScreen REST API.
|
|
6
|
+
*
|
|
7
|
+
* {@link SquareScreenPlayer} uses this for all network requests. Integrators cannot
|
|
8
|
+
* override it via player configuration; supply a custom {@link NetworkDataSource}
|
|
9
|
+
* only if you must talk to a different host (e.g. tests or a private gateway).
|
|
10
|
+
*/
|
|
11
|
+
const SQUARESCREEN_API_BASE_URL = "https://square-screen-api-development-f7zuxa.laravel.cloud/api/v1";
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/network/mappers.ts
|
|
14
|
+
/** Maps a raw playlist item to the core PlaylistItem type. */
|
|
15
|
+
function mapPlaylistItem(raw) {
|
|
16
|
+
return {
|
|
17
|
+
uuid: raw.uuid,
|
|
18
|
+
name: raw.name,
|
|
19
|
+
type: raw.type,
|
|
20
|
+
url: raw.url,
|
|
21
|
+
duration: raw.duration_seconds,
|
|
22
|
+
...raw.transition !== void 0 && { transition: raw.transition },
|
|
23
|
+
...raw.width !== void 0 && { width: raw.width },
|
|
24
|
+
...raw.height !== void 0 && { height: raw.height },
|
|
25
|
+
...raw.title !== void 0 && { title: raw.title },
|
|
26
|
+
...raw.thumbnail !== void 0 && { thumbnail: raw.thumbnail }
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Maps the raw strategy field to a PlaybackStrategy.
|
|
31
|
+
* Returns undefined when the API sends an empty array instead of a real object.
|
|
32
|
+
*/
|
|
33
|
+
function mapPlaybackStrategy(raw) {
|
|
34
|
+
if (Array.isArray(raw)) return void 0;
|
|
35
|
+
return {
|
|
36
|
+
loop: raw.loop,
|
|
37
|
+
shuffle: raw.shuffle,
|
|
38
|
+
preloadCount: raw.preload_count ?? 0
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** Maps a raw playlist response to the core Playlist type. */
|
|
42
|
+
function mapPlaylistResponse(raw) {
|
|
43
|
+
return {
|
|
44
|
+
uuid: raw.playlist.uuid,
|
|
45
|
+
items: raw.items.map(mapPlaylistItem),
|
|
46
|
+
strategy: mapPlaybackStrategy(raw.strategy),
|
|
47
|
+
schedule: raw.schedule,
|
|
48
|
+
playlistMeta: raw.playlist,
|
|
49
|
+
cachedAt: Date.now()
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Maps a raw emergency response to an EmergencyAlert.
|
|
54
|
+
* Returns null when no emergency is active.
|
|
55
|
+
*/
|
|
56
|
+
function mapEmergencyResponse(raw) {
|
|
57
|
+
if (raw.emergency === null) return null;
|
|
58
|
+
return {
|
|
59
|
+
id: raw.emergency.id,
|
|
60
|
+
uuid: raw.emergency.uuid,
|
|
61
|
+
companyId: raw.emergency.company_id,
|
|
62
|
+
title: raw.emergency.title,
|
|
63
|
+
message: raw.emergency.message,
|
|
64
|
+
backgroundColor: raw.emergency.background_color,
|
|
65
|
+
textColor: raw.emergency.text_color,
|
|
66
|
+
targetScope: raw.emergency.target_scope,
|
|
67
|
+
isActive: raw.emergency.is_active,
|
|
68
|
+
startedAt: raw.emergency.started_at,
|
|
69
|
+
...raw.emergency.ended_at !== void 0 && { endedAt: raw.emergency.ended_at }
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** Maps a raw heartbeat acknowledgement to the core HeartbeatAck type. */
|
|
73
|
+
function mapHeartbeatAck(raw) {
|
|
74
|
+
return { received: raw.received };
|
|
75
|
+
}
|
|
76
|
+
function mapHeartbeatPayload(raw) {
|
|
77
|
+
return {
|
|
78
|
+
cpu_usage: raw.cpuUsage,
|
|
79
|
+
memory_usage: raw.memoryUsage,
|
|
80
|
+
disk_usage: raw.diskUsage,
|
|
81
|
+
temperature: raw.temperature,
|
|
82
|
+
os_version: raw.osVersion,
|
|
83
|
+
app_version: raw.playerVersion
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
//#region src/network/NetworkClient.ts
|
|
88
|
+
/**
|
|
89
|
+
* Handles all HTTP communication with the SquareScreen API.
|
|
90
|
+
*
|
|
91
|
+
* Implements {@link NetworkDataSource} and is the only class in the SDK
|
|
92
|
+
* that calls `fetch` directly. Auth headers are injected automatically on
|
|
93
|
+
* every request — callers never set them manually.
|
|
94
|
+
*
|
|
95
|
+
* This class is internal to the SDK. Consumers interact with it only through
|
|
96
|
+
* the `NetworkDataSource` interface via the player module.
|
|
97
|
+
*/
|
|
98
|
+
var NetworkClient = class {
|
|
99
|
+
/**
|
|
100
|
+
* @param baseUrl - Root URL of the SquareScreen API, e.g. `"https://api.squarescreen.io/api/v1"`.
|
|
101
|
+
* @param deviceId - Unique identifier for this device.
|
|
102
|
+
* @param deviceToken - Secret token used to authenticate this device. Never log or expose this value.
|
|
103
|
+
*/
|
|
104
|
+
constructor(baseUrl, deviceId, deviceToken) {
|
|
105
|
+
this.baseUrl = baseUrl;
|
|
106
|
+
this.deviceId = deviceId;
|
|
107
|
+
this.deviceToken = deviceToken;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Central fetch wrapper used by all public methods.
|
|
111
|
+
*
|
|
112
|
+
* Injects auth headers, separates HTTP errors from network failures,
|
|
113
|
+
* and isolates JSON parse errors — so callers always receive a
|
|
114
|
+
* {@link SquareScreenResult} and never an uncaught exception.
|
|
115
|
+
*
|
|
116
|
+
* Error mapping:
|
|
117
|
+
* - 401/403 → `AuthError`
|
|
118
|
+
* - Other non-2xx → `NetworkError`
|
|
119
|
+
* - JSON parse failure → `ParseError`
|
|
120
|
+
* - `fetch` throw (no internet, CORS, timeout) → `NetworkError` with code `0`
|
|
121
|
+
*/
|
|
122
|
+
async fetchWrapper(endpoint, options) {
|
|
123
|
+
try {
|
|
124
|
+
const response = await fetch(`${this.baseUrl}${endpoint}`, {
|
|
125
|
+
...options,
|
|
126
|
+
headers: {
|
|
127
|
+
...options?.headers ?? {},
|
|
128
|
+
"Content-Type": "application/json",
|
|
129
|
+
"X-Device-Id": this.deviceId,
|
|
130
|
+
"X-Device-Token": this.deviceToken
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
if (!response.ok) {
|
|
134
|
+
if (response.status === 401) return {
|
|
135
|
+
success: false,
|
|
136
|
+
error: {
|
|
137
|
+
kind: "auth",
|
|
138
|
+
message: "Unauthorized"
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
if (response.status === 403) return {
|
|
142
|
+
success: false,
|
|
143
|
+
error: {
|
|
144
|
+
kind: "auth",
|
|
145
|
+
message: "Forbidden"
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
return {
|
|
149
|
+
success: false,
|
|
150
|
+
error: {
|
|
151
|
+
kind: "network",
|
|
152
|
+
code: response.status,
|
|
153
|
+
message: response.statusText || `HTTP error ${response.status}`
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
return {
|
|
159
|
+
success: true,
|
|
160
|
+
data: await response.json()
|
|
161
|
+
};
|
|
162
|
+
} catch {
|
|
163
|
+
return {
|
|
164
|
+
success: false,
|
|
165
|
+
error: {
|
|
166
|
+
kind: "parse",
|
|
167
|
+
message: "Response could not be parsed as JSON"
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
} catch (err) {
|
|
172
|
+
return {
|
|
173
|
+
success: false,
|
|
174
|
+
error: {
|
|
175
|
+
kind: "network",
|
|
176
|
+
code: 0,
|
|
177
|
+
message: err instanceof Error ? err.message : "Network request failed"
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/** Fetches the full active playlist for this device. */
|
|
183
|
+
async fetchPlaylist() {
|
|
184
|
+
const result = await this.fetchWrapper("/screen/now-playing", { method: "GET" });
|
|
185
|
+
if (!result.success) return result;
|
|
186
|
+
return {
|
|
187
|
+
success: true,
|
|
188
|
+
data: mapPlaylistResponse(result.data)
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/** Fetches a playlist filtered to video items only. */
|
|
192
|
+
async fetchVideoPlaylist(params) {
|
|
193
|
+
const query = new URLSearchParams({
|
|
194
|
+
type: "video",
|
|
195
|
+
...params.category && { category: params.category },
|
|
196
|
+
...params.quality && { quality: params.quality },
|
|
197
|
+
...params.limit && { limit: String(params.limit) },
|
|
198
|
+
...params.tags && { tags: params.tags.join(",") }
|
|
199
|
+
});
|
|
200
|
+
const result = await this.fetchWrapper(`/screen/now-playing?${query}`, { method: "GET" });
|
|
201
|
+
if (!result.success) return result;
|
|
202
|
+
return {
|
|
203
|
+
success: true,
|
|
204
|
+
data: mapPlaylistResponse(result.data)
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
/** Fetches a playlist filtered to image items only. */
|
|
208
|
+
async fetchImagePlaylist(params) {
|
|
209
|
+
const query = new URLSearchParams({
|
|
210
|
+
type: "image",
|
|
211
|
+
...params.category && { category: params.category },
|
|
212
|
+
...params.limit && { limit: String(params.limit) },
|
|
213
|
+
...params.tags && { tags: params.tags.join(",") }
|
|
214
|
+
});
|
|
215
|
+
const result = await this.fetchWrapper(`/screen/now-playing?${query}`, { method: "GET" });
|
|
216
|
+
if (!result.success) return result;
|
|
217
|
+
return {
|
|
218
|
+
success: true,
|
|
219
|
+
data: mapPlaylistResponse(result.data)
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Checks whether an emergency broadcast is currently active for this device.
|
|
224
|
+
* Resolves to `null` when no emergency is active.
|
|
225
|
+
*/
|
|
226
|
+
async checkForEmergencyAlert() {
|
|
227
|
+
const result = await this.fetchWrapper("/screen/emergency", { method: "GET" });
|
|
228
|
+
if (!result.success) return result;
|
|
229
|
+
return {
|
|
230
|
+
success: true,
|
|
231
|
+
data: mapEmergencyResponse(result.data)
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Posts device health metrics to the server.
|
|
236
|
+
* The payload is mapped to snake_case before sending to match the API's expected format.
|
|
237
|
+
*
|
|
238
|
+
* @param payload - Collected device metrics. Hardware fields are optional;
|
|
239
|
+
* `playerVersion` is always required.
|
|
240
|
+
*/
|
|
241
|
+
async healthCheck(payload) {
|
|
242
|
+
const result = await this.fetchWrapper("/screen/heartbeat", {
|
|
243
|
+
method: "POST",
|
|
244
|
+
body: JSON.stringify(mapHeartbeatPayload(payload))
|
|
245
|
+
});
|
|
246
|
+
if (!result.success) return result;
|
|
247
|
+
return {
|
|
248
|
+
success: true,
|
|
249
|
+
data: mapHeartbeatAck(result.data)
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
/** Reports a playback event to the server.
|
|
253
|
+
* @param event - The playback event to report.
|
|
254
|
+
* @returns A result indicating whether the event was recorded successfully.
|
|
255
|
+
* @example
|
|
256
|
+
* const result = await networkClient.reportPlaybackEvent({
|
|
257
|
+
* media_uuid: "mf-00000001-0000-0000-0000-000000000001",
|
|
258
|
+
* playlist_uuid: "pl-00000001-0000-0000-0000-000000000001",
|
|
259
|
+
* schedule_uuid: "sc-00000001-0000-0000-0000-000000000001",
|
|
260
|
+
* started_at: "2026-04-28T07:05:00Z",
|
|
261
|
+
* ended_at: "2026-04-28T07:05:10Z",
|
|
262
|
+
* });
|
|
263
|
+
*/
|
|
264
|
+
async reportPlaybackEvent(event) {
|
|
265
|
+
const result = await this.fetchWrapper("/screen/playback", {
|
|
266
|
+
method: "POST",
|
|
267
|
+
body: JSON.stringify(event)
|
|
268
|
+
});
|
|
269
|
+
if (!result.success) return result;
|
|
270
|
+
return {
|
|
271
|
+
success: true,
|
|
272
|
+
data: { recorded: result.data.recorded }
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
//#endregion
|
|
277
|
+
//#region src/cache/SquareScreenCache.ts
|
|
278
|
+
const DEFAULT_DB_NAME = "square-screen-cache";
|
|
279
|
+
const DEFAULT_CACHE_NAME = "square-screen-cache";
|
|
280
|
+
/**
|
|
281
|
+
* Default {@link SquareScreenCacheProvider} backed by IndexedDB (playlist metadata)
|
|
282
|
+
* and the Cache API (media blobs).
|
|
283
|
+
*
|
|
284
|
+
* **IndexedDB** — a single `playlists` object store holds one document per
|
|
285
|
+
* playlist UUID. A private `_ttl` field (milliseconds) is stored alongside the
|
|
286
|
+
* record and stripped before returning data to callers.
|
|
287
|
+
*
|
|
288
|
+
* **Cache API** — media files are stored under their original URL as the cache
|
|
289
|
+
* key, matching the same URL-keyed approach used by the Android SDK's
|
|
290
|
+
* `MediaFileCache`. Once a blob is retrieved from the Cache API it is wrapped
|
|
291
|
+
* in a `URL.createObjectURL` handle that is kept in an in-memory map and reused
|
|
292
|
+
* on subsequent calls to avoid redundant allocations. All handles are revoked
|
|
293
|
+
* when {@link clear} is called.
|
|
294
|
+
*
|
|
295
|
+
* Integrators who need different storage behaviour (a service-worker cache,
|
|
296
|
+
* an in-memory store for tests, a custom database) should implement
|
|
297
|
+
* {@link SquareScreenCacheProvider} and pass it via
|
|
298
|
+
* `SquareScreenPlayerConfig.cacheProvider`.
|
|
299
|
+
*/
|
|
300
|
+
var SquareScreenCache = class {
|
|
301
|
+
/**
|
|
302
|
+
* @param dbName Name of the IndexedDB database. Override in tests to isolate state.
|
|
303
|
+
* @param cacheName Name of the Cache API bucket. Override in tests to isolate state.
|
|
304
|
+
*/
|
|
305
|
+
constructor({ dbName = DEFAULT_DB_NAME, cacheName = DEFAULT_CACHE_NAME } = {}) {
|
|
306
|
+
this.objectUrls = /* @__PURE__ */ new Map();
|
|
307
|
+
this.dbName = dbName;
|
|
308
|
+
this.cacheName = cacheName;
|
|
309
|
+
}
|
|
310
|
+
/** Opens (or lazily creates) the IndexedDB database with the `playlists` object store. */
|
|
311
|
+
openDB() {
|
|
312
|
+
return (0, idb.openDB)(this.dbName, 1, { upgrade(db) {
|
|
313
|
+
if (!db.objectStoreNames.contains("playlists")) db.createObjectStore("playlists", { keyPath: "uuid" });
|
|
314
|
+
} });
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Returns the cached playlist for the given UUID, or `null` if:
|
|
318
|
+
* - nothing has been stored for that UUID, or
|
|
319
|
+
* - the record's age exceeds its TTL and `allowStale` is `false`.
|
|
320
|
+
*
|
|
321
|
+
* @param uuid The playlist UUID to look up.
|
|
322
|
+
* @param allowStale When `true`, expired records are returned as-is (useful
|
|
323
|
+
* for serving a fallback when the network is unreachable).
|
|
324
|
+
*/
|
|
325
|
+
async getPlaylist(uuid, allowStale = false) {
|
|
326
|
+
const record = await (await this.openDB()).get("playlists", uuid);
|
|
327
|
+
if (!record) return null;
|
|
328
|
+
if (!allowStale && Date.now() - record.cachedAt > record._ttl) return null;
|
|
329
|
+
const { _ttl, ...playlist } = record;
|
|
330
|
+
return playlist;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Persists a playlist to IndexedDB, overwriting any previous record with the
|
|
334
|
+
* same UUID. `cachedAt` is set to the current wall-clock time so that TTL
|
|
335
|
+
* checks in {@link getPlaylist} have an accurate baseline.
|
|
336
|
+
*
|
|
337
|
+
* @param playlist The playlist to store. Items are persisted inline as part
|
|
338
|
+
* of the same document — no separate per-item records.
|
|
339
|
+
* @param ttlMs How long (in milliseconds) the record is considered fresh.
|
|
340
|
+
* Passed through `SquareScreenPlayerConfig.ttl` by the player.
|
|
341
|
+
*/
|
|
342
|
+
async savePlaylist(playlist, ttlMs) {
|
|
343
|
+
await (await this.openDB()).put("playlists", {
|
|
344
|
+
...playlist,
|
|
345
|
+
cachedAt: Date.now(),
|
|
346
|
+
_ttl: ttlMs
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Returns a blob URL for the locally cached copy of `url`, or `null` if the
|
|
351
|
+
* media has not been downloaded yet.
|
|
352
|
+
*
|
|
353
|
+
* The blob URL is created once and stored in an in-memory map. Subsequent
|
|
354
|
+
* calls for the same `url` return the same handle without re-reading the
|
|
355
|
+
* Cache API, which avoids both I/O and unnecessary `URL.createObjectURL`
|
|
356
|
+
* allocations on long-running signage devices.
|
|
357
|
+
*
|
|
358
|
+
* @param url The original remote URL used as the Cache API key.
|
|
359
|
+
*/
|
|
360
|
+
async getMediaUrl(url) {
|
|
361
|
+
const existing = this.objectUrls.get(url);
|
|
362
|
+
if (existing) return existing;
|
|
363
|
+
const response = await (await caches.open(this.cacheName)).match(url);
|
|
364
|
+
if (!response) return null;
|
|
365
|
+
const blob = await response.blob();
|
|
366
|
+
const objectUrl = URL.createObjectURL(blob);
|
|
367
|
+
this.objectUrls.set(url, objectUrl);
|
|
368
|
+
return objectUrl;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Stores `blob` in the Cache API under `url` and returns a blob URL for
|
|
372
|
+
* immediate use by the renderer.
|
|
373
|
+
*
|
|
374
|
+
* Called by the player after a successful `fetch()` so that subsequent
|
|
375
|
+
* {@link getMediaUrl} calls for the same URL skip the network entirely.
|
|
376
|
+
*
|
|
377
|
+
* @param url The original remote URL — used as the Cache API key so that
|
|
378
|
+
* {@link getMediaUrl} can retrieve the entry with a simple `match`.
|
|
379
|
+
* @param blob The downloaded media blob to persist.
|
|
380
|
+
* @returns A blob URL that the renderer can set as `src` on an
|
|
381
|
+
* `<img>` or `<video>` element.
|
|
382
|
+
*/
|
|
383
|
+
async saveMedia(url, blob) {
|
|
384
|
+
await (await caches.open(this.cacheName)).put(url, new Response(blob));
|
|
385
|
+
const objectUrl = URL.createObjectURL(blob);
|
|
386
|
+
this.objectUrls.set(url, objectUrl);
|
|
387
|
+
return objectUrl;
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Wipes all cached data:
|
|
391
|
+
* - Revokes every outstanding blob URL to release the underlying Blob references.
|
|
392
|
+
* - Deletes the IndexedDB database entirely (recreated on next access).
|
|
393
|
+
* - Removes all entries from the Cache API bucket.
|
|
394
|
+
*
|
|
395
|
+
* Useful for a "factory reset" flow or in tests to guarantee a clean slate.
|
|
396
|
+
*/
|
|
397
|
+
async clear() {
|
|
398
|
+
for (const url of this.objectUrls.values()) URL.revokeObjectURL(url);
|
|
399
|
+
this.objectUrls.clear();
|
|
400
|
+
(await this.openDB()).close();
|
|
401
|
+
await (0, idb.deleteDB)(this.dbName);
|
|
402
|
+
const cache = await caches.open(this.cacheName);
|
|
403
|
+
const keys = await cache.keys();
|
|
404
|
+
await Promise.all(keys.map((req) => cache.delete(req)));
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
//#endregion
|
|
408
|
+
//#region src/player/SquareScreenPlayer.ts
|
|
409
|
+
const LAST_PLAYLIST_KEY = "square-screen:last-playlist-uuid";
|
|
410
|
+
/**
|
|
411
|
+
* Headless, framework-agnostic player that manages playlist fetching, caching,
|
|
412
|
+
* item advancement, preloading, polling, and emergency alerts.
|
|
413
|
+
*
|
|
414
|
+
* Extends `EventTarget` — use `addEventListener` / `removeEventListener` to
|
|
415
|
+
* react to player events. No DOM or rendering logic lives here.
|
|
416
|
+
*
|
|
417
|
+
* @example
|
|
418
|
+
* const player = new SquareScreenPlayer({ deviceId, deviceToken, version: "1.0.0" });
|
|
419
|
+
* player.addEventListener("itemchange", ({ detail }) => render(detail.item));
|
|
420
|
+
* player.addEventListener("emergencyalert", ({ detail }) => showAlert(detail.alert));
|
|
421
|
+
* await player.start();
|
|
422
|
+
*/
|
|
423
|
+
var SquareScreenPlayer = class extends EventTarget {
|
|
424
|
+
constructor(config) {
|
|
425
|
+
super();
|
|
426
|
+
this.playlist = null;
|
|
427
|
+
this.stopped = false;
|
|
428
|
+
this.currentIndex = 0;
|
|
429
|
+
this.status = "connecting";
|
|
430
|
+
this.activeAlert = null;
|
|
431
|
+
this.currentItemStartTime = null;
|
|
432
|
+
this.itemTimer = null;
|
|
433
|
+
this.playlistPollTimer = null;
|
|
434
|
+
this.emergencyPollTimer = null;
|
|
435
|
+
this.heartbeatTimer = null;
|
|
436
|
+
if (!config.networkDataSource) {
|
|
437
|
+
if (!config.deviceId) throw new Error("SquareScreenPlayer: deviceId is required.");
|
|
438
|
+
if (!config.deviceToken) throw new Error("SquareScreenPlayer: deviceToken is required.");
|
|
439
|
+
}
|
|
440
|
+
this.network = config.networkDataSource ?? new NetworkClient("https://square-screen-api-development-f7zuxa.laravel.cloud/api/v1", config.deviceId, config.deviceToken);
|
|
441
|
+
this.cache = config.cacheProvider ?? new SquareScreenCache();
|
|
442
|
+
const { networkDataSource: _n, cacheProvider: _c, ...rest } = config;
|
|
443
|
+
this.config = {
|
|
444
|
+
ttl: 300 * 1e3,
|
|
445
|
+
pollInterval: 3e4,
|
|
446
|
+
emergencyPollInterval: 15e3,
|
|
447
|
+
heartbeatInterval: 6e4,
|
|
448
|
+
...rest
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
/** The playlist item currently being displayed, or null if no playlist is loaded. */
|
|
452
|
+
get currentItem() {
|
|
453
|
+
return this.playlist?.items[this.currentIndex] ?? null;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Starts the player: fetches the playlist, begins playback, and starts polling
|
|
457
|
+
* and heartbeat intervals. Safe to await — resolves once the first playlist load
|
|
458
|
+
* attempt completes (whether from network or cache fallback).
|
|
459
|
+
*/
|
|
460
|
+
async start() {
|
|
461
|
+
this.stopped = false;
|
|
462
|
+
this.setStatus("connecting");
|
|
463
|
+
await this.loadPlaylist();
|
|
464
|
+
await this.checkEmergencyAlert();
|
|
465
|
+
this.startPolling();
|
|
466
|
+
this.startHeartbeat();
|
|
467
|
+
}
|
|
468
|
+
/** Stops all timers and clears internal state. Call this when tearing down the player. */
|
|
469
|
+
stop() {
|
|
470
|
+
if (this.itemTimer) clearTimeout(this.itemTimer);
|
|
471
|
+
if (this.playlistPollTimer) clearInterval(this.playlistPollTimer);
|
|
472
|
+
if (this.emergencyPollTimer) clearInterval(this.emergencyPollTimer);
|
|
473
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
474
|
+
this.itemTimer = null;
|
|
475
|
+
this.playlistPollTimer = null;
|
|
476
|
+
this.emergencyPollTimer = null;
|
|
477
|
+
this.heartbeatTimer = null;
|
|
478
|
+
this.stopped = true;
|
|
479
|
+
this.playlist = null;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Network-first playlist load. On success the playlist is saved to cache and
|
|
483
|
+
* applied if the UUID changed. On failure the player falls back to the last
|
|
484
|
+
* known playlist UUID stored in `localStorage`, loading it from cache with
|
|
485
|
+
* `allowStale = true` so it is served even after its TTL has expired.
|
|
486
|
+
*/
|
|
487
|
+
async loadPlaylist() {
|
|
488
|
+
const result = await this.network.fetchPlaylist();
|
|
489
|
+
if (result.success) {
|
|
490
|
+
this.setStatus("online");
|
|
491
|
+
const playlist = result.data;
|
|
492
|
+
localStorage.setItem(LAST_PLAYLIST_KEY, playlist.uuid);
|
|
493
|
+
await this.cache.savePlaylist(playlist, this.config.ttl);
|
|
494
|
+
if (!this.playlist || this.playlist.uuid !== playlist.uuid) await this.applyPlaylist(playlist);
|
|
495
|
+
else this.dispatch("playlistupdate", { playlist });
|
|
496
|
+
} else {
|
|
497
|
+
this.setStatus("offline");
|
|
498
|
+
if (!this.playlist) {
|
|
499
|
+
const lastUuid = localStorage.getItem(LAST_PLAYLIST_KEY);
|
|
500
|
+
if (lastUuid) {
|
|
501
|
+
const cached = await this.cache.getPlaylist(lastUuid, true);
|
|
502
|
+
if (cached) await this.applyPlaylist(cached);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Activates a playlist: optionally shuffles the items, resets the index to 0,
|
|
509
|
+
* emits `playlistupdate`, and kicks off the first `scheduleItem` call.
|
|
510
|
+
* Bails out immediately if `stop()` has been called.
|
|
511
|
+
*/
|
|
512
|
+
async applyPlaylist(playlist) {
|
|
513
|
+
if (this.stopped) return;
|
|
514
|
+
const items = playlist.strategy?.shuffle ? [...playlist.items].sort(() => Math.random() - .5) : playlist.items;
|
|
515
|
+
this.playlist = {
|
|
516
|
+
...playlist,
|
|
517
|
+
items
|
|
518
|
+
};
|
|
519
|
+
this.currentIndex = 0;
|
|
520
|
+
this.dispatch("playlistupdate", { playlist: this.playlist });
|
|
521
|
+
this.scheduleItem();
|
|
522
|
+
}
|
|
523
|
+
refreshPlaylist() {
|
|
524
|
+
this.loadPlaylist();
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Emits `itemchange` immediately with either the cached blob URL or the raw
|
|
528
|
+
* HTTPS URL, then arms the advancement timer. Never blocks on a network fetch —
|
|
529
|
+
* if the media isn't cached yet the browser loads it directly while
|
|
530
|
+
* `preloadNext` / `downloadInBackground` cache it for the next cycle.
|
|
531
|
+
*
|
|
532
|
+
* Guards against `stop()` being called while awaiting the cache lookup.
|
|
533
|
+
*/
|
|
534
|
+
async scheduleItem() {
|
|
535
|
+
if (this.itemTimer) clearTimeout(this.itemTimer);
|
|
536
|
+
const item = this.currentItem;
|
|
537
|
+
if (!item || !this.playlist) return;
|
|
538
|
+
this.currentItemStartTime = Date.now();
|
|
539
|
+
const url = await this.cache.getMediaUrl(item.url) ?? item.url;
|
|
540
|
+
if (!this.playlist) return;
|
|
541
|
+
this.dispatch("itemchange", {
|
|
542
|
+
item: {
|
|
543
|
+
...item,
|
|
544
|
+
url
|
|
545
|
+
},
|
|
546
|
+
index: this.currentIndex,
|
|
547
|
+
total: this.playlist.items.length
|
|
548
|
+
});
|
|
549
|
+
if (url === item.url) this.downloadInBackground(item.url);
|
|
550
|
+
this.preloadNext();
|
|
551
|
+
const elapsed = Date.now() - this.currentItemStartTime;
|
|
552
|
+
const remaining = Math.max(0, item.duration * 1e3 - elapsed);
|
|
553
|
+
this.itemTimer = setTimeout(() => this.advance(), remaining);
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Schedules background downloads for upcoming items while the current one
|
|
557
|
+
* is playing, so subsequent transitions can serve blob URLs immediately.
|
|
558
|
+
*
|
|
559
|
+
* - `preloadCount: 0` — disabled; nothing is downloaded.
|
|
560
|
+
* - `preloadCount: N` — downloads the next N items ahead (wraps at end).
|
|
561
|
+
* - `preloadCount` absent — downloads all items in the playlist up front.
|
|
562
|
+
*/
|
|
563
|
+
preloadNext() {
|
|
564
|
+
if (!this.playlist) return;
|
|
565
|
+
const preloadCount = this.playlist.strategy?.preloadCount;
|
|
566
|
+
if (preloadCount === 0) return;
|
|
567
|
+
const count = preloadCount ?? this.playlist.items.length;
|
|
568
|
+
for (let i = 1; i <= count; i++) {
|
|
569
|
+
const idx = (this.currentIndex + i) % this.playlist.items.length;
|
|
570
|
+
this.downloadInBackground(this.playlist.items[idx].url);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Fire-and-forget download. Checks the cache first; if the media is already
|
|
575
|
+
* present the call is a no-op. Errors are silently swallowed — a failed
|
|
576
|
+
* download is not fatal; the raw URL will be used until the next successful download.
|
|
577
|
+
*/
|
|
578
|
+
downloadInBackground(url) {
|
|
579
|
+
this.cache.getMediaUrl(url).then((cached) => {
|
|
580
|
+
if (cached || !this.playlist) return;
|
|
581
|
+
return fetch(url, { mode: "cors" }).then((r) => r.ok ? r.blob() : Promise.reject(/* @__PURE__ */ new Error(`HTTP ${r.status}`))).then((blob) => this.cache.saveMedia(url, blob));
|
|
582
|
+
}).catch(() => {});
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Moves to the next item. Reports the completed playback event, then either
|
|
586
|
+
* wraps back to index 0 (when `loop` is true or absent) or halts when
|
|
587
|
+
* `loop: false` and the last item has finished.
|
|
588
|
+
*/
|
|
589
|
+
advance() {
|
|
590
|
+
if (!this.playlist) return;
|
|
591
|
+
const total = this.playlist.items.length;
|
|
592
|
+
const next = this.currentIndex + 1;
|
|
593
|
+
this.reportPlaybackEvent();
|
|
594
|
+
if (next >= total) if (this.playlist.strategy?.loop ?? true) this.currentIndex = 0;
|
|
595
|
+
else return;
|
|
596
|
+
else this.currentIndex = next;
|
|
597
|
+
this.scheduleItem();
|
|
598
|
+
}
|
|
599
|
+
/** Sends a proof-of-play event to the server. Fire-and-forget; failures are not surfaced. */
|
|
600
|
+
async reportPlaybackEvent() {
|
|
601
|
+
if (!this.currentItemStartTime) return;
|
|
602
|
+
if (!this.currentItem || !this.playlist) return;
|
|
603
|
+
const endedAt = Date.now();
|
|
604
|
+
const event = {
|
|
605
|
+
media_uuid: this.currentItem.uuid,
|
|
606
|
+
playlist_uuid: this.playlist.uuid,
|
|
607
|
+
schedule_uuid: this.playlist.schedule?.uuid ?? "",
|
|
608
|
+
started_at: new Date(this.currentItemStartTime).toISOString(),
|
|
609
|
+
ended_at: new Date(endedAt).toISOString(),
|
|
610
|
+
duration_seconds: Math.round((endedAt - this.currentItemStartTime) / 1e3),
|
|
611
|
+
completed: true
|
|
612
|
+
};
|
|
613
|
+
this.network.reportPlaybackEvent(event);
|
|
614
|
+
}
|
|
615
|
+
/** Arms the playlist-refresh and emergency-alert polling intervals. */
|
|
616
|
+
startPolling() {
|
|
617
|
+
this.playlistPollTimer = setInterval(() => this.loadPlaylist(), this.config.pollInterval);
|
|
618
|
+
this.emergencyPollTimer = setInterval(() => this.checkEmergencyAlert(), this.config.emergencyPollInterval);
|
|
619
|
+
}
|
|
620
|
+
/** Arms the periodic heartbeat that keeps the device registration alive. */
|
|
621
|
+
startHeartbeat() {
|
|
622
|
+
this.heartbeatTimer = setInterval(async () => {
|
|
623
|
+
await this.network.healthCheck({ playerVersion: this.config.version });
|
|
624
|
+
}, this.config.heartbeatInterval);
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Polls the server for an active emergency alert. Emits `emergencyalert` only
|
|
628
|
+
* when the state actually changes (alert activated, cleared, or replaced by a
|
|
629
|
+
* different UUID) to avoid redundant re-renders on the consumer side.
|
|
630
|
+
*/
|
|
631
|
+
async checkEmergencyAlert() {
|
|
632
|
+
const result = await this.network.checkForEmergencyAlert();
|
|
633
|
+
if (!result.success) return;
|
|
634
|
+
const incoming = result.data;
|
|
635
|
+
const wasActive = this.activeAlert !== null;
|
|
636
|
+
const isActive = incoming !== null;
|
|
637
|
+
const alertChanged = isActive && incoming.uuid !== this.activeAlert?.uuid;
|
|
638
|
+
if (wasActive !== isActive || alertChanged) {
|
|
639
|
+
this.activeAlert = incoming;
|
|
640
|
+
this.dispatch("emergencyalert", { alert: incoming });
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
setStatus(status) {
|
|
644
|
+
if (this.status === status) return;
|
|
645
|
+
this.status = status;
|
|
646
|
+
this.dispatch("statuschange", { status });
|
|
647
|
+
}
|
|
648
|
+
dispatch(type, detail) {
|
|
649
|
+
this.dispatchEvent(new CustomEvent(type, { detail }));
|
|
650
|
+
}
|
|
651
|
+
addEventListener(type, listener, options) {
|
|
652
|
+
super.addEventListener(type, listener, options);
|
|
653
|
+
}
|
|
654
|
+
removeEventListener(type, listener, options) {
|
|
655
|
+
super.removeEventListener(type, listener, options);
|
|
656
|
+
}
|
|
657
|
+
};
|
|
658
|
+
//#endregion
|
|
659
|
+
//#region src/renderer/SquareScreenRenderer.ts
|
|
660
|
+
/**
|
|
661
|
+
* Optional vanilla JS renderer that wires a {@link SquareScreenPlayer} to a DOM container.
|
|
662
|
+
* Handles `<img>` / `<video>` element lifecycle, autoplay, transitions, and emergency alerts.
|
|
663
|
+
*
|
|
664
|
+
* When an emergency alert is active it renders a full-screen overlay on top of all content.
|
|
665
|
+
* Normal playback resumes automatically once the alert is cleared.
|
|
666
|
+
*
|
|
667
|
+
* @example
|
|
668
|
+
* const player = new SquareScreenPlayer({ ... });
|
|
669
|
+
* const renderer = new SquareScreenRenderer(document.getElementById("screen"), player);
|
|
670
|
+
* renderer.mount();
|
|
671
|
+
* await player.start();
|
|
672
|
+
*
|
|
673
|
+
* // Tear down
|
|
674
|
+
* player.stop();
|
|
675
|
+
* renderer.unmount();
|
|
676
|
+
*/
|
|
677
|
+
var SquareScreenRenderer = class {
|
|
678
|
+
constructor(container, player, config = {}) {
|
|
679
|
+
this.wrapper = null;
|
|
680
|
+
this.slots = null;
|
|
681
|
+
this.activeSlot = 0;
|
|
682
|
+
this.alertOverlay = null;
|
|
683
|
+
this.container = container;
|
|
684
|
+
this.player = player;
|
|
685
|
+
this.config = {
|
|
686
|
+
defaultTransition: "none",
|
|
687
|
+
transitionDuration: 500,
|
|
688
|
+
canPlayTimeout: 3e3,
|
|
689
|
+
...config
|
|
690
|
+
};
|
|
691
|
+
this.onItemChange = (e) => this.handleItemChange(e.detail.item);
|
|
692
|
+
this.onEmergencyAlert = (e) => this.handleEmergencyAlert(e.detail.alert);
|
|
693
|
+
}
|
|
694
|
+
/** Injects the renderer DOM into the container and begins listening to the player. */
|
|
695
|
+
mount() {
|
|
696
|
+
this.buildDOM();
|
|
697
|
+
this.player.addEventListener("itemchange", this.onItemChange);
|
|
698
|
+
this.player.addEventListener("emergencyalert", this.onEmergencyAlert);
|
|
699
|
+
}
|
|
700
|
+
/** Removes the renderer DOM and stops listening to the player. */
|
|
701
|
+
unmount() {
|
|
702
|
+
this.player.removeEventListener("itemchange", this.onItemChange);
|
|
703
|
+
this.player.removeEventListener("emergencyalert", this.onEmergencyAlert);
|
|
704
|
+
if (this.wrapper && this.container.contains(this.wrapper)) this.container.removeChild(this.wrapper);
|
|
705
|
+
this.wrapper = null;
|
|
706
|
+
this.slots = null;
|
|
707
|
+
}
|
|
708
|
+
buildDOM() {
|
|
709
|
+
this.wrapper = document.createElement("div");
|
|
710
|
+
Object.assign(this.wrapper.style, {
|
|
711
|
+
position: "relative",
|
|
712
|
+
width: "100%",
|
|
713
|
+
height: "100%",
|
|
714
|
+
overflow: "hidden",
|
|
715
|
+
backgroundColor: "#000"
|
|
716
|
+
});
|
|
717
|
+
const slotA = this.createSlot(true);
|
|
718
|
+
const slotB = this.createSlot(false);
|
|
719
|
+
this.wrapper.appendChild(slotA);
|
|
720
|
+
this.wrapper.appendChild(slotB);
|
|
721
|
+
this.slots = [slotA, slotB];
|
|
722
|
+
this.alertOverlay = document.createElement("div");
|
|
723
|
+
Object.assign(this.alertOverlay.style, {
|
|
724
|
+
display: "none",
|
|
725
|
+
position: "absolute",
|
|
726
|
+
top: "0",
|
|
727
|
+
right: "0",
|
|
728
|
+
bottom: "0",
|
|
729
|
+
left: "0",
|
|
730
|
+
zIndex: "9999",
|
|
731
|
+
flexDirection: "column",
|
|
732
|
+
alignItems: "center",
|
|
733
|
+
justifyContent: "center",
|
|
734
|
+
padding: "2rem",
|
|
735
|
+
textAlign: "center",
|
|
736
|
+
boxSizing: "border-box"
|
|
737
|
+
});
|
|
738
|
+
this.wrapper.appendChild(this.alertOverlay);
|
|
739
|
+
this.container.appendChild(this.wrapper);
|
|
740
|
+
}
|
|
741
|
+
createSlot(visible) {
|
|
742
|
+
const slot = document.createElement("div");
|
|
743
|
+
Object.assign(slot.style, {
|
|
744
|
+
position: "absolute",
|
|
745
|
+
top: "0",
|
|
746
|
+
right: "0",
|
|
747
|
+
bottom: "0",
|
|
748
|
+
left: "0",
|
|
749
|
+
display: "flex",
|
|
750
|
+
alignItems: "center",
|
|
751
|
+
justifyContent: "center",
|
|
752
|
+
opacity: visible ? "1" : "0",
|
|
753
|
+
transition: `opacity ${this.config.transitionDuration}ms ease`
|
|
754
|
+
});
|
|
755
|
+
return slot;
|
|
756
|
+
}
|
|
757
|
+
async handleItemChange(item) {
|
|
758
|
+
if (!this.slots) return;
|
|
759
|
+
const nextIndex = (this.activeSlot + 1) % 2;
|
|
760
|
+
const currentSlot = this.slots[this.activeSlot];
|
|
761
|
+
const nextSlot = this.slots[nextIndex];
|
|
762
|
+
nextSlot.innerHTML = "";
|
|
763
|
+
const media = item.type === "video" ? this.createVideo(item.url) : this.createImage(item.url);
|
|
764
|
+
nextSlot.appendChild(media);
|
|
765
|
+
if (item.type === "video") await this.waitForCanPlay(media);
|
|
766
|
+
const transitionType = item.transition ?? this.config.defaultTransition;
|
|
767
|
+
await this.applyTransition(currentSlot, nextSlot, transitionType);
|
|
768
|
+
this.activeSlot = nextIndex;
|
|
769
|
+
}
|
|
770
|
+
handleEmergencyAlert(alert) {
|
|
771
|
+
if (!this.alertOverlay) return;
|
|
772
|
+
if (!alert) {
|
|
773
|
+
this.alertOverlay.style.display = "none";
|
|
774
|
+
this.alertOverlay.innerHTML = "";
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
this.alertOverlay.style.display = "flex";
|
|
778
|
+
this.alertOverlay.style.backgroundColor = alert.backgroundColor;
|
|
779
|
+
this.alertOverlay.style.color = alert.textColor;
|
|
780
|
+
const title = document.createElement("h1");
|
|
781
|
+
title.textContent = alert.title;
|
|
782
|
+
Object.assign(title.style, {
|
|
783
|
+
margin: "0 0 1rem",
|
|
784
|
+
fontSize: "2.5rem",
|
|
785
|
+
fontWeight: "bold"
|
|
786
|
+
});
|
|
787
|
+
const message = document.createElement("p");
|
|
788
|
+
message.textContent = alert.message;
|
|
789
|
+
Object.assign(message.style, {
|
|
790
|
+
margin: "0",
|
|
791
|
+
fontSize: "1.5rem"
|
|
792
|
+
});
|
|
793
|
+
this.alertOverlay.innerHTML = "";
|
|
794
|
+
this.alertOverlay.appendChild(title);
|
|
795
|
+
this.alertOverlay.appendChild(message);
|
|
796
|
+
}
|
|
797
|
+
createImage(src) {
|
|
798
|
+
const img = document.createElement("img");
|
|
799
|
+
Object.assign(img.style, {
|
|
800
|
+
maxWidth: "100%",
|
|
801
|
+
maxHeight: "100%",
|
|
802
|
+
objectFit: "contain"
|
|
803
|
+
});
|
|
804
|
+
img.src = src;
|
|
805
|
+
return img;
|
|
806
|
+
}
|
|
807
|
+
createVideo(src) {
|
|
808
|
+
const video = document.createElement("video");
|
|
809
|
+
Object.assign(video.style, {
|
|
810
|
+
width: "100%",
|
|
811
|
+
height: "100%",
|
|
812
|
+
objectFit: "contain"
|
|
813
|
+
});
|
|
814
|
+
video.src = src;
|
|
815
|
+
video.autoplay = true;
|
|
816
|
+
video.muted = true;
|
|
817
|
+
video.playsInline = true;
|
|
818
|
+
video.loop = true;
|
|
819
|
+
return video;
|
|
820
|
+
}
|
|
821
|
+
waitForCanPlay(video) {
|
|
822
|
+
return new Promise((resolve) => {
|
|
823
|
+
if (video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) {
|
|
824
|
+
resolve();
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
const timeout = this.config.canPlayTimeout;
|
|
828
|
+
const timer = timeout > 0 ? setTimeout(resolve, timeout) : null;
|
|
829
|
+
const handler = () => {
|
|
830
|
+
if (timer) clearTimeout(timer);
|
|
831
|
+
video.removeEventListener("canplay", handler);
|
|
832
|
+
resolve();
|
|
833
|
+
};
|
|
834
|
+
video.addEventListener("canplay", handler);
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
async applyTransition(from, to, type) {
|
|
838
|
+
const duration = this.config.transitionDuration;
|
|
839
|
+
if (type === "none" || duration === 0) {
|
|
840
|
+
from.style.opacity = "0";
|
|
841
|
+
to.style.opacity = "1";
|
|
842
|
+
} else if (type === "fade") {
|
|
843
|
+
to.style.opacity = "1";
|
|
844
|
+
from.style.opacity = "0";
|
|
845
|
+
await this.wait(duration);
|
|
846
|
+
} else if (type === "slide") {
|
|
847
|
+
to.style.transition = "none";
|
|
848
|
+
to.style.transform = "translateX(100%)";
|
|
849
|
+
to.style.opacity = "1";
|
|
850
|
+
to.offsetWidth;
|
|
851
|
+
to.style.transition = `transform ${duration}ms ease`;
|
|
852
|
+
from.style.transition = `transform ${duration}ms ease`;
|
|
853
|
+
to.style.transform = "translateX(0)";
|
|
854
|
+
from.style.transform = "translateX(-100%)";
|
|
855
|
+
await this.wait(duration);
|
|
856
|
+
}
|
|
857
|
+
from.style.transition = `opacity ${duration}ms ease`;
|
|
858
|
+
from.style.transform = "";
|
|
859
|
+
from.style.opacity = "0";
|
|
860
|
+
to.style.transition = `opacity ${duration}ms ease`;
|
|
861
|
+
to.style.transform = "";
|
|
862
|
+
to.style.opacity = "1";
|
|
863
|
+
}
|
|
864
|
+
wait(ms) {
|
|
865
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
//#endregion
|
|
869
|
+
exports.SQUARESCREEN_API_BASE_URL = SQUARESCREEN_API_BASE_URL;
|
|
870
|
+
exports.SquareScreenCache = SquareScreenCache;
|
|
871
|
+
exports.SquareScreenPlayer = SquareScreenPlayer;
|
|
872
|
+
exports.SquareScreenRenderer = SquareScreenRenderer;
|
|
873
|
+
|
|
874
|
+
//# sourceMappingURL=index.cjs.map
|