jukebox
All repositories: gitoria
20.6 KB
// media-player.hl — THE MEDIA PLAYER, all Hybriel (no JavaScript file): audio and video in one phone-first player.// `MediaPlayer { src = "/media/x.mp4" kind = "video" title = "The clip" artist = "Someone" }` — `kind = "audio"` shows a// cover image (`cover`) with the title and artist instead of the video area. The browser's own media element plays (no// `controls`: this component draws the controls, sized for a thumb): a seek bar you drag with a finger (the played part in// the accent colour, the buffered part as a lighter bar, a 44 px tall touch area with a thin visible bar), Back 10 s,// play/pause (the largest button), Forward 10 s, mute, the current time / total time, the playback speed (1 / 1.25 / 1.5 / 2)// and, on video, fullscreen. THE QUEUE is the host's list: `queue = [{ src, title, dur }]` renders under the player, the// item that plays is marked with the accent colour only, and a tap calls the host's function with the record's `src`// (hybriel#87: a child talks upward through a function its host gives it) — the host hands a new `src` back, the player// loads and plays it; when an item ends, the next one is picked the same way. USE ONE PER PAGE (a composed component's// members are the page's state). Keyboard: the media element takes the focus (a click on it), Space plays / pauses,// ArrowLeft / ArrowRight jump 10 s. The handlers read the elements' own state, never the members.import Icon from '../icons/icons.hl'String src = ''String kind = 'video'String title = ''String artist = ''String cover = ''String playLabel = 'Play'String pauseLabel = 'Pause'String backLabel = 'Back 10 seconds'String forwardLabel = 'Forward 10 seconds'String muteLabel = 'Mute'String unmuteLabel = 'Unmute'String speedLabel = 'Playback speed'String fullscreenLabel = 'Fullscreen'String queueLabel = 'Queue'Hybrid queue = []onPlay = nullNumber jump = 10// the state the media events write (the framework repaints the sites that read them)String playing = 'false'String muted = 'false'String timeText = '0:00'String totalText = '0:00'String playedPct = '0'String bufferedPct = '0'String speedText = '1'String dragging = 'false'String bufferedStyle = 'width:0%'String playedStyle = 'width:0%'String thumbStyle = 'left:0%'String autoPlay = 'false'String playClass = 'mp-play'String playLabelNow = playLabelString playIsNow = playLabelString muteClass = 'mp-mute'String muteLabelNow = muteLabel// "1:23" — whole seconds are enough for a time lineclockText(t) {if (t == null || t < 0 || t != t) { return '0:00' }s = t - t % 1m = (s - s % 60) / 60sec = s - m * 60return m + ':' + (sec < 10 ? '0' : '') + sec}// the player's own element (the video or audio tag of this component)mediaOf(node) { return node.closest('media-player').querySelector('video, audio') }// the media element an event came from: the element itself (its own events can arrive while it is not yet in the page),// or the one of the player the node belongs to (the mount tick of the seek bar)mediaFrom(node) { return node.matches('video, audio') ? node : mediaOf(node) }// the seek bar of this componentbarOf(node) { return node.closest('media-player').querySelector('mp-seek') }// the media element's buffered end as a percent of its durationbufferedPctOf(v) {if (v == null || v.buffered.length == 0 || v.duration == 0 || v.duration == null) { return '0' }return '' + ((v.buffered.end(v.buffered.length - 1) / v.duration) * 100 - (v.buffered.end(v.buffered.length - 1) / v.duration) * 100 % 1)}Style {'media-player' { display = 'block' font = 'inherit' color = 'var(--color-text, #000)' background = 'var(--color-background, #fff)' }'media-player video' { display = 'block' width = '100%' aspectRatio = '16 / 9' height = 'auto' objectFit = 'contain' background = 'var(--color-background-sunken, #555)' borderRadius = 'var(--radius-large, 10px)' cursor = 'pointer' }'media-player audio' { display = 'none' }// the mount tick (the code editor's trick): an endless 100 ms animation fires animationiteration once// the page is live; the handler turns it off again. The tick sits on the seek bar: it is on screen for audio and video// alike (the audio element is display:none and a CSS animation never runs there, and a cover may be missing).'@keyframes media-player-mount' { 'from' { opacity = '.999' } to { opacity = '1' } }// the cover of an audio item, with the title and the artist'media-player .mp-cover' { display = 'flex' alignItems = 'center' gap = '.8rem' margin = '0 0 .4rem' }'media-player .mp-cover img' { flex = 'none' width = '5rem' height = '5rem' objectFit = 'cover' borderRadius = 'var(--radius-large, 10px)' background = 'var(--color-surface, #ddd)' }'media-player .mp-cover h2' { margin = '0' fontSize = '1.15rem' lineHeight = '1.3' color = 'var(--color-text-strong, #000)' overflowWrap = 'anywhere' }'media-player .mp-cover p' { margin = '.15rem 0 0' color = 'var(--color-text-muted, #555)' overflowWrap = 'anywhere' }// THE SEEK BAR: a 44 px touch area, the visible bar thin in the middle (a fat bar is decoration); the played part is the// accent, the buffered part a lighter grey over the pale track. No border anywhere.'media-player mp-seek' { display = 'block' position = 'relative' height = '2.75rem' margin = '.15rem 0' touchAction = 'none' cursor = 'pointer' animation = 'media-player-mount 100ms linear infinite' }'media-player mp-seek .mp-track' { position = 'absolute' left = '.3125rem' right = '.3125rem' top = '1.1875rem' height = '.375rem' borderRadius = 'var(--radius-small, 5px)' background = 'var(--color-surface, #ddd)' overflow = 'hidden' }'media-player mp-seek .mp-buffered' { position = 'absolute' left = '0' top = '0' bottom = '0' width = '0' background = 'var(--color-grey, #999)' opacity = '.55' }'media-player mp-seek .mp-played' { position = 'absolute' left = '0' top = '0' bottom = '0' width = '0' background = 'var(--color-accent, #000)' }'media-player mp-seek .mp-thumb' { position = 'absolute' top = '1.0625rem' width = '.625rem' height = '.625rem' borderRadius = '50%' background = 'var(--color-accent, #000)' transform = 'translateX(-50%)' left = '0' marginLeft = '.3125rem' }// the buttons: 44 px (the play / pause one larger); only the icon buttons on the row, the times between them'media-player mp-buttons' { display = 'flex' alignItems = 'center' flexWrap = 'wrap' gap = '.2rem' }'media-player mp-buttons button' { display = 'inline-flex' alignItems = 'center' justifyContent = 'center' minWidth = '2.75rem' minHeight = '2.75rem' padding = '0' font = 'inherit' fontWeight = '600' color = 'var(--color-text, #000)' background = 'transparent' border = '0' borderRadius = 'var(--radius-small, 5px)' cursor = 'pointer' }'media-player mp-buttons button:hover' { background = 'var(--color-surface, #f2f2f2)' }'media-player mp-buttons button:focus-visible' { outline = '2px solid var(--color-accent, #555)' outlineOffset = '1px' }'media-player mp-buttons button.mp-play' { background = 'var(--color-surface, #f2f2f2)' minWidth = '3.25rem' minHeight = '3.25rem' width = '3.25rem' height = '3.25rem' }'media-player mp-buttons .mp-times' { display = 'inline-flex' alignItems = 'center' minHeight = '2.75rem' padding = '0' flex = '0 1 auto' flexWrap = 'nowrap' fontVariantNumeric = 'tabular-nums' fontSize = '.85rem' whiteSpace = 'nowrap' color = 'var(--color-text-muted, #555)' }// the two icons of a toggle button: one shows, the other waits (an `if` would re-create the DOM);// the wrapping spans are inline-flex with no leading, or the icon rides the text baseline (3 px high)'media-player mp-buttons .i-play, media-player mp-buttons .i-pause, media-player mp-buttons .i-on, media-player mp-buttons .i-off' { display = 'inline-flex' flex = 'none' lineHeight = '0' }'media-player .mp-play .i-pause' { display = 'none' }'media-player .mp-play.is-playing .i-play' { display = 'none' }'media-player .mp-play.is-playing .i-pause' { display = 'inline-flex' }'media-player .mp-mute .i-off' { display = 'none' }'media-player .mp-mute.is-muted .i-on' { display = 'none' }'media-player .mp-mute.is-muted .i-off' { display = 'inline-flex' }// THE QUEUE under the player: title and length per row, dense (a 44 px tap area with thin rows, not loose ones)'media-player .mp-queue-title' { margin = '1rem 0 .2rem' fontSize = '1rem' color = 'var(--color-text-strong, #000)' }'media-player ol.mp-queue' { display = 'grid' gap = '.1rem' margin = '0' padding = '0' listStyle = 'none' }'media-player ol.mp-queue li' { margin = '0' }'media-player ol.mp-queue button' { display = 'flex' alignItems = 'center' gap = '.5rem' width = '100%' minHeight = '2.75rem' padding = '.3rem .55rem' font = 'inherit' textAlign = 'left' color = 'var(--color-text, #000)' background = 'transparent' border = '0' borderRadius = 'var(--radius-small, 5px)' cursor = 'pointer' }'media-player ol.mp-queue button:hover' { background = 'var(--color-surface, #f2f2f2)' }'media-player ol.mp-queue button:focus-visible' { outline = '2px solid var(--color-accent, #555)' outlineOffset = '1px' }'media-player ol.mp-queue li.current button' { color = 'var(--color-accent, #000)' background = 'var(--color-surface, #f2f2f2)' }'media-player ol.mp-queue .mp-q-title' { flex = '1' minWidth = '0' overflowWrap = 'anywhere' textAlign = 'left' }'media-player ol.mp-queue .mp-q-dur' { flex = 'none' fontSize = '.85rem' color = 'var(--color-text-muted, #555)' }'media-player ol.mp-queue li.current .mp-q-dur' { color = 'inherit' }}View {mediaPlayer {if (isVideo) { video { src = src preload = "metadata" playsinline = "playsinline" tabindex = "0" title = title class = "mp-media"on click(e) { emit mpToggle(e) } on play(e) { emit mpStarted(e) } on pause(e) { emit mpPaused(e) } on ended(e) { emit mpEnded(e) } on timeupdate(e) { emit mpTime(e) } on durationchange(e) { emit mpTotal(e) } on loadedmetadata(e) { emit mpLoad(e) } on progress(e) { emit mpBuffered(e) } on volumechange(e) { emit mpVolume(e) } on ratechange(e) { emit mpRate(e) } on keydown(e) { emit mpKey(e) }} }if (isAudio) { audio { src = src preload = "metadata" class = "mp-media"on play(e) { emit mpStarted(e) } on pause(e) { emit mpPaused(e) } on ended(e) { emit mpEnded(e) } on timeupdate(e) { emit mpTime(e) } on durationchange(e) { emit mpTotal(e) } on loadedmetadata(e) { emit mpLoad(e) } on progress(e) { emit mpBuffered(e) } on volumechange(e) { emit mpVolume(e) } on ratechange(e) { emit mpRate(e) } on keydown(e) { emit mpKey(e) }}if (hasCover) { div { class = "mp-cover"img { src = cover alt = "" }div {h2 { title }p { artist }}} }}mpSeek { role = "slider" 'aria-label' = "Seek" 'aria-valuemin' = "0" 'aria-valuemax' = "100" 'aria-valuenow' = playedPct 'aria-valuetext' = seekText tabindex = "0"on animationiteration(e) { emit mpMount(e) } on pointerdown(e) { emit mpDown(e) } on pointermove(e) { emit mpMove(e) } on pointerup(e) { emit mpUp(e) } on pointercancel(e) { emit mpUp(e) } on keydown(e) { emit mpBarKey(e) }div { class = "mp-track"div { class = "mp-buffered" style = bufferedStyle }div { class = "mp-played" style = playedStyle }}div { class = "mp-thumb" style = thumbStyle }}mpButtons {button { type = "button" class = "mp-back" title = backLabel 'aria-label' = backLabel Icon { name = "skipBack" size = "1.5em" } on click(e) { emit mpBack(e) } }button { type = "button" class = playClass title = playLabelNow 'aria-label' = playIsNowspan { class = "i-play" Icon { name = "play" size = "1.75em" } }span { class = "i-pause" Icon { name = "pause" size = "1.75em" } }on click(e) { emit mpToggle(e) }}button { type = "button" class = "mp-forward" title = forwardLabel 'aria-label' = forwardLabel Icon { name = "skipForward" size = "1.5em" } on click(e) { emit mpForward(e) } }span { class = "mp-times"time { timeText }span { 'aria-hidden' = "true" "/" }time { totalText }}button { type = "button" class = muteClass title = muteLabelNow 'aria-label' = muteLabelNowspan { class = "i-on" Icon { name = "volume" } }span { class = "i-off" Icon { name = "volumeOff" } }on click(e) { emit mpMute(e) }}button { type = "button" class = "mp-speed" title = speedLabel 'aria-label' = speedName on click(e) { emit mpSpeed(e) }span { 'aria-hidden' = "true" speedText + '×' }}if (isVideo) { button { type = "button" class = "mp-fullscreen" title = fullscreenLabel 'aria-label' = fullscreenLabel Icon { name = "fullscreen" } on click(e) { emit mpFull(e) } } }}if (hasQueue) { div {h2 { class = "mp-queue-title" queueLabel }ol { class = "mp-queue" 'aria-label' = queueLabelfor (q of rows) { li { class = q.clsbutton { type = "button" 'data-src' = q.src title = q.titlespan { class = "mp-q-title" q.title }span { class = "mp-q-dur" q.dur }on click(e) { emit mpPick(e) }}} }}} }}}isVideo = kind != 'audio'isAudio = kind == 'audio'hasCover = kind == 'audio' && cover != ''hasQueue = queue.length > 0seekText = timeText + ' of ' + totalTextspeedName = speedLabel + ' ' + speedText + '×'Hybrid rows = rowsOf(queue, src)// the queue rows with the current one marked (a row's class must be a field of the record)rowsOf(list, now) {out = []let i = 0while (i < list.length) {out.push({ src = list[i].src title = list[i].title dur = list[i].dur cls = list[i].src == now ? 'current' : '' })i = i + 1}return out}// ---- the buttons ----------------------------------------------------------------------------------------on mpToggle(e) {v = mediaOf(e.target)if (v.paused) { v.play() } else { v.pause() }return null}on mpBack(e) {v = mediaOf(e.target)if (v.currentTime > jump) { v.currentTime = v.currentTime - jump } else { v.currentTime = 0 }return null}on mpForward(e) {v = mediaOf(e.target)if (v.duration > 0 && v.currentTime + jump < v.duration) { v.currentTime = v.currentTime + jump } else if (v.duration > 0) { v.currentTime = v.duration }return null}on mpMute(e) {v = mediaOf(e.target)v.muted = !v.mutedreturn null}on mpSpeed(e) {v = mediaOf(e.target)s = v.playbackRatelet next = 1if (s == 1) { next = 1.25 } else if (s == 1.25) { next = 1.5 } else if (s == 1.5) { next = 2 }v.playbackRate = nextspeedText = '' + nextreturn null}on mpFull(e) {p = e.target.closest('media-player')if (document.fullscreenElement != null) { document.exitFullscreen() } else { p.requestFullscreen() }return null}// ---- the seek bar ---------------------------------------------------------------------------------------// the percent of the bar a pointer x lands onpctOf(bar, x) {r = bar.getBoundingClientRect()if (r.width == 0) { return 0 }let p = (x - r.left) / r.width * 100if (p < 0) { p = 0 }if (p > 100) { p = 100 }return p - p % 1}on mpDown(e) {v = mediaOf(e.target)bar = barOf(e.target)bar.setPointerCapture(e.pointerId)dragging = 'true'if (v.duration > 0) { v.currentTime = pctOf(bar, e.clientX) / 100 * v.duration }return null}on mpMove(e) {if (dragging != 'true') { return null }v = mediaOf(e.target)bar = barOf(e.target)if (v.duration > 0) { v.currentTime = pctOf(bar, e.clientX) / 100 * v.duration }return null}on mpUp(e) {dragging = 'false'return null}// the seek bar itself takes the keyboard too: arrows jump, Home / End go to the endson mpBarKey(e) {v = mediaOf(e.target)if (e.key == 'ArrowLeft') { e.preventDefault() emit mpBack(e) return null }if (e.key == 'ArrowRight') { e.preventDefault() emit mpForward(e) return null }if (e.key == 'Home' && v.duration > 0) { e.preventDefault() v.currentTime = 0 return null }if (e.key == 'End' && v.duration > 0) { e.preventDefault() v.currentTime = v.duration return null }return null}// ---- the media element's events --------------------------------------------------------------------------// the whole display read from the media element: the labels, the times, the bars, the play / mute / speed state. A new// source on the SAME element (a queue item of the same kind) or a new element (the kind changed) must never show the// old item's state: the time, the bars, the speed and the mute of the element are what the buttons show.on mpSync(e) {v = mediaFrom(e.target)timeText = clockText(v.currentTime)totalText = v.duration > 0 ? clockText(v.duration) : '0:00'playedPct = v.duration > 0 ? '' + (v.currentTime / v.duration * 100 - v.currentTime / v.duration * 100 % 1) : '0'playedStyle = 'width:' + playedPct + '%'thumbStyle = 'left:' + playedPct + '%'bufferedPct = bufferedPctOf(v)bufferedStyle = 'width:' + bufferedPct + '%'speedText = '' + v.playbackRatemuted = v.muted ? 'true' : 'false'muteClass = v.muted ? 'mp-mute is-muted' : 'mp-mute'muteLabelNow = v.muted ? unmuteLabel : muteLabelplayClass = v.paused ? 'mp-play' : 'mp-play is-playing'playLabelNow = v.paused ? playLabel : pauseLabelplayIsNow = playLabelNowreturn null}// the metadata of a new source arrived after the handlers were bound (a queue pick of the same kind keeps the element and// only changes its src; `loadstart` is not a DOM event the framework knows, `loadedmetadata` is): read the display again// and, when the host asked for it, start the new itemon mpLoad(e) {emit mpSync(e)v = mediaFrom(e.target)if (autoPlay == 'true') { v.play() }return null}on mpRate(e) { speedText = '' + e.target.playbackRate return null }// the first tick of the mount animation: the element's own state (already loaded before the handlers bound)// is read in, then the animation is turned offon mpMount(e) {e.target.style.animationName = 'none'emit mpSync(e)v = mediaOf(e.target)if (autoPlay == 'true') { v.play() }return null}on mpStarted(e) { playing = 'true' playClass = 'mp-play is-playing' playLabelNow = pauseLabel playIsNow = pauseLabel return null }on mpPaused(e) { playing = 'false' playClass = 'mp-play' playLabelNow = playLabel playIsNow = playLabel return null }on mpTime(e) {v = e.targettimeText = clockText(v.currentTime)if (v.duration > 0) {playedPct = '' + (v.currentTime / v.duration * 100 - v.currentTime / v.duration * 100 % 1)playedStyle = 'width:' + playedPct + '%'thumbStyle = 'left:' + playedPct + '%'if (totalText == '0:00') { totalText = clockText(v.duration) }bufferedPct = bufferedPctOf(v)bufferedStyle = 'width:' + bufferedPct + '%'}return null}on mpTotal(e) {if (e.target.duration > 0) { totalText = clockText(e.target.duration) }return null}on mpBuffered(e) {v = e.targetbufferedPct = bufferedPctOf(v)bufferedStyle = 'width:' + bufferedPct + '%'if (v.duration > 0 && totalText == '0:00') { totalText = clockText(v.duration) }return null}on mpVolume(e) {muted = e.target.muted ? 'true' : 'false'muteClass = muted == 'true' ? 'mp-mute is-muted' : 'mp-mute'muteLabelNow = muted == 'true' ? unmuteLabel : muteLabelreturn null}on mpKey(e) {if (e.key == ' ' || e.key == 'Spacebar') { e.preventDefault() emit mpToggle(e) return null }if (e.key == 'ArrowLeft') { e.preventDefault() emit mpBack(e) return null }if (e.key == 'ArrowRight') { e.preventDefault() emit mpForward(e) return null }return null}// ---- the queue ---------------------------------------------------------------------------------------------// a tap on a queue item tells the host, which hands a new src back (the player is built anew with it)// a tap on a queue item tells the host, which hands a new src back (the player is built anew with it); the// new one starts playing at once (the user asked for it — autoplay policies allow a play after a tap)on mpPick(e) {b = e.target.closest('button')if (onPlay != null) { onPlay(b.getAttribute('data-src')) }return null}// an item ended: the next one is picked the same way (the last one just stops). THE SAME AUDIO ELEMENT gets the next source and// plays it right here, in the ended event: with the screen locked the page gets no frames and no animations, and a// player that waits for a re-render, the mount tick or the new data before it calls play() is left paused (the lock// screen's notification disappears and the next song never starts). The host is told after that, so the display, the// queue and the lock screen's title follow (the host's re-render writes the same src once more; the element then// loads again and the metadata handler starts it again, which costs nothing audible).on mpEnded(e) {playing = 'false'let i = 0let next = ''while (i < queue.length) {if (queue[i].src == src && i + 1 < queue.length) { next = queue[i + 1].src }i = i + 1}if (next == '') { return null }v = mediaFrom(e.target)v.setAttribute('src', next)v.play()if (onPlay != null) { onPlay(next) }return null}
Branches
Latest commits
- 7eb2898dRecords: mpackdb second-opener rule until day38mre
- b011f98eRecords: style form live on day35mre
- 60d90cb2Records: L1 woken for the restartmre
- 75ae544fRecords: restart waits for the connection to closemre
- e0b75951Records: L1 merged and pushed, restart waits for an open connectionmre
- f2b5db98styles: format styles with nested rules and bare queriesmre
- f036bab4search: format styles with nested rules and bare queriesmre
- ef9a9d4asongs: format styles with nested rules and bare queriesmre
- f22f9aacmain: format styles with nested rules and bare queriesmre
- f56cd7c7Sync icons from 8176eb1 and verify mixed component sourcesmre
- d56e5054Sync theme and shared tokens from layouts 17e0f03mre
- b1362547Re-vendor to Hybriel set day35mre
- 89e10f08Records: mission 002 rollback wordingmre
- 9485dee7Records: mission 002 brief (live step)mre
- 9ba68fe7Records: S1b reviewedmre
- 193dfff1Records: S1 result, S1b startedmre
- 028ed776Records: mission 001 continuation S1bmre
- 1838d7e8Records: S1 startedmre
- a43fca3fRecords: mission 001 decided pointsmre
- 41773828Records: statusmre