@karnstack/kino 0.2.0 → 0.3.0

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/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  <p align="center">
6
6
  A themeable React video player with a pluggable-provider architecture —
7
7
  translucent glass chrome, keyboard-first controls, and a small typed surface.
8
- Mux is the first provider.
8
+ Mux, raw files, and YouTube are built in.
9
9
  </p>
10
10
 
11
11
  <p align="center">
@@ -24,7 +24,7 @@
24
24
 
25
25
  > **[Try it live → kino.karnstack.com](https://kino.karnstack.com)** — drop in any public Mux playback ID, pick an accent, and play with the real glass UI.
26
26
 
27
- kino ships the player UI and a provider contract. Each provider adapts a streaming engine to that contract, so the same glass chrome can sit on top of different backends. The Mux provider is built on the `@mux/mux-video` custom element.
27
+ kino ships the player UI and a provider contract. Each provider adapts a streaming engine to that contract, so the same glass chrome can sit on top of different backends. Three providers ship today: **Mux** (adaptive HLS via `@mux/mux-video`), **Native** (a plain `<video>` over any raw file URL), and **YouTube** (the IFrame Player API wrapped in the same chrome). Each lives behind its own entry point, so you only pull in the engine you use.
28
28
 
29
29
  ## Install
30
30
 
@@ -106,6 +106,32 @@ Pass sidecar subtitles/captions via `tracks`, and kino renders the cues in its o
106
106
 
107
107
  `NativePlayer` also takes `autoPlay`, `muted`, `loop`, `defaultRate`, and `crossOrigin` (set the last when the media or a caption track is cross-origin). Quality switching hides itself since a raw file carries no rendition ladder.
108
108
 
109
+ ## Playing a YouTube video
110
+
111
+ For a YouTube source, use the YouTube provider. It drives the YouTube IFrame Player API under the same glass chrome, with kino owning the controls and keyboard map (the native YouTube UI is hidden).
112
+
113
+ ```tsx
114
+ import { YouTubePlayer } from "@karnstack/kino/youtube"
115
+ import "@karnstack/kino/styles.css"
116
+
117
+ export function Clip() {
118
+ return (
119
+ <div style={{ aspectRatio: "16 / 9" }}>
120
+ <YouTubePlayer
121
+ videoId="dQw4w9WgXcQ"
122
+ accentColor="oklch(50.8% 0.118 165.612)"
123
+ />
124
+ </div>
125
+ )
126
+ }
127
+ ```
128
+
129
+ `videoId` accepts a bare id or any `watch`, `youtu.be`, `embed`, or `shorts` URL — kino resolves it (the `parseYouTubeId` helper is exported if you want it directly). It also takes `autoPlay`, `muted`, `loop`, `defaultRate`, and `metadata`.
130
+
131
+ Speed, fullscreen, and captions work. The captions menu lists the video's own subtitle tracks; YouTube renders the cues itself inside the embed, so they appear in YouTube's style rather than kino's caption overlay.
132
+
133
+ kino plays YouTube through the official IFrame Player API and, per YouTube's terms, **doesn't obscure the player**: before playback and while paused, YouTube shows its own thumbnail, play button, title, and logo, and kino's controls sit alongside them. A few things the API simply doesn't expose, so kino hides those controls: **manual quality** (YouTube dropped it — playback is always automatic), **picture-in-picture**, and **scrub-preview thumbnails** (storyboards aren't available to embeds).
134
+
109
135
  ## Theming
110
136
 
111
137
  The quickest knob is the `accentColor` prop, which drives the scrubber fill, active menu items, and range controls.
@@ -175,7 +201,7 @@ pnpm lint # eslint
175
201
 
176
202
  ## Roadmap
177
203
 
178
- - More providers: YouTube and Vimeo
204
+ - More providers: Vimeo
179
205
  - AirPlay support
180
206
  - Chapters
181
207
  - Documented headless primitives for fully custom chrome
@@ -1,38 +1,3 @@
1
- //#region src/core/fake-provider.ts
2
- const DEFAULT_CAPS = {
3
- canSetQuality: true,
4
- hasStoryboard: false,
5
- canPiP: true,
6
- canFullscreen: true,
7
- canSetRate: true,
8
- hasTextTracks: false
9
- };
10
- function defaultState() {
11
- return {
12
- paused: true,
13
- currentTime: 0,
14
- duration: 0,
15
- buffered: [],
16
- rate: 1,
17
- volume: 1,
18
- muted: false,
19
- readyState: 0,
20
- seeking: false,
21
- ended: false,
22
- error: null,
23
- qualities: [],
24
- activeQualityId: "auto",
25
- videoHeight: 0,
26
- textTracks: [],
27
- activeTextTrackId: null,
28
- activeCueText: "",
29
- fullscreen: false,
30
- pip: false,
31
- storyboard: null,
32
- capabilities: { ...DEFAULT_CAPS }
33
- };
34
- }
35
- //#endregion
36
1
  //#region src/util/platform.ts
37
2
  function detectIOS(ua, maxTouchPoints = 0) {
38
3
  if (/iPhone|iPad|iPod/.test(ua)) return true;
@@ -72,4 +37,4 @@ function activeCueText(tracks, now) {
72
37
  return "";
73
38
  }
74
39
  //#endregion
75
- export { detectIOS as n, defaultState as r, activeCueText as t };
40
+ export { detectIOS as n, activeCueText as t };
@@ -0,0 +1,36 @@
1
+ //#region src/core/fake-provider.ts
2
+ const DEFAULT_CAPS = {
3
+ canSetQuality: true,
4
+ hasStoryboard: false,
5
+ canPiP: true,
6
+ canFullscreen: true,
7
+ canSetRate: true,
8
+ hasTextTracks: false
9
+ };
10
+ function defaultState() {
11
+ return {
12
+ paused: true,
13
+ currentTime: 0,
14
+ duration: 0,
15
+ buffered: [],
16
+ rate: 1,
17
+ volume: 1,
18
+ muted: false,
19
+ readyState: 0,
20
+ seeking: false,
21
+ ended: false,
22
+ error: null,
23
+ qualities: [],
24
+ activeQualityId: "auto",
25
+ videoHeight: 0,
26
+ textTracks: [],
27
+ activeTextTrackId: null,
28
+ activeCueText: "",
29
+ fullscreen: false,
30
+ pip: false,
31
+ storyboard: null,
32
+ capabilities: { ...DEFAULT_CAPS }
33
+ };
34
+ }
35
+ //#endregion
36
+ export { defaultState as t };
package/dist/mux.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { c as Captions, d as Player, l as IdleOverlay, t as ControlBar } from "./control-bar-B-p1rMgm.js";
2
- import { n as detectIOS, r as defaultState, t as activeCueText } from "./captions-BBk_DvTt.js";
2
+ import { t as defaultState } from "./fake-provider-Do3fX4-T.js";
3
+ import { n as detectIOS, t as activeCueText } from "./captions-CGVAzrJq.js";
3
4
  import { useEffect, useRef } from "react";
4
5
  import { jsx, jsxs } from "react/jsx-runtime";
5
6
  import "@mux/mux-video";
package/dist/native.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { c as Captions, d as Player, l as IdleOverlay, t as ControlBar } from "./control-bar-B-p1rMgm.js";
2
- import { n as detectIOS, r as defaultState, t as activeCueText } from "./captions-BBk_DvTt.js";
2
+ import { t as defaultState } from "./fake-provider-Do3fX4-T.js";
3
+ import { n as detectIOS, t as activeCueText } from "./captions-CGVAzrJq.js";
3
4
  import { useEffect, useRef } from "react";
4
5
  import { jsx, jsxs } from "react/jsx-runtime";
5
6
  //#region src/native/provider.ts
package/dist/styles.css CHANGED
@@ -28,11 +28,21 @@
28
28
  box-sizing: border-box;
29
29
  }
30
30
  .kino mux-video,
31
- .kino video {
31
+ .kino video,
32
+ /* The YouTube provider mounts an <iframe> here; size it like the video. */
33
+ .kino .kino-video-host iframe {
32
34
  position: absolute;
33
35
  inset: 0;
34
36
  width: 100%;
35
37
  height: 100%;
38
+ border: 0;
39
+ }
40
+ /* Let kino's gesture layer own every pointer interaction. Without this the
41
+ YouTube iframe surfaces its own hover chrome — title, "More videos", a second
42
+ progress bar — on top of kino's controls. Killing pointer events on the
43
+ iframe stops YouTube from ever seeing a hover, so only kino's UI shows. */
44
+ .kino .kino-video-host iframe {
45
+ pointer-events: none;
36
46
  }
37
47
  .kino .kino-placeholder {
38
48
  position: absolute;
@@ -0,0 +1,54 @@
1
+ import { a as Provider } from "./types-D0bLitH2.js";
2
+ import { ReactNode } from "react";
3
+
4
+ //#region src/youtube/provider.d.ts
5
+ type YouTubeProviderOptions = {
6
+ videoId: string;
7
+ metadata?: {
8
+ videoId?: string;
9
+ videoTitle?: string;
10
+ viewerUserId?: string;
11
+ };
12
+ autoPlay?: boolean;
13
+ muted?: boolean;
14
+ loop?: boolean;
15
+ defaultRate?: number;
16
+ };
17
+ declare function parseYouTubeId(input: string): string;
18
+ declare function createYouTubeProvider(opts: YouTubeProviderOptions): Provider;
19
+ //#endregion
20
+ //#region src/youtube/youtube-player.d.ts
21
+ type YouTubePlayerProps = YouTubeProviderOptions & {
22
+ accentColor?: string;
23
+ theme?: Record<string, string>;
24
+ className?: string; /** Blur-up still painted behind the video until the first frame loads. */
25
+ placeholder?: string;
26
+ children?: ReactNode;
27
+ };
28
+ /**
29
+ * kino's glass chrome over a YouTube video, backed by the YouTube IFrame Player
30
+ * API. Pass a video id or any watch / youtu.be / embed / shorts URL.
31
+ *
32
+ * Only `videoId` and `metadata.videoTitle` are reactive (they flow through
33
+ * `swapSource`). `autoPlay`, `muted`, `loop`, and `defaultRate` are read once
34
+ * when the provider is created — changing them later is a no-op. Remount (e.g.
35
+ * via `key`) if you need them to change.
36
+ *
37
+ * The IFrame API can't expose quality or picture-in-picture, so those controls
38
+ * hide themselves automatically. Captions work through the API and are rendered
39
+ * by YouTube inside the embed.
40
+ *
41
+ * Per YouTube's API terms, kino doesn't obscure the player: YouTube shows its
42
+ * own thumbnail, play button, title, and logo before playback and while paused.
43
+ * kino's controls sit alongside them.
44
+ */
45
+ declare function YouTubePlayer({
46
+ accentColor,
47
+ theme,
48
+ className,
49
+ placeholder,
50
+ children,
51
+ ...opts
52
+ }: YouTubePlayerProps): import("react").JSX.Element;
53
+ //#endregion
54
+ export { YouTubePlayer, type YouTubePlayerProps, type YouTubeProviderOptions, createYouTubeProvider, parseYouTubeId };
@@ -0,0 +1,293 @@
1
+ import { c as Captions, d as Player, l as IdleOverlay, t as ControlBar } from "./control-bar-B-p1rMgm.js";
2
+ import { t as defaultState } from "./fake-provider-Do3fX4-T.js";
3
+ import { useEffect, useRef } from "react";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ //#region src/youtube/provider.ts
6
+ const PLAYING = 1;
7
+ const ENDED = 0;
8
+ const BUFFERING = 3;
9
+ const CAPTION_MODULES = ["captions", "cc"];
10
+ const IFRAME_API_SRC = "https://www.youtube.com/iframe_api";
11
+ function parseYouTubeId(input) {
12
+ const trimmed = input.trim();
13
+ if (/^[\w-]{11}$/.test(trimmed)) return trimmed;
14
+ const m = trimmed.match(/(?:youtu\.be\/|\/embed\/|\/shorts\/|[?&]v=)([\w-]{11})/);
15
+ return m ? m[1] : trimmed;
16
+ }
17
+ let apiPromise = null;
18
+ function loadYouTubeAPI() {
19
+ const w = window;
20
+ if (w.YT?.Player) return Promise.resolve(w.YT);
21
+ if (apiPromise) return apiPromise;
22
+ apiPromise = new Promise((resolve) => {
23
+ const prev = w.onYouTubeIframeAPIReady;
24
+ w.onYouTubeIframeAPIReady = () => {
25
+ prev?.();
26
+ if (w.YT) resolve(w.YT);
27
+ };
28
+ if (!document.querySelector(`script[src="${IFRAME_API_SRC}"]`)) {
29
+ const script = document.createElement("script");
30
+ script.src = IFRAME_API_SRC;
31
+ script.async = true;
32
+ document.head.appendChild(script);
33
+ }
34
+ });
35
+ return apiPromise;
36
+ }
37
+ function readyYT() {
38
+ if (typeof window === "undefined") return null;
39
+ const yt = window.YT;
40
+ return yt && typeof yt.Player === "function" ? yt : null;
41
+ }
42
+ function createYouTubeProvider(opts) {
43
+ const initialId = parseYouTubeId(opts.videoId);
44
+ let player = null;
45
+ let destroyed = false;
46
+ let ready = false;
47
+ let ticker;
48
+ let desiredRate = opts.defaultRate ?? 1;
49
+ let captionModule = CAPTION_MODULES[0];
50
+ let captionsSig = "";
51
+ let state = {
52
+ ...defaultState(),
53
+ rate: desiredRate,
54
+ muted: opts.muted ?? false,
55
+ capabilities: {
56
+ canSetQuality: false,
57
+ hasStoryboard: false,
58
+ canPiP: false,
59
+ canFullscreen: true,
60
+ canSetRate: true,
61
+ hasTextTracks: false
62
+ }
63
+ };
64
+ const listeners = /* @__PURE__ */ new Set();
65
+ const emit = () => listeners.forEach((l) => l());
66
+ const patch = (p) => {
67
+ state = {
68
+ ...state,
69
+ ...p
70
+ };
71
+ emit();
72
+ };
73
+ const onFullscreenChange = () => patch({ fullscreen: document.fullscreenElement != null });
74
+ const syncFromPlayer = () => {
75
+ if (!player || !ready) return;
76
+ if (player.getPlaybackRate() !== desiredRate) player.setPlaybackRate(desiredRate);
77
+ const ps = player.getPlayerState();
78
+ const duration = player.getDuration() || 0;
79
+ const loaded = player.getVideoLoadedFraction() || 0;
80
+ patch({
81
+ paused: ps !== PLAYING && ps !== BUFFERING,
82
+ ended: ps === ENDED,
83
+ currentTime: player.getCurrentTime() || 0,
84
+ duration,
85
+ buffered: duration > 0 ? [[0, loaded * duration]] : [],
86
+ rate: desiredRate,
87
+ volume: (player.getVolume() || 0) / 100,
88
+ muted: player.isMuted(),
89
+ readyState: 4
90
+ });
91
+ syncCaptions();
92
+ };
93
+ const syncCaptions = () => {
94
+ if (!player) return;
95
+ let list = [];
96
+ for (const mod of CAPTION_MODULES) try {
97
+ const got = player.getOption(mod, "tracklist");
98
+ if (Array.isArray(got)) {
99
+ list = got;
100
+ captionModule = mod;
101
+ if (got.length) break;
102
+ }
103
+ } catch {}
104
+ const tracks = list.map((t) => ({
105
+ id: t.languageCode,
106
+ kind: "captions",
107
+ label: t.displayName || t.languageCode,
108
+ lang: t.languageCode,
109
+ mode: state.activeTextTrackId === t.languageCode ? "showing" : "disabled"
110
+ }));
111
+ const sig = tracks.map((t) => `${t.id}:${t.mode}`).join("|");
112
+ if (sig === captionsSig) return;
113
+ captionsSig = sig;
114
+ patch({
115
+ textTracks: tracks,
116
+ capabilities: {
117
+ ...state.capabilities,
118
+ hasTextTracks: tracks.length > 0
119
+ }
120
+ });
121
+ };
122
+ const setSessionMetadata = (title) => {
123
+ if (typeof navigator === "undefined" || !("mediaSession" in navigator)) return;
124
+ if (typeof MediaMetadata === "undefined") return;
125
+ try {
126
+ navigator.mediaSession.metadata = new MediaMetadata({ title });
127
+ } catch {}
128
+ };
129
+ const startTicker = () => {
130
+ if (ticker == null) ticker = setInterval(syncFromPlayer, 250);
131
+ };
132
+ const actions = {
133
+ play: () => player?.playVideo(),
134
+ pause: () => player?.pauseVideo(),
135
+ seek: (t) => player?.seekTo(t, true),
136
+ setRate: (r) => {
137
+ desiredRate = r;
138
+ player?.setPlaybackRate(r);
139
+ patch({ rate: r });
140
+ },
141
+ setVolume: (v) => player?.setVolume(Math.min(100, Math.max(0, v * 100))),
142
+ setMuted: (m) => {
143
+ if (m) player?.mute();
144
+ else player?.unMute();
145
+ patch({ muted: m });
146
+ },
147
+ setQuality: () => {},
148
+ setTextTrack: (id) => {
149
+ patch({ activeTextTrackId: id });
150
+ try {
151
+ player?.setOption(captionModule, "track", id == null ? {} : { languageCode: id });
152
+ } catch {}
153
+ syncCaptions();
154
+ },
155
+ enterFullscreen: (wrapper) => {
156
+ if (wrapper.requestFullscreen) wrapper.requestFullscreen();
157
+ },
158
+ exitFullscreen: () => {
159
+ if (document.fullscreenElement) document.exitFullscreen?.();
160
+ },
161
+ enterPiP: () => {},
162
+ exitPiP: () => {}
163
+ };
164
+ const createPlayer = (yt, host) => {
165
+ player = new yt.Player(host, {
166
+ videoId: initialId,
167
+ playerVars: {
168
+ controls: 0,
169
+ playsinline: 1,
170
+ rel: 0,
171
+ modestbranding: 1,
172
+ disablekb: 1,
173
+ autoplay: opts.autoPlay ? 1 : 0,
174
+ mute: opts.muted ? 1 : 0,
175
+ loop: opts.loop ? 1 : 0,
176
+ ...opts.loop ? { playlist: initialId } : {}
177
+ },
178
+ events: {
179
+ onReady: (e) => {
180
+ player = e.target;
181
+ ready = true;
182
+ player.setPlaybackRate(desiredRate);
183
+ if (opts.muted) player.mute();
184
+ for (const mod of CAPTION_MODULES) try {
185
+ player.loadModule(mod);
186
+ } catch {}
187
+ setSessionMetadata(opts.metadata?.videoTitle ?? "Video");
188
+ syncFromPlayer();
189
+ startTicker();
190
+ },
191
+ onStateChange: syncFromPlayer,
192
+ onError: (e) => patch({ error: {
193
+ code: e.data ?? 0,
194
+ message: "YouTube playback error"
195
+ } })
196
+ }
197
+ });
198
+ };
199
+ return {
200
+ mount(container) {
201
+ const host = document.createElement("div");
202
+ container.appendChild(host);
203
+ document.addEventListener("fullscreenchange", onFullscreenChange);
204
+ const yt = readyYT();
205
+ if (yt) createPlayer(yt, host);
206
+ else loadYouTubeAPI().then((loaded) => {
207
+ if (destroyed) return;
208
+ if (host.isConnected) createPlayer(loaded, host);
209
+ });
210
+ },
211
+ swapSource(next) {
212
+ if (!player || !ready || next.src == null) return;
213
+ player.loadVideoById(parseYouTubeId(next.src));
214
+ if (next.metadata?.videoTitle != null) setSessionMetadata(next.metadata.videoTitle);
215
+ player.setPlaybackRate(desiredRate);
216
+ patch({
217
+ currentTime: 0,
218
+ duration: 0,
219
+ ended: false,
220
+ seeking: false,
221
+ error: null
222
+ });
223
+ },
224
+ getState: () => state,
225
+ subscribe: (l) => {
226
+ listeners.add(l);
227
+ return () => listeners.delete(l);
228
+ },
229
+ actions,
230
+ destroy() {
231
+ destroyed = true;
232
+ ready = false;
233
+ document.removeEventListener("fullscreenchange", onFullscreenChange);
234
+ if (ticker != null) clearInterval(ticker);
235
+ ticker = void 0;
236
+ try {
237
+ player?.destroy();
238
+ } catch {}
239
+ player = null;
240
+ listeners.clear();
241
+ }
242
+ };
243
+ }
244
+ //#endregion
245
+ //#region src/youtube/youtube-player.tsx
246
+ /**
247
+ * kino's glass chrome over a YouTube video, backed by the YouTube IFrame Player
248
+ * API. Pass a video id or any watch / youtu.be / embed / shorts URL.
249
+ *
250
+ * Only `videoId` and `metadata.videoTitle` are reactive (they flow through
251
+ * `swapSource`). `autoPlay`, `muted`, `loop`, and `defaultRate` are read once
252
+ * when the provider is created — changing them later is a no-op. Remount (e.g.
253
+ * via `key`) if you need them to change.
254
+ *
255
+ * The IFrame API can't expose quality or picture-in-picture, so those controls
256
+ * hide themselves automatically. Captions work through the API and are rendered
257
+ * by YouTube inside the embed.
258
+ *
259
+ * Per YouTube's API terms, kino doesn't obscure the player: YouTube shows its
260
+ * own thumbnail, play button, title, and logo before playback and while paused.
261
+ * kino's controls sit alongside them.
262
+ */
263
+ function YouTubePlayer({ accentColor, theme, className, placeholder, children, ...opts }) {
264
+ const providerRef = useRef(null);
265
+ if (providerRef.current === null) providerRef.current = createYouTubeProvider(opts);
266
+ const provider = providerRef.current;
267
+ const mountedRef = useRef(false);
268
+ useEffect(() => {
269
+ if (!mountedRef.current) {
270
+ mountedRef.current = true;
271
+ return;
272
+ }
273
+ provider.swapSource?.({
274
+ src: opts.videoId,
275
+ metadata: opts.metadata
276
+ });
277
+ }, [opts.videoId, opts.metadata?.videoTitle]);
278
+ return /* @__PURE__ */ jsxs(Player, {
279
+ provider,
280
+ accentColor,
281
+ theme,
282
+ className,
283
+ placeholder,
284
+ children: [
285
+ /* @__PURE__ */ jsx(IdleOverlay, {}),
286
+ /* @__PURE__ */ jsx(Captions, {}),
287
+ /* @__PURE__ */ jsx(ControlBar, {}),
288
+ children
289
+ ]
290
+ });
291
+ }
292
+ //#endregion
293
+ export { YouTubePlayer, createYouTubeProvider, parseYouTubeId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@karnstack/kino",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Themeable React video player with pluggable providers.",
5
5
  "license": "MIT",
6
6
  "author": "Karn",
@@ -17,6 +17,7 @@
17
17
  "player",
18
18
  "react",
19
19
  "mux",
20
+ "youtube",
20
21
  "hls",
21
22
  "video-player"
22
23
  ],
@@ -44,6 +45,10 @@
44
45
  "types": "./dist/native.d.ts",
45
46
  "import": "./dist/native.js"
46
47
  },
48
+ "./youtube": {
49
+ "types": "./dist/youtube.d.ts",
50
+ "import": "./dist/youtube.js"
51
+ },
47
52
  "./styles.css": "./dist/styles.css"
48
53
  },
49
54
  "peerDependencies": {