{"$schema":"https:\/\/ui.particle.academy\/schema\/registry-item.json","name":"media-embed","type":"registry:ui","title":"MediaEmbed","description":"YouTube, Vimeo, Twitch or a registered provider in a sandboxed iframe; a poster until played, so nothing loads from the provider before that.","package":"react-fancy","dependencies":["tailwind-merge","lucide-react"],"registryDependencies":["icon","channel-player","streaming-audio"],"files":[{"path":"components\/fancy\/media-embed\/MediaEmbed.tsx","content":"import { forwardRef, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"..\/lib\/utils\/cn\";\nimport { fillLabel } from \"..\/lib\/utils\/label-template\";\nimport { getEmbedProvider } from \"..\/lib\/utils\/media-sources\";\nimport { Icon } from \"..\/icon\/Icon\";\nimport { FOCUS_RING, SURFACE, TEXT, TEXT_MUTED } from \"..\/channel-player\/media-classes\";\nimport type { MediaEmbedLabels, MediaEmbedProps } from \".\/MediaEmbed.types\";\n\nconst DEFAULT_LABELS: MediaEmbedLabels = {\n  play: \"Play {title} on {provider}\",\n  unsupported: \"This video can't be embedded.\",\n};\n\n\/** The iframe may run the provider's player and nothing more: no top navigation, no forms. *\/\nconst SANDBOX = \"allow-scripts allow-same-origin allow-presentation allow-popups\";\n\n\/**\n * A provider's own player (YouTube, Vimeo, Twitch, or one a host registers\n * with `registerEmbedProvider`). Until it is first played it is a poster with a\n * play button, so a page that shows an embed makes no request to the provider\n * on load.\n *\/\nexport const MediaEmbed = forwardRef<HTMLDivElement, MediaEmbedProps>(function MediaEmbed(\n  { source, playing, onPlayingChange, title, poster, onError, labels: labelsProp, className, ...rest },\n  ref,\n) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp };\n  const provider = getEmbedProvider(source.provider);\n  const name = title ?? provider?.title ?? source.provider;\n  const key = `${source.provider}:${source.id}`;\n\n  const iframe = useRef<HTMLIFrameElement | null>(null);\n  \/** The URL the player was loaded with; fixed once loaded, so pausing never reloads the frame. *\/\n  const [loadedUrl, setLoadedUrl] = useState<{ key: string; url: string } | null>(null);\n  const [failed, setFailed] = useState<string | null>(null);\n  const latest = useRef({ onError, source, provider });\n  latest.current = { onError, source, provider };\n\n  \/\/ Validate (with the real hostname: Twitch needs it) and load on first play.\n  useEffect(() => {\n    const { source: s, provider: p } = latest.current;\n    const hostname = typeof window === \"undefined\" ? \"\" : window.location.hostname;\n    const probe = p?.embedUrl(s, { hostname, autoplay: false }) ?? null;\n    if (!probe) {\n      setLoadedUrl(null);\n      if (failed !== key) {\n        setFailed(key);\n        latest.current.onError?.();\n      }\n      return;\n    }\n    setFailed(null);\n    if (playing && (loadedUrl === null || loadedUrl.key !== key)) {\n      const url = p!.embedUrl(s, { hostname, autoplay: true });\n      if (url) setLoadedUrl({ key, url });\n    }\n  }, [key, playing]);\n\n  \/\/ Drive the loaded player.\n  const commanded = useRef<boolean | null>(null);\n  useEffect(() => {\n    const frame = iframe.current;\n    if (!loadedUrl || !frame) {\n      commanded.current = null;\n      return;\n    }\n    if (commanded.current === null) {\n      \/\/ Just loaded, autoplaying: nothing to send.\n      commanded.current = playing;\n      return;\n    }\n    if (commanded.current !== playing) {\n      commanded.current = playing;\n      latest.current.provider?.command?.(frame, playing ? \"play\" : \"pause\");\n    }\n  }, [playing, loadedUrl]);\n\n  const isFailed = failed === key;\n  const loaded = loadedUrl !== null && loadedUrl.key === key && !isFailed;\n\n  return (\n    <div\n      ref={ref}\n      data-react-fancy-media-embed=\"\"\n      data-embed-provider={source.provider}\n      data-embed-loaded={loaded ? \"true\" : \"false\"}\n      className={cn(\"relative aspect-video w-full overflow-hidden rounded-lg border\", SURFACE, className)}\n      {...rest}\n    >\n      {isFailed ? (\n        <p data-embed-error=\"\" className={cn(\"flex h-full items-center justify-center p-4 text-sm\", TEXT_MUTED)}>\n          {labels.unsupported}\n        <\/p>\n      ) : loaded ? (\n        <iframe\n          ref={iframe}\n          src={loadedUrl.url}\n          title={name}\n          allow={provider?.allow}\n          sandbox={SANDBOX}\n          referrerPolicy=\"strict-origin-when-cross-origin\"\n          allowFullScreen\n          className=\"absolute inset-0 h-full w-full border-0\"\n        \/>\n      ) : (\n        <button\n          type=\"button\"\n          data-embed-poster=\"\"\n          aria-label={fillLabel(labels.play, { title: name, provider: provider?.title ?? source.provider })}\n          onClick={() => onPlayingChange?.(true)}\n          className={cn(\"absolute inset-0 flex h-full w-full items-center justify-center\", FOCUS_RING)}\n        >\n          {poster && <img src={poster} alt=\"\" className=\"absolute inset-0 h-full w-full object-cover\" \/>}\n          <span className={cn(\"relative flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium\", SURFACE, TEXT)}>\n            <Icon name=\"play\" size=\"sm\" \/>\n            {name}\n          <\/span>\n        <\/button>\n      )}\n    <\/div>\n  );\n});\n\nMediaEmbed.displayName = \"MediaEmbed\";\n","type":"registry:ui","target":"components\/fancy\/media-embed\/MediaEmbed.tsx"},{"path":"components\/fancy\/media-embed\/MediaEmbed.types.ts","content":"import type { HTMLAttributes } from \"react\";\nimport type { EmbedSource } from \"..\/lib\/utils\/media-channel\";\n\nexport interface MediaEmbedLabels {\n  \/** The poster's button name. Slots: `{title}`, `{provider}`. *\/\n  play: string;\n  \/** Unknown provider, or an id the provider does not accept. *\/\n  unsupported: string;\n}\n\nexport interface MediaEmbedProps extends Omit<HTMLAttributes<HTMLDivElement>, \"onError\"> {\n  source: EmbedSource;\n  \/**\n   * The provider's player is not loaded (no request to the provider at all)\n   * until this is first true; after that, play \/ pause go through the\n   * provider's API where it has one (YouTube, Vimeo).\n   *\/\n  playing: boolean;\n  \/** The poster asks to play. *\/\n  onPlayingChange?: (playing: boolean) => void;\n  \/** The iframe title and the poster's name. Default: the provider's name. *\/\n  title?: string;\n  \/** Shown on the poster before the player loads. Should be self-hosted. *\/\n  poster?: string;\n  onError?: () => void;\n  labels?: Partial<MediaEmbedLabels>;\n}\n","type":"registry:ui","target":"components\/fancy\/media-embed\/MediaEmbed.types.ts"},{"path":"components\/fancy\/media-embed\/index.ts","content":"export { MediaEmbed } from \".\/MediaEmbed\";\nexport type { MediaEmbedProps, MediaEmbedLabels } from \".\/MediaEmbed.types\";\n","type":"registry:ui","target":"components\/fancy\/media-embed\/index.ts"},{"path":"components\/fancy\/lib\/utils\/cn.ts","content":"import { twMerge } from \"tailwind-merge\";\n\n\/**\n * A class value: a string, a number, a conditional map, an array of any of\n * those, or nothing. Mirrors what `clsx` accepted, because every component in\n * this package already passes these shapes.\n *\/\nexport type ClassValue =\n  | string\n  | number\n  | bigint\n  | null\n  | undefined\n  | false\n  | ClassDictionary\n  | ClassValue[];\n\ntype ClassDictionary = Record<string, unknown>;\n\n\/**\n * Flatten class values into a space-separated string.\n *\n * This was `clsx` until 2026-08-19. It is roughly twenty lines of logic, it\n * shipped as a RUNTIME dependency to every consumer of this package, and its\n * last commit was 801 days old \u2014 so it fell to the rule that third-party code\n * must be both approved and actively maintained. Owning it costs less than\n * carrying it.\n *\n * `tailwind-merge` deliberately stays: deciding which of two conflicting\n * Tailwind utilities wins requires modelling the entire utility space, which is\n * emphatically not twenty lines, and it is actively maintained.\n *\n * Falsy values are dropped \u2014 including `0` and `\"\"`, which is what `clsx` did\n * and what `tests\/cn.test.ts` pins. A truthy number is kept, because digits are\n * legal class names. `bigint` is admitted because clsx's signature did and\n * the compiler proved it reachable from two call sites here.\n *\/\nfunction flatten(value: ClassValue): string {\n  if (!value) return \"\";\n\n  if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"bigint\") {\n    return String(value);\n  }\n\n  if (Array.isArray(value)) {\n    let out = \"\";\n    for (const item of value) {\n      const part = flatten(item);\n      if (part) out = out ? `${out} ${part}` : part;\n    }\n    return out;\n  }\n\n  let out = \"\";\n  for (const key in value) {\n    if (value[key]) out = out ? `${out} ${key}` : key;\n  }\n  return out;\n}\n\nexport function cn(...inputs: ClassValue[]): string {\n  return twMerge(flatten(inputs));\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/cn.ts"},{"path":"components\/fancy\/lib\/utils\/label-template.ts","content":"\/**\n * Fill a label template's `{name}` slots: `\"Digit {n} of {total}\"`,\n * `\"Open {host}\"`. Single braces, for translatable labels only; a slot with no\n * value stays as written. Literal replacement, never evaluated.\n *\/\nexport function fillLabel(template: string, values: Record<string, string | number>): string {\n  return template.replace(\/\\{(\\w+)\\}\/g, (whole: string, name: string) =>\n    Object.prototype.hasOwnProperty.call(values, name) ? String(values[name]) : whole,\n  );\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/label-template.ts"},{"path":"components\/fancy\/lib\/utils\/media-sources.ts","content":"import { isPlayableSrc } from \"..\/..\/streaming-audio\/station-src\";\nimport { resolveMediaType } from \".\/media-type\";\nimport type { EmbedSource, ChannelSource } from \".\/media-channel\";\n\n\/**\n * \"Any streaming service\": how a {@link ChannelSource} reaches the screen.\n *\n * Two registries, both extended by the HOST:\n *\n * - **Element adapters** put a source on an `<audio>` \/ `<video>` element. The\n *   built-in one is native only: files, Icecast \/ Shoutcast mounts, and HLS\n *   where the browser plays it itself (Safari, iOS). HLS or DASH elsewhere\n *   needs a library such as hls.js, which react-fancy does not depend on: a\n *   host that wants it registers an adapter around it (see docs\/Channels.md).\n * - **Embed providers** turn `{ provider, id }` into a provider's own iframe\n *   player. YouTube, Vimeo and Twitch are built in; hosts add others.\n *\n * Whatever an adapter or a provider says, a URL that is not `http(s)` (or, for\n * an element, same-origin relative) is never used.\n *\/\n\nexport interface MediaElementAdapter {\n  id: string;\n  \/** Whether this adapter can play `source` on `el`. *\/\n  canPlay(source: ChannelSource, el: HTMLMediaElement): boolean;\n  \/** Put `source` on `el`. Returns the detach, which must stop all network activity. *\/\n  attach(el: HTMLMediaElement, source: ChannelSource): () => void;\n}\n\nconst HLS_MIME = \"application\/vnd.apple.mpegurl\";\n\nfunction urlOf(source: ChannelSource): string | null {\n  return source.type === \"embed\" ? null : source.url;\n}\n\n\/** The stream protocol: declared, else guessed from the URL's extension. *\/\nexport function streamProtocol(source: ChannelSource): \"icecast\" | \"hls\" | \"dash\" {\n  if (source.type === \"stream\" && source.protocol) return source.protocol;\n  const url = urlOf(source) ?? \"\";\n  const path = (url.split(\/[?#]\/, 1)[0] ?? \"\").toLowerCase();\n  if (path.endsWith(\".m3u8\")) return \"hls\";\n  if (path.endsWith(\".mpd\")) return \"dash\";\n  return \"icecast\";\n}\n\n\/** Whether a source shows picture (`<video>`) or not (`<audio>`). *\/\nexport function sourceMedia(source: ChannelSource): \"audio\" | \"video\" {\n  if (source.type === \"embed\") return \"video\";\n  if (source.media) return source.media;\n  if (source.type === \"file\") {\n    return resolveMediaType({ mime: source.mime, src: source.url }) === \"video\" ? \"video\" : \"audio\";\n  }\n  return streamProtocol(source) === \"icecast\" ? \"audio\" : \"video\";\n}\n\nfunction attachBySrc(el: HTMLMediaElement, url: string): () => void {\n  el.setAttribute(\"src\", url);\n  el.load();\n  return () => {\n    try {\n      el.pause();\n    } catch {\n      \/\/ jsdom and some engines throw on pause() of an unloaded element.\n    }\n    el.removeAttribute(\"src\");\n    el.load();\n  };\n}\n\nconst nativeAdapter: MediaElementAdapter = {\n  id: \"native\",\n  canPlay: (s) => s.type === \"file\" || (s.type === \"stream\" && streamProtocol(s) === \"icecast\"),\n  attach: (el, s) => attachBySrc(el, urlOf(s) ?? \"\"),\n};\n\nconst nativeHlsAdapter: MediaElementAdapter = {\n  id: \"native-hls\",\n  canPlay: (s, el) => s.type === \"stream\" && streamProtocol(s) === \"hls\" && canPlayNatively(el, HLS_MIME),\n  attach: (el, s) => attachBySrc(el, urlOf(s) ?? \"\"),\n};\n\nfunction canPlayNatively(el: HTMLMediaElement, mime: string): boolean {\n  try {\n    return typeof el.canPlayType === \"function\" && el.canPlayType(mime) !== \"\";\n  } catch {\n    return false;\n  }\n}\n\nconst BUILT_IN_ADAPTERS = [nativeAdapter, nativeHlsAdapter];\nlet hostAdapters: MediaElementAdapter[] = [];\n\n\/** Add an element adapter. Later registrations are asked first. Returns the unregister. *\/\nexport function registerMediaAdapter(adapter: MediaElementAdapter): () => void {\n  hostAdapters = [adapter, ...hostAdapters];\n  return () => {\n    hostAdapters = hostAdapters.filter((a) => a !== adapter);\n  };\n}\n\n\/** The adapter that will play `source` on `el`, or `null` when none can (or the URL is refused). *\/\nexport function resolveMediaAdapter(source: ChannelSource, el: HTMLMediaElement): MediaElementAdapter | null {\n  const url = urlOf(source);\n  if (url == null || !isPlayableSrc(url)) return null;\n  for (const adapter of [...hostAdapters, ...BUILT_IN_ADAPTERS]) {\n    try {\n      if (adapter.canPlay(source, el)) return adapter;\n    } catch {\n      \/\/ A host adapter that throws in canPlay is skipped, not fatal.\n    }\n  }\n  return null;\n}\n\n\/\/ -- embeds -----------------------------------------------------------------\n\nexport interface EmbedContext {\n  \/** The page's hostname (Twitch requires it as `parent`). Empty during a server render. *\/\n  hostname: string;\n  autoplay: boolean;\n}\n\nexport interface EmbedProvider {\n  id: string;\n  \/** Shown on the poster and used as the iframe title. *\/\n  title: string;\n  \/** The iframe URL, or `null` when the source is not one this provider accepts. Must be `https:`. *\/\n  embedUrl(source: EmbedSource, ctx: EmbedContext): string | null;\n  \/** The iframe `allow` attribute. *\/\n  allow?: string;\n  \/** Play \/ pause the loaded player, where the provider has an API for it. *\/\n  command?(iframe: HTMLIFrameElement, cmd: \"play\" | \"pause\"): void;\n}\n\nconst DEFAULT_ALLOW = \"autoplay; encrypted-media; picture-in-picture; fullscreen\";\n\nfunction post(iframe: HTMLIFrameElement, message: unknown, origin: string) {\n  try {\n    iframe.contentWindow?.postMessage(JSON.stringify(message), origin);\n  } catch {\n    \/\/ A detached frame has no window to post to.\n  }\n}\n\nconst youtube: EmbedProvider = {\n  id: \"youtube\",\n  title: \"YouTube\",\n  embedUrl: (s, ctx) => {\n    if (!\/^[A-Za-z0-9_-]{11}$\/.test(s.id)) return null;\n    return `https:\/\/www.youtube-nocookie.com\/embed\/${s.id}?enablejsapi=1&playsinline=1${ctx.autoplay ? \"&autoplay=1\" : \"\"}`;\n  },\n  allow: DEFAULT_ALLOW,\n  command: (iframe, cmd) =>\n    post(iframe, { event: \"command\", func: cmd === \"play\" ? \"playVideo\" : \"pauseVideo\", args: [] }, \"https:\/\/www.youtube-nocookie.com\"),\n};\n\nconst vimeo: EmbedProvider = {\n  id: \"vimeo\",\n  title: \"Vimeo\",\n  embedUrl: (s, ctx) => (\/^\\d{1,12}$\/.test(s.id) ? `https:\/\/player.vimeo.com\/video\/${s.id}?autoplay=${ctx.autoplay ? 1 : 0}` : null),\n  allow: DEFAULT_ALLOW,\n  command: (iframe, cmd) => post(iframe, { method: cmd }, \"https:\/\/player.vimeo.com\"),\n};\n\n\/** Twitch's embed has no postMessage control without Twitch's own script, so it is not driven. *\/\nconst twitch: EmbedProvider = {\n  id: \"twitch\",\n  title: \"Twitch\",\n  embedUrl: (s, ctx) => {\n    if (!\/^[A-Za-z0-9_]{1,25}$\/.test(s.id)) return null;\n    if (!\/^[A-Za-z0-9.-]+$\/.test(ctx.hostname)) return null;\n    return `https:\/\/player.twitch.tv\/?channel=${s.id}&parent=${ctx.hostname}&autoplay=${ctx.autoplay ? \"true\" : \"false\"}`;\n  },\n  allow: DEFAULT_ALLOW,\n};\n\nconst BUILT_IN_PROVIDERS: Record<string, EmbedProvider> = { youtube, vimeo, twitch };\nlet hostProviders: EmbedProvider[] = [];\n\n\/** Add an embed provider. One with a built-in's id replaces it until removed. Returns the unregister. *\/\nexport function registerEmbedProvider(provider: EmbedProvider): () => void {\n  hostProviders = [provider, ...hostProviders];\n  return () => {\n    hostProviders = hostProviders.filter((p) => p !== provider);\n  };\n}\n\nfunction httpsOnly(url: string | null): string | null {\n  if (typeof url !== \"string\") return null;\n  try {\n    return new URL(url).protocol === \"https:\" && !\/[\\u0000-\\u001F\\u007F\\\\]\/.test(url) ? url : null;\n  } catch {\n    return null;\n  }\n}\n\n\/** The provider for an id, with its URL held to `https:`. *\/\nexport function getEmbedProvider(id: string): EmbedProvider | undefined {\n  const provider = hostProviders.find((p) => p.id === id) ?? BUILT_IN_PROVIDERS[id];\n  if (!provider) return undefined;\n  return { ...provider, embedUrl: (s, ctx) => httpsOnly(provider.embedUrl(s, ctx)) };\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/media-sources.ts"},{"path":"components\/fancy\/lib\/utils\/media-channel.ts","content":"\/**\n * The channel model: a channel is a single track, a playlist of tracks, or a\n * live stream from any service. Every shape is plain JSON, so a host, a server\n * or an agent can emit it.\n *\n * Every channel component (ChannelPlayer, ChannelGuide, Playlist, MediaQueue)\n * is controlled through ONE {@link ChannelPlayerValue}, and every move they\n * make goes through the pure functions below. An agent bridge calls the same\n * functions, so \"next\", \"shuffle\" or \"remove\" cannot mean one thing in the UI\n * and another to an agent.\n *\/\n\n\/** Where a track or a live channel plays from. *\/\nexport type ChannelSource =\n  \/** A finite file: MP3, M4A, MP4, WebM... Seekable. *\/\n  | { type: \"file\"; url: string; mime?: string; media?: \"audio\" | \"video\" }\n  \/**\n   * An endless stream. `protocol` defaults by guess: `.m3u8` is HLS, `.mpd` is\n   * DASH, anything else is an Icecast \/ Shoutcast mount.\n   *\/\n  | { type: \"stream\"; url: string; protocol?: \"icecast\" | \"hls\" | \"dash\"; media?: \"audio\" | \"video\" }\n  \/** A provider's own player in an iframe: `youtube`, `vimeo`, `twitch`, or one a host registers. *\/\n  | { type: \"embed\"; provider: string; id: string; params?: Record<string, string> };\n\nexport type EmbedSource = Extract<ChannelSource, { type: \"embed\" }>;\n\nexport interface MediaTrack {\n  \/** Stable identity: `value.trackId`, `data-track-id`. Unique within a channel. *\/\n  id: string;\n  title: string;\n  artist?: string;\n  album?: string;\n  \/** Seconds, when known up front (shown before the file loads). *\/\n  duration?: number;\n  \/** Image URL. *\/\n  artwork?: string;\n  source: ChannelSource;\n}\n\nexport type LiveStatus = \"live\" | \"offline\" | \"starting\" | \"ended\";\n\nexport interface ChannelBase {\n  \/** Stable identity: `value.channelId`, `data-channel-id`. *\/\n  id: string;\n  name: string;\n  description?: string;\n  artwork?: string;\n  tags?: string[];\n}\n\nexport type TrackChannel = ChannelBase & { kind: \"track\"; track: MediaTrack };\nexport type PlaylistChannel = ChannelBase & { kind: \"playlist\"; tracks: MediaTrack[] };\nexport type LiveChannel = ChannelBase & {\n  kind: \"live\";\n  source: ChannelSource;\n  \/** Supplied by the host (a provider API, an Icecast status poll). Default `\"live\"`. *\/\n  status?: LiveStatus;\n  \/** What is on air, supplied by the host. *\/\n  nowPlaying?: string;\n};\n\nexport type Channel = TrackChannel | PlaylistChannel | LiveChannel;\nexport type ChannelKind = Channel[\"kind\"];\n\nexport type RepeatMode = \"off\" | \"all\" | \"one\";\n\n\/** The whole state of a channel UI, in one JSON object. *\/\nexport interface ChannelPlayerValue {\n  channelId: string | null;\n  \/** The current track: within a playlist, the track channel's own track, or `null` on live. *\/\n  trackId: string | null;\n  \/** Whether the host wants media playing. Components set it back to `false` when the browser refuses. *\/\n  playing: boolean;\n  \/** Seconds into the current track. Ignored on live. Moving it seeks. *\/\n  position: number;\n  \/** 0..1 *\/\n  volume: number;\n  muted: boolean;\n  shuffle: boolean;\n  repeat: RepeatMode;\n  \/** The shuffled play order (track ids), or `null` for playlist order. *\/\n  order: string[] | null;\n}\n\n\/** A playlist edit held for a person to confirm (an agent proposes, a human accepts). *\/\nexport type PendingQueueEdit =\n  | { id: string; op: \"remove\"; trackId: string }\n  | { id: string; op: \"clear\" }\n  | { id: string; op: \"replace\"; tracks: MediaTrack[] };\n\ntype Random = () => number;\n\n\/** Seconds into a track before \"previous\" restarts it instead of going back. *\/\nconst RESTART_THRESHOLD = 3;\n\nexport function createChannelValue(patch: Partial<ChannelPlayerValue> = {}): ChannelPlayerValue {\n  return {\n    channelId: null,\n    trackId: null,\n    playing: false,\n    position: 0,\n    volume: 1,\n    muted: false,\n    shuffle: false,\n    repeat: \"off\",\n    order: null,\n    ...patch,\n  };\n}\n\nexport function findChannel(channels: readonly Channel[], id: string | null | undefined): Channel | undefined {\n  return id == null ? undefined : channels.find((c) => c.id === id);\n}\n\n\/** The tracks a channel plays: one, the list, or none for live. *\/\nexport function channelTracks(channel: Channel | undefined): MediaTrack[] {\n  if (!channel) return [];\n  if (channel.kind === \"track\") return [channel.track];\n  if (channel.kind === \"playlist\") return channel.tracks;\n  return [];\n}\n\n\/** Fisher-Yates over a copy; `first`, when given and present, leads. *\/\nexport function shuffleIds(ids: readonly string[], random: Random = Math.random, first?: string | null): string[] {\n  const out = ids.filter((id) => id !== first);\n  for (let i = out.length - 1; i > 0; i--) {\n    const j = Math.min(i, Math.floor(random() * (i + 1)));\n    [out[i], out[j]] = [out[j]!, out[i]!];\n  }\n  return first != null && ids.includes(first) ? [first, ...out] : out;\n}\n\n\/**\n * The order tracks play in. A held shuffle order is used only while it names\n * exactly the channel's tracks; a stale one (tracks added or removed since)\n * is repaired: unknown ids dropped, missing ones appended.\n *\/\nexport function playOrder(channel: Channel | undefined, value: ChannelPlayerValue): string[] {\n  const ids = channelTracks(channel).map((t) => t.id);\n  if (!value.shuffle || !value.order) return ids;\n  const kept = value.order.filter((id) => ids.includes(id));\n  return [...kept, ...ids.filter((id) => !kept.includes(id))];\n}\n\nexport function currentTrack(channel: Channel | undefined, value: ChannelPlayerValue): MediaTrack | undefined {\n  if (value.trackId == null) return undefined;\n  return channelTracks(channel).find((t) => t.id === value.trackId);\n}\n\n\/** Tune to a channel: its first track (in shuffle order when shuffling), from the start. *\/\nexport function selectChannel(\n  value: ChannelPlayerValue,\n  channel: Channel | undefined,\n  random: Random = Math.random,\n): ChannelPlayerValue {\n  if (!channel) return { ...value, channelId: null, trackId: null, position: 0, order: null };\n  const ids = channelTracks(channel).map((t) => t.id);\n  const order = value.shuffle && channel.kind === \"playlist\" ? shuffleIds(ids, random) : null;\n  return {\n    ...value,\n    channelId: channel.id,\n    trackId: (order ?? ids)[0] ?? null,\n    position: 0,\n    order,\n  };\n}\n\nexport function selectTrack(value: ChannelPlayerValue, trackId: string): ChannelPlayerValue {\n  return { ...value, trackId, position: 0 };\n}\n\nexport function toggleShuffle(\n  value: ChannelPlayerValue,\n  channel: Channel | undefined,\n  random: Random = Math.random,\n): ChannelPlayerValue {\n  if (value.shuffle) return { ...value, shuffle: false, order: null };\n  const ids = channelTracks(channel).map((t) => t.id);\n  return { ...value, shuffle: true, order: shuffleIds(ids, random, value.trackId) };\n}\n\nexport function cycleRepeat(value: ChannelPlayerValue): ChannelPlayerValue {\n  const next: Record<RepeatMode, RepeatMode> = { off: \"all\", all: \"one\", one: \"off\" };\n  return { ...value, repeat: next[value.repeat] };\n}\n\n\/** The next track by hand. At the end: wraps with repeat all, otherwise nothing changes. *\/\nexport function nextTrack(value: ChannelPlayerValue, channel: Channel | undefined): ChannelPlayerValue {\n  const order = playOrder(channel, value);\n  if (order.length === 0) return value;\n  const at = value.trackId == null ? -1 : order.indexOf(value.trackId);\n  if (at < order.length - 1) return selectTrack(value, order[at + 1]!);\n  return value.repeat === \"all\" ? selectTrack(value, order[0]!) : value;\n}\n\n\/** Restart a track more than 3s in; otherwise the one before (wrapping with repeat all). *\/\nexport function previousTrack(value: ChannelPlayerValue, channel: Channel | undefined): ChannelPlayerValue {\n  const order = playOrder(channel, value);\n  if (order.length === 0) return value;\n  if (value.position > RESTART_THRESHOLD) return { ...value, position: 0 };\n  const at = value.trackId == null ? 0 : order.indexOf(value.trackId);\n  if (at > 0) return selectTrack(value, order[at - 1]!);\n  if (value.repeat === \"all\") return selectTrack(value, order[order.length - 1]!);\n  return { ...value, position: 0 };\n}\n\n\/** What a track finishing does: replay, advance, wrap, or stop. *\/\nexport function trackEnded(value: ChannelPlayerValue, channel: Channel | undefined): ChannelPlayerValue {\n  const order = playOrder(channel, value);\n  if (order.length === 0) return { ...value, playing: false, position: 0 };\n  if (value.repeat === \"one\" || (order.length === 1 && value.repeat === \"all\")) return { ...value, position: 0 };\n  const at = value.trackId == null ? -1 : order.indexOf(value.trackId);\n  if (at < order.length - 1) return selectTrack(value, order[at + 1]!);\n  if (value.repeat === \"all\") return selectTrack(value, order[0]!);\n  return { ...value, playing: false, position: 0 };\n}\n\n\/** What plays after the current track, in play order (wrapping with repeat all). *\/\nexport function upNext(channel: Channel | undefined, value: ChannelPlayerValue): MediaTrack[] {\n  const tracks = channelTracks(channel);\n  const order = playOrder(channel, value);\n  const at = value.trackId == null ? -1 : order.indexOf(value.trackId);\n  const after = order.slice(at + 1);\n  const ids = value.repeat === \"all\" && at >= 0 ? [...after, ...order.slice(0, at)] : after;\n  return ids.map((id) => tracks.find((t) => t.id === id)!).filter(Boolean);\n}\n\nexport function moveTrack(tracks: readonly MediaTrack[], trackId: string, toIndex: number): MediaTrack[] {\n  const from = tracks.findIndex((t) => t.id === trackId);\n  if (from < 0) return [...tracks];\n  const out = tracks.filter((t) => t.id !== trackId);\n  const to = Math.max(0, Math.min(out.length, Math.floor(toIndex)));\n  out.splice(to, 0, tracks[from]!);\n  return out;\n}\n\n\/** Add a track (at the end, or at `index`). A duplicate id is refused: the same array comes back. *\/\nexport function addTrack<T extends readonly MediaTrack[]>(tracks: T, track: MediaTrack, index?: number): T | MediaTrack[] {\n  if (tracks.some((t) => t.id === track.id)) return tracks;\n  const out = [...tracks];\n  out.splice(index == null ? out.length : Math.max(0, Math.min(out.length, index)), 0, track);\n  return out;\n}\n\nexport function removeTrack(tracks: readonly MediaTrack[], trackId: string): MediaTrack[] {\n  return tracks.filter((t) => t.id !== trackId);\n}\n\nexport function applyQueueEdit(tracks: readonly MediaTrack[], edit: PendingQueueEdit): MediaTrack[] {\n  if (edit.op === \"remove\") return removeTrack(tracks, edit.trackId);\n  if (edit.op === \"clear\") return [];\n  return [...edit.tracks];\n}\n\n\/**\n * Bring a value back in step after a channel's tracks changed. A current track\n * that was removed gives way to the one that took its place (or the first);\n * an emptied channel stops. A shuffle order keeps its sequence, drops removed\n * ids and appends added ones. Another channel's value comes back untouched.\n *\/\nexport function reconcileValue(\n  value: ChannelPlayerValue,\n  channel: Channel,\n  previous?: Channel,\n): ChannelPlayerValue {\n  if (value.channelId !== channel.id) return value;\n  const ids = channelTracks(channel).map((t) => t.id);\n  const order = value.shuffle && value.order ? playOrder(channel, value) : null;\n  const sameOrder =\n    order === value.order ||\n    (order !== null && value.order !== null && order.length === value.order.length && order.every((id, i) => id === value.order![i]));\n  if (value.trackId != null && ids.includes(value.trackId)) {\n    return sameOrder ? value : { ...value, order };\n  }\n  if (ids.length === 0) return { ...value, trackId: null, playing: false, position: 0, order: value.shuffle ? [] : null };\n  \/\/ The first survivor after the removed track, in the order that was playing\n  \/\/ (known from `previous`, or from a held shuffle order); else the first.\n  const before = previous ? playOrder(previous, value) : (value.order ?? []);\n  const oldIndex = value.trackId == null ? -1 : before.indexOf(value.trackId);\n  const survivor = oldIndex >= 0 ? before.slice(oldIndex + 1).find((id) => ids.includes(id)) : undefined;\n  return { ...value, trackId: survivor ?? (order ?? ids)[0]!, position: 0, order };\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/media-channel.ts"},{"path":"components\/fancy\/lib\/utils\/media-type.ts","content":"\/**\n * Resolve what kind of media a source is, from its MIME type (preferred) or its\n * URL \u2014 a file extension, or the type embedded in a `data:` URI.\n *\n * Shared by `<MediaViewer>` to pick the right per-type viewer, and exported so\n * downstream packages (e.g. fancy-code's file viewer) can make the same\n * text-vs-media decision without re-deriving the table.\n *\/\n\nexport type MediaKind = \"image\" | \"video\" | \"audio\" | \"pdf\" | \"unknown\";\n\nexport interface ResolveMediaTypeInput {\n  \/** MIME type \u2014 preferred when known (e.g. `\"image\/png\"`, `\"video\/mp4\"`). *\/\n  mime?: string | null;\n  \/**\n   * Source URL \u2014 used to sniff the kind from a file extension, or from the type\n   * embedded in a `data:` URI, when no `mime` is given. `http(s):` \/ `data:` \/\n   * `blob:` are all accepted (a bare `blob:` URL carries no type, so pass\n   * `mime` alongside it).\n   *\/\n  src?: string | null;\n}\n\nconst IMAGE_EXTS = new Set([\n  \"png\", \"jpg\", \"jpeg\", \"jfif\", \"pjpeg\", \"gif\", \"webp\", \"avif\", \"bmp\", \"ico\",\n  \"cur\", \"svg\", \"svgz\", \"apng\", \"tif\", \"tiff\", \"heic\", \"heif\",\n]);\nconst VIDEO_EXTS = new Set([\n  \"mp4\", \"m4v\", \"webm\", \"ogv\", \"ogm\", \"mov\", \"mkv\", \"avi\", \"wmv\", \"flv\", \"3gp\",\n  \"3g2\", \"mpg\", \"mpeg\",\n]);\nconst AUDIO_EXTS = new Set([\n  \"mp3\", \"wav\", \"wave\", \"ogg\", \"oga\", \"m4a\", \"m4b\", \"aac\", \"flac\", \"opus\",\n  \"weba\", \"mid\", \"midi\", \"aiff\", \"aif\",\n]);\n\n\/** Map a (possibly parameterized) MIME type to a media kind. *\/\nfunction mimeToKind(mime: string): MediaKind {\n  \/\/ Strip any parameters (`; charset=\u2026`) and normalize.\n  const m = mime.toLowerCase().split(\";\")[0].trim();\n  if (!m) return \"unknown\";\n  if (m === \"application\/pdf\" || m === \"application\/x-pdf\") return \"pdf\";\n  if (m.startsWith(\"image\/\")) return \"image\";\n  if (m.startsWith(\"video\/\")) return \"video\";\n  if (m.startsWith(\"audio\/\")) return \"audio\";\n  \/\/ `application\/ogg` is audio in practice; treat it as such.\n  if (m === \"application\/ogg\") return \"audio\";\n  return \"unknown\";\n}\n\n\/** Map a bare file extension (no leading dot) to a media kind. *\/\nfunction extToKind(ext: string): MediaKind {\n  const e = ext.toLowerCase();\n  if (e === \"pdf\") return \"pdf\";\n  if (IMAGE_EXTS.has(e)) return \"image\";\n  if (VIDEO_EXTS.has(e)) return \"video\";\n  if (AUDIO_EXTS.has(e)) return \"audio\";\n  return \"unknown\";\n}\n\n\/** Pull the file extension out of a URL, ignoring its query\/hash. *\/\nfunction extFromSrc(src: string): string | null {\n  const clean = src.split(\/[?#]\/, 1)[0];\n  const lastSeg = clean.split(\"\/\").pop() ?? \"\";\n  const dot = lastSeg.lastIndexOf(\".\");\n  if (dot <= 0 || dot === lastSeg.length - 1) return null;\n  return lastSeg.slice(dot + 1);\n}\n\n\/** Extract the MIME type embedded in a `data:` URI, if present. *\/\nfunction mimeFromDataUri(src: string): string | null {\n  if (!\/^data:\/i.test(src)) return null;\n  const header = src.slice(5).split(\",\", 1)[0]; \/\/ text after `data:`, before the comma\n  const mt = header.split(\";\")[0].trim();\n  return mt || null;\n}\n\n\/**\n * Resolve a {@link MediaKind} from a MIME type and\/or source URL. MIME wins\n * when it's conclusive; otherwise the `src` is sniffed (a `data:` URI's\n * embedded type first, then the file extension). Returns `\"unknown\"` when\n * nothing matches \u2014 callers treat that as \"not previewable media\" (e.g. text).\n *\/\nexport function resolveMediaType({ mime, src }: ResolveMediaTypeInput): MediaKind {\n  if (mime) {\n    const k = mimeToKind(mime);\n    if (k !== \"unknown\") return k;\n  }\n  if (src) {\n    const dataMime = mimeFromDataUri(src);\n    if (dataMime) {\n      const k = mimeToKind(dataMime);\n      if (k !== \"unknown\") return k;\n    }\n    const ext = extFromSrc(src);\n    if (ext) return extToKind(ext);\n  }\n  return \"unknown\";\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/media-type.ts"}]}